AI Agentic Handbook
Foundations

Attention

Mid levelReviewed Oct 2026In 4 interview questionsIn 1 post

How a model works out which earlier words matter for the word it is writing right now.

In plain English

Attention is the part of a language model that decides which earlier words matter for the one it is working on. In 'The lease renews unless it ends', attention lets 'it' link strongly to 'lease', so the model knows what is actually being discussed.

Every Token looks back over the others and takes a weighted blend of what they carry — bigger weights on the ones that matter. That is the whole idea. Stack that trick enough times and you get the models we have today.

Analogy

Reading with a highlighter: for each word, you highlight the earlier words that help it make sense.

Common pitfall

Attention weights look like an explanation of the answer, and it is very tempting to read them that way. They show where information flowed in one head of one layer — not the model's reasons.

How it actually works

Each token is projected into query (Q), key (K) and value (V) vectors. Scores are QKᵀ / √d_k, a causal mask blanks future positions, softmax turns each row into weights summing to 1, and the weights mix the V vectors. Multi-head attention runs this in parallel with different projections.

Compute is quadratic in sequence length (an n × n score matrix per head per layer), but at serving time memory dominates: the KV cache stores K and V for every past token, 2 × layers × kv_heads × head_dim × bytes per token. Grouped-query attention (GQA) shares K/V across query heads: Llama-3.1-70B has 64 query heads but 8 KV heads, an 8× smaller cache. FlashAttention computes exact attention in tiles without materialising the n × n matrix, cutting memory traffic. RoPE and its scaling variants decide how well attention generalises to long contexts. The same mechanism, without the causal mask, powers encoders and cross-encoders.

What I'd ship on day one

Serve GQA models on vLLM or SGLang with FlashAttention kernels, paged KV, FP8 KV cache where quality holds on your evals, prefix caching on, and max_model_len set to the p99 real context rather than the model maximum.

Worked example

Llama-3.1-8B: 32 layers × 8 KV heads × 128 dims × 2 (K and V) × 2 bytes = 128 KB per token. A 32k-token code-review prompt needs 4 GB of KV; 32 concurrent users at 8k each need 32 GB, twice the 16 GB of weights. That memory, not FLOPs, caps how many long requests one 80 GB GPU can serve.

In the interview

Good news: staff rounds rarely ask for the derivation. They test the consequences, so commit to those — long context is a KV-memory problem at serving time, GQA and FP8 KV are the first levers you reach for, prefix caching works because the K/V for a shared prefix are identical, and position affects recall. Expect 'how many concurrent 32k users fit on one H100 with an 8B model?' and work it out from bytes per token, out loud. They want to watch the estimate, not grade the digits.

Theleaserenewsunlessitends
The1.00·····
lease0.350.65····
renews0.100.600.30···
unless0.050.250.450.25··
it0.040.700.100.060.10·
ends0.030.300.200.270.120.08
One head, causal mask: each row sums to 1 over earlier tokens. 'it' puts 0.70 on 'lease'. Illustrative weights.
8B, 1 user × 32k
20 GB
8B, 32 users × 8k
48 GB
70B FP8, 1 user × 128k
110 GB
Weights (BF16)KV cache

Numbers worth knowing

KV bytes per token
2 × layers × kv_heads × head_dim × bytesLlama-3.1-8B BF16 = 128 KB; Llama-3.1-70B BF16 = 320 KB
GQA saving
8×Llama-3.1-70B: 64 query heads share 8 KV heads
Attention compute
O(n²) per layerdoubling the prompt quadruples score-matrix work in prefill

How to decide

WhenDo this
Serving long contexts to many usersPick a GQA model, enable FP8 KV and paged attention; cap per-tier context.
Many requests share a long prefixEnable prefix caching so K/V for the prefix are computed once.
Need to explain why the model answered somethingUse citations and ablations, not attention maps.

Cost maths

Concurrency = free KV memory ÷ (bytes per token × context). One H100 80 GB, Llama-3.1-8B BF16: 16 GB weights, ~56 GB usable for KV at 0.9 utilisation ≈ 440k tokens ≈ 53 users at 8k context, or 13 at 32k. At an assumed $2.50/GPU-hour (illustrative), that is ~$0.05 per 8k-user-hour versus ~$0.19 per 32k-user-hour: price long-context tiers accordingly.

Operating it

Time to scale up when…
  • KV usage above 85% at p95
  • Scheduler preemptions above 1% of requests
  • Inter-token latency p95 doubles as average context grows
What to monitor
  • KV cache usage p95: alert above 85%
  • Preemptions per minute: alert above 1% of requests
  • Inter-token latency p95 by context bucket: alert on 2× baseline

When it goes wrong

What users saw

Throughput on a code-search assistant fell 70% the day 'whole repository' mode launched; short requests timed out.

How it was caught

vLLM KV-usage gauge pinned at 100% and the preemption counter climbing.

Root cause

max_model_len was raised from 16k to 128k for everyone; a handful of 100k-token sessions held most of the KV cache and evicted dozens of short ones.

Fix

Separate long-context pool with its own quota, FP8 KV, and per-tier context caps at the gateway.

Sources

  1. Attention Is All You Need — Vaswani et al., 2017paper
  2. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — Dao et al., 2022paper
  3. GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints — Ainslie et al., 2023paper

Check yourself

Three questions. Every option is explained once you answer.

1ConceptLlama-3.1-70B has 64 query heads but only 8 KV heads. What does grouped-query attention buy at serving time?
2ScenarioAfter raising max_model_len from 16k to 128k for all users, a few 100k-token sessions evict dozens of short ones and throughput drops 70%. What fixes it?
3CalculationOne H100 serves Llama-3.1-8B in BF16 with about 440k tokens of KV capacity left after the 16 GB of weights. How many concurrent users at 32k context fit?