KV cache, MQA, GQA and latent attention
Derive KV-cache memory and incremental decoding, compare MHA, MQA, GQA, and latent attention, and test grouped conversion and rotary cache behavior.
After this lesson you can
- Explain when causal keys and values can be reused and calculate cache memory.
- Compare prefill and decoding workloads with an explicit roofline model.
- Implement incremental grouped-query attention and verify full-prefix equality.
- Derive latent key and value absorption and explain the RoPE constraint.
- Convert and evaluate grouped heads on the course GPT.
Before you start
Save what the future does not change
In autoregressive generation, each step adds a token and predicts the next. Recomputing every prefix projection and state repeats work. With a causal mask, an earlier position’s state does not depend on later tokens: at evaluation with fixed weights, its key and value can be reused. This is the KV cache. For each layer and sequence it stores previously produced keys and values; a new query needs only its own row and earlier columns.
This reuse requires the same sequence, positions, weights, mask, and evaluation configuration. Changing the prefix or adapter invalidates dependent state. The cache does not reduce work needed for the initial prompt, and storing tensors does not avoid reading them at each subsequent step.
The justification can be followed layer by layer. In the first, an earlier token’s embedding and position do not change when a future token is appended; the mask prevents its attention seeing that token. Its output and the K and V calculated from it therefore remain unchanged. If this holds in one layer, the earlier input to the next also remains unchanged and the argument repeats. The conclusion assumes deterministic evaluation and no architecture operation introducing a future dependency outside causal attention.
Without a cache, recomputing every prefix of lengths 1 through repeats old attention rows. For one head, counting causal pairs of each prefix gives , of order . With a cache only the new row is calculated at each step, with pairs, of order . This compares specific procedures and includes only QK products; projection, applying V, and the FFN add cost. It does not imply an actual implementation improves by exactly a factor of .
Memory accounting
KV cache memory for batch , layers, key and value heads of dimension , context , and bytes per component is
The two counts keys and values. The formula assumes equal dimensions, equal lengths, and dense storage without metadata. It excludes paging, fragmentation, activations, weights, or shared-prefix caches. With , , , , , and two-byte BF16, this is bytes or 4 GiB. It is capacity accounting, not measured time.
If a sequence grows from to , every layer adds one key and one value per KV head: the increase is bytes per sequence. Batch multiplies that increase when all sequences store separate states. In a real server lengths can differ and the allocator may reserve partly empty blocks; using maximum length for the whole batch bounds dense storage, not necessarily paged-cache consumption. Sharing a prefix also changes the physical copy count.
To compare specific architectures, the next figure uses dimensions of GPT-2 small, Llama 2 7B, Llama 3 8B, and DeepSeek-V2. For MLA it counts values per token: the cited configuration has 60 layers and components. It does not apply the MHA formula to that compressed state. Weight parameters are approximated by 124 million, 7, 8, and 236 billion; all weights and cache are assumed to use the chosen bytes. The 8 GiB budget is a hypothetical reference, not a measurement of the current GPU.
Two phases and a changing limit
In prefill and decoding, the same model has different workloads. Prefill processes many prompt positions in parallel and can reuse weights in large matrix products. Decoding generates few new positions per sequence and repeatedly reads weights and cache; with a small batch it often has lower arithmetic intensity. The roofline suggests when traffic limits performance, but the effective regime depends on batch, context, kernel, and hardware. Not every decoding workload is necessarily bandwidth-bound, nor every prefill compute-bound.
For a BF16 linear layer, one vector requires approximately FLOPs and reading weight bytes, assuming each weight is read once from external memory and ignoring input and output: ideal intensity is one FLOP per byte. Grouping vectors lets the same weights serve rows and multiplies the numerator by ; activation traffic and cache capacity prevent unbounded extrapolation. Incremental attention must additionally read context K and V, so cost changes as grows even with the same weight matrix.
The following roof is an illustrative model using two figures from the RTX 4060 laptop run documented in the memory and precision lab: approximately 18 TFLOP/s on large BF16 matmul and 205 GB/s memory bandwidth. These are rates measured in different operations under specific conditions, not guaranteed maxima or current machine measurements. For a linear layer, the model counts FLOPs and bytes for rows, reading each input and weight and writing output once. For attention it uses one head of dimension 64: prefill assumes two full products and materialized scores and probabilities; decoding counts one query and K/V reads. It omits caches and overheads: points are bounds only for that model.
d, dk, rows, T = 4096, 64, 8, 2048
linear_i = (2*rows*d*d)/(2*(d*d+2*rows*d))
decode_i = (4*T*dk)/(2*(2*T*dk+2*dk))
prefill_i = (4*T*T*dk)/(2*(4*T*T+4*T*dk))
ridge = 18000/205 # GFLOP/s dividido entre GB/s
print('lineal, decode, prefill, cruce (FLOP/byte):', linear_i, decode_i, prefill_i, ridge)The new query’s position must equal prefix length before appending it, respecting the model’s indexing convention. With RoPE, rotate each query and key at its correct absolute position; the already rotated key can be stored. Resetting position at every step changes logits even if the program still runs. Concatenating a new tensor per token can repeatedly copy the full prefix; preallocating capacity and tracking valid length avoids those copies at the cost of reserved space.
Sharing heads
Multi-query attention (MQA) keeps multiple queries but shares one key and value head among them. Shazeer proposes it to reduce KV traffic during incremental inference. Grouped-query attention (GQA) uses KV heads for queries, normally with divisible by : each group of queries shares a key and value. is MQA and is MHA.
Moving from to KV heads with the rest fixed reduces cache size by . It does not follow that time falls by the same factor: weights, projections, implementation, and batch also matter. Ainslie et al. convert an MHA checkpoint by averaging K and V projections within each group and continue training. Conversion does not exactly preserve the original function; their quality and speed comparisons apply to the evaluated models and tasks, not a general law.
For example, with 32 queries and 8 KV heads, each contiguous group of four queries shares one key and one value projection. Queries remain distinct, so their attention distributions can differ even when reading the same values. KV memory is one quarter of the 32-KV-head alternative if layers, dimensions, length, and format match. Averaging four matrices is a starting point for each shared head, not a mathematical identity preserving all four original products: subsequent adjustment must be measured with explicit data and budget.
To see conversion without attributing a quality result, this cell uses synthetic projections with one head on the first axis. Four heads are grouped into two contiguous pairs; queries and output projection remain separate.
import numpy as np
rg = np.random.default_rng(4)
Wk_mha = rg.normal(size=(4,2,8))
Wv_mha = rg.normal(size=(4,2,8))
Wk_gqa = Wk_mha.reshape(2,2,2,8).mean(axis=1)
Wv_gqa = Wv_mha.reshape(2,2,2,8).mean(axis=1)
assert np.allclose(Wk_gqa[0], (Wk_mha[0]+Wk_mha[1])/2)
assert np.allclose(Wv_gqa[1], (Wv_mha[2]+Wv_mha[3])/2)
print('formas MHA y GQA:', Wk_mha.shape, Wk_gqa.shape)An incremental equality check
This cell builds one-layer causal GQA with deterministic synthetic matrices and inputs. Full and incremental paths share weights; it does not load or replace the course GPT. Compare with numerical tolerance, since different calculation orders can round differently. Python indices start at zero.
import numpy as np
rng = np.random.default_rng(8)
T, d, H, G, dk = 6, 8, 4, 2, 2
X = rng.normal(size=(T, d))
Wq = rng.normal(size=(H, dk, d))
Wk = rng.normal(size=(G, dk, d))
Wv = rng.normal(size=(G, dk, d))
def attention(q, k, v):
score = (k @ q)/np.sqrt(q.size)
p = np.exp(score-score.max())
p /= p.sum()
return p @ v
def full(x):
q = np.einsum('hdm,tm->thd', Wq, x)
k = np.einsum('gdm,tm->tgd', Wk, x)
v = np.einsum('gdm,tm->tgd', Wv, x)
return np.array([[attention(q[t,h], k[:t+1,h//(H//G)], v[:t+1,h//(H//G)])
for h in range(H)] for t in range(len(x))])
def incremental(x):
keys = np.empty((len(x),G,dk))
values = np.empty_like(keys)
out = []
for t, xt in enumerate(x):
q = np.einsum('hdm,m->hd', Wq, xt)
keys[t] = np.einsum('gdm,m->gd', Wk, xt)
values[t] = np.einsum('gdm,m->gd', Wv, xt)
out.append([attention(q[h], keys[:t+1,h//(H//G)], values[:t+1,h//(H//G)])
for h in range(H)])
return np.array(out)
a, b = full(X), incremental(X)
print('error máximo:', np.max(np.abs(a-b)))
assert np.allclose(a,b,rtol=1e-12,atol=1e-12)
print('caché del ejercicio, GiB:', 2*4*32*8*128*8192*2/2**30)This small browser-executable GPT uses two causal blocks, learned positions, LayerNorm, GELU, and tied output head. It initializes synthetic weights from a seed and does not claim to be the lesson 11 trained checkpoint. It compares all recomputed-prefix logits with a preallocated cache and times both paths. A single small Pyodide measurement depends on the browser; the next local lab uses the actual checkpoint.
import time
import numpy as np
rng=np.random.default_rng(4)
d,h,L,V,T=16,4,2,24,16; dh=d//h
token=rng.normal(0,0.1,(V,d)); position=rng.normal(0,0.1,(T,d))
blocks=[]
for _ in range(L):
blocks.append({name:rng.normal(0,0.1,shape) for name,shape in (
('q',(d,d)),('k',(d,d)),('v',(d,d)),('o',(d,d)),
('fc',(d,4*d)),('proj',(4*d,d)))})
def norm(x):
z=x-x.mean(axis=-1,keepdims=True)
return z/np.sqrt((z*z).mean(axis=-1,keepdims=True)+1e-5)
def mlp(x,b):
z=x@b['fc']
return (0.5*z*(1+np.tanh(np.sqrt(2/np.pi)*(z+0.044715*z**3))))@b['proj']
def full(ids):
n=len(ids); x=token[ids]+position[:n]
for b in blocks:
a=norm(x)
q,k,v=[(a@b[name]).reshape(n,h,dh) for name in ('q','k','v')]
scores=np.einsum('thd,shd->hts',q,k)/np.sqrt(dh)
scores=np.where(np.arange(n)[None,None,:]<=np.arange(n)[None,:,None],scores,-np.inf)
p=np.exp(scores-scores.max(axis=-1,keepdims=True)); p/=p.sum(axis=-1,keepdims=True)
x=x+np.einsum('hts,shd->thd',p,v).reshape(n,d)@b['o']
x=x+mlp(norm(x),b)
return norm(x)@token.T
def cached(ids):
keys=np.empty((L,len(ids),h,dh)); values=np.empty_like(keys); out=[]
for t,idx in enumerate(ids):
x=token[idx]+position[t]
for layer,b in enumerate(blocks):
a=norm(x); q=(a@b['q']).reshape(h,dh)
keys[layer,t]=(a@b['k']).reshape(h,dh)
values[layer,t]=(a@b['v']).reshape(h,dh)
scores=np.einsum('hd,shd->hs',q,keys[layer,:t+1])/np.sqrt(dh)
p=np.exp(scores-scores.max(axis=-1,keepdims=True)); p/=p.sum(axis=-1,keepdims=True)
x=x+np.einsum('hs,shd->hd',p,values[layer,:t+1]).reshape(d)@b['o']
x=x+mlp(norm(x),b)
out.append(norm(x)@token.T)
return np.stack(out)
ids=np.arange(T)%V
start=time.perf_counter()
reference=np.stack([full(ids[:i+1])[-1] for i in range(T)])
dense_seconds=time.perf_counter()-start
start=time.perf_counter(); reused=cached(ids); cached_seconds=time.perf_counter()-start
error=np.max(np.abs(reference-reused))
print('error máximo:',error,'segundos prefijos/caché:',dense_seconds,cached_seconds)
assert np.allclose(reference,reused,atol=1e-10,rtol=1e-10)To connect this idea with the actual GPT from lesson 11, download its gpt-numpy.npz from the panel and place it in the local lab directory, or specify its path with environment variable ORYON_GPT_NUMPY. The next cell loads weights without pickle. It reconstructs the learned-position model’s forward pass and compares every logit in one window with incremental calculation that preallocates K and V per layer. It uses evaluation without dropout, like that implementation. The file is yours; the lab does not depend on course review files.
import json, os
import time
from pathlib import Path
import numpy as np
path = Path(os.environ.get('ORYON_GPT_NUMPY', 'gpt-numpy.npz'))
if not path.is_file():
raise FileNotFoundError(f'Descarga gpt-numpy.npz de m18-l11 e indica su ruta: {path}')
with np.load(path, allow_pickle=False) as archive:
cfg = json.loads(str(archive['config']))
chars = archive['characters'].tolist()
p = {key: archive[key].copy() for key in archive.files if key not in ('config','characters')}
assert len(chars) == cfg['vocab'] and cfg['width'] % cfg['heads'] == 0
def ln(x,g,b):
z=x-x.mean(axis=-1,keepdims=True)
return z/np.sqrt(np.mean(z*z,axis=-1,keepdims=True)+1e-5)*g+b
def mlp(x, pre):
z=x @ p[pre+'fc.w'] + p[pre+'fc.b']
z=.5*z*(1+np.tanh(np.sqrt(2/np.pi)*(z+.044715*z**3)))
return z @ p[pre+'proj.w'] + p[pre+'proj.b']
def full_logits(ids):
n=len(ids); h=cfg['heads']; d=cfg['width']; dh=d//h
x=p['token'][ids]+p['position'][:n]
for layer in range(cfg['layers']):
pre=f'block.{layer}.'
a=ln(x,p[pre+'n1.g'],p[pre+'n1.b'])
q,k,v=[(a @ p[pre+name+'.w'] + p[pre+name+'.b']).reshape(n,h,dh) for name in ('q','k','v')]
score=np.einsum('thd,shd->hts',q,k)/np.sqrt(dh)
score=np.where(np.arange(n)[None,None,:] <= np.arange(n)[None,:,None],score,-np.inf)
prob=np.exp(score-score.max(axis=-1,keepdims=True)); prob/=prob.sum(axis=-1,keepdims=True)
joined=np.einsum('hts,shd->thd',prob,v).reshape(n,d)
u=x+joined @ p[pre+'o.w']+p[pre+'o.b']
x=u+mlp(ln(u,p[pre+'n2.g'],p[pre+'n2.b']),pre)
return ln(x,p['final.g'],p['final.b']) @ p['token'].T
def incremental_logits(ids):
n=len(ids); h=cfg['heads']; d=cfg['width']; dh=d//h
if not 1 <= n <= cfg['context']: raise ValueError('longitud fuera del contexto')
keys=np.empty((cfg['layers'],n,h,dh)); values=np.empty_like(keys)
outputs=[]
for t, token in enumerate(ids):
x=p['token'][token]+p['position'][t]
for layer in range(cfg['layers']):
pre=f'block.{layer}.'
a=ln(x,p[pre+'n1.g'],p[pre+'n1.b'])
q=(a @ p[pre+'q.w']+p[pre+'q.b']).reshape(h,dh)
keys[layer,t]=(a @ p[pre+'k.w']+p[pre+'k.b']).reshape(h,dh)
values[layer,t]=(a @ p[pre+'v.w']+p[pre+'v.b']).reshape(h,dh)
score=np.einsum('hd,shd->hs',q,keys[layer,:t+1])/np.sqrt(dh)
prob=np.exp(score-score.max(axis=-1,keepdims=True)); prob/=prob.sum(axis=-1,keepdims=True)
joined=np.einsum('hs,shd->hd',prob,values[layer,:t+1]).reshape(d)
u=x+joined @ p[pre+'o.w']+p[pre+'o.b']
x=u+mlp(ln(u,p[pre+'n2.g'],p[pre+'n2.b']),pre)
outputs.append(ln(x,p['final.g'],p['final.b']) @ p['token'].T)
return np.stack(outputs)
ids=np.arange(min(5,cfg['context'])) % cfg['vocab']
full, cached=full_logits(ids), incremental_logits(ids)
print('Configuración:',cfg,'tokens de prueba:',ids.tolist())
print('Máximo error entre logits:',np.max(np.abs(full-cached)))
assert np.allclose(full,cached,rtol=1e-10,atol=1e-10)
long_ids=np.arange(min(cfg['context'],32)) % cfg['vocab']
def repeated_prefixes():
return np.stack([full_logits(long_ids[:t+1])[-1] for t in range(len(long_ids))])
start=time.perf_counter(); repeated=repeated_prefixes(); dense_time=time.perf_counter()-start
start=time.perf_counter(); reused=incremental_logits(long_ids); cache_time=time.perf_counter()-start
assert np.allclose(repeated,reused,rtol=1e-10,atol=1e-10)
print('Tiempo de una pasada, recalcular prefijos / caché, segundos:',dense_time,cache_time)npm run lab and open the connection link.The comparison covers a window within maximum context. The timer compares one CPU pass over that window: use it to check the flow, not as a stable estimate or GPU measurement. The lesson 11 GPT resets positions when cropping a full window; evicting one cache entry and retaining the others is insufficient because changed positions also change their states. For that policy rebuild the cropped-window cache. This cell verifies MHA, while the previous control exercises GQA.
Now convert the actual file’s K and V projections by averaging contiguous heads and calculate a GQA forward pass. This is an initial conversion without retraining: logit difference on this window is not a language-quality measure. With as many groups as heads, the result should match MHA; with fewer groups equality is not expected.
def grouped_projection(weight, bias, groups):
d=cfg['width']; heads=cfg['heads']; dh=d//heads
if heads % groups: raise ValueError('grupos deben dividir las cabezas')
w=weight.reshape(d,groups,heads//groups,dh).mean(axis=2).reshape(d,groups*dh)
b=bias.reshape(groups,heads//groups,dh).mean(axis=1).reshape(groups*dh)
return w,b
def gqa_logits(ids,groups):
n=len(ids); h=cfg['heads']; d=cfg['width']; dh=d//h; repeat=h//groups
x=p['token'][ids]+p['position'][:n]
for layer in range(cfg['layers']):
pre=f'block.{layer}.'
a=ln(x,p[pre+'n1.g'],p[pre+'n1.b'])
q=(a @ p[pre+'q.w']+p[pre+'q.b']).reshape(n,h,dh)
wk,bk=grouped_projection(p[pre+'k.w'],p[pre+'k.b'],groups)
wv,bv=grouped_projection(p[pre+'v.w'],p[pre+'v.b'],groups)
k=np.repeat((a @ wk+bk).reshape(n,groups,dh),repeat,axis=1)
v=np.repeat((a @ wv+bv).reshape(n,groups,dh),repeat,axis=1)
score=np.einsum('thd,shd->hts',q,k)/np.sqrt(dh)
score=np.where(np.arange(n)[None,None,:]<=np.arange(n)[None,:,None],score,-np.inf)
prob=np.exp(score-score.max(axis=-1,keepdims=True)); prob/=prob.sum(axis=-1,keepdims=True)
joined=np.einsum('hts,shd->thd',prob,v).reshape(n,d)
u=x+joined @ p[pre+'o.w']+p[pre+'o.b']
x=u+mlp(ln(u,p[pre+'n2.g'],p[pre+'n2.b']),pre)
return ln(x,p['final.g'],p['final.b']) @ p['token'].T
reference=full_logits(ids)
same=gqa_logits(ids,cfg['heads'])
assert np.allclose(reference,same,rtol=1e-10,atol=1e-10)
for groups in [g for g in (1,2,cfg['heads']) if g<=cfg['heads'] and cfg['heads']%g==0]:
difference=np.max(np.abs(gqa_logits(ids,groups)-reference))
print('grupos KV:',groups,'diferencia máxima de logits en la ventana:',difference)npm run lab and open the connection link.Compress and absorb
Multi-head latent attention (MLA) projects each input to a shared latent vector , from which each head’s keys and values can be recovered. Without position, if , then
The transformed query is computed once per step and head; there is no need to reconstruct every previous key. Similarly, a linear output projection can be composed with the value projection after summing latent contributions, preserving each head’s dimensions and weights. Compression does not automatically save time: it changes matmul shapes and computation.
For the value path, if , head output is . The sum is performed in latent space and projection applied once to the result. This rearrangement requires a linear projection shared across the head’s positions; a nonlinear or -dependent transformation between latent and value would prevent this equality in general. Latent space reduces storage only when its dimensions offset the positional path and remaining state.
RoPE inserts between query and key projection; it depends on and generally does not commute with . There is no single fixed matrix to absorb for every position. DeepSeek-V2 separates a compressed content part from a positional part with a shared key that is also stored. Its table 1 counts cache elements per token for that variant. MLA and MQA have no universal memory ordering without specifying dimensions.
The next control compares both ways to compute the product without position and gives a counterexample to rearrangement with rotations. This is only small-matrix algebra, not a DeepSeek-V2 implementation or measurement.
import numpy as np
rng = np.random.default_rng(21)
q = rng.normal(size=2)
c = rng.normal(size=2)
W = rng.normal(size=(2,2))
direct = q @ (W @ c)
absorbed = (W.T @ q) @ c
assert np.allclose(direct,absorbed)
def rotation(angle):
return np.array([[np.cos(angle),-np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
Ri, Rj = rotation(0.3), rotation(1.1)
actual = (Ri @ q) @ (Rj @ W @ c)
naive = (W.T @ q) @ (Ri.T @ Rj @ c)
print('diferencia de absorción sin posición:', abs(direct-absorbed))
print('diferencia al permutar W y RoPE:', abs(actual-naive))
assert not np.isclose(actual,naive)In this complete educational layer, each token caches a content latent and a shared rotated positional key. Queries have content and positional parts per head. Reconstructing K and V is compared with absorbing content projections and accumulating latents directly. This is a small random-weight construction, not the DeepSeek-V2 model or weights; it measures neither quality nor speed.
import numpy as np
rng = np.random.default_rng(12)
T, width, heads, d, latent, rope = 5, 8, 4, 4, 3, 2
x = rng.normal(size=(T,width))
down = rng.normal(size=(width,latent))
wq = rng.normal(size=(width,heads,d))
wqr = rng.normal(size=(width,heads,rope))
wkr = rng.normal(size=(width,rope))
wk = rng.normal(size=(heads,latent,d))
wv = rng.normal(size=(heads,latent,d))
wo = rng.normal(size=(heads*d,width))
cache_c = x @ down
q = np.einsum('tw,whd->thd', x, wq)
qr = np.einsum('tw,whr->thr', x, wqr)
kr = x @ wkr
def rotate(z, position):
angle = position * 0.2
c,s = np.cos(angle),np.sin(angle)
return np.stack((c*z[...,0]-s*z[...,1], s*z[...,0]+c*z[...,1]),axis=-1)
qr = np.stack([rotate(qr[i],i) for i in range(T)])
kr = np.stack([rotate(kr[i],i) for i in range(T)])
keys = np.einsum('tc,hcd->thd',cache_c,wk)
values = np.einsum('tc,hcd->thd',cache_c,wv)
def softmax(z):
e = np.exp(z-z.max(axis=-1,keepdims=True))
return e/e.sum(axis=-1,keepdims=True)
for i in range(T):
# Referencia: reconstruye cada clave y valor de contenido por cabeza.
logits = (np.einsum('hd,jhd->hj',q[i],keys[:i+1]) + qr[i] @ kr[:i+1].T)/np.sqrt(d+rope)
p = softmax(logits)
direct = np.einsum('hj,jhd->hd',p,values[:i+1]).reshape(-1) @ wo
# La clave proyectada se absorbe en q y la suma de valores se hace en el espacio latente.
q_latent = np.einsum('hd,hcd->hc',q[i],wk)
logits_abs = (q_latent @ cache_c[:i+1].T + qr[i] @ kr[:i+1].T)/np.sqrt(d+rope)
latent_sum = softmax(logits_abs) @ cache_c[:i+1]
absorbed = np.einsum('hc,hcd->hd',latent_sum,wv).reshape(-1) @ wo
assert np.allclose(logits,logits_abs,atol=1e-12)
assert np.allclose(direct,absorbed,atol=1e-12)
print('cinco prefijos: logits y salidas coinciden')
print('elementos de caché latente por token:', latent+rope,
'frente a K y V reconstruidos:', 2*heads*d)Convert and tune the small PyTorch GPT
The next test takes the lesson 12 small checkpoint, groups K and V projections by averaging, and continues training each variant on the same corpus. Copy the “PyTorch GPT and loaders” cell to gpt_pytorch.py, generate gpt-pytorch-small.pt, and save lesson 11 text as corpus.txt; environment variables can provide other paths. The cache is built step by step and compared with full computation before training. PyTorch cells concatenate for clarity and copy the prefix each step: these are not optimized caches; the previous NumPy lab shows preallocation. One parallel prefix pass is timed against one sequential cached pass: both return all logits, but are different workloads and one pass is not a stable benchmark. Times and losses are generated on your machine: a small dataset, one seed, and few steps do not prove quality equivalence. With learned positions, shifting the window requires rebuilding the cache.
import os, math, time
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
assert torch.cuda.is_available(), 'el laboratorio requiere CUDA'
scope={}
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'),scope)
path=Path(os.environ.get('ORYON_GPT_TORCH','gpt-pytorch-small.pt'))
text=Path(os.environ.get('ORYON_CORPUS','corpus.txt')).read_text(encoding='utf-8')
reference,chars=scope['load_checkpoint'](path,map_location='cpu')
stoi={c:i for i,c in enumerate(chars)}
assert len(text)>4000 and all(c in stoi for c in text)
data=torch.tensor([stoi[c] for c in text],dtype=torch.long)
split=int(0.8*len(data)); train,valid=data[:split],data[split:]
length=reference.config['context']; heads=reference.config['heads']
assert len(valid)>length+1
class GroupedAttention(nn.Module):
def __init__(self,old,width,heads,groups):
super().__init__(); assert heads%groups==0
self.heads=heads; self.groups=groups; self.dh=width//heads
self.q=nn.Linear(width,width); self.o=nn.Linear(width,width)
self.k=nn.Linear(width,groups*self.dh); self.v=nn.Linear(width,groups*self.dh)
self.q.load_state_dict(old.q.state_dict()); self.o.load_state_dict(old.o.state_dict())
for name in ('k','v'):
source=getattr(old,name); dest=getattr(self,name)
with torch.no_grad():
dest.weight.copy_(source.weight.reshape(groups,heads//groups,self.dh,width).mean(1).reshape_as(dest.weight))
dest.bias.copy_(source.bias.reshape(groups,heads//groups,self.dh).mean(1).reshape_as(dest.bias))
def projected(self,x):
b,t,_=x.shape
q=self.q(x).view(b,t,self.heads,self.dh).transpose(1,2)
k=self.k(x).view(b,t,self.groups,self.dh).transpose(1,2)
v=self.v(x).view(b,t,self.groups,self.dh).transpose(1,2)
return q,k,v
def attend(self,q,k,v,causal):
k=k.repeat_interleave(self.heads//self.groups,dim=1)
v=v.repeat_interleave(self.heads//self.groups,dim=1)
z=F.scaled_dot_product_attention(q,k,v,is_causal=causal,dropout_p=0.)
return self.o(z.transpose(1,2).contiguous().view(z.shape[0],z.shape[2],-1))
def forward(self,x,diagnostics=False):
q,k,v=self.projected(x)
return self.attend(q,k,v,True),None
def decode(self,x,cache):
q,k,v=self.projected(x)
if cache is not None:
k=torch.cat((cache[0],k),dim=2); v=torch.cat((cache[1],v),dim=2)
return self.attend(q,k,v,False),(k,v)
def convert(groups):
model,_=scope['load_checkpoint'](path,map_location='cpu')
model=model.float()
for block in model.blocks:
block.attn=GroupedAttention(block.attn,model.config['width'],heads,groups)
return model.cuda()
@torch.no_grad()
def incremental(model,ids):
caches=[None]*len(model.blocks); outputs=[]
for pos in range(ids.shape[1]):
x=model.token(ids[:,pos:pos+1])+model.position(torch.tensor([pos],device=ids.device))[None,:,:]
for i,block in enumerate(model.blocks):
a,caches[i]=block.attn.decode(block.n1(x),caches[i])
x=x+a; x=x+block.mlp(block.n2(x))
outputs.append(F.linear(model.final(x),model.token.weight))
return torch.cat(outputs,dim=1)
probe=valid[:length].unsqueeze(0).cuda(); target=valid[1:length+1].unsqueeze(0).cuda()
reference=reference.float().cuda().eval()
with torch.no_grad(): original,_,_=reference(probe,target)
steps=int(os.environ.get('ORYON_STEPS','20')); assert steps>0
print('GPU:',torch.cuda.get_device_name(),'pasos por variante:',steps)
for groups in (heads,heads//2,1):
model=convert(groups).eval()
with torch.no_grad():
# Una pasada de calentamiento antes de la comparación de tiempo.
model(probe,target); incremental(model,probe)
torch.cuda.synchronize(); start=time.perf_counter()
full,loss_before,_=model(probe,target)
torch.cuda.synchronize(); full_seconds=time.perf_counter()-start
start=time.perf_counter()
cached=incremental(model,probe)
torch.cuda.synchronize(); cached_seconds=time.perf_counter()-start
error=float((full-cached).abs().max())
assert torch.allclose(full,cached,atol=2e-5,rtol=2e-5)
if groups==heads: assert torch.allclose(full,original,atol=2e-5,rtol=2e-5)
optimizer=torch.optim.AdamW(model.parameters(),lr=3e-4)
gen=torch.Generator().manual_seed(19); model.train()
# No actualiza parámetros ni consume el generador de lotes.
optimizer.zero_grad(set_to_none=True)
_,warm_loss,_=model(probe,target); warm_loss.backward()
optimizer.zero_grad(set_to_none=True)
torch.cuda.synchronize(); start=time.perf_counter()
for _ in range(steps):
starts=torch.randint(len(train)-length,(4,),generator=gen).tolist()
xx=torch.stack([train[i:i+length] for i in starts]).cuda()
yy=torch.stack([train[i+1:i+length+1] for i in starts]).cuda()
optimizer.zero_grad(set_to_none=True); _,loss,_=model(xx,yy); loss.backward(); optimizer.step()
torch.cuda.synchronize(); elapsed=time.perf_counter()-start
model.eval()
with torch.no_grad(): _,loss_after,_=model(probe,target)
print('grupos',groups,'parámetros',sum(p.numel() for p in model.parameters()),
'error caché',error,'validación antes/después',float(loss_before),float(loss_after),
'segundos una pasada completa/caché',full_seconds,cached_seconds,
'tokens/s de entrenamiento',round(steps*4*length/elapsed))
del model,optimizernpm run lab and open the connection link.To also check RoPE on lesson 13’s mini Llama, run its lab to generate mini-llama.pt. Save definitions from class RMS through the end of class MiniLlama in mini_llama_classes.py, preceded by import math, import torch, from torch import nn, and from torch.nn import functional as F. The cell loads that file and lesson 12’s gpt_pytorch.py and reconstructs the model from saved configuration. It groups K and V by averaging and compares each prefix output with incremental decoding, applying RoPE at each token’s absolute position. Then it tunes each variant on the same batches and compares a validation window before and after. Fewer groups reduce K and V parameters, so capacity is not equalized; one seed and window cannot establish general quality.
from pathlib import Path
import os, math, torch
from torch import nn
from torch.nn import functional as F
mini_scope={}
exec(Path(os.environ.get('ORYON_MINI_CODE','mini_llama_classes.py')).read_text(encoding='utf-8'),mini_scope)
gpt_scope={}
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'),gpt_scope)
state=torch.load(Path(os.environ.get('ORYON_MINI','mini-llama.pt')),map_location='cpu',weights_only=True)
assert not state['qknorm'], 'este control usa el checkpoint sin QK-norm'
mini_chars=state['characters']; config=state['config']
corpus=Path(os.environ.get('ORYON_CORPUS','corpus.txt')).read_text(encoding='utf-8')
stoi={c:i for i,c in enumerate(mini_chars)}
assert len(corpus)>4000 and all(c in stoi for c in corpus)
all_ids=torch.tensor([stoi[c] for c in corpus],dtype=torch.long)
split=int(len(all_ids)*0.8); mini_train,mini_valid=all_ids[:split],all_ids[split:]
length=min(config['context'],32); steps=int(os.environ.get('ORYON_STEPS','20'))
assert steps>0 and len(mini_valid)>length+1
vx=mini_valid[:length].unsqueeze(0).cuda(); vy=mini_valid[1:length+1].unsqueeze(0).cuda()
def load_mini():
original=gpt_scope['TorchGPT'](**config)
model=mini_scope['MiniLlama'](original,False)
model.load_state_dict(state['state_dict'],strict=True)
return model.cuda().eval()
def rotate_at(z,start):
d=z.shape[-1]
freq=torch.exp(-math.log(10000)*torch.arange(0,d,2,device=z.device,dtype=z.dtype)/d)
angle=(torch.arange(z.shape[-2],device=z.device,dtype=z.dtype)+start)[:,None]*freq
c,s=angle.cos(),angle.sin(); even,odd=z[...,0::2],z[...,1::2]
return torch.stack((even*c-odd*s,even*s+odd*c),dim=-1).flatten(-2)
class RotaryGrouped(nn.Module):
def __init__(self,old,groups):
super().__init__(); self.heads=old.heads; self.groups=groups
width=old.q.in_features; self.dh=width//self.heads
assert self.heads%groups==0 and self.dh%2==0
self.q=old.q; self.o=old.o
self.k=nn.Linear(width,groups*self.dh,bias=False,device=old.k.weight.device)
self.v=nn.Linear(width,groups*self.dh,bias=False,device=old.v.weight.device)
for name in ('k','v'):
src=getattr(old,name).weight; dst=getattr(self,name).weight
with torch.no_grad():
dst.copy_(src.reshape(groups,self.heads//groups,self.dh,width).mean(1).reshape_as(dst))
def project(self,x,pos):
b,t,_=x.shape
q=self.q(x).view(b,t,self.heads,self.dh).transpose(1,2)
k=self.k(x).view(b,t,self.groups,self.dh).transpose(1,2)
v=self.v(x).view(b,t,self.groups,self.dh).transpose(1,2)
return rotate_at(q,pos),rotate_at(k,pos),v
def attend(self,q,k,v,causal):
k=k.repeat_interleave(self.heads//self.groups,dim=1)
v=v.repeat_interleave(self.heads//self.groups,dim=1)
z=F.scaled_dot_product_attention(q,k,v,is_causal=causal,dropout_p=0.)
return self.o(z.transpose(1,2).contiguous().view(z.shape[0],z.shape[2],-1))
def forward(self,x):
q,k,v=self.project(x,0)
return self.attend(q,k,v,True)
def decode(self,x,pos,cache):
q,k,v=self.project(x,pos)
if cache is not None:
k=torch.cat((cache[0],k),dim=2); v=torch.cat((cache[1],v),dim=2)
return self.attend(q,k,v,False),(k,v)
@torch.no_grad()
def mini_decode(model,ids):
cache=[None]*len(model.blocks); result=[]
for pos in range(ids.shape[1]):
x=model.token(ids[:,pos:pos+1])
for i,block in enumerate(model.blocks):
attn,cache[i]=block.attn.decode(block.n1(x),pos,cache[i])
x=x+attn; z=block.n2(x)
x=x+block.down(F.silu(block.gate(z))*block.up(z))
result.append(F.linear(model.final(x),model.token.weight))
return torch.cat(result,dim=1)
tokens=torch.tensor([list(range(min(16,len(mini_chars))))],device='cuda')
reference=load_mini()
with torch.no_grad(): expected=reference.logits(tokens)
for groups in (config['heads'],config['heads']//2,1):
model=load_mini()
for block in model.blocks: block.attn=RotaryGrouped(block.attn,groups)
with torch.no_grad():
full=model.logits(tokens); cached=mini_decode(model,tokens)
error=float((full-cached).abs().max())
assert torch.allclose(full,cached,atol=2e-5,rtol=2e-5)
if groups==config['heads']: assert torch.allclose(full,expected,atol=2e-5,rtol=2e-5)
with torch.no_grad(): before=float(F.cross_entropy(model.logits(vx).reshape(-1,len(mini_chars)),vy.reshape(-1)))
optimizer=torch.optim.AdamW(model.parameters(),lr=3e-4)
gen=torch.Generator().manual_seed(19); model.train()
for _ in range(steps):
starts=torch.randint(len(mini_train)-length,(4,),generator=gen).tolist()
xx=torch.stack([mini_train[i:i+length] for i in starts]).cuda()
yy=torch.stack([mini_train[i+1:i+length+1] for i in starts]).cuda()
optimizer.zero_grad(set_to_none=True)
loss=F.cross_entropy(model.logits(xx).reshape(-1,len(mini_chars)),yy.reshape(-1))
loss.backward(); optimizer.step()
model.eval()
with torch.no_grad(): after=float(F.cross_entropy(model.logits(vx).reshape(-1,len(mini_chars)),vy.reshape(-1)))
print('grupos',groups,'parámetros',sum(p.numel() for p in model.parameters()),
'error caché RoPE',error,'validación antes/después',round(before,4),round(after,4),'pasos',steps)npm run lab and open the connection link.The figure records one run of that cell on RTX 3060, PyTorch 2.11.0+cu128, using lesson 13’s mini Llama, batch seed 19, and 20 steps per configuration. The checkpoint has SHA-256 c0c99c8e304b40113aab1a5ec4136cafa5cc0df453e297dcb720c37553995413; your file may differ. It shows the same validation window before and after tuning. Parameter differences and short duration prevent attributing a general quality advantage to a group count; the cell can regenerate results with your checkpoint.
This final measurement moves the educational latent layer to CUDA. Matrices and inputs are random and untrained: token rate describes only this one-layer loop, not the entire mini Llama or DeepSeek. Both caches are preallocated and the final absorbed output is compared with explicit K/V reconstruction. The theoretical cache-byte count differs from total peak, which includes temporaries and allocator reservation rounding. Head concatenation and output projection are omitted in both paths.
import math, time, torch
assert torch.cuda.is_available()
torch.manual_seed(12)
device='cuda'; T=128; width=64; heads=4; d=16; latent=32; rope=4
x=torch.randn(T,width,device=device)
wd=torch.randn(width,latent,device=device)*0.1
wq=torch.randn(width,heads,d,device=device)*0.1
wqr=torch.randn(width,heads,rope,device=device)*0.1
wkr=torch.randn(width,rope,device=device)*0.1
wk=torch.randn(heads,latent,d,device=device)*0.1
wv=torch.randn(heads,latent,d,device=device)*0.1
def rotary(z,pos):
freq=torch.exp(-math.log(10000)*torch.arange(0,rope,2,device=z.device)/rope)
angle=pos*freq; c,s=angle.cos(),angle.sin()
a,b=z[...,0::2],z[...,1::2]
return torch.stack((a*c-b*s,a*s+b*c),dim=-1).flatten(-2)
torch.cuda.synchronize(); before=torch.cuda.memory_allocated()
cache_c=torch.empty(T,latent,device=device); cache_r=torch.empty(T,rope,device=device)
allocated=torch.cuda.memory_allocated()-before
def run():
for i in range(T):
cache_c[i]=x[i]@wd; cache_r[i]=rotary(x[i]@wkr,i)
q=torch.einsum('w,whd->hd',x[i],wq)
qr=rotary(torch.einsum('w,whr->hr',x[i],wqr),i)
qlat=torch.einsum('hd,hcd->hc',q,wk)
scores=(qlat@cache_c[:i+1].T+qr@cache_r[:i+1].T)/math.sqrt(d+rope)
p=scores.softmax(-1)
z=torch.einsum('hc,hcd->hd',p@cache_c[:i+1],wv)
return z,q,qr
with torch.no_grad():
run(); torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats(); start=time.perf_counter()
z,q,qr=run(); torch.cuda.synchronize(); elapsed=time.perf_counter()-start
peak=torch.cuda.max_memory_allocated()
keys=torch.einsum('tc,hcd->thd',cache_c,wk)
values=torch.einsum('tc,hcd->thd',cache_c,wv)
scores=(torch.einsum('hd,thd->ht',q,keys)+qr@cache_r.T)/math.sqrt(d+rope)
direct=torch.einsum('ht,thd->hd',scores.softmax(-1),values)
error=float((z-direct).abs().max())
assert torch.allclose(z,direct,atol=1e-5,rtol=1e-5)
print('GPU:',torch.cuda.get_device_name(),'error máximo:',error)
print('bytes teóricos de caché:',T*(latent+rope)*4,'incremento asignado:',allocated,
'pico total asignado MiB:',round(peak/2**20,2),'tokens/s de una pasada:',round(T/elapsed))npm run lab and open the connection link.Exercises
Step 1 of 2. How do you rewrite q transpose times Wc?
import numpy as np
def decode_step(q, k, v, keys, values, pos):
pass