File size: 6,706 Bytes
144626d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""Reference implementation — the CORRECTNESS SPEC for `megakernel-batch4-decode`.

Correct, deliberately unfused, and slow. Its speed has no bearing on your score, which is an
absolute tokens/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 _rms_norm(x, w, eps):
    return F.rms_norm(x, (x.shape[-1],), w, eps)


def _rope_cache(cfg, maxlen, device):
    hd, theta = cfg["hd"], cfg["theta"]
    inv = 1.0 / (theta ** (torch.arange(0, hd, 2, device=device).float() / hd))
    f = torch.outer(torch.arange(maxlen, device=device).float(), inv)
    return torch.cos(f), torch.sin(f)


def _apply_rope(x, cos, sin, pos):
    """x: (B, H, T, hd). Rotation is done in fp32 (cos/sin are fp32) then cast back."""
    c, s = cos[pos].unsqueeze(0).unsqueeze(0), sin[pos].unsqueeze(0).unsqueeze(0)
    xf = x.float()
    x1, x2 = xf[..., ::2], xf[..., 1::2]
    return torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1).flatten(-2).to(x.dtype)


def _quantise(w, dt):
    """Weights are shipped ALREADY QUANTISED. Quantisation error is part of the INPUT, not of the
    kernel: with an fp32 fixture a correct fp8 kernel disagrees with the reference on 17% of steps
    (measured relerr 0.137 vs 0.014 when pre-quantised)."""
    if dt == "bf16":
        return w.to(torch.bfloat16)
    if dt == "fp8":                                  # e4m3, per-output-channel bf16 scale
        amax = w.abs().amax(dim=-1, keepdim=True).clamp(min=1e-6)
        scale = amax / 448.0
        return (w / scale).clamp(-448, 448).to(torch.float8_e4m3fn), scale.to(torch.bfloat16)
    raise ValueError(dt)


def _deq(w):
    """(fp8_tensor, per-channel scale) -> bf16. Plain bf16 weights pass through."""
    if isinstance(w, tuple):
        q, s = w
        return (q.float() * s.float()).to(torch.bfloat16)
    return w

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"):
    """KV cache already holding `prefill_len` tokens. Decode starts at pos = prefill_len."""
    g = torch.Generator(device=device).manual_seed(seed + 777)
    kv = []
    for _ in range(cfg["layers"]):
        k = torch.zeros(batch, cfg["n_kv"], max_seq, cfg["hd"], device=device, dtype=torch.bfloat16)
        v = torch.zeros_like(k)
        k[:, :, :prefill_len] = torch.randn(batch, cfg["n_kv"], prefill_len, cfg["hd"], device=device,
                                            dtype=torch.float32, generator=g).to(torch.bfloat16) * 0.5
        v[:, :, :prefill_len] = torch.randn(batch, cfg["n_kv"], prefill_len, cfg["hd"], device=device,
                                            dtype=torch.float32, generator=g).to(torch.bfloat16) * 0.5
        kv.append((k, v))
    return kv


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.

    Dequantisation happens ONCE here rather than per step. That is not just a speed choice: dequantising
    a 128k-row embedding inside every step allocates ~525 MB per call, which perturbs the caching
    allocator enough that cuBLAS picks different GEMV algorithms run-to-run and two bit-identical
    implementations drift apart by ~1.4e-2. Hoisting it makes the reference exactly reproducible.
    """
    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}


@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 the cache.

    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]
    d, n_q, n_kv, hd = cfg["d"], cfg["n_q"], cfg["n_kv"], cfg["hd"]
    rep = n_q // n_kv

    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)
        kc, vc = kv[li]
        kc[:, :, pos:pos + 1] = k
        vc[:, :, pos:pos + 1] = v
        kk = kc[:, :, :pos + 1].repeat_interleave(rep, dim=1)
        vv = vc[:, :, :pos + 1].repeat_interleave(rep, dim=1)
        att = F.scaled_dot_product_attention(q, kk, vv)
        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