84 LLM Fundamentals Interview Questions and Answers (2026)

LLMs now sit inside search, support, coding tools and internal pipelines, and the teams shipping them want engineers who understand what's happening under the hood. Interviewers have stopped accepting "it predicts the next token" as an answer. They'll ask why your model can't count the r's in strawberry, why temperature changes hallucination rates, or what a MoE router is doing, and a fuzzy answer reads as someone who's only used the API.
This guide gives you 84 questions with concise, interview-ready answers, plus code where it helps. They're organized Junior → Mid → Senior, so you lock in tokenization and decoding before moving on to perplexity, scaling laws, context length and reasoning limits. Work through them in order and you'll walk in able to explain the why behind the model, not just the buzzwords.
Q1.What are special tokens, and what roles do they serve during pretraining and generation?
Special tokens are reserved vocabulary entries that carry structural or control meaning rather than text content. They mark boundaries, roles, and padding so the model can parse inputs and know when to stop generating.
Common types:
Sequence boundaries: <bos>/<s> and <eos>/<|endoftext|>.
Padding (<pad>) and unknown (<unk>, mostly in older non-byte-level tokenizers).
Encoder-style tokens: [CLS], [SEP], [MASK] (BERT).
Chat/role markers: <|im_start|>, <|eot_id|>, plus tool-call and fill-in-the-middle tokens.
During pretraining:
EOS separates documents packed into one context window, so the model learns where texts end.
PAD fills batches to equal length; it is masked out of attention and loss.
Task tokens define the objective (e.g. [MASK] for masked LM, FIM sentinels for code infilling).
During fine-tuning and generation:
Chat templates use role tokens to separate system, user, and assistant turns.
Generation stops when the model emits EOS/end-of-turn, which acts as a learned stop signal.
Tool-use tokens tell the runtime to parse a function call.
Practical pitfalls:
Special tokens are added atomically and never split by the tokenizer. User text that contains their literal strings should not be mapped to them (a prompt-injection risk).
New special tokens need freshly initialized embeddings and must be trained. A mismatched chat template degrades output quality.
Q2.What is Byte Pair Encoding (BPE)?
Byte Pair Encoding is a subword tokenization algorithm. It builds a vocabulary by starting from single characters or bytes and repeatedly merging the most frequent adjacent pair into a new token, so common words become single tokens and rare words split into reusable pieces.
Training procedure:
Pre-tokenize the corpus into words and represent each word as a sequence of characters or bytes.
Count every adjacent symbol pair across the corpus.
Merge the most frequent pair into a new symbol and record the merge rule.
Repeat until the vocabulary reaches the target size (e.g. 50k for GPT-2, about 128k for Llama-3).
Output: a vocabulary plus an ordered list of merges. At inference, the merges are applied in that same order.
Example: l o w e r → after merging (l,o) then (lo,w) → low e r.
Byte-level BPE (GPT-2 onward): The base alphabet is the 256 byte values, so any input can be encoded and there are no unknown tokens.
Origin: BPE began as a 1994 compression algorithm and was adapted for neural machine translation by Sennrich et al. (2016).
Q3.Why do modern LLMs use subword tokenization instead of character-level or whole-word tokenization?
Subword tokenization balances vocabulary size against sequence length. Frequent words become single tokens, while rare or unseen words decompose into known pieces. Word-level tokenization suffers from out-of-vocabulary (OOV) words, and character-level tokenization produces very long sequences.
Problems with whole-word tokenization:
The vocabulary explodes (morphology, names, typos, code), which makes the embedding and output softmax layers huge.
Words outside the vocabulary collapse to <unk>, and the model cannot generate novel words.
No parameters are shared between related forms such as "run", "running", and "runner".
Problems with character-level tokenization:
Sequences are roughly 4–5× longer, and attention cost is O(n²), so compute rises and the effective context window shrinks.
Each token carries little meaning, so the model must spend capacity composing characters into words.
What subwords provide:
A fixed, moderate vocabulary (roughly 32k–200k) with no OOV when byte fallback is used.
Pieces are shared across morphology (un + believ + able), which aids generalization.
Good compression, about 0.75 words per token in English.
Trade-offs:
Character-level tasks get harder (spelling, counting letters, arithmetic on split digits).
Non-English languages often split into more tokens, which raises cost and uses more context.
Q4.How does temperature transform the output logits before the softmax?
Temperature divides every logit by a scalar T before the softmax: p_i = exp(z_i / T) / Σ_j exp(z_j / T). T < 1 sharpens the distribution toward the top token, while T > 1 flattens it toward uniform. The ranking of tokens never changes.
Effect on gaps: The probability ratio between two tokens is exp((z_i − z_j)/T). Dividing by T rescales the logit gaps, so a small T exaggerates differences and a large T shrinks them.
Limits:
T → 0 approaches argmax, i.e. greedy decoding. Most APIs treat T = 0 as greedy because dividing by zero is undefined.
T = 1 gives the model's raw distribution.
T → ∞ approaches a uniform distribution over the vocabulary.
Practical use:
Low T (0–0.3) for factual answers, code, and extraction. Higher T (0.7–1.0) for creative or diverse output.
High T raises the chance of sampling tail tokens (incoherence), so it is usually combined with top-k or top-p truncation.
Temperature is applied to the logits, typically before top-k or top-p filtering (the exact order is implementation-specific).
Q5.What is the difference between top-k sampling and top-p (nucleus) sampling?
top-k sampling and top-p (nucleus) sampling?Both truncate the next-token distribution before sampling. Top-k keeps a fixed number of the most likely tokens. Top-p keeps the smallest set of tokens whose cumulative probability reaches p, so the candidate pool grows or shrinks with the model's confidence.
Top-k: fixed-size cutoff:
Sort tokens by probability, keep the top k, renormalize, and sample.
Weakness: k ignores the shape of the distribution. On a peaked distribution it still admits unlikely tokens. On a flat one it cuts off many reasonable options.
Top-p (nucleus): fixed-mass cutoff:
Sort tokens, accumulate probability until it reaches p (e.g. 0.9), keep that "nucleus", renormalize, and sample.
It adapts to confidence: when the model is confident the nucleus may be 1–2 tokens; when uncertain it may hold hundreds.
In practice:
Both are usually combined with temperature, and can be applied together (top-k first, then top-p).
Both aim to cut off the low-probability "tail", where incoherent tokens live, while keeping diversity.
Q6.How does greedy decoding work?
At each step, greedy decoding picks the single highest-probability token (the argmax of the logits), appends it, and repeats until a stop token or length limit. It makes one deterministic choice per step and never looks back.
Mechanics:
Run a forward pass and get logits for the next position.
Take argmax(logits). Softmax isn't even needed, because it preserves the ordering.
Append the token and continue until EOS or max_tokens.
Properties:
Deterministic and cheap: there is one hypothesis and no sampling. It is effectively temperature → 0 (beam search with beam width 1).
Locally optimal, not globally optimal: maximizing each token doesn't maximize whole-sequence probability.
When to use it:
Good for tasks with one right answer: extraction, classification, short factual answers, code, reproducible evals.
Poor for open-ended text, where it produces bland or repetitive output.
Q7.How does beam search work in sequence generation?
Beam search keeps the B most probable partial sequences (beams) at each step instead of just one. It expands each beam by possible next tokens, scores the candidates by cumulative log-probability, and keeps the top B. This gives a better approximation of the most likely full sequence than greedy decoding.
Algorithm:
Start with one beam: the prompt, with score 0.
For each beam, compute next-token log-probs. Each candidate's score is the beam score plus log p(token).
Pool all B × V candidates and keep the top B as the new beams.
Beams that emit EOS move to a finished list.
Stop when B hypotheses are finished or the max length is reached. Return the best-scoring one.
Scoring details:
Log-probs are summed (rather than multiplying probabilities) for numerical stability.
Every token adds a negative term, so raw scores favor short outputs. Length normalization (dividing by length^α) counteracts this.
Properties:
B = 1 is greedy decoding. Larger B means more search but roughly B× compute, and a KV cache per beam that is reordered as beams are pruned.
It is still approximate, not exhaustive, and it is deterministic.
Common extras include no_repeat_ngram_size and diverse beam search to reduce near-duplicate beams.
Use cases: translation, summarization, ASR (constrained outputs). It is rarely used for open-ended chat.
Q8.What are the typical stopping criteria that terminate an autoregressive generation loop?
An autoregressive loop keeps appending tokens until a stop condition fires. In practice that is an end-of-sequence token, a length budget, a matched stop string, or a decoding-algorithm-specific rule. Several of these usually run together, and whichever fires first ends generation.
End-of-sequence token:
The model emits a special token (e.g. </s>, <|endoftext|>, or a chat end-of-turn token). It learned to predict this during training, so it is the "natural" stop.
Configured via eos_token_id. It can be a list, which is common for chat models that have several terminators.
Length limits:
max_new_tokens (or max_length) is a hard cap. It guarantees termination and bounds cost and latency.
The model's context window is an absolute ceiling: prompt plus generated tokens cannot exceed it.
min_new_tokens does the opposite: it suppresses EOS until a minimum length is reached.
Stop sequences:
User-defined strings (e.g. "\nUser:", "```") end generation when they appear. Examples are the API stop parameter and stop_strings in Hugging Face.
They must be matched on decoded text, because a stop string can span several tokens.
Decoding-algorithm rules:
Beam search stops when all beams have finished, or (with early_stopping) when num_beams finished hypotheses exist and no live beam can beat them.
In batched generation, each sequence is marked done independently and padded until the whole batch finishes.
Custom or operational criteria:
Wall-clock timeouts and token budgets.
Grammar or structured-output completion (e.g. a JSON object closes).
Arbitrary StoppingCriteria callbacks.
Q9.How does autoregressive next-token prediction work using the probability chain rule?
The chain rule factorises the joint probability of a sequence into a product of conditionals: P(x₁…x_T) = ∏ P(x_t | x₁…x_{t−1}). An autoregressive LM is a network that models each conditional. At every step it outputs a distribution over the vocabulary for the next token, given all previous tokens.
The factorisation is exact:
No independence assumption is made, unlike n-grams. The only approximation is the model's quality and its context-window length.
Left-to-right order is a convention, but it matches how text is generated.
One step of the model:
Embed the prefix tokens and run them through the decoder, which uses causal self-attention.
Project the last position's hidden state to vocabulary-sized logits.
Apply softmax to get p(x_t | x_<t).
Training (teacher forcing):
The loss is −Σ log p(x_t | x_<t): cross-entropy against the true next token, which is maximum likelihood of the whole sequence.
A causal mask lets every position be trained in parallel in a single forward pass.
Inference (sequential):
Pick a token (greedy, sampling, top-p, beam), append it, and repeat until a stop criterion fires.
A KV cache stores past keys and values, so each step only computes the new token.
Q10.What is an n-gram language model?
An n-gram language model estimates the probability of a word from only the previous n−1 words (a Markov assumption). The conditional probabilities come from counting how often word sequences occur in a corpus.
Core idea:
The chain rule gives P(w₁…w_T) = ∏ P(w_t | w_<t). The model approximates each term with P(w_t | w_{t−n+1}…w_{t−1}).
Common sizes: unigram (n=1, no context), bigram (n=2), and trigram (n=3).
Estimation (MLE):
Bigram: P(w_t | w_{t−1}) = count(w_{t−1}, w_t) / count(w_{t−1}).
Sentences are padded with start and end tokens (<s>, </s>) so that boundaries are modelled.
Handling unseen n-grams:
Smoothing moves probability mass to unseen events. Examples are Laplace (add-one), Good-Turing, and Kneser-Ney (the strongest classical method).
Backoff and interpolation fall back to, or mix in, lower-order n-gram estimates.
Uses and limits:
Historically used for speech recognition, MT, and autocomplete. They are evaluated with perplexity.
Limits: short context, sparsity as n grows, and no generalisation across similar words. Neural LMs replaced them for these reasons.
Q11.What loss function is minimized during standard LLM pretraining?
Standard (decoder-only) LLM pretraining minimizes the next-token cross-entropy loss. This is the negative log-likelihood of each true next token given all previous tokens, averaged over tokens in the batch.
Definition: L = −(1/N) Σ log p_θ(xₜ | x₍<ₜ₎), computed over every position of every sequence.
Why this objective:
Minimizing it is maximum-likelihood estimation.
It is equivalent to minimizing the KL divergence from the data distribution to the model. The data entropy is a constant floor that the loss cannot go below.
It is self-supervised: the text itself supplies the labels, so it scales to trillions of tokens.
Relation to metrics:
Perplexity = exp(loss).
Loss in nats divided by ln 2 gives bits per token.
Common additions:
z-loss, which keeps logits from drifting large for stability (e.g., PaLM).
Auxiliary load-balancing loss in MoE models.
These are small regularizers, not the main objective.
Contrast:
Encoder models like BERT use masked-LM cross-entropy, which predicts only the masked tokens using bidirectional context.
T5 uses span-corruption cross-entropy.
Q12.What does a perplexity score of 10 represent intuitively?
A perplexity of 10 means the model is, on average, as uncertain as if it were choosing uniformly among 10 equally likely tokens at each step. Its effective branching factor is 10.
The math:
PPL = exp(average NLL), so the average cross-entropy is ln 10 ≈ 2.30 nats ≈ 3.32 bits per token.
Equivalently, the geometric mean of the probability assigned to each correct token is 1/10 = 0.1.
What it is not:
It does not mean the model literally narrows to 10 candidates.
Real distributions are skewed: many tokens are near-certain, a few are very uncertain, and the geometric mean blends them.
Reference points:
PPL = 1 means perfect prediction.
PPL = vocabulary size means no better than uniform guessing.
Context dependence:
Whether 10 is "good" depends on the dataset, the tokenizer, and the context length.
Only compare perplexities under the same setup.
Q13.How does a base model differ from an instruction-tuned model?
A base model is trained only with next-token prediction on raw text, so it continues documents. An instruction-tuned model is further trained, via SFT and often RLHF or DPO, to treat the input as a request and produce a helpful, appropriately formatted response.
Base model:
Behavior: given "What is the capital of France?", it may continue with more quiz questions instead of answering.
How to use it: steer it with few-shot examples or by framing the prompt as the start of a document.
Strengths: more diverse and better-calibrated outputs, and the best starting point for custom fine-tuning or for research.
Instruction-tuned model:
SFT on (instruction, response) pairs, with loss usually computed only on the response tokens.
Preference tuning (RLHF, DPO) shapes helpfulness, tone, and refusals.
It follows zero-shot instructions, uses a specific prompt or chat template, and emits EOS when the answer is done.
Knowledge mostly comes from pretraining: Instruction tuning mainly changes behavior and format (the "superficial alignment" view), not what the model knows.
Costs of tuning:
Possible "alignment tax" on some benchmarks.
Less output diversity and worse probability calibration.
Over-refusal.
Q14.What is in-context learning?
In-context learning (ICL) is an LLM's ability to perform a new task from instructions or a few examples placed in the prompt, without any weight updates. The model infers the task from the context and applies it to a new input in the same forward pass.
Forms:
Zero-shot: an instruction only.
Few-shot: a handful of input→output demonstrations, then the query.
Why it works:
Pretraining text contains many implicit tasks, so the model learns to infer the latent task from context (the Bayesian-inference view).
Mechanistically, attention structures such as induction heads copy and extend patterns seen earlier in the context.
It emerged strongly with scale, as popularized by GPT-3.
Properties:
Temporary: the adaptation lasts only as long as the prompt.
Bounded by context length and paid for in prompt tokens on every call.
Sensitive to example choice, format, and order. Min et al. (2022) found that label correctness often matters less than the format and label space.
Q15.What causes a language model's knowledge cutoff?
A knowledge cutoff exists because a model's knowledge is frozen into its weights at training time. It only knows what was in its training corpus, which was collected up to some date. Anything after that date is invisible unless supplied at inference.
Data snapshot: Pretraining corpora (web crawls, books, code) are gathered up to a fixed date, then filtered, deduplicated and tokenized.
Frozen weights: After training, parameters don't update during use. Inference reads knowledge but never writes new knowledge.
Pipeline lag: Data processing, months of pretraining, post-training, safety evaluation and release mean a model is often months to a year stale at launch.
The cutoff is fuzzy, not a hard line:
Text about an event keeps accumulating online for years. Recent months are underrepresented in the snapshot, so knowledge of them is thin and unreliable.
The effective cutoff varies by topic and source; Cheng et al. (2024), "Dated Data", show it is often earlier than the reported one.
Models are often unsure of their own cutoff, because training text rarely states "today's date" consistently.
Why not just keep training?:
Retraining is expensive.
Continual training risks catastrophic forgetting and requires re-running alignment and evals.
Workarounds:
RAG and web search or tools inject fresh information into the context.
Periodic continued pretraining or fine-tuning.
Putting the current date in the system prompt.
Q16.What does it mean for an autoregressive model to be memoryless outside its explicit context window?
It means the model's next-token distribution depends only on its fixed weights and the tokens currently in its context window: there is no hidden state carried between calls, so anything not in the window (earlier turns, truncated text) has no influence on the output.
Formally: p(x_t | x_{t-k..t-1}; θ): A Markov model of order k (the window size); tokens before t-k are invisible.
Weights don't change at inference: Nothing from a conversation is learned or stored; general knowledge lives in weights, but session-specific facts exist only in the prompt.
The KV cache is not memory: It caches computations over tokens already in context for speed; evict the tokens and their cache goes too.
Contrast with RNNs: An RNN compresses unbounded history into a state vector; a Transformer has exact access within the window and none outside it.
Practical consequences:
Chat apps resend history every turn; long chats need truncation or summarisation.
"Memory" features are external: retrieval (RAG), stored user profiles or summaries injected back into the prompt.
Q17.What is an emergent ability in large language models?
An emergent ability (Wei et al., 2022) is one that is absent in smaller models but present in larger ones, so it cannot be predicted by extrapolating small-model performance: accuracy sits near random, then rises sharply past some scale.
Scale axis: Measured in training compute or parameter count (data and model size usually grow together).
Classic examples:
Multi-digit arithmetic, word unscrambling, and many few-shot BIG-Bench tasks.
Prompting techniques that only help large models, e.g. chain-of-thought hurt small models but helped at ~100B params in 2022-era models.
Contrast with smooth scaling: Pretraining loss follows predictable power laws; emergence is about downstream task metrics that don't.
Why it matters: Hard to forecast capabilities (including risky ones) before training a bigger model.
The debate: Schaeffer et al. (2023) argue much emergence is an artefact of discontinuous metrics like exact match; continuous metrics often show smooth gains.
Q18.What is a Mixture of Experts architecture in language models?
Mixture of Experts (MoE) replaces a transformer's single feed-forward block with many parallel "expert" FFNs plus a router that sends each token to only a few of them. Total parameters (capacity) grow much faster than per-token compute.
Structure:
Attention layers are usually shared. The FFN in some or all layers becomes N experts.
A learned router picks the top-k experts per token, per layer. The output is the gate-weighted sum of the chosen experts' outputs.
Some designs add always-on shared experts, as in DeepSeek.
Why use it: conditional computation:
Mixtral 8x7B has about 47B total parameters but only about 13B are active per token.
You get quality closer to a large dense model at the FLOPs of a small one, for both training and inference.
Costs and challenges:
All experts must sit in memory, so memory scales with total parameters, not active ones.
Load balancing needs an auxiliary loss or bias to avoid routing collapse. Tokens may be dropped when an expert exceeds its capacity.
Expert parallelism requires all-to-all communication between devices.
Training can be unstable (router z-loss helps), and fine-tuning is trickier.
Examples: Switch Transformer, GShard, Mixtral, DeepSeek-V3, Qwen MoE, and reportedly GPT-4.
Q19.What is the difference between BPE and WordPiece?
Both build a subword vocabulary by iteratively merging symbols, but they differ in the merge criterion: BPE merges the most frequent adjacent pair, while WordPiece merges the pair that most increases the likelihood of the training data. They also differ in how they tokenize new text at inference time.
Merge criterion (training):
BPE: pick the pair with the highest raw count.
WordPiece: pick the pair with the highest score count(ab) / (count(a) * count(b)). This favors pairs whose parts rarely appear apart, not just pairs that are common overall.
Encoding (inference):
BPE replays the learned merge rules in priority order.
WordPiece uses greedy longest-match-first: it takes the longest vocabulary entry that matches from the start of the word, then repeats on the remainder.
Conventions:
WordPiece marks word-continuation pieces with ## (e.g. play ##ing). It falls back to [UNK] for the whole word if it cannot be segmented.
Byte-level BPE never needs an unknown token, because every input reduces to bytes.
Where they are used: BPE in GPT-2/3/4, Llama and RoBERTa; WordPiece in BERT, DistilBERT and ELECTRA.
Q20.How is a BPE tokeniser trained?
Training starts from a base vocabulary of characters (or bytes) and repeats one step: count adjacent symbol pairs across the corpus and merge the most frequent pair into a new token. It stops when the vocabulary reaches the target size. The output is the vocabulary plus an ordered list of merge rules.
Pre-tokenize:
Split text into words or chunks (whitespace or a regex, e.g. GPT-2's pattern) so merges never cross those boundaries.
Count the frequency of each chunk.
Initialize: Represent each word as a sequence of base symbols (characters, or the 256 bytes for byte-level BPE).
Loop until the target vocab size is reached:
Count every adjacent pair, weighted by word frequency.
Merge the top pair everywhere it occurs, add it to the vocab, and record the rule.
Encoding new text: Apply the merges in the order they were learned (rank order), so the result is deterministic.
Vocab size is a hyperparameter you choose, typically 32k to 256k.
Q21.Why do LLMs struggle with character-level tasks like counting letters in a word or spelling backwards?
The model never sees characters. It sees subword token IDs, so "strawberry" may arrive as something like str + aw + berry. The letters inside each token are not directly visible, and spelling knowledge has to be memorized indirectly.
Tokens are opaque IDs:
An embedding for berry does not explicitly encode "b, e, r, r, y".
Spelling is learned only implicitly, from contexts where words happen to be spelled out. That knowledge is incomplete, especially for rare tokens.
Inconsistent segmentation: The same word tokenizes differently depending on a leading space, capitalization or surrounding text. The model must learn many mappings for one spelling.
The task needs explicit sequential state: Counting or reversing means first decomposing each token into letters and then iterating. Doing that in a single forward pass without intermediate output is error-prone.
Mitigations:
Have the model spell the word out with separators first ("s-t-r-a-w..."), which yields one token per letter, then reason step by step.
Use a code tool.
Use character- or byte-level models.
Q22.Why does standard tokenisation make multi-digit arithmetic difficult for language models?
Standard BPE chunks numbers by frequency, not by place value. The same digits get split inconsistently and the chunks do not line up with ones, tens and hundreds. The model must therefore learn arithmetic over arbitrary, shifting units instead of a clean digit-by-digit algorithm.
Arbitrary, inconsistent chunks:
For example 12345 might become 123 + 45, while 12346 splits differently, because common numbers (years, round numbers) got their own merges.
Digit positions are misaligned between operands, so column-wise addition has no consistent structure to learn.
Huge "digit alphabet": Multi-digit tokens turn simple digit rules into lookup tables over hundreds or thousands of token pairs, many of them rare.
Generation order vs carry direction: Models emit the most significant digits first, but carries propagate from the least significant digit. The model has to compute the carry before writing earlier digits.
Fixes:
Split every digit into its own token (PaLM, Llama) for a consistent per-digit representation.
Use fixed 1–3 digit chunks (GPT-4-era tokenizers); right-to-left chunking aligns better with place value.
Write numbers in reversed order during training, use chain-of-thought, or call a calculator or code tool.
Q23.Why do non-English languages typically require more tokens to represent the same content?
Tokenizers are trained mostly on English-heavy data, so their merges compress English well and other languages poorly. Non-Latin scripts also cost more UTF-8 bytes per character before any merging happens. The result is that the same meaning takes more tokens: a "token tax".
Training-data skew: BPE spends merges on frequent strings. English words and subwords win most of the vocabulary slots, so other languages get split into small fragments.
UTF-8 byte cost:
ASCII uses 1 byte per character, Cyrillic or Arabic 2, and CJK or Devanagari 3.
Byte-level BPE starts from bytes, so under-merged scripts can need multiple tokens per character.
Linguistic factors: Rich morphology (Finnish, Turkish) and scripts without spaces produce many rare surface forms that are hard to merge efficiently.
Consequences:
Higher API cost and latency.
Less effective context length.
Often lower quality, since the model sees fewer meaningful units per language.
Mitigations:
Train the tokenizer on more balanced multilingual data.
Use a larger vocabulary (e.g. Llama 3 at ~128k, Gemma at ~256k).
Q24.What problem does byte-level BPE solve compared to character-level BPE?
Byte-level BPE removes the unknown-token problem with a tiny base vocabulary. It starts from the 256 possible bytes, so any string in any language, emoji or binary-ish text can be encoded losslessly without [UNK] and without reserving slots for all ~150k Unicode characters.
Problem with character-level BPE:
The base vocab must contain every character you might see. Including all of Unicode wastes a huge number of slots.
Excluding rare characters means unseen emoji, symbols or scripts become [UNK], which loses information.
Byte-level solution (GPT-2 onward):
Text is UTF-8 encoded. The 256 bytes form the base vocab, and BPE merges are learned over byte sequences.
Full coverage and fully reversible encode/decode.
GPT-2 maps bytes to printable stand-in characters and uses a regex pre-split, so merges don't cross categories (e.g. letters with punctuation).
Trade-offs:
Poorly represented scripts can need several tokens per character, which means longer sequences.
A single token may be a partial UTF-8 character. Streaming decoders must buffer bytes, and a model can in principle emit invalid UTF-8.
Q25.What are the trade-offs of increasing the tokenizer vocabulary size?
A larger vocabulary compresses text into fewer tokens, giving more content per context window and fewer decoding steps. The costs are bigger embedding and output layers, a more expensive softmax, and more rare tokens that each get too little training signal.
Benefits of larger vocab:
Shorter sequences: cheaper attention (quadratic in length), more effective context, and fewer generation steps per sentence.
Better coverage of multilingual text, code and numbers, which reduces the token tax on non-English languages.
Costs of larger vocab:
Parameters: the embedding and LM head are each V × d. This is significant for small models, partly offset by weight tying.
Compute and memory: output logits over V at every position, plus larger softmax and cross-entropy memory during training.
Sparsity: each token appears less often. Rare tokens are undertrained, which can produce glitch tokens.
Coarser units hide sub-token structure, which hurts spelling and arithmetic-style tasks.
Smaller vocab has the reverse profile:
Compact layers and well-trained tokens.
Longer sequences and slower inference.
Practice: ~32k (Llama 2), ~50k (GPT-2), ~100k (GPT-4 cl100k_base), 128k (Llama 3), 256k (Gemma). The trend is toward larger vocabs as models grow, because the embedding cost becomes a smaller fraction of total parameters.
Q26.How does BPE segment an unseen text string at inference time?
BPE tokenizes new text by replaying the merge rules it learned during training, in order of priority. The text is first split into base units (bytes or characters), and the highest-ranked applicable merge is applied repeatedly until no learned merge fits.
Pre-tokenize: A regex splits the text into chunks (words, spaces, punctuation, digits), so merges never cross those boundaries. GPT-2 style tokenizers attach a leading space to the following word.
Convert each chunk to base symbols: Byte-level BPE maps each chunk to UTF-8 bytes, so every possible string is representable and no <unk> token is needed.
Apply merges greedily by rank:
Find the adjacent pair with the lowest merge rank (the one learned earliest) and merge every occurrence of it.
Repeat until no adjacent pair appears in the merge table.
Map the resulting symbols to token IDs.
Key properties:
The result is deterministic. Merges follow training order rather than an optimal segmentation, so the token count is not guaranteed to be minimal.
Unseen words break into known subwords, falling back to single bytes in the worst case (e.g. a rare name becomes several pieces).
Implementations cache results per chunk for speed.
Q27.How does the Unigram language model tokenizer differ from BPE?
BPE builds its vocabulary bottom-up and tokenizes deterministically by replaying merge rules. Unigram works top-down: it starts from a large candidate vocabulary and prunes it using a probabilistic language model, then picks the most likely segmentation with Viterbi. That probabilistic view also lets it sample alternative segmentations.
Training:
BPE starts from characters or bytes and repeatedly merges the most frequent adjacent pair until it reaches the target vocabulary size.
Unigram starts from many candidate substrings and fits a probability to each piece with EM. It then drops the pieces whose removal hurts corpus likelihood the least, repeating until it reaches the target size.
Segmentation at inference:
BPE applies its ordered merges greedily.
Unigram chooses the segmentation that maximizes the product of piece probabilities, using Viterbi over a lattice of possible splits.
Subword regularization:
Because Unigram defines a probability for every segmentation, training can sample different splits of the same text. This acts as data augmentation and improves robustness.
BPE needs a separate trick for this (BPE-dropout).
Usage:
Unigram is available in SentencePiece and used by T5, ALBERT, XLNet, and mBART.
BPE (often byte-level) is used by GPT and Llama-3.
Q28.What is SentencePiece, and why does it treat whitespace as part of the token vocabulary?
SentencePiece, and why does it treat whitespace as part of the token vocabulary?SentencePiece is Google's language-independent tokenizer library. It trains BPE or Unigram models directly on raw text, without language-specific pre-tokenization. It encodes whitespace as an ordinary symbol (▁, U+2581), which makes tokenization fully reversible and lets it work for languages that don't separate words with spaces.
What it is:
It treats input as a raw stream of Unicode characters and needs no external word splitter (e.g. no Moses tokenizer).
It supports Unigram (the default) and BPE, along with byte fallback, normalization (NFKC), and subword sampling.
Used by T5, Llama-1/2, Mistral, and Gemma.
Why whitespace becomes a token:
Lossless round-trip: decode(encode(x)) == x exactly. Detokenization just concatenates the pieces and replaces ▁ with a space, with no heuristics about where spaces go.
Language independence: Chinese, Japanese, and Thai have no spaces between words. Treating the space as just another character means one algorithm handles all languages.
Word-start information is preserved: ▁the (word-initial) and the (mid-word) are different tokens.
Example: "Hello world" → ["▁Hello", "▁world"].
Q29.What is the primary failure mode of greedy decoding in open-ended generation?
Greedy decoding tends to produce degenerate text: dull, generic output that often falls into repetitive loops. It always picks the locally most likely token, and in open-ended generation that is rarely the best or most human-like continuation.
Repetition loops: Once a phrase appears, it raises its own probability in context (a self-reinforcing loop). Greedy has no randomness to escape, so it repeats sentences or phrases indefinitely.
Blandness:
Human text is not maximum-likelihood text. People regularly choose less probable but informative words.
Always taking the argmax yields safe, generic phrasing (the "neural text degeneration" finding of Holtzman et al.).
Myopia: A locally best token can lead to a globally worse sequence, and greedy never revisits earlier choices.
No diversity: It is deterministic, so the same prompt always gives the same output. That is bad for creative tasks but fine for extraction, classification or code where one correct answer exists.
Fixes: sampling with temperature plus top-p, top-k or min-p, and repetition, frequency or presence penalties.
Q30.How does a frequency penalty differ from a presence penalty at the logit level?
Both subtract from the logits of tokens that already appear in the generated text. A frequency penalty scales with how many times a token has appeared. A presence penalty is a flat, one-time deduction applied once a token has appeared at all.
Frequency penalty: proportional:
logit[j] -= count[j] * alpha_freq
A token used 5 times is penalized 5× more than one used once. This specifically suppresses verbatim repetition and loops.
Presence penalty: binary:
logit[j] -= (count[j] > 0) * alpha_pres
It is the same penalty whether a token appeared once or 50 times. This pushes the model toward new tokens, and so new topics, rather than limiting reuse counts.
Both are additive shifts to logits before softmax and sampling:
Positive values discourage repetition. Negative values encourage it.
They differ from the multiplicative repetition_penalty (e.g. in Hugging Face), which divides positive logits (or multiplies negative ones) for any previously seen token.
Pitfall: large values penalize necessary tokens too (punctuation, names, code keywords), which degrades quality.
Q31.Can you walk through the step-by-step lifecycle of generating a complete response from an input prompt at inference time?
Inference proceeds in two phases. A parallel prefill pass processes the whole prompt and builds the KV cache. Then an autoregressive decode loop produces one token per forward pass until a stop condition is hit, and the tokens are detokenized and streamed back.
Prepare the input:
Apply the chat template (system/user role markers, special tokens).
Tokenize into token IDs (BPE or SentencePiece).
Prefill:
Embed the tokens and add positional information (e.g. RoPE).
Run all prompt tokens through every transformer layer in parallel. This step is compute-bound.
Store each layer's keys and values in the KV cache.
The last position's hidden state is projected to vocabulary logits. This determines time-to-first-token (TTFT).
Logit processing and token selection:
Apply penalties, logit bias or constrained-decoding masks, then temperature, then truncation (top-k, top-p, min-p).
Softmax, then sample (or take the argmax for greedy decoding).
Decode loop:
Feed only the new token through the model. Attention reads past K/V from the cache instead of recomputing them.
This phase is memory-bandwidth-bound (weights and KV cache are read every step). It determines time per output token.
Append the result to the cache and repeat step 3.
Stopping: Stop on an EOS or end-of-turn token, a stop sequence, max_tokens, or a context-length limit.
Detokenize and return: Convert IDs back to text, usually streamed incrementally. Care is needed with multi-byte characters split across tokens.
Serving layer (worth mentioning): Engines like vLLM use continuous batching across requests, paged KV-cache memory and prefix caching to raise throughput.
Q32.Why is beam search well-suited to translation but poorly suited to open-ended creative generation?
Beam search approximately finds the highest-likelihood sequence. In translation, the most probable output is usually the correct one, because the source sentence tightly constrains it. In open-ended generation, high likelihood corresponds to bland, repetitive and low-diversity text.
Why it fits translation:
The output space is narrow: meaning and roughly the length are fixed by the source, so a few correct answers dominate.
Greedy's myopic errors (early word choices that hurt later grammar) are fixed by keeping several hypotheses alive.
Accuracy and fidelity matter more than variety, and metrics like BLEU reward the "modal" translation.
Why it fails for creative generation:
There are many valid continuations, and human text is not maximum-likelihood. Maximizing probability selects generic phrasing.
It amplifies repetition loops: repeated text becomes high-probability, so the search actively seeks it.
Beams collapse into near-duplicates differing by a token, so there is no real diversity.
It is deterministic and B× more expensive, with no creative payoff.
Nuance:
Even in translation, very wide beams can hurt quality (the "beam search curse", favoring short or empty outputs). Length normalization and modest beam widths (4–5) are used.
Open-ended LLM generation uses sampling (temperature with top-p or min-p) instead.
Q33.What advantage does min-p sampling offer over a fixed top-p threshold?
min-p sampling offer over a fixed top-p threshold?Min-p sets the cutoff relative to the top token's probability (keep tokens with p ≥ min_p × p_max), so truncation scales with model confidence. This keeps output coherent even at high temperatures, where a fixed top-p would admit a long tail of junk tokens.
How it works: With min_p = 0.1: if the top token has 0.9, only tokens ≥ 0.09 survive. If the top token has 0.2, tokens ≥ 0.02 survive.
Top-p's weakness:
Top-p fixes cumulative mass, not a quality bar. When the distribution is flat, or flattened by high temperature, reaching 90% mass can require hundreds of tiny-probability tokens, which lets incoherent ones through.
When the model is confident, top-p may still include a few low-quality tail tokens just to reach the mass threshold.
Min-p's advantages:
Confident step: an aggressive cutoff gives near-greedy behavior and protects correctness.
Uncertain step: a lenient cutoff admits many comparably good options, which gives diversity.
It enables higher temperatures for creativity without collapsing into gibberish. The single parameter behaves consistently across contexts.
Caveat: order matters. Min-p is often applied before temperature so that temperature doesn't flatten the distribution it measures (an implementation choice in engines like llama.cpp and vLLM).
Q34.Why does beam search use length normalisation when scoring candidate sequences?
Beam search ranks hypotheses by summed log-probability. Every extra token adds a negative term, so raw scores systematically favour short outputs. Length normalisation divides the score by a function of length so that hypotheses of different lengths compete fairly.
The bias:
The sequence score is log P(y) = Σ log p(y_t | y_<t), and each term is ≤ 0. Longer sequences therefore almost always score lower.
As a result, the search prefers hypotheses that emit EOS early, giving truncated translations and terse summaries.
Larger beams make it worse: they find more short, high-probability candidates (part of the "beam search curse").
The fix:
Simple form: score = log P(y) / |y|^α, where α ∈ [0, 1] controls strength. α = 0 means no normalisation; α = 1 gives the per-token average.
GNMT form: lp(Y) = ((5 + |Y|) / 6)^α, which softens the effect for very short outputs.
In Hugging Face this is length_penalty (the exponent applied to length). Values > 1 push longer outputs; values < 1 push shorter ones.
Why it matters:
Finished hypotheses of different lengths must be compared at the end. Without normalisation, that comparison is dominated by length rather than by quality.
α is a tuned hyperparameter. Other complements include a coverage penalty (in MT) and min_new_tokens.
Q35.What are the core theoretical limitations of n-gram language models compared to neural language models?
n-gram models treat words as atomic symbols and condition on a fixed, short window. They therefore suffer from data sparsity, cannot generalise to similar but unseen contexts, and miss long-range dependencies. Neural LMs address these with learned distributed representations, parameter sharing, and much longer context.
Fixed, short context (Markov assumption):
The model only sees the previous n−1 tokens, so agreement, coreference, and topic beyond that window are invisible.
Increasing n doesn't scale (see below). Transformers instead attend over thousands of tokens.
Curse of dimensionality and sparsity:
There are up to V^n possible n-grams, and most never appear in training data, so MLE gives them zero probability.
This requires smoothing, backoff, and interpolation (e.g. Kneser-Ney). These are heuristics for redistributing probability mass, not real generalisation.
Model size grows with the number of distinct n-grams, giving huge count tables.
No notion of similarity:
Seeing "the cat sat" tells the model nothing about "the dog sat", because the words are unrelated symbols.
Neural LMs embed tokens in a continuous space. Similar words get similar vectors, so evidence transfers across contexts (Bengio et al., 2003).
No compositional or abstract features: Counts can't represent syntax, semantics, or reasoning patterns. Neural networks learn hierarchical features that are shared across all contexts.
Where n-grams still win: They are cheap, fast, and interpretable, and they need no GPU. They remain useful as baselines, in ASR decoding, and for data deduplication or filtering.
Q36.Why does pretraining purely on next-token prediction give rise to general task capabilities?
To predict the next token well across a vast, diverse corpus, a model must implicitly learn whatever generated that text: grammar, facts, the intent behind instructions, and reasoning steps. Many tasks already appear in natural text as continuations. So minimising next-token loss at scale acts as an implicit multitask objective, and general capabilities fall out of it.
Prediction requires understanding:
Lower loss on "The capital of France is ___" requires facts. On a math proof it requires following the logic. On dialogue it requires modelling the speakers' goals.
Prediction is equivalent to compression: the cheapest way to compress diverse text is to capture its underlying structure, not surface statistics.
Tasks are embedded in the data:
The web contains translations, Q&A pairs, code with comments, and summaries ("TL;DR:"). Continuing a well-framed prompt therefore performs the task.
This is the thesis of GPT-2 ("Language Models are Unsupervised Multitask Learners").
Scale drives it:
Loss falls predictably with parameters, data, and compute (scaling laws). Some capabilities, such as in-context learning and few-shot prompting, become usable only at larger scale (GPT-3).
The objective is dense: every token is a training signal, and the supply of unlabeled data is effectively unlimited.
Caveats:
The base model imitates the data distribution, not the user's intent. Instruction tuning and RLHF are needed to reliably elicit helpful behaviour.
The model learns what is predictive of text, which includes errors, biases, and plausible-sounding falsehoods (hallucination).
Q37.What is exposure bias in autoregressive language models?
Exposure bias is the train/inference mismatch of teacher forcing. During training the model always conditions on ground-truth prefixes. At generation time it conditions on its own, possibly wrong, outputs, a distribution it never saw. Early mistakes can therefore push it into unfamiliar states where errors compound.
Where it comes from:
Teacher forcing optimises p(x_t | true x_<t). It is efficient and parallel, but it never exposes the model to recovering from its own errors.
At inference the prefix distribution shifts (covariate shift). Errors compound over long sequences, and the impact is often argued to grow with length.
Symptoms attributed to it:
Drift, incoherence, and repetition loops in long generations.
Some research argues the effect is small for large LMs, and that degeneration owes more to the decoding strategy and the likelihood objective.
Mitigations:
Scheduled sampling: gradually feed the model's own predictions during training.
Sequence-level training on sampled outputs: REINFORCE or minimum-risk training (MT), and RLHF/RL fine-tuning on the model's own generations.
Imitation-learning style methods (DAgger, SEARN), plus better decoding (nucleus sampling, repetition penalties).
Q38.How is perplexity mathematically related to cross-entropy loss?
Perplexity is the exponential of the average per-token cross-entropy (negative log-likelihood): PPL = exp(H), where H = −(1/N) Σ log p(x_t | x_<t). They carry the same information. Minimising cross-entropy loss minimises perplexity.
The math:
Equivalent form: PPL = P(x₁…x_N)^(−1/N), the inverse geometric mean of the token probabilities.
The base must match: with loss in nats (natural log, as in PyTorch), use e^H; with bits, use 2^H.
Intuition: effective branching factor:
A PPL of k means the model is as uncertain as if it chose uniformly among k tokens at each step.
A uniform model over vocabulary V has PPL = |V|. A perfect model has PPL = 1 (loss = 0).
Why use one or the other:
Cross-entropy is the additive, differentiable training objective. Perplexity is a more interpretable reporting metric.
Because of the exponential, small loss differences become large PPL differences: going from loss 2.0 to 1.9 moves PPL from about 7.39 to about 6.69.
Caveats:
PPL is per token, so it depends on the tokenizer. Models with different vocabularies aren't directly comparable; use bits-per-byte or per-character instead.
Low perplexity doesn't guarantee good downstream or generation quality.
Q39.Why is a lower perplexity not a guarantee of higher generation quality?
Perplexity measures how much probability a model assigns to held-out reference text, token by token, under teacher forcing. Generation quality depends on what the model produces when it samples from its own outputs, and on properties like factuality, coherence and helpfulness. Perplexity does not measure either of these directly.
It scores the wrong distribution:
Perplexity is computed on ground-truth prefixes. At generation time the model conditions on its own previous tokens, so small errors can compound (exposure bias).
Long-range coherence, staying on topic, and avoiding contradictions are barely reflected in an average of per-token log-likelihoods.
MLE is mode-covering:
Cross-entropy heavily penalizes assigning low probability to any real token. Models learn to spread some mass over many continuations, including poor ones.
When you sample, you can land in that low-quality tail. Greedy or beam decoding on a low-perplexity model can still produce repetitive, degenerate text (Holtzman et al., "neural text degeneration").
The average hides what matters:
Most tokens are easy (function words, formatting), so they dominate the score.
A model can improve perplexity on these tokens while staying wrong on the few content tokens that carry facts or reasoning.
Alignment trades perplexity for quality:
RLHF and instruction-tuned models often have higher perplexity on generic web text than their base models.
Humans still rate them far better, because they optimize for helpfulness rather than for imitating the corpus.
Comparability and leakage issues:
Scores depend on the tokenizer and the eval set.
Contamination or memorization lowers perplexity without improving generalization.
Practice: use perplexity as a pretraining health signal. Judge generation with task benchmarks, human or LLM-judge evals, and decoding-aware tests.
Q40.How is the cross-entropy loss calculated for a sequence during autoregressive pretraining?
For a sequence x₁…x_T, the model predicts each token from the true prefix (teacher forcing). The loss is the average negative log-probability of the actual next tokens: L = −(1/T) Σₜ log p(xₜ | x₍<ₜ₎). All positions are computed in parallel in one forward pass, using a causal mask.
Forward pass:
Feed tokens [x₁ … x_{T−1}].
The causal attention mask ensures position t only sees tokens ≤ t.
Output logits have shape (T−1, V), where V is the vocabulary size.
Shift labels: The target at position t is xₜ₊₁, so labels are [x₂ … x_T].
Per-token loss:
Apply log-softmax to the logits.
Take −log of the probability assigned to the correct token. This is cross-entropy against a one-hot target.
Mask and average:
Ignore padding positions (and prompt tokens in SFT) using label -100.
Average over the remaining tokens. In a batch, this is typically the mean over all non-masked tokens.
exp(loss) is the perplexity of the sequence.
Q41.Why can't perplexity scores be directly compared between two models that use different tokenizers?
Perplexity is normalized per token, and different tokenizers split the same text into different numbers and kinds of tokens. The two scores are therefore averages over different units and different prediction problems, not over the same text.
Different denominators:
Suppose two models assign the same total probability to a document.
If one tokenizer produces 1,000 tokens and the other 1,500, the per-token average NLL differs.
The finer-grained tokenizer gets a lower perplexity, because each of its tokens is easier to predict.
Different prediction tasks:
Vocabulary size changes the event space: predicting one of 32k pieces is not the same task as predicting one of 256k pieces.
A character-level model can have tiny perplexity while being a worse language model.
Preprocessing differences: Unicode normalization, special tokens (BOS/EOS), and whitespace handling change what is actually being scored.
The fix: normalize by a tokenizer-independent unit:
Sum the total NLL over the text, which is comparable because it is −log p(text).
Divide by bytes, characters, or words.
Bits-per-byte = total NLL (nats) / (ln 2 × number of UTF-8 bytes).
Word-level perplexity = exp(total NLL / number of words).
Q42.What is the difference between an instruction-tuned model and a multi-turn chat model?
An instruction-tuned model is trained to answer a single instruction well. A multi-turn chat model is additionally trained on whole conversations, in a role-structured format, so it can track context, refer back to earlier turns, and keep obeying a system prompt across many exchanges. In practice, most modern "instruct" releases are already chat models.
Instruction-tuned (single-turn):
Training data: (instruction, optional input) → response pairs, e.g., early FLAN and Alpaca.
Good at one-shot tasks.
May lose coherence, ignore earlier constraints, or drift when given a long dialogue history.
Multi-turn chat:
Trained on multi-turn transcripts, using a chat template with special role tokens (system / user / assistant).
Loss is typically applied to all assistant turns and masked on user and system turns.
Learns follow-ups, clarifications, coreference to earlier turns ("make it shorter"), and persistent persona or system-prompt adherence.
Often also trained for tool-call turns.
Practical implication:
Always format inputs with the model's own template (e.g., tokenizer.apply_chat_template).
A wrong or missing template noticeably degrades output quality.
The terms blur: The distinction is about training data and format, not a fundamentally different architecture.
Q43.Why will a base model often continue a prompt with more questions rather than answering it?
A base model is trained only to predict the next token of internet-style text, so it treats your prompt as the start of a document and continues it in the most likely way. A lone question often appears in lists of questions (FAQs, exams, forum threads), so generating more questions is a statistically plausible continuation.
Objective is document continuation, not helpfulness:
Pretraining maximizes likelihood of the next token; there is no notion of a user, an assistant, or a turn to respond to.
The model infers what kind of document it is in and imitates that genre.
Questions cluster in training data:
Quizzes, homework sheets, interview-question lists, and survey forms contain question after question with no answers.
"What is the capital of France?" followed by a newline is often followed by another question.
No end-of-turn signal: Without a chat template, there is no marker saying "the user is done; now answer".
How to fix it:
Prompting: frame a document where an answer comes next (e.g. Q: ... A:, or few-shot Q/A pairs).
Training: instruction tuning and RLHF teach the model the user/assistant turn structure, so it responds instead of continuing.
Q44.What constitutes a chat template at the raw token level?
At the token level, a chat template is just a fixed serialization format. It turns a list of role-tagged messages into one flat token sequence, using special tokens (or reserved strings) that mark where each turn starts and ends and who is speaking. The model was fine-tuned on exactly this format, so it only behaves like an assistant when the format is reproduced exactly.
Components:
Sequence markers: BOS such as <s> or <|begin_of_text|>.
Turn delimiters: e.g. <|im_start|> / <|im_end|> (ChatML) or <|start_header_id|> / <|eot_id|> (Llama 3).
Role names: system, user, assistant, tool, which are often ordinary tokens placed inside the header.
Generation prompt: an open assistant header with no closing token, which cues the model to write the reply.
Special tokens are single vocabulary IDs:
They are not split into sub-pieces, and user text normally cannot produce them. This is what separates control structure from content.
The end-of-turn token doubles as the stop signal for generation.
Why exactness matters:
Wrong delimiters, missing BOS, or extra whitespace shift the input off the fine-tuning distribution and degrade output. The model may also never stop generating.
In Hugging Face, the template is a Jinja string stored in the tokenizer and applied via apply_chat_template().
Q45.Why does chain-of-thought prompting improve an LLM's multi-step reasoning?
Chain-of-thought (CoT) lets the model generate intermediate steps that it can then condition on. This gives it more serial computation per answer and breaks a hard mapping into many easy next-token predictions, rather than forcing the answer out in a single forward pass.
More computation per problem:
A single forward pass has fixed depth, which limits how many sequential operations it can perform.
Each generated token adds another full pass. The written steps act as an external scratchpad or working memory.
Theoretical work shows transformers with CoT can solve serial problems that fixed-depth transformers cannot.
Decomposition into easier steps:
Each step (e.g. "5 × 3 = 15") is a local, well-practiced pattern, even when the whole problem is not.
Intermediate results are stored explicitly in the context instead of having to be held implicitly in activations.
Matches training data: Worked solutions, proofs, and explanations in pretraining data show step-by-step reasoning. CoT puts the model in that distribution.
Caveats:
The benefit is emergent: it mainly helps large models and hurts or does nothing for small ones (Wei et al., 2022).
An error in an early step propagates to later ones.
The written chain is not guaranteed to be faithful to the model's actual internal computation.
Q46.Why are few-shot prompts sensitive to the ordering of demonstrations?
The model processes demonstrations autoregressively and has learned biases about position and recency, so the same examples in a different order produce different conditional distributions. Zhao et al. (2021) and Lu et al. (2022) showed that order alone can swing accuracy from near-chance to near state-of-the-art.
Recency bias: Labels near the end of the prompt are over-predicted. If the last few demos are "positive", the model leans positive.
Majority-label and common-token bias: Label frequency in the prompt and token priors from pretraining skew outputs. How labels are arranged changes how strongly these biases show up.
ICL is pattern-matching, not true averaging:
Causal attention is not permutation-invariant. Later examples attend to earlier ones, so the model never sees the demos as an unordered set.
Smaller models are generally more sensitive, and adding more examples does not reliably remove the effect.
Mitigations:
Contextual calibration: estimate bias with a content-free input like "N/A" and rescale the output probabilities.
Balance and interleave labels, choose an ordering on a validation set, or ensemble over several permutations.
Q47.How does in-context learning differ from fine-tuning at the parameter level?
Fine-tuning changes the model's weights through gradient descent, so the adaptation is permanent. In-context learning (ICL) leaves every weight frozen and adapts only through the activations produced by examples in the prompt. That adaptation disappears when the context is gone.
Fine-tuning:
Backpropagation updates parameters θ → θ′ (all of them, or a subset such as LoRA adapters).
Needs labeled data, compute, and a training run. The result persists across all future inputs.
It can teach new skills or formats, but it can also cause catastrophic forgetting.
In-context learning:
Only the forward pass runs. The demos shape the hidden states and KV cache, and attention conditions the output on them.
Research suggests attention can implement something like an implicit gradient step on the demos, a "virtual" update applied to activations rather than weights.
Limited by context length. Each request pays the cost of the extra prompt tokens, and nothing is retained between requests.
Practical trade-off: ICL suits fast iteration with few examples. Fine-tuning suits many examples, stable behavior, lower per-call token cost, and deeper changes in behavior.
Q48.How does self-consistency improve output reliability over greedy chain-of-thought?
Self-consistency samples many diverse chain-of-thought paths at nonzero temperature and takes a majority vote over their final answers. A single unlucky reasoning path can no longer decide the result, and agreement across samples tends to signal correctness (Wang et al., 2022).
Weakness of greedy CoT: Greedy decoding commits to one path. An early mistake propagates, and the locally most likely tokens do not always form the best overall chain.
How self-consistency works:
Sample N reasoning chains with temperature or top-p sampling.
Extract the final answer from each chain.
Return the most frequent answer. In effect, this marginalizes over reasoning paths.
Why it helps:
There are many valid routes to a correct answer but errors are scattered, so correct answers concentrate while wrong ones split the vote.
The vote share also acts as a confidence estimate.
The original paper reported large gains on arithmetic and commonsense benchmarks (e.g. about +17 points on GSM8K).
Limits:
Costs roughly N times the inference compute.
Needs answers that can be compared for voting, so it does not apply directly to open-ended text.
It cannot fix errors the model makes systematically on every sample.
Q49.What is majority label bias in few-shot prompting, and why does it occur?
Majority label bias is the tendency of a model in few-shot prompting to predict whichever label appears most often among the demonstrations, regardless of the test input. It happens because the prompt itself shifts the model's output prior toward label tokens it has just seen many times.
What it looks like:
With 3 "positive" and 1 "negative" example, the model over-predicts "positive", even on clearly negative inputs.
Zhao et al. (2021, "Calibrate Before Use") documented it alongside two related biases: recency bias (favoring labels near the end of the prompt) and common token bias (favoring labels that are frequent in pretraining).
Why it occurs:
The model conditions on the whole context. Repeated label tokens raise their probability, much as copying and frequency patterns raise any token's probability.
In-context learning is shallow pattern-matching more than true learning, so surface statistics of the prompt leak into predictions.
The effect is strongest for smaller models and when the test input is ambiguous, because there is less input evidence to override the skewed prior.
Consequences: Accuracy becomes highly sensitive to the choice, balance and order of examples, which leads to high variance across prompts.
Mitigations:
Balance labels in the demonstrations and shuffle their order.
Contextual calibration: query with a content-free input (e.g. "N/A"), measure the label distribution it produces, then rescale outputs so that input maps to uniform.
Ensemble over several prompts or permutations.
Q50.When can chain-of-thought prompting degrade model accuracy or efficiency?
Chain-of-thought (CoT) can hurt in four main cases: when the model is too small to reason coherently, when the task doesn't benefit from explicit steps, when the extra tokens cost more than they gain, and when the generated reasoning introduces or compounds errors.
Small models: Wei et al. (2022) found CoT gains emerge only at large scale. Smaller models produce fluent but illogical chains that lower accuracy.
Tasks that don't need multi-step reasoning:
Meta-analyses (e.g. "To CoT or not to CoT", Sprague et al. 2024) find gains concentrate in math and symbolic logic. Factual recall, classification and commonsense tasks see little or no benefit.
Some tasks get worse with deliberation, mirroring humans who "overthink": implicit pattern learning, perceptual judgments, and tasks with exceptions to verbal rules (Liu et al. 2024).
Efficiency costs:
Many more output tokens means higher latency and cost, since decoding is sequential and output tokens are priced higher.
Reasoning models can "overthink" trivial queries, spending thousands of tokens on simple questions.
Error propagation and unfaithfulness:
An early mistake gets conditioned on and amplified. Long chains give more chances to drift.
Stated reasoning may not reflect the real computation (unfaithful CoT), so it can rationalize a wrong answer convincingly.
Practical breakage:
Reasoning text can break strict output formats or parsers.
Adding "think step by step" to models that already reason internally is often redundant or harmful.
Rule of thumb: use CoT for multi-step math, logic or planning on capable models. Skip it for lookups, classification and latency-sensitive paths, and always measure both ways.
Q51.Why do LLMs hallucinate from the perspective of the next-token prediction objective?
Next-token prediction rewards producing plausible continuations, not true ones. The model must always output some likely token and is never trained to say "I don't know", so when knowledge is missing or weak it generates fluent text that fits the pattern of a fact.
The objective is likelihood, not truth:
Cross-entropy pushes probability toward what typically follows in the training text.
A made-up but plausible citation or date can score nearly as well as the real one.
Softmax always commits: Probability mass must go somewhere. With no grounded answer, sampling still picks a fluent-looking token, and abstention is not a natural outcome.
Rare facts are statistically hard:
Facts seen once or rarely (e.g. a person's birthday) can't be reliably learned from patterns.
Kalai et al. (OpenAI, 2025) argue generation errors are lower-bounded by the error of classifying valid vs invalid outputs, so some hallucination is inevitable.
Training and evaluation reward guessing:
Binary-graded benchmarks give zero credit for "I don't know", so confident guessing is optimal.
Post-training can reinforce this tendency.
Autoregressive snowballing and exposure bias: Training uses teacher forcing on ground-truth prefixes. At inference the model conditions on its own outputs, so an early wrong token gets elaborated consistently.
Lossy compression of knowledge: Parameters store blended statistical associations, not a database, so similar entities and facts get conflated.
Mitigations follow from the causes:
Grounding via RAG or tools addresses missing knowledge.
Rewarding abstention and calibrated uncertainty addresses the incentive to guess.
Lower temperature for factual tasks reduces low-probability picks.
Q52.What is the difference between intrinsic and extrinsic hallucination?
The distinction is defined relative to a source, such as the input document or retrieved context. An intrinsic hallucination contradicts that source. An extrinsic hallucination adds content the source can neither confirm nor refute.
Intrinsic hallucination:
The output conflicts with information in the source.
Example: the article says the vaccine was approved in 2019, the summary says 2021. Or entities and relations get swapped.
Detectable from the source alone, e.g. NLI or entailment checks between source and output.
Extrinsic hallucination:
The output introduces claims not present in the source.
Example: the summary adds "the CEO resigned" when the article never mentions it.
The added claim may happen to be true in the world, but it is still unfaithful to the source.
Verifying it requires external knowledge, such as retrieval or fact-checking.
Origin and context:
The taxonomy comes from summarization and NLG research (Maynez et al. 2020; Ji et al. 2023 survey).
It is most meaningful for source-grounded tasks such as summarization, RAG and translation.
Related framing for open-ended chat:
Faithfulness hallucination: unfaithful to the context or instructions.
Factuality hallucination: wrong about the world (Huang et al. 2023).
Why it matters in RAG:
Intrinsic errors point to misreading the context.
Extrinsic errors point to the model leaking parametric knowledge or inventing details. Grounding constraints and citation requirements target this case.
Q53.Why does hallucination risk increase as generation length grows?
Autoregressive generation conditions every new token on all previous tokens, including the model's own mistakes. Small per-token error probabilities compound over length, and an early wrong claim becomes "context" that later tokens confidently build on.
Compounding error:
If each factual step has a small chance of going wrong, the chance of at least one error grows roughly as 1 − (1 − p)^n with length n.
There is no built-in backtracking: once a token is sampled, it is fixed.
Exposure bias and self-conditioning:
Training uses teacher forcing on ground-truth prefixes, but at inference the model reads its own outputs, which drift off the training distribution.
A fabricated detail (a fake citation or date) is then treated as true, and the model stays consistent with it (snowballing hallucination).
Weakening grounding over long contexts:
Attention to the original prompt or retrieved documents gets diluted as the generated text grows ("lost in the middle").
Later content leans more on fluent pattern completion and less on the source facts.
Running out of known facts:
Long answers push past what the model actually knows; the training objective rewards plausible continuations, so it fills gaps with confident filler.
Sampling randomness (higher temperature) accumulates more chances to pick a low-probability, wrong token.
Mitigations: chunk tasks into shorter steps, re-ground with retrieval per section, use lower temperature for factual spans, and verify claims afterward.
Q54.Why is document-level deduplication critical when preparing pretraining corpora?
Web crawls contain huge numbers of duplicate and near-duplicate documents. Leaving them in wastes compute, skews the data distribution, increases verbatim memorization, and can leak benchmark data, so deduplication reliably improves model quality per training token.
Why duplicates hurt:
Wasted compute: repeated documents add no new information but consume token budget.
Distribution skew: boilerplate, templates, and mirrored pages get overweighted, biasing what the model learns.
Memorization and privacy: text seen many times is far more likely to be regurgitated verbatim, including personal data or copyrighted text.
Evaluation leakage: duplicated test sets across the web inflate benchmark scores.
Evidence: Lee et al. (2021) showed deduplicated training reaches the same or better perplexity with fewer steps and emits memorized text much less often.
How it's done:
Exact: hash normalized documents (e.g. SHA-1/MD5) and drop collisions.
Near-duplicate: MinHash + LSH over n-gram shingles to find pairs above a Jaccard threshold (around 0.8).
Sub-document: suffix arrays to remove repeated long substrings (boilerplate, licenses).
Nuance: some deliberate repetition of high-quality data can help, but it should be a controlled choice, not an accident of crawling.
Q55.What is pretraining data contamination?
Pretraining data contamination is when evaluation data (benchmark questions, answers, or close paraphrases) ends up in the model's training corpus. The model can then score well by recalling what it saw rather than by generalizing, so benchmark results overstate its real capability.
How it happens:
Benchmarks are posted on GitHub, papers, forums, and blogs, which get scraped into web crawls.
Indirect forms: paraphrased or translated test items, or solutions discussed online.
Why it matters:
Inflated scores mislead model comparisons and research conclusions.
Hard to detect for closed models whose training data is not public.
Detection:
N-gram overlap between test items and the corpus (e.g. GPT-3 used 13-gram overlap checks).
Behavioral probes: the model completes a test question verbatim, or has unusually low perplexity on benchmark text vs. fresh rewrites.
Score drops on newly written or perturbed versions of the benchmark.
Mitigation: decontaminate the corpus against known benchmarks, use held-out or post-cutoff evaluation sets, and report contamination analyses.
Q56.How are pretraining corpora filtered for quality beyond deduplication?
Beyond deduplication, corpora pass through a pipeline of cheap heuristic filters, then model-based quality and safety classifiers, plus decontamination. The aim is to keep informative, well-formed text and drop spam, boilerplate, toxic content, and personal data.
Extraction and language ID: Strip HTML and boilerplate (e.g. trafilatura), then keep the target languages with a classifier like fastText lang-ID.
Heuristic rules (Gopher / C4 style):
Document length, mean word length, symbol-to-word ratio, fraction of lines ending in punctuation.
Repeated lines or n-grams, "lorem ipsum", JavaScript or cookie notices, bad-word lists.
Model-based quality scoring:
Classifier trained to separate reference-quality text (Wikipedia, books) from random web text, as in GPT-3.
Perplexity filtering with a small LM trained on clean data (CCNet).
LLM-annotated scores distilled into a cheap classifier, e.g. FineWeb-Edu's "educational value" score.
Safety and privacy: Toxicity/NSFW classifiers, URL blocklists, PII detection and redaction (emails, phone numbers).
Benchmark decontamination: remove documents with n-gram overlap against evaluation sets.
Trade-offs:
Aggressive filtering can remove dialects, minority topics, or valid code, introducing bias and lowering diversity.
Thresholds are tuned with small-model ablations on downstream benchmarks.
Q57.What happens to downstream performance if a model is undertrained relative to its parameter count?
An undertrained model wastes its parameters. For the same training compute, a smaller model trained on more tokens would reach lower loss and better downstream scores, and it would also be cheaper to serve.
What Chinchilla showed:
At a fixed compute budget, parameters and tokens should grow together. The rule of thumb is about 20 tokens per parameter.
GPT-3 (175B parameters, about 300B tokens) and Gopher (280B) were heavily undertrained by this measure.
Chinchilla (70B parameters, 1.4T tokens) used the same compute as Gopher yet beat it on most benchmarks.
Downstream effects:
Pretraining loss stays above what the model's capacity could reach. Since benchmark accuracy tracks loss, scores on reasoning, knowledge (e.g. MMLU) and few-shot tasks lag.
Abilities that only appear once loss drops below a certain level may never show up.
Fine-tuning and RLHF only partly compensate. They shape behavior but cannot supply the missing pretraining knowledge.
Cost effect: every query pays the inference cost of a large model while getting the quality of a smaller one.
Contrast with deliberate overtraining:
Modern models often go far beyond 20 tokens per parameter. Llama 3 8B, for example, was trained on about 15T tokens.
Loss keeps improving, just with diminishing returns per FLOP. The payoff is a small model that is cheap to serve.
Undertraining is the opposite trade and almost never optimal.
Q58.How does the router in an MoE model decide which experts process a token?
The router is a small learned linear layer in each MoE layer. It scores every expert from the token's hidden state, keeps the top-k experts, and combines their outputs weighted by the normalized router scores. This decision is made per token and per layer.
How the scoring works:
Compute logits s = h · W_r, one per expert.
Apply softmax, or sigmoid affinities in DeepSeek-V3, to get gate probabilities.
Select the top-k experts. Examples: k=1 in Switch Transformer, k=2 of 8 in Mixtral, 8 of 256 routed experts plus a shared expert in DeepSeek-V3.
Output = Σ gate_i · expert_i(h) over the chosen experts. The gates are often renormalized over the top-k.
How the router learns:
It is trained end to end. Gradients reach W_r through the gate weights that scale each expert's output.
The top-k selection itself is not differentiable.
Noisy top-k (Shazeer et al., 2017) adds noise to the logits during training to encourage exploration.
An auxiliary load-balancing loss keeps routing from collapsing onto a few experts.
Routing variants:
Token choice: each token picks its experts. This is the standard approach.
Expert choice: each expert picks its top tokens. Load is balanced by construction, but some tokens may get zero experts, and it is awkward for autoregressive decoding.
What the experts learn: specialization tends to be syntactic or token-level (punctuation, code tokens) rather than clean topic domains.
Q59.Why do glitch tokens trigger erratic model behaviour?
Glitch tokens are vocabulary entries that the model almost never saw during training, so their embeddings are essentially untrained. When one appears in a prompt, the model gets an input vector it has no learned meaning for, and its behavior becomes unpredictable.
How they arise:
The tokenizer is trained on a different corpus than the model. Example: SolidGoldMagikarp in the GPT-2/GPT-3 tokenizer, which came from frequent Reddit usernames in the tokenizer data.
That string was filtered out or rare in the model's training data, so its embedding received almost no gradient updates.
Why behavior goes wrong:
The embedding stays near its initialization, or is shrunk toward the centroid by weight decay. It carries no meaning and sits out of distribution for later layers.
The output side is also untrained, so the model can't reproduce the token. Asked to repeat it, the model may substitute other words, evade, hallucinate, or produce bizarre or hostile text.
Detection and prevention:
Train the tokenizer on the same distribution as the model.
Flag under-trained tokens by unusual embedding norms or similarity to the unused-token centroid, then verify with prompts.
Remove or remap unused tokens before release.
Q60.How does constrained, grammar-based decoding work at the logit level to force valid outputs?
At each decoding step, constrained decoding works out which tokens could legally come next under a grammar (JSON schema, regex, or CFG). It sets every other token's logit to −∞ before softmax and sampling, so the model can only ever produce strings the grammar accepts.
Per-step loop:
The model produces logits over the whole vocabulary.
The grammar state (an automaton or parser) computes the set of allowed tokens.
Disallowed logits are masked to −∞, so their probability after softmax is 0.
Sampling proceeds as normal (temperature, top-p) over the remaining tokens. The chosen token then advances the grammar state.
Representing the grammar:
Regex and simple schemas compile to a finite-state machine (FSM). Outlines precomputes, for each FSM state, which vocabulary tokens are valid.
Nested JSON or code needs a CFG handled by a pushdown automaton or Earley parser (e.g. llama.cpp GBNF, XGrammar, llguidance).
The token–character mismatch:
Grammars are defined over characters, but tokens span several characters. Each token's full string must be checked against the grammar state.
Implementations precompute masks or use vocabulary tries to keep the per-step overhead small.
Caveats:
The output is guaranteed to be syntactically valid, not correct. Forcing low-probability paths can hurt quality.
Including the schema in the prompt keeps the model's own distribution aligned with the constraint.
Q61.How would you compute perplexity on a document longer than the model's context window?
Use a sliding window with a stride smaller than the context length. Score only the new tokens in each window, so every token is predicted with as much preceding context as possible. Then sum the NLL over all scored tokens, divide by their count, and exponentiate.
Naive approach: non-overlapping chunks:
Split into max_len chunks and score each one independently.
Tokens at the start of each chunk get little or no context, so perplexity is overestimated.
Strided sliding window:
Move a window of size max_len forward by stride s (e.g., s = max_len/2).
In each window, mask the labels of the overlapping prefix (-100). Those tokens serve only as context, and only the last s tokens are scored.
Accumulate the summed NLL and the number of scored tokens. Each token must be counted exactly once.
PPL = exp(total NLL / total scored tokens).
Trade-off:
A smaller stride gives more context per token and a lower, more faithful perplexity, but needs more forward passes.
stride = 1 is exact but very costly.
Report the window and stride used:
Numbers are only comparable under the same settings.
Extending the context (e.g., RoPE scaling) changes the model itself, so it is not a neutral evaluation trick.
Q62.Why does instruction tuning often degrade the calibration of a base language model?
A pretrained base model is trained with log-loss on real text, which rewards probabilities that match observed frequencies, so it tends to be well calibrated. Instruction tuning and especially RLHF optimize for producing preferred answers rather than accurate likelihoods, which sharpens distributions and typically makes the model overconfident.
Why base models are calibrated:
Cross-entropy is a proper scoring rule: it is minimized only when predicted probabilities equal true frequencies.
The GPT-4 technical report showed the pretrained model's confidence on multiple-choice questions tracked accuracy closely, and post-training reduced this.
What post-training changes:
SFT trains on single "correct" responses, pushing mass onto one answer style regardless of real uncertainty.
RLHF maximizes reward, not likelihood. Reward-optimal policies are mode-seeking, collapse diversity, and drive token probabilities toward 0 or 1.
The KL penalty to the base model limits but does not remove this drift.
Human preference bias: Raters often prefer confident, decisive answers over hedged ones, so the reward model rewards confidence itself.
Mitigations: Temperature scaling on a held-out set, sampling-based confidence (agreement across samples), or asking for verbalized confidence. These are imperfect but better than raw post-RLHF logits.
Q63.What are the leading theories of how in-context learning works internally?
Q64.Why can few-shot prompts with randomly assigned labels still perform surprisingly well?
Q65.Are raw next-token softmax probabilities calibrated confidence measures?
softmax probabilities calibrated confidence measures?Q66.A model answers confidently but incorrectly about rare or long-tail entities. What causes this from the pretraining side?
Q67.How could you estimate a model's uncertainty about a generated answer using its token probabilities or multiple samples?
Q68.How do data mixture ratios between natural language, math and code affect downstream capabilities?
Q69.How does pretraining on synthetic data risk model collapse?
Q70.What is the curse of multilinguality in language model pretraining?
Q71.What intrinsic model properties limit an LLM's effective context length?
Q72.What is the fundamental difference between the Kaplan and Chinchilla scaling laws?
Q73.Why do labs deliberately over-train smaller models past the Chinchilla-optimal point?
Q74.Why do some researchers argue that emergent abilities are an artefact of non-linear evaluation metrics?
Q75.Where does the factor of 6 come from in the 6ND training compute approximation?
6ND training compute approximation?