ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
6.77 kB
"""Llama-shaped decoder whose KV cache is PAGED.
Instead of one contiguous `(B, n_kv, max_seq, hd)` tensor per layer, each layer owns a pool of fixed
size pages and a per-sequence page table maps logical position -> physical page. The pool is twice the
size the batch needs and the pages a sequence owns are deliberately SCATTERED through it, so a kernel
cannot quietly treat the table as the identity and read contiguously; every attention step is a gather
through one level of indirection.
This is how every production serving stack stores KV (vLLM PagedAttention and everything after it),
and it is the single change that makes the attention half of a megakernel hard: the weight stream is
still a static schedule you can prefetch, but the KV addresses only exist after a table lookup.
"""
from model import HELPERS_CORE, QUANT_FP8
BODY = r'''
def make_weights(cfg, seed=0, device="cuda"):
"""Deterministic 1/sqrt(fan_in)-scaled weights. No checkpoint is shipped or downloaded."""
g = torch.Generator(device=device).manual_seed(seed)
d, ffn, n_q, n_kv, hd = cfg["d"], cfg["ffn"], cfg["n_q"], cfg["n_kv"], cfg["hd"]
dt = cfg["wdtype"]
def rnd(*shape, fan_in):
w = torch.randn(*shape, device=device, dtype=torch.float32, generator=g) / (fan_in ** 0.5)
return _quantise(w, dt)
ones = lambda: torch.ones(d, device=device, dtype=torch.bfloat16)
W = {"embed": rnd(cfg["vocab"], d, fan_in=d), "final_norm": ones(), "layers": []}
for _ in range(cfg["layers"]):
W["layers"].append(dict(
in_norm=ones(), post_norm=ones(),
q=rnd(n_q * hd, d, fan_in=d), k=rnd(n_kv * hd, d, fan_in=d),
v=rnd(n_kv * hd, d, fan_in=d), o=rnd(d, n_q * hd, fan_in=n_q * hd),
gate=rnd(ffn, d, fan_in=d), up=rnd(ffn, d, fan_in=d), down=rnd(d, ffn, fan_in=ffn)))
return W
def make_kv(cfg, batch, prefill_len, max_seq, seed=0, device="cuda"):
"""Paged KV pool + page table.
Returns {"k": [per-layer pool], "v": [...], "page_table": (B, pages_per_seq) int32,
"page_size": int}. Pools are (n_pages, n_kv, page_size, hd) bf16.
The pool is OVERSUBSCRIBED: it holds twice as many pages as this batch needs, and the page table
is a random SELECTION of half of them, so logically adjacent positions are physically scattered
and the pages in between belong to somebody else. `page_table[b, j]` is the physical page holding
logical positions [j*page_size, (j+1)*page_size) of sequence b.
Every page in the pool holds live-looking KV, including the ones this batch does not own. That is
what a real pool looks like (other sequences' pages, and freed pages still holding stale data),
and it is also what makes the indirection GRADEABLE. When the table was a permutation of a pool
that the sequence owned entirely, a kernel that ignored the table and read the pool contiguously
gathered a PERMUTED COPY OF THE SAME KEYS -- and attention is permutation-invariant over the key
axis, so the measured error of that shortcut was 0.087, barely above the 0.028 numerical floor.
With the pool oversubscribed the same shortcut measures 0.76 (see the spec's Precision section)."""
g = torch.Generator(device=device).manual_seed(seed + 777)
ps = cfg["page_size"]
per_seq = (max_seq + ps - 1) // ps
n_pages = 2 * batch * per_seq
sel = torch.randperm(n_pages, device=device, generator=g)[:batch * per_seq].to(torch.int32)
table = sel.view(batch, per_seq).contiguous()
ks, vs = [], []
for _ in range(cfg["layers"]):
k = (torch.randn(n_pages, cfg["n_kv"], ps, cfg["hd"], device=device, dtype=torch.float32,
generator=g) * 0.5).to(torch.bfloat16)
v = (torch.randn(n_pages, cfg["n_kv"], ps, cfg["hd"], device=device, dtype=torch.float32,
generator=g) * 0.5).to(torch.bfloat16)
ks.append(k)
vs.append(v)
return {"k": ks, "v": vs, "page_table": table, "page_size": ps}
def build_model(weights, kv_cache, cfg, max_seq_len):
"""UNTIMED setup. Returns whatever handle you like; the grader only passes it back to decode_step."""
cos, sin = _rope_cache(cfg, max_seq_len, weights["final_norm"].device)
W = {"embed": _deq(weights["embed"]), "final_norm": weights["final_norm"],
"layers": [{k: (v if k.endswith("norm") else _deq(v)) for k, v in L.items()}
for L in weights["layers"]]}
return {"W": W, "kv": kv_cache, "cfg": cfg, "cos": cos, "sin": sin}
def _gather_pages(pool, table, b, n_pos, ps):
"""Logical (n_kv, n_pos, hd) view of sequence b, gathered through the page table."""
npg = (n_pos + ps - 1) // ps
phys = table[b, :npg].long()
g = pool[phys] # (npg, n_kv, ps, hd)
g = g.permute(1, 0, 2, 3).reshape(g.shape[1], npg * ps, g.shape[3])
return g[:, :n_pos]
@torch.no_grad()
def decode_step(handle, token_ids, pos):
"""One decode step for every sequence in the batch. Appends this position's K/V into its page.
token_ids: (B,) int64 pos: int, the absolute position being written
returns: (B, vocab) logits
"""
W, kv, cfg = handle["W"], handle["kv"], handle["cfg"]
cos, sin = handle["cos"], handle["sin"]
B = token_ids.shape[0]
n_q, n_kv, hd = cfg["n_q"], cfg["n_kv"], cfg["hd"]
rep, ps = n_q // n_kv, kv["page_size"]
table = kv["page_table"]
pg, slot = pos // ps, pos % ps
x = W["embed"][token_ids]
for li, L in enumerate(W["layers"]):
h = _rms_norm(x, L["in_norm"], cfg["eps"])
q = (h @ L["q"].T).view(B, n_q, 1, hd)
k = (h @ L["k"].T).view(B, n_kv, 1, hd)
v = (h @ L["v"].T).view(B, n_kv, 1, hd)
q = _apply_rope(q, cos, sin, pos)
k = _apply_rope(k, cos, sin, pos)
kp, vp = kv["k"][li], kv["v"][li]
outs = []
for b in range(B):
p = int(table[b, pg])
kp[p, :, slot] = k[b, :, 0] # append THIS position into its page
vp[p, :, slot] = v[b, :, 0]
kk = _gather_pages(kp, table, b, pos + 1, ps).unsqueeze(0)
vv = _gather_pages(vp, table, b, pos + 1, ps).unsqueeze(0)
kk = kk.repeat_interleave(rep, dim=1)
vv = vv.repeat_interleave(rep, dim=1)
outs.append(F.scaled_dot_product_attention(q[b:b + 1], kk, vv))
att = torch.cat(outs, dim=0)
x = x + (att.reshape(B, n_q * hd) @ L["o"].T)
h = _rms_norm(x, L["post_norm"], cfg["eps"])
x = x + ((F.silu(h @ L["gate"].T) * (h @ L["up"].T)) @ L["down"].T)
x = _rms_norm(x, W["final_norm"], cfg["eps"])
return x @ W["embed"].T # tied lm_head
'''
MODEL_SRC = HELPERS_CORE + QUANT_FP8 + BODY