TExcelTAD

Exercises

Twenty exercises across the whole course, from text clean-up to deployment. Most can be done on paper; six answers include a short program that checks the hand computation, which you can edit and run. Try each one before opening its answer.

# Exercise Practises
1 Pick the approach Introduction, Text Classification, Dense Retrieval
2 Four strings through normalisation Text Normalisation
3 Stem or lemma? Stemming and Lemmatisation
4 TF-IDF by hand Bag of Words, TF-IDF
5 BM25 saturation and length Keyword Search
6 Perplexity of four tokens n-gram Language Models
7 Entity F1 against token accuracy Named Entity Recognition, Token Classification
8 Three BPE merges Byte-Pair Encoding
9 When greedy WordPiece fails WordPiece and Unigram
10 Padding side for generation Tokenizers in Practice
11 Attention memory at 4,096 tokens Self-Attention, Fast Inference
12 Which model family? Encoder, Decoder and Encoder-Decoder, Positional Encoding
13 The 80/10/10 rule Pretraining Objectives
14 A compute-optimal budget Scaling Laws
15 The KV cache of a 7B model Inside a Decoder-Only LM
16 Which tokens carry the SFT loss? Supervised Fine-Tuning, Instruction Tuning
17 A DPO loss by hand Preference Tuning
18 LoRA parameters and int8 weights LoRA and QLoRA for LLMs, Quantization
19 Diagnose a RAG failure RAG Pipeline, Evaluating Retrieval and RAG
20 An evaluation and launch plan Evaluating LLMs, Deploying LLMs

Exercise 1: Pick the approach

Choose a first approach for each task and name the baseline you would beat.

  1. Route 50,000 labelled support e-mails into 12 queues; the model must run on a CPU in 5 ms.
  2. Find the 3 help articles that answer a free-text question; 2,000 articles, no labelled questions.
  3. Extract product names and prices from invoices; 800 labelled invoices.
  4. Answer employees' questions from 300 internal policy documents, with citations.
  5. Make an open 8B chat model follow your company's answer style; 4,000 example dialogues, one 24 GB GPU.
Answer
  1. TF-IDF (word and bigram) plus logistic regression or a linear SVM: fast, strong with 50,000 labels, explainable. Beat it with a fine-tuned small BERT only if the gain is worth the latency.
  2. Dense retrieval with a sentence encoder, compared with BM25; consider a hybrid. With no labels, write 30 to 50 test questions first so the comparison is measured.
  3. Token classification (BIO tags) with a fine-tuned BERT, against a feature-based tagger as the baseline; evaluate with entity-level F1.
  4. RAG: chunk, embed, retrieve, prompt with numbered sources, check grounding; evaluate retrieval and answers separately.
  5. SFT with LoRA, or QLoRA if the 16-bit model plus training state does not fit in 24 GB; hold out dialogues to compare with the base model plus a good prompt.

Exercise 2: Four strings through normalisation

Predict what NFKC, lower(), casefold() and accent stripping (NFD, then drop combining marks) do to "final" (with the one-character "fi" ligature), "123 km" (full-width digits), "Straße" and "café". Then run the check. Which of these transformations would you apply before a cased BERT model?

Answer
python · try it yourself
import unicodedata

for s in ["final", "123 km", "Straße", "café"]:
    nfkc = unicodedata.normalize("NFKC", s)
    nfd = unicodedata.normalize("NFD", s)
    no_accents = "".join(c for c in nfd if not unicodedata.combining(c))
    print(f"{s!r:10} NFKC {nfkc!r:10} lower {s.lower()!r:10} casefold {s.casefold()!r:10} accents off {no_accents!r}")
'final'     NFKC 'final'    lower 'final'     casefold 'final'    accents off 'final'
'123 km'   NFKC '123 km'   lower '123 km'   casefold '123 km'   accents off '123 km'
'Straße'   NFKC 'Straße'   lower 'straße'   casefold 'strasse'  accents off 'Straße'
'café'     NFKC 'café'     lower 'café'     casefold 'café'     accents off 'cafe'

NFKC folds compatibility characters: the ligature becomes "fi" and the full-width digits become ASCII digits, but it keeps "ß" and "é". lower() changes only case ("Straße" to "straße"); casefold() goes further for caseless matching ("strasse") and also unfolds the ligature. Accent stripping removes the acute accent of "café" but leaves the ligature and the full-width digits alone, because they are not combining marks. Before a cased model apply at most NFKC (or NFC): its tokenizer was trained on cased, accented text, so lower-casing or stripping accents destroys information it can use.

Exercise 3: Stem or lemma?

For each use, choose a Porter stemmer, a lemmatiser or neither, and say why: (a) a BM25 index for a help centre; (b) features for a naive Bayes spam filter; (c) the input of a fine-tuned BERT; (d) counting how often each dictionary word appears in a corpus for a language-learning app.

Answer

(a) Stemmer: queries and documents are stemmed the same way, so "docks" matches "dock"; stems need not be real words. (b) Stemmer (or nothing): fewer, denser features help a count model; check on validation that it does not hurt. (c) Neither: the subword tokenizer and the model handle word forms, and stemming would produce text unlike the pretraining data. (d) Lemmatiser: the output must be dictionary words ("mice" counted as "mouse", "better" as "good" with its part of speech).

Exercise 4: TF-IDF by hand

Three documents: "the bike is red", "the red bike is fast", "a fast train". With scikit-learn's defaults (smooth idf idf⁡(t)=ln⁡1+n1+df⁡(t)+1\operatorname{idf}(t) = \ln\frac{1 + n}{1 + \operatorname{df}(t)} + 1, raw counts, l2 normalisation, tokens of two or more characters), compute the idf of "bike" and "train" and the TF-IDF vector of the first document.

Answer

n=3n = 3. "bike" is in 2 documents: ln⁡(4/3)+1=1.288\ln(4/3) + 1 = 1.288. "train" is in 1: ln⁡(4/2)+1=1.693\ln(4/2) + 1 = 1.693. In document 1 every term ("the", "bike", "is", "red") occurs once and appears in 2 documents, so all four weights are equal before normalisation, and after l2 normalisation each is 1/4=0.51/\sqrt{4} = 0.5. ("a" is dropped by the default token pattern.)

python · try it yourself
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

docs = ["the bike is red", "the red bike is fast", "a fast train"]
vec = TfidfVectorizer().fit(docs)
idf = dict(zip(vec.get_feature_names_out(), np.round(vec.idf_, 3)))
print("idf:", {w: float(idf[w]) for w in ["bike", "fast", "red", "the", "train"]})
row = vec.transform(docs[:1]).toarray()[0]
print("doc 1:", {w: round(float(v), 3) for w, v in zip(vec.get_feature_names_out(), row) if v})
idf: {'bike': 1.288, 'fast': 1.288, 'red': 1.288, 'the': 1.288, 'train': 1.693}
doc 1: {'bike': 0.5, 'is': 0.5, 'red': 0.5, 'the': 0.5}

Exercise 5: BM25 saturation and length

With k1=1.5k_1 = 1.5 and b=0.75b = 0.75, the term-frequency part of BM25 is f (k1+1)f+k1(1−b+b ∣d∣/avgdl⁡)\frac{f\,(k_1 + 1)}{f + k_1 (1 - b + b\,\lvert d \rvert / \operatorname{avgdl})}. For a document of average length, how much more does a term contribute with f=5f = 5 than with f=1f = 1? And with f=1f = 1, how much does a document twice the average length get, compared with an average one?

Answer

At average length the denominator is f+1.5f + 1.5. f=1f = 1: 2.5/2.5=12.5 / 2.5 = 1. f=5f = 5: 12.5/6.5=1.92312.5 / 6.5 = 1.923. Five occurrences count less than twice one occurrence: the score saturates towards k1+1=2.5k_1 + 1 = 2.5. At twice the average length the denominator is 1+1.5⋅(0.25+1.5)=3.6251 + 1.5 \cdot (0.25 + 1.5) = 3.625, so the term gives 2.5/3.625=0.6902.5 / 3.625 = 0.690 instead of 1: a long document needs more occurrences to be equally relevant. TF-IDF with raw counts has neither effect.

Exercise 6: Perplexity of four tokens

A bigram model gives the four tokens of a held-out sentence the probabilities 0.5, 0.25, 0.1 and 0.4. What is the perplexity? What happens if one more token gets probability 0, and how do smoothing methods prevent it?

Answer
PPL⁡=exp⁡(−14∑iln⁡pi)=(0.5⋅0.25⋅0.1⋅0.4)−1/4=0.005−1/4≈3.76\operatorname{PPL} = \exp\left(-\frac{1}{4}\sum_i \ln p_i\right) = \left(0.5 \cdot 0.25 \cdot 0.1 \cdot 0.4\right)^{-1/4} = 0.005^{-1/4} \approx 3.76

The model is as uncertain as a uniform choice among about 3.76 tokens. A single zero probability makes the log-likelihood −∞-\infty and the perplexity infinite. Add-kk smoothing gives every unseen bigram a little mass; interpolation and backoff fall back to the unigram probability, which is never zero for a known word.

Exercise 7: Entity F1 against token accuracy

Gold tags: B-PER I-PER O O B-ORG I-ORG O B-LOC. Predicted: B-PER O O O B-ORG I-ORG O B-PER. Compute token accuracy and entity-level precision, recall and F1 (an entity counts only when its span and type are both right).

Answer

Token accuracy: 6 of 8 tags match, 0.750. Gold entities: PER at tokens 0 to 1, ORG at 4 to 5, LOC at 7. Predicted: PER at 0 only (wrong span), ORG at 4 to 5 (right), PER at 7 (wrong type). One of three predictions is right and one of three gold entities is found: precision, recall and F1 are all 0.333. Token accuracy flatters the tagger because most tokens are O.

python · try it yourself
def spans(tags):
    out, start, label = [], None, None
    for i, t in enumerate(tags + ["O"]):
        if start is not None and not (t.startswith("I-") and t[2:] == label):
            out.append((start, i, label))
            start = None
        if t.startswith("B-") or (t.startswith("I-") and start is None):
            start, label = i, t[2:]
    return set(out)

gold = ["B-PER", "I-PER", "O", "O", "B-ORG", "I-ORG", "O", "B-LOC"]
pred = ["B-PER", "O",     "O", "O", "B-ORG", "I-ORG", "O", "B-PER"]
g, p = spans(gold), spans(pred)
tp = len(g & p)
prec, rec = tp / len(p), tp / len(g)
print("gold:", sorted(g)); print("pred:", sorted(p))
print(f"precision {prec:.3f} recall {rec:.3f} F1 {2 * prec * rec / (prec + rec):.3f}")
token_acc = sum(a == b for a, b in zip(gold, pred)) / len(gold)
print(f"token accuracy {token_acc:.3f}")
gold: [(0, 2, 'PER'), (4, 6, 'ORG'), (7, 8, 'LOC')]
pred: [(0, 1, 'PER'), (4, 6, 'ORG'), (7, 8, 'PER')]
precision 0.333 recall 0.333 F1 0.333
token accuracy 0.750

Exercise 8: Three BPE merges

Word counts: "tan" 6, "tank" 3, "than" 4, "ant" 5. Learn three merges by hand (most frequent pair; ties do not occur here), then encode "tanks", "thank" and "pant".

Answer

Merge 1: "a n" occurs in every word, 6+3+4+5=186 + 3 + 4 + 5 = 18 times. After it the words are t an, t an k, t h an, an t. Merge 2: "t an" occurs 6+3=96 + 3 = 9 times, more than "an t" (5), "t h" and "h an" (4 each). Merge 3: "an t" with 5, ahead of "t h" and "h an" (4) and "tan k" (3). Encoding applies the merges in the order learned: "tanks" becomes tan k s, "thank" t h an k (the merge "t an" never applies because "h" sits between them), "pant" p ant. The function is the one of Byte-Pair Encoding from Scratch.

python · try it yourself
from collections import Counter

def merge_pair(symbols, pair):
    out, i = [], 0
    while i < len(symbols):
        if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
            out.append(symbols[i] + symbols[i + 1])
            i += 2
        else:
            out.append(symbols[i])
            i += 1
    return tuple(out)

def train_bpe(words, num_merges):
    table = {tuple(w): c for w, c in words.items()}
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for symbols, c in table.items():
            for p in zip(symbols, symbols[1:]):
                pairs[p] += c
        if not pairs:
            break
        best = max(pairs, key=lambda p: (pairs[p], p))
        merges.append(best)
        table = {merge_pair(s, best): c for s, c in table.items()}
    return merges

def encode(word, merges):
    rank = {p: i for i, p in enumerate(merges)}
    symbols = tuple(word)
    while len(symbols) > 1:
        candidates = [p for p in zip(symbols, symbols[1:]) if p in rank]
        if not candidates:
            break
        symbols = merge_pair(symbols, min(candidates, key=rank.get))
    return list(symbols)

words = {"tan": 6, "tank": 3, "than": 4, "ant": 5}
merges = train_bpe(words, 3)
print("merges:", merges)
for w in ["tanks", "thank", "pant"]:
    print(w, "->", encode(w, merges))
merges: [('a', 'n'), ('t', 'an'), ('an', 't')]
tanks -> ['tan', 'k', 's']
thank -> ['t', 'h', 'an', 'k']
pant -> ['p', 'ant']

Exercise 9: When greedy WordPiece fails

A WordPiece vocabulary holds un, unhap, happy, ##happ, ##happy, ##ily, ##ly, ##i, ##y, play, ##ful, ##s. Encode "unhappily", "playful" and "plays" with greedy longest-match-first. Is there a segmentation of "unhappily" with these pieces that the greedy method misses?

Answer

"playful" is play ##ful and "plays" play ##s. For "unhappily" the longest first piece is unhap; the rest, "pily", must start with a ## piece, and no ##p… piece exists, so the whole word becomes [UNK]. Yet un ##happ ##ily is a valid segmentation. Greedy longest-match never backtracks; a Unigram tokenizer's Viterbi search over all segmentations would find it. Real BERT vocabularies contain every single character as a ## piece, which is why [UNK] is rare in practice.

python · try it yourself
def wordpiece(word, vocab, unk="[UNK]"):
    pieces, start = [], 0
    while start < len(word):
        end = len(word)
        while end > start:
            piece = word[start:end] if start == 0 else "##" + word[start:end]
            if piece in vocab:
                break
            end -= 1
        if end == start:
            return [unk]
        pieces.append(piece)
        start = end
    return pieces

vocab = {"un", "unhap", "happy", "##happ", "##happy", "##ily", "##ly", "##i", "##y", "play", "##ful", "##s"}
for w in ["unhappily", "playful", "plays"]:
    print(w, "->", wordpiece(w, vocab))
unhappily -> ['[UNK]']
playful -> ['play', '##ful']
plays -> ['play', '##s']

Exercise 10: Padding side for generation

You batch two prompts of 5 and 9 tokens for a decoder-only model and generate 20 new tokens. Why must the shorter prompt be padded on the left, and what else has to come from the attention mask?

Answer

Generation appends new tokens at the end of each row. With right padding the short prompt's continuation would start after 4 pad tokens, so the model predicts from the last pad position, not from the prompt's last token. With left padding every row ends with a real token. The attention mask must keep pad positions out of attention, and the position ids must count from the first real token (computed from the mask); otherwise the short prompt starts at position 4 and its logits change slightly, as Tokenizers in Practice measures. generate builds those position ids from the mask itself.

Exercise 11: Attention memory at 4,096 tokens

One layer has 32 heads. In fp16, how much memory does the full attention-score matrix of one sequence of 4,096 tokens take? Why does FlashAttention not need it?

Answer

32⋅40962⋅232 \cdot 4096^2 \cdot 2 bytes =230= 2^{30} bytes =1= 1 GiB per layer and sequence, growing with T2T^2. FlashAttention computes the softmax in tiles with a running maximum and running sum (the online softmax), so it never stores the full T×TT \times T matrix; the result is exactly the same, and memory grows only with TT.

Exercise 12: Which model family?

Pick encoder-only, decoder-only or encoder-decoder for: (a) sentence classification at low latency; (b) open-ended chat; (c) translating sentences with a fixed source and target; (d) embedding documents for search. And why does a model with learned absolute positions up to 512 fail on 2,000-token inputs, while RoPE degrades more gracefully?

Answer

(a) Encoder (BERT-like): bidirectional context, one forward pass. (b) Decoder-only: one causal stack that generates. (c) Encoder-decoder (T5, BART, Marian): the encoder reads the whole source, the decoder attends to it through cross-attention; decoder-only models also translate well at scale. (d) Encoder with pooling (a sentence-embedding model). A learned position table has no row for position 512 or beyond, so the model cannot even run without truncation. RoPE has no table: it rotates queries and keys by an angle, and attention depends on relative distance, so longer inputs still run, although quality drops beyond the trained length unless the rotation is rescaled (position interpolation).

Exercise 13: The 80/10/10 rule

A 200-token sequence is prepared for BERT's masked-LM objective. How many tokens are selected for prediction, and how many of those are replaced by [MASK], by a random token and left unchanged (in expectation)? Why not always use [MASK]?

Answer

15% of 200 = 30 selected: 24 [MASK], 3 random, 3 unchanged. The loss is computed on all 30, and only there. [MASK] never occurs at fine-tuning time; if every target were [MASK], the model would learn useful representations only for [MASK] positions. Random and unchanged tokens force it to model every input token, because any token might be a target.

Exercise 14: A compute-optimal budget

You can spend C=1021C = 10^{21} FLOPs on pretraining. Using C≈6NDC \approx 6ND and the rule of thumb of 20 tokens per parameter, how many parameters NN and tokens DD should you choose? Why do many deployed models train on far more tokens than this?

Answer

With D=20ND = 20N: C=120N2C = 120 N^2, so N=1021/120≈2.9×109N = \sqrt{10^{21}/120} \approx 2.9 \times 10^9 parameters and D≈5.8×1010D \approx 5.8 \times 10^{10} tokens. The rule minimises training compute for a given loss. A model that will serve billions of requests is cheaper overall if it is smaller and trained longer, because inference cost grows with NN for every token served; Scaling Laws works through that trade-off.

Exercise 15: The KV cache of a 7B model

A model has 32 layers, hidden size 4,096 and 32 heads of 128 dimensions, in fp16. How large is the KV cache for one sequence of 4,096 tokens? And with grouped-query attention using 8 key-value heads?

Answer

Keys and values: 2⋅32 layers⋅4096 tokens⋅4096⋅2 bytes=2312 \cdot 32 \text{ layers} \cdot 4096 \text{ tokens} \cdot 4096 \cdot 2 \text{ bytes} = 2^{31} bytes =2= 2 GiB per sequence. With 8 KV heads of 128 the width per layer is 1,024 instead of 4,096: 0.5 GiB. A batch of 16 long sequences needs 32 GiB without GQA and 8 GiB with it, which is why GQA and paged KV memory matter more for serving than the weights.

Exercise 16: Which tokens carry the SFT loss?

An SFT example is <user> what is 7 + 5 ? <assistant> 12 <eos>, 10 tokens. Which positions get label −100-100, and what goes wrong if the prompt is not masked? What goes wrong if <eos> is masked?

Answer

The labels of <user>, the six prompt tokens and <assistant> are −100-100; only 12 and <eos> are trained. Without masking, the model also learns to produce user prompts and spends much of the loss on text it will never have to write; with many short answers the answer tokens become a small share of the gradient. If <eos> is masked, the model never learns to stop, so it continues after the answer, often inventing a new user turn.

Exercise 17: A DPO loss by hand

β=0.1\beta = 0.1. For one preference pair, the policy gives the chosen response log-probability −12-12 and the rejected one −15-15; the frozen reference gives −13-13 and −14-14. Compute the DPO loss, and compare with its value at the start of training.

Answer

The margin is β[(−12+13)−(−15+14)]=0.1⋅2=0.2\beta \left[(-12 + 13) - (-15 + 14)\right] = 0.1 \cdot 2 = 0.2, and the loss is −ln⁡σ(0.2)=0.598-\ln \sigma(0.2) = 0.598. At the start the policy equals the reference, the margin is 0 and the loss is ln⁡2=0.693\ln 2 = 0.693. Training raises the chosen response's probability relative to the reference and lowers the rejected one's; β\beta sets how far it may move from the reference.

python · try it yourself
import numpy as np

def logsigmoid(x):
    return -np.logaddexp(0, -x)

beta = 0.1
# log-probabilities of the chosen (w) and rejected (l) responses under the policy and the frozen reference
pol_w, pol_l, ref_w, ref_l = -12.0, -15.0, -13.0, -14.0
margin = beta * ((pol_w - ref_w) - (pol_l - ref_l))
print(f"margin {margin:.3f}, DPO loss {-logsigmoid(margin):.4f}, at the start (policy = reference) {-logsigmoid(0.0):.4f}")

w = np.array([0.52, -1.27, 0.031, 1.004, -0.4])
scale = np.abs(w).max() / 127
q = np.round(w / scale).astype(int)
print("scale", round(float(scale), 4), "int8", q.tolist(), "max error", round(float(np.abs(q * scale - w).max()), 5))
margin 0.200, DPO loss 0.5981, at the start (policy = reference) 0.6931
scale 0.01 int8 [52, -127, 3, 100, -40] max error 0.004

The program also answers the int8 part of Exercise 18.

Exercise 18: LoRA parameters and int8 weights

(a) A model has 32 layers with 4096×40964096 \times 4096 projections q,k,v,oq, k, v, o. How many trainable parameters does LoRA with rank 16 on all four add? (b) Quantize the weights [0.52,−1.27,0.031,1.004,−0.4][0.52, -1.27, 0.031, 1.004, -0.4] to int8 with absmax scaling and give the largest rounding error.

Answer

(a) Each adapted matrix gets r(din+dout)=16⋅8192=131,072r(d_{in} + d_{out}) = 16 \cdot 8192 = 131{,}072 parameters; 4⋅324 \cdot 32 matrices give 16,777,21616{,}777{,}216, about 16.8 million, roughly 0.25% of a 7B model. (b) The scale is 1.27/127=0.011.27 / 127 = 0.01, the integers are 52,−127,3,100,−4052, -127, 3, 100, -40, and the largest error is 0.0040.004 (on 1.004, stored as 1.00). One outlier of 10 in the same group would make the scale 0.079 and wipe out the small weights, which is why LLMs are quantized per channel or per group of 32 to 128 weights.

Exercise 19: Diagnose a RAG failure

A RAG assistant answers "The day pass costs 20 euros [1]" for "price for a whole day". Source [1] in the prompt is the hourly-rates page; the day-pass page (15 euros) was retrieved at rank 4 and cut by the top-3 limit. Which stage failed, how would you detect this automatically, and what would you change?

Answer

Retrieval failed first (the relevant page was not in the prompt) and then the generator did not abstain: it invented a number that the cited source does not contain. Detect retrieval misses with recall@3 on a labelled question set, and the unsupported number with a grounding check that compares the answer's numbers and content words with the cited source (the Mini Project flags exactly this). Fixes: a better retriever or hybrid with re-ranking, a larger kk within the token budget, a prompt that tells the model to say when the sources do not answer, and rejecting answers that fail the grounding check.

Exercise 20: An evaluation and launch plan

You fine-tuned a model to answer billing questions. Write a five-line plan: offline evaluation, the comparison with the current system, the launch, what you monitor, and when you roll back.

Answer
  1. Offline: a held-out golden set of real (anonymised) questions with reference answers, written before training; exact match or token F1 for facts, a grounding check, and an LLM judge with a fixed rubric for tone, spot-checked by people.
  2. Comparison: the new model against the current one on the same questions, pairwise win rate with a bootstrap confidence interval; check that general skills did not regress.
  3. Launch: a canary at 5% of traffic, then 25% and 100% if the metrics hold.
  4. Monitor: latency percentiles (p50, p95), tokens and cost per request, refusal and escalation rates, grounding-check failures, user ratings, and a weekly human review sample.
  5. Roll back automatically when p95 latency, cost or grounding failures exceed preset thresholds, keeping the previous model and adapter ready to serve.

Test yourself

In Exercise 7, why is token accuracy 0.750 but entity F1 only 0.333?

  1. Entity F1 ignores the O tags
  2. Most tokens are O and easy; an entity counts only when its whole span and its type are right
  3. Token accuracy double-counts B- tags
  4. F1 is always lower than accuracy

With BM25 (k1=1.5k_1 = 1.5, average document length), a term appearing 5 times contributes about how much compared with appearing once?

  1. 5 times as much
  2. About 1.92 times as much
  3. The same
  4. 2.5 times as much

Why does greedy WordPiece turn 'unhappily' into [UNK] in Exercise 9?

  1. The word is too long
  2. It takes the longest first piece 'unhap', after which no ## piece starts with 'p', and it never backtracks to 'un'
  3. WordPiece cannot split words into three pieces
  4. The vocabulary has no ## pieces

A 32-layer model with hidden size 4,096 stores its KV cache in fp16. Roughly how much memory does one 4,096-token sequence need, without grouped-query attention?

  1. 128 MiB
  2. 512 MiB
  3. 2 GiB
  4. 16 GiB

In SFT, what happens if the end-of-sequence token is masked out of the loss?

  1. Training becomes faster with no side effects
  2. The model never learns when to stop and keeps generating after the answer
  3. The prompt tokens get trained instead
  4. The loss becomes negative