| """Append K/V into a PAGED cache and attend over it -- including the entry just written -- in one |
| kernel, with no launch boundary between the write and the read. |
| |
| Every serving stack does append-then-attend, and almost every one of them does it as two kernels, |
| because a kernel boundary is a free device-wide fence: the append kernel's stores are guaranteed |
| visible to the attention kernel's loads. Fusing the two removes that guarantee, and you have to |
| recreate it yourself -- a release fence after the scattered page write, a grid-wide barrier, an |
| acquire on the other side -- for a store whose address came out of a page table and whose reader is a |
| different block than the writer. |
| |
| The cache is paged and the page table is SHUFFLED, so consecutive logical positions are scattered |
| across the pool: the reader cannot assume anything about locality, and the writer's target page is |
| data-dependent. |
| """ |
|
|
| BODY = r''' |
| 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()) |
| ''' |
|
|
| MODEL_SRC = BODY |
|
|