TensoriumInterview preparation
← Home

Core concepts · 62 topics

A guided path through the ideas behind modern LLMs.

Read the stages in order: how text becomes a prediction, what happens inside the Transformer block, how a model learns, then serving, scale, and post-training. Every topic names what to know first, then gives the intuition, the math with concrete numbers, the common misconception, and a self-check. Already comfortable with the basics? Switch to By area and jump straight to a topic.

New to machine learning? Start here instead.

These topics work best as a refresher; they assume ideas like probability and loss. Begin with three short beginner lessons (tokens, embeddings, next-token prediction), then the visual walkthrough for attention and the Transformer.

Finish line: You can explain how text becomes a prediction and what training does to improve that prediction.

Topic 29 of 62 · Generating and serving

KV cache and head sharing

Medium

Why can decoder attention reuse past keys and values during generation, and how do you size the KV cache?

Why this mattersThe KV cache turns quadratic projection recompute into linear state growth—making memory capacity and HBM bandwidth the central constraints of LLM serving.

1 · Start with the intuition

In a causal Transformer with frozen weights, earlier tokens never attend to later tokens—so appending token t+1 does not change the hidden states, keys, or values of tokens 1…t. Instead of recomputing projections for the entire prefix on every decode step, we store each past token’s key (K) and value (V) vectors in GPU memory (the KV cache). Only the newly generated token needs a query, key, and value projection; its query then attends over the cached K and V.

2 · How the mechanism works

Mechanism step 1 of 3 · no question to answer

Prefill the prompt

Process all prompt tokens in parallel and write their K and V tensors for every layer into the KV cache.

Next, we will look at: Project & append 1 token. Move on when this operation makes sense.

Visualizing the behavior

KV cache for one 4,096-token sequence (32 layers, head dim 128, BF16)

Derived
MHA: 32 KV heads
2 GiB
GQA: 8 KV heads
512 MiB
MQA: 1 KV head
64 MiB
2 (K and V) × 32 layers × 4,096 tokens × H_kv × 128 × 2 bytes. Sharing K/V across query heads cuts the cache in direct proportion to the number of KV heads.

Cache grows linearly with cached tokens

Derived
0163248640326496128cached tokens (×1,024), summed over all active sequencesKV cache (GiB)GQA-8 · 32K tokens = 4 GiB
  • MHA-32 (512 KiB/token)
  • GQA-8 (128 KiB/token)
  • MQA-1 (16 KiB/token)
The x-axis is total cached tokens: one 128K-token request and thirty-two 4K-token requests cost the same. This is what limits concurrency in serving.