Inside a Decoder-Only LM: Logits, Generation and the KV Cache
Every chat model you used in Generative AI & LLMs is, at its core, a function from a sequence of token ids to a table of logits: one row per position, one column per vocabulary entry. Training uses all rows at once; generation uses only the last row, picks a token, appends it and calls the function again. This lesson makes that loop concrete: the shifted next-token loss, greedy and sampled decoding written from scratch, and the KV cache that makes generation affordable, implemented and checked for exactness, with its memory bill computed for a realistic model. The recorded part shows the same objects in Hugging Face Transformers. You trained a character-level decoder in Training a Tiny Character Transformer; here the focus is on the inference side.
Logits for every position, loss on shifted targets
A decoder-only model maps token ids to logits . Because of the causal mask, depends only on , so it can be trained to predict . The training loss over one sequence is the mean cross-entropy of the shifted targets:
The last logit row has no target inside the sequence; it is exactly the row generation uses. To see the bookkeeping without a transformer in the way, the first example uses the simplest decoder there is: a bigram model whose logits at position are a learned row for token (here filled with smoothed log-counts from a tiny original corpus). Its forward pass still returns (T, V) logits, and the same loss and generation code would work unchanged with a transformer.
import numpy as np
corpus = ("the ferry leaves the harbour at noon . the ferry returns at dusk . "
"the bus leaves the station at noon . the bus returns at night . "
"the ferry is late . the bus is early .").split()
vocab = sorted(set(corpus))
idx = {w: i for i, w in enumerate(vocab)}
V = len(vocab)
# A "model" whose logits for the next token depend only on the current token: a bigram table
# stored as log-probabilities (add-0.1 smoothing). Its forward pass is a row lookup per position.
counts = np.full((V, V), 0.1)
for a, b in zip(corpus[:-1], corpus[1:]):
counts[idx[a], idx[b]] += 1
W = np.log(counts / counts.sum(1, keepdims=True)) # (V, V): logits = W[token]
def forward(ids): # (T,) -> logits (T, V): one row per position
return W[ids]
def log_softmax(z):
z = z - z.max(-1, keepdims=True)
return z - np.log(np.exp(z).sum(-1, keepdims=True))
seq = np.array([idx[w] for w in "the bus leaves the harbour at dusk .".split()])
logits = forward(seq)
print("tokens", seq.shape, "-> logits", logits.shape, f"(V = {V})")
# Shifted next-token loss: position t predicts token t + 1, so drop the last logit and the first token.
lp = log_softmax(logits[:-1])
nll = -lp[np.arange(len(seq) - 1), seq[1:]]
for w, nxt, l in zip([vocab[i] for i in seq[:-1]], [vocab[i] for i in seq[1:]], nll):
print(f" after {w:8s} predict {nxt:8s} loss {l:.3f}")
print(f"mean loss {nll.mean():.3f} nats, perplexity {np.exp(nll.mean()):.2f}")
def generate(prompt, n, temperature=0.0, top_k=None, seed=0):
rng = np.random.default_rng(seed)
ids = [idx[w] for w in prompt.split()]
for _ in range(n):
z = forward(np.array(ids))[-1] # only the last position's logits are used
if temperature == 0:
nxt = int(z.argmax()) # greedy
else:
z = z / temperature
if top_k is not None: # keep the k largest logits
z = np.where(z >= np.sort(z)[-top_k], z, -np.inf)
p = np.exp(z - z.max()); p /= p.sum()
nxt = int(rng.choice(V, p=p))
ids.append(nxt)
return " ".join(vocab[i] for i in ids)
print("greedy :", generate("the", 12))
print("T=1.0 :", generate("the", 12, temperature=1.0))
print("T=1.0, top-3:", generate("the", 12, temperature=1.0, top_k=3))
print("T=2.0 :", generate("the", 12, temperature=2.0))tokens (8,) -> logits (8, 15) (V = 15)
after the predict bus loss 1.120
after bus predict leaves loss 1.409
after leaves predict the loss 0.511
after the predict harbour loss 2.156
after harbour predict at loss 0.821
after at predict dusk loss 1.609
after dusk predict . loss 0.821
mean loss 1.207 nats, perplexity 3.34
greedy : the bus is early . the bus is early . the bus is
T=1.0 : the ferry is at . the station ferry returns at noon late .
T=1.0, top-3: the ferry is at dusk night returns at noon . the harbour .
T=2.0 : the harbour bus . . the station late night is station noon .
- Eight tokens give eight logit rows; the loss uses the first seven, each scored on the next token. "harbour" after "the" costs 2.156 nats ("the harbour" occurs once among 8 uses of "the" in the corpus), "the" after "leaves" only 0.511. Mean 1.207 nats, perplexity 3.34 (Perplexity).
- Greedy decoding takes the argmax every time and falls into a loop, "the bus is early . the bus is early .": with one token of context the model's state repeats, so its choices repeat. Larger models loop less, but greedy text is still notoriously repetitive.
- Sampling at draws from the model's distribution and produces varied, sometimes odd text ("the station ferry returns"). Top- removes everything outside the most likely tokens before sampling, cutting the long tail; flattens the distribution and the text falls apart. The trade-offs, and top-, are in Sampling and Sampling and Temperature.
The KV cache
Generating token with a transformer needs the attention of position over keys and values of positions . Without a cache, each step runs the whole prefix through the model again, recomputing keys and values that have not changed: the first positions' and are fixed once computed, because the causal mask means later tokens never affect them. A KV cache stores them per layer and per head; each step computes , , for the new token only, appends and , and attends over the cache.
The example implements a 2-layer, 2-head decoder in NumPy twice: forward_full recomputes everything at every step, forward_step uses a cache. The prompt is first pushed through the cache ("prefill"); then both decode 8 tokens greedily.
import numpy as np
rng = np.random.default_rng(0)
V, E, h, L = 20, 16, 2, 2 # vocabulary, width, heads, layers
dh = E // h
emb = rng.normal(0, 1, (V, E))
pos = rng.normal(0, 0.3, (64, E))
layers = [{k: rng.normal(0, E ** -0.5, (E, E)) for k in ("q", "k", "v", "o")} for _ in range(L)]
W_out = rng.normal(0, E ** -0.5, (E, V))
def softmax(z):
z = z - z.max(-1, keepdims=True)
e = np.exp(z)
return e / e.sum(-1, keepdims=True)
def heads(x): # (T, E) -> (h, T, dh)
return x.reshape(len(x), h, dh).transpose(1, 0, 2)
def forward_full(ids):
"""No cache: recompute every position. Returns the logits of the last position."""
x = emb[ids] + pos[:len(ids)]
T = len(ids)
mask = np.tril(np.ones((T, T), dtype=bool))
for p in layers:
q, k, v = heads(x @ p["q"]), heads(x @ p["k"]), heads(x @ p["v"])
A = softmax(np.where(mask, q @ k.transpose(0, 2, 1) / np.sqrt(dh), -np.inf))
x = x + (A @ v).transpose(1, 0, 2).reshape(T, E) @ p["o"]
return x[-1] @ W_out
def forward_step(token, t, cache):
"""One new token at position t. cache[l] holds K and V of positions 0..t-1 for layer l."""
x = emb[token] + pos[t] # (E,): only the new position is computed
for l, p in enumerate(layers):
q = (x @ p["q"]).reshape(h, 1, dh)
k_new, v_new = (x @ p["k"]).reshape(h, 1, dh), (x @ p["v"]).reshape(h, 1, dh)
K = np.concatenate([cache[l][0], k_new], axis=1) if cache[l] else k_new
Vv = np.concatenate([cache[l][1], v_new], axis=1) if cache[l] else v_new
cache[l] = (K, Vv) # append, never recompute
A = softmax(q @ K.transpose(0, 2, 1) / np.sqrt(dh)) # (h, 1, t+1): no mask needed
x = x + (A @ Vv).reshape(E) @ p["o"]
return x @ W_out
prompt = [3, 7, 1]
ids_full, ids_cache = list(prompt), list(prompt)
cache = [None] * L
for t, tok in enumerate(prompt[:-1]): # "prefill": push the prompt through the cache
forward_step(tok, t, cache)
max_diff = 0.0
for step in range(8): # greedy decoding both ways
z_full = forward_full(np.array(ids_full))
z_cache = forward_step(ids_cache[-1], len(ids_cache) - 1, cache)
max_diff = max(max_diff, float(np.abs(z_full - z_cache).max()))
ids_full.append(int(z_full.argmax()))
ids_cache.append(int(z_cache.argmax()))
print("tokens without cache:", ids_full)
print("tokens with cache :", ids_cache)
print("logits equal up to rounding (max difference < 1e-12):", max_diff < 1e-12)
print("cache of layer 0: K", cache[0][0].shape, "V", cache[0][1].shape, "= (heads, positions, head dim)")
T = len(ids_full)
print("K/V rows computed per layer, no cache:", sum(range(len(prompt), T)), " with cache:", T - 1)tokens without cache: [3, 7, 1, 11, 16, 19, 9, 17, 9, 14, 12]
tokens with cache : [3, 7, 1, 11, 16, 19, 9, 17, 9, 14, 12]
logits equal up to rounding (max difference < 1e-12): True
cache of layer 0: K (2, 10, 8) V (2, 10, 8) = (heads, positions, head dim)
K/V rows computed per layer, no cache: 52 with cache: 10
The two loops produce the same 11 tokens and the same logits up to floating-point rounding: the cache is an exact optimisation, not an approximation. Note that forward_step needs no mask: the cache only contains the past. The cache of layer 0 holds keys and values of shape (2, 10, 8): 2 heads, 10 positions (every token except the last generated one, which has not been fed back yet), head dimension 8. Without a cache the 8 steps computed 52 key/value rows per layer; with it, 10. The saving grows quadratically with the length: generating tokens without a cache costs projections and attention work, with a cache and . The derivation is in KV Cache.
What the cache costs in memory
Per token, each layer stores one key and one value vector for each KV head. With layers, KV heads of dimension , tokens, batch and bytes per number:
With ordinary multi-head attention , the model width, giving per sequence. Two variants share keys and values between query heads to shrink it: grouped-query attention (GQA) uses a few KV heads, each shared by a group of query heads, and multi-query attention (MQA) uses a single one. The example computes the bill for a 32-layer model of width 4096 (32 heads of 128), the shape of Llama-2-7B, at 4096 tokens in 16-bit numbers.
def kv_cache_bytes(layers, kv_heads, head_dim, tokens, batch=1, bytes_per=2):
return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per # 2 = keys and values
GiB = 2 ** 30
# A 32-layer model with width 4096 = 32 query heads x 128, at 4096 tokens, 16-bit values.
for name, kv_heads in [("MHA (32 KV heads)", 32), ("GQA (8 KV heads)", 8), ("MQA (1 KV head)", 1)]:
per_seq = kv_cache_bytes(32, kv_heads, 128, 4096)
print(f"{name:18s}: {per_seq / GiB:6.3f} GiB per sequence, "
f"{kv_cache_bytes(32, kv_heads, 128, 4096, batch=32) / GiB:5.1f} GiB for a batch of 32")
print(f"per token (MHA): {kv_cache_bytes(32, 32, 128, 1) / 2**10:.0f} KiB")
print(f"weights of a 7B model in 16 bits: {7e9 * 2 / GiB:.1f} GiB")MHA (32 KV heads) : 2.000 GiB per sequence, 64.0 GiB for a batch of 32
GQA (8 KV heads) : 0.500 GiB per sequence, 16.0 GiB for a batch of 32
MQA (1 KV head) : 0.062 GiB per sequence, 2.0 GiB for a batch of 32
per token (MHA): 512 KiB
weights of a 7B model in 16 bits: 13.0 GiB
Full multi-head attention needs 2 GiB per sequence, 512 KiB per token. A batch of 32 such sequences needs 64 GiB of cache, far more than the 13.0 GiB of the 7B model's own weights. GQA with 8 KV heads (as in Llama-2-70B, Llama 3 and Mistral 7B) cuts it 4 times, to 0.5 GiB per sequence; MQA 32 times. That is why GQA became standard: at long contexts and large batches, the cache, not the weights, decides how many requests fit on a GPU. Paged attention (vLLM), cache quantisation and sliding windows are the other levers (Fast Inference).
The same objects in Transformers
The course image has no real pretrained generative LLM. sshleifer/tiny-gpt2 has GPT-2's exact architecture and tokenizer but random, tiny weights (width 2), so its text is gibberish; it is used here for shapes and APIs only. Everything below works the same with real GPT-2 or Llama weights.
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers.utils import logging
logging.set_verbosity_error()
torch.manual_seed(0)
name = "sshleifer/tiny-gpt2" # GPT-2 shape, RANDOM tiny weights: output is gibberish
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name).eval()
c = model.config
print(f"layers {c.n_layer}, width {c.n_embd}, heads {c.n_head}, vocab {c.vocab_size}, "
f"parameters {sum(p.numel() for p in model.parameters()):,}")
enc = tok("The ferry leaves the harbour at noon", return_tensors="pt")
ids = enc["input_ids"]
with torch.no_grad():
out = model(**enc, labels=ids) # labels = inputs: the model shifts them itself
print("input_ids", tuple(ids.shape), "-> logits", tuple(out.logits.shape))
manual = F.cross_entropy(out.logits[0, :-1], ids[0, 1:]) # position t predicts token t + 1
print(f"loss from the model {out.loss.item():.4f}, shifted by hand {manual.item():.4f}, ln V = {torch.log(torch.tensor(50257.)).item():.4f}")
# The KV cache object: one (keys, values) pair per layer.
with torch.no_grad():
out = model(**enc, use_cache=True)
pkv = out.past_key_values
k0, v0 = pkv.layers[0].keys, pkv.layers[0].values
print("cache:", type(pkv).__name__, "with", len(pkv.layers), "layers; layer 0 keys", tuple(k0.shape), "values", tuple(v0.shape))
# Next step with the cache: feed ONLY the new token. Same logits as recomputing everything.
nxt = out.logits[:, -1].argmax(-1, keepdim=True)
with torch.no_grad():
step = model(input_ids=nxt, past_key_values=pkv, use_cache=True)
full = model(input_ids=torch.cat([ids, nxt], 1))
print("cached step logits", tuple(step.logits.shape), "== full recompute:",
torch.allclose(step.logits[0, -1], full.logits[0, -1], atol=1e-6))
print("cache length now:", step.past_key_values.get_seq_length())
# generate(): greedy and sampling. Random weights, so the text is nonsense; the API is the point.
g1 = model.generate(**enc, max_new_tokens=6, do_sample=False, pad_token_id=tok.eos_token_id)
g2 = model.generate(**enc, max_new_tokens=6, do_sample=True, temperature=0.8, top_k=50,
pad_token_id=tok.eos_token_id)
g3 = model.generate(**enc, max_new_tokens=6, do_sample=False, use_cache=False, pad_token_id=tok.eos_token_id)
print("greedy :", g1[0, ids.shape[1]:].tolist(), repr(tok.decode(g1[0, ids.shape[1]:])))
print("sampled:", g2[0, ids.shape[1]:].tolist())
print("greedy without cache gives the same tokens:", torch.equal(g1, g3))layers 2, width 2, heads 2, vocab 50257, parameters 102,714
input_ids (1, 7) -> logits (1, 7, 50257)
loss from the model 10.8471, shifted by hand 10.8471, ln V = 10.8249
cache: DynamicCache with 2 layers; layer 0 keys (1, 2, 7, 1) values (1, 2, 7, 1)
cached step logits (1, 1, 50257) == full recompute: True
cache length now: 8
greedy : [5087, 5087, 5087, 5087, 5087, 5087] ' factors factors factors factors factors factors'
sampled: [11377, 45292, 28986, 11976, 26002, 27714]
greedy without cache gives the same tokens: True
- Logits
(1, 7, 50257): one row per position, one column per token of GPT-2's vocabulary. - Passing
labels=input_idsmakes the model shift internally; the loss (10.8471) equals our hand-shifted cross-entropy exactly. It is slightly above , the loss of a uniform guess, as expected from random weights. - The cache is a
DynamicCachewith one entry per layer; layer 0's keys are(batch, heads, positions, head dim)=(1, 2, 7, 1). (Width 2 split over 2 heads gives head dimension 1: this model really is tiny.) Older Transformers versions returned a tuple of(key, value)tuples instead; code that indexespast_key_values[0][0]may need updating. - One cached step: feeding only the new token with
past_key_valuesgives the same last-position logits as recomputing the full 8-token sequence, and the cache length becomes 8. generatewraps the loop: greedy (do_sample=False) repeats one token six times, " factors", the degenerate loop from the bigram example in extreme form; sampling withtemperatureandtop_kgives different ids each time (seeded here).use_cache=Falsegives identical tokens, only slower. GPT-2 has no padding token, sopad_token_id=tok.eos_token_idis passed, the usual convention.
Pitfalls
- Forgetting the shift. Comparing with instead of trains the identity function. In Transformers, pass
labels=input_idsand let the model shift; when computing your own loss, shift yourself. - Shifting twice. Passing already-shifted labels to a model that shifts internally trains it to predict two tokens ahead.
- Wrong positions with a cache. The new token's position is the cache length, not 0. Hand-written loops that reset positions produce degraded text without any error.
- Left versus right padding in batched generation. Decoder-only models generate after the last token, so batches must be left-padded (
tok.padding_side = "left") with an attention mask; right padding puts pad tokens between the prompt and the new text. - Budgeting memory by weights only. At long contexts or large batches the KV cache dominates (64 GiB against 13 GiB in the example).
- Greedy decoding for open-ended text. It loops; use sampling with a moderate temperature and top-/top-, or a repetition penalty, unless you need determinism (then greedy is fine for short, constrained outputs).
Practice
- In
ig1.py, compute by hand which token greedy decoding picks after "at", using the corpus. Why can greedy decoding never produce "dusk" after "at"?
Answer
After "at" the corpus has "noon" twice, "dusk" once and "night" once, so greedy always picks "noon". "dusk" has a lower probability and argmax never selects it; only sampling can.
- In
ig2.py, how many key/value rows per layer would 100 generated tokens after a 3-token prompt need without and with a cache?
Answer
Without: the step lengths run from 3 to 102, rows. With a cache: every position once, 102 rows (all but the last generated token).
- Compute the KV cache of one 32,768-token sequence for a model with 80 layers, 8 KV heads of dimension 128, in 16-bit numbers.
Answer
bytes, 10 GiB (this is the shape of a 70B model with GQA).
- In the recorded example, why is the loss slightly above even though the weights are random?
Answer
Random logits are not exactly uniform. For targets unrelated to the logits (roughly uniform over the vocabulary), any deviation from the uniform distribution makes the expected cross-entropy larger than (Jensen's inequality), so a random model scores a little worse than a uniform guess.
Test yourself
A decoder-only model receives 10 tokens. How many next-token losses does one training sequence contribute?
- 1
- 9
- 10
- 45
Why are cached keys and values of earlier positions still correct after new tokens are added?
- Because they are recomputed each step
- Because the causal mask means later tokens never influence earlier positions' keys and values
- Because the cache is quantised
- Because attention is linear
KV cache size for one sequence with multi-head attention is…
- independent of
Grouped-query attention with 8 KV heads instead of 32 changes the KV cache by…
- nothing
- a factor 4 smaller
- a factor 32 smaller
- a factor 4 larger
Why does sshleifer/tiny-gpt2 produce nonsense like ' factors factors factors'?
- The tokenizer is broken
- Its weights are random; it has GPT-2's architecture only, so it is useful for shapes and APIs
- Greedy decoding always repeats
- The cache is disabled