ZMC2019 commited on
Commit
42832bf
·
verified ·
1 Parent(s): 25f4e8d

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

Browse files
Files changed (27) hide show
  1. tasks/moe/README.md +6 -1
  2. tasks/moe/deepseek-node-dispatch-pack/RUN.md +42 -0
  3. tasks/moe/deepseek-node-dispatch-pack/environment/CLAUDE.md +25 -0
  4. tasks/moe/deepseek-node-dispatch-pack/environment/Dockerfile +41 -0
  5. tasks/moe/deepseek-node-dispatch-pack/environment/PROCESS_MANAGEMENT.md +96 -0
  6. tasks/moe/deepseek-node-dispatch-pack/environment/dispatch_pack.py +30 -0
  7. tasks/moe/deepseek-node-dispatch-pack/environment/docker-compose.yaml +18 -0
  8. tasks/moe/deepseek-node-dispatch-pack/environment/measure.py +130 -0
  9. tasks/moe/deepseek-node-dispatch-pack/environment/reference.py +28 -0
  10. tasks/moe/deepseek-node-dispatch-pack/environment/restrict-network.sh +52 -0
  11. tasks/moe/deepseek-node-dispatch-pack/instruction.md +219 -0
  12. tasks/moe/deepseek-node-dispatch-pack/task.toml +38 -0
  13. tasks/moe/deepseek-node-dispatch-pack/tests/test.sh +5 -0
  14. tasks/moe/deepseek-node-dispatch-pack/tests/verify_env.py +197 -0
  15. tasks/moe/fsdp-reduce-scatter-bucket/RUN.md +42 -0
  16. tasks/moe/fsdp-reduce-scatter-bucket/environment/CLAUDE.md +25 -0
  17. tasks/moe/fsdp-reduce-scatter-bucket/environment/Dockerfile +41 -0
  18. tasks/moe/fsdp-reduce-scatter-bucket/environment/PROCESS_MANAGEMENT.md +96 -0
  19. tasks/moe/fsdp-reduce-scatter-bucket/environment/docker-compose.yaml +18 -0
  20. tasks/moe/fsdp-reduce-scatter-bucket/environment/measure.py +142 -0
  21. tasks/moe/fsdp-reduce-scatter-bucket/environment/reference.py +34 -0
  22. tasks/moe/fsdp-reduce-scatter-bucket/environment/restrict-network.sh +52 -0
  23. tasks/moe/fsdp-reduce-scatter-bucket/environment/rs_copy_in.py +29 -0
  24. tasks/moe/fsdp-reduce-scatter-bucket/instruction.md +246 -0
  25. tasks/moe/fsdp-reduce-scatter-bucket/task.toml +38 -0
  26. tasks/moe/fsdp-reduce-scatter-bucket/tests/test.sh +5 -0
  27. tasks/moe/fsdp-reduce-scatter-bucket/tests/verify_env.py +215 -0
tasks/moe/README.md CHANGED
@@ -2,11 +2,13 @@
2
 
3
  Mixture-of-experts routing, permutation, grouped GEMM and combine.
4
 
5
- **15 tasks.**
6
 
7
  | task | metric | roofline | what the kernel does |
8
  |---|---|---|---|
 
9
  | [`fp8-grouped-gemm-masked`](fp8-grouped-gemm-masked/) | TFLOP/s | 687 us | MoE decode under CUDA graphs cannot change tensor shapes between steps, so the expert GEMM is given a fixed per-expert capacity and a device… |
 
10
  | [`grouped-fp8-gemm`](grouped-fp8-gemm/) | tokens/s | — | Write a fast grouped (mixture-of-experts) blockwise-FP8 GEMM — the MoE expert matmul: given FP8 (e4m3) grouped activations + per-expert weig… |
11
  | [`moe-capacity-drop-dispatch`](moe-capacity-drop-dispatch/) | GB/s | 483 us | Every MoE layer that runs on a fixed-shape expert buffer has to decide, per expert, which of the tokens routed to it actually fit: each expe… |
12
  | [`moe-combine-backward`](moe-combine-backward/) | GB/s | 581 us | Training an MoE layer means differentiating its last step, the weighted un-permute. The gradient splits in two directions that want opposite… |
@@ -21,3 +23,6 @@ Mixture-of-experts routing, permutation, grouped GEMM and combine.
21
  | [`moe-shared-expert-fused`](moe-shared-expert-fused/) | TFLOP/s | 1032 us | DeepSeek-V3 and Qwen3-MoE both keep one always-on 'shared' expert alongside the routed ones: every token goes through a dense SwiGLU FFN who… |
22
  | [`moe-token-permute`](moe-token-permute/) | GB/s | 205 us | Between the router and the expert GEMM every MoE layer has to physically reorder its tokens so that all rows going to the same expert are co… |
23
  | [`moe-topk-softmax-fused`](moe-topk-softmax-fused/) | GB/s | 277 us | The simplest and most widely deployed MoE router — Mixtral, Qwen3-MoE, GPT-OSS and every framework's default `topk_softmax`: soften the gate… |
 
 
 
 
2
 
3
  Mixture-of-experts routing, permutation, grouped GEMM and combine.
4
 
5
+ **20 tasks.**
6
 
7
  | task | metric | roofline | what the kernel does |
8
  |---|---|---|---|
9
+ | [`deepseek-node-dispatch-pack`](deepseek-node-dispatch-pack/) | GB/s | 456 us | DeepSeek-V3's node-limited routing exists so that a token's experts live on at most a handful of nodes — and the payoff is collected right h… |
10
  | [`fp8-grouped-gemm-masked`](fp8-grouped-gemm-masked/) | TFLOP/s | 687 us | MoE decode under CUDA graphs cannot change tensor shapes between steps, so the expert GEMM is given a fixed per-expert capacity and a device… |
11
+ | [`fsdp-reduce-scatter-bucket`](fsdp-reduce-scatter-bucket/) | GB/s | 569 us | Every FSDP backward ends by packing a whole unit's gradients into ONE reduce-scatter bucket: each parameter's rows split across the ranks an… |
12
  | [`grouped-fp8-gemm`](grouped-fp8-gemm/) | tokens/s | — | Write a fast grouped (mixture-of-experts) blockwise-FP8 GEMM — the MoE expert matmul: given FP8 (e4m3) grouped activations + per-expert weig… |
13
  | [`moe-capacity-drop-dispatch`](moe-capacity-drop-dispatch/) | GB/s | 483 us | Every MoE layer that runs on a fixed-shape expert buffer has to decide, per expert, which of the tokens routed to it actually fit: each expe… |
14
  | [`moe-combine-backward`](moe-combine-backward/) | GB/s | 581 us | Training an MoE layer means differentiating its last step, the weighted un-permute. The gradient splits in two directions that want opposite… |
 
23
  | [`moe-shared-expert-fused`](moe-shared-expert-fused/) | TFLOP/s | 1032 us | DeepSeek-V3 and Qwen3-MoE both keep one always-on 'shared' expert alongside the routed ones: every token goes through a dense SwiGLU FFN who… |
24
  | [`moe-token-permute`](moe-token-permute/) | GB/s | 205 us | Between the router and the expert GEMM every MoE layer has to physically reorder its tokens so that all rows going to the same expert are co… |
25
  | [`moe-topk-softmax-fused`](moe-topk-softmax-fused/) | GB/s | 277 us | The simplest and most widely deployed MoE router — Mixtral, Qwen3-MoE, GPT-OSS and every framework's default `topk_softmax`: soften the gate… |
26
+ | [`qwen3-moe-route-align`](qwen3-moe-route-align/) | GB/s | 331 us | Qwen3-Next routes every token to 10 of 512 experts, and the router is only half the job: before the grouped expert GEMM can launch, the rout… |
27
+ | [`swiglu-blockwise-fp8-quant`](swiglu-blockwise-fp8-quant/) | GB/s | 590 us | Between the two GEMMs of an FP8-served MLP there is exactly one elementwise step: split the fused gate/up projection, apply SwiGLU, and imme… |
28
+ | [`zero3-param-regroup`](zero3-param-regroup/) | GB/s | 469 us | ZeRO-3 does not all-gather 200 expert matrices one at a time — it coalesces them into fixed-capacity buckets first, walking the parameter li… |
tasks/moe/deepseek-node-dispatch-pack/RUN.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Running `deepseek-node-dispatch-pack`
2
+
3
+ DeepSeek-V3's node-limited routing exists so that a token's experts live on at most a handful of nodes — and the payoff is collected right here, in the kernel that builds the all-to-all send buffer. A token routed to four experts on the same node is sent to that node ONCE, not four times, so the dispatch has to deduplicate every token's expert set down to a node set, rank the tokens per node, and gather the hidden states into node-major order. It is the largest tensor in the layer moved once, with an index computation that is anything but a memcpy.
4
+
5
+ | | |
6
+ |---|---|
7
+ | **Task id** | `mle-bench/deepseek-node-dispatch-pack` |
8
+ | **Group** | `kernel-generation` |
9
+ | **GPUs** | 1 |
10
+ | **Agent edits** | `/app/dispatch_pack.py` |
11
+ | **Score** | achieved **GB/s** (uncapped speed leaderboard), `0` if incorrect |
12
+ | **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
13
+
14
+ ## Run through harbor
15
+
16
+ ```bash
17
+ harbor run --dataset-path kernel-generation/kernels/deepseek-node-dispatch-pack --task-name deepseek-node-dispatch-pack \
18
+ --agent claude-code --model anthropic/claude-opus-4-1 -e docker
19
+ ```
20
+
21
+ ## Run manually
22
+
23
+ ```bash
24
+ cd kernel-generation/kernels/deepseek-node-dispatch-pack
25
+ docker build -t deepseek-node-dispatch-pack environment/
26
+ docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep deepseek-node-dispatch-pack infinity
27
+ docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
28
+ docker rm -f v
29
+ ```
30
+
31
+ Use an **idle** GPU: the score is a timing measurement.
32
+
33
+ ## Design
34
+
35
+ Correctness is a hard gate; the score is an absolute hardware metric (GB/s), so the task is
36
+ hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
37
+
38
+ Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
39
+ copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
40
+ with the timed output itself validated, so memoize-and-replay fails the gate.
41
+
42
+ Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
tasks/moe/deepseek-node-dispatch-pack/environment/CLAUDE.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Working in this environment
2
+
3
+ ## ⚠️ Stop background processes without killing yourself
4
+
5
+ You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
6
+ file names and commands it mentions — is on **your own** process's command line. Any command that
7
+ finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
8
+ cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
9
+ (`NonZeroAgentExitCodeError`) and grading you on unfinished work.
10
+
11
+ This bites whenever you background something and later stop/restart it — a **server**, a long
12
+ **build** or **training run**, or an **ncu / nsys profiling** session.
13
+
14
+ **Always** manage a background process by its **exact recorded PID**, never by a name pattern:
15
+
16
+ ```bash
17
+ nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
18
+ kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
19
+ ```
20
+
21
+ Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
22
+ If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
23
+ **exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
24
+
25
+ Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
tasks/moe/deepseek-node-dispatch-pack/environment/Dockerfile ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kernel-generation task: Write a fast node-limited MoE dispatch (dedup + all-to-all send-buffer pack) kernel
2
+ #
3
+ # DeepSeek-V3's node-limited routing exists so that a token's experts live on at most a handful of nodes — and the payoff is collected right here, in the kernel that builds the all-to-all send buffer. A token routed to four experts on the same node is sent to that node ONCE, not four times, so the dispatch has to deduplicate every token's expert set down to a node set, rank the tokens per node, and gather the hidden states into node-major order. It is the largest tensor in the layer moved once, with an index computation that is anything but a memcpy.
4
+ #
5
+ # SCORING: correctness is a hard gate; the score is achieved GB/s (uncapped leaderboard, 0 if wrong).
6
+ # There is no gold solution and no oracle, so nothing has to be vendored or sealed.
7
+ #
8
+ # TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
9
+ # the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
10
+ # there is no internet, so nothing else can be obtained.
11
+ #
12
+ # GENERATED by _factory/build.py.
13
+ FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
14
+
15
+ # NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
16
+ # lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
17
+ RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
18
+ apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
19
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
20
+ /root/.local/bin/uv tool install mini-swe-agent
21
+ # header-only CUTLASS for the agent's CUDA/CuTe route
22
+ RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
23
+ # pre-bake Claude Code; harbor's claude_code.install() skips when present
24
+ RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
25
+ apt-get install -y nodejs procps && \
26
+ npm install -g @anthropic-ai/claude-code && claude --version
27
+ ENV PATH=/root/.local/bin:$PATH
28
+ ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
29
+
30
+ COPY restrict-network.sh /app/restrict-network.sh
31
+ RUN chmod +x /app/restrict-network.sh
32
+ # strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
33
+ RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
34
+
35
+ WORKDIR /app
36
+ COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
37
+
38
+ # task-specific files LAST so the layers above stay shared across every task
39
+ COPY reference.py /app/reference.py
40
+ COPY measure.py /app/measure.py
41
+ COPY dispatch_pack.py /app/dispatch_pack.py
tasks/moe/deepseek-node-dispatch-pack/environment/PROCESS_MANAGEMENT.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Managing background processes — READ THIS before you `kill` anything
2
+
3
+ You may start and stop background processes while iterating — a **server**, a long **build** or
4
+ **training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
5
+ *your own agent process* and end the whole run.** This has happened repeatedly, including via a
6
+ hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
7
+
8
+ ## The trap: matching task text against process command lines
9
+
10
+ You were launched as roughly:
11
+
12
+ ```
13
+ claude --print -- '<the entire task instruction text>'
14
+ ```
15
+
16
+ The full task instruction is on **your own** process's command line, and it contains the file names
17
+ and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
18
+ So **any** command that finds processes by matching those strings will match — and can kill — **the
19
+ agent itself**:
20
+
21
+ ```
22
+ pkill -9 -f "train.py" # matches the claude agent -> kills YOU
23
+ pgrep -f "server.py" | xargs kill # same: the pid list includes claude
24
+ for p in $(pgrep -f build.sh); do kill -9 $p; done # same
25
+ for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
26
+ ```
27
+
28
+ It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
29
+ a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
30
+ the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
31
+ immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
32
+ worse than what you were about to finish.
33
+
34
+ ## The one safe rule: kill only the exact PID you recorded
35
+
36
+ **Start** a background job and record its PID in a file:
37
+
38
+ ```bash
39
+ nohup <your command> > /tmp/job.log 2>&1 &
40
+ echo $! > /tmp/job.pid
41
+ ```
42
+
43
+ **Stop / restart** by that exact PID — never by a name pattern:
44
+
45
+ ```bash
46
+ kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
47
+ sleep 3
48
+ kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
49
+ ```
50
+
51
+ If the job spawns workers, run it in its own process group and signal the group by its (negative)
52
+ PGID — still an exact id, never a pattern:
53
+
54
+ ```bash
55
+ setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
56
+ kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
57
+ ```
58
+
59
+ ## If you ever enumerate processes, EXCLUDE the agent
60
+
61
+ Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
62
+ your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
63
+ a unique name and match only that:
64
+
65
+ ```bash
66
+ # job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
67
+ pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
68
+ # only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
69
+ ```
70
+
71
+ Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
72
+ single addition re-introduces the self-kill. Match the unique token **only**.
73
+
74
+ ## Freeing the GPU without going nuclear
75
+
76
+ If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
77
+ collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
78
+ `/proc` sweep:
79
+
80
+ - Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
81
+ the process fully exits.
82
+ - Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
83
+ single `kill $PID` is enough.
84
+ - Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
85
+ - Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
86
+ confirming its cmdline is **not** `claude` / `--print`.
87
+
88
+ ## Rules of thumb
89
+
90
+ - **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
91
+ with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
92
+ agent (its argv holds the prompt).
93
+ - **Always** kill a background job by the exact PID from its pidfile (or its PGID).
94
+ - If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
95
+ and your own shell**; `pgrep -af` and look before you kill.
96
+ - `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
tasks/moe/deepseek-node-dispatch-pack/environment/dispatch_pack.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Your implementation goes here.
2
+
3
+ Replace the body of `node_dispatch_pack` with a FAST implementation that reproduces the output of /app/reference.py
4
+ (same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
5
+ Run `python /app/measure.py` to check your correctness and achieved GB/s.
6
+
7
+ You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
8
+ signature and returned value are fixed by the contract.
9
+ """
10
+
11
+
12
+ def node_dispatch_pack(x, topk_ids, num_nodes, experts_per_node):
13
+ """Node-limited MoE dispatch: dedup to node sets and pack the all-to-all send buffer.
14
+
15
+ Args:
16
+ x: (T, H) bfloat16 — token hidden states.
17
+ topk_ids: (T, K) int32 — the K expert ids chosen for each token (distinct within a row).
18
+ num_nodes: int — N, the number of expert-parallel nodes.
19
+ experts_per_node: int — EPN; expert e lives on node e // EPN.
20
+
21
+ Returns:
22
+ (send_buf, src_token, node_counts, node_offsets) where
23
+ send_buf: (T*M, H) bfloat16 — hidden states in NODE-MAJOR order, tokens ascending inside a node
24
+ src_token: (T*M,) int32 — the token each packed row came from
25
+ node_counts: (N,) int32 — rows destined for each node
26
+ node_offsets: (N+1,) int32 — node n owns rows [node_offsets[n], node_offsets[n+1])
27
+ M is the (fixed) number of distinct nodes every token's experts span, so T*M rows are always
28
+ produced.
29
+ """
30
+ raise NotImplementedError("Implement a fast node_dispatch_pack in /app/dispatch_pack.py")
tasks/moe/deepseek-node-dispatch-pack/environment/docker-compose.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
2
+ # NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
3
+ # reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
4
+ # Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
5
+ # the (now-blocked) network install when it is already present.
6
+ services:
7
+ main:
8
+ cap_add:
9
+ - NET_ADMIN
10
+ entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
11
+ environment:
12
+ - ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
13
+ - FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
14
+ - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
15
+ - OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
16
+ - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
17
+ - LLM_BASE_URL=${LLM_BASE_URL:-}
18
+ - LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
tasks/moe/deepseek-node-dispatch-pack/environment/measure.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-assessment tool — your correctness + achieved GB/s across a RANGE of shapes.
2
+
3
+ python /app/measure.py # the graded regime
4
+ python /app/measure.py --quick # smaller sizes for fast iteration
5
+
6
+ You are scored on the **geomean achieved GB/s** — NOT one fixed size, and the leaderboard is UNCAPPED
7
+ (higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
8
+ optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
9
+ printed here is computed exactly as your score is.
10
+
11
+ GENERATED by _factory/build.py.
12
+ """
13
+ import argparse
14
+ import math
15
+ import sys
16
+
17
+ import torch
18
+
19
+ sys.path.insert(0, "/app")
20
+ from reference import node_dispatch_pack as _ref
21
+ from dispatch_pack import node_dispatch_pack as _agent
22
+
23
+ TOL = 1e-05
24
+ NAMES = ('send_buf', 'src_token', 'node_counts', 'node_offsets')
25
+
26
+ FULL = [(28672, 7168, 8, 8, 4, 32), (20480, 7168, 8, 8, 4, 32), (40960, 4096, 8, 8, 4, 32), (28672, 7168, 6, 8, 3, 32), (28672, 5120, 8, 4, 3, 64)]
27
+ QUICK = [(4096, 2048, 8, 8, 4, 32), (8192, 1024, 6, 4, 3, 16), (2048, 4096, 8, 8, 2, 32)]
28
+
29
+ def canonical_work(T, H, K, N, M, EPN):
30
+ """BYTES attributed to one dispatch pack, from the SHAPE ALONE.
31
+
32
+ The unavoidable traffic: read the (T, H) bf16 hidden states once, read the (T, K) int32 routing table,
33
+ write the (T*M, H) bf16 send buffer and the (T*M,) int32 source map. The membership bitset, the
34
+ per-node counters and the prefix sum are tiny and never need to reach HBM. Node-limited routing fixes
35
+ the number of copies at exactly M per token, so this is a function of the shape alone. This is a
36
+ memory-bound kernel, so the score is achieved bandwidth against this fixed byte count.
37
+ """
38
+ return 2 * T * H + 4 * T * K + 2 * T * M * H + 4 * T * M + 4 * (2 * N + 1)
39
+
40
+ def _mk(T, H, K, N, M, EPN, seed):
41
+ """Hidden states plus a NODE-LIMITED routing table: every token's K experts are distinct and span
42
+ EXACTLY M distinct nodes, which is what the node-limited router guarantees and what makes the packed
43
+ length T*M a function of the shape alone.
44
+
45
+ Slot j of a token goes to the (j % M)-th of its M chosen nodes, and takes the (j // M)-th entry of a
46
+ random permutation of that node's experts — so the K experts are always distinct.
47
+ """
48
+ gen = torch.Generator(device="cuda").manual_seed(seed)
49
+ x = torch.randn(T, H, device="cuda", dtype=torch.bfloat16, generator=gen)
50
+
51
+ nodes = torch.rand(T, N, device="cuda", generator=gen).argsort(dim=-1)[:, :M] # (T, M) distinct
52
+ perm = torch.rand(T, M, EPN, device="cuda", generator=gen).argsort(dim=-1) # (T, M, EPN)
53
+ j = torch.arange(K, device="cuda")
54
+ m, r = j % M, j // M
55
+ sel_node = nodes[:, m] # (T, K)
56
+ sel_off = perm[:, m, r] # (T, K)
57
+ topk_ids = (sel_node * EPN + sel_off).to(torch.int32)
58
+ del nodes, perm, sel_node, sel_off
59
+ return x, topk_ids.contiguous(), N, EPN
60
+
61
+
62
+ def _check(out, ref):
63
+ """-> (ok, value, msg). value = MAX relative error across the returned tuple."""
64
+ if out is None or len(out) != len(NAMES):
65
+ return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
66
+ per = []
67
+ for n, a, b in zip(NAMES, out, ref):
68
+ if a is None or tuple(a.shape) != tuple(b.shape):
69
+ return False, 1.0, f"{n} bad shape"
70
+ if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
71
+ # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
72
+ bad = int((a != b).sum())
73
+ if bad:
74
+ return False, 1.0, f"{n}: {bad} elements differ"
75
+ continue
76
+ per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
77
+ if not per:
78
+ return True, 0.0, "all integer outputs exact"
79
+ wn, wv = max(per, key=lambda x: x[1])
80
+ return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
81
+
82
+
83
+ def _bench(fn, reps=8, warm=3):
84
+ for _ in range(warm):
85
+ fn()
86
+ torch.cuda.synchronize()
87
+ best = float("inf")
88
+ for _ in range(reps):
89
+ s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
90
+ s.record()
91
+ fn()
92
+ e.record()
93
+ torch.cuda.synchronize()
94
+ best = min(best, s.elapsed_time(e))
95
+ return best / 1e3
96
+
97
+
98
+ def main():
99
+ ap = argparse.ArgumentParser()
100
+ ap.add_argument("--quick", action="store_true")
101
+ a = ap.parse_args()
102
+ shapes = QUICK if a.quick else FULL
103
+ print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
104
+ f"DIFFERENT sizes in the same regime — optimize for generality\n")
105
+ vals, allok = [], True
106
+ for shp in shapes:
107
+ args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
108
+ ref = _ref(*args)
109
+ try:
110
+ out = _agent(*args)
111
+ except Exception as ex:
112
+ print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
113
+ allok = False
114
+ continue
115
+ ok, val, msg = _check(out, ref)
116
+ allok = allok and ok
117
+ t = _bench(lambda: _agent(*args))
118
+ v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
119
+ vals.append(v)
120
+ print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} GB/s | {msg} {'ok' if ok else 'FAIL'}")
121
+ del args, ref, out
122
+ torch.cuda.empty_cache()
123
+ geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
124
+ print(f"\n => GEOMEAN {geo:.2f} GB/s "
125
+ f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
126
+ print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
tasks/moe/deepseek-node-dispatch-pack/environment/reference.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference implementation — the CORRECTNESS SPEC for `node_dispatch_pack`.
2
+
3
+ This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
4
+ bearing on your score, which is an absolute GB/s number. GENERATED by _factory/build.py.
5
+ """
6
+ import torch
7
+
8
+
9
+ def node_dispatch_pack(x, topk_ids, num_nodes, experts_per_node):
10
+ """Deduplicate each token's experts to a node set, then gather node-major.
11
+
12
+ Correct and simple — it is the exact SPECIFICATION, not a performance target. It materialises a dense
13
+ (T, N) boolean membership matrix and lets `nonzero` do the ordering and the ranking, which is exactly
14
+ the multi-pass shape a real kernel replaces with one privatised histogram and one gather.
15
+ """
16
+ T, K = topk_ids.shape
17
+ node = topk_ids.to(torch.int64) // experts_per_node # (T, K) node of every routed slot
18
+ member = torch.zeros(T, num_nodes, dtype=torch.bool, device=x.device)
19
+ member.scatter_(1, node, True) # DEDUP: token -> set of nodes
20
+
21
+ pairs = member.t().nonzero() # (R, 2) = [node, token], node-major, token-ascending
22
+ src = pairs[:, 1]
23
+ send_buf = x[src] # the gather
24
+
25
+ counts = member.sum(0).to(torch.int32) # rows per node
26
+ offsets = torch.cat([torch.zeros(1, dtype=torch.int32, device=x.device),
27
+ torch.cumsum(counts, 0).to(torch.int32)])
28
+ return send_buf, src.to(torch.int32), counts, offsets
tasks/moe/deepseek-node-dispatch-pack/environment/restrict-network.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
3
+ # endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
4
+ # so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
5
+ # copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
6
+ # installer skips the network install when it is already present), so no package index is needed at run time.
7
+ #
8
+ # Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
9
+ # apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
10
+ set -uo pipefail
11
+
12
+ # LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
13
+ API_HOSTS=(
14
+ api.fireworks.ai
15
+ openrouter.ai openrouter.io
16
+ api.openai.com api.anthropic.com generativelanguage.googleapis.com
17
+ api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
18
+ )
19
+ # Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
20
+ CUSTOM=()
21
+ while IFS='=' read -r n v; do
22
+ case "$n" in
23
+ *_BASE_URL|*_URL|*_ENDPOINT)
24
+ [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
25
+ esac
26
+ done < <(env)
27
+ if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
28
+ ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
29
+
30
+ if iptables -L OUTPUT -n >/dev/null 2>&1; then
31
+ echo "restrict-network: applying outbound allowlist firewall..."
32
+ iptables -F OUTPUT 2>/dev/null || true
33
+ iptables -A OUTPUT -o lo -j ACCEPT
34
+ iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
35
+ iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
36
+ iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
37
+ iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
38
+ iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
39
+ iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
40
+ iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
41
+ for h in "${ALL_HOSTS[@]}"; do
42
+ for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
43
+ iptables -A OUTPUT -d "$ip" -j ACCEPT
44
+ done
45
+ done
46
+ iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
47
+ echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
48
+ else
49
+ echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
50
+ fi
51
+
52
+ exec "$@"
tasks/moe/deepseek-node-dispatch-pack/instruction.md ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Write a fast node-limited MoE dispatch (dedup + all-to-all send-buffer pack) kernel
2
+
3
+ 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.**
4
+
5
+ Write **`/app/dispatch_pack.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
6
+
7
+ ```python
8
+ def node_dispatch_pack(x, topk_ids, num_nodes, experts_per_node):
9
+ ...
10
+ ```
11
+
12
+ ## The computation (this is the exact spec)
13
+
14
+ In expert-parallel serving the experts are spread over `N` nodes — expert `e` lives on node
15
+ `e // EPN` — and before the all-to-all can run, every token's hidden state has to be copied into the send
16
+ buffer of each node that owns one of its experts.
17
+
18
+ **The dedup is the point.** A token routed to four experts that happen to live on the same node is sent to
19
+ that node **once**. So the first step is to turn each token's `K` expert ids into a *set* of nodes:
20
+
21
+ ```
22
+ node[t, j] = topk_ids[t, j] // EPN
23
+ member[t,n] = True iff any j has node[t, j] == n
24
+ ```
25
+
26
+ DeepSeek's node-limited routing guarantees each token's experts span exactly `M` distinct nodes, so
27
+ `member` has exactly `M` true entries per row and the packed buffer is exactly `T*M` rows long.
28
+
29
+ **The packing is node-major, token-ascending inside a node:**
30
+
31
+ ```
32
+ node_counts[n] = number of tokens with member[t, n]
33
+ node_offsets = [0, cumsum(node_counts)] # (N+1,)
34
+ ```
35
+
36
+ Node `n` owns rows `[node_offsets[n], node_offsets[n+1])` of `send_buf`, and those rows hold its tokens in
37
+ **increasing token index**. Formally, if `r` is the rank of token `t` among the tokens that chose node `n`
38
+ (counting in increasing `t`):
39
+
40
+ ```
41
+ send_buf[node_offsets[n] + r, :] = x[t, :]
42
+ src_token[node_offsets[n] + r] = t
43
+ ```
44
+
45
+ `src_token` is what the combine step later uses to scatter the expert outputs back, so it is part of the
46
+ contract, not a debugging aid.
47
+
48
+ Note what is **not** asked for: no per-expert grouping, no weights, no padding. This is the transport
49
+ layer — one copy of each token per destination node, in the order the receiver expects.
50
+
51
+ `/app/reference.py` builds a dense `(T, N)` boolean matrix and lets `nonzero` produce the ordering. That is
52
+ the exact specification; it is deliberately simple rather than fast.
53
+
54
+ ## The contract (fixed — do not change these)
55
+
56
+ | arg | shape | dtype | meaning |
57
+ |-----|-------|-------|---------|
58
+ | `x` | `(T, H)` | `bfloat16` | token hidden states |
59
+ | `topk_ids` | `(T, K)` | `int32` | the `K` expert ids per token, **distinct within a row** |
60
+ | `num_nodes` | int | | `N` |
61
+ | `experts_per_node` | int | | `EPN`; expert `e` is on node `e // EPN` |
62
+
63
+ **Return a 4-tuple in exactly this order:**
64
+
65
+ | out | shape | dtype | notes |
66
+ |-----|-------|-------|-------|
67
+ | `send_buf` | `(T*M, H)` | `bfloat16` | node-major, token-ascending inside each node |
68
+ | `src_token` | `(T*M,)` | `int32` | source token of each packed row; compared **exactly** |
69
+ | `node_counts` | `(N,)` | `int32` | compared **exactly** |
70
+ | `node_offsets` | `(N+1,)` | `int32` | exclusive prefix sum, `node_offsets[N] == T*M`; compared **exactly** |
71
+
72
+ `M` — the number of distinct nodes each token's experts span — is **fixed for a given call** and is what
73
+ makes `T*M` a shape-only quantity; you can compute it, but you do not need to guess it, because
74
+ `send_buf`'s length follows from the routing table you are given.
75
+
76
+ All inputs are **read-only**; the copy is functional. `T` is **not** guaranteed to be a multiple of any
77
+ tile size — the correctness shapes include `T = 129`.
78
+
79
+ **Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `T`
80
+ (tokens in the micro-batch) in 24576–49152, `H` in 4096–7168, `K` in 6–8, `N` (nodes) 4 or 8, `M`
81
+ (distinct nodes per token) 3 or 4, `EPN` in 32–64. The send buffer is 3–4x the size of the input, so this
82
+ call moves more bytes than any other single op in the MoE layer.
83
+
84
+ ## How success is decided (runs on GPU)
85
+
86
+ **1. Correctness — a required gate.** Three of the four outputs are **integer** and are compared **bit-exactly** — one
87
+ wrong row index anywhere and the score is 0. `send_buf` is a pure gather, so a correct kernel reproduces it
88
+ **bit for bit**; its `1e-5` gate exists only to reject a change of dtype.
89
+
90
+ The ordering rules are an exact specification, not a convention: **node-major** blocks, **ascending token
91
+ index** inside each block. Two variants that break them were tried and both fail outright — packing
92
+ token-major (all of token 0's copies, then token 1's) and leaving the tokens unsorted inside a node. So
93
+ does skipping the dedup and emitting one row per expert slot, which produces `T*K` rows instead of `T*M`
94
+ and fails on shape. A wrong kernel scores **0**, no matter how fast.
95
+
96
+ **2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
97
+
98
+ ```
99
+ reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [GB/s]
100
+ reward = 0 if the submission is wrong at any graded shape
101
+ ```
102
+
103
+ `canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
104
+ credited the same work and this is a pure speed ranking in useful units:
105
+
106
+ ```
107
+ bytes = 2*T*H + 4*T*K + 2*T*M*H + 4*T*M + 4*(2*N+1)
108
+ # read x read ids write buf src map counts+offsets
109
+ ```
110
+
111
+ **There is no cap and no target.** Higher GB/s is always a strictly better score, so **push the
112
+ performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
113
+ it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
114
+ after every change. **Use your full time budget.**
115
+
116
+ Run **`python /app/measure.py`** at any point to see your per-shape and geomean GB/s plus correctness.
117
+
118
+ ## Where the performance comes from
119
+
120
+ One read of `x`, `M` writes of each row, and an index computation in between. The floor is
121
+ `(1 + M)` passes over a `(T, H)`-sized tensor and nothing else, which is what the byte count assumes.
122
+
123
+ The index side is small but it is where the naive version dies. The reference's `(T, N)` boolean matrix,
124
+ `nonzero`, and the implied sort cost several passes over `T*N` and a device-wide scan. What it actually is:
125
+
126
+ * a **bitset per token** — `N <= 8` nodes fit in one byte, so the dedup is `mask |= 1 << (e // EPN)` over
127
+ `K` ids, entirely in registers;
128
+ * a **histogram** of `N` counters, which wants per-block privatised counters and one atomic per block per
129
+ node, not one atomic per token;
130
+ * a **prefix sum over `N <= 8` numbers**, which is one warp;
131
+ * a **rank within node**, which is the block's own offset plus a lane prefix — again no global sort.
132
+
133
+ Then the gather. Each destination row is a full `H`-wide bf16 copy (8–14 KB), so use vectorised 128-bit
134
+ accesses and give each row enough lanes to saturate; the read of `x[t]` serves all `M` of its destinations,
135
+ so a block that has a token's row in registers or shared memory should write **all** its copies before
136
+ moving on — reading `x` once instead of `M` times is a 25–33% bandwidth saving on its own.
137
+
138
+ The destinations of one token are `M` widely separated offsets, so the writes are scattered at row
139
+ granularity but perfectly coalesced within a row. Prefer a grid over (token tile) with the row resident,
140
+ rather than a grid over output rows that re-reads the source.
141
+
142
+ ## Precision and faithfulness (read this)
143
+
144
+ `x` and `send_buf` are **bfloat16** and the copy is exact — no arithmetic happens to
145
+ the payload at all, so a correct kernel is bit-identical to the reference and the `1e-5` gate is
146
+ effectively an exactness check. Returning `send_buf` in fp32 would change the contract (and cost twice the
147
+ bandwidth for no benefit); returning it in fp8 would be a lossy transform of data that is supposed to be
148
+ transported unchanged.
149
+
150
+ The three integer outputs are compared **exactly**: `.float()` is lossy above 2^24 and `T*M` reaches
151
+ 200000 here, so the grader never converts them.
152
+
153
+ **Where the tolerance comes from.** It is measured, and the measurement is that there is nothing to
154
+ measure: an independent implementation — the membership computed as a per-token bitmask, the ranking from
155
+ a scatter-add histogram plus a segmented rank instead of `nonzero`, and the gather written as an explicit
156
+ row copy — differs from this reference by a relative Frobenius error of exactly **0.0e+00** on `send_buf`
157
+ and reproduces all three integer outputs **bit for bit**, at every correctness shape and at a full-size
158
+ graded shape, over several seeds. The gate is set at `1e-5` rather than at zero only so that a legitimate
159
+ bf16 round-trip cannot fail on a denormal; it admits nothing except the specified bf16 payload, and in
160
+ particular an fp8 or fp16 payload would miss it by 1e-3 or more.
161
+
162
+ ### What the tolerance does NOT permit
163
+
164
+ The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
165
+ implementation of the specified computation**. It is not a budget to spend on approximation. The following
166
+ are wrong answers even if they happen to land inside the tolerance at some shape:
167
+
168
+ - changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
169
+ series, low-rank or sketched substitutes, skipping a correction term);
170
+ - shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
171
+ or striding over the sequence, ignoring positions whose contribution "looks small");
172
+ - computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
173
+ that the spec gives their own);
174
+ - anything whose error **grows** with sequence length, batch, or head count.
175
+
176
+ A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
177
+ magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
178
+ are deliberately large, so the difference shows up.
179
+
180
+ ## What's available
181
+
182
+ - **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
183
+ extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
184
+ (`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
185
+ - `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
186
+ - A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist.
187
+ The exact part is deliberately **not** stated: query it and tune to what you actually find.
188
+
189
+ ```python
190
+ p = torch.cuda.get_device_properties(0)
191
+ p.name, p.major, p.minor # part and compute capability
192
+ p.multi_processor_count # SM count -- size your persistent grid from this, never a constant
193
+ p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor
194
+ p.shared_memory_per_block_optin # opt-in dynamic smem, the number that matters for big tiles
195
+ ```
196
+
197
+ `nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK`
198
+ give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a
199
+ datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak
200
+ FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the
201
+ score is an absolute metric, so a kernel tuned to a machine it never sees is just slower.
202
+ - **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
203
+ already installed, and no library implementation of this kernel exists on the machine.
204
+ - Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
205
+ `/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
206
+
207
+ ## How the grading actually runs (so there are no surprises)
208
+
209
+ - **`/app/dispatch_pack.py` is the only file that is graded.** The grader imports `node_dispatch_pack` from it and reads nothing
210
+ else from `/app`.
211
+ - **The grader is not on this machine while you work.** It is copied in only after your session ends and it
212
+ carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
213
+ or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
214
+ your score**. Do not spend budget on them.
215
+ - **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
216
+ against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
217
+ than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
218
+ - **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
219
+ - Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
tasks/moe/deepseek-node-dispatch-pack/task.toml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.1"
2
+
3
+ [task]
4
+ name = "mle-bench/deepseek-node-dispatch-pack"
5
+ description = "DeepSeek-V3's node-limited routing exists so that a token's experts live on at most a handful of nodes — and the payoff is collected right here, in the kernel that builds the all-to-all send buffer. A token routed to four experts on the same node is sent to that node ONCE, not four times, so the dispatch has to deduplicate every token's expert set down to a node set, rank the tokens per node, and gather the hidden states into node-major order. It is the largest tensor in the layer moved once, with an index computation that is anything but a memcpy."
6
+ authors = []
7
+ keywords = ["mle", "kernel-generation", "moe", "expert-parallel", "dispatch", "all-to-all", "deepseek", "node-limited", "gather", "memory-bound"]
8
+
9
+ [metadata]
10
+ suite = "mle-bench"
11
+ group = "kernel-generation"
12
+ level = "1.0"
13
+ difficulty = "hard"
14
+ category = "mle"
15
+ tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]
16
+
17
+ [verifier]
18
+ timeout_sec = 1800.0
19
+
20
+ [agent]
21
+ timeout_sec = 14400.0
22
+
23
+ # GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
24
+ # in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
25
+ [environment]
26
+ build_timeout_sec = 3600.0
27
+ cpus = 8
28
+ memory_mb = 65536
29
+ storage_mb = 40960
30
+ gpus = 1
31
+ network_mode = "public"
32
+ mcp_servers = []
33
+
34
+ [verifier.env]
35
+
36
+ [environment.env]
37
+
38
+ [solution.env]
tasks/moe/deepseek-node-dispatch-pack/tests/test.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.
3
+ set -u
4
+ mkdir -p /logs/verifier
5
+ python3 /tests/verify_env.py
tasks/moe/deepseek-node-dispatch-pack/tests/verify_env.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """deepseek-node-dispatch-pack verifier — correctness gate + achieved-GB/s SPEED LEADERBOARD (uncapped).
2
+
3
+ reward = 0 if the submission is incorrect
4
+ reward = geomean over graded shapes of GB/s otherwise
5
+
6
+ GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
7
+
8
+ There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
9
+ by construction and nothing has to be vendored, sealed, or re-benchmarked.
10
+
11
+ CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
12
+ shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
13
+ scores 0.
14
+
15
+ ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
16
+ timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
17
+ result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
18
+ throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
19
+
20
+ WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
21
+ submissions are credited identically and the ranking is a pure speed ranking.
22
+ """
23
+ import importlib.util
24
+ import json
25
+ import math
26
+ import os
27
+ import sys
28
+ import traceback
29
+
30
+ import torch
31
+
32
+ REWARD_DIR = "/logs/verifier"
33
+ MODULE_PATH = "/app/dispatch_pack.py"
34
+ TOL = 1e-05
35
+ NAMES = ('send_buf', 'src_token', 'node_counts', 'node_offsets')
36
+
37
+ GRADER_SHAPES = [(32768, 7168, 8, 8, 4, 32), (24576, 7168, 8, 8, 4, 32), (49152, 4096, 8, 8, 4, 32), (32768, 7168, 6, 8, 3, 32), (32768, 5120, 8, 4, 3, 64)]
38
+ CORRECT_SHAPES = [(256, 512, 8, 4, 2, 16), (129, 256, 6, 4, 3, 8), (512, 1024, 8, 8, 4, 16), (64, 128, 4, 4, 2, 8)]
39
+
40
+ sys.path.insert(0, "/app")
41
+
42
+ def canonical_work(T, H, K, N, M, EPN):
43
+ """BYTES attributed to one dispatch pack, from the SHAPE ALONE.
44
+
45
+ The unavoidable traffic: read the (T, H) bf16 hidden states once, read the (T, K) int32 routing table,
46
+ write the (T*M, H) bf16 send buffer and the (T*M,) int32 source map. The membership bitset, the
47
+ per-node counters and the prefix sum are tiny and never need to reach HBM. Node-limited routing fixes
48
+ the number of copies at exactly M per token, so this is a function of the shape alone. This is a
49
+ memory-bound kernel, so the score is achieved bandwidth against this fixed byte count.
50
+ """
51
+ return 2 * T * H + 4 * T * K + 2 * T * M * H + 4 * T * M + 4 * (2 * N + 1)
52
+
53
+ def _ref(x, topk_ids, num_nodes, experts_per_node):
54
+ """Deduplicate each token's experts to a node set, then gather node-major.
55
+
56
+ Correct and simple — it is the exact SPECIFICATION, not a performance target. It materialises a dense
57
+ (T, N) boolean membership matrix and lets `nonzero` do the ordering and the ranking, which is exactly
58
+ the multi-pass shape a real kernel replaces with one privatised histogram and one gather.
59
+ """
60
+ T, K = topk_ids.shape
61
+ node = topk_ids.to(torch.int64) // experts_per_node # (T, K) node of every routed slot
62
+ member = torch.zeros(T, num_nodes, dtype=torch.bool, device=x.device)
63
+ member.scatter_(1, node, True) # DEDUP: token -> set of nodes
64
+
65
+ pairs = member.t().nonzero() # (R, 2) = [node, token], node-major, token-ascending
66
+ src = pairs[:, 1]
67
+ send_buf = x[src] # the gather
68
+
69
+ counts = member.sum(0).to(torch.int32) # rows per node
70
+ offsets = torch.cat([torch.zeros(1, dtype=torch.int32, device=x.device),
71
+ torch.cumsum(counts, 0).to(torch.int32)])
72
+ return send_buf, src.to(torch.int32), counts, offsets
73
+
74
+ def _mk(T, H, K, N, M, EPN, seed):
75
+ """Hidden states plus a NODE-LIMITED routing table: every token's K experts are distinct and span
76
+ EXACTLY M distinct nodes, which is what the node-limited router guarantees and what makes the packed
77
+ length T*M a function of the shape alone.
78
+
79
+ Slot j of a token goes to the (j % M)-th of its M chosen nodes, and takes the (j // M)-th entry of a
80
+ random permutation of that node's experts — so the K experts are always distinct.
81
+ """
82
+ gen = torch.Generator(device="cuda").manual_seed(seed)
83
+ x = torch.randn(T, H, device="cuda", dtype=torch.bfloat16, generator=gen)
84
+
85
+ nodes = torch.rand(T, N, device="cuda", generator=gen).argsort(dim=-1)[:, :M] # (T, M) distinct
86
+ perm = torch.rand(T, M, EPN, device="cuda", generator=gen).argsort(dim=-1) # (T, M, EPN)
87
+ j = torch.arange(K, device="cuda")
88
+ m, r = j % M, j // M
89
+ sel_node = nodes[:, m] # (T, K)
90
+ sel_off = perm[:, m, r] # (T, K)
91
+ topk_ids = (sel_node * EPN + sel_off).to(torch.int32)
92
+ del nodes, perm, sel_node, sel_off
93
+ return x, topk_ids.contiguous(), N, EPN
94
+
95
+
96
+ def _check(out, ref):
97
+ """-> (ok, value, msg). value = MAX relative error across the returned tuple."""
98
+ if out is None or len(out) != len(NAMES):
99
+ return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
100
+ per = []
101
+ for n, a, b in zip(NAMES, out, ref):
102
+ if a is None or tuple(a.shape) != tuple(b.shape):
103
+ return False, 1.0, f"{n} bad shape"
104
+ if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
105
+ # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
106
+ bad = int((a != b).sum())
107
+ if bad:
108
+ return False, 1.0, f"{n}: {bad} elements differ"
109
+ continue
110
+ per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
111
+ if not per:
112
+ return True, 0.0, "all integer outputs exact"
113
+ wn, wv = max(per, key=lambda x: x[1])
114
+ return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
115
+
116
+
117
+ def _bench_fresh(fn, mkargs, reps=5, warm=3):
118
+ """Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
119
+ wargs = mkargs(0)
120
+ for _ in range(warm):
121
+ fn(*wargs)
122
+ torch.cuda.synchronize()
123
+ del wargs
124
+ torch.cuda.empty_cache()
125
+
126
+ best, timed_ok = float("inf"), True
127
+ for i in range(reps):
128
+ args = mkargs(10_000 + i)
129
+ s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
130
+ s.record()
131
+ out = fn(*args)
132
+ e.record()
133
+ torch.cuda.synchronize()
134
+ best = min(best, s.elapsed_time(e))
135
+ if i == reps - 1:
136
+ timed_ok = _check(out, _ref(*args))[0]
137
+ del args, out
138
+ torch.cuda.empty_cache()
139
+ return best / 1e3, timed_ok
140
+
141
+
142
+ def _geomean(xs):
143
+ return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
144
+
145
+
146
+ def main():
147
+ details, correct_gate, geo = {}, False, 0.0
148
+ try:
149
+ spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
150
+ m = importlib.util.module_from_spec(spec)
151
+ spec.loader.exec_module(m)
152
+ fn = m.node_dispatch_pack
153
+
154
+ corr_ok, msg = True, ""
155
+ for i, shp in enumerate(CORRECT_SHAPES):
156
+ args = _mk(*shp, seed=10 + i)
157
+ ok, val, m_ = _check(fn(*args), _ref(*args))
158
+ if not ok:
159
+ corr_ok, msg = False, f"cfg{i} {shp} {m_}"
160
+ break
161
+ del args
162
+ torch.cuda.empty_cache()
163
+ details["correct_msg"] = msg or "all correctness shapes pass"
164
+
165
+ vals, per_shape, perf_ok = [], [], corr_ok
166
+ for i, shp in enumerate(GRADER_SHAPES):
167
+ args = _mk(*shp, seed=100 + i)
168
+ ok, val, m_ = _check(fn(*args), _ref(*args))
169
+ if not ok:
170
+ perf_ok = False
171
+ del args
172
+ torch.cuda.empty_cache()
173
+ t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
174
+ if not timed_ok:
175
+ perf_ok = False
176
+ v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
177
+ vals.append(v)
178
+ per_shape.append({"shape": list(shp), "gbps": round(v, 3), "ms": round(t * 1e3, 3),
179
+ "check": m_, "timed_ok": timed_ok})
180
+ geo = _geomean(vals)
181
+ details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
182
+ correct_gate = corr_ok and perf_ok
183
+ except Exception as e:
184
+ details["error"] = f"{e.__class__.__name__}: {e}"[:220]
185
+ details["trace"] = traceback.format_exc()[-800:]
186
+
187
+ reward = round(geo, 4) if correct_gate else 0.0
188
+ os.makedirs(REWARD_DIR, exist_ok=True)
189
+ json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
190
+ "geomean": round(geo, 4), "metric": "GB/s (geomean over graded shapes)"},
191
+ open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
192
+ open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
193
+ json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
194
+ print("reward:", reward, "GB/s | correct:", 1.0 if correct_gate else 0.0)
195
+
196
+
197
+ main()
tasks/moe/fsdp-reduce-scatter-bucket/RUN.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Running `fsdp-reduce-scatter-bucket`
2
+
3
+ Every FSDP backward ends by packing a whole unit's gradients into ONE reduce-scatter bucket: each parameter's rows split across the ranks and written rank-major, the padding rows zeroed so they cannot poison the sum, the whole thing pre-divided by the world size and cast down to the bf16 reduce dtype — and, since every element is already in registers, the per-parameter squared gradient norm the clipper needs falls out of the same pass. On an MoE unit that is hundreds of expert matrices and gigabytes of fp32 gradient, and it is what the backward waits on.
4
+
5
+ | | |
6
+ |---|---|
7
+ | **Task id** | `mle-bench/fsdp-reduce-scatter-bucket` |
8
+ | **Group** | `kernel-generation` |
9
+ | **GPUs** | 1 |
10
+ | **Agent edits** | `/app/rs_copy_in.py` |
11
+ | **Score** | achieved **GB/s** (uncapped speed leaderboard), `0` if incorrect |
12
+ | **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
13
+
14
+ ## Run through harbor
15
+
16
+ ```bash
17
+ harbor run --dataset-path kernel-generation/kernels/fsdp-reduce-scatter-bucket --task-name fsdp-reduce-scatter-bucket \
18
+ --agent claude-code --model anthropic/claude-opus-4-1 -e docker
19
+ ```
20
+
21
+ ## Run manually
22
+
23
+ ```bash
24
+ cd kernel-generation/kernels/fsdp-reduce-scatter-bucket
25
+ docker build -t fsdp-reduce-scatter-bucket environment/
26
+ docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep fsdp-reduce-scatter-bucket infinity
27
+ docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
28
+ docker rm -f v
29
+ ```
30
+
31
+ Use an **idle** GPU: the score is a timing measurement.
32
+
33
+ ## Design
34
+
35
+ Correctness is a hard gate; the score is an absolute hardware metric (GB/s), so the task is
36
+ hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
37
+
38
+ Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
39
+ copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
40
+ with the timed output itself validated, so memoize-and-replay fails the gate.
41
+
42
+ Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
tasks/moe/fsdp-reduce-scatter-bucket/environment/CLAUDE.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Working in this environment
2
+
3
+ ## ⚠️ Stop background processes without killing yourself
4
+
5
+ You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
6
+ file names and commands it mentions — is on **your own** process's command line. Any command that
7
+ finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
8
+ cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
9
+ (`NonZeroAgentExitCodeError`) and grading you on unfinished work.
10
+
11
+ This bites whenever you background something and later stop/restart it — a **server**, a long
12
+ **build** or **training run**, or an **ncu / nsys profiling** session.
13
+
14
+ **Always** manage a background process by its **exact recorded PID**, never by a name pattern:
15
+
16
+ ```bash
17
+ nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
18
+ kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
19
+ ```
20
+
21
+ Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
22
+ If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
23
+ **exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
24
+
25
+ Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
tasks/moe/fsdp-reduce-scatter-bucket/environment/Dockerfile ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kernel-generation task: Write a fast FSDP reduce-scatter bucketing kernel (gradient copy-in)
2
+ #
3
+ # Every FSDP backward ends by packing a whole unit's gradients into ONE reduce-scatter bucket: each parameter's rows split across the ranks and written rank-major, the padding rows zeroed so they cannot poison the sum, the whole thing pre-divided by the world size and cast down to the bf16 reduce dtype — and, since every element is already in registers, the per-parameter squared gradient norm the clipper needs falls out of the same pass. On an MoE unit that is hundreds of expert matrices and gigabytes of fp32 gradient, and it is what the backward waits on.
4
+ #
5
+ # SCORING: correctness is a hard gate; the score is achieved GB/s (uncapped leaderboard, 0 if wrong).
6
+ # There is no gold solution and no oracle, so nothing has to be vendored or sealed.
7
+ #
8
+ # TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
9
+ # the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
10
+ # there is no internet, so nothing else can be obtained.
11
+ #
12
+ # GENERATED by _factory/build.py.
13
+ FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
14
+
15
+ # NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
16
+ # lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
17
+ RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
18
+ apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
19
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
20
+ /root/.local/bin/uv tool install mini-swe-agent
21
+ # header-only CUTLASS for the agent's CUDA/CuTe route
22
+ RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
23
+ # pre-bake Claude Code; harbor's claude_code.install() skips when present
24
+ RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
25
+ apt-get install -y nodejs procps && \
26
+ npm install -g @anthropic-ai/claude-code && claude --version
27
+ ENV PATH=/root/.local/bin:$PATH
28
+ ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
29
+
30
+ COPY restrict-network.sh /app/restrict-network.sh
31
+ RUN chmod +x /app/restrict-network.sh
32
+ # strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
33
+ RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
34
+
35
+ WORKDIR /app
36
+ COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
37
+
38
+ # task-specific files LAST so the layers above stay shared across every task
39
+ COPY reference.py /app/reference.py
40
+ COPY measure.py /app/measure.py
41
+ COPY rs_copy_in.py /app/rs_copy_in.py
tasks/moe/fsdp-reduce-scatter-bucket/environment/PROCESS_MANAGEMENT.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Managing background processes — READ THIS before you `kill` anything
2
+
3
+ You may start and stop background processes while iterating — a **server**, a long **build** or
4
+ **training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
5
+ *your own agent process* and end the whole run.** This has happened repeatedly, including via a
6
+ hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
7
+
8
+ ## The trap: matching task text against process command lines
9
+
10
+ You were launched as roughly:
11
+
12
+ ```
13
+ claude --print -- '<the entire task instruction text>'
14
+ ```
15
+
16
+ The full task instruction is on **your own** process's command line, and it contains the file names
17
+ and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
18
+ So **any** command that finds processes by matching those strings will match — and can kill — **the
19
+ agent itself**:
20
+
21
+ ```
22
+ pkill -9 -f "train.py" # matches the claude agent -> kills YOU
23
+ pgrep -f "server.py" | xargs kill # same: the pid list includes claude
24
+ for p in $(pgrep -f build.sh); do kill -9 $p; done # same
25
+ for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
26
+ ```
27
+
28
+ It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
29
+ a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
30
+ the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
31
+ immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
32
+ worse than what you were about to finish.
33
+
34
+ ## The one safe rule: kill only the exact PID you recorded
35
+
36
+ **Start** a background job and record its PID in a file:
37
+
38
+ ```bash
39
+ nohup <your command> > /tmp/job.log 2>&1 &
40
+ echo $! > /tmp/job.pid
41
+ ```
42
+
43
+ **Stop / restart** by that exact PID — never by a name pattern:
44
+
45
+ ```bash
46
+ kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
47
+ sleep 3
48
+ kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
49
+ ```
50
+
51
+ If the job spawns workers, run it in its own process group and signal the group by its (negative)
52
+ PGID — still an exact id, never a pattern:
53
+
54
+ ```bash
55
+ setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
56
+ kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
57
+ ```
58
+
59
+ ## If you ever enumerate processes, EXCLUDE the agent
60
+
61
+ Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
62
+ your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
63
+ a unique name and match only that:
64
+
65
+ ```bash
66
+ # job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
67
+ pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
68
+ # only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
69
+ ```
70
+
71
+ Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
72
+ single addition re-introduces the self-kill. Match the unique token **only**.
73
+
74
+ ## Freeing the GPU without going nuclear
75
+
76
+ If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
77
+ collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
78
+ `/proc` sweep:
79
+
80
+ - Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
81
+ the process fully exits.
82
+ - Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
83
+ single `kill $PID` is enough.
84
+ - Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
85
+ - Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
86
+ confirming its cmdline is **not** `claude` / `--print`.
87
+
88
+ ## Rules of thumb
89
+
90
+ - **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
91
+ with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
92
+ agent (its argv holds the prompt).
93
+ - **Always** kill a background job by the exact PID from its pidfile (or its PGID).
94
+ - If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
95
+ and your own shell**; `pgrep -af` and look before you kill.
96
+ - `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
tasks/moe/fsdp-reduce-scatter-bucket/environment/docker-compose.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
2
+ # NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
3
+ # reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
4
+ # Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
5
+ # the (now-blocked) network install when it is already present.
6
+ services:
7
+ main:
8
+ cap_add:
9
+ - NET_ADMIN
10
+ entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
11
+ environment:
12
+ - ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
13
+ - FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
14
+ - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
15
+ - OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
16
+ - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
17
+ - LLM_BASE_URL=${LLM_BASE_URL:-}
18
+ - LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
tasks/moe/fsdp-reduce-scatter-bucket/environment/measure.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-assessment tool — your correctness + achieved GB/s across a RANGE of shapes.
2
+
3
+ python /app/measure.py # the graded regime
4
+ python /app/measure.py --quick # smaller sizes for fast iteration
5
+
6
+ You are scored on the **geomean achieved GB/s** — NOT one fixed size, and the leaderboard is UNCAPPED
7
+ (higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
8
+ optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
9
+ printed here is computed exactly as your score is.
10
+
11
+ GENERATED by _factory/build.py.
12
+ """
13
+ import argparse
14
+ import math
15
+ import sys
16
+
17
+ import torch
18
+
19
+ sys.path.insert(0, "/app")
20
+ from reference import reduce_scatter_bucket as _ref
21
+ from rs_copy_in import reduce_scatter_bucket as _agent
22
+
23
+ TOL = 1e-05
24
+ NAMES = ('rs_in', 'sq')
25
+
26
+ FULL = [(3, 2048, 1408, 32000, 8, 48), (4, 2048, 1408, 32000, 6, 24), (5, 1536, 1024, 32000, 8, 12), (3, 2048, 1792, 32768, 8, 40), (4, 1792, 1280, 48000, 8, 24)]
27
+ QUICK = [(2, 512, 352, 8000, 4, 24), (2, 384, 256, 8000, 8, 12), (1, 640, 448, 8192, 6, 48)]
28
+
29
+ def _param_grid(L, D, F, V, E):
30
+ """(rows, cols) of every parameter of an L-block MoE unit, from the SHAPE ALONE."""
31
+ R = [V]
32
+ C = [D] # embed_tokens
33
+ for _ in range(L):
34
+ R += [D, D // 4, D // 4, D, E] # q, k, v, o, router
35
+ C += [D, D, D, D, D]
36
+ for _ in range(E):
37
+ R += [F, F, D] # expert gate, up, down
38
+ C += [D, D, F]
39
+ R += [D, D]
40
+ C += [1, 1] # the two RMSNorm gains
41
+ R += [D, V]
42
+ C += [1, D] # final norm, lm_head
43
+ return R, C
44
+
45
+
46
+ def canonical_work(L, D, F, V, E, W):
47
+ """BYTES attributed to one reduce-scatter copy-in, from the SHAPE ALONE.
48
+
49
+ Read every fp32 gradient element once (4*Ntot) and write the whole bf16 bucket once (2*W*S), where S is
50
+ one rank's block length, i.e. sum over parameters of ceil(rows/W)*cols. The (P,) norm vector is
51
+ negligible. Bandwidth-bound: the score is achieved bandwidth against that fixed byte count.
52
+ """
53
+ R, C = _param_grid(L, D, F, V, E)
54
+ S = sum(-(-r // W) * c for r, c in zip(R, C))
55
+ return 4 * sum(r * c for r, c in zip(R, C)) + 2 * W * S
56
+
57
+ def _mk(L, D, F, V, E, W, seed):
58
+ """The fp32 gradients of an L-block MoE unit, in the module's natural parameter order.
59
+
60
+ Per block: q/k/v/o with 4x GQA, a router, E experts of (gate, up, down), and two RMSNorm gains, plus
61
+ the embedding table, the final norm and the LM head — 100 to 250 separate tensors at the graded sizes.
62
+ """
63
+ gen = torch.Generator(device="cuda").manual_seed(seed)
64
+ R, C = _param_grid(L, D, F, V, E)
65
+ n = sum(r * c for r, c in zip(R, C))
66
+ grads = torch.randn(n, device="cuda", dtype=torch.float32, generator=gen) * 1e-3
67
+ return (grads,
68
+ torch.tensor(R, device="cuda", dtype=torch.int32),
69
+ torch.tensor(C, device="cuda", dtype=torch.int32),
70
+ W,
71
+ torch.tensor(1.0 / W, device="cuda", dtype=torch.float32))
72
+
73
+
74
+ def _check(out, ref):
75
+ """-> (ok, value, msg). value = MAX relative error across the returned tuple."""
76
+ if out is None or len(out) != len(NAMES):
77
+ return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
78
+ per = []
79
+ for n, a, b in zip(NAMES, out, ref):
80
+ if a is None or tuple(a.shape) != tuple(b.shape):
81
+ return False, 1.0, f"{n} bad shape"
82
+ if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
83
+ # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
84
+ bad = int((a != b).sum())
85
+ if bad:
86
+ return False, 1.0, f"{n}: {bad} elements differ"
87
+ continue
88
+ per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
89
+ if not per:
90
+ return True, 0.0, "all integer outputs exact"
91
+ wn, wv = max(per, key=lambda x: x[1])
92
+ return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
93
+
94
+
95
+ def _bench(fn, reps=8, warm=3):
96
+ for _ in range(warm):
97
+ fn()
98
+ torch.cuda.synchronize()
99
+ best = float("inf")
100
+ for _ in range(reps):
101
+ s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
102
+ s.record()
103
+ fn()
104
+ e.record()
105
+ torch.cuda.synchronize()
106
+ best = min(best, s.elapsed_time(e))
107
+ return best / 1e3
108
+
109
+
110
+ def main():
111
+ ap = argparse.ArgumentParser()
112
+ ap.add_argument("--quick", action="store_true")
113
+ a = ap.parse_args()
114
+ shapes = QUICK if a.quick else FULL
115
+ print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
116
+ f"DIFFERENT sizes in the same regime — optimize for generality\n")
117
+ vals, allok = [], True
118
+ for shp in shapes:
119
+ args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
120
+ ref = _ref(*args)
121
+ try:
122
+ out = _agent(*args)
123
+ except Exception as ex:
124
+ print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
125
+ allok = False
126
+ continue
127
+ ok, val, msg = _check(out, ref)
128
+ allok = allok and ok
129
+ t = _bench(lambda: _agent(*args))
130
+ v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
131
+ vals.append(v)
132
+ print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} GB/s | {msg} {'ok' if ok else 'FAIL'}")
133
+ del args, ref, out
134
+ torch.cuda.empty_cache()
135
+ geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
136
+ print(f"\n => GEOMEAN {geo:.2f} GB/s "
137
+ f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
138
+ print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
tasks/moe/fsdp-reduce-scatter-bucket/environment/reference.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference implementation — the CORRECTNESS SPEC for `reduce_scatter_bucket`.
2
+
3
+ This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
4
+ bearing on your score, which is an absolute GB/s number. GENERATED by _factory/build.py.
5
+ """
6
+ import torch
7
+
8
+
9
+ def reduce_scatter_bucket(grads, rows, cols, world_size, pre_divide):
10
+ """Pack the bucket one parameter at a time, in fp32.
11
+
12
+ Correct and simple — it is the SPECIFICATION, not a performance target. It syncs the shape tables to the
13
+ host, zero-fills the whole bucket, and then makes a separate pass per parameter for the copy and another
14
+ for the norm.
15
+ """
16
+ W = world_size
17
+ R = rows.tolist() # device -> host sync on the critical path
18
+ C = cols.tolist()
19
+ S = sum(-(-r // W) * c for r, c in zip(R, C))
20
+ rs_in = torch.zeros(W, S, device=grads.device, dtype=torch.bfloat16)
21
+ sq = torch.empty(len(R), device=grads.device, dtype=torch.float32)
22
+
23
+ src_off = 0
24
+ dst_off = 0
25
+ for p, (r, c) in enumerate(zip(R, C)):
26
+ g = grads[src_off:src_off + r * c]
27
+ sq[p] = (g * g).sum() # squared norm of the RAW gradient
28
+ sh = -(-r // W) # rows each rank gets, padded up
29
+ blk = torch.zeros(W * sh, c, device=grads.device, dtype=torch.bfloat16)
30
+ blk[:r] = (g.view(r, c) * pre_divide).bfloat16() # pre-divide, then cast
31
+ rs_in[:, dst_off:dst_off + sh * c] = blk.view(W, sh * c)
32
+ src_off += r * c
33
+ dst_off += sh * c
34
+ return rs_in, sq
tasks/moe/fsdp-reduce-scatter-bucket/environment/restrict-network.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
3
+ # endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
4
+ # so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
5
+ # copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
6
+ # installer skips the network install when it is already present), so no package index is needed at run time.
7
+ #
8
+ # Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
9
+ # apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
10
+ set -uo pipefail
11
+
12
+ # LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
13
+ API_HOSTS=(
14
+ api.fireworks.ai
15
+ openrouter.ai openrouter.io
16
+ api.openai.com api.anthropic.com generativelanguage.googleapis.com
17
+ api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
18
+ )
19
+ # Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
20
+ CUSTOM=()
21
+ while IFS='=' read -r n v; do
22
+ case "$n" in
23
+ *_BASE_URL|*_URL|*_ENDPOINT)
24
+ [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
25
+ esac
26
+ done < <(env)
27
+ if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
28
+ ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
29
+
30
+ if iptables -L OUTPUT -n >/dev/null 2>&1; then
31
+ echo "restrict-network: applying outbound allowlist firewall..."
32
+ iptables -F OUTPUT 2>/dev/null || true
33
+ iptables -A OUTPUT -o lo -j ACCEPT
34
+ iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
35
+ iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
36
+ iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
37
+ iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
38
+ iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
39
+ iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
40
+ iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
41
+ for h in "${ALL_HOSTS[@]}"; do
42
+ for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
43
+ iptables -A OUTPUT -d "$ip" -j ACCEPT
44
+ done
45
+ done
46
+ iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
47
+ echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
48
+ else
49
+ echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
50
+ fi
51
+
52
+ exec "$@"
tasks/moe/fsdp-reduce-scatter-bucket/environment/rs_copy_in.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Your implementation goes here.
2
+
3
+ Replace the body of `reduce_scatter_bucket` with a FAST implementation that reproduces the output of /app/reference.py
4
+ (same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
5
+ Run `python /app/measure.py` to check your correctness and achieved GB/s.
6
+
7
+ You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
8
+ signature and returned value are fixed by the contract.
9
+ """
10
+
11
+
12
+ def reduce_scatter_bucket(grads, rows, cols, world_size, pre_divide):
13
+ """Pack an FSDP unit's gradients into the reduce-scatter input bucket.
14
+
15
+ Args:
16
+ grads: (Ntot,) float32 — the unsharded gradients, each parameter row-major, concatenated in
17
+ parameter order with NO padding.
18
+ rows: (P,) int32 — dim-0 length of each parameter.
19
+ cols: (P,) int32 — dim-1 length of each parameter (1 for the 1-D ones).
20
+ world_size: int — number of ranks the bucket is scattered to.
21
+ pre_divide: () float32 — 0-dim tensor, the pre-divide factor (1/world_size) the values are
22
+ MULTIPLIED by before the cast.
23
+
24
+ Returns:
25
+ (rs_in, sq) where
26
+ rs_in: (world_size, S) bfloat16 — the reduce-scatter input, rank-major, padding rows EXACTLY zero
27
+ sq: (P,) float32 — sum of squares of each parameter's RAW (undivided) gradient
28
+ """
29
+ raise NotImplementedError("Implement a fast reduce_scatter_bucket in /app/rs_copy_in.py")
tasks/moe/fsdp-reduce-scatter-bucket/instruction.md ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Write a fast FSDP reduce-scatter bucketing kernel (gradient copy-in)
2
+
3
+ You are given a **correct but slow** reference at **`/app/reference.py`** — `reduce_scatter_bucket(grads, rows, cols, world_size, pre_divide)`. **Read it, run it, profile it.**
4
+
5
+ Write **`/app/rs_copy_in.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
6
+
7
+ ```python
8
+ def reduce_scatter_bucket(grads, rows, cols, world_size, pre_divide):
9
+ ...
10
+ ```
11
+
12
+ ## The computation (this is the exact spec)
13
+
14
+ Parameter `p` is a `(rows[p], cols[p])` row-major matrix (1-D parameters have `cols = 1`) and
15
+ its gradient sits in `grads` at the offset given by the running sum of `rows*cols`. The reduce-scatter wants
16
+ that same data **rank-major**, with each parameter's rows split evenly across the `world_size` ranks:
17
+
18
+ ```
19
+ sh[p] = ceil(rows[p] / world_size) # rows each rank contributes for parameter p
20
+ S = sum over p of sh[p]*cols[p] # length of ONE rank's block
21
+ off[p] = sum over q < p of sh[q]*cols[q]
22
+ ```
23
+
24
+ For every parameter, view its gradient as `(rows[p], cols[p])`, pad it down to `world_size*sh[p]` rows with
25
+ **exact zeros**, scale, cast, and write the `r`-th row block into rank `r`'s slot:
26
+
27
+ ```
28
+ padded[i, j] = grad_p[i, j] * pre_divide rounded to bf16 for i < rows[p]
29
+ padded[i, j] = 0 for i >= rows[p]
30
+ rs_in[r, off[p] : off[p] + sh[p]*cols[p]] = padded[r*sh[p] : (r+1)*sh[p]].reshape(-1)
31
+ ```
32
+
33
+ The zeros are not cosmetic: the reduce-scatter sums the ranks' buckets elementwise, so a padding slot that
34
+ holds stale memory corrupts a real parameter's gradient on whichever rank owns that slot.
35
+
36
+ `pre_divide` is a **0-dim fp32 tensor** holding `1/world_size`, and the spec is a **multiply** by it in
37
+ fp32 followed by a single round to bf16 — not a divide, and not a cast followed by a scale. That makes the
38
+ result bit-exact and identical for every correct implementation.
39
+
40
+ Alongside the copy, report each parameter's squared gradient norm, computed on the **raw** gradient before
41
+ the pre-divide, accumulated in fp32:
42
+
43
+ ```
44
+ sq[p] = sum over all rows[p]*cols[p] elements of grad_p^2
45
+ ```
46
+
47
+ Every element is already in registers for the copy, so the norm is free if you fuse it and a second full
48
+ pass over 2 GB if you do not.
49
+
50
+ `/app/reference.py` zero-fills the whole bucket, then makes one pass per parameter for the norm and another
51
+ for the copy. That is the exact specification; it is deliberately simple rather than fast.
52
+
53
+ ## The contract (fixed — do not change these)
54
+
55
+ | arg | shape | dtype | meaning |
56
+ |-----|-------|-------|---------|
57
+ | `grads` | `(Ntot,)` | `float32` | unsharded gradients, parameter order, row-major, no padding |
58
+ | `rows` | `(P,)` | `int32` | dim-0 length of each parameter |
59
+ | `cols` | `(P,)` | `int32` | dim-1 length of each parameter; `1` for the 1-D ones |
60
+ | `world_size` | scalar | `int` (python) | number of ranks; 12, 24, 40 or 48 |
61
+ | `pre_divide` | `()` | `float32` | 0-dim tensor holding `1/world_size`; **multiply** by it |
62
+
63
+ **Return** a 2-tuple `(rs_in, sq)` **in that order**:
64
+
65
+ | out | shape | dtype | notes |
66
+ |-----|-------|-------|-------|
67
+ | `rs_in` | `(world_size, S)` | `bfloat16` | rank-major bucket; padding rows **exactly 0** |
68
+ | `sq` | `(P,)` | `float32` | squared norm of each parameter's **raw** gradient, fp32 accumulation |
69
+
70
+ `rows[p]` is **not** a multiple of `world_size` at any graded shape, and the router (`E` rows) and the norm
71
+ gains are single-column parameters, one of which has fewer rows than there are ranks — its later ranks
72
+ contribute nothing but zeros. All inputs are read-only; the call is functional.
73
+
74
+ **Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L`
75
+ (blocks in the FSDP unit) 3–6, `D` 1536–2048, `F` (per-expert intermediate) 1024–1792, `V` 32000–48000, `E`
76
+ (experts per block) 6–12, and a world size of 12, 24, 40 or 48 — the shard-group sizes you get from 2–6
77
+ nodes, none of which divide the row counts. That is **330 M – 480 M fp32 gradient elements**, 100–250
78
+ separate tensors dominated by the expert matrices, and 2.0–2.9 GB of traffic per call. The reduce-scatter
79
+ cannot start until this finishes, so it sits directly on the backward's critical path.
80
+
81
+ ## How success is decided (runs on GPU)
82
+
83
+ **1. Correctness — a required gate.** **Both** returned values must match the reference within **relative error `1e-5`** at
84
+ every graded shape, including the timed ones; the grader scores the **worse** of the two.
85
+
86
+ `rs_in` carries no rounding freedom at all — the pre-divide is a multiply by a given fp32 constant followed
87
+ by one round to bf16 — so a correct kernel reproduces it **bit for bit** and the gate on it is effectively
88
+ exact. The whole `1e-5` budget exists for `sq`, whose fp32 accumulation order is yours to choose.
89
+
90
+ That gate is **measured**, and every shortcut misses it by orders of magnitude: writing the bucket in
91
+ parameter-major instead of rank-major order scores **1.41**, leaving the shard padding holding stale memory
92
+ scores **1.79**, skipping the pre-divide scores **23.0**, and accumulating `sq` in bf16 instead of fp32
93
+ scores **9.5e-4**, still 95x the tolerance. A wrong kernel scores **0**, no matter how fast.
94
+
95
+ **2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
96
+
97
+ ```
98
+ reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [GB/s]
99
+ reward = 0 if the submission is wrong at any graded shape
100
+ ```
101
+
102
+ `canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
103
+ credited the same work and this is a pure speed ranking in useful units:
104
+
105
+ ```
106
+ Ntot = sum over p of rows[p] * cols[p] # the unsharded gradients
107
+ S = sum over p of ceil(rows[p] / W) * cols[p] # one rank's block of the bucket
108
+
109
+ canonical_work(L, D, F, V, E, W) = 4*Ntot + 2*W*S # read the fp32 gradients once, write the bf16 bucket once
110
+
111
+ `rows`/`cols` are the parameter grid of an L-block MoE unit (q/k/v/o with 4x GQA, a router, E experts of
112
+ gate/up/down, two norm gains, plus the embedding table, the final norm and the LM head), so the byte count
113
+ is a function of the shape and never of the data.
114
+ ```
115
+
116
+ **There is no cap and no target.** Higher GB/s is always a strictly better score, so **push the
117
+ performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
118
+ it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
119
+ after every change. **Use your full time budget.**
120
+
121
+ Run **`python /app/measure.py`** at any point to see your per-shape and geomean GB/s plus correctness.
122
+
123
+ ## Where the performance comes from
124
+
125
+ Six bytes per gradient element — one fp32 read, one bf16 write — so this is a bandwidth
126
+ kernel, and your score is achieved bandwidth against that count.
127
+
128
+ The reference throws most of that away: `torch.zeros(W, S)` writes the entire bucket before anything real
129
+ lands in it, every parameter then allocates its own zeroed `(W*sh, cols)` staging block, and the squared
130
+ norm is a completely separate reduction pass over the same 2 GB.
131
+
132
+ The kernel to write is **one launch that reads `grads` once**. For a tile of consecutive source elements,
133
+ the parameter `p` is a binary search over the offset table and then
134
+
135
+ ```
136
+ i = local / cols[p] , j = local % cols[p] # row, column within the parameter
137
+ r = i / sh[p] # the rank that owns this row
138
+ dst = r*S + off[p] + (i - r*sh[p])*cols[p] + j
139
+ ```
140
+
141
+ which is contiguous in `dst` as long as the tile stays inside one `(p, r)` pair — so both sides vectorise.
142
+
143
+ Where the time goes:
144
+
145
+ - **Do not pre-zero the bucket.** The padding is well under 1% of `S`; emit those zeros from the same pass
146
+ that writes the real values, or write them with a tiny separate kernel over just the padding slots.
147
+ - **Fuse the norm.** `sq[p]` is a segmented reduction over exactly the elements you already loaded. Reduce
148
+ in registers, then across the block, then one atomic per parameter per block — the segments are enormous
149
+ (millions of elements) so contention is not the issue, the second read of HBM is.
150
+ - **fp32 accumulation, and mind the order.** The tolerance is tight enough that a bf16 or fp16 accumulator
151
+ fails; a per-thread fp32 accumulator followed by a tree reduction is both faster and more accurate than a
152
+ serial one.
153
+ - **The size spread is the scheduling problem.** The expert matrices are all the same size and dominate, but
154
+ each block also carries a router and two norm gains that are a few kilobytes. Grid by tiles, not by
155
+ parameter.
156
+ - **Avoid the host sync.** The offset tables depend only on `rows`, `cols` and `world_size`, so they can be
157
+ built on the device once per shape and reused — shape-keyed caching is explicitly allowed.
158
+
159
+ ## Precision and faithfulness (read this)
160
+
161
+ Gradients arrive **fp32** and the bucket is **bfloat16** — that is the real FSDP mixed
162
+ precision setting, where the reduce-scatter runs in the reduce dtype to halve the wire traffic.
163
+
164
+ The scaling is specified exactly to remove any rounding freedom: multiply the fp32 value by the 0-dim fp32
165
+ `pre_divide` tensor, then round **once** to bf16. Do not divide by `world_size` (a divide and a
166
+ reciprocal-multiply disagree in the last fp32 ulp, and about one element in 2^16 then rounds to a different
167
+ bf16 value), and do not cast first and scale afterwards. With the multiply as specified, every correct
168
+ kernel produces bit-identical `rs_in`.
169
+
170
+ `sq` must be accumulated in **fp32**. It is a sum of up to 6e7 squares per parameter, so the accumulation
171
+ order is visible; that is what the tolerance is for.
172
+
173
+ **fp8 is not useful here** and is not expected: the output dtype is fixed at bf16 by the contract.
174
+
175
+ **Where the tolerance comes from (measured, not guessed).** An independent implementation — the bucket
176
+ built by a single vectorised `index_copy_` from a precomputed destination-index map with no per-parameter
177
+ staging, and `sq` accumulated by a chunked `(g*g).view(-1, 4096).sum(0).sum()` tree instead of a flat
178
+ `sum()` — agrees with the reference to **`E = 8.0e-8`** worst over the correctness shapes and a full graded
179
+ shape, entirely in `sq`; `rs_in` matched **bit for bit** (`0.0`) everywhere. Two further fp32 reduction
180
+ orders were checked at a graded shape: the reference against a float64 sum, **1.4e-8**, and a deliberately
181
+ poor 256-chain fp32 accumulation, **1.6e-8**. Every fp32 accumulation order tried lands within an order of
182
+ magnitude of 1e-8, so the gate is set at **`1e-5`** — 125x above the measured floor, which leaves room for
183
+ whatever reduction tree you pick, and still 95x below the cheapest shortcut.
184
+
185
+ Drop-the-feature measurements, all far outside it: parameter-major instead of rank-major placement
186
+ **D = 1.41**; shard padding left holding stale memory **D = 1.79**; no pre-divide **D = 23.0**; `sq`
187
+ accumulated in bf16 **D = 9.5e-4**.
188
+
189
+ ### What the tolerance does NOT permit
190
+
191
+ The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
192
+ implementation of the specified computation**. It is not a budget to spend on approximation. The following
193
+ are wrong answers even if they happen to land inside the tolerance at some shape:
194
+
195
+ - changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
196
+ series, low-rank or sketched substitutes, skipping a correction term);
197
+ - shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
198
+ or striding over the sequence, ignoring positions whose contribution "looks small");
199
+ - computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
200
+ that the spec gives their own);
201
+ - anything whose error **grows** with sequence length, batch, or head count.
202
+
203
+ A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
204
+ magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
205
+ are deliberately large, so the difference shows up.
206
+
207
+ ## What's available
208
+
209
+ - **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
210
+ extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
211
+ (`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
212
+ - `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
213
+ - A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist.
214
+ The exact part is deliberately **not** stated: query it and tune to what you actually find.
215
+
216
+ ```python
217
+ p = torch.cuda.get_device_properties(0)
218
+ p.name, p.major, p.minor # part and compute capability
219
+ p.multi_processor_count # SM count -- size your persistent grid from this, never a constant
220
+ p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor
221
+ p.shared_memory_per_block_optin # opt-in dynamic smem, the number that matters for big tiles
222
+ ```
223
+
224
+ `nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK`
225
+ give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a
226
+ datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak
227
+ FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the
228
+ score is an absolute metric, so a kernel tuned to a machine it never sees is just slower.
229
+ - **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
230
+ already installed, and no library implementation of this kernel exists on the machine.
231
+ - Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
232
+ `/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
233
+
234
+ ## How the grading actually runs (so there are no surprises)
235
+
236
+ - **`/app/rs_copy_in.py` is the only file that is graded.** The grader imports `reduce_scatter_bucket` from it and reads nothing
237
+ else from `/app`.
238
+ - **The grader is not on this machine while you work.** It is copied in only after your session ends and it
239
+ carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
240
+ or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
241
+ your score**. Do not spend budget on them.
242
+ - **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
243
+ against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
244
+ than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
245
+ - **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
246
+ - Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
tasks/moe/fsdp-reduce-scatter-bucket/task.toml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.1"
2
+
3
+ [task]
4
+ name = "mle-bench/fsdp-reduce-scatter-bucket"
5
+ description = "Every FSDP backward ends by packing a whole unit's gradients into ONE reduce-scatter bucket: each parameter's rows split across the ranks and written rank-major, the padding rows zeroed so they cannot poison the sum, the whole thing pre-divided by the world size and cast down to the bf16 reduce dtype — and, since every element is already in registers, the per-parameter squared gradient norm the clipper needs falls out of the same pass. On an MoE unit that is hundreds of expert matrices and gigabytes of fp32 gradient, and it is what the backward waits on."
6
+ authors = []
7
+ keywords = ["mle", "kernel-generation", "fsdp", "zero", "reduce-scatter", "bucketing", "gradient", "mixed-precision", "moe", "distributed", "training", "memory-bound"]
8
+
9
+ [metadata]
10
+ suite = "mle-bench"
11
+ group = "kernel-generation"
12
+ level = "1.0"
13
+ difficulty = "hard"
14
+ category = "mle"
15
+ tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]
16
+
17
+ [verifier]
18
+ timeout_sec = 1800.0
19
+
20
+ [agent]
21
+ timeout_sec = 14400.0
22
+
23
+ # GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
24
+ # in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
25
+ [environment]
26
+ build_timeout_sec = 3600.0
27
+ cpus = 8
28
+ memory_mb = 65536
29
+ storage_mb = 40960
30
+ gpus = 1
31
+ network_mode = "public"
32
+ mcp_servers = []
33
+
34
+ [verifier.env]
35
+
36
+ [environment.env]
37
+
38
+ [solution.env]
tasks/moe/fsdp-reduce-scatter-bucket/tests/test.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.
3
+ set -u
4
+ mkdir -p /logs/verifier
5
+ python3 /tests/verify_env.py
tasks/moe/fsdp-reduce-scatter-bucket/tests/verify_env.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """fsdp-reduce-scatter-bucket verifier — correctness gate + achieved-GB/s SPEED LEADERBOARD (uncapped).
2
+
3
+ reward = 0 if the submission is incorrect
4
+ reward = geomean over graded shapes of GB/s otherwise
5
+
6
+ GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
7
+
8
+ There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
9
+ by construction and nothing has to be vendored, sealed, or re-benchmarked.
10
+
11
+ CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
12
+ shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
13
+ scores 0.
14
+
15
+ ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
16
+ timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
17
+ result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
18
+ throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
19
+
20
+ WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
21
+ submissions are credited identically and the ranking is a pure speed ranking.
22
+ """
23
+ import importlib.util
24
+ import json
25
+ import math
26
+ import os
27
+ import sys
28
+ import traceback
29
+
30
+ import torch
31
+
32
+ REWARD_DIR = "/logs/verifier"
33
+ MODULE_PATH = "/app/rs_copy_in.py"
34
+ TOL = 1e-05
35
+ NAMES = ('rs_in', 'sq')
36
+
37
+ GRADER_SHAPES = [(4, 2048, 1408, 32000, 8, 24), (3, 2048, 1408, 32000, 12, 12), (6, 1536, 1024, 32000, 8, 48), (4, 2048, 1792, 32768, 6, 40), (5, 1792, 1280, 48000, 8, 24)]
38
+ CORRECT_SHAPES = [(1, 128, 96, 512, 3, 12), (2, 100, 70, 257, 2, 24), (2, 64, 48, 129, 5, 48), (1, 96, 56, 401, 4, 40), (1, 32, 24, 97, 2, 12)]
39
+
40
+ sys.path.insert(0, "/app")
41
+
42
+ def _param_grid(L, D, F, V, E):
43
+ """(rows, cols) of every parameter of an L-block MoE unit, from the SHAPE ALONE."""
44
+ R = [V]
45
+ C = [D] # embed_tokens
46
+ for _ in range(L):
47
+ R += [D, D // 4, D // 4, D, E] # q, k, v, o, router
48
+ C += [D, D, D, D, D]
49
+ for _ in range(E):
50
+ R += [F, F, D] # expert gate, up, down
51
+ C += [D, D, F]
52
+ R += [D, D]
53
+ C += [1, 1] # the two RMSNorm gains
54
+ R += [D, V]
55
+ C += [1, D] # final norm, lm_head
56
+ return R, C
57
+
58
+
59
+ def canonical_work(L, D, F, V, E, W):
60
+ """BYTES attributed to one reduce-scatter copy-in, from the SHAPE ALONE.
61
+
62
+ Read every fp32 gradient element once (4*Ntot) and write the whole bf16 bucket once (2*W*S), where S is
63
+ one rank's block length, i.e. sum over parameters of ceil(rows/W)*cols. The (P,) norm vector is
64
+ negligible. Bandwidth-bound: the score is achieved bandwidth against that fixed byte count.
65
+ """
66
+ R, C = _param_grid(L, D, F, V, E)
67
+ S = sum(-(-r // W) * c for r, c in zip(R, C))
68
+ return 4 * sum(r * c for r, c in zip(R, C)) + 2 * W * S
69
+
70
+ def _ref(grads, rows, cols, world_size, pre_divide):
71
+ """Pack the bucket one parameter at a time, in fp32.
72
+
73
+ Correct and simple — it is the SPECIFICATION, not a performance target. It syncs the shape tables to the
74
+ host, zero-fills the whole bucket, and then makes a separate pass per parameter for the copy and another
75
+ for the norm.
76
+ """
77
+ W = world_size
78
+ R = rows.tolist() # device -> host sync on the critical path
79
+ C = cols.tolist()
80
+ S = sum(-(-r // W) * c for r, c in zip(R, C))
81
+ rs_in = torch.zeros(W, S, device=grads.device, dtype=torch.bfloat16)
82
+ sq = torch.empty(len(R), device=grads.device, dtype=torch.float32)
83
+
84
+ src_off = 0
85
+ dst_off = 0
86
+ for p, (r, c) in enumerate(zip(R, C)):
87
+ g = grads[src_off:src_off + r * c]
88
+ sq[p] = (g * g).sum() # squared norm of the RAW gradient
89
+ sh = -(-r // W) # rows each rank gets, padded up
90
+ blk = torch.zeros(W * sh, c, device=grads.device, dtype=torch.bfloat16)
91
+ blk[:r] = (g.view(r, c) * pre_divide).bfloat16() # pre-divide, then cast
92
+ rs_in[:, dst_off:dst_off + sh * c] = blk.view(W, sh * c)
93
+ src_off += r * c
94
+ dst_off += sh * c
95
+ return rs_in, sq
96
+
97
+ def _mk(L, D, F, V, E, W, seed):
98
+ """The fp32 gradients of an L-block MoE unit, in the module's natural parameter order.
99
+
100
+ Per block: q/k/v/o with 4x GQA, a router, E experts of (gate, up, down), and two RMSNorm gains, plus
101
+ the embedding table, the final norm and the LM head — 100 to 250 separate tensors at the graded sizes.
102
+ """
103
+ gen = torch.Generator(device="cuda").manual_seed(seed)
104
+ R, C = _param_grid(L, D, F, V, E)
105
+ n = sum(r * c for r, c in zip(R, C))
106
+ grads = torch.randn(n, device="cuda", dtype=torch.float32, generator=gen) * 1e-3
107
+ return (grads,
108
+ torch.tensor(R, device="cuda", dtype=torch.int32),
109
+ torch.tensor(C, device="cuda", dtype=torch.int32),
110
+ W,
111
+ torch.tensor(1.0 / W, device="cuda", dtype=torch.float32))
112
+
113
+
114
+ def _check(out, ref):
115
+ """-> (ok, value, msg). value = MAX relative error across the returned tuple."""
116
+ if out is None or len(out) != len(NAMES):
117
+ return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
118
+ per = []
119
+ for n, a, b in zip(NAMES, out, ref):
120
+ if a is None or tuple(a.shape) != tuple(b.shape):
121
+ return False, 1.0, f"{n} bad shape"
122
+ if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
123
+ # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
124
+ bad = int((a != b).sum())
125
+ if bad:
126
+ return False, 1.0, f"{n}: {bad} elements differ"
127
+ continue
128
+ per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
129
+ if not per:
130
+ return True, 0.0, "all integer outputs exact"
131
+ wn, wv = max(per, key=lambda x: x[1])
132
+ return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
133
+
134
+
135
+ def _bench_fresh(fn, mkargs, reps=5, warm=3):
136
+ """Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
137
+ wargs = mkargs(0)
138
+ for _ in range(warm):
139
+ fn(*wargs)
140
+ torch.cuda.synchronize()
141
+ del wargs
142
+ torch.cuda.empty_cache()
143
+
144
+ best, timed_ok = float("inf"), True
145
+ for i in range(reps):
146
+ args = mkargs(10_000 + i)
147
+ s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
148
+ s.record()
149
+ out = fn(*args)
150
+ e.record()
151
+ torch.cuda.synchronize()
152
+ best = min(best, s.elapsed_time(e))
153
+ if i == reps - 1:
154
+ timed_ok = _check(out, _ref(*args))[0]
155
+ del args, out
156
+ torch.cuda.empty_cache()
157
+ return best / 1e3, timed_ok
158
+
159
+
160
+ def _geomean(xs):
161
+ return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
162
+
163
+
164
+ def main():
165
+ details, correct_gate, geo = {}, False, 0.0
166
+ try:
167
+ spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
168
+ m = importlib.util.module_from_spec(spec)
169
+ spec.loader.exec_module(m)
170
+ fn = m.reduce_scatter_bucket
171
+
172
+ corr_ok, msg = True, ""
173
+ for i, shp in enumerate(CORRECT_SHAPES):
174
+ args = _mk(*shp, seed=10 + i)
175
+ ok, val, m_ = _check(fn(*args), _ref(*args))
176
+ if not ok:
177
+ corr_ok, msg = False, f"cfg{i} {shp} {m_}"
178
+ break
179
+ del args
180
+ torch.cuda.empty_cache()
181
+ details["correct_msg"] = msg or "all correctness shapes pass"
182
+
183
+ vals, per_shape, perf_ok = [], [], corr_ok
184
+ for i, shp in enumerate(GRADER_SHAPES):
185
+ args = _mk(*shp, seed=100 + i)
186
+ ok, val, m_ = _check(fn(*args), _ref(*args))
187
+ if not ok:
188
+ perf_ok = False
189
+ del args
190
+ torch.cuda.empty_cache()
191
+ t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
192
+ if not timed_ok:
193
+ perf_ok = False
194
+ v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
195
+ vals.append(v)
196
+ per_shape.append({"shape": list(shp), "gbps": round(v, 3), "ms": round(t * 1e3, 3),
197
+ "check": m_, "timed_ok": timed_ok})
198
+ geo = _geomean(vals)
199
+ details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
200
+ correct_gate = corr_ok and perf_ok
201
+ except Exception as e:
202
+ details["error"] = f"{e.__class__.__name__}: {e}"[:220]
203
+ details["trace"] = traceback.format_exc()[-800:]
204
+
205
+ reward = round(geo, 4) if correct_gate else 0.0
206
+ os.makedirs(REWARD_DIR, exist_ok=True)
207
+ json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
208
+ "geomean": round(geo, 4), "metric": "GB/s (geomean over graded shapes)"},
209
+ open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
210
+ open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
211
+ json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
212
+ print("reward:", reward, "GB/s | correct:", 1.0 if correct_gate else 0.0)
213
+
214
+
215
+ main()