The KV cache
Implement a preallocated KV cache per layer with separate prefill and decoding paths, correct RoPE positions and GQA support; verify token-by-token greedy-generation equality with and without caching, and measure speedup and memory.
After this lesson you can
- Explain why causal prefix keys and values can be cached.
- Implement a preallocated per-layer KV cache with valid lengths.
- Split prefill and decoding using absolute positions and the correct causal mask.
- Demonstrate token-by-token equality of cached and uncached greedy generation, and compare their logits in FP32 and bf16.
- Measure cache speedup and memory as a function of context length.
Before you start
Work repeated by the baseline
The engine from the previous lesson generates as follows: run the model on the prompt, choose the most probable token, append it and rerun the model on the entire prefix. To produce token 500 it projects the previous 499 positions again, layer by layer, although it already did so in calls 499, 498 and every earlier one. If outputs at those positions never changed, that work would be wasted.
They do not change because of the causal mask: no position can look to its right, so adding text on the right changes nothing already calculated. A new position only needs past keys and values at each layer. If stored, each call after the prompt processes one position instead of all of them. That memory is the KV cache, introduced conceptually in the transformers module and now built, proved and measured on the custom model.
The figure shows work in both strategies. Each row is a model call; each column is an input position, starting at 0 as in the code.
What to observe:
- Without cache, work is a trapezoid; with cache, one row (prefill) plus a diagonal. For a prompt of tokens and generated tokens, the call producing token processes positions without cache and one with cache, except prefill, which processes all prompt positions in both.
- The first row is identical in both modes. The first token comes from prefill. Cache does not accelerate it; it makes later work cheaper.
- The row ratio grows without limit with . For and it is ; with it is already .
- Attention does not disappear. Even with cache, the new query is compared with every prior key: what is removed is recomputing those keys, not reading them again.
Both sums fit on one line. Without cache, calls process prefixes of lengths ; with cache, prefill processes rows and each of the remaining calls processes one:
This counts rows passing through each positionwise projection (Q, K, V, attention output and MLP) in every layer. With fixed , and . Attention worsens by another degree: an uncached call with positions scores causal pairs, and the generation sum is ; with cache, a call with valid positions scores pairs and the sum is . Cache removes one degree of growth from each term, but full-context attention remains quadratic in generated length. This quadratic term is addressed by the project’s long-context attention kernels.
Why the past can be stored
The statement “adding text on the right does not change the past” is a theorem with assumptions, each of which will later appear as a real error if violated. Fix a decoder transformer like the baseline and call the representation of position at the input of layer , with for embeddings, and its key and value in that layer.
The proof is induction over layers. Build it yourself:
Step 1 of 4. What is the base case, ?
The theorem says more than “something can be stored.” The only way a future position reads the past is attention, and attention reads only and . Past representations and queries are never reused. Thus the pair for all layers is exactly the state to retain: storing less would require recomputation, and storing more, such as queries or MLP outputs, adds nothing. The other side of that fact is that cache is the only channel through which the past influences the future, making it a natural point to intervene in the model. Replacing a position’s value in one layer changes everything generated afterwards without touching weights, and the mechanistic interpretability project (P11) will use interventions of this kind to locate what information travels where.
Each assumption can fail in its own way. Changing weights mid-generation breaks (i). Counting positions from the end breaks (ii). Batch normalization along the sequence breaks (iii). Assumption (iv) fails if the mask exposes the future, as happens when a block of multiple new tokens is processed without a mask, shown shortly. Note also what the theorem does not say: that two floating-point implementations of the same calculation produce identical bits. That gap between function and program is central to the lab.
Cache design: shape, capacity and valid length
Each contract decision addresses a concrete error. Preallocation avoids the naive alternative, torch.cat at every step, which copies the whole cache to append one position: bytes per step and total, while fragmenting the allocator. The counter separates capacity from content: reserved memory contains garbage (torch.empty does not initialize), and only the counter identifies state. The pos == s check turns an indexing mistake that could otherwise produce plausible false outputs into an immediate exception. A counter per layer allows checking all layers advance together; the lab checks this after each generation.
The cache stores K and V before expanding them for GQA. With query heads and key and value heads, each KV head serves queries; expansion (repeat_interleave on the head axis) occurs when reading in each call. Storing the expanded version would multiply memory by without adding information. Cache memory for valid positions and bytes per component is
where 2 counts K and V. Physical reservation uses instead of and is paid upfront. For SmolLM2-135M (, , , ) in bf16, each token costs bytes, about 22.5 KiB. This is the transformers module’s cache memory calculation, now with a model you will run.
What to observe:
- Reservation stays fixed during generation; the valid part changes. Fixed capacity pays the maximum from the first token. Matching capacity to each request saves memory but requires knowing duration in advance, which a server does not. Paged cache addresses that dilemma with block reservations.
- GQA divides memory by . Llama 2 7B uses multi-head attention (, ): 512 KiB per token. Llama 3 8B has nearly the same shape with : 128 KiB per token, four times less. The idea comes from multi-query attention by Shazeer (2019), which shares one KV head to reduce decode memory traffic, and its grouped generalization by Ainslie et al. (2023).
- Cache can outweigh the model. The “context with KV equal to weights” readout is the token count at which one sequence’s cache occupies as much as bf16 weights: about 11,700 for SmolLM2-135M, 25,700 for Llama 2 7B and 122,500 for Llama 3 8B. With batch the threshold is divided by . In serving, cache rather than weights can limit concurrent requests; Pope et al. (2022) analyze this tradeoff.
- Avoided FLOPs grow as . They are the avoided rows in the preceding formula times the cost of one block’s matrices.
One final design detail: the cache stores keys already rotated with RoPE. Each key is rotated once with its absolute position in the call that writes it, and is never touched again. The next section explains why that works and how it breaks.
def kv_bytes(layers, kv_heads, head_dim, tokens, batch=1, bytes_per=2):
return 2 * layers * batch * kv_heads * tokens * head_dim * bytes_per
print("SmolLM2-135M, bytes por token:", kv_bytes(30, 3, 64, 1))
print("Llama 2 7B y Llama 3 8B, KiB por token:", kv_bytes(32, 32, 128, 1) / 1024, kv_bytes(32, 8, 128, 1) / 1024)
print("SmolLM2-135M, 2048 posiciones, MiB:", kv_bytes(30, 3, 64, 2048) / 2**20)
for P, G in [(6, 10), (6, 16), (16, 2048)]:
rows_sin = sum(P + i for i in range(G)) # cada llamada reproyecta todo
rows_con = P + (G - 1) # prefill y una fila por paso
pairs_sin = sum((P + i) * (P + i + 1) // 2 for i in range(G))
pairs_con = P * (P + 1) // 2 + sum(P + i for i in range(1, G))
assert rows_sin == G * P + G * (G - 1) // 2 and rows_con == P + G - 1
assert rows_sin - rows_con == (G - 1) * P + (G - 1) * (G - 2) // 2
print(f"P={P}, G={G}: filas {rows_sin} frente a {rows_con} ({rows_sin / rows_con:.1f}x), "
f"pares {pairs_sin} frente a {pairs_con} ({pairs_sin / pairs_con:.1f}x)")Prefill and decoding: a position contract
Splitting prefill and decoding divides generation into two call types to the same model with the same cache:
- Prefill. All prompt positions enter together. Each layer computes Q, K and V in parallel, writes K and V to positions and applies attention with a square causal mask. Only the final position’s logit row is needed: it produces the first token.
- Decoding. One token enters, the last chosen, at the absolute position following those already written. Each layer computes its Q, K and V, writes K and V at that position and compares its query to every valid key, including its own. No mask is needed: no written key is in its future.
Watch the counter. The token just chosen is not yet in the cache: it is an output, not an already processed input. After generating tokens, the cache contains positions because the last chosen token has never been fed to the model. The lab therefore reserves positions, no more.
Both call types are cases of one rule. Suppose the cache has valid positions and a block of new tokens arrives. Their absolute positions are ; after writing them there are keys. Query in the block () occupies position , and the correct mask is
Prefill is the case , , the usual square mask. Decoding is : the only row sees all columns. With and there is chunked prefill, used by servers to avoid blocking the GPU with long prompts and used as a lab test.
With RoPE the position rule extends to rotations. For each coordinate pair with frequency , the query at position is multiplied by rotation and the key at position by . The property making caching work is that the score depends only on the difference:
Two implementation consequences follow. First, because the key at position is stored already multiplied by , it can be used unchanged by any future query; rotating it again would change the distance. Second, the new query must be rotated at absolute position . If an implementation uses the index inside the call (, always 0 in decoding), its score against a cached key sees distance instead of : the whole past appears positions closer. Keys in the same block, however, receive the same wrong offset and retain relative distances, making the error harder to see in small tests.
What to observe:
- “Upper-left triangle” hides the past. A causal mask built as if rows were positions lets query see only columns . This is exactly what
is_causal=Truein PyTorchscaled_dot_product_attentiondoes for a nonsquare matrix: its documentation says the mask aligns with the upper-left corner. With and , the only query sees only key 0. - “Unmasked block” leaks the future. Reading the entire block without a mask is correct for (set and the warning disappears) and false for : early block rows see later keys.
- “Reset RoPE” keeps the mask intact but corrupts distances to the cache: all subtract . With there is no error, so prefill on this faulty path is correct and the first token always matches. The error can first appear at the second token.
The lab mask implements the absolute-index rule in a line: blocked = arange(S + K)[None, :] > (S + arange(K))[:, None]. Prefill, chunked prefill and one-token decode use the same code; there is no separate corner-case mask.
Lab: the cache from scratch
The lab rewrites the custom model from Llama weight loading here (each Oryon Learn page has its own kernel, so it does not depend on cells in the previous lesson) and adds the cache. It uses the same checkpoint and revision: SmolLM2-135M. CUDA GPU, PyTorch and Transformers are needed. All sizes are read from environment variables with full defaults: 100 prompts of 32 tokens for correctness and outputs up to 2048 tokens for performance. At those values, a full run takes on the order of half an hour on a laptop GPU, estimated from our short run, almost all in long uncached generations; for a first pass, P10_L02_PROMPTS=12, P10_L02_CONTEXTS=16,256,1024, P10_L02_LENGTHS=16,64,256 and P10_L02_REPS=1 reduce it to about three or four minutes. This is the short-run configuration discussed below.
The first cell loads the model directly onto the GPU. It includes a memory guard: a thread measures its own process’s resident memory and terminates it above a limit. A misconfigured uncached sweep can reserve large temporary memory, and terminating the process is preferable to making the machine unresponsive.
import math, os, statistics, threading, time
import torch
import torch.nn.functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
def memory_guard(limit_gb):
"""Termina el proceso si su memoria residente supera limit_gb."""
import psutil
proc = psutil.Process(os.getpid())
def watch():
while True:
if proc.memory_info().rss > limit_gb * 2**30:
print(f"memoria residente por encima de {limit_gb} GB: se aborta", flush=True)
os._exit(3)
time.sleep(0.5)
threading.Thread(target=watch, daemon=True).start()
if not globals().get("GUARD_ON"):
memory_guard(float(os.environ.get("P10_L02_MAX_RSS_GB", "8")))
GUARD_ON = True
MODEL, REV = "HuggingFaceTB/SmolLM2-135M", "93efa2f097d58c2a74874c7e644dbc9b0cee75a2"
assert torch.cuda.is_available(), "El laboratorio necesita una GPU con CUDA"
dev = torch.device("cuda")
torch.backends.cuda.matmul.allow_tf32 = False # FP32 de verdad en la prueba de paridad
torch.backends.cudnn.allow_tf32 = False
tok = AutoTokenizer.from_pretrained(MODEL, revision=REV)
ref = AutoModelForCausalLM.from_pretrained(MODEL, revision=REV, dtype=torch.bfloat16, device_map="cuda",
low_cpu_mem_usage=True, attn_implementation="eager").eval()
cfg = ref.config
rope = getattr(cfg, "rope_parameters", None) or getattr(cfg, "rope_scaling", None) or {}
assert cfg.model_type == "llama" and rope.get("rope_type", rope.get("type", "default")) == "default"
assert not cfg.attention_bias and cfg.hidden_act == "silu"
THETA = rope.get("rope_theta", getattr(cfg, "rope_theta", 10000.0))
L, HQ, HKV = cfg.num_hidden_layers, cfg.num_attention_heads, cfg.num_key_value_heads
D = cfg.hidden_size // HQ
assert HQ % HKV == 0 and D % 2 == 0
INV_FREQ = 1.0 / THETA ** (torch.arange(0, D, 2, device=dev, dtype=torch.float32) / D)
W16 = dict(ref.state_dict()) # comparte memoria con la referencia
W16.setdefault("lm_head.weight", W16["model.embed_tokens.weight"])
W32 = {k: v.float() for k, v in W16.items() if k != "lm_head.weight"} # mismos valores, cálculo en FP32
W32["lm_head.weight"] = W32["model.embed_tokens.weight"] if cfg.tie_word_embeddings else W16["lm_head.weight"].float()
print(f"{MODEL}: {L} capas, h = {HQ}, h_kv = {HKV}, d_h = {D}; KV por token en bf16: {2 * L * HKV * D * 2} bytes")npm run lab and open the connection link.W32 contains the same values as the bf16 checkpoint, converted to float32 for computation. It cannot recover precision absent from the checkpoint; it runs the same function with much finer rounding, as the equality test shows.
The class follows the definition’s contract exactly. Checks raise ValueError before writing, so a rejected call does not leave the cache partially modified in that layer.
class KVCache:
"""Por capa, K y V preasignados de forma (B, h_kv, C, d_h) y una longitud válida."""
def __init__(self, batch, capacity, dtype):
shape = (batch, HKV, capacity, D)
self.k = [torch.empty(shape, dtype=dtype, device=dev) for _ in range(L)]
self.v = [torch.empty(shape, dtype=dtype, device=dev) for _ in range(L)]
self.length = [0] * L
self.capacity = capacity
def update(self, layer, k, v, pos):
n = k.shape[2]
if pos != self.length[layer]:
raise ValueError(f"capa {layer}: se escribe en {pos} pero hay {self.length[layer]} posiciones válidas")
if pos + n > self.capacity:
raise ValueError(f"capa {layer}: {pos} + {n} supera la capacidad {self.capacity}")
self.k[layer][:, :, pos:pos + n] = k
self.v[layer][:, :, pos:pos + n] = v
self.length[layer] = pos + n
def get(self, layer):
n = self.length[layer]
return self.k[layer][:, :, :n], self.v[layer][:, :, :n]
def reset(self):
self.length = [0] * L
def nbytes(self):
return sum(t.numel() * t.element_size() for t in self.k + self.v)npm run lab and open the connection link.The forward step matches the baseline with three changes: it receives start position pos, builds a mask using absolute indices and, if a cache exists, writes to it and reads its valid portion. The bug argument deliberately injects two mistakes from the preceding section; a test that fails to detect an injected error is ineffective, which we will check.
def rms_norm(x, w):
xf = x.float()
return (xf * torch.rsqrt(xf.square().mean(-1, keepdim=True) + cfg.rms_norm_eps)).to(x.dtype) * w
def rotate_half(x):
a, b = x.chunk(2, dim=-1)
return torch.cat((-b, a), dim=-1)
def forward(W, ids, cache=None, pos=0, last_only=True, bug=None):
"""Logits de las posiciones pos..pos+T-1. Con caché, las anteriores se leen de ella."""
B, T = ids.shape
assert cache is not None or pos == 0
x = F.embedding(ids, W["model.embed_tokens.weight"])
absolute = torch.arange(pos, pos + T, device=dev)
rope_pos = absolute - pos if bug == "rope-relativa" else absolute # el error: reiniciar en cada llamada
ang = torch.outer(rope_pos.float(), INV_FREQ)
ang = torch.cat((ang, ang), dim=-1)
cos, sin = ang.cos().to(x.dtype)[None, None], ang.sin().to(x.dtype)[None, None]
# La fila i es la posición absoluta pos+i y ve las columnas j <= pos+i.
blocked = torch.arange(pos + T, device=dev)[None, :] > absolute[:, None]
for l in range(L):
p = f"model.layers.{l}."
h = rms_norm(x, W[p + "input_layernorm.weight"])
q = F.linear(h, W[p + "self_attn.q_proj.weight"]).view(B, T, HQ, D).transpose(1, 2)
k = F.linear(h, W[p + "self_attn.k_proj.weight"]).view(B, T, HKV, D).transpose(1, 2)
v = F.linear(h, W[p + "self_attn.v_proj.weight"]).view(B, T, HKV, D).transpose(1, 2)
q = q * cos + rotate_half(q) * sin
k = k * cos + rotate_half(k) * sin # K se guarda ya rotada con su posición
if cache is not None:
cache.update(l, k, v, pos)
k, v = cache.get(l)
if bug == "leer-todo": # el error: toda la capacidad, escrita o no
k, v = cache.k[l], cache.v[l]
k = k.repeat_interleave(HQ // HKV, dim=1) # GQA: cada cabeza KV sirve a su grupo
v = v.repeat_interleave(HQ // HKV, dim=1)
s = (q @ k.transpose(-1, -2)) / math.sqrt(D)
if bug != "leer-todo":
s = s.masked_fill(blocked, torch.finfo(s.dtype).min)
a = F.softmax(s, dim=-1, dtype=torch.float32).to(q.dtype)
x = x + F.linear((a @ v).transpose(1, 2).reshape(B, T, HQ * D), W[p + "self_attn.o_proj.weight"])
h = rms_norm(x, W[p + "post_attention_layernorm.weight"])
gate = F.silu(F.linear(h, W[p + "mlp.gate_proj.weight"]))
x = x + F.linear(gate * F.linear(h, W[p + "mlp.up_proj.weight"]), W[p + "mlp.down_proj.weight"])
if last_only:
x = x[:, -1:]
return F.linear(rms_norm(x, W["model.norm.weight"]), W["lm_head.weight"]).float()
@torch.inference_mode()
def generate(W, ids, n_new, use_cache, bug=None, keep_logits=False):
"""Voraz. Devuelve los n_new tokens nuevos y, si se pide, los logits de cada paso."""
B, P = ids.shape
cache = KVCache(B, P + n_new - 1, W["lm_head.weight"].dtype) if use_cache else None
seq, kept = ids, []
for i in range(n_new):
if not use_cache:
logits = forward(W, seq) # recalcula todo el prefijo
elif i == 0:
logits = forward(W, ids, cache, 0) # prefill: P posiciones
else:
logits = forward(W, seq[:, -1:], cache, P + i - 1, bug=bug) # una posición, la P+i-1
nxt = logits[:, -1].argmax(-1, keepdim=True)
seq = torch.cat((seq, nxt), dim=1)
if keep_logits:
kept.append(logits[:, -1])
if use_cache: # todas las capas, a la par
assert cache.length == [P + n_new - 1] * L, cache.length
return (seq[:, P:], torch.stack(kept, 1)) if keep_logits else seq[:, P:]
with torch.inference_mode():
probe = tok("The capital of France is a city with a long history", return_tensors="pt").input_ids.to(dev)
err = (forward(W16, probe, last_only=False) - ref(probe, use_cache=False).logits.float()).abs().max().item()
print(f"paridad con Transformers en bf16, sin caché: error máximo de logits {err:.3g}")npm run lab and open the connection link.Before comparing complete generations, test the pieces separately with cases designed to fail if the contract breaks: writes with gaps, overlaps and exactly at the capacity limit; a free region poisoned with NaN, which would contaminate any over-read; and chunked prefill exercising the rectangular mask with .
with torch.inference_mode():
# 1) Escritura contigua, rechazo de huecos, sobrescrituras y desbordamiento; capas independientes.
c = KVCache(1, 4, torch.float32)
one = torch.ones(1, HKV, 1, D, device=dev)
c.update(0, one, 2 * one, 0)
c.update(0, 3 * one.repeat(1, 1, 2, 1), 4 * one.repeat(1, 1, 2, 1), 1)
k0, v0 = c.get(0)
assert k0.shape == (1, HKV, 3, D) and k0[0, 0, :, 0].tolist() == [1, 3, 3] and v0[0, 0, :, 0].tolist() == [2, 4, 4]
assert c.get(1)[0].shape[2] == 0
for pos, n in [(5, 1), (2, 1), (3, 2)]: # hueco, sobrescritura, desbordamiento
try:
c.update(0, one.repeat(1, 1, n, 1), one.repeat(1, 1, n, 1), pos)
raise AssertionError(f"aceptó pos={pos}, n={n}")
except ValueError:
pass
c.update(0, one, one, 3) # la última posición libre sí cabe
c.reset()
assert c.get(0)[0].shape[2] == 0
print("contrato de KVCache: correcto")
# 2) La zona no escrita no influye: se envenena con NaN y la salida no cambia ni un bit.
ids = tok("Rain falls because water vapour condenses into droplets", return_tensors="pt").input_ids.to(dev)
P = ids.shape[1]
clean, poisoned = KVCache(1, P + 8, torch.float32), KVCache(1, P + 8, torch.float32)
for t in poisoned.k + poisoned.v:
t.fill_(float("nan"))
nxt = forward(W32, ids, clean)[:, -1].argmax(-1, keepdim=True)
forward(W32, ids, poisoned)
a, b = forward(W32, nxt, clean, P), forward(W32, nxt, poisoned, P)
assert torch.equal(a, b) and not b.isnan().any()
print("zona libre con NaN y lectura de la parte válida: logits idénticos bit a bit")
leak = KVCache(1, P + 8, torch.float32)
for t in leak.k + leak.v:
t.fill_(float("nan"))
forward(W32, ids, leak)
print("la misma caché leída entera (error inyectado), logits NaN:", bool(forward(W32, nxt, leak, P, bug="leer-todo").isnan().all()))
# 3) Prefill por trozos: 5 posiciones y después un bloque rectangular con el resto.
full = forward(W32, ids, last_only=False)
c = KVCache(1, P, torch.float32)
forward(W32, ids[:, :5], c, 0, last_only=False)
chunk = forward(W32, ids[:, 5:], c, 5, last_only=False)
print(f"bloque de {P - 5} consultas sobre {P} claves, FP32: error máximo frente al prefill entero "
f"{(chunk - full[:, 5:]).abs().max().item():.2g}")
del c, clean, poisoned, leaknpm run lab and open the connection link.The equality test
The project’s correctness requirement is strict: with greedy decoding, the cache-generated sequence must be identical token by token to the uncached sequence across 100 different prompts. Three design decisions make the test reliable.
- Greedy rather than sampling. With sampling, output is random and a difference does not distinguish error from chance. With
argmax, output is a deterministic function of logits. - Compare logits only with the same history. Once two generations choose different tokens, their next inputs differ and logit comparison mixes two causes. The suite compares step logits up to and including the first divergence, never afterwards.
- FP32 first, then bf16. The theorem concerns exact arithmetic. FP32 is the closest available approximation; bf16 is the production precision. These are different questions and should remain distinct.
For each divergent generation, the cell also records the margin between the top two uncached-path logits at divergence, measured in bf16 ulps (distance between consecutive bf16 numbers at that magnitude: , because bf16 has eight significand bits). It ends with a mutation test: the same suite with an injected RoPE error.
N_PROMPTS = int(os.environ.get("P10_L02_PROMPTS", "100"))
N_NEW = int(os.environ.get("P10_L02_NEW", "32"))
topics = ["why rain falls", "how plants grow", "what causes tides", "how magnets work", "why stars shine",
"how vaccines help", "how computers add", "why ice floats", "how bridges stand", "what makes music"]
frames = ["Explain {} to a student.", "Summarize {} for a beginner.", "Describe {} with an example.",
"Teach {} in simple words.", "Write a short paragraph on {}.", "What should we know about {}?",
"Give an overview of {}.", "Write a brief lesson about {}.", "Help me understand {}.",
"Start an explanation of {}."]
PROMPTS = [f.format(t) for f in frames for t in topics][:N_PROMPTS]
assert len(set(PROMPTS)) == len(PROMPTS)
def first_divergence(a, b):
diff = (a != b).nonzero()
return None if len(diff) == 0 else int(diff[0])
def battery(W, prompts, bug=None):
"""Generación voraz con y sin caché, prompt a prompt (lote 1, sin padding)."""
same, firsts, max_err, ulps = 0, [], 0.0, []
for text in prompts:
ids = tok(text, return_tensors="pt").input_ids.to(dev)
a, la = generate(W, ids, N_NEW, use_cache=False, keep_logits=True)
b, lb = generate(W, ids, N_NEW, use_cache=True, bug=bug, keep_logits=True)
j = first_divergence(a[0], b[0])
upto = N_NEW if j is None else j + 1 # solo logits con el mismo historial
max_err = max(max_err, (la[0, :upto] - lb[0, :upto]).abs().max().item())
if j is None:
same += 1
else:
firsts.append(j + 1) # 1 = el token que sale del prefill
top = la[0, j].topk(2).values
ulp = 2.0 ** (math.floor(math.log2(abs(top[0].item()))) - 7)
ulps.append(round((top[0] - top[1]).item() / ulp))
return same, firsts, max_err, ulps
t0 = time.perf_counter()
for name, W in [("fp32", W32), ("bf16", W16)]:
same, firsts, err, ulps = battery(W, PROMPTS)
print(f"{name}: {same}/{len(PROMPTS)} generaciones idénticas de {N_NEW} tokens; "
f"error máximo de logits con el mismo historial: {err:.3g}")
if firsts:
print(f" primer token distinto: {sorted(firsts)}")
print(f" margen entre los dos mejores logits sin caché allí, en ulps de bf16: {sorted(ulps)}")
n_bug = min(20, len(PROMPTS))
same, firsts, _, _ = battery(W32, PROMPTS[:n_bug], bug="rope-relativa")
print(f"fp32 con RoPE relativa a la llamada (error inyectado): {same}/{n_bug} idénticas; "
f"primer token distinto: mínimo {min(firsts) if firsts else '-'}, mediana {statistics.median(firsts) if firsts else '-'}")
print(f"tiempo de la batería: {time.perf_counter() - t0:.0f} s")npm run lab and open the connection link.What the suite shows
The output discussed is our short verification run, with 12 prompts of 32 tokens (P10_L02_PROMPTS=12); the full run uses 100. Three results each teach something.
In FP32, 12 of 12 generations matched, with maximum logit error while histories match. This is the footprint of floating point: the paths do not execute the same operations (one multiplies matrices of rows, the other one row) and sum in a different order. With that error, a greedy decision would require the top two logits to be less than apart to change, uncommon when the winning logit lies between 10 and 40 as in this model. With 100 prompts and 3200 decisions we expect the same result, 100 of 100; if a generation diverges, inspect its margin before suspecting logic.
With injected RoPE error, 0 of 12 matched, with earliest divergence at the second token (minimum 2, median 3). This is precisely the previous figure’s signature: prefill is correct (), so the first token cannot fail, and sometimes the second does not either because the error moves logits without changing their maximum. The test detects the fault in every prompt.
In bf16, 8 of 12 matched. All four divergences occur late (tokens 14, 24, 30 and 32), and in each the top-two uncached-logit margin was 0 or 1 bf16 ulp. A 0-ulp margin is an exact tie: two tokens share the same representable logit and argmax picks the lower index. Maximum logit error, 0.688, is ten thousand times larger than in FP32 because bf16 rounds each activation to eight significand bits and summation-order differences propagate through 30 layers.
Is the cache wrong? The argument is precise. The theorem guarantees equality of the function; the paths are two floating-point programs approximating it with different rounding, because libraries choose kernels and reduction orders according to operation shape. He and Thinking Machines Lab (2025) call the missing property batch invariance: a row’s result does not depend on how many rows accompany it. Neither path is the exact answer: the uncached path is another rounding of the same function. The suite checks FP32 agreement, where rounding is too fine to change decisions except at near-exact ties, and bf16 divergences occurring only at margins of a few ulps. Bitwise equality in bf16 would require batch-invariant kernels fixing reduction order independently of shape, at a performance cost.
With the library
Transformers implements the same idea in its cache classes (DynamicCache, which grows by concatenation, and preallocated StaticCache like ours), and generate(use_cache=...) toggles it. The cell repeats the comparison with the library and also checks our cache against its own token by token on the first prompts in the suite.
HF_PROMPTS = PROMPTS[:min(20, len(PROMPTS))]
same_hf = same_ours = 0
for text in HF_PROMPTS:
ids = tok(text, return_tensors="pt").input_ids.to(dev)
kw = dict(max_new_tokens=N_NEW, min_new_tokens=N_NEW, do_sample=False, pad_token_id=tok.eos_token_id)
with torch.inference_mode():
hf_cache = ref.generate(ids, use_cache=True, **kw)[0, ids.shape[1]:]
hf_plain = ref.generate(ids, use_cache=False, **kw)[0, ids.shape[1]:]
ours = generate(W16, ids, N_NEW, use_cache=True)[0]
same_hf += bool(torch.equal(hf_cache, hf_plain))
same_ours += bool(torch.equal(ours, hf_cache))
print(f"Transformers bf16, con su caché frente a sin caché: {same_hf}/{len(HF_PROMPTS)} idénticas")
print(f"nuestra caché bf16 frente a la caché de Transformers: {same_ours}/{len(HF_PROMPTS)} idénticas")npm run lab and open the connection link.In the short run, Transformers with its cache matched Transformers without cache in 8 of 12 generations, the same proportion as ours, and our cache matched its cache in 12 of 12. The library shows the same phenomenon for the same reason, and our cached path matches its tokens because it executes the same operations with the same shapes. This provides independent confirmation that bf16 divergences are not a defect of our implementation.
Performance: when the cache shows up on the clock
Cache removes nearly all projected rows. Does it speed up proportionally? The answer depends on what limits a call. In the baseline, each call launches roughly a thousand small kernels from Python, about 45 operations per layer across 30 layers, and the GPU finishes each before the next arrives. While this holds, a call costs the same whether it processes 1 position or 200: a launch floor sets duration rather than work. The last cell measures this first in individual calls and then full generation using the previous lesson’s metrics harness, with synchronization and CPU token availability at each step.
CONTEXTS = [int(x) for x in os.environ.get("P10_L02_CONTEXTS", "16,256,1024,2048").split(",")]
LENGTHS = [int(x) for x in os.environ.get("P10_L02_LENGTHS", "16,64,256,1024,2048").split(",")]
REPS = int(os.environ.get("P10_L02_REPS", "3"))
def median_ms(fn, n=5):
fn()
samples = []
for _ in range(n):
torch.cuda.synchronize()
t0 = time.perf_counter()
fn()
torch.cuda.synchronize()
samples.append(1e3 * (time.perf_counter() - t0))
return statistics.median(samples)
@torch.inference_mode()
def timed(W, ids, n_new, use_cache):
"""Instante en que cada token está en la CPU: TTFT, TPOT, total y tokens."""
B, P = ids.shape
torch.cuda.synchronize()
t0 = time.perf_counter()
cache = KVCache(B, P + n_new - 1, W["lm_head.weight"].dtype) if use_cache else None
seq, marks = ids, []
for i in range(n_new):
if not use_cache:
logits = forward(W, seq)
elif i == 0:
logits = forward(W, ids, cache, 0)
else:
logits = forward(W, seq[:, -1:], cache, P + i - 1)
nxt = logits[:, -1].argmax(-1, keepdim=True)
seq = torch.cat((seq, nxt), dim=1)
nxt.cpu()
marks.append(time.perf_counter())
return marks[0] - t0, (marks[-1] - marks[0]) / max(1, n_new - 1), marks[-1] - t0, seq
with torch.inference_mode():
print("coste de una llamada en bf16, lote 1, mediana de 5:")
gen = torch.Generator(device=dev).manual_seed(0)
for t in CONTEXTS:
x = torch.randint(0, cfg.vocab_size, (1, t), generator=gen, device=dev)
plain = median_ms(lambda: forward(W16, x))
c = KVCache(1, t, torch.bfloat16)
forward(W16, x[:, :-1], c, 0)
def step():
c.length = [t - 1] * L # reescribe siempre la última posición
forward(W16, x[:, -1:], c, t - 1)
print(f" t = {t:5d}: sin caché (t posiciones) {plain:7.1f} ms | con caché (1 posición) {median_ms(step):6.1f} ms")
del c, x
ids = tok(PROMPTS[0], return_tensors="pt").input_ids.to(dev)
P = ids.shape[1]
timed(W16, ids, 4, False), timed(W16, ids, 4, True) # calentamiento
print(f"\ngeneración voraz en bf16, prompt de {P} tokens, mediana de {REPS} repeticiones:")
print(" G | TPOT sin | TPOT con | total sin | total con | aceleración | mismos tokens")
for G in LENGTHS:
runs = {u: [timed(W16, ids, G, u) for _ in range(REPS)] for u in (False, True)}
tpot = {u: 1e3 * statistics.median(r[1] for r in runs[u]) for u in runs}
total = {u: statistics.median(r[2] for r in runs[u]) for u in runs}
equal = torch.equal(runs[False][0][3], runs[True][0][3])
print(f" {G:6d} | {tpot[False]:6.1f} ms | {tpot[True]:6.1f} ms | {total[False]:7.2f} s | {total[True]:7.2f} s |"
f" {total[False] / total[True]:10.2f}x | {'sí' if equal else 'no'}")
# Memoria: la caché frente a la fórmula y el pico adicional de cada ruta.
before = torch.cuda.memory_allocated()
c = KVCache(1, P + max(LENGTHS) - 1, torch.bfloat16)
formula = 2 * L * HKV * (P + max(LENGTHS) - 1) * D * 2
print(f"\ncaché para {P + max(LENGTHS) - 1} posiciones: fórmula {formula / 2**20:.2f} MiB, "
f"tensores {c.nbytes() / 2**20:.2f} MiB, asignador {(torch.cuda.memory_allocated() - before) / 2**20:.2f} MiB")
assert c.nbytes() == formula
del c
for u in (False, True):
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
timed(W16, ids, max(LENGTHS), u)
print(f"pico de memoria sobre lo ya asignado, {max(LENGTHS)} tokens {'con' if u else 'sin'} caché: "
f"{(torch.cuda.max_memory_allocated() - base) / 2**20:.1f} MiB")
del ids
torch.cuda.empty_cache()npm run lab and open the connection link.In the short run (contexts up to 1024 and outputs up to 256 tokens, one repetition on a laptop GPU shared with other processes), an uncached call cost 20.1 ms at 16 positions, 23.9 ms at 256 and 54.5 ms at 1024; a cached call cost 23.7 to 27.7 ms across the three contexts. Processing 256 positions cost the same as processing one. In complete generation, speedups were 1.01, 0.96 and 0.95 for 16, 64 and 256 tokens, with the same tokens on both paths. Cache removed 90% to 99% of projected rows without affecting the clock.
We repeated the same short run later under heavier machine load and the floor rose: 36 to 38 ms per cached call across all three contexts, 37.2 and 34.3 ms uncached at 16 and 256 positions, and 60.2 ms at 1024. Speedups were 0.96, 1.06 and 1.13. The two runs differ by nearly two tenths, 0.95 versus 1.13 at 256 tokens, which with one repetition on a shared machine is measurement noise; they agree on the main observation: for this model and these lengths speedup remains near 1. The two correctness figures repeated exactly, 12 of 12 FP32 and 8 of 12 bf16 at the same divergent tokens, because they do not depend on time. For the full run use several repetitions and inspect dispersion before interpreting 5% differences: each cached-path layer launches two extra kernels, K and V writes, and when launch sets time that detail can move the result either way.
The floor explains this. A call costs the maximum of kernel launch time and GPU execution time. With 135 million parameters and fewer than a thousand positions, the GPU finishes each kernel before Python launches the next, so removing work shortens nothing. Cache begins to matter only when the uncached call exceeds the floor, as it already does at 1024 positions. The figure turns this reasoning into an explicit model.
What to observe:
- At initial values, speedup is 1 until a few hundred tokens. The model fitted to the first short run (25 ms floor, and 56 ms versus measured 54.5 ms for an uncached 1024-position call) puts that call above the floor from roughly 640 positions and predicts total speedup 1.2 at 1024 tokens and 3.0 at 2048. This is the reasoned expectation for the full lab reaching 2048: modest speedup that rises at the curve’s end. Your value will differ with your machine’s floor, but the shape should be similar.
- Lowering the floor changes the picture. With ms, the same model gives about 2.3 at 256 tokens and 15 at 1024. Reducing launch cost is the goal of the next lesson’s CUDA Graphs: cache creates headroom and graphs expose it.
- Batch also exposes it. With each uncached call processes eight times as many rows and exceeds the floor much earlier. Continuous batching exploits this.
- Fused attention makes the uncached path much cheaper. Much of the uncached baseline cost is not projections but score matrices that eager attention writes and rereads in memory. Fused attention does not materialize them, so cache takes longer to pay off with this floor.
Memory behaved as predicted. For the longest output’s 263 positions, the formula gives 5.78 MiB and cache tensors total exactly that (the cell checks with an assert); PyTorch’s allocator counted 5.80 MiB because it reserves in blocks. Peak memory above already allocated memory was 9.7 MiB uncached and 6.9 MiB cached: the uncached path stores no state but creates temporaries growing as every call. In the full run with 2048 tokens, each layer’s score matrix has elements, about 72 MiB in bf16 and twice that in FP32 softmax, while the whole cache occupies about 45 MiB: the path that “uses no memory” has the higher peak.
Exercises
import numpy as np
class KVCache:
def __init__(self, layers, batch, heads, capacity, dim):
self.shape = (batch, heads, capacity, dim)
self.keys = [np.empty(self.shape) for _ in range(layers)]
self.values = [np.empty(self.shape) for _ in range(layers)]
self.lengths = [0] * layers
def update(self, layer, k, v, pos):
pass
def get(self, layer):
passThe causal mask guarantees that a position’s keys and values at every layer depend only on its prefix: they are the exact state a future position needs, and the KV cache stores them once instead of recomputing at every step. Correct implementation is a position contract: contiguous writes at valid length, reading only the valid part, RoPE with absolute indices and mask covering prefill, chunked prefill and decoding. Token-by-token equality is certified in FP32; in bf16 both paths round the same function differently and diverge at ties. Cache removes a factor of work, but the clock notices only when that work, rather than kernel launch, dominates each call.