Session S17
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
Before the material, three items.
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.
| piece | what 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 encoding | a position-dependent vector added to each token's embedding; without it, shuffling the tokens only reorders the outputs |
| residual connection | every sublayer computes \(\mathbf{x}+\operatorname{sublayer}(\mathbf{x})\): S10's identity path for the gradient |
| layer normalization | standardizes 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.
The title page's question has four clauses (bold): Part 1 answers the first two, Parts 2 and 3 one each.
| part | the question it answers |
|---|---|
| 1 · One block | how 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 keep | which 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 is | what 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 · Close | today's answer; next session S18 (HW2 due, HW3 out) |
First, the block.
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)\](B, T, d_model): both sums need equal shapes.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:
(2, 8, 64), out (2, 8, 64): \(N\) identical blocks chain with no reshaping.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\).
qkv \(64\cdot192+192=12{,}480\); proj \(64\cdot64+64=4{,}160\); together \(16{,}640=4\,(64^2+64)\).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 same pieces, two arrangements; the blue line is the residual stream \(\mathbf{x}\), the branch below holds the sublayer:
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.
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\).
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.
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\).
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):
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.
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))
triu(..., diagonal=1) is True strictly above the diagonal, in the grey cells, where key \(j\) comes after query \(i\).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.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 0.000000 at positions 0–4 is not rounding: with the mask, position \(t\)'s output is computed from tokens \(0\) to \(t\) only.
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:
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.HW3's test_causality_property runs this same test on the model you build.
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.
# 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))
[[0.8808 0.1192 0. ]] [1.]
[[0.4902 0.0663 0. ]] [0.5565]
Both masks add \(-\infty\) before the softmax and never zero weights after it.
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:
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.
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.
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:
id of a \(V\times d\) table (reading 3.1); positions added as in S16.ln_f).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).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):
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.
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 attention | |||
| objective | masked language modeling (MLM): hide 15% of the tokens, reconstruct them from both sides | next-token prediction | text-to-text: input into the encoder, answer out of the decoder |
| built for | classification, embeddings and retrieval, tagging | dialogue, code, instruction following | translation, summarization |
| generates? | no native left-to-right way | yes, left to right | yes, left to right |
BERT has no causal decoder: generation methods can be built around masked models, but none is native (reading 3.4).
Next-token prediction asks position \(t\) for token \(t+1\). Without a causal mask, token \(t+1\) is one of position \(t\)'s keys.
Next-token training needs causal attention: no position sees its target.
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:
Decoder-only dominance is practice, not a theorem: one decoder reads the prompt and extends it with the answer (reading 3.4).
So the right family depends on the task. Reading 3.4's working rule for practitioners:
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.
Part 3 · What a token is. The embedding table is indexed by integers. How is text cut into the pieces those integers name?
[UNK] loses it), and learn, learns, learned, learner get four unrelated ids.The dominant subword algorithm, byte-pair encoding (BPE): a 1994 compression method (Gage), adapted to translation by Sennrich, Haddow & Birch (ACL 2016). Training:
</w>, so est ending a word differs from est starting one.Training produces an ordered list of merges; tokenizing replays it.
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> × 5l o w e r </w> × 2n e w e s t </w> × 6w i d e s t </w> × 3
Count each adjacent pair, weighted by its word's count. Which pair is most frequent?
| pair | from | count |
|---|---|---|
| e s · s t · t </w> | newest 6 + widest 3 | 9 each |
| w e | lower 2 + newest 6 | 8 |
| l o · o w | low 5 + lower 2 | 7 each |
| n e · e w | newest 6 | 6 each |
| w </w> | low 5 | 5 |
| w i · i d · d e | widest 3 | 3 each |
| e r · r </w> | lower 2 | 2 each |
Three pairs tie at 9; reading 3.4's script takes the one it counts first, e + s.
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>
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):
| merge | result |
|---|---|
| 1 · e + s | l o w es t </w> |
| 2 · es + t | l o w est </w> |
| 3 · est + </w> | l o w est</w> |
| 4 · l + o | lo w est</w> |
| 5 · lo + w | low 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>
e + r, so they stay characters.Two frequent units, low + est</w>, for a word the corpus never had.
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:
</w>), one more per merge.[UNK]), 16 tokens: the best on text it has seen, [UNK] on the one word it has not.More merges trade sequence length for table size (reading 3.4):
| more merges: a larger vocabulary \(V\) | fewer merges: a smaller \(V\) | |
|---|---|---|
| sequences | shorter: 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 |
| tables | a larger \(V\times d_{\text{model}}\) embedding table, and a softmax over \(V\) at every position | smaller |
| training | rarer tokens, each seen less often | each token seen more often |
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):
[UNK] again, now for single characters.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")))
[UNK], emoji and typos included."hello" and " hello" get different ids.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)}\]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>
learn, ##er.e+w, where the first script took n+e (both count 6).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)
lo 3 + west 2) and a spell-out. Every split has a probability, so training can sample splits (subword regularization).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:
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.
Part 4 · Close. Back to the title page's question, clause by clause.
(B, T, d_model) in and out; 49,984 parameters at \(d_{\text{model}}=64\), \(d_{\text{ff}}=256\), two-thirds in the FFN.