KatInterview

KV Cache, RoPE, and Nucleus Sampling with Temperature

Machine LearningModel answer
HardModel answerMachine Learningtransformerskv-cacherope

Last 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

  1. 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 width d_model, layer count n_layers and batch size B. Then describe how Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) change that cost relative to standard Multi-Head Attention (MHA).
  2. 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:

  1. Divide the logits by temperature.
  2. Turn them into probabilities with a numerically stable softmax.
  3. 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.
  4. Discard every token outside that group.
  5. Renormalize the survivors so they sum to 1.
  6. 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.