File size: 7,515 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""Llama-shaped decoder verifying a speculative-decoding DRAFT TREE in one forward pass.

A speculative decoder proposes a *tree* of candidate continuations, not a chain: node 0 is the last
accepted token, and every other node has a parent, so the 8 nodes cover several branching futures at
once. Verifying them means one forward pass in which

* every node attends to the whole committed KV cache, and
* among the 8 new nodes, node `i` attends to node `j` only if `j` is an ancestor of `i` (or `i`
  itself) -- an arbitrary DAG mask, **not** a causal triangle;
* node `i` gets RoPE position `pos + depth(i)`, so two siblings share a position;
* all 8 nodes are appended to the cache at slots `pos .. pos+7`, because the accepted prefix will be
  compacted out of them afterwards.

The mask and the position ids arrive as inputs, freshly generated per step. This is the EAGLE / Medusa
tree-attention kernel, and it is a genuinely different shape from a causal chunk: the mask is data, it
is not decomposable into a triangle, and it is tiny (8x8) while the KV it sits next to is enormous.

Acceptance is deliberately NOT part of the graded contract. Deciding which drafts are accepted is an
argmax over near-tied logits, which two correct implementations disagree about; the kernel problem is
the masked forward pass, and that is what is graded.
"""
from model import HELPERS_CORE, QUANT_FP8

BODY = r'''
def _rope_at(x, cos, sin, pos_ids):
    """x: (B, H, T, hd), pos_ids: (T,) int64 -- one RoPE position per node. fp32, then cast back."""
    c = cos[pos_ids].unsqueeze(0).unsqueeze(0)                 # (1, 1, T, hd/2)
    s = sin[pos_ids].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 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` committed tokens."""
    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 make_step_args(cfg, batch, base_pos, seed, n):
    """(tokens, tree_mask, pos_ids, pos) per step.

    A random tree over `tree` nodes: node 0 is the root (the last accepted token), node i > 0 picks a
    uniformly random parent among 0..i-1. `tree_mask[i, j]` is True iff j is an ancestor of i or j == i;
    `pos_ids[i]` is `depth(i)`, the RoPE offset relative to `pos`."""
    g = torch.Generator(device="cuda").manual_seed(seed)
    T = cfg["tree"]
    out = []
    for i in range(n):
        tok = torch.randint(0, cfg["vocab"], (batch, T), device="cuda", generator=g)
        r = torch.rand(T, device="cuda", generator=g)
        mask = torch.zeros(T, T, dtype=torch.bool, device="cuda")
        depth = torch.zeros(T, dtype=torch.int64, device="cuda")
        parent = [0] * T
        for j in range(1, T):
            parent[j] = int(r[j] * j)                          # uniform over 0..j-1
        for j in range(T):
            mask[j, j] = True
            p, dep = parent[j], 0
            u = j
            while u != 0:
                u = parent[u]
                mask[j, u] = True
                dep += 1
            depth[j] = dep
        out.append((tok, mask, depth, base_pos + i * T))
    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 verify_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}


@torch.no_grad()
def verify_step(handle, tokens, tree_mask, depth, pos):
    """Verify a whole draft tree in one forward pass. Appends all `tree` nodes at pos .. pos+tree-1.

    tokens:    (B, tree) int64   node tokens, node 0 is the root
    tree_mask: (tree, tree) bool  tree_mask[i, j] -> node i attends to node j
    depth:     (tree,) int64      RoPE offset of each node relative to `pos`
    pos:       int                absolute position of node 0
    returns:   (B, tree, vocab) logits, one row per node
    """
    W, kv, cfg = handle["W"], handle["kv"], handle["cfg"]
    cos, sin = handle["cos"], handle["sin"]
    B, T = tokens.shape
    n_q, n_kv, hd = cfg["n_q"], cfg["n_kv"], cfg["hd"]
    rep = n_q // n_kv

    # every node sees the whole committed cache [0, pos), plus the tree mask over the new nodes
    full = torch.ones(T, pos, dtype=torch.bool, device=tokens.device)
    mask = torch.cat([full, tree_mask], dim=1)                 # (T, pos + T)

    x = W["embed"][tokens]                                     # (B, T, d)
    for li, L in enumerate(W["layers"]):
        h = _rms_norm(x, L["in_norm"], cfg["eps"])
        q = (h @ L["q"].T).view(B, T, n_q, hd).transpose(1, 2)
        k = (h @ L["k"].T).view(B, T, n_kv, hd).transpose(1, 2)
        v = (h @ L["v"].T).view(B, T, n_kv, hd).transpose(1, 2)
        q = _rope_at(q, cos, sin, pos + depth)
        k = _rope_at(k, cos, sin, pos + depth)
        kc, vc = kv[li]
        kc[:, :, pos:pos + T] = k
        vc[:, :, pos:pos + T] = v
        kk = kc[:, :, :pos + T].repeat_interleave(rep, dim=1)
        vv = vc[:, :, :pos + T].repeat_interleave(rep, dim=1)
        att = F.scaled_dot_product_attention(q, kk, vv, attn_mask=mask)
        x = x + (att.transpose(1, 2).reshape(B, T, 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                                    # (B, T, vocab), tied lm_head
'''

MODEL_SRC = HELPERS_CORE + QUANT_FP8 + BODY