Token-Free and Byte-Level Language Models

Michael BrenndoerferNovember 17, 202654 min read

Explore token-free byte-level language models: UTF-8 encoding, byte factorization, patching architectures like ByT5, CANINE, MEGABYTE, BLT, and fair evaluation.

Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 135Token-Free and Byte-Level Language Models
Reading the full chapter · 13 sections · 54 min13 sections · 54 min

All 13 sections · 54 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Token-Free and Byte-Level Language Models

The word café can occupy five UTF-8 bytes or six, depending on how the accent was encoded. A direct byte model spends one content position on each byte. What looks like the same word on screen can take up a different share of its context window.

A learned subword tokenizer maps strings to sequences of IDs whose lengths depend on the tokenizer and its input. Removing that tokenizer shifts the design choice into the model. ByT5 represents each byte directly. Other architectures allocate their large model to coarser positions and use smaller components at byte resolution.

We will follow Unicode text from scalar values to bytes, then count the positions each part of a model processes. These counts explain fixed and learned patch boundaries and help compare the likelihood scores for byte and subword models.

The encoding facts here build on Character Encoding, and the tokenizer mechanics build on the subword tokenization part, especially Byte Pair Encoding, SentencePiece, and Tokenization Challenges. If you want a refresher on why vocabulary size is a design tension at all, revisit The Vocabulary Problem.

The Byte Interface

Encode the text as UTF-8 and map each byte to an input ID. The content alphabet contains all 256 byte values. Models may reserve distinct IDs for boundaries and padding.

Strict UTF-8 gives every sequence of Unicode scalar values a reversible encoding. A Python string can contain an unpaired surrogate, which the strict encoder rejects.

Some subword tokenizers use a byte fallback for text outside their learned pieces. A direct byte model uses the byte representation for every input and leaves grouping to subsequent model layers.

UTF-8 in Four Forms

RFC 3629 defines UTF-8 as a variable-length encoding of Unicode scalar values into sequences of one to four bytes. A scalar value is any integer from U+0000 to U+10FFFF except the surrogate range U+D800 to U+DFFF. The encoding table is short enough to memorize.

UTF-8 byte patterns for each Unicode scalar value range.
Scalar value rangeByte patternBytes
U+0000 to U+007F0xxxxxxx1
U+0080 to U+07FF110xxxxx 10xxxxxx2
U+0800 to U+FFFF, excluding U+D800 to U+DFFF1110xxxx 10xxxxxx 10xxxxxx3
U+10000 to U+10FFFF11110xxx 10xxxxxx 10xxxxxx 10xxxxxx4

The table is worth reading carefully because the bit patterns are doing two jobs at once. The leading bits of the first byte encode how many bytes the sequence contains, and the leading bits of every subsequent byte mark it as a continuation. That design is what lets a decoder know, from the first byte alone, how many bytes to consume.

Every continuation byte matches 10xxxxxx, which means a lead byte can never be mistaken for a continuation and vice versa. That is the self-synchronizing property. If you land in the middle of a stream, you can scan forward until you find a byte that is not a continuation byte and resynchronize.

In an otherwise valid stream, a cut inside a scalar value can leave at most three continuation bytes before the next boundary or the end of the stream.

RFC 3629 also imposes three constraints that separate strict UTF-8 from the looser encodings of the 1990s.

  • Shortest form only. A scalar value must use the shortest sequence that can represent it. The two-byte encoding of U+002F is illegal.
  • No surrogates. Code points U+D800 to U+DFFF are excluded, so CESU-8 style encodings are rejected.
  • Nothing above U+10FFFF. The original five- and six-byte forms were removed.

Each constraint closes a security or correctness hole. Overlong encodings let the same character be written in multiple ways, which defeats naive string comparison and has been used to bypass filters. Surrogates are reserved for UTF-16 and have no meaning as standalone scalar values. The five- and six-byte forms could represent values outside the Unicode range, which made decoders disagree about what a stream contained. Strict UTF-8 is the subset that avoids all three ambiguities.

Strict UTF-8

A byte string is strict UTF-8 when it decodes under all three constraints of RFC 3629 with no error. Python's default bytes.decode("utf-8") implements strict UTF-8. The distinction matters because a byte language model can emit byte strings that are not strict UTF-8, and a decoder that silently repairs them can hide real failures.

Three Different Counts

Three quantities get mixed up constantly in discussion of token-free models. Keep them separate.

  • Unicode scalar values. Python’s string length counts code points. For a string of Unicode scalar values, that is also its scalar count.
  • UTF-8 bytes. The number of bytes after encoding. This is len(s.encode("utf-8")).
  • Model positions. A direct byte model has one content position per byte. A subword model’s count depends on its tokenizer and input. A patched model has separate positions for bytes and patches. Count padding and special markers separately.

The scalar count and byte count agree for ASCII. A byte count grows faster when UTF-8 uses more than one byte per scalar value.

Let us compute all of this on a mixed-script example that contains ASCII, a two-byte accented letter, its combining form, CJK, and an emoji.

PythonIn [3]
CollapseExpand
SAMPLES = {
    "ascii": "cafe",
    "precomposed": "caf\u00e9",
    "decomposed": "cafe\u0301",
    "cjk": "\u4e2d\u6587",
    "emoji": "\U0001f600",
}

rows = []
for name, text in SAMPLES.items():
    raw = text.encode("utf-8")
    rows.append(
        {
            "name": name,
            "text": text,
            "scalars": len(text),
            "bytes": len(raw),
            "codepoints": " ".join(f"U+{ord(ch):04X}" for ch in text),
            "hex": raw.hex(" "),
        }
    )
ConsoleOut [4]
CollapseExpand
sample        scalars  bytes  hex                       scalar values
---------------------------------------------------------------------
ascii               4      4  63 61 66 65               U+0063 U+0061 U+0066 U+0065
precomposed         4      5  63 61 66 c3 a9            U+0063 U+0061 U+0066 U+00E9
decomposed          5      6  63 61 66 65 cc 81         U+0063 U+0061 U+0066 U+0065 U+0301
cjk                 2      6  e4 b8 ad e6 96 87         U+4E2D U+6587
emoji               1      4  f0 9f 98 80               U+1F600

Read the first three rows together. The ASCII string cafe is four scalar values and four bytes. The precomposed café is four scalar values and five bytes, because U+00E9 needs two bytes. The decomposed café is five scalar values and six bytes, because it is e followed by U+0301 COMBINING ACUTE ACCENT, and U+0301 also needs two bytes.

Two strings that render almost identically occupy different numbers of model positions under a byte interface. That is the first practical consequence of going token-free, and it is entirely a property of the encoding rather than of the model.

Each of the two CJK scalar values in this example needs three bytes, for six bytes total. Supplementary CJK scalar values such as U+20000 need four bytes. The sampled emoji also needs four bytes. Compare byte lengths on the actual texts. A translation can use a different number of scalar values, so the sample costs do not give a fixed multiplier across languages.

The chart compares Unicode scalar and UTF-8 byte counts for the mixed-script examples. For a direct byte model, the byte count also gives the number of content positions.

PythonIn [5]
CollapseExpand
import numpy as np

sample_names = [r["name"] for r in rows]
scalar_counts = np.array([r["scalars"] for r in rows])
byte_counts = np.array([r["bytes"] for r in rows])
x_positions = np.arange(len(sample_names))
bar_width = 0.38
scalar_positions = x_positions - bar_width / 2
byte_positions = x_positions + bar_width / 2
VisualizationOut [6]
CollapseExpand
Grouped bar chart of Unicode scalar and UTF-8 byte counts for five mixed-script samples.
Unicode scalar counts and UTF-8 byte counts for the five mixed-script samples. The precomposed and decomposed accented forms differ in both counts, while the CJK and emoji samples show larger byte-to-scalar multipliers.
PythonIn [7]
CollapseExpand
roundtrip = []
for r in rows:
    decoded = r["text"].encode("utf-8").decode("utf-8")
    roundtrip.append((r["name"], decoded == r["text"]))
ConsoleOut [8]
CollapseExpand
text -> bytes -> text is lossless for every sample: True
byte lengths: {'ascii': 4, 'precomposed': 5, 'decomposed': 6, 'cjk': 6, 'emoji': 4}

The round trip holds for every sample. That is worth stating precisely, because it is easy to overclaim.

UTF-8 maps Unicode scalar sequences bijectively to well-formed UTF-8 byte strings. Validity depends on the whole sequence. At length one, 128 of the 256 possible strings are valid, all of them ASCII. At length two, 1282+30⋅64=18,304128^2 + 30 \cdot 64 = 18{,}304 of the 2562256^2 strings are valid, either as two ASCII bytes or as one two-byte scalar. These counts give the rates under uniform byte draws at those lengths. A trained model has its own distribution. RFC 3629, §4

What Lives in the Vocabulary

A byte vocabulary maps the 256 possible byte values to distinct IDs. An implementation can reserve additional nonoverlapping markers for padding and sequence boundaries. This example keeps byte values as IDs and places special markers above them.

PythonIn [9]
CollapseExpand
SPECIALS = ["<pad>", "<eos>", "<bos>"]
BYTE_TO_ID = {b: b for b in range(256)}
SPECIAL_IDS = {name: 256 + i for i, name in enumerate(SPECIALS)}
VOCAB_SIZE = 256 + len(SPECIALS)

collision_free = all(SPECIAL_IDS[s] >= 256 for s in SPECIALS)
ConsoleOut [10]
CollapseExpand
byte identifiers: 0 .. 255
special identifiers: {'<pad>': 256, '<eos>': 257, '<bos>': 258}
total vocabulary size: 259
special ids disjoint from byte ids: True
input embedding parameters at width 4,096: 1,060,864

At embedding width 4,096, the input matrix has one row per vocabulary entry.

Input embedding storage at fixed width, before any other model weights or runtime allocations.
Vocabulary rowsInput embedding parametersWeight storage at two bytes per parameter
2591,060,8642,121,728 bytes
128,000524,288,0001,048,576,000 bytes

An input lookup reads the selected row. A dense output projection that scores every symbol does work proportional to vocabulary size times the projection width at each scored position. Weight tying can share storage between these matrices when the input and output vocabularies and widths match. The share of total model memory depends on the other parameters and their storage format. Press and Wolf, §3

The trade is not free in the other direction. A byte vocabulary means the model must learn, from data, that certain byte pairs and triples co-occur and what they mean. A subword vocabulary hands it those groupings for free. That is the central tension of the chapter, and the patching architectures we examine later are all attempts to recover the grouping inside the model rather than outside it.

With the same fitted tokenizer, preprocessing, and deterministic encoding settings, two models receive the same subword segmentation for the same text. Byte models receive the same initial byte sequence under the same encoding policy, but the groupings they use inside the model can differ. For example, MEGABYTE groups fixed-width spans while BLT can assign boundaries from next-byte entropy. MEGABYTE, §2.1 · Byte Latent Transformer, §§2.1 and 2.3

Normalization Is a Policy

Because the byte interface is a faithful encoding of whatever string you give it, it inherits every inconsistency in how that string was produced. Unicode has canonical equivalences. café written as U+00E9 and café written as e plus U+0301 are canonically equivalent, and a strict byte model sees two different sequences. There is no automatic resolution.

This makes normalization a first-class decision, not an implementation detail. The usual options are:

  • NFC canonically decomposes the input, then recomposes sequences where Unicode's composition rules permit.
  • NFD applies canonical decomposition without recomposition.
  • NFKC and NFKD additionally apply compatibility mappings, which are lossy. The ligature fi becomes fi, superscript digits become plain digits, and full-width Latin letters become ASCII.
  • None leaves the input scalar sequence unchanged before UTF-8 encoding.

A change in normalization can change both the encoded sequence and its length. Record the policy used in training and evaluation. Unicode Normalization Forms

PythonIn [11]
CollapseExpand
import unicodedata

norm_rows = []
for form in ["NFC", "NFD", "NFKC", "NFKD"]:
    normalized = unicodedata.normalize(form, "caf\u00e9")
    encoded = normalized.encode("utf-8")
    norm_rows.append(
        (form, normalized, len(normalized), len(encoded), encoded.hex(" "))
    )

ligature = "\ufb01"
compat_rows = []
for form in ["NFC", "NFKC"]:
    normalized = unicodedata.normalize(form, ligature)
    compat_rows.append((form, normalized, len(normalized)))
ConsoleOut [12]
CollapseExpand
NFC   scalars=4 bytes=5  63 61 66 c3 a9
NFD   scalars=5 bytes=6  63 61 66 65 cc 81
NFKC  scalars=4 bytes=5  63 61 66 c3 a9
NFKD  scalars=5 bytes=6  63 61 66 65 cc 81

U+FB01 under NFC   -> 'fi' (1 scalar values)
U+FB01 under NFKC  -> 'fi' (2 scalar values)

For this word, NFC and NFKC both use the precomposed letter. NFD and NFKD both use the base letter and combining accent. NFKC maps U+FB01 to two ASCII letters, which matters when a task needs to reproduce the original typography.

Compatibility normalization is a good example of a preprocessing choice that looks like a cleanup and is actually a modeling decision. If you apply NFKC, you are telling the model that fi and fi are the same string, which is true for many search and retrieval tasks and false for tasks that need to reproduce a document exactly. The byte interface does not make that decision for you, and it does not hide it. The bytes you feed are the bytes you chose.

The rule that follows is unglamorous and important. Pick one normalization form, apply it identically at corpus construction, at training, and at inference, and record the choice in the model card. A byte model does not remove the need for this decision. It removes the excuse for leaving it implicit, because the decision now shows up directly in the position count.

The same argument applies to case folding, whitespace collapsing, and Unicode-aware cleanup. Those are preprocessing choices, not tokenizer choices, and going token-free does not make them disappear.

Default Unicode lowercasing maps İ (U+0130, LATIN CAPITAL LETTER I WITH DOT ABOVE) to i (U+0069) followed by U+0307 COMBINING DOT ABOVE. The UTF-8 length grows from two bytes to three. Whitespace collapsing can also change the byte count, which changes the loss denominator. Document which preprocessing operations you apply. Unicode 17.0, SpecialCasing

Byte Streams That Are Not Text

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.

The Autoregressive Byte Model

The causal factorization for a direct byte model works over 256 content symbols and any separately defined boundary symbols. The same factorization can use a Transformer, RNN, or state-space model.

Byte lengths change sequence cost and evaluation units. Architectures can also change depth, masking, or the level at which their largest components operate. Compute those costs for the model and sequence lengths under comparison.

Factorization and Length Conventions

Let b1:T=(b1,…,bT)b_{1:T} = (b_1, \dots, b_T) be a byte string with bt∈{0,…,255}b_t \in \{0, \dots, 255\}, and let TT be its length in bytes. Append a distinguished end-of-sequence symbol. A causal byte language model defines

pθ(b1:T,EOS)=∏t=1Tpθ(bt∣b<t)⋅pθ(EOS∣b≤T).p_\theta(b_{1:T}, \text{EOS}) = \prod_{t=1}^{T} p_\theta(b_t \mid b_{<t}) \cdot p_\theta(\text{EOS} \mid b_{\le T}).

Three conventions need to be stated whenever you report a number derived from this.

  • What counts as a scored position. The beginning-of-sequence marker is a fixed context symbol and is not scored. The TT content bytes and the terminating EOS are scored. That gives T+1T+1 scored positions.
  • What the denominator is. Dividing the total negative log-likelihood by T+1T+1 gives nats per scored position. For nonempty content, dividing by TT gives nats per content byte, with EOS loss included. EOS-only output has one scored position and an undefined per-content-byte score.
  • Which normalization form the bytes came from. NFC and NFD can yield identical UTF-8 bytes. When the bytes differ, their count TT can change too. To compare models on the same input, use the same normalization and score the same bytes. To study the effect of normalization, report each representation and its own byte count.

The same conventions apply to a subword model with the obvious substitution. Its TT becomes a token count SS, its alphabet becomes the vocabulary, and its EOS is the end-of-sentence token.

For T>0T>0, adding EOS to the numerator at fixed content-byte denominator adds its surprisal, −ln⁡pθ(EOS∣b≤T)-\ln p_\theta(\text{EOS}\mid b_{\le T}), divided by TT to the score. This change is O(1/T)O(1/T) if the EOS surprisal stays bounded as the content length grows. A small EOS probability can make the effect large at a given length. Match the scoring convention before comparing models.

Bits per Byte

For T>0T>0 and the factorization above, the per-content-byte negative log-likelihood in nats is

L=1T[∑t=1T−ln⁡pθ(bt∣b<t)  −  ln⁡pθ(EOS∣b≤T)],\mathcal{L} = \frac{1}{T}\left[\sum_{t=1}^{T} -\ln p_\theta(b_t \mid b_{<t}) \;-\; \ln p_\theta(\text{EOS} \mid b_{\le T})\right],

and the same quantity in bits is L/ln⁡2\mathcal{L} / \ln 2. Using the same numerator, the mean loss over T+1T+1 scored positions is L T/(T+1)\mathcal{L}\,T/(T+1). For finite loss, the absolute difference is L/(T+1)\mathcal{L}/(T+1). An O(1/T)O(1/T) absolute difference therefore requires bounded per-content-byte loss.

Bits per byte (BPB) divides the negative log probability, in bits, by the number of content bytes. An average of one bit per byte does not specify the uncertainty at any single position.

Normalize every model's score by the same positive byte count of the text being scored, after any agreed Unicode normalization and UTF-8 encoding. Document the EOS policy. Verify that each model's scored token sequence decodes to the same byte string.

The Canonical Segmentation Caveat

Converting the log-probability of a token sequence to bits per byte changes the unit of its score. The underlying probability still belongs to that token sequence.

Cao and Rimell study this distinction in their EMNLP 2021 evaluation of marginal likelihood. Let D(s)D(s) be the bytes decoded from a content-token path ss under the chosen policy. Sum the probabilities of all EOS-terminated paths that decode to the evaluated bytes xx. Cao and Rimell, 2021

pθ(x)=∑s: D(s)=xpθ(s,EOS).p_\theta(x) = \sum_{s:\,D(s)=x} p_\theta(s,\text{EOS}).

If the canonical encoder EE gives a path with D(E(x))=xD(E(x))=x, its probability under the same EOS convention is one term in the sum and lower-bounds the string probability. For the same positive byte count, its bits-per-byte score upper-bounds the marginal score. The toy below decodes each path by concatenating its token bytes.

A small worked example makes the size of the gap concrete. Take the two-byte string ab and a toy token vocabulary containing a, b, and ab. The first-order model below assigns zero probability to unlisted transitions. A string can have a valid segmentation yet receive zero probability when every path uses an unlisted transition.

PythonIn [19]
CollapseExpand
import math

TOY_VOCAB = [("a", b"a"), ("b", b"b"), ("ab", b"ab")]
TOY_TABLE = {
    "<s>": {"a": 0.6, "b": 0.1, "ab": 0.1, "</s>": 0.2},
    "a": {"b": 0.5, "a": 0.1, "ab": 0.1, "</s>": 0.3},
    "b": {"a": 0.2, "</s>": 0.8},
    "ab": {"a": 0.1, "</s>": 0.9},
}


def segmentations(byte_string, vocab):
    if not byte_string:
        yield []
        return
    for tok, tb in vocab:
        if byte_string.startswith(tb):
            for rest in segmentations(byte_string[len(tb) :], vocab):
                yield [tok] + rest


def sequence_logprob(tokens, table):
    prev, total = "<s>", 0.0
    for tok in tokens + ["</s>"]:
        prob = table[prev].get(tok, 0.0)
        if prob == 0.0:
            return -math.inf
        total += math.log(prob)
        prev = tok
    return total


def longest_match(byte_string, vocab):
    ordered = sorted(vocab, key=lambda kv: -len(kv[1]))
    toks, i = [], 0
    while i < len(byte_string):
        for tok, tb in ordered:
            if byte_string.startswith(tb, i):
                toks.append(tok)
                i += len(tb)
                break
        else:
            raise ValueError("no vocabulary item matches")
    return toks
PythonIn [20]
CollapseExpand
TARGET = b"ab"
N_BYTES = len(TARGET)

segs = list(segmentations(TARGET, TOY_VOCAB))
seg_rows = []
for seg in segs:
    lp = sequence_logprob(seg, TOY_TABLE)
    seg_rows.append((seg, lp, math.exp(lp)))

canonical = longest_match(TARGET, TOY_VOCAB)
canonical_lp = sequence_logprob(canonical, TOY_TABLE)
marginal = sum(prob for _, _, prob in seg_rows)
marginal_lp = math.log(marginal) if marginal > 0 else -math.inf

LN2 = math.log(2.0)
canonical_bpb = -canonical_lp / (N_BYTES * LN2)
marginal_bpb = -marginal_lp / (N_BYTES * LN2)
ConsoleOut [21]
CollapseExpand
target string: b'ab', 2 bytes
segmentations found: 2
  a b      prob=0.2400  bits/byte=1.0294
  ab       prob=0.0900  bits/byte=1.7370

canonical (longest match): ab
canonical-only bits/byte:  1.7370
marginalized bits/byte:    0.7997
gap in bits/byte:          0.9372

The canonical path has probability 0.09, and the marginal over both paths is 0.33. The canonical score is about 0.94 bits per byte higher on this example. A string outside the toy model's support has infinite negative log-likelihood.

The size of that pessimism is worth making visible. This chart compares the two numbers already computed for the toy string.

PythonIn [22]
CollapseExpand
import numpy as np

bpb_labels = ["canonical segmentation", "marginalized over segmentations"]
bpb_values = np.array([canonical_bpb, marginal_bpb])
bpb_positions = np.arange(len(bpb_labels))
bpb_width = 0.45
VisualizationOut [23]
CollapseExpand
Bar chart of canonical versus marginalized bits per byte in a two-byte toy example.
Canonical-segmentation-only bits per byte versus marginalized bits per byte for the two-byte toy string. The canonical score is higher because it ignores probability mass assigned to alternative segmentations.

When the canonical token path decodes to the scored bytes under the same EOS convention, its bits per byte are at least the marginal bits per byte for the same positive byte count. A positive-probability alternative path increases the marginal probability. With one content symbol per byte and a single termination convention, the byte string determines one content-symbol sequence.

A general autoregressive model can assign different next-token probabilities to token histories that decode to the same byte prefix. An exact algorithm needs to distinguish histories with different predictive states. The number of segmentations can grow exponentially in string length.

If every token appends a fixed nonempty byte string, an exact algorithm can sum the mass of paths that reach the same byte offset with the same predictive state. A unigram model needs only the offset. A first-order model also needs the preceding token. For a decoder whose output depends on earlier tokens, paths can be merged only if they also share a sufficient decoding state. A neural model can have as many distinct predictive states as paths. When exact summation is impractical, report the marginal approximation used.

Conditional Scores Are a Different Object

The previous examples score observed text without an external source sequence. For translation, teacher-forced likelihood scores a target given the source and the preceding target symbols. Decoding settings affect scores that evaluate the model’s own generated translation.

A compression score on held-out text and a quality measure on generated translations answer different questions. Use the metric and baseline appropriate to each evaluation.

Where the Compute Goes

Suppose a particular subword tokenizer represents a passage using one position for every four bytes on average. A direct byte model uses about four times as many content positions on that passage.

In a dense causal mask, the number of allowed attention pairs grows roughly with the square of the position count. Four times the positions give about sixteen times as many pairs for long sequences.

Measure the byte-to-token ratio on the actual corpus. Its value can vary with the tokenizer, domain, language and normalization.

Exact Position-Pair Counts

For a causal transformer with LL positions, the number of ordered query-key pairs that participate in attention, counting the diagonal, is

Ncausal(L)=∑i=1Li=L(L+1)2.N_{\text{causal}}(L) = \sum_{i=1}^{L} i = \frac{L(L+1)}{2}.

This is exact for dense causal attention with no sliding window and no sparse pattern. It is the quantity that scales quadratically.

Now consider a patched model. The byte sequence of length TT is partitioned into PP patches of sizes s1,…,sPs_1, \dots, s_P with ∑ksk=T\sum_k s_k = T. A global model attends over the PP patch representations. A local model attends over the bytes within each patch. The pair counts are

Nglobal=P(P+1)2,Nlocal=∑k=1Psk(sk+1)2.N_{\text{global}} = \frac{P(P+1)}{2}, \qquad N_{\text{local}} = \sum_{k=1}^{P} \frac{s_k(s_k+1)}{2}.

For equal patches of width ww with T=PwT = Pw, the local count becomes Pw(w+1)/2=T(w+1)/2P w(w+1)/2 = T(w+1)/2. Substituting P=T/wP = T/w into the global count and adding the local count gives the two terms below plus T/(2w)+T/2T/(2w) + T/2. Dropping those added terms gives the continuous width approximation.

Ntotal≈T22w2+Tw2.N_{\text{total}} \approx \frac{T^2}{2w^2} + \frac{Tw}{2}.

Treating the approximate pair count as a function of continuous width ww, differentiate it and set the result to zero to get the width that minimizes this proxy.

w⋆=(2T)1/3.w^\star = (2T)^{1/3}.

For T=106T = 10^6 bytes, this approximation gives w⋆≈126w^\star \approx 126 bytes. Integer widths and partially filled final patches change the exact counts.

This derivation is a useful sanity check on architecture design. It is not a performance model.

PythonIn [24]
CollapseExpand
import numpy as np

LENGTHS = np.unique(np.round(np.logspace(2, 6, 60)).astype(int)).astype(
    np.int64
)
WIDTHS = [64, 256, 1024]


def causal_pairs(n):
    return n * (n + 1) / 2.0


def patched_pairs(n, w):
    p = int(np.ceil(n / w))
    global_pairs = p * (p + 1) / 2.0
    local_pairs = 0.0
    remaining = n
    for _ in range(p):
        s = min(w, remaining)
        local_pairs += s * (s + 1) / 2.0
        remaining -= s
    return global_pairs + local_pairs


full_curve = np.array([causal_pairs(n) for n in LENGTHS])
patched_curves = {
    w: np.array([patched_pairs(n, w) for n in LENGTHS]) for w in WIDTHS
}
optimal_widths = np.array([(2.0 * n) ** (1.0 / 3.0) for n in LENGTHS])
optimal_curve = np.array(
    [
        patched_pairs(n, max(1, int(round(w))))
        for n, w in zip(LENGTHS, optimal_widths)
    ]
)
VisualizationOut [25]
CollapseExpand
Log-log line chart comparing quadratic attention pair counts against patched counts at three fixed widths, with a curve using the approximate minimizing width.
Exact causal attention position-pair counts for full attention and for patched attention at three fixed patch widths, on log-log axes. The dashed line uses the rounded width suggested by the leading-term approximation. Pair counts are an attention-only proxy and not a FLOP or latency measurement.

At one million bytes, full causal attention includes about 5.00×10115.00 \times 10^{11} pairs. Width 256 gives 3,907 patches including a final 64-byte patch. The global and local terms together give about 1.36×1081.36 \times 10^8 pairs, roughly 3,673 times fewer. The dashed curve chooses widths using the leading-term approximation and computes exact counts at those widths.

What Pair Counts Do Not Measure

Position-pair counts are exact for what they count and misleading for everything else. A production comparison needs four separate quantities, and conflating them is how architecture claims get overstated.

  • Pair-dependent work. Attention score and value operations scale with pair count, head width and head count. The attention softmax also runs over the allowed pairs. Include cross-attention pairs where the architecture uses them.
  • Per-position work. Count attention projections, feed-forward layers, normalization and any vocabulary projection at the positions and widths where they run. MEGABYTE emits byte-vocabulary logits in its local decoder. BLT also uses a local encoder. Global patch processing and local byte work may have different widths and layer counts.
  • Memory. Count cached positions, cache-bearing layers, KV heads, dimensions, and element sizes. Four times as many cached positions needs four times the KV payload only when the remaining layout and retention policy are the same. Training activation memory uses different accounting.
  • Runtime. Wall-clock time depends on kernel efficiency, occupancy, batch size, sequence length relative to the hardware's preferred tile size, and whether the implementation can keep the accelerator busy. A model with fewer FLOPs can be slower if its shapes are awkward.

In MEGABYTE and BLT, the global model works over patch positions while a local decoder generates at byte resolution. Fewer patches mean fewer global position updates for the same byte string. The number of sequential byte predictions remains fixed in the autoregressive decoding discussed here.

The four quantities can point in different directions, and that is the source of most of the confusion in the literature. For example:

  • A model can have fewer attention FLOPs and more total FLOPs, because the linear terms grew.
  • It can have fewer FLOPs and higher latency, because the kernels are less efficient.
  • It can have a smaller KV cache and a larger activation footprint, because the global and local models have different shapes.

A claim that a patched model is "more efficient" is incomplete until you say which quantity you mean and under what conditions you measured it.

We take up parallel and semi-autoregressive generation in Part XIX, Chapter 5, where the serial constraint is relaxed.

Architectures That Make Bytes Practical

Five research lines have shaped how byte-level modeling is done in practice. They differ in what counts as a position, in whether the grouping is fixed or learned, and in whether the model generates text.

The five are worth studying together because they are not variations on a theme. They are five different answers to the same question, which is how to recover the compression that a tokenizer used to provide. CANINE answers it with a fixed architectural stride. ByT5 answers it by declining to compress at all. MEGABYTE answers it with a fixed data layout. BLT answers it with an external uncertainty signal. H-Net answers it by learning the signal inside the model. Seeing them side by side makes the design space legible.

Code-Point Encoders with Downsampling (CANINE)

Clark and colleagues’ CANINE encodes Unicode code points with hashed embeddings. It applies a local attention layer before strided convolution reduces the sequence length seen by the deep Transformer encoder. The paper uses a stride of four. CANINE paper

Local attention composes nearby code points before downsampling. The deep Transformer then processes that shorter sequence. The reduction is relative to the code-point input; the length a subword tokenizer would produce depends on the text and tokenizer.

The hash tables cover the input code points without one embedding row per code point. Canonically equivalent sequences can still have distinct code-point inputs unless preprocessing normalizes them.

CANINE-C predicts bucketed code-point IDs from masked inputs. CANINE-S uses subword prediction targets during pretraining. Both feed code points to the encoder at inference.

The subword-target variant uses the tokenizer to define supervision while keeping code-point input at inference. Compare the variants on the individual tasks to determine where that supervision helps.

CANINE is an encoder that produces contextual representations. The paper's experiments used sequences of up to 2,048 code points, with 512 positions in the deep encoder at stride four.

Clark and colleagues evaluate the encoder on multilingual TyDi QA and NER. Their results show how a code-point encoder with downsampling can compete in the tested settings. CANINE paper

Byte-to-Byte Encoder-Decoders (ByT5)

Xue and colleagues’ ByT5 uses a T5-family encoder-decoder to model UTF-8 bytes. The paper describes 256 byte values and three reserved IDs for padding, end of sequence and an unused unknown marker. ByT5 paper

Relative to mT5, the authors use a smaller embedding vocabulary, allocate more model layers to the encoder than the decoder and adjust span corruption for byte sequences.

The paper compares ByT5 with mT5 at several model sizes. It reports competitive results and gains on selected tasks sensitive to character-level detail. Throughput depends on the length of the input and the target. Longer byte targets can impose a substantial decoding cost.

Those results are conditional on the paper's model sizes, datasets, and compute budget. They do not establish that byte models are universally more robust or universally more efficient. A reasonable reading is that the byte interface removes a class of tokenizer-induced failures and pays for it with sequence length. Whether the trade is worth it depends on the task.

An unusual spelling can change the subword segmentation and sequence length. A byte interface preserves the underlying bytes. The robustness experiments measure whether the trained model handles selected perturbations correctly.

An autoregressive byte decoder predicts each of the TT content bytes in the target, with another prediction if it emits EOS. A subword decoder uses the token count for the same target. Report the number of generated bytes and the latency along with decode steps when comparing both systems.

Fixed-Width Patches (MEGABYTE)

Yu and colleagues’ MEGABYTE splits the byte sequence into patches of width ww. A global Transformer attends over patch representations. A local Transformer generates the bytes of each patch using its global representation and the bytes already generated in that patch. The paper also describes a cross-patch variant that gives the local model access to trailing bytes of the previous patch. MEGABYTE, §2.3.2

The factorization is

pθ(b1:T)=∏k=1Ppθ(patchk∣patch<k),p_\theta(b_{1:T}) = \prod_{k=1}^{P} p_\theta(\text{patch}_k \mid \text{patch}_{<k}),

where PP counts the patches. The local model factorizes each patch probability autoregressively over its bytes. During autoregressive generation the global model advances once per patch and the local model advances once per byte. With fixed-width patches and fixed local context, local attention work per byte is bounded. Its total work grows linearly with byte count.

With fixed patch width, the total length of the local sequences grows linearly in the number of bytes. The global position count also grows with sequence length, so dense global attention retains a quadratic term. The width reduces the coefficient by reducing the count of global positions.

Fixed width gives a predictable number of patches for each byte length. The paper's 640 × 640 RGB ImageNet experiment processes 1,228,800 bytes per image. The dense Transformer baseline in that comparison uses 1,024-byte segments. The paper's text experiments include MEGABYTE configurations with 8,192-byte context on arXiv and PG-19. MEGABYTE, Tables 2, 3 and 5 and Appendix A.2

Fixed offsets can coincide with word boundaries or split words and multibyte scalars. A fixed-width schedule still advances the global model across predictable spans. Entropy-driven and learned routing vary that schedule with the content.

Entropy-Driven Patches (Byte Latent Transformer)

Pagnoni and colleagues’ Byte Latent Transformer uses next-byte entropy to place variable-width boundaries. A separately trained byte language model estimates the distribution of each byte from prior bytes. The paper compares an absolute entropy threshold with a threshold on increases relative to the previous entropy. Byte Latent Transformer paper

The boundary model’s entropy is its expected next-byte surprisal. BLT uses high entropy as a signal to allocate another patch. That makes the budget depend on the input. Whether the extra global step helps at a particular location is an empirical question.

The architecture has three parts. The local encoder contextualizes nearby bytes and builds each patch representation from the encoded bytes in that patch. The global Transformer attends over patch representations, and the local decoder uses global context to predict bytes. The entropy model supplies the patch boundaries. Byte Latent Transformer, §3

For BLT’s pre-byte boundary, the decision to start a patch at tt uses the entropy model’s distribution given b<tb_{<t}. It can be made before seeing the target byte. Check the shift from context outputs to predicted positions. A rule that allocates a representation after consuming the current byte needs a different account of which output it scores.

For logits computed at each input position, check which next position the logits predict before comparing entropies. A shift that lets the boundary for byte tt depend on byte tt exposes information unavailable before prediction.

Causal patch boundary

For this pre-byte rule, the boundary decision at byte position tt depends only on bytes before tt. A truncated input and its extension agree on boundary starts strictly inside the truncated input. The last patch of the truncated input can still be shorter.

Check agreement on boundary starts strictly inside a truncated prefix. To check whether a rule reads the current byte, also keep the first tt bytes fixed, change the byte at zero-based index tt, and compare the boundary decision at that index.

The authors report quality comparable to their tokenization-based baselines at scales up to 8 billion parameters and 4 trillion training bytes. They separately report configurations that trade small drops on evaluation metrics for up to 50% fewer inference FLOPs. They also report gains on some character-level perturbation benchmarks. Byte Latent Transformer, §§5 and 6

A fixed stride spends a global update at regular intervals. The entropy rule makes that allocation depend on the predictions of its boundary model. It cannot tell us by itself which extra updates improve the final model.

Learned Routing (H-Net)

Sukjun Hwang, Brandon Wang, and Albert Gu introduce H-Net, which learns dynamic chunk boundaries as part of a hierarchical model. The work appeared at ICLR 2026. ICLR 2026 proceedings

The routing module compares projected representations at adjacent positions using cosine similarity. It converts the score to a boundary decision. The downsampler selects the representations at those boundaries for the coarser level. H-Net paper

The authors use decompression smoothing and a straight-through estimator to train through discrete chunk decisions. BLT’s entropy threshold comes from a separate predictive model. H-Net learns its routing scores jointly with the model that uses them.

The reported results show H-Net outperforming BPE-based transformers at matched compute in the paper's settings, with the advantage persisting as scale increases. Those are results at the scales the paper tested, and hierarchical routing is a young technique. It is best read as evidence that learned grouping is a promising direction rather than as a settled replacement for either fixed patching or subword tokenization.

Comparing the Families

The five architectures answer different questions.

Comparison of tokenizer-free and byte-level architectures.
ModelInput unitGroupingGenerates textPrimary claim
CANINEUnicode code pointFixed stride downsamplingNoTokenizer-free encoding is competitive for understanding tasks
ByT5UTF-8 byteNoneYesDirect byte modeling works end to end, with length costs
MEGABYTERaw byte, including UTF-8 for textFixed-width patchesYesModels full 1,228,800-byte RGB images in the reported experiment
BLTUTF-8 byteEntropy-driven variable patchesYesVaries model size and patch width under fixed FLOP budgets in the reported scaling study
H-NetUTF-8 byteLearned routingYesGrouping can be learned end to end with the model

The progression from CANINE to H-Net is a progression in where the grouping decision lives. CANINE fixes it in the architecture. MEGABYTE fixes it in the data layout. BLT derives it from a separate model's uncertainty. H-Net learns it as part of the network. Each step moves more of the tokenizer's old job inside the model, which is the underlying theme of this whole part of the book.

Read the table with the caveats from the next section in mind. The "primary claim" column is a summary of what each paper argues, not a statement that the claim has been independently replicated. The models were evaluated on different data, at different scales, against different baselines, so the rows are not a leaderboard.

Synthetic Grouping Experiments

The claims above about patch structure are easy to state and hard to see. Let us build both a fixed-width grouper and a causal entropy grouper from scratch, run them on the mixed-script sample, and check the properties that matter.

The entropy grouper needs a next-byte distribution. Rather than train one, we will define a small synthetic conditional distribution that depends only on the previous byte's character class. It is an illustration of the mechanism, not an implementation of BLT, and the numbers it produces should not be read as measurements of anything.

PythonIn [26]
CollapseExpand
def byte_class(b):
    if b == 0x20:
        return "space"
    if 0x61 <= b <= 0x7A:
        return "lower"
    if 0x30 <= b <= 0x39:
        return "digit"
    return "other"


CLASS_OF = {b: byte_class(b) for b in range(256)}

WEIGHTS = {
    "space": {ord(c): 1 for c in "etaoinshrdlucmfwypvbg"},
    "lower": dict(
        zip((ord(c) for c in "eainorstl"), (50, 20, 10, 5, 3, 2, 1, 1, 1))
    ),
    "digit": dict(
        zip((ord(c) for c in "0123456789"), (40, 20, 10, 5, 5, 3, 2, 1, 1, 1))
    ),
    "other": dict(
        zip(
            (ord(c) for c in ".,\n-'\"()"),
            (30, 25, 20, 10, 8, 5, 2, 2),
            strict=True,
        )
    ),
}

FLOOR = 1e-6


def next_byte_distribution(prev_byte):
    weights = WEIGHTS[CLASS_OF[prev_byte]]
    total = float(sum(weights.values()))
    probs = np.full(256, FLOOR / 256.0)
    for b, w in weights.items():
        probs[b] += (1.0 - FLOOR) * w / total
    return probs


def entropy_bits(probs):
    p = probs[probs > 0.0]
    return float(-(p * np.log2(p)).sum())

The previous-space class puts almost all its mass uniformly over 21 letters. The previous-lowercase class has more concentrated weights. Compute each class’s entropy before choosing thresholds.

PythonIn [27]
CollapseExpand
class_entropies = {}
for name in ["space", "lower", "digit", "other"]:
    representative = {
        "space": 0x20,
        "lower": ord("e"),
        "digit": ord("1"),
        "other": ord("."),
    }[name]
    class_entropies[name] = entropy_bits(next_byte_distribution(representative))
ConsoleOut [28]
CollapseExpand
previous byte class space  -> next-byte entropy 4.392 bits
previous byte class lower  -> next-byte entropy 2.021 bits
previous byte class digit  -> next-byte entropy 2.340 bits
previous byte class other  -> next-byte entropy 2.530 bits

At a threshold of 3.0 bits, only the previous-space class exceeds the cutoff. Beyond the initial boundary, the toy starts patches only after spaces. BLT evaluates a separate space-based rule. Its entropy threshold, applied to estimates from a separately trained model, can place a boundary inside a word. Byte Latent Transformer, §2.3 and Figure 4

A zero probability contributes zero to entropy by the limit of −plog⁡2p-p\log_2 p as pp tends to zero. Observing a zero-probability byte has infinite surprisal under that distribution. The toy mixes in a small uniform distribution to give each byte positive probability. Softmax with finite logits also assigns positive probabilities in exact arithmetic, though floating-point exponentiation can underflow to zero.

Now define the two groupers. The fixed grouper cuts every ww bytes. The entropy grouper starts a new patch at position tt when the entropy of the distribution over byte tt given byte t−1t-1 exceeds a threshold. The entropy at tt is computed before byte tt is observed.

PythonIn [29]
CollapseExpand
def fixed_patches(ids, width):
    return [ids[i : i + width] for i in range(0, len(ids), width)]


def entropy_bounds(ids, threshold_bits):
    if not ids:
        return []
    bounds = [0]
    for t in range(1, len(ids)):
        if entropy_bits(next_byte_distribution(ids[t - 1])) > threshold_bits:
            bounds.append(t)
    return bounds


def entropy_patches(ids, threshold_bits):
    bounds = entropy_bounds(ids, threshold_bits) + [len(ids)]
    return [ids[bounds[i] : bounds[i + 1]] for i in range(len(bounds) - 1)]

Note that entropy_bounds reads ids[t - 1] when deciding about position t. Nothing at or after t is consulted. That is the causality property in code.

Run both groupers on the mixed-script sample and check that concatenating their patches reproduces the original bytes. For the entropy grouper, also check strict decoding, agreement on boundary starts strictly inside each truncated prefix, and whether changing the current byte affects a boundary decision when the preceding bytes stay fixed.

PythonIn [30]
CollapseExpand
GROUP_TEXT = "caf\u00e9 \u4e2d\u6587 \U0001f600 the quick brown fox"
GROUP_BYTES = GROUP_TEXT.encode("utf-8")
GROUP_IDS = list(GROUP_BYTES)

FIXED_W = 8
THRESHOLDS = [2.1, 3.0, 4.5]

fixed_groups = fixed_patches(GROUP_IDS, FIXED_W)
entropy_groups = {thr: entropy_patches(GROUP_IDS, thr) for thr in THRESHOLDS}


def reconstruct(groups):
    return b"".join(bytes(g) for g in groups)


fixed_ok = reconstruct(fixed_groups) == GROUP_BYTES
entropy_ok = {
    thr: reconstruct(groups) == GROUP_BYTES
    for thr, groups in entropy_groups.items()
}
decode_ok = {
    thr: reconstruct(groups).decode("utf-8") == GROUP_TEXT
    for thr, groups in entropy_groups.items()
}

prefix_ok = {}
for thr in THRESHOLDS:
    full = entropy_bounds(GROUP_IDS, thr)
    good = True
    for k in range(1, len(GROUP_IDS) + 1):
        pre = entropy_bounds(GROUP_IDS[:k], thr)
        if pre != [b for b in full if b < k]:
            good = False
            break
    prefix_ok[thr] = good

prediction_time_ok = {}
for thr in THRESHOLDS:
    starts = set(entropy_bounds(GROUP_IDS, thr))
    prediction_time_ok[thr] = all(
        (t in starts)
        == (t in entropy_bounds(GROUP_IDS[:t] + [replacement], thr))
        for t in range(1, len(GROUP_IDS))
        for replacement in (ord(" "), ord("a"), ord("1"), ord("."))
    )
ConsoleOut [31]
CollapseExpand
text: café 中文 😀 the quick brown fox
bytes: 37

fixed width 8: 5 patches, sizes [8, 8, 8, 8, 5]
  reconstruction ok: True

entropy threshold 2.1 bits: 19 patches, sizes [4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 6, 6, 3]
  reconstruction ok: True  decode ok: True
  prefix invariant: True  changed current byte: True
entropy threshold 3.0 bits: 7 patches, sizes [6, 7, 5, 4, 6, 6, 3]
  reconstruction ok: True  decode ok: True
  prefix invariant: True  changed current byte: True
entropy threshold 4.5 bits: 1 patches, sizes [37]
  reconstruction ok: True  decode ok: True
  prefix invariant: True  changed current byte: True

As the cutoff rises on this sample, the router produces fewer patches and the mean width grows. At 3.0 bits, each nonfinal patch ends at a space, so some patches contain a whole word and its trailing space. Byte reconstruction, strict decoding, prefix agreement, and the current-byte perturbation check all pass at every cutoff.

If concatenating the patches fails to reproduce the input bytes, the grouper has changed the byte sequence. A likelihood computed from that altered sequence would score different bytes.

The prefix check compares existing starts after truncation. The second check changes the current byte while holding prior bytes fixed. This tests current-byte dependence directly for the chosen replacements.

Let us plot the groupings as spans over byte positions so the difference in structure is visible.

PythonIn [32]
CollapseExpand
def spans(groups):
    out, start = [], 0
    for g in groups:
        out.append((start, len(g)))
        start += len(g)
    return out


fixed_spans = spans(fixed_groups)
entropy_spans = {thr: spans(entropy_groups[thr]) for thr in THRESHOLDS}
VisualizationOut [33]
CollapseExpand
Horizontal span chart showing patch extents over byte positions for fixed and entropy-based groupings.
Byte positions covered by each patch under a fixed-width grouper and a synthetic causal entropy grouper at three thresholds. Boundaries depend only on the preceding byte, so the grouping is prefix invariant. The router is a hand-built illustration and not an implementation of any published model.

Fixed-width patches contain eight bytes until the shorter final patch. With the 2.1-bit threshold, the toy router starts patches after spaces and bytes in its other class. At 3 bits only spaces trigger breaks. At 4.5 bits the whole example stays in one patch.

The toy illustrates how a threshold changes the placement and number of boundaries. In one BLT comparison, its entropy patcher averaged about 4.5 bytes per patch on the pretraining data mix. BLT also evaluates other average widths by changing the cutoff. Byte Latent Transformer, §§4.4, 5.2 and 5.3

Wider patches leave fewer global positions to process. The byte count and local byte positions stay the same across the rows.

Key Parameters

The key parameters for the grouping experiments are:

  • FIXED_W. Width of each full fixed-width patch in bytes. At a fixed byte count, increasing the width can reduce the number of global patch positions or leave it unchanged. Full patches contain more bytes, while the final patch size depends on the remainder.
  • THRESHOLDS. Entropy thresholds in bits. Increasing the cutoff can only remove boundary starts for a fixed set of entropies. No starts change if the two cutoffs lie between the same observed values.
  • FLOOR. The toy distribution mixes the base probabilities with a uniform distribution of total weight 10−610^{-6}. Every byte then has probability at least 10−6/25610^{-6}/256. Entropy itself can handle zero probabilities by treating their summands as zero.
  • threshold_bits (in entropy_bounds): The per-boundary cutoff; a boundary starts when next-byte entropy exceeds this value, using only the previous byte.

What the Evidence Supports

The empirical literature on byte-level models is young enough that its claims need careful reading. Several patterns are well supported and several are not.

What the evidence supports, within the settings that were tested:

  • Tokenizer-free encoding works for understanding tasks. CANINE reports results on multilingual TyDi QA and named entity recognition. CANINE-S improves SELECTP F1 by 2.8 points over mBERT in the authors' TyDi QA comparison. CANINE, §4.2
  • Byte-to-byte encoder-decoders work end to end. ByT5 trains and generates without a tokenizer and matches or exceeds mT5 on many tasks, with clear advantages on character-sensitive ones. The length cost is real and measurable.
  • Multiscale attention can process long raw-byte sequences. MEGABYTE processes 1,228,800 bytes per image in its 640 × 640 RGB ImageNet experiment. Its reported arXiv and PG-19 text configurations use 8,192-byte contexts. MEGABYTE, Tables 2, 3 and 5
  • Entropy-driven patching changes the quality–compute tradeoff. BLT reports quality comparable to subword baselines at the tested scales, and configurations with lower inference FLOPs and small metric drops. Byte Latent Transformer, §§5 and 6
  • Learned routing is competitive at the scales tested. H-Net's results show end-to-end learned chunking outperforming BPE baselines at matched compute in the paper's experiments.

What the evidence does not support:

  • That byte models are universally more robust. The robustness gains reported by ByT5 and BLT are on specific perturbation benchmarks and character-level tasks. A byte model can be more fragile on other distributions, particularly when the training data is dominated by one script.
  • That byte models are universally more efficient. Every efficiency claim in this literature is conditional on model scale, patch configuration, sequence length, hardware, and batch size. BLT's FLOP savings at large scale do not imply savings at small scale, and FLOP savings do not imply latency savings.
  • That tokenizers are obsolete. When a subword encoding uses fewer positions than a byte encoding for the same text, it lets the model fit more of that text into the same position budget.
  • That the architectural comparison is settled. The five studies above use different datasets, scales, and baselines. To compare the architectures directly, hold the training data, compute budget, and evaluation protocol fixed.

The asymmetry between the two lists is itself informative. The supported claims tend to be about whether a technique works at all in a particular setting. The unsupported claims tend to be about whether a technique dominates another in general. That pattern is common in a young literature, and it is a reason to read "byte models are better" claims with the same skepticism you would apply to any other universal claim.

As with subword models, check for overlap between benchmark text and training data. Use a documented overlap test on matched representations, such as consistently normalized text or byte spans.

Evaluating Byte-Level Systems Fairly

Suppose you have a byte model and a subword model and you want to know which one to deploy. The comparison has more moving parts than it first appears, and a careless table will mislead you. Here is a protocol that at least avoids the obvious errors.

Match the content. Evaluate on the same held-out byte spans and disclose normalization, EOS scoring and context-window policies. At an observed average of four bytes per subword position, 8,192 subword content positions cover about 32,768 bytes, compared with 8,192 bytes at one byte per position. Measure the ratio on the evaluated documents. If a model cannot score the chosen span under its supported length limits, report that limit or apply a shared truncation rule and score the resulting common span.

Compute bits per byte on the same encoded held-out documents. State whether EOS is included in the loss. For a subword model, state whether the score uses the canonical tokenization or estimates the sum over segmentations.

Separate unconditional compression from conditional task scores. A bits-per-byte figure from a monolingual corpus and an exact-match score from a translation benchmark are different measurements of different things. Report them in separate tables with separate baselines.

Report bytes per second and latency, not just FLOPs. For a generation workload, the quantities that matter are time to first byte, bytes per second at steady state, and p99 latency under realistic batching. A model with fewer FLOPs can be slower if its kernels are inefficient or its batch shapes are poor. Report the hardware, the batch size, the sequence length distribution, and the number of concurrent requests.

Report throughput at equal quality, not at equal parameters. A byte model with more parameters but shorter effective sequences may be the better deployment. A subword model with fewer parameters but a larger vocabulary may be worse for small devices because of embedding memory. The comparison that matters is quality at a fixed latency budget or latency at a fixed quality target.

Test the failure modes. Generate with the byte model under sampling and check how often it emits invalid UTF-8, how often it emits valid but nonsensical text, and how it behaves on the tail of the distribution. Check the same for the subword model's handling of rare strings and unknown characters. These are the cases where the interface difference shows up most clearly.

Report the tokenizer's own cost. A subword model ships a tokenizer that must be maintained, versioned, and applied consistently. Its training cost, its failure modes on unusual input, and its interaction with the serving stack are part of the total system cost. Byte models remove this line item, which is a real advantage even when the model itself is not faster.

Measure throughput and latency on the serving hardware under the intended workload. Two models with similar FLOP counts can run at different speeds when their sequence lengths and kernel shapes differ.

Limitations & Impact

Byte-level models can need more positions for the same text. The multiplier depends on the tokenizer, normalization and corpus, so measure it on the workload. More positions can increase attention cost, KV cache memory and serial generation steps. Patching reduces the number of global positions while the autoregressive local decoder still generates one byte at a time.

The model must learn from its data how bytes form text units. The useful context captured by a patch depends on the architecture, routing rule and training distribution. Measure quality on tasks that depend on preserving those details.

Tools that report throughput, cost or attribution per model position need a declared unit. A patch is a unit of global-model work. Bytes are a unit of throughput at the external interface.

The tooling gap is easy to underestimate because it is invisible until you try to do something practical. A profiler that reports cost per token needs to know what a token is. An attribution method that highlights the input spans responsible for an output needs a segmentation to highlight. A rate limiter that charges per token needs a unit to charge. None of these is insurmountable, but each one is a small piece of engineering that has to be redone, and the aggregate cost is real.

The byte interface supports Unicode scalar-value strings in any script under a specified UTF-8 policy. A system can also model arbitrary bytes when it uses a raw byte interface. Tasks that generate files need checks for the required format.

To reproduce a fitted tokenizer's output, record its model artifact, preprocessing settings, and implementation version. A SentencePiece model file, for example, can store the pieces and the normalization specification. For well-formed UTF-8 input, conforming strict decoders produce the same sequence of scalar values. SentencePiece model schema · RFC 3629, §§3–4

ByT5 and BLT report improvements on some character-level perturbations in their tested settings. A model may still be sensitive to examples or scripts uncommon in its training data. Input representability follows from the encoding policy. Interpretation of those inputs remains an empirical question.

A separately fitted subword tokenizer can supply a fixed segmentation during language-model training, as in mT5. The byte hierarchies here choose their own grouping. MEGABYTE uses fixed widths, BLT can use predicted uncertainty, and H-Net learns its boundaries during training. Each choice determines how often the global model runs. The next chapter examines diffusion language models, followed by blockwise and semi-autoregressive generation. mT5, §3.2

Summary

Direct byte models use the 256 byte values as content symbols. Other tokenizer-free designs can use Unicode code points or learn coarser positions from bytes.

Track Unicode scalar values, UTF-8 bytes and model positions separately. The precomposed and decomposed spellings of café differ by one scalar value and one byte in the example.

UTF-8 under RFC 3629 uses one to four bytes per scalar value, excludes surrogates, and uses the shortest encoding with a maximum of U+10FFFF. Valid UTF-8 sequences are a proper subset of all byte sequences.

A valid UTF-8 string can have an incomplete byte prefix. Incremental decoders can buffer trailing bytes until a later chunk or final flush. Report the policy for rejecting, regenerating or repairing malformed output, and use byte-level constraints when every emitted prefix must admit a valid UTF-8 completion.

A normalization policy selects which text distinctions to preserve. NFC and NFKC compose the sample accent. NFD and NFKD keep it decomposed. Compatibility mappings can erase distinctions such as the ligature in the example.

The autoregressive byte model scores content bytes and a separate EOS outcome, starting from unscored BOS context. If the canonical token path decodes to the same bytes and uses the same EOS convention, the probability of that path with EOS lower-bounds the marginal string probability. Dividing the negative base-two logs of both probabilities by the same positive content byte count gives canonical bits per byte at least as large as marginal bits per byte. The two-byte example gives a gap of about 0.94 bits per byte.

Dense causal attention includes L(L+1)/2L(L+1)/2 pairs at length LL. Splitting the input into patches changes the global and local position counts. Pair counts compare masks. FLOPs, cache size and latency also depend on model and implementation details.

The five examples make different grouping choices. CANINE encodes code points with strided downsampling. ByT5 uses a byte-to-byte encoder-decoder. MEGABYTE uses fixed-width patches with global and local autoregressive models. The Byte Latent Transformer derives variable patch boundaries from next-byte entropy computed from the preceding bytes. H-Net learns routing jointly inside a hierarchical model.

Efficiency and robustness results depend on the model sizes, data, and evaluation settings. Compare bits per byte on the same scored bytes and state the EOS and context-window policies. Report conditional task scores, bytes per second and latency on the declared workload. A byte vocabulary represents every input byte directly. An unconstrained output distribution can assign positive probability to malformed UTF-8.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about token-free and byte-level language models.

Token-Free and Byte-Level Language Models

Question 1 of 80 of 8 completed
In the chapter's mixed-script example, the precomposed string café (with U+00E9) is described as 4 scalar values and 5 bytes, while the decomposed café (e plus U+0301) is 5 scalar values and 6 bytes. What is the main point this example makes?
Join the discussionAsk a question or share what you learned.

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!

A different angle
All writing
Language AI Handbook · Vol. 6

Comparing Architecture Families Fairly

Learn how to compare Transformer, SSM, and hybrid architectures fairly with matched compute, bits per byte, roofline cost models, and clustered uncertainty.

64 min read
Language AI Handbook · Vol. 6

Blockwise and Semi-Autoregressive Generation

Explore semi-autoregressive block generation, blockwise parallel decoding, and exact speculative sampling with acceptance and residual repair rules.

42 min read
Language AI Handbook · Vol. 6

Diffusion Language Models

Learn how masked diffusion language models corrupt text with absorbing masks, bound likelihood, sample in parallel, and evaluate quality and compute.

45 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026tokenfree, author = {Michael Brenndoerfer}, title = {Token-Free and Byte-Level Language Models}, year = {2026}, url = {https://mbrenndoerfer.com/writing/token-free-byte-level-language-models-utf8-architectures}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-11-25} }
APAAcademic
Michael Brenndoerfer (2026). Token-Free and Byte-Level Language Models. Retrieved from https://mbrenndoerfer.com/writing/token-free-byte-level-language-models-utf8-architectures
MLAAcademic
Michael Brenndoerfer. "Token-Free and Byte-Level Language Models." 2026. Web. November 25, 2026. <https://mbrenndoerfer.com/writing/token-free-byte-level-language-models-utf8-architectures>.
CHICAGOAcademic
Michael Brenndoerfer. "Token-Free and Byte-Level Language Models." Accessed November 25, 2026. https://mbrenndoerfer.com/writing/token-free-byte-level-language-models-utf8-architectures.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Token-Free and Byte-Level Language Models'. Available at: https://mbrenndoerfer.com/writing/token-free-byte-level-language-models-utf8-architectures (Accessed: November 25, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Token-Free and Byte-Level Language Models. https://mbrenndoerfer.com/writing/token-free-byte-level-language-models-utf8-architectures
Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy