"""persistent-scheduler-loadbalance -- fixed bytes, 32x length skew, re-permuted every call.""" 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 ragged_sched LENS = ([65536] * 2 + [32768] * 4 + [16384] * 8 + [8192] * 16 + [4096] * 32 + [2048] * 66) CFG = dict(n_q=32, n_kv=8, hd=128, lens=LENS, wdtype="bf16") B = len(LENS) BYTES = sum(LENS) * CFG["n_kv"] * CFG["hd"] * 2 * 2 SPEC = MegaSpec( name="persistent-scheduler-loadbalance", family="e2", title="Schedule a 32x-skewed ragged decode batch on the device, from data, every call", blurb=("128 decode requests whose contexts span 2048 to 65536 tokens. The total bytes are fixed, so " "this is not a bandwidth puzzle -- it is a scheduling one. One block per request leaves all but " "a couple of the device's SMs idle while the longest sequences grind through alone. The " "lengths are " "re-permuted on every call, so the schedule has to be computed on the device from data " "that did not exist at build time. Graded on GB/s."), keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "scheduler", "load-balancing", "work-queue", "ragged-batch", "flash-decoding", "gqa"], cfg=CFG, model_src=ragged_sched.MODEL_SRC, batch=B, prefill_len=0, max_seq=1, decode_steps=32, correct_steps=8, prof_steps=4, tol=1e-2, max_kernels_per_step=2.0, min_dominant_share=0.90, bytes_per_step=BYTES, reward_metric="GB/s", reward_work=BYTES / 1e9, entry_build="build_sched", entry_step="ragged_decode", step_sig="handle, q, starts, lens", step_ret="out", step_doc=("One decode-attention per request, over that request's own slice of the arena." "\n\n q : (B, n_q, hd) bf16 already rotated queries" "\n starts : (B,) int32 first row of this request's context" "\n lens : (B,) int32 number of context tokens for this request" "\n returns : (B, n_q*hd)\n "), arg_doc=("weights : {} -- no projection weights; queries arrive already computed and rotated" "\n kv_cache : dict with `k`, `v` (total_tokens, n_kv, hd) bf16 -- one flat arena"), unfused_kernels=514, intro_md="""A megakernel is only as fast as its worst-scheduled block. Everything else in this group is about moving bytes; this one is about deciding *who moves which bytes*, and it is deliberately constructed so that the byte count is identical no matter what you decide. 128 concurrent decode requests. Two of them have 65536 tokens of context; sixty-six of them have 2048. Assign one block per request and the short ones retire in microseconds while every SM but the two still grinding the 65536-token sequences sits idle -- a ~16x loss against a balanced schedule that reads exactly the same 3.24 GB. Assign a fixed number of KV-splits per request and you over-decompose the short ones and under-decompose the long ones. And you cannot precompute the answer: the lengths and offsets are GPU tensors, re-permuted on every call.""", spec_md="""## The computation One flat KV arena holds every request's context back to back. Request `b` owns rows `starts[b] .. starts[b]+lens[b]-1`. ``` for b in range(128): K = k_arena[starts[b] : starts[b]+lens[b]] # (L_b, n_kv, hd) V = v_arena[starts[b] : starts[b]+lens[b]] out[b] = softmax(q[b] @ K.T / sqrt(hd)) @ V # 32 query / 8 KV heads (GQA, rep 4) ``` 32 query heads, 8 KV heads, head_dim 128. The length multiset is **fixed**: | length | count | tokens | |---|---|---| | 65536 | 2 | 131072 | | 32768 | 4 | 131072 | | 16384 | 8 | 131072 | | 8192 | 16 | 131072 | | 4096 | 32 | 131072 | | 2048 | 66 | 135168 | | **total** | **128** | **790528** | so every call reads exactly 3.24 GB and the GB/s reward is directly comparable call to call. What changes every call is **which request gets which segment** -- `starts` and `lens` are a fresh random permutation of that fixed multiset. `/app/reference.py` loops over the 128 requests on the host: 514 kernel launches per call. Paging is deliberately not part of this task. The arena is contiguous and the offsets are given, so nothing distracts from the scheduling.""", contract_md="""```python def build_sched(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED def ragged_decode(handle, q, starts, lens) -> out # TIMED def teardown(handle) # OPTIONAL ``` `build_sched` is handed all four arguments below. `ragged_decode` is handed the handle you returned, plus `q`, `starts` and `lens`. `B` = 128 requests, and `T` = `sum(cfg["lens"])` = 790528 arena rows. | arg | shape | dtype | meaning | |-----|-------|-------|---------| | `weights` | `{}` | -- | an **empty dict**: there are no projection weights, the queries arrive already computed and already rotated | | `kv_cache` | `dict` | see rows below | two keys, `k` and `v` | | `kv_cache["k"]` | `(T, n_kv, hd)` = `(790528, 8, 128)` | `bfloat16` | one flat, contiguous key arena; request `b` owns rows `starts[b] .. starts[b]+lens[b]-1` | | `kv_cache["v"]` | same shape as `["k"]` | `bfloat16` | the value arena, same row layout | | `cfg` | `dict` | python `int` / `list` / `str` | `n_q` = 32, `n_kv` = 8, `hd` = 128, `wdtype` = `"bf16"`, and `lens` = the fixed multiset of 128 context lengths as a **Python list** (host-side, not a tensor) | | `max_seq_len` | scalar | python `int` | `1`. This task has no positions and no per-request cache capacity -- the arena is sized by `cfg["lens"]` -- so the argument exists only because every task in this family shares one builder signature. **Ignore it** | | `q` | `(B, n_q, hd)` = `(128, 32, 128)` | `bfloat16`, on the GPU | already-rotated queries, one per request | | `starts` | `(B,)` = `(128,)` | `int32`, **on the GPU** | first arena row of each request's context | | `lens` | `(B,)` = `(128,)` | `int32`, **on the GPU** | context length of each request. A permutation of `cfg["lens"]`, re-drawn every call | **Return** -- `ragged_decode` returns a **single tensor** `out` of shape `(B, n_q*hd)` = `(128, 4096)`, **head-major** (head `h`'s `hd` values are contiguous), **bf16 or fp32, both accepted** (the grader compares in fp32). `build_sched` returns an opaque handle of any type; the grader never inspects it and only passes it back to `ragged_decode`. Every argument is **read-only** -- the arena is never written, nothing is updated in place, and `ragged_decode` is a pure function of `(q, starts, lens)` given the handle. The softmax scale is `1/sqrt(hd)`; there is no mask. `cfg["lens"]` gives you the multiset (so you may size buffers and plan a decomposition at build time) but **not** the per-call assignment: `starts` and `lens` are re-permuted every call and only exist on the device. `build_sched` is untimed: allocate partial-result buffers, work queues, atomic counters, launch a persistent kernel.""", gates_md="""**Why these gates, for this task.** The gates here are a floor, not the point, and it is worth being explicit about that rather than pretending otherwise. `<= 2 kernels/call` rules out the implementation the reference uses -- a host loop over 128 requests, 514 launches -- and, more importantly, rules out any design that launches per length bucket or per request. Two launches is chosen because the classic and entirely legitimate way to write ragged decode attention is **two-phase flash-decoding**: a big kernel producing per-split partial `(max, sumexp, acc)` triples, then a small kernel combining them. Forbidding that would be forbidding good engineering, not forbidding laziness. `>= 0.90` dominant share matches: it leaves room for that combine pass (which is genuinely small here -- 128 x 32 x 128 partials against 3.24 GB of KV) while still failing anything that splits the *main* work in two. So what makes this task hard is **not** the gates -- it is the leaderboard, and that is by design. Every legal implementation reads the same 3.24 GB, so GB/s is a pure measure of how much of the machine you kept busy: * one block per request: the two 65536-token requests serialise, ~16x off the roofline; * a fixed number of splits per request: the 2048-token requests are over-decomposed into work units smaller than a memory transaction, the 65536-token ones are still under-decomposed; * a device-side work queue over fixed-size KV tiles, with atomics handing out tiles: within reach of the roofline. That spread is the task. Nothing in the gates tells you which one you wrote; the GB/s number does. **Why `tol` is 1e-2.** Measured on the graded fixtures over 8 steps and 2 seeds: an independent implementation that tiles every sequence into 2048-token work items and merges flash-decoding partials -- a completely different reduction order from the reference's per-request SDPA -- differs by **E = 2.3e-3**, so the tolerance is **4.4x** the floor. The cheapest mishandling of the ragged structure, clamping every length at 8192, measures **D = 0.159**, i.e. **16x** the tolerance; ignoring `starts` measures 1.42 and using one fixed length for every request 0.96.""", regime_md="""**Regime**: 128 concurrent decode requests, contexts from 2048 to 65536 tokens (32x skew), 32 query / 8 KV heads, head_dim 128, one flat 3.24 GB bf16 arena. Total bytes per call are constant by construction; only the assignment changes. Roofline **675 us**. Measured eager torch (128 host-driven attention calls): 8015 us -- 11.9x the roofline.""", correctness_md="""The returned `(B, n_q*hd)` must match the reference within **relative error 1e-2** at every compared step. Measured on this fixture over 8 steps and 2 seeds: | implementation | relative error | |---|---| | **independent fp32 attention, 2048-token tiles, flash-decoding merge** | **0.0023** | | the same with bf16 partial accumulators | 0.0034 -- passes, but spends 1.5x the floor for nothing | | *(the gate)* | *0.01* | | **every length clamped at 8192** | **0.159** | | one fixed length used for every request | 0.959 | | `starts` ignored (every request read from the top of the arena) | 1.42 | `tol/E` is 4.4 and `D/tol` is 16. Anything that mishandles the ragged structure is caught. Use an online (streaming) softmax with a running maximum and rescale, in fp32, and accumulate `p @ V` in fp32. At 65536 keys this is not optional. If you split a sequence across blocks (and you should), combine the partials the flash-decoding way: each partial carries `(m_i, l_i, acc_i)`, and the merge is `m = max(m_i)`, `l = sum(l_i * exp(m_i - m))`, `acc = sum(acc_i * exp(m_i - m)) / l`. Adding softmaxed partials without rescaling is a silent, plausible-looking error that this tolerance will catch.""", precision_md="""`q` and the arena are **bfloat16**. Queries arrive already rotated; there is no RoPE in this task. Scores are `q . k / sqrt(hd)` accumulated in **fp32**, the softmax runs in fp32 with a running max, and `p @ V` accumulates in fp32. The partial-merge arithmetic above is also fp32. Store partials in fp32. Measured with 32 splits of the 65536-token sequences, bf16 partial accumulators land at 3.4e-3 against a 2.3e-3 floor -- inside the 1e-2 gate, but half your budget spent on a register that costs nothing to widen, and the loss grows with the number of splits.""", 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 | GB/s | x floor | |---|---|---|---| | roofline | 3.24 GB -> divide by `BW` | `BW` | 1.0 | | eager torch (128 host-driven attentions, 514 launches) | 8015 | 404 | 11.9 | | one block per request (estimated from the length skew) | ~10000 | ~320 | ~15 | Note the third row: a *fused, single-kernel, gate-passing* implementation that schedules naively is worse than the unfused reference. That is unusual in this family and it is the point of the task. What actually wins here: * **Tile the KV, not the batch.** Chop every sequence into fixed-size tiles (1024 or 2048 tokens is a good starting point) and make the tile the unit of work. Then the 65536-token request is 32 or 64 independent work items and the 2048-token one is one or two, and total work items (~500-800) exceeds the block count comfortably. * **Hand tiles out with an atomic counter.** A persistent grid of 132 blocks, each doing `while ((t = atomicAdd(&next, 1)) < n_tiles)`, is self-balancing with no schedule to compute. The tile-to-(request, offset) mapping can be derived on the device from `starts`/`lens` with a small prefix sum -- 128 elements, one warp. * **Or: sort by length on the device.** A 128-element sort is nothing. Scheduling longest-first is the classic LPT approximation and gets you most of the way with a fully static per-tile assignment. * **Do the combine cheaply.** Partial results are `(B, n_splits, n_q, hd)` fp32; with 512 splits for the longest that is a few MB. Either a second tiny kernel (allowed -- 2 launches) or a second phase after a grid-wide barrier in the same kernel. * **Do not over-split the short sequences.** A 2048-token request split 64 ways is 32 tokens per block -- less than one memory transaction's worth of useful work per block, and the merge cost then exceeds the attention cost. Choose splits per sequence from `lens`, on the device. * **The permutation changes every call.** Anything you precompute in `build_sched` must be a function of the multiset, not of the assignment.""", faithfulness_md="""Your kernel must attend over each request's full, actual context. Specifically: * Do **not** use a single length for all requests, pad to the maximum, or truncate the long ones. `lens` is data and it changes every call. * Do **not** precompute a schedule keyed to a particular permutation -- it is re-drawn every call, and the last timed rep is validated. * Do **not** subsample keys or approximate the softmax normalisation. You may allocate partial buffers, work queues and counters in `build_sched`, precompute anything that depends only on the fixed length multiset, and launch a persistent kernel there -- that is untimed setup, and a daemon signalled by a flag shows 0 launches/call.""", ).validate()