ZMC2019's picture
400 tasks: kernel-optimization agent, profiler permissions, relaxed exact gates (part 9)
74edf23 verified
|
Raw History Blame Contribute Delete
13.5 kB
# Write a fast node-limited MoE dispatch (dedup + all-to-all send-buffer pack) kernel
You are given a **correct but slow** reference at **`/app/reference.py`** — `node_dispatch_pack(x, topk_ids, num_nodes, experts_per_node)`. **Read it, run it, profile it.**
Write **`/app/dispatch_pack.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
```python
def node_dispatch_pack(x, topk_ids, num_nodes, experts_per_node):
...
```
## The computation (this is the exact spec)
In expert-parallel serving the experts are spread over `N` nodes — expert `e` lives on node
`e // EPN` — and before the all-to-all can run, every token's hidden state has to be copied into the send
buffer of each node that owns one of its experts.
**The dedup is the point.** A token routed to four experts that happen to live on the same node is sent to
that node **once**. So the first step is to turn each token's `K` expert ids into a *set* of nodes:
```
node[t, j] = topk_ids[t, j] // EPN
member[t,n] = True iff any j has node[t, j] == n
```
DeepSeek's node-limited routing guarantees each token's experts span exactly `M` distinct nodes, so
`member` has exactly `M` true entries per row and the packed buffer is exactly `T*M` rows long.
**The packing is node-major, token-ascending inside a node:**
```
node_counts[n] = number of tokens with member[t, n]
node_offsets = [0, cumsum(node_counts)] # (N+1,)
```
Node `n` owns rows `[node_offsets[n], node_offsets[n+1])` of `send_buf`, and those rows hold its tokens in
**increasing token index**. Formally, if `r` is the rank of token `t` among the tokens that chose node `n`
(counting in increasing `t`):
```
send_buf[node_offsets[n] + r, :] = x[t, :]
src_token[node_offsets[n] + r] = t
```
`src_token` is what the combine step later uses to scatter the expert outputs back, so it is part of the
contract, not a debugging aid.
Note what is **not** asked for: no per-expert grouping, no weights, no padding. This is the transport
layer — one copy of each token per destination node, in the order the receiver expects.
`/app/reference.py` builds a dense `(T, N)` boolean matrix and lets `nonzero` produce the ordering. That is
the exact specification; it is deliberately simple rather than fast.
## The contract (fixed — do not change these)
| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `x` | `(T, H)` | `bfloat16` | token hidden states |
| `topk_ids` | `(T, K)` | `int32` | the `K` expert ids per token, **distinct within a row** |
| `num_nodes` | int | | `N` |
| `experts_per_node` | int | | `EPN`; expert `e` is on node `e // EPN` |
**Return a 4-tuple in exactly this order:**
| out | shape | dtype | notes |
|-----|-------|-------|-------|
| `send_buf` | `(T*M, H)` | `bfloat16` | node-major, token-ascending inside each node |
| `src_token` | `(T*M,)` | `int32` | source token of each packed row; compared **exactly** |
| `node_counts` | `(N,)` | `int32` | compared **exactly** |
| `node_offsets` | `(N+1,)` | `int32` | exclusive prefix sum, `node_offsets[N] == T*M`; compared **exactly** |
`M` — the number of distinct nodes each token's experts span — is **fixed for a given call** and is what
makes `T*M` a shape-only quantity; you can compute it, but you do not need to guess it, because
`send_buf`'s length follows from the routing table you are given.
All inputs are **read-only**; the copy is functional. `T` is **not** guaranteed to be a multiple of any
tile size — the correctness shapes include `T = 129`.
**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `T`
(tokens in the micro-batch) in 24576–49152, `H` in 4096–7168, `K` in 6–8, `N` (nodes) 4 or 8, `M`
(distinct nodes per token) 3 or 4, `EPN` in 32–64. The send buffer is 3–4x the size of the input, so this
call moves more bytes than any other single op in the MoE layer.
## How success is decided (runs on GPU)
**1. Correctness — a required gate.** Three of the four outputs are **integer** and are compared **bit-exactly** — one
wrong row index anywhere and the score is 0. `send_buf` is a pure gather, so a correct kernel reproduces it
**bit for bit**; its `1e-5` gate exists only to reject a change of dtype.
The ordering rules are an exact specification, not a convention: **node-major** blocks, **ascending token
index** inside each block. Two variants that break them were tried and both fail outright — packing
token-major (all of token 0's copies, then token 1's) and leaving the tokens unsorted inside a node. So
does skipping the dedup and emitting one row per expert slot, which produces `T*K` rows instead of `T*M`
and fails on shape. A wrong kernel scores **0**, no matter how fast.
**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
```
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [GB/s]
reward = 0 if the submission is wrong at any graded shape
```
`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
credited the same work and this is a pure speed ranking in useful units:
```
bytes = 2*T*H + 4*T*K + 2*T*M*H + 4*T*M + 4*(2*N+1)
# read x read ids write buf src map counts+offsets
```
**There is no cap and no target.** Higher GB/s is always a strictly better score, so **push the
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
after every change. **Use your full time budget.**
Run **`python /app/measure.py`** at any point to see your per-shape and geomean GB/s plus correctness.
## Where the performance comes from
One read of `x`, `M` writes of each row, and an index computation in between. The floor is
`(1 + M)` passes over a `(T, H)`-sized tensor and nothing else, which is what the byte count assumes.
The index side is small but it is where the naive version dies. The reference's `(T, N)` boolean matrix,
`nonzero`, and the implied sort cost several passes over `T*N` and a device-wide scan. What it actually is:
* a **bitset per token** — `N <= 8` nodes fit in one byte, so the dedup is `mask |= 1 << (e // EPN)` over
`K` ids, entirely in registers;
* a **histogram** of `N` counters, which wants per-block privatised counters and one atomic per block per
node, not one atomic per token;
* a **prefix sum over `N <= 8` numbers**, which is one warp;
* a **rank within node**, which is the block's own offset plus a lane prefix — again no global sort.
Then the gather. Each destination row is a full `H`-wide bf16 copy (8–14 KB), so use vectorised 128-bit
accesses and give each row enough lanes to saturate; the read of `x[t]` serves all `M` of its destinations,
so a block that has a token's row in registers or shared memory should write **all** its copies before
moving on — reading `x` once instead of `M` times is a 25–33% bandwidth saving on its own.
The destinations of one token are `M` widely separated offsets, so the writes are scattered at row
granularity but perfectly coalesced within a row. Prefer a grid over (token tile) with the row resident,
rather than a grid over output rows that re-reads the source.
## Precision and faithfulness (read this)
`x` and `send_buf` are **bfloat16** and the copy is exact — no arithmetic happens to
the payload at all, so a correct kernel is bit-identical to the reference and the `1e-5` gate is
effectively an exactness check. Returning `send_buf` in fp32 would change the contract (and cost twice the
bandwidth for no benefit); returning it in fp8 would be a lossy transform of data that is supposed to be
transported unchanged.
The three integer outputs are compared **exactly**: `.float()` is lossy above 2^24 and `T*M` reaches
200000 here, so the grader never converts them.
**Where the tolerance comes from.** It is measured, and the measurement is that there is nothing to
measure: an independent implementation — the membership computed as a per-token bitmask, the ranking from
a scatter-add histogram plus a segmented rank instead of `nonzero`, and the gather written as an explicit
row copy — differs from this reference by a relative Frobenius error of exactly **0.0e+00** on `send_buf`
and reproduces all three integer outputs **bit for bit**, at every correctness shape and at a full-size
graded shape, over several seeds. The gate is set at `1e-5` rather than at zero only so that a legitimate
bf16 round-trip cannot fail on a denormal; it admits nothing except the specified bf16 payload, and in
particular an fp8 or fp16 payload would miss it by 1e-3 or more.
### What the tolerance does NOT permit
The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
implementation of the specified computation**. It is not a budget to spend on approximation. The following
are wrong answers even if they happen to land inside the tolerance at some shape:
- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
series, low-rank or sketched substitutes, skipping a correction term);
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
or striding over the sequence, ignoring positions whose contribution "looks small");
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
that the spec gives their own);
- anything whose error **grows** with sequence length, batch, or head count.
A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
are deliberately large, so the difference shows up.
## What's available
- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
(`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
- A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist.
The exact part is deliberately **not** stated: query it and tune to what you actually find.
```python
p = torch.cuda.get_device_properties(0)
p.name, p.major, p.minor # part and compute capability
p.multi_processor_count # SM count -- size your persistent grid from this, never a constant
p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor
p.shared_memory_per_block_optin # opt-in dynamic smem, the number that matters for big tiles
```
`nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK`
give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a
datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak
FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the
score is an absolute metric, so a kernel tuned to a machine it never sees is just slower.
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
already installed, and no library implementation of this kernel exists on the machine.
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
`/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
- **Profilers.** `nsys` works here and answers the first question — is the time actually inside your
kernel, or in launch gaps and dispatch? `ncu` reads GPU performance counters, which the container may
not be permitted to access: if it prints `ERR_NVGPUCTRPERM`, counters are unavailable on this run.
That is an environment permission, not something you can fix from inside — fall back to `nsys` plus
A/B ablation (change one thing, re-time it) instead of spending your budget fighting it. Note that
`ncu --version` succeeds either way; it never touches a counter.
## How the grading actually runs (so there are no surprises)
- **`/app/dispatch_pack.py` is the only file that is graded.** The grader imports `node_dispatch_pack` from it and reads nothing
else from `/app`.
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
your score**. Do not spend budget on them.
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.