12. Sampling and the KV cache
Why this layer exists
A trained model maps a sequence of token ids to a vector of logits for the next position. A product needs a sequence of tokens, so something has to turn each distribution into one id, append it and ask again. That something is the sampler, and it is where an inference server’s per-request knobs live. Every request to llama-server can carry temperature, top_k, top_p, min_p, repeat_penalty, repeat_last_n, presence_penalty and frequency_penalty, and n_probs to have the probabilities of the top candidates reported back; the server’s --samplers option fixes the order in which the filters run. (What this chapter says about llama.cpp and llama-server is as of llama.cpp commit da89bb3, 2026-09-29.) Each of these is a few lines of arithmetic on the logits vector, and after this chapter each is one you have written.
The other half of inference is not choosing a token but computing the logits for it. Chapter 8’s generate recomputes the whole window at every step: to produce token 100 it runs the model over tokens 0 to 99 again, although tokens 0 to 98 were processed one step earlier. The KV cache keeps each layer’s keys and values for every position already processed, so that each new token costs one position’s work. It is why llama-server reports two speeds: its timings object gives prompt_n and prompt_ms for prompt processing, where many new positions go through the model together, and predicted_n and predicted_ms for generation, one position per forward pass, plus cache_n, the prompt tokens whose keys and values were reused from an earlier request instead of computed. It is also what -c sizes (the number of positions the cache holds), what the server’s slots (-np) share, and what --cache-type-k q8_0 and --cache-type-v q8_0 store at 8 bits instead of the default f16.
The chapter builds tinygpt.sample: log-softmax, the penalties, top-k, top-p and min-p, a sampler that chains them in llama.cpp’s order, a KV cache, a second forward pass for inference that reads and extends the cache, and a generate that uses both.
Mechanism
One token at a time
The model defines a distribution over the next token given the ones before it, , a vector of shape (V,) for each prefix. Chapter 8’s generate draws each token from that distribution given everything so far and appends it: ancestral sampling, which by the chain rule of probability draws the whole continuation from the model’s joint distribution. Every other decoding rule in this chapter changes the per-step distribution before the draw, so none of them samples from the model’s own joint distribution any more; each trades faithfulness to the model for text that reads better.
The simplest change is to take the most probable token every time, greedy decoding. It is deterministic and needs no random numbers. It does not find the most probable continuation: each choice changes every later factor of the product, so maximising the factors one at a time need not maximise the product. And it has a characteristic failure: once a phrase is the most likely continuation of itself, greedy decoding repeats it. The lab’s Persuasion model, prompted with “Anne was”, decodes greedily to “…concertaining the same, and the same daying of the same, and the same,”. The repetition is in the model’s distribution, not in the decoder: each token of the phrase is, at its position, the most probable token, so greedy decoding writes it again. Exercise (f) finds a prompt on which “, and the same” repeats until the context is full, every token of it the argmax.
Temperature
Chapter 4’s exercise (b) scaled logits by before the softmax. Temperature is : the sampler draws from
Chapter 4 derived the limits: as the distribution collapses onto the argmax, which is why temperature 0 means greedy decoding; as it approaches uniform. At it is the model’s own distribution.
In between, temperature moves the entropy monotonically. Write and , so and . The entropy is
using . Two derivatives are needed. First, . Second, , so
Then
Raising (lowering the temperature) lowers the entropy, strictly unless all logits are equal. For the distribution at is with entropy 1.2065 nats; at it is , 0.6086 nats; at it is , 1.4915 nats, against the uniform maximum . At , , and a numerical derivative of at gives , as the formula says.
Temperature changes every probability but never their order, so it never changes the argmax. What it changes is how much of the draw goes to the tail: at the lab model’s 512 tokens share whatever mass the top few leave, and any of them can be drawn.
Truncation: top-k, top-p, min-p
Truncation samplers remove the tail outright: they choose a set of tokens to keep, set every other logit to (probability 0), and let the softmax renormalise over the survivors.
Top-k keeps the tokens with the largest logits. It is blind to the shape of the distribution: keeps 39 tokens beside a favourite with probability 0.99, and cuts off plausible tokens when a hundred are about equally likely.
Top-p, or nucleus sampling, keeps the smallest set of most probable tokens whose probabilities sum to at least a threshold , the request’s top_p. Sort the probabilities in decreasing order, , and keep the first , where
The token that crosses is kept: on the example distribution the running sums are 0.563, 0.770, 0.896, 0.972, 1, so keeps two tokens and four. The set always holds at least one token, and reaching exactly counts: two tokens of probability 0.5 each with keep one. llama.cpp’s loop is written the same way (cum_sum >= p, then keep through that index). The size of the nucleus adapts to the distribution, one token when the favourite already has mass , hundreds when the mass is spread thin.
Min-p keeps every token whose probability is at least a fraction of the top token’s, the request’s min_p:
The threshold moves with the confidence of the model: when the favourite has probability 0.9 and , only tokens of at least 0.09 survive; when the favourite has 0.004, anything of at least 0.0004 does. The test needs no softmax at all. Since and share the denominator,
taking logarithms, which preserve order. The reference compares logits with , as llama.cpp’s min-p sampler does (min_logit = max_logit + logf(p)). On the example with the cut is : logits 2, 1 and 0.5 survive, with ratios 1, 0.368 and 0.223 to the top, and 0 and (ratios 0.135 and 0.050) go.
The two adaptive rules answer different questions. Top-p’s set is decided by the tail’s total mass, however many tokens that takes; min-p’s by each token’s size relative to the head. Exercise (c) measures how far apart that puts them on a large vocabulary.
Repetition penalties
Penalties change the logits of tokens that already occur in the context. llama.cpp’s rule, for a token with logit that occurs times in the penalty window, is
with the repetition penalty (repeat_penalty, 1 disables it), the frequency penalty (frequency_penalty), charged per occurrence, and the presence penalty (presence_penalty), charged once. Tokens that do not occur are unchanged.
The two branches of the first term exist because the repetition penalty is multiplicative. CTRL, which introduced it, divided every seen token’s logit by . That lowers a positive logit, but it raises a negative one toward 0: with , becomes , and a seen token that the model disfavoured becomes more likely, the opposite of the intent. Multiplying a non-positive logit by moves it away from 0 instead, to , so both branches lower the logit. The llama.cpp source carries a comment explaining exactly this. The two additive penalties have no such problem, and they differ in what they count: is a fixed charge for having appeared at all, grows with each repetition. A logit shift of multiplies that token’s probability, relative to every unpenalised token, by .
llama.cpp counts occurrences over the last repeat_last_n tokens (default 64; 0 disables the penalties), and llama-server feeds the prompt’s tokens into that window before generating, so the prompt counts. The reference counts over the whole history, prompt and generated tokens. The lab model’s context is 64, so its history never exceeds llama.cpp’s default window and the two agree. The code default for repeat_penalty is 1.0 (disabled), per common/common.h and --repeat-penalty’s help text; the README’s list of request parameters says 1.1.
The order of the chain
The filters do not commute. llama.cpp’s default chain, common_params_sampling::samplers in common/common.h, is
penalties → dry → top_n_sigma → top_k → typ_p → top_p → min_p → xtc → temperature,
followed by the draw (the dist sampler), and --samplers prints the same default. Any logit biases run before all of these. DRY, top-n-σ, typical-p and XTC are disabled by default and not built here; the reference implements the remaining subset in the same order:
Three consequences follow from where temperature sits. The truncation filters see the distribution at temperature 1, so the set of candidates depends only on the model and the filter parameters, and temperature then only redistributes mass among the survivors; high temperature cannot resurrect a token that top-p or min-p removed. Placed after temperature, min-p would test , that is , a cut that loosens as rises; before it, the cut is fixed at . And the penalties are applied to the raw logits, so they are sized in logit units at temperature 1 and then divided by with everything else.
The order among the filters matters too, because each renormalises over what the last one kept. After top- with , the two survivors of the example have probabilities and , so a following top-p 0.7 keeps only the first; top-p before top-k would have kept both. After top-p 0.8, which keeps three tokens, min-p 0.2 keeps the same three; in the other order min-p keeps those three first, their renormalised probabilities are 0.629, 0.231, 0.140, and top-p 0.8 then keeps two. test_filter_order_is_top_k_then_top_p_then_min_p pins both cases.
Temperature 0 is special-cased: llama.cpp’s temperature sampler, given , keeps only the argmax, and the reference returns the argmax of the penalised logits directly, without drawing a random number. The three filters built here cannot change the argmax, since each keeps the most probable token.
Logprobs
The log-probabilities an API reports are the log-softmax of the logits,
the second form being the stable one from chapter 8’s cross-entropy: every exponent is at most 0 and the largest is exactly 0, so the sum is between 1 and and neither overflows nor rounds to 0. log_softmax computes it along the last axis, so it takes a (V,) vector or the (T, V) logits of a whole window. Here and in the KV-cache sections below, is a number of positions, as in chapters 10 and 11, not the temperature of the sections above.
What llama-server reports, from its source: with n_probs greater than 0 (/v1/chat/completions sets it from top_logprobs, default 20, when logprobs is true), each generated token comes back with its own logprob and a top_logprobs list of the n_probs most probable candidates. By default these are computed by get_token_probabilities, a softmax of the model’s raw logits over the whole vocabulary: before penalties, before truncation and at temperature 1, the model’s own distribution, whatever sampling settings produced the token. The request option post_sampling_probs switches to probabilities taken from the sampler chain’s surviving candidates after it has run, reported as prob and top_probs, with possibly fewer than n_probs entries. The values are natural logarithms (std::log), as chapter 4 said.
So a default logprob of means the model gave the token probability 0.905 at temperature 1; it does not say how likely the sampler was to pick it. The lab prints this quantity for eight sampled tokens with its rank among all 512.
The KV cache
At generation step the model needs the logits at the last position only. Consider what that position’s computation reads. In each layer the new position’s query is scored against the keys of every position up to , and the weights average those positions’ values. Every other part of the block (the layer norms, the projections, the feed-forward sublayer, the residual additions) works on each position separately.
Claim. Under a causal mask, the state of position after any number of layers depends only on the tokens . By induction on the layer. Before the first block, position holds the embedding of plus, with learned positions, row of the position table, which depends on alone. Suppose the claim holds for the input of layer . Layer ’s attention output at is computed from the query at and the keys and values at positions , the mask giving every later position weight 0; each of those is a function of the input at position (and, with RoPE, of itself), which by the hypothesis depends only on , a subset of . Everything else in the block is per-position. So the output at depends only on , which completes the induction.
Consequently the keys and values of layer at position are fixed once is known: appending tokens after cannot change them. They can be computed once and stored, and each step computes only the new position: its embedding, its own query, key and value in each layer, one row of scores against the stored keys, and the rest of the block for one position. Queries are not stored: only the newest position’s query is ever used. With RoPE, the stored keys are the rotated ones, since a key’s rotation depends only on its own position.
The figure shows the cache of a two-layer model after a four-token prompt and four generated tokens.
Cost. Count the positions pushed through the projections and feed-forward sublayers, the part of the work proportional to the number of positions. Generating tokens after a prompt of without a cache, step processes all positions:
quadratic in the number of tokens generated. With a cache, step 0 processes the prompt positions and each later step one, in all, linear. For the lab’s 3-token prompt “Anne was” (A, nne, " was") and that is 1,950 positions against 62, a ratio of 31.5. Attention adds a term that grows with the length in both cases: without a cache the reference computes a full score matrix for an -position window at every step, with one a single row of scores. Exercise (e) times the two on the lab model; the measured ratio is smaller than 31.5, and the exercise explains why.
Memory. Each layer stores a key and a value vector of width for each position (the heads of width side by side). For layers, positions and bytes per stored number,
The lab model, and , stores numpy float64 (): 2,048 bytes per position, 131,072 bytes (128 KiB) for its full context of 64, against 1,354,752 bytes for its 169,344 parameters. For a model with and at , llama-server’s default f16 () gives 819,200 bytes per position and
about the size of that model’s weights at the same precision: its blocks hold about parameters by chapter 11’s count, 23.4 GiB at 2 bytes. q8_0 stores blocks of 32 values as one 2-byte f16 scale and 32 signed bytes, 34 bytes per 32 values (block_q8_0 in ggml’s ggml-common.h, which asserts sizeof(block_q8_0) == sizeof(ggml_half) + QK8_0 with QK8_0 = 32), so : 14,260,633,600 bytes, 13.28 GiB, 53% of f16. Chapter 14 builds this kind of block quantization for weights. The formula assumes every head has its own keys and values. Models with grouped-query attention share each key and value head among a group of query heads, which divides by the group size; for those, in the formula is the number of key-value heads times the head width.
The cache is sized in positions, which is what -c sets. llama-server’s slots are the requests it decodes concurrently; with --kv-unified (the default when the slot count is automatic) all slots draw on one buffer of -c positions, and without it each slot gets -c divided by the number of slots.
Positions, masks and rollback
forward_cached(model, ids, cache) processes ids, new tokens, as positions , where is len(cache), the number of positions already stored. Three things depend on that offset.
- Learned positions add row of the table to new token , not row . Getting this wrong leaves the first step correct and every later one wrong.
- RoPE rotates the new queries and keys by angles for positions . The score between a query and a key depends on the difference of their positions (chapter 11), so a new query rotated for position against cached keys rotated for their true positions scores as if it were far earlier in the sequence.
- The mask is
(T, S_0 + T): new token , at absolute position , may read every cached key and the new keys up to itself, and is masked from key exactly when . With nothing is masked. With a chunk of several tokens after a non-empty cache, which is what llama-server does when it processes a long prompt in batches, the mask is chapter 10’s causal mask shifted right by columns.
truncate(n) forgets every position from on. It is how a cache is rolled back when positions turn out to be unwanted. llama-server’s cache_prompt (on by default) keeps a slot’s cache between requests and processes only the suffix of a new prompt that differs from the previous one: for the cache that means keeping the common prefix, truncating after it, and appending the new suffix. Speculative decoding, in chapter 14, has a cheap model draft several tokens and the real model verify them in one pass; an engine that caches must then drop the rejected tokens’ keys and values. After truncate(n), the next forward_cached call starts at position again, and test_cache_truncate_rolls_back checks that it then matches the uncached model on the edited sequence.
The cached generate stops at the context length rather than sliding its window as chapter 8’s does. Dropping the first token of a window changes what every later position attended to, so none of the stored keys would be exact any more. llama-server’s --context-shift (off by default) slides anyway: when a slot’s cache is full it discards a block of positions after the first n_keep and moves the later ones down, re-rotating their RoPE keys for the new positions. Every stored value, and every key above the first layer, was still computed with the discarded tokens in view, so what it continues from is an approximation of the model on the shorter window, not the model itself.
Two implementations and one oracle
forward_cached is a second implementation of the model’s forward pass, written directly in numpy against the parameter arrays of a GPT. It does not reuse GPT.__call__. Inference needs no graph, and chapter 6’s engine has no switch to stop recording one; and two independent code paths make the test between them a real check. The oracle is the uncached model: feed a sequence through forward_cached as a 4-token prompt and then one token at a time, and the concatenated logits must equal GPT’s logits for the whole sequence, computed in one call, to , for both position schemes (test_cached_logits_equal_uncached). test_cached_chunks_after_a_nonempty_cache feeds a full context of 12 in chunks of 2, 3, 1, 4 and 2, which exercises the shifted mask. The two paths agree to within on the test models of test_cached_logits_equal_uncached, whose logits are at most 1.54 in size, and to on the lab’s Persuasion model over 62 positions; a mistake in positions, rotation angles or the mask changes what the model computes, not just its rounding, and fails the tolerance. A freshly initialised model hides one kind of mistake: every layer-norm gain is 1 and every bias and layer-norm shift 0, so a cached path that leaves out a bias, a norm’s parameters, or uses the wrong norm before the head still matches it exactly. test_cached_logits_equal_uncached_with_parameters_moved_off_init adds noise of standard deviation 0.5 to every parameter first, as training moves them, so that each has to be used. All three tests also run on chapter 11’s mixture-of-experts model, with four experts and top-2 routing in both blocks, where the cached path computes only the chosen experts and the uncached one computes all four; test_cached_logits_equal_uncached_with_parameters_moved_off_init also runs it with top-1 and top-3 routing, so a cached path that fixes the number of experts at two fails.
Walkthrough
The reference module is py/tinygpt/sample.py.
def log_softmax(logits):
"""log softmax(logits) along the last axis: the logprobs an API returns."""
z = np.asarray(logits, dtype=np.float64)
z = z - z.max(axis=-1, keepdims=True)
return z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
def apply_penalties(logits, history, repeat=1.0, presence=0.0, frequency=0.0):
"""Discourage tokens in history: divide positive logits by repeat (multiply the others),
then subtract presence once and frequency per occurrence."""
out = np.array(logits, dtype=np.float64)
ids, counts = np.unique(np.asarray(history, dtype=np.int64), return_counts=True)
if ids.size:
z = out[ids]
out[ids] = np.where(z > 0, z / repeat, z * repeat) - presence - frequency * counts
return out
def top_k(logits, k):
"""Keep the k largest logits; the rest become -inf. k <= 0 keeps everything."""
out = np.array(logits, dtype=np.float64)
if 0 < k < out.size:
drop = np.argsort(-out, kind="stable")[k:]
out[drop] = -np.inf
return out
def top_p(logits, p):
"""Keep the smallest set of most-probable tokens whose probabilities sum to at least p."""
out = np.array(logits, dtype=np.float64)
if p >= 1.0:
return out
order = np.argsort(-out, kind="stable")
probs = np.exp(log_softmax(out))[order]
cutoff = int(np.searchsorted(np.cumsum(probs), p)) + 1 # tokens needed to reach p; at least 1
out[order[cutoff:]] = -np.inf
return out
def min_p(logits, p):
"""Keep tokens whose probability is at least p times the top token's probability."""
out = np.array(logits, dtype=np.float64)
if p > 0: # prob_i / prob_max = exp(z_i - z_max), so compare logits directly
out[out < out.max() + np.log(p)] = -np.inf
return out
Every filter copies its input with np.array(logits, dtype=np.float64) before writing, so the caller’s logits are never modified and a list of ints is accepted. log_softmax subtracts the maximum along the last axis with keepdims=True, so each row of a (T, V) array is shifted by its own maximum. apply_penalties counts the history with np.unique(..., return_counts=True), which returns each distinct id once with its count, and updates only those entries; np.where implements the two branches of the repetition penalty. top_k ranks with a stable argsort of the negated logits, so ties keep the lower id, and sets everything from rank on to . top_p sorts the probabilities in decreasing order and finds the crossing point with np.searchsorted on the running sum: it returns the first index whose running sum is at least (the argument p), and the + 1 keeps that token. The probabilities come from log_softmax of the current logits, so entries already at contribute 0 and the survivors are renormalised. min_p is the logit comparison derived above.
def sample_token(logits, rng, temperature=1.0, k=0, p=1.0, minp=0.0, history=(), repeat=1.0,
presence=0.0, frequency=0.0):
"""One token id: penalties, then top-k, top-p, min-p, then temperature, then a draw.
temperature <= 0 means greedy: the argmax after the penalties, and rng is not used.
ValueError when no token is left to choose, rather than a NaN inside rng.choice.
"""
if repeat <= 0 or not 0.0 <= minp <= 1.0:
raise ValueError(f"need repeat > 0 and 0 <= minp <= 1, got repeat={repeat}, minp={minp}")
z = apply_penalties(logits, history, repeat, presence, frequency)
if temperature > 0:
z = min_p(top_p(top_k(z, k), p), minp)
if not np.isfinite(z.max()): # every logit -inf (e.g. a mask allowed nothing), or a nan
raise ValueError("no token left to sample: the logits have no finite maximum")
if temperature <= 0:
return int(np.argmax(z))
with np.errstate(over="ignore", invalid="ignore"):
probs = np.exp(log_softmax(z / temperature))
if not np.isfinite(probs).all():
raise ValueError(f"temperature {temperature} overflows the logits; use 0 for greedy")
return int(rng.choice(probs.size, p=probs))
sample_token is the chain. The penalties go first, on the raw logits. Temperature 0 or below returns the argmax of the penalised logits. Otherwise the three filters run in llama.cpp’s order, the result is divided by the temperature, and log_softmax followed by exp turns it into probabilities: the entries become exactly 0, so rng.choice can never draw them. The draw is rng.choice(V, p=probs), as in chapter 8, which makes a run reproducible from its seed. The checks make every impossible request a ValueError that names it, rather than a NaN that rng.choice reports as “probabilities contain NaN”: a repetition penalty of 0 or below divides by zero or flips signs, a min-p above 1 removes even the favourite, a row whose logits are all has nothing to draw (chapter 18 proves that a correct grammar mask over a vocabulary holding every single byte never leaves one; a buggy constraint, a filter whose allowed set misses the mask’s, or a vocabulary that cannot spell some byte can, and its server turns the ValueError into an error to the client), and a temperature so small that overflows turns the softmax into . The lab does not test these; py/tests/test_sample.py does.
class KVCache:
"""Per-layer keys and values of every position processed so far, each (H, S, d_head)."""
def __init__(self, n_layers):
self.k = [None] * n_layers
self.v = [None] * n_layers
def __len__(self):
return 0 if self.k[0] is None else self.k[0].shape[1]
def append(self, layer, k, v):
"""Add this step's (H, T, d_head) keys and values; return the full (H, S + T, d_head) arrays."""
if self.k[layer] is not None:
k = np.concatenate([self.k[layer], k], axis=1)
v = np.concatenate([self.v[layer], v], axis=1)
self.k[layer], self.v[layer] = k, v
return k, v
def truncate(self, n):
"""Forget every position from n on, e.g. to roll back rejected speculative tokens."""
for i in range(len(self.k)):
if self.k[i] is not None:
self.k[i], self.v[i] = self.k[i][:, :n], self.v[i][:, :n]
The cache holds one (H, S, d_head) key array and one value array per layer, None until the first append. append concatenates along axis 1, the position axis, and returns the full arrays, which is what the attention step needs next. Concatenating copies the whole cache at every step, work per step per layer; a real engine allocates the cache for -c positions up front and writes each new position in place. At these sizes the copies do not show in the timings. len reads the position count from layer 0, which is valid because a forward pass appends to every layer. truncate slices each layer’s arrays back to n positions.
def layer_norm_np(x, ln, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True)
var = ((x - mu) ** 2).mean(axis=-1, keepdims=True)
return (x - mu) / np.sqrt(var + eps) * ln.gamma.data + ln.beta.data
def gelu_np(x):
return 0.5 * x * (1.0 + np.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * x ** 3)))
def _heads(y, H):
T = y.shape[0]
return y.reshape(T, H, -1).transpose(1, 0, 2) # (T, d) -> (H, T, d/H)
def _rope(x, positions):
cos, sin, swap = _rope_tables(positions, x.shape[-1])
return x * cos + (x @ swap) * sin
def _moe(moe, h):
"""Chapter 11's MoE on (T, d) rows, computing only the top_k experts each row's router picks."""
z = h @ moe.router.weight.data # (T, E)
top = np.argsort(-z, axis=-1, kind="stable")[:, :moe.top_k] # (T, k)
zk = np.take_along_axis(z, top, axis=-1)
g = np.exp(zk - zk.max(axis=-1, keepdims=True))
g /= g.sum(axis=-1, keepdims=True) # (T, k) gates
out = np.zeros_like(h)
for t, (experts, gates) in enumerate(zip(top, g)):
for e, w in zip(experts, gates): # k experts, not all E
u = gelu_np(h[t] @ moe.up.data[e] + moe.up_bias.data[e])
out[t] += w * (u @ moe.down.data[e] + moe.down_bias.data[e])
return out
def forward_cached(model, ids, cache):
"""Logits (T, V) for new tokens ids (T,) of one sequence, reusing and extending cache.
Plain numpy: inference needs no graph. Position i of ids is absolute position len(cache) + i.
"""
cfg, H = model.cfg, model.cfg.n_heads
if not all(blk.attn.causal for blk in model.blocks):
raise ValueError("forward_cached needs causal attention; a bidirectional model has no KV cache")
ids = np.asarray(ids, dtype=np.int64)
start, T = len(cache), len(ids)
if start + T > cfg.context:
raise ValueError(f"{start + T} positions exceed context {cfg.context}")
if T and (ids.min() < 0 or ids.max() >= cfg.vocab_size):
raise ValueError(f"token ids must lie in [0, {cfg.vocab_size})")
pos = np.arange(start, start + T)
x = model.tok.data[ids] # (T, d)
if model.pos is not None:
x = x + model.pos.data[pos]
# A new token at absolute position start + t may read cached and new keys up to start + t.
mask = np.where(np.arange(start + T)[None, :] > pos[:, None], -np.inf, 0.0) # (T, S)
for i, blk in enumerate(model.blocks):
a, h = blk.attn, layer_norm_np(x, blk.ln1)
q, k, v = (_heads(h @ lin.weight.data, H) for lin in (a.query, a.key, a.value))
if a.rope:
q, k = _rope(q, pos), _rope(k, pos)
k, v = cache.append(i, k, v) # (H, S, d/H), S = start + T
scores = q @ k.transpose(0, 2, 1) / np.sqrt(q.shape[-1]) + mask
w = np.exp(scores - scores.max(axis=-1, keepdims=True))
w /= w.sum(axis=-1, keepdims=True)
y = (w @ v).transpose(1, 0, 2).reshape(T, -1) # (T, d)
x = x + y @ a.proj.weight.data + a.proj.bias.data
h = layer_norm_np(x, blk.ln2)
if blk.moe is not None:
x = x + _moe(blk.moe, h)
else:
u = gelu_np(h @ blk.up.weight.data + blk.up.bias.data)
x = x + u @ blk.down.weight.data + blk.down.bias.data
return layer_norm_np(x, model.ln_f) @ model.head.weight.data # (T, V)
The helpers restate chapter 11’s pieces for plain arrays: layer_norm_np is layer_norm with the same biased variance and , gelu_np the same tanh approximation, _heads the same split of (T, d) into (H, T, d/H) for one sequence, and _rope chapter 11’s rope built on the same _rope_tables. forward_cached checks the context and that every id lies in before touching anything, so a rejected call leaves the cache as it was; an id of would otherwise index the table’s last row without complaint. It also refuses a model any of whose blocks has its causal mask switched off (chapter 15’s encoder): the cache rests on the induction above, which needs the mask, and such a model would otherwise run here as a causal one. pos holds the absolute positions of the new tokens, used for the learned table, for RoPE and for the mask. The mask is -inf where key index exceeds the query’s absolute position. In each block the new tokens’ queries, keys and values are computed, the keys rotated if the model uses RoPE, and the keys and values appended; the scores are then the (H, T, d/H) queries against all (H, S, d/H) keys, (H, T, S), scaled by and masked. The softmax is written out with the maximum subtracted. The rest of the block, the output projection, the residual additions and the feed-forward sublayer, is the per-position computation of chapter 11’s Block. A block with a mixture of experts goes through _moe, which is not chapter 11’s computation but what an inference engine does: for each new position it takes the router’s logits, keeps the top_k largest with the same stable sort, takes the softmax of those logits, and runs only those experts, where MoE ran all and multiplied the rest by 0. The two agree because a gate of 0 contributes nothing, and the cached tests check it for a model with four experts, with and, in the test on parameters moved off their initial values, also and 3. The result is (T, V).
def generate(model, prompt, n_new, rng, use_cache=True, stop=(), **sampling):
"""Up to n_new tokens after prompt, sampled with sample_token(**sampling).
Stops early after emitting a token in stop (that token is included in the result).
"""
ids = list(prompt)
if not ids:
raise ValueError("generate needs a non-empty prompt")
if len(ids) + n_new > model.cfg.context:
raise ValueError(f"prompt {len(ids)} + n_new {n_new} exceeds context {model.cfg.context}")
cache = KVCache(model.cfg.n_layers)
out = []
for step in range(n_new):
if use_cache:
new = ids if step == 0 else ids[-1:] # the prompt once, then one token
logits = forward_cached(model, new, cache)[-1]
else:
full = model(np.array([ids])) # recompute every position
logits = full.data[0, -1]
free_graph(full)
free_aux(model)
tok = sample_token(logits, rng, history=ids, **sampling)
ids.append(tok)
out.append(tok)
if tok in stop:
break
return out
generate refuses an empty prompt and a request that would run past the context, since the cached path cannot slide. With the cache, step 0 feeds the whole prompt and every later step only the token just drawn; the logits come from the last row. Without it, each step runs GPT over everything so far and frees the graph, as chapter 8’s generate does. Both paths pass the whole history, prompt included, to the penalties. A token in stop ends generation after it has been appended, so the result includes it, as an end-of-sequence token would be the last token of a reply. Called with the same seed, the two paths draw from distributions that agree to rounding and consume the random generator identically, so in practice they return the same tokens (a rounding-level difference could in principle flip a draw that lands on a boundary of the cumulative distribution, or an exact argmax tie), which test_generate_cached_equals_uncached checks.
Exercises
(a) Compute the entropy of for at temperatures , 1 and 2, compare each with the largest possible entropy on five outcomes, and check at with a numerical derivative.
Answer
With and :
: the scaled logits are , the probabilities 0.9478, 0.0472, 0.0023, 0.0023 and 0.0003, and nats.
: the probabilities are 0.7457, 0.1664, 0.0371, 0.0371 and 0.0137, and nats.
: the scaled logits are , the probabilities 0.4869, 0.2300, 0.1086, 0.1086 and 0.0659, and nats.
The maximum on five outcomes is the uniform distribution’s nats (chapter 4). The exponentials of the three entropies, 1.25, 2.27 and 3.86, are the number of equally likely tokens with the same entropy. At , , so the formula gives at , and a central difference of , with the logits scaled by , gives the same . This distribution is more peaked than the chapter’s example, whose variance at is 0.6474, so its entropy falls faster as the temperature drops.
(b) By hand, find the top-p set for on the distribution of (a), the distribution the sampler draws from at temperature 1 and at 0.5, and say what decides between the two tokens of equal probability.
Answer
Sorted, the probabilities are 0.7457, 0.1664, 0.0371, 0.0371, 0.0137, and the running sums 0.7457, 0.9121, 0.9492. The second is below 0.94 and the third reaches it, so three tokens are kept, holding mass 0.9492. The third and fourth tokens have the same logit, 0, so they tie for third place, and only one of them fits. The reference sorts with a stable argsort, so the lower id, token 2, is kept and token 3 dropped; an implementation with an unstable sort may keep either, and the lab pins the reference’s choice only for top-k. At temperature 1 the sampler draws from , , and 0 for the other two. At temperature 0.5 the set is the same, because the filter runs at temperature 1, and the draw is the softmax of the three surviving logits divided by 0.5, : 0.9503, 0.0473 and 0.0024.
(c) Build a peaked and a flat distribution over 1,000 tokens and compare how many tokens top-p 0.9 and min-p 0.1 keep. Explain why min-p adapts where top-p does not.
Answer
import numpy as np
from tinygpt.sample import min_p, top_p
rng = np.random.default_rng(0)
flat = rng.normal(0.0, 0.5, size=1000) # 1,000 logits, no clear favourite
peaked = flat.copy()
peaked[0] = 8.0 # the same, with one token far ahead
for name, z in [("peaked", peaked), ("flat", flat)]:
p = np.exp(z - z.max())
p /= p.sum()
kp, km = np.isfinite(top_p(z, 0.9)), np.isfinite(min_p(z, 0.1))
print(f"{name:6s} p_max {p.max():.4f} top-p 0.9 keeps {kp.sum():3d} (mass {p[kp].sum():.3f})"
f" min-p 0.1 keeps {km.sum():3d} (mass {p[km].sum():.3f})")
peaked p_max 0.7308 top-p 0.9 keeps 437 (mass 0.900) min-p 0.1 keeps 1 (mass 0.731)
flat p_max 0.0042 top-p 0.9 keeps 789 (mass 0.900) min-p 0.1 keeps 949 (mass 0.983)
Top-p and min-p both adapt, but to different things. Top-p must collect a fixed mass. In the peaked case the favourite has 0.73, and the remaining 0.17 has to come from 999 tokens of about 0.0003 each, so it keeps 436 of them: the tail is thin per token but heavy in total, and top-p lets all of it in. Min-p compares each token with the favourite: nothing else is within a factor of 10 of 0.73, so it keeps one token. In the flat case the favourite has 0.0042 and the threshold is 0.00042; the logits have standard deviation 0.5, so almost every token is within a factor of 10 ( logit units, 4.6 standard deviations) of the maximum, and min-p keeps 949 while top-p stops at a fixed 90% of the mass. Min-p tightens when the model is confident and loosens when it is not; top-p follows the tail’s total mass, which a large vocabulary makes heavy even when every tail token is individually implausible.
(d) Compute the KV-cache size, per position and for 32,768 positions at f16 and q8_0, of Qwen3-30B-A3B, whose config.json gives num_hidden_layers 48, hidden_size 2048, num_attention_heads 32, num_key_value_heads 4 and head_dim 128. Compare it with the same model without grouped-query attention. Then read the same three numbers for the model your llama-server serves from its GGUF metadata, and compute its cache at the -c you run it with.
Answer
With grouped-query attention the cache stores the key-value heads only, so the width in is the number of key-value heads times the head width, , not hidden_size. (Qwen3’s heads are not hidden_size divided by the head count either: 32 query heads of 128 are 4,096 wide, twice the 2,048 of the residual stream.) Per position at f16: bytes, 96 KiB. For 32,768 positions: 3,221,225,472 bytes, exactly 3 GiB. At q8_0, : 52,224 bytes per position and 1,711,276,032 bytes, 1.59 GiB, the same factor 17/32 of f16 as in the text. Without grouped-query attention every one of the 32 query heads would have its own key and value head, a width of 4,096 and eight times as much: 786,432 bytes per position and 24 GiB at f16.
For your own model the GGUF keys are, with <arch> the value of general.architecture: <arch>.block_count for , <arch>.attention.head_count_kv for the key-value heads, and <arch>.attention.key_length and <arch>.attention.value_length for the head widths, which default to the embedding width divided by the head count when absent (ggml’s docs/gguf.md). llama-server logs the same values as it loads the model (n_layer, n_head_kv per layer, n_embd_head_k) and then a line llama_kv_cache: size = … MiB (… cells, … layers, …) for the cache it allocated, which your computation should match. The layer count in that line is the number of layers that store keys and values; a model that mixes attention layers with layers of another kind has fewer of them than n_layer, and you should use that count for .
(e) Time 60 greedy tokens with and without the cache on the Persuasion model, and relate the ratio to the derivation.
Answer
import pathlib
import time
import numpy as np
from tinygpt.bpe import BPE
from tinygpt.nn import free_graph
from tinygpt.sample import KVCache, forward_cached, generate
from tinygpt.transformer import load
run = pathlib.Path("/tmp/tinygpt-persuasion")
tok, model = BPE.load(run / "tokenizer.json"), load(run / "model.npz")
prompt = tok.encode("Anne was")
def median_ms(f, reps=21):
ts = []
for _ in range(reps):
start = time.perf_counter()
f()
ts.append(time.perf_counter() - start)
return 1000 * float(np.median(ts))
for use_cache in [False, True]:
ms = median_ms(lambda: generate(model, prompt, 60, np.random.default_rng(0), use_cache=use_cache, temperature=0), 7)
print(f"60 greedy tokens, use_cache={use_cache}: {ms:.1f} ms")
ids = prompt + generate(model, prompt, 60, np.random.default_rng(0), temperature=0)
def uncached(T):
free_graph(model(np.array([ids[:T]])))
def cached_step(S):
cache = KVCache(model.cfg.n_layers)
forward_cached(model, ids[:S], cache)
return lambda: (forward_cached(model, ids[S:S + 1], cache), cache.truncate(S))
for T in [1, 16, 32, 63]:
print(f"uncached forward of {T:2d} positions: {median_ms(lambda: uncached(T)):.2f} ms")
for S in [3, 32, 62]:
print(f"cached step after {S:2d} positions: {median_ms(cached_step(S)):.2f} ms")
Run from py/ with OPENBLAS_NUM_THREADS=1 PYTHONPATH=., on talos, chapter 11’s laptop:
60 greedy tokens, use_cache=False: 191.8 ms
60 greedy tokens, use_cache=True: 21.9 ms
uncached forward of 1 positions: 0.90 ms
uncached forward of 16 positions: 1.69 ms
uncached forward of 32 positions: 2.57 ms
uncached forward of 63 positions: 6.25 ms
cached step after 3 positions: 0.29 ms
cached step after 32 positions: 0.29 ms
cached step after 62 positions: 0.30 ms
The cache is 8.8 times faster, against the 31.5 the position count predicts (1,950 positions against 62, for and ). The count assumed each forward pass costs a fixed amount per position. The measurements say otherwise: an uncached pass costs 0.90 ms for one position and 1.69 ms for sixteen, so most of the one-position cost is not per-position work but a fixed cost per call, the Python overhead of building and freeing a graph of Tensor nodes. The per-position part is about 0.05 ms up to 32 positions and grows faster after that as the attention scores and larger arrays take over. The cached step is flat at 0.29 to 0.30 ms whatever the cache length: at 62 positions one row of scores is negligible next to the fixed cost of the pass’s numpy calls. So the cached run is 60 fixed costs of about 0.3 ms, and the uncached run 60 fixed costs of about 0.9 ms plus the per-position work, which is what grows quadratically. Modelling a call as , the ratio of the two runs is , which approaches the position ratio only when the per-position terms dominate the per-call ones, as they do in a model whose per-position arithmetic is large.
(f) Find a prompt on which greedy decoding loops, and show which penalty settings break the loop.
Answer
import collections
import pathlib
import numpy as np
from tinygpt.bpe import BPE
from tinygpt.sample import generate
from tinygpt.transformer import load
run = pathlib.Path("/tmp/tinygpt-persuasion")
tok, model = BPE.load(run / "tokenizer.json"), load(run / "model.npz")
prompt = tok.encode("Captain Wentworth")
n = model.cfg.context - len(prompt)
for s in [dict(), dict(repeat=1.1), dict(repeat=1.3), dict(presence=0.5), dict(frequency=0.3)]:
out = generate(model, prompt, n, np.random.default_rng(0), temperature=0, **s)
trigrams = collections.Counter(zip(out, out[1:], out[2:]))
(top, count), = trigrams.most_common(1)
print(f"{s}: {len(set(out))} distinct of {len(out)}, {tok.decode(list(top))!r} x{count}")
print(" ", repr(tok.decode(out[-24:])))
{}: 31 distinct of 60, ' the same' x5
'ch was afterwards, and the same, and the same, and the same\n'
{'repeat': 1.1}: 48 distinct of 60, ', and Anne' x1
' been acquainted with him,” said Lady Russell, “I have\n'
{'repeat': 1.3}: 57 distinct of 60, ', and Anne' x1
'\ngraved by him.”\n\n“I will do you know it that he is very'
{'presence': 0.5}: 38 distinct of 60, ', and a' x2
'twentymanity of the others, and he had been about\ninting'
{'frequency': 0.3}: 39 distinct of 60, ', and\n' x2
'ch was able to be justice to be acquainted with\nthe'
“Captain Wentworth” fills the context with 60 greedy tokens, and the last of them are “, and the same” three times over; the most common token trigram occurs five times, and only 31 of the 60 tokens are distinct. Every penalty setting ends the loop: no trigram repeats more than twice, and the distinct count rises to 38 to 57. In the loop the looping tokens (,, " and", " the", " s", ame) win with logits between 6.8 and 10.7, some only narrowly (the comma beats its runner-up by 0.10). Dividing a logit of 7 by lowers it by 1.6; a presence penalty of 0.5 lowers it by 0.5, and a frequency penalty of 0.3 by 0.3 per earlier occurrence. In these runs the repetition penalty moved furthest from the loop. The text is still not good; the model is small. And the penalties are indiscriminate: English repeats “the” and “and” legitimately, and a penalty large enough to stop this loop also taxes them. With repeat_last_n of 64, as in llama.cpp, the results here would be the same, since prompt and output together never exceed 64 tokens.
Lab
Implement py/labs/ch12/starter.py: the five functions on logits, sample_token, KVCache, forward_cached and generate. Run
make lab CH=12 IMPL=mine
until it passes. Read py/labs/ch12/test_lab.py first. It pins each filter on the five-logit example, including the edges: top-p keeps the token that reaches , including exactly, and renormalises over survivors; min-p is relative to the top token; the penalties count every occurrence and multiply negative logits. It checks the exact distribution sample_token hands to rng.choice, through a stand-in generator that records it, for temperature, for penalties before temperature and before truncation, for truncation (top-p and min-p) at temperature 1, and for the order top-k, top-p, min-p; and that a temperature of 0 or below is greedy and top-k ties keep the lower id. The acceptance test is test_cached_logits_equal_uncached, with both position schemes and with and without chapter 11’s mixture of experts (a block whose moe is not None needs the router, the top- choice and the gates in your forward_cached), together with the chunked version, the version on parameters moved off their initial values, a model whose router logits tie (your top- must break the tie as chapter 11’s stable sort does, toward the lower index), and the rollback test; the last tests check that the two generate paths agree, that greedy generation follows the model’s argmax, that the prompt counts toward the penalties, and the stop and error behaviour.
Then sample from chapter 11’s Persuasion model, which its lab left in /tmp/tinygpt-persuasion (rerun that lab’s training command if it is gone; on another machine the new file can differ from talos’s in its last bits, chapter 11). Save as /tmp/sampling_lab.py:
import pathlib
import sys
import time
import numpy as np
from tinygpt.bpe import BPE
from tinygpt.sample import generate, log_softmax
from tinygpt.transformer import load
run = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/tinygpt-persuasion")
tok, model = BPE.load(run / "tokenizer.json"), load(run / "model.npz")
prompt = tok.encode("Anne was")
for use_cache in [False, True]:
start = time.time()
out = generate(model, prompt, 60, np.random.default_rng(0), use_cache=use_cache, temperature=0)
print(f"use_cache={use_cache}: 60 tokens in {time.time() - start:.2f}s")
print("greedy: ", repr(tok.decode(prompt + out)))
settings = [dict(temperature=0.7), dict(temperature=1.0), dict(temperature=1.0, p=0.9),
dict(temperature=1.0, minp=0.1), dict(temperature=0, repeat=1.3)]
for s in settings:
out = generate(model, prompt, 40, np.random.default_rng(1), **s)
print(f"{s}:", repr(tok.decode(prompt + out)))
ids = prompt + generate(model, prompt, 8, np.random.default_rng(2), temperature=1.0)
lp = log_softmax(model(np.array([ids[:-1]])).data[0])
for pos in range(len(prompt) - 1, len(ids) - 1):
t = ids[pos + 1]
print(f"{tok.decode([t])!r:>12} logprob {lp[pos, t]:7.3f} rank {int((lp[pos] > lp[pos, t]).sum()) + 1}")
and run it from py/:
OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/sampling_lab.py /tmp/tinygpt-persuasion
It printed:
use_cache=False: 60 tokens in 0.19s
use_cache=True: 60 tokens in 0.02s
greedy: 'Anne was justy, and\nsuch acquainted with a few moments and sense and\nconcertaining the same, and the same daying of the same, and the same,'
{'temperature': 0.7}: 'Anne was a very\nlegantly. My was to fase.\n\nAnd young man’s children are most impo'
{'temperature': 1.0}: 'Anne was beath.”\n\n“I tolerve her soon before, he never done anything to age of\nwith Captain Benwick'
{'temperature': 1.0, 'p': 0.9}: 'Anne was fally knwelly taking ladies to\nhis settl their letters, where are soon necessary,'
{'temperature': 1.0, 'minp': 0.1}: 'Anne was some\nlighted with the inconsequence. Mymple had made him guess, which\nbeen gone, and ind'
{'temperature': 0, 'repeat': 1.3}: 'Anne was justy, and\nshered to be about the same. He had been soon ascied by her\nfather’s re'
' a' logprob -2.164 rank 2
'd' logprob -2.440 rank 2
'ed' logprob -2.380 rank 3
',' logprob -1.808 rank 1
' it' logprob -5.245 rank 43
' is' logprob -1.980 rank 3
' a' logprob -2.199 rank 1
'\n' logprob -1.730 rank 1
The timings depend on the machine. The text depends on the model file: this is talos’s, and a model you train on another machine can sample differently.
- The cache is several times faster, and the text is the same. The script prints the cached run’s continuation; the uncached run produced the same 60 tokens, as
test_generate_cached_equals_uncachedchecks on the toy models. The printed times are rounded to hundredths of a second; exercise (e) measures the ratio properly and explains why it is not 31. - Greedy decoding loops. The model’s most probable continuation of “, and the same” is itself. The last line of the settings, greedy with a repetition penalty of 1.3, avoids the loop. Its first nine tokens, through “justy, and\ns”, are the unpenalised run’s; they must be until the unpenalised argmax is a token already in the history, since a penalty lowers only tokens that have occurred and cannot overtake an argmax that has not. At the tenth, greedy’s choice
uhas occurred before, and the penalised run takesheinstead. - Every sampled line is less repetitive and more broken. At temperature 1 the model’s full distribution produces non-words (“beath”, “tolerve”) alongside a character’s name, Captain Benwick. Temperature 0.7, top-p 0.9 and min-p 0.1 each cut some of the tail, and at this model size none of them turns the output into sentences; they change how often a low-probability piece is drawn. Comparing single samples says little about which is better. The seeds are shared across settings, so the differences are the settings’, but a proper comparison needs many samples and a measure.
- The logprobs are the model’s, not the sampler’s. Each line is a sampled token, its logprob under the uncached model at temperature 1, the quantity llama-server reports by default, and its rank among all 512 tokens. The fifth token,
" it", had probability and rank 43, and was drawn anyway: at temperature 1 with no truncation nothing prevents it. Top-k 40 would have excluded it. Top-p 0.9 would not: at that position the favourite has only 0.223 and the nucleus holds 56 tokens," it"among them. Min-p 0.1 would have, keeping only the 9 tokens above 0.0223.
Further reading
- Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes and Yejin Choi, “The Curious Case of Neural Text Degeneration”, ICLR (2020). Why maximisation-based decoding such as greedy and beam search produces repetitive text, why pure sampling wanders into the tail, and nucleus (top-p) sampling as the smallest set of tokens with cumulative probability at least a threshold, this chapter’s .
- Angela Fan, Mike Lewis and Yann Dauphin, “Hierarchical Neural Story Generation”, ACL (2018). Story generation that samples from the most likely tokens at each step, the top-k sampling llama.cpp’s
top_kimplements. - Nitish Shirish Keskar, Bryan McCann, Lav R. Varshney, Caiming Xiong and Richard Socher, “CTRL: A Conditional Transformer Language Model for Controllable Generation” (2019). Section 4.1 defines penalized sampling, dividing the logits of already generated tokens by inside the softmax and recommending with greedy decoding: the repetition penalty, before llama.cpp’s fix for negative logits.
- Minh Nhat Nguyen, Andrew Baker, Clement Neo, Allen Roush, Andreas Kirsch and Ravid Shwartz-Ziv, “Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs”, ICLR (2025). Min-p: a truncation threshold scaled by the top token’s probability, and its behaviour at high temperatures.
- Reiner Pope, Sholto Douglas, Aakanksha Chowdhery, Jacob Devlin, James Bradbury, Anselm Levskaya, Jonathan Heek, Kefan Xiao, Shivani Agrawal and Jeff Dean, “Efficiently Scaling Transformer Inference”, MLSys (2023). The costs of generation at scale, with the KV cache’s memory as a central constraint, and how multiquery attention’s smaller cache allows much longer contexts.
- Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, Federico Lebrón and Sumit Sanghai, “GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints”, EMNLP (2023). Grouped-query attention, in which groups of query heads share one key and value head, shrinking the KV cache by the group size.
- llama.cpp,
tools/server/README.md: the sampling parameters of each request,n_probsandpost_sampling_probs,cache_prompt, thetimingsobject, and the--samplers,-c,-npand--cache-type-k/--cache-type-voptions. The sampler implementations are insrc/llama-sampler.cpp, the default chain incommon/common.h.