Session S17

Transformer II

How do S16's pieces assemble into one block, how do we prove its mask hides the future, which half of the original model do today's models keep, and what exactly is a token?

Deep Learning · CS 4715/5715 · University of Idaho

The proposal, HW2 and HW3 come next

Before the material, three items.

  • Project proposal: due at the end of the week after next (the S23 week). A 1–2 page document, no code; build it on your pre-proposal feedback. Teams of 1–3 (CS 5715: 1–2); every member submits.
  • Fair comparison: a well-designed experiment where the simple baseline wins is a successful project. Details and rubric: the project guide on the course site.
  • Next session (S18): HW2 due; HW3 (Transformer from scratch) out, due in two weeks (S22). It builds today's mask and block.

S16 named five pieces but did not yet assemble them into one block

Today starts where S16 ended: S14's three lacks answered by five pieces. S16 ran the first two as code and named the last three; none is assembled into a block yet.

piecewhat it does
multi-head attention\(h\) heads, each S14's attention formula in \(d_{\text{head}}=d_{\text{model}}/h\) dimensions, concatenated and multiplied by \(W_O\); (B, T, d_model) in and out
positional encodinga position-dependent vector added to each token's embedding; without it, shuffling the tokens only reorders the outputs
residual connectionevery sublayer computes \(\mathbf{x}+\operatorname{sublayer}(\mathbf{x})\): S10's identity path for the gradient
layer normalizationstandardizes each token's \(d_{\text{model}}\) features, then a learned scale and shift; no batch statistics
feedforward network (FFN)Linear(d_model, d_ff), GELU (S02), Linear(d_ff, d_model), \(d_{\text{ff}}=4\,d_{\text{model}}\): the nonlinearity within each position, about two-thirds of a block's parameters

Attention mixes across positions; the FFN transforms within one. S16 left two things for today: where each LayerNorm goes, and the causal mask its code left out.

Today builds the block and its mask, then turns to stacks and tokens

The title page's question has four clauses (bold): Part 1 answers the first two, Parts 2 and 3 one each.

partthe question it answers
1 · One blockhow do the pieces assemble into one block, and how do we prove its mask hides the future? The two update lines, where the LayerNorm goes, the code, the mask and its test, two bugs
2 · Which stack to keepwhich half of the original model do today's models keep? The full model, its two stacks, three families and their training objectives, choosing one
3 · What a token iswhat exactly is a token? Byte-pair encoding (BPE) by hand, the vocabulary size and its costs, real text and byte-level BPE, two other algorithms, a checkpoint's own tokenizer
4 · Closetoday's answer; next session S18 (HW2 due, HW3 out)

First, the block.

The block is two lines that wrap both sublayers the same way

Part 1 · One block. Both sublayers get the same wrapping: a LayerNorm (LN) on the input, the sublayer, the input added back. Attention first, then the FFN:

\[\mathbf{x}\leftarrow\mathbf{x}+\operatorname{MHA}\big(\operatorname{LN}_1(\mathbf{x})\big),\qquad \mathbf{x}\leftarrow\mathbf{x}+\operatorname{FFN}\big(\operatorname{LN}_2(\mathbf{x})\big)\]
x residual: x added backresidual: x added back LN1MHALN2FFN ++ x mixes across positionswithin each position
  • MHA: multi-head self-attention. \(\operatorname{LN}_1\), \(\operatorname{LN}_2\): two LayerNorms, each with its own learned scale and shift.
  • Every arrow carries (B, T, d_model): both sums need equal shapes.
  • LayerNorm before each sublayer is called pre-norm. The 2017 paper placed it elsewhere; after the shapes and the parameter count, Part 1 compares the two.

The block's output has its input's shape, so blocks stack

Reading 3.4's one-page version of this block (its own code, these sizes: \(B=2\), \(T=8\), \(d_{\text{model}}=64\), 4 heads, \(d_{\text{ff}}=256\)) lists the shape of every intermediate:

xLN1QKVsplit into4 headsconcat, proj+qkv(LN(x))q per headscoresattn @ v(2, 8, 64)(2, 8, 192)(2, 4, 8, 16)(2, 4, 8, 8)(2, 4, 8, 16)(2, 8, 64)every position vs every positionLN2ffn hidden(2, 8, 256)dff  = 4 dmodel (2, 8, 64)+y(2, 8, 64)same shape as xEach block has one row per position (8 rows)and a width proportional to its last dimension.Every tensor has batch 2 in front.The labels are the shapes reading 3.4’sscript prints.
  • In (2, 8, 64), out (2, 8, 64): \(N\) identical blocks chain with no reshaping.
  • Inside, widths change (\(3\,d_{\text{model}}\) for Q, K, V; 16 per head; 256 in the FFN), and each sublayer returns to \(d_{\text{model}}\) before its sum.

Counted by hand, two-thirds of the 49,984 parameters are in the FFN

Reading 3.4's script prints 49,984 parameters: attention 16,640 and FFN 33,088. Counted term by term, a Linear(n_in, n_out) has \(n_{\text{in}}\cdot n_{\text{out}}\) weights and \(n_{\text{out}}\) biases; here \(d_{\text{model}}=64\), \(d_{\text{ff}}=256\).

  1. Attention (S16's class): qkv \(64\cdot192+192=12{,}480\); proj \(64\cdot64+64=4{,}160\); together \(16{,}640=4\,(64^2+64)\).
  2. FFN: \(64\cdot256+256=16{,}640\) and \(256\cdot64+64=16{,}448\); together \(33{,}088\).
  3. Two LayerNorms: a scale and a shift per feature, \(2\cdot64=128\) each; together \(256\).
total 49,984attention 16,640FFN 33,08833,088 / 49,984 = 0.662LayerNorms256The FFN holds about two-thirds, as S16 derived (8d2  against 4d2 , biases aside).

The mask, the softmax and the residual sums add no parameters (reading 3.3), and moving a LayerNorm adds none: where it goes is the choice S16 left open.

The LayerNorm can go on the residual stream (2017) or on the branch

The same pieces, two arrangements; the blue line is the residual stream \(\mathbf{x}\), the branch below holds the sublayer:

post-norm (2017)pre-norm (GPT-2 onward; HW3) xxxx LNLNsublayersublayer ++ the stream passes through LNthe stream: never normalized

Post-norm (Vaswani et al.): \(\mathbf{x}\leftarrow\operatorname{LN}\big(\mathbf{x}+\operatorname{sublayer}(\mathbf{x})\big)\). The sum is normalized: the stream itself passes through a LayerNorm after every sublayer.

Pre-norm (most models since GPT-2): \(\mathbf{x}\leftarrow\mathbf{x}+\operatorname{sublayer}\big(\operatorname{LN}(\mathbf{x})\big)\). Only the sublayer's input is normalized; the stream is never normalized.

What differs is what the stream passes through: a LayerNorm after every sublayer in post-norm, none in pre-norm.

Pre-norm is a common default since the output is the input plus a sum

Why the place matters: stack \(L\) sublayers \(F_0,\dots,F_{L-1}\) and follow the stream from \(\mathbf{x}_0\) to \(\mathbf{x}_L\).

  1. Pre-norm: \(\mathbf{x}_{l+1}=\mathbf{x}_l+F_l(\operatorname{LN}_l(\mathbf{x}_l))\), so \(\mathbf{x}_L=\mathbf{x}_0+\sum_{l=0}^{L-1}F_l(\operatorname{LN}_l(\mathbf{x}_l))\).
  2. Post-norm: \(\mathbf{x}_{l+1}=\operatorname{LN}_l(\mathbf{x}_l+F_l(\mathbf{x}_l))\); each LayerNorm divides by its input's standard deviation (S16).
pre-normx0 LNF0 +LNF1 +LNF2 +x3 A route through sums onlygives ∂x3/∂x0 = I plusthe branches’ terms: S10’sidentity path, at any depth.post-normx0 F0 +LNF1 +LNF2 +LNx3 Every route passes through3 LayerNorms, so there is no term I.
  • Readings 3.3 and 3.4: pre-norm leaves the residual stream unnormalized end to end and is generally easier to train deep; deep post-norm stacks lean on a learning-rate warmup.
  • No stronger than that: post-norm can reach slightly better tuned quality, and large recipes still tune warmup, initialization, residual scaling and gradient clipping either way.

The block in PyTorch runs the two update lines

Reading 3.3's class (imports torch, torch.nn as nn); forward is the two update lines. Its attention is S16's MultiHeadSelfAttention plus one argument, causal, which adds two lines before the softmax.


class TransformerBlock(nn.Module):
    """Pre-norm block: x + Attn(LN(x)), then x + FFN(LN(x))."""
    def __init__(self, d_model, n_heads, d_ff):
        super().__init__()
        self.ln1 = nn.LayerNorm(d_model)
        self.attn = MultiHeadSelfAttention(d_model, n_heads)
        self.ln2 = nn.LayerNorm(d_model)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model))
    def forward(self, x, causal=True):
        x = x + self.attn(self.ln1(x), causal=causal)
        x = x + self.ffn(self.ln2(x))
        return x
  
  • ln1, ln2: one LayerNorm per sublayer. HW3's TransformerBlock keeps these names (its grader inspects them), fixes \(d_{\text{ff}}=4\,d_{\text{model}}\), and takes a (T, T) mask, not causal.

The block is assembled except for those two lines; the causal mask comes next.

A language model is a classifier over the vocabulary at every position

The causal mask follows from how a language model is trained. \(V\) is the vocabulary size, the number of distinct tokens, and \(x_t\) is token \(t\).

  • Output: at every position the model gives \(V\) logits, and a softmax turns them into a distribution over the next token: S03's multiclass classification, with \(V\) classes.
  • Loss: S03's cross-entropy against the true next token, averaged over the \(T\) positions: \[L=-\frac{1}{T}\sum_{t=0}^{T-1}\log p\big(x_{t+1}\mid x_0,\dots,x_t\big)\]
  • An RNN (S13) computes one step at a time: \(\mathbf{h}_t\) has read only \(x_0\) to \(x_t\), no later token.
  • A Transformer computes all \(T\) positions in one pass, for speed (next page). Then the attention at position \(t\) can see every token, including \(x_{t+1}\), the token it must predict, so it needs a mask.

One pass predicts every next token, so no position may see its answer

In training, the inputs the cat sat on the are the true text, not the model's own guesses, and the targets are the same text shifted by one token (teacher forcing):

targetpredictsinputcat0thesat1caton2satthe3onmat4the×maskedposition 3 sees tokens 0 to 3Five positions give fivenext-token examples inone forward pass.

Without a mask, the keys of position \(t\) would include token \(t+1\), the very token it must predict, so no query may see a key after its own position.

One forward pass over \(T\) tokens gives \(T\) next-token examples, each from its own past only.

The causal mask blocks every key after the query, before the softmax

So query \(t\) must not see keys after \(t\). The two lines causal adds, at \(T=4\), with equal scores so the weights can be checked by hand:


import torch
T = 4
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
scores = torch.zeros(T, T)                      # equal scores: weights by hand
scores = scores.masked_fill(mask, float("-inf"))
print(mask)
print(torch.softmax(scores, dim=-1))
  
scores after masked_fillweightskey0123key0123query012301−∞0−∞0−∞0= 101/201/2−∞0−∞0= 101/301/301/3−∞0= 101/401/401/401/4= 1softmax,row by rowmask = True: key after queryThe grids are the two prints above: grey cells get weight 0,and the fractions print as 1.0000, 0.5000, 0.3333 and 0.2500.
  • triu(..., diagonal=1) is True strictly above the diagonal, in the grey cells, where key \(j\) comes after query \(i\).
  • \(-\infty\) before the softmax: \(e^{-\infty}=0\), so row \(t\) shares its weight among keys 0 to \(t\).
  • HW3's causal_mask(T) is the complement, tril (True = may attend): mask the scores with ~mask. HW3's TransformerBlock takes this (T, T) tensor itself as mask, instead of a causal flag.

The perturbation test edits token 5 and measures each position's change

Does the mask hide the future? Reading 3.3's perturbation test: TransformerBlock(64, 4, 256), seed 0, x of shape (2, 8, 64). Replace token 5's vector with a new random one, run the block on both inputs, print each position's largest change; then the same edit with causal=False.


# TransformerBlock from slide 10; seed 0
torch.manual_seed(0)
B, T, d_model, n_heads, d_ff = 2, 8, 64, 4, 256
block = TransformerBlock(d_model, n_heads, d_ff)
x = torch.randn(B, T, d_model)
y = block(x)
x2 = x.clone()
x2[:, 5, :] = torch.randn(B, d_model)
y2 = block(x2)
diff = (y2 - y).abs().amax(dim=(0, 2))  # max abs change per position
for t in range(T):
    print(f"position {t}: max |change| = {diff[t].item():.6f}")
y_nc, y2_nc = block(x, causal=False), block(x2, causal=False)
diff_nc = (y2_nc - y_nc).abs().amax(dim=(0, 2))
print(f"no mask, positions 0-4 max |change| = {diff_nc[:5].amax().item():.6f}")
  

Before running it: which positions may change, and which must not change at all?

The outputs before the edited token match to the last bit

The 0.000000 at positions 0–4 is not rounding: with the mask, position \(t\)'s output is computed from tokens \(0\) to \(t\) only.

max |change|with the mask0.0000000.0000000.0000000.0000000.0000003.3577780.2685590.215717inputtoken012345 edited67With the mask, token 5 reaches only positions 5 to 7.no maskcausal=False: positions 0–4 change by up to 0.205075
  1. Attention: weights on keys after \(t\) are \(e^{-\infty}=0\) exactly; later tokens add \(0\cdot\mathbf{v}_j\).
  2. Projections, LayerNorm, the FFN and the sums act on each position alone.
  3. So positions 0–4 repeat the same arithmetic on the same numbers: equal to the last bit (HW3's test allows \(10^{-6}\)).

Two one-line bugs in the mask, and the test catches both

All of this needs the mask exactly right. Reading 3.3 warns of two mistakes: an off-by-one in triu, and masking after the softmax. Each is one line away from the correct class; both run through the same test with the same weights:

correct (diagonal=1)10001/21/2001/31/31/301/41/41/41/40.0000000.0000000.0000000.0000000.000000diagonal=010001/21/2001/31/31/30all −∞: 0/0 = NaNnan0.0000000.0000000.0000000.000000masked after the softmax1/41/41/41/41/41/41/41/41/41/4sum 0.25sum 0.5sum 0.75sum 1the denominator still counts the future keys0.0074090.0054750.0098780.0109810.012591The grids are computed with equal scores at T = 4, as on the causal-mask page;the five numbers under each grid are the test’s largest change at positions 0–4.
  • diagonal=0 also blocks the diagonal, so position 0 sees no key at all; its row is all \(-\infty\), and the softmax returns \(0/0\), NaN.
  • Masking after the softmax: each weight's denominator \(\sum_k e^{s_{tk}}\) runs over all keys, the future included, so the past moves by 0.005 to 0.013 when the future does.

HW3's test_causality_property runs this same test on the model you build.

Padded keys' scores get \(-\infty\) before the softmax, never after

The same rule, \(-\infty\) before the softmax, handles a second mask: a batch fills its shorter sequences with padding, filler positions that make all lengths equal. A padded key still has a vector, so it gets a score; it must get weight 0.

  • Add \(-\infty\) to padded keys' scores before the softmax: \(e^{-\infty}=0\), and the rest still sum to 1. The max subtraction (S03) stays finite: the row max is a real key's score.

# np, softmax as in S14. S14's animal scores; key 2 is padding
scores = np.array([[2.0, 0.0, 1.9]])
pad = np.array([0.0, 0.0, -np.inf])      # -inf on the padded key
w = softmax(scores + pad, axis=-1)       # mask before the softmax
print(np.round(w, 4), w.sum(axis=-1))
w_after = softmax(scores, axis=-1) * np.array([1.0, 1.0, 0.0])
print(np.round(w_after, 4), np.round(w_after.sum(axis=-1), 4))
  
seq 1seq 2scores+ maskweightstokentokentokentokentokenpadkey 0key 1key 22.00.01.900−∞0.88080.11920the paddedkey gets 0

[[0.8808 0.1192 0.    ]] [1.]
[[0.4902 0.0663 0.    ]] [0.5565]
  
  • Masked before, the padded key gets 0 and the row sums to 1.
  • Zeroing it after the softmax loses its share: the row sums to 0.5565, which S14's row-sum assert catches.

Both masks add \(-\infty\) before the softmax and never zero weights after it.

A leak shows in training as a loss below what the data allows

The second bug, masking after the softmax, is the dangerous one (reading 3.3). Train a one-block causal language model (embeddings, one block, a head to the vocabulary; \(d_{\text{model}}=32\), \(T=16\)) on uniformly random tokens from a vocabulary of 16, a fresh batch every step. The next token cannot be predicted, so the best a model that does not see it can do is give each of the 16 tokens \(\tfrac1{16}\), and its loss (slide 11) averages at least \(-\ln\tfrac1{16}=\ln16\approx2.77\); any other split averages more:

0123loss1100200300500stepfloor: ln 16 ≈ 2.77ln 16/16≈ 2.92, all three2.3910.9220.393correct mask 2.773masked aftersoftmax 0.207no mask 0.177
  • Correct: stays at \(\ln16\); there is nothing to learn.
  • After the softmax: below 2.77 by step 200: it learns to read the next token through the denominators.
  • No mask: 0.393 by step 100: the target is one of the keys, except at the last position (hence 0.177, near \(\ln16/16\)).

Same initial weights and batches in all three; 4 heads, batch 32, Adam (lr 0.003).

The symptom is a training loss better than the data allows, and a model useless at generation, where the future does not exist yet.

Self-check on update lines, examples per pass and a suspicious loss

Three questions on Part 1. In (c), as on the previous page, every training batch is new.

(a) Write the two pre-norm update lines. Where does post-norm's LayerNorm go?

(b) One forward pass over 32 sequences of 128 tokens: how many next-token examples, and which tokens does position 10's example see?

(c) Random tokens, vocabulary 32: a causal model's training loss reaches 0.5. Conclusion? Next step?

(a) \(\mathbf{x}\leftarrow\mathbf{x}+\operatorname{MHA}(\operatorname{LN}(\mathbf{x}))\), \(\mathbf{x}\leftarrow\mathbf{x}+\operatorname{FFN}(\operatorname{LN}(\mathbf{x}))\); post-norm: \(\operatorname{LN}(\mathbf{x}+\operatorname{sublayer}(\mathbf{x}))\).

(b) \(32\cdot128=4{,}096\); tokens 0–10.

(c) The floor is \(\ln32\approx3.47\); 0.5 on new batches is a leak. Run the perturbation test (slide 14).

That settles the block and its mask. Next comes the model around it.

The full model runs \(N\) blocks between an embedding and a head

Part 2 · Which stack to keep. A block maps (B, T, d_model) to itself. A language model starts from token ids and ends with a score for every vocabulary entry (reading 3.3); \(d=d_{\text{model}}\), \(V\) = vocabulary size:

ids(B, T)logits(B, T, V) embeddingtable V × d+ positionsN blocksfinal LNlinear headd × V (B, T, d)(B, T, d)(B, T, d)(B, T, d)(B, T, V)
  • Embedding: row id of a \(V\times d\) table (reading 3.1); positions added as in S16.
  • Final LayerNorm: pre-norm blocks never normalize the stream, so one LayerNorm does, before the head (HW3's ln_f).
  • Head: a \(d\times V\) matrix, one logit per vocabulary entry at every position; a softmax over the \(V\) entries gives the next-token distribution (S03).
  • HW3's TinyLM is this model: token embedding, learned position embedding, \(N\) blocks, final LayerNorm, and a linear head with its own matrix (untied from the embedding table).

The 2017 model's encoder sees all, and its decoder sees the past

That model is one stack of blocks. The 2017 model translated, so it had two (the readings call them towers). Which keys each query may see (rows: queries, columns: keys, filled: allowed):

encoder self-attention decoder self-attention cross-attention source × source (5 × 5): alltarget × target (4 × 4): itself and earliertarget × source (4 × 5): all
sourceencoder: N blocksunmasked self-attention, FFNencoder outputskeys and values (S14’s wiring 1)The grids above are the threeattentions in this picture.target, written so fardecoder:N blockscausal self-attentionqueriescross-attentionFFNheadnext targettoken

Later work (2018–2020) found that you rarely need both stacks. Which one you keep, and the objective it is trained on, defines the model families.

Three families differ in stack, attention and training objective

Reading 3.4's comparison, the rows that decide. HW3's TinyLM is the middle column: one causal stack, the architecture next-token prediction trains:

encoder-only (BERT, 2019)decoder-only (GPT, 2018 on)encoder–decoder (T5, 2020)
stack and attentionencoderbidirectionaldecoderno cross-attentioncausalencoderdecodercross-attentionbidirectional incausal out
objectivemasked language modeling (MLM): hide 15% of the tokens, reconstruct them from both sidesnext-token predictiontext-to-text: input into the encoder, answer out of the decoder
built forclassification, embeddings and retrieval, taggingdialogue, code, instruction followingtranslation, summarization
generates?no native left-to-right wayyes, left to rightyes, left to right

BERT has no causal decoder: generation methods can be built around masked models, but none is native (reading 3.4).

BERT cannot train on next-token prediction because it sees the answer

Next-token prediction asks position \(t\) for token \(t+1\). Without a causal mask, token \(t+1\) is one of position \(t\)'s keys.

causal (GPT)thecatsatonthematIt predicts token 4, the,which it cannot see.no maskthecatsatonthematIts target, token 4, is oneof its keys.satBERTthecat[MASK]onthematBERT hides 15% of the inputtokens and predicts themfrom both sides.
  • Part 1 measured it: without the mask, editing token 5 moved positions 0–4 by up to 0.205, and training reached 0.393 by step 100, far below \(\ln16\approx2.77\).
  • Two different masks: the causal mask hides keys; BERT's masking hides input tokens.
  • The price: no native left-to-right generation; when generating, the right-hand side does not exist yet.

Next-token training needs causal attention: no position sees its target.

Next-token prediction is the objective that scaled

Next-token prediction needs no labels (nor does BERT's objective), and every position of every text is an example, where BERT predicts only the 15% it hides. The GPT line kept that objective and scaled it:

  • GPT-2 (1.5B parameters, 2019): zero-shot results, tasks done without training on them, made next-token prediction the objective to beat (reading 3.4).
  • GPT-3 (175B, 2020): many tasks done with no gradient updates at all (reading 3.5, S18).
  • Today: decoder-only causal models dominate public general-purpose large language models (LLMs), such as the GPT and Llama families.
  • Encoder–decoders still compete: Flan-T5 (2022), T5 fine-tuned on about 1,800 tasks phrased as instructions, competed with much larger decoders; T5Gemma (2025) turns Google's Gemma decoders into encoder–decoders.

Decoder-only dominance is practice, not a theorem: one decoder reads the prompt and extends it with the answer (reading 3.4).

The task's output decides which family to use

So the right family depends on the task. Reading 3.4's working rule for practitioners:

What does thetask output?a fixed output: a label, an embedding, a tagencoder-onlyclassify, embed for retrieval, tagopen-ended textdecoder-onlydialogue, code, instructionsone text from another, distinct rolesencoder–decodertranslation, tightly groundedsummarizationdocumentone passscorepasspasspassone token per pass(S20’s KV cache)
  • Encoder-only gives bidirectional context in one parallel pass, and small BERT-family checkpoints remain good value.
  • For decoder-only models the choices move to scale, fine-tuning and prompting (S18–S20).
  • Whichever you pick: family, weights and vocabulary are one artifact; the tokenizer comes with the checkpoint (Part 3 shows why).

Self-check on matching each task to a family, with a reason

Three tasks; name the family and the property of the task that decides it.

(a) Flag 10 million emails a day as spam or not spam.

(b) A course assistant that answers students' questions in free text.

(c) Translate product descriptions from English to German.

(a) Encoder-only: a fixed output, one bidirectional pass per email, cheap at that volume.

(b) Decoder-only: open-ended generation, token by token.

(c) Encoder–decoder: one text to another with distinct roles; the encoder reads the source both ways (a decoder-only model also works).

That settles which stack to keep. Next come the integers that enter the embedding table.

Word ids fail on new words, and character ids make sequences long

Part 3 · What a token is. The embedding table is indexed by integers. How is text cut into the pieces those integers name?

  • Word-level (one id per distinct word): short sequences. But a word unseen in training has no id (a catch-all [UNK] loses it), and learn, learns, learned, learner get four unrelated ids.
  • Character-level: a few dozen ids, and no word is unknown if its characters were seen. But sequences grow several times longer: reading 3.4's 16-word corpus is 16 word tokens or 107 character tokens (counting an end marker per word), \(107/16\approx6.7\) times longer. And one character means almost nothing alone.
  • Subwords take both ends: frequent words whole, rare words in pieces (un + believ + able), the cut learned from corpus counts.
The held-out word learners, three ways:word-level[UNK]1 tokencharacter-levellearners</w>9 tokenssubwordlearners</w>3 tokens: BPE learns this split later in this part.S14’s attention scores: a T × T matrix per headT = 1616 word tokens162 = 256T = 107107 character tokens1072 = 11,4496.72 ≈ 45×

Byte-pair encoding repeatedly merges the most frequent adjacent pair

The dominant subword algorithm, byte-pair encoding (BPE): a 1994 compression method (Gage), adapted to translation by Sennrich, Haddow & Birch (ACL 2016). Training:

Trainingwords as characters + </w>n e w e s t </w> × 6count adjacent pairs,weighted by word counte s: 9merge the most frequentpair everywhere; record itmerge 1: e + s → esrepeat for a chosen number of merges; +1 symbol eachordered merges:1 · e + s2 · es + t…Tokenizing new texta new wordcharacters + </w>replay the merges in their ordertokens
  • Write each word as characters plus an end-of-word marker </w>, so est ending a word differs from est starting one.

Training produces an ordered list of merges; tokenizing replays it.

By hand, which pair does BPE merge first?

Reading 3.4's toy corpus, each word with its count: low 5, lower 2, newest 6, widest 3. As symbols:

l o w </w> × 5
l o w e r </w> × 2
n e w e s t </w> × 6
w i d e s t </w> × 3

Count each adjacent pair, weighted by its word's count. Which pair is most frequent?

pairfromcount
e s · s t · t </w>newest 6 + widest 39 each
w elower 2 + newest 68
l o · o wlow 5 + lower 27 each
n e · e wnewest 66 each
w </w>low 55
w i · i d · d ewidest 33 each
e r · r </w>lower 22 each

Three pairs tie at 9; reading 3.4's script takes the one it counts first, e + s.

The script's eight merges build the suffix est, then low, then new

Reading 3.4's script runs the loop eight times on the same corpus (ties go to the pair counted first). The first 14 lines of its output; the last three are on the next page:


merge 1: 'e' + 's' -> 'es'  (count 9)
merge 2: 'es' + 't' -> 'est'  (count 9)
merge 3: 'est' + '</w>' -> 'est</w>'  (count 9)
merge 4: 'l' + 'o' -> 'lo'  (count 7)
merge 5: 'lo' + 'w' -> 'low'  (count 7)
merge 6: 'n' + 'e' -> 'ne'  (count 6)
merge 7: 'ne' + 'w' -> 'new'  (count 6)
merge 8: 'new' + 'est</w>' -> 'newest</w>'  (count 6)

vocabulary entries for each corpus word after 8 merges:
  low </w>
  low e r </w>
  newest</w>
  w i d est</w>
  
Pair counts alone findthe superlative suffix.lownewest</w>4 · lo (7)5 · low (7)6 · ne (6)7 · new (6)1 · es (9)2 · est (9)3 · est</w> (9)8 · newest</w> (6)Merges 1–3 (count 9 = newest 6 + widest 3)build est</w>.Merges 4–5 (count 7 = low 5 + lower 2) build low.Merges 6–8 (count 6) build newest</w>, one symbolfor the whole word.

Every word is split the same way, so an unseen word still gets subwords

Tokenizing is the same for every word: characters plus </w>, then the eight merges in order. On lowest, which is not in the corpus (word-level would give [UNK], slide 27):

mergeresult
1 · e + sl o w es t </w>
2 · es + tl o w est </w>
3 · est + </w>l o w est</w>
4 · l + olo w est</w>
5 · lo + wlow est</w>
6–8 · n + e, ne + w, new + est</w>no match: low est</w>

unseen word 'lowest' -> low est</w>
unseen word 'newer' -> new e r </w>
unseen word 'lowlow' -> low low </w>
  
  • The script's last three lines. newer: no merge joins e + r, so they stay characters.
  • Worst case, a full spell-out: no word built from the corpus's characters is ever out of vocabulary.

Two frequent units, low + est</w>, for a word the corpus never had.

Reading 3.4 measures how the merge count sets the vocabulary size

How many merges? Another script of reading 3.4 measures it: BPE on a 16-word corpus (the tokenizer tokenizes the text the transformer transforms the tokens a learner learns the learned tokens), with the held-out word learners, which never occurs in it:

02550751001020304050corpus tokenstable size0 merges (17, 107)10 merges (27, 65)20 merges (37, 41)30 merges (47, 26)words: [UNK] on learners (12, 16)learners after 0, 10, 20 and 30 merges0learners</w>10learners</w>20learners</w>30learners</w>
  • Table size: 17 base symbols (16 letters and </w>), one more per merge.
  • 30 merges: the corpus is about 4 times shorter, for a table \(47/17\approx2.8\) times larger; learners becomes three entries of the table.
  • Word level: 12 entries (11 words and [UNK]), 16 tokens: the best on text it has seen, [UNK] on the one word it has not.

Each side of the merge count has a cost

More merges trade sequence length for table size (reading 3.4):

more merges: a larger vocabulary \(V\)fewer merges: a smaller \(V\)
sequencesshorter: fewer of S14's \(T^2\) scores, more text per context window (the \(T\) a model reads at once)longer: more scores, less text per window
tablesa larger \(V\times d_{\text{model}}\) embedding table, and a softmax over \(V\) at every positionsmaller
trainingrarer tokens, each seen less ofteneach token seen more often
  • Production sizes: GPT-2's tokenizer has 50,257 entries, BERT's about 30,000 (reading 3.4). GPT-2 small (\(d_{\text{model}}=768\)): an embedding table of \(50{,}257\times768=38{,}597{,}376\) parameters, about 31% of its 124.4M (reading 3.3).
  • Text unlike the tokenizer's training corpus (an underrepresented language, digit strings) splits into more tokens per word than text like it (the next page measures it): less effective context, often worse performance per character.

In real text, capitals, digits and other languages cost more tokens

Which text pays more tokens? Reading 3.4's last script runs the 30-merge tokenizer from the lowercase 16-word corpus on four inputs of 16 characters each (spaces not counted): the learner learns, The Learner Learns, learner 2026 44444, der lernende lernt; <?L?> marks a symbol with no id (not in its training corpus):

caseworst word, as tokenswhole input: tokens / charsin-domainlearner →learner</w>5 / 16 = 0.31capitalizedLearner →Learner</w>16 / 16 = 1.00numbers44444 →44444</w>13 / 16 = 0.81Germanlernende →lernende</w>15 / 16 = 0.94A red dashed box is a symbol with no id, which the script prints as <?L?>;the counts are for the whole 16-character input.
  • Capitals and digits are not even base symbols, so each gets no id, and the two inputs cost 16 and 13 tokens against 5. [UNK] again, now for single characters.
  • German: every symbol is known, but its endings (-ende, -t) match no learned merge, so it costs three times the in-domain text, as any underrepresented language does.

Byte-level BPE starts from 256 base symbols, so every string has ids

The <?L?> rows have a fix: start BPE from bytes, not characters (GPT-2's tokenizer). UTF-8 writes each character as 1 to 4 bytes, each byte one of 256 values:


print(list("Lé4".encode("utf-8")))
  
Lé476195169522 bytes256 base symbols0255The four bytes are what the print shows.
  • With all 256 byte values as base symbols, any UTF-8 string is representable: no [UNK], emoji and typos included.
  • What it fixes: representability. What it does not fix: efficiency. The German row had no unknown symbol and still cost three times as many tokens: bytes give rare text ids, not fewer tokens.
  • Whitespace is a convention: GPT-2-style tokenizers fold a leading space into the next word, so "hello" and " hello" get different ids.

WordPiece merges greedily too, but chooses the pair differently

GPT-2's tokenizer is BPE; BERT's and T5's are not. WordPiece (BERT's) runs the same greedy loop but merges the pair seen together most often relative to its parts' counts; reading 3.4's teaching version of its pair score (libraries differ):

\[\operatorname{score}(a,b)=\frac{\operatorname{count}(a,b)}{\operatorname{count}(a)\cdot\operatorname{count}(b)}\]
  • Step 1, toy corpus: i and d occur only in widest, 3 times each, always together: \(\operatorname{score}(\text{i},\text{d})=3/(3\cdot3)=1/3\). e occurs 17 times (lower 2, newest \(2\cdot6\), widest 3), s 9 times: \(\operatorname{score}(\text{e},\text{s})=9/(17\cdot9)=1/17\approx0.06\).

step    BPE (by count)   WordPiece (by score)
   1               e+s                    i+d
   2              es+t                    l+o
   3          est+</w>                    s+t
   4               l+o                   lo+w
   5              lo+w                   w+id
   6               e+w                 r+</w>
  
  • Frequency asks what is seen most; the score, what is seen together more than its parts predict. At scale the two give broadly similar vocabularies; BERT marks word-internal pieces: learn, ##er.
  • This script breaks ties alphabetically: BPE's step 6 is e+w, where the first script took n+e (both count 6).

Unigram takes the most probable split, with a probability per token

The third algorithm, Kudo's unigram tokenizer (ACL 2018; T5's), replays no merges: it keeps a probability per token and takes the split whose log-probabilities sum highest, found by dynamic programming. Reading 3.4's script fixes 17 tokens and their counts, summing to 58 (a real trainer learns them by pruning a large candidate list):


'lowest' -> low est   (total log-prob -3.978)
'newest' -> new est   (total log-prob -4.132)
'lowers' -> low er s   (total log-prob -8.156)
  
l−3.367o−3.367w−2.674e−2.451s−3.367t−3.367001−3.3672−2.9623−2.1154−4.0605−7.4286−3.978lowe −4.060west −3.367low: ln(7/58) = −2.115est: ln(9/58) = −1.863lo −2.962candidate scoreslow + est −3.978 (best)lo + west −6.329l + o + w + est −11.272Node i holds the best log-probabilityof the first i characters; dynamicprogramming fills the nodes leftto right.
  • Two frequent tokens beat two rarer ones (lo 3 + west 2) and a spell-out. Every split has a probability, so training can sample splits (subword regularization).
  • Kudo: without sampling, unigram and BPE gave almost the same BLEU; sampling splits added 1 to 2. The choice follows the checkpoint you must match.

A checkpoint and its tokenizer are one artifact

Different tokenizers give the same text different ids, and a checkpoint's embedding row \(k\) learned what id \(k\) meant to its own tokenizer. Two BPE tokenizers trained the same way (8 merges, reading 3.4's code) on reading 3.4's two corpora; ids numbered one simple way, base symbols sorted, then one per merge:

lowesttokenizer A1513024xsB’s table: 25 rowsx sthe wrongembedding rowstokenstokenizer B2420018no row 24: crashA’s table: 19 rowsTokenizer A has 19 ids from 8 merges on low, lower, newest and widest; tokenizer B has 25 ids from 8 merges on the 16-word corpus.
  • Reading 3.4's failure modes: fluent nonsense, or a crash.
  • Fix: load the tokenizer distributed with the exact checkpoint, and round-trip a sample sentence: encode with your tokenizer, decode with the checkpoint's vocabulary (lowest, not x s). If a model behaves oddly, look at the token ids first (reading 3.4).

Self-check on three BPE merges by hand, then an unseen word

A new corpus, each word with its count: bat 5, bats 3, cat 2; the end marker </w> as before.

(a) The first merge, and the counts that make it?

(b) The second and third merges?

(c) Segment the unseen word cats with these three merges.

(a) a + t: bat 5 + bats 3 + cat 2 = 10 (next: b + a 8, t + </w> 7).

(b) b + at: bat 5 + bats 3 = 8 (above at + </w> 7); then bat + </w>: 5.

(c) c at s </w>: merge 1 applies; merges 2 and 3 find no b + at and no bat.

That settles what a token is. Next comes today's answer, clause by clause.

Today's question gets four answers, from one block to learned tokens

Part 4 · Close. Back to the title page's question, clause by clause.

  • One block: \(\mathbf{x}+\operatorname{MHA}(\operatorname{LN}(\mathbf{x}))\), then \(\mathbf{x}+\operatorname{FFN}(\operatorname{LN}(\mathbf{x}))\): pre-norm, the stream never normalized; (B, T, d_model) in and out; 49,984 parameters at \(d_{\text{model}}=64\), \(d_{\text{ff}}=256\), two-thirds in the FFN.
  • The mask, proved: \(-\infty\) above the diagonal, before the softmax, gives later keys weight exactly 0, and everything else acts per position; the perturbation test agrees (edit token 5: positions 0–4 change by exactly 0). So one pass gives \(T\) next-token examples; a leak shows as a loss below what the data allows.
  • The half kept: mostly the decoder, trained on next-token prediction, which learns from every position and scaled. BERT keeps the encoder (masked language modeling), T5 both.
  • A token: a piece of text learned from corpus counts: BPE's merges, replayed in order; byte-level BPE starts from 256 bytes; a tokenizer belongs to its checkpoint.

For next time

  • Next session (S18), Wednesday: LLM pretraining: the objective, the data, what training costs, scaling laws, and which claims about scale hold up.
  • Read: 3.5 LLM Pretraining.
  • At S18: HW2 due · HW3 (Transformer from scratch) out, due in two weeks (S22). Today's mask, block and full model are its tasks 2, 4 and 5.
  • Project: the proposal is due at the end of the week after next (the S23 week).
  • Quiz 3 (Module 3) is the week after next, at S23; it covers today's material.