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.
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:
| Variant | Idea | Effect |
|---|---|---|
| MQA / GQA (multi-query / grouped-query attention) | Many query heads share fewer K/V heads | Shrinks the KV cache 4–8×, nearly the same quality: standard in modern models |
| FlashAttention | Computes attention in tiles inside fast on-chip memory, avoiding the n×n matrix in HBM | Same result, much faster, less memory |
| Sliding-window / sparse attention | Attend to a local window plus some global tokens | Linear-ish cost, long context |
| MoE (mixture of experts) | Router sends each token to a few expert MLPs | Many total parameters but few active per token: cheaper per token, but all experts must sit in memory |
| RoPE and long-context scaling | Rotary position embeddings, extended with scaling tricks | Enables 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) | Layers | KV heads | Head dim | fp16 KV per token | At 8K tokens | At 128K tokens |
|---|---|---|---|---|---|---|
| ~8B with GQA | 32 | 8 | 128 | 2×32×8×128×2 B = 128 KB | 1 GB | 16 GB |
| ~70B with GQA | 80 | 8 | 128 | 2×80×8×128×2 B = 320 KB | 2.6 GB | 41 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.
| Method | What | Notes |
|---|---|---|
| bf16/fp16 | 16-bit floats | Baseline for serving and training |
| FP8 | 8-bit float on recent GPUs | Near-lossless, ~2× throughput on supporting hardware |
| INT8 (LLM.int8, SmoothQuant) | 8-bit integers, handling activation outliers | Small quality loss |
| INT4: GPTQ, AWQ | Post-training weight-only quantization, 4-bit | 4× smaller; AWQ protects the most important weights; quality drop small but real on reasoning, code and long context |
| GGUF / llama.cpp | CPU/edge-friendly formats with many bit widths | Local deployment |
| QLoRA | 4-bit base model + LoRA adapters for fine-tuning | Fine-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.