File size: 12,063 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""megakernel-spec-decode-verify — whole-model verification of a speculative DRAFT TREE, fused."""
import pathlib, sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "models"))
from spec import MegaSpec
from _common import CORRECTNESS_MD, PRECISION_MD, perf_md
import spec_verify

# MEASURED over 8 steps and 2 seeds: E = 0.033 (worst of an all-fp32 twin and a
# bf16-GEMM/fp32-residual twin), cheapest feature-drop D = 0.27 (a causal triangle instead
# of the tree mask). 6.5e-2 is 2.0x E and 4.1x below D. The old 5e-2 was only 1.5x E.
TOL = 6.5e-2
CFG = dict(layers=16, d=2048, ffn=8192, n_q=32, n_kv=8, hd=64, vocab=128256,
           eps=1e-5, theta=500000.0, wdtype="bf16", tree=8, tokens_per_step=8)

SPEC = MegaSpec(
    name="megakernel-spec-decode-verify",
    unfused_kernels=660,
    title="Write a whole-model speculative-verification megakernel (8-node draft tree)",
    blurb=("Verify a speculative draft TREE in one fused forward pass: 8 candidate nodes, each "
           "attending to the full committed KV cache plus exactly its own ancestors, each carrying the "
           "RoPE position of its depth so siblings share a position. The tree mask is 8x8 of data "
           "handed to you per call -- not a causal triangle, not decomposable, and sitting next to a "
           "2.5 GB weight stream."),
    keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "speculative-decoding",
              "tree-attention", "eagle", "medusa", "low-latency"],
    cfg=CFG, model_src=spec_verify.MODEL_SRC,
    batch=1, prefill_len=2048, max_seq=2560, decode_steps=32,
    tol=TOL,
    bytes_per_step=2_546_600_000,
    reward_metric="verified-positions/s", reward_work=8,
    entry_step="verify_step",
    step_sig="handle, tokens, tree_mask, depth, pos",
    step_doc=("Verify a whole draft tree in one pass; append all `tree` nodes at pos .. pos+tree-1."
              "\n\n    tokens    : (B, tree) int64      node tokens, node 0 is the root"
              "\n    tree_mask : (tree, tree) bool     tree_mask[i, j] -> node i attends to node j"
              "\n    depth     : (tree,) int64         RoPE offset of each node relative to pos"
              "\n    pos       : int                   absolute position of node 0"
              "\n    returns   : (B, tree, vocab) logits, one row per node\n    "),
    step_ret="logits",
    spec_md="""## The computation

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

```
x = embed[tokens]                                  # (B, 8, d)
for each layer:
    h     = rmsnorm(x, in_norm)
    q,k,v = h @ Wq.T, h @ Wk.T, h @ Wv.T           # q: 32 heads, k/v: 8 heads (GQA, rep = 4)
    q,k   = rope(q, pos + depth), rope(k, pos + depth)     # per-NODE position, not per-slot
    kv_cache[layer].k[:, :, pos:pos+8] = k         # all 8 nodes appended
    kv_cache[layer].v[:, :, pos:pos+8] = v
    mask  = [ ones(8, pos) | tree_mask ]           # full history, then the tree among the new nodes
    a     = softmax(masked(q @ K[:pos+8].T / sqrt(hd))) @ V[:pos+8]
    x     = x + a_flat @ Wo.T
    h     = rmsnorm(x, post_norm)
    x     = x + (silu(h @ Wgate.T) * (h @ Wup.T)) @ Wdown.T
logits = rmsnorm(x, final_norm) @ embed.T          # (B, 8, vocab), tied lm_head
```

`/app/reference.py` implements exactly this, unfused, in eager torch.

Three things follow from the tree that do not follow from a chunk:

* **`tree_mask` is arbitrary data.** `tree_mask[i, j]` is true iff `j` is an ancestor of `i` or `j == i`.
  It is not a triangle, it is not banded, and it changes every call. You cannot bake it into a loop
  bound; you have to consult it.
* **Siblings share a RoPE position.** `depth[i]` is the node's depth in the tree, so two children of
  the same parent both get position `pos + depth`. RoPE is a per-node gather, not an affine function of
  the slot index.
* **All 8 nodes go into the cache** at slots `pos .. pos+7`, including nodes that will be rejected. A
  real scheduler compacts the accepted path afterwards; that compaction is not part of this task.

### What is deliberately NOT graded

Acceptance -- deciding which drafted tokens survive -- is an argmax over near-tied logits. Two correct
implementations of this model disagree about it routinely (this family measured top-1 agreement between
correct implementations at 0.79-0.92). The kernel problem is the masked forward pass, and that is what
is graded: all `8 x vocab` logits, by relative error.""",
    contract_md="""```python
def build_model(weights, kv_cache, cfg, max_seq_len) -> handle              # UNTIMED
def verify_step(handle, tokens, tree_mask, depth, pos) -> logits            # TIMED
def teardown(handle)                                                        # OPTIONAL
```

`build_model` is handed all four arguments below. `verify_step` is handed the handle you returned, plus
`tokens`, `tree_mask`, `depth` and `pos`.

| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `weights` | `dict` | `bfloat16` throughout | keys: `embed`, `final_norm`, `layers` (a `list` of 16 dicts) |
| `weights["embed"]` | `(vocab, d)` = `(128256, 2048)` | `bfloat16` | token embedding table; also the **tied** LM head, used as `embed.T` |
| `weights["final_norm"]` | `(d,)` | `bfloat16` | RMSNorm gain before the LM head |
| `weights["layers"][i]` | 9 tensors | `bfloat16` | `in_norm (d,)`, `post_norm (d,)`, `q (n_q*hd, d)`, `k (n_kv*hd, d)`, `v (n_kv*hd, d)`, `o (d, n_q*hd)`, `gate (ffn, d)`, `up (ffn, d)`, `down (d, ffn)` -- row-major, applied as `h @ W.T` |
| `kv_cache` | `list` of 16 `(k, v)` pairs | `bfloat16` | each tensor `(B, n_kv, max_seq_len, hd)`; slots `[0, 2048)` hold the committed prefix, the rest are zero |
| `cfg` | `dict` | python `int` / `float` / `str` | `layers, d, ffn, n_q, n_kv, hd, vocab, eps, theta, wdtype, tree` (`tree` = 8) |
| `max_seq_len` | scalar | python `int` | `2560` -- the allocated time capacity of every cache, exactly `kv_cache[i][0].shape[2]`. `pos + tree <= max_seq_len` always holds, so a RoPE table of this length covers the whole run |
| `tokens` | `(B, tree)` = `(1, 8)` | `int64`, on the GPU | the 8 node tokens; node 0 is the root |
| `tree_mask` | `(tree, tree)` = `(8, 8)` | `bool`, on the GPU | `tree_mask[i, j]` is True iff node `i` attends to node `j`. Lower-triangular in *index* order but not otherwise structured |
| `depth` | `(tree,)` = `(8,)` | `int64`, on the GPU | `depth[i]` is node `i`'s depth in the tree; its RoPE position is `pos + depth[i]`, so siblings share a position |
| `pos` | scalar | python `int` | absolute position of node 0; the tree occupies cache slots `pos .. pos+7`, and `pos` advances by 8 per call |

**Return** -- `verify_step` returns a **single tensor** `logits` of shape `(B, tree, vocab)` =
`(1, 8, 128256)`, one row per node **in node-index order**, **bf16 or fp32, both accepted** (the grader
compares in fp32). `build_model` returns an opaque handle of any type; the grader never inspects it and
only passes it back to `verify_step`.

`weights`, `cfg`, `tokens`, `tree_mask` and `depth` are **read-only**. `kv_cache` is the one thing you
must update **in place**: all 8 nodes' K and V go into slots `pos .. pos+7`, because the next call
attends over them.

`tree_mask` and `depth` are **regenerated every call** from a seed you do not control, so nothing about
the tree shape can be precomputed in `build_model`. Successive calls advance `pos` by 8.

Every node attends to the **entire** committed prefix `[0, pos)` unconditionally; the mask only governs
the 8 new columns.

`build_model` is untimed: repack weights, pre-transpose, allocate scratch, launch a persistent kernel,
build an instruction schedule -- whatever you need.""",
    correctness_md=CORRECTNESS_MD.format(tol=TOL).replace("(B, vocab)", "(B, 8, vocab)") + """

All 8 rows are compared in one Frobenius norm, so a kernel that handles the root correctly and gets the
mask wrong for the deeper nodes fails immediately. Measured: dropping the tree mask entirely -- letting
every node see every other node -- gives **0.46**; substituting a causal triangle for the DAG gives
**0.27**; giving the nodes chain positions instead of `pos + depth` gives **0.57**. The gate is at
6.5e-2 and a correct kernel measures 0.033 -- see the Precision section.""",
    precision_md=PRECISION_MD + """

Masked positions must be `-inf` **before** the softmax max is taken, not zeroed afterwards. With only 8
new columns against thousands of unmasked ones the difference is small in magnitude and completely
wrong in the rows where it matters.

**Where the tolerance comes from (measured, not guessed).** `tol` is `6.5e-2`. Measured on the graded
fixtures (batch 1, committed cache 2048+, 8 consecutive trees, 2 weight/tree seeds):

| implementation | worst relative error |
|---|---|
| all-fp32 twin: residual, GEMMs and the masked softmax in fp32 | 2.9e-2 |
| **bf16 GEMMs + fp32 residual, hand-rolled masked softmax** | **3.3e-2** |
| *(the gate)* | *6.5e-2* |
| **a causal triangle over the 8 nodes instead of the ancestor DAG** | **1.8e-1 - 2.7e-1** |
| no mask over the 8 nodes at all | 4.6e-1 |
| chain RoPE positions (`pos + i`) instead of `pos + depth(i)` | 5.7e-1 |
| the tree is never appended to the cache | 2.9e-1 - 1.07 |

So **E = 3.3e-2**, **tol = 6.5e-2 = 2.0x E**, and the closest wrong implementation -- a causal
triangle, which is what you get if you reach for an off-the-shelf causal kernel -- is **4.1x** the
tolerance. That is below this benchmark's 10x target and it cannot be widened by moving the gate: at
8 tree nodes against a 2048-token committed cache, the new columns are 0.4% of the attention, so even
a completely wrong mask over them only moves the logits so far. Note it is still caught at every one
of the 8 compared steps. This is an arithmetic gate; bf16 and fp32 residual streams both pass.""",
    perf_md=perf_md(
        floor_us=531, eager_us=9250, graph_us=3200, toks=8, unit="positions/s",
        lead="""This is still the **bandwidth** regime, and that is exactly why speculative decoding
works. Verifying 8 positions costs the same 2.47 GB of weight traffic as verifying 1 -- the arithmetic
goes up 8x (to a still-trivial 12 GFLOP) while the bytes barely move. Per call: 2.47 GB of weights,
76 MB of KV, and an 8x8 mask.""",
        extra="""
* **The 8 nodes are free; do not serialise them.** The whole point is that one weight stream serves all
  8 rows. A kernel that loops over nodes, or that is really 8 GEMVs sharing a launch, reads `Wgate`
  eight times and performs exactly like a batch-1 decode.
* **The mask costs nothing if you keep it in registers.** It is 64 bits. Load it once per call, not
  once per layer and certainly not once per head.
* **Two attention regimes in one kernel.** Columns `[0, pos)` are unmasked and enormous; columns
  `[pos, pos+8)` are masked and tiny. Stream the bulk with a flash-style online softmax and handle the
  8-column tail as a separate, register-resident epilogue.
* **Never expand GQA.** 32 query heads over 8 KV heads: four query heads share one KV load.
* **The LM head runs 8 times over one 525 MB matrix.** Read it once, compute 8 dot products per tile."""),
    regime_md=("**Regime**: batch 1, **8 draft-tree nodes per call**, 16 layers, `d`=2048, ffn=8192, 32 "
               "query / 8 KV heads, head_dim 64, vocab 128256, tied LM head. The cache arrives holding "
               "2048 tokens and grows by 8 per call. ~2.55 GB per call puts the floor near 531 us -- "
               "for **eight** positions, which is the whole economic argument for speculative decoding. "
               "Reward is verified positions per second."),
).validate()