diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/RUN.md b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/RUN.md new file mode 100644 index 0000000000000000000000000000000000000000..ef086309cf7ac70801df936023a60c6b7b0ebce3 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/RUN.md @@ -0,0 +1,42 @@ +# Running `zamba-shared-attn-lora-backward` + +Fine-tuning a Zamba-style hybrid means differentiating a block that was called at L different depths with one frozen weight and L different rank-64 adapters, over an input that was a concatenation of the depth's residual stream and the model's original embedding. So the embedding's gradient is a sum over EVERY depth, each adapter's gradient is a pair of tall-skinny reductions over the token axis, and the frozen weight is read L times and never updated. + +| | | +|---|---| +| **Task id** | `mle-bench/zamba-shared-attn-lora-backward` | +| **Group** | `kernel-generation` | +| **GPUs** | 1 | +| **Agent edits** | `/app/shared_qkv_bwd.py` | +| **Score** | achieved **TFLOP/s** (uncapped speed leaderboard), `0` if incorrect | +| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` | + +## Run through harbor + +```bash +harbor run --dataset-path kernel-generation/kernels/zamba-shared-attn-lora-backward --task-name zamba-shared-attn-lora-backward \ + --agent claude-code --model anthropic/claude-opus-4-1 -e docker +``` + +## Run manually + +```bash +cd kernel-generation/kernels/zamba-shared-attn-lora-backward +docker build -t zamba-shared-attn-lora-backward environment/ +docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep zamba-shared-attn-lora-backward infinity +docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0 +docker rm -f v +``` + +Use an **idle** GPU: the score is a timing measurement. + +## Design + +Correctness is a hard gate; the score is an absolute hardware metric (TFLOP/s), so the task is +hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed. + +Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is +copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs +with the timed output itself validated, so memoize-and-replay fails the gate. + +Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/CLAUDE.md b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/Dockerfile b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f2512e1418870fd950a6b28021387ed84fe68ae7 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/Dockerfile @@ -0,0 +1,41 @@ +# Kernel-generation task: Write a fast backward kernel for the shared-attention-block QKV projection +# +# Fine-tuning a Zamba-style hybrid means differentiating a block that was called at L different depths with one frozen weight and L different rank-64 adapters, over an input that was a concatenation of the depth's residual stream and the model's original embedding. So the embedding's gradient is a sum over EVERY depth, each adapter's gradient is a pair of tall-skinny reductions over the token axis, and the frozen weight is read L times and never updated. +# +# SCORING: correctness is a hard gate; the score is achieved TFLOP/s (uncapped leaderboard, 0 if wrong). +# There is no gold solution and no oracle, so nothing has to be vendored or sealed. +# +# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or +# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and +# there is no internet, so nothing else can be obtained. +# +# GENERATED by _factory/build.py. +FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel + +# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this +# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder. +RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \ + apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \ + curl -LsSf https://astral.sh/uv/install.sh | sh && \ + /root/.local/bin/uv tool install mini-swe-agent +# header-only CUTLASS for the agent's CUDA/CuTe route +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git +# pre-bake Claude Code; harbor's claude_code.install() skips when present +RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \ + apt-get install -y nodejs procps && \ + npm install -g @anthropic-ai/claude-code && claude --version +ENV PATH=/root/.local/bin:$PATH +ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 + +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh +# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds +RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d + +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ + +# task-specific files LAST so the layers above stay shared across every task +COPY reference.py /app/reference.py +COPY measure.py /app/measure.py +COPY shared_qkv_bwd.py /app/shared_qkv_bwd.py diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/PROCESS_MANAGEMENT.md b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/docker-compose.yaml b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2c38481425a227ceafac34304135a05b3e1cd7e --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/docker-compose.yaml @@ -0,0 +1,18 @@ +# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container +# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are +# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not +# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips +# the (now-blocked) network install when it is already present. +services: + main: + cap_add: + - NET_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/measure.py b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/measure.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ad9c74410dec282a69a3f31cde3e5c6bf0a42a --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/measure.py @@ -0,0 +1,131 @@ +"""Self-assessment tool — your correctness + achieved TFLOP/s across a RANGE of shapes. + + python /app/measure.py # the graded regime + python /app/measure.py --quick # smaller sizes for fast iteration + +You are scored on the **geomean achieved TFLOP/s** — NOT one fixed size, and the leaderboard is UNCAPPED +(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so +optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number +printed here is computed exactly as your score is. + +GENERATED by _factory/build.py. +""" +import argparse +import math +import sys + +import torch + +sys.path.insert(0, "/app") +from reference import shared_qkv_backward as _ref +from shared_qkv_bwd import shared_qkv_backward as _agent + +TOL = 0.006 +NAMES = ('dh', 'demb', 'dlora_a', 'dlora_b') + +FULL = [(6, 3584, 2048, 64), (4, 3584, 2560, 64), (8, 1792, 2048, 32), (6, 2560, 2048, 128), (4, 5120, 2048, 64)] +QUICK = [(4, 512, 1024, 32), (2, 1024, 512, 16), (6, 256, 1024, 64)] + +def canonical_work(L, T, Dm, r): + """FLOPs attributed to one backward call, from the SHAPE ALONE. + + Per depth, at 2 FLOPs per multiply-add: + * ONE pass of the big shared shape: dxc = dqkv @ w_qkv (the base weight is frozen, + so there is no dw_qkv and no second pass over it) + * THREE passes of the (2*Dm, r) adapter shape: recompute mid = xc @ lora_a.T (the LoRA output is a + forward temporary), dxc += dmid @ lora_a, dlora_a = dmid.T @ xc + * TWO passes of the (3*Dm, r) adapter shape: dmid = dqkv @ lora_b, dlora_b = dqkv.T @ mid + The concatenation, the split of dxc and the sum of demb over depths are O(L*T*Dm) data movement and + are not credited. + """ + return L * (2 * T * (2 * Dm) * (3 * Dm) + + 3 * (2 * T * (2 * Dm) * r) + + 2 * (2 * T * (3 * Dm) * r)) + +def _mk(L, T, Dm, r, seed): + """Saved forward inputs plus the incoming gradient. The adapters are scaled so the LoRA delta is a real + but minority part of the forward (RMS `16/r` of the base projection), which is what a trained LoRA + looks like.""" + gen = torch.Generator(device="cuda").manual_seed(seed) + + def rnd(*sh, s=1.0): + return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16) + + h = rnd(L, T, Dm) + emb = rnd(T, Dm) + w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5) + dqkv = rnd(L, T, 3 * Dm) + return h, emb, w_qkv, lora_a, lora_b, 16.0 / r, dqkv + + +def _check(out, ref): + """-> (ok, value, msg). value = MAX relative error across the returned tuple.""" + if out is None or len(out) != len(NAMES): + return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}" + per = [] + for n, a, b in zip(NAMES, out, ref): + if a is None or tuple(a.shape) != tuple(b.shape): + return False, 1.0, f"{n} bad shape" + if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool): + # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal + bad = int((a != b).sum()) + if bad: + return False, 1.0, f"{n}: {bad} elements differ" + continue + per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12)))) + if not per: + return True, 0.0, "all integer outputs exact" + wn, wv = max(per, key=lambda x: x[1]) + return wv <= TOL, wv, f"worst {wn} {wv:.2e}" + + +def _bench(fn, reps=8, warm=3): + for _ in range(warm): + fn() + torch.cuda.synchronize() + best = float("inf") + for _ in range(reps): + s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + s.record() + fn() + e.record() + torch.cuda.synchronize() + best = min(best, s.elapsed_time(e)) + return best / 1e3 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--quick", action="store_true") + a = ap.parse_args() + shapes = QUICK if a.quick else FULL + print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses " + f"DIFFERENT sizes in the same regime — optimize for generality\n") + vals, allok = [], True + for shp in shapes: + args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973) + ref = _ref(*args) + try: + out = _agent(*args) + except Exception as ex: + print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}") + allok = False + continue + ok, val, msg = _check(out, ref) + allok = allok and ok + t = _bench(lambda: _agent(*args)) + v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0 + vals.append(v) + print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} TFLOP/s | {msg} {'ok' if ok else 'FAIL'}") + del args, ref, out + torch.cuda.empty_cache() + geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0 + print(f"\n => GEOMEAN {geo:.2f} TFLOP/s " + f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})") + print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.") + + +if __name__ == "__main__": + main() diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/reference.py b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..74eaaa6980144d6889ebea02a57be039373b31c7 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/reference.py @@ -0,0 +1,27 @@ +"""Reference implementation — the CORRECTNESS SPEC for `shared_qkv_backward`. + +This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no +bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py. +""" +import torch + + +def _shared_qkv(h, emb, w_qkv, lora_a, lora_b, scaling): + """The fp32 forward of `zamba-shared-attn-lora-qkv`, differentiable. Autograd through THIS defines + every gradient this task asks for.""" + L, T, Dm = h.shape + outs = [] + for l in range(L): + xc = torch.cat([h[l], emb], dim=-1) # (T, 2*Dm) [state | embedding] + base = xc @ w_qkv.t() + delta = (xc @ lora_a[l].t()) @ lora_b[l].t() + outs.append(base + scaling * delta) + return torch.stack(outs, 0) + + +def shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv): + """The baseline re-runs the fp32 forward under autograd. The shared weight is FROZEN: only the two + activations and the L adapters receive gradients.""" + ins = [t.detach().clone().float().requires_grad_(True) for t in (h, emb, lora_a, lora_b)] + o = _shared_qkv(ins[0], ins[1], w_qkv.float(), ins[2], ins[3], scaling) + return torch.autograd.grad(o, ins, dqkv.float()) diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/restrict-network.sh b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..bf996c1a42dd2037b4ea475249eb2920c03b7d77 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and +# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched +# installer skips the network install when it is already present), so no package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also +# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + api.fireworks.ai + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/shared_qkv_bwd.py b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/shared_qkv_bwd.py new file mode 100644 index 0000000000000000000000000000000000000000..2f49d07ed2ad5caf54d254026671d89624163e00 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/shared_qkv_bwd.py @@ -0,0 +1,28 @@ +"""Your implementation goes here. + +Replace the body of `shared_qkv_backward` with a FAST implementation that reproduces the output of /app/reference.py +(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md. +Run `python /app/measure.py` to check your correctness and achieved TFLOP/s. + +You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name, +signature and returned value are fixed by the contract. +""" + + +def shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv): + """Backward of the shared attention-block QKV projection (frozen base, L LoRA adapters). + + Args: + h: (L, T, Dm) bfloat16 — residual stream at each depth, saved by the forward. + emb: (T, Dm) bfloat16 — the shared original embedding, saved by the forward. + w_qkv: (3*Dm, 2*Dm) bfloat16 — the shared projection. FROZEN: no gradient is returned for it. + lora_a: (L, r, 2*Dm) bfloat16 — per-depth LoRA down-projection. + lora_b: (L, 3*Dm, r) bfloat16 — per-depth LoRA up-projection. + scaling: float — the LoRA scale (alpha / r). + dqkv: (L, T, 3*Dm) bfloat16 — incoming gradient w.r.t. the fused QKV output. + + Returns: + (dh, demb, dlora_a, dlora_b) with shapes + (L, T, Dm), (T, Dm), (L, r, 2*Dm), (L, 3*Dm, r). + """ + raise NotImplementedError("Implement a fast shared_qkv_backward in /app/shared_qkv_bwd.py") diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/instruction.md b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c775fd2f63673cf64a41e056fc2be16ff94a7cd --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/instruction.md @@ -0,0 +1,213 @@ +# Write a fast backward kernel for the shared-attention-block QKV projection + +You are given a **correct but slow** reference at **`/app/reference.py`** — `shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv)`. **Read it, run it, profile it.** + +Write **`/app/shared_qkv_bwd.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**. + +```python +def shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv): + ... +``` + +## The computation (this is the exact spec) + +The forward being differentiated is the shared attention block's QKV projection, called at +`L` depths with one shared weight and a per-depth LoRA adapter: + +``` +xc[l] = concat( h[l], emb ) # (T, 2*Dm), state first +mid[l] = xc[l] @ lora_a[l].T # (T, r) +qkv[l] = xc[l] @ w_qkv.T + scaling * mid[l] @ lora_b[l].T +``` + +`w_qkv` is **frozen** — this is adapter fine-tuning, so no gradient is produced for it and it is never +transposed-reduced over the token axis. Given `dqkv` you must return four things: + +``` +dmid[l] = scaling * ( dqkv[l] @ lora_b[l] ) # (T, r) +dxc[l] = dqkv[l] @ w_qkv + dmid[l] @ lora_a[l] # (T, 2*Dm) +dlora_a[l] = dmid[l].T @ xc[l] # (r, 2*Dm) +dlora_b[l] = scaling * ( dqkv[l].T @ mid[l] ) # (3*Dm, r) +``` + +and then the concatenation is undone: + +``` +dh[l] = dxc[l][:, :Dm] +demb = sum over ALL l of dxc[l][:, Dm:] +``` + +**`demb` is a sum over every depth.** The same embedding tensor was fed to all `L` invocations, so its +gradient collects a contribution from each one — this is the piece that makes the backward of a *shared* +block different from `L` independent backwards. + +Note that `mid[l]` was a forward temporary and is not an argument: `dlora_b` needs it, so it must be +recomputed. + +`/app/reference.py` re-runs the fp32 forward under autograd and differentiates it. That is the exact +specification; it is deliberately simple rather than fast. + +## The contract (fixed — do not change these) + +| arg | shape | dtype | meaning | +|-----|-------|-------|---------| +| `h` | `(L, T, Dm)` | `bfloat16` | residual stream at each depth | +| `emb` | `(T, Dm)` | `bfloat16` | shared original embedding | +| `w_qkv` | `(3*Dm, 2*Dm)` | `bfloat16` | shared projection, **frozen** | +| `lora_a` | `(L, r, 2*Dm)` | `bfloat16` | per-depth LoRA down | +| `lora_b` | `(L, 3*Dm, r)` | `bfloat16` | per-depth LoRA up | +| `scaling` | float | | LoRA scale `alpha / r` | +| `dqkv` | `(L, T, 3*Dm)` | `bfloat16` | incoming gradient w.r.t. the fused QKV output | + +**Return a 4-tuple in exactly this order:** `dh (L, T, Dm)`, `demb (T, Dm)`, `dlora_a (L, r, 2*Dm)`, +`dlora_b (L, 3*Dm, r)`. + +`dh` and `demb` may be bf16 or fp32; the two adapter gradients should be **fp32** — each is a reduction +over every token. **No gradient is returned for `w_qkv`.** The concatenation order is `[h[l] ‖ emb]`, so +`dh` comes from the first `Dm` channels of `dxc` and `demb` from the last `Dm`, summed over depths. + +All inputs are **read-only**. `T` is **not** guaranteed to be a multiple of any tile size (the correctness +shapes include `T = 129`), and `r` is as small as 4. + +**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L` in +4–8, `T` in 2048–6144, `Dm` in 2048–2560, `r` in 32–128. One big matmul per depth dominates the FLOPs; the +adapter work is a few percent of it and most of the difficulty. + +## How success is decided (runs on GPU) + +**1. Correctness — a required gate.** **All four** returned tensors must match the reference (evaluated in fp32) within +**relative Frobenius error `6e-3`** at every graded shape, including the timed ones; the grader scores the +**worst** of the four. + +That gate is **measured**, and the two structural mistakes this task invites miss it badly: taking `demb` +from depth 0 instead of summing over **all** depths scores **0.70–0.91**, and omitting the adapter's +contribution `dmid @ lora_a` from `dxc` scores **0.124** at the largest graded shape (0.45–0.97 at the +small ones) — 21x the tolerance at worst. A wrong kernel scores **0**, no matter how fast. + +**2. Performance — this is your score, and it is an UNCAPPED leaderboard.** + +``` +reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [TFLOP/s] +reward = 0 if the submission is wrong at any graded shape +``` + +`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is +credited the same work and this is a pure speed ranking in useful units: + +``` +canonical_work(L, T, Dm, r) = L * ( 2*T*(2*Dm)*(3*Dm) # dxc = dqkv @ w_qkv + + 3 * 2*T*(2*Dm)*r # mid, dxc +=, dlora_a + + 2 * 2*T*(3*Dm)*r ) # dmid, dlora_b +``` + +**There is no cap and no target.** Higher TFLOP/s is always a strictly better score, so **push the +performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of +it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness +after every change. **Use your full time budget.** + +Run **`python /app/measure.py`** at any point to see your per-shape and geomean TFLOP/s plus correctness. + +## Where the performance comes from + +`L` big matmuls against one frozen weight, plus four tall-skinny ones per depth, plus a +reduction that ties all the depths together. + +**The frozen weight is read `L` times if you let it be.** `w_qkv` is 40–65 MB; a persistent grid that +walks all `L` depths per weight tile pays for it once. Note the transpose: the backward needs +`dqkv @ w_qkv` (not `w_qkv.T`), so the reduction runs over the `3*Dm` axis — plan the layout for that +rather than transposing a 65 MB tensor at run time. + +**`demb` is a cross-depth reduction.** Do not build `L` copies of `dxc[:, Dm:]` and add them afterwards: +that is `L` extra full-size writes and reads. Accumulate into one fp32 `(T, Dm)` buffer as each depth's +tile is produced — with `L <= 8` a deterministic tree or a per-depth atomic-free accumulation over a +partition of the token axis both work, and both beat materialising the intermediates. + +**Fuse the adapter path.** `mid[l]` and `dmid[l]` are `(T, r)` with `r <= 128`. Both belong in shared +memory: recompute `mid` from the `xc` tile you already have, form `dmid` from the `dqkv` tile you already +have, and feed both straight into the two weight-gradient reductions. An autograd-shaped implementation +sends four `(T, r)` tensors and two `(T, 2*Dm)` tensors through HBM per depth for a delta worth a few +percent of the arithmetic. + +**`dlora_a` and `dlora_b` are split-K reductions** over the token axis into tiny outputs (`r x 2*Dm` and +`3*Dm x r`). Use fp32 accumulators and a cross-block reduction; do not use one atomic per element. + +`xc` should never be materialised: its first half is `h[l]`, its second half is `emb`, and every consumer +can read them separately. + +## Precision and faithfulness (read this) + +Inputs are **bfloat16**; accumulate every matmul, the `demb` cross-depth sum and both +adapter-gradient reductions in **fp32**. + +`demb` sums `L` full-size contributions and the adapter gradients sum over up to 6144 tokens — a bf16 +accumulator in either place gives an error that *grows* with the problem size, which the faithfulness +clause below rejects. + +**fp8 is not appropriate here**: the saved activations arrive in bf16 and re-quantising them is an +approximation of the specified computation. + +**Where the tolerance comes from.** `1e-2` is measured. A second, independent implementation — the +analytic backward written out by hand, all `L` depths batched into `bmm`s, `xc` never materialised, the +adapter gradients accumulated in a different order from autograd's — differs from this fp32 autograd +reference by a worst relative Frobenius error of **2.90e-3** across the correctness shapes and two +full-size graded shapes, over several seeds. The tolerance is **2.07x** that, and the error *falls* with +problem size (2.37e-3 at the large shapes) — it is the bf16 rounding of the operands, nothing more. + +### What the tolerance does NOT permit + +The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful +implementation of the specified computation**. It is not a budget to spend on approximation. The following +are wrong answers even if they happen to land inside the tolerance at some shape: + +- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a + series, low-rank or sketched substitutes, skipping a correction term); +- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling + or striding over the sequence, ignoring positions whose contribution "looks small"); +- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions + that the spec gives their own); +- anything whose error **grows** with sequence length, batch, or head count. + +A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of +magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes +are deliberately large, so the difference shows up. + +## What's available + +- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline + extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL** + (`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported. +- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping. +- A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist. + The exact part is deliberately **not** stated: query it and tune to what you actually find. + +```python +p = torch.cuda.get_device_properties(0) +p.name, p.major, p.minor # part and compute capability +p.multi_processor_count # SM count -- size your persistent grid from this, never a constant +p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor +p.shared_memory_per_block_optin # opt-in dynamic smem, the number that matters for big tiles +``` + + `nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK` + give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a + datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak + FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the + score is an absolute metric, so a kernel tuned to a machine it never sees is just slower. +- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is + already installed, and no library implementation of this kernel exists on the machine. +- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see + `/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`. + +## How the grading actually runs (so there are no surprises) + +- **`/app/shared_qkv_bwd.py` is the only file that is graded.** The grader imports `shared_qkv_backward` from it and reads nothing + else from `/app`. +- **The grader is not on this machine while you work.** It is copied in only after your session ends and it + carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py` + or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on + your score**. Do not spend budget on them. +- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked + against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather + than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised. +- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**. +- Inputs are random each grade and the graded shapes are not the ones in `measure.py`. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/task.toml b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..502e6cad2a9f04aac1e0398d9249ac2db856b056 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/zamba-shared-attn-lora-backward" +description = "Fine-tuning a Zamba-style hybrid means differentiating a block that was called at L different depths with one frozen weight and L different rank-64 adapters, over an input that was a concatenation of the depth's residual stream and the model's original embedding. So the embedding's gradient is a sum over EVERY depth, each adapter's gradient is a pair of tall-skinny reductions over the token axis, and the frozen weight is read L times and never updated." +authors = [] +keywords = ["mle", "kernel-generation", "zamba", "hybrid", "shared-attention", "lora", "multi-adapter", "backward", "training", "gemm", "compute-bound"] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",] + +[verifier] +timeout_sec = 1800.0 + +[agent] +timeout_sec = 14400.0 + +# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0 +# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5). +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 65536 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/test.sh b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..96147b7a26c9a89b5c158060756222d7b0fe22a5 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/test.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink. +set -u +mkdir -p /logs/verifier +python3 /tests/verify_env.py diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/verify_env.py b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/verify_env.py new file mode 100644 index 0000000000000000000000000000000000000000..e196a08354299057171c34b446177740b907d49f --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/verify_env.py @@ -0,0 +1,197 @@ +"""zamba-shared-attn-lora-backward verifier — correctness gate + achieved-TFLOP/s SPEED LEADERBOARD (uncapped). + + reward = 0 if the submission is incorrect + reward = geomean over graded shapes of TFLOP/s otherwise + +GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate. + +There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable +by construction and nothing has to be vendored, sealed, or re-benchmarked. + +CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded +shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel +scores 0. + +ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last +timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a +result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate +throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised. + +WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all +submissions are credited identically and the ranking is a pure speed ranking. +""" +import importlib.util +import json +import math +import os +import sys +import traceback + +import torch + +REWARD_DIR = "/logs/verifier" +MODULE_PATH = "/app/shared_qkv_bwd.py" +TOL = 0.006 +NAMES = ('dh', 'demb', 'dlora_a', 'dlora_b') + +GRADER_SHAPES = [(6, 4096, 2048, 64), (4, 4096, 2560, 64), (8, 2048, 2048, 32), (6, 3072, 2048, 128), (4, 6144, 2048, 64)] +CORRECT_SHAPES = [(2, 256, 256, 16), (3, 129, 128, 8), (4, 512, 512, 32), (2, 64, 128, 4)] + +sys.path.insert(0, "/app") + +def canonical_work(L, T, Dm, r): + """FLOPs attributed to one backward call, from the SHAPE ALONE. + + Per depth, at 2 FLOPs per multiply-add: + * ONE pass of the big shared shape: dxc = dqkv @ w_qkv (the base weight is frozen, + so there is no dw_qkv and no second pass over it) + * THREE passes of the (2*Dm, r) adapter shape: recompute mid = xc @ lora_a.T (the LoRA output is a + forward temporary), dxc += dmid @ lora_a, dlora_a = dmid.T @ xc + * TWO passes of the (3*Dm, r) adapter shape: dmid = dqkv @ lora_b, dlora_b = dqkv.T @ mid + The concatenation, the split of dxc and the sum of demb over depths are O(L*T*Dm) data movement and + are not credited. + """ + return L * (2 * T * (2 * Dm) * (3 * Dm) + + 3 * (2 * T * (2 * Dm) * r) + + 2 * (2 * T * (3 * Dm) * r)) + +def _shared_qkv(h, emb, w_qkv, lora_a, lora_b, scaling): + """The fp32 forward of `zamba-shared-attn-lora-qkv`, differentiable. Autograd through THIS defines + every gradient this task asks for.""" + L, T, Dm = h.shape + outs = [] + for l in range(L): + xc = torch.cat([h[l], emb], dim=-1) # (T, 2*Dm) [state | embedding] + base = xc @ w_qkv.t() + delta = (xc @ lora_a[l].t()) @ lora_b[l].t() + outs.append(base + scaling * delta) + return torch.stack(outs, 0) + + +def _ref(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv): + """The baseline re-runs the fp32 forward under autograd. The shared weight is FROZEN: only the two + activations and the L adapters receive gradients.""" + ins = [t.detach().clone().float().requires_grad_(True) for t in (h, emb, lora_a, lora_b)] + o = _shared_qkv(ins[0], ins[1], w_qkv.float(), ins[2], ins[3], scaling) + return torch.autograd.grad(o, ins, dqkv.float()) + +def _mk(L, T, Dm, r, seed): + """Saved forward inputs plus the incoming gradient. The adapters are scaled so the LoRA delta is a real + but minority part of the forward (RMS `16/r` of the base projection), which is what a trained LoRA + looks like.""" + gen = torch.Generator(device="cuda").manual_seed(seed) + + def rnd(*sh, s=1.0): + return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16) + + h = rnd(L, T, Dm) + emb = rnd(T, Dm) + w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5) + dqkv = rnd(L, T, 3 * Dm) + return h, emb, w_qkv, lora_a, lora_b, 16.0 / r, dqkv + + +def _check(out, ref): + """-> (ok, value, msg). value = MAX relative error across the returned tuple.""" + if out is None or len(out) != len(NAMES): + return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}" + per = [] + for n, a, b in zip(NAMES, out, ref): + if a is None or tuple(a.shape) != tuple(b.shape): + return False, 1.0, f"{n} bad shape" + if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool): + # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal + bad = int((a != b).sum()) + if bad: + return False, 1.0, f"{n}: {bad} elements differ" + continue + per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12)))) + if not per: + return True, 0.0, "all integer outputs exact" + wn, wv = max(per, key=lambda x: x[1]) + return wv <= TOL, wv, f"worst {wn} {wv:.2e}" + + +def _bench_fresh(fn, mkargs, reps=5, warm=3): + """Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring.""" + wargs = mkargs(0) + for _ in range(warm): + fn(*wargs) + torch.cuda.synchronize() + del wargs + torch.cuda.empty_cache() + + best, timed_ok = float("inf"), True + for i in range(reps): + args = mkargs(10_000 + i) + s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + s.record() + out = fn(*args) + e.record() + torch.cuda.synchronize() + best = min(best, s.elapsed_time(e)) + if i == reps - 1: + timed_ok = _check(out, _ref(*args))[0] + del args, out + torch.cuda.empty_cache() + return best / 1e3, timed_ok + + +def _geomean(xs): + return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0 + + +def main(): + details, correct_gate, geo = {}, False, 0.0 + try: + spec = importlib.util.spec_from_file_location("submission", MODULE_PATH) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + fn = m.shared_qkv_backward + + corr_ok, msg = True, "" + for i, shp in enumerate(CORRECT_SHAPES): + args = _mk(*shp, seed=10 + i) + ok, val, m_ = _check(fn(*args), _ref(*args)) + if not ok: + corr_ok, msg = False, f"cfg{i} {shp} {m_}" + break + del args + torch.cuda.empty_cache() + details["correct_msg"] = msg or "all correctness shapes pass" + + vals, per_shape, perf_ok = [], [], corr_ok + for i, shp in enumerate(GRADER_SHAPES): + args = _mk(*shp, seed=100 + i) + ok, val, m_ = _check(fn(*args), _ref(*args)) + if not ok: + perf_ok = False + del args + torch.cuda.empty_cache() + t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s)) + if not timed_ok: + perf_ok = False + v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0 + vals.append(v) + per_shape.append({"shape": list(shp), "tflops": round(v, 3), "ms": round(t * 1e3, 3), + "check": m_, "timed_ok": timed_ok}) + geo = _geomean(vals) + details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok) + correct_gate = corr_ok and perf_ok + except Exception as e: + details["error"] = f"{e.__class__.__name__}: {e}"[:220] + details["trace"] = traceback.format_exc()[-800:] + + reward = round(geo, 4) if correct_gate else 0.0 + os.makedirs(REWARD_DIR, exist_ok=True) + json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0, + "geomean": round(geo, 4), "metric": "TFLOP/s (geomean over graded shapes)"}, + open(f"{REWARD_DIR}/reward.json", "w"), indent=2) + open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward)) + json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str) + print("reward:", reward, "TFLOP/s | correct:", 1.0 if correct_gate else 0.0) + + +main() diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/RUN.md b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/RUN.md new file mode 100644 index 0000000000000000000000000000000000000000..a661c440d2c1127d85a910dbe3c2de813e18abca --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/RUN.md @@ -0,0 +1,42 @@ +# Running `zamba-shared-attn-lora-qkv` + +Zamba-2 does not give every attention layer its own weights — it has ONE attention block and calls it at several depths of a Mamba stack, feeding it the concatenation of the current residual stream and the original token embedding, and giving each invocation its own low-rank adapter so the shared weights can still specialise. The QKV projection therefore runs L times against the same 50 MB of weights with L different rank-64 deltas, and done as L separate library calls the shared weight is re-read from HBM every time and the adapters get three extra launches each. + +| | | +|---|---| +| **Task id** | `mle-bench/zamba-shared-attn-lora-qkv` | +| **Group** | `kernel-generation` | +| **GPUs** | 1 | +| **Agent edits** | `/app/shared_qkv.py` | +| **Score** | achieved **TFLOP/s** (uncapped speed leaderboard), `0` if incorrect | +| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` | + +## Run through harbor + +```bash +harbor run --dataset-path kernel-generation/kernels/zamba-shared-attn-lora-qkv --task-name zamba-shared-attn-lora-qkv \ + --agent claude-code --model anthropic/claude-opus-4-1 -e docker +``` + +## Run manually + +```bash +cd kernel-generation/kernels/zamba-shared-attn-lora-qkv +docker build -t zamba-shared-attn-lora-qkv environment/ +docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep zamba-shared-attn-lora-qkv infinity +docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0 +docker rm -f v +``` + +Use an **idle** GPU: the score is a timing measurement. + +## Design + +Correctness is a hard gate; the score is an absolute hardware metric (TFLOP/s), so the task is +hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed. + +Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is +copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs +with the timed output itself validated, so memoize-and-replay fails the gate. + +Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/CLAUDE.md b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/Dockerfile b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a9794626cd9d5d8a2fd2626d775c69542032810 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/Dockerfile @@ -0,0 +1,41 @@ +# Kernel-generation task: Write a fast shared-attention-block QKV kernel (one weight, L per-depth LoRA adapters) +# +# Zamba-2 does not give every attention layer its own weights — it has ONE attention block and calls it at several depths of a Mamba stack, feeding it the concatenation of the current residual stream and the original token embedding, and giving each invocation its own low-rank adapter so the shared weights can still specialise. The QKV projection therefore runs L times against the same 50 MB of weights with L different rank-64 deltas, and done as L separate library calls the shared weight is re-read from HBM every time and the adapters get three extra launches each. +# +# SCORING: correctness is a hard gate; the score is achieved TFLOP/s (uncapped leaderboard, 0 if wrong). +# There is no gold solution and no oracle, so nothing has to be vendored or sealed. +# +# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or +# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and +# there is no internet, so nothing else can be obtained. +# +# GENERATED by _factory/build.py. +FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel + +# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this +# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder. +RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \ + apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \ + curl -LsSf https://astral.sh/uv/install.sh | sh && \ + /root/.local/bin/uv tool install mini-swe-agent +# header-only CUTLASS for the agent's CUDA/CuTe route +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git +# pre-bake Claude Code; harbor's claude_code.install() skips when present +RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \ + apt-get install -y nodejs procps && \ + npm install -g @anthropic-ai/claude-code && claude --version +ENV PATH=/root/.local/bin:$PATH +ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 + +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh +# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds +RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d + +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ + +# task-specific files LAST so the layers above stay shared across every task +COPY reference.py /app/reference.py +COPY measure.py /app/measure.py +COPY shared_qkv.py /app/shared_qkv.py diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/PROCESS_MANAGEMENT.md b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/docker-compose.yaml b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2c38481425a227ceafac34304135a05b3e1cd7e --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/docker-compose.yaml @@ -0,0 +1,18 @@ +# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container +# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are +# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not +# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips +# the (now-blocked) network install when it is already present. +services: + main: + cap_add: + - NET_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/measure.py b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/measure.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc13997ff0a951da94327e0f6652cbaa0a57bc5 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/measure.py @@ -0,0 +1,121 @@ +"""Self-assessment tool — your correctness + achieved TFLOP/s across a RANGE of shapes. + + python /app/measure.py # the graded regime + python /app/measure.py --quick # smaller sizes for fast iteration + +You are scored on the **geomean achieved TFLOP/s** — NOT one fixed size, and the leaderboard is UNCAPPED +(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so +optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number +printed here is computed exactly as your score is. + +GENERATED by _factory/build.py. +""" +import argparse +import math +import sys + +import torch + +sys.path.insert(0, "/app") +from reference import shared_block_qkv as _ref +from shared_qkv import shared_block_qkv as _agent + +TOL = 0.007 + +FULL = [(6, 3584, 2048, 64), (4, 3584, 2560, 64), (8, 1792, 2048, 32), (6, 2560, 2048, 128), (4, 5120, 2048, 64)] +QUICK = [(4, 512, 1024, 32), (2, 1024, 512, 16), (6, 256, 1024, 64)] + +def canonical_work(L, T, Dm, r): + """FLOPs attributed to one call, from the SHAPE ALONE. + + Per depth, at 2 FLOPs per multiply-add: the shared projection (T, 2*Dm) x (2*Dm, 3*Dm), the adapter's + down-projection (T, 2*Dm) x (2*Dm, r) and its up-projection (T, r) x (r, 3*Dm). The concatenation and + the residual add are O(T*Dm) data movement and are not credited. + """ + return L * (2 * T * (2 * Dm) * (3 * Dm) + 2 * T * (2 * Dm) * r + 2 * T * r * (3 * Dm)) + +def _mk(L, T, Dm, r, seed): + """Per-depth residual streams, one shared embedding, the shared weight and L LoRA adapters. + + The adapters are scaled so the delta is a real but minority contribution (its RMS is `16/r` of the + base projection's), which is what a trained LoRA looks like — big enough that ignoring it is obvious, + small enough that it is a correction rather than the answer. + """ + gen = torch.Generator(device="cuda").manual_seed(seed) + + def rnd(*sh, s=1.0): + return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16) + + h = rnd(L, T, Dm) + emb = rnd(T, Dm) + w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5) + return h, emb, w_qkv, lora_a, lora_b, 16.0 / r + + +def _is_exact(t): + """Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large + ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass.""" + return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool) + + +def _check(out, ref): + """-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise.""" + if out is None or tuple(out.shape) != tuple(ref.shape): + return False, 1.0, "bad/None shape" + if _is_exact(ref): + bad = int((out != ref).sum()) + return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ") + e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12)) + return e <= TOL, e, f"relerr {e:.2e}" + + +def _bench(fn, reps=8, warm=3): + for _ in range(warm): + fn() + torch.cuda.synchronize() + best = float("inf") + for _ in range(reps): + s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + s.record() + fn() + e.record() + torch.cuda.synchronize() + best = min(best, s.elapsed_time(e)) + return best / 1e3 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--quick", action="store_true") + a = ap.parse_args() + shapes = QUICK if a.quick else FULL + print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses " + f"DIFFERENT sizes in the same regime — optimize for generality\n") + vals, allok = [], True + for shp in shapes: + args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973) + ref = _ref(*args) + try: + out = _agent(*args) + except Exception as ex: + print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}") + allok = False + continue + ok, val, msg = _check(out, ref) + allok = allok and ok + t = _bench(lambda: _agent(*args)) + v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0 + vals.append(v) + print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} TFLOP/s | {msg} {'ok' if ok else 'FAIL'}") + del args, ref, out + torch.cuda.empty_cache() + geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0 + print(f"\n => GEOMEAN {geo:.2f} TFLOP/s " + f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})") + print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.") + + +if __name__ == "__main__": + main() diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/reference.py b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..8facc0db0e5ee15e5f88bd50e67aebf8edd8e0d3 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/reference.py @@ -0,0 +1,24 @@ +"""Reference implementation — the CORRECTNESS SPEC for `shared_block_qkv`. + +This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no +bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py. +""" +import torch + + +def shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling): + """One depth at a time: concatenate, project with the shared weight, add the depth's LoRA delta. + + Correct and simple — it is the numerical SPECIFICATION, not a performance target. The shared weight is + re-read for every depth and the rank-wide intermediate goes to HBM. + """ + L, T, Dm = h.shape + out = torch.empty(L, T, 3 * Dm, device=h.device, dtype=torch.float32) + w = w_qkv.float() + e = emb.float() + for l in range(L): + xc = torch.cat([h[l].float(), e], dim=-1) # (T, 2*Dm) [state | embedding] + base = xc @ w.t() # the SHARED projection + delta = (xc @ lora_a[l].float().t()) @ lora_b[l].float().t() + out[l] = base + scaling * delta + return out.to(torch.bfloat16) diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/restrict-network.sh b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..bf996c1a42dd2037b4ea475249eb2920c03b7d77 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and +# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched +# installer skips the network install when it is already present), so no package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also +# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + api.fireworks.ai + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/shared_qkv.py b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/shared_qkv.py new file mode 100644 index 0000000000000000000000000000000000000000..ff03c6b92b97e55639cf202029c04b2d25ac18b1 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/shared_qkv.py @@ -0,0 +1,26 @@ +"""Your implementation goes here. + +Replace the body of `shared_block_qkv` with a FAST implementation that reproduces the output of /app/reference.py +(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md. +Run `python /app/measure.py` to check your correctness and achieved TFLOP/s. + +You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name, +signature and returned value are fixed by the contract. +""" + + +def shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling): + """Shared attention-block QKV projection with a per-depth LoRA adapter. + + Args: + h: (L, T, Dm) bfloat16 — the residual stream at each of the L depths the block is called at. + emb: (T, Dm) bfloat16 — the ORIGINAL token embedding, concatenated at every depth. + w_qkv: (3*Dm, 2*Dm) bfloat16 — the SHARED qkv projection, nn.Linear layout (out, in). + lora_a: (L, r, 2*Dm) bfloat16 — per-depth LoRA down-projection. + lora_b: (L, 3*Dm, r) bfloat16 — per-depth LoRA up-projection. + scaling: float — the LoRA scale (alpha / r). + + Returns: + qkv: (L, T, 3*Dm), bfloat16 or float32 — must match /app/reference.py numerically. + """ + raise NotImplementedError("Implement a fast shared_block_qkv in /app/shared_qkv.py") diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/instruction.md b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..561780ba572e89626e873ff3e968792dd1a39196 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/instruction.md @@ -0,0 +1,199 @@ +# Write a fast shared-attention-block QKV kernel (one weight, L per-depth LoRA adapters) + +You are given a **correct but slow** reference at **`/app/reference.py`** — `shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling)`. **Read it, run it, profile it.** + +Write **`/app/shared_qkv.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**. + +```python +def shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling): + ... +``` + +## The computation (this is the exact spec) + +A Zamba-style hybrid stack has **one** attention block, invoked at `L` different depths of a +Mamba backbone. Two things make its QKV projection unusual. + +**1 — the input is a concatenation.** At every depth the block sees the current residual stream *and* the +original token embedding, glued along the feature axis: + +``` +xc[l] = concat( h[l], emb ) # (T, 2*Dm) — state first, embedding second +``` + +`emb` is the **same** tensor at every depth: it is the model's input embedding, re-fed so the shared block +always has the original token available no matter how deep it is being called. + +**2 — the weights are shared, the adapters are not.** One `(3*Dm, 2*Dm)` projection serves every depth, +and each depth gets its own rank-`r` LoRA delta: + +``` +qkv[l] = xc[l] @ w_qkv.T + scaling * ( xc[l] @ lora_a[l].T ) @ lora_b[l].T +``` + +That is the whole computation: `L` applications of one big shared GEMM, each with its own tiny two-matmul +correction. The output layout is the usual fused one — `qkv[l][:, 0:Dm]` is Q, `[Dm:2*Dm]` is K, +`[2*Dm:3*Dm]` is V — but nothing here needs to know that; you return the fused tensor. + +`/app/reference.py` loops over depths and materialises the concatenation and the rank-wide intermediate for +each. That is the exact specification; it is deliberately simple rather than fast. + +## The contract (fixed — do not change these) + +| arg | shape | dtype | meaning | +|-----|-------|-------|---------| +| `h` | `(L, T, Dm)` | `bfloat16` | residual stream at each of the `L` invocation depths | +| `emb` | `(T, Dm)` | `bfloat16` | the original token embedding, **shared** across depths | +| `w_qkv` | `(3*Dm, 2*Dm)` | `bfloat16` | the shared projection, `nn.Linear` layout `(out, in)` | +| `lora_a` | `(L, r, 2*Dm)` | `bfloat16` | per-depth LoRA down-projection | +| `lora_b` | `(L, 3*Dm, r)` | `bfloat16` | per-depth LoRA up-projection | +| `scaling` | float | | LoRA scale `alpha / r`, a Python float | + +**Return** a single tensor `qkv` of shape `(L, T, 3*Dm)`, bfloat16 or float32 (the grader compares in +fp32). + +The concatenation order is **`[h[l] ‖ emb]`** — state in channels `[0, Dm)`, embedding in `[Dm, 2*Dm)` — +and `w_qkv`'s columns are laid out to match. All inputs are **read-only**. `T` is **not** guaranteed to be +a multiple of any tile size (the correctness shapes include `T = 129`), and `r` is as small as 4. + +**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L` +(invocation depths) in 4–8, `T` (tokens) in 2048–6144, `Dm` in 2048–2560, `r` in 32–128. The shared weight +is 40–65 MB and is used `L` times; the `L` adapters together are a few megabytes. That ratio is the whole +design of the layer and it should be the whole design of your kernel. + +## How success is decided (runs on GPU) + +**1. Correctness — a required gate.** The returned tensor must match the reference (evaluated in fp32) within **relative +Frobenius error `7e-3`** at every graded shape, including the timed ones. + +That gate is **measured**, and the plausible ways to get this wrong miss it by a wide margin: dropping the +LoRA delta entirely scores **0.12–0.24** at the graded shapes (0.45–0.97 at the small ones, where `r` is +a larger fraction of the width), using depth 0's adapter for every depth scores **0.16–0.30**, and +concatenating `[emb ‖ h[l]]` instead of `[h[l] ‖ emb]` scores **1.41** — the closest is **18x** the +tolerance. A wrong kernel scores **0**, no matter how fast. + +**2. Performance — this is your score, and it is an UNCAPPED leaderboard.** + +``` +reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [TFLOP/s] +reward = 0 if the submission is wrong at any graded shape +``` + +`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is +credited the same work and this is a pure speed ranking in useful units: + +``` +canonical_work(L, T, Dm, r) = L * ( 2*T*(2*Dm)*(3*Dm) + 2*T*(2*Dm)*r + 2*T*r*(3*Dm) ) +# shared projection LoRA down LoRA up +``` + +**There is no cap and no target.** Higher TFLOP/s is always a strictly better score, so **push the +performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of +it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness +after every change. **Use your full time budget.** + +Run **`python /app/measure.py`** at any point to see your per-shape and geomean TFLOP/s plus correctness. + +## Where the performance comes from + +One big GEMM done `L` times against the same weight, plus `2L` tiny ones. Three things +decide the score. + +**Read the shared weight once.** `w_qkv` is 40–65 MB; `L` separate `torch.matmul` calls stream it from HBM +`L` times. A kernel that tiles over `(depth, token)` blocks with the weight tile resident — or a persistent +grid that walks all `L` depths for each weight tile — pays for it once. At `L = 8` that is the difference +between 500 MB and 60 MB of weight traffic. + +**Never materialise the concatenation.** `xc[l]` is `(T, 2*Dm)` and half of it is `emb`, which is the same +for every depth. Building it explicitly costs `L` writes and `L` reads of a tensor twice the size of `h`. +The GEMM's K-loop can simply read the first `Dm` steps from `h[l]` and the next `Dm` from `emb` — the +operands are contiguous within each half, and `emb`'s half is reused by all `L` depths, so it is a +shared-memory tile you load once. + +**Fuse the adapter.** The rank-wide intermediate `xc @ lora_a[l].T` is `(T, r)` with `r <= 128` — a few +hundred kilobytes. It has no business in HBM: compute it into shared memory while the tile is resident, +then accumulate `scaling * (that) @ lora_b[l].T` straight into the same accumulator the shared projection +is building. Done separately, the adapter costs a second full read of `xc`, two extra launches per depth, +and a round trip of the intermediate — on a delta that is a few percent of the arithmetic. + +The `L` depths are completely independent, which is free parallelism for filling the machine at small `T`, +and `T` is ragged, so size the tail carefully. + +## Precision and faithfulness (read this) + +Inputs are **bfloat16** and the output may be bf16 or fp32. Accumulate every matmul in +**fp32** — including the adapter's two, whose product is added to a much larger base term, so its own +rounding is amplified by nothing but must not be thrown away. + +`scaling` is a Python float. Fold it into the adapter's up-projection or apply it to the rank-wide +intermediate; either is fine, but do it in fp32. + +**fp8 is not appropriate here**: the weights and activations arrive in bf16 and re-quantising them is an +approximation of the specified computation, not an implementation of it. + +**Where the tolerance comes from.** `1e-2` is measured. A second, independent implementation — all `L` +depths batched into one `bmm` against a broadcast weight, the concatenation formed implicitly by splitting +the K-loop, the LoRA fused as `xc @ (lora_a.T @ lora_b.T)` in the other association order, bf16 operands +with fp32 accumulate — differs from this fp32 reference by a worst relative Frobenius error of **3.30e-3** +across the correctness shapes and two full-size graded shapes, over several seeds. The tolerance is +**2.1x** that, and the error is flat in `L` and `T` (2.86e-3 at the large shapes) because it is the bf16 +rounding of the operands and of the returned tensor and nothing else. + +### What the tolerance does NOT permit + +The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful +implementation of the specified computation**. It is not a budget to spend on approximation. The following +are wrong answers even if they happen to land inside the tolerance at some shape: + +- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a + series, low-rank or sketched substitutes, skipping a correction term); +- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling + or striding over the sequence, ignoring positions whose contribution "looks small"); +- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions + that the spec gives their own); +- anything whose error **grows** with sequence length, batch, or head count. + +A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of +magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes +are deliberately large, so the difference shows up. + +## What's available + +- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline + extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL** + (`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported. +- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping. +- A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist. + The exact part is deliberately **not** stated: query it and tune to what you actually find. + +```python +p = torch.cuda.get_device_properties(0) +p.name, p.major, p.minor # part and compute capability +p.multi_processor_count # SM count -- size your persistent grid from this, never a constant +p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor +p.shared_memory_per_block_optin # opt-in dynamic smem, the number that matters for big tiles +``` + + `nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK` + give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a + datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak + FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the + score is an absolute metric, so a kernel tuned to a machine it never sees is just slower. +- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is + already installed, and no library implementation of this kernel exists on the machine. +- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see + `/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`. + +## How the grading actually runs (so there are no surprises) + +- **`/app/shared_qkv.py` is the only file that is graded.** The grader imports `shared_block_qkv` from it and reads nothing + else from `/app`. +- **The grader is not on this machine while you work.** It is copied in only after your session ends and it + carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py` + or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on + your score**. Do not spend budget on them. +- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked + against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather + than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised. +- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**. +- Inputs are random each grade and the graded shapes are not the ones in `measure.py`. diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/task.toml b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d9159300c73c8d678d3b19089edbd52357ed8fa5 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/zamba-shared-attn-lora-qkv" +description = "Zamba-2 does not give every attention layer its own weights — it has ONE attention block and calls it at several depths of a Mamba stack, feeding it the concatenation of the current residual stream and the original token embedding, and giving each invocation its own low-rank adapter so the shared weights can still specialise. The QKV projection therefore runs L times against the same 50 MB of weights with L different rank-64 deltas, and done as L separate library calls the shared weight is re-read from HBM every time and the adapters get three extra launches each." +authors = [] +keywords = ["mle", "kernel-generation", "zamba", "hybrid", "shared-attention", "lora", "multi-adapter", "gemm", "fusion", "compute-bound"] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",] + +[verifier] +timeout_sec = 1800.0 + +[agent] +timeout_sec = 14400.0 + +# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0 +# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5). +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 65536 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/test.sh b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..96147b7a26c9a89b5c158060756222d7b0fe22a5 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/test.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink. +set -u +mkdir -p /logs/verifier +python3 /tests/verify_env.py diff --git a/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/verify_env.py b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/verify_env.py new file mode 100644 index 0000000000000000000000000000000000000000..f93769a86bc6d4f8f2eeba36913e8d82f852ac56 --- /dev/null +++ b/tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/verify_env.py @@ -0,0 +1,184 @@ +"""zamba-shared-attn-lora-qkv verifier — correctness gate + achieved-TFLOP/s SPEED LEADERBOARD (uncapped). + + reward = 0 if the submission is incorrect + reward = geomean over graded shapes of TFLOP/s otherwise + +GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate. + +There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable +by construction and nothing has to be vendored, sealed, or re-benchmarked. + +CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded +shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel +scores 0. + +ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last +timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a +result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate +throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised. + +WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all +submissions are credited identically and the ranking is a pure speed ranking. +""" +import importlib.util +import json +import math +import os +import sys +import traceback + +import torch + +REWARD_DIR = "/logs/verifier" +MODULE_PATH = "/app/shared_qkv.py" +TOL = 0.007 + +GRADER_SHAPES = [(6, 4096, 2048, 64), (4, 4096, 2560, 64), (8, 2048, 2048, 32), (6, 3072, 2048, 128), (4, 6144, 2048, 64)] +CORRECT_SHAPES = [(2, 256, 256, 16), (3, 129, 128, 8), (4, 512, 512, 32), (2, 64, 128, 4)] + +sys.path.insert(0, "/app") + +def canonical_work(L, T, Dm, r): + """FLOPs attributed to one call, from the SHAPE ALONE. + + Per depth, at 2 FLOPs per multiply-add: the shared projection (T, 2*Dm) x (2*Dm, 3*Dm), the adapter's + down-projection (T, 2*Dm) x (2*Dm, r) and its up-projection (T, r) x (r, 3*Dm). The concatenation and + the residual add are O(T*Dm) data movement and are not credited. + """ + return L * (2 * T * (2 * Dm) * (3 * Dm) + 2 * T * (2 * Dm) * r + 2 * T * r * (3 * Dm)) + +def _ref(h, emb, w_qkv, lora_a, lora_b, scaling): + """One depth at a time: concatenate, project with the shared weight, add the depth's LoRA delta. + + Correct and simple — it is the numerical SPECIFICATION, not a performance target. The shared weight is + re-read for every depth and the rank-wide intermediate goes to HBM. + """ + L, T, Dm = h.shape + out = torch.empty(L, T, 3 * Dm, device=h.device, dtype=torch.float32) + w = w_qkv.float() + e = emb.float() + for l in range(L): + xc = torch.cat([h[l].float(), e], dim=-1) # (T, 2*Dm) [state | embedding] + base = xc @ w.t() # the SHARED projection + delta = (xc @ lora_a[l].float().t()) @ lora_b[l].float().t() + out[l] = base + scaling * delta + return out.to(torch.bfloat16) + +def _mk(L, T, Dm, r, seed): + """Per-depth residual streams, one shared embedding, the shared weight and L LoRA adapters. + + The adapters are scaled so the delta is a real but minority contribution (its RMS is `16/r` of the + base projection's), which is what a trained LoRA looks like — big enough that ignoring it is obvious, + small enough that it is a correction rather than the answer. + """ + gen = torch.Generator(device="cuda").manual_seed(seed) + + def rnd(*sh, s=1.0): + return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16) + + h = rnd(L, T, Dm) + emb = rnd(T, Dm) + w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5) + lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5) + return h, emb, w_qkv, lora_a, lora_b, 16.0 / r + + +def _is_exact(t): + """Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large + ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass.""" + return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool) + + +def _check(out, ref): + """-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise.""" + if out is None or tuple(out.shape) != tuple(ref.shape): + return False, 1.0, "bad/None shape" + if _is_exact(ref): + bad = int((out != ref).sum()) + return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ") + e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12)) + return e <= TOL, e, f"relerr {e:.2e}" + + +def _bench_fresh(fn, mkargs, reps=5, warm=3): + """Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring.""" + wargs = mkargs(0) + for _ in range(warm): + fn(*wargs) + torch.cuda.synchronize() + del wargs + torch.cuda.empty_cache() + + best, timed_ok = float("inf"), True + for i in range(reps): + args = mkargs(10_000 + i) + s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + s.record() + out = fn(*args) + e.record() + torch.cuda.synchronize() + best = min(best, s.elapsed_time(e)) + if i == reps - 1: + timed_ok = _check(out, _ref(*args))[0] + del args, out + torch.cuda.empty_cache() + return best / 1e3, timed_ok + + +def _geomean(xs): + return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0 + + +def main(): + details, correct_gate, geo = {}, False, 0.0 + try: + spec = importlib.util.spec_from_file_location("submission", MODULE_PATH) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + fn = m.shared_block_qkv + + corr_ok, msg = True, "" + for i, shp in enumerate(CORRECT_SHAPES): + args = _mk(*shp, seed=10 + i) + ok, val, m_ = _check(fn(*args), _ref(*args)) + if not ok: + corr_ok, msg = False, f"cfg{i} {shp} {m_}" + break + del args + torch.cuda.empty_cache() + details["correct_msg"] = msg or "all correctness shapes pass" + + vals, per_shape, perf_ok = [], [], corr_ok + for i, shp in enumerate(GRADER_SHAPES): + args = _mk(*shp, seed=100 + i) + ok, val, m_ = _check(fn(*args), _ref(*args)) + if not ok: + perf_ok = False + del args + torch.cuda.empty_cache() + t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s)) + if not timed_ok: + perf_ok = False + v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0 + vals.append(v) + per_shape.append({"shape": list(shp), "tflops": round(v, 3), "ms": round(t * 1e3, 3), + "check": m_, "timed_ok": timed_ok}) + geo = _geomean(vals) + details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok) + correct_gate = corr_ok and perf_ok + except Exception as e: + details["error"] = f"{e.__class__.__name__}: {e}"[:220] + details["trace"] = traceback.format_exc()[-800:] + + reward = round(geo, 4) if correct_gate else 0.0 + os.makedirs(REWARD_DIR, exist_ok=True) + json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0, + "geomean": round(geo, 4), "metric": "TFLOP/s (geomean over graded shapes)"}, + open(f"{REWARD_DIR}/reward.json", "w"), indent=2) + open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward)) + json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str) + print("reward:", reward, "TFLOP/s | correct:", 1.0 if correct_gate else 0.0) + + +main() diff --git a/tasks/raw-cuda/README.md b/tasks/raw-cuda/README.md index cf68e60dfdd2dcf0c4a8c97ffaae4cd8e1d68d01..5b2f536318bf119f6f88073e7ebcec78fff49594 100644 --- a/tasks/raw-cuda/README.md +++ b/tasks/raw-cuda/README.md @@ -2,13 +2,19 @@ Raw-CUDA tasks. No PyTorch and no Triton are installed at all — the agent gets `nvcc`, CUTLASS and the profilers, and writes CUDA C++ against a C-level harness. -**6 tasks.** +**12 tasks.** | task | metric | roofline | what the kernel does | |---|---|---|---| +| [`cuda-blockwise-softmax`](cuda-blockwise-softmax/) | — | — | | +| [`cuda-fp8-cast-pack`](cuda-fp8-cast-pack/) | — | — | | +| [`cuda-histogram-atomics`](cuda-histogram-atomics/) | — | — | | | [`cuda-linear-recurrence`](cuda-linear-recurrence/) | — | — | | +| [`cuda-radix-partition`](cuda-radix-partition/) | — | — | | | [`cuda-relu2-aggregation`](cuda-relu2-aggregation/) | — | — | | | [`cuda-topk-indices`](cuda-topk-indices/) | — | — | | +| [`cuda-transpose-vectorized`](cuda-transpose-vectorized/) | — | — | | +| [`cuda-warp-scan-segmented`](cuda-warp-scan-segmented/) | — | — | | | [`flash-attention-fwd`](flash-attention-fwd/) | — | — | | | [`gptq-w4a16-gemm`](gptq-w4a16-gemm/) | — | — | | | [`qserve-w4a8-gemm`](qserve-w4a8-gemm/) | — | — | | diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/CLAUDE.md b/tasks/raw-cuda/cuda-blockwise-softmax/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/Dockerfile b/tasks/raw-cuda/cuda-blockwise-softmax/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bd27b254973c75a793a2ec18fc2b8791c0b69b0 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/Dockerfile @@ -0,0 +1,34 @@ +# CUDA kernel-generation task: write a fast row-wise (online) softmax kernel in solution.cu. +# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton. +FROM nvidia/cuda:12.8.1-devel-ubuntu24.04 + +# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps. +RUN apt-get update && apt-get install -y --no-install-recommends \ + git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \ + rm -rf /var/lib/apt/lists/* + +# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled). +# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed, +# and dropping it keeps the environment free of any torch/triton files. +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \ + git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \ + mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi + +# Pre-bake the agent (the offline firewall blocks installing it at run time). +RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent +ENV PATH=/root/.local/bin:$PATH + +# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper. +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ +COPY solution.cu /app/solution.cu +COPY harness.cu /app/harness.cu +COPY build.sh /app/build.sh +RUN chmod +x /app/build.sh + +# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched). +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh + +# Strip apt sources so harbor's base apt-setup is a no-op under the firewall. +RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/* diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/PROCESS_MANAGEMENT.md b/tasks/raw-cuda/cuda-blockwise-softmax/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/build.sh b/tasks/raw-cuda/cuda-blockwise-softmax/environment/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..357f55e23f8935d722b8d834360ae4e1fe68d3cc --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Compile your solution against the harness and run one seed (the grader uses a different seed). +set -e +nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run +/app/run 0 diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/docker-compose.yaml b/tasks/raw-cuda/cuda-blockwise-softmax/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b626bc85e10f49e564a9bb840c97b1fc5d66561f --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/docker-compose.yaml @@ -0,0 +1,17 @@ +# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose. +# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked). +# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has +# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it. +services: + main: + cap_add: + - NET_ADMIN + - SYS_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/harness.cu b/tasks/raw-cuda/cuda-blockwise-softmax/environment/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..f489091a6f5879023743caf5fd7da338d8affe35 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/harness.cu @@ -0,0 +1,128 @@ +// Grading harness for cuda-blockwise-softmax. +// out[b, v] = exp(x[b,v] - max_v x[b,v]) / sum_v exp(x[b,v] - max_v x[b,v]) per row, in fp32 +// x[B, V] bfloat16 row-major in, out[B, V] bfloat16 row-major out. +// Rows are LONG (V = 131072) and a few of them carry logits large enough that exp() overflows fp32 +// unless the row max is subtracted first -- the numerically stable form is required, not optional. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one thread per row, three sequential passes over the row. +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int B = 4096, V = 131072; // 5.4e8 elements: 1.07 GB in, 1.07 GB out +static const float TOL = 5e-3f; +#ifndef R_BAR +#define R_BAR 29.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(__nv_bfloat16* x, long n, int V_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u); + float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2); + int row = (int)(i / V_); + // most rows are ordinary attention-scale logits; every 97th row is an outlier row whose + // logits reach ~140, so exp() overflows fp32 if the row max is not subtracted first + float sc = (row % 97 == 0) ? 30.0f : 3.0f; + x[i] = __float2bfloat16(g * sc); + } +} + +// ---- naive reference: one thread per row, three sequential passes -------------------------------- +__global__ void naive_kernel(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_){ + for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < B_; r += (long)gridDim.x * blockDim.x){ + const __nv_bfloat16* xr = x + r * (long)V_; + __nv_bfloat16* orow = out + r * (long)V_; + float m = -INFINITY; + for(int j = 0; j < V_; j++) m = fmaxf(m, __bfloat162float(xr[j])); + float s = 0.f; + for(int j = 0; j < V_; j++) s += expf(__bfloat162float(xr[j]) - m); + float inv = 1.f / s; + for(int j = 0; j < V_; j++) orow[j] = __float2bfloat16(expf(__bfloat162float(xr[j]) - m) * inv); + } +} + +// ---- comparison: relative Frobenius -------------------------------------------------------------- +__global__ void cmp_kernel(const __nv_bfloat16* a, const __nv_bfloat16* b, long n, double* acc){ + __shared__ double sn[256], sd[256]; + double num = 0.0, den = 0.0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + double va = (double)__bfloat162float(a[i]), vb = (double)__bfloat162float(b[i]); + if(!isfinite(va)) va = 1e30; // an inf/nan from an unstable kernel must not pass + num += (va - vb) * (va - vb); + den += vb * vb; + } + sn[threadIdx.x] = num; sd[threadIdx.x] = den; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ + if(threadIdx.x < o){ sn[threadIdx.x] += sn[threadIdx.x + o]; sd[threadIdx.x] += sd[threadIdx.x + o]; } + __syncthreads(); + } + if(threadIdx.x == 0){ atomicAdd(acc, sn[0]); atomicAdd(acc + 1, sd[0]); } +} + +typedef void(*Fn)(const __nv_bfloat16*, __nv_bfloat16*); +static float time_ms(Fn run, const __nv_bfloat16* a, __nv_bfloat16* b, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(a, b); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const __nv_bfloat16* a, __nv_bfloat16* b){ naive_kernel<<<64, 64>>>(a, b, B, V); } +static void run_agent(const __nv_bfloat16* a, __nv_bfloat16* b){ row_softmax(a, b, B, V); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)B * V; + __nv_bfloat16 *x, *oref, *oag; double* acc; + CK(cudaMalloc(&x, n * 2)); CK(cudaMalloc(&oref, n * 2)); CK(cudaMalloc(&oag, n * 2)); + CK(cudaMalloc(&acc, 16)); CK(cudaMemset(acc, 0, 16)); CK(cudaMemset(oag, 0, n * 2)); + gen_kernel<<<1024, 256>>>(x, n, V, seed); + CK(cudaDeviceSynchronize()); + + run_naive(x, oref); CK(cudaDeviceSynchronize()); + run_agent(x, oag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(oag, oref, n, acc); + CK(cudaDeviceSynchronize()); + double h[2]; CK(cudaMemcpy(h, acc, 16, cudaMemcpyDeviceToHost)); + double rel = sqrt(h[0] / (h[1] + 1e-30)); + + float tn = time_ms(run_naive, x, oref, 1, 3); + float ta = time_ms(run_agent, x, oag, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (rel < TOL); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("rel_err=%.3e | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d " + "-> reward=%.1f\n", rel, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"rel_err\": %.3e, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, rel, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/restrict-network.sh b/tasks/raw-cuda/cuda-blockwise-softmax/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..10f759d82f01fe8868baa01a7816d23deea150c1 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone +# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is +# pre-installed (harbor's patched installer skips the network install when it is already present), so no +# package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they +# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/environment/solution.cu b/tasks/raw-cuda/cuda-blockwise-softmax/environment/solution.cu new file mode 100644 index 0000000000000000000000000000000000000000..101fe50001a5fb48fc387037dd55c1693718f444 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/environment/solution.cu @@ -0,0 +1,18 @@ +// solution.cu — implement the row-wise softmax described in the instruction. +// m[b] = max over v of x[b,v] +// out[b,v] = exp(x[b,v] - m[b]) / sum_v exp(x[b,v] - m[b]) +// x[B,V] and out[B,V] are bfloat16 row-major; all arithmetic in fp32. B = 4096, V = 131072 (fixed). +// Some rows carry logits near 140, so the max MUST be subtracted before exp() or fp32 overflows. +// This stub writes zeros (it compiles and runs, but is incorrect — reward 0). +#include +#include + +__global__ void stub_k(__nv_bfloat16* out, long n){ + long i = (long)blockIdx.x * blockDim.x + threadIdx.x; + if(i < n) out[i] = __float2bfloat16(0.f); +} + +void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V){ + long n = (long)B * V; + stub_k<<<(n + 255) / 256, 256>>>(out, n); +} diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/instruction.md b/tasks/raw-cuda/cuda-blockwise-softmax/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01ec15c240dc8d8430ccda1fc4e1eb8026fa700f --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/instruction.md @@ -0,0 +1,64 @@ +# Write a fast CUDA kernel for a row-wise softmax over very long rows + +Implement a high-performance CUDA kernel in `/app/solution.cu` that softmaxes each row of a large `bfloat16` +matrix — the shape a vocabulary-sized logits matrix or a long attention-score row has. + +Input: `x` of shape `[B, V]` (`__nv_bfloat16`, row-major). Output: `out` of shape `[B, V]` +(`__nv_bfloat16`, row-major). For each row `b`: + +``` +m[b] = max over v of x[b, v] +s[b] = sum over v of exp( x[b, v] - m[b] ) +out[b,v] = exp( x[b, v] - m[b] ) / s[b] +``` + +All arithmetic in **fp32**; only the stored result is bfloat16. The sizes are fixed: +**B = 4096, V = 131072** — 1.07 GB in, 1.07 GB out, and a row is 256 KB. + +**Subtracting the row max is required, not an optimisation.** Roughly one row in a hundred is an outlier row +whose logits reach ~140, and `expf(140)` overflows fp32. A kernel that computes `exp(x)/sum(exp(x))` +directly produces `inf`/`nan` on those rows and fails the correctness gate. + +The function signature (fixed) is in `/app/solution.cu`: +```cpp +void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V); +``` + +## How success is decided + +The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and +checks: +1. **Correctness** — relative Frobenius error below **5e-3** against the reference (non-finite outputs are + scored as maximally wrong). That gate is measured: the reference sums each row **sequentially** in fp32 + while any block-parallel kernel sums it as a tree, and with a bf16 output that difference alone measures + **8e-4 – 9.5e-4**. The gate is ~5x that, which covers reduction order and a fast `expf`, and is nowhere + near loose enough to admit a softmax over the wrong axis or an unstable one. +2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event + timed, warmup + median; the exact bar is printed when you build). + +Both must pass for reward 1.0. + +## Notes + +- The reference the bar is measured against is **one thread per row**, walking the row **three times** (max, + then sum, then normalise). It is uncoalesced *and* it makes three trips over the data — both are worth + fixing, and only one of them is obvious. +- A row is 256 KB, so it does not fit in registers or shared memory: you cannot keep it on chip between + passes. But you do not need three passes either — the max and the sum can be accumulated **together** in a + single sweep if you carry a running `(max, sum)` pair and rescale the sum whenever the max moves + (`s <- s * exp(m_old - m_new)`). That is the standard online-softmax recurrence, and it turns three passes + over HBM into two. +- One block per row is the natural decomposition (`B = 4096` rows, so there is plenty of parallelism). Inside + the block you need a max reduction and a sum reduction; warp shuffles plus a small shared-memory stage are + enough, and a block-wide barrier per row is unavoidable — but there should be only **one** of each. +- Vectorise: an element is 2 bytes and a 128-bit access moves 8 of them, on both the load and the store side. +- Think about where the second pass reads from. The rows a wave of blocks is working on are a few tens of MB + in total, which is not nothing relative to the L2 you can query with `cudaGetDeviceProperties` — how many + blocks you keep resident changes whether the re-read is an HBM read or an L2 hit. +- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer** + (`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA, including block-wide reductions), and the + profilers **`ncu`** and **`nsys`**. There is **no PyTorch and no Triton**; this is a pure CUDA task. +- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader + uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how + you are measured; you only edit `solution.cu`. +- **No internet access.** diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/solution/solution.oracle.cu b/tasks/raw-cuda/cuda-blockwise-softmax/solution/solution.oracle.cu new file mode 100644 index 0000000000000000000000000000000000000000..80295097989abdf4bd3b67afcd4b5e3083b4b2b2 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/solution/solution.oracle.cu @@ -0,0 +1,65 @@ +// Oracle: one block per row, ONLINE softmax so the row is read twice instead of three times. +// pass 1: running (max, sum) with rescaling -> block reduce -> (m, S) +// pass 2: re-read the row and emit exp(x-m)/S +// 128-bit loads and stores (8 bf16 per access); everything in fp32. +#include +#include + +#define NTHREAD 512 + +__global__ __launch_bounds__(NTHREAD) void softmax_k(const __nv_bfloat16* __restrict__ x, + __nv_bfloat16* __restrict__ out, int V){ + const long row = blockIdx.x; + const uint4* xr = reinterpret_cast(x + row * (long)V); + uint4* orow = reinterpret_cast(out + row * (long)V); + const int nvec = V / 8; + + float m = -INFINITY, s = 0.f; + for(int i = threadIdx.x; i < nvec; i += NTHREAD){ // online max+sum + uint4 v = xr[i]; + const __nv_bfloat16* h = reinterpret_cast(&v); + float lm = -INFINITY; + #pragma unroll + for(int j = 0; j < 8; j++) lm = fmaxf(lm, __bfloat162float(h[j])); + if(lm > m){ s *= __expf(m - lm); m = lm; } + #pragma unroll + for(int j = 0; j < 8; j++) s += __expf(__bfloat162float(h[j]) - m); + } + // block reduce: max first, then rescale each lane's sum onto it + __shared__ float sm[NTHREAD / 32], ss[NTHREAD / 32]; + float mm = m; + for(int o = 16; o; o >>= 1) mm = fmaxf(mm, __shfl_xor_sync(0xffffffff, mm, o)); + if((threadIdx.x & 31) == 0) sm[threadIdx.x >> 5] = mm; + __syncthreads(); + if(threadIdx.x < 32){ + float v = (threadIdx.x < NTHREAD / 32) ? sm[threadIdx.x] : -INFINITY; + for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + if(threadIdx.x == 0) sm[0] = v; + } + __syncthreads(); + const float M = sm[0]; + float sv = s * __expf(m - M); + for(int o = 16; o; o >>= 1) sv += __shfl_xor_sync(0xffffffff, sv, o); + if((threadIdx.x & 31) == 0) ss[threadIdx.x >> 5] = sv; + __syncthreads(); + if(threadIdx.x < 32){ + float v = (threadIdx.x < NTHREAD / 32) ? ss[threadIdx.x] : 0.f; + for(int o = 16; o; o >>= 1) v += __shfl_xor_sync(0xffffffff, v, o); + if(threadIdx.x == 0) ss[0] = v; + } + __syncthreads(); + const float inv = 1.0f / ss[0]; + + for(int i = threadIdx.x; i < nvec; i += NTHREAD){ + uint4 v = xr[i]; + const __nv_bfloat16* h = reinterpret_cast(&v); + __nv_bfloat16 o8[8]; + #pragma unroll + for(int j = 0; j < 8; j++) o8[j] = __float2bfloat16(__expf(__bfloat162float(h[j]) - M) * inv); + orow[i] = *reinterpret_cast(o8); + } +} + +void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V){ + softmax_k<<>>(x, out, V); +} diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/solution/solve.sh b/tasks/raw-cuda/cuda-blockwise-softmax/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4124f8ba256e220c1ea3826306df1bbd1354269 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/solution/solve.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Oracle: restore the reference fast kernel. +set -e +cat > /app/solution.cu <<'ORACLE_CU_EOF' +// Oracle: one block per row, ONLINE softmax so the row is read twice instead of three times. +// pass 1: running (max, sum) with rescaling -> block reduce -> (m, S) +// pass 2: re-read the row and emit exp(x-m)/S +// 128-bit loads and stores (8 bf16 per access); everything in fp32. +#include +#include + +#define NTHREAD 512 + +__global__ __launch_bounds__(NTHREAD) void softmax_k(const __nv_bfloat16* __restrict__ x, + __nv_bfloat16* __restrict__ out, int V){ + const long row = blockIdx.x; + const uint4* xr = reinterpret_cast(x + row * (long)V); + uint4* orow = reinterpret_cast(out + row * (long)V); + const int nvec = V / 8; + + float m = -INFINITY, s = 0.f; + for(int i = threadIdx.x; i < nvec; i += NTHREAD){ // online max+sum + uint4 v = xr[i]; + const __nv_bfloat16* h = reinterpret_cast(&v); + float lm = -INFINITY; + #pragma unroll + for(int j = 0; j < 8; j++) lm = fmaxf(lm, __bfloat162float(h[j])); + if(lm > m){ s *= __expf(m - lm); m = lm; } + #pragma unroll + for(int j = 0; j < 8; j++) s += __expf(__bfloat162float(h[j]) - m); + } + // block reduce: max first, then rescale each lane's sum onto it + __shared__ float sm[NTHREAD / 32], ss[NTHREAD / 32]; + float mm = m; + for(int o = 16; o; o >>= 1) mm = fmaxf(mm, __shfl_xor_sync(0xffffffff, mm, o)); + if((threadIdx.x & 31) == 0) sm[threadIdx.x >> 5] = mm; + __syncthreads(); + if(threadIdx.x < 32){ + float v = (threadIdx.x < NTHREAD / 32) ? sm[threadIdx.x] : -INFINITY; + for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + if(threadIdx.x == 0) sm[0] = v; + } + __syncthreads(); + const float M = sm[0]; + float sv = s * __expf(m - M); + for(int o = 16; o; o >>= 1) sv += __shfl_xor_sync(0xffffffff, sv, o); + if((threadIdx.x & 31) == 0) ss[threadIdx.x >> 5] = sv; + __syncthreads(); + if(threadIdx.x < 32){ + float v = (threadIdx.x < NTHREAD / 32) ? ss[threadIdx.x] : 0.f; + for(int o = 16; o; o >>= 1) v += __shfl_xor_sync(0xffffffff, v, o); + if(threadIdx.x == 0) ss[0] = v; + } + __syncthreads(); + const float inv = 1.0f / ss[0]; + + for(int i = threadIdx.x; i < nvec; i += NTHREAD){ + uint4 v = xr[i]; + const __nv_bfloat16* h = reinterpret_cast(&v); + __nv_bfloat16 o8[8]; + #pragma unroll + for(int j = 0; j < 8; j++) o8[j] = __float2bfloat16(__expf(__bfloat162float(h[j]) - M) * inv); + orow[i] = *reinterpret_cast(o8); + } +} + +void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V){ + softmax_k<<>>(x, out, V); +} +ORACLE_CU_EOF +echo restored diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/task.toml b/tasks/raw-cuda/cuda-blockwise-softmax/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f621ac2f0b7f9b5c228d7d28adfc8d6a62e1129f --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/task.toml @@ -0,0 +1,36 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/cuda-blockwise-softmax" +description = "Write a fast hand-written CUDA kernel for a row-wise softmax over very long rows (bf16 [4096, 131072], 2.15 GB), beating a one-thread-per-row three-pass reference by a calibrated margin. A row is 256 KB so it cannot be held on chip: the win is the online (running max + rescaled sum) recurrence that turns three HBM passes into two, one block per row with a single max and a single sum reduction, and 128-bit accesses. Outlier rows overflow fp32 unless the row max is subtracted, so the numerically stable form is graded. Hand-written CUDA only (CUTLASS/flashinfer/CUB); no PyTorch/Triton; ncu/nsys available." +authors = [] +keywords = [ "mle", "kernel-generation", "cuda", "softmax", "online-softmax", "reduction", "bandwidth", "gpu",] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "cuda", "gpu", "performance", "real-world",] + +[verifier] +timeout_sec = 600.0 + +[agent] +timeout_sec = 14400.0 + +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 32768 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/tests/harness.cu b/tasks/raw-cuda/cuda-blockwise-softmax/tests/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..f489091a6f5879023743caf5fd7da338d8affe35 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/tests/harness.cu @@ -0,0 +1,128 @@ +// Grading harness for cuda-blockwise-softmax. +// out[b, v] = exp(x[b,v] - max_v x[b,v]) / sum_v exp(x[b,v] - max_v x[b,v]) per row, in fp32 +// x[B, V] bfloat16 row-major in, out[B, V] bfloat16 row-major out. +// Rows are LONG (V = 131072) and a few of them carry logits large enough that exp() overflows fp32 +// unless the row max is subtracted first -- the numerically stable form is required, not optional. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one thread per row, three sequential passes over the row. +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int B = 4096, V = 131072; // 5.4e8 elements: 1.07 GB in, 1.07 GB out +static const float TOL = 5e-3f; +#ifndef R_BAR +#define R_BAR 29.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(__nv_bfloat16* x, long n, int V_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u); + float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2); + int row = (int)(i / V_); + // most rows are ordinary attention-scale logits; every 97th row is an outlier row whose + // logits reach ~140, so exp() overflows fp32 if the row max is not subtracted first + float sc = (row % 97 == 0) ? 30.0f : 3.0f; + x[i] = __float2bfloat16(g * sc); + } +} + +// ---- naive reference: one thread per row, three sequential passes -------------------------------- +__global__ void naive_kernel(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_){ + for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < B_; r += (long)gridDim.x * blockDim.x){ + const __nv_bfloat16* xr = x + r * (long)V_; + __nv_bfloat16* orow = out + r * (long)V_; + float m = -INFINITY; + for(int j = 0; j < V_; j++) m = fmaxf(m, __bfloat162float(xr[j])); + float s = 0.f; + for(int j = 0; j < V_; j++) s += expf(__bfloat162float(xr[j]) - m); + float inv = 1.f / s; + for(int j = 0; j < V_; j++) orow[j] = __float2bfloat16(expf(__bfloat162float(xr[j]) - m) * inv); + } +} + +// ---- comparison: relative Frobenius -------------------------------------------------------------- +__global__ void cmp_kernel(const __nv_bfloat16* a, const __nv_bfloat16* b, long n, double* acc){ + __shared__ double sn[256], sd[256]; + double num = 0.0, den = 0.0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + double va = (double)__bfloat162float(a[i]), vb = (double)__bfloat162float(b[i]); + if(!isfinite(va)) va = 1e30; // an inf/nan from an unstable kernel must not pass + num += (va - vb) * (va - vb); + den += vb * vb; + } + sn[threadIdx.x] = num; sd[threadIdx.x] = den; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ + if(threadIdx.x < o){ sn[threadIdx.x] += sn[threadIdx.x + o]; sd[threadIdx.x] += sd[threadIdx.x + o]; } + __syncthreads(); + } + if(threadIdx.x == 0){ atomicAdd(acc, sn[0]); atomicAdd(acc + 1, sd[0]); } +} + +typedef void(*Fn)(const __nv_bfloat16*, __nv_bfloat16*); +static float time_ms(Fn run, const __nv_bfloat16* a, __nv_bfloat16* b, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(a, b); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const __nv_bfloat16* a, __nv_bfloat16* b){ naive_kernel<<<64, 64>>>(a, b, B, V); } +static void run_agent(const __nv_bfloat16* a, __nv_bfloat16* b){ row_softmax(a, b, B, V); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)B * V; + __nv_bfloat16 *x, *oref, *oag; double* acc; + CK(cudaMalloc(&x, n * 2)); CK(cudaMalloc(&oref, n * 2)); CK(cudaMalloc(&oag, n * 2)); + CK(cudaMalloc(&acc, 16)); CK(cudaMemset(acc, 0, 16)); CK(cudaMemset(oag, 0, n * 2)); + gen_kernel<<<1024, 256>>>(x, n, V, seed); + CK(cudaDeviceSynchronize()); + + run_naive(x, oref); CK(cudaDeviceSynchronize()); + run_agent(x, oag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(oag, oref, n, acc); + CK(cudaDeviceSynchronize()); + double h[2]; CK(cudaMemcpy(h, acc, 16, cudaMemcpyDeviceToHost)); + double rel = sqrt(h[0] / (h[1] + 1e-30)); + + float tn = time_ms(run_naive, x, oref, 1, 3); + float ta = time_ms(run_agent, x, oag, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (rel < TOL); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("rel_err=%.3e | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d " + "-> reward=%.1f\n", rel, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"rel_err\": %.3e, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, rel, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-blockwise-softmax/tests/test.sh b/tasks/raw-cuda/cuda-blockwise-softmax/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..18efdf3a3a726f0f80160d553ce52bc77c051af4 --- /dev/null +++ b/tasks/raw-cuda/cuda-blockwise-softmax/tests/test.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Verifier: compile the FRESH harness + the agent's solution, grade with a random seed. +set -uo pipefail +mkdir -p /logs/verifier +SEED=$(( (RANDOM << 15) ^ RANDOM )) +nvcc -O3 -arch=native /tests/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /tmp/grade 2>/tmp/nvcc.log +if [ ! -x /tmp/grade ]; then + echo "COMPILE FAILED:"; tail -20 /tmp/nvcc.log + echo "0.0" > /logs/verifier/reward.txt + echo '{"reward": 0.0, "error": "compile_failed"}' > /logs/verifier/reward.json + exit 0 +fi +/tmp/grade "$SEED" # the harness writes /logs/verifier/reward.{txt,json} +cat /logs/verifier/reward.json 2>/dev/null || true diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/CLAUDE.md b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/Dockerfile b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bc831a5ec5497e66eba8c14d199f691bd84a9205 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/Dockerfile @@ -0,0 +1,34 @@ +# CUDA kernel-generation task: write a fast per-token FP8 quantisation kernel in solution.cu. +# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton. +FROM nvidia/cuda:12.8.1-devel-ubuntu24.04 + +# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps. +RUN apt-get update && apt-get install -y --no-install-recommends \ + git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \ + rm -rf /var/lib/apt/lists/* + +# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled). +# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed, +# and dropping it keeps the environment free of any torch/triton files. +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \ + git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \ + mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi + +# Pre-bake the agent (the offline firewall blocks installing it at run time). +RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent +ENV PATH=/root/.local/bin:$PATH + +# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper. +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ +COPY solution.cu /app/solution.cu +COPY harness.cu /app/harness.cu +COPY build.sh /app/build.sh +RUN chmod +x /app/build.sh + +# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched). +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh + +# Strip apt sources so harbor's base apt-setup is a no-op under the firewall. +RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/* diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/PROCESS_MANAGEMENT.md b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/build.sh b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..357f55e23f8935d722b8d834360ae4e1fe68d3cc --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Compile your solution against the harness and run one seed (the grader uses a different seed). +set -e +nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run +/app/run 0 diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/docker-compose.yaml b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b626bc85e10f49e564a9bb840c97b1fc5d66561f --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/docker-compose.yaml @@ -0,0 +1,17 @@ +# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose. +# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked). +# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has +# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it. +services: + main: + cap_add: + - NET_ADMIN + - SYS_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/harness.cu b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..ad03b557db7d4a2b785794c0b825594b7c252827 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/harness.cu @@ -0,0 +1,145 @@ +// Grading harness for cuda-fp8-cast-pack. +// Per-row (per-token) FP8 e4m3 activation quantisation: +// scale[m] = max( max_n |x[m,n]| , 1e-12f ) / 448.0f +// q[m,n] = fp8_e4m3( x[m,n] / scale[m] ) (round-to-nearest-even, saturating) +// x[M,N] bfloat16 row-major in; q[M,N] fp8_e4m3 + scale[M] float32 out. +// Inputs are generated ON DEVICE from the seed (deterministic, and fast enough to iterate on). +// The naive reference is one thread per row, two sequential passes over the row. +// Correctness: scales must agree to 1e-6 relative, and the DEQUANTISED values (q*scale) to 5e-3 +// relative Frobenius -- which tolerates the odd 1-ulp code flip but not a wrong rounding rule. +#include +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int M = 32768, N = 16384; // 5.4e8 elements: 1.07 GB in, 537 MB + 128 KB out +static const float FP8_MAX = 448.0f; +static const float TOL_DEQ = 5e-3f; // relative Frobenius on dequantised values +static const float TOL_SCALE = 1e-6f; // relative, per row +#ifndef R_BAR +#define R_BAR 20.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M_, int N_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +// gaussian-ish (Box-Muller) times a per-row magnitude that spans ~30x, so row scales really differ +__global__ void gen_kernel(__nv_bfloat16* x, long n, int N_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u); + float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2); + int row = (int)(i / N_); + float rs = expf(unif(mix(row * 9781u + seed)) * 3.4f - 1.7f); + x[i] = __float2bfloat16(g * rs); + } +} + +// ---- naive reference: one thread per row, two sequential passes ---------------------------------- +__global__ void naive_kernel(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M_, int N_){ + for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < M_; r += (long)gridDim.x * blockDim.x){ + const __nv_bfloat16* xr = x + r * (long)N_; + float amax = 0.f; + for(int j = 0; j < N_; j++) amax = fmaxf(amax, fabsf(__bfloat162float(xr[j]))); + float s = fmaxf(amax, 1e-12f) / FP8_MAX; + scale[r] = s; + __nv_fp8_e4m3* qr = q + r * (long)N_; + for(int j = 0; j < N_; j++) qr[j] = __nv_fp8_e4m3(__bfloat162float(xr[j]) / s); + } +} + +// ---- comparison --------------------------------------------------------------------------------- +__global__ void cmp_kernel(const __nv_fp8_e4m3* a, const float* sa, const __nv_fp8_e4m3* b, + const float* sb, long n, int N_, double* acc){ + __shared__ double sn[256], sd[256]; + double num = 0.0, den = 0.0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + int row = (int)(i / N_); + double va = (double)__half2float(__nv_cvt_fp8_to_halfraw(a[i].__x, __NV_E4M3)) * sa[row]; + double vb = (double)__half2float(__nv_cvt_fp8_to_halfraw(b[i].__x, __NV_E4M3)) * sb[row]; + num += (va - vb) * (va - vb); + den += vb * vb; + } + sn[threadIdx.x] = num; sd[threadIdx.x] = den; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ + if(threadIdx.x < o){ sn[threadIdx.x] += sn[threadIdx.x + o]; sd[threadIdx.x] += sd[threadIdx.x + o]; } + __syncthreads(); + } + if(threadIdx.x == 0){ atomicAdd(acc, sn[0]); atomicAdd(acc + 1, sd[0]); } +} +__global__ void cmp_scale(const float* a, const float* b, int m, float* worst){ + for(int i = blockIdx.x * blockDim.x + threadIdx.x; i < m; i += gridDim.x * blockDim.x){ + float e = fabsf(a[i] - b[i]) / fmaxf(fabsf(b[i]), 1e-30f); + atomicMax((int*)worst, __float_as_int(e)); // all values are >= 0 + } +} + +typedef void(*Fn)(const __nv_bfloat16*, __nv_fp8_e4m3*, float*); +static float time_ms(Fn run, const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s, int warm, int iters){ + cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b)); + for(int i = 0; i < warm; i++) run(x, q, s); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(a)); run(x, q, s); CK(cudaEventRecord(b)); + CK(cudaEventSynchronize(b)); float ms; CK(cudaEventElapsedTime(&ms, a, b)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s){ naive_kernel<<<256, 128>>>(x, q, s, M, N); } +static void run_agent(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s){ fp8_row_quant(x, q, s, M, N); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)M * N; + __nv_bfloat16* x; __nv_fp8_e4m3 *qr, *qa; float *sr, *sa; double* acc; float* worst; + CK(cudaMalloc(&x, n * 2)); CK(cudaMalloc(&qr, n)); CK(cudaMalloc(&qa, n)); + CK(cudaMalloc(&sr, M * 4)); CK(cudaMalloc(&sa, M * 4)); + CK(cudaMalloc(&acc, 16)); CK(cudaMalloc(&worst, 4)); + CK(cudaMemset(acc, 0, 16)); CK(cudaMemset(worst, 0, 4)); + CK(cudaMemset(qa, 0, n)); CK(cudaMemset(sa, 0, M * 4)); + gen_kernel<<<1024, 256>>>(x, n, N, seed); + CK(cudaDeviceSynchronize()); + + run_naive(x, qr, sr); CK(cudaDeviceSynchronize()); + run_agent(x, qa, sa); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(qa, sa, qr, sr, n, N, acc); + cmp_scale<<<64, 256>>>(sa, sr, M, worst); + CK(cudaDeviceSynchronize()); + double h[2]; float ws; + CK(cudaMemcpy(h, acc, 16, cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(&ws, worst, 4, cudaMemcpyDeviceToHost)); + double rel = sqrt(h[0] / (h[1] + 1e-30)); + + float tn = time_ms(run_naive, x, qr, sr, 1, 5); + float ta = time_ms(run_agent, x, qa, sa, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (rel < TOL_DEQ) && (ws < TOL_SCALE); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("rel_deq=%.3e scale_err=%.3e | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | " + "correct=%d fast=%d -> reward=%.1f\n", rel, ws, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"rel_deq\": %.3e, " + "\"scale_err\": %.3e, \"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, rel, ws, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/restrict-network.sh b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..10f759d82f01fe8868baa01a7816d23deea150c1 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone +# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is +# pre-installed (harbor's patched installer skips the network install when it is already present), so no +# package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they +# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/environment/solution.cu b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/solution.cu new file mode 100644 index 0000000000000000000000000000000000000000..93ab45312a25f49db5675b438256799b3ee84bf6 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/environment/solution.cu @@ -0,0 +1,20 @@ +// solution.cu — implement the per-row FP8 quantisation described in the instruction. +// scale[m] = max( max_n |x[m,n]| , 1e-12f ) / 448.0f +// q[m,n] = fp8_e4m3( x[m,n] / scale[m] ) round-to-nearest-even, saturating +// x[M,N] is bfloat16 row-major; q[M,N] is float8_e4m3 row-major; scale[M] is float32. +// M = 32768, N = 16384 (fixed). Reductions and the division must be done in fp32. +// This stub writes zeros (it compiles and runs, but is incorrect — reward 0). +#include +#include +#include + +__global__ void stub_k(__nv_fp8_e4m3* q, float* s, long n, int m){ + long i = (long)blockIdx.x * blockDim.x + threadIdx.x; + if(i < n) q[i] = __nv_fp8_e4m3(0.f); + if(i < m) s[i] = 1.f; +} + +void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M, int N){ + long n = (long)M * N; + stub_k<<<(n + 255) / 256, 256>>>(q, scale, n, M); +} diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/instruction.md b/tasks/raw-cuda/cuda-fp8-cast-pack/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e89bfb721d2d487ee3295e5346d1f9c8e590efb --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/instruction.md @@ -0,0 +1,61 @@ +# Write a fast CUDA kernel for per-token FP8 activation quantisation + +Implement a high-performance CUDA kernel in `/app/solution.cu` that quantises a `bfloat16` activation matrix +to **float8_e4m3** with one scale per row — the step every FP8-served transformer runs in front of every GEMM. + +Input: `x` of shape `[M, N]` (`__nv_bfloat16`, row-major). Outputs: `q` of shape `[M, N]` (`__nv_fp8_e4m3`, +row-major) and `scale` of shape `[M]` (`float`). For each row `m`: + +``` +amax = max over n of |x[m, n]| # computed in fp32 +scale[m] = max(amax, 1e-12f) / 448.0f # 448 = max finite e4m3 magnitude +q[m, n] = fp8_e4m3( x[m, n] / scale[m] ) # round-to-nearest-even, saturating +``` + +so that `q[m,n] * scale[m]` reconstructs `x[m,n]` to FP8 accuracy. The sizes are fixed: +**M = 32768, N = 16384** — 1.07 GB in, 537 MB + 128 KB out. + +The function signature (fixed) is in `/app/solution.cu`: +```cpp +void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M, int N); +``` + +## How success is decided + +The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and +checks: +1. **Correctness** — every `scale[m]` matches the reference to `1e-6` relative (the absmax is an exact + reduction, so a correct kernel matches it essentially exactly), and the dequantised values `q*scale` match + to `5e-3` relative Frobenius error. That tolerance absorbs the odd 1-ulp code flip — multiplying by + `1/scale` instead of dividing by `scale` measures `2e-3` and passes — but not a wrong rounding rule: + truncating instead of rounding to nearest scores about `4e-2`. +2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event + timed, warmup + median; the exact bar is printed when you build). + +Both must pass for reward 1.0. + +## Notes + +- This is a **pure bandwidth** problem: 1.07 GB has to come in and 537 MB has to go out, and the arithmetic + is one `fabsf`, one multiply and one conversion per element. Work out the roofline from the bandwidth you + measure (a large device-to-device copy is a good yardstick — do not trust a datasheet number), and treat + anything below it as a bug in your memory access pattern. +- The reference the bar is measured against is **one thread per row**, walking the row twice. Every element + it touches is uncoalesced, which is exactly the trap: the fix is to give each row a *block* (or a warp) so + that consecutive lanes read consecutive addresses. +- The scale for a row is not known until the whole row has been seen, so the obvious structure is two passes. + A row is `N * 2 = 32 KB`, which is small enough that it does **not** have to be re-read from HBM — think + about where you can keep it between the two passes, and how many rows a block should own. +- Access width matters on both sides: `x` is 2 bytes/element and `q` is 1, so a 128-bit load covers 8 inputs + while a 128-bit store covers 16 outputs. Getting the store side wrong is the most common way to leave + bandwidth on the table. `__nv_cvt_float2_to_fp8x2` converts two values per instruction. +- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer** + (`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA), and the profilers **`ncu`** and **`nsys`** + (use them — `ncu` will tell you your achieved DRAM throughput directly). There is **no PyTorch and no + Triton**; this is a pure CUDA task. +- Query the device you actually get with `cudaGetDeviceProperties` (SM count, shared memory per block, L2 + size) and size your launch from that rather than from constants. +- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader + uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how + you are measured; you only edit `solution.cu`. +- **No internet access.** diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/solution/solution.oracle.cu b/tasks/raw-cuda/cuda-fp8-cast-pack/solution/solution.oracle.cu new file mode 100644 index 0000000000000000000000000000000000000000..e2bd7bf50ae7a85191fbe68feb0c2057ce64a80c --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/solution/solution.oracle.cu @@ -0,0 +1,97 @@ +// Oracle: one block per row, the whole row held in registers, 128-bit loads and 128-bit FP8 stores. +// scale[m] = max(max_n |x[m,n]|, 1e-12) / 448 ; q[m,n] = fp8_e4m3(x[m,n] / scale[m]) +// The row is read EXACTLY ONCE: each thread keeps its slice in registers across the block-wide +// absmax reduction, so the quantisation pass needs no second trip to HBM. +#include +#include +#include + +#define FP8_MAX 448.0f +#define THREADS 512 +#define VPT 32 // elements per thread; THREADS*VPT = 16384 = N + +__device__ __forceinline__ float blockmax(float v){ + __shared__ float s[THREADS / 32]; + for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + if((threadIdx.x & 31) == 0) s[threadIdx.x >> 5] = v; + __syncthreads(); + v = (threadIdx.x < THREADS / 32) ? s[threadIdx.x] : 0.f; + if(threadIdx.x < 32) for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + __shared__ float out; + if(threadIdx.x == 0) out = v; + __syncthreads(); + return out; +} + +__global__ __launch_bounds__(THREADS) void quant_fast(const __nv_bfloat16* __restrict__ x, + __nv_fp8_e4m3* __restrict__ q, + float* __restrict__ scale, int N){ + const long row = blockIdx.x; + const uint4* xr = reinterpret_cast(x + row * (long)N); + uint4 reg[VPT / 8]; + float amax = 0.f; + // each thread owns 16 CONSECUTIVE elements per pair (two adjacent 128-bit loads), so that one + // 128-bit FP8 store later covers exactly those 16 elements + #pragma unroll + for(int c = 0; c < VPT / 16; c++){ + #pragma unroll + for(int h2 = 0; h2 < 2; h2++){ + reg[2 * c + h2] = xr[2 * (threadIdx.x + c * THREADS) + h2]; + const __nv_bfloat16* h = reinterpret_cast(®[2 * c + h2]); + #pragma unroll + for(int j = 0; j < 8; j++) amax = fmaxf(amax, fabsf(__bfloat162float(h[j]))); + } + } + float s = fmaxf(blockmax(amax), 1e-12f) / FP8_MAX; + if(threadIdx.x == 0) scale[row] = s; + float inv = 1.0f / s; + + uint4* qr = reinterpret_cast(q + row * (long)N); + uint4 outv[VPT / 16]; + #pragma unroll + for(int c = 0; c < VPT / 16; c++){ + unsigned w[4]; + #pragma unroll + for(int p = 0; p < 4; p++){ + const __nv_bfloat16* h = reinterpret_cast(®[c * 2 + (p >> 1)]); + int b = (p & 1) * 4; + float2 a0 = make_float2(__bfloat162float(h[b + 0]) * inv, __bfloat162float(h[b + 1]) * inv); + float2 a1 = make_float2(__bfloat162float(h[b + 2]) * inv, __bfloat162float(h[b + 3]) * inv); + unsigned lo = __nv_cvt_float2_to_fp8x2(a0, __NV_SATFINITE, __NV_E4M3); + unsigned hi = __nv_cvt_float2_to_fp8x2(a1, __NV_SATFINITE, __NV_E4M3); + w[p] = (lo & 0xffffu) | (hi << 16); + } + outv[c] = make_uint4(w[0], w[1], w[2], w[3]); + } + // the 128-bit store covers 16 consecutive elements, i.e. reg[2c] and reg[2c+1] + #pragma unroll + for(int c = 0; c < VPT / 16; c++) qr[threadIdx.x + c * THREADS] = outv[c]; +} + +// generic fallback (correct for any N, not tuned) +__global__ void quant_gen(const __nv_bfloat16* __restrict__ x, __nv_fp8_e4m3* __restrict__ q, + float* __restrict__ scale, int N){ + long row = blockIdx.x; + const __nv_bfloat16* xr = x + row * (long)N; + float amax = 0.f; + for(int j = threadIdx.x; j < N; j += blockDim.x) amax = fmaxf(amax, fabsf(__bfloat162float(xr[j]))); + __shared__ float sh[32]; + for(int o = 16; o; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffff, amax, o)); + if((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = amax; + __syncthreads(); + if(threadIdx.x < 32){ + float v = (threadIdx.x < (blockDim.x + 31) / 32) ? sh[threadIdx.x] : 0.f; + for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + if(threadIdx.x == 0) sh[0] = v; + } + __syncthreads(); + float s = fmaxf(sh[0], 1e-12f) / FP8_MAX; + if(threadIdx.x == 0) scale[row] = s; + __nv_fp8_e4m3* qr = q + row * (long)N; + for(int j = threadIdx.x; j < N; j += blockDim.x) qr[j] = __nv_fp8_e4m3(__bfloat162float(xr[j]) / s); +} + +void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M, int N){ + if(N == THREADS * VPT) quant_fast<<>>(x, q, scale, N); + else quant_gen<<>>(x, q, scale, N); +} diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/solution/solve.sh b/tasks/raw-cuda/cuda-fp8-cast-pack/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e1f28ab57667fb2693ecdd646b1e1c67f2e11a62 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/solution/solve.sh @@ -0,0 +1,103 @@ +#!/bin/bash +# Oracle: restore the reference fast kernel. +set -e +cat > /app/solution.cu <<'ORACLE_CU_EOF' +// Oracle: one block per row, the whole row held in registers, 128-bit loads and 128-bit FP8 stores. +// scale[m] = max(max_n |x[m,n]|, 1e-12) / 448 ; q[m,n] = fp8_e4m3(x[m,n] / scale[m]) +// The row is read EXACTLY ONCE: each thread keeps its slice in registers across the block-wide +// absmax reduction, so the quantisation pass needs no second trip to HBM. +#include +#include +#include + +#define FP8_MAX 448.0f +#define THREADS 512 +#define VPT 32 // elements per thread; THREADS*VPT = 16384 = N + +__device__ __forceinline__ float blockmax(float v){ + __shared__ float s[THREADS / 32]; + for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + if((threadIdx.x & 31) == 0) s[threadIdx.x >> 5] = v; + __syncthreads(); + v = (threadIdx.x < THREADS / 32) ? s[threadIdx.x] : 0.f; + if(threadIdx.x < 32) for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + __shared__ float out; + if(threadIdx.x == 0) out = v; + __syncthreads(); + return out; +} + +__global__ __launch_bounds__(THREADS) void quant_fast(const __nv_bfloat16* __restrict__ x, + __nv_fp8_e4m3* __restrict__ q, + float* __restrict__ scale, int N){ + const long row = blockIdx.x; + const uint4* xr = reinterpret_cast(x + row * (long)N); + uint4 reg[VPT / 8]; + float amax = 0.f; + // each thread owns 16 CONSECUTIVE elements per pair (two adjacent 128-bit loads), so that one + // 128-bit FP8 store later covers exactly those 16 elements + #pragma unroll + for(int c = 0; c < VPT / 16; c++){ + #pragma unroll + for(int h2 = 0; h2 < 2; h2++){ + reg[2 * c + h2] = xr[2 * (threadIdx.x + c * THREADS) + h2]; + const __nv_bfloat16* h = reinterpret_cast(®[2 * c + h2]); + #pragma unroll + for(int j = 0; j < 8; j++) amax = fmaxf(amax, fabsf(__bfloat162float(h[j]))); + } + } + float s = fmaxf(blockmax(amax), 1e-12f) / FP8_MAX; + if(threadIdx.x == 0) scale[row] = s; + float inv = 1.0f / s; + + uint4* qr = reinterpret_cast(q + row * (long)N); + uint4 outv[VPT / 16]; + #pragma unroll + for(int c = 0; c < VPT / 16; c++){ + unsigned w[4]; + #pragma unroll + for(int p = 0; p < 4; p++){ + const __nv_bfloat16* h = reinterpret_cast(®[c * 2 + (p >> 1)]); + int b = (p & 1) * 4; + float2 a0 = make_float2(__bfloat162float(h[b + 0]) * inv, __bfloat162float(h[b + 1]) * inv); + float2 a1 = make_float2(__bfloat162float(h[b + 2]) * inv, __bfloat162float(h[b + 3]) * inv); + unsigned lo = __nv_cvt_float2_to_fp8x2(a0, __NV_SATFINITE, __NV_E4M3); + unsigned hi = __nv_cvt_float2_to_fp8x2(a1, __NV_SATFINITE, __NV_E4M3); + w[p] = (lo & 0xffffu) | (hi << 16); + } + outv[c] = make_uint4(w[0], w[1], w[2], w[3]); + } + // the 128-bit store covers 16 consecutive elements, i.e. reg[2c] and reg[2c+1] + #pragma unroll + for(int c = 0; c < VPT / 16; c++) qr[threadIdx.x + c * THREADS] = outv[c]; +} + +// generic fallback (correct for any N, not tuned) +__global__ void quant_gen(const __nv_bfloat16* __restrict__ x, __nv_fp8_e4m3* __restrict__ q, + float* __restrict__ scale, int N){ + long row = blockIdx.x; + const __nv_bfloat16* xr = x + row * (long)N; + float amax = 0.f; + for(int j = threadIdx.x; j < N; j += blockDim.x) amax = fmaxf(amax, fabsf(__bfloat162float(xr[j]))); + __shared__ float sh[32]; + for(int o = 16; o; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffff, amax, o)); + if((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = amax; + __syncthreads(); + if(threadIdx.x < 32){ + float v = (threadIdx.x < (blockDim.x + 31) / 32) ? sh[threadIdx.x] : 0.f; + for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + if(threadIdx.x == 0) sh[0] = v; + } + __syncthreads(); + float s = fmaxf(sh[0], 1e-12f) / FP8_MAX; + if(threadIdx.x == 0) scale[row] = s; + __nv_fp8_e4m3* qr = q + row * (long)N; + for(int j = threadIdx.x; j < N; j += blockDim.x) qr[j] = __nv_fp8_e4m3(__bfloat162float(xr[j]) / s); +} + +void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M, int N){ + if(N == THREADS * VPT) quant_fast<<>>(x, q, scale, N); + else quant_gen<<>>(x, q, scale, N); +} +ORACLE_CU_EOF +echo restored diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/task.toml b/tasks/raw-cuda/cuda-fp8-cast-pack/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8728d2e595bd405f30b417d5da6f57a335bee090 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/task.toml @@ -0,0 +1,36 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/cuda-fp8-cast-pack" +description = "Write a fast hand-written CUDA kernel for per-token FP8 (e4m3) activation quantisation: per-row absmax, scale = absmax/448, cast-and-pack a bf16 [32768, 16384] matrix to float8_e4m3 plus one fp32 scale per row, beating a one-thread-per-row reference by a calibrated margin. Pure bandwidth: 1.07 GB in, 537 MB out, with a row-wide reduction between the read and the write and a 2-byte-in / 1-byte-out access-width mismatch. Hand-written CUDA only (CUTLASS/flashinfer/CUB); no PyTorch/Triton; ncu/nsys available." +authors = [] +keywords = [ "mle", "kernel-generation", "cuda", "fp8", "quantization", "bandwidth", "performance", "gpu",] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "cuda", "gpu", "performance", "real-world",] + +[verifier] +timeout_sec = 600.0 + +[agent] +timeout_sec = 14400.0 + +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 32768 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/tests/harness.cu b/tasks/raw-cuda/cuda-fp8-cast-pack/tests/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..ad03b557db7d4a2b785794c0b825594b7c252827 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/tests/harness.cu @@ -0,0 +1,145 @@ +// Grading harness for cuda-fp8-cast-pack. +// Per-row (per-token) FP8 e4m3 activation quantisation: +// scale[m] = max( max_n |x[m,n]| , 1e-12f ) / 448.0f +// q[m,n] = fp8_e4m3( x[m,n] / scale[m] ) (round-to-nearest-even, saturating) +// x[M,N] bfloat16 row-major in; q[M,N] fp8_e4m3 + scale[M] float32 out. +// Inputs are generated ON DEVICE from the seed (deterministic, and fast enough to iterate on). +// The naive reference is one thread per row, two sequential passes over the row. +// Correctness: scales must agree to 1e-6 relative, and the DEQUANTISED values (q*scale) to 5e-3 +// relative Frobenius -- which tolerates the odd 1-ulp code flip but not a wrong rounding rule. +#include +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int M = 32768, N = 16384; // 5.4e8 elements: 1.07 GB in, 537 MB + 128 KB out +static const float FP8_MAX = 448.0f; +static const float TOL_DEQ = 5e-3f; // relative Frobenius on dequantised values +static const float TOL_SCALE = 1e-6f; // relative, per row +#ifndef R_BAR +#define R_BAR 20.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M_, int N_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +// gaussian-ish (Box-Muller) times a per-row magnitude that spans ~30x, so row scales really differ +__global__ void gen_kernel(__nv_bfloat16* x, long n, int N_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u); + float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2); + int row = (int)(i / N_); + float rs = expf(unif(mix(row * 9781u + seed)) * 3.4f - 1.7f); + x[i] = __float2bfloat16(g * rs); + } +} + +// ---- naive reference: one thread per row, two sequential passes ---------------------------------- +__global__ void naive_kernel(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M_, int N_){ + for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < M_; r += (long)gridDim.x * blockDim.x){ + const __nv_bfloat16* xr = x + r * (long)N_; + float amax = 0.f; + for(int j = 0; j < N_; j++) amax = fmaxf(amax, fabsf(__bfloat162float(xr[j]))); + float s = fmaxf(amax, 1e-12f) / FP8_MAX; + scale[r] = s; + __nv_fp8_e4m3* qr = q + r * (long)N_; + for(int j = 0; j < N_; j++) qr[j] = __nv_fp8_e4m3(__bfloat162float(xr[j]) / s); + } +} + +// ---- comparison --------------------------------------------------------------------------------- +__global__ void cmp_kernel(const __nv_fp8_e4m3* a, const float* sa, const __nv_fp8_e4m3* b, + const float* sb, long n, int N_, double* acc){ + __shared__ double sn[256], sd[256]; + double num = 0.0, den = 0.0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + int row = (int)(i / N_); + double va = (double)__half2float(__nv_cvt_fp8_to_halfraw(a[i].__x, __NV_E4M3)) * sa[row]; + double vb = (double)__half2float(__nv_cvt_fp8_to_halfraw(b[i].__x, __NV_E4M3)) * sb[row]; + num += (va - vb) * (va - vb); + den += vb * vb; + } + sn[threadIdx.x] = num; sd[threadIdx.x] = den; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ + if(threadIdx.x < o){ sn[threadIdx.x] += sn[threadIdx.x + o]; sd[threadIdx.x] += sd[threadIdx.x + o]; } + __syncthreads(); + } + if(threadIdx.x == 0){ atomicAdd(acc, sn[0]); atomicAdd(acc + 1, sd[0]); } +} +__global__ void cmp_scale(const float* a, const float* b, int m, float* worst){ + for(int i = blockIdx.x * blockDim.x + threadIdx.x; i < m; i += gridDim.x * blockDim.x){ + float e = fabsf(a[i] - b[i]) / fmaxf(fabsf(b[i]), 1e-30f); + atomicMax((int*)worst, __float_as_int(e)); // all values are >= 0 + } +} + +typedef void(*Fn)(const __nv_bfloat16*, __nv_fp8_e4m3*, float*); +static float time_ms(Fn run, const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s, int warm, int iters){ + cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b)); + for(int i = 0; i < warm; i++) run(x, q, s); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(a)); run(x, q, s); CK(cudaEventRecord(b)); + CK(cudaEventSynchronize(b)); float ms; CK(cudaEventElapsedTime(&ms, a, b)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s){ naive_kernel<<<256, 128>>>(x, q, s, M, N); } +static void run_agent(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s){ fp8_row_quant(x, q, s, M, N); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)M * N; + __nv_bfloat16* x; __nv_fp8_e4m3 *qr, *qa; float *sr, *sa; double* acc; float* worst; + CK(cudaMalloc(&x, n * 2)); CK(cudaMalloc(&qr, n)); CK(cudaMalloc(&qa, n)); + CK(cudaMalloc(&sr, M * 4)); CK(cudaMalloc(&sa, M * 4)); + CK(cudaMalloc(&acc, 16)); CK(cudaMalloc(&worst, 4)); + CK(cudaMemset(acc, 0, 16)); CK(cudaMemset(worst, 0, 4)); + CK(cudaMemset(qa, 0, n)); CK(cudaMemset(sa, 0, M * 4)); + gen_kernel<<<1024, 256>>>(x, n, N, seed); + CK(cudaDeviceSynchronize()); + + run_naive(x, qr, sr); CK(cudaDeviceSynchronize()); + run_agent(x, qa, sa); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(qa, sa, qr, sr, n, N, acc); + cmp_scale<<<64, 256>>>(sa, sr, M, worst); + CK(cudaDeviceSynchronize()); + double h[2]; float ws; + CK(cudaMemcpy(h, acc, 16, cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(&ws, worst, 4, cudaMemcpyDeviceToHost)); + double rel = sqrt(h[0] / (h[1] + 1e-30)); + + float tn = time_ms(run_naive, x, qr, sr, 1, 5); + float ta = time_ms(run_agent, x, qa, sa, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (rel < TOL_DEQ) && (ws < TOL_SCALE); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("rel_deq=%.3e scale_err=%.3e | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | " + "correct=%d fast=%d -> reward=%.1f\n", rel, ws, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"rel_deq\": %.3e, " + "\"scale_err\": %.3e, \"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, rel, ws, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-fp8-cast-pack/tests/test.sh b/tasks/raw-cuda/cuda-fp8-cast-pack/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..18efdf3a3a726f0f80160d553ce52bc77c051af4 --- /dev/null +++ b/tasks/raw-cuda/cuda-fp8-cast-pack/tests/test.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Verifier: compile the FRESH harness + the agent's solution, grade with a random seed. +set -uo pipefail +mkdir -p /logs/verifier +SEED=$(( (RANDOM << 15) ^ RANDOM )) +nvcc -O3 -arch=native /tests/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /tmp/grade 2>/tmp/nvcc.log +if [ ! -x /tmp/grade ]; then + echo "COMPILE FAILED:"; tail -20 /tmp/nvcc.log + echo "0.0" > /logs/verifier/reward.txt + echo '{"reward": 0.0, "error": "compile_failed"}' > /logs/verifier/reward.json + exit 0 +fi +/tmp/grade "$SEED" # the harness writes /logs/verifier/reward.{txt,json} +cat /logs/verifier/reward.json 2>/dev/null || true diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/CLAUDE.md b/tasks/raw-cuda/cuda-histogram-atomics/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/Dockerfile b/tasks/raw-cuda/cuda-histogram-atomics/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b3ade19084ebc72f9add0d442d555f0c8b444f7 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/Dockerfile @@ -0,0 +1,34 @@ +# CUDA kernel-generation task: write a fast MoE expert-load histogram kernel in solution.cu. +# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton. +FROM nvidia/cuda:12.8.1-devel-ubuntu24.04 + +# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps. +RUN apt-get update && apt-get install -y --no-install-recommends \ + git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \ + rm -rf /var/lib/apt/lists/* + +# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled). +# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed, +# and dropping it keeps the environment free of any torch/triton files. +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \ + git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \ + mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi + +# Pre-bake the agent (the offline firewall blocks installing it at run time). +RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent +ENV PATH=/root/.local/bin:$PATH + +# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper. +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ +COPY solution.cu /app/solution.cu +COPY harness.cu /app/harness.cu +COPY build.sh /app/build.sh +RUN chmod +x /app/build.sh + +# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched). +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh + +# Strip apt sources so harbor's base apt-setup is a no-op under the firewall. +RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/* diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/PROCESS_MANAGEMENT.md b/tasks/raw-cuda/cuda-histogram-atomics/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/build.sh b/tasks/raw-cuda/cuda-histogram-atomics/environment/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..357f55e23f8935d722b8d834360ae4e1fe68d3cc --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Compile your solution against the harness and run one seed (the grader uses a different seed). +set -e +nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run +/app/run 0 diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/docker-compose.yaml b/tasks/raw-cuda/cuda-histogram-atomics/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b626bc85e10f49e564a9bb840c97b1fc5d66561f --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/docker-compose.yaml @@ -0,0 +1,17 @@ +# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose. +# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked). +# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has +# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it. +services: + main: + cap_add: + - NET_ADMIN + - SYS_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/harness.cu b/tasks/raw-cuda/cuda-histogram-atomics/environment/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..1f78d69f1fac3df939ecaedf0f88173cf7a3b7f6 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/harness.cu @@ -0,0 +1,104 @@ +// Grading harness for cuda-histogram-atomics. +// counts[e] = number of i in [0, N) with expert[i] == e (E bins, exact integer result) +// expert[N] int32 in, counts[E] int32 out (zero-initialised by the caller). +// This is the expert-load histogram of an MoE dispatch: N routed (token, slot) assignments over +// E = 256 experts, with a realistically skewed load -- the hottest expert takes ~3.5% of ALL +// assignments, so a global-atomic histogram serialises hard on a handful of addresses. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one global atomicAdd per element. +// Correctness is EXACT: every bin must match. +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const long NTOK = 536870912L; // 2^29 routed assignments = 2.15 GB of int32 +static const int V = 256; // experts (DeepSeek-V3 scale): 256 bins = 1 KB of int32 +#ifndef R_BAR +#define R_BAR 180.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void expert_histogram(const int* expert, int* counts, long N, int E_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(int* t, long n, int V_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u = unif(s); + int id = (int)(V_ * powf(u, 2.5f)); // skewed load: expert 0 takes ~3.5% of all tokens + t[i] = id < V_ ? id : V_ - 1; + } +} + +// ---- naive reference: one global atomic per element ---------------------------------------------- +__global__ void naive_kernel(const int* t, int* counts, long n){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + atomicAdd(&counts[t[i]], 1); +} + +// ---- comparison: exact --------------------------------------------------------------------------- +__global__ void cmp_kernel(const int* a, const int* b, int v, int* bad){ + for(int i = blockIdx.x * blockDim.x + threadIdx.x; i < v; i += gridDim.x * blockDim.x) + if(a[i] != b[i]) atomicAdd(bad, 1); +} + +typedef void(*Fn)(const int*, int*); +static float time_ms(Fn run, const int* t, int* c, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++){ CK(cudaMemset(c, 0, V * 4)); run(t, c); } + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaMemset(c, 0, V * 4)); // the output buffer is zeroed by the CALLER + CK(cudaEventRecord(ev0)); run(t, c); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const int* t, int* c){ naive_kernel<<<2048, 256>>>(t, c, NTOK); } +static void run_agent(const int* t, int* c){ expert_histogram(t, c, NTOK, V); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + int *tok, *cref, *cag, *bad; + CK(cudaMalloc(&tok, NTOK * 4)); CK(cudaMalloc(&cref, V * 4)); CK(cudaMalloc(&cag, V * 4)); + CK(cudaMalloc(&bad, 4)); CK(cudaMemset(bad, 0, 4)); + CK(cudaMemset(cref, 0, V * 4)); CK(cudaMemset(cag, 0, V * 4)); + gen_kernel<<<1024, 256>>>(tok, NTOK, V, seed); + CK(cudaDeviceSynchronize()); + + run_naive(tok, cref); CK(cudaDeviceSynchronize()); + run_agent(tok, cag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<64, 256>>>(cag, cref, V, bad); + CK(cudaDeviceSynchronize()); + int hb; CK(cudaMemcpy(&hb, bad, 4, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, tok, cref, 1, 5); + float ta = time_ms(run_agent, tok, cag, 5, 20); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hb == 0); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("wrong_experts=%d/%d | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d " + "-> reward=%.1f\n", hb, V, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"wrong_experts\": %d, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hb, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/restrict-network.sh b/tasks/raw-cuda/cuda-histogram-atomics/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..10f759d82f01fe8868baa01a7816d23deea150c1 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone +# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is +# pre-installed (harbor's patched installer skips the network install when it is already present), so no +# package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they +# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/raw-cuda/cuda-histogram-atomics/environment/solution.cu b/tasks/raw-cuda/cuda-histogram-atomics/environment/solution.cu new file mode 100644 index 0000000000000000000000000000000000000000..d68fb6c6cad5b8cdd09888e7fcc91cb094b67623 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/environment/solution.cu @@ -0,0 +1,15 @@ +// solution.cu — implement the MoE expert-load histogram described in the instruction. +// counts[e] = number of i in [0, N) with expert[i] == e +// expert[N] is int32 (values in [0, E)); counts[E] is int32 and is ZEROED BY THE CALLER before +// every call, so accumulate into it. N = 536870912, E = 256 (fixed). The result must be EXACT. +// This stub leaves the counts at zero (it compiles and runs, but is incorrect — reward 0). +#include + +__global__ void stub_k(int* counts, int E){ + int i = blockIdx.x * blockDim.x + threadIdx.x; + if(i < E) counts[i] = 0; +} + +void expert_histogram(const int* expert, int* counts, long N, int E){ + stub_k<<<(E + 255) / 256, 256>>>(counts, E); +} diff --git a/tasks/raw-cuda/cuda-histogram-atomics/instruction.md b/tasks/raw-cuda/cuda-histogram-atomics/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dfbfc16fa91096076c78c70966a0531926bb7b29 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/instruction.md @@ -0,0 +1,61 @@ +# Write a fast CUDA kernel for an MoE expert-load histogram + +Implement a high-performance CUDA kernel in `/app/solution.cu` that counts how many routed assignments land +on each expert — the load histogram an MoE dispatch builds before it can size its per-expert buffers. + +Input: `expert` of shape `[N]` (`int`, values in `[0, E)`), one entry per routed `(token, slot)` assignment. +Output: `counts` of shape `[E]` (`int`). For every expert `e`: + +``` +counts[e] = number of i in [0, N) with expert[i] == e +``` + +`counts` is **zeroed by the caller before every call**, so accumulate into it. The sizes are fixed: +**N = 536870912 (2^29) assignments = 2.15 GB, E = 256 experts.** + +The expert loads are **skewed**, the way a real router's are: the hottest expert takes about 3.5% of all +assignments and the top handful take a large share between them. + +The function signature (fixed) is in `/app/solution.cu`: +```cpp +void expert_histogram(const int* expert, int* counts, long N, int E); +``` + +## How success is decided + +The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and +checks: +1. **Correctness — exact.** Every one of the 256 counts must match the reference exactly. There is no + tolerance; this is an integer result. +2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event + timed, warmup + median; the exact bar is printed when you build). + +Both must pass for reward 1.0. + +## Notes + +- The reference the bar is measured against is the obvious one: **one `atomicAdd` into global memory per + element**. With 2^29 elements and a skewed distribution over only 256 addresses, that is 500 million + serialised read-modify-writes on a handful of cache lines, and it is roughly **300x** off the roofline. + The bar is set well above what fixing *only* the access width can achieve — the atomics themselves have to + go. +- What the problem actually costs: 2.15 GB has to be read, once. Nothing else is fundamental. Work out that + roofline from the bandwidth you measure (a large device-to-device copy is a good yardstick) and treat the + gap as contention you have not removed yet. +- The direction is **privatisation**: 256 bins is 1 KB, which fits many times over in one block's shared + memory, so each block can accumulate its own copy and merge it into the global counts once at the end — + turning 500 million global atomics into a few thousand. How many private copies to keep, how to index + them, and how to lay them out so that the lanes of a warp do not queue behind each other are yours to + work out; measure, do not guess, because the hardware does more for you here than you might expect. +- The read side still matters: `int` is 4 bytes, so a 128-bit load brings in 4 ids at once. Size the grid + from the SM count you query with `cudaGetDeviceProperties`, and keep enough blocks in flight to cover the + memory latency. +- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer** + (`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA), warp intrinsics such as + `__match_any_sync`/`__ballot_sync`, and the profilers **`ncu`** and **`nsys`**. `ncu` reports both DRAM + throughput and shared-memory bank conflicts, which is exactly the pair of numbers to watch. There is **no + PyTorch and no Triton**; this is a pure CUDA task. +- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader + uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how + you are measured; you only edit `solution.cu`. +- **No internet access.** diff --git a/tasks/raw-cuda/cuda-histogram-atomics/solution/solution.oracle.cu b/tasks/raw-cuda/cuda-histogram-atomics/solution/solution.oracle.cu new file mode 100644 index 0000000000000000000000000000000000000000..fbcbd832f5a5fb541b936e6ab1b337548ceb0bf5 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/solution/solution.oracle.cu @@ -0,0 +1,47 @@ +// Oracle: per-block privatised histogram in shared memory, read with 128-bit loads. +// The 256 bins are 1 KB, so the private copy is replicated a few ways (and padded by one int so +// the replicas are bank-staggered) to spread the skew; on this class of hardware the shared-memory +// atomic unit already aggregates same-address atomics within a warp, so the decisive win is simply +// NOT touching global memory per element -- with privatisation the kernel is bandwidth-bound. +// The replicas are summed and merged into the global counts with one atomicAdd per expert per block. +#include + +#define NTHREAD 256 +#define REPL 8 +#define STRIDE 257 // 256 bins + 1 pad int, so replicas are bank-staggered + +extern __shared__ int smem[]; // REPL * STRIDE ints + +__global__ __launch_bounds__(NTHREAD) void hist_k(const int* __restrict__ t, int* __restrict__ counts, + long n, int E){ + for(int i = threadIdx.x; i < REPL * STRIDE; i += NTHREAD) smem[i] = 0; + __syncthreads(); + + int* mine = smem + (threadIdx.x % REPL) * STRIDE; + const int4* t4 = reinterpret_cast(t); + long n4 = n / 4; + for(long i = (long)blockIdx.x * NTHREAD + threadIdx.x; i < n4; i += (long)gridDim.x * NTHREAD){ + int4 v = t4[i]; + atomicAdd(&mine[v.x], 1); + atomicAdd(&mine[v.y], 1); + atomicAdd(&mine[v.z], 1); + atomicAdd(&mine[v.w], 1); + } + __syncthreads(); + for(int e = threadIdx.x; e < E; e += NTHREAD){ + int c = 0; + #pragma unroll + for(int r = 0; r < REPL; r++) c += smem[r * STRIDE + e]; + if(c) atomicAdd(&counts[e], c); + } +} + +void expert_histogram(const int* expert, int* counts, long N, int E){ + static int grid = 0; + if(!grid){ + int dev; cudaGetDevice(&dev); + int sm; cudaDeviceGetAttribute(&sm, cudaDevAttrMultiProcessorCount, dev); + grid = sm * 4; + } + hist_k<<>>(expert, counts, N, E); +} diff --git a/tasks/raw-cuda/cuda-histogram-atomics/solution/solve.sh b/tasks/raw-cuda/cuda-histogram-atomics/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a88dc26cfdf9662a240fd2a60f162a3fbccb212f --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/solution/solve.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# Oracle: restore the reference fast kernel. +set -e +cat > /app/solution.cu <<'ORACLE_CU_EOF' +// Oracle: per-block privatised histogram in shared memory, read with 128-bit loads. +// The 256 bins are 1 KB, so the private copy is replicated a few ways (and padded by one int so +// the replicas are bank-staggered) to spread the skew; on this class of hardware the shared-memory +// atomic unit already aggregates same-address atomics within a warp, so the decisive win is simply +// NOT touching global memory per element -- with privatisation the kernel is bandwidth-bound. +// The replicas are summed and merged into the global counts with one atomicAdd per expert per block. +#include + +#define NTHREAD 256 +#define REPL 8 +#define STRIDE 257 // 256 bins + 1 pad int, so replicas are bank-staggered + +extern __shared__ int smem[]; // REPL * STRIDE ints + +__global__ __launch_bounds__(NTHREAD) void hist_k(const int* __restrict__ t, int* __restrict__ counts, + long n, int E){ + for(int i = threadIdx.x; i < REPL * STRIDE; i += NTHREAD) smem[i] = 0; + __syncthreads(); + + int* mine = smem + (threadIdx.x % REPL) * STRIDE; + const int4* t4 = reinterpret_cast(t); + long n4 = n / 4; + for(long i = (long)blockIdx.x * NTHREAD + threadIdx.x; i < n4; i += (long)gridDim.x * NTHREAD){ + int4 v = t4[i]; + atomicAdd(&mine[v.x], 1); + atomicAdd(&mine[v.y], 1); + atomicAdd(&mine[v.z], 1); + atomicAdd(&mine[v.w], 1); + } + __syncthreads(); + for(int e = threadIdx.x; e < E; e += NTHREAD){ + int c = 0; + #pragma unroll + for(int r = 0; r < REPL; r++) c += smem[r * STRIDE + e]; + if(c) atomicAdd(&counts[e], c); + } +} + +void expert_histogram(const int* expert, int* counts, long N, int E){ + static int grid = 0; + if(!grid){ + int dev; cudaGetDevice(&dev); + int sm; cudaDeviceGetAttribute(&sm, cudaDevAttrMultiProcessorCount, dev); + grid = sm * 4; + } + hist_k<<>>(expert, counts, N, E); +} +ORACLE_CU_EOF +echo restored diff --git a/tasks/raw-cuda/cuda-histogram-atomics/task.toml b/tasks/raw-cuda/cuda-histogram-atomics/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..46f3d2e4cc5343a8f31dba6748d9eda53ed14067 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/task.toml @@ -0,0 +1,36 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/cuda-histogram-atomics" +description = "Write a fast hand-written CUDA kernel for an MoE expert-load histogram: count 2^29 skewed routed assignments into 256 expert bins (2.15 GB read), beating a global-atomic-per-element reference by a calibrated margin. The reference serialises 500M read-modify-writes on a handful of addresses; the fix is per-block privatisation in shared memory plus wide coalesced loads, which makes the kernel bandwidth-bound. Exact integer correctness. Hand-written CUDA only (CUTLASS/flashinfer/CUB, warp intrinsics); no PyTorch/Triton; ncu/nsys available." +authors = [] +keywords = [ "mle", "kernel-generation", "cuda", "histogram", "atomics", "moe", "shared-memory", "gpu",] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "cuda", "gpu", "performance", "real-world",] + +[verifier] +timeout_sec = 600.0 + +[agent] +timeout_sec = 14400.0 + +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 32768 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/raw-cuda/cuda-histogram-atomics/tests/harness.cu b/tasks/raw-cuda/cuda-histogram-atomics/tests/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..1f78d69f1fac3df939ecaedf0f88173cf7a3b7f6 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/tests/harness.cu @@ -0,0 +1,104 @@ +// Grading harness for cuda-histogram-atomics. +// counts[e] = number of i in [0, N) with expert[i] == e (E bins, exact integer result) +// expert[N] int32 in, counts[E] int32 out (zero-initialised by the caller). +// This is the expert-load histogram of an MoE dispatch: N routed (token, slot) assignments over +// E = 256 experts, with a realistically skewed load -- the hottest expert takes ~3.5% of ALL +// assignments, so a global-atomic histogram serialises hard on a handful of addresses. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one global atomicAdd per element. +// Correctness is EXACT: every bin must match. +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const long NTOK = 536870912L; // 2^29 routed assignments = 2.15 GB of int32 +static const int V = 256; // experts (DeepSeek-V3 scale): 256 bins = 1 KB of int32 +#ifndef R_BAR +#define R_BAR 180.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void expert_histogram(const int* expert, int* counts, long N, int E_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(int* t, long n, int V_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u = unif(s); + int id = (int)(V_ * powf(u, 2.5f)); // skewed load: expert 0 takes ~3.5% of all tokens + t[i] = id < V_ ? id : V_ - 1; + } +} + +// ---- naive reference: one global atomic per element ---------------------------------------------- +__global__ void naive_kernel(const int* t, int* counts, long n){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + atomicAdd(&counts[t[i]], 1); +} + +// ---- comparison: exact --------------------------------------------------------------------------- +__global__ void cmp_kernel(const int* a, const int* b, int v, int* bad){ + for(int i = blockIdx.x * blockDim.x + threadIdx.x; i < v; i += gridDim.x * blockDim.x) + if(a[i] != b[i]) atomicAdd(bad, 1); +} + +typedef void(*Fn)(const int*, int*); +static float time_ms(Fn run, const int* t, int* c, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++){ CK(cudaMemset(c, 0, V * 4)); run(t, c); } + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaMemset(c, 0, V * 4)); // the output buffer is zeroed by the CALLER + CK(cudaEventRecord(ev0)); run(t, c); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const int* t, int* c){ naive_kernel<<<2048, 256>>>(t, c, NTOK); } +static void run_agent(const int* t, int* c){ expert_histogram(t, c, NTOK, V); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + int *tok, *cref, *cag, *bad; + CK(cudaMalloc(&tok, NTOK * 4)); CK(cudaMalloc(&cref, V * 4)); CK(cudaMalloc(&cag, V * 4)); + CK(cudaMalloc(&bad, 4)); CK(cudaMemset(bad, 0, 4)); + CK(cudaMemset(cref, 0, V * 4)); CK(cudaMemset(cag, 0, V * 4)); + gen_kernel<<<1024, 256>>>(tok, NTOK, V, seed); + CK(cudaDeviceSynchronize()); + + run_naive(tok, cref); CK(cudaDeviceSynchronize()); + run_agent(tok, cag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<64, 256>>>(cag, cref, V, bad); + CK(cudaDeviceSynchronize()); + int hb; CK(cudaMemcpy(&hb, bad, 4, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, tok, cref, 1, 5); + float ta = time_ms(run_agent, tok, cag, 5, 20); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hb == 0); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("wrong_experts=%d/%d | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d " + "-> reward=%.1f\n", hb, V, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"wrong_experts\": %d, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hb, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-histogram-atomics/tests/test.sh b/tasks/raw-cuda/cuda-histogram-atomics/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..18efdf3a3a726f0f80160d553ce52bc77c051af4 --- /dev/null +++ b/tasks/raw-cuda/cuda-histogram-atomics/tests/test.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Verifier: compile the FRESH harness + the agent's solution, grade with a random seed. +set -uo pipefail +mkdir -p /logs/verifier +SEED=$(( (RANDOM << 15) ^ RANDOM )) +nvcc -O3 -arch=native /tests/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /tmp/grade 2>/tmp/nvcc.log +if [ ! -x /tmp/grade ]; then + echo "COMPILE FAILED:"; tail -20 /tmp/nvcc.log + echo "0.0" > /logs/verifier/reward.txt + echo '{"reward": 0.0, "error": "compile_failed"}' > /logs/verifier/reward.json + exit 0 +fi +/tmp/grade "$SEED" # the harness writes /logs/verifier/reward.{txt,json} +cat /logs/verifier/reward.json 2>/dev/null || true diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/CLAUDE.md b/tasks/raw-cuda/cuda-radix-partition/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/Dockerfile b/tasks/raw-cuda/cuda-radix-partition/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cee8eeb2094cb482b461bb59120eccb961bd834f --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/Dockerfile @@ -0,0 +1,34 @@ +# CUDA kernel-generation task: write a fast stable MoE token partition (counting sort by expert) in solution.cu. +# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton. +FROM nvidia/cuda:12.8.1-devel-ubuntu24.04 + +# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps. +RUN apt-get update && apt-get install -y --no-install-recommends \ + git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \ + rm -rf /var/lib/apt/lists/* + +# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled). +# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed, +# and dropping it keeps the environment free of any torch/triton files. +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \ + git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \ + mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi + +# Pre-bake the agent (the offline firewall blocks installing it at run time). +RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent +ENV PATH=/root/.local/bin:$PATH + +# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper. +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ +COPY solution.cu /app/solution.cu +COPY harness.cu /app/harness.cu +COPY build.sh /app/build.sh +RUN chmod +x /app/build.sh + +# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched). +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh + +# Strip apt sources so harbor's base apt-setup is a no-op under the firewall. +RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/* diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/PROCESS_MANAGEMENT.md b/tasks/raw-cuda/cuda-radix-partition/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/build.sh b/tasks/raw-cuda/cuda-radix-partition/environment/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..357f55e23f8935d722b8d834360ae4e1fe68d3cc --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Compile your solution against the harness and run one seed (the grader uses a different seed). +set -e +nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run +/app/run 0 diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/docker-compose.yaml b/tasks/raw-cuda/cuda-radix-partition/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b626bc85e10f49e564a9bb840c97b1fc5d66561f --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/docker-compose.yaml @@ -0,0 +1,17 @@ +# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose. +# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked). +# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has +# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it. +services: + main: + cap_add: + - NET_ADMIN + - SYS_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/harness.cu b/tasks/raw-cuda/cuda-radix-partition/environment/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..ffb613875fc0ebdf087c1b9e1d033e7d2383a60d --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/harness.cu @@ -0,0 +1,144 @@ +// Grading harness for cuda-radix-partition. +// Stable partition (counting sort) of N routed assignments by expert id: +// offsets[e] = number of i with expert[i] < e (exclusive prefix over the counts) +// dst[i] = offsets[expert[i]] + #{ j < i : expert[j] == expert[i] } +// expert[N] int32 in; dst[N] int32 and offsets[E+1] int32 out. offsets[E] == N. +// dst is a PERMUTATION of [0, N) and the order WITHIN each expert is stable, so the answer is +// unique and is compared exactly. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is the straightforward library route: for each expert, build a 0/1 flag array, +// run a cub exclusive scan over it, and scatter -- E full passes over the data. +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const long NTOK = 268435456L; // 2^28 routed assignments = 1.07 GB of int32 +static const int E = 64; // experts +#ifndef R_BAR +#define R_BAR 70.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void expert_partition(const int* expert, int* dst, int* offsets, long N, int E_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(int* t, long n, int E_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u = unif(s); + int id = (int)(E_ * powf(u, 2.0f)); // skewed load, as a real router produces + t[i] = id < E_ ? id : E_ - 1; + } +} + +// ---- naive reference ------------------------------------------------------------------------------ +__global__ void hist_kernel(const int* t, int* counts, long n){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + atomicAdd(&counts[t[i]], 1); +} +__global__ void offs_kernel(const int* counts, int* offsets, int E_, long n){ + if(threadIdx.x == 0){ + int acc = 0; + for(int e = 0; e < E_; e++){ offsets[e] = acc; acc += counts[e]; } + offsets[E_] = (int)n; + } +} +__global__ void flag_kernel(const int* t, int* flags, long n, int e){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + flags[i] = (t[i] == e) ? 1 : 0; +} +__global__ void scatter_kernel(const int* t, const int* ranks, int* dst, long n, int e, const int* offsets){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + if(t[i] == e) dst[i] = offsets[e] + ranks[i]; +} + +static int *g_flags = nullptr, *g_ranks = nullptr, *g_counts = nullptr; +static void* g_temp = nullptr; static size_t g_tb = 0; + +static void run_naive(const int* t, int* dst, int* offsets){ + CK(cudaMemset(g_counts, 0, E * 4)); + hist_kernel<<<2048, 256>>>(t, g_counts, NTOK); + offs_kernel<<<1, 32>>>(g_counts, offsets, E, NTOK); + for(int e = 0; e < E; e++){ + flag_kernel<<<2048, 256>>>(t, g_flags, NTOK, e); + cub::DeviceScan::ExclusiveSum(g_temp, g_tb, g_flags, g_ranks, (int)NTOK); + scatter_kernel<<<2048, 256>>>(t, g_ranks, dst, NTOK, e, offsets); + } +} +static void run_agent(const int* t, int* dst, int* offsets){ expert_partition(t, dst, offsets, NTOK, E); } + +// ---- comparison: exact --------------------------------------------------------------------------- +__global__ void cmp_kernel(const int* a, const int* b, long n, unsigned long long* bad){ + unsigned long long c = 0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + if(a[i] != b[i]) c++; + __shared__ unsigned long long s[256]; + s[threadIdx.x] = c; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ if(threadIdx.x < o) s[threadIdx.x] += s[threadIdx.x + o]; __syncthreads(); } + if(threadIdx.x == 0) atomicAdd(bad, s[0]); +} + +typedef void(*Fn)(const int*, int*, int*); +static float time_ms(Fn run, const int* t, int* d, int* o, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(t, d, o); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(t, d, o); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + int *tok, *dref, *dag, *oref, *oag; unsigned long long* bad; + CK(cudaMalloc(&tok, NTOK * 4)); CK(cudaMalloc(&dref, NTOK * 4)); CK(cudaMalloc(&dag, NTOK * 4)); + CK(cudaMalloc(&oref, (E + 1) * 4)); CK(cudaMalloc(&oag, (E + 1) * 4)); + CK(cudaMalloc(&g_flags, NTOK * 4)); CK(cudaMalloc(&g_ranks, NTOK * 4)); CK(cudaMalloc(&g_counts, E * 4)); + CK(cudaMalloc(&bad, 8)); CK(cudaMemset(bad, 0, 8)); + CK(cudaMemset(dag, 0xff, NTOK * 4)); CK(cudaMemset(oag, 0xff, (E + 1) * 4)); + cub::DeviceScan::ExclusiveSum(g_temp, g_tb, g_flags, g_ranks, (int)NTOK); + CK(cudaMalloc(&g_temp, g_tb)); + gen_kernel<<<1024, 256>>>(tok, NTOK, E, seed); + CK(cudaDeviceSynchronize()); + + run_naive(tok, dref, oref); CK(cudaDeviceSynchronize()); + run_agent(tok, dag, oag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(dag, dref, NTOK, bad); + cmp_kernel<<<1, 256>>>(oag, oref, E + 1, bad); + CK(cudaDeviceSynchronize()); + unsigned long long hb; CK(cudaMemcpy(&hb, bad, 8, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, tok, dref, oref, 1, 3); + float ta = time_ms(run_agent, tok, dag, oag, 5, 20); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hb == 0); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("wrong=%llu/%ld | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d " + "-> reward=%.1f\n", hb, NTOK + E + 1, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"wrong\": %llu, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hb, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/restrict-network.sh b/tasks/raw-cuda/cuda-radix-partition/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..10f759d82f01fe8868baa01a7816d23deea150c1 --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone +# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is +# pre-installed (harbor's patched installer skips the network install when it is already present), so no +# package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they +# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/raw-cuda/cuda-radix-partition/environment/solution.cu b/tasks/raw-cuda/cuda-radix-partition/environment/solution.cu new file mode 100644 index 0000000000000000000000000000000000000000..20715e9b1169311154e14e6c3fee1930df38e8f8 --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/environment/solution.cu @@ -0,0 +1,18 @@ +// solution.cu — implement the stable expert partition described in the instruction. +// offsets[e] = number of i with expert[i] < e (exclusive prefix over the per-expert counts) +// offsets[E] = N +// dst[i] = offsets[expert[i]] + #{ j < i : expert[j] == expert[i] } (STABLE) +// expert[N] is int32 with values in [0, E); dst[N] and offsets[E+1] are int32 outputs. +// N = 268435456, E = 64 (fixed). The result is exact integer data and is compared exactly. +// This stub writes zeros (it compiles and runs, but is incorrect — reward 0). +#include + +__global__ void stub_k(int* dst, int* offsets, long n, int E){ + long i = (long)blockIdx.x * blockDim.x + threadIdx.x; + if(i < n) dst[i] = 0; + if(i <= E) offsets[i] = 0; +} + +void expert_partition(const int* expert, int* dst, int* offsets, long N, int E){ + stub_k<<<(N + 255) / 256, 256>>>(dst, offsets, N, E); +} diff --git a/tasks/raw-cuda/cuda-radix-partition/instruction.md b/tasks/raw-cuda/cuda-radix-partition/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d78681583e90722e754876c1e4b9d05c5ec3b673 --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/instruction.md @@ -0,0 +1,66 @@ +# Write a fast CUDA kernel for a stable MoE token partition (counting sort by expert) + +Implement a high-performance CUDA kernel in `/app/solution.cu` that groups routed assignments by expert — +the permutation an MoE layer computes before it can run one contiguous GEMM per expert. + +Input: `expert` of shape `[N]` (`int`, values in `[0, E)`), one entry per routed `(token, slot)` assignment. +Outputs: `offsets` of shape `[E+1]` (`int`) and `dst` of shape `[N]` (`int`): + +``` +counts[e] = number of i with expert[i] == e +offsets[e] = counts[0] + ... + counts[e-1] # exclusive prefix; offsets[0] = 0 +offsets[E] = N +dst[i] = offsets[expert[i]] + #{ j < i : expert[j] == expert[i] } +``` + +`dst[i]` is where assignment `i` moves to in the grouped layout. The ordering inside each expert's segment +is **stable** — assignments keep their original relative order — so `dst` is a *unique* permutation of +`[0, N)` and it is compared **exactly**. The sizes are fixed: **N = 268435456 (2^28), E = 64**, and the +expert loads are **skewed** the way a real router's are. + +The function signature (fixed) is in `/app/solution.cu`: +```cpp +void expert_partition(const int* expert, int* dst, int* offsets, long N, int E); +``` + +## How success is decided + +The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and +checks: +1. **Correctness — exact.** All `N` entries of `dst` and all `E+1` entries of `offsets` must match the + reference exactly. There is no tolerance: this is integer bookkeeping, and an unstable ordering (for + example ranks handed out by a global `atomicAdd`) is **wrong**, not merely different. +2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event + timed, warmup + median; the exact bar is printed when you build). + +Both must pass for reward 1.0. + +## Notes + +- The reference the bar is measured against is the obvious library route: **for each expert**, build a 0/1 + flag array, run a `cub::DeviceScan::ExclusiveSum` over all `N` elements, and scatter. It is correct and + stable, and it makes `E = 64` full passes over the data. Your kernel should need **two**. +- The shape of a fast solution is the classic counting sort: (1) a pass that histograms the ids per + block/warp into a small private table, (2) a scan of those per-partition counts that turns them into a + start offset for every (partition, expert) pair — this is also where `offsets` comes from — and (3) a + second pass that walks the data again and assigns each element its rank. Only passes 1 and 3 touch the + `N`-sized array; the middle step works on a table of size `partitions * E`, which is a few MB at most. +- The rank inside a partition is where the interesting warp-level work is. `__match_any_sync` gives you, for + each lane, the mask of lanes in the warp holding the **same** expert id; `__popc(peers & lanemask_lt)` is + then that lane's rank among them, and one `__popc(peers)` per group advances a running per-expert counter. + That computes the stable rank for 32 elements with no atomics and no shared-memory scan. +- Keep the partitions independent and ordered: whatever unit you assign a contiguous span to (block or + warp), stability requires that ranks within a span are assigned in index order and that spans are offset + by the counts of all *earlier* spans. Choose the number of partitions carefully — too few and the second + pass is latency-bound on the dependent counter updates, too many and the middle scan grows. +- Alignment matters if you use `int4` loads: give each partition a span whose start is a multiple of 4. +- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer** + (`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA — `BlockScan`, `DeviceScan`, + `DeviceRadixSort`), warp intrinsics, and the profilers **`ncu`** and **`nsys`**. You may use CUB + primitives; a device-wide radix sort of the whole array is *a* correct answer, but it is not a fast one. + There is **no PyTorch and no Triton**; this is a pure CUDA task. +- Query the device with `cudaGetDeviceProperties` and size the grid from the SM count you find. +- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader + uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how + you are measured; you only edit `solution.cu`. +- **No internet access.** diff --git a/tasks/raw-cuda/cuda-radix-partition/solution/solution.oracle.cu b/tasks/raw-cuda/cuda-radix-partition/solution/solution.oracle.cu new file mode 100644 index 0000000000000000000000000000000000000000..c8f6b6a3f85c943cfafbb1c0802a28e6d406e276 --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/solution/solution.oracle.cu @@ -0,0 +1,136 @@ +// Oracle: two passes over the ids + three tiny bookkeeping kernels. +// pass 1 : each WARP owns a contiguous span and histograms it (privatised in shared, int4 loads) +// scan : per-expert totals -> exclusive scan over experts (= offsets) -> per-warp start offsets +// pass 2 : each warp re-walks its span 32 elements at a time; __match_any_sync gives the lanes +// carrying the same expert, popc(peers & lanemask_lt) gives the STABLE rank inside the +// group, and a per-warp shared counter carries the rank across chunks. +// Total traffic: read the ids twice, write dst once. No device-wide scan of an N-sized array. +#include + +#define NTHREAD 256 +#define WPB (NTHREAD / 32) +#define GRIDMUL 4 + +// span per warp, rounded up to a multiple of 4 so every warp's span starts 16-byte aligned +__device__ __host__ __forceinline__ long span_per_warp(long n, int nwarp){ + return ((n + (long)nwarp * 4 - 1) / ((long)nwarp * 4)) * 4; +} + +__global__ __launch_bounds__(NTHREAD) void count_k(const int* __restrict__ t, int* __restrict__ cnt, + long n, int E, int nwarp){ + extern __shared__ int sh[]; // WPB * E + const int w = threadIdx.x >> 5, lane = threadIdx.x & 31; + int* mine = sh + w * E; + for(int e = lane; e < E; e += 32) mine[e] = 0; + __syncwarp(); + + const int gw = blockIdx.x * WPB + w; // global warp id + const long per = span_per_warp(n, nwarp); + long lo = (long)gw * per; if(lo > n) lo = n; + long hi = lo + per; if(hi > n) hi = n; + const long nvec = (hi - lo) / 4; // complete 4-element groups in this span + for(long g = lane; g < nvec; g += 32){ + int4 v = *reinterpret_cast(t + lo + g * 4); + atomicAdd(&mine[v.x], 1); atomicAdd(&mine[v.y], 1); + atomicAdd(&mine[v.z], 1); atomicAdd(&mine[v.w], 1); + } + for(long i = lo + nvec * 4 + lane; i < hi; i += 32) atomicAdd(&mine[t[i]], 1); + __syncwarp(); + for(int e = lane; e < E; e += 32) cnt[(long)gw * E + e] = mine[e]; +} + +__global__ void totals_k(const int* cnt, int* totals, int E, int nwarp){ + int e = blockIdx.x; + __shared__ int s[256]; + int acc = 0; + for(int w = threadIdx.x; w < nwarp; w += blockDim.x) acc += cnt[(long)w * E + e]; + s[threadIdx.x] = acc; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ if(threadIdx.x < o) s[threadIdx.x] += s[threadIdx.x + o]; __syncthreads(); } + if(threadIdx.x == 0) totals[e] = s[0]; +} + +__global__ void offsets_k(const int* totals, int* offsets, int E, long n){ + if(threadIdx.x == 0){ + int acc = 0; + for(int e = 0; e < E; e++){ offsets[e] = acc; acc += totals[e]; } + offsets[E] = (int)n; + } +} + +// start[w][e] = offsets[e] + sum_{w' < w} cnt[w'][e] +__global__ void starts_k(const int* cnt, const int* offsets, int* start, int E, int nwarp){ + int e = blockIdx.x; + __shared__ int carry; + __shared__ int s[256]; + if(threadIdx.x == 0) carry = offsets[e]; + __syncthreads(); + for(int base = 0; base < nwarp; base += blockDim.x){ + int w = base + threadIdx.x; + int v = (w < nwarp) ? cnt[(long)w * E + e] : 0; + s[threadIdx.x] = v; + __syncthreads(); + // exclusive scan in shared (Hillis-Steele on 256 elements) + for(int o = 1; o < (int)blockDim.x; o <<= 1){ + int add = (threadIdx.x >= o) ? s[threadIdx.x - o] : 0; + __syncthreads(); + s[threadIdx.x] += add; + __syncthreads(); + } + int incl = s[threadIdx.x]; + if(w < nwarp) start[(long)w * E + e] = carry + incl - v; + int tot = s[blockDim.x - 1]; + __syncthreads(); + if(threadIdx.x == 0) carry += tot; + __syncthreads(); + } +} + +__global__ __launch_bounds__(NTHREAD) void scatter_k(const int* __restrict__ t, int* __restrict__ dst, + const int* __restrict__ start, long n, int E, int nwarp){ + extern __shared__ int sh[]; // WPB * E running counters + const int w = threadIdx.x >> 5, lane = threadIdx.x & 31; + int* cnt = sh + w * E; + const int gw = blockIdx.x * WPB + w; + for(int e = lane; e < E; e += 32) cnt[e] = start[(long)gw * E + e]; + __syncwarp(); + + const long per = span_per_warp(n, nwarp); + long lo = (long)gw * per; if(lo > n) lo = n; + long hi = lo + per; if(hi > n) hi = n; + const unsigned lt = (1u << lane) - 1u; + for(long base = lo; base < hi; base += 32){ + long i = base + lane; + bool act = i < hi; + unsigned mask = __ballot_sync(0xffffffff, act); + if(!act) continue; + int e = t[i]; + unsigned peers = __match_any_sync(mask, e) & mask; + int rank = cnt[e] + __popc(peers & lt); + dst[i] = rank; + int leader = __ffs(peers) - 1; + int add = __popc(peers); + if(lane == leader) cnt[e] += add; + __syncwarp(mask); + } +} + +void expert_partition(const int* expert, int* dst, int* offsets, long N, int E){ + static int grid = 0, nwarp = 0; + static int *cnt = nullptr, *totals = nullptr, *start = nullptr; + if(!grid){ + int dev; cudaGetDevice(&dev); + int sm; cudaDeviceGetAttribute(&sm, cudaDevAttrMultiProcessorCount, dev); + grid = sm * GRIDMUL; + nwarp = grid * WPB; + cudaMalloc(&cnt, (size_t)nwarp * E * sizeof(int)); + cudaMalloc(&start, (size_t)nwarp * E * sizeof(int)); + cudaMalloc(&totals, E * sizeof(int)); + } + size_t smem = (size_t)WPB * E * sizeof(int); + count_k<<>>(expert, cnt, N, E, nwarp); + totals_k<<>>(cnt, totals, E, nwarp); + offsets_k<<<1, 32>>>(totals, offsets, E, N); + starts_k<<>>(cnt, offsets, start, E, nwarp); + scatter_k<<>>(expert, dst, start, N, E, nwarp); +} diff --git a/tasks/raw-cuda/cuda-radix-partition/task.toml b/tasks/raw-cuda/cuda-radix-partition/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f56c9a834f6d15b6ce12d92e6d3a869205ce13c --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/task.toml @@ -0,0 +1,36 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/cuda-radix-partition" +description = "Write a fast hand-written CUDA kernel for a stable MoE token partition -- the counting sort by expert that an MoE layer runs before it can do one contiguous GEMM per expert. Given an expert id per routed (token, slot) assignment, produce the per-expert offsets and the destination permutation, STABLE within each expert. Graded on BIT-EXACT integer output, so the whole task is the histogram, the exclusive scan and a stable scatter without serialising on atomics. Hand-written CUDA only (CUTLASS/flashinfer/CUB); no PyTorch/Triton; ncu/nsys available." +authors = [] +keywords = [ "mle", "kernel-generation", "cuda", "moe", "counting-sort", "scan", "permutation", "performance", "gpu",] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "cuda", "gpu", "performance", "real-world",] + +[verifier] +timeout_sec = 600.0 + +[agent] +timeout_sec = 14400.0 + +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 32768 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/raw-cuda/cuda-radix-partition/tests/harness.cu b/tasks/raw-cuda/cuda-radix-partition/tests/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..ffb613875fc0ebdf087c1b9e1d033e7d2383a60d --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/tests/harness.cu @@ -0,0 +1,144 @@ +// Grading harness for cuda-radix-partition. +// Stable partition (counting sort) of N routed assignments by expert id: +// offsets[e] = number of i with expert[i] < e (exclusive prefix over the counts) +// dst[i] = offsets[expert[i]] + #{ j < i : expert[j] == expert[i] } +// expert[N] int32 in; dst[N] int32 and offsets[E+1] int32 out. offsets[E] == N. +// dst is a PERMUTATION of [0, N) and the order WITHIN each expert is stable, so the answer is +// unique and is compared exactly. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is the straightforward library route: for each expert, build a 0/1 flag array, +// run a cub exclusive scan over it, and scatter -- E full passes over the data. +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const long NTOK = 268435456L; // 2^28 routed assignments = 1.07 GB of int32 +static const int E = 64; // experts +#ifndef R_BAR +#define R_BAR 70.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void expert_partition(const int* expert, int* dst, int* offsets, long N, int E_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(int* t, long n, int E_, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u = unif(s); + int id = (int)(E_ * powf(u, 2.0f)); // skewed load, as a real router produces + t[i] = id < E_ ? id : E_ - 1; + } +} + +// ---- naive reference ------------------------------------------------------------------------------ +__global__ void hist_kernel(const int* t, int* counts, long n){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + atomicAdd(&counts[t[i]], 1); +} +__global__ void offs_kernel(const int* counts, int* offsets, int E_, long n){ + if(threadIdx.x == 0){ + int acc = 0; + for(int e = 0; e < E_; e++){ offsets[e] = acc; acc += counts[e]; } + offsets[E_] = (int)n; + } +} +__global__ void flag_kernel(const int* t, int* flags, long n, int e){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + flags[i] = (t[i] == e) ? 1 : 0; +} +__global__ void scatter_kernel(const int* t, const int* ranks, int* dst, long n, int e, const int* offsets){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + if(t[i] == e) dst[i] = offsets[e] + ranks[i]; +} + +static int *g_flags = nullptr, *g_ranks = nullptr, *g_counts = nullptr; +static void* g_temp = nullptr; static size_t g_tb = 0; + +static void run_naive(const int* t, int* dst, int* offsets){ + CK(cudaMemset(g_counts, 0, E * 4)); + hist_kernel<<<2048, 256>>>(t, g_counts, NTOK); + offs_kernel<<<1, 32>>>(g_counts, offsets, E, NTOK); + for(int e = 0; e < E; e++){ + flag_kernel<<<2048, 256>>>(t, g_flags, NTOK, e); + cub::DeviceScan::ExclusiveSum(g_temp, g_tb, g_flags, g_ranks, (int)NTOK); + scatter_kernel<<<2048, 256>>>(t, g_ranks, dst, NTOK, e, offsets); + } +} +static void run_agent(const int* t, int* dst, int* offsets){ expert_partition(t, dst, offsets, NTOK, E); } + +// ---- comparison: exact --------------------------------------------------------------------------- +__global__ void cmp_kernel(const int* a, const int* b, long n, unsigned long long* bad){ + unsigned long long c = 0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + if(a[i] != b[i]) c++; + __shared__ unsigned long long s[256]; + s[threadIdx.x] = c; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ if(threadIdx.x < o) s[threadIdx.x] += s[threadIdx.x + o]; __syncthreads(); } + if(threadIdx.x == 0) atomicAdd(bad, s[0]); +} + +typedef void(*Fn)(const int*, int*, int*); +static float time_ms(Fn run, const int* t, int* d, int* o, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(t, d, o); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(t, d, o); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + int *tok, *dref, *dag, *oref, *oag; unsigned long long* bad; + CK(cudaMalloc(&tok, NTOK * 4)); CK(cudaMalloc(&dref, NTOK * 4)); CK(cudaMalloc(&dag, NTOK * 4)); + CK(cudaMalloc(&oref, (E + 1) * 4)); CK(cudaMalloc(&oag, (E + 1) * 4)); + CK(cudaMalloc(&g_flags, NTOK * 4)); CK(cudaMalloc(&g_ranks, NTOK * 4)); CK(cudaMalloc(&g_counts, E * 4)); + CK(cudaMalloc(&bad, 8)); CK(cudaMemset(bad, 0, 8)); + CK(cudaMemset(dag, 0xff, NTOK * 4)); CK(cudaMemset(oag, 0xff, (E + 1) * 4)); + cub::DeviceScan::ExclusiveSum(g_temp, g_tb, g_flags, g_ranks, (int)NTOK); + CK(cudaMalloc(&g_temp, g_tb)); + gen_kernel<<<1024, 256>>>(tok, NTOK, E, seed); + CK(cudaDeviceSynchronize()); + + run_naive(tok, dref, oref); CK(cudaDeviceSynchronize()); + run_agent(tok, dag, oag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(dag, dref, NTOK, bad); + cmp_kernel<<<1, 256>>>(oag, oref, E + 1, bad); + CK(cudaDeviceSynchronize()); + unsigned long long hb; CK(cudaMemcpy(&hb, bad, 8, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, tok, dref, oref, 1, 3); + float ta = time_ms(run_agent, tok, dag, oag, 5, 20); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hb == 0); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("wrong=%llu/%ld | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d " + "-> reward=%.1f\n", hb, NTOK + E + 1, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"wrong\": %llu, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hb, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-radix-partition/tests/test.sh b/tasks/raw-cuda/cuda-radix-partition/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..18efdf3a3a726f0f80160d553ce52bc77c051af4 --- /dev/null +++ b/tasks/raw-cuda/cuda-radix-partition/tests/test.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Verifier: compile the FRESH harness + the agent's solution, grade with a random seed. +set -uo pipefail +mkdir -p /logs/verifier +SEED=$(( (RANDOM << 15) ^ RANDOM )) +nvcc -O3 -arch=native /tests/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /tmp/grade 2>/tmp/nvcc.log +if [ ! -x /tmp/grade ]; then + echo "COMPILE FAILED:"; tail -20 /tmp/nvcc.log + echo "0.0" > /logs/verifier/reward.txt + echo '{"reward": 0.0, "error": "compile_failed"}' > /logs/verifier/reward.json + exit 0 +fi +/tmp/grade "$SEED" # the harness writes /logs/verifier/reward.{txt,json} +cat /logs/verifier/reward.json 2>/dev/null || true diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/CLAUDE.md b/tasks/raw-cuda/cuda-transpose-vectorized/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/Dockerfile b/tasks/raw-cuda/cuda-transpose-vectorized/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..420fe93d80c45143ec38adc35285e739ae451fbf --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/Dockerfile @@ -0,0 +1,34 @@ +# CUDA kernel-generation task: write a fast vectorised bf16 matrix transpose in solution.cu. +# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton. +FROM nvidia/cuda:12.8.1-devel-ubuntu24.04 + +# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps. +RUN apt-get update && apt-get install -y --no-install-recommends \ + git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \ + rm -rf /var/lib/apt/lists/* + +# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled). +# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed, +# and dropping it keeps the environment free of any torch/triton files. +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \ + git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \ + mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi + +# Pre-bake the agent (the offline firewall blocks installing it at run time). +RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent +ENV PATH=/root/.local/bin:$PATH + +# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper. +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ +COPY solution.cu /app/solution.cu +COPY harness.cu /app/harness.cu +COPY build.sh /app/build.sh +RUN chmod +x /app/build.sh + +# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched). +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh + +# Strip apt sources so harbor's base apt-setup is a no-op under the firewall. +RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/* diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/PROCESS_MANAGEMENT.md b/tasks/raw-cuda/cuda-transpose-vectorized/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/build.sh b/tasks/raw-cuda/cuda-transpose-vectorized/environment/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..357f55e23f8935d722b8d834360ae4e1fe68d3cc --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Compile your solution against the harness and run one seed (the grader uses a different seed). +set -e +nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run +/app/run 0 diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/docker-compose.yaml b/tasks/raw-cuda/cuda-transpose-vectorized/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b626bc85e10f49e564a9bb840c97b1fc5d66561f --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/docker-compose.yaml @@ -0,0 +1,17 @@ +# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose. +# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked). +# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has +# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it. +services: + main: + cap_add: + - NET_ADMIN + - SYS_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/harness.cu b/tasks/raw-cuda/cuda-transpose-vectorized/environment/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..d2bfa9aa640fc4a686af79541eb7873cc29d93ee --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/harness.cu @@ -0,0 +1,107 @@ +// Grading harness for cuda-transpose-vectorized. +// out[n, m] = in[m, n] for a bf16 matrix in[M, N] -> out[N, M], both row-major. +// This is the layout change a backward pass needs before the weight-gradient GEMM: pure data movement, +// 1.07 GB in and 1.07 GB out, no arithmetic at all. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one thread per element (coalesced reads, strided writes). +// Correctness is EXACT: the output must be bit-identical, so the check counts mismatching elements. +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int M = 32768, N = 16384; // 5.4e8 elements: 1.07 GB in, 1.07 GB out +#ifndef R_BAR +#define R_BAR 26.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void transpose_bf16(const __nv_bfloat16* in, __nv_bfloat16* out, int M_, int N_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__global__ void gen_kernel(__nv_bfloat16* x, long n, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned h = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + // arbitrary but reproducible bit patterns that are always finite bf16 values + x[i] = __float2bfloat16(((h >> 8) * (1.0f / 16777216.0f) - 0.5f) * 8.0f); + } +} + +// ---- naive reference: one thread per element ---------------------------------------------------- +__global__ void naive_kernel(const __nv_bfloat16* in, __nv_bfloat16* out, int M_, int N_){ + long total = (long)M_ * N_; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long)gridDim.x * blockDim.x){ + int m = (int)(i / N_), n = (int)(i % N_); + out[(long)n * M_ + m] = in[i]; + } +} + +// ---- comparison: exact --------------------------------------------------------------------------- +__global__ void cmp_kernel(const __nv_bfloat16* a, const __nv_bfloat16* b, long n, unsigned long long* bad){ + unsigned long long c = 0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + if(__bfloat16_as_ushort(a[i]) != __bfloat16_as_ushort(b[i])) c++; + __shared__ unsigned long long s[256]; + s[threadIdx.x] = c; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ if(threadIdx.x < o) s[threadIdx.x] += s[threadIdx.x + o]; __syncthreads(); } + if(threadIdx.x == 0) atomicAdd(bad, s[0]); +} + +typedef void(*Fn)(const __nv_bfloat16*, __nv_bfloat16*); +static float time_ms(Fn run, const __nv_bfloat16* a, __nv_bfloat16* b, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(a, b); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const __nv_bfloat16* a, __nv_bfloat16* b){ naive_kernel<<<2048, 256>>>(a, b, M, N); } +static void run_agent(const __nv_bfloat16* a, __nv_bfloat16* b){ transpose_bf16(a, b, M, N); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)M * N; + __nv_bfloat16 *in, *oref, *oag; unsigned long long* bad; + CK(cudaMalloc(&in, n * 2)); CK(cudaMalloc(&oref, n * 2)); CK(cudaMalloc(&oag, n * 2)); + CK(cudaMalloc(&bad, 8)); CK(cudaMemset(bad, 0, 8)); CK(cudaMemset(oag, 0, n * 2)); + gen_kernel<<<1024, 256>>>(in, n, seed); + CK(cudaDeviceSynchronize()); + + run_naive(in, oref); CK(cudaDeviceSynchronize()); + run_agent(in, oag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(oag, oref, n, bad); + CK(cudaDeviceSynchronize()); + unsigned long long hb; CK(cudaMemcpy(&hb, bad, 8, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, in, oref, 1, 5); + float ta = time_ms(run_agent, in, oag, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hb == 0); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("mismatched=%llu/%ld | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | " + "correct=%d fast=%d -> reward=%.1f\n", hb, n, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"mismatched\": %llu, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hb, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/restrict-network.sh b/tasks/raw-cuda/cuda-transpose-vectorized/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..10f759d82f01fe8868baa01a7816d23deea150c1 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone +# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is +# pre-installed (harbor's patched installer skips the network install when it is already present), so no +# package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they +# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/environment/solution.cu b/tasks/raw-cuda/cuda-transpose-vectorized/environment/solution.cu new file mode 100644 index 0000000000000000000000000000000000000000..540fc2a093e4c2c054ce83a4045a2b05866d8385 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/environment/solution.cu @@ -0,0 +1,16 @@ +// solution.cu — implement the bf16 matrix transpose described in the instruction. +// out[n, m] = in[m, n] in[M, N] and out[N, M] are both row-major __nv_bfloat16. +// M = 32768, N = 16384 (fixed). The output must be BIT-IDENTICAL: this is pure data movement. +// This stub writes zeros (it compiles and runs, but is incorrect — reward 0). +#include +#include + +__global__ void stub_k(__nv_bfloat16* out, long n){ + long i = (long)blockIdx.x * blockDim.x + threadIdx.x; + if(i < n) out[i] = __float2bfloat16(0.f); +} + +void transpose_bf16(const __nv_bfloat16* in, __nv_bfloat16* out, int M, int N){ + long n = (long)M * N; + stub_k<<<(n + 255) / 256, 256>>>(out, n); +} diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/instruction.md b/tasks/raw-cuda/cuda-transpose-vectorized/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5dfd993b800d0764571f5f7add0e5bbc7b96b408 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/instruction.md @@ -0,0 +1,61 @@ +# Write a fast CUDA kernel for a bf16 matrix transpose + +Implement a high-performance CUDA kernel in `/app/solution.cu` that transposes a large `bfloat16` matrix — +the layout change a training step performs on its activations before the weight-gradient GEMM. + +Input: `in` of shape `[M, N]` (`__nv_bfloat16`, row-major). Output: `out` of shape `[N, M]` +(`__nv_bfloat16`, row-major), with + +``` +out[n, m] = in[m, n] for all m in [0, M), n in [0, N) +``` + +The sizes are fixed: **M = 32768, N = 16384** — 1.07 GB in, 1.07 GB out. There is **no arithmetic at all**: +every output element is a copy of an input element. + +The function signature (fixed) is in `/app/solution.cu`: +```cpp +void transpose_bf16(const __nv_bfloat16* in, __nv_bfloat16* out, int M, int N); +``` + +## How success is decided + +The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and +checks: +1. **Correctness — exact.** Every one of the 5.4e8 output elements must be **bit-identical** to the + reference; the check counts mismatching elements and requires zero. There is no tolerance, because there + is no arithmetic. +2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event + timed, warmup + median; the exact bar is printed when you build). + +Both must pass for reward 1.0. + +## Notes + +- This is the cleanest possible **bandwidth** problem: 2.15 GB must move, and the only question is whether + your accesses are wide and coalesced in **both** directions. Measure a large device-to-device copy to find + the machine's practical ceiling (do not trust a datasheet number) — that copy is your target, and a good + transpose lands within a small factor of it. +- The reference the bar is measured against is **one thread per element**: reads are coalesced, writes are + strided by `M` elements, so every 32-thread write touches 32 different cache lines. That is the entire + cost. Fixing it means never issuing a strided global access at all, in either direction, which requires + staging a tile somewhere on chip. +- Two things separate a merely-working tiled transpose from a fast one: + - **access width.** An element is 2 bytes; a 128-bit access moves 8 of them. A tile scheme that reads or + writes one element per thread per instruction cannot reach the roofline no matter how well it is + coalesced. + - **shared-memory bank conflicts.** The store phase reads *down a column* of the staged tile. With a + naively laid-out tile that is an N-way conflict, and it can cost more than the padding trick you might + reach for first — with 2-byte elements, the padding that removes the conflict can also break the + alignment that the wide access needs. Think about swizzling the layout instead. +- The tile shape is yours to choose; `cudaGetDeviceProperties` gives you the SM count and the shared memory + per block. Both `M` and `N` are multiples of 64, so you do not have to handle a partial tile — but you do + have to keep enough blocks in flight to saturate the device. +- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer** + (`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA), and the profilers **`ncu`** and **`nsys`**. + `ncu` reports both achieved DRAM throughput and shared-memory bank conflicts — both numbers are directly + actionable here. There is **no PyTorch and no Triton**; this is a pure CUDA task. +- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader + uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how + you are measured; you only edit `solution.cu`. +- **No internet access.** diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/solution/solution.oracle.cu b/tasks/raw-cuda/cuda-transpose-vectorized/solution/solution.oracle.cu new file mode 100644 index 0000000000000000000000000000000000000000..cd35aff23df4b4ea76b9998b02d552ca9792d708 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/solution/solution.oracle.cu @@ -0,0 +1,39 @@ +// Oracle: 64x64 shared-memory tiled bf16 transpose, XOR-swizzled to kill the shared-memory bank +// conflicts of the column gather, with 128-bit loads AND 128-bit stores (8 bf16 per access). +// load : thread reads 8 consecutive elements of an input row -> tile[r][(c8 ^ ((r>>3)&7))*8] +// store: thread emits 8 consecutive elements of an OUTPUT row = 8 consecutive input rows of one column +#include +#include +#define TILE 64 +#define NTHREAD 512 +__global__ __launch_bounds__(NTHREAD) void transpose_k(const __nv_bfloat16* __restrict__ in, + __nv_bfloat16* __restrict__ out, int M, int N){ + __shared__ __nv_bfloat16 tile[TILE][TILE]; + const int row0 = blockIdx.y * TILE, col0 = blockIdx.x * TILE; + const int tid = threadIdx.x; + { + int r = tid >> 3, c8 = tid & 7; // 8 chunks of 8 elements per row + const uint4 v = *reinterpret_cast(in + (long)(row0 + r) * N + col0 + c8 * 8); + *reinterpret_cast(&tile[r][(c8 ^ ((r >> 3) & 7)) * 8]) = v; + } + __syncthreads(); + { + int c = tid >> 3, rc = tid & 7; // output row c, 8 consecutive input rows + __nv_bfloat16 buf[8]; + #pragma unroll + for(int j = 0; j < 8; j++) buf[j] = tile[rc * 8 + j][c ^ (rc * 8)]; + *reinterpret_cast(out + (long)(col0 + c) * M + row0 + rc * 8) = + *reinterpret_cast(buf); + } +} +__global__ void transpose_gen(const __nv_bfloat16* in, __nv_bfloat16* out, int M, int N){ + long total = (long)M * N; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long)gridDim.x * blockDim.x){ + int m = (int)(i / N), n = (int)(i % N); + out[(long)n * M + m] = in[i]; + } +} +void transpose_bf16(const __nv_bfloat16* in, __nv_bfloat16* out, int M, int N){ + if(M % TILE == 0 && N % TILE == 0){ dim3 g(N / TILE, M / TILE); transpose_k<<>>(in, out, M, N); } + else transpose_gen<<<2048, 256>>>(in, out, M, N); +} diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/solution/solve.sh b/tasks/raw-cuda/cuda-transpose-vectorized/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e22a85fc3282f112a7d7a38677e00d0773111007 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/solution/solve.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Oracle: restore the reference fast kernel. +set -e +cat > /app/solution.cu <<'ORACLE_CU_EOF' +// Oracle: 64x64 shared-memory tiled bf16 transpose, XOR-swizzled to kill the shared-memory bank +// conflicts of the column gather, with 128-bit loads AND 128-bit stores (8 bf16 per access). +// load : thread reads 8 consecutive elements of an input row -> tile[r][(c8 ^ ((r>>3)&7))*8] +// store: thread emits 8 consecutive elements of an OUTPUT row = 8 consecutive input rows of one column +#include +#include +#define TILE 64 +#define NTHREAD 512 +__global__ __launch_bounds__(NTHREAD) void transpose_k(const __nv_bfloat16* __restrict__ in, + __nv_bfloat16* __restrict__ out, int M, int N){ + __shared__ __nv_bfloat16 tile[TILE][TILE]; + const int row0 = blockIdx.y * TILE, col0 = blockIdx.x * TILE; + const int tid = threadIdx.x; + { + int r = tid >> 3, c8 = tid & 7; // 8 chunks of 8 elements per row + const uint4 v = *reinterpret_cast(in + (long)(row0 + r) * N + col0 + c8 * 8); + *reinterpret_cast(&tile[r][(c8 ^ ((r >> 3) & 7)) * 8]) = v; + } + __syncthreads(); + { + int c = tid >> 3, rc = tid & 7; // output row c, 8 consecutive input rows + __nv_bfloat16 buf[8]; + #pragma unroll + for(int j = 0; j < 8; j++) buf[j] = tile[rc * 8 + j][c ^ (rc * 8)]; + *reinterpret_cast(out + (long)(col0 + c) * M + row0 + rc * 8) = + *reinterpret_cast(buf); + } +} +__global__ void transpose_gen(const __nv_bfloat16* in, __nv_bfloat16* out, int M, int N){ + long total = (long)M * N; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long)gridDim.x * blockDim.x){ + int m = (int)(i / N), n = (int)(i % N); + out[(long)n * M + m] = in[i]; + } +} +void transpose_bf16(const __nv_bfloat16* in, __nv_bfloat16* out, int M, int N){ + if(M % TILE == 0 && N % TILE == 0){ dim3 g(N / TILE, M / TILE); transpose_k<<>>(in, out, M, N); } + else transpose_gen<<<2048, 256>>>(in, out, M, N); +} +ORACLE_CU_EOF +echo restored diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/task.toml b/tasks/raw-cuda/cuda-transpose-vectorized/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..29ab03808e345e28a8d3d62224390bfab5306319 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/task.toml @@ -0,0 +1,36 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/cuda-transpose-vectorized" +description = "Write a fast hand-written CUDA kernel for a 32768x16384 bf16 matrix transpose (out[n,m] = in[m,n]), beating a one-thread-per-element reference by a calibrated margin. Pure data movement, 2.15 GB, graded on BIT-EXACT output: the whole task is wide coalesced accesses in both directions plus a shared-memory tile layout whose column gather is free of bank conflicts (padding breaks 128-bit alignment for 2-byte elements, so a swizzle is wanted). Hand-written CUDA only (CUTLASS/flashinfer/CUB); no PyTorch/Triton; ncu/nsys available." +authors = [] +keywords = [ "mle", "kernel-generation", "cuda", "transpose", "bandwidth", "shared-memory", "performance", "gpu",] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "cuda", "gpu", "performance", "real-world",] + +[verifier] +timeout_sec = 600.0 + +[agent] +timeout_sec = 14400.0 + +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 32768 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/tests/harness.cu b/tasks/raw-cuda/cuda-transpose-vectorized/tests/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..d2bfa9aa640fc4a686af79541eb7873cc29d93ee --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/tests/harness.cu @@ -0,0 +1,107 @@ +// Grading harness for cuda-transpose-vectorized. +// out[n, m] = in[m, n] for a bf16 matrix in[M, N] -> out[N, M], both row-major. +// This is the layout change a backward pass needs before the weight-gradient GEMM: pure data movement, +// 1.07 GB in and 1.07 GB out, no arithmetic at all. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one thread per element (coalesced reads, strided writes). +// Correctness is EXACT: the output must be bit-identical, so the check counts mismatching elements. +#include +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int M = 32768, N = 16384; // 5.4e8 elements: 1.07 GB in, 1.07 GB out +#ifndef R_BAR +#define R_BAR 26.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void transpose_bf16(const __nv_bfloat16* in, __nv_bfloat16* out, int M_, int N_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__global__ void gen_kernel(__nv_bfloat16* x, long n, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned h = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + // arbitrary but reproducible bit patterns that are always finite bf16 values + x[i] = __float2bfloat16(((h >> 8) * (1.0f / 16777216.0f) - 0.5f) * 8.0f); + } +} + +// ---- naive reference: one thread per element ---------------------------------------------------- +__global__ void naive_kernel(const __nv_bfloat16* in, __nv_bfloat16* out, int M_, int N_){ + long total = (long)M_ * N_; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long)gridDim.x * blockDim.x){ + int m = (int)(i / N_), n = (int)(i % N_); + out[(long)n * M_ + m] = in[i]; + } +} + +// ---- comparison: exact --------------------------------------------------------------------------- +__global__ void cmp_kernel(const __nv_bfloat16* a, const __nv_bfloat16* b, long n, unsigned long long* bad){ + unsigned long long c = 0; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x) + if(__bfloat16_as_ushort(a[i]) != __bfloat16_as_ushort(b[i])) c++; + __shared__ unsigned long long s[256]; + s[threadIdx.x] = c; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ if(threadIdx.x < o) s[threadIdx.x] += s[threadIdx.x + o]; __syncthreads(); } + if(threadIdx.x == 0) atomicAdd(bad, s[0]); +} + +typedef void(*Fn)(const __nv_bfloat16*, __nv_bfloat16*); +static float time_ms(Fn run, const __nv_bfloat16* a, __nv_bfloat16* b, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(a, b); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const __nv_bfloat16* a, __nv_bfloat16* b){ naive_kernel<<<2048, 256>>>(a, b, M, N); } +static void run_agent(const __nv_bfloat16* a, __nv_bfloat16* b){ transpose_bf16(a, b, M, N); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)M * N; + __nv_bfloat16 *in, *oref, *oag; unsigned long long* bad; + CK(cudaMalloc(&in, n * 2)); CK(cudaMalloc(&oref, n * 2)); CK(cudaMalloc(&oag, n * 2)); + CK(cudaMalloc(&bad, 8)); CK(cudaMemset(bad, 0, 8)); CK(cudaMemset(oag, 0, n * 2)); + gen_kernel<<<1024, 256>>>(in, n, seed); + CK(cudaDeviceSynchronize()); + + run_naive(in, oref); CK(cudaDeviceSynchronize()); + run_agent(in, oag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(oag, oref, n, bad); + CK(cudaDeviceSynchronize()); + unsigned long long hb; CK(cudaMemcpy(&hb, bad, 8, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, in, oref, 1, 5); + float ta = time_ms(run_agent, in, oag, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hb == 0); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("mismatched=%llu/%ld | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | " + "correct=%d fast=%d -> reward=%.1f\n", hb, n, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"mismatched\": %llu, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hb, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-transpose-vectorized/tests/test.sh b/tasks/raw-cuda/cuda-transpose-vectorized/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..18efdf3a3a726f0f80160d553ce52bc77c051af4 --- /dev/null +++ b/tasks/raw-cuda/cuda-transpose-vectorized/tests/test.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Verifier: compile the FRESH harness + the agent's solution, grade with a random seed. +set -uo pipefail +mkdir -p /logs/verifier +SEED=$(( (RANDOM << 15) ^ RANDOM )) +nvcc -O3 -arch=native /tests/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /tmp/grade 2>/tmp/nvcc.log +if [ ! -x /tmp/grade ]; then + echo "COMPILE FAILED:"; tail -20 /tmp/nvcc.log + echo "0.0" > /logs/verifier/reward.txt + echo '{"reward": 0.0, "error": "compile_failed"}' > /logs/verifier/reward.json + exit 0 +fi +/tmp/grade "$SEED" # the harness writes /logs/verifier/reward.{txt,json} +cat /logs/verifier/reward.json 2>/dev/null || true diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/CLAUDE.md b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..af9c8ddfbeaef8867f118620c7adbb0df98c6150 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/CLAUDE.md @@ -0,0 +1,25 @@ +# Working in this environment + +## ⚠️ Stop background processes without killing yourself + +You are launched as `claude --print -- ''`, so the task text — including the +file names and commands it mentions — is on **your own** process's command line. Any command that +finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc` +cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run +(`NonZeroAgentExitCodeError`) and grading you on unfinished work. + +This bites whenever you background something and later stop/restart it — a **server**, a long +**build** or **training run**, or an **ncu / nsys profiling** session. + +**Always** manage a background process by its **exact recorded PID**, never by a name pattern: + +```bash +nohup > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID +kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed +``` + +Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children. +If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and +**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill. + +Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**. diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/Dockerfile b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c47a87c555b66a5996568cb5084bc306043f2fc6 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/Dockerfile @@ -0,0 +1,34 @@ +# CUDA kernel-generation task: write a fast segmented (per-row) inclusive prefix-sum kernel in solution.cu. +# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton. +FROM nvidia/cuda:12.8.1-devel-ubuntu24.04 + +# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps. +RUN apt-get update && apt-get install -y --no-install-recommends \ + git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \ + rm -rf /var/lib/apt/lists/* + +# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled). +# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed, +# and dropping it keeps the environment free of any torch/triton files. +RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \ + git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \ + mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi + +# Pre-bake the agent (the offline firewall blocks installing it at run time). +RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent +ENV PATH=/root/.local/bin:$PATH + +# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper. +WORKDIR /app +COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/ +COPY solution.cu /app/solution.cu +COPY harness.cu /app/harness.cu +COPY build.sh /app/build.sh +RUN chmod +x /app/build.sh + +# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched). +COPY restrict-network.sh /app/restrict-network.sh +RUN chmod +x /app/restrict-network.sh + +# Strip apt sources so harbor's base apt-setup is a no-op under the firewall. +RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/* diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/PROCESS_MANAGEMENT.md b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/PROCESS_MANAGEMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a72c175464128226fd62f2b875fba9c1e50e2c --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/PROCESS_MANAGEMENT.md @@ -0,0 +1,96 @@ +# Managing background processes — READ THIS before you `kill` anything + +You may start and stop background processes while iterating — a **server**, a long **build** or +**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill +*your own agent process* and end the whole run.** This has happened repeatedly, including via a +hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe. + +## The trap: matching task text against process command lines + +You were launched as roughly: + +``` +claude --print -- '' +``` + +The full task instruction is on **your own** process's command line, and it contains the file names +and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`). +So **any** command that finds processes by matching those strings will match — and can kill — **the +agent itself**: + +``` +pkill -9 -f "train.py" # matches the claude agent -> kills YOU +pgrep -f "server.py" | xargs kill # same: the pid list includes claude +for p in $(pgrep -f build.sh); do kill -9 $p; done # same +for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same +``` + +It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`, +a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or +the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies +immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually +worse than what you were about to finish. + +## The one safe rule: kill only the exact PID you recorded + +**Start** a background job and record its PID in a file: + +```bash +nohup > /tmp/job.log 2>&1 & +echo $! > /tmp/job.pid +``` + +**Stop / restart** by that exact PID — never by a name pattern: + +```bash +kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly +sleep 3 +kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit +``` + +If the job spawns workers, run it in its own process group and signal the group by its (negative) +PGID — still an exact id, never a pattern: + +```bash +setsid > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid +kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null +``` + +## If you ever enumerate processes, EXCLUDE the agent + +Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and +your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job +a unique name and match only that: + +```bash +# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text +pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST +# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print' +``` + +Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that +single addition re-introduces the self-kill. Match the unique token **only**. + +## Freeing the GPU without going nuclear + +If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet- +collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a +`/proc` sweep: + +- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after + the process fully exits. +- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a + single `kill $PID` is enough. +- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it. +- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after + confirming its cmdline is **not** `claude` / `--print`. + +## Rules of thumb + +- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …) + with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the + agent (its argv holds the prompt). +- **Always** kill a background job by the exact PID from its pidfile (or its PGID). +- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print` + and your own shell**; `pgrep -af` and look before you kill. +- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID. diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/build.sh b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..357f55e23f8935d722b8d834360ae4e1fe68d3cc --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Compile your solution against the harness and run one seed (the grader uses a different seed). +set -e +nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run +/app/run 0 diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/docker-compose.yaml b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b626bc85e10f49e564a9bb840c97b1fc5d66561f --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/docker-compose.yaml @@ -0,0 +1,17 @@ +# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose. +# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked). +# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has +# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it. +services: + main: + cap_add: + - NET_ADMIN + - SYS_ADMIN + entrypoint: ["/bin/bash", "/app/restrict-network.sh"] + environment: + - ALLOWED_HOSTS=${ALLOWED_HOSTS:-} + - OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-} + - OPENAI_BASE_URL=${OPENAI_BASE_URL:-} + - ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-} + - LLM_BASE_URL=${LLM_BASE_URL:-} + - LITELLM_BASE_URL=${LITELLM_BASE_URL:-} diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/harness.cu b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..52741756ea79ef17a75b4680a377c1986855f262 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/harness.cu @@ -0,0 +1,121 @@ +// Grading harness for cuda-warp-scan-segmented. +// y[r, j] = sum_{i <= j} x[r, i] -- an INCLUSIVE prefix sum along each row, independently. +// x[R, N] float32 row-major in, y[R, N] float32 row-major out. +// This is the cumulative log-decay a gated linear-attention / SSM layer builds along the sequence: +// every element of x is <= 0, so the running sum is monotone and there is no cancellation. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one thread per row, one sequential dependent add per element. +// Correctness is checked ELEMENTWISE as max |a-b| / (|b| + 1). The +1 floor keeps the head of the +// row (where the running sum is still tiny) from dominating, and the ratio keeps the tail honest: +// a parallel scan and this sequential one differ by ~6.6e-2 in absolute terms at the tail, which is +// 2e-5 relative -- 50x inside the gate -- while an off-by-one (exclusive) scan is 0.05, 50x outside. +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int R = 4096, N = 65536; // 2.7e8 elements: 1.07 GB in, 1.07 GB out +static const float RTOL = 1e-3f; // max of |a-b| / (|b| + 1) over ALL elements +#ifndef R_BAR +#define R_BAR 10.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void segmented_scan(const float* x, float* y, int R_, int N_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(float* x, long n, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u); + float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2); + x[i] = -expf(0.8f * g - 3.0f); // log-gate: always negative, typical magnitude ~0.05 + } +} + +// ---- naive reference: one thread per row, sequential scan ---------------------------------------- +__global__ void naive_kernel(const float* x, float* y, int R_, int N_){ + for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < R_; r += (long)gridDim.x * blockDim.x){ + const float* xr = x + r * (long)N_; + float* yr = y + r * (long)N_; + float acc = 0.f; + for(int j = 0; j < N_; j++){ acc += xr[j]; yr[j] = acc; } + } +} + +// ---- comparison: max scaled deviation ----------------------------------------------------------- +__global__ void cmp_kernel(const float* a, const float* b, long n, float* worst){ + float w = 0.f; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + float d = fabsf(a[i] - b[i]) / (fabsf(b[i]) + 1.0f); + if(!isfinite(d)) d = 1e30f; + w = fmaxf(w, d); + } + __shared__ float s[256]; + s[threadIdx.x] = w; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ + if(threadIdx.x < o) s[threadIdx.x] = fmaxf(s[threadIdx.x], s[threadIdx.x + o]); + __syncthreads(); + } + if(threadIdx.x == 0) atomicMax((int*)worst, __float_as_int(s[0])); // all values >= 0 +} + +typedef void(*Fn)(const float*, float*); +static float time_ms(Fn run, const float* a, float* b, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(a, b); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const float* a, float* b){ naive_kernel<<<64, 64>>>(a, b, R, N); } +static void run_agent(const float* a, float* b){ segmented_scan(a, b, R, N); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)R * N; + float *x, *yref, *yag, *worst; + CK(cudaMalloc(&x, n * 4)); CK(cudaMalloc(&yref, n * 4)); CK(cudaMalloc(&yag, n * 4)); + CK(cudaMalloc(&worst, 4)); CK(cudaMemset(worst, 0, 4)); CK(cudaMemset(yag, 0, n * 4)); + gen_kernel<<<1024, 256>>>(x, n, seed); + CK(cudaDeviceSynchronize()); + + run_naive(x, yref); CK(cudaDeviceSynchronize()); + run_agent(x, yag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(yag, yref, n, worst); + CK(cudaDeviceSynchronize()); + float hw; CK(cudaMemcpy(&hw, worst, 4, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, x, yref, 1, 3); + float ta = time_ms(run_agent, x, yag, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hw < RTOL); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("max_rel_err=%.3e (gate %.2e) | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | " + "correct=%d fast=%d -> reward=%.1f\n", hw, RTOL, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"max_rel_err\": %.3e, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hw, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/restrict-network.sh b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/restrict-network.sh new file mode 100644 index 0000000000000000000000000000000000000000..10f759d82f01fe8868baa01a7816d23deea150c1 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/restrict-network.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API +# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface, +# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone +# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is +# pre-installed (harbor's patched installer skips the network install when it is already present), so no +# package index is needed at run time. +# +# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they +# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN. +set -uo pipefail + +# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme). +API_HOSTS=( + openrouter.ai openrouter.io + api.openai.com api.anthropic.com generativelanguage.googleapis.com + api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com +) +# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …). +CUSTOM=() +while IFS='=' read -r n v; do + case "$n" in + *_BASE_URL|*_URL|*_ENDPOINT) + [ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;; + esac +done < <(env) +if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi +ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"}) + +if iptables -L OUTPUT -n >/dev/null 2>&1; then + echo "restrict-network: applying outbound allowlist firewall..." + iptables -F OUTPUT 2>/dev/null || true + iptables -A OUTPUT -o lo -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p udp --dport 53 -j ACCEPT + iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT + iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT + iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT + iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT + iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT + for h in "${ALL_HOSTS[@]}"; do + for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do + iptables -A OUTPUT -d "$ip" -j ACCEPT + done + done + iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked." +else + echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2 +fi + +exec "$@" diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/environment/solution.cu b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/solution.cu new file mode 100644 index 0000000000000000000000000000000000000000..5dec03ecd92b29b1b23d15ce8f24c18cdf8009f1 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/environment/solution.cu @@ -0,0 +1,16 @@ +// solution.cu — implement the segmented inclusive scan described in the instruction. +// y[r, j] = sum_{i <= j} x[r, i] for every row r, independently. +// x[R, N] and y[R, N] are float32 row-major. R = 4096, N = 65536 (fixed). Accumulate in fp32. +// Note it is INCLUSIVE: y[r, 0] == x[r, 0]. +// This stub writes zeros (it compiles and runs, but is incorrect — reward 0). +#include + +__global__ void stub_k(float* y, long n){ + long i = (long)blockIdx.x * blockDim.x + threadIdx.x; + if(i < n) y[i] = 0.f; +} + +void segmented_scan(const float* x, float* y, int R, int N){ + long n = (long)R * N; + stub_k<<<(n + 255) / 256, 256>>>(y, n); +} diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/instruction.md b/tasks/raw-cuda/cuda-warp-scan-segmented/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..532e5d6882566a6f462d2e2c89cbd99ef3a7f5da --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/instruction.md @@ -0,0 +1,62 @@ +# Write a fast CUDA kernel for a segmented (per-row) inclusive prefix sum + +Implement a high-performance CUDA kernel in `/app/solution.cu` that computes an **inclusive** prefix sum +along each row of a `float32` matrix — the cumulative log-decay a gated linear-attention or SSM layer builds +along its sequence before it can apply the decay to the state. + +Input: `x` of shape `[R, N]` (`float`, row-major). Output: `y` of shape `[R, N]` (`float`, row-major): + +``` +y[r, j] = sum over i = 0 .. j of x[r, i] # INCLUSIVE: y[r, 0] == x[r, 0] +``` + +Rows are independent. Every element of `x` is a log-gate and is **negative**, so each row's running sum is +monotone and there is no cancellation. The sizes are fixed: **R = 4096, N = 65536** — 1.07 GB in, 1.07 GB +out, and a row is 256 KB. + +The function signature (fixed) is in `/app/solution.cu`: +```cpp +void segmented_scan(const float* x, float* y, int R, int N); +``` + +## How success is decided + +The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and +checks: +1. **Correctness** — `max over all elements of |yours - ref| / (|ref| + 1)` below **1e-3**. That form is + deliberate: the running sum reaches ~-3300 by the end of a row, where fp32 summation *order* alone moves + the absolute value by ~6.6e-2 (the reference sums sequentially; any parallel scan sums as a tree), which + is 1.5e-5 in the graded ratio — **67x inside** the gate. An **exclusive** scan, by contrast, scores + **0.51**, 510x outside it. Reordering is free; being off by one element is not. +2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event + timed, warmup + median; the exact bar is printed when you build). + +Both must pass for reward 1.0. + +## Notes + +- The reference the bar is measured against is **one thread per row** doing `acc += x[j]; y[j] = acc;` — + a chain of 65536 dependent adds, with every access uncoalesced. Both problems have to go. +- A prefix sum looks serial but is not: the standard decomposition is per-thread serial scan → warp scan via + `__shfl_up_sync` → one small scan over the warp totals → add the offsets back. There are 4096 independent + rows, which is plenty of block-level parallelism, so you do **not** need a device-wide scan or a + decoupled-lookback scheme — but you do need the scan *within* a row to be parallel. +- A row is 256 KB, so a block sweeps it in chunks carrying a running total from one chunk to the next. Doing + that in **one** pass — read the chunk, scan it, add the carry, write it — is the difference between 2.15 GB + of traffic and the 4 GB+ that a "scan the block sums into a scratch array, then run a second kernel to add + them" structure costs. CUB's device-wide scan is available and is a reasonable thing to measure yourself + against, but it is solving a harder problem than you have. +- Vectorise: `float4` loads and stores move 4 elements per access, and the serial scan of those 4 elements + inside a thread is free. +- Watch the barriers. A chunked scan needs a `__syncthreads()` around the shared-memory warp-total scan and + another before the carry is updated; a sloppy version ends up with four or five per chunk, and at this size + the barrier count is visible in the profile. +- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer** + (`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA, including `BlockScan` and `WarpScan`), and the + profilers **`ncu`** and **`nsys`**. There is **no PyTorch and no Triton**; this is a pure CUDA task. +- Query the device with `cudaGetDeviceProperties` and size the grid from the SM count you find rather than + from a constant. +- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader + uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how + you are measured; you only edit `solution.cu`. +- **No internet access.** diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/solution/solution.oracle.cu b/tasks/raw-cuda/cuda-warp-scan-segmented/solution/solution.oracle.cu new file mode 100644 index 0000000000000000000000000000000000000000..008ec2feb9c546ee0a6928615344459f0a88b4bf --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/solution/solution.oracle.cu @@ -0,0 +1,62 @@ +// Oracle: one block per row; the row is swept in 128-bit-loaded chunks with a running carry. +// per thread : serial scan of its 4 elements (float4) +// per warp : shfl_up inclusive scan of the 4-element totals +// per block : one shared-memory scan over the warp totals +// carry : the block total is added into a running carry for the next chunk +// One read and one write of the row, no scratch buffer, no second kernel. +#include + +#define NTHREAD 256 +#define VPT 4 // float4 +#define NWARP (NTHREAD / 32) + +__global__ __launch_bounds__(NTHREAD) void scan_k(const float* __restrict__ x, float* __restrict__ y, int N){ + const long row = blockIdx.x; + const float4* xr = reinterpret_cast(x + row * (long)N); + float4* yr = reinterpret_cast(y + row * (long)N); + const int nvec = N / VPT; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + + __shared__ float wsum[NWARP]; + __shared__ float carry_s; + if(threadIdx.x == 0) carry_s = 0.f; + __syncthreads(); + + for(int base = 0; base < nvec; base += NTHREAD){ + int i = base + threadIdx.x; + float4 v = (i < nvec) ? xr[i] : make_float4(0.f, 0.f, 0.f, 0.f); + // serial scan within the thread + v.y += v.x; v.z += v.y; v.w += v.z; + float t = v.w; + // inclusive warp scan of the per-thread totals + #pragma unroll + for(int o = 1; o < 32; o <<= 1){ + float u = __shfl_up_sync(0xffffffff, t, o); + if(lane >= o) t += u; + } + if(lane == 31) wsum[warp] = t; + __syncthreads(); + if(threadIdx.x < 32){ // scan the warp totals (NWARP <= 32) + float w = (threadIdx.x < NWARP) ? wsum[threadIdx.x] : 0.f; + #pragma unroll + for(int o = 1; o < 32; o <<= 1){ + float u = __shfl_up_sync(0xffffffff, w, o); + if((int)threadIdx.x >= o) w += u; + } + if(threadIdx.x < NWARP) wsum[threadIdx.x] = w; + } + __syncthreads(); + float off = carry_s + (warp ? wsum[warp - 1] : 0.f) + (t - v.w); // exclusive prefix + if(i < nvec){ + v.x += off; v.y += off; v.z += off; v.w += off; + yr[i] = v; + } + __syncthreads(); + if(threadIdx.x == 0) carry_s += wsum[NWARP - 1]; + __syncthreads(); + } +} + +void segmented_scan(const float* x, float* y, int R, int N){ + scan_k<<>>(x, y, N); +} diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/solution/solve.sh b/tasks/raw-cuda/cuda-warp-scan-segmented/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b89ff07c3051e12470f30846d5ac4a296c1bbfc --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/solution/solve.sh @@ -0,0 +1,68 @@ +#!/bin/bash +# Oracle: restore the reference fast kernel. +set -e +cat > /app/solution.cu <<'ORACLE_CU_EOF' +// Oracle: one block per row; the row is swept in 128-bit-loaded chunks with a running carry. +// per thread : serial scan of its 4 elements (float4) +// per warp : shfl_up inclusive scan of the 4-element totals +// per block : one shared-memory scan over the warp totals +// carry : the block total is added into a running carry for the next chunk +// One read and one write of the row, no scratch buffer, no second kernel. +#include + +#define NTHREAD 256 +#define VPT 4 // float4 +#define NWARP (NTHREAD / 32) + +__global__ __launch_bounds__(NTHREAD) void scan_k(const float* __restrict__ x, float* __restrict__ y, int N){ + const long row = blockIdx.x; + const float4* xr = reinterpret_cast(x + row * (long)N); + float4* yr = reinterpret_cast(y + row * (long)N); + const int nvec = N / VPT; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + + __shared__ float wsum[NWARP]; + __shared__ float carry_s; + if(threadIdx.x == 0) carry_s = 0.f; + __syncthreads(); + + for(int base = 0; base < nvec; base += NTHREAD){ + int i = base + threadIdx.x; + float4 v = (i < nvec) ? xr[i] : make_float4(0.f, 0.f, 0.f, 0.f); + // serial scan within the thread + v.y += v.x; v.z += v.y; v.w += v.z; + float t = v.w; + // inclusive warp scan of the per-thread totals + #pragma unroll + for(int o = 1; o < 32; o <<= 1){ + float u = __shfl_up_sync(0xffffffff, t, o); + if(lane >= o) t += u; + } + if(lane == 31) wsum[warp] = t; + __syncthreads(); + if(threadIdx.x < 32){ // scan the warp totals (NWARP <= 32) + float w = (threadIdx.x < NWARP) ? wsum[threadIdx.x] : 0.f; + #pragma unroll + for(int o = 1; o < 32; o <<= 1){ + float u = __shfl_up_sync(0xffffffff, w, o); + if((int)threadIdx.x >= o) w += u; + } + if(threadIdx.x < NWARP) wsum[threadIdx.x] = w; + } + __syncthreads(); + float off = carry_s + (warp ? wsum[warp - 1] : 0.f) + (t - v.w); // exclusive prefix + if(i < nvec){ + v.x += off; v.y += off; v.z += off; v.w += off; + yr[i] = v; + } + __syncthreads(); + if(threadIdx.x == 0) carry_s += wsum[NWARP - 1]; + __syncthreads(); + } +} + +void segmented_scan(const float* x, float* y, int R, int N){ + scan_k<<>>(x, y, N); +} +ORACLE_CU_EOF +echo restored diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/task.toml b/tasks/raw-cuda/cuda-warp-scan-segmented/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..71c61ef39bb1cb48e8e0101d7992f4557db750e1 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/task.toml @@ -0,0 +1,36 @@ +schema_version = "1.1" + +[task] +name = "mle-bench/cuda-warp-scan-segmented" +description = "Write a fast hand-written CUDA kernel for a segmented (per-row) inclusive prefix sum over fp32 [4096, 65536] -- the cumulative log-decay of a gated linear-attention/SSM layer -- beating a one-thread-per-row sequential-scan reference by a calibrated margin. The win is a parallel scan inside each row (per-thread serial scan, shfl_up warp scan, one scan over warp totals) swept in float4 chunks with a running carry, in a single read+write pass rather than a scratch-buffer two-kernel scan. Correctness is elementwise-scaled so fp32 reordering is free but an exclusive (off-by-one) scan fails by 510x. Hand-written CUDA only (CUTLASS/flashinfer/CUB); no PyTorch/Triton; ncu/nsys available." +authors = [] +keywords = [ "mle", "kernel-generation", "cuda", "scan", "prefix-sum", "warp-shuffle", "bandwidth", "gpu",] + +[metadata] +suite = "mle-bench" +group = "kernel-generation" +level = "1.0" +difficulty = "hard" +category = "mle" +tags = [ "mle", "kernel-generation", "cuda", "gpu", "performance", "real-world",] + +[verifier] +timeout_sec = 600.0 + +[agent] +timeout_sec = 14400.0 + +[environment] +build_timeout_sec = 3600.0 +cpus = 8 +memory_mb = 32768 +storage_mb = 40960 +gpus = 1 +network_mode = "public" +mcp_servers = [] + +[verifier.env] + +[environment.env] + +[solution.env] diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/tests/harness.cu b/tasks/raw-cuda/cuda-warp-scan-segmented/tests/harness.cu new file mode 100644 index 0000000000000000000000000000000000000000..52741756ea79ef17a75b4680a377c1986855f262 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/tests/harness.cu @@ -0,0 +1,121 @@ +// Grading harness for cuda-warp-scan-segmented. +// y[r, j] = sum_{i <= j} x[r, i] -- an INCLUSIVE prefix sum along each row, independently. +// x[R, N] float32 row-major in, y[R, N] float32 row-major out. +// This is the cumulative log-decay a gated linear-attention / SSM layer builds along the sequence: +// every element of x is <= 0, so the running sum is monotone and there is no cancellation. +// Inputs are generated ON DEVICE from the seed (deterministic and fast). +// The naive reference is one thread per row, one sequential dependent add per element. +// Correctness is checked ELEMENTWISE as max |a-b| / (|b| + 1). The +1 floor keeps the head of the +// row (where the running sum is still tiny) from dominating, and the ratio keeps the tail honest: +// a parallel scan and this sequential one differ by ~6.6e-2 in absolute terms at the tail, which is +// 2e-5 relative -- 50x inside the gate -- while an off-by-one (exclusive) scan is 0.05, 50x outside. +#include +#include +#include +#include +#include +#include + +#define CK(x) do{ cudaError_t e=(x); if(e!=cudaSuccess){ printf("CUDA err %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); exit(2);} }while(0) + +static const int R = 4096, N = 65536; // 2.7e8 elements: 1.07 GB in, 1.07 GB out +static const float RTOL = 1e-3f; // max of |a-b| / (|b| + 1) over ALL elements +#ifndef R_BAR +#define R_BAR 10.0f +#endif + +// ---- the agent's kernel ------------------------------------------------------------------------ +void segmented_scan(const float* x, float* y, int R_, int N_); + +// ---- deterministic device-side input generation ------------------------------------------------- +__device__ __forceinline__ unsigned mix(unsigned a){ + a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a; +} +__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); } + +__global__ void gen_kernel(float* x, long n, unsigned seed){ + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed); + float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u); + float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2); + x[i] = -expf(0.8f * g - 3.0f); // log-gate: always negative, typical magnitude ~0.05 + } +} + +// ---- naive reference: one thread per row, sequential scan ---------------------------------------- +__global__ void naive_kernel(const float* x, float* y, int R_, int N_){ + for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < R_; r += (long)gridDim.x * blockDim.x){ + const float* xr = x + r * (long)N_; + float* yr = y + r * (long)N_; + float acc = 0.f; + for(int j = 0; j < N_; j++){ acc += xr[j]; yr[j] = acc; } + } +} + +// ---- comparison: max scaled deviation ----------------------------------------------------------- +__global__ void cmp_kernel(const float* a, const float* b, long n, float* worst){ + float w = 0.f; + for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){ + float d = fabsf(a[i] - b[i]) / (fabsf(b[i]) + 1.0f); + if(!isfinite(d)) d = 1e30f; + w = fmaxf(w, d); + } + __shared__ float s[256]; + s[threadIdx.x] = w; + __syncthreads(); + for(int o = blockDim.x >> 1; o; o >>= 1){ + if(threadIdx.x < o) s[threadIdx.x] = fmaxf(s[threadIdx.x], s[threadIdx.x + o]); + __syncthreads(); + } + if(threadIdx.x == 0) atomicMax((int*)worst, __float_as_int(s[0])); // all values >= 0 +} + +typedef void(*Fn)(const float*, float*); +static float time_ms(Fn run, const float* a, float* b, int warm, int iters){ + cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1)); + for(int i = 0; i < warm; i++) run(a, b); + CK(cudaDeviceSynchronize()); + std::vector ts; + for(int i = 0; i < iters; i++){ + CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1)); + CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms); + } + std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2]; +} +static void run_naive(const float* a, float* b){ naive_kernel<<<64, 64>>>(a, b, R, N); } +static void run_agent(const float* a, float* b){ segmented_scan(a, b, R, N); } + +int main(int argc, char** argv){ + unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u; + long n = (long)R * N; + float *x, *yref, *yag, *worst; + CK(cudaMalloc(&x, n * 4)); CK(cudaMalloc(&yref, n * 4)); CK(cudaMalloc(&yag, n * 4)); + CK(cudaMalloc(&worst, 4)); CK(cudaMemset(worst, 0, 4)); CK(cudaMemset(yag, 0, n * 4)); + gen_kernel<<<1024, 256>>>(x, n, seed); + CK(cudaDeviceSynchronize()); + + run_naive(x, yref); CK(cudaDeviceSynchronize()); + run_agent(x, yag); CK(cudaDeviceSynchronize()); + cudaError_t ge = cudaGetLastError(); + + cmp_kernel<<<1024, 256>>>(yag, yref, n, worst); + CK(cudaDeviceSynchronize()); + float hw; CK(cudaMemcpy(&hw, worst, 4, cudaMemcpyDeviceToHost)); + + float tn = time_ms(run_naive, x, yref, 1, 3); + float ta = time_ms(run_agent, x, yag, 5, 30); + float sp = tn / ta; + bool correct = (ge == cudaSuccess) && (hw < RTOL); + bool fast = sp >= R_BAR; + double reward = (correct && fast) ? 1.0 : 0.0; + printf("max_rel_err=%.3e (gate %.2e) | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | " + "correct=%d fast=%d -> reward=%.1f\n", hw, RTOL, tn, ta, sp, (float)R_BAR, correct, fast, reward); + if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge)); + system("mkdir -p /logs/verifier"); + FILE* f = fopen("/logs/verifier/reward.json", "w"); + if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"max_rel_err\": %.3e, " + "\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n", + reward, correct, fast, hw, tn, ta, sp); fclose(f); } + FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); } + return 0; +} diff --git a/tasks/raw-cuda/cuda-warp-scan-segmented/tests/test.sh b/tasks/raw-cuda/cuda-warp-scan-segmented/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..18efdf3a3a726f0f80160d553ce52bc77c051af4 --- /dev/null +++ b/tasks/raw-cuda/cuda-warp-scan-segmented/tests/test.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Verifier: compile the FRESH harness + the agent's solution, grade with a random seed. +set -uo pipefail +mkdir -p /logs/verifier +SEED=$(( (RANDOM << 15) ^ RANDOM )) +nvcc -O3 -arch=native /tests/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /tmp/grade 2>/tmp/nvcc.log +if [ ! -x /tmp/grade ]; then + echo "COMPILE FAILED:"; tail -20 /tmp/nvcc.log + echo "0.0" > /logs/verifier/reward.txt + echo '{"reward": 0.0, "error": "compile_failed"}' > /logs/verifier/reward.json + exit 0 +fi +/tmp/grade "$SEED" # the harness writes /logs/verifier/reward.{txt,json} +cat /logs/verifier/reward.json 2>/dev/null || true diff --git a/tasks/sampling-speculative-decoding/README.md b/tasks/sampling-speculative-decoding/README.md index d8692753fae2b9f0d0c5dbcad85859285931566c..599cde35719528d46cdb540b6430f9902133eef2 100644 --- a/tasks/sampling-speculative-decoding/README.md +++ b/tasks/sampling-speculative-decoding/README.md @@ -2,7 +2,7 @@ Top-k/top-p/min-p filtering, beam search, and speculative decoding. -**9 tasks.** +**10 tasks.** | task | metric | roofline | what the kernel does | |---|---|---|---| @@ -12,6 +12,7 @@ Top-k/top-p/min-p filtering, beam search, and speculative decoding. | [`guided-decoding-mask`](guided-decoding-mask/) | GB/s | 317 us | Structured / JSON-mode decoding constrains every sampling step to the tokens a grammar FSM currently allows. Each sequence in the batch sits… | | [`min-p-sampling-filter`](min-p-sampling-filter/) | GB/s | 417 us | Min-p truncation keeps every token whose probability is at least `min_p` times the most likely token's — a scale-free alternative to top-p t… | | [`ngram-lookahead-match`](ngram-lookahead-match/) | GB/s | 300 us | Prompt-lookup decoding drafts speculative tokens with no draft model at all: take the last n tokens of a sequence, find where that n-gram la… | +| [`penalty-count-bincount-build`](penalty-count-bincount-build/) | GB/s | 418 us | Presence, frequency and repetition penalties need, for every sequence in the batch, how often each vocabulary entry occurs in its prompt and… | | [`repetition-penalty-logits`](repetition-penalty-logits/) | GB/s | 625 us | Before sampling, a serving engine rewrites the whole logit matrix with three per-request penalties driven by per-sequence token-count histog… | | [`spec-decode-tree-attention`](spec-decode-tree-attention/) | TFLOP/s | 792 us | Speculative decoding verifies a TREE of draft tokens in one forward pass. Each draft token attends to the whole KV cache plus only its own a… | | [`spec-decode-verify-accept`](spec-decode-verify-accept/) | GB/s | 469 us | After the target model scores a draft path, every speculative-decoding stack runs the rejection-sampling rule that decides how many draft to… |