ZMC2019 commited on
Commit
ec51e7b
·
verified ·
1 Parent(s): 4161512

Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 22)

Browse files
tools/factory/specs/qwen3_moe_route_align.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `qwen3-moe-route-align` — high-sparsity (512-expert) MoE routing fused with the block-aligned
2
+ expert-sorted dispatch table the grouped expert GEMM consumes."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="qwen3-moe-route-align",
11
+ title="Write a fast high-sparsity MoE router + block-aligned dispatch-table kernel",
12
+ blurb=("Qwen3-Next routes every token to 10 of 512 experts, and the router is only half the job: before "
13
+ "the grouped expert GEMM can launch, the routing decisions have to be turned into a work table — "
14
+ "every routed slot sorted by expert, each expert's segment padded up to a whole tile, and a "
15
+ "block-to-expert map so the GEMM knows which weight matrix each tile uses. At half a million "
16
+ "tokens the score matrix alone is more than a gigabyte, and the usual implementation drags it "
17
+ "through HBM five times and then runs a full sort it does not need."),
18
+ keywords=["mle", "kernel-generation", "moe", "routing", "top-k", "qwen3-next", "high-sparsity",
19
+ "dispatch", "block-align", "memory-bound"],
20
+ module="route_align.py",
21
+ func="route_and_align",
22
+ signature="route_and_align(logits, topk, block_size)",
23
+ returns_doc="""High-sparsity MoE routing plus the block-aligned expert-sorted dispatch table.
24
+
25
+ Args:
26
+ logits: (T, E) float32 — raw gate logits, one row per token.
27
+ topk: int — K, experts kept per token.
28
+ block_size: int — BM, the row-tile size of the grouped expert GEMM.
29
+
30
+ Returns:
31
+ (topk_ids, topk_w, sorted_ids, block_expert, num_tokens_post_pad) where
32
+ topk_ids: (T, K) int32 — selected expert ids, ASCENDING within each row
33
+ topk_w: (T, K) float32 — renormalised softmax weights, aligned with topk_ids
34
+ sorted_ids: (L,) int32 — routed slot ids grouped by expert and padded per expert to a
35
+ multiple of BM; L = T*K + E*(BM-1); unused entries are T*K
36
+ block_expert: (L//BM,) int32 — expert owning each BM-row block; -1 past the last used block
37
+ num_tokens_post_pad: (1,) int32 — total padded length (a multiple of BM)""",
38
+
39
+ reference_imports="import torch",
40
+ reference_src='''
41
+ def route_and_align(logits, topk, block_size):
42
+ """Softmax + top-k + renormalise, then the expert-sorted, block-padded dispatch table.
43
+
44
+ Correct and simple — it is the exact SPECIFICATION, not a performance target. It materialises the full
45
+ fp32 score matrix, runs a global argsort over every routed slot, and builds the table with several more
46
+ full-length passes.
47
+ """
48
+ T, E = logits.shape
49
+ dev = logits.device
50
+ n = T * topk
51
+
52
+ scores = torch.softmax(logits.float(), dim=-1) # (T, E)
53
+ idx = scores.topk(topk, dim=-1).indices # best-first
54
+ idx = idx.sort(dim=-1).values # canonical order: ASCENDING expert id
55
+ w = scores.gather(1, idx)
56
+ w = w / w.sum(-1, keepdim=True) # renormalise over the selected set
57
+
58
+ flat = idx.reshape(n).to(torch.int64) # expert of routed slot s = t*K + j
59
+ slot = torch.arange(n, device=dev)
60
+ order = (flat * n + slot).argsort() # group by expert, slots ascending inside
61
+
62
+ counts = torch.bincount(flat, minlength=E) # rows per expert
63
+ padded = ((counts + block_size - 1) // block_size) * block_size
64
+ starts = torch.cumsum(padded, 0) - padded # where each expert's padded segment begins
65
+ total = int(padded.sum())
66
+
67
+ L = n + E * (block_size - 1)
68
+ sorted_ids = torch.full((L,), n, dtype=torch.int32, device=dev) # sentinel = n means "padding"
69
+ e_of = flat[order] # expert at each position of `order`
70
+ raw_start = torch.cumsum(counts, 0) - counts
71
+ dest = starts[e_of] + (slot - raw_start[e_of]) # padded destination of each row
72
+ sorted_ids[dest] = order.to(torch.int32)
73
+
74
+ block_expert = torch.full((L // block_size,), -1, dtype=torch.int32, device=dev)
75
+ nb = padded // block_size
76
+ block_expert[: total // block_size] = torch.repeat_interleave(
77
+ torch.arange(E, device=dev, dtype=torch.int32), nb)
78
+
79
+ return (idx.to(torch.int32), w.float(), sorted_ids, block_expert,
80
+ torch.tensor([total], dtype=torch.int32, device=dev))
81
+ ''',
82
+ make_inputs_src='''
83
+ MARGIN = 0.25 # guaranteed separation between the K-th and (K+1)-th gate logit of every token
84
+
85
+
86
+ def _mk(T, E, K, BM, seed):
87
+ """Gate logits with a GUARANTEED top-k margin.
88
+
89
+ A constant MARGIN is added to each token's K largest logits. That cannot change which experts are
90
+ largest (all K of them only move up), and it forces the gap between the K-th and (K+1)-th logit to at
91
+ least MARGIN = 0.25 — a factor of 1.28 in softmax score. bf16 cannot move a logit of that magnitude by
92
+ even a tenth of it, so the selected expert SET is unambiguous and is an exact-match target.
93
+ """
94
+ gen = torch.Generator(device="cuda").manual_seed(seed)
95
+ logits = torch.randn(T, E, device="cuda", dtype=torch.float32, generator=gen)
96
+ idx = logits.topk(K, dim=-1).indices
97
+ logits.scatter_add_(1, idx, torch.full_like(idx, 0, dtype=torch.float32) + MARGIN)
98
+ return logits, K, BM
99
+ ''',
100
+ flops_src='''
101
+ def canonical_work(T, E, K, BM):
102
+ """BYTES attributed to one routing + alignment pass, from the SHAPE ALONE.
103
+
104
+ The unavoidable traffic: read the (T, E) fp32 logit matrix once, write the (T, K) int32 ids and the
105
+ (T, K) fp32 weights, write the padded dispatch table of L = T*K + E*(BM-1) int32 entries and the
106
+ L/BM int32 block-to-expert map. The per-expert counters and prefix sums are tiny and never need to
107
+ reach HBM. This is a memory-bound kernel, so the score is achieved bandwidth against this fixed byte
108
+ count.
109
+ """
110
+ L = T * K + E * (BM - 1)
111
+ return T * E * 4 + T * K * 8 + 4 * L + 4 * (L // BM) + 4
112
+ ''',
113
+ flops_formula=("L = T*K + E*(BM-1) # padded table length\n"
114
+ "bytes = T*E*4 + T*K*8 + 4*L + 4*(L//BM) + 4\n"
115
+ "# logits ids+w table block map count"),
116
+
117
+ metric="GB/s",
118
+ compare="tuple",
119
+ tuple_names=("topk_ids", "topk_w", "sorted_ids", "block_expert", "num_tokens_post_pad"),
120
+ tol=1e-4, # MEASURED: 1400x the 7.2e-8 gap to an independent implementation; it only forbids bf16
121
+ shape_names=("T", "E", "K", "BM"),
122
+ grader_shapes=[(786432, 512, 10, 128), (655360, 512, 10, 128), (393216, 1024, 8, 128),
123
+ (524288, 768, 10, 64), (786432, 512, 8, 64)],
124
+ measure_shapes=[(720896, 512, 10, 128), (589824, 512, 10, 128), (327680, 1024, 8, 128),
125
+ (458752, 768, 10, 64), (720896, 512, 8, 64)],
126
+ measure_quick_shapes=[(65536, 512, 8, 128), (32768, 256, 6, 64), (131072, 128, 4, 128)],
127
+ correct_shapes=[(4096, 512, 10, 128), (1023, 256, 8, 64), (777, 128, 4, 32), (8192, 64, 6, 128)],
128
+
129
+ spec_md="""Two things happen here, and a real MoE layer needs both before it can launch anything.
130
+
131
+ **1 — the router.** A softmax over the expert axis, the `K` largest kept, renormalised so each token's
132
+ weights sum to one:
133
+
134
+ ```
135
+ scores = softmax(logits, dim=-1) # (T, E), fp32
136
+ idx = indices of the K largest scores # then SORTED ASCENDING by expert id
137
+ w = scores[idx] / sum(scores[idx]) # renormalised over the selected set only
138
+ ```
139
+
140
+ `topk_ids` must be **ascending by expert id** within each row, and `topk_w[t, j]` is the weight of
141
+ `topk_ids[t, j]`. The fixture guarantees a separation of at least `0.25` between each token's K-th and
142
+ (K+1)-th logit — a factor of 1.28 in score — so the selected set is never a near-tie and is compared
143
+ exactly.
144
+
145
+ **2 — the block-aligned dispatch table.** Number the routed slots `s = t*K + j`, so slot `s` belongs to
146
+ token `s // K` and asks for expert `topk_ids[t, j]`. The grouped expert GEMM wants those slots grouped by
147
+ expert, and it wants every expert's group to start on a tile boundary so a tile never straddles two
148
+ experts:
149
+
150
+ ```
151
+ counts[e] = number of slots that chose expert e
152
+ padded[e] = ceil(counts[e] / BM) * BM # round each expert's group up to a whole tile
153
+ starts[e] = padded[0] + ... + padded[e-1] # exclusive prefix sum of the PADDED counts
154
+ total = padded[0] + ... + padded[E-1] # = num_tokens_post_pad
155
+ ```
156
+
157
+ Expert `e` owns `sorted_ids[starts[e] : starts[e] + padded[e]]`. Its first `counts[e]` entries are the slot
158
+ ids that chose it, **in ascending slot order**; the remaining `padded[e] - counts[e]` entries are the
159
+ sentinel `T*K`, which the GEMM reads as "this row is padding, skip it". Every entry of `sorted_ids` past
160
+ `total` is also the sentinel.
161
+
162
+ `block_expert[b]` is the expert that owns block `b` — i.e. `sorted_ids[b*BM : (b+1)*BM]` — for every block
163
+ below `total / BM`, and `-1` for every block above it.
164
+
165
+ The output length is fixed by the shape alone: `L = T*K + E*(BM-1)` is the worst case (`E` experts each
166
+ wasting up to `BM-1` rows), so `sorted_ids` is `(L,)` and `block_expert` is `(L // BM,)` regardless of how
167
+ the tokens actually fall.
168
+
169
+ `/app/reference.py` builds this with a full argsort over every routed slot. That is the exact
170
+ specification; it is deliberately simple rather than fast.""",
171
+
172
+ contract_md="""| arg | shape | dtype | meaning |
173
+ |-----|-------|-------|---------|
174
+ | `logits` | `(T, E)` | `float32` | raw gate logits, one row per token |
175
+ | `topk` | int | | `K`, experts kept per token |
176
+ | `block_size` | int | | `BM`, the expert GEMM's row-tile size |
177
+
178
+ **Return a 5-tuple in exactly this order:**
179
+
180
+ | out | shape | dtype | notes |
181
+ |-----|-------|-------|-------|
182
+ | `topk_ids` | `(T, K)` | `int32` | **ascending by expert id** within each row; compared **exactly** |
183
+ | `topk_w` | `(T, K)` | `float32` | renormalised, aligned with `topk_ids` |
184
+ | `sorted_ids` | `(L,)` | `int32` | `L = T*K + E*(BM-1)`; slot ids grouped by expert, ascending inside each expert; padding entries are `T*K`; compared **exactly** |
185
+ | `block_expert` | `(L // BM,)` | `int32` | expert per block, `-1` past `num_tokens_post_pad / BM`; compared **exactly** |
186
+ | `num_tokens_post_pad` | `(1,)` | `int32` | total padded length; compared **exactly** |
187
+
188
+ `logits` is **read-only**. `E` is a multiple of nothing in particular and `T` is **not** guaranteed to be a
189
+ multiple of any tile size — the correctness shapes include `T = 1023` and `T = 777`. `BM` divides `L` by
190
+ construction. All four integer outputs are compared **bit-exactly**; only `topk_w` has a tolerance.""",
191
+
192
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `T`
193
+ (routed tokens in the step) in 393216–786432, `E` in 512–1024, `K` in 8–10, `BM` in 64–128. This is the
194
+ high-sparsity regime — 2% of the experts active per token — so the logit matrix is over a gigabyte while
195
+ everything downstream of it is two orders of magnitude smaller. Reading that matrix once, at full
196
+ bandwidth, is most of the achievable score.""",
197
+
198
+ correctness_md="""Four of the five outputs are **integer** and are compared **bit-exactly** — one wrong
199
+ entry anywhere in the dispatch table scores 0. `topk_w` must match the reference within **relative
200
+ Frobenius error `1e-4`**.
201
+
202
+ The expert *selection* is safe to compare exactly because the fixture guarantees a `0.25` logit margin
203
+ between the K-th and (K+1)-th expert of every token (a 1.28x score ratio). That is more than 15x what bf16
204
+ rounding of a logit of this magnitude can move, so two correct implementations cannot disagree about the
205
+ set — but note the consequence: the ordering, the padding rule and the sentinel are **exact**
206
+ specifications, not conventions you may vary. Each of these variants was tried and every one fails
207
+ outright: not padding each expert's segment up to `BM`, leaving `topk_ids` in best-first order instead of
208
+ ascending, filling the padding with `0` instead of `T*K`. Skipping the weight renormalisation lands at
209
+ **1.9**, four orders of magnitude above the `1e-4` weight gate.""",
210
+
211
+ perf_md="""The `(T, E)` fp32 logit matrix is 1–1.6 GB at the graded shapes and everything else is
212
+ smaller by two orders of magnitude, so the score is decided almost entirely by how close to a single
213
+ streaming read of it you get.
214
+
215
+ Three things go wrong in the obvious implementation. First, `softmax` then `topk` then `sum` then a divide
216
+ is four passes over that matrix; it should be one — a row fits in registers only 512 wide, so a block per
217
+ row can keep a running max, a running exponential sum, and a K-entry top-k list in one sweep. Second, a
218
+ full `topk` over 512 experts sorts far more than it needs: you need the K largest, unsorted, then a tiny
219
+ K-element sort to put them in ascending id order. Third, the reference's global argsort over `T*K` slots is
220
+ entirely avoidable — the table is a **counting sort** with `E` buckets, and the histogram can be built with
221
+ per-block privatised counters while the router is still streaming.
222
+
223
+ Once you have `counts`, the rest is a prefix sum over `E <= 1024` numbers (one block) and a scatter: slot
224
+ `s` lands at `starts[e] + rank(s within e)`, and the rank comes from an atomic increment on the bucket or
225
+ from a second pass. Filling the padding with the sentinel is a memset of a buffer you are writing anyway —
226
+ do not write it twice.
227
+
228
+ `block_expert` is `L/BM` entries, tiny; build it from the padded prefix sums directly rather than by
229
+ scanning `sorted_ids`.
230
+
231
+ Watch the tail: `T` is ragged, `E` need not be a power of two, and the number of used blocks depends on the
232
+ data, so the `-1` fill has to be right at any occupancy.""",
233
+
234
+ precision_md="""`logits` arrives in **float32** and `topk_w` is returned in **float32**. Do the softmax
235
+ and the renormalisation in fp32: the weights gate an expert's entire contribution to a token, the gate on
236
+ them is `1e-4`, and bf16 has nowhere near that precision.
237
+
238
+ **Do not compute the scores in bf16 or fp16.** It is not a speed win here — the read of `logits` is the
239
+ bottleneck and it is fp32 on the wire either way — and it would blow the weight tolerance.
240
+
241
+ The selection itself only needs the *ordering* of the logits, which is exact in fp32; you can select on the
242
+ raw logits and exponentiate only the K survivors plus the row maximum, which is the numerically stable and
243
+ cheap route.
244
+
245
+ **Where the tolerance comes from.** `1e-4` is measured. A second, independent implementation — a chunked
246
+ row-wise softmax that subtracts the row max at a different point, selects on the raw logits instead of on
247
+ the scores, and renormalises with a reciprocal-multiply instead of a divide — agrees with this reference to
248
+ a relative Frobenius error of **7.2e-8** on `topk_w` and **bit-exactly** on all four integer outputs, over
249
+ every correctness shape and a full-size graded shape. The tolerance is three orders of magnitude above the
250
+ observed difference, so it constrains nothing except the use of a narrower dtype.""",
251
+ ).validate()
tools/factory/specs/qwen3_next_gated_attention.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `qwen3-next-gated-attention` — Qwen3-Next style GQA attention with the per-head SIGMOID output
2
+ gate projected from the layer input and applied inside the attention epilogue."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="qwen3-next-gated-attention",
11
+ title="Write a fast gated attention kernel (attention + fused per-head output gate)",
12
+ blurb=("Qwen3-Next does not read the attention output straight out of the softmax: every element of "
13
+ "every head is multiplied by a SIGMOID gate that is projected from the block's input, which is "
14
+ "what lets the model shut a head off per token. Run as separate ops that is a second full-size "
15
+ "projection plus two extra round trips of the (T, H*D) attention output through HBM, on top of "
16
+ "an attention kernel that already had the tile in registers. Fusing the gate into the attention "
17
+ "epilogue makes it nearly free — but the gate GEMM and the attention have completely different "
18
+ "shapes, so the scheduling is the whole problem."),
19
+ keywords=["mle", "kernel-generation", "qwen3-next", "gated-attention", "output-gate", "gqa",
20
+ "flash-attention", "fusion", "compute-bound"],
21
+ module="gated_attn.py",
22
+ func="gated_attention",
23
+ signature="gated_attention(q, k, v, x, w_gate, scale=None)",
24
+ returns_doc="""Causal GQA attention with a fused per-head sigmoid output gate.
25
+
26
+ Args:
27
+ q: (B, T, Hq, D) bfloat16 — queries.
28
+ k, v: (B, T, Hkv, D) bfloat16 — keys and values; Hq is a multiple of Hkv (GQA).
29
+ x: (B, T, Dm) bfloat16 — the block INPUT, the source of the gate.
30
+ w_gate: (Hq*D, Dm) bfloat16 — gate projection, nn.Linear layout (out, in).
31
+ scale: float or None — logit scale; None means D ** -0.5.
32
+
33
+ Returns:
34
+ o: (B, T, Hq, D), bfloat16 or float32 — must match /app/reference.py numerically.""",
35
+
36
+ reference_imports="import torch",
37
+ reference_src='''
38
+ CH = 1024 # the reference tiles over queries purely so it FITS; it makes no attempt to be fast
39
+
40
+
41
+ def gated_attention(q, k, v, x, w_gate, scale=None):
42
+ """Causal GQA attention in fp32, then the sigmoid output gate projected from x.
43
+
44
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. Every query tile
45
+ materialises its full fp32 score row and the gate is a separate full-size GEMM through HBM.
46
+ """
47
+ B, T, Hq, D = q.shape
48
+ Hkv = k.shape[2]
49
+ if scale is None:
50
+ scale = D ** -0.5
51
+ rep = Hq // Hkv
52
+
53
+ kf = k.float().repeat_interleave(rep, dim=2).transpose(1, 2) # (B, Hq, T, D)
54
+ vf = v.float().repeat_interleave(rep, dim=2).transpose(1, 2)
55
+ qf = q.float().transpose(1, 2)
56
+ pos = torch.arange(T, device=q.device)
57
+
58
+ o = torch.empty(B, Hq, T, D, device=q.device, dtype=torch.float32)
59
+ for s in range(0, T, CH):
60
+ e = min(s + CH, T)
61
+ sc = torch.einsum("bhqd,bhkd->bhqk", qf[:, :, s:e], kf) * scale # (B, Hq, ch, T)
62
+ sc = sc.masked_fill(pos[s:e, None] < pos[None, :], float("-inf")) # causal
63
+ o[:, :, s:e] = torch.einsum("bhqk,bhkd->bhqd", torch.softmax(sc, dim=-1), vf)
64
+
65
+ g = x.float() @ w_gate.float().t() # (B, T, Hq*D) gate logits
66
+ o = o.transpose(1, 2).reshape(B, T, Hq * D) * torch.sigmoid(g) # SIGMOID gate, elementwise
67
+ return o.reshape(B, T, Hq, D).to(torch.bfloat16)
68
+ ''',
69
+ make_inputs_src='''
70
+ def _mk(B, T, Hq, Hkv, D, Dm, seed):
71
+ """Attention inputs plus the block input and the gate projection. The gate logits are kept in a range
72
+ where the sigmoid is genuinely selective (roughly 0.02 .. 0.98) rather than saturated at 1."""
73
+ gen = torch.Generator(device="cuda").manual_seed(seed)
74
+ q = torch.randn(B, T, Hq, D, device="cuda", dtype=torch.bfloat16, generator=gen)
75
+ k = torch.randn(B, T, Hkv, D, device="cuda", dtype=torch.bfloat16, generator=gen)
76
+ v = torch.randn(B, T, Hkv, D, device="cuda", dtype=torch.bfloat16, generator=gen)
77
+ x = torch.randn(B, T, Dm, device="cuda", dtype=torch.bfloat16, generator=gen)
78
+ w_gate = (torch.randn(Hq * D, Dm, device="cuda", generator=gen) * (2.0 * Dm ** -0.5)).to(torch.bfloat16)
79
+ return q, k, v, x, w_gate, None
80
+ ''',
81
+ flops_src='''
82
+ def canonical_work(B, T, Hq, Hkv, D, Dm):
83
+ """FLOPs attributed to one gated-attention forward, from the SHAPE ALONE.
84
+
85
+ Causal attention touches half the T-by-T grid and each surviving (query, key) pair costs 4*D FLOPs
86
+ (2*D for the q.k dot, 2*D for the p*v accumulate), giving 2*B*Hq*T*T*D. The gate projection is a dense
87
+ (B*T, Dm) x (Dm, Hq*D) GEMM. The softmax, the sigmoid and the elementwise multiply are O(B*T*Hq*D) and
88
+ are NOT credited — fusing them is a saving, not extra work you get paid for.
89
+ """
90
+ return 2 * B * Hq * T * T * D + 2 * B * T * Dm * (Hq * D)
91
+ ''',
92
+ flops_formula=("canonical_work(B, T, Hq, Hkv, D, Dm) = 2*B*Hq*T*T*D + 2*B*T*Dm*(Hq*D)\n"
93
+ "# causal attention gate projection"),
94
+
95
+ metric="TFLOP/s",
96
+ compare="tensor",
97
+ tol=7e-3, # MEASURED: 2.0x the 3.46e-3 worst gap to an independent bf16 SDPA+gate implementation
98
+ shape_names=("B", "T", "Hq", "Hkv", "D", "Dm"),
99
+ grader_shapes=[(1, 8192, 32, 4, 128, 4096), (2, 8192, 16, 2, 128, 2048),
100
+ (1, 16384, 16, 2, 128, 2048), (2, 6144, 32, 8, 128, 4096),
101
+ (1, 8192, 48, 8, 128, 6144)],
102
+ measure_shapes=[(1, 6144, 32, 4, 128, 4096), (2, 6144, 16, 2, 128, 2048),
103
+ (1, 12288, 16, 2, 128, 2048), (2, 4096, 32, 8, 128, 4096),
104
+ (1, 6144, 48, 8, 128, 6144)],
105
+ measure_quick_shapes=[(1, 2048, 8, 2, 128, 1024), (2, 1024, 8, 4, 128, 1024),
106
+ (1, 2048, 16, 2, 64, 1024)],
107
+ correct_shapes=[(1, 256, 8, 2, 64, 512), (2, 512, 8, 4, 128, 1024), (1, 333, 4, 1, 128, 256),
108
+ (3, 129, 8, 2, 64, 512)],
109
+
110
+ spec_md="""A Qwen3-Next attention block computes ordinary causal grouped-query attention and then gates
111
+ it, per head and per channel, with a sigmoid projected from the block's own input.
112
+
113
+ **1 — causal GQA attention**, in the usual layout:
114
+
115
+ ```
116
+ rep = Hq // Hkv # query heads per KV head
117
+ K[h] = k[:, :, h // rep] # head h reads KV head h // rep
118
+ a[b,h,i,j] = scale * dot( q[b,i,h,:], K[h][b,j,:] ) # scale = D**-0.5 when scale is None
119
+ a[b,h,i,j] = -inf for j > i # causal, no sinks, no windows
120
+ p = softmax(a, over j)
121
+ u[b,i,h,:] = sum_j p[b,h,i,j] * V[h][b,j,:]
122
+ ```
123
+
124
+ **2 — the output gate**, projected from `x` (the block INPUT, not the attention output) and applied with a
125
+ **sigmoid**:
126
+
127
+ ```
128
+ g = x @ w_gate.T # (B, T, Hq*D)
129
+ o[b, i, h, d] = u[b, i, h, d] * sigmoid( g[b, i, h*D + d] )
130
+ ```
131
+
132
+ The flattening is **head-major**: channel `h*D + d` of `g` gates head `h`, channel `d`. This is a *gate*,
133
+ not an activation — it is a function of `x`, so it is available before the attention even starts, and it is
134
+ per (token, head, channel) rather than per head.
135
+
136
+ Note the sigmoid, not SiLU: the gate multiplies the attention output by a number in `(0, 1)`, so a head can
137
+ be switched off for a token without changing its sign.
138
+
139
+ `/app/reference.py` runs the attention in fp32 over query tiles and then does the gate as a separate
140
+ full-size GEMM. That is the exact specification; it is deliberately simple rather than fast.""",
141
+
142
+ contract_md="""| arg | shape | dtype | meaning |
143
+ |-----|-------|-------|---------|
144
+ | `q` | `(B, T, Hq, D)` | `bfloat16` | queries |
145
+ | `k` | `(B, T, Hkv, D)` | `bfloat16` | keys; query head `h` uses KV head `h // (Hq//Hkv)` |
146
+ | `v` | `(B, T, Hkv, D)` | `bfloat16` | values, same grouping |
147
+ | `x` | `(B, T, Dm)` | `bfloat16` | the block input — the gate's source |
148
+ | `w_gate` | `(Hq*D, Dm)` | `bfloat16` | gate projection, `nn.Linear` layout `(out, in)` |
149
+ | `scale` | float or `None` | | logit scale; `None` means `D ** -0.5` |
150
+
151
+ **Return** a single tensor `o` of shape `(B, T, Hq, D)`, bfloat16 or float32 (the grader compares in fp32).
152
+
153
+ All inputs are **read-only**. `Hq` is always a multiple of `Hkv`. `T` is **not** guaranteed to be a multiple
154
+ of any tile size — the correctness shapes include `T = 333` and `T = 129`, so handle the ragged tail. There
155
+ are no attention sinks, no sliding window and no positional encoding to apply: `q` and `k` arrive with RoPE
156
+ already applied.""",
157
+
158
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in
159
+ 1–2, `T` in 6144–16384, `Hq` in 16–48 with `Hkv` in 1–8 (GQA ratios of 4–8), `D` = 128, and `Dm` equal to
160
+ `Hq*D` or half of it. The attention term dominates the FLOP count at these lengths but the gate GEMM is
161
+ 20–35% of it, so a kernel that gets the attention right and then bolts a separate gate on the end leaves a
162
+ large fraction on the table.""",
163
+
164
+ correctness_md="""The returned tensor must match the reference (evaluated in fp32) within **relative
165
+ Frobenius error `7e-3`** at every graded shape, including the timed ones.
166
+
167
+ That gate is **measured**, not guessed, and kernels that skip this task's actual work miss it by orders of
168
+ magnitude: returning the ungated attention output scores **1.00**, applying the gate logits raw (no
169
+ sigmoid) scores **2.99**, using SiLU instead of sigmoid scores **1.59**, and projecting the gate from the
170
+ attention output instead of from `x` scores **0.58** — the closest of them is still **83x** the
171
+ tolerance.""",
172
+
173
+ perf_md="""Two very different GEMM shapes have to share the machine. The attention is the usual
174
+ flash-attention problem — tile the query axis, stream K and V tiles, keep the running max/sum and the
175
+ accumulator in registers, and never write the score matrix. The gate is a plain `(B*T, Dm) x (Dm, Hq*D)`
176
+ projection.
177
+
178
+ The win is that the gate result is consumed **exactly where the attention accumulator already lives**. A
179
+ kernel that computes `g` into HBM, reads it back, multiplies and writes again pays three extra full-size
180
+ passes over a `(B, T, Hq*D)` tensor — at the graded shapes that is hundreds of megabytes of avoidable
181
+ traffic per call, and it also costs a second kernel launch on the critical path of every layer.
182
+
183
+ Two ways to spend that: fuse the gate GEMM into the attention epilogue so the `(BLOCK_M, D)` slice of `g`
184
+ each query tile needs is computed while the tile is still resident, or run the gate as a persistent
185
+ producer that overlaps the attention mainloop. Either way, `sigmoid` is cheap but not free — it is one
186
+ `exp` per output element, so evaluate it on the tile rather than on a materialised tensor.
187
+
188
+ GQA gives you `Hq/Hkv` query heads sharing one KV tile: load K and V once per group, not once per head.
189
+ Causality means half the tiles are fully masked and must be **skipped**, not computed and thrown away, and
190
+ the diagonal tile is the only one that needs the elementwise mask.""",
191
+
192
+ precision_md="""Inputs are **bfloat16** and the output may be bf16 or fp32. Accumulate the attention
193
+ logits, the softmax and the `p @ v` product in **fp32**, and evaluate the sigmoid in fp32 — a bf16 sigmoid
194
+ loses enough precision near zero to show up in the norm. Tensor-core GEMMs on bf16 inputs with fp32
195
+ accumulate are exactly what this task expects.
196
+
197
+ **fp8 is not appropriate here.** The inputs arrive in bf16 and quantising them to fp8 to use a wider tensor
198
+ core is an approximation of the specified computation, not an implementation of it — and the measured
199
+ tolerance does not have room for it.
200
+
201
+ Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
202
+ numerical specification.
203
+
204
+ **Where the tolerance comes from.** `1.2e-2` is measured. A second, independent implementation — bf16
205
+ `scaled_dot_product_attention` with `is_causal=True` and GQA broadcasting for the attention, a bf16 tensor
206
+ -core GEMM for the gate, and the sigmoid multiply in bf16 — differs from this fp32 reference by relative
207
+ Frobenius error at most **3.46e-3** across the correctness shapes and a full-size graded shape (it is
208
+ remarkably flat: 3.35e-3 to 3.46e-3 over every shape and seed tried). The tolerance is **2.0x** that. Almost all of it is the bf16 rounding of the two GEMMs and of the returned tensor, which
209
+ is the floor for any bf16 kernel; a faithful implementation lands in the same place regardless of how it
210
+ tiles.""",
211
+ ).validate()
tools/factory/specs/qwen3_next_gated_attn_decode.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `qwen3-next-gated-attn-decode` — the Qwen3-Next attention decode step: paged GQA over a fused
2
+ KV cache, then zero-centred per-head RMSNorm and the projected sigmoid output gate, all in one pass."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="qwen3-next-gated-attn-decode",
11
+ title="Write a fast gated attention DECODE kernel (paged GQA + head-norm + output gate)",
12
+ blurb=("What a Qwen3-Next server actually runs at every generated token in its attention layers: "
13
+ "grouped-query attention over a paged KV cache that holds K and V interleaved at each position, "
14
+ "followed immediately by a zero-centred per-head RMSNorm and a sigmoid output gate projected "
15
+ "from the block input. The attention is pure cache bandwidth; the epilogue is a projection and "
16
+ "two normalisations on a tensor small enough that it should never leave registers — and as three "
17
+ "separate launches it adds three round trips and three kernel launches to the critical path of "
18
+ "every layer of every token."),
19
+ keywords=["mle", "kernel-generation", "qwen3-next", "gated-attention", "output-gate", "decode",
20
+ "paged-attention", "kv-cache", "rmsnorm", "memory-bound"],
21
+ module="gated_decode.py",
22
+ func="gated_attn_decode",
23
+ signature=("gated_attn_decode(q, kv_cache, page_table, seq_lens, x, w_gate, w_norm, "
24
+ "eps=1e-6, scale=None)"),
25
+ returns_doc="""Paged GQA decode with a fused zero-centred head-norm and sigmoid output gate.
26
+
27
+ Args:
28
+ q: (B, Hq, D) bfloat16 — this token's query, per head.
29
+ kv_cache: (NUM_PAGES, P, 2, Hkv, D) bfloat16 — page pool; index 0 of axis 2 is K, index 1 is V.
30
+ page_table: (B, NP) int32 — physical page of logical positions
31
+ [p*P, (p+1)*P) of request b.
32
+ seq_lens: (B,) int32 — valid cached positions of request b.
33
+ x: (B, Dm) bfloat16 — the block INPUT, the source of the gate.
34
+ w_gate: (Hq*D, Dm) bfloat16 — gate projection, nn.Linear layout (out, in).
35
+ w_norm: (D,) bfloat16 — ZERO-CENTRED head-norm gain; effective gain 1+w_norm.
36
+ eps: float — RMSNorm epsilon.
37
+ scale: float or None — logit scale; None means D ** -0.5.
38
+
39
+ Returns:
40
+ out: (B, Hq, D), bfloat16 or float32 — must match /app/reference.py numerically.""",
41
+
42
+ reference_imports="import torch",
43
+ reference_src='''
44
+ CH = 8 # the reference tiles over requests purely so it FITS; it makes no attempt to be fast
45
+
46
+
47
+ def gated_attn_decode(q, kv_cache, page_table, seq_lens, x, w_gate, w_norm, eps=1e-6, scale=None):
48
+ """Paged GQA decode in fp32, then the head-norm and the gate as separate dense steps.
49
+
50
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. It materialises the
51
+ whole logical cache of each request in fp32 and the full score row, which is exactly what a real kernel
52
+ must avoid: pages should be read once, in bfloat16, straight into registers.
53
+ """
54
+ B, Hq, D = q.shape
55
+ P, Hkv = kv_cache.shape[1], kv_cache.shape[3]
56
+ NP = page_table.shape[1]
57
+ S = NP * P
58
+ rep = Hq // Hkv
59
+ if scale is None:
60
+ scale = D ** -0.5
61
+ dev = q.device
62
+
63
+ o = torch.empty(B, Hq, D, device=dev, dtype=torch.float32)
64
+ pos = torch.arange(S, device=dev)
65
+ for b0 in range(0, B, CH):
66
+ b1 = min(b0 + CH, B)
67
+ kv = kv_cache[page_table[b0:b1].long()].reshape(b1 - b0, S, 2, Hkv, D).float()
68
+ kc, vc = kv[:, :, 0], kv[:, :, 1] # (b, S, Hkv, D)
69
+ qq = (q[b0:b1].float() * scale).reshape(b1 - b0, Hkv, rep, D)
70
+ s = torch.einsum("bgrd,bsgd->bgrs", qq, kc)
71
+ valid = pos.view(1, 1, 1, -1) < seq_lens[b0:b1].long().view(-1, 1, 1, 1)
72
+ s = s.masked_fill(~valid, float("-inf"))
73
+ p = torch.softmax(s, dim=-1)
74
+ o[b0:b1] = torch.einsum("bgrs,bsgd->bgrd", p, vc).reshape(b1 - b0, Hq, D)
75
+
76
+ # zero-centred RMSNorm over each head's D channels, then the projected sigmoid gate
77
+ n = o * torch.rsqrt(o.pow(2).mean(-1, keepdim=True) + eps) * (1.0 + w_norm.float())
78
+ g = x.float() @ w_gate.float().t() # (B, Hq*D)
79
+ out = n.reshape(B, Hq * D) * torch.sigmoid(g)
80
+ return out.reshape(B, Hq, D).to(torch.bfloat16)
81
+ ''',
82
+ make_inputs_src='''
83
+ def _mk(B, S, Hq, Hkv, D, Dm, P, seed):
84
+ gen = torch.Generator(device="cuda").manual_seed(seed)
85
+ NP = (S + P - 1) // P # pages reserved per request (S is the MAX history length)
86
+ npages = B * NP # the shared pool is exactly full
87
+ q = torch.randn(B, Hq, D, device="cuda", dtype=torch.bfloat16, generator=gen)
88
+ kv_cache = torch.randn(npages, P, 2, Hkv, D, device="cuda", dtype=torch.bfloat16, generator=gen)
89
+ # a real allocator hands out whatever pages are free: the table is a PERMUTATION of the pool, so a
90
+ # request's history is scattered, and the slots past seq_len hold other requests' leftover data
91
+ page_table = torch.randperm(npages, device="cuda", generator=gen).view(B, NP).int()
92
+ seq_lens = torch.tensor(_lens(B, S), device="cuda", dtype=torch.int32) # matches canonical_work()
93
+ x = torch.randn(B, Dm, device="cuda", dtype=torch.bfloat16, generator=gen)
94
+ w_gate = (torch.randn(Hq * D, Dm, device="cuda", generator=gen)
95
+ * (2.0 * Dm ** -0.5)).to(torch.bfloat16)
96
+ w_norm = (torch.rand(D, device="cuda", generator=gen) - 0.5).to(torch.bfloat16) # 1+w in [0.5, 1.5]
97
+ return q, kv_cache, page_table, seq_lens, x, w_gate, w_norm, 1e-6, None
98
+ ''',
99
+ flops_src='''
100
+ def _lens(B, S):
101
+ """The per-request history lengths, from the SHAPE ALONE — a ragged batch spread over [S/2, S)."""
102
+ h = S // 2
103
+ return [h + (b * 997) % h for b in range(B)]
104
+
105
+
106
+ def canonical_work(B, S, Hq, Hkv, D, Dm, P):
107
+ """BYTES attributed to one gated decode step, from the SHAPE ALONE.
108
+
109
+ The unavoidable traffic:
110
+ * the LIVE part of the KV cache read exactly once in bfloat16 -- sum_b seq_len[b] positions, each
111
+ holding Hkv*D keys and Hkv*D values. Reserved-but-unfilled pages are not credited, and neither is
112
+ re-reading a KV head once per query head: the Hq//Hkv heads of a group share it.
113
+ * the gate projection matrix read once: Hq*D*Dm bfloat16 elements.
114
+ * the per-token tensors: q and x in, the (B, Hq, D) output out.
115
+ This is a memory-bound kernel, so the score is achieved bandwidth against this fixed byte count.
116
+ """
117
+ kv = 2 * 2 * Hkv * D * sum(_lens(B, S))
118
+ gate = 2 * Hq * D * Dm
119
+ small = 2 * B * (2 * Hq * D + Dm)
120
+ return kv + gate + small
121
+ ''',
122
+ flops_formula=("seq_len[b] = S//2 + (b * 997) % (S//2) # ragged batch, fixed by the shape\n"
123
+ "bytes = 2*2*Hkv*D*sum_b seq_len[b] + 2*Hq*D*Dm + 2*B*(2*Hq*D + Dm)\n"
124
+ "# one bf16 read of K and V the gate weight per-token tensors"),
125
+
126
+ metric="GB/s",
127
+ compare="tensor",
128
+ tol=7e-3, # MEASURED: 2.1x the 3.31e-3 worst gap to an independent per-request SDPA implementation
129
+ shape_names=("B", "S", "Hq", "Hkv", "D", "Dm", "P"),
130
+ grader_shapes=[(128, 8192, 32, 4, 128, 4096, 64), (160, 8192, 32, 4, 128, 4096, 64),
131
+ (128, 8192, 32, 8, 128, 4096, 128), (96, 16384, 32, 4, 128, 4096, 64),
132
+ (192, 8192, 16, 4, 128, 2048, 64)],
133
+ measure_shapes=[(112, 8192, 32, 4, 128, 4096, 64), (144, 8192, 32, 4, 128, 4096, 64),
134
+ (112, 8192, 32, 8, 128, 4096, 128), (80, 16384, 32, 4, 128, 4096, 64),
135
+ (176, 8192, 16, 4, 128, 2048, 64)],
136
+ measure_quick_shapes=[(16, 2048, 16, 4, 128, 2048, 64), (32, 1024, 8, 2, 128, 1024, 64),
137
+ (8, 4096, 32, 8, 128, 4096, 128)],
138
+ correct_shapes=[(5, 1024, 8, 2, 64, 512, 64), (3, 512, 4, 1, 128, 256, 32),
139
+ (7, 2048, 8, 4, 128, 1024, 128), (2, 256, 16, 4, 64, 512, 64)],
140
+
141
+ spec_md="""One generated token, for every request in the batch. Three things happen and they belong in
142
+ one kernel.
143
+
144
+ **1 — paged GQA attention.** The cache holds K and V **interleaved at each position**: logical position `s`
145
+ of request `b` lives at
146
+
147
+ ```
148
+ page = page_table[b, s // P] ; row = s % P
149
+ K[b, s, g, :] = kv_cache[page, row, 0, g, :]
150
+ V[b, s, g, :] = kv_cache[page, row, 1, g, :]
151
+ ```
152
+
153
+ so one read brings in both. With `rep = Hq // Hkv`, query head `h` uses KV head `h // rep`:
154
+
155
+ ```
156
+ a[b, h, s] = ( q[b, h, :] . K[b, s, h//rep, :] ) * scale for s < seq_lens[b] (scale = D**-0.5)
157
+ a[b, h, s] = -inf for s >= seq_lens[b]
158
+ o[b, h, :] = sum_s softmax(a)[b, h, s] * V[b, s, h//rep, :]
159
+ ```
160
+
161
+ Decode has no causal mask beyond the length: the new token sees the whole valid history.
162
+
163
+ **2 — zero-centred per-head RMSNorm.** Over the `D` channels of **each head separately**, with the gain
164
+ stored centred on zero so the effective multiplier is `1 + w_norm`:
165
+
166
+ ```
167
+ n[b, h, :] = o[b, h, :] * rsqrt( mean_d( o[b, h, d]^2 ) + eps ) * (1 + w_norm)
168
+ ```
169
+
170
+ `w_norm` is a single `(D,)` vector shared by every head. Note the `1 +` — this is not the ordinary RMSNorm
171
+ gain, and using `w_norm` directly is a different function.
172
+
173
+ **3 — the projected sigmoid output gate**, from the block INPUT:
174
+
175
+ ```
176
+ g = x @ w_gate.T # (B, Hq*D)
177
+ out[b, h, d] = n[b, h, d] * sigmoid( g[b, h*D + d] )
178
+ ```
179
+
180
+ The flattening is **head-major**: channel `h*D + d` of `g` gates head `h`, channel `d`. The gate depends
181
+ only on `x`, so it can be computed before or during the attention — it does not wait for it.
182
+
183
+ `/app/reference.py` gathers each request's whole logical cache into fp32 and then does the norm and the
184
+ gate as separate dense steps. That is the exact specification; it is deliberately simple rather than
185
+ fast.""",
186
+
187
+ contract_md="""| arg | shape | dtype | meaning |
188
+ |-----|-------|-------|---------|
189
+ | `q` | `(B, Hq, D)` | `bfloat16` | this token's query |
190
+ | `kv_cache` | `(NUM_PAGES, P, 2, Hkv, D)` | `bfloat16` | page pool; axis 2 is `0 = K`, `1 = V` |
191
+ | `page_table` | `(B, NP)` | `int32` | physical page of each logical page of a request |
192
+ | `seq_lens` | `(B,)` | `int32` | valid cached positions per request |
193
+ | `x` | `(B, Dm)` | `bfloat16` | the block input — the gate's source |
194
+ | `w_gate` | `(Hq*D, Dm)` | `bfloat16` | gate projection, `nn.Linear` layout `(out, in)` |
195
+ | `w_norm` | `(D,)` | `bfloat16` | **zero-centred** head-norm gain; effective gain `1 + w_norm` |
196
+ | `eps` | float | | RMSNorm epsilon, default `1e-6` |
197
+ | `scale` | float or `None` | | logit scale; `None` means `D ** -0.5` |
198
+
199
+ **Return** a single tensor `out` of shape `(B, Hq, D)`, bfloat16 or float32 (the grader compares in fp32).
200
+
201
+ All inputs are **read-only**; nothing is appended to the cache here. `seq_lens[b]` is **not** a multiple of
202
+ `P` — the last page of every request is partially valid — and the batch is ragged, with lengths from `S/2`
203
+ to `S`. `B` is small and not a multiple of anything: the correctness shapes include `B = 3`, `5` and
204
+ `7`.""",
205
+
206
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B`
207
+ (concurrent requests) in 96–192, `S` (maximum history, `NP*P`) in 8192–16384 with real lengths over
208
+ `[S/2, S)`, `Hq` in 16–32 with `Hkv` = `Hq/4` or `Hq/8`, `D` = 128, `Dm` in 2048–4096, `P` 64 or 128.
209
+ That is 1.5–3 GiB of cache read per call against an epilogue that touches a few megabytes — which is
210
+ exactly why the epilogue must cost nothing.""",
211
+
212
+ correctness_md="""The returned tensor must match the reference (evaluated in fp32) within **relative
213
+ Frobenius error `7e-3`** at every graded shape, including the timed ones.
214
+
215
+ That gate is **measured**, and dropping any part of the epilogue misses it by orders of magnitude:
216
+ returning the ungated (but normalised) attention output scores **0.97**, using a plain RMSNorm gain
217
+ `w_norm` instead of the zero-centred `1 + w_norm` scores **0.93**, skipping the per-head normalisation
218
+ scores **0.87**, and using SiLU instead of sigmoid for the gate scores **1.38** — the closest is **124x**
219
+ the tolerance.""",
220
+
221
+ perf_md="""The KV cache decides the score and everything else must hide behind it.
222
+
223
+ **The attention.** A page is `P x 2 x Hkv x D` contiguous, with K and V adjacent at every position, so one
224
+ sweep brings in both operands of the two matmuls — that layout exists precisely so a decode kernel does not
225
+ make two passes. Use an online (flash-decoding) softmax with the query in registers, vectorised 128-bit
226
+ loads, and one KV tile serving all `Hq/Hkv` query heads of its group. Skip whole pages past `seq_lens[b]`:
227
+ they are mapped but dead, and at these lengths a quarter of the reserved pages are.
228
+
229
+ **The load imbalance is the other half of the problem.** Lengths run from `S/2` to `S` and `B` is only
230
+ around 128, so a one-block-per-(request, head-group) grid leaves most of the machine idle. Split each
231
+ request's history across blocks, keep per-block partial `(o, m, l)` triples, and merge them with the
232
+ standard log-sum-exp combine — the merge is tiny compared with the read.
233
+
234
+ **The epilogue is free if you fuse it.** `o` is `(B, Hq, D)` — a few megabytes. The head-norm is a
235
+ reduction over `D = 128` lanes, i.e. one warp, on data that is already in registers at the end of the
236
+ softmax merge. The gate is a `(B, Dm) x (Dm, Hq*D)` projection: at `B` in the low hundreds it is
237
+ weight-bound, ~33 MB read once, and it depends only on `x` — so it can be issued first, or overlapped with
238
+ the cache streaming, and its result consumed exactly where the accumulator lives. Writing `o` to HBM,
239
+ reading it back to normalise, then reading it again to gate is three avoidable round trips plus two
240
+ launches on the per-token critical path.""",
241
+
242
+ precision_md="""The cache, the query, `x` and both weights are **bfloat16**; the output may be bf16 or
243
+ fp32.
244
+
245
+ Accumulate the logits, the online softmax, the `p @ v` product, the RMSNorm reduction and the gate GEMM in
246
+ **fp32**, and evaluate the sigmoid in fp32 — a bf16 sigmoid loses enough precision near zero to show up in
247
+ the norm. When you merge partial softmaxes across split-K blocks, merge in fp32 as well.
248
+
249
+ **fp8 is not appropriate here**: the cache arrives in bf16 and re-quantising it on the fly is an
250
+ approximation of the specified computation rather than an implementation of it.
251
+
252
+ **Where the tolerance comes from.** `8e-3` is measured. A second, independent implementation — the pages
253
+ gathered per request, the attention run as a bf16 `scaled_dot_product_attention` over the gathered cache
254
+ (an online softmax with a completely different reduction order from the reference's dense one), the gate
255
+ as a bf16 tensor-core GEMM and the head-norm computed with `norm()` instead of `mean(pow(2))` — differs
256
+ from this fp32 reference by a worst relative Frobenius error of **3.31e-3** across the correctness shapes
257
+ and a full-size graded shape, over several seeds. The tolerance is **2.1x** that, and nearly all of it is
258
+ the bf16 rounding of the returned tensor — the number does not move with `S` or `B`.""",
259
+ ).validate()
tools/factory/specs/qwen3_next_gdn_inproj.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `qwen3-next-gdn-inproj` — the Qwen3-Next gated-DeltaNet input projection: zero-centred RMSNorm,
2
+ one fused QKVZ+BA projection, per-head L2 normalisation and the two recurrence gates."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="qwen3-next-gdn-inproj",
11
+ title="Write a fast gated-DeltaNet input-projection kernel (norm + fused proj + gates)",
12
+ blurb=("Three quarters of the layers in Qwen3-Next are gated-DeltaNet blocks, and every one of them "
13
+ "starts here: zero-centred RMSNorm on the residual stream, one wide fused projection into "
14
+ "queries, keys, values and the output gate, a second tiny projection into the two recurrence "
15
+ "gates, then per-head L2 normalisation of q and k, a sigmoid for the delta-rule step size and a "
16
+ "softplus-and-negate for the log forget gate. Run as fifteen separate torch ops it drags the "
17
+ "(T, 12k) projection output through HBM four times and launches a kernel for every activation; "
18
+ "fused, it is one GEMM with an epilogue."),
19
+ keywords=["mle", "kernel-generation", "qwen3-next", "gated-deltanet", "linear-attention", "rmsnorm",
20
+ "l2-norm", "gemm", "fusion", "compute-bound"],
21
+ module="gdn_inproj.py",
22
+ func="gdn_in_projection",
23
+ signature=("gdn_in_projection(x, w_norm, w_qkvz, w_ba, a_log, dt_bias, "
24
+ "num_k_heads, head_k_dim, head_v_dim, eps=1e-6)"),
25
+ returns_doc="""Gated-DeltaNet input projection: zero-centred RMSNorm, fused projection, gates.
26
+
27
+ Args:
28
+ x: (T, Dm) bfloat16 — the residual stream entering the block.
29
+ w_norm: (Dm,) bfloat16 — ZERO-CENTRED RMSNorm gain; the effective gain is (1 + w_norm).
30
+ w_qkvz: (Wq, Dm) bfloat16 — fused q|k|v|z projection, nn.Linear layout (out, in), where
31
+ Wq = 2*Hk*Dk + 2*Hv*Dv.
32
+ w_ba: (2*Hv, Dm) bfloat16 — fused b|a projection, nn.Linear layout (out, in).
33
+ a_log: (Hv,) float32 — log of the per-head base decay rate; Hv is taken from its length.
34
+ dt_bias: (Hv,) float32 — per-head bias added before the softplus.
35
+ num_k_heads: int — Hk.
36
+ head_k_dim: int — Dk.
37
+ head_v_dim: int — Dv.
38
+ eps: float — RMSNorm epsilon.
39
+
40
+ Returns:
41
+ (q, k, v, z, beta, g) where
42
+ q: (T, Hk, Dk) bfloat16 — L2-normalised per head
43
+ k: (T, Hk, Dk) bfloat16 — L2-normalised per head
44
+ v: (T, Hv, Dv) bfloat16
45
+ z: (T, Hv, Dv) bfloat16 — the block's output gate, passed through un-activated
46
+ beta: (T, Hv) float32 — delta-rule step size, sigmoid(b)
47
+ g: (T, Hv) float32 — log forget gate, -exp(a_log) * softplus(a + dt_bias)""",
48
+
49
+ reference_imports="import torch\nimport torch.nn.functional as F",
50
+ reference_src='''
51
+ def gdn_in_projection(x, w_norm, w_qkvz, w_ba, a_log, dt_bias,
52
+ num_k_heads, head_k_dim, head_v_dim, eps=1e-6):
53
+ """Norm, project, split, normalise, gate — as separate fp32 steps.
54
+
55
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. The full (T, Wq)
56
+ projection output is materialised in fp32 and then read again by every split.
57
+ """
58
+ T = x.shape[0]
59
+ Hk, Dk, Dv = num_k_heads, head_k_dim, head_v_dim
60
+ Hv = a_log.shape[0]
61
+
62
+ xf = x.float()
63
+ h = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) * (1.0 + w_norm.float()) # ZERO-CENTRED
64
+ p = h @ w_qkvz.float().t() # (T, 2*Hk*Dk + 2*Hv*Dv)
65
+
66
+ o = 0
67
+ q = p[:, o:o + Hk * Dk].reshape(T, Hk, Dk); o += Hk * Dk
68
+ k = p[:, o:o + Hk * Dk].reshape(T, Hk, Dk); o += Hk * Dk
69
+ v = p[:, o:o + Hv * Dv].reshape(T, Hv, Dv); o += Hv * Dv
70
+ z = p[:, o:o + Hv * Dv].reshape(T, Hv, Dv)
71
+
72
+ q = q * torch.rsqrt(q.pow(2).sum(-1, keepdim=True) + 1e-12) # per-head L2 normalisation
73
+ k = k * torch.rsqrt(k.pow(2).sum(-1, keepdim=True) + 1e-12)
74
+
75
+ ba = h @ w_ba.float().t() # (T, 2*Hv)
76
+ beta = torch.sigmoid(ba[:, :Hv])
77
+ g = -torch.exp(a_log.float()) * F.softplus(ba[:, Hv:] + dt_bias.float())
78
+ return (q.to(torch.bfloat16), k.to(torch.bfloat16), v.to(torch.bfloat16), z.to(torch.bfloat16),
79
+ beta.float(), g.float())
80
+ ''',
81
+ make_inputs_src='''
82
+ def _mk(T, Dm, Hk, Dk, Hv, Dv, seed):
83
+ """Residual stream, the two projections and the gate parameters. `dt_bias` is centred so the softplus
84
+ argument spans roughly (-2, 2) — the regime where the forget gate is actually data-dependent rather
85
+ than saturated."""
86
+ gen = torch.Generator(device="cuda").manual_seed(seed)
87
+
88
+ def r(*sh, s=1.0):
89
+ return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
90
+
91
+ Wq = 2 * Hk * Dk + 2 * Hv * Dv
92
+ x = r(T, Dm)
93
+ w_norm = (torch.rand(Dm, device="cuda", generator=gen) - 0.5).to(torch.bfloat16) # (1 + w) in [.5,1.5]
94
+ w_qkvz = r(Wq, Dm, s=Dm ** -0.5)
95
+ w_ba = r(2 * Hv, Dm, s=Dm ** -0.5)
96
+ a_log = torch.rand(Hv, device="cuda", dtype=torch.float32, generator=gen) * 2.0 - 1.0
97
+ dt_bias = torch.randn(Hv, device="cuda", dtype=torch.float32, generator=gen) * 0.5
98
+ return x, w_norm, w_qkvz, w_ba, a_log, dt_bias, Hk, Dk, Dv, 1e-6
99
+ ''',
100
+ flops_src='''
101
+ def canonical_work(T, Dm, Hk, Dk, Hv, Dv):
102
+ """FLOPs attributed to one input projection, from the SHAPE ALONE.
103
+
104
+ Two GEMMs at 2 FLOPs per multiply-add against the same normalised activation: the wide q|k|v|z
105
+ projection of width 2*Hk*Dk + 2*Hv*Dv, and the tiny b|a projection of width 2*Hv. The RMSNorm, the
106
+ per-head L2 normalisation, the sigmoid and the softplus are O(T * width) elementwise work and are NOT
107
+ credited — fusing them is a saving, not extra work you get paid for.
108
+ """
109
+ return 2 * T * Dm * (2 * Hk * Dk + 2 * Hv * Dv) + 2 * T * Dm * (2 * Hv)
110
+ ''',
111
+ flops_formula=("canonical_work(T, Dm, Hk, Dk, Hv, Dv) = 2*T*Dm*(2*Hk*Dk + 2*Hv*Dv) + 2*T*Dm*(2*Hv)\n"
112
+ "# q|k|v|z projection b|a projection"),
113
+
114
+ metric="TFLOP/s",
115
+ compare="tuple",
116
+ tuple_names=("q", "k", "v", "z", "beta", "g"),
117
+ tol=7e-3, # MEASURED: 2.1x the 3.31e-3 worst gap to an independent fused-GEMM implementation
118
+ shape_names=("T", "Dm", "Hk", "Dk", "Hv", "Dv"),
119
+ grader_shapes=[(32768, 2048, 16, 128, 32, 128), (16384, 4096, 16, 128, 32, 128),
120
+ (49152, 2048, 8, 128, 16, 128), (24576, 2048, 16, 128, 32, 128),
121
+ (32768, 2048, 32, 64, 32, 128)],
122
+ measure_shapes=[(28672, 2048, 16, 128, 32, 128), (12288, 4096, 16, 128, 32, 128),
123
+ (40960, 2048, 8, 128, 16, 128), (20480, 2048, 16, 128, 32, 128),
124
+ (28672, 2048, 32, 64, 32, 128)],
125
+ measure_quick_shapes=[(4096, 1024, 8, 128, 8, 128), (2048, 2048, 4, 128, 8, 128),
126
+ (8192, 512, 4, 64, 8, 64)],
127
+ correct_shapes=[(256, 512, 4, 64, 8, 64), (129, 256, 2, 32, 4, 64), (512, 1024, 8, 128, 8, 128),
128
+ (64, 128, 1, 64, 2, 64)],
129
+
130
+ spec_md="""Everything a gated-DeltaNet block needs, produced from the residual stream in one pass.
131
+
132
+ **1 — zero-centred RMSNorm.** The gain is stored *centred on zero* and the effective multiplier is
133
+ `1 + w_norm`, so an untrained parameter is the identity and weight decay pulls towards it:
134
+
135
+ ```
136
+ h[t, :] = x[t, :] * rsqrt( mean_c( x[t, c]^2 ) + eps ) * (1 + w_norm)
137
+ ```
138
+
139
+ The mean runs over the full `Dm` feature axis. Note the `1 +`: this is **not** the ordinary RMSNorm gain.
140
+
141
+ **2 — the two projections**, both from `h`:
142
+
143
+ ```
144
+ p = h @ w_qkvz.T # (T, 2*Hk*Dk + 2*Hv*Dv)
145
+ ba = h @ w_ba.T # (T, 2*Hv)
146
+ ```
147
+
148
+ `p` is split along its last axis, **in this order**, into four contiguous blocks:
149
+
150
+ ```
151
+ q = p[:, : Hk*Dk ].view(T, Hk, Dk)
152
+ k = p[:, Hk*Dk : 2*Hk*Dk ].view(T, Hk, Dk)
153
+ v = p[:, 2*Hk*Dk : 2*Hk*Dk + Hv*Dv ].view(T, Hv, Dv)
154
+ z = p[:, 2*Hk*Dk + Hv*Dv : ].view(T, Hv, Dv)
155
+ ```
156
+
157
+ `ba` splits into `b = ba[:, :Hv]` and `a = ba[:, Hv:]`.
158
+
159
+ **3 — per-head L2 normalisation of q and k** (this is what keeps the delta rule stable; it is an L2
160
+ normalisation, **not** an RMSNorm and there is no learned gain):
161
+
162
+ ```
163
+ q[t, h, :] <- q[t, h, :] * rsqrt( sum_d q[t, h, d]^2 + 1e-12 )
164
+ k[t, h, :] <- k[t, h, :] * rsqrt( sum_d k[t, h, d]^2 + 1e-12 )
165
+ ```
166
+
167
+ `v` and `z` are **not** normalised and `z` is **not** activated — the output gate's SiLU happens later, in
168
+ the block's output path, not here.
169
+
170
+ **4 — the two recurrence gates**, per token and per value head:
171
+
172
+ ```
173
+ beta[t, h] = sigmoid( b[t, h] ) # delta-rule step size, in (0, 1)
174
+ g[t, h] = -exp( a_log[h] ) * softplus( a[t, h] + dt_bias[h] ) # LOG forget gate, <= 0
175
+ ```
176
+
177
+ `softplus(u) = log(1 + exp(u))`, and `exp(g)` is the multiplicative decay the recurrence applies — so `g`
178
+ is always negative and must be produced in fp32, not bf16: it is fed to an exponential downstream and bf16
179
+ rounding of a log-decay is a visible change in the decay itself.
180
+
181
+ `/app/reference.py` materialises the whole fp32 projection output and then slices it. That is the exact
182
+ specification; it is deliberately simple rather than fast.""",
183
+
184
+ contract_md="""| arg | shape | dtype | meaning |
185
+ |-----|-------|-------|---------|
186
+ | `x` | `(T, Dm)` | `bfloat16` | residual stream entering the block |
187
+ | `w_norm` | `(Dm,)` | `bfloat16` | **zero-centred** RMSNorm gain; effective gain is `1 + w_norm` |
188
+ | `w_qkvz` | `(2*Hk*Dk + 2*Hv*Dv, Dm)` | `bfloat16` | fused q\\|k\\|v\\|z projection, `(out, in)` |
189
+ | `w_ba` | `(2*Hv, Dm)` | `bfloat16` | fused b\\|a projection, `(out, in)` |
190
+ | `a_log` | `(Hv,)` | `float32` | log of the per-head base decay |
191
+ | `dt_bias` | `(Hv,)` | `float32` | per-head bias inside the softplus |
192
+ | `num_k_heads` | int | | `Hk` |
193
+ | `head_k_dim` | int | | `Dk` |
194
+ | `head_v_dim` | int | | `Dv`; `Hv` is `len(a_log)` |
195
+ | `eps` | float | | RMSNorm epsilon, default `1e-6` |
196
+
197
+ **Return a 6-tuple in exactly this order:**
198
+
199
+ | out | shape | dtype | notes |
200
+ |-----|-------|-------|-------|
201
+ | `q` | `(T, Hk, Dk)` | bf16 | L2-normalised per head |
202
+ | `k` | `(T, Hk, Dk)` | bf16 | L2-normalised per head |
203
+ | `v` | `(T, Hv, Dv)` | bf16 | not normalised |
204
+ | `z` | `(T, Hv, Dv)` | bf16 | not normalised, not activated |
205
+ | `beta` | `(T, Hv)` | **fp32** | |
206
+ | `g` | `(T, Hv)` | **fp32** | negative |
207
+
208
+ `Hk` divides `Hv` in practice but nothing in the kernel needs that. All inputs are **read-only**. `T` is
209
+ **not** guaranteed to be a multiple of any tile size — the correctness shapes include `T = 129` and
210
+ `T = 64`.""",
211
+
212
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `T`
213
+ (tokens in the micro-batch) in 16384–49152, `Dm` in 2048–4096, `Hk` in 8–32 with `Dk` 64–128, `Hv` in
214
+ 16–32 with `Dv` = 128. The fused projection is 3–6x wider than the model dimension, so its output is the
215
+ largest tensor in the block — which is exactly why the epilogue has to stay fused.""",
216
+
217
+ correctness_md="""**All six** returned tensors must match the reference (evaluated in fp32) within
218
+ **relative Frobenius error `7e-3`** at every graded shape, including the timed ones; the grader scores the
219
+ **worst** of the six.
220
+
221
+ That gate is **measured**, and dropping any single piece of this kernel misses it by orders of magnitude:
222
+ skipping the per-head L2 normalisation of `q` and `k` scores **4.8**, using a plain RMSNorm gain `w_norm`
223
+ instead of the zero-centred `1 + w_norm` scores **1.15**, dropping the `-exp(a_log)` head scale from the
224
+ forget gate scores **0.41**, and using `exp` instead of `softplus` inside it scores **2.1** — the closest
225
+ of them is **59x** the tolerance.""",
226
+
227
+ perf_md="""One wide GEMM, one skinny GEMM, and an epilogue that a framework implementation turns into
228
+ a dozen full-size passes over HBM.
229
+
230
+ The wide projection is `(T, Dm) x (Dm, 2*Hk*Dk + 2*Hv*Dv)` and dominates the FLOP count. The skinny one is
231
+ `(T, Dm) x (Dm, 2*Hv)` — 64 output columns against 2048 reduction steps, so on its own it is pure latency;
232
+ it wants to be concatenated onto the wide one (they share the operand `h`) or run as a tail wave rather
233
+ than as its own launch.
234
+
235
+ `h` itself is worth computing once and keeping: both GEMMs read it, and the RMSNorm that produces it is a
236
+ row reduction over `Dm` that fits in a block. Writing `h` to HBM and reading it back twice is one avoidable
237
+ round trip of a `(T, Dm)` tensor.
238
+
239
+ The epilogue is where the naive version loses. Splitting `p` into four views and normalising two of them
240
+ means, done separately, four reads and four writes of a tensor several times larger than `x`. Fused, the
241
+ L2 normalisation is a reduction over `Dk = 64..128` contiguous lanes of an accumulator tile that is
242
+ **already in registers** when the GEMM epilogue runs — one warp-level reduction, no HBM round trip at all.
243
+
244
+ `beta` and `g` come out of only 64 columns; compute them in the same launch, and remember `softplus` needs
245
+ the numerically stable form (`max(u,0) + log1p(exp(-|u|))`) because `a + dt_bias` is unbounded.""",
246
+
247
+ precision_md="""Inputs are **bfloat16** and the four projected outputs are returned in bf16, but
248
+ `beta` and `g` **must be fp32**: they parameterise a recurrence that runs for thousands of steps, and `g`
249
+ in particular is a log-decay that gets exponentiated downstream, so bf16 rounding of it is a change to the
250
+ model, not a rounding of an activation.
251
+
252
+ Do the RMSNorm reduction, the L2 reduction, the sigmoid and the softplus in **fp32**; bf16 tensor-core
253
+ GEMMs with fp32 accumulate are exactly what this task expects.
254
+
255
+ **fp8 is not appropriate here**: the activations and weights arrive in bf16 and re-quantising them is an
256
+ approximation of the specified computation, not an implementation of it.
257
+
258
+ **Where the tolerance comes from.** `1e-2` is measured, not inherited. A second, independent implementation
259
+ — one fused `[w_qkvz ; w_ba]` GEMM instead of two, bf16 operands with fp32 accumulate, the RMSNorm computed
260
+ from a `float()` upcast in a different order, and the L2 normalisation done as a `norm()` divide rather
261
+ than an `rsqrt` multiply — differs from this fp32 reference by a worst relative Frobenius error of
262
+ **3.31e-3** across the correctness shapes and a full-size graded shape, over several seeds. The tolerance
263
+ is **2.1x** that. It is flat in the problem size (3.19e-3 to 3.31e-3 everywhere tried) because it is
264
+ nothing but the bf16 rounding of the returned tensors; an error that *grows* with `T` means an accumulator
265
+ is too narrow, not that the gate is too tight.""",
266
+ ).validate()
tools/factory/specs/qwen3_next_gdn_inproj_backward.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `qwen3-next-gdn-inproj-backward` — the training-side backward of the Qwen3-Next gated-DeltaNet
2
+ input projection (zero-centred RMSNorm, fused projection, per-head L2 norm, sigmoid/softplus gates)."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ _FWD = '''
10
+ def _gdn_in_projection(x, w_norm, w_qkvz, w_ba, a_log, dt_bias, Hk, Dk, Dv, eps):
11
+ """The fp32 forward of `qwen3-next-gdn-inproj`, differentiable. Autograd through THIS defines
12
+ every gradient this task asks for."""
13
+ T = x.shape[0]
14
+ Hv = a_log.shape[0]
15
+ h = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * (1.0 + w_norm) # ZERO-CENTRED RMSNorm
16
+ p = h @ w_qkvz.t()
17
+ o = 0
18
+ q = p[:, o:o + Hk * Dk].reshape(T, Hk, Dk); o += Hk * Dk
19
+ k = p[:, o:o + Hk * Dk].reshape(T, Hk, Dk); o += Hk * Dk
20
+ v = p[:, o:o + Hv * Dv].reshape(T, Hv, Dv); o += Hv * Dv
21
+ z = p[:, o:o + Hv * Dv].reshape(T, Hv, Dv)
22
+ q = q * torch.rsqrt(q.pow(2).sum(-1, keepdim=True) + 1e-12) # per-head L2 norm
23
+ k = k * torch.rsqrt(k.pow(2).sum(-1, keepdim=True) + 1e-12)
24
+ ba = h @ w_ba.t()
25
+ beta = torch.sigmoid(ba[:, :Hv])
26
+ g = -torch.exp(a_log) * F.softplus(ba[:, Hv:] + dt_bias)
27
+ return q, k, v, z, beta, g
28
+
29
+
30
+ def gdn_in_projection_backward(x, w_norm, w_qkvz, w_ba, a_log, dt_bias,
31
+ dq, dk, dv, dz, dbeta, dg,
32
+ num_k_heads, head_k_dim, head_v_dim, eps=1e-6):
33
+ """The baseline re-runs the fp32 forward under autograd and lets it differentiate itself."""
34
+ ins = [t.detach().clone().float().requires_grad_(True)
35
+ for t in (x, w_norm, w_qkvz, w_ba, a_log, dt_bias)]
36
+ outs = _gdn_in_projection(*ins, num_k_heads, head_k_dim, head_v_dim, eps)
37
+ gs = [t.float() for t in (dq, dk, dv, dz, dbeta, dg)]
38
+ return torch.autograd.grad(outs, ins, gs)
39
+ '''
40
+
41
+ SPEC = TaskSpec(
42
+ name="qwen3-next-gdn-inproj-backward",
43
+ title="Write a fast backward kernel for the gated-DeltaNet input projection",
44
+ blurb=("Differentiating the Qwen3-Next gated-DeltaNet input projection is four separate backward "
45
+ "problems glued together: a per-head L2 normalisation (whose Jacobian is a rank-1 correction, "
46
+ "not a scale), a sigmoid and a softplus feeding a log-decay gate, one wide and one skinny "
47
+ "projection, and a zero-centred RMSNorm whose gain gradient is a reduction over every token. "
48
+ "Autograd runs it as thirty kernels and rebuilds the (T, 12k) projection output twice."),
49
+ keywords=["mle", "kernel-generation", "qwen3-next", "gated-deltanet", "backward", "training",
50
+ "rmsnorm", "l2-norm", "gemm", "compute-bound"],
51
+ module="gdn_inproj_bwd.py",
52
+ func="gdn_in_projection_backward",
53
+ signature=("gdn_in_projection_backward(x, w_norm, w_qkvz, w_ba, a_log, dt_bias, "
54
+ "dq, dk, dv, dz, dbeta, dg, num_k_heads, head_k_dim, head_v_dim, eps=1e-6)"),
55
+ returns_doc="""Backward of the gated-DeltaNet input projection.
56
+
57
+ Args:
58
+ x: (T, Dm) bfloat16 — the residual stream saved by the forward.
59
+ w_norm: (Dm,) bfloat16 — zero-centred RMSNorm gain; effective gain is (1 + w_norm).
60
+ w_qkvz: (Wq, Dm) bfloat16 — fused q|k|v|z projection, Wq = 2*Hk*Dk + 2*Hv*Dv.
61
+ w_ba: (2*Hv, Dm) bfloat16 — fused b|a projection.
62
+ a_log: (Hv,) float32 — log of the per-head base decay.
63
+ dt_bias: (Hv,) float32 — per-head bias inside the softplus.
64
+ dq, dk: (T, Hk, Dk) bfloat16 — incoming gradients w.r.t. the L2-NORMALISED q and k.
65
+ dv, dz: (T, Hv, Dv) bfloat16 — incoming gradients w.r.t. v and z.
66
+ dbeta: (T, Hv) float32 — incoming gradient w.r.t. beta.
67
+ dg: (T, Hv) float32 — incoming gradient w.r.t. the log forget gate g.
68
+ num_k_heads, head_k_dim, head_v_dim: int — Hk, Dk, Dv. Hv is len(a_log).
69
+ eps: float — RMSNorm epsilon.
70
+
71
+ Returns:
72
+ (dx, dw_norm, dw_qkvz, dw_ba, da_log, ddt_bias) with shapes
73
+ (T, Dm), (Dm,), (Wq, Dm), (2*Hv, Dm), (Hv,), (Hv,).""",
74
+
75
+ reference_imports="import torch\nimport torch.nn.functional as F",
76
+ reference_src=_FWD,
77
+ make_inputs_src='''
78
+ def _mk(T, Dm, Hk, Dk, Hv, Dv, seed):
79
+ """Saved forward inputs plus the six incoming gradients.
80
+
81
+ `dq` and `dk` are NOT pure noise: each is given a component ALONG the (normalised) q or k it belongs
82
+ to, because that radial component is exactly what the L2-normalisation Jacobian annihilates. A
83
+ gradient drawn from isotropic noise would put only 1/sqrt(Dk) of its energy there and would barely
84
+ exercise the term. `dt_bias` is centred so the softplus argument spans roughly (-2, 2), the regime
85
+ where the forget gate is genuinely data-dependent.
86
+ """
87
+ gen = torch.Generator(device="cuda").manual_seed(seed)
88
+
89
+ def r(*sh, s=1.0):
90
+ return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
91
+
92
+ Wq = 2 * Hk * Dk + 2 * Hv * Dv
93
+ x = r(T, Dm)
94
+ w_norm = (torch.rand(Dm, device="cuda", generator=gen) - 0.5).to(torch.bfloat16)
95
+ w_qkvz = r(Wq, Dm, s=Dm ** -0.5)
96
+ w_ba = r(2 * Hv, Dm, s=Dm ** -0.5)
97
+ a_log = torch.rand(Hv, device="cuda", dtype=torch.float32, generator=gen) * 2.0 - 1.0
98
+ dt_bias = torch.randn(Hv, device="cuda", dtype=torch.float32, generator=gen) * 0.5
99
+
100
+ # the forward q/k directions, so the incoming gradient can be given a radial component
101
+ xf = x.float()
102
+ h = (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + 1e-6) * (1.0 + w_norm.float())).to(
103
+ torch.bfloat16)
104
+ qk = (h @ w_qkvz[:2 * Hk * Dk].t()).float().reshape(T, 2 * Hk, Dk)
105
+ direction = qk * torch.rsqrt(qk.pow(2).sum(-1, keepdim=True) + 1e-12)
106
+ base = torch.randn(T, 2 * Hk, Dk, device="cuda", dtype=torch.float32, generator=gen)
107
+ gqk = base + direction * base.norm(dim=-1, keepdim=True) # ~half the energy is radial
108
+ dq = gqk[:, :Hk].contiguous().to(torch.bfloat16)
109
+ dk = gqk[:, Hk:].contiguous().to(torch.bfloat16)
110
+ del xf, h, qk, direction, base, gqk
111
+
112
+ dv, dz = r(T, Hv, Dv), r(T, Hv, Dv)
113
+ dbeta = torch.randn(T, Hv, device="cuda", dtype=torch.float32, generator=gen)
114
+ dg = torch.randn(T, Hv, device="cuda", dtype=torch.float32, generator=gen)
115
+ return (x, w_norm, w_qkvz, w_ba, a_log, dt_bias, dq, dk, dv, dz, dbeta, dg, Hk, Dk, Dv, 1e-6)
116
+ ''',
117
+ flops_src='''
118
+ def canonical_work(T, Dm, Hk, Dk, Hv, Dv):
119
+ """FLOPs attributed to one backward call, from the SHAPE ALONE.
120
+
121
+ THREE passes of each projection shape, at 2 FLOPs per multiply-add:
122
+ 1. recomputing p = h @ w_qkvz.T and ba = h @ w_ba.T (the pre-normalisation q and k are NOT
123
+ arguments, and the L2 backward needs them)
124
+ 2. dh = dp @ w_qkvz + dba @ w_ba
125
+ 3. dw_qkvz = dp.T @ h and dw_ba = dba.T @ h
126
+ Everything else — the L2-normalisation Jacobian, the sigmoid and softplus derivatives, the RMSNorm
127
+ backward and the dw_norm / da_log / ddt_bias reductions — is O(T * width) elementwise work and is NOT
128
+ credited.
129
+ """
130
+ return 6 * T * Dm * (2 * Hk * Dk + 2 * Hv * Dv + 2 * Hv)
131
+ ''',
132
+ flops_formula=("canonical_work(T, Dm, Hk, Dk, Hv, Dv) = 6 * T * Dm * (2*Hk*Dk + 2*Hv*Dv + 2*Hv)\n"
133
+ "# = 3 passes (recompute p/ba, dh, dw) over both projection shapes"),
134
+
135
+ metric="TFLOP/s",
136
+ compare="tuple",
137
+ tuple_names=("dx", "dw_norm", "dw_qkvz", "dw_ba", "da_log", "ddt_bias"),
138
+ tol=2e-2, # MEASURED: 2.4x the 8.4e-3 worst gap to an independent hand-written bf16 backward
139
+ shape_names=("T", "Dm", "Hk", "Dk", "Hv", "Dv"),
140
+ grader_shapes=[(16384, 2048, 16, 128, 32, 128), (8192, 4096, 16, 128, 32, 128),
141
+ (24576, 2048, 8, 128, 16, 128), (12288, 2048, 16, 128, 32, 128),
142
+ (16384, 2048, 32, 64, 32, 128)],
143
+ measure_shapes=[(14336, 2048, 16, 128, 32, 128), (7168, 4096, 16, 128, 32, 128),
144
+ (20480, 2048, 8, 128, 16, 128), (10240, 2048, 16, 128, 32, 128),
145
+ (14336, 2048, 32, 64, 32, 128)],
146
+ measure_quick_shapes=[(2048, 1024, 8, 128, 8, 128), (1024, 2048, 4, 128, 8, 128),
147
+ (4096, 512, 4, 64, 8, 64)],
148
+ correct_shapes=[(256, 512, 4, 64, 8, 64), (257, 256, 2, 32, 4, 64), (512, 1024, 8, 128, 8, 128),
149
+ (192, 128, 2, 64, 4, 64)],
150
+
151
+ spec_md="""The forward being differentiated is the gated-DeltaNet input projection:
152
+
153
+ ```
154
+ h = x * rsqrt(mean_c(x^2) + eps) * (1 + w_norm) # ZERO-CENTRED RMSNorm
155
+ p = h @ w_qkvz.T # (T, 2*Hk*Dk + 2*Hv*Dv)
156
+ ba = h @ w_ba.T # (T, 2*Hv)
157
+ qr,kr,v,z= split(p) in that order, widths Hk*Dk, Hk*Dk, Hv*Dv, Hv*Dv
158
+ q = qr * rsqrt(sum_d qr^2 + 1e-12) # per-head L2 normalisation
159
+ k = kr * rsqrt(sum_d kr^2 + 1e-12)
160
+ beta = sigmoid(ba[:, :Hv])
161
+ g = -exp(a_log) * softplus(ba[:, Hv:] + dt_bias)
162
+ ```
163
+
164
+ You get `dq, dk, dv, dz, dbeta, dg` and must return the gradient w.r.t. `x`, `w_norm`, `w_qkvz`, `w_ba`,
165
+ `a_log` and `dt_bias`.
166
+
167
+ **The L2 normalisation is the piece that catches people.** With `r = rsqrt(sum_d qr^2 + 1e-12)` and `q` the
168
+ *normalised* output, the Jacobian is a rank-1 correction, not a scale:
169
+
170
+ ```
171
+ dqr[t,h,:] = r[t,h] * ( dq[t,h,:] - q[t,h,:] * dot( dq[t,h,:], q[t,h,:] ) )
172
+ ```
173
+
174
+ Multiplying `dq` by `r` and stopping is wrong by a term of the same magnitude.
175
+
176
+ **The gates**, with `u = ba[:, Hv:] + dt_bias`:
177
+
178
+ ```
179
+ db[t,h] = dbeta[t,h] * beta[t,h] * (1 - beta[t,h])
180
+ da[t,h] = dg[t,h] * ( -exp(a_log[h]) ) * sigmoid(u[t,h]) # d softplus / du = sigmoid(u)
181
+ da_log[h] = sum_t dg[t,h] * g[t,h] # since dg/d a_log = g itself
182
+ ddt_bias[h] = sum_t da[t,h]
183
+ ```
184
+
185
+ **The projections**, with `dp = concat(dqr, dkr, dv, dz)` and `dba = concat(db, da)`:
186
+
187
+ ```
188
+ dh = dp @ w_qkvz + dba @ w_ba # (T, Dm)
189
+ dw_qkvz = dp.T @ h # (Wq, Dm)
190
+ dw_ba = dba.T @ h # (2*Hv, Dm)
191
+ ```
192
+
193
+ **The zero-centred RMSNorm**, with `rstd[t] = rsqrt(mean_c(x[t]^2) + eps)` and `xhat = x * rstd`:
194
+
195
+ ```
196
+ dw_norm[c] = sum_t dh[t,c] * xhat[t,c] # gain is (1 + w_norm), so d/dw = xhat
197
+ dxhat[t,c] = dh[t,c] * (1 + w_norm[c])
198
+ dx[t,c] = ( dxhat[t,c] - xhat[t,c] * mean_c( dxhat[t,:] * xhat[t,:] ) ) * rstd[t]
199
+ ```
200
+
201
+ Note what is **not** an argument: `h`, `p`, and the pre-normalisation `qr`/`kr` were all forward
202
+ temporaries. They must be recomputed — `h` is cheap, `p` costs a full matmul, and the L2 backward cannot be
203
+ written without `qr` (or equivalently without `q` and `r`).
204
+
205
+ `/app/reference.py` re-runs the fp32 forward under autograd and differentiates it. That is the exact
206
+ specification; it is deliberately simple rather than fast.""",
207
+
208
+ contract_md="""| arg | shape | dtype | meaning |
209
+ |-----|-------|-------|---------|
210
+ | `x` | `(T, Dm)` | `bfloat16` | residual stream saved by the forward |
211
+ | `w_norm` | `(Dm,)` | `bfloat16` | zero-centred gain; effective gain is `1 + w_norm` |
212
+ | `w_qkvz` | `(Wq, Dm)` | `bfloat16` | fused projection, `Wq = 2*Hk*Dk + 2*Hv*Dv` |
213
+ | `w_ba` | `(2*Hv, Dm)` | `bfloat16` | fused gate projection |
214
+ | `a_log`, `dt_bias` | `(Hv,)` | `float32` | forget-gate parameters |
215
+ | `dq`, `dk` | `(T, Hk, Dk)` | `bfloat16` | gradients w.r.t. the **normalised** q and k |
216
+ | `dv`, `dz` | `(T, Hv, Dv)` | `bfloat16` | gradients w.r.t. v and z |
217
+ | `dbeta`, `dg` | `(T, Hv)` | `float32` | gradients w.r.t. the two gates |
218
+ | `num_k_heads`, `head_k_dim`, `head_v_dim` | int | | `Hk`, `Dk`, `Dv`; `Hv = len(a_log)` |
219
+ | `eps` | float | | RMSNorm epsilon, default `1e-6` |
220
+
221
+ **Return a 6-tuple in exactly this order:** `dx (T, Dm)`, `dw_norm (Dm,)`, `dw_qkvz (Wq, Dm)`,
222
+ `dw_ba (2*Hv, Dm)`, `da_log (Hv,)`, `ddt_bias (Hv,)`.
223
+
224
+ `dx` may be bf16 or fp32; the five parameter gradients should be **fp32** — each is a reduction over every
225
+ token in the micro-batch. All inputs are **read-only**. `T` is **not** guaranteed to be a multiple of any
226
+ tile size (the correctness shapes include `T = 129`).""",
227
+
228
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `T` in
229
+ 8192–24576, `Dm` in 2048–4096, `Hk` in 8–32 with `Dk` 64–128, `Hv` in 16–32 with `Dv` = 128. The projection
230
+ is 3–6x wider than the model dimension, so `dp` is the largest tensor in the problem and every pass over it
231
+ that you can avoid is worth more than any single matmul optimisation.""",
232
+
233
+ correctness_md="""**All six** returned tensors must match the reference (evaluated in fp32) within
234
+ **relative Frobenius error `2e-2`** at every graded shape, including the timed ones; the grader scores the
235
+ **worst** of the six, so a perfect `dw_qkvz` does not rescue a wrong `da_log`.
236
+
237
+ That gate is **measured**, and dropping a piece of this backward misses it by orders of magnitude:
238
+ multiplying `dq` by the L2 scale without the rank-1 `- q * dot(dq, q)` correction scores **0.59**, using a
239
+ plain RMSNorm gain instead of the zero-centred `1 + w_norm` scores **2.0**, and using `softplus(u)` where
240
+ `g` itself belongs in `da_log` scores **1.5** — the closest is **29x** the tolerance.""",
241
+
242
+ perf_md="""Three passes over the wide projection shape and a large amount of elementwise work that a
243
+ framework implementation spills to HBM between every step.
244
+
245
+ The `(T, Wq)` tensors are the problem. `p` has to be rebuilt (the L2 backward needs the *pre*-normalisation
246
+ q and k), `dp` has to be formed, and both are 3–6x wider than `x`. A fused kernel recomputes the slice of
247
+ `p` a tile needs, applies the L2 Jacobian, and hands the resulting `dp` tile straight to the next matmul
248
+ without ever writing it; the naive version writes `p`, reads it, writes `dp`, reads it twice more.
249
+
250
+ `dh = dp @ w_qkvz + dba @ w_ba` is one accumulation, not two matmuls plus an add — the two right-hand
251
+ operands can be concatenated exactly as the forward's two projections can.
252
+
253
+ `dw_qkvz = dp.T @ h` is the transposed-A GEMM that dominates: `Wq x Dm` output, `T` reduction. Split-K
254
+ across token tiles with an fp32 accumulator is the usual answer; be careful that the split-K reduction
255
+ stays in fp32.
256
+
257
+ The L2 Jacobian is a per-head dot product over `Dk = 64..128` contiguous lanes — a warp reduction on a tile
258
+ that is already in registers, not a separate kernel. `da_log` and `ddt_bias` are reductions over `T` into
259
+ `Hv <= 32` numbers: a per-block partial then one cross-block pass, never an atomic per element.
260
+
261
+ `dw_norm` and the `dx` row projection both need `xhat`, which is cheap to recompute from `x` — cheaper than
262
+ storing it.""",
263
+
264
+ precision_md="""Inputs are **bfloat16** for the activations and **float32** for the gate parameters and
265
+ their gradients. Do every accumulation, the sigmoid, the softplus derivative and both normalisation
266
+ backwards in **fp32**; bf16 tensor-core matmuls with fp32 accumulate are what this task expects.
267
+
268
+ The parameter gradients (`dw_norm`, `dw_qkvz`, `dw_ba`, `da_log`, `ddt_bias`) are reductions over up to
269
+ 24576 tokens. Accumulate them in fp32 — a bf16 accumulator loses the tail of that sum, and the error would
270
+ *grow* with `T`, which is exactly the signature the faithfulness clause below rejects.
271
+
272
+ **fp8 is not appropriate here**: the saved activations arrive in bf16 and re-quantising them is an
273
+ approximation of the specified computation.
274
+
275
+ **Where the tolerance comes from.** `1e-2` is measured, not inherited. A second, independent implementation
276
+ — the analytic backward written out by hand, one fused `[w_qkvz ; w_ba]` matmul instead of two, bf16
277
+ operands with fp32 accumulate, and the reductions ordered differently from autograd's — differs from this
278
+ fp32 autograd reference by a worst relative Frobenius error of **8.4e-3** over 20 seeds at the correctness
279
+ shapes and 6 seeds at a full-size graded shape. The tolerance is **2.4x** that.
280
+
281
+ That worst case is always `da_log` or `ddt_bias` at the *smallest* correctness shapes, where the reduction
282
+ runs over only a few hundred tokens and partial cancellation inflates the relative norm of a `(Hv,)`
283
+ vector. At graded sizes every output sits at **3.0e-3 or below** — `dx` at 1.7e-3, `dw_qkvz` at 2.4e-3 —
284
+ which is the plain bf16 rounding floor. If your error *grows* with `T` you have a narrow accumulator, not
285
+ a tight gate.""",
286
+ ).validate()
tools/factory/specs/qwen3_next_output_gate_backward.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `qwen3-next-output-gate-backward` — the training-side backward of the Qwen3-Next gated attention
2
+ output path (per-head RMSNorm -> SiLU output gate -> output projection)."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ # the forward, written once and used as the differentiable spec the reference backprops through
10
+ _FWD = '''
11
+ def _gated_output(attn_out, x, w_norm, w_gate, w_out, eps=1e-6):
12
+ """Per-head RMSNorm, SiLU output gate, output projection — the fp32 forward, differentiable.
13
+
14
+ Autograd through THIS defines every gradient this task asks for.
15
+ """
16
+ T, H, Dh = attn_out.shape
17
+ a = attn_out.float()
18
+ n = a * torch.rsqrt(a.pow(2).mean(-1, keepdim=True) + eps) * w_norm.float() # RMSNorm over Dh, per head
19
+ g = x.float() @ w_gate.float().t() # (T, H*Dh) gate logits
20
+ y = n.reshape(T, H * Dh) * (g * torch.sigmoid(g)) # SiLU gate
21
+ return y @ w_out.float().t() # (T, Dm)
22
+
23
+
24
+ def gated_output_backward(attn_out, x, w_norm, w_gate, w_out, do, eps=1e-6):
25
+ """The baseline runs the fp32 forward again under autograd and lets it differentiate itself."""
26
+ ins = [t.detach().clone().requires_grad_(True) for t in (attn_out, x, w_norm, w_gate, w_out)]
27
+ o = _gated_output(*ins, eps=eps)
28
+ return torch.autograd.grad(o, ins, do.float())
29
+ '''
30
+
31
+ SPEC = TaskSpec(
32
+ name="qwen3-next-output-gate-backward",
33
+ title="Write a fast backward kernel for the gated attention-output path",
34
+ blurb=("The training-side counterpart of the Qwen3-Next gated attention output: an attention result is "
35
+ "RMS-normalised per head, multiplied by a SiLU gate projected from the block input, and "
36
+ "projected back to the model width. Differentiating it means pushing one gradient back through "
37
+ "a projection, splitting it between the normalised activation and the gate, and then back "
38
+ "through BOTH a per-head normaliser and a second projection — five matmuls and two reductions "
39
+ "that autograd runs as two dozen full-size kernels with the gate logits recomputed in the "
40
+ "middle."),
41
+ keywords=["mle", "kernel-generation", "qwen3-next", "gated-attention", "output-gate", "backward",
42
+ "rmsnorm", "silu", "training", "gemm", "compute-bound"],
43
+ module="gate_bwd.py",
44
+ func="gated_output_backward",
45
+ signature="gated_output_backward(attn_out, x, w_norm, w_gate, w_out, do, eps=1e-6)",
46
+ returns_doc="""Backward pass of RMSNorm -> SiLU output gate -> output projection.
47
+
48
+ Args:
49
+ attn_out: (T, H, Dh) bfloat16 — per-head attention output saved by the forward.
50
+ x: (T, Dm) bfloat16 — the block input, the gate's source, saved by the forward.
51
+ w_norm: (Dh,) bfloat16 — per-head RMSNorm gain, shared by all H heads.
52
+ w_gate: (H*Dh, Dm) bfloat16 — gate projection, nn.Linear layout (out, in).
53
+ w_out: (Dm, H*Dh) bfloat16 — output projection, nn.Linear layout (out, in).
54
+ do: (T, Dm) bfloat16 — incoming gradient w.r.t. the forward output.
55
+ eps: float — the RMSNorm epsilon used by the forward.
56
+
57
+ Returns:
58
+ (d_attn_out, dx, dw_norm, dw_gate, dw_out) with shapes
59
+ (T, H, Dh), (T, Dm), (Dh,), (H*Dh, Dm), (Dm, H*Dh).""",
60
+
61
+ reference_imports="import torch",
62
+ reference_src=_FWD,
63
+ make_inputs_src='''
64
+ def _mk(T, Dm, H, Dh, seed):
65
+ """Saved forward activations, weights and the incoming gradient. Each head gets its OWN magnitude
66
+ (a spread of e^-1.5 .. e^1.5), which is what a real attention output looks like and what makes the
67
+ per-head normaliser's gradient different from a whole-row one's."""
68
+ gen = torch.Generator(device="cuda").manual_seed(seed)
69
+
70
+ def r(*sh, s=1.0):
71
+ return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
72
+
73
+ hs = torch.exp(1.5 * (2 * torch.rand(H, 1, device="cuda", generator=gen) - 1))
74
+ attn_out = (torch.randn(T, H, Dh, device="cuda", generator=gen) * hs).to(torch.bfloat16)
75
+ x = r(T, Dm)
76
+ w_norm = (0.5 + torch.rand(Dh, device="cuda", generator=gen)).to(torch.bfloat16)
77
+ w_gate = r(H * Dh, Dm, s=Dm ** -0.5)
78
+ w_out = r(Dm, H * Dh, s=(H * Dh) ** -0.5)
79
+ do = r(T, Dm)
80
+ return attn_out, x, w_norm, w_gate, w_out, do, 1e-6
81
+ ''',
82
+ flops_src='''
83
+ def canonical_work(T, Dm, H, Dh):
84
+ """FLOPs attributed to one backward call, from the SHAPE ALONE.
85
+
86
+ FIVE (T, Dm) x (Dm, H*Dh)-shaped matmuls at 2 FLOPs per multiply-add, all of the same size:
87
+ 1. recomputing the gate logits g = x @ w_gate.T (g is NOT an argument, so it must be rebuilt)
88
+ 2. dy = do @ w_out
89
+ 3. dw_out = do.T @ y
90
+ 4. dx = dg @ w_gate
91
+ 5. dw_gate = dg.T @ x
92
+ The per-head RMSNorm backward, the SiLU derivative and the dw_norm reduction are O(T*H*Dh) elementwise
93
+ work and are NOT credited — fusing them is a saving, not extra work you get paid for.
94
+ """
95
+ return 10 * T * Dm * (H * Dh)
96
+ ''',
97
+ flops_formula=("canonical_work(T, Dm, H, Dh) = 10 * T * Dm * (H*Dh)\n"
98
+ "# = 5 matmuls of that shape: recompute g, dy, dw_out, dx, dw_gate"),
99
+
100
+ metric="TFLOP/s",
101
+ compare="tuple",
102
+ tuple_names=("d_attn_out", "dx", "dw_norm", "dw_gate", "dw_out"),
103
+ tol=8e-3, # MEASURED: 2.25x the 3.55e-3 worst gap to an independent hand-written bf16 backward
104
+ shape_names=("T", "Dm", "H", "Dh"),
105
+ grader_shapes=[(16384, 4096, 32, 128), (8192, 8192, 32, 128), (16384, 6144, 24, 128),
106
+ (12288, 4096, 48, 128), (24576, 4096, 16, 128)],
107
+ measure_shapes=[(14336, 4096, 32, 128), (7168, 8192, 32, 128), (14336, 6144, 24, 128),
108
+ (10240, 4096, 48, 128), (20480, 4096, 16, 128)],
109
+ measure_quick_shapes=[(2048, 2048, 16, 128), (4096, 1024, 8, 128), (1024, 4096, 16, 64)],
110
+ correct_shapes=[(256, 512, 4, 64), (129, 256, 6, 32), (512, 1024, 8, 128), (64, 128, 1, 64)],
111
+
112
+ spec_md="""The forward this differentiates is the Qwen3-Next gated attention output path:
113
+
114
+ ```
115
+ n[t, h, :] = attn_out[t, h, :] * rsqrt( mean_d( attn_out[t, h, d]^2 ) + eps ) * w_norm # per HEAD
116
+ g = x @ w_gate.T # (T, H*Dh) gate logits
117
+ y = n.reshape(T, H*Dh) * silu(g) # silu(z) = z * sigmoid(z)
118
+ out = y @ w_out.T # (T, Dm)
119
+ ```
120
+
121
+ The RMS mean runs over the `Dh` channels of **one head**, not over the flattened row, and `w_norm` is a
122
+ single `(Dh,)` gain shared by every head. The head-major flattening lines `g`'s channel `h*Dh + d` up with
123
+ head `h`, channel `d`.
124
+
125
+ You are given `do = dL/dout` and must return the gradient w.r.t. **everything the forward consumed**:
126
+
127
+ ```
128
+ dy = do @ w_out # (T, H*Dh)
129
+ dw_out = do.T @ y # (Dm, H*Dh)
130
+ dg = dy * n * dsilu(g) where dsilu(z) = sigmoid(z) * (1 + z * (1 - sigmoid(z)))
131
+ dx = dg @ w_gate # (T, Dm)
132
+ dw_gate = dg.T @ x # (H*Dh, Dm)
133
+ dn = dy * silu(g) # (T, H*Dh) -> view (T, H, Dh)
134
+ ```
135
+
136
+ and then back through the per-head RMSNorm. Writing `r[t,h] = rsqrt(mean_d(a[t,h,d]^2) + eps)` and
137
+ `xhat[t,h,d] = a[t,h,d] * r[t,h]`:
138
+
139
+ ```
140
+ dxhat[t,h,d] = dn[t,h,d] * w_norm[d]
141
+ c[t,h] = mean_d( dxhat[t,h,:] * xhat[t,h,:] )
142
+ d_attn_out[t,h,d]= ( dxhat[t,h,d] - xhat[t,h,d] * c[t,h] ) * r[t,h]
143
+ dw_norm[d] = sum over t and h of dn[t,h,d] * xhat[t,h,d]
144
+ ```
145
+
146
+ Note what is **not** an argument: the gate logits `g`, the normalised activation `n` and the gated product
147
+ `y` were all forward temporaries. They have to be recomputed — `g` costs a full matmul, `n` and `y` are
148
+ elementwise on top of it.
149
+
150
+ `dw_norm` is a reduction over **both** `t` and `h`: every head contributes to the same `(Dh,)` gain.
151
+
152
+ `/app/reference.py` re-runs the fp32 forward under autograd and differentiates it. That is the exact
153
+ specification; it is deliberately simple rather than fast.""",
154
+
155
+ contract_md="""| arg | shape | dtype | meaning |
156
+ |-----|-------|-------|---------|
157
+ | `attn_out` | `(T, H, Dh)` | `bfloat16` | per-head attention output saved by the forward |
158
+ | `x` | `(T, Dm)` | `bfloat16` | block input, the gate's source |
159
+ | `w_norm` | `(Dh,)` | `bfloat16` | per-head RMSNorm gain, **shared** by all `H` heads |
160
+ | `w_gate` | `(H*Dh, Dm)` | `bfloat16` | gate projection, `nn.Linear` layout `(out, in)` |
161
+ | `w_out` | `(Dm, H*Dh)` | `bfloat16` | output projection, `nn.Linear` layout `(out, in)` |
162
+ | `do` | `(T, Dm)` | `bfloat16` | incoming gradient w.r.t. the forward output |
163
+ | `eps` | float | | RMSNorm epsilon, default `1e-6` |
164
+
165
+ **Return a 5-tuple in exactly this order:**
166
+
167
+ | out | shape | notes |
168
+ |-----|-------|-------|
169
+ | `d_attn_out` | `(T, H, Dh)` | bf16 or fp32 |
170
+ | `dx` | `(T, Dm)` | bf16 or fp32 |
171
+ | `dw_norm` | `(Dh,)` | fp32 recommended — it is a reduction over `T*H` terms |
172
+ | `dw_gate` | `(H*Dh, Dm)` | fp32 recommended |
173
+ | `dw_out` | `(Dm, H*Dh)` | fp32 recommended |
174
+
175
+ All inputs are **read-only**; nothing is updated in place. `T` is **not** guaranteed to be a multiple of any
176
+ tile size — the correctness shapes include `T = 129` and `T = 64` — and `H` may be as small as 1.""",
177
+
178
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `T`
179
+ (tokens in the micro-batch) in 8192–24576, `Dm` in 4096–8192, `H` in 16–48, `Dh` = 128, with `H*Dh` between
180
+ 2048 and 6144. All five matmuls are the same `(T, Dm) x (Dm, H*Dh)` shape, so this is a compute-bound task
181
+ where the entire question is how much of the elementwise work you can hide inside them.""",
182
+
183
+ correctness_md="""**All five** returned tensors must match the reference (evaluated in fp32) within
184
+ **relative Frobenius error `8e-3`** at every graded shape, including the timed ones; the grader scores the
185
+ **worst** of the five, so a perfect `dx` does not rescue a wrong `dw_norm`.
186
+
187
+ That gate is **measured**, and implementations that skip a piece of this backward miss it by orders of
188
+ magnitude: using `silu(g)` where the SiLU *derivative* belongs scores **0.66**, dropping the
189
+ `- xhat * c` projection term from the RMSNorm backward scores **0.088**, normalising over the flattened
190
+ `H*Dh` row instead of per head scores **0.40**, and forming `dw_norm` without the `xhat` factor scores
191
+ **1.23** — the closest of them is still **11x** the tolerance.""",
192
+
193
+ perf_md="""Five matmuls of identical shape and a pile of elementwise work between them. The elementwise
194
+ work is what decides the score, because done naively it costs more HBM traffic than the matmuls do.
195
+
196
+ The dependency chain is short: `g` (recompute), then `dy` and `dw_out`, then `dg`, then `dx` and `dw_gate`.
197
+ `dy = do @ w_out` and `dw_out = do.T @ y` share the operand `do`; `dx = dg @ w_gate` and `dw_gate = dg.T @ x`
198
+ share `dg`. Each pair wants to be a single pass over its shared operand, not two.
199
+
200
+ Everything in the middle — recomputing `n` from `attn_out`, `silu(g)` and its derivative, the products that
201
+ form `dn` and `dg`, the per-head RMSNorm backward and the `dw_norm` reduction — touches `(T, H*Dh)` tensors.
202
+ An autograd-shaped implementation writes each of those to HBM and reads it back; a fused one produces `dg`
203
+ in registers directly from the `dy` tile and never materialises `n`, `y` or `silu(g)` at all.
204
+
205
+ Two reductions need care. `dw_norm` sums over `T*H` — a per-head partial in registers, then a cross-block
206
+ reduction; do **not** run it as an atomic per element. The RMSNorm backward's `c[t,h]` is a reduction over
207
+ only `Dh = 128` lanes, so it belongs inside a warp, not in a separate kernel.
208
+
209
+ Recomputing `g` is unavoidable but it is also an opportunity: it is the same operand `x` that `dw_gate`
210
+ consumes, so a kernel that keeps `x` tiles resident pays for the load once.""",
211
+
212
+ precision_md="""Inputs are **bfloat16**; do every accumulation, the sigmoid and the SiLU derivative in
213
+ **fp32**. bf16 tensor-core matmuls with fp32 accumulate are exactly what this task expects.
214
+
215
+ `dw_norm` is a sum over `T*H` terms — at the graded shapes that is up to a million contributions to each of
216
+ 128 numbers, and a bf16 accumulator loses it. Accumulate in fp32 (or better, pairwise/tree in fp32).
217
+
218
+ **fp8 is not appropriate here**: the saved activations arrive in bf16, and re-quantising them to fp8 is an
219
+ approximation of the specified computation rather than an implementation of it.
220
+
221
+ **Where the tolerance comes from.** `2e-2` is measured, not inherited. A second, independent implementation
222
+ — the analytic backward written out by hand, matmuls in bf16 with fp32 accumulate, the RMSNorm backward
223
+ reduced in a different order, `dw_norm` accumulated as a two-stage fp32 tree — differs from this fp32
224
+ autograd reference by a worst relative Frobenius error of **3.55e-3** across the correctness shapes and a
225
+ full-size graded shape, over several seeds. The tolerance is **2.25x** that. The number is flat in the
226
+ problem size (3.37e-3 to 3.55e-3 everywhere tried), because it is the bf16 rounding of the matmul operands
227
+ and of the returned tensors and nothing else — which is the floor for any bf16 kernel. An error that
228
+ *grows* with `T` means an accumulator somewhere is too narrow, not that the tolerance is too tight.""",
229
+ ).validate()
tools/factory/specs/rmsnorm_quant_transpose.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `rmsnorm-quant-transpose-fused` — RMSNorm fused with the FP8 cast-transpose an FP8 training step needs."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="rmsnorm-quant-transpose-fused",
10
+ title="Write a fast fused RMSNorm + FP8 cast-transpose kernel",
11
+ blurb=("An FP8 training step needs each normalised activation matrix twice: quantised along the feature "
12
+ "axis for the forward GEMM, and transposed and quantised along the token axis for the weight "
13
+ "gradient. Both copies come from the SAME RMS-normalised values, so the column-group scales "
14
+ "depend on a row reduction — which is what makes this more than a cast-transpose. As separate "
15
+ "ops it is a norm, a full fp32 transpose and two quantisations; fused it is a read of the bf16 "
16
+ "matrix and two FP8 writes."),
17
+ keywords=["mle", "kernel-generation", "fp8", "rmsnorm", "quantization", "transpose", "training",
18
+ "memory-bound", "low-precision"],
19
+ module="norm_quant_transpose.py",
20
+ func="rmsnorm_quant_transpose",
21
+ signature="rmsnorm_quant_transpose(x, weight, eps=1e-6)",
22
+ returns_doc="""RMSNorm, then FP8 quantisation of the result AND of its transpose.
23
+
24
+ Args:
25
+ x: (M, N) bfloat16 — hidden states; M tokens, N features.
26
+ weight: (N,) bfloat16 — RMSNorm gain.
27
+ eps: float — added inside the rsqrt; default 1e-6.
28
+
29
+ Returns a 4-tuple, in this order:
30
+ q: (M, N) float8_e4m3fn — y quantised in 1x128 groups along N
31
+ s: (M, N // 128) float32 — the matching scales
32
+ qt: (N, M) float8_e4m3fn — y.T quantised in 1x128 groups along M (= 128x1 groups of y)
33
+ st: (N, M // 128) float32 — the matching scales""",
34
+
35
+ reference_imports="import torch",
36
+ reference_src='''
37
+ FP8_MAX = 448.0 # max finite magnitude of float8_e4m3fn
38
+ GROUP = 128 # quantisation group length, along the last axis of each output
39
+
40
+
41
+ def rmsnorm_quant_transpose(x, weight, eps=1e-6):
42
+ """RMSNorm, then two independent FP8 quantisations of the SAME normalised values.
43
+
44
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target.
45
+
46
+ NOTE the TENSOR divisor: `amax / fmax` with a 0-dim tensor is a correctly-rounded IEEE fp32 division,
47
+ which is exactly what `amax / 448.0f` gives in CUDA/Triton. (torch turns `tensor / python_float` into a
48
+ multiply by the rounded reciprocal, which is off by an ulp on many elements.)
49
+ """
50
+ M, N = x.shape
51
+ fmax = torch.tensor(FP8_MAX, device=x.device)
52
+ xf = x.float()
53
+ rms = torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) # per row, over ALL N features
54
+ y = xf * rms * weight.float() # normalised, gained, fp32
55
+
56
+ yr = y.view(M, N // GROUP, GROUP) # 1 x 128 groups along N
57
+ s = (yr.abs().amax(-1) / fmax).clamp(min=1e-12)
58
+ q = (yr / s.unsqueeze(-1)).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn).view(M, N)
59
+
60
+ yt = y.t().contiguous().view(N, M // GROUP, GROUP) # 128 x 1 groups of y
61
+ st = (yt.abs().amax(-1) / fmax).clamp(min=1e-12)
62
+ qt = (yt / st.unsqueeze(-1)).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn).view(N, M)
63
+
64
+ return q, s, qt, st
65
+ ''',
66
+ make_inputs_src='''
67
+ def _mk(M, N, seed):
68
+ """A ~20x magnitude spread along BOTH axes. The row spread is mostly removed by the RMSNorm (that is
69
+ what it is for), so the column-group scales are driven by the per-feature spread and the gain — which
70
+ is exactly the regime a real activation matrix is in."""
71
+ gen = torch.Generator(device="cuda").manual_seed(seed)
72
+ col = torch.exp(torch.rand(1, N, device="cuda", generator=gen) * 3.0 - 1.5)
73
+ row = torch.exp(torch.rand(M, 1, device="cuda", generator=gen) * 3.0 - 1.5)
74
+ x = (torch.randn(M, N, device="cuda", generator=gen) * col * row).to(torch.bfloat16)
75
+ weight = (0.5 + torch.rand(N, device="cuda", generator=gen)).to(torch.bfloat16)
76
+ return x, weight
77
+ ''',
78
+ flops_src='''
79
+ def canonical_work(M, N):
80
+ """BYTES attributed to one fused RMSNorm + FP8 cast-transpose, from the SHAPE ALONE.
81
+
82
+ The ideal traffic: read x once (2 bytes/elt, bf16), write q and qt (1 byte/elt each, fp8), and write one
83
+ fp32 scale per 128 elements for each of the two groupings. Memory-bound, so the score is achieved
84
+ bandwidth against this fixed byte count. (See the perf notes: the row normaliser makes a single read of
85
+ x hard, so this floor is aspirational rather than easy — it is the same fixed count for every
86
+ submission either way.)
87
+ """
88
+ return M * N * 2 + M * N + M * N + 2 * (M * N // 128) * 4
89
+ ''',
90
+ flops_formula="M * N * 2 + M * N + M * N + 2 * (M * N // 128) * 4",
91
+
92
+ metric="GB/s",
93
+ compare="tuple",
94
+ tuple_names=("q", "s", "qt", "st"),
95
+ tol=3e-3, # MEASURED: 2.1x the 1.4e-3 spread between two independent correct implementations
96
+ shape_names=("M", "N"),
97
+ grader_shapes=[(65536, 8192), (131072, 4096), (32768, 16384), (262144, 2048), (98304, 6144)],
98
+ measure_shapes=[(49152, 8192), (98304, 4096), (32768, 12288), (196608, 2048), (65536, 6144)],
99
+ measure_quick_shapes=[(4096, 4096), (2048, 8192), (8192, 2048)],
100
+ correct_shapes=[(256, 512), (128, 1024), (512, 256), (1024, 2048)],
101
+
102
+ spec_md="""One bf16 matrix in, one RMSNorm, and **two** FP8 matrices out — and they are not the same
103
+ bytes transposed, because each is quantised in groups along its own last axis.
104
+
105
+ ### 1 — RMSNorm over the full feature axis
106
+
107
+ ```
108
+ rms[m] = rsqrt( mean_n( x[m, n]^2 ) + eps ) # over ALL N features of row m
109
+ y[m, n] = x[m, n] * rms[m] * weight[n]
110
+ ```
111
+
112
+ No mean subtraction, `eps` inside the rsqrt, gain applied after normalising. `y` is fp32 and is **never
113
+ materialised in memory** — it is the input to both quantisations.
114
+
115
+ ### 2 — `q`, `s`: 1 x 128 groups along `N` (the per-token grouping)
116
+
117
+ For row `m`, group `j` covering `n in [128j, 128j + 128)`:
118
+
119
+ ```
120
+ amax = max |y[m, n]| over the group
121
+ s[m,j] = max( amax / 448.0 , 1e-12 ) # 448 = max finite float8_e4m3fn
122
+ q[m,n] = cast_to_float8_e4m3fn( y[m, n] / s[m, j] )
123
+ ```
124
+
125
+ ### 3 — `qt`, `st`: 1 x 128 groups along `M` (128 x 1 groups of `y`)
126
+
127
+ `qt` has shape `(N, M)` and holds the transpose: `qt[n, m]` is the quantised form of `y[m, n]`, but grouped
128
+ down the **token** axis. For column `n`, group `i` covering `m in [128i, 128i + 128)`:
129
+
130
+ ```
131
+ amax = max |y[m, n]| over m in [128i, 128i + 128)
132
+ st[n,i] = max( amax / 448.0 , 1e-12 )
133
+ qt[n,m] = cast_to_float8_e4m3fn( y[m, n] / st[n, i] )
134
+ ```
135
+
136
+ The same `y[m, n]` therefore appears **twice, with two different scales**, and the two codes are generally
137
+ different. That is the point: each copy is grouped along the axis that its GEMM contracts over.
138
+
139
+ The interesting dependency is between the two halves: the column-group absmax in step 3 is an absmax of
140
+ **normalised** values, so it cannot be computed until `rms` is known for all 128 rows of the group — and
141
+ `rms[m]` needs the whole row of `x`. A pure cast-transpose has no such coupling.
142
+
143
+ `/app/reference.py` does this in fp32 with an explicit `.t().contiguous()`. That is the exact specification
144
+ and also what to avoid: a full fp32 transpose of the whole matrix is `4*M*N` bytes read and written for
145
+ nothing.""",
146
+
147
+ contract_md="""| arg | shape | dtype | meaning |
148
+ |-----|-------|-------|---------|
149
+ | `x` | `(M, N)` | `bfloat16` | hidden states, M tokens x N features |
150
+ | `weight` | `(N,)` | `bfloat16` | RMSNorm gain, applied after normalising |
151
+ | `eps` | scalar | `float` | added inside the rsqrt; default `1e-6` |
152
+
153
+ **Return** a 4-tuple `(q, s, qt, st)` **in that order**:
154
+
155
+ | out | shape | dtype |
156
+ |-----|-------|-------|
157
+ | `q` | `(M, N)` | `torch.float8_e4m3fn` |
158
+ | `s` | `(M, N // 128)` | `float32` |
159
+ | `qt` | `(N, M)` | `torch.float8_e4m3fn` |
160
+ | `st` | `(N, M // 128)` | `float32` |
161
+
162
+ `qt` must be a real `(N, M)` **contiguous** tensor, not a transposed view of `q` — the consumer is a GEMM
163
+ that reads it row-major. Both `q` and `qt` must be genuine `float8_e4m3fn`.
164
+
165
+ **`M` and `N` are both multiples of 128** in every graded and correctness shape, so the groups always divide
166
+ evenly; you do not have to handle a partial group. `eps` is added to the **mean** of squares. Treat all
167
+ inputs as read-only.""",
168
+
169
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `M` (tokens
170
+ in the microbatch) in 32768–262144 and `N` (model width) in 2048–16384, both multiples of 128 — one
171
+ activation matrix of an FP8 training step. The aspect ratio varies by 128x across the graded shapes, which
172
+ changes which of the two outputs is the awkward one; write a **general** kernel.""",
173
+
174
+ correctness_md="""**All four** returned tensors must match the reference within **relative error `3e-3`**
175
+ at every graded shape, including the timed ones; the grader scores the **worst** of the four.
176
+
177
+ Grading all four matters, because a block scale absorbs any change in the *magnitude* of `y` and hides
178
+ mistakes in the codes. Measured: RMS-normalising **per 128-block instead of per row** scores **0.11 – 0.14**;
179
+ using one scale per **whole column** instead of per 128-row group scores **0.20 – 0.43**; dropping the
180
+ RMSNorm **gain** scores **0.32 – 0.34**. And the numerical one to watch — rounding `y` through **bfloat16**
181
+ before quantising — scores **1.28e-2**, still **4.2x** the tolerance and a fail.""",
182
+
183
+ perf_md="""This kernel is **memory-bound**. `canonical_work` counts the ideal traffic — one bf16 read and
184
+ two FP8 writes — and your score is achieved bandwidth against that count. The ceiling is the HBM bandwidth
185
+ you measure on the device (time a large bf16 `copy_` and aim there).
186
+
187
+ **Read this before you design the kernel:** the column-group scales need the absmax of `y` over 128 *rows*,
188
+ and `y` needs `rms[m]`, which needs the *whole* row of `x`. A block cannot own both a full row and 128 full
189
+ rows unless the row fits in shared memory 128 times over, which it does not. The natural structure is
190
+ therefore **two passes over `x`**:
191
+
192
+ 1. a cheap pass that computes `rms[m]` for every row into an `(M,)` fp32 buffer — this is a pure reduction,
193
+ `2*M*N` bytes read, nothing written but `4*M` bytes;
194
+ 2. a tile pass over aligned **128 x 128** tiles: read the bf16 tile, scale by `rms[m]` and `weight[n]` in
195
+ fp32, and the tile now contains **exactly** 128 complete row-groups (one per row) and 128 complete
196
+ column-groups (one per column). Take both absmaxes, emit the `q` tile row-major and the `qt` tile
197
+ transposed, and write both scale vectors.
198
+
199
+ That costs `6*M*N` bytes against a counted `4*M*N`, so ~2/3 of your measured copy bandwidth is the realistic
200
+ ceiling. Beating it means finding a way to avoid the second read — and the leaderboard is uncapped, so if you
201
+ find one it pays.
202
+
203
+ Beyond the structure:
204
+
205
+ - **transpose in shared memory, never in HBM.** A 128x128 bf16 tile is 32 KB; stage it (padded to avoid bank
206
+ conflicts), then write `q` along rows and `qt` along the other axis with fully coalesced 128-bit stores.
207
+ - **vectorise the FP8 stores.** One byte per element means a scalar store wastes most of the bandwidth; pack
208
+ 16 codes into a 128-bit store. The FP8 conversion instructions convert two values at a time.
209
+ - **the two absmaxes are different reductions over the same tile.** The row-group one is along the tile's
210
+ fast axis (a warp shuffle); the column-group one is along the slow axis (through shared memory or a
211
+ transposed register layout). Do them in one sweep over the staged tile, not two.
212
+ - **`rms` and `weight` are tiny** — the `(M,)` buffer from pass 1 is `4*M` bytes and the gain is `2*N`; both
213
+ stay in cache. Do not recompute the normaliser per tile.
214
+ - **size the grid from the SM count you query**, and remember that pass 1 is bandwidth-bound with almost no
215
+ arithmetic — it should run at close to pure read speed.""",
216
+
217
+ precision_md="""The input is **bfloat16**, the outputs are **float8_e4m3fn** with **fp32** scales, and the
218
+ RMS reduction, the normalisation and both absmaxes must be computed in **fp32**.
219
+
220
+ **Keep `y` in fp32 all the way into both casts.** e4m3 has a 3-bit mantissa, so consecutive codes are ~6%
221
+ apart and the output is a *step function* of `y`: an upstream perturbation of relative size `d` does not
222
+ produce an error of size `d`, it flips roughly `d/0.06` of the elements by a full step, i.e. an error near
223
+ `0.25 * sqrt(d)`. Rounding `y` through bfloat16 first (`d ~ 4e-3`) measures **1.28e-2** — 4.2x this gate, and
224
+ a fail. `y` is never written to memory, so there is no bandwidth argument for narrowing it.
225
+
226
+ **Where the tolerance comes from.** `3e-3` is measured, not inherited. A second, independent implementation —
227
+ the sum of squares accumulated as a two-level `(N/128, 128)` partial-sum tree instead of one flat row
228
+ reduction, `1/sqrt` instead of `rsqrt`, the gain folded in before the normaliser, the matrix processed in
229
+ 512-row stripes, and both quantisations done as a **multiply by the reciprocal** rather than a divide —
230
+ differs from this reference by relative Frobenius error at most **1.4e-3** across the correctness shapes and
231
+ two full-scale shapes, six seeds each. The gate is **2.1x** that.
232
+
233
+ That `1.4e-3` is larger than you might expect from an fp32 reduction, and the `0.25*sqrt(d)` law above is
234
+ why: a relative difference of only `~2e-6` in the normaliser — entirely ordinary for a different reduction
235
+ order over 16384 elements — is amplified into ~1e-3 of FP8 code flips. It is the floor for *any* kernel that
236
+ does not reproduce the reference's exact reduction order, which is why the gate cannot be tighter, and it is
237
+ also why the scales (`s`, `st`) are much more accurate than the codes: an absmax is exact, so the scales
238
+ agree to fp32 round-off and the whole budget is spent on `q` and `qt`.
239
+
240
+ **fp8 output is required, not optional** — returning bf16 or fp16 values that happen to be numerically close
241
+ does not satisfy the contract.""",
242
+ ).validate()
tools/factory/specs/rwkv7_token_shift.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `rwkv7-token-shift-mix` — RWKV-7's token shift: one read of the activation, six lerped views out."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="rwkv7-token-shift-mix",
10
+ title="Write a fast RWKV-7 token-shift kernel (six lerped projections in one pass)",
11
+ blurb=("Every RWKV-7 time-mixing block starts by blending each token with the one before it — a "
12
+ "learned per-channel interpolation between x[t] and x[t-1] — and it does so SIX times with six "
13
+ "different mixing vectors, one for each of the r, w, k, v, a and g projections. Done as six "
14
+ "separate lerps it reads the activation six times and materialises six full temporaries; done "
15
+ "properly it is one read, one shifted neighbour already in registers, and six stores. The shift "
16
+ "also carries state across chunk boundaries, so the kernel owns a boundary condition as well."),
17
+ keywords=["mle", "kernel-generation", "rwkv7", "token-shift", "linear-attention", "lerp",
18
+ "memory-bound", "recurrent"],
19
+ module="token_shift.py",
20
+ func="rwkv7_token_shift",
21
+ signature="rwkv7_token_shift(x, x_prev, mu)",
22
+ returns_doc="""RWKV-7 token shift: six per-channel lerps against the previous token, plus the carry.
23
+
24
+ Args:
25
+ x: (B, T, D) bfloat16 — this chunk's activations.
26
+ x_prev: (B, D) bfloat16 — the last token of the PREVIOUS chunk, per sequence.
27
+ mu: (6, D) bfloat16 — the six per-channel mixing vectors, in the order r, w, k, v, a, g.
28
+
29
+ Returns a 7-tuple, in this order:
30
+ xr, xw, xk, xv, xa, xg: (B, T, D) bfloat16 — the six mixed activations
31
+ state_out: (B, D) bfloat16 — x[:, T-1], the carry for the next chunk""",
32
+
33
+ reference_imports="import torch",
34
+ reference_src='''
35
+ def rwkv7_token_shift(x, x_prev, mu):
36
+ """RWKV-7 token shift, as separate fp32 tensor ops.
37
+
38
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target.
39
+ """
40
+ shifted = torch.cat([x_prev.unsqueeze(1).float(), x[:, :-1].float()], dim=1) # x[t-1], carry at t=0
41
+ xx = shifted - x.float()
42
+ outs = [(x.float() + xx * mu[i].float()).to(x.dtype) for i in range(mu.shape[0])]
43
+ return tuple(outs) + (x[:, -1].contiguous(),)
44
+ ''',
45
+ make_inputs_src='''
46
+ def _mk(B, T, D, seed):
47
+ gen = torch.Generator(device="cuda").manual_seed(seed)
48
+ x = torch.randn(B, T, D, device="cuda", dtype=torch.bfloat16, generator=gen)
49
+ x_prev = torch.randn(B, D, device="cuda", dtype=torch.bfloat16, generator=gen)
50
+ mu = torch.rand(6, D, device="cuda", generator=gen).to(torch.bfloat16) # mixing weights in [0, 1)
51
+ return x, x_prev, mu
52
+ ''',
53
+ flops_src='''
54
+ def canonical_work(B, T, D):
55
+ """BYTES attributed to one token shift, from the SHAPE ALONE.
56
+
57
+ Read x once and write the six mixed tensors, all bf16 — the shifted operand is the SAME data offset by
58
+ one token, so it costs no second read in a fused kernel and none is counted. The per-sequence carry is
59
+ read and written as well. The (6, D) mixing vectors are negligible and stay resident. This is a
60
+ bandwidth kernel, so the score is achieved bandwidth against this fixed byte count.
61
+ """
62
+ return (1 + 6) * B * T * D * 2 + 2 * B * D * 2
63
+ ''',
64
+ flops_formula="7 * B * T * D * 2 + 4 * B * D bytes",
65
+
66
+ metric="GB/s",
67
+ compare="tuple",
68
+ tuple_names=("xr", "xw", "xk", "xv", "xa", "xg", "state_out"),
69
+ tol=1e-5, # MEASURED: 8.5x the 1.17e-6 worst spread between two independent correct implementations
70
+ shape_names=("B", "T", "D"),
71
+ grader_shapes=[(4, 16384, 4096), (8, 8192, 4096), (2, 32768, 4096),
72
+ (4, 32768, 2048), (6, 16384, 3072)],
73
+ measure_shapes=[(4, 12288, 4096), (8, 6144, 4096), (2, 24576, 4096),
74
+ (4, 24576, 2048), (6, 12288, 3072)],
75
+ measure_quick_shapes=[(2, 2048, 2048), (4, 1024, 2048), (1, 4096, 4096)],
76
+ correct_shapes=[(3, 65, 512), (2, 128, 1024), (5, 33, 256), (1, 257, 2048)],
77
+
78
+ spec_md="""The token shift blends every token with its predecessor, per channel, six different ways:
79
+
80
+ ```
81
+ shifted[b, t, d] = x[b, t-1, d] for t > 0
82
+ shifted[b, 0, d] = x_prev[b, d] the carry from the previous chunk
83
+
84
+ xx[b, t, d] = shifted[b, t, d] - x[b, t, d]
85
+ out_i[b, t, d] = x[b, t, d] + xx[b, t, d] * mu[i, d] for i in [0, 6)
86
+ ```
87
+
88
+ which is a per-channel linear interpolation: `out_i = (1 - mu[i]) * x + mu[i] * shifted`. Both forms are
89
+ acceptable; they differ only in the last fp32 bit.
90
+
91
+ The six outputs are the inputs to the six projections of an RWKV-7 time-mixing block, in the fixed order
92
+ **`r, w, k, v, a, g`** — `mu[0]` produces `xr`, `mu[5]` produces `xg`. `mu` lies in `[0, 1)`: at `mu = 0`
93
+ the output is `x` untouched, at `mu -> 1` it is the previous token.
94
+
95
+ **The boundary is part of the contract.** Position `t = 0` of every sequence mixes against `x_prev[b]`, the
96
+ last token of the previous chunk — not against zero and not against `x[b, 0]`. Sequences are independent:
97
+ the shift never crosses the batch axis. And because this chunk's last token becomes the next chunk's carry,
98
+ the kernel also returns `state_out = x[:, T-1]` — a plain copy, but the recurrence breaks without it.
99
+
100
+ `/app/reference.py` builds `shifted` with a concatenate and evaluates the six lerps as separate fp32 tensor
101
+ ops. That is the exact numerical specification; it is deliberately simple rather than fast — it
102
+ materialises a full `(B, T, D)` fp32 copy of the shifted tensor, a second one for `xx`, and one more per
103
+ output.""",
104
+
105
+ contract_md="""| arg | shape | dtype | meaning |
106
+ |-----|-------|-------|---------|
107
+ | `x` | `(B, T, D)` | `bfloat16` | this chunk's activations, contiguous, `d` fastest |
108
+ | `x_prev` | `(B, D)` | `bfloat16` | last token of the previous chunk, one row per sequence |
109
+ | `mu` | `(6, D)` | `bfloat16` | per-channel mixing vectors, row order `r, w, k, v, a, g` |
110
+
111
+ **Return** a 7-tuple `(xr, xw, xk, xv, xa, xg, state_out)` **in that order**:
112
+
113
+ | out | shape | dtype | notes |
114
+ |-----|-------|-------|-------|
115
+ | `xr` … `xg` | `(B, T, D)` | `bfloat16` | one per row of `mu`, same order |
116
+ | `state_out` | `(B, D)` | `bfloat16` | `x[:, T-1]` — the carry for the next chunk |
117
+
118
+ `state_out` must be a **new contiguous tensor**, not a view into `x`. Treat all inputs as **read-only**:
119
+ the contract is functional, so allocate and return new tensors; the grader calls your function and the
120
+ reference on the same buffers, and an in-place update corrupts the comparison and fails.
121
+
122
+ `T` is **not** guaranteed to be a multiple of any tile size (the correctness shapes include `T = 33`,
123
+ `T = 65` and `T = 257`), and neither is `B`. Handle the tail, and handle `t = 0` of every sequence.""",
124
+
125
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B`
126
+ (sequences in the batch) in 2–8, `T` (tokens per chunk) in 8192–32768, `D` (model width) in 2048–4096.
127
+ That is one chunk of a long-context RWKV-7 training step or prefill: the chunk is large enough that the
128
+ shift is a streaming problem, and there are always at least a couple of sequences, so the per-sequence
129
+ boundary can never be ignored. The six outputs are four times the size of the input, which is what makes
130
+ this worth a dedicated kernel. Write a **general** kernel — `B*T` varies by a factor of four and `D` by
131
+ two.""",
132
+
133
+ correctness_md="""**All seven** returned tensors must match the reference (evaluated in fp32) within
134
+ **relative error `1e-5`** at every graded shape, including the timed ones; the grader scores the **worst**
135
+ of the seven.
136
+
137
+ The gate is tight because this kernel has almost no numerical freedom — it is one FMA per output element —
138
+ and it is **measured**. Every structural mistake misses it by orders of magnitude:
139
+
140
+ * shifting the wrong way (mixing with `x[t+1]` instead of `x[t-1]`) scores **1.05e0**, **10^5x** the
141
+ tolerance;
142
+ * forgetting the `- x` in `xx`, i.e. `x + shifted * mu` instead of a lerp, scores **7.40e-1**;
143
+ * ignoring `x_prev` and starting each sequence from zero scores **1.35e-1** — a boundary error on one token
144
+ in ten thousand, still **13500x** the gate, because the norm is relative and that token is not small;
145
+ * doing the arithmetic in bf16 instead of fp32 scores **3.12e-3**, **312x**.
146
+
147
+ `state_out` carries no arithmetic at all — it is a bf16 copy of values that were already bf16 — so a
148
+ correct kernel reproduces it **bit for bit**.""",
149
+
150
+ perf_md="""This kernel is **memory-bound and nothing else**: one subtract and six FMAs per input
151
+ element, against 14 bytes of traffic. Your score is achieved bandwidth, and the ceiling is the HBM
152
+ bandwidth you measure on the device — note the mix is 1 byte read for every 6 written, so a pure-write
153
+ benchmark is a better yardstick than a `copy_`.
154
+
155
+ Where the reference loses: `shifted` is a full `(B, T, D)` **fp32** materialised copy, `xx` is another, and
156
+ each of the six outputs is computed as its own fp32 temporary before being cast. That is roughly six reads
157
+ of the activation and thirteen full-size tensors through HBM to do the work of one read and six writes.
158
+
159
+ What a fast kernel does:
160
+
161
+ * **the shifted operand is not a second tensor.** `x[t-1]` is the same memory as `x[t]`, offset by `D`
162
+ elements. A thread (or tile) that owns a range of `t` loads its own row and keeps the previous row in
163
+ registers as it walks forward — or, if you parallelise over `t`, loads two rows and reuses them across
164
+ the six outputs. Either way, `x` is read **once**; `canonical_work` counts one read, so an implementation
165
+ that reads it twice starts at half the achievable score.
166
+ * **six stores from one register set.** All six outputs share the same `x` and `xx`; the only thing that
167
+ differs is a per-channel scalar. That is six independent, fully coalesced, vectorisable stores. Issue
168
+ them back-to-back so the store queue stays full, and vectorise them (128-bit) — the store side is 6/7 of
169
+ the traffic and is what this kernel lives or dies by.
170
+ * **hoist `mu`.** It is indexed by channel only: a block that owns a fixed range of `d` loads its `6 x
171
+ tile_d` slice once into registers and reuses it for every token. Six values per channel is real register
172
+ pressure, so pick the channel tile with that in mind; loading `mu` per token instead turns a resident
173
+ vector into a seventh stream.
174
+ * **the boundary is per sequence, and it is a `t = 0` special case only.** Do not branch per token: either
175
+ peel `t = 0` into its own tiny launch or handle it with a predicated select on the tile that contains it.
176
+ A per-element `if (t == 0)` inside the main loop costs more than the boundary is worth.
177
+ * **`state_out` is 2 KB per sequence.** Copy it in the same launch (a single block can do it) rather than
178
+ paying a separate kernel launch for a few kilobytes.
179
+ * **the `d` axis is contiguous and the `t` axis has a stride of `D`** — both are friendly. The layout that
180
+ usually wins is a 2-D grid over `(t-tile, d-tile)` with each thread holding several `d` per `t`, so the
181
+ previous-token value it needs is a register from the previous iteration of its own loop.""",
182
+
183
+ precision_md="""`x`, `x_prev`, `mu` and all seven outputs are **bfloat16**. Do the subtract and the six
184
+ fused multiply-adds in **fp32**, and round to bf16 exactly once per output, at the store.
185
+
186
+ **fp8 is not useful here** and is not expected: the dtypes are fixed at both ends and the kernel is pure
187
+ bandwidth.
188
+
189
+ **Where the tolerance comes from.** `1e-5` is measured, not inherited, over five shapes (including a
190
+ `(4, 2048, 2048)` full-width one) and five seeds each. Two independent implementations of this spec were
191
+ compared against the fp32 reference:
192
+
193
+ * the **lerp form** `x * (1 - mu) + shifted * mu`, with the shifted tensor built by an explicit strided
194
+ copy rather than a concatenate — a different algebraic arrangement and a different rounding sequence:
195
+ **1.17e-6**;
196
+ * a **chunked** implementation that walks `T` in blocks of 61, threads the carry from block to block, and
197
+ uses `addcmul` (a true FMA) for the epilogue: **7.32e-7**.
198
+
199
+ The tolerance is **8.5x** the worse of the two, which is deliberate slack for a kernel whose only real
200
+ freedom is that arrangement — there is no reduction here, so there is no reduction order to argue about.
201
+
202
+ What that slack does **not** cover is **bf16 arithmetic**, which scores **3.12e-3**, 312x the gate. The
203
+ reason it fails so badly is specific to a lerp: `xx = shifted - x` is a *difference of two nearby numbers*.
204
+ When consecutive tokens are similar — which is exactly when the token shift is doing something useful — the
205
+ subtraction cancels most of the mantissa, and computing it in bf16 leaves the difference with only a couple
206
+ of significant bits before it is scaled by `mu` and added back. Widen to fp32 before subtracting.
207
+
208
+ A useful self-check: at `mu[i] = 0` output `i` must equal `x` **bit-identically**, and at `mu[i] = 1` it
209
+ must equal `shifted` bit-identically. Both are exactly representable and both are worth asserting while you
210
+ develop.""",
211
+ ).validate()
tools/factory/specs/sandwich_norm_residual.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sandwich-norm-residual-fused` — Gemma-2 / OLMo-2 sandwich norm: post-norm + residual + pre-norm."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="sandwich-norm-residual-fused",
10
+ title="Write a fast sandwich-norm (post-norm + residual + pre-norm) kernel",
11
+ blurb=("Gemma-2, OLMo-2 and Grok wrap every sublayer in TWO RMSNorms: the sublayer output is normalised "
12
+ "before it is added to the residual stream, and the new residual stream is normalised again on "
13
+ "the way into the next sublayer. Between two blocks that is a norm, an add and a norm over the "
14
+ "same row, with the second reduction depending on the first — five HBM round trips as separate "
15
+ "torch ops, and two reads and two writes when it is one kernel."),
16
+ keywords=["mle", "kernel-generation", "rmsnorm", "residual", "sandwich-norm", "gemma", "olmo",
17
+ "memory-bound", "serving"],
18
+ module="sandwich_norm.py",
19
+ func="sandwich_norm_residual",
20
+ signature="sandwich_norm_residual(residual, branch, post_weight, pre_weight, eps=1e-6)",
21
+ returns_doc="""Post-norm of a sublayer output, residual add, then pre-norm for the next sublayer.
22
+
23
+ Args:
24
+ residual: (M, N) bfloat16 — the residual stream entering this point.
25
+ branch: (M, N) bfloat16 — the sublayer (attention / MLP) output, un-normalised.
26
+ post_weight: (N,) bfloat16 — RMSNorm gain applied to the branch BEFORE the add.
27
+ pre_weight: (N,) bfloat16 — RMSNorm gain applied to the new residual stream.
28
+ eps: float — added inside both rsqrts; default 1e-6.
29
+
30
+ Returns:
31
+ (h, y) where
32
+ h: (M, N) bfloat16 — the updated residual stream, residual + post_norm(branch)
33
+ y: (M, N) bfloat16 — pre_norm(h), the input to the next sublayer""",
34
+
35
+ reference_imports="import torch",
36
+ reference_src='''
37
+ def sandwich_norm_residual(residual, branch, post_weight, pre_weight, eps=1e-6):
38
+ """Two RMSNorms with a residual add sandwiched between them, as separate fp32 steps.
39
+
40
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target.
41
+ """
42
+ bf = branch.float()
43
+ rms_b = torch.rsqrt(bf.pow(2).mean(-1, keepdim=True) + eps) # over the branch row
44
+ h = (residual.float() + bf * rms_b * post_weight.float()).to(residual.dtype) # bf16 residual stream
45
+
46
+ hf = h.float() # re-read the BF16 h
47
+ rms_h = torch.rsqrt(hf.pow(2).mean(-1, keepdim=True) + eps) # over the NEW residual row
48
+ y = (hf * rms_h * pre_weight.float()).to(residual.dtype)
49
+ return h, y
50
+ ''',
51
+ make_inputs_src='''
52
+ def _mk(M, N, seed):
53
+ gen = torch.Generator(device="cuda").manual_seed(seed)
54
+ # the residual stream is several times larger than a single sublayer's output, as it is in a
55
+ # trained model -- so the post-norm gain genuinely matters and the two normalisers differ.
56
+ residual = torch.randn(M, N, device="cuda", dtype=torch.bfloat16, generator=gen) * 2.0
57
+ branch = torch.randn(M, N, device="cuda", dtype=torch.bfloat16, generator=gen) * 0.7
58
+ post_w = (0.5 + torch.rand(N, device="cuda", generator=gen)).to(torch.bfloat16)
59
+ pre_w = (0.5 + torch.rand(N, device="cuda", generator=gen)).to(torch.bfloat16)
60
+ return residual, branch, post_w, pre_w
61
+ ''',
62
+ flops_src='''
63
+ def canonical_work(M, N):
64
+ """BYTES attributed to one sandwich-norm step, from the SHAPE ALONE.
65
+
66
+ The unavoidable traffic: read residual and branch, write h and y — four (M, N) bf16 tensors at 2
67
+ bytes/element. The two (N,) gains are negligible and stay resident. Memory-bound, so the score is
68
+ achieved bandwidth against this fixed byte count.
69
+ """
70
+ return 4 * M * N * 2 + 4 * N
71
+ ''',
72
+
73
+ metric="GB/s",
74
+ compare="tuple",
75
+ tuple_names=("h", "y"),
76
+ tol=1e-3, # MEASURED: 23x the 4.3e-5 worst spread between two independent correct implementations
77
+ shape_names=("M", "N"),
78
+ grader_shapes=[(65536, 8192), (131072, 4096), (32768, 16384), (262144, 2048), (98304, 6144)],
79
+ measure_shapes=[(49152, 8192), (98304, 4096), (32768, 12288), (196608, 2048), (65536, 6144)],
80
+ measure_quick_shapes=[(4096, 4096), (2048, 8192), (8192, 2048)],
81
+ correct_shapes=[(256, 512), (129, 1024), (513, 256), (64, 2048)],
82
+
83
+ spec_md="""Three steps over the same row, fused. `rmsnorm(v)[n] = v[n] * rsqrt(mean_n(v^2) + eps)` — no
84
+ mean subtraction, `eps` inside the rsqrt, and the reduction is over the **whole row of `N` features**.
85
+
86
+ ```
87
+ # 1 - POST-norm: the sublayer output is normalised before it enters the residual stream
88
+ rms_b[m] = rsqrt( mean_n( branch[m, n]^2 ) + eps )
89
+ # 2 - residual add, in bf16
90
+ h[m, n] = bf16( residual[m, n] + branch[m, n] * rms_b[m] * post_weight[n] )
91
+ # 3 - PRE-norm: the NEW residual stream is normalised for the next sublayer
92
+ rms_h[m] = rsqrt( mean_n( h[m, n]^2 ) + eps )
93
+ y[m, n] = bf16( h[m, n] * rms_h[m] * pre_weight[n] )
94
+ ```
95
+
96
+ Both `h` and `y` are returned: `h` is the residual stream that the *next* residual add will need, `y` is what
97
+ the next attention or MLP block consumes.
98
+
99
+ Two things make this more than two independent norms:
100
+
101
+ - **the second reduction depends on the first.** `rms_h` cannot be started until the whole normalised branch
102
+ has been added, so the row has to be held (registers or shared memory) across both reductions, or read
103
+ twice.
104
+ - **`h` is rounded to bfloat16 before the second norm.** `y` is computed from the **bf16** value of `h`, not
105
+ from the fp32 accumulator that produced it — exactly as it would be if `h` were written to HBM and read
106
+ back by a separate kernel. This is part of the specification, not an artefact: carrying the fp32 value into
107
+ the second norm instead changes `y` by **2.8e-3**, which is **2.8x the tolerance** and fails.
108
+
109
+ `/app/reference.py` writes this as a chain of torch ops. That is the exact numerical specification and also
110
+ what a fused kernel must avoid: `bf.pow(2)`, the mean, two broadcast multiplies, the add, and then the same
111
+ again for the second norm — each a full `(M, N)` fp32 tensor through HBM.""",
112
+
113
+ contract_md="""| arg | shape | dtype | meaning |
114
+ |-----|-------|-------|---------|
115
+ | `residual` | `(M, N)` | `bfloat16` | residual stream entering this point |
116
+ | `branch` | `(M, N)` | `bfloat16` | sublayer output, un-normalised |
117
+ | `post_weight` | `(N,)` | `bfloat16` | gain for the norm **before** the add |
118
+ | `pre_weight` | `(N,)` | `bfloat16` | gain for the norm **after** the add |
119
+ | `eps` | scalar | `float` | added inside both rsqrts; default `1e-6` |
120
+
121
+ **Return** a 2-tuple `(h, y)` **in that order**, both `(M, N)` **bfloat16**.
122
+
123
+ The two gains are **not** interchangeable — swapping them scores 0.33, i.e. 330x the tolerance. `N` is always
124
+ a multiple of 128; `M` is **not** a multiple of any tile size (the correctness shapes include `M = 129` and
125
+ `M = 513`), so handle the tail. The update is **functional**: `residual` and `branch` are read-only, and `h`
126
+ must be a newly allocated tensor — the grader calls your function and the reference on the same buffers, so
127
+ an in-place update corrupts the comparison and fails.""",
128
+
129
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `M` (tokens)
130
+ in 32768–262144 and `N` (model width) in 2048–16384 — one inter-block boundary of a large prefill or a big
131
+ decode batch. A row is 4–32 KB of bf16, so whether a whole row fits in one block's shared memory changes
132
+ across the regime; write a **general** kernel rather than one tuned to a single `N`.""",
133
+
134
+ correctness_md="""**Both** returned tensors must match the reference within **relative error `1e-3`** at
135
+ every graded shape, including the timed ones; the grader scores the **worse** of the two.
136
+
137
+ Returning only `y` correctly is not enough — `h` is the residual stream every later layer builds on, and it
138
+ is graded just as hard.
139
+
140
+ That gate is measured, and the structural errors are far outside it: skipping the post-norm on the branch
141
+ (the plain `residual + branch` fusion) scores **0.14**; swapping the two gains scores **0.33**; and reusing
142
+ the branch's normaliser for the second norm instead of recomputing it on `h` scores **2.22**. The one
143
+ near-miss to know about is numerical rather than structural: carrying `h` into the second norm as fp32
144
+ instead of rounding it to bf16 first scores **2.8e-3**, which also fails — see the spec.""",
145
+
146
+ perf_md="""This kernel is **memory-bound**: four `(M, N)` bf16 tensors of traffic and about six flops per
147
+ element. Your score is achieved bandwidth; the ceiling is the HBM bandwidth you measure on the device (time a
148
+ large bf16 `copy_` and aim there). A perfect kernel is two streaming reads and two streaming writes that
149
+ happen to normalise twice on the way through.
150
+
151
+ Where the reference loses: it materialises `bf`, `bf.pow(2)`, the normalised branch, `h` in fp32, `hf` again,
152
+ and the gained result — five or six full-size fp32 temporaries, so the data crosses HBM roughly ten times at
153
+ double width.
154
+
155
+ What a fast kernel does:
156
+
157
+ - **one block per row (or per few rows), one pass.** Load the row of `branch` into registers/shared memory,
158
+ reduce for `rms_b`, add the residual, round to bf16, reduce *again* for `rms_h`, and write both outputs —
159
+ all without going back to HBM for a second read. This is the whole task: the second reduction is a
160
+ dependent barrier in the middle of the row.
161
+ - **do not re-read the row.** At `N = 2048` a row is 4 KB and lives comfortably in registers; at `N = 16384`
162
+ it is 32 KB, which still fits in shared memory but constrains how many rows a block can own. A kernel that
163
+ falls back to re-reading `branch` and `h` from HBM for the second pass pays 8 bytes/element of extra
164
+ traffic and loses roughly a third of the bandwidth. Tune the rows-per-block from
165
+ `p.shared_memory_per_block_optin`, not from a constant.
166
+ - **keep the residual row in registers too.** It is needed after the first reduction; re-loading it is a
167
+ second read of a tensor you already had.
168
+ - **hold `h` in bf16 for the second reduction.** That is what the spec requires anyway, and it halves the
169
+ register/shared footprint of the value that has to survive the barrier.
170
+ - **the two gains are tiny and reused by every row** — stage them once in shared memory.
171
+ - **vectorise.** All four tensors are contiguous bf16; use 128-bit loads and stores, and make the stores as
172
+ wide as the loads.
173
+ - **watch the tail:** `M` is ragged, and at `N = 16384` a single block's shared-memory row is large enough
174
+ that the last partial wave is a visible fraction of the runtime.""",
175
+
176
+ precision_md="""Inputs and outputs are **bfloat16**; both reductions and both gain multiplications must be
177
+ done in **fp32**. A bf16 accumulator over `N = 16384` squared values is not adequate — it moves the
178
+ normaliser visibly.
179
+
180
+ There are exactly **two** bf16 roundings in the specified computation, and where they sit is part of the spec:
181
+
182
+ 1. `h` is rounded to bf16 **after** the residual add, and the second reduction consumes that rounded value;
183
+ 2. `y` is rounded to bf16 at the very end.
184
+
185
+ Carrying the fp32 accumulator across the boundary — i.e. computing `rms_h` and `y` from the un-rounded sum —
186
+ is *more* accurate and still **wrong** here: it measures **2.8e-3** against the reference, 2.8x the gate. The
187
+ reason to specify it this way is that `h` is a real tensor that gets written to memory in bf16; a kernel that
188
+ keeps a private higher-precision copy is not reproducing the model the trainer trained.
189
+
190
+ **Where the tolerance comes from.** `1e-3` is measured, not inherited. A second, independent implementation —
191
+ sum of squares accumulated as a two-level `(N/128, 128)` partial-sum tree instead of one flat row reduction,
192
+ `1/sqrt` instead of `rsqrt`, and the gain folded in before the normaliser instead of after — differs from the
193
+ fp32 reference by relative Frobenius error at most **4.3e-5** across the correctness shapes and two
194
+ full-scale shapes, four seeds each. The gate is **23x** that. The headroom is deliberate: it covers a range
195
+ of reduction orders and a `rsqrt` that is a few ulp off, while still sitting 138x below the mildest
196
+ structural error and 2.8x below the fp32-carry mistake above.
197
+
198
+ Two exactness properties are useful self-checks:
199
+
200
+ - **RMSNorm is scale-invariant.** Scaling `branch` by any positive constant leaves the post-normed branch —
201
+ and therefore `h` and `y` — unchanged, up to `eps`. If it does not, the normaliser is being computed over
202
+ the wrong axis or the gain is being applied before the division.
203
+ - **with `pre_weight = 1` and `eps = 0`, every row of `y` has L2 norm exactly `sqrt(N)`**, whatever the
204
+ inputs were.""",
205
+ ).validate()
tools/factory/specs/sd3_joint_attention_tripletext.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sd3-joint-attention-tripletext` — SD3.5 joint attention over four separate token segments."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="sd3-joint-attention-tripletext",
10
+ title="Write a fast SD3.5 four-segment joint attention (image + three text encoders, no concatenation)",
11
+ blurb=("Stable Diffusion 3.5 conditions on THREE text encoders — CLIP-L, CLIP-G and T5-XXL — whose "
12
+ "token streams the pipeline holds as three separate tensors, and its MMDiT attends over the "
13
+ "concatenation of all of them with the image latents, image first. Building that concatenation "
14
+ "for Q, K and V and splitting the result again, once per block for 38 blocks, is four full "
15
+ "round-trips of a multi-gigabyte working set that buys nothing: the concatenation only exists to "
16
+ "define one softmax denominator. This kernel takes the four segments where they live and gives "
17
+ "back four separate outputs."),
18
+ keywords=["mle", "kernel-generation", "stable-diffusion-3", "sd3", "mmdit", "joint-attention",
19
+ "flash-attention", "multi-segment", "diffusion-transformer", "image-generation"],
20
+ module="sd3_joint_attn.py",
21
+ func="sd3_joint_attention_tripletext",
22
+ signature="sd3_joint_attention_tripletext(img_q, img_k, img_v, ctx, scale=None)",
23
+ returns_doc="""Bidirectional attention over concat([img, clip_l, clip_g, t5]), returned per segment.
24
+
25
+ Args:
26
+ img_q, img_k, img_v: (B, H, Ni, D) bfloat16 — the image latents.
27
+ ctx: a 3-tuple of (q, k, v) triples, in this order:
28
+ ctx[0] = CLIP-L, each (B, H, Nc, D) bfloat16
29
+ ctx[1] = CLIP-G, each (B, H, Nc, D) bfloat16
30
+ ctx[2] = T5, each (B, H, Nt5, D) bfloat16
31
+ scale: float or None — softmax scale; defaults to D ** -0.5.
32
+
33
+ Returns:
34
+ (img_out, clip_l_out, clip_g_out, t5_out) of shapes (B, Ni, H*D), (B, Nc, H*D), (B, Nc, H*D) and
35
+ (B, Nt5, H*D), all bfloat16 — heads already merged.""",
36
+
37
+ reference_imports="import torch",
38
+ reference_src='''
39
+ def sd3_joint_attention_tripletext(img_q, img_k, img_v, ctx, scale=None):
40
+ """Joint attention over the four-segment concatenation, in fp32.
41
+
42
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. The query loop
43
+ chunks only so the fp32 score matrix fits in memory.
44
+ """
45
+ B, H, Ni, D = img_q.shape
46
+ sc = (D ** -0.5) if scale is None else float(scale)
47
+ segs = [(img_q, img_k, img_v)] + list(ctx) # IMAGE FIRST
48
+ lens = [s[0].shape[2] for s in segs]
49
+ N = sum(lens)
50
+
51
+ q = torch.cat([s[0].float() for s in segs], dim=2)
52
+ k = torch.cat([s[1].float() for s in segs], dim=2)
53
+ v = torch.cat([s[2].float() for s in segs], dim=2)
54
+
55
+ out = torch.zeros(B, H, N, D, device=img_q.device, dtype=torch.float32)
56
+ for b in range(B):
57
+ for s0 in range(0, N, 512):
58
+ e = min(s0 + 512, N)
59
+ p = torch.softmax((q[b, :, s0:e] * sc) @ k[b].transpose(1, 2), dim=-1)
60
+ out[b, :, s0:e] = p @ v[b]
61
+
62
+ out = out.permute(0, 2, 1, 3).reshape(B, N, H * D)
63
+ res, off = [], 0
64
+ for L in lens:
65
+ res.append(out[:, off:off + L].to(torch.bfloat16))
66
+ off += L
67
+ return res[0], res[1], res[2], res[3]
68
+ ''',
69
+ make_inputs_src='''
70
+ def _mk(B, Ni, Nc, Nt5, H, D, seed):
71
+ gen = torch.Generator(device="cuda").manual_seed(seed)
72
+
73
+ def qk(L):
74
+ # already QK-RMS-normalised by the block prologue: unit-RMS rows with a mild per-head gain
75
+ t = torch.randn(B, H, L, D, device="cuda", generator=gen)
76
+ t = t * torch.rsqrt(t.pow(2).mean(-1, keepdim=True) + 1e-6)
77
+ g = 1.0 + 0.2 * torch.randn(1, H, 1, D, device="cuda", generator=gen)
78
+ return (t * g).to(torch.bfloat16)
79
+
80
+ def val(L, s=1.0):
81
+ ch = torch.exp(0.5 * (2 * torch.rand(1, H, 1, D, device="cuda", generator=gen) - 1))
82
+ return (s * torch.randn(B, H, L, D, device="cuda", generator=gen) * ch).to(torch.bfloat16)
83
+
84
+ ctx = ((qk(Nc), qk(Nc), val(Nc, 1.3)), # CLIP-L
85
+ (qk(Nc), qk(Nc), val(Nc, 0.8)), # CLIP-G
86
+ (qk(Nt5), qk(Nt5), val(Nt5, 1.1))) # T5
87
+ return qk(Ni), qk(Ni), val(Ni), ctx
88
+ ''',
89
+ flops_src='''
90
+ def canonical_work(B, Ni, Nc, Nt5, H, D):
91
+ """FLOPs for one dense bidirectional attention over the four segments, from the SHAPE ALONE.
92
+
93
+ N = Ni + 2*Nc + Nt5. Every (query, key) pair costs 2*D FLOPs in Q K^T and another 2*D in P V, for
94
+ 4*D per pair per head. There is no mask, so all N*N pairs are real work. The softmax is not counted.
95
+ """
96
+ N = Ni + 2 * Nc + Nt5
97
+ return 4 * B * H * D * N * N
98
+ ''',
99
+ flops_formula="4*B*H*D*(Ni + 2*Nc + Nt5)**2",
100
+
101
+ metric="TFLOP/s",
102
+ compare="tuple",
103
+ tuple_names=("img_out", "clip_l_out", "clip_g_out", "t5_out"),
104
+ tol=5e-3, # MEASURED -- see precision_md
105
+ shape_names=("B", "Ni", "Nc", "Nt5", "H", "D"),
106
+ grader_shapes=[(1, 16384, 77, 256, 38, 64), (2, 12288, 77, 256, 38, 64),
107
+ (2, 8192, 77, 256, 38, 64), (4, 4096, 77, 77, 38, 64),
108
+ (1, 16384, 77, 77, 24, 128)],
109
+ measure_shapes=[(1, 15360, 77, 256, 38, 64), (2, 11264, 77, 256, 38, 64),
110
+ (2, 7680, 77, 77, 38, 64), (3, 4096, 77, 256, 38, 64),
111
+ (1, 14336, 77, 77, 24, 128)],
112
+ measure_quick_shapes=[(1, 2048, 77, 256, 38, 64), (2, 1024, 77, 77, 38, 64),
113
+ (1, 1536, 33, 65, 12, 64)],
114
+ correct_shapes=[(1, 517, 33, 65, 4, 64), (2, 333, 21, 41, 8, 64),
115
+ (1, 2048, 77, 256, 38, 64), (3, 129, 13, 19, 6, 128)],
116
+
117
+ spec_md="""One dense bidirectional attention over four token segments that are never concatenated in
118
+ memory.
119
+
120
+ ```
121
+ segments, in order: img (Ni) | clip_l (Nc) | clip_g (Nc) | t5 (Nt5)
122
+ N = Ni + 2*Nc + Nt5
123
+
124
+ q = concat([img_q, clip_l_q, clip_g_q, t5_q], dim=2) # (B, H, N, D); same for k and v
125
+ out = softmax( scale * q k^T ) v # no mask of any kind
126
+ out = out.transpose(1, 2).reshape(B, N, H*D)
127
+
128
+ img_out = out[:, :Ni]
129
+ clip_l_out = out[:, Ni : Ni+Nc]
130
+ clip_g_out = out[:, Ni+Nc : Ni+2*Nc]
131
+ t5_out = out[:, Ni+2*Nc :]
132
+ ```
133
+
134
+ `scale` defaults to `D ** -0.5` when it is `None`. The softmax denominator spans **all four** segments:
135
+ an image query attends to every text token of all three encoders and to every image token, and each text
136
+ token attends to everything as well. There is no per-encoder mask, no padding to skip, and no separate
137
+ cross-attention — SD3 has none.
138
+
139
+ Q and K arrive **already** RMS-normalised by the block prologue and V arrives untouched; none of that is
140
+ your job here. Your job is the attention and the segmentation.
141
+
142
+ `/app/reference.py` builds the joint tensors, loops over query chunks in fp32 and slices the result back
143
+ into four. That is the exact specification; it is deliberately simple rather than fast, and its runtime has
144
+ no bearing on your score.""",
145
+
146
+ contract_md="""| arg | shape | dtype | meaning |
147
+ |-----|-------|-------|---------|
148
+ | `img_q`, `img_k`, `img_v` | `(B, H, Ni, D)` | `bfloat16` | image latents, head-major |
149
+ | `ctx` | 3-tuple of 3-tuples | — | the three text encoders' `(q, k, v)`, in the order below |
150
+ | `ctx[0]` | 3-tuple of `(B, H, Nc, D)` | `bfloat16` | CLIP-L `(q, k, v)` |
151
+ | `ctx[1]` | 3-tuple of `(B, H, Nc, D)` | `bfloat16` | CLIP-G `(q, k, v)` |
152
+ | `ctx[2]` | 3-tuple of `(B, H, Nt5, D)` | `bfloat16` | T5 `(q, k, v)` |
153
+ | `scale` | scalar or `None` | `float` | softmax scale; `None` means `D ** -0.5` |
154
+
155
+ **Return** a 4-tuple `(img_out, clip_l_out, clip_g_out, t5_out)` **in that order**:
156
+
157
+ | out | shape | dtype |
158
+ |-----|-------|-------|
159
+ | `img_out` | `(B, Ni, H*D)` | `bfloat16` |
160
+ | `clip_l_out` | `(B, Nc, H*D)` | `bfloat16` |
161
+ | `clip_g_out` | `(B, Nc, H*D)` | `bfloat16` |
162
+ | `t5_out` | `(B, Nt5, H*D)` | `bfloat16` |
163
+
164
+ Note the **asymmetry between input and output layout**: inputs are `(B, H, L, D)` (head-major) and outputs
165
+ are `(B, L, H*D)` (token-major). That transpose is part of the contract and part of the work.
166
+
167
+ The two CLIP segments have the **same length** but are different tensors and must not be merged into one
168
+ `2*Nc` block unless you can prove your layout keeps them separate on the way out.
169
+
170
+ None of `Ni`, `Nc`, `Nt5` is a multiple of any tile size — the correctness shapes include `Nc = 21` and
171
+ `Nt5 = 41`. All tensors are CUDA and contiguous; treat them as read-only.""",
172
+
173
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in
174
+ 1–4 images, `Ni` in **4096–16384** image tokens, `Nc = 77` (both CLIP encoders emit 77 tokens), `Nt5` in
175
+ {77, 256} (SD3 uses 77 T5 tokens, SD3.5 up to 256), `H = 38` with `D = 64` (SD3.5-Large) plus one
176
+ `H = 24, D = 128` shape. Every graded shape is **0.7–3.4 TFLOP** of dense attention. Write a **general**
177
+ kernel: the correctness shapes go down to `H = 4` and thoroughly ragged segment lengths.""",
178
+
179
+ correctness_md="""**All four** returned tensors must match the reference (evaluated in fp32 as a stable
180
+ ground truth) within **relative Frobenius error `5e-3`** at every graded shape, including the
181
+ timed ones; the grader scores the **worst** of the four. The three text outputs together are under 3% of
182
+ the data and are graded exactly as hard as the image output — they are what a kernel tuned only for the
183
+ image segment gets wrong, and they are also where a segment-boundary bug shows up first.""",
184
+
185
+ perf_md="""A dense, unmasked, perfectly load-balanced attention wrapped in a segmentation problem.
186
+
187
+ * **Never build the joint Q, K, V.** The concatenation exists only to define the key axis. A flash
188
+ kernel's inner loop can walk the three text blocks and then the image blocks, switching base pointer at
189
+ each boundary; the query grid can be launched as four ranges over the four sources. Materialising
190
+ `concat` costs three full copies of the working set and the final split costs a fourth.
191
+ * **The three text segments are 410 rows against up to 16384** — they are one small K/V region that every
192
+ query tile reads. Load them once into shared memory (or rely on L2) and fold them into the same running
193
+ softmax rather than giving them a second pass over the output accumulator.
194
+ * **Fuse the head transpose into the epilogue.** The outputs want `(B, L, H*D)` while the accumulator is
195
+ per `(head, query tile)`; writing head-major and permuting afterwards is an extra read-modify-write of
196
+ the whole output.
197
+ * **One grid for all four query ranges.** The text queries are 2–10% of the rows; three extra launches for
198
+ them cost three launches and three tails. A tile -> segment lookup costs one integer compare.
199
+ * **`D = 64` at `H = 38`** means a shallow MMA K-depth and lots of heads: parallelise over
200
+ (query tile, head, batch) and keep the key loop long rather than splitting it.
201
+ * Never materialise the `N x N` scores — at `Ni = 16384` that is 282M entries per head.""",
202
+
203
+ precision_md="""Q, K and V are **bfloat16**; all four outputs are **bfloat16**. The score GEMM and the
204
+ `P V` GEMM belong on **bf16 tensor cores with fp32 accumulation**, and the online-softmax running maximum,
205
+ sum and output accumulator must be **fp32** — a bf16 accumulator over 17k keys loses well over the whole
206
+ error budget.
207
+
208
+ `P` (the probabilities) may be rounded to bf16 before the second GEMM; that is what the tolerance is sized
209
+ for.
210
+
211
+ **Where the tolerance comes from.** `5e-3` is measured. An independent
212
+ implementation — `scaled_dot_product_attention` on the concatenated bf16 tensors with a completely
213
+ different tiling, against the reference's chunked fp32 loop — differs by relative Frobenius error at most
214
+ **2.51e-3** (worst of the four outputs) over 25 (shape, seed) combinations spanning the correctness shapes
215
+ and an 8192-token graded shape. That is essentially the bf16 rounding of the returned tensors and is the
216
+ floor for *any* bf16-returning kernel; the gate is **2.0x** it. For contrast, swapping the CLIP-L and
217
+ CLIP-G segments scores **1.12–1.15** (they are different tensors and land in different outputs), and
218
+ letting each segment attend only to itself scores **3.8–13.4**.
219
+
220
+ **fp8** is a legitimate strategy here and is not forbidden, but you must pay for it out of the same budget
221
+ — there is no separate fp8 gate on this task.
222
+
223
+ Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
224
+ numerical *specification*.""",
225
+ ).validate()
tools/factory/specs/sd3_mmdit_block.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sd3-mmdit-block` — a whole Stable Diffusion 3.5 JointTransformerBlock forward."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="sd3-mmdit-block",
10
+ title="Write a fast Stable Diffusion 3.5 MMDiT block (dual-stream all the way, no RoPE)",
11
+ blurb=("Every one of SD3.5's 38 blocks is dual-stream — unlike FLUX there is no single-stream phase at "
12
+ "all — so the image latents and the concatenated triple-text-encoder context each keep their own "
13
+ "6-way adaLN, their own QKV projection, their own QK-RMSNorm gains, their own output projection "
14
+ "and their own MLP, and meet only in one joint attention over the concatenation, IMAGE FIRST. "
15
+ "There is no rotary embedding anywhere: position was added once as a 2-D sincos table at "
16
+ "patchify, so the block is pure GEMM, norm and attention with a 50:1 row imbalance between the "
17
+ "two streams."),
18
+ keywords=["mle", "kernel-generation", "stable-diffusion-3", "sd3", "mmdit", "dual-stream",
19
+ "transformer-block", "joint-attention", "fusion", "gemm", "adaln",
20
+ "diffusion-transformer", "image-generation"],
21
+ module="sd3_block.py",
22
+ func="sd3_mmdit_block",
23
+ signature="sd3_mmdit_block(hidden, context, temb, hidden_w, context_w, num_heads, eps=1e-6)",
24
+ returns_doc="""One full SD3.5 JointTransformerBlock forward.
25
+
26
+ Args:
27
+ hidden: (B, Ni, C) bfloat16 — the image-latent stream.
28
+ context: (B, Nt, C) bfloat16 — the text context (CLIP-L + CLIP-G + T5, already concatenated).
29
+ temb: (B, C) bfloat16 — the timestep + pooled-text conditioning embedding.
30
+ hidden_w: a 12-tuple of the IMAGE stream's parameters, in this exact order:
31
+ 0 mod_w (6*C, C) 1 mod_b (6*C,)
32
+ 2 qkv_w (3*C, C) 3 qkv_b (3*C,)
33
+ 4 q_norm_w (D,) 5 k_norm_w (D,)
34
+ 6 proj_w (C, C) 7 proj_b (C,)
35
+ 8 fc1_w (Cm, C) 9 fc1_b (Cm,)
36
+ 10 fc2_w (C, Cm) 11 fc2_b (C,)
37
+ context_w: the same 12-tuple for the TEXT stream — entirely different tensors.
38
+ num_heads: int — H; D = C // H.
39
+ eps: float — LayerNorm / RMSNorm epsilon.
40
+
41
+ Returns:
42
+ (hidden_out, context_out) of shapes (B, Ni, C) and (B, Nt, C), both bfloat16.""",
43
+
44
+ reference_imports="import torch\nimport torch.nn.functional as F",
45
+ reference_src='''
46
+ def sd3_mmdit_block(hidden, context, temb, hidden_w, context_w, num_heads, eps=1e-6):
47
+ """The whole SD3.5 joint block, one torch op at a time, in fp32.
48
+
49
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. The attention loop
50
+ chunks queries only so the fp32 score matrix fits in memory.
51
+ """
52
+ B, Ni, C = hidden.shape
53
+ Nt = context.shape[1]
54
+ H = num_heads
55
+ D = C // H
56
+ N = Ni + Nt
57
+
58
+ (h_modw, h_modb, h_qkvw, h_qkvb, h_qn, h_kn, h_pw, h_pb, h_f1w, h_f1b, h_f2w, h_f2b) = hidden_w
59
+ (c_modw, c_modb, c_qkvw, c_qkvb, c_qn, c_kn, c_pw, c_pb, c_f1w, c_f1b, c_f2w, c_f2b) = context_w
60
+
61
+ sv = F.silu(temb.float())
62
+ hm = sv @ h_modw.float().t() + h_modb.float() # (B, 6C)
63
+ cm = sv @ c_modw.float().t() + c_modb.float()
64
+
65
+ def _P(m, i):
66
+ return m[:, i * C:(i + 1) * C].unsqueeze(1) # (B, 1, C)
67
+
68
+ def _rms(t, g):
69
+ return t * torch.rsqrt(t.pow(2).mean(-1, keepdim=True) + eps) * g.float()
70
+
71
+ def _pre(x, m, qkvw, qkvb, qn, kn):
72
+ L = x.shape[1]
73
+ xn = F.layer_norm(x.float(), (C,), None, None, eps)
74
+ xm = (xn * (1.0 + _P(m, 1)) + _P(m, 0)).to(torch.bfloat16)
75
+ qkv = (xm.float() @ qkvw.float().t() + qkvb.float()).reshape(B, L, 3, H, D)
76
+ return (_rms(qkv[:, :, 0], qn).permute(0, 2, 1, 3),
77
+ _rms(qkv[:, :, 1], kn).permute(0, 2, 1, 3),
78
+ qkv[:, :, 2].permute(0, 2, 1, 3))
79
+
80
+ hq, hk, hv = _pre(hidden, hm, h_qkvw, h_qkvb, h_qn, h_kn)
81
+ cq, ck, cv = _pre(context, cm, c_qkvw, c_qkvb, c_qn, c_kn)
82
+
83
+ # IMAGE FIRST, then context -- this is the SD3 concatenation order. No rotary embedding.
84
+ q = torch.cat([hq, cq], dim=2) # (B, H, N, D)
85
+ k = torch.cat([hk, ck], dim=2)
86
+ v = torch.cat([hv, cv], dim=2)
87
+
88
+ sa = D ** -0.5
89
+ attn = torch.zeros(B, N, H, D, device=hidden.device, dtype=torch.float32)
90
+ for b in range(B):
91
+ qb = q[b] * sa
92
+ kb = k[b]
93
+ vb = v[b]
94
+ for s0 in range(0, N, 512):
95
+ e = min(s0 + 512, N)
96
+ p = torch.softmax(qb[:, s0:e] @ kb.transpose(1, 2), dim=-1)
97
+ attn[b, s0:e] = (p @ vb).transpose(0, 1)
98
+
99
+ def _post(x, a, m, pw, pb, f1w, f1b, f2w, f2b):
100
+ x1 = x.float() + _P(m, 2) * (a @ pw.float().t() + pb.float())
101
+ xn = F.layer_norm(x1, (C,), None, None, eps)
102
+ xm = xn * (1.0 + _P(m, 4)) + _P(m, 3)
103
+ h = F.gelu(xm @ f1w.float().t() + f1b.float(), approximate="tanh")
104
+ return (x1 + _P(m, 5) * (h @ f2w.float().t() + f2b.float())).to(torch.bfloat16)
105
+
106
+ hidden_out = _post(hidden, attn[:, :Ni].reshape(B, Ni, C), hm,
107
+ h_pw, h_pb, h_f1w, h_f1b, h_f2w, h_f2b)
108
+ context_out = _post(context, attn[:, Ni:].reshape(B, Nt, C), cm,
109
+ c_pw, c_pb, c_f1w, c_f1b, c_f2w, c_f2b)
110
+ return hidden_out, context_out
111
+ ''',
112
+ make_inputs_src='''
113
+ def _mk(B, Ni, Nt, H, D, Cm, seed):
114
+ gen = torch.Generator(device="cuda").manual_seed(seed)
115
+ C = H * D
116
+
117
+ def r(*sh, s=1.0):
118
+ return (torch.randn(*sh, device="cuda", generator=gen) * s).to(torch.bfloat16)
119
+
120
+ def stream():
121
+ return (r(6 * C, C, s=0.02), r(6 * C, s=0.05),
122
+ r(3 * C, C, s=1.7 * C ** -0.5), r(3 * C, s=0.05),
123
+ (1.0 + 0.2 * torch.randn(D, device="cuda", generator=gen)).to(torch.bfloat16),
124
+ (1.0 + 0.2 * torch.randn(D, device="cuda", generator=gen)).to(torch.bfloat16),
125
+ r(C, C, s=C ** -0.5), r(C, s=0.05),
126
+ r(Cm, C, s=C ** -0.5), r(Cm, s=0.05),
127
+ r(C, Cm, s=Cm ** -0.5), r(C, s=0.05))
128
+
129
+ ch = torch.exp(0.6 * (2 * torch.rand(C, device="cuda", generator=gen) - 1))
130
+
131
+ def act(L):
132
+ return (torch.randn(B, L, C, device="cuda", generator=gen) * ch
133
+ + torch.randn(B, L, 1, device="cuda", generator=gen)).to(torch.bfloat16)
134
+
135
+ return act(Ni), act(Nt), r(B, C), stream(), stream(), H
136
+ ''',
137
+ flops_src='''
138
+ def canonical_work(B, Ni, Nt, H, D, Cm):
139
+ """FLOPs attributed to one block forward, from the SHAPE ALONE.
140
+
141
+ Per stream, with L rows: a (L, C) x (C, 3C) QKV projection, a (L, C) x (C, C) output projection and a
142
+ two-layer MLP (L, C) x (C, Cm) + (L, Cm) x (Cm, C) -- 2 FLOPs per multiply-accumulate. Plus one joint
143
+ attention over N = Ni + Nt tokens, bidirectional and unmasked, at 4*D FLOPs per (query, key) pair per
144
+ head. The two 6-way adaLN projections are (B, C) x (C, 6C) and are four orders of magnitude smaller;
145
+ the LayerNorms, RMSNorms, GELU, softmax, gates and residuals are elementwise and are not counted.
146
+ """
147
+ C = H * D
148
+ N = Ni + Nt
149
+ return 2 * B * N * C * (4 * C + 2 * Cm) + 4 * B * H * D * N * N
150
+ ''',
151
+ flops_formula="2*B*(Ni+Nt)*C*(4*C + 2*Cm) + 4*B*H*D*(Ni+Nt)**2, C = H*D",
152
+
153
+ metric="TFLOP/s",
154
+ compare="tuple",
155
+ tuple_names=("hidden_out", "context_out"),
156
+ tol=4.5e-3, # MEASURED -- see precision_md
157
+ shape_names=("B", "Ni", "Nt", "H", "D", "Cm"),
158
+ grader_shapes=[(1, 16384, 333, 38, 64, 9728), (2, 10240, 333, 38, 64, 9728),
159
+ (2, 8192, 333, 38, 64, 9728), (4, 4096, 154, 38, 64, 9728),
160
+ (1, 16384, 154, 24, 64, 6144)],
161
+ measure_shapes=[(1, 15360, 333, 38, 64, 9728), (2, 9216, 333, 38, 64, 9728),
162
+ (2, 7680, 154, 38, 64, 9728), (3, 4096, 333, 38, 64, 9728),
163
+ (1, 14336, 154, 24, 64, 6144)],
164
+ measure_quick_shapes=[(1, 2048, 333, 38, 64, 9728), (2, 1024, 154, 38, 64, 9728),
165
+ (1, 1536, 77, 12, 64, 3072)],
166
+ correct_shapes=[(1, 517, 77, 4, 64, 1024), (2, 333, 65, 8, 64, 2048),
167
+ (1, 1024, 333, 38, 64, 9728), (3, 129, 13, 6, 64, 1536)],
168
+
169
+ spec_md="""One complete SD3.5 `JointTransformerBlock`. Two token sequences, two full parameter sets,
170
+ one shared conditioning embedding, and exactly one point of contact — the joint attention.
171
+ `C = num_heads * D`.
172
+
173
+ **Step 1 — 6-way adaLN, once per stream (different matrices, same `temb`):**
174
+
175
+ ```
176
+ hm = silu(temb) @ hidden_w.mod_w.T + hidden_w.mod_b # (B, 6C)
177
+ cm = silu(temb) @ context_w.mod_w.T + context_w.mod_b
178
+ chunks, in order: [ shift_msa | scale_msa | gate_msa | shift_mlp | scale_mlp | gate_mlp ]
179
+ 0 1 2 3 4 5
180
+ ```
181
+
182
+ **Step 2 — attention prologue, once per stream:**
183
+
184
+ ```
185
+ xm = layer_norm(x, (C,), None, None, eps) * (1 + scale_msa) + shift_msa
186
+ qkv = xm @ qkv_w.T + qkv_b # (B, L, 3C), laid out [3][H][D]
187
+ q,k,v = split(qkv) # each (B, L, H, D) -> (B, H, L, D)
188
+ q = q * rsqrt(mean_d(q^2) + eps) * q_norm_w # per (token, head), over D only
189
+ k = k * rsqrt(mean_d(k^2) + eps) * k_norm_w
190
+ ```
191
+
192
+ **Step 3 — joint attention over the concatenation, IMAGE FIRST**, bidirectional, no mask:
193
+
194
+ ```
195
+ q = concat([hidden_q, context_q], dim=2) # (B, H, N, D), N = Ni + Nt; same for k, v
196
+ attn = softmax( (D ** -0.5) * q k^T ) v
197
+ hidden_attn, context_attn = attn[:, :, :Ni], attn[:, :, Ni:]
198
+ ```
199
+
200
+ **There is no rotary embedding.** SD3 adds position once, as a 2-D sincos table on the patch embeddings,
201
+ before the first block — nothing in this block is position-dependent.
202
+
203
+ **Step 4 — epilogue, once per stream, with that stream's own weights and gates:**
204
+
205
+ ```
206
+ x1 = x + gate_msa * (x_attn @ proj_w.T + proj_b) # x_attn is (B, L, C) after merging heads
207
+ xn = layer_norm(x1, (C,), None, None, eps) * (1 + scale_mlp) + shift_mlp
208
+ h = gelu_tanh(xn @ fc1_w.T + fc1_b)
209
+ out = x1 + gate_mlp * (h @ fc2_w.T + fc2_b)
210
+ ```
211
+
212
+ `gelu_tanh` is exactly `torch.nn.functional.gelu(z, approximate="tanh")`. `V` is not normalised. Note the
213
+ second LayerNorm is taken on `x1`, **after** the attention residual — the two sub-layers are chained.
214
+
215
+ `/app/reference.py` writes all of this out as separate fp32 torch ops. That is the exact specification; it
216
+ is deliberately simple rather than fast, and its runtime has no bearing on your score.""",
217
+
218
+ contract_md="""| arg | shape | dtype | meaning |
219
+ |-----|-------|-------|---------|
220
+ | `hidden` | `(B, Ni, C)` | `bfloat16` | image-latent stream, `C = num_heads * D` |
221
+ | `context` | `(B, Nt, C)` | `bfloat16` | text context, the three encoders already concatenated |
222
+ | `temb` | `(B, C)` | `bfloat16` | timestep + pooled-text embedding, one row per image |
223
+ | `hidden_w` | 12-tuple | `bfloat16` | the image stream's parameters (order below) |
224
+ | `context_w` | 12-tuple | `bfloat16` | the text stream's parameters — **entirely different tensors** |
225
+ | `num_heads` | scalar | `int` | `H`; `D = C // H` |
226
+ | `eps` | scalar | `float` | LayerNorm **and** RMSNorm epsilon (`1e-6`) |
227
+
228
+ Each parameter tuple is, **in this exact index order**:
229
+
230
+ | idx | name | shape | | idx | name | shape |
231
+ |-----|------|-------|-|-----|------|-------|
232
+ | 0 | `mod_w` | `(6*C, C)` | | 6 | `proj_w` | `(C, C)` |
233
+ | 1 | `mod_b` | `(6*C,)` | | 7 | `proj_b` | `(C,)` |
234
+ | 2 | `qkv_w` | `(3*C, C)` | | 8 | `fc1_w` | `(Cm, C)` |
235
+ | 3 | `qkv_b` | `(3*C,)` | | 9 | `fc1_b` | `(Cm,)` |
236
+ | 4 | `q_norm_w` | `(D,)` | | 10 | `fc2_w` | `(C, Cm)` |
237
+ | 5 | `k_norm_w` | `(D,)` | | 11 | `fc2_b` | `(C,)` |
238
+
239
+ All weights use the `nn.Linear` `(out, in)` layout. The QKV output axis is ordered `[3][H][D]`.
240
+
241
+ **Return** a 2-tuple `(hidden_out, context_out)` **in that order**, shapes `(B, Ni, C)` and `(B, Nt, C)`,
242
+ both **`bfloat16`**.
243
+
244
+ The joint sequence is **image first**: joint row `n < Ni` is an image token. That is the model's order;
245
+ attention is permutation-invariant in the key axis, so it is bookkeeping rather than arithmetic here, but
246
+ it fixes which rows land in which returned tensor. `Ni` and `Nt` are **not**
247
+ multiples of any tile size, and `Nt` is one to two orders of magnitude smaller than `Ni`. All tensors are
248
+ CUDA and contiguous; treat them as read-only.""",
249
+
250
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in
251
+ 1–4 images, `Ni` in **4096–16384** image tokens (SD3.5 patchifies a 1024x1024 latent to 4096 tokens and a
252
+ 2048x2048 one to 16384), `Nt` in {154, 333} context tokens (77 CLIP + 77 or 256 T5), `H = 38`, `D = 64`
253
+ (so `C = 2432`, the SD3.5-Large width) with a narrower `H = 24, D = 64` shape as well, `Cm = 4*C`. Every
254
+ graded shape is **2.6–5.2 TFLOP**, split roughly half and half between the GEMMs and the attention.
255
+ Write a **general** kernel: the correctness shapes go down to `H = 4`, `C = 256` and thoroughly ragged
256
+ lengths.""",
257
+
258
+ correctness_md="""**Both** returned tensors must match the reference (evaluated in fp32 as a stable
259
+ ground truth) within **relative Frobenius error `4.5e-3`** at every graded shape, including the
260
+ timed ones, and the grader scores the **worse** of the two. `context_out` is 1–4% of the data and is graded
261
+ exactly as hard as `hidden_out` — which is the point, because it is the part a kernel tuned for the image
262
+ stream gets wrong.""",
263
+
264
+ perf_md="""Everything in this block happens **twice**, with `M ~ 10^4` and `M ~ 10^2`. That asymmetry,
265
+ not the arithmetic, is what separates a good implementation from a mediocre one.
266
+
267
+ * **Fuse the two streams' identically-shaped GEMMs into grouped GEMMs.** There are four pairs — QKV,
268
+ output projection, MLP fc1, MLP fc2 — and in each pair the two problems share a shape but not a weight.
269
+ Run each pair as a **2-group grouped GEMM** in one launch, with a tile -> group lookup selecting the
270
+ weight, bias, gate and residual. Eight sequential `torch.matmul`s, four of which cannot fill a single
271
+ wave, is where the naive implementation loses most of its time.
272
+ * **`D = 64` changes the attention's shape.** SD3.5-Large runs 38 heads of 64 channels rather than 24 of
273
+ 128: the `Q K^T` GEMM has half the K depth, so the score matrix costs the same but the MMA pipeline is
274
+ shallower and you need more key-tile parallelism to keep it fed. There is no mask, so the loop is dense
275
+ and perfectly load-balanced.
276
+ * **The QKV epilogue is three fused ops** — split `[3][H][D]`, RMS-normalise Q and K per head, and write
277
+ into the *joint* q/k/v buffers at the right offset with the head transpose. Done as separate torch ops
278
+ that is four more round-trips of a `(B, L, 3C)` tensor; done in the GEMM epilogue it is free, and the
279
+ "concatenation" is just a different output base pointer.
280
+ * **The MLP hidden is the biggest intermediate** — `Cm = 9728` wide. Fuse the GELU into `fc1`'s epilogue
281
+ and store bf16, or fuse `fc1 -> GELU -> fc2` so it never reaches HBM.
282
+ * **The two adaLN passes and the two LayerNorms are bandwidth, not compute.** Fuse each LayerNorm with its
283
+ modulate (and the second one with the preceding gated residual) into a single pass, and fuse both
284
+ streams into one launch.
285
+ * Both `(B, C) x (C, 6C)` modulation projections are negligible — compute them once and keep the twelve
286
+ parameter rows resident.
287
+
288
+ CUTLASS / CuTe DSL is installed and its grouped-GEMM plus epilogue-visitor machinery is the natural fit;
289
+ Triton works too if you write the group lookup yourself.""",
290
+
291
+ precision_md="""All activations and weights are **bfloat16**; both outputs are **bfloat16**. Every GEMM
292
+ belongs on **bf16 tensor cores with fp32 accumulation**.
293
+
294
+ What must be fp32: both LayerNorms' mean/variance, the RMSNorm mean-of-squares and `rsqrt`, the softmax
295
+ running max/sum/accumulator, the GELU, and each gated residual before its rounding to bf16. In particular
296
+ `x1` — the intermediate residual after the attention sub-layer — must be **formed in fp32 and the second
297
+ LayerNorm taken on that fp32 value**.
298
+
299
+ Intermediate *activations* (the modulated tensors, QKV after the norm, the attention output, the MLP
300
+ hidden) may all be stored in bf16 — that is what the tolerance is sized for.
301
+
302
+ **Where the tolerance comes from.** `4.5e-3` is measured. An independent bf16
303
+ implementation — LayerNorm arithmetic written out instead of `F.layer_norm`, `addmm` in bf16 for all eight
304
+ GEMMs, `scaled_dot_product_attention` in place of the chunked fp32 loop, and every intermediate rounded to
305
+ bf16 — differs from this fp32 reference by relative Frobenius error at most **2.23e-3** over 25
306
+ (shape, seed) combinations spanning the correctness shapes and a 4096-token graded shape. The gate is
307
+ **2.0x** that floor. For contrast, skipping the QK-RMSNorm scores **7.7e-2–4.0e-1**, 17x the gate at
308
+ worst. Two things this block does turn out **not** to be gradeable and are documented as conventions
309
+ rather than as arithmetic: the image-first concatenation order (attention is permutation-invariant in the
310
+ key axis, and the two streams are returned separately) and the tanh-vs-erf choice of GELU, which moves the
311
+ output by about the same 1e-3 as bf16 rounding does.
312
+
313
+ **fp8** is plausible for the four GEMM pairs, but the block's error budget is shared across a long chain —
314
+ if you quantise, do it in one place and measure.
315
+
316
+ Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
317
+ numerical *specification*.""",
318
+ ).validate()
tools/factory/specs/sd3_pos_embed_interpolate.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sd3-pos-embed-interpolate` — SD3 patch embed + bilinearly interpolated 2-D sincos positions."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="sd3-pos-embed-interpolate",
10
+ title="Write a fast SD3 patch-embed + interpolated 2-D position embedding",
11
+ blurb=("SD3 has no rotary embedding: position enters the model exactly once, as a fixed 2-D sincos "
12
+ "table added to the patch embeddings. The table is built for one base grid, so every "
13
+ "resolution other than the native one needs it BILINEARLY RESAMPLED to the target grid before "
14
+ "it is added. The kernel is therefore a strided 2x2x16 gather feeding a skinny (64 -> 2432) "
15
+ "projection, plus a float32 table resample whose source addresses are a non-integer function of "
16
+ "the output coordinate — a gather, a GEMV and an interpolation that all want to be one pass."),
17
+ keywords=["mle", "kernel-generation", "stable-diffusion-3", "sd3", "patch-embed", "positional-embedding",
18
+ "interpolation", "memory-bound", "diffusion-transformer", "image-generation"],
19
+ module="sd3_patch_embed.py",
20
+ func="sd3_patch_pos_embed",
21
+ signature="sd3_patch_pos_embed(lat, proj_w, proj_b, pos_base, patch)",
22
+ returns_doc="""SD3 patch embedding plus the resampled 2-D position table.
23
+
24
+ Args:
25
+ lat: (B, Cin, Hp, Wp) bfloat16 — the VAE latent.
26
+ proj_w: (C, Cin*patch*patch) bfloat16 — the patch projection, nn.Linear layout (out, in).
27
+ proj_b: (C,) bfloat16 — its bias.
28
+ pos_base: (base, base, C) float32 — the 2-D sincos position table at its base grid.
29
+ patch: int — the patch side (2 for SD3).
30
+
31
+ Returns:
32
+ out: (B, (Hp//patch)*(Wp//patch), C) bfloat16 — patch tokens with position added, row-major.""",
33
+
34
+ reference_imports="import torch",
35
+ reference_src='''
36
+ def sd3_patch_pos_embed(lat, proj_w, proj_b, pos_base, patch):
37
+ """Patchify, project, and add the bilinearly resampled position table, in fp32.
38
+
39
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target.
40
+ """
41
+ B, Cin, Hp, Wp = lat.shape
42
+ P = patch
43
+ gh, gw = Hp // P, Wp // P
44
+ base, _, C = pos_base.shape
45
+ dev = lat.device
46
+
47
+ # patchify: token (i, j) is the (Cin, P, P) block at (i*P, j*P), flattened channel-major
48
+ x = lat.float().reshape(B, Cin, gh, P, gw, P).permute(0, 2, 4, 1, 3, 5)
49
+ x = x.reshape(B, gh * gw, Cin * P * P)
50
+ tok = x @ proj_w.float().t() + proj_b.float() # (B, N, C)
51
+
52
+ def _axis(g):
53
+ s = base / g
54
+ src = torch.clamp(((torch.arange(g, device=dev, dtype=torch.float32) + 0.5) * s - 0.5), min=0.0)
55
+ i0 = torch.floor(src).to(torch.int64).clamp(max=base - 1)
56
+ i1 = torch.clamp(i0 + 1, max=base - 1)
57
+ return i0, i1, (src - i0.float())
58
+
59
+ y0, y1, wy = _axis(gh)
60
+ x0, x1, wx = _axis(gw)
61
+ t = pos_base
62
+ top = t[y0][:, x0] * (1.0 - wx)[None, :, None] + t[y0][:, x1] * wx[None, :, None]
63
+ bot = t[y1][:, x0] * (1.0 - wx)[None, :, None] + t[y1][:, x1] * wx[None, :, None]
64
+ pos = top * (1.0 - wy)[:, None, None] + bot * wy[:, None, None] # (gh, gw, C)
65
+
66
+ return (tok + pos.reshape(1, gh * gw, C)).to(torch.bfloat16)
67
+ ''',
68
+ make_inputs_src='''
69
+ def _mk(B, Hp, Wp, Cin, C, P, base, seed):
70
+ gen = torch.Generator(device="cuda").manual_seed(seed)
71
+ lat = (torch.randn(B, Cin, Hp, Wp, device="cuda", generator=gen) * 1.5).to(torch.bfloat16)
72
+ K = Cin * P * P
73
+ proj_w = (torch.randn(C, K, device="cuda", generator=gen) * K ** -0.5).to(torch.bfloat16)
74
+ proj_b = (torch.randn(C, device="cuda", generator=gen) * 0.05).to(torch.bfloat16)
75
+
76
+ # a real 2-D sincos table: half the channels encode the row, half the column
77
+ half = C // 2
78
+ omega = 1.0 / (10000.0 ** (torch.arange(half // 2, device="cuda", dtype=torch.float32) / (half // 2)))
79
+ grid = torch.arange(base, device="cuda", dtype=torch.float32)
80
+ ang = grid[:, None] * omega[None, :] # (base, half/2)
81
+ emb = torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1) # (base, half)
82
+ pos = torch.cat([emb[:, None, :].expand(base, base, half),
83
+ emb[None, :, :].expand(base, base, half)], dim=-1).contiguous()
84
+ return lat, proj_w, proj_b, pos.float(), P
85
+ ''',
86
+ flops_src='''
87
+ def canonical_work(B, Hp, Wp, Cin, C, P, base):
88
+ """BYTES attributed to this pass, from the SHAPE ALONE.
89
+
90
+ Read the latent (Cin*P*P bf16 values per token), write the token stream (C bf16 channels per token),
91
+ and read the float32 base table once. The (C, Cin*P*P) projection weight is tiny and fully reused and
92
+ is not counted. This is a bandwidth kernel, so the score is achieved bandwidth against this fixed
93
+ byte count.
94
+ """
95
+ N = (Hp // P) * (Wp // P)
96
+ return 2 * B * N * (Cin * P * P + C) + 4 * base * base * C
97
+ ''',
98
+ flops_formula="2*B*(Hp//P)*(Wp//P)*(Cin*P*P + C) + 4*base*base*C",
99
+
100
+ metric="GB/s",
101
+ compare="tensor",
102
+ tol=4e-4, # MEASURED -- see precision_md
103
+ shape_names=("B", "Hp", "Wp", "Cin", "C", "P", "base"),
104
+ grader_shapes=[(24, 256, 256, 16, 2432, 2, 64), (16, 288, 288, 16, 2432, 2, 64),
105
+ (12, 352, 352, 16, 2432, 2, 64), (32, 192, 192, 16, 2432, 2, 64),
106
+ (48, 160, 160, 16, 2432, 2, 64)],
107
+ measure_shapes=[(20, 256, 256, 16, 2432, 2, 64), (16, 256, 288, 16, 2432, 2, 64),
108
+ (12, 320, 320, 16, 2432, 2, 64), (28, 192, 192, 16, 2432, 2, 64),
109
+ (40, 160, 160, 16, 2432, 2, 64)],
110
+ measure_quick_shapes=[(4, 128, 128, 16, 2432, 2, 64), (2, 192, 192, 16, 2432, 2, 64),
111
+ (8, 64, 64, 16, 1536, 2, 32)],
112
+ correct_shapes=[(1, 34, 46, 16, 512, 2, 32), (2, 26, 26, 16, 768, 2, 32),
113
+ (3, 120, 136, 16, 2432, 2, 64), (1, 18, 50, 8, 1536, 2, 24)],
114
+
115
+ spec_md="""Patchify the latent, project each patch to `C` channels, and add the position table
116
+ resampled to the token grid.
117
+
118
+ **1. Patchify + project.** With `gh = Hp // P` and `gw = Wp // P`, token `n = i*gw + j` (row-major) is the
119
+ `(Cin, P, P)` block at `(i*P, j*P)`, flattened **channel-major** — index `((c*P) + pi)*P + pj`:
120
+
121
+ ```
122
+ tok[b, i*gw + j, :] = proj_w @ vec(lat[b, :, i*P:(i+1)*P, j*P:(j+1)*P]) + proj_b
123
+ ```
124
+
125
+ That is exactly a `Conv2d(Cin, C, kernel=P, stride=P)` with its weight flattened to `(C, Cin*P*P)`.
126
+
127
+ **2. Resample the position table** from `(base, base, C)` to `(gh, gw, C)` by **bilinear** interpolation
128
+ with the half-pixel convention. Per axis, with `g` the target length:
129
+
130
+ ```
131
+ s = base / g
132
+ src(i) = max(0, (i + 0.5) * s - 0.5)
133
+ i0 = min(floor(src(i)), base - 1)
134
+ i1 = min(i0 + 1, base - 1)
135
+ w(i) = src(i) - i0 # in [0, 1)
136
+ ```
137
+
138
+ and then, with `(y0, y1, wy)` from the row axis and `(x0, x1, wx)` from the column axis,
139
+
140
+ ```
141
+ pos[i, j] = (1-wy)*(1-wx) * T[y0, x0] + (1-wy)*wx * T[y0, x1]
142
+ + wy *(1-wx) * T[y1, x0] + wy *wx * T[y1, x1]
143
+ ```
144
+
145
+ This is the same convention as `align_corners=False` bilinear resampling, including the clamp of a
146
+ negative source coordinate to 0. Note `gh` and `gw` are resampled **independently**, and either can be
147
+ larger or smaller than `base`.
148
+
149
+ **3. Add and round.**
150
+
151
+ ```
152
+ out[b, n, :] = tok[b, n, :] + pos[n // gw, n % gw, :] # bfloat16
153
+ ```
154
+
155
+ `/app/reference.py` writes all of this out as separate fp32 torch ops with an advanced-indexing gather.
156
+ That is the exact specification; it is deliberately simple rather than fast, and its runtime has no
157
+ bearing on your score.""",
158
+
159
+ contract_md="""| arg | shape | dtype | meaning |
160
+ |-----|-------|-------|---------|
161
+ | `lat` | `(B, Cin, Hp, Wp)` | `bfloat16` | the VAE latent; `Hp` and `Wp` are multiples of `patch` |
162
+ | `proj_w` | `(C, Cin*P*P)` | `bfloat16` | patch projection, `(out, in)`; input index `((c*P)+pi)*P+pj` |
163
+ | `proj_b` | `(C,)` | `bfloat16` | projection bias |
164
+ | `pos_base` | `(base, base, C)` | `float32` | 2-D sincos table at the base grid, row axis first |
165
+ | `patch` | scalar | `int` | patch side, always 2 at the graded shapes |
166
+
167
+ **Return** a single tensor of shape `(B, (Hp//P)*(Wp//P), C)` and dtype **`bfloat16`**, with the token axis
168
+ **row-major over the grid**: token `n` is at `(i, j) = (n // gw, n % gw)`.
169
+
170
+ `pos_base` is **float32 and shared by the whole batch** — it does not depend on `b`. The resampled table
171
+ likewise does not depend on `b`, so it is computed once for the whole call.
172
+
173
+ `gh` and `gw` are **not** multiples of any tile size and are **not** equal in general — the correctness
174
+ shapes include `17 x 23`, `60 x 68` and `9 x 25` token grids, and both up-sampling (`g > base`) and down-sampling
175
+ (`g < base`) occur. All tensors are CUDA and contiguous; treat them as read-only.""",
176
+
177
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in
178
+ 12–48 images per batch, `Hp` and `Wp` in **160–352** latent pixels (an SD3 latent is the image divided by
179
+ 8, so 256 corresponds to a 2048x2048 image and 160 to 1280x1280), `Cin = 16`, `C = 2432` (the SD3.5-Large
180
+ width), `P = 2`, `base = 64`. Every graded shape moves **1.4–1.9 GiB**. Batching is the point: the patch
181
+ embed runs once per denoising step, so it only ever matters as a throughput kernel over a batch. Write a
182
+ **general** kernel: the correctness shapes go down to `C = 512`, `Cin = 8`, `base = 24` and thoroughly
183
+ ragged grids.""",
184
+
185
+ correctness_md="""Your output must match the reference (evaluated in fp32 as a stable ground truth)
186
+ within **relative Frobenius error `4e-4`** at every graded shape, including the timed ones.
187
+
188
+ The resampling convention is the part that is easy to get wrong and is graded hard: nearest-neighbour
189
+ instead of bilinear, or the `align_corners=True` coordinate mapping, both land orders of magnitude outside
190
+ the gate.""",
191
+
192
+ perf_md="""A `Cin*P*P = 64`-wide read, a `C = 2432`-wide write, and a table lookup between them.
193
+
194
+ * **The write dominates.** 64 bf16 in, 2432 bf16 out per token — a **1:38** read-to-write ratio, the
195
+ inverse of the final layer's. The output store must be perfectly coalesced and vectorised along `C`.
196
+ * **Resample the table ONCE, not per image.** `pos` is `(gh, gw, C)` and independent of `b`; computing it
197
+ in a small prologue kernel (or in the first CTA wave into a workspace) and then streaming it is far
198
+ cheaper than redoing four fp32 gathers per output element for every batch element. At `B = 24` that is a
199
+ 24x difference on the interpolation work.
200
+ * **Better: keep the row weights per tile.** A tile of tokens in one grid row shares `y0`, `y1` and `wy`,
201
+ and consecutive columns share nothing but are contiguous in the table's `x` axis — so a tile can load
202
+ two table rows into shared memory and interpolate on the fly with no workspace at all.
203
+ * **The projection is a skinny GEMM (`K = 64`, `N = 2432`) and is memory bound.** `proj_w` is only
204
+ `2432 x 64` and is reused by every token of every image: hold it in shared memory, and give each CTA a
205
+ few tokens so the `K = 64` reduction stays in registers.
206
+ * **The patchify gather is strided.** Token `(i, j)` needs `lat[b, :, i*P:(i+1)*P, j*P:(j+1)*P]`, which is
207
+ `Cin` rows of 2 contiguous bf16 values at a `Wp` stride. Reading a whole `P`-row band of the latent into
208
+ shared memory and re-indexing there beats per-token strided loads.
209
+ * Watch the ragged grid: `gh` and `gw` are arbitrary, so the last tile of each row is partial.""",
210
+
211
+ precision_md="""`lat`, `proj_w`, `proj_b` and the output are **bfloat16**; `pos_base` is **float32**.
212
+
213
+ What must be fp32: the projection accumulator, the four interpolation weights and their combination, and
214
+ the final add. The table is fp32 for a reason — the sincos values are the same for every image and every
215
+ step, and rounding them to bf16 before the interpolation is a coherent error on a term that is added
216
+ directly to the output.
217
+
218
+ **Where the tolerance comes from.** `4e-4` is measured. An independent
219
+ implementation — `F.conv2d` for the patch projection and `F.interpolate(mode="bilinear",
220
+ align_corners=False)` for the resample, against the reference's explicit gather and matmul — differs by
221
+ relative Frobenius error at most **4.29e-5** over 25 (shape, seed) combinations spanning the correctness
222
+ shapes and a 96x96-grid graded shape. (That the two agree to 4e-5 is also the check that the resampling
223
+ convention written above really is `align_corners=False`.) The gate is **9.3x** that floor, and it is
224
+ below every way of getting the position term wrong: nearest-neighbour resampling scores
225
+ **3.1e-2–3.6e-2** (78x the gate), the `align_corners=True` coordinate mapping scores **2.1e-3–9.3e-3**
226
+ (5.2x), rounding the fp32 table to bf16 before interpolating scores **1.0e-3–1.1e-3** (2.5x), and
227
+ omitting the position entirely scores **0.42**.
228
+
229
+ **fp8 is not useful here** and is not expected — this is a bandwidth kernel with a `K = 64` projection.
230
+
231
+ Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
232
+ numerical *specification*.""",
233
+ ).validate()
tools/factory/specs/sd3_qkv_proj_qknorm.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sd3-qkv-proj-qknorm` — SD3.5's dual-stream QKV projection with a fused QK-RMSNorm epilogue."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="sd3-qkv-proj-qknorm",
10
+ title="Write a fast SD3.5 dual-stream QKV projection (2-group GEMM, fused QK-RMSNorm, joint write)",
11
+ blurb=("Both halves of every SD3.5 block project their own QKV: one (Ni, C) x (C, 3C) GEMM for the "
12
+ "image latents and one (Nt, C) x (C, 3C) GEMM for the concatenated text context, with different "
13
+ "weights and a 50:1 row imbalance. Whatever they produce then has to be de-interleaved into "
14
+ "[3][H][D], RMS-normalised per head with four different gain vectors, transposed to head-major "
15
+ "and written into ONE joint Q/K/V triple with the image first — so the interesting part is not "
16
+ "the matmul, it is that the matmul's epilogue is a norm, a transpose and a concatenation at once."),
17
+ keywords=["mle", "kernel-generation", "stable-diffusion-3", "sd3", "mmdit", "grouped-gemm",
18
+ "epilogue-fusion", "rmsnorm", "diffusion-transformer", "image-generation"],
19
+ module="sd3_qkv.py",
20
+ func="sd3_qkv_proj_qknorm",
21
+ signature="sd3_qkv_proj_qknorm(hidden, context, hidden_w, context_w, num_heads, eps=1e-6)",
22
+ returns_doc="""Both streams' QKV projections, QK-RMSNormed and joined image-first.
23
+
24
+ Args:
25
+ hidden: (B, Ni, C) bfloat16 — the already-modulated image-latent stream.
26
+ context: (B, Nt, C) bfloat16 — the already-modulated text context stream.
27
+ hidden_w: 4-tuple (qkv_w (3*C, C), qkv_b (3*C,), q_norm_w (D,), k_norm_w (D,)) bfloat16.
28
+ context_w: the same 4-tuple for the text stream — entirely different tensors.
29
+ num_heads: int — H; D = C // H.
30
+ eps: float — RMSNorm epsilon.
31
+
32
+ Returns:
33
+ (q, k, v), each (B, H, Ni + Nt, D) bfloat16, image tokens occupying rows [0, Ni).""",
34
+
35
+ reference_imports="import torch",
36
+ reference_src='''
37
+ def sd3_qkv_proj_qknorm(hidden, context, hidden_w, context_w, num_heads, eps=1e-6):
38
+ """Two QKV projections with a norm + transpose + join epilogue, one torch op at a time, in fp32.
39
+
40
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target.
41
+ """
42
+ B, Ni, C = hidden.shape
43
+ Nt = context.shape[1]
44
+ H = num_heads
45
+ D = C // H
46
+
47
+ def _rms(t, g):
48
+ return t * torch.rsqrt(t.pow(2).mean(-1, keepdim=True) + eps) * g.float()
49
+
50
+ def _one(x, w):
51
+ qkv_w, qkv_b, qn, kn = w
52
+ L = x.shape[1]
53
+ p = (x.float() @ qkv_w.float().t() + qkv_b.float()).reshape(B, L, 3, H, D)
54
+ return _rms(p[:, :, 0], qn), _rms(p[:, :, 1], kn), p[:, :, 2]
55
+
56
+ hq, hk, hv = _one(hidden, hidden_w)
57
+ cq, ck, cv = _one(context, context_w)
58
+
59
+ # IMAGE FIRST, then context; head-major
60
+ q = torch.cat([hq, cq], dim=1).permute(0, 2, 1, 3).contiguous().to(torch.bfloat16)
61
+ k = torch.cat([hk, ck], dim=1).permute(0, 2, 1, 3).contiguous().to(torch.bfloat16)
62
+ v = torch.cat([hv, cv], dim=1).permute(0, 2, 1, 3).contiguous().to(torch.bfloat16)
63
+ return q, k, v
64
+ ''',
65
+ make_inputs_src='''
66
+ def _mk(B, Ni, Nt, H, D, seed):
67
+ gen = torch.Generator(device="cuda").manual_seed(seed)
68
+ C = H * D
69
+
70
+ def r(*sh, s=1.0):
71
+ return (torch.randn(*sh, device="cuda", generator=gen) * s).to(torch.bfloat16)
72
+
73
+ def w():
74
+ # per-head output scales vary, which is exactly what the QK-RMSNorm is there to remove
75
+ sc = torch.exp(0.5 * (2 * torch.rand(3, H, 1, device="cuda", generator=gen) - 1))
76
+ m = (torch.randn(3, H, D, C, device="cuda", generator=gen) * (1.7 * C ** -0.5) * sc[..., None])
77
+ return (m.reshape(3 * C, C).to(torch.bfloat16), r(3 * C, s=0.05),
78
+ (1.0 + 0.2 * torch.randn(D, device="cuda", generator=gen)).to(torch.bfloat16),
79
+ (1.0 + 0.2 * torch.randn(D, device="cuda", generator=gen)).to(torch.bfloat16))
80
+
81
+ # both streams arrive already LayerNormed and modulated: roughly unit variance, per-channel gain
82
+ ch = torch.exp(0.4 * (2 * torch.rand(C, device="cuda", generator=gen) - 1))
83
+
84
+ def act(L):
85
+ return (torch.randn(B, L, C, device="cuda", generator=gen) * ch).to(torch.bfloat16)
86
+
87
+ return act(Ni), act(Nt), w(), w(), H
88
+ ''',
89
+ flops_src='''
90
+ def canonical_work(B, Ni, Nt, H, D):
91
+ """FLOPs attributed to both QKV projections, from the SHAPE ALONE.
92
+
93
+ Per stream with L rows: (L, C) x (C, 3C), 2 FLOPs per multiply-accumulate. The per-head RMSNorm, the
94
+ de-interleave, the head transpose and the join are elementwise or pure layout and are not counted --
95
+ they are exactly the overhead you are expected to fuse into the epilogue.
96
+ """
97
+ C = H * D
98
+ return 2 * B * (Ni + Nt) * C * 3 * C
99
+ ''',
100
+ flops_formula="2*B*(Ni+Nt)*C*3*C, C = H*D",
101
+
102
+ metric="TFLOP/s",
103
+ compare="tuple",
104
+ tuple_names=("q", "k", "v"),
105
+ tol=6e-3, # MEASURED -- see precision_md
106
+ shape_names=("B", "Ni", "Nt", "H", "D"),
107
+ grader_shapes=[(1, 16384, 333, 38, 64), (2, 12288, 333, 38, 64),
108
+ (4, 8192, 333, 38, 64), (8, 4096, 333, 38, 64),
109
+ (2, 16384, 154, 24, 128)],
110
+ measure_shapes=[(1, 15360, 333, 38, 64), (2, 11264, 333, 38, 64),
111
+ (4, 7680, 154, 38, 64), (6, 4096, 333, 38, 64),
112
+ (2, 14336, 154, 24, 128)],
113
+ measure_quick_shapes=[(1, 4096, 333, 38, 64), (2, 2048, 154, 38, 64), (1, 1536, 77, 12, 64)],
114
+ correct_shapes=[(1, 517, 77, 4, 64), (2, 333, 65, 8, 64),
115
+ (1, 2048, 333, 38, 64), (3, 129, 13, 6, 128)],
116
+
117
+ spec_md="""Two independent QKV projections and one fused epilogue. `C = num_heads * D`.
118
+
119
+ ```
120
+ # per stream, with that stream's own weights:
121
+ p = x @ qkv_w.T + qkv_b # (B, L, 3C), the output axis is ordered [3][H][D]
122
+ q, k, v = p.reshape(B, L, 3, H, D) split on axis 2 # each (B, L, H, D)
123
+
124
+ q = q * rsqrt(mean_d(q^2) + eps) * q_norm_w # per (token, head), over D only
125
+ k = k * rsqrt(mean_d(k^2) + eps) * k_norm_w
126
+ # v is not normalised
127
+
128
+ # then join IMAGE FIRST and transpose to head-major
129
+ q = concat([hidden_q, context_q], dim=1).permute(0, 2, 1, 3) # (B, H, Ni + Nt, D)
130
+ # same for k and v
131
+ ```
132
+
133
+ Four different gain vectors are in play: the image stream and the text stream each have their own Q gain
134
+ and K gain. The RMSNorm is over the **head dimension `D` of one token**, not over the full `C`, and the
135
+ same `(D,)` gain is shared by every head of that stream.
136
+
137
+ There is **no rotary embedding** — SD3 adds position once as a 2-D sincos table at patchify, so nothing
138
+ here is position-dependent.
139
+
140
+ `/app/reference.py` writes this out as separate fp32 torch ops with a `cat` and a `permute`. That is the
141
+ exact specification; it is deliberately simple rather than fast, and its runtime has no bearing on your
142
+ score.""",
143
+
144
+ contract_md="""| arg | shape | dtype | meaning |
145
+ |-----|-------|-------|---------|
146
+ | `hidden` | `(B, Ni, C)` | `bfloat16` | image stream, already LayerNormed and modulated |
147
+ | `context` | `(B, Nt, C)` | `bfloat16` | text stream, already LayerNormed and modulated |
148
+ | `hidden_w` | 4-tuple | `bfloat16` | `(qkv_w (3C,C), qkv_b (3C,), q_norm_w (D,), k_norm_w (D,))` |
149
+ | `context_w` | 4-tuple | `bfloat16` | same shapes, **entirely different tensors** |
150
+ | `num_heads` | scalar | `int` | `H`; `D = C // H` |
151
+ | `eps` | scalar | `float` | RMSNorm epsilon (`1e-6`) |
152
+
153
+ Both weight matrices use the `nn.Linear` `(out, in)` layout, and their output axis is ordered `[3][H][D]`
154
+ — all heads of Q, then all heads of K, then all heads of V.
155
+
156
+ **Return** a 3-tuple `(q, k, v)` **in that order**, each `(B, Ni + Nt, D)` promoted to head-major
157
+ `(B, H, Ni + Nt, D)` and **`bfloat16`**, with the **image** stream occupying rows `[0, Ni)` of the token
158
+ axis and the text stream rows `[Ni, Ni + Nt)`.
159
+
160
+ `Ni` and `Nt` are **not** multiples of any tile size, and `Nt` is one to two orders of magnitude smaller
161
+ than `Ni`. All tensors are CUDA and contiguous; treat them as read-only.""",
162
+
163
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in
164
+ 1–8 images, `Ni` in **4096–16384** image tokens, `Nt` in {154, 333} context tokens, `H = 38` with `D = 64`
165
+ (so `C = 2432`, the SD3.5-Large width) plus one `H = 24, D = 128` shape. Every graded shape is
166
+ **0.6–1.9 TFLOP** in the GEMMs and writes **0.6–1.9 GB** of output, so the epilogue's bandwidth is a real
167
+ part of the cost and not a rounding error. Write a **general** kernel: the correctness shapes go down to
168
+ `H = 4`, `C = 256` and ragged lengths.""",
169
+
170
+ correctness_md="""**All three** returned tensors must match the reference (evaluated in fp32 as a
171
+ stable ground truth) within **relative Frobenius error `6e-3`** at every graded shape, including
172
+ the timed ones; the grader scores the **worst** of the three. `v` exercises only the projection and the
173
+ layout, so it is effectively an exactness check on your GEMM, while `q` and `k` additionally exercise the
174
+ per-head norm and the choice of gain vector.""",
175
+
176
+ perf_md="""Two GEMMs with a 50:1 row imbalance and an epilogue that is three things at once.
177
+
178
+ * **Run the pair as a 2-group grouped GEMM in ONE launch.** The two problems share `(C, 3C)` but not the
179
+ weight; a tile -> group lookup picks the weight, the bias, the two gain vectors and the output row
180
+ offset. Two sequential `torch.matmul`s leave the machine idle through the second one, which has a few
181
+ hundred rows.
182
+ * **The join is a row offset, not a copy.** Image tiles write to joint rows `[0, Ni)` and context tiles to
183
+ `[Ni, Ni+Nt)`. Building the two halves and calling `cat` is a full extra round-trip of the three largest
184
+ tensors here.
185
+ * **The per-head RMSNorm wants the tile to span a whole head.** The mean-of-squares is over the `D`
186
+ channels of one `(token, head)`; if your N-tile covers `D` columns of one head the reduction is a
187
+ register/warp reduction inside the epilogue, and if it does not you need a cross-tile pass and the
188
+ fusion is gone. With `D = 64` a 64-wide N-tile is the natural choice; note the three sections `[0, C)`,
189
+ `[C, 2C)`, `[2C, 3C)` need different treatment (Q gain, K gain, nothing).
190
+ * **The head transpose is a scatter.** Accumulator element `(b, n, h, d)` lands at `q[b, h, n, d]`, a
191
+ stride-`N*D` jump per head; stage through shared memory so the global stores stay coalesced along `d`.
192
+ * **`K = C` is only 2432.** Do not split-K: you have plenty of tiles from `M = 10^4` and `3C` columns, and
193
+ split-K would force the norm into a second pass, which is the one thing this task is about avoiding.
194
+ * The four gain vectors are `D` values each and fully reused — keep them in registers.
195
+
196
+ CUTLASS / CuTe DSL is installed and its grouped-GEMM plus epilogue-visitor machinery fits this exactly;
197
+ Triton works too if you write the group and section lookups yourself.""",
198
+
199
+ precision_md="""Activations, weights and all three outputs are **bfloat16**. The GEMM belongs on
200
+ **bf16 tensor cores with fp32 accumulation**.
201
+
202
+ What must be fp32: the GEMM accumulator, the RMSNorm mean-of-squares and `rsqrt`, and the gain multiply.
203
+ Round to bf16 only when storing. Accumulating `q^2` over `D` channels in bf16 costs roughly an order of
204
+ magnitude more than the gate allows.
205
+
206
+ **Where the tolerance comes from.** `6e-3` is measured. An independent implementation —
207
+ a bf16 `addmm` instead of the fp32 matmul, the de-interleave by indexing rather than slicing, and the
208
+ RMSNorm written out by hand — differs from this fp32 reference by relative Frobenius error at most
209
+ **2.82e-3** (worst of the three outputs) over 20 (shape, seed) combinations spanning the correctness
210
+ shapes and a 2048-token graded shape. The gate is **2.1x** that floor, and it is two orders of magnitude
211
+ below what the distinguishing pieces cost: skipping the QK-RMSNorm scores **0.83–1.08**, joining
212
+ context-before-image scores **1.41**, and normalising over the whole `C` instead of per head scores
213
+ **0.16–0.26**.
214
+
215
+ **fp8** for the projection is possible but will eat most of this budget on its own — measure before you
216
+ commit.
217
+
218
+ Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
219
+ numerical *specification*.""",
220
+ ).validate()
tools/factory/specs/seqparallel_partial_norm.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `seqparallel-partial-norm` — the sequence/tensor-parallel RMSNorm: per-shard partial sums of
2
+ squares for the all-reduce, and the normalisation against the combined statistic, over a rank-major layout."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="seqparallel-partial-norm",
11
+ title="Write a fast sequence-parallel RMSNorm kernel (per-shard partials + combined normalisation)",
12
+ blurb=("At the sequence-parallel to tensor-parallel boundary the hidden dimension is split across "
13
+ "ranks, so a norm whose statistic spans the whole hidden vector cannot be computed locally. "
14
+ "Each rank reduces its own shard, the partials are all-reduced, and only then can anything be "
15
+ "normalised. The single-GPU work is the awkward half: a residual add, a partial sum of squares "
16
+ "per (token, shard) in the rank-major layout the collective produced, and a second pass that "
17
+ "normalises against the combined statistic with each shard's own gain."),
18
+ keywords=["mle", "kernel-generation", "sequence-parallel", "tensor-parallel", "rmsnorm", "partial-sum",
19
+ "all-reduce", "residual", "distributed", "training", "memory-bound"],
20
+ module="sp_norm.py",
21
+ func="seqparallel_partial_norm",
22
+ signature="seqparallel_partial_norm(x, res, g, eps=1e-6)",
23
+ returns_doc="""Sequence-parallel RMSNorm over a hidden dimension sharded across W ranks.
24
+
25
+ Args:
26
+ x: (W, S, Hs) bfloat16 — this block's output, rank-major: block w is rank w's hidden shard.
27
+ res: (W, S, Hs) bfloat16 — the incoming residual stream, same layout.
28
+ g: (W, Hs) bfloat16 — the RMSNorm gain, also sharded across the ranks.
29
+ eps: float — added to the mean square before the reciprocal square root.
30
+
31
+ Returns:
32
+ (h, partial, y) where
33
+ h: (W, S, Hs) bfloat16 — the updated residual stream, x + res
34
+ partial: (W, S) float32 — per (shard, token) sum of squares of h; the all-reduce payload
35
+ y: (W, S, Hs) bfloat16 — h * rsqrt(sum_w partial / H + eps) * g, with H = W*Hs""",
36
+
37
+ reference_imports="import torch",
38
+ reference_src='''
39
+ def seqparallel_partial_norm(x, res, g, eps=1e-6):
40
+ """Residual add, per-shard partial sums, then normalise against the combined statistic, in fp32.
41
+
42
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. Every line
43
+ materialises another full-size fp32 temporary in HBM.
44
+ """
45
+ W, S, Hs = x.shape
46
+ H = W * Hs
47
+ h = x.float() + res.float() # the updated residual stream
48
+ partial = (h * h).sum(dim=-1) # (W, S) -- what each rank all-reduces
49
+ total = partial.sum(dim=0) # (S,) -- after the all-reduce
50
+ scale = torch.rsqrt(total / H + eps) # (S,)
51
+ y = h * scale.view(1, S, 1) * g.float().unsqueeze(1)
52
+ return h.to(torch.bfloat16), partial, y.to(torch.bfloat16)
53
+ ''',
54
+ make_inputs_src='''
55
+ def _mk(W, S, Hs, seed):
56
+ """A rank-major activation block: W hidden shards of Hs channels, S tokens, plus the sharded gain.
57
+
58
+ The shards do NOT have equal scale. In a trained model the hidden channels' magnitudes vary by several
59
+ times across the vector, so which rank a channel lands on matters, and a shard's own mean square is a
60
+ poor estimate of the whole vector's. That is exactly why the partials have to be all-reduced.
61
+ """
62
+ gen = torch.Generator(device="cuda").manual_seed(seed)
63
+ shard_scale = (0.25 + 1.75 * torch.rand(W, 1, 1, device="cuda", generator=gen))
64
+ x = (torch.randn(W, S, Hs, device="cuda", dtype=torch.float32, generator=gen) * shard_scale).bfloat16()
65
+ res = (torch.randn(W, S, Hs, device="cuda", dtype=torch.float32, generator=gen)
66
+ * 2.0 * shard_scale).bfloat16()
67
+ g = (1.0 + 0.1 * torch.randn(W, Hs, device="cuda", dtype=torch.float32, generator=gen)).bfloat16()
68
+ return x, res, g, 1e-6
69
+ ''',
70
+ flops_src='''
71
+ def canonical_work(W, S, Hs):
72
+ """BYTES attributed to one sequence-parallel norm, from the SHAPE ALONE.
73
+
74
+ Read x and res (2 bytes/elt each), write h and y (2 each). The (W, S) partial vector and the (W, Hs)
75
+ gain are 1/Hs and 1/S of the traffic and are not counted. Bandwidth-bound: the score is achieved
76
+ bandwidth against that fixed 8-bytes-per-element count.
77
+ """
78
+ return 8 * W * S * Hs
79
+ ''',
80
+ flops_formula="canonical_work(W, S, Hs) = (2 + 2 + 2 + 2) * W*S*Hs = 8 * W*S*Hs bytes",
81
+
82
+ metric="GB/s",
83
+ compare="tuple",
84
+ tuple_names=("h", "partial", "y"),
85
+ tol=1e-4,
86
+ shape_names=("W", "S", "Hs"),
87
+ grader_shapes=[(8, 16384, 1536), (4, 16384, 3072), (8, 12288, 2048),
88
+ (16, 8192, 1024), (2, 24576, 5120)],
89
+ measure_shapes=[(8, 12288, 1536), (4, 12288, 3072), (8, 10240, 2048),
90
+ (16, 6144, 1024), (2, 20480, 5120)],
91
+ measure_quick_shapes=[(4, 2048, 1024), (8, 1024, 512), (2, 4096, 2048)],
92
+ correct_shapes=[(4, 64, 128), (3, 129, 96), (8, 17, 200), (2, 256, 33), (5, 33, 64)],
93
+
94
+ spec_md="""The hidden dimension `H = W * Hs` is split across `W` tensor-parallel ranks and the
95
+ activation arrives **rank-major**: `x[w]` is rank `w`'s `Hs`-wide shard of every token. The block is
96
+
97
+ ```
98
+ h[w, s, j] = x[w, s, j] + res[w, s, j] # residual add, in fp32
99
+ partial[w, s] = sum over j of h[w, s, j]^2 # each rank's own contribution
100
+ total[s] = sum over w of partial[w, s] # what the all-reduce produces
101
+ y[w, s, j] = h[w, s, j] * rsqrt( total[s] / H + eps ) * g[w, j] # H = W*Hs, the FULL hidden size
102
+ ```
103
+
104
+ Three things are easy to get wrong and all three are graded.
105
+
106
+ **The normaliser spans every shard.** `total[s]` sums over all `W` of them, and it is divided by the
107
+ **full** `H`, not by `Hs`. Normalising a shard against its own partial is the classic mistake and it
108
+ changes every output.
109
+
110
+ **`partial` is an output in its own right.** It is the buffer that goes on the wire, so it is graded
111
+ against the reference just like `y`, and it must be accumulated in **fp32** — the sum is over `Hs`
112
+ elements of squares and a bf16 accumulator loses it.
113
+
114
+ **The gain is sharded too.** `g[w, j]` belongs to shard `w`; it is indexed by the shard, not by a global
115
+ channel index.
116
+
117
+ `h` is returned as well because the residual stream is what the next block consumes, and re-deriving it
118
+ costs a second pass over `x` and `res`.
119
+
120
+ `/app/reference.py` computes each of those lines as a separate full-size fp32 tensor. That is the exact
121
+ specification; it is deliberately simple rather than fast.""",
122
+
123
+ contract_md="""| arg | shape | dtype | meaning |
124
+ |-----|-------|-------|---------|
125
+ | `x` | `(W, S, Hs)` | `bfloat16` | this block's output, rank-major over the hidden shards |
126
+ | `res` | `(W, S, Hs)` | `bfloat16` | the incoming residual stream, same layout |
127
+ | `g` | `(W, Hs)` | `bfloat16` | the RMSNorm gain, sharded the same way |
128
+ | `eps` | scalar | `float` | keyword argument, default `1e-6` |
129
+
130
+ **Return** a 3-tuple `(h, partial, y)` **in that order**:
131
+
132
+ | out | shape | dtype | notes |
133
+ |-----|-------|-------|-------|
134
+ | `h` | `(W, S, Hs)` | `bfloat16` | `x + res`, rounded once |
135
+ | `partial` | `(W, S)` | `float32` | per-shard sum of squares of `h`, **fp32** |
136
+ | `y` | `(W, S, Hs)` | `bfloat16` | normalised and gained output |
137
+
138
+ `partial` is computed from the **fp32** `h` (i.e. `x.float() + res.float()`), not from the bf16 `h` that is
139
+ returned. `Hs` is not a multiple of any tile size (`Hs = 33`, `Hs = 200` appear in the correctness shapes)
140
+ and neither is `S`. All inputs are read-only.""",
141
+
142
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `W`
143
+ (tensor-parallel ranks sharing the hidden dimension) 2–16, `S` (tokens in the sequence-parallel region)
144
+ 8192–24576, `Hs` (channels per shard) 1024–5120, so the full hidden size `W*Hs` is 10240–12288 and the
145
+ block holds **200–250 M activation elements**, 1.6–2.0 GB of traffic. This runs twice per transformer
146
+ block (pre-attention and pre-MLP norm) on every stage of every step.""",
147
+
148
+ correctness_md="""**All three** returned values must match the reference within **relative error
149
+ `1e-4`** at every graded shape, including the timed ones; the grader scores the **worst** of the three.
150
+
151
+ `h` is a bf16 rounding of an fp32 add and carries no freedom at all, so a correct kernel reproduces it bit
152
+ for bit. `partial` is an fp32 reduction over `Hs` elements — the accumulation order is yours. `y` inherits
153
+ the tiny variation in `partial` through an `rsqrt`, plus its own bf16 rounding.
154
+
155
+ The gate is **measured**, and everything this task exists to test is orders of magnitude outside it:
156
+ normalising each shard against its own partial instead of the combined total scores **0.52**, dividing by
157
+ `Hs` instead of `H` scores **0.65**, dropping the residual add scores **1.05**, applying the gain with a
158
+ global channel index instead of a per-shard one scores **0.14**, and accumulating `partial` in bf16 scores
159
+ **1.4e-3** — the closest of them, and still 14x outside.""",
160
+
161
+ perf_md="""Eight bytes per element and about four flops — a bandwidth kernel, and your score is
162
+ achieved bandwidth against one read of `x` and `res` and one write of `h` and `y`.
163
+
164
+ The reference is ~3x off it: `x.float() + res.float()` writes a full fp32 `h` to HBM, `(h*h).sum(-1)` reads
165
+ it back, and the final line reads it a third time and writes an fp32 `y` before the cast.
166
+
167
+ The structural problem is that `y` needs `total[s]`, which needs **every shard** of token `s`, and those
168
+ shards are `S*Hs` elements apart in memory. Two shapes of solution:
169
+
170
+ 1. **Two passes, `h` cached.** Pass one computes `h` (writing the bf16 output you owe anyway) and the
171
+ partials; pass two re-reads `h` — which is bf16, not fp32 — and writes `y`. That is 2+2 read and 2+2
172
+ write, exactly the counted traffic, and the second pass reads back what is likely still in L2 for the
173
+ smaller shapes.
174
+ 2. **One pass, token-resident.** Assign a whole token — all `W*Hs = H` channels, spread across `W` blocks
175
+ of the buffer — to one program. `H` is 10240–12288, i.e. 20–24 KB of bf16, which fits in shared memory
176
+ or even registers on a large block. Then the reduction is entirely local, no second read of `h` is
177
+ needed, and the traffic is exactly the floor. The catch is the strided access: the `W` pieces of a
178
+ token are `S*Hs` apart, so each is its own coalesced run and you want them all in flight at once.
179
+
180
+ Either way:
181
+
182
+ - **Accumulate in fp32**, reduce within the warp with shuffles, and keep the per-shard partials separate —
183
+ you need all `W` of them as an output, not just their sum.
184
+ - **Compute `rsqrt` once per token**, in fp32, and broadcast it.
185
+ - **`g` is tiny and fully reused** (`W*Hs` values for `S` tokens) — hold it in shared memory.
186
+ - **Ragged `Hs`.** The correctness shapes go down to `Hs = 33`; guard the tail off the main path.""",
187
+
188
+ precision_md="""Activations and the gain are **bfloat16**; the residual add, the sum of squares, the
189
+ `rsqrt` and the scaling are all **fp32**. `partial` is returned in fp32 because that is what goes on the
190
+ wire — a bf16 all-reduce of a sum of squares is not accurate enough, and the measured cost of accumulating
191
+ it in bf16 is **1.4e-3**, 14x the gate.
192
+
193
+ `h` is the bf16 rounding of the fp32 sum `x + res`; `partial` is computed from the **fp32** value, before
194
+ that rounding. Do not compute the partial from the rounded `h` — it is a different number, and the
195
+ reference's is the specification.
196
+
197
+ Use a proper `rsqrt` (`rsqrt.rn` or torch's `torch.rsqrt`); a fast approximate reciprocal square root has
198
+ ~1e-3 of relative error on its own and would eat the entire budget.
199
+
200
+ **fp8 is not useful here** and is not expected: the dtypes are fixed by the contract.
201
+
202
+ **Where the tolerance comes from (measured, not guessed).** An independent implementation — the sum of
203
+ squares taken as a chunked two-stage tree instead of a single `sum(-1)`, the normalisation folded into the
204
+ gain as one fp32 multiplier per (shard, token) rather than two separate multiplies, and `y` produced with
205
+ `torch.addcmul` — differs from the reference by **`E = 1.4e-5`** at a full graded shape and `0.0` at every
206
+ correctness shape. Essentially all of that is the bf16 rounding of `y` moving by one code when the two
207
+ multiplies are reassociated; `partial` agreed to 5.3e-8 and `h` bit for bit. The gate is set at **`1e-4`**,
208
+ 7x the measured floor — enough room for any sensible fp32 reduction tree and multiply ordering, and still
209
+ 14x below the cost of accumulating `partial` in bf16.
210
+
211
+ Drop-the-feature measurements at a graded shape: per-shard normaliser instead of the combined total
212
+ **D = 0.52**; dividing by `Hs` instead of `H` **D = 0.65**; no residual add **D = 1.05**; the gain applied
213
+ with a global channel index **D = 0.14**; `partial` accumulated in bf16 **D = 1.4e-3**.""",
214
+ ).validate()
tools/factory/specs/sliding_window_sink_attn.py CHANGED
@@ -80,10 +80,8 @@ def canonical_work(B, T, H, D, W):
80
  compare="tensor",
81
  tol=5e-3,
82
  shape_names=("B", "T", "H", "D", "W"),
83
- grader_shapes=[(1, 8192, 16, 128, 1024), (2, 8192, 8, 128, 2048), (1, 16384, 8, 128, 1024),
84
- (1, 8192, 16, 64, 2048), (2, 4096, 16, 128, 512)],
85
- measure_shapes=[(1, 6144, 16, 128, 1024), (2, 6144, 8, 128, 1536), (1, 12288, 8, 128, 2048),
86
- (1, 4096, 16, 128, 512), (2, 8192, 8, 64, 1024)],
87
  measure_quick_shapes=[(1, 2048, 8, 128, 512), (2, 1024, 8, 128, 256), (1, 2048, 16, 64, 1024)],
88
  correct_shapes=[(1, 256, 4, 64, 64), (2, 512, 8, 128, 128), (1, 512, 4, 128, 1024), (2, 128, 4, 64, 33)],
89
 
@@ -140,7 +138,7 @@ All tensors are CUDA and contiguous. No GQA (`q`, `k`, `v` share the same `H`),
140
  no RoPE, no dropout, no additional bias, no ALiBi. Treat all inputs as read-only.""",
141
 
142
  regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in 1–2,
143
- `T` in 4096–16384, `H` in 8–16, `D` in {64, 128}, `W` in 512–2048 — and `W` is always much smaller than `T`,
144
  which is the whole point of the pattern. Write a **general** kernel: it must handle both head dimensions and
145
  an arbitrary integer `W`, including `W >= T`.
146
 
 
80
  compare="tensor",
81
  tol=5e-3,
82
  shape_names=("B", "T", "H", "D", "W"),
83
+ grader_shapes=[(1, 16384, 16, 128, 1024), (2, 16384, 8, 128, 2048), (1, 32768, 8, 128, 1024), (1, 16384, 16, 64, 2048), (2, 8192, 16, 128, 512)],
84
+ measure_shapes=[(1, 12288, 16, 128, 1024), (2, 12288, 8, 128, 1536), (1, 24576, 8, 128, 2048), (1, 8192, 16, 128, 512), (2, 16384, 8, 64, 1024)],
 
 
85
  measure_quick_shapes=[(1, 2048, 8, 128, 512), (2, 1024, 8, 128, 256), (1, 2048, 16, 64, 1024)],
86
  correct_shapes=[(1, 256, 4, 64, 64), (2, 512, 8, 128, 128), (1, 512, 4, 128, 1024), (2, 128, 4, 64, 33)],
87
 
 
138
  no RoPE, no dropout, no additional bias, no ALiBi. Treat all inputs as read-only.""",
139
 
140
  regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in 1–2,
141
+ `T` in 8192–32768, `H` in 8–16, `D` in {64, 128}, `W` in 512–2048 — and `W` is always much smaller than `T`,
142
  which is the whole point of the pattern. Write a **general** kernel: it must handle both head dimensions and
143
  an arbitrary integer `W`, including `W >= T`.
144
 
tools/factory/specs/sparse24_backward_densify.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sparse24-backward-densify` — the backward of a 2:4-sparse linear: densify the 2-bit mask to
2
+ apply SR-STE's decay to the pruned weights, and compress the incoming gradient onto the kept positions."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="sparse24-backward-densify",
11
+ title="Write a fast 2:4 sparse-training backward kernel (SR-STE decay + gradient compression)",
12
+ blurb=("Training with 2:4 sparsity keeps a DENSE master weight and re-prunes it every step, so the "
13
+ "backward has to do two opposite things at once. The straight-through estimator passes the "
14
+ "gradient to the dense weight, plus SR-STE's decay term that pushes the currently-pruned entries "
15
+ "toward zero — which needs the 2-bit metadata densified back into a full mask. And the sparse "
16
+ "optimiser state lives in the compressed layout, so the same gradient has to be gathered onto "
17
+ "the kept positions. One pass over three full-size tensors, both directions of the format."),
18
+ keywords=["mle", "kernel-generation", "sparsity", "2:4", "structured-sparsity", "sr-ste", "backward",
19
+ "straight-through", "sparse-training", "training", "memory-bound"],
20
+ module="srste_bwd.py",
21
+ func="srste_backward",
22
+ signature="srste_backward(w, dy, meta, lam)",
23
+ returns_doc="""Backward of a 2:4-sparse linear under SR-STE.
24
+
25
+ Args:
26
+ w: (M, K) bfloat16 — the DENSE master weight.
27
+ dy: (M, K) bfloat16 — the gradient with respect to the pruned (sparse) weight.
28
+ meta: (M, K//8) uint8 — the current 2:4 mask, 2 bits per kept entry, two groups per byte.
29
+ lam: () float32 — 0-dim tensor, the SR-STE decay coefficient.
30
+
31
+ Returns:
32
+ (dw, dvals) where
33
+ dw: (M, K) bfloat16 — dy + lam * w on the PRUNED positions, dy alone on the kept ones
34
+ dvals: (M, K//2) bfloat16 — dy at the KEPT positions, compressed, ascending column order""",
35
+
36
+ reference_imports="import torch",
37
+ reference_src='''
38
+ def _decode(meta, M, K):
39
+ """meta -> (M, K//4, 2) int64 slot indices of the two kept entries per group."""
40
+ mi = meta.int()
41
+ q = torch.stack([mi & 3, (mi >> 2) & 3, (mi >> 4) & 3, (mi >> 6) & 3], dim=-1) # (M, K//8, 4)
42
+ return q.reshape(M, K // 4, 2).long()
43
+
44
+
45
+ def srste_backward(w, dy, meta, lam):
46
+ """Densify the mask, apply the SR-STE decay, and gather the gradient onto the kept positions.
47
+
48
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. It materialises a
49
+ full-size boolean mask and several full-size fp32 temporaries.
50
+ """
51
+ M, K = w.shape
52
+ idx = _decode(meta, M, K)
53
+ keep = torch.zeros(M, K // 4, 4, device=w.device, dtype=torch.bool).scatter_(-1, idx, True)
54
+ pruned_w = torch.where(keep.view(M, K), torch.zeros_like(w), w) # only the dropped entries
55
+ dw = (dy.float() + lam * pruned_w.float()).bfloat16() # SR-STE
56
+ dvals = torch.gather(dy.view(M, K // 4, 4), -1, idx).view(M, K // 2) # compressed gradient
57
+ return dw, dvals
58
+ ''',
59
+ make_inputs_src='''
60
+ _LO = [0, 0, 0, 1, 1, 2] # the six ways to choose 2 of 4
61
+ _HI = [1, 2, 3, 2, 3, 3]
62
+
63
+
64
+ def _mk(M, K, seed):
65
+ """A dense master weight, its incoming gradient, and the 2:4 mask from the last re-prune."""
66
+ gen = torch.Generator(device="cuda").manual_seed(seed)
67
+ w = (torch.randn(M, K, device="cuda", dtype=torch.float32, generator=gen) * 0.02).bfloat16()
68
+ dy = (torch.randn(M, K, device="cuda", dtype=torch.float32, generator=gen) * 2e-4).bfloat16()
69
+ pat = torch.randint(0, 6, (M, K // 4), device="cuda", dtype=torch.int64, generator=gen)
70
+ lo = torch.tensor(_LO, device="cuda", dtype=torch.int32)[pat]
71
+ hi = torch.tensor(_HI, device="cuda", dtype=torch.int32)[pat]
72
+ nib = (lo | (hi << 2)).view(M, K // 8, 2)
73
+ meta = (nib[..., 0] | (nib[..., 1] << 4)).to(torch.uint8)
74
+ # SR-STE's decay is chosen so the decay term is comparable to the gradient itself -- if it were
75
+ # negligible the task would not be measuring it, and if it dominated nothing else would be.
76
+ lam = torch.tensor(1e-2, device="cuda", dtype=torch.float32)
77
+ return w, dy, meta, lam
78
+ ''',
79
+ flops_src='''
80
+ def canonical_work(M, K):
81
+ """BYTES attributed to one backward, from the SHAPE ALONE.
82
+
83
+ Read w (2*M*K), dy (2*M*K) and the metadata (M*K/8); write dw (2*M*K) and the compressed gradient
84
+ (2*M*K/2 = M*K). The decay coefficient is a scalar. Bandwidth-bound: the score is achieved bandwidth
85
+ against that fixed count.
86
+ """
87
+ return 2 * M * K + 2 * M * K + M * K // 8 + 2 * M * K + M * K
88
+ ''',
89
+ flops_formula="canonical_work(M, K) = 2*M*K + 2*M*K + M*K/8 + 2*M*K + M*K = 7.125 * M*K bytes",
90
+
91
+ metric="GB/s",
92
+ compare="tuple",
93
+ tuple_names=("dw", "dvals"),
94
+ tol=1e-4,
95
+ shape_names=("M", "K"),
96
+ grader_shapes=[(24576, 12288), (16384, 20480), (32768, 10240), (12288, 24576), (28672, 11264)],
97
+ measure_shapes=[(20480, 12288), (14336, 20480), (28672, 10240), (10240, 24576), (24576, 11264)],
98
+ measure_quick_shapes=[(4096, 4096), (2048, 8192), (8192, 2048)],
99
+ correct_shapes=[(64, 128), (129, 64), (17, 256), (256, 24), (33, 8)],
100
+
101
+ spec_md="""A 2:4-sparse linear keeps a **dense** master weight `w` and a mask that says which two of
102
+ every four entries the forward pass actually used. `meta` is that mask in the compressed form: byte `t` of
103
+ row `m` describes groups `2t` and `2t+1`,
104
+
105
+ ```
106
+ i0(2t) = (meta[m,t] >> 0) & 3 i1(2t) = (meta[m,t] >> 2) & 3
107
+ i0(2t+1) = (meta[m,t] >> 4) & 3 i1(2t+1) = (meta[m,t] >> 6) & 3
108
+ keep[m, 4g + i0(g)] = keep[m, 4g + i1(g)] = true , the other two slots false
109
+ ```
110
+
111
+ Two outputs come out of the same pass.
112
+
113
+ **`dw` — the SR-STE gradient for the dense weight.** The straight-through estimator sends `dy` to every
114
+ entry of `w`; SR-STE (sparse-refined STE, the standard 2:4 training recipe) adds a decay on the entries the
115
+ mask currently drops, so they keep shrinking and the mask can stabilise:
116
+
117
+ ```
118
+ dw[m, k] = dy[m, k] if keep[m, k]
119
+ dw[m, k] = dy[m, k] + lam * w[m, k] otherwise
120
+ ```
121
+
122
+ computed in fp32 and rounded **once** to bf16. Note which side gets the decay: the **pruned** entries, not
123
+ the kept ones. Applying it to the kept entries instead is the classic sign error and it is what the gate is
124
+ watching for.
125
+
126
+ **`dvals` — the gradient in the compressed layout.** The sparse optimiser state is stored the same way the
127
+ weight is, so the gradient has to be gathered onto the kept positions, in ascending column order:
128
+
129
+ ```
130
+ dvals[m, 2g] = dy[m, 4g + i0(g)]
131
+ dvals[m, 2g + 1] = dy[m, 4g + i1(g)]
132
+ ```
133
+
134
+ That is a bit-exact gather — no arithmetic.
135
+
136
+ So the kernel densifies the metadata into a mask (for `dw`) and uses it as a gather map (for `dvals`), in
137
+ one pass, without ever writing a mask to memory. `K` is a multiple of 8.
138
+
139
+ `/app/reference.py` scatters a full-size boolean mask, builds an fp32 copy of the pruned weight and gathers
140
+ with `torch.gather`. That is the exact specification; it is deliberately simple rather than fast.""",
141
+
142
+ contract_md="""| arg | shape | dtype | meaning |
143
+ |-----|-------|-------|---------|
144
+ | `w` | `(M, K)` | `bfloat16` | the dense master weight |
145
+ | `dy` | `(M, K)` | `bfloat16` | gradient w.r.t. the pruned weight |
146
+ | `meta` | `(M, K//8)` | `uint8` | the current 2:4 mask, 2 bits per kept entry |
147
+ | `lam` | `()` | `float32` | 0-dim tensor, the SR-STE decay coefficient |
148
+
149
+ **Return** a 2-tuple `(dw, dvals)` **in that order**:
150
+
151
+ | out | shape | dtype | notes |
152
+ |-----|-------|-------|-------|
153
+ | `dw` | `(M, K)` | `bfloat16` | fp32 arithmetic, one rounding to bf16 |
154
+ | `dvals` | `(M, K//2)` | `bfloat16` | bit-exact gather of `dy` at the kept positions |
155
+
156
+ `lam` is a **0-dim tensor**, not a python float — multiply by it directly. `K` is a multiple of 8 and
157
+ nothing more (the correctness shapes include `K = 24` and `K = 8`); `M` is not a multiple of any tile size.
158
+ All inputs are read-only; the call is functional.""",
159
+
160
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `M`
161
+ 12288–32768, `K` 10240–24576, with `M*K` around **300 M elements** — one large projection of a
162
+ frontier-scale model under 2:4 sparse fine-tuning, about 2.1 GB of traffic per weight per step. This runs
163
+ for every weight in the backward of every step, alongside the re-prune, so it is a fixed tax on sparse
164
+ training.""",
165
+
166
+ correctness_md="""**Both** returned values must match the reference within **relative error `1e-4`** at
167
+ every graded shape, including the timed ones; the grader scores the **worse** of the two.
168
+
169
+ `dvals` carries no arithmetic — it is a bf16 gather — so a correct kernel reproduces it **bit for bit**.
170
+ The whole budget exists for `dw`, whose only freedom is whether `dy + lam*w` is evaluated as an FMA or as a
171
+ separate multiply and add; that moves a handful of values across a bf16 rounding boundary and nothing more.
172
+
173
+ The gate is **measured**, and the mistakes this task exists to catch are nearly four orders of magnitude
174
+ outside it: applying the decay to the KEPT entries instead of the pruned ones scores **0.82**, dropping the
175
+ decay term altogether scores **0.58**, and using the metadata's nibbles in the wrong order scores **0.58**
176
+ on `dw` while getting 83% of the `dvals` groups wrong.""",
177
+
178
+ perf_md="""Just over seven bytes per element and two flops — entirely a bandwidth problem, and your
179
+ score is achieved bandwidth against one read of `w`, `dy` and `meta` and one write of `dw` and `dvals`.
180
+
181
+ The reference is several times that: `scatter_` writes a full-size boolean mask to HBM, `torch.where`
182
+ reads it back, `.float()` materialises two full-size fp32 temporaries, and `torch.gather` makes yet another
183
+ pass with a full-size int64 index tensor.
184
+
185
+ The kernel to write handles **eight columns (two groups, one metadata byte) per lane**:
186
+
187
+ - One 128-bit load of `w` and one of `dy` give 8 bf16 values each; one byte of `meta` decodes both groups.
188
+ - Decode with a 16-entry constant table (nibble -> the two slots, or nibble -> a 4-bit keep mask) held in
189
+ registers or shared memory. The keep mask makes `dw` a branch-free select between `dy` and
190
+ `fma(lam, w, dy)`; the slot pair makes `dvals` two register selects.
191
+ - The stores are a 128-bit write to `dw` and a 64-bit write to `dvals` — both naturally aligned when a
192
+ thread owns 8 consecutive columns.
193
+ - **Never materialise the mask.** It exists only in registers.
194
+ - `meta` is 1/16th of the traffic of `w`; read it once and keep it.
195
+ - **Ragged tails.** `M` is arbitrary and `K` can be 8; guard the tail off the main path.
196
+
197
+ The read:write ratio is 4:3, so both directions have to stay saturated — this is a kernel where a
198
+ non-temporal store on `dw` (which nothing re-reads) is worth trying.""",
199
+
200
+ precision_md="""Everything is **bfloat16** except `lam`, which is a **0-dim fp32 tensor**. Do the
201
+ `dy + lam * w` arithmetic in **fp32** and round once to bf16; do not add in bf16.
202
+
203
+ `dvals` involves no arithmetic at all and must be a bit-exact gather of `dy`.
204
+
205
+ `lam` is a tensor rather than a python float on purpose: `tensor * python_float` goes through a
206
+ reciprocal/scalar path in torch and would introduce a rounding difference that has nothing to do with this
207
+ kernel. Multiply by the 0-dim tensor.
208
+
209
+ **fp8 is not useful here** and is not expected — the dtypes are fixed by the contract.
210
+
211
+ **Where the tolerance comes from (measured, not guessed).** An independent implementation — the mask
212
+ decoded through a 16-entry nibble lookup table with no `scatter_`, `dw` computed with `torch.addcmul`
213
+ (a fused multiply-add) instead of a separate multiply and add, and `dvals` built by two `torch.where`
214
+ selects instead of `torch.gather` — differs from the reference by **`E = 7.5e-11`** at a full graded shape
215
+ and `0.0` at every correctness shape, entirely in `dw` (`dvals` matched bit for bit everywhere). The only
216
+ freedom in this kernel is whether the multiply-add is fused, and that almost never crosses a bf16 rounding
217
+ boundary. The gate is set at **`1e-4`** rather than 2x the measured floor, as a deliberate cushion: an
218
+ implementation whose fp32 intermediate differs by one ulp everywhere would flip roughly one bf16 value in
219
+ 2^15, worth about **2e-5** of relative error, and `1e-4` covers that with margin while still sitting ~6000x
220
+ below the cheapest algorithmic mistake.
221
+
222
+ Drop-the-feature measurements at a graded shape: decay applied to the kept entries instead of the pruned
223
+ ones **D = 0.82**; no decay term at all **D = 0.58**; metadata nibbles swapped **D = 0.58** on `dw` with
224
+ 83% of the `dvals` groups wrong.""",
225
+ ).validate()
tools/factory/specs/sparse24_compress_layout.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sparse24-compress-layout` — turn an already-2:4-sparse matrix into the half-size value buffer
2
+ plus the packed 2-bit index metadata that a sparse tensor core actually consumes."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="sparse24-compress-layout",
11
+ title="Write a fast 2:4 compression kernel (half-size values + packed 2-bit metadata)",
12
+ blurb=("A 2:4-pruned weight is still stored densely, half of it zeros — that saves nothing. The format "
13
+ "the sparse tensor cores take is a COMPRESSED one: a (M, K/2) buffer holding only the survivors, "
14
+ "plus two bits per survivor saying which of the four slots it came from, packed four indices to "
15
+ "a byte. Compressing is what actually halves the weight traffic of a sparse layer, it runs on "
16
+ "every weight after every re-prune, and the metadata is a bit-exact integer contract."),
17
+ keywords=["mle", "kernel-generation", "sparsity", "2:4", "structured-sparsity", "compression",
18
+ "metadata", "bit-packing", "sparse-tensor-core", "training", "memory-bound"],
19
+ module="compress24.py",
20
+ func="compress_24",
21
+ signature="compress_24(a)",
22
+ returns_doc="""Compress a 2:4-sparse matrix into the sparse-tensor-core layout.
23
+
24
+ Args:
25
+ a: (M, K) bfloat16 — already 2:4 sparse: EXACTLY two of every aligned group of four columns are
26
+ non-zero, the other two are exactly +0.0. K is a multiple of 8.
27
+
28
+ Returns:
29
+ (vals, meta) where
30
+ vals: (M, K//2) bfloat16 — the survivors only, in ascending column order
31
+ meta: (M, K//8) uint8 — 2 bits per survivor; byte t carries groups 2t and 2t+1""",
32
+
33
+ reference_imports="import torch",
34
+ reference_src='''
35
+ def compress_24(a):
36
+ """Compact the survivors and pack their indices two bits at a time.
37
+
38
+ Correct and simple — it is the SPECIFICATION, not a performance target. It materialises a full-size
39
+ boolean mask, uses it to index the survivors out, and builds the metadata with min/max reductions.
40
+ """
41
+ M, K = a.shape
42
+ g = a.view(M, K // 4, 4)
43
+ nz = g != 0
44
+ vals = g[nz].view(M, K // 2) # survivors, row-major => ascending column order
45
+
46
+ ar = torch.arange(4, device=a.device, dtype=torch.uint8).expand_as(nz)
47
+ i0 = torch.where(nz, ar, torch.full_like(ar, 9)).amin(-1).int() # first survivor's slot
48
+ i1 = torch.where(nz, ar, torch.zeros_like(ar)).amax(-1).int() # second survivor's slot
49
+ nib = (i0 | (i1 << 2)).view(M, K // 8, 2) # 4 bits per group
50
+ meta = (nib[..., 0] | (nib[..., 1] << 4)).to(torch.uint8) # two groups per byte
51
+ return vals, meta
52
+ ''',
53
+ make_inputs_src='''
54
+ LO = [0, 0, 0, 1, 1, 2] # the six ways to choose 2 of 4, as (first, second)
55
+ HI = [1, 2, 3, 2, 3, 3]
56
+
57
+
58
+ def _mk(M, K, seed):
59
+ """A weight that is already exactly 2:4 sparse: a random 2-of-4 pattern per group, random values.
60
+
61
+ The surviving values are drawn from a normal distribution; the roughly one in 2^24 samples that comes
62
+ out exactly zero is replaced, so the "exactly two non-zeros per group" invariant holds to the element.
63
+ """
64
+ gen = torch.Generator(device="cuda").manual_seed(seed)
65
+ v = (torch.randn(M, K, device="cuda", dtype=torch.float32, generator=gen) * 0.02).bfloat16()
66
+ v = torch.where(v == 0, torch.full_like(v, 0.01), v) # keep every survivor strictly non-zero
67
+ pat = torch.randint(0, 6, (M, K // 4), device="cuda", dtype=torch.int64, generator=gen)
68
+ lo = torch.tensor(LO, device="cuda", dtype=torch.uint8)[pat]
69
+ hi = torch.tensor(HI, device="cuda", dtype=torch.uint8)[pat]
70
+ ar = torch.arange(4, device="cuda", dtype=torch.uint8).view(1, 1, 4)
71
+ keep = (ar == lo.unsqueeze(-1)) | (ar == hi.unsqueeze(-1))
72
+ return (torch.where(keep.view(M, K), v, torch.zeros_like(v)),)
73
+ ''',
74
+ flops_src='''
75
+ def canonical_work(M, K):
76
+ """BYTES attributed to one compression, from the SHAPE ALONE.
77
+
78
+ Read the dense bf16 matrix once (2*M*K), write the half-size value buffer (2*M*K/2 = M*K) and the
79
+ packed metadata (M*K/8). Bandwidth-bound: the score is achieved bandwidth against that count.
80
+ """
81
+ return 2 * M * K + M * K + M * K // 8
82
+ ''',
83
+ flops_formula="canonical_work(M, K) = 2*M*K + M*K + M*K/8 = 3.125 * M*K bytes",
84
+
85
+ metric="GB/s",
86
+ compare="tuple",
87
+ tuple_names=("vals", "meta"),
88
+ tol=0.0,
89
+ shape_names=("M", "K"),
90
+ grader_shapes=[(32768, 16384), (49152, 12288), (24576, 24576), (65536, 8192), (40960, 13312)],
91
+ measure_shapes=[(28672, 16384), (40960, 12288), (20480, 24576), (57344, 8192), (36864, 13312)],
92
+ measure_quick_shapes=[(4096, 4096), (2048, 8192), (8192, 2048)],
93
+ correct_shapes=[(64, 128), (129, 64), (17, 256), (256, 24), (33, 8)],
94
+
95
+ spec_md="""`a` is already 2:4 sparse: in every aligned group of four consecutive columns
96
+ `(a0, a1, a2, a3)` exactly two entries are non-zero. Let `i0 < i1` be their slots within the group.
97
+
98
+ **Values.** The survivors are compacted in ascending column order, so group `t` of row `m` contributes two
99
+ consecutive elements:
100
+
101
+ ```
102
+ vals[m, 2t] = a[m, 4t + i0]
103
+ vals[m, 2t + 1] = a[m, 4t + i1]
104
+ ```
105
+
106
+ **Metadata.** Each survivor's slot is two bits, so a group is four bits and a byte carries **two groups**.
107
+ Byte `t` of row `m` covers groups `2t` (low nibble) and `2t+1` (high nibble):
108
+
109
+ ```
110
+ meta[m, t] = ( i0(2t) << 0 ) | ( i1(2t) << 2 )
111
+ | ( i0(2t+1) << 4 ) | ( i1(2t+1) << 6 )
112
+ ```
113
+
114
+ so bits 0–1 are the first survivor of the even group, bits 2–3 the second survivor of the even group, bits
115
+ 4–5 the first survivor of the odd group, bits 6–7 the second. Lower group in the **low** nibble, lower slot
116
+ in the **lower** bits of its nibble. That is the ordering the sparse MMA metadata operand expects, and it is
117
+ the whole content of the task — get either ordering backwards and every byte is wrong.
118
+
119
+ `K` is a multiple of 8, so the byte packing never has a partial group.
120
+
121
+ The values are copied through **unchanged**; there is no arithmetic anywhere in this kernel.
122
+
123
+ `/app/reference.py` materialises a full-size boolean mask, indexes the survivors out with it, and derives
124
+ the slots with min/max reductions. That is the exact specification; it is deliberately simple rather than
125
+ fast.""",
126
+
127
+ contract_md="""| arg | shape | dtype | meaning |
128
+ |-----|-------|-------|---------|
129
+ | `a` | `(M, K)` | `bfloat16` | already 2:4 sparse; the two dropped entries per group are exactly `+0.0` |
130
+
131
+ **Return** a 2-tuple `(vals, meta)` **in that order**:
132
+
133
+ | out | shape | dtype | notes |
134
+ |-----|-------|-------|-------|
135
+ | `vals` | `(M, K//2)` | `bfloat16` | survivors in ascending column order, copied bit-exactly |
136
+ | `meta` | `(M, K//8)` | `uint8` | 2 bits per survivor, two groups per byte, as defined above |
137
+
138
+ You may rely on the input invariant: **exactly two non-zeros per aligned group of four**, never one, never
139
+ three. `K` is a multiple of 8 and nothing more — the correctness shapes include `K = 24` and `K = 8` — and
140
+ `M` is not a multiple of any tile size (`M = 129`, `M = 33`). `a` is read-only; the call is functional.""",
141
+
142
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `M`
143
+ 24576–65536, `K` 8192–24576, with `M*K` around **550 M elements** — one very large 2:4-pruned projection of
144
+ a frontier-scale model, 1.1 GB of dense bf16 in and 0.6 GB of compressed weight out. This is the step that
145
+ makes the sparsity pay: everything downstream reads the half-size buffer instead of the dense one.""",
146
+
147
+ correctness_md="""**Both** returned values must match the reference **exactly** at every graded shape,
148
+ including the timed ones. `vals` is a bf16 gather, so its tolerance is **`0.0`** — bit-identical — and
149
+ `meta` is `uint8` and compared elementwise.
150
+
151
+ The metadata is an integer the hardware indexes with, so it is either exactly right or it is wrong, and
152
+ every plausible layout mistake changes it everywhere: swapping the two nibbles (odd group in the low
153
+ nibble) mismatches **83%** of the bytes, swapping the two slots within a nibble (`i1` in the low bits)
154
+ mismatches **100%**, and emitting the values without compacting them — i.e. leaving the dense stride —
155
+ scores **1.22** on `vals`.""",
156
+
157
+ perf_md="""Three and an eighth bytes per element, and no arithmetic — pure bandwidth, and your score is
158
+ achieved bandwidth against one read of `a` and one write of `vals` plus `meta`.
159
+
160
+ The reference is far off it: `g != 0` writes a full-size boolean mask to HBM, `g[nz]` is a general boolean
161
+ gather that must first count the mask, and the two `torch.where` + reduction pairs are three more full-size
162
+ passes.
163
+
164
+ The kernel to write processes **eight input columns (two groups) per lane**:
165
+
166
+ - A 128-bit load gives you 8 bf16 values = two complete groups. The survivors of those two groups are 4
167
+ bf16 values = one 64-bit store into `vals`, and their four 2-bit slots are exactly **one byte** of
168
+ `meta` — so the natural unit of work emits one aligned 8-byte value store and one byte of metadata.
169
+ - Detecting a non-zero bf16 is an integer test on the 16-bit pattern, not a float compare.
170
+ - The compaction within a group is a 2-element select: with `nz = (nz0, nz1, nz2, nz3)`, the first survivor
171
+ is a 3-deep select chain and the second is the last set bit. A branch-free formulation using the 4-bit
172
+ mask as an index into a tiny constant table (16 entries, 2 slots each) removes the chain entirely, and
173
+ the same table gives you the nibble directly.
174
+ - Have each thread cover several groups so the `meta` stores coalesce into 32- or 128-bit words rather than
175
+ single bytes — byte-wide scattered stores are what usually costs this kernel its bandwidth.
176
+ - **Ragged tails.** `M` is arbitrary and `K` can be as small as 8; guard the tail without putting a branch
177
+ on the main path.""",
178
+
179
+ precision_md="""There is **no arithmetic in this task at all**. `vals` is a bit-exact gather of bf16
180
+ values and `meta` is a bit-packing of integers, so a correct kernel is bit-identical to the reference and
181
+ the tolerance on `vals` is **`0.0`**.
182
+
183
+ Do not convert through fp32 and do not compare values as floats to find the survivors — test the 16-bit
184
+ pattern. (Testing `x != 0` as a float is also correct here, because the dropped entries are exactly `+0.0`
185
+ and no survivor is zero, but the integer test is free.)
186
+
187
+ `meta` is `uint8` and compared **exactly**; integer outputs are never compared through `float()`, so a
188
+ single wrong nibble is caught.
189
+
190
+ **Where the tolerance comes from (measured, not guessed).** An independent implementation — the survivors
191
+ selected with an explicit branch-free 2-element compaction driven by the 4-bit non-zero mask and a 16-entry
192
+ lookup table, and the metadata assembled by shifting that table's nibble into place, with no boolean-mask
193
+ indexing anywhere — reproduces the reference **bit for bit**, `E = 0.0`, for both outputs at every
194
+ correctness shape and at a full graded shape. `tol = 0.0` is the floor.
195
+
196
+ For calibration: swapping just **two** of the 268 M elements of `vals` at a graded shape already registers a
197
+ relative error of **9.7e-5**, so a single misplaced survivor is caught, never mind a systematic one.
198
+
199
+ Drop-the-feature measurements at a graded shape: nibble order swapped **83%** of `meta` bytes wrong; slot
200
+ order swapped inside each nibble **100%** wrong; values written at the dense stride instead of compacted
201
+ **D = 1.22** on `vals`.""",
202
+ ).validate()
tools/factory/specs/sparse24_prune_metadata.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sparse24-prune-metadata` — magnitude-prune a weight matrix to the 2:4 pattern the sparse
2
+ tensor cores consume, and emit the per-group index metadata."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="sparse24-prune-metadata",
11
+ title="Write a fast 2:4 structured pruning kernel (mask + index metadata)",
12
+ blurb=("Sparse tensor cores only accept one pattern: exactly two non-zeros in every aligned group of "
13
+ "four along K. Getting a trained weight into that form means, for every group of four, ranking "
14
+ "the magnitudes, keeping the top two, zeroing the rest, and recording WHICH two — the 2-bit "
15
+ "indices the hardware needs to pick the matching operands out of B. It is run on every weight "
16
+ "of the model at every re-prune during sparse fine-tuning, it is pure bandwidth, and the "
17
+ "metadata is integer, so it is either exactly right or it is wrong."),
18
+ keywords=["mle", "kernel-generation", "sparsity", "2:4", "structured-sparsity", "pruning", "metadata",
19
+ "sparse-tensor-core", "training", "memory-bound"],
20
+ module="prune24.py",
21
+ func="prune_24",
22
+ signature="prune_24(w)",
23
+ returns_doc="""Magnitude-prune a weight matrix to the 2:4 structured pattern.
24
+
25
+ Args:
26
+ w: (M, K) bfloat16 — the dense weight. K is a multiple of 4.
27
+
28
+ Returns:
29
+ (pruned, meta) where
30
+ pruned: (M, K) bfloat16 — w with the two smaller-magnitude entries of every aligned group
31
+ of four set to exactly 0, the other two untouched
32
+ meta: (M, K//4, 2) uint8 — the two KEPT indices (0..3) of each group, in ASCENDING order""",
33
+
34
+ reference_imports="import torch",
35
+ reference_src='''
36
+ def prune_24(w):
37
+ """Rank each group of four by magnitude with a stable sort and keep the top two.
38
+
39
+ Correct and simple — it is the SPECIFICATION, not a performance target. `stable=True` is what defines
40
+ the tie-break: among equal magnitudes the LOWER index wins.
41
+ """
42
+ M, K = w.shape
43
+ g = w.view(M, K // 4, 4)
44
+ s = g.abs().float()
45
+ order = torch.argsort(s, dim=-1, descending=True, stable=True) # ties keep original order
46
+ idx = order[..., :2].sort(dim=-1).values # the two kept indices, ascending
47
+ mask = torch.zeros_like(g, dtype=torch.bool).scatter_(-1, idx, True)
48
+ pruned = torch.where(mask, g, torch.zeros_like(g)).view(M, K)
49
+ return pruned, idx.to(torch.uint8)
50
+ ''',
51
+ make_inputs_src='''
52
+ def _mk(M, K, seed):
53
+ """A trained-looking bf16 weight matrix.
54
+
55
+ Values are bf16, which has only 8 mantissa bits, so about 1.1% of the groups of four contain two
56
+ entries with EXACTLY equal magnitude, and in 0.41% of groups that tie straddles the keep/drop boundary.
57
+ Those ties are why the tie-break is part of the spec rather than an afterthought.
58
+ """
59
+ gen = torch.Generator(device="cuda").manual_seed(seed)
60
+ return ((torch.randn(M, K, device="cuda", dtype=torch.float32, generator=gen) * 0.02).bfloat16(),)
61
+ ''',
62
+ flops_src='''
63
+ def canonical_work(M, K):
64
+ """BYTES attributed to one prune, from the SHAPE ALONE.
65
+
66
+ Read the dense bf16 weight once (2*M*K), write the pruned bf16 weight once (2*M*K) and the two index
67
+ bytes per group of four (2*M*K/4). Bandwidth-bound: the score is achieved bandwidth against that count.
68
+ """
69
+ return 2 * M * K + 2 * M * K + 2 * (M * K // 4)
70
+ ''',
71
+ flops_formula="canonical_work(M, K) = 2*M*K + 2*M*K + M*K/2 = 4.5 * M*K bytes",
72
+
73
+ metric="GB/s",
74
+ compare="tuple",
75
+ tuple_names=("pruned", "meta"),
76
+ tol=0.0,
77
+ shape_names=("M", "K"),
78
+ grader_shapes=[(32768, 12288), (24576, 16384), (49152, 8192), (16384, 24576), (40960, 10240)],
79
+ measure_shapes=[(28672, 12288), (20480, 16384), (40960, 8192), (14336, 24576), (36864, 10240)],
80
+ measure_quick_shapes=[(4096, 4096), (2048, 8192), (8192, 2048)],
81
+ correct_shapes=[(64, 128), (129, 64), (17, 256), (256, 12), (33, 4)],
82
+
83
+ spec_md="""Split every row of `w` into aligned groups of four consecutive columns. Within a group
84
+ `(w0, w1, w2, w3)`, index `i` is **kept** exactly when
85
+
86
+ ```
87
+ #{ j : |w_j| > |w_i| or ( |w_j| == |w_i| and j < i ) } < 2
88
+ ```
89
+
90
+ i.e. rank the four by descending magnitude, breaking ties toward the **lower** index, and keep the top two.
91
+ That is precisely what a stable descending sort gives you, and it is not an academic detail: `w` is
92
+ bfloat16, so about **1.1% of the groups contain two entries of exactly equal magnitude** and a kernel that
93
+ breaks those ties the other way disagrees with the reference on hundreds of thousands of groups.
94
+
95
+ The outputs are
96
+
97
+ ```
98
+ pruned[m, 4t + i] = w[m, 4t + i] if i is kept, else exactly 0.0
99
+ meta[m, t, 0] = the smaller of the two kept indices
100
+ meta[m, t, 1] = the larger of the two kept indices
101
+ ```
102
+
103
+ `meta` is what the sparse tensor core uses to select the matching four-of-eight operands from the dense
104
+ side, so it is **integer and compared exactly** — one wrong group is a failure, not a rounding error. The
105
+ two indices are always in ascending order, and there are always exactly two of them: no group is ever
106
+ all-zero in the output, even if some of its entries were already zero in `w`.
107
+
108
+ The kept values are copied through **unchanged**. There is no rescaling of the survivors.
109
+
110
+ `/app/reference.py` builds a `(M, K/4, 4)` view, does a full stable `argsort` over the last axis and
111
+ scatters a boolean mask. That is the exact specification; it is deliberately simple rather than fast.""",
112
+
113
+ contract_md="""| arg | shape | dtype | meaning |
114
+ |-----|-------|-------|---------|
115
+ | `w` | `(M, K)` | `bfloat16` | the dense weight, row-major; `K` is a multiple of 4 |
116
+
117
+ **Return** a 2-tuple `(pruned, meta)` **in that order**:
118
+
119
+ | out | shape | dtype | notes |
120
+ |-----|-------|-------|-------|
121
+ | `pruned` | `(M, K)` | `bfloat16` | survivors copied bit-exactly, the other two per group exactly `0.0` |
122
+ | `meta` | `(M, K//4, 2)` | `uint8` | the two kept indices per group, **ascending**, values in `0..3` |
123
+
124
+ `K` is a multiple of 4 and nothing more — the correctness shapes include `K = 12` and `K = 4` — and `M` is
125
+ not a multiple of any tile size (`M = 129`, `M = 33`). `w` is read-only; the call is functional.""",
126
+
127
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `M`
128
+ 16384–49152, `K` 8192–24576, with `M*K` around **400 M elements** — one very large projection matrix of a
129
+ frontier-scale model (or a stack of smaller ones viewed as one matrix), 0.8 GB of bf16 weight in and 1.0 GB
130
+ out. Sparse fine-tuning re-prunes on a schedule, so this runs over every weight in the model repeatedly,
131
+ and at these sizes it is entirely a memory-bandwidth problem.""",
132
+
133
+ correctness_md="""**Both** returned values must match the reference **exactly** at every graded shape,
134
+ including the timed ones. `pruned` is a bf16 copy-or-zero, so its tolerance is **`0.0`** — bit-identical —
135
+ and `meta` is `uint8` and compared elementwise.
136
+
137
+ This is the strictest kind of gate in the suite and it is deliberate: the metadata is an integer the
138
+ hardware indexes with, so "close" is meaningless. The two shortcuts both fail enormously: keeping the first
139
+ two entries of every group instead of the largest two scores **0.76** on `pruned` and mismatches **83%** of
140
+ the metadata groups, and ranking by signed value instead of magnitude scores **0.76** and mismatches
141
+ **75%**. Breaking magnitude ties toward the *higher* index instead of the lower one mismatches **0.41%** of
142
+ the groups — a small fraction, but 410 thousand groups at a graded shape, and it fails just as hard.""",
143
+
144
+ perf_md="""Four and a half bytes per element and about ten comparisons — entirely a bandwidth problem,
145
+ and your score is achieved bandwidth against one read of `w`, one write of `pruned` and one write of `meta`.
146
+
147
+ The reference is roughly 5x off that: `argsort` over a length-4 axis launches a general sorting kernel,
148
+ `scatter_` materialises a full-size boolean mask in HBM, and `torch.where` reads it back.
149
+
150
+ A group of four fits in a register pair. The whole task per group is:
151
+
152
+ - Load 4 bf16 values as one 64-bit word (`K` is a multiple of 4, so the groups are naturally aligned; with
153
+ a 128-bit load you get two groups at once).
154
+ - Take absolute values by masking the sign bit — no conversion needed, `|bf16|` ordering is the same as the
155
+ integer ordering of the sign-cleared bit pattern, so the whole ranking can be done on `uint16` keys.
156
+ - Compute the rank of each of the four with the 6 pairwise comparisons the spec defines (or a 5-comparison
157
+ sorting network), including the index tie-break. Branch-free: the tie-break is just `(a == b) & (j < i)`.
158
+ - Emit the two survivors and the two index bytes.
159
+
160
+ Things that matter:
161
+
162
+ - **Do not materialise a mask.** The output value is `select(keep, w, 0)` in registers.
163
+ - **Vectorise the stores.** `pruned` is fully coalesced; `meta` is 2 bytes per group, so a thread handling
164
+ 8 groups writes a clean 16-byte store.
165
+ - **The tie-break costs nothing** if you fold it into the comparison as a lexicographic `(|w|, -i)` key —
166
+ for bf16 you can pack the sign-cleared 16-bit magnitude and the 2-bit index into a single 18-bit integer
167
+ and compare those. Do not implement it as a branch.
168
+ - **Ragged M and small K.** The correctness shapes go down to `K = 4`, so guard the tail rather than
169
+ assuming a 128-column tile.""",
170
+
171
+ precision_md="""There is **no arithmetic in this task** beyond taking absolute values and comparing
172
+ them. Survivors are copied unchanged, the losers become exactly `0.0`, so a correct kernel is bit-identical
173
+ to the reference and the tolerance on `pruned` is **`0.0`**.
174
+
175
+ Compare in a way that is exact. `|bf16|` can be obtained by clearing the sign bit of the 16-bit pattern, and
176
+ for finite non-negative floats the IEEE ordering agrees with the unsigned integer ordering of that pattern —
177
+ so the whole ranking can be integer. Converting to fp32 first is also exact and costs nothing. What is
178
+ **not** safe is comparing in a lower precision or using an approximate absolute value: that would flip
179
+ groups whose magnitudes are close but not equal.
180
+
181
+ `meta` is `uint8` and compared **exactly**; integer outputs are never compared through `float()`.
182
+
183
+ **Where the tolerance comes from (measured, not guessed).** An independent implementation — the rank rule
184
+ evaluated directly as the 16 pairwise comparisons of the spec (`|w_j| > |w_i|` or `|w_j| == |w_i|` and
185
+ `j < i`), with no sort anywhere, operating on sign-cleared `uint16` keys — reproduces the reference **bit
186
+ for bit**, `E = 0.0`, for both outputs at every correctness shape and at a full graded shape. That also
187
+ confirms `stable=True` in the reference implements exactly the stated tie-break. `tol = 0.0` is the floor.
188
+
189
+ Drop-the-feature measurements at a graded shape: keeping the first two of each group **D = 0.76** on
190
+ `pruned` with 83% of `meta` groups wrong; ranking by signed value rather than magnitude **D = 0.76** with
191
+ 75% wrong; breaking ties toward the higher index **D = 0.043** with 0.41% wrong.""",
192
+ ).validate()
tools/factory/specs/sparse24_sparse_gemm.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `sparse24-sparse-gemm` — a GEMM whose A operand is in the compressed 2:4 layout: half-size
2
+ values plus 2-bit slot metadata, exactly what the sparse tensor cores take."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="sparse24-sparse-gemm",
11
+ title="Write a fast 2:4 structured-sparse GEMM (compressed A operand)",
12
+ blurb=("This is the kernel 2:4 sparsity exists for. A is stored compressed — a (M, K/2) value buffer "
13
+ "and two bits per value saying which of its group of four it came from — and the GEMM has to "
14
+ "walk B with those indices, doing half the multiply-accumulates of the dense problem. Ampere and "
15
+ "later expose it directly through the sparse MMA instruction; done properly it is the fastest "
16
+ "matmul on the machine, and done as a densify-then-dense-GEMM it does twice the arithmetic for "
17
+ "the same answer."),
18
+ keywords=["mle", "kernel-generation", "sparsity", "2:4", "structured-sparsity", "sparse-gemm",
19
+ "sparse-tensor-core", "mma-sp", "training", "compute-bound"],
20
+ module="sgemm24.py",
21
+ func="sparse24_gemm",
22
+ signature="sparse24_gemm(vals, meta, b)",
23
+ returns_doc="""GEMM with a 2:4 structured-sparse A operand in compressed form.
24
+
25
+ Args:
26
+ vals: (M, K//2) bfloat16 — A's surviving values, two per group of four, in ascending column order.
27
+ meta: (M, K//8) uint8 — 2 bits per survivor; byte t carries groups 2t (low nibble) and 2t+1 (high).
28
+ b: (K, N) bfloat16 — the dense right-hand operand.
29
+
30
+ Returns:
31
+ c: (M, N) bfloat16 — A_dense @ b, accumulated in fp32 and rounded once to bf16.""",
32
+
33
+ reference_imports="import torch",
34
+ reference_src='''
35
+ def _decode(meta, M, K):
36
+ """meta -> (M, K//4, 2) int64 slot indices."""
37
+ mi = meta.int()
38
+ q = torch.stack([mi & 3, (mi >> 2) & 3, (mi >> 4) & 3, (mi >> 6) & 3], dim=-1) # (M, K//8, 4)
39
+ return q.reshape(M, K // 4, 2).long()
40
+
41
+
42
+ def sparse24_gemm(vals, meta, b):
43
+ """Densify A and do a plain fp32 matmul.
44
+
45
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. It materialises the
46
+ full (M, K) dense A, converts everything to fp32, and does twice the necessary arithmetic.
47
+ """
48
+ M = vals.shape[0]
49
+ K = b.shape[0]
50
+ idx = _decode(meta, M, K)
51
+ dense = torch.zeros(M, K, device=vals.device, dtype=vals.dtype).view(M, K // 4, 4)
52
+ dense.scatter_(-1, idx, vals.view(M, K // 4, 2))
53
+ return (dense.view(M, K).float() @ b.float()).bfloat16()
54
+ ''',
55
+ make_inputs_src='''
56
+ _LO = [0, 0, 0, 1, 1, 2] # the six ways to choose 2 of 4
57
+ _HI = [1, 2, 3, 2, 3, 3]
58
+
59
+
60
+ def _mk(M, N, K, seed):
61
+ """A random 2:4 pattern per group of A, already compressed, plus a dense B."""
62
+ gen = torch.Generator(device="cuda").manual_seed(seed)
63
+ vals = (torch.randn(M, K // 2, device="cuda", dtype=torch.float32, generator=gen) * 0.05).bfloat16()
64
+ pat = torch.randint(0, 6, (M, K // 4), device="cuda", dtype=torch.int64, generator=gen)
65
+ lo = torch.tensor(_LO, device="cuda", dtype=torch.int32)[pat]
66
+ hi = torch.tensor(_HI, device="cuda", dtype=torch.int32)[pat]
67
+ nib = (lo | (hi << 2)).view(M, K // 8, 2)
68
+ meta = (nib[..., 0] | (nib[..., 1] << 4)).to(torch.uint8)
69
+ b = (torch.randn(K, N, device="cuda", dtype=torch.float32, generator=gen) * 0.05).bfloat16()
70
+ return vals, meta, b
71
+ ''',
72
+ flops_src='''
73
+ def canonical_work(M, N, K):
74
+ """FLOPs attributed to one sparse GEMM, from the SHAPE ALONE.
75
+
76
+ A has exactly K/2 non-zeros per row, so the problem is 2*M*N*(K/2) = M*N*K useful flops -- HALF the
77
+ dense count. That is what is credited, so a kernel that densifies A and runs a dense GEMM is doing
78
+ twice the arithmetic for the same credit and is scored accordingly.
79
+ """
80
+ return M * N * K
81
+ ''',
82
+ flops_formula="canonical_work(M, N, K) = 2 * M * N * (K/2) = M*N*K # half the dense GEMM's flops",
83
+
84
+ metric="TFLOP/s",
85
+ compare="tensor",
86
+ tol=2e-3,
87
+ shape_names=("M", "N", "K"),
88
+ grader_shapes=[(8192, 8192, 8192), (4096, 8192, 16384), (16384, 4096, 8192),
89
+ (8192, 6144, 12288), (12288, 8192, 6144)],
90
+ measure_shapes=[(8192, 8192, 6144), (4096, 6144, 16384), (12288, 4096, 8192),
91
+ (6144, 8192, 12288), (10240, 8192, 6144)],
92
+ measure_quick_shapes=[(2048, 2048, 2048), (1024, 4096, 2048), (4096, 1024, 4096)],
93
+ correct_shapes=[(64, 64, 128), (129, 96, 64), (33, 200, 8), (256, 33, 512), (17, 129, 24)],
94
+
95
+ spec_md="""`A` is a `(M, K)` matrix that is 2:4 structured-sparse, handed to you **compressed**. Group
96
+ `t` of row `m` covers columns `4t .. 4t+3` and has exactly two non-zeros, whose slots `i0 < i1` are stored
97
+ as two bits each:
98
+
99
+ ```
100
+ i0(2t) = (meta[m, t] >> 0) & 3 i1(2t) = (meta[m, t] >> 2) & 3
101
+ i0(2t+1) = (meta[m, t] >> 4) & 3 i1(2t+1) = (meta[m, t] >> 6) & 3
102
+ ```
103
+
104
+ so byte `t` describes groups `2t` and `2t+1`, lower group in the low nibble, lower slot in the lower bits.
105
+ The matching values are
106
+
107
+ ```
108
+ A[m, 4g + i0(g)] = vals[m, 2g]
109
+ A[m, 4g + i1(g)] = vals[m, 2g + 1]
110
+ A[m, everything else] = 0
111
+ ```
112
+
113
+ and the output is the ordinary product
114
+
115
+ ```
116
+ c[m, n] = sum over k of A[m, k] * b[k, n]
117
+ = sum over groups g of vals[m,2g]*b[4g+i0(g), n] + vals[m,2g+1]*b[4g+i1(g), n]
118
+ ```
119
+
120
+ accumulated in **fp32** and rounded **once** to bf16 at the end.
121
+
122
+ The second form is the point: only `K/2` products per output element are non-zero, and the metadata tells
123
+ you exactly which rows of `b` they need. That is what the sparse MMA instruction consumes — it takes a
124
+ half-width A fragment plus the index bits and internally selects the matching halves of a full-width B
125
+ fragment.
126
+
127
+ `K` is a multiple of 8. `A` is never explicitly materialised by the spec: it is defined by `(vals, meta)`.
128
+
129
+ `/app/reference.py` scatters `vals` back into a dense `(M, K)` buffer and calls a plain fp32 matmul. That
130
+ is the exact numerical specification, and it is deliberately the slow way round: it does twice the
131
+ arithmetic and touches twice the memory.""",
132
+
133
+ contract_md="""| arg | shape | dtype | meaning |
134
+ |-----|-------|-------|---------|
135
+ | `vals` | `(M, K//2)` | `bfloat16` | A's survivors, two per group, ascending column order |
136
+ | `meta` | `(M, K//8)` | `uint8` | 2 bits per survivor, two groups per byte, as defined above |
137
+ | `b` | `(K, N)` | `bfloat16` | the dense right operand, row-major |
138
+
139
+ **Return** a single tensor:
140
+
141
+ | out | shape | dtype | notes |
142
+ |-----|-------|-------|-------|
143
+ | `c` | `(M, N)` | `bfloat16` | `A_dense @ b`, fp32 accumulation, one rounding to bf16 |
144
+
145
+ `K = b.shape[0]` — it is not passed separately, and `vals.shape[1] == K//2`. `K` is a multiple of 8;
146
+ `M` and `N` are not multiples of any tile size (the correctness shapes include `M = 33`, `N = 33`,
147
+ `M = 129`). All inputs are read-only.""",
148
+
149
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `M`
150
+ 4096–16384, `N` 4096–8192, `K` 6144–16384, i.e. **0.5–0.6 TFLOP of credited work per call** — a single
151
+ projection of a large model at a substantial batch, or one expert's GEMM. These are square-ish,
152
+ compute-bound shapes: at the graded sizes the operands are a few hundred megabytes and the arithmetic
153
+ dominates, so this is a tensor-core problem, not a bandwidth one.""",
154
+
155
+ correctness_md="""The returned tensor must match the reference within **relative error `2e-3`** at
156
+ every graded shape, including the timed ones.
157
+
158
+ The output is bf16, but that final rounding is common to the reference and to your kernel, so it cancels:
159
+ what is left is only the fp32 accumulation order, and a faithful bf16 tensor-core GEMM measures
160
+ **1.6e-4 to 2.9e-4** against the reference across every graded shape and every timed seed (a split-K
161
+ variant, **5.0e-5**). The gate is 7x the worst of those.
162
+
163
+ What it actually tests is whether you used the metadata. Every way of getting the sparsity structure wrong
164
+ is three orders of magnitude outside: assuming slots `(0, 1)` for every group scores **1.16**, reading the
165
+ nibbles in the wrong order **1.11**, swapping `i0` and `i1` within each group **1.41**. Accumulating in
166
+ bf16 instead of fp32 also fails, which is intended.""",
167
+
168
+ perf_md="""This is a **compute-bound GEMM** and you are credited `M*N*K` flops — half the dense count —
169
+ so the ranking is about how much of the machine's sparse (or dense) tensor-core throughput you can hold.
170
+
171
+ There are two levels of solution and both are worth having:
172
+
173
+ 1. **Densify and run a dense GEMM.** Scatter `vals` into a `(M, K)` buffer using `meta` and call an
174
+ ordinary bf16 tensor-core GEMM. Correct, straightforward, and it does *twice* the credited arithmetic —
175
+ so it can score at best about half of what the machine's dense peak would suggest. Fusing the densify
176
+ into the GEMM's A-fragment load (rather than writing a dense A to HBM first) is a large win on its own.
177
+
178
+ 2. **Use the sparse MMA.** sm≥80 exposes `mma.sp` (and sm≥90 `wgmma.sp`) which takes a half-width A
179
+ fragment plus a metadata operand and internally selects the matching halves of the B fragment. That is
180
+ the instruction this data layout exists for, and it doubles the achievable rate. Getting there means
181
+ writing PTX (inline `asm` in a CUDA extension) or driving CUTLASS's sparse GEMM collectives from
182
+ `/opt/cutlass/include`. The metadata operand's expected register layout is the fiddly part — work out
183
+ the per-lane mapping carefully and check it against the reference at a small shape before scaling up.
184
+
185
+ Whichever route you take, the usual GEMM engineering decides the score: a persistent tile schedule sized
186
+ from `multi_processor_count`, a double- or triple-buffered pipeline into shared memory (TMA where
187
+ available), an epilogue that writes bf16 in 128-bit stores, and split-K only where the shape needs it.
188
+
189
+ Two things specific to this problem:
190
+
191
+ - **`b` is read with a gather along K.** In the compressed formulation the rows of `b` you need are chosen
192
+ per group; loading whole `K`-tiles of `b` into shared memory and selecting there costs nothing extra,
193
+ whereas gathering from HBM per index would destroy the bandwidth.
194
+ - **`meta` is tiny** — one byte per four columns of A — so it should live in registers or shared memory
195
+ for the whole tile, never be re-read.""",
196
+
197
+ precision_md="""Both operands are **bfloat16** and the output is **bfloat16**. Accumulate in **fp32**
198
+ and round **once**, at the end.
199
+
200
+ Because `vals` and `b` are already bf16, there is no quantisation error in this task at all: the products
201
+ are exact and the only numerical freedom is the fp32 accumulation order and the final rounding. That is why
202
+ the tolerance is what it is rather than the 1e-2 a bf16 GEMM sometimes gets.
203
+
204
+ Do **not** accumulate in bf16 or fp16, and do not use an approximate reciprocal/rounding on the epilogue.
205
+ Split-K is fine — it changes the accumulation order, which is within the tolerance — as long as the partial
206
+ sums are combined in fp32.
207
+
208
+ **Where the tolerance comes from (measured, not guessed).** An independent implementation — the same
209
+ densification followed by a **bf16 tensor-core** matmul with fp32 accumulation (i.e. what a good kernel
210
+ actually does) instead of the reference's fp32 matmul — differs from the reference by **`E = 1.9e-4`** at a
211
+ full graded shape (`0.0` at the small correctness shapes, where `K` is tiny). Swept over all five graded
212
+ shapes and the seeds the grader uses for the **timed** validation, that stays in **1.6e-4 .. 2.9e-4** — a
213
+ 1.8x spread, so the gate is not a seed lottery. A split-K variant (K split in 4, partials summed in fp32)
214
+ measured **5.0e-5**. The gate is set at **`2e-3`**, 7x the worst measured floor, which leaves room for other
215
+ accumulation orders and tilings while staying ~550x below the cheapest structural mistake.
216
+
217
+ Drop-the-feature measurements at a graded shape: ignoring `meta` and assuming slots `(0, 1)` in every group
218
+ **D = 1.16**; nibble order swapped **D = 1.11**; `i0`/`i1` swapped **D = 1.41**.""",
219
+ ).validate()
tools/factory/specs/spec_decode_kv_rollback.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `speculative-draft-kv-rollback` — compacting the KV of the accepted path after verification."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="speculative-draft-kv-rollback",
10
+ title="Write a fast speculative-decode KV rollback kernel",
11
+ blurb=("Tree speculative decoding writes KV for every draft token before it knows which ones survive. "
12
+ "Verification then accepts one PATH through the tree, and the cache has to be rolled back: the "
13
+ "accepted tokens' KV — scattered across the slots the draft occupied, in tree order, not in "
14
+ "sequence order — is compacted to the front of the sequence's region and everything else is "
15
+ "discarded. It runs after every verify step, for every layer, on the whole batch."),
16
+ keywords=["mle", "kernel-generation", "speculative-decoding", "eagle", "mtp", "kv-cache", "rollback",
17
+ "tree-attention", "serving", "memory-bound"],
18
+ module="rollback.py",
19
+ func="spec_kv_rollback",
20
+ signature="spec_kv_rollback(k_cache, v_cache, draft_slot, accept_idx, accept_len)",
21
+ returns_doc="""Compact the KV of the accepted draft path, for every layer.
22
+
23
+ Args:
24
+ k_cache: (L, NSLOT, H, D) bfloat16 — flat token-slot key pool.
25
+ v_cache: (L, NSLOT, H, D) bfloat16 — flat token-slot value pool.
26
+ draft_slot: (B, K) int32 — physical slot the KV of draft position j of sequence b was written to.
27
+ accept_idx: (B, K) int32 — accept_idx[b, t] = the draft position accepted at step t, -1 once the
28
+ path ends; strictly increasing while >= 0.
29
+ accept_len: (B,) int32 — how many draft tokens sequence b accepted, in [0, K].
30
+
31
+ Returns:
32
+ (k_acc, v_acc), each (L, B, K, H, D) bfloat16 — the accepted path's KV packed at the front of the
33
+ K axis; rows t >= accept_len[b] are exactly 0.""",
34
+
35
+ reference_imports="import torch",
36
+ reference_src='''
37
+ def spec_kv_rollback(k_cache, v_cache, draft_slot, accept_idx, accept_len):
38
+ """Resolve the accepted path to physical slots, gather the whole (B, K) grid, blank the rejected part.
39
+
40
+ Correct and simple — it is the exact SPECIFICATION, not a performance target: it gathers K slots for
41
+ every sequence even where the path stopped after one token.
42
+ """
43
+ L, NSLOT, H, D = k_cache.shape
44
+ B, K = draft_slot.shape
45
+ dev = k_cache.device
46
+
47
+ src = torch.gather(draft_slot, 1, accept_idx.clamp(min=0).long()) # (B, K) slot of step t
48
+ live = torch.arange(K, device=dev).unsqueeze(0) < accept_len.long().unsqueeze(1)
49
+ s = torch.where(live, src, torch.zeros_like(src)).long().reshape(-1)
50
+
51
+ z = torch.zeros((), device=dev, dtype=k_cache.dtype)
52
+ m = live.view(1, B, K, 1, 1)
53
+ k_acc = torch.where(m, k_cache[:, s].view(L, B, K, H, D), z)
54
+ v_acc = torch.where(m, v_cache[:, s].view(L, B, K, H, D), z)
55
+ return k_acc, v_acc
56
+ ''',
57
+ make_inputs_src='''
58
+ def _mk(L, B, K, H, D, seed):
59
+ """A KV pool with the batch's draft tokens scattered through it, plus one accepted tree path each.
60
+
61
+ The accepted path is a strictly increasing subset of the K draft positions — what a path through a
62
+ draft tree stored in breadth-first order looks like — of the shape-only length `_alen`, which includes
63
+ sequences that accepted nothing at all. `draft_slot` is a random subset of the pool, so the gather is
64
+ scattered by token, not by page.
65
+ """
66
+ gen = torch.Generator(device="cuda").manual_seed(seed)
67
+ dev, NSLOT = "cuda", _pool(B, K)
68
+ k = torch.randn(L, NSLOT, H, D, device=dev, dtype=torch.bfloat16, generator=gen)
69
+ v = torch.randn(L, NSLOT, H, D, device=dev, dtype=torch.bfloat16, generator=gen)
70
+
71
+ draft_slot = torch.randperm(NSLOT, device=dev, generator=gen)[:B * K].view(B, K).to(torch.int32)
72
+ alen = torch.tensor(_alen(B, K), device=dev, dtype=torch.int32)
73
+
74
+ col = torch.arange(K, device=dev).unsqueeze(0).expand(B, K)
75
+ r = torch.rand(B, K, device=dev, generator=gen)
76
+ rank = r.argsort(dim=1).argsort(dim=1) # a random rank per column
77
+ mask = rank < alen.long().unsqueeze(1) # exactly alen[b] chosen positions
78
+ pos = torch.where(mask, col, torch.full_like(col, K)).sort(dim=1).values
79
+ accept_idx = torch.where(pos < K, pos, torch.full_like(pos, -1)).to(torch.int32).contiguous()
80
+ return k, v, draft_slot.contiguous(), accept_idx, alen
81
+ ''',
82
+ flops_src='''
83
+ def _mix(i):
84
+ """A shape-only 32-bit hash: deterministic, seed-independent, low-discrepancy."""
85
+ i = (i * 2654435761 + 1013904223) % 2 ** 32
86
+ i ^= i >> 15
87
+ return (i * 2246822519) % 2 ** 32
88
+
89
+
90
+ def _pool(B, K):
91
+ """Token slots in the pool, from the SHAPE ALONE: two and a half times the drafts in flight."""
92
+ return (5 * B * K) // 2
93
+
94
+
95
+ def _alen(B, K):
96
+ """Accepted tokens per sequence, from the SHAPE ALONE: 0..K, averaging a little over half of K —
97
+ the acceptance profile of a decent draft model, including the sequences that accept nothing."""
98
+ return [((K + 1) * _mix(131 + b)) // 2 ** 32 for b in range(B)]
99
+
100
+
101
+ def canonical_work(L, B, K, H, D):
102
+ """BYTES attributed to one rollback, from the SHAPE ALONE.
103
+
104
+ Per layer: the KV of every ACCEPTED draft token is read once (H*D bf16 elements of K and of V) and the
105
+ whole (B, K) destination grid is written once — the rejected rows are written as zeros, which is real
106
+ traffic. Plus the three per-sequence index tensors. The rejected tokens' KV is never read. This is a
107
+ pure data-movement kernel: the score is achieved bandwidth against this fixed byte count.
108
+ """
109
+ acc = sum(_alen(B, K))
110
+ return 2 * L * acc * H * D * 2 + 2 * L * B * K * H * D * 2 + B * (8 * K + 4)
111
+ ''',
112
+ flops_formula=("ACC = sum of accept_len over the batch # _alen(B, K), averaging just over K/2\n\n"
113
+ "canonical_work(L, B, K, H, D) = 2*L*ACC*H*D*2 + 2*L*B*K*H*D*2 + B*(8*K + 4)\n"
114
+ "# read the write the whole draft_slot,\n"
115
+ "# accepted KV, destination grid, accept_idx,\n"
116
+ "# K and V zeros included accept_len"),
117
+
118
+ metric="GB/s",
119
+ compare="tuple",
120
+ tuple_names=("k_acc", "v_acc"),
121
+ tol=1e-6,
122
+ shape_names=("L", "B", "K", "H", "D"),
123
+ grader_shapes=[(16, 2048, 8, 8, 128), (8, 4096, 8, 8, 128), (16, 1024, 16, 8, 128),
124
+ (16, 1536, 8, 16, 128), (32, 1024, 8, 8, 128)],
125
+ measure_shapes=[(16, 1792, 8, 8, 128), (8, 3584, 8, 8, 128), (16, 896, 16, 8, 128),
126
+ (16, 1280, 8, 16, 128), (28, 1024, 8, 8, 128)],
127
+ measure_quick_shapes=[(4, 256, 8, 8, 128), (2, 512, 4, 8, 128), (8, 128, 16, 4, 128)],
128
+ correct_shapes=[(2, 33, 8, 4, 64), (1, 7, 4, 8, 128), (3, 64, 16, 2, 128),
129
+ (2, 5, 2, 8, 64), (4, 129, 8, 4, 32)],
130
+
131
+ spec_md="""A tree speculative step proposes `K` draft tokens per sequence and writes their K and V into
132
+ the cache **before** verification, one token per physical slot:
133
+
134
+ ```
135
+ k_cache[layer, slot, head, channel] shape (L, NSLOT, H, D)
136
+ draft_slot[b, j] the slot draft position j of sequence b was written to
137
+ ```
138
+
139
+ The slots are whatever the allocator handed out, so they are **scattered** — this is a flat token-slot
140
+ pool, the page-table lookup has already happened.
141
+
142
+ Verification then accepts **one path** through the draft tree. `accept_idx[b, t]` is the draft position of
143
+ the `t`-th accepted token, for `t < accept_len[b]`, and `-1` afterwards. Because a draft tree is stored in
144
+ breadth-first order, an accepted path visits **strictly increasing** positions — but it skips: accepting
145
+ positions `0, 3, 4` is normal, and it is *not* the same as accepting positions `0, 1, 2`.
146
+
147
+ The rollback compacts the surviving KV to the front:
148
+
149
+ ```
150
+ for t < accept_len[b]: k_acc[l, b, t] = k_cache[l, draft_slot[b, accept_idx[b, t]]]
151
+ for t >= accept_len[b]: k_acc[l, b, t] = 0
152
+ ```
153
+
154
+ and identically for `v`. **Two indirections in a row**: `accept_idx` selects a draft position, and
155
+ `draft_slot` turns that position into a physical slot. Doing only one of them (using `accept_idx` as if it
156
+ were a slot, or `draft_slot[b, t]` as if the path were the first `accept_len[b]` positions) reads entirely
157
+ different data.
158
+
159
+ `accept_len[b] == 0` is legal and happens in the graded data — a sequence whose very first draft token was
160
+ rejected contributes an all-zero row.
161
+
162
+ Returning the compacted KV as a dense `(L, B, K, H, D)` tensor is the functional form of what a real engine
163
+ does in place; the grader needs a value it can compare.
164
+
165
+ `/app/reference.py` resolves the path, gathers the full `(B, K)` grid for every layer, and then multiplies
166
+ the rejected part away. That is the exact specification; it is deliberately simple rather than fast.""",
167
+
168
+ contract_md="""| arg | shape | dtype | meaning |
169
+ |-----|-------|-------|---------|
170
+ | `k_cache` | `(L, NSLOT, H, D)` | `bfloat16` | flat token-slot key pool |
171
+ | `v_cache` | `(L, NSLOT, H, D)` | `bfloat16` | flat token-slot value pool |
172
+ | `draft_slot` | `(B, K)` | `int32` | slot of each draft position; all `B*K` values distinct, in `[0, NSLOT)` |
173
+ | `accept_idx` | `(B, K)` | `int32` | draft position accepted at step `t`; strictly increasing while `>= 0`, then `-1` |
174
+ | `accept_len` | `(B,)` | `int32` | accepted count per sequence, in `[0, K]`; `accept_idx[b, t] >= 0` exactly for `t < accept_len[b]` |
175
+
176
+ **Return** a 2-tuple `(k_acc, v_acc)` **in that order**, each of shape `(L, B, K, H, D)`, dtype
177
+ `bfloat16`.
178
+
179
+ Fixed facts you may rely on:
180
+
181
+ - `accept_len[b]` and the `-1` padding of `accept_idx` agree, so either one tells you where the path ends;
182
+ - `accept_idx[b, t] < K` always, and the values in a row are pairwise distinct and increasing;
183
+ - rows `t >= accept_len[b]` of the output must be **exactly `0`** for both tensors, every head and channel;
184
+ - `accept_len[b] == 0` occurs in the graded data;
185
+ - the pool is 2.5x the size of the draft grid, so most of it must **not** be read.
186
+
187
+ All tensors are CUDA and contiguous. Treat all inputs as read-only.""",
188
+
189
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L`
190
+ (layers rolled back per call) in 8–32, `B` (sequences) in 1024–4096, `K` (draft tokens per sequence) in
191
+ 8–16, `H` (KV heads) in 8–16, `D = 128`. That is a large-batch EAGLE/MTP configuration: 8k–32k draft
192
+ tokens in flight, one to two and a half gigabytes of bf16 KV touched per verify step. Write a **general**
193
+ kernel: `K` and `H` both vary, and the accepted lengths are ragged across the whole `0..K` range, so the
194
+ work per sequence differs by an unbounded factor.""",
195
+
196
+ correctness_md="""**Both** returned tensors must match the reference within **relative error `1e-6`** at
197
+ every graded shape, including the timed ones. That is effectively an **exact** gate and deliberately so:
198
+ this kernel performs no arithmetic — it relocates bf16 values — so a correct implementation reproduces the
199
+ reference **bit for bit** and scores `0.0`.
200
+
201
+ **Measured, so you know where the gate is.** An independent implementation that loops over sequences,
202
+ resolves the path with two scalar index loads per accepted token and copies into a pre-zeroed output (no
203
+ materialised `(B, K)` gather, no masking pass) reproduces the reference at **`E = 0.0` exactly** at every
204
+ correctness and graded shape. For contrast, on the same inputs: treating the accepted path as the first
205
+ `accept_len[b]` draft positions (skipping the `accept_idx` indirection) measures **`D = 1.04 – 1.05`** at
206
+ the graded shapes, and copying all `K` rows instead of stopping at `accept_len[b]` measures
207
+ **`D = 1.00 – 1.01`**. Both are six orders of magnitude outside the gate.""",
208
+
209
+ perf_md="""This is **pure data movement** and your score is achieved bandwidth against one read of the
210
+ accepted tokens' KV and one write of the destination grid. The reference is several times off it: it
211
+ gathers **all** `B*K` rows for every layer — nearly twice the credited read, since fewer than half the
212
+ draft tokens are rejected — materialises that as a temporary, and then `torch.where` reads it back and
213
+ writes it again, so the payload crosses HBM about four times instead of two.
214
+
215
+ What a fast kernel does:
216
+
217
+ - **One pass, one block per `(layer, sequence)`** (or per `(layer, sequence, accepted token)`). Two `int32`
218
+ loads resolve the double indirection for one output row, then `H * D` bf16 values — 2 to 4 KiB — are
219
+ copied contiguously. Both endpoints are naturally aligned, so 128-bit vector loads and stores saturate
220
+ the line.
221
+ - **Do not gather the rejected rows.** They are known from `accept_len` before any payload is touched. The
222
+ destination rows past `accept_len[b]` still have to be *written* (as zeros), but that write costs nothing
223
+ to generate — it is a memset, not a copy.
224
+ - **The double indirection is cheap; keep it in registers.** `accept_idx[b, t]` and then
225
+ `draft_slot[b, that]` are two dependent 4-byte loads per 4 KiB of payload. Issue them for several `t` at
226
+ once so the dependent loads overlap rather than serialising.
227
+ - **Fuse K and V and all layers.** They share every index; the layer stride is a constant. A grid over
228
+ `(L, B)` with the `K` loop inside amortises the index loads `L` times over and gives plenty of
229
+ memory-level parallelism.
230
+ - **The ragged accepted length is the load-balancing problem.** `accept_len` spans `0..K`, so a static
231
+ one-block-per-sequence grid has blocks doing nothing next to blocks doing 16 rows. Flatten the work to
232
+ `(layer, sequence, t)` triples and let a persistent grid pull from a counter, or precompute a prefix sum
233
+ of `accept_len` and index the flattened work directly.
234
+ - **Stream the stores.** The output is never re-read; non-temporal stores keep it out of L2 and leave the
235
+ cache to the scattered pool reads.""",
236
+
237
+ precision_md="""**The measured basis for the tolerance.** There is no arithmetic here, so an independent
238
+ implementation reproduces the reference **bit for bit**: the measured `E` is **0.0** at every correctness
239
+ and graded shape, and `1e-6` is simply the exactness check that fact calls for, not a "tight" gate. The
240
+ two shortcuts it exists to catch were measured on the same inputs and land at `D = 0.67 – 1.05` (path
241
+ indirection skipped) and `D = 0.51 – 1.01` (all `K` rows copied) — five to six orders of magnitude out.
242
+
243
+ There is **no arithmetic** in this kernel and therefore no precision question: the KV
244
+ values are `bfloat16` and must be reproduced **bit-identically** — this is the cache the next step will
245
+ attend over. Do not convert to fp32 and back, and do not quantise to fp8; the contract fixes the output
246
+ dtype at `bfloat16` and the grader compares against a bit-exact reference at `1e-6`.
247
+
248
+ The zeros past `accept_len[b]` are part of the contract and must be **exact zeros**. Allocating the output
249
+ with `torch.empty` and writing only the accepted rows leaves the rest uninitialised: it passes on a warm
250
+ allocator and fails as soon as the allocator hands you a dirty buffer — which the grader's fresh-input
251
+ timing loop will do.
252
+
253
+ Everything delicate here is **integer index bookkeeping**, and there are three traps:
254
+
255
+ - **Two indirections, in this order:** `slot = draft_slot[b, accept_idx[b, t]]`. Using `accept_idx` as a
256
+ slot, or `draft_slot[b, t]` directly, both run and both are wrong by `D ≈ 1`.
257
+ - **`accept_idx` skips.** A path through a draft tree is increasing but not contiguous; assuming
258
+ `accept_idx[b, t] == t` is exactly the "linear draft chain" special case and is wrong for every tree.
259
+ - **Index width.** `L * NSLOT * H * D` exceeds `2**31` elements at the larger graded shapes, so compute
260
+ element and byte offsets in 64-bit; `draft_slot` arrives as `int32` and must be widened before it is
261
+ scaled by the slot stride.""",
262
+ ).validate()
tools/factory/specs/swiglu_blockwise_fp8.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `swiglu-blockwise-fp8-quant` — SwiGLU fused with the 1x128 FP8 quantisation of its output."""
2
+ import pathlib
3
+ import sys
4
+
5
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
6
+ from spec import TaskSpec
7
+
8
+ SPEC = TaskSpec(
9
+ name="swiglu-blockwise-fp8-quant",
10
+ title="Write a fast fused SwiGLU + blockwise FP8 quantisation kernel",
11
+ blurb=("Between the two GEMMs of an FP8-served MLP there is exactly one elementwise step: split the "
12
+ "fused gate/up projection, apply SwiGLU, and immediately quantise the result to FP8 with a "
13
+ "per-128-element block scale so the down-projection can consume it directly. Done as separate "
14
+ "ops the intermediate — which is twice the width of the hidden state — crosses HBM four or five "
15
+ "times; fused it is one read of the projection and one four-times-narrower write."),
16
+ keywords=["mle", "kernel-generation", "fp8", "swiglu", "quantization", "moe", "memory-bound",
17
+ "deepseek", "serving"],
18
+ module="swiglu_quant.py",
19
+ func="swiglu_fp8_quant",
20
+ signature="swiglu_fp8_quant(x)",
21
+ returns_doc="""Fused SwiGLU + per-128-block FP8 quantisation.
22
+
23
+ Args:
24
+ x: (M, 2N) bfloat16 — the fused gate/up projection output, [gate half | up half].
25
+
26
+ Returns:
27
+ (q, s) where
28
+ q: (M, N) float8_e4m3fn — the quantised SwiGLU output
29
+ s: (M, N // 128) float32 — one scale per 128-element block along N""",
30
+
31
+ reference_imports="import torch",
32
+ reference_src='''
33
+ FP8_MAX = 448.0 # max finite magnitude of float8_e4m3fn
34
+ BLOCK = 128 # quantisation block along the feature axis
35
+
36
+
37
+ def swiglu_fp8_quant(x):
38
+ """SwiGLU then per-128-block FP8 quantisation, as separate steps in fp32.
39
+
40
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target.
41
+
42
+ NOTE the TENSOR divisor: `amax / fmax` with a 0-dim tensor is a correctly-rounded IEEE fp32 division,
43
+ which is exactly what `amax / 448.0f` gives in CUDA/Triton. (torch turns `tensor / python_float` into a
44
+ multiply by the rounded reciprocal, which is off by an ulp on many elements.)
45
+ """
46
+ M, N2 = x.shape
47
+ N = N2 // 2
48
+ fmax = torch.tensor(FP8_MAX, device=x.device)
49
+ xf = x.float()
50
+ g, u = xf[:, :N], xf[:, N:] # gate half, up half
51
+ y = (g * torch.sigmoid(g)) * u # SwiGLU, in fp32
52
+
53
+ yb = y.view(M, N // BLOCK, BLOCK)
54
+ s = (yb.abs().amax(-1) / fmax).clamp(min=1e-12) # (M, N//128) block scales
55
+ q = (yb / s.unsqueeze(-1)).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn).view(M, N)
56
+ return q, s
57
+ ''',
58
+ make_inputs_src='''
59
+ def _mk(M, N, seed):
60
+ """A ~14x magnitude spread BETWEEN 128-blocks, so a per-row scale is genuinely wrong and the per-block
61
+ absmax is a real reduction rather than a formality."""
62
+ gen = torch.Generator(device="cuda").manual_seed(seed)
63
+ blk = torch.exp(torch.rand(1, 2 * N // 128, device="cuda", generator=gen) * 2.6 - 1.3)
64
+ blk = blk.repeat_interleave(128, dim=1)
65
+ x = (torch.randn(M, 2 * N, device="cuda", generator=gen) * blk).to(torch.bfloat16)
66
+ return (x,)
67
+ ''',
68
+ flops_src='''
69
+ def canonical_work(M, N):
70
+ """BYTES attributed to one fused SwiGLU+quant, from the SHAPE ALONE.
71
+
72
+ The unavoidable traffic: read x (M*2N elements at 2 bytes, bf16), write q (M*N at 1 byte, fp8), write one
73
+ fp32 scale per 128-element block. Memory-bound, so the score is achieved bandwidth against this fixed
74
+ byte count. Note the 4:1 read:write ratio — the input is twice as wide as the output and four times the
75
+ element width.
76
+ """
77
+ return M * 2 * N * 2 + M * N * 1 + M * (N // 128) * 4
78
+ ''',
79
+
80
+ metric="GB/s",
81
+ compare="tuple",
82
+ tuple_names=("q", "s"),
83
+ tol=8e-4, # MEASURED: 3.3x the 2.4e-4 spread between two independent correct implementations; still
84
+ # 15x below the 1.2e-2 that rounding the SwiGLU output through bf16 scores.
85
+ shape_names=("M", "N"),
86
+ grader_shapes=[(65536, 8192), (131072, 4096), (32768, 16384), (262144, 2048), (98304, 6144)],
87
+ measure_shapes=[(49152, 8192), (98304, 4096), (32768, 12288), (196608, 2048), (65536, 6144)],
88
+ measure_quick_shapes=[(4096, 4096), (2048, 8192), (8192, 2048)],
89
+ correct_shapes=[(256, 512), (129, 1024), (513, 256), (64, 2048)],
90
+
91
+ spec_md="""Two steps, fused. The input is the **fused gate/up projection**: one `(M, 2N)` matrix whose
92
+ first `N` columns are the gate and whose last `N` columns are the value.
93
+
94
+ **1 — SwiGLU**, with `silu(v) = v * sigmoid(v)`:
95
+
96
+ ```
97
+ g[m, n] = x[m, n] # gate, columns 0 .. N-1
98
+ u[m, n] = x[m, N + n] # up, columns N .. 2N-1
99
+ y[m, n] = silu(g[m, n]) * u[m, n]
100
+ ```
101
+
102
+ The gate is the **first** half and it is the one that goes through the nonlinearity. Swapping them scores
103
+ 0.77.
104
+
105
+ **2 — blockwise FP8 quantisation** of `y` along `N`, in blocks of **128**:
106
+
107
+ ```
108
+ for each row m and block b covering n in [128b, 128b + 128):
109
+ amax = max |y[m, n]| over the block (clamped below at 1e-12)
110
+ s[m,b] = amax / 448.0 # 448 = max finite float8_e4m3fn
111
+ q[m,n] = cast_to_float8_e4m3fn( y[m, n] / s[m, b] )
112
+ ```
113
+
114
+ so that `q * s` reconstructs `y` to FP8 accuracy. Both are returned — the scales are what the consuming FP8
115
+ GEMM needs. The block boundary is at multiples of 128 **within a row**; the blocks never straddle rows.
116
+
117
+ The intermediate `y` is **never materialised**: it exists only in registers between the SwiGLU and the cast,
118
+ and it must stay **fp32** all the way into the cast (see Precision — rounding it through bf16 fails the gate).
119
+
120
+ `/app/reference.py` does this as separate fp32 passes. That is the exact specification, and it is also what a
121
+ fused kernel must avoid: it writes `y`, reads it back for the absmax, and reads it a third time to divide and
122
+ cast.""",
123
+
124
+ contract_md="""| arg | shape | dtype | meaning |
125
+ |-----|-------|-------|---------|
126
+ | `x` | `(M, 2N)` | `bfloat16` | fused projection output, `[gate half | up half]` |
127
+
128
+ **Return** a 2-tuple `(q, s)` **in that order**:
129
+
130
+ | out | shape | dtype |
131
+ |-----|-------|-------|
132
+ | `q` | `(M, N)` | `torch.float8_e4m3fn` |
133
+ | `s` | `(M, N // 128)` | `float32` |
134
+
135
+ `N` is always a multiple of 128 (so `x` has `2N` columns, also a multiple of 128). `q` must be genuine
136
+ `float8_e4m3fn`, not a wider dtype holding small values — the four-times-narrower write is the entire point.
137
+ `M` is **not** a multiple of any tile size (the correctness shapes include `M = 129` and `M = 513`), so handle
138
+ the tail. Treat `x` as read-only.""",
139
+
140
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `M` (tokens,
141
+ or tokens-per-expert after an MoE permute) in 32768–262144 and `N` (the MLP intermediate width) in
142
+ 2048–16384, so `x` has up to 32768 columns. Write a **general** kernel; both very tall/narrow and short/wide
143
+ shapes appear, and the number of 128-blocks per row varies from 16 to 128.""",
144
+
145
+ correctness_md="""**Both** returned tensors must match the reference within **relative error `8e-4`** at
146
+ every graded shape, including the timed ones — the scales as well as the quantised values, and the grader
147
+ scores the **worse** of the two.
148
+
149
+ Grading the pair is not a formality here. Because the block scale absorbs any change in the *magnitude* of
150
+ `y`, a kernel that emits **one scale per row** instead of one per 128-block produces FP8 codes that are not
151
+ obviously wrong, while its scales are off by **0.98 – 3.4** — a factor of 1000 above the gate.
152
+
153
+ The other failure modes: swapping the gate and up halves scores **0.77**; using a GELU instead of the SiLU
154
+ scores **0.13**; and the numerical one to watch, rounding the SwiGLU output through **bfloat16** before
155
+ quantising, scores **1.2e-2**, still **15x** the tolerance.""",
156
+
157
+ perf_md="""This kernel is **memory-bound** with an unusual, lopsided profile: `4*M*N` bytes in and
158
+ `~1.03*M*N` bytes out. Your score is achieved bandwidth against that total, and the ceiling is the HBM
159
+ bandwidth you measure on the device (time a large bf16 `copy_` and aim there).
160
+
161
+ Where the reference loses: `y` is a full `(M, N)` fp32 tensor written and then read twice more, and the
162
+ `.view`/`.amax`/`.clamp`/`.to` chain is four more full-size passes.
163
+
164
+ What a fast kernel does:
165
+
166
+ - **one pass, `y` never leaves registers.** A thread block owns a tile of rows and a whole 128-block (or
167
+ several); it loads the gate and up columns, computes the SwiGLU in fp32, takes the block absmax with a
168
+ warp-shuffle reduction, and emits the FP8 bytes and the scale. Nothing intermediate touches memory.
169
+ - **the two halves are `N` columns apart.** `g[m,n]` and `u[m,n]` live at `x[m,n]` and `x[m,N+n]`: two
170
+ coalesced 128-bit streams at a fixed offset, not an interleave. Issue both loads before either is needed.
171
+ - **a 128-block maps exactly onto a warp** with four elements per lane (one 64-bit load per half), so the
172
+ absmax is a five-step `__shfl_xor` reduction with no shared memory and no block barrier. Do not use a
173
+ block-wide reduction for a 128-element group.
174
+ - **vectorise the FP8 stores.** `q` is one byte per element; storing it one element at a time will cap you
175
+ far below the roofline. Pack 8 or 16 codes into a 64/128-bit store. The FP8 conversion instructions convert
176
+ two values at a time — use them rather than a per-element cast.
177
+ - **the read side is 80% of the traffic.** Perfect stores with scalar loads is the wrong trade here; make the
178
+ loads 128-bit first.
179
+ - **the scale write is small but not free** at `N = 2048` (one fp32 per 128 elements is 1/64 of the output);
180
+ keep it coalesced across the row.""",
181
+
182
+ precision_md="""The input is **bfloat16** and the output is **float8_e4m3fn** with **fp32** scales. The
183
+ SwiGLU and the block absmax must be computed in **fp32**.
184
+
185
+ **Keep `y` in fp32 all the way into the cast.** e4m3 has a 3-bit mantissa, so consecutive codes are ~6%
186
+ apart and the output is a *step function* of `y`: an upstream perturbation of relative size `d` does not
187
+ produce an error of size `d`, it flips roughly `d/0.06` of the elements by a full step, i.e. an error near
188
+ `0.25 * sqrt(d)`. Rounding `y` through bfloat16 first (`d ~ 4e-3`) measures **1.2e-2** — **15x** this gate,
189
+ and a fail. There is no bandwidth argument for narrowing `y`: it is never written to memory.
190
+
191
+ The quantisation itself is otherwise essentially **deterministic** — the per-block absmax is an exact max, so
192
+ two correct kernels compute bit-identical scales and almost identical codes. If your error is large it is a
193
+ bug, most often a block boundary that is not a multiple of 128 or an absmax taken over the wrong axis.
194
+
195
+ **Where the tolerance comes from.** `8e-4` is measured, not inherited. A second, independent implementation —
196
+ rows chunked in blocks of 64, `silu` evaluated as `g / (1 + exp(-g))` instead of `g * sigmoid(g)`, and the
197
+ quantisation done as a **multiply by the reciprocal** `1/s` rather than a divide by `s` — differs from this
198
+ reference by relative Frobenius error at most **2.4e-4** over the correctness shapes and two full-scale
199
+ shapes, six seeds each (all of it in `q`; the scales agree to 8e-8). The gate is **3.3x** that. The extra
200
+ headroom over the usual 2x is for exactly one thing: the reciprocal-vs-divide difference is a single ulp that
201
+ flips a small, seed-dependent fraction of codes, and that fraction has a tail. It still leaves the bf16-`y`
202
+ mistake 15x outside and every structural error 160x or more outside.
203
+
204
+ **fp8 output is required, not optional** — returning bf16 or fp16 values that happen to be numerically close
205
+ does not satisfy the contract.""",
206
+ ).validate()
tools/factory/specs/video_cfg_zero_star.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `video-cfg-zero-star-rescale` — the CFG-Zero* guidance combination: a per-sample projection
2
+ coefficient from two whole-latent dot products, then a rescaled classifier-free-guidance blend."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="video-cfg-zero-star-rescale",
11
+ title="Write a fast CFG-Zero* guidance-rescale kernel for video diffusion",
12
+ blurb=("Every video diffusion sampler runs the transformer twice per step and blends the two "
13
+ "predictions. CFG-Zero* replaces the naive blend with a rescaled one: it first projects the "
14
+ "unconditional prediction onto the conditional one — a pair of dot products over the ENTIRE "
15
+ "latent of each sample — and uses that coefficient to shrink the unconditional branch before "
16
+ "the guidance extrapolation. So a step that used to be one elementwise pass becomes a "
17
+ "whole-tensor reduction followed by a blend that cannot start until the reduction is finished, "
18
+ "over a gigabyte of predictions per denoising step."),
19
+ keywords=["mle", "kernel-generation", "video-diffusion", "classifier-free-guidance", "cfg-zero-star",
20
+ "guidance", "reduction", "dot-product", "sampler", "memory-bound"],
21
+ module="cfg_zero_star.py",
22
+ func="cfg_zero_star_rescale",
23
+ signature="cfg_zero_star_rescale(cond, uncond, guidance_scale)",
24
+ returns_doc="""CFG-Zero* rescaled classifier-free-guidance combination.
25
+
26
+ Args:
27
+ cond: (B, C, T, H, W) bfloat16 — the conditional model prediction.
28
+ uncond: (B, C, T, H, W) bfloat16 — the unconditional prediction.
29
+ guidance_scale: float — the guidance weight.
30
+
31
+ Returns:
32
+ (out, alpha) where
33
+ out: (B, C, T, H, W) bfloat16 — the guided prediction
34
+ alpha: (B,) float32 — the per-sample projection coefficient""",
35
+
36
+ reference_imports="import torch",
37
+ reference_src='''
38
+ EPS = 1e-8
39
+
40
+
41
+ def cfg_zero_star_rescale(cond, uncond, guidance_scale):
42
+ """Per-sample projection coefficient, then the rescaled guidance blend.
43
+
44
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. It walks the batch
45
+ so the fp32 intermediates stay bounded.
46
+ """
47
+ B = cond.shape[0]
48
+ alpha = torch.empty(B, device=cond.device, dtype=torch.float32)
49
+ out = torch.empty_like(cond)
50
+ for b in range(B):
51
+ c = cond[b].float().reshape(-1)
52
+ u = uncond[b].float().reshape(-1)
53
+ num = torch.dot(c, u) # <cond, uncond>
54
+ den = torch.dot(u, u) # ||uncond||^2
55
+ a = num / (den + EPS)
56
+ alpha[b] = a
57
+ proj = u * a # the projected unconditional branch
58
+ out[b] = (proj + guidance_scale * (c - proj)).reshape(cond.shape[1:]).to(torch.bfloat16)
59
+ return out, alpha
60
+ ''',
61
+ make_inputs_src='''
62
+ def _mk(B, C, T, H, W, seed):
63
+ gen = torch.Generator(device="cuda").manual_seed(seed)
64
+ # the two branches come from the SAME model on the same latent, so they are strongly correlated --
65
+ # which is precisely why the projection coefficient sits near 1 and why the blend cancels
66
+ base = torch.randn(B, C, T, H, W, device="cuda", generator=gen)
67
+ cond = (base + 0.30 * torch.randn(B, C, T, H, W, device="cuda", generator=gen)).to(torch.bfloat16)
68
+ uncond = (base + 0.32 * torch.randn(B, C, T, H, W, device="cuda", generator=gen)).to(torch.bfloat16)
69
+ return cond, uncond, 5.0
70
+ ''',
71
+ flops_src='''
72
+ def canonical_work(B, C, T, H, W):
73
+ """BYTES moved, from the SHAPE ALONE: one bf16 read of each prediction and one bf16 write.
74
+
75
+ That is the floor: a kernel that had the reduction for free would touch exactly these bytes. The
76
+ (B,) coefficient is negligible. This is a bandwidth kernel, so the score is achieved GB/s against this
77
+ fixed byte count.
78
+ """
79
+ return 3 * (B * C * T * H * W * 2)
80
+ ''',
81
+
82
+ metric="GB/s",
83
+ compare="tuple",
84
+ tuple_names=("out", "alpha"),
85
+ tol=3e-4,
86
+ shape_names=("B", "C", "T", "H", "W"),
87
+ grader_shapes=[(48, 16, 21, 90, 160), (32, 16, 33, 90, 160), (80, 16, 25, 68, 120),
88
+ (24, 32, 21, 90, 160), (56, 16, 33, 68, 120)],
89
+ measure_shapes=[(40, 16, 21, 90, 160), (28, 16, 33, 90, 160), (64, 16, 25, 68, 120),
90
+ (20, 32, 21, 90, 160), (48, 16, 33, 68, 120)],
91
+ measure_quick_shapes=[(8, 16, 13, 45, 80), (4, 16, 21, 45, 80), (16, 16, 9, 30, 52)],
92
+ correct_shapes=[(3, 16, 5, 13, 19), (2, 32, 3, 11, 17), (7, 16, 4, 9, 23), (1, 8, 7, 15, 13)],
93
+
94
+ spec_md="""Two dot products per sample, over the **whole** latent — every channel, frame, row and
95
+ column — then an elementwise blend.
96
+
97
+ ```
98
+ num[b] = sum over (c, t, y, x) of cond[b,c,t,y,x] * uncond[b,c,t,y,x]
99
+ den[b] = sum over (c, t, y, x) of uncond[b,c,t,y,x] * uncond[b,c,t,y,x]
100
+ alpha[b] = num[b] / (den[b] + 1e-8)
101
+ ```
102
+
103
+ `alpha[b]` is the least-squares projection of the conditional prediction onto the unconditional one. The
104
+ blend then uses the **projected** unconditional branch instead of the raw one:
105
+
106
+ ```
107
+ proj[b,c,t,y,x] = uncond[b,c,t,y,x] * alpha[b]
108
+ out[b,c,t,y,x] = proj + guidance_scale * (cond - proj)
109
+ ```
110
+
111
+ Setting `alpha = 1` recovers ordinary classifier-free guidance; the whole point of the method is that
112
+ `alpha` is *not* 1, and that it is computed **per sample**, not once for the batch.
113
+
114
+ `guidance_scale` is a python float, the same for every sample. `1e-8` is added to the denominator exactly
115
+ as written.
116
+
117
+ `/app/reference.py` walks the batch, takes the two dot products in fp32 and applies the blend. That is the
118
+ exact specification; it is deliberately simple rather than fast.""",
119
+
120
+ contract_md="""| arg | shape | dtype | meaning |
121
+ |-----|-------|-------|---------|
122
+ | `cond` | `(B, C, T, H, W)` | `bfloat16` | conditional prediction, contiguous |
123
+ | `uncond` | `(B, C, T, H, W)` | `bfloat16` | unconditional prediction, same shape and layout |
124
+ | `guidance_scale` | python `float` | | guidance weight; around 5 at every graded shape |
125
+
126
+ **Return** a 2-tuple `(out, alpha)` **in that order**:
127
+
128
+ | out | shape | dtype |
129
+ |-----|-------|-------|
130
+ | `out` | `(B, C, T, H, W)` | **bfloat16** |
131
+ | `alpha` | `(B,)` | **float32** — one coefficient per sample |
132
+
133
+ Both are graded and the grader scores the worse of the two. All inputs are **read-only** — the op is
134
+ functional, do not write into `cond` or `uncond`.
135
+
136
+ `C*T*H*W` is not a multiple of any tile size (the correctness shapes include `(16, 5, 13, 19)` and
137
+ `(16, 4, 9, 23)`), and `B` is not either.""",
138
+
139
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in
140
+ 24–80 — one entry per prediction in flight, i.e. the serving batch, since a single video's latent is far
141
+ too small to keep a GPU busy on its own — `C` in 16–32 latent channels, `T` in 21–33 latent frames, `H` in
142
+ 68–90 and `W` in 120–160. One call moves 1.3-1.5 GB and it runs once per denoising step.""",
143
+
144
+ correctness_md="""**Both** returned tensors must match the reference (evaluated in fp32) within
145
+ **relative error `3e-4`** at every graded shape, including the timed ones; the grader scores the **worse**
146
+ of the two.
147
+
148
+ That gate is **measured**, and a kernel that skips this task's distinguishing work misses it by orders of
149
+ magnitude: using `alpha = 1` — i.e. ordinary classifier-free guidance — scores **2.5e-1**; computing one
150
+ `alpha` for the whole batch instead of one per sample scores **1.3e-2**; putting `||cond||^2` in the
151
+ denominator instead of `||uncond||^2` scores **2.6e-1**; and applying the guidance to the raw
152
+ unconditional branch (`uncond + scale*(cond - uncond)`, then scaling by alpha) scores **2.4e-1**. All are
153
+ 40x to 900x the tolerance.""",
154
+
155
+ perf_md="""`canonical_work` counts the ideal floor — one read of each prediction and one write — and a
156
+ kernel cannot quite reach it, because `alpha[b]` depends on **every** element of sample `b` and nothing can
157
+ be written until it is known. Two shapes of solution, and it is worth measuring both:
158
+
159
+ * **Two passes.** Pass 1 reduces `cond*uncond` and `uncond*uncond` per sample into `(B,)` accumulators;
160
+ pass 2 re-reads both tensors and writes the blend. That is 4 reads and 1 write against the floor's 3, so
161
+ the ceiling is about 60% of peak bandwidth. Pass 1 is read-only and streams perfectly; keep both partial
162
+ sums in the same pass so each element is loaded once, not twice.
163
+ * **One pass with a grid-wide barrier.** A persistent kernel sized to the device's SM count can hold a
164
+ slab of both tensors in L2 between the reduction and the blend. At the graded sizes the pair is 1 GB, so
165
+ only a fraction of it stays resident — but the fraction that does is a real saving, and the barrier
166
+ itself is cheap compared with a second full HBM pass.
167
+
168
+ Either way the reduction is the interesting part: it is two independent sums per sample over up to 5x10^6
169
+ elements, so use a two-stage tree (block partials into a small `(num_blocks, B, 2)` buffer, then a tiny
170
+ second kernel) or fp32 atomics. Do **not** materialise the elementwise products — `cond*uncond` as a
171
+ tensor is another gigabyte.
172
+
173
+ The epilogue is fully fusible: `out = alpha*(1 - scale)*uncond + scale*cond` is two fused multiply-adds
174
+ once `alpha` is in a register, and both coefficients are per sample, so they are loaded once per block.
175
+
176
+ `B` is large and each sample is contiguous, so the natural decomposition is a flat grid over elements with
177
+ the sample index derived by division — precompute the per-sample element count on the host and pass it as
178
+ a constant rather than dividing per element.""",
179
+
180
+ precision_md="""`cond`, `uncond` and `out` are **bfloat16**; both dot products, `alpha` and the blend
181
+ are **fp32**.
182
+
183
+ The reduction runs over up to 5x10^6 elements per sample, so accumulate in fp32 with a tree or two-stage
184
+ reduction. A bf16 accumulator is hopeless here, and even a single fp32 running scalar chained over
185
+ millions of elements drifts: the two sums are of strictly positive-ish quantities (the branches are highly
186
+ correlated, so `cond*uncond` rarely changes sign), which means the error accumulates rather than cancels.
187
+
188
+ `alpha` is **float32** and is checked at the same gate. It is `B` values, so keeping it wide costs nothing.
189
+
190
+ Note the blend **cancels**: with `guidance_scale` around 5 and `alpha` near 0.9, `out` is a difference of
191
+ two quantities several times its own size, so it inherits roughly a 3x amplification of any error in
192
+ `alpha`. That is the real behaviour of guidance and the tolerance is measured with it in place.
193
+
194
+ **fp8 is not useful here** and is not expected: this is a bandwidth kernel with a fixed bf16 output.
195
+
196
+ **Where the tolerance comes from.** `3e-4` is measured, not inherited. A second, independent implementation
197
+ — the two reductions computed as a chunked pass over a flattened view with per-chunk fp32 partials
198
+ combined at the end (a completely different summation order from `torch.dot`), and the blend folded as
199
+ `alpha*(1-scale)*uncond + scale*cond` — differs from this reference by relative Frobenius error **1.4e-4**
200
+ at worst over the correctness shapes and **1.3e-4** at a graded-scale shape. It is the bf16 rounding of
201
+ `out`, amplified by the cancellation described above, and it does not grow with the volume. The tolerance
202
+ is **2.1x** that.""",
203
+ ).validate()
tools/factory/specs/zamba_shared_attn_lora_backward.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `zamba-shared-attn-lora-backward` — the training-side backward of the Zamba-2 shared attention
2
+ block's QKV projection: frozen shared weight, L per-depth LoRA adapters, concatenated input."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ _FWD = '''
10
+ def _shared_qkv(h, emb, w_qkv, lora_a, lora_b, scaling):
11
+ """The fp32 forward of `zamba-shared-attn-lora-qkv`, differentiable. Autograd through THIS defines
12
+ every gradient this task asks for."""
13
+ L, T, Dm = h.shape
14
+ outs = []
15
+ for l in range(L):
16
+ xc = torch.cat([h[l], emb], dim=-1) # (T, 2*Dm) [state | embedding]
17
+ base = xc @ w_qkv.t()
18
+ delta = (xc @ lora_a[l].t()) @ lora_b[l].t()
19
+ outs.append(base + scaling * delta)
20
+ return torch.stack(outs, 0)
21
+
22
+
23
+ def shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv):
24
+ """The baseline re-runs the fp32 forward under autograd. The shared weight is FROZEN: only the two
25
+ activations and the L adapters receive gradients."""
26
+ ins = [t.detach().clone().float().requires_grad_(True) for t in (h, emb, lora_a, lora_b)]
27
+ o = _shared_qkv(ins[0], ins[1], w_qkv.float(), ins[2], ins[3], scaling)
28
+ return torch.autograd.grad(o, ins, dqkv.float())
29
+ '''
30
+
31
+ SPEC = TaskSpec(
32
+ name="zamba-shared-attn-lora-backward",
33
+ title="Write a fast backward kernel for the shared-attention-block QKV projection",
34
+ blurb=("Fine-tuning a Zamba-style hybrid means differentiating a block that was called at L different "
35
+ "depths with one frozen weight and L different rank-64 adapters, over an input that was a "
36
+ "concatenation of the depth's residual stream and the model's original embedding. So the "
37
+ "embedding's gradient is a sum over EVERY depth, each adapter's gradient is a pair of tall-skinny "
38
+ "reductions over the token axis, and the frozen weight is read L times and never updated."),
39
+ keywords=["mle", "kernel-generation", "zamba", "hybrid", "shared-attention", "lora", "multi-adapter",
40
+ "backward", "training", "gemm", "compute-bound"],
41
+ module="shared_qkv_bwd.py",
42
+ func="shared_qkv_backward",
43
+ signature="shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv)",
44
+ returns_doc="""Backward of the shared attention-block QKV projection (frozen base, L LoRA adapters).
45
+
46
+ Args:
47
+ h: (L, T, Dm) bfloat16 — residual stream at each depth, saved by the forward.
48
+ emb: (T, Dm) bfloat16 — the shared original embedding, saved by the forward.
49
+ w_qkv: (3*Dm, 2*Dm) bfloat16 — the shared projection. FROZEN: no gradient is returned for it.
50
+ lora_a: (L, r, 2*Dm) bfloat16 — per-depth LoRA down-projection.
51
+ lora_b: (L, 3*Dm, r) bfloat16 — per-depth LoRA up-projection.
52
+ scaling: float — the LoRA scale (alpha / r).
53
+ dqkv: (L, T, 3*Dm) bfloat16 — incoming gradient w.r.t. the fused QKV output.
54
+
55
+ Returns:
56
+ (dh, demb, dlora_a, dlora_b) with shapes
57
+ (L, T, Dm), (T, Dm), (L, r, 2*Dm), (L, 3*Dm, r).""",
58
+
59
+ reference_imports="import torch",
60
+ reference_src=_FWD,
61
+ make_inputs_src='''
62
+ def _mk(L, T, Dm, r, seed):
63
+ """Saved forward inputs plus the incoming gradient. The adapters are scaled so the LoRA delta is a real
64
+ but minority part of the forward (RMS `16/r` of the base projection), which is what a trained LoRA
65
+ looks like."""
66
+ gen = torch.Generator(device="cuda").manual_seed(seed)
67
+
68
+ def rnd(*sh, s=1.0):
69
+ return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
70
+
71
+ h = rnd(L, T, Dm)
72
+ emb = rnd(T, Dm)
73
+ w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5)
74
+ lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5)
75
+ lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5)
76
+ dqkv = rnd(L, T, 3 * Dm)
77
+ return h, emb, w_qkv, lora_a, lora_b, 16.0 / r, dqkv
78
+ ''',
79
+ flops_src='''
80
+ def canonical_work(L, T, Dm, r):
81
+ """FLOPs attributed to one backward call, from the SHAPE ALONE.
82
+
83
+ Per depth, at 2 FLOPs per multiply-add:
84
+ * ONE pass of the big shared shape: dxc = dqkv @ w_qkv (the base weight is frozen,
85
+ so there is no dw_qkv and no second pass over it)
86
+ * THREE passes of the (2*Dm, r) adapter shape: recompute mid = xc @ lora_a.T (the LoRA output is a
87
+ forward temporary), dxc += dmid @ lora_a, dlora_a = dmid.T @ xc
88
+ * TWO passes of the (3*Dm, r) adapter shape: dmid = dqkv @ lora_b, dlora_b = dqkv.T @ mid
89
+ The concatenation, the split of dxc and the sum of demb over depths are O(L*T*Dm) data movement and
90
+ are not credited.
91
+ """
92
+ return L * (2 * T * (2 * Dm) * (3 * Dm)
93
+ + 3 * (2 * T * (2 * Dm) * r)
94
+ + 2 * (2 * T * (3 * Dm) * r))
95
+ ''',
96
+ flops_formula=("canonical_work(L, T, Dm, r) = L * ( 2*T*(2*Dm)*(3*Dm) # dxc = dqkv @ w_qkv\n"
97
+ " + 3 * 2*T*(2*Dm)*r # mid, dxc +=, dlora_a\n"
98
+ " + 2 * 2*T*(3*Dm)*r ) # dmid, dlora_b"),
99
+
100
+ metric="TFLOP/s",
101
+ compare="tuple",
102
+ tuple_names=("dh", "demb", "dlora_a", "dlora_b"),
103
+ tol=6e-3, # MEASURED: 2.07x the 2.90e-3 worst gap to an independent hand-written bf16 backward
104
+ shape_names=("L", "T", "Dm", "r"),
105
+ grader_shapes=[(6, 4096, 2048, 64), (4, 4096, 2560, 64), (8, 2048, 2048, 32),
106
+ (6, 3072, 2048, 128), (4, 6144, 2048, 64)],
107
+ measure_shapes=[(6, 3584, 2048, 64), (4, 3584, 2560, 64), (8, 1792, 2048, 32),
108
+ (6, 2560, 2048, 128), (4, 5120, 2048, 64)],
109
+ measure_quick_shapes=[(4, 512, 1024, 32), (2, 1024, 512, 16), (6, 256, 1024, 64)],
110
+ correct_shapes=[(2, 256, 256, 16), (3, 129, 128, 8), (4, 512, 512, 32), (2, 64, 128, 4)],
111
+
112
+ spec_md="""The forward being differentiated is the shared attention block's QKV projection, called at
113
+ `L` depths with one shared weight and a per-depth LoRA adapter:
114
+
115
+ ```
116
+ xc[l] = concat( h[l], emb ) # (T, 2*Dm), state first
117
+ mid[l] = xc[l] @ lora_a[l].T # (T, r)
118
+ qkv[l] = xc[l] @ w_qkv.T + scaling * mid[l] @ lora_b[l].T
119
+ ```
120
+
121
+ `w_qkv` is **frozen** — this is adapter fine-tuning, so no gradient is produced for it and it is never
122
+ transposed-reduced over the token axis. Given `dqkv` you must return four things:
123
+
124
+ ```
125
+ dmid[l] = scaling * ( dqkv[l] @ lora_b[l] ) # (T, r)
126
+ dxc[l] = dqkv[l] @ w_qkv + dmid[l] @ lora_a[l] # (T, 2*Dm)
127
+ dlora_a[l] = dmid[l].T @ xc[l] # (r, 2*Dm)
128
+ dlora_b[l] = scaling * ( dqkv[l].T @ mid[l] ) # (3*Dm, r)
129
+ ```
130
+
131
+ and then the concatenation is undone:
132
+
133
+ ```
134
+ dh[l] = dxc[l][:, :Dm]
135
+ demb = sum over ALL l of dxc[l][:, Dm:]
136
+ ```
137
+
138
+ **`demb` is a sum over every depth.** The same embedding tensor was fed to all `L` invocations, so its
139
+ gradient collects a contribution from each one — this is the piece that makes the backward of a *shared*
140
+ block different from `L` independent backwards.
141
+
142
+ Note that `mid[l]` was a forward temporary and is not an argument: `dlora_b` needs it, so it must be
143
+ recomputed.
144
+
145
+ `/app/reference.py` re-runs the fp32 forward under autograd and differentiates it. That is the exact
146
+ specification; it is deliberately simple rather than fast.""",
147
+
148
+ contract_md="""| arg | shape | dtype | meaning |
149
+ |-----|-------|-------|---------|
150
+ | `h` | `(L, T, Dm)` | `bfloat16` | residual stream at each depth |
151
+ | `emb` | `(T, Dm)` | `bfloat16` | shared original embedding |
152
+ | `w_qkv` | `(3*Dm, 2*Dm)` | `bfloat16` | shared projection, **frozen** |
153
+ | `lora_a` | `(L, r, 2*Dm)` | `bfloat16` | per-depth LoRA down |
154
+ | `lora_b` | `(L, 3*Dm, r)` | `bfloat16` | per-depth LoRA up |
155
+ | `scaling` | float | | LoRA scale `alpha / r` |
156
+ | `dqkv` | `(L, T, 3*Dm)` | `bfloat16` | incoming gradient w.r.t. the fused QKV output |
157
+
158
+ **Return a 4-tuple in exactly this order:** `dh (L, T, Dm)`, `demb (T, Dm)`, `dlora_a (L, r, 2*Dm)`,
159
+ `dlora_b (L, 3*Dm, r)`.
160
+
161
+ `dh` and `demb` may be bf16 or fp32; the two adapter gradients should be **fp32** — each is a reduction
162
+ over every token. **No gradient is returned for `w_qkv`.** The concatenation order is `[h[l] ‖ emb]`, so
163
+ `dh` comes from the first `Dm` channels of `dxc` and `demb` from the last `Dm`, summed over depths.
164
+
165
+ All inputs are **read-only**. `T` is **not** guaranteed to be a multiple of any tile size (the correctness
166
+ shapes include `T = 129`), and `r` is as small as 4.""",
167
+
168
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L` in
169
+ 4–8, `T` in 2048–6144, `Dm` in 2048–2560, `r` in 32–128. One big matmul per depth dominates the FLOPs; the
170
+ adapter work is a few percent of it and most of the difficulty.""",
171
+
172
+ correctness_md="""**All four** returned tensors must match the reference (evaluated in fp32) within
173
+ **relative Frobenius error `6e-3`** at every graded shape, including the timed ones; the grader scores the
174
+ **worst** of the four.
175
+
176
+ That gate is **measured**, and the two structural mistakes this task invites miss it badly: taking `demb`
177
+ from depth 0 instead of summing over **all** depths scores **0.70–0.91**, and omitting the adapter's
178
+ contribution `dmid @ lora_a` from `dxc` scores **0.124** at the largest graded shape (0.45–0.97 at the
179
+ small ones) — 21x the tolerance at worst.""",
180
+
181
+ perf_md="""`L` big matmuls against one frozen weight, plus four tall-skinny ones per depth, plus a
182
+ reduction that ties all the depths together.
183
+
184
+ **The frozen weight is read `L` times if you let it be.** `w_qkv` is 40–65 MB; a persistent grid that
185
+ walks all `L` depths per weight tile pays for it once. Note the transpose: the backward needs
186
+ `dqkv @ w_qkv` (not `w_qkv.T`), so the reduction runs over the `3*Dm` axis — plan the layout for that
187
+ rather than transposing a 65 MB tensor at run time.
188
+
189
+ **`demb` is a cross-depth reduction.** Do not build `L` copies of `dxc[:, Dm:]` and add them afterwards:
190
+ that is `L` extra full-size writes and reads. Accumulate into one fp32 `(T, Dm)` buffer as each depth's
191
+ tile is produced — with `L <= 8` a deterministic tree or a per-depth atomic-free accumulation over a
192
+ partition of the token axis both work, and both beat materialising the intermediates.
193
+
194
+ **Fuse the adapter path.** `mid[l]` and `dmid[l]` are `(T, r)` with `r <= 128`. Both belong in shared
195
+ memory: recompute `mid` from the `xc` tile you already have, form `dmid` from the `dqkv` tile you already
196
+ have, and feed both straight into the two weight-gradient reductions. An autograd-shaped implementation
197
+ sends four `(T, r)` tensors and two `(T, 2*Dm)` tensors through HBM per depth for a delta worth a few
198
+ percent of the arithmetic.
199
+
200
+ **`dlora_a` and `dlora_b` are split-K reductions** over the token axis into tiny outputs (`r x 2*Dm` and
201
+ `3*Dm x r`). Use fp32 accumulators and a cross-block reduction; do not use one atomic per element.
202
+
203
+ `xc` should never be materialised: its first half is `h[l]`, its second half is `emb`, and every consumer
204
+ can read them separately.""",
205
+
206
+ precision_md="""Inputs are **bfloat16**; accumulate every matmul, the `demb` cross-depth sum and both
207
+ adapter-gradient reductions in **fp32**.
208
+
209
+ `demb` sums `L` full-size contributions and the adapter gradients sum over up to 6144 tokens — a bf16
210
+ accumulator in either place gives an error that *grows* with the problem size, which the faithfulness
211
+ clause below rejects.
212
+
213
+ **fp8 is not appropriate here**: the saved activations arrive in bf16 and re-quantising them is an
214
+ approximation of the specified computation.
215
+
216
+ **Where the tolerance comes from.** `1e-2` is measured. A second, independent implementation — the
217
+ analytic backward written out by hand, all `L` depths batched into `bmm`s, `xc` never materialised, the
218
+ adapter gradients accumulated in a different order from autograd's — differs from this fp32 autograd
219
+ reference by a worst relative Frobenius error of **2.90e-3** across the correctness shapes and two
220
+ full-size graded shapes, over several seeds. The tolerance is **2.07x** that, and the error *falls* with
221
+ problem size (2.37e-3 at the large shapes) — it is the bf16 rounding of the operands, nothing more.""",
222
+ ).validate()
tools/factory/specs/zamba_shared_attn_lora_qkv.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `zamba-shared-attn-lora-qkv` — the Zamba-2 shared attention block's QKV projection: one shared
2
+ weight applied at L depths, each with its own LoRA adapter, over a concatenated [state ‖ embedding] input."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="zamba-shared-attn-lora-qkv",
11
+ title="Write a fast shared-attention-block QKV kernel (one weight, L per-depth LoRA adapters)",
12
+ blurb=("Zamba-2 does not give every attention layer its own weights — it has ONE attention block and "
13
+ "calls it at several depths of a Mamba stack, feeding it the concatenation of the current "
14
+ "residual stream and the original token embedding, and giving each invocation its own low-rank "
15
+ "adapter so the shared weights can still specialise. The QKV projection therefore runs L times "
16
+ "against the same 50 MB of weights with L different rank-64 deltas, and done as L separate "
17
+ "library calls the shared weight is re-read from HBM every time and the adapters get three "
18
+ "extra launches each."),
19
+ keywords=["mle", "kernel-generation", "zamba", "hybrid", "shared-attention", "lora", "multi-adapter",
20
+ "gemm", "fusion", "compute-bound"],
21
+ module="shared_qkv.py",
22
+ func="shared_block_qkv",
23
+ signature="shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling)",
24
+ returns_doc="""Shared attention-block QKV projection with a per-depth LoRA adapter.
25
+
26
+ Args:
27
+ h: (L, T, Dm) bfloat16 — the residual stream at each of the L depths the block is called at.
28
+ emb: (T, Dm) bfloat16 — the ORIGINAL token embedding, concatenated at every depth.
29
+ w_qkv: (3*Dm, 2*Dm) bfloat16 — the SHARED qkv projection, nn.Linear layout (out, in).
30
+ lora_a: (L, r, 2*Dm) bfloat16 — per-depth LoRA down-projection.
31
+ lora_b: (L, 3*Dm, r) bfloat16 — per-depth LoRA up-projection.
32
+ scaling: float — the LoRA scale (alpha / r).
33
+
34
+ Returns:
35
+ qkv: (L, T, 3*Dm), bfloat16 or float32 — must match /app/reference.py numerically.""",
36
+
37
+ reference_imports="import torch",
38
+ reference_src='''
39
+ def shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling):
40
+ """One depth at a time: concatenate, project with the shared weight, add the depth's LoRA delta.
41
+
42
+ Correct and simple — it is the numerical SPECIFICATION, not a performance target. The shared weight is
43
+ re-read for every depth and the rank-wide intermediate goes to HBM.
44
+ """
45
+ L, T, Dm = h.shape
46
+ out = torch.empty(L, T, 3 * Dm, device=h.device, dtype=torch.float32)
47
+ w = w_qkv.float()
48
+ e = emb.float()
49
+ for l in range(L):
50
+ xc = torch.cat([h[l].float(), e], dim=-1) # (T, 2*Dm) [state | embedding]
51
+ base = xc @ w.t() # the SHARED projection
52
+ delta = (xc @ lora_a[l].float().t()) @ lora_b[l].float().t()
53
+ out[l] = base + scaling * delta
54
+ return out.to(torch.bfloat16)
55
+ ''',
56
+ make_inputs_src='''
57
+ def _mk(L, T, Dm, r, seed):
58
+ """Per-depth residual streams, one shared embedding, the shared weight and L LoRA adapters.
59
+
60
+ The adapters are scaled so the delta is a real but minority contribution (its RMS is `16/r` of the
61
+ base projection's), which is what a trained LoRA looks like — big enough that ignoring it is obvious,
62
+ small enough that it is a correction rather than the answer.
63
+ """
64
+ gen = torch.Generator(device="cuda").manual_seed(seed)
65
+
66
+ def rnd(*sh, s=1.0):
67
+ return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
68
+
69
+ h = rnd(L, T, Dm)
70
+ emb = rnd(T, Dm)
71
+ w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5)
72
+ lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5)
73
+ lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5)
74
+ return h, emb, w_qkv, lora_a, lora_b, 16.0 / r
75
+ ''',
76
+ flops_src='''
77
+ def canonical_work(L, T, Dm, r):
78
+ """FLOPs attributed to one call, from the SHAPE ALONE.
79
+
80
+ Per depth, at 2 FLOPs per multiply-add: the shared projection (T, 2*Dm) x (2*Dm, 3*Dm), the adapter's
81
+ down-projection (T, 2*Dm) x (2*Dm, r) and its up-projection (T, r) x (r, 3*Dm). The concatenation and
82
+ the residual add are O(T*Dm) data movement and are not credited.
83
+ """
84
+ return L * (2 * T * (2 * Dm) * (3 * Dm) + 2 * T * (2 * Dm) * r + 2 * T * r * (3 * Dm))
85
+ ''',
86
+ flops_formula=("canonical_work(L, T, Dm, r) = L * ( 2*T*(2*Dm)*(3*Dm) + 2*T*(2*Dm)*r + 2*T*r*(3*Dm) )\n"
87
+ "# shared projection LoRA down LoRA up"),
88
+
89
+ metric="TFLOP/s",
90
+ compare="tensor",
91
+ tol=7e-3, # MEASURED: 2.1x the 3.30e-3 worst gap to an independent batched-bmm implementation
92
+ shape_names=("L", "T", "Dm", "r"),
93
+ grader_shapes=[(6, 4096, 2048, 64), (4, 4096, 2560, 64), (8, 2048, 2048, 32),
94
+ (6, 3072, 2048, 128), (4, 6144, 2048, 64)],
95
+ measure_shapes=[(6, 3584, 2048, 64), (4, 3584, 2560, 64), (8, 1792, 2048, 32),
96
+ (6, 2560, 2048, 128), (4, 5120, 2048, 64)],
97
+ measure_quick_shapes=[(4, 512, 1024, 32), (2, 1024, 512, 16), (6, 256, 1024, 64)],
98
+ correct_shapes=[(2, 256, 256, 16), (3, 129, 128, 8), (4, 512, 512, 32), (2, 64, 128, 4)],
99
+
100
+ spec_md="""A Zamba-style hybrid stack has **one** attention block, invoked at `L` different depths of a
101
+ Mamba backbone. Two things make its QKV projection unusual.
102
+
103
+ **1 — the input is a concatenation.** At every depth the block sees the current residual stream *and* the
104
+ original token embedding, glued along the feature axis:
105
+
106
+ ```
107
+ xc[l] = concat( h[l], emb ) # (T, 2*Dm) — state first, embedding second
108
+ ```
109
+
110
+ `emb` is the **same** tensor at every depth: it is the model's input embedding, re-fed so the shared block
111
+ always has the original token available no matter how deep it is being called.
112
+
113
+ **2 — the weights are shared, the adapters are not.** One `(3*Dm, 2*Dm)` projection serves every depth,
114
+ and each depth gets its own rank-`r` LoRA delta:
115
+
116
+ ```
117
+ qkv[l] = xc[l] @ w_qkv.T + scaling * ( xc[l] @ lora_a[l].T ) @ lora_b[l].T
118
+ ```
119
+
120
+ That is the whole computation: `L` applications of one big shared GEMM, each with its own tiny two-matmul
121
+ correction. The output layout is the usual fused one — `qkv[l][:, 0:Dm]` is Q, `[Dm:2*Dm]` is K,
122
+ `[2*Dm:3*Dm]` is V — but nothing here needs to know that; you return the fused tensor.
123
+
124
+ `/app/reference.py` loops over depths and materialises the concatenation and the rank-wide intermediate for
125
+ each. That is the exact specification; it is deliberately simple rather than fast.""",
126
+
127
+ contract_md="""| arg | shape | dtype | meaning |
128
+ |-----|-------|-------|---------|
129
+ | `h` | `(L, T, Dm)` | `bfloat16` | residual stream at each of the `L` invocation depths |
130
+ | `emb` | `(T, Dm)` | `bfloat16` | the original token embedding, **shared** across depths |
131
+ | `w_qkv` | `(3*Dm, 2*Dm)` | `bfloat16` | the shared projection, `nn.Linear` layout `(out, in)` |
132
+ | `lora_a` | `(L, r, 2*Dm)` | `bfloat16` | per-depth LoRA down-projection |
133
+ | `lora_b` | `(L, 3*Dm, r)` | `bfloat16` | per-depth LoRA up-projection |
134
+ | `scaling` | float | | LoRA scale `alpha / r`, a Python float |
135
+
136
+ **Return** a single tensor `qkv` of shape `(L, T, 3*Dm)`, bfloat16 or float32 (the grader compares in
137
+ fp32).
138
+
139
+ The concatenation order is **`[h[l] ‖ emb]`** — state in channels `[0, Dm)`, embedding in `[Dm, 2*Dm)` —
140
+ and `w_qkv`'s columns are laid out to match. All inputs are **read-only**. `T` is **not** guaranteed to be
141
+ a multiple of any tile size (the correctness shapes include `T = 129`), and `r` is as small as 4.""",
142
+
143
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L`
144
+ (invocation depths) in 4–8, `T` (tokens) in 2048–6144, `Dm` in 2048–2560, `r` in 32–128. The shared weight
145
+ is 40–65 MB and is used `L` times; the `L` adapters together are a few megabytes. That ratio is the whole
146
+ design of the layer and it should be the whole design of your kernel.""",
147
+
148
+ correctness_md="""The returned tensor must match the reference (evaluated in fp32) within **relative
149
+ Frobenius error `7e-3`** at every graded shape, including the timed ones.
150
+
151
+ That gate is **measured**, and the plausible ways to get this wrong miss it by a wide margin: dropping the
152
+ LoRA delta entirely scores **0.12–0.24** at the graded shapes (0.45–0.97 at the small ones, where `r` is
153
+ a larger fraction of the width), using depth 0's adapter for every depth scores **0.16–0.30**, and
154
+ concatenating `[emb ‖ h[l]]` instead of `[h[l] ‖ emb]` scores **1.41** — the closest is **18x** the
155
+ tolerance.""",
156
+
157
+ perf_md="""One big GEMM done `L` times against the same weight, plus `2L` tiny ones. Three things
158
+ decide the score.
159
+
160
+ **Read the shared weight once.** `w_qkv` is 40–65 MB; `L` separate `torch.matmul` calls stream it from HBM
161
+ `L` times. A kernel that tiles over `(depth, token)` blocks with the weight tile resident — or a persistent
162
+ grid that walks all `L` depths for each weight tile — pays for it once. At `L = 8` that is the difference
163
+ between 500 MB and 60 MB of weight traffic.
164
+
165
+ **Never materialise the concatenation.** `xc[l]` is `(T, 2*Dm)` and half of it is `emb`, which is the same
166
+ for every depth. Building it explicitly costs `L` writes and `L` reads of a tensor twice the size of `h`.
167
+ The GEMM's K-loop can simply read the first `Dm` steps from `h[l]` and the next `Dm` from `emb` — the
168
+ operands are contiguous within each half, and `emb`'s half is reused by all `L` depths, so it is a
169
+ shared-memory tile you load once.
170
+
171
+ **Fuse the adapter.** The rank-wide intermediate `xc @ lora_a[l].T` is `(T, r)` with `r <= 128` — a few
172
+ hundred kilobytes. It has no business in HBM: compute it into shared memory while the tile is resident,
173
+ then accumulate `scaling * (that) @ lora_b[l].T` straight into the same accumulator the shared projection
174
+ is building. Done separately, the adapter costs a second full read of `xc`, two extra launches per depth,
175
+ and a round trip of the intermediate — on a delta that is a few percent of the arithmetic.
176
+
177
+ The `L` depths are completely independent, which is free parallelism for filling the machine at small `T`,
178
+ and `T` is ragged, so size the tail carefully.""",
179
+
180
+ precision_md="""Inputs are **bfloat16** and the output may be bf16 or fp32. Accumulate every matmul in
181
+ **fp32** — including the adapter's two, whose product is added to a much larger base term, so its own
182
+ rounding is amplified by nothing but must not be thrown away.
183
+
184
+ `scaling` is a Python float. Fold it into the adapter's up-projection or apply it to the rank-wide
185
+ intermediate; either is fine, but do it in fp32.
186
+
187
+ **fp8 is not appropriate here**: the weights and activations arrive in bf16 and re-quantising them is an
188
+ approximation of the specified computation, not an implementation of it.
189
+
190
+ **Where the tolerance comes from.** `1e-2` is measured. A second, independent implementation — all `L`
191
+ depths batched into one `bmm` against a broadcast weight, the concatenation formed implicitly by splitting
192
+ the K-loop, the LoRA fused as `xc @ (lora_a.T @ lora_b.T)` in the other association order, bf16 operands
193
+ with fp32 accumulate — differs from this fp32 reference by a worst relative Frobenius error of **3.30e-3**
194
+ across the correctness shapes and two full-size graded shapes, over several seeds. The tolerance is
195
+ **2.1x** that, and the error is flat in `L` and `T` (2.86e-3 at the large shapes) because it is the bf16
196
+ rounding of the operands and of the returned tensor and nothing else.""",
197
+ ).validate()
tools/factory/specs/zero3_param_regroup.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec for `zero3-param-regroup` — coalesce an MoE unit's parameters into fixed-capacity all-gather
2
+ buckets with a greedy first-fit walk, and emit the placement map."""
3
+ import pathlib
4
+ import sys
5
+
6
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
7
+ from spec import TaskSpec
8
+
9
+ SPEC = TaskSpec(
10
+ name="zero3-param-regroup",
11
+ title="Write a fast ZeRO-3 parameter regrouping kernel (greedy capacity bucketing)",
12
+ blurb=("ZeRO-3 does not all-gather 200 expert matrices one at a time — it coalesces them into "
13
+ "fixed-capacity buckets first, walking the parameter list in order and starting a new bucket "
14
+ "whenever the next tensor will not fit. Nothing may straddle a bucket, so the tail of every "
15
+ "bucket is a zeroed hole, and every parameter needs its (bucket, offset) recorded so the "
16
+ "gathered copy can be found again. It moves the whole unit and it decides how many collectives "
17
+ "the step issues."),
18
+ keywords=["mle", "kernel-generation", "zero3", "deepspeed", "fsdp", "bucketing", "all-gather",
19
+ "moe", "distributed", "training", "layout", "memory-bound"],
20
+ module="regroup.py",
21
+ func="zero3_param_regroup",
22
+ signature="zero3_param_regroup(src, numel, cap)",
23
+ returns_doc="""Coalesce parameters into fixed-capacity all-gather buckets.
24
+
25
+ Args:
26
+ src: (Ntot,) bfloat16 — the parameters concatenated back to back, in parameter order.
27
+ numel: (P,) int32 — element count of each parameter; sum(numel) == Ntot, max(numel) <= cap.
28
+ cap: int — bucket capacity in elements.
29
+
30
+ Returns:
31
+ (buckets, meta) where
32
+ buckets: (NB, cap) bfloat16 — the packed buckets; every unused slot EXACTLY zero
33
+ meta: (P, 2) int32 — per parameter: [bucket index, offset inside that bucket]""",
34
+
35
+ reference_imports="import torch",
36
+ reference_src='''
37
+ def zero3_param_regroup(src, numel, cap):
38
+ """Greedy first-fit packing, one parameter at a time.
39
+
40
+ Correct and simple — it is the SPECIFICATION, not a performance target. It syncs `numel` to the host,
41
+ walks the list in Python, zero-fills every bucket and then issues one slice copy per parameter.
42
+ """
43
+ ns = numel.tolist() # device -> host sync on the critical path
44
+ bid, off = [], []
45
+ cur, nb = 0, 1
46
+ for n in ns:
47
+ if cur + n > cap: # it does not fit -> close this bucket
48
+ nb += 1
49
+ cur = 0
50
+ bid.append(nb - 1)
51
+ off.append(cur)
52
+ cur += n
53
+
54
+ buckets = torch.zeros(nb, cap, device=src.device, dtype=src.dtype) # holes must end up EXACTLY zero
55
+ so = 0
56
+ for p, n in enumerate(ns):
57
+ buckets[bid[p], off[p]:off[p] + n] = src[so:so + n]
58
+ so += n
59
+
60
+ meta = torch.tensor([[b, o] for b, o in zip(bid, off)], device=src.device, dtype=torch.int32)
61
+ return buckets, meta
62
+ ''',
63
+ make_inputs_src='''
64
+ def _mk(L, D, F, E, CAPK, seed):
65
+ """An L-block MoE unit's bf16 parameters, in module order, plus the bucket capacity.
66
+
67
+ Per block: q/k/v/o with 4x GQA, a router, E experts of (gate, up, down), and two RMSNorm gains —
68
+ 120 to 250 tensors at the graded sizes, mostly identical expert matrices with a handful of tiny ones
69
+ mixed in, which is exactly the size profile that makes the greedy walk non-uniform.
70
+ """
71
+ gen = torch.Generator(device="cuda").manual_seed(seed)
72
+ ns = _numels(L, D, F, E)
73
+ src = (torch.randn(sum(ns), device="cuda", dtype=torch.float32, generator=gen) * 0.02).bfloat16()
74
+ return src, torch.tensor(ns, device="cuda", dtype=torch.int32), CAPK * 1024
75
+ ''',
76
+ flops_src='''
77
+ def _numels(L, D, F, E):
78
+ """Every parameter's element count, from the SHAPE ALONE."""
79
+ ns = []
80
+ for _ in range(L):
81
+ ns += [D * D, (D // 4) * D, (D // 4) * D, D * D, E * D] # q, k, v, o, router
82
+ for _ in range(E):
83
+ ns += [F * D, F * D, D * F] # expert gate, up, down
84
+ ns += [D, D] # the two RMSNorm gains
85
+ return ns
86
+
87
+
88
+ def _nbuckets(ns, cap):
89
+ """How many buckets the greedy first-fit walk produces. Depends only on the sizes, i.e. on the shape."""
90
+ cur, nb = 0, 1
91
+ for n in ns:
92
+ if cur + n > cap:
93
+ nb += 1
94
+ cur = 0
95
+ cur += n
96
+ return nb
97
+
98
+
99
+ def canonical_work(L, D, F, E, CAPK):
100
+ """BYTES attributed to one regroup, from the SHAPE ALONE.
101
+
102
+ Read every bf16 parameter once (2*Ntot) and write the whole bucket array once (2*NB*cap) -- the holes
103
+ are part of the output because they have to be zeroed. The (P, 2) placement map is negligible. Pure
104
+ data movement: the score is achieved bandwidth against that fixed byte count.
105
+ """
106
+ ns = _numels(L, D, F, E)
107
+ cap = CAPK * 1024
108
+ return 2 * sum(ns) + 2 * _nbuckets(ns, cap) * cap
109
+ ''',
110
+ flops_formula="""Ntot = sum(numel)
111
+ NB = number of buckets the greedy first-fit walk produces for these sizes and this capacity
112
+
113
+ canonical_work(L, D, F, E, CAPK) = 2*Ntot + 2*NB*cap # cap = CAPK * 1024
114
+
115
+ `numel` is the parameter list of an L-block MoE unit (q/k/v/o with 4x GQA, a router, E experts of
116
+ gate/up/down and two norm gains per block), so both `Ntot` and `NB` are functions of the shape and never of
117
+ the data.""",
118
+
119
+ metric="GB/s",
120
+ compare="tuple",
121
+ tuple_names=("buckets", "meta"),
122
+ tol=0.0,
123
+ shape_names=("L", "D", "F", "E", "CAPK"),
124
+ grader_shapes=[(6, 2048, 1408, 8, 24576), (5, 2048, 1408, 12, 32768),
125
+ (8, 1536, 1024, 8, 16384), (6, 2048, 1792, 6, 49152),
126
+ (7, 1792, 1280, 8, 24576)],
127
+ measure_shapes=[(5, 2048, 1408, 8, 32768), (4, 2048, 1408, 12, 24576),
128
+ (7, 1536, 1024, 8, 49152), (5, 2048, 1792, 6, 16384),
129
+ (6, 1792, 1280, 8, 32768)],
130
+ measure_quick_shapes=[(2, 512, 352, 4, 2048), (2, 384, 256, 8, 1024), (1, 640, 448, 6, 4096)],
131
+ correct_shapes=[(1, 128, 96, 3, 64), (2, 100, 70, 2, 48), (2, 64, 48, 5, 16),
132
+ (1, 96, 56, 4, 32), (3, 32, 24, 2, 8)],
133
+
134
+ spec_md="""Walk the parameters **in order**, keeping a running offset inside the current bucket:
135
+
136
+ ```
137
+ cur = 0 ; nb = 1
138
+ for p in 0 .. P-1:
139
+ if cur + numel[p] > cap: # it will not fit -> close the bucket and open the next
140
+ nb += 1
141
+ cur = 0
142
+ meta[p] = [nb - 1, cur]
143
+ cur += numel[p]
144
+ ```
145
+
146
+ `max(numel) <= cap` is guaranteed, so a parameter always fits in a freshly opened bucket and the walk never
147
+ stalls. Then copy:
148
+
149
+ ```
150
+ buckets[ meta[p,0], meta[p,1] : meta[p,1] + numel[p] ] = the p-th parameter's data
151
+ buckets[ everything else ] = 0.0 # EXACTLY zero
152
+ ```
153
+
154
+ Two things define the task. **No parameter may straddle a bucket** — that is the entire reason for the
155
+ greedy walk, because a bucket is one collective's payload and a tensor split across two of them could not be
156
+ found on the other side. And **the holes must be zero**, because the tail of the last bucket in particular
157
+ is a large region that the gathered copy will read.
158
+
159
+ The walk is a genuine sequential dependence: whether parameter `p` starts a new bucket depends on every
160
+ parameter before it. It is also entirely a function of `numel` — it never looks at a value — so it can be
161
+ computed once and reused for a given shape.
162
+
163
+ `/app/reference.py` does the walk in Python, zero-fills every bucket and then issues one slice copy per
164
+ parameter. That is the exact specification; it is deliberately simple rather than fast.""",
165
+
166
+ contract_md="""| arg | shape | dtype | meaning |
167
+ |-----|-------|-------|---------|
168
+ | `src` | `(Ntot,)` | `bfloat16` | the P parameters concatenated with no padding, in parameter order |
169
+ | `numel` | `(P,)` | `int32` | element count of each parameter; `sum(numel) == Ntot`, `max(numel) <= cap` |
170
+ | `cap` | scalar | `int` (python) | bucket capacity in **elements** |
171
+
172
+ **Return** a 2-tuple `(buckets, meta)` **in that order**:
173
+
174
+ | out | shape | dtype | notes |
175
+ |-----|-------|-------|-------|
176
+ | `buckets` | `(NB, cap)` | `bfloat16` | packed buckets; every unused element **exactly 0.0** |
177
+ | `meta` | `(P, 2)` | `int32` | `[bucket index, offset in that bucket]` per parameter |
178
+
179
+ `NB` is whatever the greedy walk produces — it is not passed in and it is not `ceil(Ntot/cap)`, because the
180
+ no-straddle rule wastes part of most buckets. Sizes are uneven: the expert matrices dominate, the routers
181
+ are three orders of magnitude smaller, and the norm gains smaller still. `src` and `numel` are read-only;
182
+ the call is functional.""",
183
+
184
+ regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L`
185
+ (blocks in the unit) 5–8, `D` 1536–2048, `F` (per-expert intermediate) 1024–1792, `E` (experts) 6–12, and a
186
+ bucket capacity `CAPK*1024` elements with `CAPK` in 16384–49152, i.e. **16–48 Mi elements (32–96 MB)** per
187
+ bucket. That is **330 M – 490 M bf16 parameters**, 120–250 tensors, 15–35 buckets, and 1.4–2.1 GB of
188
+ traffic. Bucket capacity is a real tuning knob: bigger buckets mean fewer collectives but more wasted tail,
189
+ and the graded shapes span both ends of it.""",
190
+
191
+ correctness_md="""**Both** returned values must match the reference **exactly** at every graded shape,
192
+ including the timed ones: `buckets` is a pure bf16 relayout, so the tolerance is **`0.0`** — every element,
193
+ including every zeroed hole — and `meta` is integer and compared elementwise.
194
+
195
+ There is no arithmetic here; the gate measures whether your greedy walk agrees with the reference's, to the
196
+ element. It is unforgiving of the two natural shortcuts: packing the parameters contiguously and letting
197
+ them straddle bucket boundaries scores **1.38** on `buckets` and mismatches 176 of 186 `meta` rows, and leaving the
198
+ holes uninitialised is caught to the last element.""",
199
+
200
+ perf_md="""Four bytes per parameter plus the zeroed holes — this is entirely a bandwidth problem, and
201
+ your score is achieved bandwidth against that count.
202
+
203
+ The reference wastes most of it: `numel.tolist()` is a device-to-host sync, `torch.zeros(NB, cap)` writes
204
+ the entire output before anything real lands in it, and then 120–250 separate slice copies each launch their
205
+ own kernel.
206
+
207
+ The kernel to write is **one launch over the destination**, with the placement decided first:
208
+
209
+ - **The greedy walk is P steps of a sequential scan** and `P` is at most 250. It is genuinely sequential —
210
+ a parameter's bucket depends on all its predecessors — but it is also tiny, and it depends only on
211
+ `numel`, never on the data. Compute it once per shape and cache it; shape-keyed caching is explicitly
212
+ allowed and is exactly what a real trainer does at wrap time.
213
+ - **Then it is a ragged gather.** For a tile of destination elements, binary-search the placement table to
214
+ find which parameter (if any) owns them, and copy; a tile that lands in a hole stores zeros. Both sides
215
+ are contiguous within a parameter, so 128-bit accesses cover essentially all of the traffic.
216
+ - **Do not pre-zero.** The holes are roughly 10% of the output at the graded capacities — significant, but far
217
+ cheaper to write once from the main pass than to write twice.
218
+ - **Size the grid by destination tiles, not by parameter.** The expert matrices are all the same size, but
219
+ each block also contributes a router and two norm gains that are three to four orders of magnitude
220
+ smaller; a per-parameter grid leaves the machine idle on those.
221
+ - **Watch the write:read ratio.** The output is larger than the input because of the holes, so the store
222
+ path is the one to keep saturated — streaming/non-temporal stores help, since nothing re-reads it.""",
223
+
224
+ precision_md="""There is **no arithmetic in this task at all**. Every output element is either a bf16
225
+ value copied unchanged or an exact `0.0`, so a correct kernel is bit-identical to the reference and the
226
+ tolerance is **`0.0`**.
227
+
228
+ Do not round-trip through fp32 and do not use a cast on the copy path — bf16 in, bf16 out, unchanged.
229
+
230
+ `meta` is `int32` and compared **exactly**. Integer outputs are never compared through `float()`, so an
231
+ off-by-one in a bucket offset is caught rather than absorbed.
232
+
233
+ **Where the tolerance comes from (measured, not guessed).** An independent implementation — the greedy walk
234
+ done with a vectorised prefix-sum-and-rescan (repeatedly `cumsum`-ing within the current bucket rather than
235
+ stepping parameter by parameter) and the copy done as one `index_copy_` from a precomputed destination-index
236
+ map — reproduces the reference **bit for bit**, `E = 0.0`, at every correctness shape and at a full graded
237
+ shape, for both outputs. `tol = 0.0` is exactly the floor.
238
+
239
+ For calibration: swapping just **two** of the 528 M elements of `buckets` at a graded shape already
240
+ registers a relative error of **3.8e-5**, so a single parameter placed one slot off is caught outright.
241
+
242
+ Drop-the-feature measurements: allowing parameters to straddle bucket boundaries (i.e. packing contiguously
243
+ into `NB*cap` slots) gives **D = 1.38** on `buckets` and mismatches 176 of 186 `meta` rows at a graded shape.
244
+ Both are infinitely above a gate of zero.""",
245
+ ).validate()