Token-Free and Byte-Level Language Models › The Autoregressive Byte Model

Michael BrenndoerferNovember 17, 20268 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 135Token-Free and Byte-Level Language Models › The Autoregressive Byte Model
Reading section 4 of 13 · The Autoregressive Byte Model · 8 minSection 4 of 13 · 8 min

Section 4 of 13 · 8 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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.

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