ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 6)
baf356c verified
Raw History Blame Contribute Delete
5.32 kB
"""Reference implementation — the CORRECTNESS SPEC for `persistent-kv-append-inline`.
Correct, deliberately unfused, and slow. Its speed has no bearing on your score, which is an
absolute GB/s number. GENERATED by _mega_factory/build.py.
"""
import torch
import torch.nn.functional as F
def make_step_args(cfg, batch, base_pos, seed, n):
"""Arguments passed to each step, after the handle. Default: (token_ids, pos)."""
g = torch.Generator(device="cuda").manual_seed(seed)
return [(torch.randint(0, cfg["vocab"], (batch,), device="cuda", generator=g), base_pos + i)
for i in range(n)]
def compare(got, exp):
"""Relative error (Frobenius) used by the correctness gate. Tuples compare worst-elementwise."""
if isinstance(exp, (tuple, list)):
return max(compare(g, e) for g, e in zip(got, exp))
a, b = got.float(), exp.float()
return ((a - b).norm() / b.norm().clamp(min=1e-9)).item()
def make_weights(cfg, seed=0, device="cuda"):
"""No projection weights: K and V arrive already computed and already rotated."""
return {}
def make_kv(cfg, batch, prefill_len, max_seq, seed=0, device="cuda"):
"""A paged K/V pool plus a shuffled page table, already holding `prefill_len` tokens/request."""
g = torch.Generator(device=device).manual_seed(seed + 777)
P, n_kv, hd = cfg["page"], cfg["n_kv"], cfg["hd"]
per = (max_seq + P - 1) // P
npg = batch * per
kp = torch.zeros(npg, n_kv, P, hd, device=device, dtype=torch.bfloat16)
vp = torch.zeros_like(kp)
tab = torch.randperm(npg, device=device, generator=g).view(batch, per).to(torch.int32)
t = torch.arange(prefill_len, device=device)
pg = tab.to(torch.int64)[:, t // P] # (B, prefill_len)
sl = t % P
kp[pg, :, sl] = (torch.randn(batch, prefill_len, n_kv, hd, device=device, dtype=torch.float32,
generator=g) * 0.5).to(torch.bfloat16)
vp[pg, :, sl] = (torch.randn(batch, prefill_len, n_kv, hd, device=device, dtype=torch.float32,
generator=g) * 0.5).to(torch.bfloat16)
return {"k": kp, "v": vp, "table": tab}
def make_step_args(cfg, batch, base_pos, seed, n):
"""(q, k_new, v_new, pos) per call. `pos` is a (B,) int32 CUDA tensor -- no host scalar needed.
`q` is deliberately CORRELATED with `k_new`: in a real model both come from the same hidden state,
so a token attends strongly to the position it is itself writing. Here that self term carries about
15% of the softmax mass, which is what makes the appended entry matter to the returned output --
an implementation that attends over 0..pos-1 and forgets the token it just wrote is wrong by
~0.9, not by 1/context. The queries are also scaled so the
softmax over the 16k-token context is genuinely peaked rather than a flat average that would wash
out any error in the bulk of the cache."""
g = torch.Generator(device="cuda").manual_seed(seed)
n_q, n_kv, hd = cfg["n_q"], cfg["n_kv"], cfg["hd"]
rep = n_q // n_kv
out = []
for i in range(n):
k = (torch.randn(batch, n_kv, hd, device="cuda", dtype=torch.float32, generator=g) * 0.5)
v = (torch.randn(batch, n_kv, hd, device="cuda", dtype=torch.float32, generator=g) * 0.5)
q = (torch.randn(batch, n_q, hd, device="cuda", dtype=torch.float32, generator=g) * 3.0
+ k.repeat_interleave(rep, dim=1) * 3.5)
pos = torch.full((batch,), base_pos + i, device="cuda", dtype=torch.int32)
out.append((q.to(torch.bfloat16), k.to(torch.bfloat16), v.to(torch.bfloat16), pos))
return out
def build_attn(weights, kv_cache, cfg, max_seq_len):
"""UNTIMED setup. Re-layout the pool, pin the page table, launch a persistent kernel, ..."""
return {"kv": kv_cache, "cfg": cfg}
@torch.no_grad()
def append_attend(handle, q, k_new, v_new, pos):
"""Write this position's K/V into the paged cache, then attend over 0..pos inclusive.
q : (B, n_q, hd) bf16 already rotated queries
k_new : (B, n_kv, hd) bf16 already rotated keys for this position
v_new : (B, n_kv, hd) bf16
pos : (B,) int32 absolute position to append for each request (all equal here)
returns : (out, k_rd, v_rd) -- out (B, n_q*hd) attention INCLUDING the token just appended;
k_rd, v_rd (B, n_kv*hd) read back OUT OF THE CACHE at the slot just written
"""
kvp, cfg = handle["kv"], handle["cfg"]
kp, vp, tab = kvp["k"], kvp["v"], kvp["table"].to(torch.int64)
P, n_q, n_kv, hd = cfg["page"], cfg["n_q"], cfg["n_kv"], cfg["hd"]
B = q.shape[0]
p = pos.to(torch.int64)
b = torch.arange(B, device=q.device)
pg, sl = tab[b, p // P], p % P
kp[pg, :, sl] = k_new # scattered append
vp[pg, :, sl] = v_new
L = int(p.max()) + 1
t = torch.arange(L, device=q.device)
pgs, sls = tab[:, t // P], t % P
K = kp[pgs, :, sls].permute(0, 2, 1, 3) # (B, n_kv, L, hd)
V = vp[pgs, :, sls].permute(0, 2, 1, 3)
o = F.scaled_dot_product_attention(q.unsqueeze(2), K, V, enable_gqa=True)
return (o.reshape(B, n_q * hd).float(),
kp[pg, :, sl].reshape(B, n_kv * hd).float(),
vp[pg, :, sl].reshape(B, n_kv * hd).float())