File size: 6,551 Bytes
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Llama-shaped decoder with a DeepSeek-V3-style Multi-Token Prediction head.

The main model produces `logits0` for the next token as usual. An MTP module then takes the main
model's final hidden state together with the embedding of the *following* token, normalises both,
concatenates them, projects `2d -> d`, runs one more full decoder block against its own KV cache, and
produces `logits1` -- a prediction two tokens ahead. Both logit sets are returned and both are graded.

For a megakernel this is the interesting case where the step is not a straight line: `logits0` and the
MTP block both depend on the same hidden state, they share the tied LM head, and the MTP block has its
own attention over its own cache. A fused implementation can compute `logits0` and start the MTP
projection from the same registers; an unfused one writes the hidden state to HBM and reads it twice.

`next_token_ids` is an input rather than a sample of `logits0`. In generation it would be the sampled
token; here it is supplied so the step is deterministic -- sampling from near-uniform random-weight
logits is exactly the argmax coin-flip this family refuses to grade on.
"""
from model import HELPERS_CORE, QUANT_FP8

BODY = r'''
def make_weights(cfg, seed=0, device="cuda"):
    """Deterministic 1/sqrt(fan_in)-scaled weights. `mtp` holds the extra module."""
    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)

    def block():
        return 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))

    W = {"embed": rnd(cfg["vocab"], d, fan_in=d), "final_norm": ones(), "layers": []}
    for _ in range(cfg["layers"]):
        W["layers"].append(block())
    W["mtp"] = dict(enorm=ones(), hnorm=ones(), proj=rnd(d, 2 * d, fan_in=2 * d), block=block())
    return W


def make_kv(cfg, batch, prefill_len, max_seq, seed=0, device="cuda"):
    """`layers + 1` caches: one per main layer, plus one for the MTP block."""
    g = torch.Generator(device=device).manual_seed(seed + 777)
    kv = []
    for _ in range(cfg["layers"] + 1):
        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 make_step_args(cfg, batch, base_pos, seed, n):
    """(token_ids, next_token_ids, pos) per step."""
    g = torch.Generator(device="cuda").manual_seed(seed)
    out = []
    for i in range(n):
        t0 = torch.randint(0, cfg["vocab"], (batch,), device="cuda", generator=g)
        t1 = torch.randint(0, cfg["vocab"], (batch,), device="cuda", generator=g)
        out.append((t0, t1, base_pos + i))
    return out


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)
    dq = lambda L: {k: (v if k.endswith("norm") else _deq(v)) for k, v in L.items()}
    W = {"embed": _deq(weights["embed"]), "final_norm": weights["final_norm"],
         "layers": [dq(L) for L in weights["layers"]],
         "mtp": dict(enorm=weights["mtp"]["enorm"], hnorm=weights["mtp"]["hnorm"],
                     proj=_deq(weights["mtp"]["proj"]), block=dq(weights["mtp"]["block"]))}
    return {"W": W, "kv": kv_cache, "cfg": cfg, "cos": cos, "sin": sin}


def _block(L, x, kv_pair, cos, sin, pos, cfg):
    """One decoder block: attention over its own cache, then the MLP. Returns the new residual."""
    B = x.shape[0]
    n_q, n_kv, hd = cfg["n_q"], cfg["n_kv"], cfg["hd"]
    rep = n_q // n_kv
    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_pair
    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"])
    return x + ((F.silu(h @ L["gate"].T) * (h @ L["up"].T)) @ L["down"].T)


@torch.no_grad()
def decode_step(handle, token_ids, next_token_ids, pos):
    """One decode step plus one MTP step. Appends `pos` into all `layers + 1` caches.

    token_ids:      (B,) int64  the current token
    next_token_ids: (B,) int64  the token that follows it (the MTP module's second input)
    pos:            int, the absolute position being written
    returns:        (logits0, logits1), each (B, vocab)
    """
    W, kv, cfg = handle["W"], handle["kv"], handle["cfg"]
    cos, sin = handle["cos"], handle["sin"]

    x = W["embed"][token_ids]
    for li, L in enumerate(W["layers"]):
        x = _block(L, x, kv[li], cos, sin, pos, cfg)
    logits0 = _rms_norm(x, W["final_norm"], cfg["eps"]) @ W["embed"].T      # tied lm_head

    M = W["mtp"]
    he = _rms_norm(W["embed"][next_token_ids], M["enorm"], cfg["eps"])
    hh = _rms_norm(x, M["hnorm"], cfg["eps"])                               # x = pre-final-norm hidden
    xm = torch.cat([hh, he], dim=-1) @ M["proj"].T                          # (B, 2d) -> (B, d)
    xm = _block(M["block"], xm, kv[cfg["layers"]], cos, sin, pos, cfg)
    logits1 = _rms_norm(xm, W["final_norm"], cfg["eps"]) @ W["embed"].T     # SAME tied head
    return logits0, logits1
'''

MODEL_SRC = HELPERS_CORE + QUANT_FP8 + BODY