Tokenization & Language Modeling
Level: 4 — Application (novel problems, no hints) Time limit: 60 minutes Total marks: 60
Answer all questions. Show all working. Use / notation for mathematics where appropriate.
Question 1 — BPE Merge Trace (12 marks)
You are training a Byte-Pair Encoding tokenizer on the following tiny corpus (word : frequency), where each word is pre-split into characters and terminated with the end-of-word symbol _:
| Word | Frequency |
|---|---|
low_ |
5 |
lower_ |
2 |
newest_ |
6 |
widest_ |
3 |
(a) Perform the first two BPE merge operations. For each merge, state the winning pair, its total frequency count, and the resulting new symbol. Show the count of the top competing pairs at each step. (8 marks)
(b) After these two merges, write the final token sequence for the word newest_. (2 marks)
(c) State one reason why BPE uses an explicit end-of-word marker _ rather than merging freely across word boundaries. (2 marks)
Question 2 — Vocabulary & Embedding Budget (14 marks)
A team is designing a decoder-only language model. They must choose between two tokenizer vocabularies for the same 10-billion-token training corpus:
- Vocab A: 8,000 tokens, producing an average of 1.60 tokens per word.
- Vocab B: 50,000 tokens, producing an average of 1.15 tokens per word.
The model uses embedding dimension and ties the input embedding and output projection weights.
(a) Compute the number of parameters in the (tied) embedding matrix for each vocabulary. (4 marks)
(b) The corpus contains 6.25 billion words. Compute the total number of tokens the model must process in one epoch under each vocabulary. (4 marks)
(c) Compute the extra embedding-parameter cost of Vocab B over Vocab A, and the reduction in tokens-per-epoch of Vocab B relative to Vocab A (as a percentage). Based on these numbers, give a one-sentence recommendation and justify it with a tradeoff argument. (6 marks)
Question 3 — Perplexity Under Two Objectives (14 marks)
A causal language model assigns the following per-token conditional probabilities to a 5-token test sequence:
(a) Compute the cross-entropy (in bits per token) and the perplexity of this sequence. (6 marks)
(b) A second model achieves a perplexity of exactly 8 on the same 5-token sequence. What is the average per-token log-probability (natural log) for this second model? (4 marks)
(c) Explain why perplexity computed from a masked language model (BERT-style) is not directly comparable to perplexity from a causal model, referencing the difference in what each objective conditions on. (4 marks)
Question 4 — MLM Objective Design (12 marks)
You are pretraining a BERT-style encoder. Consider the sentence (already tokenized):
[CLS] the cat sat on the mat [SEP]
with masking probability 15%, of which 80% are replaced by [MASK], 10% by a random token, and 10% left unchanged.
(a) The 7 content tokens (the cat sat on the mat plus the first the) are candidates for masking. If exactly 1 token is selected for masking (rounding ), enumerate the three possible replacement outcomes for that selected token and give the probability of each outcome. (6 marks)
(b) Explain the purpose of the 10%-random and 10%-unchanged rules — what pretraining/fine-tuning mismatch do they mitigate? (4 marks)
(c) Next Sentence Prediction (NSP) was later found to add little value in RoBERTa. Give one plausible reason NSP is a weak pretraining signal. (2 marks)
Question 5 — Context Window & Cost (8 marks)
A model has a maximum context window of 4,096 tokens. Self-attention cost scales as in sequence length .
(a) A document tokenizes to 10,000 tokens. Using non-overlapping chunks of the full window, how many forward passes are needed, and how many tokens are in the final (shortest) chunk? (4 marks)
(b) If the context window is doubled to 8,192, by what factor does the per-window attention compute increase, and what is the corresponding factor for number of chunks needed for the same 10,000-token document? Comment on the net compute effect. (4 marks)
Answer keyMark scheme & solutions
Question 1 (12 marks)
Initial symbol sequences with frequencies:
l o w _×5l o w e r _×2n e w e s t _×6w i d e s t _×3
(a) Merge 1 (4 marks): Count adjacent pairs across the weighted corpus.
l o: 5+2 = 7o w: 5+2 = 7w _: 5 (from low_)w e: 2 (lower) + 6 (newest) = 8e s: 6+3 = 9s t: 6+3 = 9t _: 6+3 = 9
Top pairs tie at 9: e s, s t, t _. Break ties by first occurrence / lexicographic — take e s (accept any of the 9-count pairs with justification). Winning pair: e s, count 9 → new symbol es. (2 marks for correct top count of 9; 2 marks for valid identification and tie-handling.)
Updated: n e w es t _ ×6, w i d es t _ ×3.
Merge 2 (4 marks): Recount.
es t: 6+3 = 9 (nowesfollowed byt)s tno longer exists (s absorbed).- Other candidates:
l o=7,o w=7,w e=8,t _=9.
Top count 9: es t and t _. Take es t, count 9 → new symbol est. (2 marks count, 2 marks identification.)
Full marks awarded for any internally consistent tie-break yielding correct counts.
(b) (2 marks): After merges es then est: newest_ → n e w est _. (2 marks)
(c) (2 marks): The _ marker preserves word boundaries so merges do not span two words, keeping tokens morphologically meaningful and allowing detokenization (reconstructing spaces). (2 marks for any valid reason.)
Question 2 (14 marks)
(a) (4 marks): Tied embedding = one matrix of size .
- Vocab A: ≈ 8.19M params.
- Vocab B: ≈ 51.2M params. (2 marks each.)
(b) (4 marks): Tokens per epoch = words × tokens/word.
- Vocab A: .
- Vocab B: . (2 marks each.)
(c) (6 marks):
- Extra embedding cost: params (≈ 43.0M extra). (2)
- Token reduction: fewer tokens. (2)
- Recommendation: Vocab B — a ~28% reduction in sequence tokens lowers training/inference compute (attention is superlinear in sequence length) and the extra ~43M embedding params are modest relative to full model size; the shorter sequences also fit more content per context window. (2 for reasoned recommendation; accept Vocab A if student argues small-model / rare-token / memory constraints.)
Question 3 (14 marks)
(a) (6 marks): Cross-entropy in bits/token: .
values: , , , , .
Sum of bits. bits/token. (3 marks)
Perplexity (equivalently geometric mean of ). PPL ≈ 3.98. (3 marks)
(b) (4 marks): , so . Average per-token log-prob ≈ −2.079 nats. (4 marks)
(c) (4 marks): Causal PPL uses factorized probabilities — a proper joint over the sequence (left context only). MLM predicts each masked token conditioned on both left and right context, and does not define a normalized joint distribution over the whole sequence (pseudo-likelihood). Hence MLM "perplexity" measures a different quantity and is not on the same scale as autoregressive PPL. (2 marks conditioning difference, 2 marks no valid joint / non-comparable.)
Question 4 (12 marks)
(a) (6 marks): token selected. Given selection, outcomes:
- Replaced by
[MASK]: probability 0.80. - Replaced by a random token: probability 0.10.
- Left unchanged (kept original): probability 0.10. (2 marks each outcome+probability.)
(b) (4 marks): [MASK] never appears at fine-tuning/inference time, so training only on [MASK] creates a pretrain–finetune distribution mismatch. The 10% random forces the model to use context to judge every token (not just masked positions) and be robust to corrupted input; the 10% unchanged biases the model toward the actual observed token so representations stay accurate for real (non-masked) inputs. (2 marks mismatch, 2 marks role of the two rules.)
(c) (2 marks): NSP mixes topic prediction (easy) with coherence, and the negative "next sentence" is usually from a different document, so it collapses to trivial topic matching — a weak signal that a strong MLM already learns. (2 marks any valid reason.)
Question 5 (8 marks)
(a) (4 marks): forward passes (chunks of 4096, 4096, and remainder). Final chunk tokens. 3 passes; final chunk 1808 tokens. (2+2)
(b) (4 marks): Doubling window: per-window attention scales as , so factor . Chunks needed: chunks (was 3), factor . Net: attention compute per full pass over the document ≈ higher — the quadratic per-window growth dominates the fewer-chunks saving. (2 marks factor 4, 1 chunk factor, 1 net comment.)
[
{"claim":"BPE first merge es and second merge est both have count 9","code":"corpus={('l','o','w','_'):5,('l','o','w','e','r','_'):2,('n','e','w','e','s','t','_'):6,('w','i','d','e','s','t','_'):3}\nfrom collections import Counter\ndef pc(c):\n p=Counter()\n for w,f in c.items():\n for i in range(len(w)-1):\n p[(w[i],w[i+1])]+=f\n return p\np=pc(corpus)\nm1=max(p.values())\nresult=(m1==9 and p[('e','s')]==9)"},
{"claim":"Vocab embedding params and token reduction 28.125%","code":"A=8000*1024; B=50000*1024\nextra=B-A\ntokA=6.25e9*1.60; tokB=6.25e9*1.15\nred=(tokA-tokB)/tokA*100\nresult=(A==8192000 and B==51200000 and abs(red-28.125)<1e-6)"},
{"claim":"Sequence perplexity approx 3.9811 and CE 1.9932 bits","code":"import math\nps=[0.5,0.25,0.1,0.4,0.2]\nH=-sum(math.log2(p) for p in ps)/len(ps)\nppl=2**H\nresult=(abs(H-1.9931569)<1e-4 and abs(ppl-3.98107)<1e-3)"},
{"claim":"Model2 avg ln prob = -ln8","code":"import math\nv=-math.log(8)\nresult=abs(v+2.0794415)<1e-6"},
{"claim":"Context chunks: 3 passes, final 1808; doubled net factor 8/3","code":"import math\npasses=math.ceil(10000/4096); final=10000-2*4096\np2=math.ceil(10000/8192); net=4*(p2/passes)\nresult=(passes==3 and final==1808 and p2==2 and abs(net-8/3)<1e-9)"}
]