Simple Algorithm
Deep Learning · Representation · 24 min

Transformer Language Models

Tokenization, next-token prediction, encoders versus decoders, and generating text.

A transformer turns a sequence of vectors into a sequence of vectors. Three more pieces make it a language model: a tokenizer that turns text into integers, a training objective that turns every position of every document into a prediction, and a decoding rule that turns predicted distributions back into text. Each piece has costs you can compute and failure modes you can watch, and this lesson works through all three.

What you’ll learn

  • Train byte-pair encoding by hand and apply its merges to new words, explain byte-level BPE and the unigram tokenizer, and quantify how vocabulary size trades sequence length against embedding parameters and output-layer FLOPs.
  • Write the autoregressive factorization, implement the shifted next-token loss under a causal mask, and turn a loss into a perplexity.
  • Compare encoder-only, decoder-only and encoder–decoder models by their attention masks, training objectives and typical uses.
  • Define greedy decoding, temperature, top-kk and top-pp sampling precisely, prove that temperature raises the entropy, and explain how a KV cache removes the recomputation of the prefix.
  • Describe in-context learning as GPT-3 displayed it, and say what that observation does and does not establish.

From text to token ids

A network computes with numbers, so text is first cut into tokens from a fixed vocabulary V\mathcal V, and each token becomes an integer id. Two obvious choices both fail:

  • Words give short sequences but an open-ended vocabulary. Names, typos, numbers and new coinages fall outside any fixed list and turn into one "unknown" symbol, and their meaning is lost.
  • Characters (or bytes) never fail, but a text becomes several times longer, every layer pays for every extra position, and the model must learn spelling from scratch.

Subword tokenization sits in between: frequent words stay whole and rare words are spelled from frequent pieces. A tokenizer is fit once on a corpus, frozen, and shipped with the model; the network never sees anything but ids.

Byte-pair encoding (BPE) builds its vocabulary greedily (Sennrich, Haddow & Birch, 2016, adapting a 1994 compression algorithm of Gage). Start from single symbols. Count every adjacent pair in the corpus, weighting each word by its frequency, merge the most frequent pair into a new symbol, and repeat. The final vocabulary is the base symbols plus one token per merge, and the ordered merge list is the tokenizer: to encode new text, split it into base symbols and replay the merges in the order they were learned. Here is a full run on a five-word corpus.

MergePairCountThe corpus after the merge
1i + n12s·in·g, s·in·g·s, r·in·g, s·t·r·in·g, s·in
2in + g9s·ing, s·ing·s, r·ing, s·t·r·ing, s·in
3r + ing5s·ing, s·ing·s, ring, s·t·ring, s·in
4s + ing4sing, sing·s, ring, s·t·ring, s·in
5s + in3sing, sing·s, ring, s·t·ring, sin
The corpus is sing ×2, sings ×2, ring ×3, string ×2 and sin ×3. The pair "i n" occurs in every word, 2+2+3+2+3=122+2+3+2+3=12 times, so it is merged first; at each step the winner is strictly ahead (12 against 9, then 9 against 7, 5 against 4, 4 against 3 and 3 against 2). After five merges the vocabulary has 6+5=116+5=11 tokens, and string still costs three of them, because "s t" never won. Real tokenizers also mark word boundaries: Sennrich et al. append an end-of-word symbol, and GPT-2 attaches the preceding space to a word, so " sing" and "sing" are different tokens.
Check your understanding

Encode the word singing, which never occurs in the corpus, with these five merges.

  1. s + ing + ing
  2. sin + g + in + g
  3. sing + ing
  4. singing, a single token
Show the answer

C. sing + ing

Replay the merges in order. Merge 1 turns s·i·n·g·i·n·g into s·in·g·in·g; merge 2 gives s·ing·ing; merge 3 needs an r; merge 4 joins s and ing into sing·ing; merge 5 finds no "s in" left. Two tokens. Encoding never searches for the shortest segmentation; it only replays the merge list.

Byte-level BPE. A base vocabulary of Unicode characters would need over 130,000 symbols before the first merge, so GPT-2 runs BPE on UTF-8 bytes instead: 256 base tokens, so every string can be encoded and nothing is ever unknown. To keep BPE from spending entries on variants such as "dog." and "dog!", merges may not cross character categories, except that a space may join the word that follows it (Radford et al., 2019). The result has 50,257 tokens: the 256 bytes, 50,000 merges and one end-of-text token. LLaMA's tokenizer instead runs BPE on Unicode characters (with SentencePiece, below), splits every number into single digits, and falls back to bytes for characters outside its vocabulary (Touvron et al., 2023).

The unigram tokenizer. Kudo (2018) turned the procedure around. Start from a large seed vocabulary and model a text as a sequence of independently drawn subwords with probabilities p(x)p(x). Fit the probabilities by EM, treating the segmentation as hidden, then drop the subwords whose removal lowers the likelihood least, keeping, say, 80% per round (single characters always stay, so nothing becomes unknown). A word is encoded by its most probable segmentation, found with the Viterbi algorithm, and subword regularization samples other segmentations during training as a form of noise. SentencePiece (Kudo & Richardson, 2018) implements both BPE and the unigram model on raw text, with the space treated as an ordinary symbol (written ▁), so decoding restores the input exactly; T5 used a 32,000-token SentencePiece vocabulary. The Artificial Intelligence course's lesson Tokenization: BPE & Friends analyzes these algorithms as approximate compressors.

What a vocabulary costs

Tokens enter the network through an embedding table E∈R∣V∣×dE\in\R^{|\mathcal V|\times d}, a lookup that costs essentially nothing. They leave through the output layer, ℓt=WU ht\boldsymbol\ell_t=W_U\,\mathbf h_t with WU∈R∣V∣×dW_U\in\R^{|\mathcal V|\times d}, which scores every vocabulary entry at every position: 2∣V∣d2|\mathcal V|d FLOPs per token. Kaplan et al. (2020) list this "de-embedding" separately and leave it out of C≈2NC\approx2N, which counts only the blocks. Tying WU=EW_U=E (The Transformer Block) saves the parameters but not these FLOPs.

The size of V\mathcal V is therefore a trade-off. A larger vocabulary shortens every text, so each layer processes fewer positions and a fixed context window holds more text. But it adds ∣V∣ d|\mathcal V|\,d parameters per table, adds 2d2d output FLOPs per token for every new entry, and spreads the training signal over more and rarer tokens, whose embeddings are updated less often.

Model∣V∣|\mathcal V|ddEmbedding tableOutput layer per tokenBlocks per token (2N2N)
GPT-2 small50,25776838.6 M of 124.4 M parameters77.2 MFLOP170.1 MFLOP
LLaMA-2-7B shape32,0004,096131 M per table, untied262 MFLOP13.0 GFLOP
The forward FLOPs of the dense parts for one token; attention over the context comes on top. In the small model the output layer is almost a third of the dense work, in the 7-billion-parameter shape about 2%. The per-block counts are derived in The Transformer Block and Anatomy of a Modern LLM.
Predict before you look

For GPT-2 small, what fraction of the dense forward FLOPs per token (blocks plus output layer, ignoring attention over the context) does the output layer take, in percent?

Show the answer

31 %

2∣V∣d=2×50,257×768≈77.22|\mathcal V|d=2\times50{,}257\times768\approx77.2 million FLOPs against 2N≈170.12N\approx170.1 million for the twelve blocks, so 77.2/(170.1+77.2)≈31%77.2/(170.1+77.2)\approx31\%. For a 7-billion-parameter model with 32,000 tokens the same share is about 2%2\%: the vocabulary is a large cost only for small models, or for very large vocabularies.

How much text a token covers depends on the domain. Averaged over the Pile, GPT-2's tokenizer produces 0.29 tokens per byte of text, about 3.4 bytes per token; on English Wikipedia it is 0.24, on a dataset of mathematics problems 0.81 (Gao et al., 2020). Languages differ even more: the same text translated into different languages can differ up to 15-fold in token count (Petrov et al., 2023), which changes what users pay, how long they wait and how much fits into the context. Vocabularies have grown accordingly, from 32,000 tokens in LLaMA to about 128,000 in Llama 3, and scaling-law fits that include the vocabulary find that its compute-optimal size grows with the compute budget; Tao et al. (2024) estimated that Llama 2 70B should have had at least 216,000 tokens instead of 32,000.

Next-token prediction

A language model is a probability distribution over token sequences. The chain rule factors any such distribution exactly, with no assumption, into next-token conditionals, which is what makes the model autoregressive:

pθ(x1,…,xT)=∏t=1Tpθ(xt∣x<t).p_{\boldsymbol\theta}(x_1,\dots,x_T)=\prod_{t=1}^{T}p_{\boldsymbol\theta}(x_t\mid x_{<t}).

Maximum likelihood turns the product into a sum: minimize the negative log-likelihood −∑tlog⁡pθ(xt∣x<t)-\sum_t\log p_{\boldsymbol\theta}(x_t\mid x_{<t}), the cross-entropy between the data and the model, one term per position. This is next-token prediction.

A decoder gets all of these terms from one forward pass. Feed it x1,…,xT−1x_1,\dots,x_{T-1}; the causal mask makes the state ht\mathbf h_t depend only on x≤tx_{\le t}, the output layer turns it into logits ℓt\boldsymbol\ell_t, and the target at position tt is xt+1x_{t+1}:

L(θ)=−1T−1∑t=1T−1log⁡softmax⁡(ℓt)xt+1,ℓt=WU ht(x≤t)\loss(\boldsymbol\theta)=-\frac1{T-1}\sum_{t=1}^{T-1}\log\softmax(\boldsymbol\ell_t)_{x_{t+1}},\qquad\boldsymbol\ell_t=W_U\,\mathbf h_t(x_{\le t})
Every term conditions on the true prefix, which is teacher forcing: it is exact maximum likelihood, and all T−1T-1 predictions train in parallel. The gradient of position tt's term with respect to ℓt\boldsymbol\ell_t is softmax⁡(ℓt)−ext+1\softmax(\boldsymbol\ell_t)-\mathbf e_{x_{t+1}} (Loss Functions & Maximum Likelihood), so each position raises its target's logit and lowers every other logit in proportion to its probability.
python
import torch.nn.functional as F

def lm_loss(model, tokens):                       # tokens: (B, T) token ids
    inputs, targets = tokens[:, :-1], tokens[:, 1:]   # predict token t+1 from tokens 1..t
    logits = model(inputs)                        # (B, T-1, |V|); causal mask inside the model
    return F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))

# loss is the mean negative log-likelihood in nats per token:
# perplexity = loss.exp(), bits per token = loss / math.log(2)

The whole objective is a shift by one. Training documents are usually concatenated, separated by an end-of-text token, and cut into fixed-length sequences; GPT-3 relied on that token alone to separate documents (Brown et al., 2020), while some later models also mask attention across document boundaries.

Perplexity. Language models report the exponential of the mean loss,

PPL=exp⁡(−1T∑t=1Tlog⁡pθ(xt∣x<t))=(∏t=1T1pθ(xt∣x<t))1/T,\mathrm{PPL}=\exp\Big(-\frac1T\sum_{t=1}^{T}\log p_{\boldsymbol\theta}(x_t\mid x_{<t})\Big)=\Big(\prod_{t=1}^{T}\frac{1}{p_{\boldsymbol\theta}(x_t\mid x_{<t})}\Big)^{1/T},

the geometric mean of the inverse probabilities of the observed tokens: a model with perplexity 20 is, on average, as uncertain as a uniform choice among 20 tokens. One sanity check follows at once. A freshly initialized model outputs nearly uniform distributions, so its loss starts near ln⁡∣V∣\ln|\mathcal V|; for GPT-2's 50,257 tokens that is 10.810.8 nats, a perplexity of about 50,000. An initial loss far above ln⁡∣V∣\ln|\mathcal V| means the logits start too large.

Predict before you look

A model assigns probabilities 0.50.5, 0.20.2, 0.80.8 and 0.050.05 to the four tokens of a short text, each given the tokens before it. What is its perplexity on this text?

Show the answer

3.98

The mean loss is (ln⁡2+ln⁡5+ln⁡1.25+ln⁡20)/4=5.52/4≈1.38(\ln2+\ln5+\ln1.25+\ln20)/4=5.52/4\approx1.38 nats, and e1.38≈3.98e^{1.38}\approx3.98. Equivalently, (2×5×1.25×20)1/4=2501/4≈3.98(2\times5\times1.25\times20)^{1/4}=250^{1/4}\approx3.98. The single token at probability 0.050.05 contributes more than half of the loss: perplexity punishes confident mistakes hard.

One block, three families

The blocks of The Transformer Block can be wired into three families. They differ in which positions each query may see, and in what the model is trained to predict. Write the attention pattern as a matrix whose row tt lists the positions query tt may attend to:

(1111111111111111)⏟bidirectional(1000110011101111)⏟causal(1100110011101111)⏟prefix LM, prefix of 2\underbrace{\begin{pmatrix}1&1&1&1\\1&1&1&1\\1&1&1&1\\1&1&1&1\end{pmatrix}}_{\text{bidirectional}}\qquad\underbrace{\begin{pmatrix}1&0&0&0\\1&1&0&0\\1&1&1&0\\1&1&1&1\end{pmatrix}}_{\text{causal}}\qquad\underbrace{\begin{pmatrix}1&1&0&0\\1&1&0&0\\1&1&1&0\\1&1&1&1\end{pmatrix}}_{\text{prefix LM, prefix of 2}}
A 11 means "may attend"; a 00 becomes a −∞-\infty in the additive mask. The prefix pattern lets the prompt see itself in both directions and keeps the continuation causal, so one stack can both read and write.
FamilyAttentionPretraining objectiveNatural uses
Encoder-only: BERT (Devlin et al., 2019)bidirectionalmasked language modeling: hide about 15% of the tokens and predict them from both sidesclassification, tagging and retrieval embeddings, after fine-tuning with a small output head
Decoder-only: the GPT series, LLaMAcausalcausal language modeling: predict every next tokengeneration, chat, code, prompting and in-context learning
Encoder–decoder: T5 (Raffel et al., 2020), BART (Lewis et al., 2020)bidirectional encoder, causal decoder, cross-attention from decoder to encoderdenoising: T5 writes out masked spans (span corruption), BART reconstructs a corrupted documentconditional generation such as translation and summarization, where the input is read once in both directions
A decoder-only model can mimic the other two: give it a prefix mask and it reads its input bidirectionally, as in the prefix language models that Raffel et al. compared and that UniLM (Dong et al., 2019) mixed with other masks in one network. As of the mid-2020s, general-purpose large language models are almost all causal decoders, while bidirectional encoders remain common for classification and search; Pretraining Objectives Compared examines the controlled comparisons behind that division.
Think first BERT was trained to fill in hidden words using the context on both sides. Why can't you simply use it to write text from left to right?

Writing needs the conditionals p(xt∣x<t)p(x_t\mid x_{<t}). BERT learned something else: the distribution of a hidden token given visible tokens on both sides, at a masking rate near 15%. At the right edge of a growing text everything to the right is missing, a situation it never trained on. You can still draw text from it by repeatedly masking and refilling positions, but such learned conditionals need not agree with any single joint distribution. Masked diffusion language models repair this by training at every masking rate, which turns a BERT-like loss into a bound on the likelihood (Beyond Left-to-Right: Multi-Token & Diffusion LMs).

Choosing the next token

A decoder writes by repeating one step: compute p(⋅∣x<t)p(\cdot\mid x_{<t}), choose a token, append it, run again. The choice is not part of the model, and it changes the text a great deal.

  • Greedy decoding takes arg max⁡vp(v∣x<t)\argmax_vp(v\mid x_{<t}). It is deterministic, but a chain of locally best tokens is in general not the most probable sequence. Beam search keeps several candidates to search better, and Decoding: Beam Search & Its Pathologies shows why maximizing probability tends to produce repetitive text when the output is open-ended.
  • Ancestral sampling draws xt∼p(⋅∣x<t)x_t\sim p(\cdot\mid x_{<t}) at every step, which samples exactly from the model's distribution over whole sequences, its unreliable tail included.
  • Reshaped sampling sharpens, flattens or truncates each distribution before drawing from it:
pτ(v)=eℓv/τ∑ueℓu/τ=p(v)1/τ∑up(u)1/τ,top-k: keep the k largest,top-p: keep the smallest S with ∑v∈Sp(v)≥pp_\tau(v)=\frac{e^{\ell_v/\tau}}{\sum_ue^{\ell_u/\tau}}=\frac{p(v)^{1/\tau}}{\sum_up(u)^{1/\tau}},\qquad\text{top-}k:\ \text{keep the }k\text{ largest},\qquad\text{top-}p:\ \text{keep the smallest }S\text{ with }\sum_{v\in S}p(v)\ge p
Temperature τ\tau rescales the logits. Top-kk sampling keeps a fixed number of candidates (Fan, Lewis & Dauphin, 2018); top-pp (nucleus) sampling keeps a fixed amount of probability, so its candidate set is small after a confident prefix and large after an open one (Holtzman et al., 2020). Both renormalize what they keep.
DerivationTemperature raises the entropy
  1. H(β)=−∑vpβ(v)(βℓv−log⁡Z(β))=log⁡Z(β)−β Eβ[ℓ]H(\beta)=-\sum_vp_\beta(v)\big(\beta\ell_v-\log Z(\beta)\big)=\log Z(\beta)-\beta\,\E_\beta[\ell]

    Write β=1/τ\beta=1/\tau and pβ(v)=eβℓv/Z(β)p_\beta(v)=e^{\beta\ell_v}/Z(\beta) with Z(β)=∑ueβℓuZ(\beta)=\sum_ue^{\beta\ell_u}. Since log⁡pβ(v)=βℓv−log⁡Z\log p_\beta(v)=\beta\ell_v-\log Z, the entropy is

  2. ddβlog⁡Z(β)=Eβ[ℓ],ddβEβ[ℓ]=Var⁡β(ℓ)\frac{d}{d\beta}\log Z(\beta)=\E_\beta[\ell],\qquad\frac{d}{d\beta}\E_\beta[\ell]=\Var_\beta(\ell)

    Differentiating the log-partition function gives the mean logit, and differentiating the mean gives the variance:

  3. dHdβ=−βVar⁡β(ℓ)⟹dHdτ=Var⁡pτ(ℓ)τ3 ≥ 0\frac{dH}{d\beta}=-\beta\Var_\beta(\ell)\quad\Longrightarrow\quad\frac{dH}{d\tau}=\frac{\Var_{p_\tau}(\ell)}{\tau^{3}}\ \ge\ 0

    The two mean terms cancel, and dβ/dτ=−1/τ2d\beta/d\tau=-1/\tau^2:

  4. τ→0: pτ→earg max⁡vℓv,τ→∞: pτ→1∣V∣1\tau\to0:\ p_\tau\to\mathbf e_{\argmax_v\ell_v},\qquad\tau\to\infty:\ p_\tau\to\tfrac{1}{|\mathcal V|}\mathbf 1

    The derivative vanishes only when all logits are equal. As τ→0\tau\to0 the distribution concentrates on the largest logit, which is greedy decoding when the maximum is unique; as τ→∞\tau\to\infty it tends to the uniform distribution, with entropy log⁡∣V∣\log|\mathcal V|.

RuleProbabilities of the six candidatesEntropy (nats)
model, τ=1\tau=10.45, 0.25, 0.12, 0.08, 0.06, 0.041.46
τ=0.5\tau=0.50.696, 0.215, 0.049, 0.022, 0.012, 0.0050.90
τ=2\tau=20.299, 0.223, 0.154, 0.126, 0.109, 0.0891.70
top-kk, k=2k=20.643, 0.357, 0, 0, 0, 00.65
top-pp, p=0.8p=0.80.549, 0.305, 0.146, 0, 0, 00.97
Top-pp at 0.80.8 keeps three candidates because the first two hold only 0.700.70. Truncation removes the tail entirely; a temperature below 11 only shrinks it. The uniform distribution over six candidates would have entropy ln⁡6≈1.79\ln6\approx1.79.
python
import torch

def sample_next(logits, temperature=1.0, top_k=0, top_p=1.0):
    """logits: (|V|,) scores for the next token. Returns a token id."""
    if temperature == 0:
        return int(logits.argmax())                          # greedy decoding
    logits = logits / temperature
    if top_k > 0:                                            # keep the k largest logits
        kth = torch.topk(logits, top_k).values[-1]
        logits = logits.masked_fill(logits < kth, float('-inf'))
    if top_p < 1.0:                                          # keep the smallest set with mass >= top_p
        sorted_logits, idx = torch.sort(logits, descending=True)
        probs = sorted_logits.softmax(-1)
        drop = probs.cumsum(-1) - probs >= top_p             # mass before this token already reaches top_p
        sorted_logits[drop] = float('-inf')
        logits = torch.full_like(logits, float('-inf')).scatter(0, idx, sorted_logits)
    return int(torch.multinomial(logits.softmax(-1), 1))

Temperature is applied first, then truncation. The order does not matter for top-kk, since dividing by τ\tau preserves the ranking, but it does for top-pp, whose nucleus is computed from the tempered probabilities.

Generating fast, and learning from the prompt

Generation runs one forward pass per new token, and most of that work would repeat earlier work. Under a causal mask the keys and values of position jj, in every layer, depend only on x≤jx_{\le j}, so they never change once computed. A KV cache stores them:

  1. Prefill. Run the prompt through the model in one parallel pass, as in training, and keep every layer's keys and values.
  2. Decode. For each new token, compute its query, key and value in every layer, append the key and value to the cache, and attend over the cache. The token costs about 2N2N FLOPs for the weights plus about 4Ltd4Ltd for attending to tt cached positions: 2td2td for the scores and 2td2td for the weighted sum, in each of LL layers.
text
GENERATE(model, prompt, n_new)
    logits, cache ← model(prompt, cache = empty)    // prefill: all prompt positions at once
    repeat n_new times:
        x ← CHOOSE(logits at the last position)     // greedy, or sampled with τ, top-k, top-p
        emit x; stop if x is the end-of-text token
        logits, cache ← model([x], cache)           // decode: one position, appends its keys and values

Only the decode loop is sequential. The prefill is as parallel as a training step.

Think first Without a cache, how much more weight computation does it take to generate 1,000 tokens from an empty prompt?

Without a cache, token tt means rerunning all tt positions, about 2Nt2Nt FLOPs, so the total is 2N(1+2+⋯+1000)=2N×500,5002N(1+2+\cdots+1000)=2N\times500{,}500 against 2N×1,0002N\times1{,}000 with the cache: about 500 times more. The cache turns a cost that grows like T2T^2 into one that grows like TT, plus attention over the cache. Its price is memory, which grows with the context length, the number of layers and the number of key–value heads. Efficient Transformers computes how many bytes that is, and why decoding is limited by memory bandwidth rather than arithmetic.

In-context learning. GPT-3 (Brown et al., 2020) showed how much a large decoder trained only on next-token prediction can do with its prompt alone. Given a task description and KK worked examples, typically 10 to 100, as many as fit in its 2,048-token context, followed by a new input, it often completed the new input correctly with no gradient update at all: in-context learning. Comparing zero, one and many examples across model sizes, the authors found that the gap between zero-shot and few-shot performance often grew with model size, which they read as larger models being better at learning from context.

What this shows is limited. The examples are only conditioning: no weight changes, so any "learning" is computation inside the forward pass, and with web-scale pretraining it is not always clear whether a task is new to the model or merely recognized. Proposed mechanisms include induction heads, implicit Bayesian inference over latent tasks, and constructions in which attention carries out steps of gradient descent; the Artificial Intelligence course's lesson In-Context Learning & Emergence develops them.

Key takeaways

  • Subword tokenizers trade vocabulary size against sequence length (BPE replays greedy merges in the order learned; the unigram model prunes by likelihood and segments with Viterbi), and a vocabulary costs ∣V∣ d|\mathcal V|\,d parameters per table and 2∣V∣d2|\mathcal V|d output FLOPs per token: almost a third of GPT-2 small's dense forward cost.
  • The chain rule p(x)=∏tp(xt∣x<t)p(\mathbf x)=\prod_tp(x_t\mid x_{<t}) is exact; with a causal mask, one forward pass on x1:T−1x_{1:T-1} trains all T−1T-1 next-token predictions by cross-entropy.
  • Perplexity is the exponential of the mean loss per token; it starts near ∣V∣|\mathcal V| at initialization and is comparable only between models that share a tokenizer.
  • Encoders attend both ways and learn by masked prediction (classification, retrieval); decoders attend causally and predict every next token (generation, prompting, in-context learning); encoder–decoders join the two through cross-attention.
  • Decoding is a choice: greedy, beam search or sampling, with temperature (pτ∝p1/τp_\tau\propto p^{1/\tau}, entropy increasing in τ\tau) and top-kk or top-pp truncation; a KV cache makes each new token cost about 2N2N FLOPs plus attention over the cache.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A team doubles its byte-level BPE vocabulary from 50,000 to 100,000 tokens for a model of width d=1,024d=1{,}024 with untied input and output embeddings. What should they expect?

  1. Every text becomes half as many tokens, since each token now covers twice as much text
  2. No change in parameters; only the tokenizer file grows
  3. Texts get somewhat shorter, the two embedding tables gain about 102 million parameters, and the output layer costs twice as many FLOPs per token
  4. The model can now encode strings it could not encode before
Show the answer

C. Texts get somewhat shorter, the two embedding tables gain about 102 million parameters, and the output layer costs twice as many FLOPs per token

Each new token adds a row to EE and to WUW_U: 2×50,000×1,024≈1.0×1082\times50{,}000\times1{,}024\approx1.0\times10^8 parameters, and the output layer's 2∣V∣d2|\mathcal V|d FLOPs double. Later merges join rarer pairs, so the sequence shrinks by far less than half.

Question 2

Why does a decoder need the causal mask when it computes the next-token loss at all positions in one forward pass?

  1. Without it, position tt could attend to xt+1x_{t+1}, the very token it must predict, and the loss could be driven down by copying instead of predicting
  2. To reduce the memory of the attention matrix
  3. Because attention has no other source of positional information
  4. It is needed only at generation time, not in training
Show the answer

A. Without it, position tt could attend to xt+1x_{t+1}, the very token it must predict, and the loss could be driven down by copying instead of predicting

The target at position tt is xt+1x_{t+1}, which is also an input. Hiding all later positions from every query makes each prediction a genuine function of its prefix, so T−1T-1 honest predictions come out of one pass.

Question 3

A freshly initialized model with GPT-2's 50,257-token vocabulary outputs nearly uniform next-token distributions. What validation loss should its first evaluation show?

  1. About 00 nats
  2. About 11 nat
  3. About 50,25750{,}257 nats
  4. About 10.810.8 nats, a perplexity near 50,00050{,}000
Show the answer

D. About 10.810.8 nats, a perplexity near 50,00050{,}000

A uniform distribution gives every token probability 1/∣V∣1/|\mathcal V|, so the loss is ln⁡50,257≈10.8\ln50{,}257\approx10.8 nats and the perplexity is ∣V∣|\mathcal V| itself. A first loss far above this suggests overconfident initial logits.

Question 4

A model's next-token probabilities are 0.60.6, 0.20.2, 0.10.1, 0.050.05 and 0.050.05. Which distribution does top-pp sampling with p=0.75p=0.75 draw from?

  1. Probability 11 on the first token
  2. 0.750.75 and 0.250.25 on the first two tokens
  3. The first three tokens, renormalized
  4. All five tokens, with the temperature set to 0.750.75
Show the answer

B. 0.750.75 and 0.250.25 on the first two tokens

The cumulative probabilities are 0.60.6, then 0.80.8. The smallest set reaching 0.750.75 is the first two tokens, renormalized: 0.6/0.8=0.750.6/0.8=0.75 and 0.2/0.8=0.250.2/0.8=0.25.

Question 5

Why can a decoder reuse the keys and values of earlier tokens when it generates the next one?

  1. Because the attention weights are the same at every step
  2. Because keys and values are fixed parameters of the model
  3. Because under the causal mask, each position's keys and values in every layer depend only on the tokens up to that position, and those never change
  4. Because only the last layer's keys and values are needed
Show the answer

C. Because under the causal mask, each position's keys and values in every layer depend only on the tokens up to that position, and those never change

A new token cannot change the states of earlier positions, since they never attend to it. So their keys and values, computed once, stay valid; only the new token's query, key and value must be computed, and its query attends over the cache.

Go deeper

Further reading

  • R. Sennrich, B. Haddow & A. Birch, "Neural machine translation of rare words with subword units," ACL (2016).
  • T. Kudo, "Subword regularization: Improving neural network translation models with multiple subword candidates," ACL (2018).
  • A. Radford, J. Wu, R. Child, D. Luan, D. Amodei & I. Sutskever, "Language models are unsupervised multitask learners," OpenAI technical report (2019).
  • T. B. Brown et al., "Language models are few-shot learners," NeurIPS (2020).
  • A. Holtzman, J. Buys, L. Du, M. Forbes & Y. Choi, "The curious case of neural text degeneration," ICLR (2020).