KBench / tools /mega_factory /specs /cross_layer_fusion_2layer.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 18)
4d31ab5 verified
Raw
History Blame Contribute Delete
14.3 kB
"""cross-layer-fusion-2layer -- two layers, ONE kernel: the layer boundary must be a barrier."""
import pathlib, sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "models"))
from spec import MegaSpec
import fused_layers
CFG = dict(layers=2, d=4096, ffn=14336, n_q=32, n_kv=8, hd=128,
eps=1e-5, theta=500000.0, wdtype="bf16")
PF, DS = 4096, 32
PER = (CFG["n_q"] * CFG["hd"] * CFG["d"] + 2 * CFG["n_kv"] * CFG["hd"] * CFG["d"]
+ CFG["d"] * CFG["n_q"] * CFG["hd"] + 3 * CFG["ffn"] * CFG["d"])
WB = 2 * PER * 2
KVB = 2 * 1 * 2 * CFG["n_kv"] * (PF + DS) * CFG["hd"] * 2
SPEC = MegaSpec(
name="cross-layer-fusion-2layer",
family="e2",
title="Run two decoder layers in ONE kernel -- the layer boundary becomes a grid-wide barrier",
blurb=("Fusing inside a layer is a known technique. Fusing ACROSS one is the thing that turns a "
"fast layer kernel into a megakernel: the residual stream must survive the transition "
"without touching HBM, and layer 2's weights must already be in flight while layer 1's "
"attention is still running. The gates are set so that one-kernel-per-layer fails, which "
"leaves exactly one legal shape: two layers, one launch, a barrier in between."),
keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "cross-layer-fusion",
"grid-sync", "decode", "gqa", "memory-bound"],
cfg=CFG, model_src=fused_layers.src("build_block", "block_step"),
batch=1, prefill_len=PF, max_seq=4224, decode_steps=DS, correct_steps=8, prof_steps=4,
tol=2e-2,
max_kernels_per_step=1.0, min_dominant_share=0.98,
bytes_per_step=WB + KVB,
reward_metric="tokens/s", reward_work=1.0,
entry_build="build_block", entry_step="block_step",
step_sig="handle, x, pos",
step_ret="x_out",
step_doc=("Run BOTH layers on one hidden state; append this position's K/V into both caches."
"\n\n x : (B, d) bf16 the incoming residual stream"
"\n pos : int the absolute position being written"
"\n returns : (B, d) the residual stream after layer 2\n "),
arg_doc=("weights : dict with `layers[0..1]`, each holding"
" `in_norm, post_norm, q, k, v, o, gate, up, down`"
"\n kv_cache : list of TWO (k, v), each (B, n_kv, max_seq_len, hd) bf16, prefilled"),
unfused_kernels=89,
intro_md="""Everything a decoder layer does internally can be fused by a good kernel author working
one layer at a time. What separates that from a **megakernel** is the boundary *between* layers, and
this task is built to make that boundary the only thing that matters.
Two layers. One launch. The gates are deliberately arranged so that the obvious answer -- write an
excellent single-layer kernel and call it twice -- does not pass, because a kernel boundary at the
layer transition is precisely the thing being removed.""",
spec_md="""## The computation
Two identical-shaped decoder layers, applied in sequence to one decode position `pos`:
```
for L in (layer0, layer1):
h = rmsnorm(x, L.in_norm)
q,k,v = h @ L.Wq.T, h @ L.Wk.T, h @ L.Wv.T # 32 query / 8 KV heads (GQA, rep = 4)
q,k = rope(q, pos), rope(k, pos)
kv_cache[L].k[:, :, pos] = k # append THIS position, in BOTH layers
kv_cache[L].v[:, :, pos] = v
a = softmax(q @ K[:pos+1].T / sqrt(hd)) @ V[:pos+1]
x = x + a_flat @ L.Wo.T
h = rmsnorm(x, L.post_norm)
x = x + (silu(h @ L.Wgate.T) * (h @ L.Wup.T)) @ L.Wdown.T
return x
```
`d` = 4096, `ffn` = 14336, 32 query / 8 KV heads, head_dim 128 -- two layers of an 8B-class model,
436 M parameters, 873 MB. Each layer has its **own** KV cache and both must be appended to.
`/app/reference.py` implements exactly this, unfused, in eager torch: 89 kernel launches per call.
### What the layer boundary costs if you keep it
Between the two layers there is exactly one live value: `x`, which is 4096 numbers -- 8 KB. Ending a
kernel there means writing those 8 KB to HBM, draining every in-flight load, tearing down a whole
grid's worth of block state, and starting cold again with layer 2's first tiles not yet requested. It
also throws away the only opportunity in the whole call to prefetch: layer 2's `Wq` address is known from the
moment the kernel starts.""",
contract_md="""```python
def build_block(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED
def block_step(handle, x, pos) -> x_out # TIMED
def teardown(handle) # OPTIONAL
```
`build_block` is handed all four arguments below. `block_step` is handed the handle you returned, plus
`x` and `pos`.
| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `weights` | `dict` | `bfloat16` | exactly one key, `layers`. There is **no** embedding and **no** LM head in this task |
| `weights["layers"][i]` | 9 tensors, `i` in `{0, 1}` | `bfloat16` | `in_norm (d,)`, `post_norm (d,)`, `q (n_q*hd, d)`, `k (n_kv*hd, d)`, `v (n_kv*hd, d)`, `o (d, n_q*hd)`, `gate (ffn, d)`, `up (ffn, d)`, `down (d, ffn)` -- row-major, applied as `h @ W.T`. With `d`=4096, `ffn`=14336, `n_q`=32, `n_kv`=8, `hd`=128 |
| `kv_cache` | `list` of **2** `(k, v)` pairs | `bfloat16` | one per layer, each tensor `(B, n_kv, max_seq_len, hd)`; slots `[0, 4096)` hold the prefix, the rest are zero |
| `cfg` | `dict` | python `int` / `float` / `str` | `layers` = 2, `d, ffn, n_q, n_kv, hd, eps, theta, wdtype` |
| `max_seq_len` | scalar | python `int` | `4224` -- the allocated time capacity of both caches, exactly `kv_cache[i][0].shape[2]`. `pos < max_seq_len` always holds, so a RoPE table of this length covers the whole run |
| `x` | `(B, d)` = `(1, 4096)` | `bfloat16`, on the GPU | the incoming residual stream, fresh every call |
| `pos` | scalar | python `int` | the absolute position to write, in **both** layers; it advances by 1 per call |
**Return** -- `block_step` returns a **single tensor** `x_out` of shape `(B, d)` = `(1, 4096)`, the
residual stream after both layers, **bf16 or fp32, both accepted** (the grader compares in fp32).
`build_block` returns an opaque handle of any type; the grader never inspects it and only passes it
back to `block_step`.
`weights`, `cfg` and `x` are **read-only**. `kv_cache` is the one thing you must update **in place**:
both caches must be appended at `pos`, because the next call attends over both, and the final timed
step is validated.
`build_block` is untimed: concatenate the two layers' weights into one contiguous stream in execution
order, fuse Q/K/V, build RoPE tables, allocate scratch, launch a persistent kernel.""",
gates_md="""**Why these gates, for this task.**
This task allows **one** launch, not the two that the rest of this group allows, and the reason is
specific: the single thing being graded is the elimination of the layer boundary, and any second
launch *is* a layer boundary.
The obvious near-miss is worth spelling out. Write one excellent single-layer kernel and call it
twice: that is 2 launches, and because the profiler aggregates by kernel *name*, both calls collapse
into one entry with a dominant share of 1.00. A dominant-share gate cannot see it. Only the launch
count can, which is why the count is 1 here and 2 elsewhere.
Dominant share >= 0.98 then closes the other direction: whatever single kernel you launch must be
doing essentially all the work, so you cannot pass by hiding half the block in a differently-named
second kernel (that would be 2 launches anyway) or by leaving a large chunk in torch ops.
**One launch is achievable and here is how**, because a limit of 1 is unforgiving and the difficulty
should come from the kernel and not from a trap:
* Do not reset your barrier counter with a separate `bar.zero_()` -- that is a second launch. Keep a
monotonically increasing goal instead (`goal += gridDim.x` at each barrier) and compare against it,
or alternate two counters by parity. This is standard practice for persistent kernels.
* Do not build tensors from Python scalars inside the timed call; a host-to-device copy shows up as
device time. `pos` is a plain `int` and belongs in the kernel's argument list.
* `torch.empty` for the output is allocator-only and is *not* a launch.
* Best of all: launch a persistent kernel in `build_block` and signal it with a flag. That measures 0
launches/call and passes outright. Define `teardown(handle)` so it exits cleanly.
**Why `tol` is 2e-2.** It is measured, not inherited. Two independent-but-correct implementations of
this block (an all-fp32 one, and a bf16-GEMV one with an fp32 residual stream and a manually
chunked attention) differ from the reference by at most **E = 8.6e-3** over 5 weight/token seeds.
Dropping the thing this task exists to test -- the second layer -- lands at **D = 4.7e-1**. The gate
sits at 2e-2: **2.3x above E and 23x below D**. See the Precision section for the full table.""",
regime_md="""**Regime**: batch 1, two layers, `d` = 4096, `ffn` = 14336, 32 query / 8 KV heads,
head_dim 128. 873 MB of weights plus 34 MB of KV; the roofline is that 907 MB divided by the HBM
bandwidth you measure. Measured eager torch: 1043 us -- 0.87 TB/s, **5.5x** that roofline. The KV caches
arrive holding 4096 tokens each and you decode 32 more.""",
correctness_md="""The returned `(B, d)` residual stream must match the reference within **relative
error 2e-2** at every compared step, and both KV caches must be appended at `pos` -- the next call
reads them and the last timed step is validated.
Accumulate in fp32 in every reduction: both RMSNorms per layer, both attention softmaxes, and all
twelve GEMV dot products.
**The residual stream may be kept in bf16 or fp32 -- both pass** (measured difference 5.3e-3). This
matters more here than in a single-layer task: the entire point is that `x` never leaves the chip
between layers, and a kernel that keeps it in registers will naturally hold it in fp32.
**Drop-the-feature margin.** An implementation that skips the second layer -- the shortcut this gate
exists to catch -- measures **0.47**, i.e. **23x** the tolerance, so the gate discriminates the work
comfortably. Running layer 0's weights twice is 0.66 and dropping the residual adds is 1.08. Both are
far outside.""",
precision_md="""Weights and both KV caches are **bfloat16**; compute in bf16 with **fp32
accumulation**.
RoPE is applied in **fp32** to `q` and `k` before the cache write (the cos/sin tables are fp32), then
`k` is cast back to bf16 for storage -- in both layers, at the same `pos`, with the same `theta`.
The two layers have independent `in_norm`/`post_norm` gains and independent caches; nothing is shared
between them except the residual stream.
**Where the tolerance comes from (measured, not guessed).** `tol` is `2e-2`. Two *independent* correct
implementations were written and compared against the reference on the graded fixtures (batch 1,
prefill 4096, 8 steps, 5 weight/token seeds):
| implementation | worst relative error |
|---|---|
| all-fp32: fp32 residual, fp32 GEMVs, manual fp32 softmax attention | 5.3e-3 |
| **bf16 GEMVs, fp32 residual, hand-rolled attention (what a megakernel writes)** | **8.6e-3** |
| *(gate)* | *2e-2* |
| skip the second layer | 4.7e-1 |
| run layer 0's weights twice instead of layer 1's | 6.6e-1 |
| drop the residual adds | 1.08 |
So **E = 8.6e-3**, **tol = 2e-2 = 2.3x E**, and the cheapest feature-drop is **23x the tolerance**.
This is an *arithmetic* gate, not an exactness check: the output is a bf16-or-fp32 residual stream and
the honest spread between correct implementations is ~1e-2, which is why the gate is nowhere near
bf16 epsilon.
**One thing the correctness gate cannot see, so do not rely on it:** at a 4096-token prefix, *not*
appending this position's K/V changes the output by only 5.8e-3 -- inside the noise floor. The append
is still part of the contract and the caches are state that the following calls and the final timed
step depend on; it is simply not what this particular relative-error bound is measuring.""",
perf_md="""`BW` is the HBM bandwidth you measure on the device with a large stream-copy -- never a
datasheet figure. The measured rows come from one machine, so read the **x floor** column, not the
absolute microseconds.
| | us/call | tokens/s | x floor |
|---|---|---|---|
| roofline | 907 MB -> divide by `BW` | -- | 1.0 |
| eager torch (89 launches) | 1043 | 959 | 5.52 |
Roughly 5.5x of headroom, and the shape of it is unusual for this family: with only 873 MB to move, the
fixed costs (two kernel ramps, four full HBM round trips of the SwiGLU intermediate, the residual
stream bouncing in and out) are a large fraction of the total. That is why the cross-layer fusion pays
here in a way it would not at 16 layers, where those costs amortise.
What actually wins here:
* **One barrier at the layer boundary, and prefetch across it.** Layer 2's `Wq`/`Wk`/`Wv` addresses do
not depend on layer 1's output. Issue those loads before you arrive at the barrier and the
transition costs you the barrier latency (~1 us) instead of a cold restart (~100 us).
* **Lay the weights out in execution order.** In `build_block`, concatenate layer 0's fused QKV, `Wo`,
`gate`/`up` interleaved and `down`, then layer 1's, into one contiguous 873 MB stream. Then the whole
call is a single linear sweep of HBM and the prefetcher works for you.
* **Keep `x` in registers or shared memory across the boundary.** 8 KB. It should be written to HBM
exactly zero times.
* **Fuse Q/K/V per layer**, never materialise the `(1, 14336)` SwiGLU intermediate, and give the
attention (17 MB of KV out of 907 MB) a small slice of the grid rather than stalling everyone on it.
* **Watch the barrier count.** You need one at each of: after the norm's reduction, after the QKV
projection (before attention), after attention (before `Wo`), after the second norm, and at the layer
boundary -- about 5 per layer, ~10 per call, ~10 us of the 189 us floor. Fewer, coarser barriers is a
real optimisation; a barrier per output tile is not.""",
).validate()