KV Cache, RoPE, and Nucleus Sampling with Temperature
Machine LearningModel answerLast updated
Explain why decoder-only transformers use a KV cache and rotary embeddings, then implement a temperature-scaled nucleus (top-p) sampler over next-token logits.
Background
A decoder-only language model produces text one token at a time. To work on inference systems for such models, you need to understand both how the model reuses past computation and how the next token is picked from the output scores.
Part 1: Short conceptual answers
- KV cache. Explain why a key/value cache is needed during token-by-token generation. Give the asymptotic memory cost per request in terms of context length
L, model widthd_model, layer countn_layersand batch sizeB. Then describe how Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) change that cost relative to standard Multi-Head Attention (MHA). - Rotary position embeddings (RoPE). Explain how RoPE makes attention aware of relative positions, even though no absolute position vector is added to the token embeddings.
Part 2: Implement a nucleus sampler
Write sample_top_p, which receives the logits for the next token and returns one sampled token index.
Inputs:
logits: a 1D NumPy array (or PyTorch tensor) of shape(vocab_size,)with unnormalized scores.temperature: a float> 0. Smaller values sharpen the distribution, larger values flatten it.top_p: a float in(0, 1], the cumulative probability threshold.
Steps the function should follow:
- Divide the logits by
temperature. - Turn them into probabilities with a numerically stable softmax.
- Order tokens by probability, highest first, and keep the smallest group whose cumulative probability reaches at least
top_p. At least one token must always be kept. - Discard every token outside that group.
- Renormalize the survivors so they sum to 1.
- Draw one token from the renormalized distribution and return its original vocabulary index.
import numpy as np
def sample_top_p(logits: np.ndarray, temperature: float = 1.0, top_p: float = 0.9) -> int:
pass
Example
logits = np.array([2.0, 1.0, 0.1, -1.0])
token = sample_top_p(logits, temperature=1.0, top_p=0.75)
# The softmax is roughly [0.638, 0.235, 0.095, 0.032].
# Cumulative sums: [0.638, 0.873, 0.968, 1.0].
# The threshold 0.75 is first reached at the second token,
# so the nucleus is {0, 1}, renormalized to about [0.731, 0.269].
# The result is therefore 0 or 1.
Discuss the complexity of your implementation and the edge cases you handle.
Hints
Hint 1
Keys and values of earlier tokens never change under causal masking, so think about what you can store instead of recompute. Then count the bytes: two tensors (K and V), per layer, per token, per sequence.
Hint 2
For GQA and MQA, express d_model as n_heads * d_head and ask how many distinct K/V heads must be stored. For RoPE, think of rotating 2D pairs of features by an angle proportional to position, and look at what a dot product of two rotated vectors depends on.
Hint 3
For the sampler, subtract the maximum logit before exponentiating, sort descending, take a cumulative sum, and find the first index where it reaches top_p using a search. Keep that index plus one tokens, clamp the cutoff to the valid range, and map the sampled position back through the sort order.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Conceptual answers
Why a KV cache
With causal masking, the keys and values of earlier positions depend only on tokens at or before them, so they never change as generation continues. Recomputing them at every step is pure waste.
- Without a cache: step
tre-projects K and V for the whole prefix, costing about O(t·d²) per layer. OverLsteps that is O(L²·d²), mostly redundant. - With a cache: step
tprojects only the new token (O(d²)) and attends over stored keys (O(t·d)).
The trade is compute for memory. Decode steps become memory-bandwidth bound, since each step must stream the weights and the whole cache from HBM. That is why cache size drives throughput and batch capacity.
Cache size
Per layer, per token, per sequence we store one K and one V vector:
KV bytes = 2 · n_layers · B · L · d_model · bytes_per_element
Asymptotically O(n_layers · B · L · d_model): linear in context and batch. At long contexts it can exceed the weight memory.
MHA vs GQA vs MQA
Let d_model = n_heads · d_head and let n_kv be the number of K/V heads.
| Variant | K/V heads | Per-token, per-layer cache |
|---|---|---|
| MHA | n_heads | 2 · n_heads · d_head |
| GQA | n_kv (query heads grouped) | 2 · n_kv · d_head |
| MQA | 1 | 2 · d_head |
GQA divides the cache by n_heads / n_kv; MQA divides it by n_heads. Example: 32 layers, 32 query heads, 8 KV heads, d_head = 128, fp16. GQA needs 2·32·8·128·2 B = 128 KB per token (512 KB with MHA). At 32k tokens that is about 4 GB versus 16 GB per sequence. MQA saves the most but can hurt quality and complicates tensor parallelism, so GQA is the usual compromise.
RoPE
RoPE injects position inside attention rather than at the input. After the Q and K projections in each layer:
- Split each head vector into
d_head/2two-dimensional pairs. - Rotate pair
iat positionmby anglem·θ_i, withθ_i = base^(-2i/d_head)(base typically 10000).
Because rotations are orthogonal,
⟨R(mθ) q, R(nθ) k⟩ = ⟨q, R((n−m)θ) k⟩
so the score depends on the content and only on the offset n − m. Further points:
- Values are not rotated.
- Different frequencies give multi-scale position signals and a mild long-range decay.
- Keys are rotated once at their own position and cached in rotated form, so RoPE works well with the KV cache.
- Context extension methods (position interpolation, NTK scaling, YaRN) work by rescaling the frequencies.
Part 2: Nucleus sampling
Approach
- Subtract the max logit, divide by temperature, exponentiate and normalize (stable softmax).
- Sort probabilities descending and take the cumulative sum.
- Find the first index where the cumulative sum is >=
top_p; keep that many tokens plus the crossing token. - Renormalize the kept mass and sample.
- Map the sampled position back to the vocabulary index via the sort order.
Sorting descending guarantees that any prefix of length k has the largest possible mass among all k-token sets, so the first qualifying prefix is the smallest nucleus.
Note on the example: the true softmax is about [0.638, 0.235, 0.095, 0.032]. The nucleus {0, 1} and the renormalized [0.731, 0.269] are the same either way.
Code
import numpy as np
def sample_top_p(logits, temperature: float = 1.0, top_p: float = 0.9) -> int:
if hasattr(logits, "detach"):
logits = logits.detach().cpu().numpy()
logits = np.asarray(logits, dtype=np.float64).ravel()
if logits.size == 0:
raise ValueError("logits must be non-empty")
if not temperature > 0.0:
raise ValueError("temperature must be > 0")
if not (0.0 < top_p <= 1.0):
raise ValueError("top_p must be in (0, 1]")
if np.isnan(logits).any() or not np.isfinite(logits).any():
raise ValueError("need at least one finite logit and no NaNs")
if temperature < 1e-6: # effectively greedy
return int(np.argmax(logits))
shifted = (logits - logits.max()) / temperature
exp = np.exp(shifted)
probs = exp / exp.sum()
order = np.argsort(-probs, kind="stable")
sorted_probs = probs[order]
cumsum = np.cumsum(sorted_probs)
cutoff = int(np.searchsorted(cumsum, top_p, side="left")) + 1
cutoff = min(max(cutoff, 1), sorted_probs.size)
nucleus = sorted_probs[:cutoff]
nucleus = nucleus / nucleus.sum()
pick = np.random.choice(cutoff, p=nucleus)
return int(order[pick])
Complexity
- Time: O(V log V), dominated by the sort; everything else is O(V). A partial selection or a top-k prefilter can reduce this in practice.
- Space: O(V).
Edge cases and common mistakes
- Exponent overflow: subtract the max before dividing by temperature so every exponent is <= 0. Computing
exp(logits / T)directly overflows at low T. - Off-by-one at the cutoff: the token that crosses the threshold must be included. Stopping just before it gives too small a nucleus.
top_p = 1.0with float error: the final cumulative sum may be 0.9999999, making the search returnV. Clamp the cutoff toV.- Very small
top_p: the cutoff is clamped to at least 1, so only the argmax survives. - Forgetting to map back: sampling from the sorted array returns a rank, not a vocabulary id.
- Forgetting to renormalize:
np.random.choicerequires probabilities summing to 1. - Masked tokens (
-inf): they get probability 0, which is fine; raise an error if every logit is-infor any is NaN. - Ties: a stable sort makes the cutoff deterministic.
- Tensors: convert to float64 NumPy first for consistent behavior.
- Near-zero temperature: fall back to argmax rather than dividing by a tiny number.
Follow-ups worth preparing
- Combining top-k with top-p, and the order in which filters and temperature are applied.
- Seeding a
Generatorfor reproducible sampling and batching the sampler over(B, V). - Why top-p adapts better than top-k: the nucleus size grows when the model is uncertain and shrinks when it is confident.