File size: 5,320 Bytes
baf356c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""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())