Token-Free and Byte-Level Language Models › Byte Streams That Are Not Text

Michael BrenndoerferNovember 17, 20265 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 135Token-Free and Byte-Level Language Models › Byte Streams That Are Not Text
Reading section 3 of 13 · Byte Streams That Are Not Text · 5 minSection 3 of 13 · 5 min

Section 3 of 13 · 5 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

A byte model can assign positive probability to an invalid UTF-8 byte string. Serving code needs to distinguish a partial scalar value from a prefix that is already malformed.

Partial Prefixes

A prefix of a valid UTF-8 string is not necessarily a valid UTF-8 string. Cut café中文😀 at an arbitrary byte offset and you will often land in the middle of a multi-byte sequence. Let us enumerate every prefix and check.

PythonIn [13]
CollapseExpand
MIXED = "caf\u00e9\u4e2d\u6587\U0001f600"
MIXED_BYTES = MIXED.encode("utf-8")

prefix_status = []
for k in range(len(MIXED_BYTES) + 1):
    try:
        MIXED_BYTES[:k].decode("utf-8")
        prefix_status.append((k, "decodes"))
    except UnicodeDecodeError:
        prefix_status.append((k, "fails"))
ConsoleOut [14]
CollapseExpand
total bytes: 15
hex: 63 61 66 c3 a9 e4 b8 ad e6 96 87 f0 9f 98 80
prefix lengths that decode: [0, 1, 2, 3, 5, 8, 11, 15]
prefix lengths that fail:   [4, 6, 7, 9, 10, 12, 13, 14]

Eight of the sixteen prefixes, including the empty prefix, decode. The other eight cuts land inside a multibyte scalar value.

The prefix check above only covers truncation. A generated stream can also contain bytes that never form a valid sequence no matter how much you append. Test a few of those directly.

PythonIn [15]
CollapseExpand
probes = {
    "lone continuation byte": b"\x80",
    "truncated three-byte": b"\xe4\xb8",
    "overlong encoding of U+002F": b"\xc0\xaf",
    "surrogate U+D800": b"\xed\xa0\x80",
    "above U+10FFFF": b"\xf4\x90\x80\x80",
    "valid emoji": "\U0001f600".encode("utf-8"),
}

probe_results = []
for label, blob in probes.items():
    try:
        blob.decode("utf-8", errors="strict")
        probe_results.append((label, blob.hex(" "), "accepted"))
    except UnicodeDecodeError as exc:
        probe_results.append((label, blob.hex(" "), f"rejected: {exc.reason}"))
ConsoleOut [16]
CollapseExpand
lone continuation byte         80             rejected: invalid start byte
truncated three-byte           e4 b8          rejected: unexpected end of data
overlong encoding of U+002F    c0 af          rejected: invalid start byte
surrogate U+D800               ed a0 80       rejected: invalid continuation byte
above U+10FFFF                 f4 90 80 80    rejected: invalid continuation byte
valid emoji                    f0 9f 98 80    accepted

Every invalid case is rejected by the strict decoder for a specific, nameable reason. The lone continuation byte has no lead byte. The truncated sequence is incomplete. The overlong form violates shortest-form encoding. The surrogate is excluded by RFC 3629. The value above U+10FFFF is out of range.

The distinction between incomplete and invalid is the one that matters operationally. An incomplete sequence is a prefix that could still become valid if the right bytes arrive, so the correct response is to wait. An invalid sequence can never become valid no matter what arrives, so the correct response is to abort or repair. A decoder that treats both cases the same way either drops bytes that were about to complete or waits forever on a stream that will never decode.

An unconstrained generator can assign positive probability to malformed UTF-8. Report whether the system rejects the output, regenerates it, or repairs it. Count decoding errors or repair events directly, for example by validating the original bytes or using an instrumented error handler. U+FFFD can also be intentional text, encoded as the valid bytes EF BF BD. Counting it in rendered text can therefore overcount repairs, and one malformed sequence can produce multiple replacement characters under a particular repair policy. Unicode Standard, §3.9.6

Incremental Decoding

An incremental decoder emits complete scalar values and can keep trailing bytes until the next chunk or the end of the stream. An incomplete sequence at end of stream needs a declared policy, such as raising an error or emitting U+FFFD.

The standard library’s strict incremental decoder accepts one chunk at a time. It returns completed text and can retain trailing bytes for the next call. Pass final=True on the last call to flush the buffer.

PythonIn [17]
CollapseExpand
import codecs

decoder = codecs.getincrementaldecoder("utf-8")(errors="strict")
trace, decoded = [], ""
for offset, value in enumerate(MIXED_BYTES, start=1):
    decoded += decoder.decode(bytes([value]), final=False)
    pending, _ = decoder.getstate()
    trace.append((offset, decoded, len(pending)))

decoded += decoder.decode(b"", final=True)
monotone = all(MIXED.startswith(text) for _, text, _ in trace)
final_ok = decoded == MIXED
ConsoleOut [18]
CollapseExpand
k= 1  decoded='c'                held_back=0
k= 2  decoded='ca'               held_back=0
k= 3  decoded='caf'              held_back=0
k= 4  decoded='caf'              held_back=1
k= 5  decoded='café'             held_back=0
k= 6  decoded='café'             held_back=1
k= 7  decoded='café'             held_back=2
k= 8  decoded='café中'            held_back=0
k= 9  decoded='café中'            held_back=1
k=10  decoded='café中'            held_back=2
k=11  decoded='café中文'           held_back=0
k=12  decoded='café中文'           held_back=1
k=13  decoded='café中文'           held_back=2
k=14  decoded='café中文'           held_back=3
k=15  decoded='café中文😀'          held_back=0
every decoded prefix is a prefix of the target: True
final decode equals the original text: True

The output stays unchanged while the decoder awaits the remaining bytes of a scalar value. A successful strict final flush establishes UTF-8 validity for the completed stream. An empty nonfinal return can also mean the decoder deferred an error. Under RFC 3629, ED A0 cannot begin a valid scalar encoding because ED must be followed by a byte from 80 through 9F. The strict incremental decoder in CPython 3.11.14 can buffer ED A0 at a chunk boundary and raise on final flush. If every emitted byte prefix must admit a valid UTF-8 completion, constrain the byte generator with a UTF-8 state machine and allow termination only at scalar boundaries. RFC 3629, §4 · CPython 3.11.14 UTF-8 decoder

There is a third subtlety that matters for evaluation. A model that emits a valid prefix and then an invalid byte has produced a stream that decodes partially. Whether to score that as a full failure, a partial success, or something in between is a policy decision, and different papers make it differently. When you compare reported invalid-output rates, check that the definition of "invalid" is the same across the numbers you are comparing.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy