PrepStack › AI › NLP & Transformers

NLP & Transformers interview cheat sheet

Tokens, embeddings, attention, BERT vs GPT vs T5, and how LLMs run fast

NLP interviews move from the classic pipeline (tokenisation, TF-IDF, word2vec) to the transformer: self-attention, Q/K/V, why we scale by √d_k, multi-head, positional encodings and the encoder vs decoder split. Senior rounds add efficiency (O(n²) attention, FlashAttention, GQA, KV cache), decoding strategies and evaluation metrics. The small Python demos use only the standard library so you can trace every number by hand. Read the 15-minute revision first, then switch to Quiz mode and answer out loud.

15-minute revision

  1. Classic pipeline: normalise → tokenise → (stop words) → stem or lemmatise → vectorise. Transformers skip stop-word removal and stemming; they use subword tokenisers.
  2. Stemming chops suffixes by rules (studies → studi); lemmatisation uses a dictionary and part of speech to return a real word (better → good).
  3. TF-IDF = term frequency × log(N / document frequency). It boosts words that are frequent in one doc but rare overall. BoW and TF-IDF ignore word order unless you add n-grams.
  4. word2vec: CBOW predicts the centre word from context; skip-gram predicts context from the centre (better for rare words). GloVe factorises global co-occurrence counts. FastText adds character n-grams, so it handles unseen words.
  5. Static embeddings give one vector per word, so bank (river) = bank (money). Contextual embeddings (ELMo, BERT) give a different vector per occurrence.
  6. Subword tokenisers: BPE merges the most frequent pair (GPT, Llama); WordPiece merges the pair with the best likelihood score and marks continuations with ## (BERT); Unigram prunes a big vocab by loss (T5, via SentencePiece).
  7. RNNs are sequential (no parallel training) and suffer vanishing gradients; LSTMs/GRUs help with gates but still squeeze the input into one hidden state. Attention lets every output look at every input.
  8. Scaled dot-product attention: softmax(QKᵀ / √d_k) V. Scale because dot products grow with d_k, which saturates softmax and kills gradients.
  9. Multi-head attention runs h smaller attentions in parallel (d_k = d_model / h) so each head can learn a different relation. Same cost as one big head.
  10. Attention is permutation-invariant, so we add positional information: sinusoidal (original), learned (BERT, GPT-2), RoPE (Llama, rotates Q and K), ALiBi (linear distance bias).
  11. A transformer block = attention + feed-forward, each wrapped in a residual connection and LayerNorm. Modern LLMs use pre-LN (norm before the sublayer) for stable deep training, often with RMSNorm.
  12. Encoder-only (BERT): bidirectional, masked LM, for understanding. Decoder-only (GPT, Llama): causal mask, next-token prediction, for generation. Encoder-decoder (T5, BART): seq2seq tasks like translation.
  13. Attention costs O(n²) time and memory in sequence length. Fixes: FlashAttention (exact, IO-aware tiling), sparse / sliding-window attention, and MQA/GQA (share K/V heads to shrink the KV cache).
  14. KV cache: during generation, store each layer's past keys and values so each new token costs O(n) instead of recomputing the whole prefix. Size = 2 × layers × kv_heads × head_dim × tokens × bytes.
  15. Decoding: greedy, beam search, temperature, top-k, top-p (nucleus). Low temperature = sharper, more deterministic.
  16. Metrics: BLEU (n-gram precision + brevity penalty, translation), ROUGE (n-gram/LCS recall, summarisation), perplexity = exp(mean negative log-likelihood), F1 for NER/classification/extractive QA.

Classic NLP

Text preprocessing: tokens, stop words, stemming & lemmas

Turn raw text into clean, comparable units before counting or embedding them.

  • Normalisation: lowercase, strip accents, expand contractions, handle Unicode (NFKC). Keep case when it carries meaning (NER: Apple vs apple).
  • Tokenisation splits text into units: words, subwords or characters. Word splitting is hard for contractions (isn't), URLs, hashtags, and languages without spaces (Chinese, Japanese).
  • Stop words (the, is, of) are very common and carry little topic signal, so classic search and topic models drop them. Never drop them blindly for sentiment: not flips meaning.
  • Stemming (Porter, Snowball) strips suffixes with rules. It is fast but crude, and the stem may not be a word (studies → studi).
  • Lemmatisation (WordNet, spaCy) uses a vocabulary plus the part of speech to return the dictionary form (ran → run, better → good). Slower but accurate.
  • Modern transformer pipelines do almost none of this: the model's own subword tokeniser handles raw text, and the model learns which words matter.

Interview questions

  • What is the difference between stemming and lemmatisation?
  • Should you always remove stop words?
  • Why is tokenisation harder than splitting on spaces?

Bag-of-words, TF-IDF & n-grams

Represent a document as counts of words, weighted so rare-but-present words matter more.

  • Bag-of-words (BoW): a vector of word counts over a fixed vocabulary. Simple and sparse, but it loses word order and meaning.
  • TF-IDF weights each count: tf(t, d) × idf(t), with idf = log(N / df(t)). Words that appear in every document get weight near 0.
  • scikit-learn's TfidfVectorizer uses a smoothed idf (ln((1 + N) / (1 + df)) + 1) and L2-normalises each row by default, so numbers differ from the textbook formula.
  • n-grams add short word sequences (not good) as features, which brings back some local order. The vocabulary grows quickly, so cap it with min_df / max_features.
  • Similarity between documents is usually cosine similarity of their TF-IDF vectors.
  • Still a strong baseline: TF-IDF + logistic regression is fast, explainable, and hard to beat on small labelled datasets. BM25 is the TF-IDF variant used in search engines.

Interview questions

  • Explain TF-IDF and why it beats raw counts.
  • What are the limits of bag-of-words models?
  • When would you still choose TF-IDF over a transformer?

Core NLP tasks

Know the input, output and typical model family for each common task.

  • Text classification: one label per text (sentiment, spam, intent). Encoder + classification head on the [CLS] or pooled vector.
  • NER / token classification: one label per token, usually in BIO format (B-PER, I-PER, O). Subword tokens need their labels aligned to words.
  • Extractive QA: given a question and a context, predict the start and end positions of the answer span (SQuAD style).
  • Summarisation: extractive (pick sentences) or abstractive (write new text, seq2seq like BART/T5 or an LLM).
  • Machine translation: classic encoder-decoder task; still the reference use case for BLEU.
  • Today a single instruction-tuned LLM can do all of these with a prompt, but small fine-tuned encoders are often cheaper, faster and more accurate for one narrow task.

Interview questions

  • How does NER labelling work with subword tokenisers?
  • How does a BERT model answer an extractive question?
  • Extractive vs abstractive summarisation?

Embeddings & Tokenisation

Word embeddings: word2vec, GloVe, FastText

Dense vectors where words used in similar contexts end up close together.

  • Distributional hypothesis: a word is known by the company it keeps. Embeddings are typically 100–300 dims, versus vocab-sized one-hot vectors.
  • word2vec (Mikolov et al., 2013) is a shallow network. CBOW predicts the centre word from the averaged context; skip-gram predicts each context word from the centre word.
  • Training tricks: negative sampling (score the true pair against a few random words instead of a full softmax) and subsampling of very frequent words.
  • GloVe (Stanford, 2014) fits vectors so that their dot product matches the log of global co-occurrence counts. It mixes count-based and predictive ideas.
  • FastText (Facebook, 2016) represents a word as the sum of its character n-grams (3–6 chars), so it can build vectors for unseen or misspelled words and works well for rich morphology.
  • Famous property: vector arithmetic like king − man + woman ≈ queen. Similarity is measured with cosine similarity.

Interview questions

  • CBOW vs skip-gram?
  • How does GloVe differ from word2vec?
  • Why does FastText handle out-of-vocabulary words?
  • What are the main limitations of static word embeddings?

Contextual embeddings

The vector for a word depends on the sentence it appears in.

  • ELMo (2018) used a bidirectional LSTM language model; a word's vector was a learned mix of its layer outputs, so it changed with context.
  • BERT and other transformers produce one vector per token per layer. bank in 'river bank' and 'bank loan' gets two different vectors.
  • These models are pre-trained on huge unlabelled text, then fine-tuned (or prompted) for a task: this transfer learning is the core shift from 2018 on.
  • Different layers capture different things: lower layers lean towards syntax, upper layers towards task-specific meaning.
  • To get one vector for a whole sentence you pool token vectors (mean pooling or [CLS]), but raw BERT pooling is weak for similarity; use a model trained for sentence embeddings.

Interview questions

  • What is a contextual embedding and why does it matter?
  • How did ELMo differ from BERT?
  • Can you use BERT's [CLS] vector directly for semantic search?

Subword tokenisation: BPE, WordPiece, Unigram

Split rare words into frequent pieces so the vocabulary stays small and nothing is unknown.

  • Word-level vocabularies explode and still hit unknown words; character-level sequences get too long. Subwords sit in between: common words stay whole, rare words split (annoyingly → annoying + ly).
  • BPE: start from characters, count adjacent pairs, merge the most frequent pair, repeat until the target vocab size. Encoding replays the learned merges in order. Used by GPT-2/3/4, Llama, RoBERTa.
  • Byte-level BPE starts from the 256 byte values, so any string can be encoded with no <unk>. GPT-2's vocab is 50,257 (256 bytes + 50,000 merges + <|endoftext|>).
  • WordPiece (BERT): also merges bottom-up, but picks the pair with the highest freq(ab) / (freq(a) × freq(b)). Continuation pieces start with ## (un ##aff ##able).
  • Unigram (T5, ALBERT, XLNet): start from a large candidate vocab and prune tokens whose removal hurts the corpus likelihood least. It can sample several segmentations (subword regularisation).
  • SentencePiece is a library, not an algorithm: it runs BPE or Unigram on raw text, treating the space as a normal symbol ▁, so it works for languages without spaces and decodes losslessly.

Interview questions

  • Why do transformers use subword tokenisation?
  • BPE vs WordPiece?
  • What is SentencePiece and why use it?
  • How does Unigram differ from BPE?

Sentence embeddings & semantic search

One vector per sentence, trained so cosine similarity matches meaning.

  • Sentence-BERT (2019) fine-tunes BERT in a siamese setup on sentence pairs, then mean-pools token vectors. Comparing 10,000 sentences becomes 10,000 encodes + fast cosine, instead of ~50M cross-encoder passes.
  • Modern models train with contrastive loss using in-batch negatives (e.g. MultipleNegativesRankingLoss): pull matching pairs together, push others apart.
  • Bi-encoder: encode query and document separately, compare vectors. Fast, indexable (vector DB). Cross-encoder: feed both together, output a score. More accurate, too slow for millions of docs, so it is used to re-rank the top-k.
  • Mean pooling must respect the attention mask so padding tokens do not drag the average.
  • Normalise vectors to unit length; then dot product = cosine similarity, which vector indexes (HNSW, IVF) handle efficiently.
  • Pick models from the MTEB leaderboard for your language and task; check dimension, max sequence length and licence.

Interview questions

  • Bi-encoder vs cross-encoder: when to use each?
  • How are sentence-embedding models trained?
  • Design: semantic search over 10M support tickets with low latency.

From RNNs to Attention

RNNs, LSTMs and their limits

Recurrent models read one token at a time, which is slow and forgets long-range context.

  • An RNN updates a hidden state hₜ = f(W·xₜ + U·hₜ₋₁) token by token. The same weights are reused at every step.
  • Vanishing / exploding gradients: back-propagating through many steps multiplies many Jacobians, so gradients shrink or blow up. Long-range dependencies are hard to learn.
  • LSTM adds a cell state and forget, input and output gates; the mostly additive cell update lets gradients flow further. GRU is a simpler 2-gate version.
  • Sequential computation: step t needs step t−1, so you cannot parallelise over the sequence during training. GPUs sit idle.
  • Seq2seq bottleneck: in the classic encoder-decoder RNN the whole source sentence is squeezed into one fixed-size vector, so quality drops on long inputs.
  • Exploding gradients are handled with gradient clipping; vanishing gradients needed architecture changes (gates, then attention).

Interview questions

  • Why did transformers replace RNNs/LSTMs?
  • What is the vanishing gradient problem?
  • How do LSTM gates work at a high level?

The attention mechanism

For each output, compute a weighted average of all inputs, with weights learned from relevance.

  • Introduced for translation by Bahdanau et al. (2014): instead of one fixed context vector, the decoder builds a fresh context at each step from all encoder states.
  • Steps: score each input against the current query, softmax the scores into weights that sum to 1, return the weighted sum of the values.
  • Score functions: additive (Bahdanau, a small MLP) and multiplicative / dot-product (Luong, 2015). Transformers use scaled dot-product because it is just matrix multiplication.
  • Cross-attention: queries from one sequence (decoder), keys/values from another (encoder). Self-attention: Q, K and V all come from the same sequence.
  • Attention weights give a rough, not fully reliable, view of what the model focused on (e.g. word alignment in translation).
  • The 2017 paper 'Attention Is All You Need' dropped recurrence entirely and built the model from attention plus feed-forward layers.

Interview questions

  • Explain attention in simple terms.
  • Self-attention vs cross-attention?
  • Are attention weights a good explanation of a model's decision?

Self-attention: Q, K, V & scaled dot-product

Attention(Q, K, V) = softmax(QKᵀ / √d_k) · V.

  • Each token embedding x is projected three ways: Q = XW_Q, K = XW_K, V = XW_V. These are learned matrices.
  • QKᵀ gives an n × n matrix of scores: how much token i should attend to token j.
  • Why divide by √d_k: if q and k have independent unit-variance components, their dot product has variance d_k. Large scores push softmax into a near one-hot region where gradients are almost zero. Scaling keeps the variance around 1.
  • Softmax is applied row-wise, so each query's weights sum to 1. A mask adds −∞ to forbidden positions (padding, or future tokens in a decoder) before softmax.
  • Output is weights · V: an n × d_v matrix, one context-aware vector per token.
  • All of this is a few matrix multiplies, so it is highly parallel on GPUs. In PyTorch use torch.nn.functional.scaled_dot_product_attention, which picks fused kernels such as FlashAttention.

Interview questions

  • What are Q, K and V?
  • Why do we scale by √d_k?
  • What is the shape of the attention matrix, and what does a mask do?
  • Why use separate W_Q and W_K instead of just X·Xᵀ?

Multi-head attention

Run several smaller attentions in parallel, then concatenate and project.

  • Split d_model into h heads of size d_k = d_model / h. Original transformer: d_model 512, h = 8, d_k = 64.
  • Each head has its own Q/K/V projections, so different heads can learn different patterns: syntax, coreference, nearby tokens, delimiters.
  • Outputs of all heads are concatenated (back to d_model) and passed through an output projection W_O.
  • Cost is about the same as one full-width head, because each head is smaller.
  • Parameters per attention layer: 4 matrices of d_model × d_model (Q, K, V, O) plus biases, i.e. about 4·d_model².
  • Research shows many heads can be pruned after training with little loss, which hints at redundancy; MQA/GQA exploit a related idea for K and V.

Interview questions

  • Why use multiple heads instead of one big attention?
  • How do heads get combined?
  • Does adding more heads always help?

Transformer Architecture

Positional encodings: sinusoidal, learned, RoPE, ALiBi

Attention ignores order, so position must be injected into the embeddings or the scores.

  • Self-attention is permutation-equivariant: shuffle the tokens and the outputs shuffle the same way. Without position info dog bites man = man bites dog.
  • Sinusoidal (original paper): PE(pos, 2i) = sin(pos / 10000^(2i/d)), PE(pos, 2i+1) = cos(...). Added to embeddings, no parameters, and any offset is a linear function of the encoding.
  • Learned absolute (BERT, GPT-2): a trainable vector per position. Simple, but cannot go past the trained max length (512 for BERT, 1024 for GPT-2).
  • Relative schemes encode the distance i − j instead: T5 adds a learned bias per distance bucket to the attention scores.
  • RoPE (rotary, RoFormer 2021): rotate each pair of Q and K dimensions by an angle proportional to position. Then q·k depends only on the relative offset. Used by Llama, Mistral, Qwen, Gemma.
  • ALiBi: add a fixed linear penalty −m·|i − j| to scores (per-head slope). Good length extrapolation; used by BLOOM and MPT. Context extension for RoPE models uses tricks like position interpolation and YaRN.

Interview questions

  • Why do transformers need positional encodings?
  • How does RoPE work and why is it popular?
  • Sinusoidal vs learned absolute positions?

Transformer block: FFN, residuals, LayerNorm, masks

Each layer = attention sublayer + feed-forward sublayer, each with a residual path and normalisation.

  • Feed-forward network (FFN): two linear layers applied to every position independently, expanding to ~4 × d_model (2048 for d_model 512) with a non-linearity (ReLU, GELU). Modern LLMs use SwiGLU variants.
  • FFN layers hold about two-thirds of a transformer's parameters and are often described as key-value memories of facts.
  • Residual connections (x + sublayer(x)) give gradients a direct path through dozens of layers.
  • LayerNorm normalises each token's features (not across the batch). Post-LN (original): LN(x + sublayer(x)). Pre-LN (GPT-2 onwards): x + sublayer(LN(x)), more stable and needs less warm-up.
  • Many LLMs (Llama, Mistral) use RMSNorm: no mean subtraction and no bias, slightly cheaper with similar quality.
  • Causal mask: in a decoder, token i may attend only to positions ≤ i, so training can predict all next tokens in parallel without cheating.

Interview questions

  • What does the feed-forward layer do in a transformer?
  • Pre-LN vs Post-LN?
  • Why are residual connections essential?
  • How does a decoder train on all positions in parallel without seeing the future?

Encoder-only vs decoder-only vs encoder-decoder

BERT understands, GPT generates, T5 maps one sequence to another.

  • Encoder-only (BERT, RoBERTa, DeBERTa): bidirectional self-attention over the full input. Best for classification, NER, extractive QA, embeddings.
  • Decoder-only (GPT, Llama, Mistral, Claude-style LLMs): causal self-attention, trained to predict the next token. Generates text; with scale and instruction tuning it handles almost any task.
  • Encoder-decoder (original Transformer, T5, BART, mT5, Whisper): encoder reads input bidirectionally, decoder generates output with cross-attention to the encoder. Natural for translation and summarisation.
  • BERT-base: 12 layers, hidden 768, 12 heads, ~110M params, WordPiece vocab ~30K, 512 max tokens.
  • T5 casts every task as text-to-text (translate English to German: ..., summarize: ...).
  • Most frontier LLMs are decoder-only: one simple objective, easy to scale, and a single model can do both understanding and generation via prompting.

Interview questions

  • BERT vs GPT: what is the core difference?
  • When would you choose an encoder-decoder model?
  • Why are most modern LLMs decoder-only?
  • You need a fast sentiment classifier for 50M reviews a day. Which architecture?

Masked LM vs causal LM & fine-tuning

MLM fills in blanks using both sides; CLM predicts the next token from the left side only.

  • Masked LM (BERT): pick 15% of tokens; of those, 80% become [MASK], 10% a random token, 10% unchanged. Predict the originals. Only the masked positions give loss.
  • BERT also used Next Sentence Prediction; RoBERTa showed it was unnecessary and dropped it (and used dynamic masking and more data).
  • Causal LM (GPT): maximise Σ log P(xₜ | x₍<t₎). Every position gives a loss, so it is sample-efficient, and the model can generate.
  • Span corruption (T5): replace random spans with sentinel tokens (<extra_id_0>) and have the decoder output the missing spans. BART denoises with shuffling, deletion and infilling.
  • ELECTRA trains a discriminator to spot replaced tokens, learning from every position instead of 15%.
  • After pre-training: fine-tuning (full, or parameter-efficient like LoRA), instruction tuning (SFT on prompt-response pairs) and preference tuning (RLHF, DPO) for chat models.

Interview questions

  • Why does BERT replace only 80% of selected tokens with [MASK]?
  • Masked LM vs causal LM: trade-offs?
  • What is teacher forcing and exposure bias?
  • Full fine-tuning vs LoRA?

Efficiency & Inference

Attention complexity & efficient attention

Full attention is O(n²) in sequence length; fix memory traffic, skip pairs, or share K/V heads.

  • Score matrix is n × n per head per layer: O(n²·d) compute and O(n²) memory if materialised. Doubling context quadruples that part.
  • FlashAttention (Dao et al., 2022): computes exact attention in tiles that fit in fast on-chip SRAM, with an online softmax, so the n × n matrix is never written to GPU memory (HBM). Memory becomes O(n); FLOPs stay O(n²) but wall-clock drops a lot. FlashAttention-2 and -3 improve GPU utilisation.
  • Sparse attention: each token attends to a subset. Longformer: sliding window + a few global tokens. BigBird: window + global + random. Gives O(n·w).
  • Sliding-window attention (Mistral 7B, window 4096): each layer sees w tokens back, but stacking L layers gives a receptive field of about L × w.
  • MQA (multi-query): all query heads share one K/V head. GQA (grouped-query): groups of query heads share K/V heads (Llama 2 70B, Llama 3, Mistral). Cuts the KV cache and memory bandwidth with little quality loss.
  • Other ideas: linear attention / kernel methods (approximate), state-space models like Mamba (linear time), and PagedAttention (vLLM) for KV memory management.

Interview questions

  • What is the complexity of self-attention and why is it a problem?
  • How does FlashAttention speed things up if it is still exact?
  • Explain MQA vs GQA.
  • How do sparse and sliding-window attention reduce cost?

KV cache & inference

Store past keys and values so each new token only computes its own Q, K, V.

  • Autoregressive generation runs one forward pass per new token. Without caching, step t recomputes K and V for all t previous tokens: O(n²) total projections, O(n³) attention.
  • With a KV cache, each layer appends the new token's K and V to a buffer; the new query attends over the cached keys. Each step is O(n) attention.
  • Two phases: prefill processes the whole prompt in parallel (compute-bound) and fills the cache; decode generates one token at a time (memory-bandwidth-bound).
  • Size = 2 × layers × kv_heads × head_dim × seq_len × batch × bytes. It often exceeds the weights for long contexts or big batches.
  • Shrink it with GQA/MQA, quantised KV (FP8/INT8), sliding windows, and PagedAttention (vLLM), which stores the cache in fixed-size blocks to avoid fragmentation and share prompt prefixes.
  • Serving engines (vLLM, TGI, TensorRT-LLM) add continuous batching and prefix caching; speculative decoding uses a small draft model to propose tokens the big model verifies in one pass.

Interview questions

  • What is the KV cache and why does it help?
  • How do you estimate KV cache memory?
  • Prefill vs decode: why do they behave differently?
  • How would you cut LLM serving cost and latency?

Decoding strategies: greedy, beam, temperature, top-k, top-p

How you pick the next token from the model's probability distribution.

  • Greedy: always pick the most likely token. Deterministic and fast, but repetitive and can miss better sequences.
  • Beam search: keep the best b partial sequences by total log-probability. Good for translation and summarisation; tends to be bland and repetitive for open-ended text.
  • Temperature divides logits by T before softmax: T < 1 sharpens (more deterministic), T > 1 flattens (more random). T → 0 approaches greedy.
  • Top-k: sample only from the k most likely tokens. Top-p (nucleus): sample from the smallest set whose cumulative probability ≥ p, so the set size adapts to the model's confidence.
  • Repetition / frequency penalties down-weight tokens already generated. Stop sequences and max_new_tokens bound the output.
  • Constrained decoding (JSON schema, grammars) masks invalid tokens at each step to guarantee structured output.

Interview questions

  • Top-k vs top-p sampling?
  • What does temperature do mathematically?
  • When is beam search a bad idea?

Practice: Hugging Face & Evaluation

Hugging Face basics: pipeline, tokenizer, model

pipeline() for one-liners; AutoTokenizer + AutoModel... for control.

  • pipeline(task, model=...) bundles tokenizer, model and post-processing. Tasks include text-classification, token-classification (ner), question-answering, summarization, translation, text-generation, fill-mask, feature-extraction.
  • AutoTokenizer.from_pretrained(name) loads the matching tokenizer (fast Rust version by default). Calling it returns input_ids, attention_mask and, for BERT, token_type_ids.
  • AutoModel gives hidden states; task classes add heads: AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelForQuestionAnswering, AutoModelForCausalLM, AutoModelForSeq2SeqLM.
  • Use padding=True, truncation=True, return_tensors="pt" for batches. Models output logits; apply softmax or argmax yourself.
  • Inference: model.eval() and torch.no_grad() (or torch.inference_mode()). For big models, device_map="auto" (needs accelerate) spreads weights over available devices.
  • Fine-tuning: the Trainer API, or TRL's SFTTrainer for LLMs, plus peft for LoRA. Recent Transformers releases (v5) are PyTorch-first.

Interview questions

  • What does pipeline() do under the hood?
  • What is the attention_mask?
  • AutoModel vs AutoModelForSequenceClassification?

Evaluation: BLEU, ROUGE, perplexity, F1

Match the metric to the task, and back automatic scores with human or model-based evaluation.

  • BLEU (translation): modified n-gram precision for n = 1..4 (counts clipped by the reference), geometric mean, times a brevity penalty for short outputs. Corpus-level; use sacreBLEU for comparable numbers.
  • ROUGE (summarisation): recall-oriented overlap. ROUGE-1/2 = unigram/bigram overlap; ROUGE-L = longest common subsequence. Usually reported as F1.
  • Perplexity = exp(average negative log-likelihood per token). Lower is better; 'as confused as choosing among PPL equally likely tokens'. Only comparable between models with the same tokenizer.
  • F1 = harmonic mean of precision and recall. NER uses entity-level F1 (seqeval); extractive QA uses exact match + token-overlap F1; classification uses macro/micro F1 for imbalance.
  • Overlap metrics miss paraphrases. Embedding-based (BERTScore), learned (COMET for MT) and LLM-as-a-judge scores correlate better with humans.
  • For LLMs, also use task benchmarks (MMLU, GSM8K, HumanEval) and your own eval set from real traffic.

Interview questions

  • BLEU vs ROUGE?
  • What is perplexity and what are its limits?
  • How is NER evaluated?
  • How would you evaluate an LLM-powered summariser before launch?