Interview Study Guide

Guide / AI engineering Fundamentals

Transformer internals, KV cache and quantization

Attention, why the KV cache dominates memory, the memory math for weights and cache, GQA, FlashAttention, quantization (INT8/INT4, GPTQ, AWQ) and context length trade-offs.

Created · Updated · 7 min read

Senior AI rounds ask “why is this slow or expensive” and expect numbers. This page gives the mechanics and the arithmetic.

Fundamentals#

T.1 The transformer in one page#

Text → tokens → embeddings (vectors) + positional information → N stacked blocks. Each block: self-attention (each token mixes information from earlier tokens) then a feed-forward network (MLP), each wrapped with residual connections and normalisation. The final vector is projected to a distribution over the vocabulary; the next token is sampled (LLM fundamentals). Decoder-only models (GPT, Llama, Claude-style) use causal masking: a token attends only to earlier tokens.

Attention: for each token compute a query (Q), key (K) and value (V) vector. The score between tokens is softmax(Q·Kᵀ / √d); the output is the weighted sum of V. Multi-head attention runs several of these in parallel with different projections. Cost: attention compute grows quadratically with sequence length (n²), which is why long context is expensive.

Variants you should name:

VariantIdeaEffect
MQA / GQA (multi-query / grouped-query attention)Many query heads share fewer K/V headsShrinks the KV cache 4–8×, nearly the same quality: standard in modern models
FlashAttentionComputes attention in tiles inside fast on-chip memory, avoiding the n×n matrix in HBMSame result, much faster, less memory
Sliding-window / sparse attentionAttend to a local window plus some global tokensLinear-ish cost, long context
MoE (mixture of experts)Router sends each token to a few expert MLPsMany total parameters but few active per token: cheaper per token, but all experts must sit in memory
RoPE and long-context scalingRotary position embeddings, extended with scaling tricksEnables longer windows; quality at the far end can still degrade

T.2 Prefill vs decode#

  • Prefill: process the whole prompt in parallel (compute-bound). Determines time to first token (TTFT).
  • Decode: generate one token at a time, each step reading all weights and the KV cache from GPU memory (memory-bandwidth-bound). Determines tokens per second.

Because decode is bandwidth-bound, an upper bound on single-stream speed is memory bandwidth ÷ bytes read per token. An H100 with ~3.35 TB/s reading a 16 GB model gives roughly 200 tokens/s for one sequence; batching many sequences amortises the weight reads, which is why throughput rises with batch size until compute or KV memory limits.

T.3 The KV cache and its memory math#

Without a cache, each new token would recompute K and V for all previous tokens. The KV cache stores them, trading memory for compute.

KV bytes per token = 2 (K and V) × layers × kv_heads × head_dim × bytes per element

Model (example config)LayersKV headsHead dimfp16 KV per tokenAt 8K tokensAt 128K tokens
~8B with GQA3281282×32×8×128×2 B = 128 KB1 GB16 GB
~70B with GQA8081282×80×8×128×2 B = 320 KB2.6 GB41 GB

Capacity planning: a 70B model in fp16 needs ~140 GB for weights. Serving 100 concurrent 8K-token conversations needs another 100 × 2.6 GB ≈ 260 GB of KV cache, more than the weights. KV cache, not weights, often limits concurrency. Levers: GQA, quantised KV cache (FP8/INT8), paged allocation (vLLM PagedAttention), prefix caching, shorter context, eviction of idle sessions, and offloading to CPU memory.

T.4 Weights and quantization#

weight memory ≈ parameters × bytes per parameter: 7–8B model: ~16 GB (fp16/bf16), ~8 GB (INT8), ~4–5 GB (INT4). 70B: 140 GB / 70 GB / ~35–40 GB.

MethodWhatNotes
bf16/fp1616-bit floatsBaseline for serving and training
FP88-bit float on recent GPUsNear-lossless, ~2× throughput on supporting hardware
INT8 (LLM.int8, SmoothQuant)8-bit integers, handling activation outliersSmall quality loss
INT4: GPTQ, AWQPost-training weight-only quantization, 4-bit4× smaller; AWQ protects the most important weights; quality drop small but real on reasoning, code and long context
GGUF / llama.cppCPU/edge-friendly formats with many bit widthsLocal deployment
QLoRA4-bit base model + LoRA adapters for fine-tuningFine-tune large models on one GPU (Model adaptation)

Always evaluate the quantised model on your own eval set; benchmark averages hide task-specific regressions (Evals). Weight-only quantization speeds decode (less to read); activation quantization also speeds compute.

T.5 Context length trade-offs#

Longer context costs quadratic attention compute at prefill, linear KV memory and per-token read cost during decode, higher latency and money, and “lost in the middle” (models use information at the start and end better than the middle). Use retrieval and summarisation instead of stuffing everything (RAG); order important content at the edges; measure with needle-in-haystack and task-specific tests.

T.6 Training concepts to recognise#

Pre-training (next-token prediction on trillions of tokens), supervised fine-tuning (instruction following), preference tuning (RLHF, DPO), scaling laws (loss falls predictably with compute, data, parameters; Chinchilla: roughly 20 tokens per parameter for compute-optimal training), distributed training (data, tensor, pipeline parallelism, ZeRO/FSDP), mixed precision, gradient checkpointing.

Most asked questions#

1. What is attention and why is it quadratic? Every token’s query is compared with every earlier token’s key; n tokens → n² comparisons; FlashAttention reduces memory traffic, not the asymptotic compute.

2. What is the KV cache and why does it matter? Stored keys and values of previous tokens so each decode step computes only the new token; it speeds generation but consumes memory proportional to tokens × layers × KV heads.

3. Prefill vs decode? Prefill: parallel prompt processing, compute-bound, sets TTFT. Decode: sequential, memory-bandwidth-bound, sets tokens/s.

4. Why do GQA and MQA exist? To shrink the KV cache and bandwidth with little quality loss.

5. What is quantization and its trade-off? Lower-precision weights (or KV) for memory and speed, at some accuracy risk; validate on your tasks.

6. Dense vs MoE? Dense uses all parameters per token; MoE activates a few experts, giving big capacity at lower per-token compute but larger memory footprint and routing complexity.

Senior-level questions#

1. “Will a 70B model fit on one 80 GB GPU?” fp16 weights are 140 GB: no. INT4 ≈ 35–40 GB fits the weights, leaving ~40 GB for KV cache; check concurrency and context needs, and quality after quantization; otherwise use tensor parallelism across 2–4 GPUs.

2. “Latency doubled after we raised max context from 8K to 32K.” Longer prompts mean longer prefill and TTFT (quadratic part), bigger KV cache reduces batch size (lower throughput) and each decode step reads more cache. Fix by trimming context, prefix caching, chunked prefill, GQA/quantised KV, and routing short requests to a short-context pool.

3. “Why is throughput much higher with batching?” Weight reads during decode are amortised across the batch (bandwidth-bound), so throughput scales until KV memory or compute saturates; trade-off is per-request latency.

4. “How would you decide between FP8, INT8 and INT4 serving?” Hardware support, quality on a held-out eval, memory needed for concurrency, and cost per million tokens; start FP8/INT8, go INT4 only if the eval holds or memory demands it.

5. “Why can long-context models still miss facts in the middle?” Attention dilution and training distribution; mitigate with retrieval, reranking, structured prompts, and placing key instructions at the start and end.

Quiz#

1. KV cache per token for 32 layers, 8 KV heads, head dim 128, fp16?

2 × 32 × 8 × 128 × 2 bytes = 131,072 bytes = 128 KB per token.

2. Memory for a 13B model in INT4 (weights only)?

About 13B × 0.5 bytes ≈ 6.5 GB (plus overhead for scales).

3. Is decode compute-bound or memory-bound?

Memory-bandwidth-bound: each step reads all weights and the KV cache for a single new token.

4. What does GQA change?

Several query heads share one K/V head, reducing KV cache size and bandwidth.

5. What does FlashAttention change?

It computes exact attention in tiles using on-chip memory, avoiding materialising the full n×n matrix, so it is faster and uses less memory.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes