| """instruction-interpreter-dispatch -- an MPK-style task-graph executor in one persistent kernel.""" |
| import pathlib, sys |
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) |
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "models")) |
| from spec import MegaSpec |
| import instr_interp |
|
|
| I, D = 512, 1024 |
| CFG = dict(d=D, n_instr=I, n_bank=64, window=16, eps=1e-5, wdtype="bf16") |
| BYTES = int(0.5 * I) * D * D * 2 + (I + 1) * D * 4 * 3 |
|
|
| SPEC = MegaSpec( |
| name="instruction-interpreter-dispatch", |
| family="e2", |
| title="Write an on-GPU task-graph interpreter: 512 instructions, one launch, no host in the loop", |
| blurb=("Megakernel compilers (Mirage/MPK, Hazy's low-latency stack) do not hard-code the model -- " |
| "they lower it to a stream of tasks and let one persistent kernel pop, execute and retire " |
| "them, decrementing successors' dependency counters as it goes. Build that executor. The " |
| "512-instruction program is a GPU tensor that changes on every call, so it cannot be " |
| "specialised away; graded on instructions per second."), |
| keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "task-graph", "scheduler", |
| "work-queue", "interpreter", "dependency-tracking"], |
| cfg=CFG, model_src=instr_interp.MODEL_SRC, |
| batch=1, prefill_len=0, max_seq=1, decode_steps=32, correct_steps=8, prof_steps=4, |
| tol=4e-2, |
| max_kernels_per_step=2.0, min_dominant_share=0.95, |
| bytes_per_step=BYTES, |
| reward_metric="instructions/s", reward_work=float(I), |
| entry_build="build_interpreter", entry_step="run_program", |
| step_sig="handle, x0, program", |
| step_ret="slots", |
| step_doc=("Execute the whole program and return every slot." |
| "\n\n x0 : (d,) fp32 slot 0" |
| "\n program : (n_instr, 4) int32 (op, src0, src1, bank) per instruction" |
| "\n returns : (n_instr+1, d) fp32 slot 0 is x0, slot i+1 is instruction i's result\n "), |
| arg_doc=("weights : dict with `bank`, a (n_bank, d, d) bf16 tensor of matrices" |
| "\n kv_cache : [] -- unused in this task"), |
| unfused_kernels=2181, |
| intro_md="""A megakernel does not have to be a *hard-coded* model. The state of the art -- Mirage's |
| MPK, and the task-graph executors inside modern low-latency serving stacks -- compiles the model into |
| a stream of **tasks**: `(opcode, operand slots, dependency count)`. One persistent kernel then pops |
| tasks off a queue, runs them, and atomically decrements the dependency counters of their successors, |
| which pushes newly-ready tasks back onto the queue. The model becomes data; the kernel becomes an |
| interpreter. |
| |
| That interpreter is what you are writing here. It is the hardest of the enabling primitives, because |
| you are paying for dispatch out of the same budget you are paying for arithmetic: a task that reads |
| 2 MB of weights takes about 400 ns of bandwidth, so a dispatch path costing 2 us has already lost.""", |
| spec_md="""## The computation |
| |
| A **slot arena** of `n_instr + 1` = 513 vectors of `d` = 1024 fp32. Slot 0 is the input `x0`. |
| Instruction `i` writes slot `i + 1`. The program is `(512, 4)` int32, one row per instruction: |
| |
| ``` |
| (op, src0, src1, bank) |
| ``` |
| |
| | op | name | slot[i+1] = | |
| |----|------|-------------| |
| | 0 | MATVEC | `bank[bank_idx] @ slot[src0]` (weights bf16, accumulate fp32) | |
| | 1 | ADD | `(slot[src0] + slot[src1]) * 0.70710678` | |
| | 2 | RMSNORM | `slot[src0] * rsqrt(mean(slot[src0]^2) + eps)` | |
| | 3 | GATE | `1.8 * slot[src0] * sigmoid(slot[src1])` | |
| |
| Roughly 50% of the instructions are MATVEC, 16% ADD, 22% RMSNORM, 12% GATE. |
| |
| The program is **SSA**: instruction `i` only ever reads slots `<= i`, and every slot is written exactly |
| once. There are therefore no write-after-read or write-after-write hazards -- the dependency graph is |
| pure data flow, and the program order is always *a* valid topological order. |
| |
| It is not the only one, and that is the point. Source slots are drawn uniformly from the 16 most |
| recent slots, so the graph is roughly 8 instructions wide: the critical path through 512 instructions |
| is only about 60 long. An interpreter that executes in program order leaves ~8x on the table. |
| |
| `/app/reference.py` walks the program on the host and issues one or two torch ops per instruction -- |
| about 2180 launches per call. It is the numerical spec, not a performance target. |
| |
| ### The program is data, not a schedule |
| |
| `program` is a **GPU tensor** and it is regenerated from a fresh seed on every call. You cannot inspect |
| it at build time, and copying it to the host to drive a Python loop costs a synchronisation per call |
| plus 512 launches. The dependency analysis has to happen on the device, inside your kernel, on every |
| call.""", |
| contract_md="""```python |
| def build_interpreter(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED |
| def run_program(handle, x0, program) -> slots # TIMED |
| def teardown(handle) # OPTIONAL |
| ``` |
| |
| `build_interpreter` is handed all four arguments below. `run_program` is handed the handle you |
| returned, plus `x0` and `program`. |
| |
| | arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `weights` | `dict` | -- | exactly one key, `bank` | |
| | `weights["bank"]` | `(n_bank, d, d)` = `(64, 1024, 1024)` | `bfloat16`, on the GPU | the matrix bank, row-major. `bank[j] @ v` is the matrix-vector product a MATVEC instruction performs. Fixed for the life of the handle | |
| | `kv_cache` | `[]` | -- | an **empty list**: this task has no KV cache. Ignore it | |
| | `cfg` | `dict` | python `int` / `float` / `str` | `d` = 1024, `n_instr` = 512, `n_bank` = 64, `window` = 16, `eps` = 1e-5, `wdtype` = `"bf16"` | |
| | `max_seq_len` | scalar | python `int` | `1`. This task has no positions and no cache; the argument exists only because every task in this family shares one builder signature. **Ignore it** | |
| | `x0` | `(d,)` = `(1024,)` | `float32`, on the GPU | slot 0 of the arena, fresh every call | |
| | `program` | `(n_instr, 4)` = `(512, 4)` | `int32`, on the GPU | `(op, src0, src1, bank_idx)` per instruction. Regenerated every call, so it cannot be precompiled | |
| |
| **Return** -- `run_program` returns a **single tensor** `slots` of shape `(n_instr + 1, d)` = |
| `(513, 1024)`, **float32**: `slots[0]` is `x0` and `slots[i + 1]` is instruction `i`'s result. The whole |
| arena is compared, so every instruction is graded, not just the last one. |
| |
| `build_interpreter` returns an opaque handle of any type; the grader never inspects it and only passes |
| it back to `run_program`. |
| |
| `weights`, `cfg`, `x0` and `program` are **read-only**; nothing is updated in place, and `run_program` |
| is a pure function of `(x0, program)` given the handle. |
| |
| Guarantees you may rely on: `0 <= op < 4`; `max(0, i+1-window) <= src0, src1 <= i`; |
| `0 <= bank_idx < n_bank`. You do not need to validate the program. |
| |
| `build_interpreter` is untimed: re-tile the bank, allocate the arena and the ready queue, launch a |
| persistent daemon, precompile per-opcode device functions -- whatever you need.""", |
| gates_md="""**Why these gates, for this task.** |
| |
| `<= 2 kernels/call` is what makes this an *interpreter* rather than a Python loop. The natural |
| implementation of a task graph in torch is one launch per task, and at 512 tasks of ~400 ns of real |
| work each that is a 95% dispatch-overhead implementation -- exactly the thing MPK-style executors |
| exist to eliminate. Forcing the whole program into one launch means the ready queue, the dependency |
| counters and the operand routing all have to live on the device. |
| |
| Note what this gate does *not* do: it does not require you to schedule well. A single kernel that |
| walks the program strictly in order passes both gates and scores maybe an eighth of what a |
| dependency-driven scheduler scores. The gates say "no host in the loop"; the **leaderboard** is where |
| the scheduling quality shows up, which is the honest split for this task. |
| |
| Two launches rather than one so that an arena reset or a queue-init at the top of the call does not |
| disqualify a correct design; the 0.95 dominant-share gate keeps that second launch trivial. |
| |
| **Why `tol` is 4e-2.** Measured: an implementation that keeps the slot arena in **bf16** instead of |
| fp32 differs from the reference by 0.017 over a 512-instruction program. That is a legitimate design |
| choice, so the tolerance has to span it -- it is set at ~2x. An implementation that executes the |
| program in the wrong order, or that gets one opcode wrong, is off by order 1.""", |
| regime_md="""**Regime**: 512 instructions, `d` = 1024, a 64-matrix bank (134 MB, so about half of it |
| stays resident in the 60 MB L2), slot arena 513 x 1024 fp32 = 2.1 MB. Critical path ~60 instructions |
| against 512 total. A MATVEC moves 2 MB and takes ~400 ns at peak bandwidth; a kernel launch takes |
| ~3 us. That ratio is the whole task.""", |
| correctness_md="""The full `(513, 1024)` slot arena must match the reference within **relative |
| error 4e-2** (Frobenius over the whole tensor) at every compared step. Every instruction's output is |
| in there, so there is nowhere for a mis-executed opcode to hide. |
| |
| The op mix is chosen so slot magnitudes stay pinned: measured RMS across the arena is 0.87 to 1.59 |
| with median 1.00, so no slot is numerically ignorable and no slot dominates the norm. |
| |
| Accumulate MATVEC in **fp32** -- the bank is bf16 and `d` is 1024, so a bf16 running sum loses about a |
| digit per instruction and compounds down the chain. |
| |
| The tolerance is calibrated on a real alternative: keeping the arena in bf16 instead of fp32 measures |
| 0.017, so both storage choices pass.""", |
| precision_md="""The bank is **bfloat16**. The slot arena is **fp32** in the reference; bf16 also |
| passes (measured divergence 0.017, tolerance 4e-2), so you may trade arena precision for arena |
| bandwidth if it helps. |
| |
| `RMSNORM` reduces over all 1024 elements -- do that reduction in fp32. `GATE` needs a real `sigmoid`; |
| a piecewise approximation will not hold 4e-2 over a 60-deep chain.""", |
| perf_md="""Per call: ~256 MATVECs x 2 MB = 537 MB of weight traffic, ~113 us at HBM peak. The |
| reference takes **27.5 ms**, 243x the roofline, because it is a host-driven loop issuing 2181 |
| kernel launches. Even a perfect torch implementation with CUDA Graphs would still pay 512 launch |
| latencies (~1.5 ms) and, more importantly, 512 pipeline drains. |
| |
| | | us/call | instructions/s | |
| |---|---|---| |
| | bandwidth floor | 113 | 4.5e6 | |
| | eager torch, host-driven (2181 launches) | 27533 | 1.86e4 | |
| |
| What actually wins here: |
| |
| * **A device-side ready queue.** Precompute (on the device, in the same kernel) the in-degree of every |
| instruction from the `src0`/`src1` columns; seed the queue with the zero-in-degree instructions; each |
| worker pops an index, executes it, then `atomicSub`s the in-degree of its successors and pushes any |
| that hit zero. This is the design that gets the 8x from the graph's width. |
| * **Persist and specialise the workers.** One block per SM, each running the fetch-decode-execute loop. |
| A `switch` on the opcode inside the loop costs nothing next to a launch. |
| * **Keep the arena in L2 (or better).** 2.1 MB fits comfortably; operands should never touch HBM. |
| The bank is the only thing that must stream, so *that* is what you double-buffer. |
| * **Cheap ops should not go through the queue at the same granularity as MATVEC.** ADD, GATE and |
| RMSNORM on 1024 elements are ~4 us of *nothing*; a single warp does each of them in under a |
| microsecond. Sizing the work unit per opcode is a real lever. |
| * **Beware the dependency-counter contention.** 512 instructions with a fan-out of ~2 means ~1000 |
| atomics per call on a handful of cachelines. Batch them, or keep counters in a compact int8 array so |
| a whole successor list lands in one sector.""", |
| faithfulness_md="""Your interpreter must actually interpret the program it is given. Specifically: |
| |
| * Do **not** read the program on the host and drive execution from Python -- it will not fit in the |
| kernel budget anyway, but be clear that this is out of bounds. |
| * Do **not** assume the program is the same as last call. It is regenerated from a fresh seed every |
| call, and the last timed rep is validated. |
| * Do **not** skip instructions whose result you think is unused. Every slot is compared. |
| * Do **not** reorder in a way that violates data flow. Program order is always valid; any other order |
| you use must respect the `src0`/`src1` dependencies. |
| |
| You may repack the bank, precompute per-opcode dispatch tables, allocate the arena and the queue, and |
| launch a persistent daemon inside `build_interpreter` -- that is untimed setup, and a daemon signalled |
| by a flag shows 0 launches/call.""", |
| ).validate() |
|
|