LLM Internals and Architecture Interview Questions
Short answers to 16 llm internals and architecture interview questions.
Questions and answers (16)
Answers are written in plain English and reviewed for technical accuracy. Each answer states the point first, then the reason.
1. Explain scaled dot-product attention and why the 1/sqrt(d_k) scaling factor matters.
Scaled dot-product attention computes softmax(Q K^T / sqrt(d_k)) V for each query. The 1/sqrt(d_k) factor keeps the dot products small as the key dimension grows. Without it, large logits push softmax into a flat or saturated region, and gradients become very small. With d_k = 64, the raw dot product has variance near 64, so the scale divides the spread by 8.
2. What is the KV cache, and what are its memory implications at scale? Derive the formula.
The KV cache stores the key and value tensors of past tokens so the model does not recompute them at each step. Its size is 2 * layers * heads * head_dim * seq_len * batch * bytes_per_value. For a 7B model with 32 layers, 32 heads, head_dim 128, fp16, and 4096 tokens, one sequence needs about 2 GB. Memory grows linearly with context length and batch size, so long contexts limit throughput.
3. What are Multi-Query Attention (MQA) and Grouped-Query Attention (GQA), and what do they trade away?
MQA uses one key and value head for all query heads, and GQA uses a small group of key and value heads. Both shrink the KV cache and the memory traffic during decoding. The tradeoff is less capacity in the key and value projections, which can lower quality. GQA with 8 groups often keeps quality close to full multi-head attention.
4. What is Multi-head Latent Attention (MLA) and why did DeepSeek introduce it?
MLA compresses keys and values into a low-rank latent vector and caches that latent instead of full tensors. DeepSeek introduced it to cut KV cache memory while keeping quality near full multi-head attention. The model projects the latent back to keys and values at run time. This lowers memory per token and allows longer contexts at a given budget.
5. Explain FlashAttention. It does not reduce FLOPs, so why is it faster?
FlashAttention tiles the attention computation and keeps intermediate blocks in fast on-chip memory. It does not reduce FLOPs, but it cuts slow reads and writes to high-bandwidth memory. It also avoids storing the full attention matrix, so memory use drops from quadratic to linear in sequence length. The result is faster wall-clock time on long sequences.
6. How does Byte Pair Encoding work, and what are its failure modes (numbers, code, non-Latin scripts)?
Byte Pair Encoding starts from single bytes. It repeatedly merges the most frequent adjacent pair into a new token. It fails when a number splits into odd pieces. So 12345 can become several tokens and arithmetic gets harder. Non-Latin scripts often need more tokens per character because the merge table favors common training text. A tokenizer trained mostly on English can use 2 to 4 times more tokens for other scripts.
7. What is positional encoding in transformers, and how has it evolved (sinusoidal → learned → RoPE → ALiBi)?
Positional encoding gives the model order information because attention alone is permutation invariant. Sinusoidal encoding used fixed waves, and learned encoding trained a vector per position. RoPE rotates query and key vectors by an angle that depends on position, and ALiBi adds a distance-based bias to attention scores. RoPE now dominates because it supports relative positions and context extension.
8. Explain RoPE and how position interpolation / YaRN extend context beyond the trained length.
RoPE rotates each query and key pair by an angle proportional to position, so the dot product depends on relative distance. Position interpolation scales positions down to fit the trained range, and YaRN adds frequency scaling with a temperature term. These methods extend context without full retraining, but quality can drop far beyond the trained length. A common setup trains at 4k tokens and extends to 32k with tuning.
9. What do the Chinchilla scaling laws say, and how do they differ from earlier scaling intuitions?
The Chinchilla laws say that model size and training tokens must grow together. For a fixed compute budget, the best loss comes from a near-equal split. Earlier work scaled model size much faster than data. Chinchilla found that about 20 tokens per parameter is close to optimal.
10. What is a mixture-of-experts architecture and how does it scale capacity without scaling FLOPs?
A mixture-of-experts model has many expert subnetworks and a router that sends each token to a few of them. Only the selected experts run, so FLOPs per token stay small while total parameters grow. The tradeoff is memory, because all experts must sit in memory. A common setup uses 8 experts and activates 2 per token.
11. Explain the difference between pre-training, supervised fine-tuning and preference optimisation.
Pre-training learns general language patterns from raw text with next-token prediction. Supervised fine-tuning then teaches the model to follow instructions using labelled input and output pairs. Preference optimisation goes further and aligns outputs with human or model preferences. It uses pairs of better and worse answers, often with a reward model.
12. Compare greedy, beam search, top-k, top-p and temperature sampling. When does each fail?
Greedy decoding picks the top token at each step and beam search keeps several partial sequences. Top-k and top-p cut the tail of the probability distribution, and temperature rescales the logits. Greedy and beam search fail by repeating text or missing variety. Top-k fails when the true next token sits outside the fixed k set. Top-p fails when one token already holds most of the mass. High temperature fails by adding noise and low temperature fails by removing diversity.
13. What is the lost-in-the-middle problem in long contexts and how do you address it?
Models often recall facts at the start and end of a long context better than facts in the middle. This is the lost-in-the-middle problem. Place key information near the start or end of the prompt. Rerank retrieved chunks so the most relevant ones sit at the edges. Keep contexts short when you can.
14. Why is LayerNorm placed pre-block in modern transformers, and what is RMSNorm?
Pre-block LayerNorm keeps the residual stream clean and makes deep training more stable. The block reads a normalised copy, and the raw signal passes through the skip path. RMSNorm is a cheaper variant that divides by the root mean square and skips mean centering. It uses fewer operations and works as well in most large models.
15. Explain SwiGLU and why gated activations replaced ReLU/GELU in modern LLM MLP blocks.
SwiGLU is a gated MLP that multiplies a Swish-activated branch by a linear branch. The gate lets the network control how much signal passes. This gives better quality at the same parameter count than ReLU or GELU. The cost is one extra weight matrix, so the hidden size is often scaled down to keep FLOPs equal.
16. Walk me through what happens, tensor by tensor, in one forward pass of a decoder-only transformer.
The tokenizer turns text into token IDs, and an embedding table maps each ID to a vector. Each block applies RMSNorm, then attention with a KV cache, then a residual add. A second RMSNorm and the SwiGLU MLP follow, with another residual add. A final norm and the output matrix produce logits over the vocabulary.
x = embed[ids] # [B, T, D]
for block in blocks:
x = x + attn(norm(x))
x = x + mlp(norm(x))
logits = out(norm(x)) # [B, T, V]