Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 14)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/RUN.md +42 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/CLAUDE.md +25 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/Dockerfile +41 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/docker-compose.yaml +18 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/measure.py +131 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/reference.py +27 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/restrict-network.sh +52 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/shared_qkv_bwd.py +28 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/instruction.md +213 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/task.toml +38 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/test.sh +5 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/verify_env.py +197 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/RUN.md +42 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/CLAUDE.md +25 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/Dockerfile +41 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/docker-compose.yaml +18 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/measure.py +121 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/reference.py +24 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/restrict-network.sh +52 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/shared_qkv.py +26 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/instruction.md +199 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/task.toml +38 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/test.sh +5 -0
- tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/verify_env.py +184 -0
- tasks/raw-cuda/README.md +7 -1
- tasks/raw-cuda/cuda-blockwise-softmax/environment/CLAUDE.md +25 -0
- tasks/raw-cuda/cuda-blockwise-softmax/environment/Dockerfile +34 -0
- tasks/raw-cuda/cuda-blockwise-softmax/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/raw-cuda/cuda-blockwise-softmax/environment/build.sh +5 -0
- tasks/raw-cuda/cuda-blockwise-softmax/environment/docker-compose.yaml +17 -0
- tasks/raw-cuda/cuda-blockwise-softmax/environment/harness.cu +128 -0
- tasks/raw-cuda/cuda-blockwise-softmax/environment/restrict-network.sh +52 -0
- tasks/raw-cuda/cuda-blockwise-softmax/environment/solution.cu +18 -0
- tasks/raw-cuda/cuda-blockwise-softmax/instruction.md +64 -0
- tasks/raw-cuda/cuda-blockwise-softmax/solution/solution.oracle.cu +65 -0
- tasks/raw-cuda/cuda-blockwise-softmax/solution/solve.sh +71 -0
- tasks/raw-cuda/cuda-blockwise-softmax/task.toml +36 -0
- tasks/raw-cuda/cuda-blockwise-softmax/tests/harness.cu +128 -0
- tasks/raw-cuda/cuda-blockwise-softmax/tests/test.sh +14 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/CLAUDE.md +25 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/Dockerfile +34 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/build.sh +5 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/docker-compose.yaml +17 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/harness.cu +145 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/restrict-network.sh +52 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/environment/solution.cu +20 -0
- tasks/raw-cuda/cuda-fp8-cast-pack/instruction.md +61 -0
tasks/quantization-gemm/zamba-shared-attn-lora-backward/RUN.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Running `zamba-shared-attn-lora-backward`
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
| | |
|
| 6 |
+
|---|---|
|
| 7 |
+
| **Task id** | `mle-bench/zamba-shared-attn-lora-backward` |
|
| 8 |
+
| **Group** | `kernel-generation` |
|
| 9 |
+
| **GPUs** | 1 |
|
| 10 |
+
| **Agent edits** | `/app/shared_qkv_bwd.py` |
|
| 11 |
+
| **Score** | achieved **TFLOP/s** (uncapped speed leaderboard), `0` if incorrect |
|
| 12 |
+
| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
|
| 13 |
+
|
| 14 |
+
## Run through harbor
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
harbor run --dataset-path kernel-generation/kernels/zamba-shared-attn-lora-backward --task-name zamba-shared-attn-lora-backward \
|
| 18 |
+
--agent claude-code --model anthropic/claude-opus-4-1 -e docker
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Run manually
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
cd kernel-generation/kernels/zamba-shared-attn-lora-backward
|
| 25 |
+
docker build -t zamba-shared-attn-lora-backward environment/
|
| 26 |
+
docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep zamba-shared-attn-lora-backward infinity
|
| 27 |
+
docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
|
| 28 |
+
docker rm -f v
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Use an **idle** GPU: the score is a timing measurement.
|
| 32 |
+
|
| 33 |
+
## Design
|
| 34 |
+
|
| 35 |
+
Correctness is a hard gate; the score is an absolute hardware metric (TFLOP/s), so the task is
|
| 36 |
+
hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
|
| 37 |
+
|
| 38 |
+
Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
|
| 39 |
+
copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
|
| 40 |
+
with the timed output itself validated, so memoize-and-replay fails the gate.
|
| 41 |
+
|
| 42 |
+
Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/Dockerfile
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kernel-generation task: Write a fast backward kernel for the shared-attention-block QKV projection
|
| 2 |
+
#
|
| 3 |
+
# 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.
|
| 4 |
+
#
|
| 5 |
+
# SCORING: correctness is a hard gate; the score is achieved TFLOP/s (uncapped leaderboard, 0 if wrong).
|
| 6 |
+
# There is no gold solution and no oracle, so nothing has to be vendored or sealed.
|
| 7 |
+
#
|
| 8 |
+
# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
|
| 9 |
+
# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
|
| 10 |
+
# there is no internet, so nothing else can be obtained.
|
| 11 |
+
#
|
| 12 |
+
# GENERATED by _factory/build.py.
|
| 13 |
+
FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
|
| 14 |
+
|
| 15 |
+
# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
|
| 16 |
+
# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
|
| 17 |
+
RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
|
| 18 |
+
apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
|
| 19 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 20 |
+
/root/.local/bin/uv tool install mini-swe-agent
|
| 21 |
+
# header-only CUTLASS for the agent's CUDA/CuTe route
|
| 22 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
|
| 23 |
+
# pre-bake Claude Code; harbor's claude_code.install() skips when present
|
| 24 |
+
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
|
| 25 |
+
apt-get install -y nodejs procps && \
|
| 26 |
+
npm install -g @anthropic-ai/claude-code && claude --version
|
| 27 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 28 |
+
ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
|
| 29 |
+
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
|
| 33 |
+
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
|
| 34 |
+
|
| 35 |
+
WORKDIR /app
|
| 36 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 37 |
+
|
| 38 |
+
# task-specific files LAST so the layers above stay shared across every task
|
| 39 |
+
COPY reference.py /app/reference.py
|
| 40 |
+
COPY measure.py /app/measure.py
|
| 41 |
+
COPY shared_qkv_bwd.py /app/shared_qkv_bwd.py
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
|
| 2 |
+
# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
|
| 3 |
+
# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
|
| 4 |
+
# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
|
| 5 |
+
# the (now-blocked) network install when it is already present.
|
| 6 |
+
services:
|
| 7 |
+
main:
|
| 8 |
+
cap_add:
|
| 9 |
+
- NET_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
|
| 14 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 15 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 16 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 17 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 18 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/measure.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-assessment tool — your correctness + achieved TFLOP/s across a RANGE of shapes.
|
| 2 |
+
|
| 3 |
+
python /app/measure.py # the graded regime
|
| 4 |
+
python /app/measure.py --quick # smaller sizes for fast iteration
|
| 5 |
+
|
| 6 |
+
You are scored on the **geomean achieved TFLOP/s** — NOT one fixed size, and the leaderboard is UNCAPPED
|
| 7 |
+
(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
|
| 8 |
+
optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
|
| 9 |
+
printed here is computed exactly as your score is.
|
| 10 |
+
|
| 11 |
+
GENERATED by _factory/build.py.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import math
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, "/app")
|
| 20 |
+
from reference import shared_qkv_backward as _ref
|
| 21 |
+
from shared_qkv_bwd import shared_qkv_backward as _agent
|
| 22 |
+
|
| 23 |
+
TOL = 0.006
|
| 24 |
+
NAMES = ('dh', 'demb', 'dlora_a', 'dlora_b')
|
| 25 |
+
|
| 26 |
+
FULL = [(6, 3584, 2048, 64), (4, 3584, 2560, 64), (8, 1792, 2048, 32), (6, 2560, 2048, 128), (4, 5120, 2048, 64)]
|
| 27 |
+
QUICK = [(4, 512, 1024, 32), (2, 1024, 512, 16), (6, 256, 1024, 64)]
|
| 28 |
+
|
| 29 |
+
def canonical_work(L, T, Dm, r):
|
| 30 |
+
"""FLOPs attributed to one backward call, from the SHAPE ALONE.
|
| 31 |
+
|
| 32 |
+
Per depth, at 2 FLOPs per multiply-add:
|
| 33 |
+
* ONE pass of the big shared shape: dxc = dqkv @ w_qkv (the base weight is frozen,
|
| 34 |
+
so there is no dw_qkv and no second pass over it)
|
| 35 |
+
* THREE passes of the (2*Dm, r) adapter shape: recompute mid = xc @ lora_a.T (the LoRA output is a
|
| 36 |
+
forward temporary), dxc += dmid @ lora_a, dlora_a = dmid.T @ xc
|
| 37 |
+
* TWO passes of the (3*Dm, r) adapter shape: dmid = dqkv @ lora_b, dlora_b = dqkv.T @ mid
|
| 38 |
+
The concatenation, the split of dxc and the sum of demb over depths are O(L*T*Dm) data movement and
|
| 39 |
+
are not credited.
|
| 40 |
+
"""
|
| 41 |
+
return L * (2 * T * (2 * Dm) * (3 * Dm)
|
| 42 |
+
+ 3 * (2 * T * (2 * Dm) * r)
|
| 43 |
+
+ 2 * (2 * T * (3 * Dm) * r))
|
| 44 |
+
|
| 45 |
+
def _mk(L, T, Dm, r, seed):
|
| 46 |
+
"""Saved forward inputs plus the incoming gradient. The adapters are scaled so the LoRA delta is a real
|
| 47 |
+
but minority part of the forward (RMS `16/r` of the base projection), which is what a trained LoRA
|
| 48 |
+
looks like."""
|
| 49 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 50 |
+
|
| 51 |
+
def rnd(*sh, s=1.0):
|
| 52 |
+
return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
|
| 53 |
+
|
| 54 |
+
h = rnd(L, T, Dm)
|
| 55 |
+
emb = rnd(T, Dm)
|
| 56 |
+
w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 57 |
+
lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 58 |
+
lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5)
|
| 59 |
+
dqkv = rnd(L, T, 3 * Dm)
|
| 60 |
+
return h, emb, w_qkv, lora_a, lora_b, 16.0 / r, dqkv
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _check(out, ref):
|
| 64 |
+
"""-> (ok, value, msg). value = MAX relative error across the returned tuple."""
|
| 65 |
+
if out is None or len(out) != len(NAMES):
|
| 66 |
+
return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
|
| 67 |
+
per = []
|
| 68 |
+
for n, a, b in zip(NAMES, out, ref):
|
| 69 |
+
if a is None or tuple(a.shape) != tuple(b.shape):
|
| 70 |
+
return False, 1.0, f"{n} bad shape"
|
| 71 |
+
if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
|
| 72 |
+
# exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
|
| 73 |
+
bad = int((a != b).sum())
|
| 74 |
+
if bad:
|
| 75 |
+
return False, 1.0, f"{n}: {bad} elements differ"
|
| 76 |
+
continue
|
| 77 |
+
per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
|
| 78 |
+
if not per:
|
| 79 |
+
return True, 0.0, "all integer outputs exact"
|
| 80 |
+
wn, wv = max(per, key=lambda x: x[1])
|
| 81 |
+
return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _bench(fn, reps=8, warm=3):
|
| 85 |
+
for _ in range(warm):
|
| 86 |
+
fn()
|
| 87 |
+
torch.cuda.synchronize()
|
| 88 |
+
best = float("inf")
|
| 89 |
+
for _ in range(reps):
|
| 90 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 91 |
+
s.record()
|
| 92 |
+
fn()
|
| 93 |
+
e.record()
|
| 94 |
+
torch.cuda.synchronize()
|
| 95 |
+
best = min(best, s.elapsed_time(e))
|
| 96 |
+
return best / 1e3
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main():
|
| 100 |
+
ap = argparse.ArgumentParser()
|
| 101 |
+
ap.add_argument("--quick", action="store_true")
|
| 102 |
+
a = ap.parse_args()
|
| 103 |
+
shapes = QUICK if a.quick else FULL
|
| 104 |
+
print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
|
| 105 |
+
f"DIFFERENT sizes in the same regime — optimize for generality\n")
|
| 106 |
+
vals, allok = [], True
|
| 107 |
+
for shp in shapes:
|
| 108 |
+
args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
|
| 109 |
+
ref = _ref(*args)
|
| 110 |
+
try:
|
| 111 |
+
out = _agent(*args)
|
| 112 |
+
except Exception as ex:
|
| 113 |
+
print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
|
| 114 |
+
allok = False
|
| 115 |
+
continue
|
| 116 |
+
ok, val, msg = _check(out, ref)
|
| 117 |
+
allok = allok and ok
|
| 118 |
+
t = _bench(lambda: _agent(*args))
|
| 119 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 120 |
+
vals.append(v)
|
| 121 |
+
print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} TFLOP/s | {msg} {'ok' if ok else 'FAIL'}")
|
| 122 |
+
del args, ref, out
|
| 123 |
+
torch.cuda.empty_cache()
|
| 124 |
+
geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
|
| 125 |
+
print(f"\n => GEOMEAN {geo:.2f} TFLOP/s "
|
| 126 |
+
f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
|
| 127 |
+
print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
main()
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/reference.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference implementation — the CORRECTNESS SPEC for `shared_qkv_backward`.
|
| 2 |
+
|
| 3 |
+
This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
|
| 4 |
+
bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _shared_qkv(h, emb, w_qkv, lora_a, lora_b, scaling):
|
| 10 |
+
"""The fp32 forward of `zamba-shared-attn-lora-qkv`, differentiable. Autograd through THIS defines
|
| 11 |
+
every gradient this task asks for."""
|
| 12 |
+
L, T, Dm = h.shape
|
| 13 |
+
outs = []
|
| 14 |
+
for l in range(L):
|
| 15 |
+
xc = torch.cat([h[l], emb], dim=-1) # (T, 2*Dm) [state | embedding]
|
| 16 |
+
base = xc @ w_qkv.t()
|
| 17 |
+
delta = (xc @ lora_a[l].t()) @ lora_b[l].t()
|
| 18 |
+
outs.append(base + scaling * delta)
|
| 19 |
+
return torch.stack(outs, 0)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv):
|
| 23 |
+
"""The baseline re-runs the fp32 forward under autograd. The shared weight is FROZEN: only the two
|
| 24 |
+
activations and the L adapters receive gradients."""
|
| 25 |
+
ins = [t.detach().clone().float().requires_grad_(True) for t in (h, emb, lora_a, lora_b)]
|
| 26 |
+
o = _shared_qkv(ins[0], ins[1], w_qkv.float(), ins[2], ins[3], scaling)
|
| 27 |
+
return torch.autograd.grad(o, ins, dqkv.float())
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
|
| 5 |
+
# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
|
| 6 |
+
# installer skips the network install when it is already present), so no package index is needed at run time.
|
| 7 |
+
#
|
| 8 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
|
| 9 |
+
# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
|
| 12 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 13 |
+
API_HOSTS=(
|
| 14 |
+
api.fireworks.ai
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/environment/shared_qkv_bwd.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Your implementation goes here.
|
| 2 |
+
|
| 3 |
+
Replace the body of `shared_qkv_backward` with a FAST implementation that reproduces the output of /app/reference.py
|
| 4 |
+
(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
|
| 5 |
+
Run `python /app/measure.py` to check your correctness and achieved TFLOP/s.
|
| 6 |
+
|
| 7 |
+
You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
|
| 8 |
+
signature and returned value are fixed by the contract.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv):
|
| 13 |
+
"""Backward of the shared attention-block QKV projection (frozen base, L LoRA adapters).
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
h: (L, T, Dm) bfloat16 — residual stream at each depth, saved by the forward.
|
| 17 |
+
emb: (T, Dm) bfloat16 — the shared original embedding, saved by the forward.
|
| 18 |
+
w_qkv: (3*Dm, 2*Dm) bfloat16 — the shared projection. FROZEN: no gradient is returned for it.
|
| 19 |
+
lora_a: (L, r, 2*Dm) bfloat16 — per-depth LoRA down-projection.
|
| 20 |
+
lora_b: (L, 3*Dm, r) bfloat16 — per-depth LoRA up-projection.
|
| 21 |
+
scaling: float — the LoRA scale (alpha / r).
|
| 22 |
+
dqkv: (L, T, 3*Dm) bfloat16 — incoming gradient w.r.t. the fused QKV output.
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
(dh, demb, dlora_a, dlora_b) with shapes
|
| 26 |
+
(L, T, Dm), (T, Dm), (L, r, 2*Dm), (L, 3*Dm, r).
|
| 27 |
+
"""
|
| 28 |
+
raise NotImplementedError("Implement a fast shared_qkv_backward in /app/shared_qkv_bwd.py")
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/instruction.md
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast backward kernel for the shared-attention-block QKV projection
|
| 2 |
+
|
| 3 |
+
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.**
|
| 4 |
+
|
| 5 |
+
Write **`/app/shared_qkv_bwd.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
def shared_qkv_backward(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv):
|
| 9 |
+
...
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## The computation (this is the exact spec)
|
| 13 |
+
|
| 14 |
+
The forward being differentiated is the shared attention block's QKV projection, called at
|
| 15 |
+
`L` depths with one shared weight and a per-depth LoRA adapter:
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
xc[l] = concat( h[l], emb ) # (T, 2*Dm), state first
|
| 19 |
+
mid[l] = xc[l] @ lora_a[l].T # (T, r)
|
| 20 |
+
qkv[l] = xc[l] @ w_qkv.T + scaling * mid[l] @ lora_b[l].T
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
`w_qkv` is **frozen** — this is adapter fine-tuning, so no gradient is produced for it and it is never
|
| 24 |
+
transposed-reduced over the token axis. Given `dqkv` you must return four things:
|
| 25 |
+
|
| 26 |
+
```
|
| 27 |
+
dmid[l] = scaling * ( dqkv[l] @ lora_b[l] ) # (T, r)
|
| 28 |
+
dxc[l] = dqkv[l] @ w_qkv + dmid[l] @ lora_a[l] # (T, 2*Dm)
|
| 29 |
+
dlora_a[l] = dmid[l].T @ xc[l] # (r, 2*Dm)
|
| 30 |
+
dlora_b[l] = scaling * ( dqkv[l].T @ mid[l] ) # (3*Dm, r)
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
and then the concatenation is undone:
|
| 34 |
+
|
| 35 |
+
```
|
| 36 |
+
dh[l] = dxc[l][:, :Dm]
|
| 37 |
+
demb = sum over ALL l of dxc[l][:, Dm:]
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
**`demb` is a sum over every depth.** The same embedding tensor was fed to all `L` invocations, so its
|
| 41 |
+
gradient collects a contribution from each one — this is the piece that makes the backward of a *shared*
|
| 42 |
+
block different from `L` independent backwards.
|
| 43 |
+
|
| 44 |
+
Note that `mid[l]` was a forward temporary and is not an argument: `dlora_b` needs it, so it must be
|
| 45 |
+
recomputed.
|
| 46 |
+
|
| 47 |
+
`/app/reference.py` re-runs the fp32 forward under autograd and differentiates it. That is the exact
|
| 48 |
+
specification; it is deliberately simple rather than fast.
|
| 49 |
+
|
| 50 |
+
## The contract (fixed — do not change these)
|
| 51 |
+
|
| 52 |
+
| arg | shape | dtype | meaning |
|
| 53 |
+
|-----|-------|-------|---------|
|
| 54 |
+
| `h` | `(L, T, Dm)` | `bfloat16` | residual stream at each depth |
|
| 55 |
+
| `emb` | `(T, Dm)` | `bfloat16` | shared original embedding |
|
| 56 |
+
| `w_qkv` | `(3*Dm, 2*Dm)` | `bfloat16` | shared projection, **frozen** |
|
| 57 |
+
| `lora_a` | `(L, r, 2*Dm)` | `bfloat16` | per-depth LoRA down |
|
| 58 |
+
| `lora_b` | `(L, 3*Dm, r)` | `bfloat16` | per-depth LoRA up |
|
| 59 |
+
| `scaling` | float | | LoRA scale `alpha / r` |
|
| 60 |
+
| `dqkv` | `(L, T, 3*Dm)` | `bfloat16` | incoming gradient w.r.t. the fused QKV output |
|
| 61 |
+
|
| 62 |
+
**Return a 4-tuple in exactly this order:** `dh (L, T, Dm)`, `demb (T, Dm)`, `dlora_a (L, r, 2*Dm)`,
|
| 63 |
+
`dlora_b (L, 3*Dm, r)`.
|
| 64 |
+
|
| 65 |
+
`dh` and `demb` may be bf16 or fp32; the two adapter gradients should be **fp32** — each is a reduction
|
| 66 |
+
over every token. **No gradient is returned for `w_qkv`.** The concatenation order is `[h[l] ‖ emb]`, so
|
| 67 |
+
`dh` comes from the first `Dm` channels of `dxc` and `demb` from the last `Dm`, summed over depths.
|
| 68 |
+
|
| 69 |
+
All inputs are **read-only**. `T` is **not** guaranteed to be a multiple of any tile size (the correctness
|
| 70 |
+
shapes include `T = 129`), and `r` is as small as 4.
|
| 71 |
+
|
| 72 |
+
**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L` in
|
| 73 |
+
4–8, `T` in 2048–6144, `Dm` in 2048–2560, `r` in 32–128. One big matmul per depth dominates the FLOPs; the
|
| 74 |
+
adapter work is a few percent of it and most of the difficulty.
|
| 75 |
+
|
| 76 |
+
## How success is decided (runs on GPU)
|
| 77 |
+
|
| 78 |
+
**1. Correctness — a required gate.** **All four** returned tensors must match the reference (evaluated in fp32) within
|
| 79 |
+
**relative Frobenius error `6e-3`** at every graded shape, including the timed ones; the grader scores the
|
| 80 |
+
**worst** of the four.
|
| 81 |
+
|
| 82 |
+
That gate is **measured**, and the two structural mistakes this task invites miss it badly: taking `demb`
|
| 83 |
+
from depth 0 instead of summing over **all** depths scores **0.70–0.91**, and omitting the adapter's
|
| 84 |
+
contribution `dmid @ lora_a` from `dxc` scores **0.124** at the largest graded shape (0.45–0.97 at the
|
| 85 |
+
small ones) — 21x the tolerance at worst. A wrong kernel scores **0**, no matter how fast.
|
| 86 |
+
|
| 87 |
+
**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
|
| 88 |
+
|
| 89 |
+
```
|
| 90 |
+
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [TFLOP/s]
|
| 91 |
+
reward = 0 if the submission is wrong at any graded shape
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
|
| 95 |
+
credited the same work and this is a pure speed ranking in useful units:
|
| 96 |
+
|
| 97 |
+
```
|
| 98 |
+
canonical_work(L, T, Dm, r) = L * ( 2*T*(2*Dm)*(3*Dm) # dxc = dqkv @ w_qkv
|
| 99 |
+
+ 3 * 2*T*(2*Dm)*r # mid, dxc +=, dlora_a
|
| 100 |
+
+ 2 * 2*T*(3*Dm)*r ) # dmid, dlora_b
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
**There is no cap and no target.** Higher TFLOP/s is always a strictly better score, so **push the
|
| 104 |
+
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
|
| 105 |
+
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
|
| 106 |
+
after every change. **Use your full time budget.**
|
| 107 |
+
|
| 108 |
+
Run **`python /app/measure.py`** at any point to see your per-shape and geomean TFLOP/s plus correctness.
|
| 109 |
+
|
| 110 |
+
## Where the performance comes from
|
| 111 |
+
|
| 112 |
+
`L` big matmuls against one frozen weight, plus four tall-skinny ones per depth, plus a
|
| 113 |
+
reduction that ties all the depths together.
|
| 114 |
+
|
| 115 |
+
**The frozen weight is read `L` times if you let it be.** `w_qkv` is 40–65 MB; a persistent grid that
|
| 116 |
+
walks all `L` depths per weight tile pays for it once. Note the transpose: the backward needs
|
| 117 |
+
`dqkv @ w_qkv` (not `w_qkv.T`), so the reduction runs over the `3*Dm` axis — plan the layout for that
|
| 118 |
+
rather than transposing a 65 MB tensor at run time.
|
| 119 |
+
|
| 120 |
+
**`demb` is a cross-depth reduction.** Do not build `L` copies of `dxc[:, Dm:]` and add them afterwards:
|
| 121 |
+
that is `L` extra full-size writes and reads. Accumulate into one fp32 `(T, Dm)` buffer as each depth's
|
| 122 |
+
tile is produced — with `L <= 8` a deterministic tree or a per-depth atomic-free accumulation over a
|
| 123 |
+
partition of the token axis both work, and both beat materialising the intermediates.
|
| 124 |
+
|
| 125 |
+
**Fuse the adapter path.** `mid[l]` and `dmid[l]` are `(T, r)` with `r <= 128`. Both belong in shared
|
| 126 |
+
memory: recompute `mid` from the `xc` tile you already have, form `dmid` from the `dqkv` tile you already
|
| 127 |
+
have, and feed both straight into the two weight-gradient reductions. An autograd-shaped implementation
|
| 128 |
+
sends four `(T, r)` tensors and two `(T, 2*Dm)` tensors through HBM per depth for a delta worth a few
|
| 129 |
+
percent of the arithmetic.
|
| 130 |
+
|
| 131 |
+
**`dlora_a` and `dlora_b` are split-K reductions** over the token axis into tiny outputs (`r x 2*Dm` and
|
| 132 |
+
`3*Dm x r`). Use fp32 accumulators and a cross-block reduction; do not use one atomic per element.
|
| 133 |
+
|
| 134 |
+
`xc` should never be materialised: its first half is `h[l]`, its second half is `emb`, and every consumer
|
| 135 |
+
can read them separately.
|
| 136 |
+
|
| 137 |
+
## Precision and faithfulness (read this)
|
| 138 |
+
|
| 139 |
+
Inputs are **bfloat16**; accumulate every matmul, the `demb` cross-depth sum and both
|
| 140 |
+
adapter-gradient reductions in **fp32**.
|
| 141 |
+
|
| 142 |
+
`demb` sums `L` full-size contributions and the adapter gradients sum over up to 6144 tokens — a bf16
|
| 143 |
+
accumulator in either place gives an error that *grows* with the problem size, which the faithfulness
|
| 144 |
+
clause below rejects.
|
| 145 |
+
|
| 146 |
+
**fp8 is not appropriate here**: the saved activations arrive in bf16 and re-quantising them is an
|
| 147 |
+
approximation of the specified computation.
|
| 148 |
+
|
| 149 |
+
**Where the tolerance comes from.** `1e-2` is measured. A second, independent implementation — the
|
| 150 |
+
analytic backward written out by hand, all `L` depths batched into `bmm`s, `xc` never materialised, the
|
| 151 |
+
adapter gradients accumulated in a different order from autograd's — differs from this fp32 autograd
|
| 152 |
+
reference by a worst relative Frobenius error of **2.90e-3** across the correctness shapes and two
|
| 153 |
+
full-size graded shapes, over several seeds. The tolerance is **2.07x** that, and the error *falls* with
|
| 154 |
+
problem size (2.37e-3 at the large shapes) — it is the bf16 rounding of the operands, nothing more.
|
| 155 |
+
|
| 156 |
+
### What the tolerance does NOT permit
|
| 157 |
+
|
| 158 |
+
The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
|
| 159 |
+
implementation of the specified computation**. It is not a budget to spend on approximation. The following
|
| 160 |
+
are wrong answers even if they happen to land inside the tolerance at some shape:
|
| 161 |
+
|
| 162 |
+
- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
|
| 163 |
+
series, low-rank or sketched substitutes, skipping a correction term);
|
| 164 |
+
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
|
| 165 |
+
or striding over the sequence, ignoring positions whose contribution "looks small");
|
| 166 |
+
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
|
| 167 |
+
that the spec gives their own);
|
| 168 |
+
- anything whose error **grows** with sequence length, batch, or head count.
|
| 169 |
+
|
| 170 |
+
A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
|
| 171 |
+
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
|
| 172 |
+
are deliberately large, so the difference shows up.
|
| 173 |
+
|
| 174 |
+
## What's available
|
| 175 |
+
|
| 176 |
+
- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
|
| 177 |
+
extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
|
| 178 |
+
(`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
|
| 179 |
+
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
|
| 180 |
+
- A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist.
|
| 181 |
+
The exact part is deliberately **not** stated: query it and tune to what you actually find.
|
| 182 |
+
|
| 183 |
+
```python
|
| 184 |
+
p = torch.cuda.get_device_properties(0)
|
| 185 |
+
p.name, p.major, p.minor # part and compute capability
|
| 186 |
+
p.multi_processor_count # SM count -- size your persistent grid from this, never a constant
|
| 187 |
+
p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor
|
| 188 |
+
p.shared_memory_per_block_optin # opt-in dynamic smem, the number that matters for big tiles
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
`nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK`
|
| 192 |
+
give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a
|
| 193 |
+
datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak
|
| 194 |
+
FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the
|
| 195 |
+
score is an absolute metric, so a kernel tuned to a machine it never sees is just slower.
|
| 196 |
+
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
|
| 197 |
+
already installed, and no library implementation of this kernel exists on the machine.
|
| 198 |
+
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
|
| 199 |
+
`/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
|
| 200 |
+
|
| 201 |
+
## How the grading actually runs (so there are no surprises)
|
| 202 |
+
|
| 203 |
+
- **`/app/shared_qkv_bwd.py` is the only file that is graded.** The grader imports `shared_qkv_backward` from it and reads nothing
|
| 204 |
+
else from `/app`.
|
| 205 |
+
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
|
| 206 |
+
carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
|
| 207 |
+
or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
|
| 208 |
+
your score**. Do not spend budget on them.
|
| 209 |
+
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
|
| 210 |
+
against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
|
| 211 |
+
than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
|
| 212 |
+
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
|
| 213 |
+
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/task.toml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.1"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "mle-bench/zamba-shared-attn-lora-backward"
|
| 5 |
+
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."
|
| 6 |
+
authors = []
|
| 7 |
+
keywords = ["mle", "kernel-generation", "zamba", "hybrid", "shared-attention", "lora", "multi-adapter", "backward", "training", "gemm", "compute-bound"]
|
| 8 |
+
|
| 9 |
+
[metadata]
|
| 10 |
+
suite = "mle-bench"
|
| 11 |
+
group = "kernel-generation"
|
| 12 |
+
level = "1.0"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
category = "mle"
|
| 15 |
+
tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]
|
| 16 |
+
|
| 17 |
+
[verifier]
|
| 18 |
+
timeout_sec = 1800.0
|
| 19 |
+
|
| 20 |
+
[agent]
|
| 21 |
+
timeout_sec = 14400.0
|
| 22 |
+
|
| 23 |
+
# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
|
| 24 |
+
# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
|
| 25 |
+
[environment]
|
| 26 |
+
build_timeout_sec = 3600.0
|
| 27 |
+
cpus = 8
|
| 28 |
+
memory_mb = 65536
|
| 29 |
+
storage_mb = 40960
|
| 30 |
+
gpus = 1
|
| 31 |
+
network_mode = "public"
|
| 32 |
+
mcp_servers = []
|
| 33 |
+
|
| 34 |
+
[verifier.env]
|
| 35 |
+
|
| 36 |
+
[environment.env]
|
| 37 |
+
|
| 38 |
+
[solution.env]
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/test.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.
|
| 3 |
+
set -u
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
python3 /tests/verify_env.py
|
tasks/quantization-gemm/zamba-shared-attn-lora-backward/tests/verify_env.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""zamba-shared-attn-lora-backward verifier — correctness gate + achieved-TFLOP/s SPEED LEADERBOARD (uncapped).
|
| 2 |
+
|
| 3 |
+
reward = 0 if the submission is incorrect
|
| 4 |
+
reward = geomean over graded shapes of TFLOP/s otherwise
|
| 5 |
+
|
| 6 |
+
GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
|
| 7 |
+
|
| 8 |
+
There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
|
| 9 |
+
by construction and nothing has to be vendored, sealed, or re-benchmarked.
|
| 10 |
+
|
| 11 |
+
CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
|
| 12 |
+
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
|
| 13 |
+
scores 0.
|
| 14 |
+
|
| 15 |
+
ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
|
| 16 |
+
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
|
| 17 |
+
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
|
| 18 |
+
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
|
| 19 |
+
|
| 20 |
+
WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
|
| 21 |
+
submissions are credited identically and the ranking is a pure speed ranking.
|
| 22 |
+
"""
|
| 23 |
+
import importlib.util
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import traceback
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
REWARD_DIR = "/logs/verifier"
|
| 33 |
+
MODULE_PATH = "/app/shared_qkv_bwd.py"
|
| 34 |
+
TOL = 0.006
|
| 35 |
+
NAMES = ('dh', 'demb', 'dlora_a', 'dlora_b')
|
| 36 |
+
|
| 37 |
+
GRADER_SHAPES = [(6, 4096, 2048, 64), (4, 4096, 2560, 64), (8, 2048, 2048, 32), (6, 3072, 2048, 128), (4, 6144, 2048, 64)]
|
| 38 |
+
CORRECT_SHAPES = [(2, 256, 256, 16), (3, 129, 128, 8), (4, 512, 512, 32), (2, 64, 128, 4)]
|
| 39 |
+
|
| 40 |
+
sys.path.insert(0, "/app")
|
| 41 |
+
|
| 42 |
+
def canonical_work(L, T, Dm, r):
|
| 43 |
+
"""FLOPs attributed to one backward call, from the SHAPE ALONE.
|
| 44 |
+
|
| 45 |
+
Per depth, at 2 FLOPs per multiply-add:
|
| 46 |
+
* ONE pass of the big shared shape: dxc = dqkv @ w_qkv (the base weight is frozen,
|
| 47 |
+
so there is no dw_qkv and no second pass over it)
|
| 48 |
+
* THREE passes of the (2*Dm, r) adapter shape: recompute mid = xc @ lora_a.T (the LoRA output is a
|
| 49 |
+
forward temporary), dxc += dmid @ lora_a, dlora_a = dmid.T @ xc
|
| 50 |
+
* TWO passes of the (3*Dm, r) adapter shape: dmid = dqkv @ lora_b, dlora_b = dqkv.T @ mid
|
| 51 |
+
The concatenation, the split of dxc and the sum of demb over depths are O(L*T*Dm) data movement and
|
| 52 |
+
are not credited.
|
| 53 |
+
"""
|
| 54 |
+
return L * (2 * T * (2 * Dm) * (3 * Dm)
|
| 55 |
+
+ 3 * (2 * T * (2 * Dm) * r)
|
| 56 |
+
+ 2 * (2 * T * (3 * Dm) * r))
|
| 57 |
+
|
| 58 |
+
def _shared_qkv(h, emb, w_qkv, lora_a, lora_b, scaling):
|
| 59 |
+
"""The fp32 forward of `zamba-shared-attn-lora-qkv`, differentiable. Autograd through THIS defines
|
| 60 |
+
every gradient this task asks for."""
|
| 61 |
+
L, T, Dm = h.shape
|
| 62 |
+
outs = []
|
| 63 |
+
for l in range(L):
|
| 64 |
+
xc = torch.cat([h[l], emb], dim=-1) # (T, 2*Dm) [state | embedding]
|
| 65 |
+
base = xc @ w_qkv.t()
|
| 66 |
+
delta = (xc @ lora_a[l].t()) @ lora_b[l].t()
|
| 67 |
+
outs.append(base + scaling * delta)
|
| 68 |
+
return torch.stack(outs, 0)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _ref(h, emb, w_qkv, lora_a, lora_b, scaling, dqkv):
|
| 72 |
+
"""The baseline re-runs the fp32 forward under autograd. The shared weight is FROZEN: only the two
|
| 73 |
+
activations and the L adapters receive gradients."""
|
| 74 |
+
ins = [t.detach().clone().float().requires_grad_(True) for t in (h, emb, lora_a, lora_b)]
|
| 75 |
+
o = _shared_qkv(ins[0], ins[1], w_qkv.float(), ins[2], ins[3], scaling)
|
| 76 |
+
return torch.autograd.grad(o, ins, dqkv.float())
|
| 77 |
+
|
| 78 |
+
def _mk(L, T, Dm, r, seed):
|
| 79 |
+
"""Saved forward inputs plus the incoming gradient. The adapters are scaled so the LoRA delta is a real
|
| 80 |
+
but minority part of the forward (RMS `16/r` of the base projection), which is what a trained LoRA
|
| 81 |
+
looks like."""
|
| 82 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 83 |
+
|
| 84 |
+
def rnd(*sh, s=1.0):
|
| 85 |
+
return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
|
| 86 |
+
|
| 87 |
+
h = rnd(L, T, Dm)
|
| 88 |
+
emb = rnd(T, Dm)
|
| 89 |
+
w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 90 |
+
lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 91 |
+
lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5)
|
| 92 |
+
dqkv = rnd(L, T, 3 * Dm)
|
| 93 |
+
return h, emb, w_qkv, lora_a, lora_b, 16.0 / r, dqkv
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _check(out, ref):
|
| 97 |
+
"""-> (ok, value, msg). value = MAX relative error across the returned tuple."""
|
| 98 |
+
if out is None or len(out) != len(NAMES):
|
| 99 |
+
return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
|
| 100 |
+
per = []
|
| 101 |
+
for n, a, b in zip(NAMES, out, ref):
|
| 102 |
+
if a is None or tuple(a.shape) != tuple(b.shape):
|
| 103 |
+
return False, 1.0, f"{n} bad shape"
|
| 104 |
+
if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
|
| 105 |
+
# exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
|
| 106 |
+
bad = int((a != b).sum())
|
| 107 |
+
if bad:
|
| 108 |
+
return False, 1.0, f"{n}: {bad} elements differ"
|
| 109 |
+
continue
|
| 110 |
+
per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
|
| 111 |
+
if not per:
|
| 112 |
+
return True, 0.0, "all integer outputs exact"
|
| 113 |
+
wn, wv = max(per, key=lambda x: x[1])
|
| 114 |
+
return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _bench_fresh(fn, mkargs, reps=5, warm=3):
|
| 118 |
+
"""Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
|
| 119 |
+
wargs = mkargs(0)
|
| 120 |
+
for _ in range(warm):
|
| 121 |
+
fn(*wargs)
|
| 122 |
+
torch.cuda.synchronize()
|
| 123 |
+
del wargs
|
| 124 |
+
torch.cuda.empty_cache()
|
| 125 |
+
|
| 126 |
+
best, timed_ok = float("inf"), True
|
| 127 |
+
for i in range(reps):
|
| 128 |
+
args = mkargs(10_000 + i)
|
| 129 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 130 |
+
s.record()
|
| 131 |
+
out = fn(*args)
|
| 132 |
+
e.record()
|
| 133 |
+
torch.cuda.synchronize()
|
| 134 |
+
best = min(best, s.elapsed_time(e))
|
| 135 |
+
if i == reps - 1:
|
| 136 |
+
timed_ok = _check(out, _ref(*args))[0]
|
| 137 |
+
del args, out
|
| 138 |
+
torch.cuda.empty_cache()
|
| 139 |
+
return best / 1e3, timed_ok
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _geomean(xs):
|
| 143 |
+
return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def main():
|
| 147 |
+
details, correct_gate, geo = {}, False, 0.0
|
| 148 |
+
try:
|
| 149 |
+
spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
|
| 150 |
+
m = importlib.util.module_from_spec(spec)
|
| 151 |
+
spec.loader.exec_module(m)
|
| 152 |
+
fn = m.shared_qkv_backward
|
| 153 |
+
|
| 154 |
+
corr_ok, msg = True, ""
|
| 155 |
+
for i, shp in enumerate(CORRECT_SHAPES):
|
| 156 |
+
args = _mk(*shp, seed=10 + i)
|
| 157 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 158 |
+
if not ok:
|
| 159 |
+
corr_ok, msg = False, f"cfg{i} {shp} {m_}"
|
| 160 |
+
break
|
| 161 |
+
del args
|
| 162 |
+
torch.cuda.empty_cache()
|
| 163 |
+
details["correct_msg"] = msg or "all correctness shapes pass"
|
| 164 |
+
|
| 165 |
+
vals, per_shape, perf_ok = [], [], corr_ok
|
| 166 |
+
for i, shp in enumerate(GRADER_SHAPES):
|
| 167 |
+
args = _mk(*shp, seed=100 + i)
|
| 168 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 169 |
+
if not ok:
|
| 170 |
+
perf_ok = False
|
| 171 |
+
del args
|
| 172 |
+
torch.cuda.empty_cache()
|
| 173 |
+
t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
|
| 174 |
+
if not timed_ok:
|
| 175 |
+
perf_ok = False
|
| 176 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 177 |
+
vals.append(v)
|
| 178 |
+
per_shape.append({"shape": list(shp), "tflops": round(v, 3), "ms": round(t * 1e3, 3),
|
| 179 |
+
"check": m_, "timed_ok": timed_ok})
|
| 180 |
+
geo = _geomean(vals)
|
| 181 |
+
details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
|
| 182 |
+
correct_gate = corr_ok and perf_ok
|
| 183 |
+
except Exception as e:
|
| 184 |
+
details["error"] = f"{e.__class__.__name__}: {e}"[:220]
|
| 185 |
+
details["trace"] = traceback.format_exc()[-800:]
|
| 186 |
+
|
| 187 |
+
reward = round(geo, 4) if correct_gate else 0.0
|
| 188 |
+
os.makedirs(REWARD_DIR, exist_ok=True)
|
| 189 |
+
json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
|
| 190 |
+
"geomean": round(geo, 4), "metric": "TFLOP/s (geomean over graded shapes)"},
|
| 191 |
+
open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
|
| 192 |
+
open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
|
| 193 |
+
json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
|
| 194 |
+
print("reward:", reward, "TFLOP/s | correct:", 1.0 if correct_gate else 0.0)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
main()
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/RUN.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Running `zamba-shared-attn-lora-qkv`
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
| | |
|
| 6 |
+
|---|---|
|
| 7 |
+
| **Task id** | `mle-bench/zamba-shared-attn-lora-qkv` |
|
| 8 |
+
| **Group** | `kernel-generation` |
|
| 9 |
+
| **GPUs** | 1 |
|
| 10 |
+
| **Agent edits** | `/app/shared_qkv.py` |
|
| 11 |
+
| **Score** | achieved **TFLOP/s** (uncapped speed leaderboard), `0` if incorrect |
|
| 12 |
+
| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
|
| 13 |
+
|
| 14 |
+
## Run through harbor
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
harbor run --dataset-path kernel-generation/kernels/zamba-shared-attn-lora-qkv --task-name zamba-shared-attn-lora-qkv \
|
| 18 |
+
--agent claude-code --model anthropic/claude-opus-4-1 -e docker
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Run manually
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
cd kernel-generation/kernels/zamba-shared-attn-lora-qkv
|
| 25 |
+
docker build -t zamba-shared-attn-lora-qkv environment/
|
| 26 |
+
docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep zamba-shared-attn-lora-qkv infinity
|
| 27 |
+
docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
|
| 28 |
+
docker rm -f v
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Use an **idle** GPU: the score is a timing measurement.
|
| 32 |
+
|
| 33 |
+
## Design
|
| 34 |
+
|
| 35 |
+
Correctness is a hard gate; the score is an absolute hardware metric (TFLOP/s), so the task is
|
| 36 |
+
hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
|
| 37 |
+
|
| 38 |
+
Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
|
| 39 |
+
copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
|
| 40 |
+
with the timed output itself validated, so memoize-and-replay fails the gate.
|
| 41 |
+
|
| 42 |
+
Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/Dockerfile
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kernel-generation task: Write a fast shared-attention-block QKV kernel (one weight, L per-depth LoRA adapters)
|
| 2 |
+
#
|
| 3 |
+
# 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.
|
| 4 |
+
#
|
| 5 |
+
# SCORING: correctness is a hard gate; the score is achieved TFLOP/s (uncapped leaderboard, 0 if wrong).
|
| 6 |
+
# There is no gold solution and no oracle, so nothing has to be vendored or sealed.
|
| 7 |
+
#
|
| 8 |
+
# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
|
| 9 |
+
# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
|
| 10 |
+
# there is no internet, so nothing else can be obtained.
|
| 11 |
+
#
|
| 12 |
+
# GENERATED by _factory/build.py.
|
| 13 |
+
FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
|
| 14 |
+
|
| 15 |
+
# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
|
| 16 |
+
# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
|
| 17 |
+
RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
|
| 18 |
+
apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
|
| 19 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 20 |
+
/root/.local/bin/uv tool install mini-swe-agent
|
| 21 |
+
# header-only CUTLASS for the agent's CUDA/CuTe route
|
| 22 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
|
| 23 |
+
# pre-bake Claude Code; harbor's claude_code.install() skips when present
|
| 24 |
+
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
|
| 25 |
+
apt-get install -y nodejs procps && \
|
| 26 |
+
npm install -g @anthropic-ai/claude-code && claude --version
|
| 27 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 28 |
+
ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
|
| 29 |
+
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
|
| 33 |
+
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
|
| 34 |
+
|
| 35 |
+
WORKDIR /app
|
| 36 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 37 |
+
|
| 38 |
+
# task-specific files LAST so the layers above stay shared across every task
|
| 39 |
+
COPY reference.py /app/reference.py
|
| 40 |
+
COPY measure.py /app/measure.py
|
| 41 |
+
COPY shared_qkv.py /app/shared_qkv.py
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
|
| 2 |
+
# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
|
| 3 |
+
# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
|
| 4 |
+
# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
|
| 5 |
+
# the (now-blocked) network install when it is already present.
|
| 6 |
+
services:
|
| 7 |
+
main:
|
| 8 |
+
cap_add:
|
| 9 |
+
- NET_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
|
| 14 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 15 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 16 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 17 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 18 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/measure.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-assessment tool — your correctness + achieved TFLOP/s across a RANGE of shapes.
|
| 2 |
+
|
| 3 |
+
python /app/measure.py # the graded regime
|
| 4 |
+
python /app/measure.py --quick # smaller sizes for fast iteration
|
| 5 |
+
|
| 6 |
+
You are scored on the **geomean achieved TFLOP/s** — NOT one fixed size, and the leaderboard is UNCAPPED
|
| 7 |
+
(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
|
| 8 |
+
optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
|
| 9 |
+
printed here is computed exactly as your score is.
|
| 10 |
+
|
| 11 |
+
GENERATED by _factory/build.py.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import math
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, "/app")
|
| 20 |
+
from reference import shared_block_qkv as _ref
|
| 21 |
+
from shared_qkv import shared_block_qkv as _agent
|
| 22 |
+
|
| 23 |
+
TOL = 0.007
|
| 24 |
+
|
| 25 |
+
FULL = [(6, 3584, 2048, 64), (4, 3584, 2560, 64), (8, 1792, 2048, 32), (6, 2560, 2048, 128), (4, 5120, 2048, 64)]
|
| 26 |
+
QUICK = [(4, 512, 1024, 32), (2, 1024, 512, 16), (6, 256, 1024, 64)]
|
| 27 |
+
|
| 28 |
+
def canonical_work(L, T, Dm, r):
|
| 29 |
+
"""FLOPs attributed to one call, from the SHAPE ALONE.
|
| 30 |
+
|
| 31 |
+
Per depth, at 2 FLOPs per multiply-add: the shared projection (T, 2*Dm) x (2*Dm, 3*Dm), the adapter's
|
| 32 |
+
down-projection (T, 2*Dm) x (2*Dm, r) and its up-projection (T, r) x (r, 3*Dm). The concatenation and
|
| 33 |
+
the residual add are O(T*Dm) data movement and are not credited.
|
| 34 |
+
"""
|
| 35 |
+
return L * (2 * T * (2 * Dm) * (3 * Dm) + 2 * T * (2 * Dm) * r + 2 * T * r * (3 * Dm))
|
| 36 |
+
|
| 37 |
+
def _mk(L, T, Dm, r, seed):
|
| 38 |
+
"""Per-depth residual streams, one shared embedding, the shared weight and L LoRA adapters.
|
| 39 |
+
|
| 40 |
+
The adapters are scaled so the delta is a real but minority contribution (its RMS is `16/r` of the
|
| 41 |
+
base projection's), which is what a trained LoRA looks like — big enough that ignoring it is obvious,
|
| 42 |
+
small enough that it is a correction rather than the answer.
|
| 43 |
+
"""
|
| 44 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 45 |
+
|
| 46 |
+
def rnd(*sh, s=1.0):
|
| 47 |
+
return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
|
| 48 |
+
|
| 49 |
+
h = rnd(L, T, Dm)
|
| 50 |
+
emb = rnd(T, Dm)
|
| 51 |
+
w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 52 |
+
lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 53 |
+
lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5)
|
| 54 |
+
return h, emb, w_qkv, lora_a, lora_b, 16.0 / r
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _is_exact(t):
|
| 58 |
+
"""Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large
|
| 59 |
+
ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass."""
|
| 60 |
+
return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _check(out, ref):
|
| 64 |
+
"""-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise."""
|
| 65 |
+
if out is None or tuple(out.shape) != tuple(ref.shape):
|
| 66 |
+
return False, 1.0, "bad/None shape"
|
| 67 |
+
if _is_exact(ref):
|
| 68 |
+
bad = int((out != ref).sum())
|
| 69 |
+
return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ")
|
| 70 |
+
e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12))
|
| 71 |
+
return e <= TOL, e, f"relerr {e:.2e}"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _bench(fn, reps=8, warm=3):
|
| 75 |
+
for _ in range(warm):
|
| 76 |
+
fn()
|
| 77 |
+
torch.cuda.synchronize()
|
| 78 |
+
best = float("inf")
|
| 79 |
+
for _ in range(reps):
|
| 80 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 81 |
+
s.record()
|
| 82 |
+
fn()
|
| 83 |
+
e.record()
|
| 84 |
+
torch.cuda.synchronize()
|
| 85 |
+
best = min(best, s.elapsed_time(e))
|
| 86 |
+
return best / 1e3
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main():
|
| 90 |
+
ap = argparse.ArgumentParser()
|
| 91 |
+
ap.add_argument("--quick", action="store_true")
|
| 92 |
+
a = ap.parse_args()
|
| 93 |
+
shapes = QUICK if a.quick else FULL
|
| 94 |
+
print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
|
| 95 |
+
f"DIFFERENT sizes in the same regime — optimize for generality\n")
|
| 96 |
+
vals, allok = [], True
|
| 97 |
+
for shp in shapes:
|
| 98 |
+
args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
|
| 99 |
+
ref = _ref(*args)
|
| 100 |
+
try:
|
| 101 |
+
out = _agent(*args)
|
| 102 |
+
except Exception as ex:
|
| 103 |
+
print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
|
| 104 |
+
allok = False
|
| 105 |
+
continue
|
| 106 |
+
ok, val, msg = _check(out, ref)
|
| 107 |
+
allok = allok and ok
|
| 108 |
+
t = _bench(lambda: _agent(*args))
|
| 109 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 110 |
+
vals.append(v)
|
| 111 |
+
print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} TFLOP/s | {msg} {'ok' if ok else 'FAIL'}")
|
| 112 |
+
del args, ref, out
|
| 113 |
+
torch.cuda.empty_cache()
|
| 114 |
+
geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
|
| 115 |
+
print(f"\n => GEOMEAN {geo:.2f} TFLOP/s "
|
| 116 |
+
f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
|
| 117 |
+
print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
main()
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/reference.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference implementation — the CORRECTNESS SPEC for `shared_block_qkv`.
|
| 2 |
+
|
| 3 |
+
This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
|
| 4 |
+
bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling):
|
| 10 |
+
"""One depth at a time: concatenate, project with the shared weight, add the depth's LoRA delta.
|
| 11 |
+
|
| 12 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. The shared weight is
|
| 13 |
+
re-read for every depth and the rank-wide intermediate goes to HBM.
|
| 14 |
+
"""
|
| 15 |
+
L, T, Dm = h.shape
|
| 16 |
+
out = torch.empty(L, T, 3 * Dm, device=h.device, dtype=torch.float32)
|
| 17 |
+
w = w_qkv.float()
|
| 18 |
+
e = emb.float()
|
| 19 |
+
for l in range(L):
|
| 20 |
+
xc = torch.cat([h[l].float(), e], dim=-1) # (T, 2*Dm) [state | embedding]
|
| 21 |
+
base = xc @ w.t() # the SHARED projection
|
| 22 |
+
delta = (xc @ lora_a[l].float().t()) @ lora_b[l].float().t()
|
| 23 |
+
out[l] = base + scaling * delta
|
| 24 |
+
return out.to(torch.bfloat16)
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
|
| 5 |
+
# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
|
| 6 |
+
# installer skips the network install when it is already present), so no package index is needed at run time.
|
| 7 |
+
#
|
| 8 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
|
| 9 |
+
# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
|
| 12 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 13 |
+
API_HOSTS=(
|
| 14 |
+
api.fireworks.ai
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/environment/shared_qkv.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Your implementation goes here.
|
| 2 |
+
|
| 3 |
+
Replace the body of `shared_block_qkv` with a FAST implementation that reproduces the output of /app/reference.py
|
| 4 |
+
(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
|
| 5 |
+
Run `python /app/measure.py` to check your correctness and achieved TFLOP/s.
|
| 6 |
+
|
| 7 |
+
You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
|
| 8 |
+
signature and returned value are fixed by the contract.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling):
|
| 13 |
+
"""Shared attention-block QKV projection with a per-depth LoRA adapter.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
h: (L, T, Dm) bfloat16 — the residual stream at each of the L depths the block is called at.
|
| 17 |
+
emb: (T, Dm) bfloat16 — the ORIGINAL token embedding, concatenated at every depth.
|
| 18 |
+
w_qkv: (3*Dm, 2*Dm) bfloat16 — the SHARED qkv projection, nn.Linear layout (out, in).
|
| 19 |
+
lora_a: (L, r, 2*Dm) bfloat16 — per-depth LoRA down-projection.
|
| 20 |
+
lora_b: (L, 3*Dm, r) bfloat16 — per-depth LoRA up-projection.
|
| 21 |
+
scaling: float — the LoRA scale (alpha / r).
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
qkv: (L, T, 3*Dm), bfloat16 or float32 — must match /app/reference.py numerically.
|
| 25 |
+
"""
|
| 26 |
+
raise NotImplementedError("Implement a fast shared_block_qkv in /app/shared_qkv.py")
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/instruction.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast shared-attention-block QKV kernel (one weight, L per-depth LoRA adapters)
|
| 2 |
+
|
| 3 |
+
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.**
|
| 4 |
+
|
| 5 |
+
Write **`/app/shared_qkv.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
def shared_block_qkv(h, emb, w_qkv, lora_a, lora_b, scaling):
|
| 9 |
+
...
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## The computation (this is the exact spec)
|
| 13 |
+
|
| 14 |
+
A Zamba-style hybrid stack has **one** attention block, invoked at `L` different depths of a
|
| 15 |
+
Mamba backbone. Two things make its QKV projection unusual.
|
| 16 |
+
|
| 17 |
+
**1 — the input is a concatenation.** At every depth the block sees the current residual stream *and* the
|
| 18 |
+
original token embedding, glued along the feature axis:
|
| 19 |
+
|
| 20 |
+
```
|
| 21 |
+
xc[l] = concat( h[l], emb ) # (T, 2*Dm) — state first, embedding second
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
`emb` is the **same** tensor at every depth: it is the model's input embedding, re-fed so the shared block
|
| 25 |
+
always has the original token available no matter how deep it is being called.
|
| 26 |
+
|
| 27 |
+
**2 — the weights are shared, the adapters are not.** One `(3*Dm, 2*Dm)` projection serves every depth,
|
| 28 |
+
and each depth gets its own rank-`r` LoRA delta:
|
| 29 |
+
|
| 30 |
+
```
|
| 31 |
+
qkv[l] = xc[l] @ w_qkv.T + scaling * ( xc[l] @ lora_a[l].T ) @ lora_b[l].T
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
That is the whole computation: `L` applications of one big shared GEMM, each with its own tiny two-matmul
|
| 35 |
+
correction. The output layout is the usual fused one — `qkv[l][:, 0:Dm]` is Q, `[Dm:2*Dm]` is K,
|
| 36 |
+
`[2*Dm:3*Dm]` is V — but nothing here needs to know that; you return the fused tensor.
|
| 37 |
+
|
| 38 |
+
`/app/reference.py` loops over depths and materialises the concatenation and the rank-wide intermediate for
|
| 39 |
+
each. That is the exact specification; it is deliberately simple rather than fast.
|
| 40 |
+
|
| 41 |
+
## The contract (fixed — do not change these)
|
| 42 |
+
|
| 43 |
+
| arg | shape | dtype | meaning |
|
| 44 |
+
|-----|-------|-------|---------|
|
| 45 |
+
| `h` | `(L, T, Dm)` | `bfloat16` | residual stream at each of the `L` invocation depths |
|
| 46 |
+
| `emb` | `(T, Dm)` | `bfloat16` | the original token embedding, **shared** across depths |
|
| 47 |
+
| `w_qkv` | `(3*Dm, 2*Dm)` | `bfloat16` | the shared projection, `nn.Linear` layout `(out, in)` |
|
| 48 |
+
| `lora_a` | `(L, r, 2*Dm)` | `bfloat16` | per-depth LoRA down-projection |
|
| 49 |
+
| `lora_b` | `(L, 3*Dm, r)` | `bfloat16` | per-depth LoRA up-projection |
|
| 50 |
+
| `scaling` | float | | LoRA scale `alpha / r`, a Python float |
|
| 51 |
+
|
| 52 |
+
**Return** a single tensor `qkv` of shape `(L, T, 3*Dm)`, bfloat16 or float32 (the grader compares in
|
| 53 |
+
fp32).
|
| 54 |
+
|
| 55 |
+
The concatenation order is **`[h[l] ‖ emb]`** — state in channels `[0, Dm)`, embedding in `[Dm, 2*Dm)` —
|
| 56 |
+
and `w_qkv`'s columns are laid out to match. All inputs are **read-only**. `T` is **not** guaranteed to be
|
| 57 |
+
a multiple of any tile size (the correctness shapes include `T = 129`), and `r` is as small as 4.
|
| 58 |
+
|
| 59 |
+
**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `L`
|
| 60 |
+
(invocation depths) in 4–8, `T` (tokens) in 2048–6144, `Dm` in 2048–2560, `r` in 32–128. The shared weight
|
| 61 |
+
is 40–65 MB and is used `L` times; the `L` adapters together are a few megabytes. That ratio is the whole
|
| 62 |
+
design of the layer and it should be the whole design of your kernel.
|
| 63 |
+
|
| 64 |
+
## How success is decided (runs on GPU)
|
| 65 |
+
|
| 66 |
+
**1. Correctness — a required gate.** The returned tensor must match the reference (evaluated in fp32) within **relative
|
| 67 |
+
Frobenius error `7e-3`** at every graded shape, including the timed ones.
|
| 68 |
+
|
| 69 |
+
That gate is **measured**, and the plausible ways to get this wrong miss it by a wide margin: dropping the
|
| 70 |
+
LoRA delta entirely scores **0.12–0.24** at the graded shapes (0.45–0.97 at the small ones, where `r` is
|
| 71 |
+
a larger fraction of the width), using depth 0's adapter for every depth scores **0.16–0.30**, and
|
| 72 |
+
concatenating `[emb ‖ h[l]]` instead of `[h[l] ‖ emb]` scores **1.41** — the closest is **18x** the
|
| 73 |
+
tolerance. A wrong kernel scores **0**, no matter how fast.
|
| 74 |
+
|
| 75 |
+
**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
|
| 76 |
+
|
| 77 |
+
```
|
| 78 |
+
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [TFLOP/s]
|
| 79 |
+
reward = 0 if the submission is wrong at any graded shape
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
|
| 83 |
+
credited the same work and this is a pure speed ranking in useful units:
|
| 84 |
+
|
| 85 |
+
```
|
| 86 |
+
canonical_work(L, T, Dm, r) = L * ( 2*T*(2*Dm)*(3*Dm) + 2*T*(2*Dm)*r + 2*T*r*(3*Dm) )
|
| 87 |
+
# shared projection LoRA down LoRA up
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
**There is no cap and no target.** Higher TFLOP/s is always a strictly better score, so **push the
|
| 91 |
+
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
|
| 92 |
+
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
|
| 93 |
+
after every change. **Use your full time budget.**
|
| 94 |
+
|
| 95 |
+
Run **`python /app/measure.py`** at any point to see your per-shape and geomean TFLOP/s plus correctness.
|
| 96 |
+
|
| 97 |
+
## Where the performance comes from
|
| 98 |
+
|
| 99 |
+
One big GEMM done `L` times against the same weight, plus `2L` tiny ones. Three things
|
| 100 |
+
decide the score.
|
| 101 |
+
|
| 102 |
+
**Read the shared weight once.** `w_qkv` is 40–65 MB; `L` separate `torch.matmul` calls stream it from HBM
|
| 103 |
+
`L` times. A kernel that tiles over `(depth, token)` blocks with the weight tile resident — or a persistent
|
| 104 |
+
grid that walks all `L` depths for each weight tile — pays for it once. At `L = 8` that is the difference
|
| 105 |
+
between 500 MB and 60 MB of weight traffic.
|
| 106 |
+
|
| 107 |
+
**Never materialise the concatenation.** `xc[l]` is `(T, 2*Dm)` and half of it is `emb`, which is the same
|
| 108 |
+
for every depth. Building it explicitly costs `L` writes and `L` reads of a tensor twice the size of `h`.
|
| 109 |
+
The GEMM's K-loop can simply read the first `Dm` steps from `h[l]` and the next `Dm` from `emb` — the
|
| 110 |
+
operands are contiguous within each half, and `emb`'s half is reused by all `L` depths, so it is a
|
| 111 |
+
shared-memory tile you load once.
|
| 112 |
+
|
| 113 |
+
**Fuse the adapter.** The rank-wide intermediate `xc @ lora_a[l].T` is `(T, r)` with `r <= 128` — a few
|
| 114 |
+
hundred kilobytes. It has no business in HBM: compute it into shared memory while the tile is resident,
|
| 115 |
+
then accumulate `scaling * (that) @ lora_b[l].T` straight into the same accumulator the shared projection
|
| 116 |
+
is building. Done separately, the adapter costs a second full read of `xc`, two extra launches per depth,
|
| 117 |
+
and a round trip of the intermediate — on a delta that is a few percent of the arithmetic.
|
| 118 |
+
|
| 119 |
+
The `L` depths are completely independent, which is free parallelism for filling the machine at small `T`,
|
| 120 |
+
and `T` is ragged, so size the tail carefully.
|
| 121 |
+
|
| 122 |
+
## Precision and faithfulness (read this)
|
| 123 |
+
|
| 124 |
+
Inputs are **bfloat16** and the output may be bf16 or fp32. Accumulate every matmul in
|
| 125 |
+
**fp32** — including the adapter's two, whose product is added to a much larger base term, so its own
|
| 126 |
+
rounding is amplified by nothing but must not be thrown away.
|
| 127 |
+
|
| 128 |
+
`scaling` is a Python float. Fold it into the adapter's up-projection or apply it to the rank-wide
|
| 129 |
+
intermediate; either is fine, but do it in fp32.
|
| 130 |
+
|
| 131 |
+
**fp8 is not appropriate here**: the weights and activations arrive in bf16 and re-quantising them is an
|
| 132 |
+
approximation of the specified computation, not an implementation of it.
|
| 133 |
+
|
| 134 |
+
**Where the tolerance comes from.** `1e-2` is measured. A second, independent implementation — all `L`
|
| 135 |
+
depths batched into one `bmm` against a broadcast weight, the concatenation formed implicitly by splitting
|
| 136 |
+
the K-loop, the LoRA fused as `xc @ (lora_a.T @ lora_b.T)` in the other association order, bf16 operands
|
| 137 |
+
with fp32 accumulate — differs from this fp32 reference by a worst relative Frobenius error of **3.30e-3**
|
| 138 |
+
across the correctness shapes and two full-size graded shapes, over several seeds. The tolerance is
|
| 139 |
+
**2.1x** that, and the error is flat in `L` and `T` (2.86e-3 at the large shapes) because it is the bf16
|
| 140 |
+
rounding of the operands and of the returned tensor and nothing else.
|
| 141 |
+
|
| 142 |
+
### What the tolerance does NOT permit
|
| 143 |
+
|
| 144 |
+
The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
|
| 145 |
+
implementation of the specified computation**. It is not a budget to spend on approximation. The following
|
| 146 |
+
are wrong answers even if they happen to land inside the tolerance at some shape:
|
| 147 |
+
|
| 148 |
+
- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
|
| 149 |
+
series, low-rank or sketched substitutes, skipping a correction term);
|
| 150 |
+
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
|
| 151 |
+
or striding over the sequence, ignoring positions whose contribution "looks small");
|
| 152 |
+
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
|
| 153 |
+
that the spec gives their own);
|
| 154 |
+
- anything whose error **grows** with sequence length, batch, or head count.
|
| 155 |
+
|
| 156 |
+
A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
|
| 157 |
+
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
|
| 158 |
+
are deliberately large, so the difference shows up.
|
| 159 |
+
|
| 160 |
+
## What's available
|
| 161 |
+
|
| 162 |
+
- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
|
| 163 |
+
extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
|
| 164 |
+
(`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
|
| 165 |
+
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
|
| 166 |
+
- A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist.
|
| 167 |
+
The exact part is deliberately **not** stated: query it and tune to what you actually find.
|
| 168 |
+
|
| 169 |
+
```python
|
| 170 |
+
p = torch.cuda.get_device_properties(0)
|
| 171 |
+
p.name, p.major, p.minor # part and compute capability
|
| 172 |
+
p.multi_processor_count # SM count -- size your persistent grid from this, never a constant
|
| 173 |
+
p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor
|
| 174 |
+
p.shared_memory_per_block_optin # opt-in dynamic smem, the number that matters for big tiles
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
`nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK`
|
| 178 |
+
give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a
|
| 179 |
+
datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak
|
| 180 |
+
FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the
|
| 181 |
+
score is an absolute metric, so a kernel tuned to a machine it never sees is just slower.
|
| 182 |
+
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
|
| 183 |
+
already installed, and no library implementation of this kernel exists on the machine.
|
| 184 |
+
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
|
| 185 |
+
`/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
|
| 186 |
+
|
| 187 |
+
## How the grading actually runs (so there are no surprises)
|
| 188 |
+
|
| 189 |
+
- **`/app/shared_qkv.py` is the only file that is graded.** The grader imports `shared_block_qkv` from it and reads nothing
|
| 190 |
+
else from `/app`.
|
| 191 |
+
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
|
| 192 |
+
carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
|
| 193 |
+
or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
|
| 194 |
+
your score**. Do not spend budget on them.
|
| 195 |
+
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
|
| 196 |
+
against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
|
| 197 |
+
than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
|
| 198 |
+
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
|
| 199 |
+
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/task.toml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.1"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "mle-bench/zamba-shared-attn-lora-qkv"
|
| 5 |
+
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."
|
| 6 |
+
authors = []
|
| 7 |
+
keywords = ["mle", "kernel-generation", "zamba", "hybrid", "shared-attention", "lora", "multi-adapter", "gemm", "fusion", "compute-bound"]
|
| 8 |
+
|
| 9 |
+
[metadata]
|
| 10 |
+
suite = "mle-bench"
|
| 11 |
+
group = "kernel-generation"
|
| 12 |
+
level = "1.0"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
category = "mle"
|
| 15 |
+
tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]
|
| 16 |
+
|
| 17 |
+
[verifier]
|
| 18 |
+
timeout_sec = 1800.0
|
| 19 |
+
|
| 20 |
+
[agent]
|
| 21 |
+
timeout_sec = 14400.0
|
| 22 |
+
|
| 23 |
+
# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
|
| 24 |
+
# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
|
| 25 |
+
[environment]
|
| 26 |
+
build_timeout_sec = 3600.0
|
| 27 |
+
cpus = 8
|
| 28 |
+
memory_mb = 65536
|
| 29 |
+
storage_mb = 40960
|
| 30 |
+
gpus = 1
|
| 31 |
+
network_mode = "public"
|
| 32 |
+
mcp_servers = []
|
| 33 |
+
|
| 34 |
+
[verifier.env]
|
| 35 |
+
|
| 36 |
+
[environment.env]
|
| 37 |
+
|
| 38 |
+
[solution.env]
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/test.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.
|
| 3 |
+
set -u
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
python3 /tests/verify_env.py
|
tasks/quantization-gemm/zamba-shared-attn-lora-qkv/tests/verify_env.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""zamba-shared-attn-lora-qkv verifier — correctness gate + achieved-TFLOP/s SPEED LEADERBOARD (uncapped).
|
| 2 |
+
|
| 3 |
+
reward = 0 if the submission is incorrect
|
| 4 |
+
reward = geomean over graded shapes of TFLOP/s otherwise
|
| 5 |
+
|
| 6 |
+
GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
|
| 7 |
+
|
| 8 |
+
There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
|
| 9 |
+
by construction and nothing has to be vendored, sealed, or re-benchmarked.
|
| 10 |
+
|
| 11 |
+
CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
|
| 12 |
+
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
|
| 13 |
+
scores 0.
|
| 14 |
+
|
| 15 |
+
ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
|
| 16 |
+
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
|
| 17 |
+
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
|
| 18 |
+
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
|
| 19 |
+
|
| 20 |
+
WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
|
| 21 |
+
submissions are credited identically and the ranking is a pure speed ranking.
|
| 22 |
+
"""
|
| 23 |
+
import importlib.util
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import traceback
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
REWARD_DIR = "/logs/verifier"
|
| 33 |
+
MODULE_PATH = "/app/shared_qkv.py"
|
| 34 |
+
TOL = 0.007
|
| 35 |
+
|
| 36 |
+
GRADER_SHAPES = [(6, 4096, 2048, 64), (4, 4096, 2560, 64), (8, 2048, 2048, 32), (6, 3072, 2048, 128), (4, 6144, 2048, 64)]
|
| 37 |
+
CORRECT_SHAPES = [(2, 256, 256, 16), (3, 129, 128, 8), (4, 512, 512, 32), (2, 64, 128, 4)]
|
| 38 |
+
|
| 39 |
+
sys.path.insert(0, "/app")
|
| 40 |
+
|
| 41 |
+
def canonical_work(L, T, Dm, r):
|
| 42 |
+
"""FLOPs attributed to one call, from the SHAPE ALONE.
|
| 43 |
+
|
| 44 |
+
Per depth, at 2 FLOPs per multiply-add: the shared projection (T, 2*Dm) x (2*Dm, 3*Dm), the adapter's
|
| 45 |
+
down-projection (T, 2*Dm) x (2*Dm, r) and its up-projection (T, r) x (r, 3*Dm). The concatenation and
|
| 46 |
+
the residual add are O(T*Dm) data movement and are not credited.
|
| 47 |
+
"""
|
| 48 |
+
return L * (2 * T * (2 * Dm) * (3 * Dm) + 2 * T * (2 * Dm) * r + 2 * T * r * (3 * Dm))
|
| 49 |
+
|
| 50 |
+
def _ref(h, emb, w_qkv, lora_a, lora_b, scaling):
|
| 51 |
+
"""One depth at a time: concatenate, project with the shared weight, add the depth's LoRA delta.
|
| 52 |
+
|
| 53 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. The shared weight is
|
| 54 |
+
re-read for every depth and the rank-wide intermediate goes to HBM.
|
| 55 |
+
"""
|
| 56 |
+
L, T, Dm = h.shape
|
| 57 |
+
out = torch.empty(L, T, 3 * Dm, device=h.device, dtype=torch.float32)
|
| 58 |
+
w = w_qkv.float()
|
| 59 |
+
e = emb.float()
|
| 60 |
+
for l in range(L):
|
| 61 |
+
xc = torch.cat([h[l].float(), e], dim=-1) # (T, 2*Dm) [state | embedding]
|
| 62 |
+
base = xc @ w.t() # the SHARED projection
|
| 63 |
+
delta = (xc @ lora_a[l].float().t()) @ lora_b[l].float().t()
|
| 64 |
+
out[l] = base + scaling * delta
|
| 65 |
+
return out.to(torch.bfloat16)
|
| 66 |
+
|
| 67 |
+
def _mk(L, T, Dm, r, seed):
|
| 68 |
+
"""Per-depth residual streams, one shared embedding, the shared weight and L LoRA adapters.
|
| 69 |
+
|
| 70 |
+
The adapters are scaled so the delta is a real but minority contribution (its RMS is `16/r` of the
|
| 71 |
+
base projection's), which is what a trained LoRA looks like — big enough that ignoring it is obvious,
|
| 72 |
+
small enough that it is a correction rather than the answer.
|
| 73 |
+
"""
|
| 74 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 75 |
+
|
| 76 |
+
def rnd(*sh, s=1.0):
|
| 77 |
+
return (torch.randn(*sh, device="cuda", dtype=torch.float32, generator=gen) * s).to(torch.bfloat16)
|
| 78 |
+
|
| 79 |
+
h = rnd(L, T, Dm)
|
| 80 |
+
emb = rnd(T, Dm)
|
| 81 |
+
w_qkv = rnd(3 * Dm, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 82 |
+
lora_a = rnd(L, r, 2 * Dm, s=(2 * Dm) ** -0.5)
|
| 83 |
+
lora_b = rnd(L, 3 * Dm, r, s=r ** -0.5)
|
| 84 |
+
return h, emb, w_qkv, lora_a, lora_b, 16.0 / r
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _is_exact(t):
|
| 88 |
+
"""Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large
|
| 89 |
+
ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass."""
|
| 90 |
+
return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _check(out, ref):
|
| 94 |
+
"""-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise."""
|
| 95 |
+
if out is None or tuple(out.shape) != tuple(ref.shape):
|
| 96 |
+
return False, 1.0, "bad/None shape"
|
| 97 |
+
if _is_exact(ref):
|
| 98 |
+
bad = int((out != ref).sum())
|
| 99 |
+
return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ")
|
| 100 |
+
e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12))
|
| 101 |
+
return e <= TOL, e, f"relerr {e:.2e}"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _bench_fresh(fn, mkargs, reps=5, warm=3):
|
| 105 |
+
"""Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
|
| 106 |
+
wargs = mkargs(0)
|
| 107 |
+
for _ in range(warm):
|
| 108 |
+
fn(*wargs)
|
| 109 |
+
torch.cuda.synchronize()
|
| 110 |
+
del wargs
|
| 111 |
+
torch.cuda.empty_cache()
|
| 112 |
+
|
| 113 |
+
best, timed_ok = float("inf"), True
|
| 114 |
+
for i in range(reps):
|
| 115 |
+
args = mkargs(10_000 + i)
|
| 116 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 117 |
+
s.record()
|
| 118 |
+
out = fn(*args)
|
| 119 |
+
e.record()
|
| 120 |
+
torch.cuda.synchronize()
|
| 121 |
+
best = min(best, s.elapsed_time(e))
|
| 122 |
+
if i == reps - 1:
|
| 123 |
+
timed_ok = _check(out, _ref(*args))[0]
|
| 124 |
+
del args, out
|
| 125 |
+
torch.cuda.empty_cache()
|
| 126 |
+
return best / 1e3, timed_ok
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _geomean(xs):
|
| 130 |
+
return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def main():
|
| 134 |
+
details, correct_gate, geo = {}, False, 0.0
|
| 135 |
+
try:
|
| 136 |
+
spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
|
| 137 |
+
m = importlib.util.module_from_spec(spec)
|
| 138 |
+
spec.loader.exec_module(m)
|
| 139 |
+
fn = m.shared_block_qkv
|
| 140 |
+
|
| 141 |
+
corr_ok, msg = True, ""
|
| 142 |
+
for i, shp in enumerate(CORRECT_SHAPES):
|
| 143 |
+
args = _mk(*shp, seed=10 + i)
|
| 144 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 145 |
+
if not ok:
|
| 146 |
+
corr_ok, msg = False, f"cfg{i} {shp} {m_}"
|
| 147 |
+
break
|
| 148 |
+
del args
|
| 149 |
+
torch.cuda.empty_cache()
|
| 150 |
+
details["correct_msg"] = msg or "all correctness shapes pass"
|
| 151 |
+
|
| 152 |
+
vals, per_shape, perf_ok = [], [], corr_ok
|
| 153 |
+
for i, shp in enumerate(GRADER_SHAPES):
|
| 154 |
+
args = _mk(*shp, seed=100 + i)
|
| 155 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 156 |
+
if not ok:
|
| 157 |
+
perf_ok = False
|
| 158 |
+
del args
|
| 159 |
+
torch.cuda.empty_cache()
|
| 160 |
+
t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
|
| 161 |
+
if not timed_ok:
|
| 162 |
+
perf_ok = False
|
| 163 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 164 |
+
vals.append(v)
|
| 165 |
+
per_shape.append({"shape": list(shp), "tflops": round(v, 3), "ms": round(t * 1e3, 3),
|
| 166 |
+
"check": m_, "timed_ok": timed_ok})
|
| 167 |
+
geo = _geomean(vals)
|
| 168 |
+
details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
|
| 169 |
+
correct_gate = corr_ok and perf_ok
|
| 170 |
+
except Exception as e:
|
| 171 |
+
details["error"] = f"{e.__class__.__name__}: {e}"[:220]
|
| 172 |
+
details["trace"] = traceback.format_exc()[-800:]
|
| 173 |
+
|
| 174 |
+
reward = round(geo, 4) if correct_gate else 0.0
|
| 175 |
+
os.makedirs(REWARD_DIR, exist_ok=True)
|
| 176 |
+
json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
|
| 177 |
+
"geomean": round(geo, 4), "metric": "TFLOP/s (geomean over graded shapes)"},
|
| 178 |
+
open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
|
| 179 |
+
open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
|
| 180 |
+
json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
|
| 181 |
+
print("reward:", reward, "TFLOP/s | correct:", 1.0 if correct_gate else 0.0)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
main()
|
tasks/raw-cuda/README.md
CHANGED
|
@@ -2,13 +2,19 @@
|
|
| 2 |
|
| 3 |
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.
|
| 4 |
|
| 5 |
-
**
|
| 6 |
|
| 7 |
| task | metric | roofline | what the kernel does |
|
| 8 |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
| 9 |
| [`cuda-linear-recurrence`](cuda-linear-recurrence/) | — | — | |
|
|
|
|
| 10 |
| [`cuda-relu2-aggregation`](cuda-relu2-aggregation/) | — | — | |
|
| 11 |
| [`cuda-topk-indices`](cuda-topk-indices/) | — | — | |
|
|
|
|
|
|
|
| 12 |
| [`flash-attention-fwd`](flash-attention-fwd/) | — | — | |
|
| 13 |
| [`gptq-w4a16-gemm`](gptq-w4a16-gemm/) | — | — | |
|
| 14 |
| [`qserve-w4a8-gemm`](qserve-w4a8-gemm/) | — | — | |
|
|
|
|
| 2 |
|
| 3 |
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.
|
| 4 |
|
| 5 |
+
**12 tasks.**
|
| 6 |
|
| 7 |
| task | metric | roofline | what the kernel does |
|
| 8 |
|---|---|---|---|
|
| 9 |
+
| [`cuda-blockwise-softmax`](cuda-blockwise-softmax/) | — | — | |
|
| 10 |
+
| [`cuda-fp8-cast-pack`](cuda-fp8-cast-pack/) | — | — | |
|
| 11 |
+
| [`cuda-histogram-atomics`](cuda-histogram-atomics/) | — | — | |
|
| 12 |
| [`cuda-linear-recurrence`](cuda-linear-recurrence/) | — | — | |
|
| 13 |
+
| [`cuda-radix-partition`](cuda-radix-partition/) | — | — | |
|
| 14 |
| [`cuda-relu2-aggregation`](cuda-relu2-aggregation/) | — | — | |
|
| 15 |
| [`cuda-topk-indices`](cuda-topk-indices/) | — | — | |
|
| 16 |
+
| [`cuda-transpose-vectorized`](cuda-transpose-vectorized/) | — | — | |
|
| 17 |
+
| [`cuda-warp-scan-segmented`](cuda-warp-scan-segmented/) | — | — | |
|
| 18 |
| [`flash-attention-fwd`](flash-attention-fwd/) | — | — | |
|
| 19 |
| [`gptq-w4a16-gemm`](gptq-w4a16-gemm/) | — | — | |
|
| 20 |
| [`qserve-w4a8-gemm`](qserve-w4a8-gemm/) | — | — | |
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/Dockerfile
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CUDA kernel-generation task: write a fast row-wise (online) softmax kernel in solution.cu.
|
| 2 |
+
# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton.
|
| 3 |
+
FROM nvidia/cuda:12.8.1-devel-ubuntu24.04
|
| 4 |
+
|
| 5 |
+
# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps.
|
| 6 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
+
git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \
|
| 8 |
+
rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled).
|
| 11 |
+
# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed,
|
| 12 |
+
# and dropping it keeps the environment free of any torch/triton files.
|
| 13 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \
|
| 14 |
+
git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \
|
| 15 |
+
mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi
|
| 16 |
+
|
| 17 |
+
# Pre-bake the agent (the offline firewall blocks installing it at run time).
|
| 18 |
+
RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent
|
| 19 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 20 |
+
|
| 21 |
+
# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper.
|
| 22 |
+
WORKDIR /app
|
| 23 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 24 |
+
COPY solution.cu /app/solution.cu
|
| 25 |
+
COPY harness.cu /app/harness.cu
|
| 26 |
+
COPY build.sh /app/build.sh
|
| 27 |
+
RUN chmod +x /app/build.sh
|
| 28 |
+
|
| 29 |
+
# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched).
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
|
| 33 |
+
# Strip apt sources so harbor's base apt-setup is a no-op under the firewall.
|
| 34 |
+
RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/*
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/build.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Compile your solution against the harness and run one seed (the grader uses a different seed).
|
| 3 |
+
set -e
|
| 4 |
+
nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run
|
| 5 |
+
/app/run 0
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose.
|
| 2 |
+
# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked).
|
| 3 |
+
# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has
|
| 4 |
+
# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it.
|
| 5 |
+
services:
|
| 6 |
+
main:
|
| 7 |
+
cap_add:
|
| 8 |
+
- NET_ADMIN
|
| 9 |
+
- SYS_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 14 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 15 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 16 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 17 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/harness.cu
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Grading harness for cuda-blockwise-softmax.
|
| 2 |
+
// 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
|
| 3 |
+
// x[B, V] bfloat16 row-major in, out[B, V] bfloat16 row-major out.
|
| 4 |
+
// Rows are LONG (V = 131072) and a few of them carry logits large enough that exp() overflows fp32
|
| 5 |
+
// unless the row max is subtracted first -- the numerically stable form is required, not optional.
|
| 6 |
+
// Inputs are generated ON DEVICE from the seed (deterministic and fast).
|
| 7 |
+
// The naive reference is one thread per row, three sequential passes over the row.
|
| 8 |
+
#include <cuda_runtime.h>
|
| 9 |
+
#include <cuda_bf16.h>
|
| 10 |
+
#include <cstdio>
|
| 11 |
+
#include <cstdlib>
|
| 12 |
+
#include <cmath>
|
| 13 |
+
#include <vector>
|
| 14 |
+
#include <algorithm>
|
| 15 |
+
|
| 16 |
+
#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)
|
| 17 |
+
|
| 18 |
+
static const int B = 4096, V = 131072; // 5.4e8 elements: 1.07 GB in, 1.07 GB out
|
| 19 |
+
static const float TOL = 5e-3f;
|
| 20 |
+
#ifndef R_BAR
|
| 21 |
+
#define R_BAR 29.0f
|
| 22 |
+
#endif
|
| 23 |
+
|
| 24 |
+
// ---- the agent's kernel ------------------------------------------------------------------------
|
| 25 |
+
void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_);
|
| 26 |
+
|
| 27 |
+
// ---- deterministic device-side input generation -------------------------------------------------
|
| 28 |
+
__device__ __forceinline__ unsigned mix(unsigned a){
|
| 29 |
+
a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a;
|
| 30 |
+
}
|
| 31 |
+
__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); }
|
| 32 |
+
|
| 33 |
+
__global__ void gen_kernel(__nv_bfloat16* x, long n, int V_, unsigned seed){
|
| 34 |
+
for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){
|
| 35 |
+
unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed);
|
| 36 |
+
float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u);
|
| 37 |
+
float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2);
|
| 38 |
+
int row = (int)(i / V_);
|
| 39 |
+
// most rows are ordinary attention-scale logits; every 97th row is an outlier row whose
|
| 40 |
+
// logits reach ~140, so exp() overflows fp32 if the row max is not subtracted first
|
| 41 |
+
float sc = (row % 97 == 0) ? 30.0f : 3.0f;
|
| 42 |
+
x[i] = __float2bfloat16(g * sc);
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// ---- naive reference: one thread per row, three sequential passes --------------------------------
|
| 47 |
+
__global__ void naive_kernel(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_){
|
| 48 |
+
for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < B_; r += (long)gridDim.x * blockDim.x){
|
| 49 |
+
const __nv_bfloat16* xr = x + r * (long)V_;
|
| 50 |
+
__nv_bfloat16* orow = out + r * (long)V_;
|
| 51 |
+
float m = -INFINITY;
|
| 52 |
+
for(int j = 0; j < V_; j++) m = fmaxf(m, __bfloat162float(xr[j]));
|
| 53 |
+
float s = 0.f;
|
| 54 |
+
for(int j = 0; j < V_; j++) s += expf(__bfloat162float(xr[j]) - m);
|
| 55 |
+
float inv = 1.f / s;
|
| 56 |
+
for(int j = 0; j < V_; j++) orow[j] = __float2bfloat16(expf(__bfloat162float(xr[j]) - m) * inv);
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// ---- comparison: relative Frobenius --------------------------------------------------------------
|
| 61 |
+
__global__ void cmp_kernel(const __nv_bfloat16* a, const __nv_bfloat16* b, long n, double* acc){
|
| 62 |
+
__shared__ double sn[256], sd[256];
|
| 63 |
+
double num = 0.0, den = 0.0;
|
| 64 |
+
for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){
|
| 65 |
+
double va = (double)__bfloat162float(a[i]), vb = (double)__bfloat162float(b[i]);
|
| 66 |
+
if(!isfinite(va)) va = 1e30; // an inf/nan from an unstable kernel must not pass
|
| 67 |
+
num += (va - vb) * (va - vb);
|
| 68 |
+
den += vb * vb;
|
| 69 |
+
}
|
| 70 |
+
sn[threadIdx.x] = num; sd[threadIdx.x] = den;
|
| 71 |
+
__syncthreads();
|
| 72 |
+
for(int o = blockDim.x >> 1; o; o >>= 1){
|
| 73 |
+
if(threadIdx.x < o){ sn[threadIdx.x] += sn[threadIdx.x + o]; sd[threadIdx.x] += sd[threadIdx.x + o]; }
|
| 74 |
+
__syncthreads();
|
| 75 |
+
}
|
| 76 |
+
if(threadIdx.x == 0){ atomicAdd(acc, sn[0]); atomicAdd(acc + 1, sd[0]); }
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
typedef void(*Fn)(const __nv_bfloat16*, __nv_bfloat16*);
|
| 80 |
+
static float time_ms(Fn run, const __nv_bfloat16* a, __nv_bfloat16* b, int warm, int iters){
|
| 81 |
+
cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1));
|
| 82 |
+
for(int i = 0; i < warm; i++) run(a, b);
|
| 83 |
+
CK(cudaDeviceSynchronize());
|
| 84 |
+
std::vector<float> ts;
|
| 85 |
+
for(int i = 0; i < iters; i++){
|
| 86 |
+
CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1));
|
| 87 |
+
CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms);
|
| 88 |
+
}
|
| 89 |
+
std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2];
|
| 90 |
+
}
|
| 91 |
+
static void run_naive(const __nv_bfloat16* a, __nv_bfloat16* b){ naive_kernel<<<64, 64>>>(a, b, B, V); }
|
| 92 |
+
static void run_agent(const __nv_bfloat16* a, __nv_bfloat16* b){ row_softmax(a, b, B, V); }
|
| 93 |
+
|
| 94 |
+
int main(int argc, char** argv){
|
| 95 |
+
unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u;
|
| 96 |
+
long n = (long)B * V;
|
| 97 |
+
__nv_bfloat16 *x, *oref, *oag; double* acc;
|
| 98 |
+
CK(cudaMalloc(&x, n * 2)); CK(cudaMalloc(&oref, n * 2)); CK(cudaMalloc(&oag, n * 2));
|
| 99 |
+
CK(cudaMalloc(&acc, 16)); CK(cudaMemset(acc, 0, 16)); CK(cudaMemset(oag, 0, n * 2));
|
| 100 |
+
gen_kernel<<<1024, 256>>>(x, n, V, seed);
|
| 101 |
+
CK(cudaDeviceSynchronize());
|
| 102 |
+
|
| 103 |
+
run_naive(x, oref); CK(cudaDeviceSynchronize());
|
| 104 |
+
run_agent(x, oag); CK(cudaDeviceSynchronize());
|
| 105 |
+
cudaError_t ge = cudaGetLastError();
|
| 106 |
+
|
| 107 |
+
cmp_kernel<<<1024, 256>>>(oag, oref, n, acc);
|
| 108 |
+
CK(cudaDeviceSynchronize());
|
| 109 |
+
double h[2]; CK(cudaMemcpy(h, acc, 16, cudaMemcpyDeviceToHost));
|
| 110 |
+
double rel = sqrt(h[0] / (h[1] + 1e-30));
|
| 111 |
+
|
| 112 |
+
float tn = time_ms(run_naive, x, oref, 1, 3);
|
| 113 |
+
float ta = time_ms(run_agent, x, oag, 5, 30);
|
| 114 |
+
float sp = tn / ta;
|
| 115 |
+
bool correct = (ge == cudaSuccess) && (rel < TOL);
|
| 116 |
+
bool fast = sp >= R_BAR;
|
| 117 |
+
double reward = (correct && fast) ? 1.0 : 0.0;
|
| 118 |
+
printf("rel_err=%.3e | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d "
|
| 119 |
+
"-> reward=%.1f\n", rel, tn, ta, sp, (float)R_BAR, correct, fast, reward);
|
| 120 |
+
if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge));
|
| 121 |
+
system("mkdir -p /logs/verifier");
|
| 122 |
+
FILE* f = fopen("/logs/verifier/reward.json", "w");
|
| 123 |
+
if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"rel_err\": %.3e, "
|
| 124 |
+
"\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n",
|
| 125 |
+
reward, correct, fast, rel, tn, ta, sp); fclose(f); }
|
| 126 |
+
FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); }
|
| 127 |
+
return 0;
|
| 128 |
+
}
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone
|
| 5 |
+
# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is
|
| 6 |
+
# pre-installed (harbor's patched installer skips the network install when it is already present), so no
|
| 7 |
+
# package index is needed at run time.
|
| 8 |
+
#
|
| 9 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they
|
| 10 |
+
# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 11 |
+
set -uo pipefail
|
| 12 |
+
|
| 13 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 14 |
+
API_HOSTS=(
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/raw-cuda/cuda-blockwise-softmax/environment/solution.cu
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// solution.cu — implement the row-wise softmax described in the instruction.
|
| 2 |
+
// m[b] = max over v of x[b,v]
|
| 3 |
+
// out[b,v] = exp(x[b,v] - m[b]) / sum_v exp(x[b,v] - m[b])
|
| 4 |
+
// x[B,V] and out[B,V] are bfloat16 row-major; all arithmetic in fp32. B = 4096, V = 131072 (fixed).
|
| 5 |
+
// Some rows carry logits near 140, so the max MUST be subtracted before exp() or fp32 overflows.
|
| 6 |
+
// This stub writes zeros (it compiles and runs, but is incorrect — reward 0).
|
| 7 |
+
#include <cuda_runtime.h>
|
| 8 |
+
#include <cuda_bf16.h>
|
| 9 |
+
|
| 10 |
+
__global__ void stub_k(__nv_bfloat16* out, long n){
|
| 11 |
+
long i = (long)blockIdx.x * blockDim.x + threadIdx.x;
|
| 12 |
+
if(i < n) out[i] = __float2bfloat16(0.f);
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V){
|
| 16 |
+
long n = (long)B * V;
|
| 17 |
+
stub_k<<<(n + 255) / 256, 256>>>(out, n);
|
| 18 |
+
}
|
tasks/raw-cuda/cuda-blockwise-softmax/instruction.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast CUDA kernel for a row-wise softmax over very long rows
|
| 2 |
+
|
| 3 |
+
Implement a high-performance CUDA kernel in `/app/solution.cu` that softmaxes each row of a large `bfloat16`
|
| 4 |
+
matrix — the shape a vocabulary-sized logits matrix or a long attention-score row has.
|
| 5 |
+
|
| 6 |
+
Input: `x` of shape `[B, V]` (`__nv_bfloat16`, row-major). Output: `out` of shape `[B, V]`
|
| 7 |
+
(`__nv_bfloat16`, row-major). For each row `b`:
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
m[b] = max over v of x[b, v]
|
| 11 |
+
s[b] = sum over v of exp( x[b, v] - m[b] )
|
| 12 |
+
out[b,v] = exp( x[b, v] - m[b] ) / s[b]
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
All arithmetic in **fp32**; only the stored result is bfloat16. The sizes are fixed:
|
| 16 |
+
**B = 4096, V = 131072** — 1.07 GB in, 1.07 GB out, and a row is 256 KB.
|
| 17 |
+
|
| 18 |
+
**Subtracting the row max is required, not an optimisation.** Roughly one row in a hundred is an outlier row
|
| 19 |
+
whose logits reach ~140, and `expf(140)` overflows fp32. A kernel that computes `exp(x)/sum(exp(x))`
|
| 20 |
+
directly produces `inf`/`nan` on those rows and fails the correctness gate.
|
| 21 |
+
|
| 22 |
+
The function signature (fixed) is in `/app/solution.cu`:
|
| 23 |
+
```cpp
|
| 24 |
+
void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V);
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
## How success is decided
|
| 28 |
+
|
| 29 |
+
The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and
|
| 30 |
+
checks:
|
| 31 |
+
1. **Correctness** — relative Frobenius error below **5e-3** against the reference (non-finite outputs are
|
| 32 |
+
scored as maximally wrong). That gate is measured: the reference sums each row **sequentially** in fp32
|
| 33 |
+
while any block-parallel kernel sums it as a tree, and with a bf16 output that difference alone measures
|
| 34 |
+
**8e-4 – 9.5e-4**. The gate is ~5x that, which covers reduction order and a fast `expf`, and is nowhere
|
| 35 |
+
near loose enough to admit a softmax over the wrong axis or an unstable one.
|
| 36 |
+
2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event
|
| 37 |
+
timed, warmup + median; the exact bar is printed when you build).
|
| 38 |
+
|
| 39 |
+
Both must pass for reward 1.0.
|
| 40 |
+
|
| 41 |
+
## Notes
|
| 42 |
+
|
| 43 |
+
- The reference the bar is measured against is **one thread per row**, walking the row **three times** (max,
|
| 44 |
+
then sum, then normalise). It is uncoalesced *and* it makes three trips over the data — both are worth
|
| 45 |
+
fixing, and only one of them is obvious.
|
| 46 |
+
- A row is 256 KB, so it does not fit in registers or shared memory: you cannot keep it on chip between
|
| 47 |
+
passes. But you do not need three passes either — the max and the sum can be accumulated **together** in a
|
| 48 |
+
single sweep if you carry a running `(max, sum)` pair and rescale the sum whenever the max moves
|
| 49 |
+
(`s <- s * exp(m_old - m_new)`). That is the standard online-softmax recurrence, and it turns three passes
|
| 50 |
+
over HBM into two.
|
| 51 |
+
- One block per row is the natural decomposition (`B = 4096` rows, so there is plenty of parallelism). Inside
|
| 52 |
+
the block you need a max reduction and a sum reduction; warp shuffles plus a small shared-memory stage are
|
| 53 |
+
enough, and a block-wide barrier per row is unavoidable — but there should be only **one** of each.
|
| 54 |
+
- Vectorise: an element is 2 bytes and a 128-bit access moves 8 of them, on both the load and the store side.
|
| 55 |
+
- Think about where the second pass reads from. The rows a wave of blocks is working on are a few tens of MB
|
| 56 |
+
in total, which is not nothing relative to the L2 you can query with `cudaGetDeviceProperties` — how many
|
| 57 |
+
blocks you keep resident changes whether the re-read is an HBM read or an L2 hit.
|
| 58 |
+
- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer**
|
| 59 |
+
(`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA, including block-wide reductions), and the
|
| 60 |
+
profilers **`ncu`** and **`nsys`**. There is **no PyTorch and no Triton**; this is a pure CUDA task.
|
| 61 |
+
- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader
|
| 62 |
+
uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how
|
| 63 |
+
you are measured; you only edit `solution.cu`.
|
| 64 |
+
- **No internet access.**
|
tasks/raw-cuda/cuda-blockwise-softmax/solution/solution.oracle.cu
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Oracle: one block per row, ONLINE softmax so the row is read twice instead of three times.
|
| 2 |
+
// pass 1: running (max, sum) with rescaling -> block reduce -> (m, S)
|
| 3 |
+
// pass 2: re-read the row and emit exp(x-m)/S
|
| 4 |
+
// 128-bit loads and stores (8 bf16 per access); everything in fp32.
|
| 5 |
+
#include <cuda_runtime.h>
|
| 6 |
+
#include <cuda_bf16.h>
|
| 7 |
+
|
| 8 |
+
#define NTHREAD 512
|
| 9 |
+
|
| 10 |
+
__global__ __launch_bounds__(NTHREAD) void softmax_k(const __nv_bfloat16* __restrict__ x,
|
| 11 |
+
__nv_bfloat16* __restrict__ out, int V){
|
| 12 |
+
const long row = blockIdx.x;
|
| 13 |
+
const uint4* xr = reinterpret_cast<const uint4*>(x + row * (long)V);
|
| 14 |
+
uint4* orow = reinterpret_cast<uint4*>(out + row * (long)V);
|
| 15 |
+
const int nvec = V / 8;
|
| 16 |
+
|
| 17 |
+
float m = -INFINITY, s = 0.f;
|
| 18 |
+
for(int i = threadIdx.x; i < nvec; i += NTHREAD){ // online max+sum
|
| 19 |
+
uint4 v = xr[i];
|
| 20 |
+
const __nv_bfloat16* h = reinterpret_cast<const __nv_bfloat16*>(&v);
|
| 21 |
+
float lm = -INFINITY;
|
| 22 |
+
#pragma unroll
|
| 23 |
+
for(int j = 0; j < 8; j++) lm = fmaxf(lm, __bfloat162float(h[j]));
|
| 24 |
+
if(lm > m){ s *= __expf(m - lm); m = lm; }
|
| 25 |
+
#pragma unroll
|
| 26 |
+
for(int j = 0; j < 8; j++) s += __expf(__bfloat162float(h[j]) - m);
|
| 27 |
+
}
|
| 28 |
+
// block reduce: max first, then rescale each lane's sum onto it
|
| 29 |
+
__shared__ float sm[NTHREAD / 32], ss[NTHREAD / 32];
|
| 30 |
+
float mm = m;
|
| 31 |
+
for(int o = 16; o; o >>= 1) mm = fmaxf(mm, __shfl_xor_sync(0xffffffff, mm, o));
|
| 32 |
+
if((threadIdx.x & 31) == 0) sm[threadIdx.x >> 5] = mm;
|
| 33 |
+
__syncthreads();
|
| 34 |
+
if(threadIdx.x < 32){
|
| 35 |
+
float v = (threadIdx.x < NTHREAD / 32) ? sm[threadIdx.x] : -INFINITY;
|
| 36 |
+
for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o));
|
| 37 |
+
if(threadIdx.x == 0) sm[0] = v;
|
| 38 |
+
}
|
| 39 |
+
__syncthreads();
|
| 40 |
+
const float M = sm[0];
|
| 41 |
+
float sv = s * __expf(m - M);
|
| 42 |
+
for(int o = 16; o; o >>= 1) sv += __shfl_xor_sync(0xffffffff, sv, o);
|
| 43 |
+
if((threadIdx.x & 31) == 0) ss[threadIdx.x >> 5] = sv;
|
| 44 |
+
__syncthreads();
|
| 45 |
+
if(threadIdx.x < 32){
|
| 46 |
+
float v = (threadIdx.x < NTHREAD / 32) ? ss[threadIdx.x] : 0.f;
|
| 47 |
+
for(int o = 16; o; o >>= 1) v += __shfl_xor_sync(0xffffffff, v, o);
|
| 48 |
+
if(threadIdx.x == 0) ss[0] = v;
|
| 49 |
+
}
|
| 50 |
+
__syncthreads();
|
| 51 |
+
const float inv = 1.0f / ss[0];
|
| 52 |
+
|
| 53 |
+
for(int i = threadIdx.x; i < nvec; i += NTHREAD){
|
| 54 |
+
uint4 v = xr[i];
|
| 55 |
+
const __nv_bfloat16* h = reinterpret_cast<const __nv_bfloat16*>(&v);
|
| 56 |
+
__nv_bfloat16 o8[8];
|
| 57 |
+
#pragma unroll
|
| 58 |
+
for(int j = 0; j < 8; j++) o8[j] = __float2bfloat16(__expf(__bfloat162float(h[j]) - M) * inv);
|
| 59 |
+
orow[i] = *reinterpret_cast<const uint4*>(o8);
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V){
|
| 64 |
+
softmax_k<<<B, NTHREAD>>>(x, out, V);
|
| 65 |
+
}
|
tasks/raw-cuda/cuda-blockwise-softmax/solution/solve.sh
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Oracle: restore the reference fast kernel.
|
| 3 |
+
set -e
|
| 4 |
+
cat > /app/solution.cu <<'ORACLE_CU_EOF'
|
| 5 |
+
// Oracle: one block per row, ONLINE softmax so the row is read twice instead of three times.
|
| 6 |
+
// pass 1: running (max, sum) with rescaling -> block reduce -> (m, S)
|
| 7 |
+
// pass 2: re-read the row and emit exp(x-m)/S
|
| 8 |
+
// 128-bit loads and stores (8 bf16 per access); everything in fp32.
|
| 9 |
+
#include <cuda_runtime.h>
|
| 10 |
+
#include <cuda_bf16.h>
|
| 11 |
+
|
| 12 |
+
#define NTHREAD 512
|
| 13 |
+
|
| 14 |
+
__global__ __launch_bounds__(NTHREAD) void softmax_k(const __nv_bfloat16* __restrict__ x,
|
| 15 |
+
__nv_bfloat16* __restrict__ out, int V){
|
| 16 |
+
const long row = blockIdx.x;
|
| 17 |
+
const uint4* xr = reinterpret_cast<const uint4*>(x + row * (long)V);
|
| 18 |
+
uint4* orow = reinterpret_cast<uint4*>(out + row * (long)V);
|
| 19 |
+
const int nvec = V / 8;
|
| 20 |
+
|
| 21 |
+
float m = -INFINITY, s = 0.f;
|
| 22 |
+
for(int i = threadIdx.x; i < nvec; i += NTHREAD){ // online max+sum
|
| 23 |
+
uint4 v = xr[i];
|
| 24 |
+
const __nv_bfloat16* h = reinterpret_cast<const __nv_bfloat16*>(&v);
|
| 25 |
+
float lm = -INFINITY;
|
| 26 |
+
#pragma unroll
|
| 27 |
+
for(int j = 0; j < 8; j++) lm = fmaxf(lm, __bfloat162float(h[j]));
|
| 28 |
+
if(lm > m){ s *= __expf(m - lm); m = lm; }
|
| 29 |
+
#pragma unroll
|
| 30 |
+
for(int j = 0; j < 8; j++) s += __expf(__bfloat162float(h[j]) - m);
|
| 31 |
+
}
|
| 32 |
+
// block reduce: max first, then rescale each lane's sum onto it
|
| 33 |
+
__shared__ float sm[NTHREAD / 32], ss[NTHREAD / 32];
|
| 34 |
+
float mm = m;
|
| 35 |
+
for(int o = 16; o; o >>= 1) mm = fmaxf(mm, __shfl_xor_sync(0xffffffff, mm, o));
|
| 36 |
+
if((threadIdx.x & 31) == 0) sm[threadIdx.x >> 5] = mm;
|
| 37 |
+
__syncthreads();
|
| 38 |
+
if(threadIdx.x < 32){
|
| 39 |
+
float v = (threadIdx.x < NTHREAD / 32) ? sm[threadIdx.x] : -INFINITY;
|
| 40 |
+
for(int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o));
|
| 41 |
+
if(threadIdx.x == 0) sm[0] = v;
|
| 42 |
+
}
|
| 43 |
+
__syncthreads();
|
| 44 |
+
const float M = sm[0];
|
| 45 |
+
float sv = s * __expf(m - M);
|
| 46 |
+
for(int o = 16; o; o >>= 1) sv += __shfl_xor_sync(0xffffffff, sv, o);
|
| 47 |
+
if((threadIdx.x & 31) == 0) ss[threadIdx.x >> 5] = sv;
|
| 48 |
+
__syncthreads();
|
| 49 |
+
if(threadIdx.x < 32){
|
| 50 |
+
float v = (threadIdx.x < NTHREAD / 32) ? ss[threadIdx.x] : 0.f;
|
| 51 |
+
for(int o = 16; o; o >>= 1) v += __shfl_xor_sync(0xffffffff, v, o);
|
| 52 |
+
if(threadIdx.x == 0) ss[0] = v;
|
| 53 |
+
}
|
| 54 |
+
__syncthreads();
|
| 55 |
+
const float inv = 1.0f / ss[0];
|
| 56 |
+
|
| 57 |
+
for(int i = threadIdx.x; i < nvec; i += NTHREAD){
|
| 58 |
+
uint4 v = xr[i];
|
| 59 |
+
const __nv_bfloat16* h = reinterpret_cast<const __nv_bfloat16*>(&v);
|
| 60 |
+
__nv_bfloat16 o8[8];
|
| 61 |
+
#pragma unroll
|
| 62 |
+
for(int j = 0; j < 8; j++) o8[j] = __float2bfloat16(__expf(__bfloat162float(h[j]) - M) * inv);
|
| 63 |
+
orow[i] = *reinterpret_cast<const uint4*>(o8);
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B, int V){
|
| 68 |
+
softmax_k<<<B, NTHREAD>>>(x, out, V);
|
| 69 |
+
}
|
| 70 |
+
ORACLE_CU_EOF
|
| 71 |
+
echo restored
|
tasks/raw-cuda/cuda-blockwise-softmax/task.toml
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.1"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "mle-bench/cuda-blockwise-softmax"
|
| 5 |
+
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."
|
| 6 |
+
authors = []
|
| 7 |
+
keywords = [ "mle", "kernel-generation", "cuda", "softmax", "online-softmax", "reduction", "bandwidth", "gpu",]
|
| 8 |
+
|
| 9 |
+
[metadata]
|
| 10 |
+
suite = "mle-bench"
|
| 11 |
+
group = "kernel-generation"
|
| 12 |
+
level = "1.0"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
category = "mle"
|
| 15 |
+
tags = [ "mle", "kernel-generation", "cuda", "gpu", "performance", "real-world",]
|
| 16 |
+
|
| 17 |
+
[verifier]
|
| 18 |
+
timeout_sec = 600.0
|
| 19 |
+
|
| 20 |
+
[agent]
|
| 21 |
+
timeout_sec = 14400.0
|
| 22 |
+
|
| 23 |
+
[environment]
|
| 24 |
+
build_timeout_sec = 3600.0
|
| 25 |
+
cpus = 8
|
| 26 |
+
memory_mb = 32768
|
| 27 |
+
storage_mb = 40960
|
| 28 |
+
gpus = 1
|
| 29 |
+
network_mode = "public"
|
| 30 |
+
mcp_servers = []
|
| 31 |
+
|
| 32 |
+
[verifier.env]
|
| 33 |
+
|
| 34 |
+
[environment.env]
|
| 35 |
+
|
| 36 |
+
[solution.env]
|
tasks/raw-cuda/cuda-blockwise-softmax/tests/harness.cu
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Grading harness for cuda-blockwise-softmax.
|
| 2 |
+
// 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
|
| 3 |
+
// x[B, V] bfloat16 row-major in, out[B, V] bfloat16 row-major out.
|
| 4 |
+
// Rows are LONG (V = 131072) and a few of them carry logits large enough that exp() overflows fp32
|
| 5 |
+
// unless the row max is subtracted first -- the numerically stable form is required, not optional.
|
| 6 |
+
// Inputs are generated ON DEVICE from the seed (deterministic and fast).
|
| 7 |
+
// The naive reference is one thread per row, three sequential passes over the row.
|
| 8 |
+
#include <cuda_runtime.h>
|
| 9 |
+
#include <cuda_bf16.h>
|
| 10 |
+
#include <cstdio>
|
| 11 |
+
#include <cstdlib>
|
| 12 |
+
#include <cmath>
|
| 13 |
+
#include <vector>
|
| 14 |
+
#include <algorithm>
|
| 15 |
+
|
| 16 |
+
#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)
|
| 17 |
+
|
| 18 |
+
static const int B = 4096, V = 131072; // 5.4e8 elements: 1.07 GB in, 1.07 GB out
|
| 19 |
+
static const float TOL = 5e-3f;
|
| 20 |
+
#ifndef R_BAR
|
| 21 |
+
#define R_BAR 29.0f
|
| 22 |
+
#endif
|
| 23 |
+
|
| 24 |
+
// ---- the agent's kernel ------------------------------------------------------------------------
|
| 25 |
+
void row_softmax(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_);
|
| 26 |
+
|
| 27 |
+
// ---- deterministic device-side input generation -------------------------------------------------
|
| 28 |
+
__device__ __forceinline__ unsigned mix(unsigned a){
|
| 29 |
+
a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a;
|
| 30 |
+
}
|
| 31 |
+
__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); }
|
| 32 |
+
|
| 33 |
+
__global__ void gen_kernel(__nv_bfloat16* x, long n, int V_, unsigned seed){
|
| 34 |
+
for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){
|
| 35 |
+
unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed);
|
| 36 |
+
float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u);
|
| 37 |
+
float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2);
|
| 38 |
+
int row = (int)(i / V_);
|
| 39 |
+
// most rows are ordinary attention-scale logits; every 97th row is an outlier row whose
|
| 40 |
+
// logits reach ~140, so exp() overflows fp32 if the row max is not subtracted first
|
| 41 |
+
float sc = (row % 97 == 0) ? 30.0f : 3.0f;
|
| 42 |
+
x[i] = __float2bfloat16(g * sc);
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// ---- naive reference: one thread per row, three sequential passes --------------------------------
|
| 47 |
+
__global__ void naive_kernel(const __nv_bfloat16* x, __nv_bfloat16* out, int B_, int V_){
|
| 48 |
+
for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < B_; r += (long)gridDim.x * blockDim.x){
|
| 49 |
+
const __nv_bfloat16* xr = x + r * (long)V_;
|
| 50 |
+
__nv_bfloat16* orow = out + r * (long)V_;
|
| 51 |
+
float m = -INFINITY;
|
| 52 |
+
for(int j = 0; j < V_; j++) m = fmaxf(m, __bfloat162float(xr[j]));
|
| 53 |
+
float s = 0.f;
|
| 54 |
+
for(int j = 0; j < V_; j++) s += expf(__bfloat162float(xr[j]) - m);
|
| 55 |
+
float inv = 1.f / s;
|
| 56 |
+
for(int j = 0; j < V_; j++) orow[j] = __float2bfloat16(expf(__bfloat162float(xr[j]) - m) * inv);
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// ---- comparison: relative Frobenius --------------------------------------------------------------
|
| 61 |
+
__global__ void cmp_kernel(const __nv_bfloat16* a, const __nv_bfloat16* b, long n, double* acc){
|
| 62 |
+
__shared__ double sn[256], sd[256];
|
| 63 |
+
double num = 0.0, den = 0.0;
|
| 64 |
+
for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){
|
| 65 |
+
double va = (double)__bfloat162float(a[i]), vb = (double)__bfloat162float(b[i]);
|
| 66 |
+
if(!isfinite(va)) va = 1e30; // an inf/nan from an unstable kernel must not pass
|
| 67 |
+
num += (va - vb) * (va - vb);
|
| 68 |
+
den += vb * vb;
|
| 69 |
+
}
|
| 70 |
+
sn[threadIdx.x] = num; sd[threadIdx.x] = den;
|
| 71 |
+
__syncthreads();
|
| 72 |
+
for(int o = blockDim.x >> 1; o; o >>= 1){
|
| 73 |
+
if(threadIdx.x < o){ sn[threadIdx.x] += sn[threadIdx.x + o]; sd[threadIdx.x] += sd[threadIdx.x + o]; }
|
| 74 |
+
__syncthreads();
|
| 75 |
+
}
|
| 76 |
+
if(threadIdx.x == 0){ atomicAdd(acc, sn[0]); atomicAdd(acc + 1, sd[0]); }
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
typedef void(*Fn)(const __nv_bfloat16*, __nv_bfloat16*);
|
| 80 |
+
static float time_ms(Fn run, const __nv_bfloat16* a, __nv_bfloat16* b, int warm, int iters){
|
| 81 |
+
cudaEvent_t ev0, ev1; CK(cudaEventCreate(&ev0)); CK(cudaEventCreate(&ev1));
|
| 82 |
+
for(int i = 0; i < warm; i++) run(a, b);
|
| 83 |
+
CK(cudaDeviceSynchronize());
|
| 84 |
+
std::vector<float> ts;
|
| 85 |
+
for(int i = 0; i < iters; i++){
|
| 86 |
+
CK(cudaEventRecord(ev0)); run(a, b); CK(cudaEventRecord(ev1));
|
| 87 |
+
CK(cudaEventSynchronize(ev1)); float ms; CK(cudaEventElapsedTime(&ms, ev0, ev1)); ts.push_back(ms);
|
| 88 |
+
}
|
| 89 |
+
std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2];
|
| 90 |
+
}
|
| 91 |
+
static void run_naive(const __nv_bfloat16* a, __nv_bfloat16* b){ naive_kernel<<<64, 64>>>(a, b, B, V); }
|
| 92 |
+
static void run_agent(const __nv_bfloat16* a, __nv_bfloat16* b){ row_softmax(a, b, B, V); }
|
| 93 |
+
|
| 94 |
+
int main(int argc, char** argv){
|
| 95 |
+
unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u;
|
| 96 |
+
long n = (long)B * V;
|
| 97 |
+
__nv_bfloat16 *x, *oref, *oag; double* acc;
|
| 98 |
+
CK(cudaMalloc(&x, n * 2)); CK(cudaMalloc(&oref, n * 2)); CK(cudaMalloc(&oag, n * 2));
|
| 99 |
+
CK(cudaMalloc(&acc, 16)); CK(cudaMemset(acc, 0, 16)); CK(cudaMemset(oag, 0, n * 2));
|
| 100 |
+
gen_kernel<<<1024, 256>>>(x, n, V, seed);
|
| 101 |
+
CK(cudaDeviceSynchronize());
|
| 102 |
+
|
| 103 |
+
run_naive(x, oref); CK(cudaDeviceSynchronize());
|
| 104 |
+
run_agent(x, oag); CK(cudaDeviceSynchronize());
|
| 105 |
+
cudaError_t ge = cudaGetLastError();
|
| 106 |
+
|
| 107 |
+
cmp_kernel<<<1024, 256>>>(oag, oref, n, acc);
|
| 108 |
+
CK(cudaDeviceSynchronize());
|
| 109 |
+
double h[2]; CK(cudaMemcpy(h, acc, 16, cudaMemcpyDeviceToHost));
|
| 110 |
+
double rel = sqrt(h[0] / (h[1] + 1e-30));
|
| 111 |
+
|
| 112 |
+
float tn = time_ms(run_naive, x, oref, 1, 3);
|
| 113 |
+
float ta = time_ms(run_agent, x, oag, 5, 30);
|
| 114 |
+
float sp = tn / ta;
|
| 115 |
+
bool correct = (ge == cudaSuccess) && (rel < TOL);
|
| 116 |
+
bool fast = sp >= R_BAR;
|
| 117 |
+
double reward = (correct && fast) ? 1.0 : 0.0;
|
| 118 |
+
printf("rel_err=%.3e | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | correct=%d fast=%d "
|
| 119 |
+
"-> reward=%.1f\n", rel, tn, ta, sp, (float)R_BAR, correct, fast, reward);
|
| 120 |
+
if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge));
|
| 121 |
+
system("mkdir -p /logs/verifier");
|
| 122 |
+
FILE* f = fopen("/logs/verifier/reward.json", "w");
|
| 123 |
+
if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"rel_err\": %.3e, "
|
| 124 |
+
"\"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n",
|
| 125 |
+
reward, correct, fast, rel, tn, ta, sp); fclose(f); }
|
| 126 |
+
FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); }
|
| 127 |
+
return 0;
|
| 128 |
+
}
|
tasks/raw-cuda/cuda-blockwise-softmax/tests/test.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Verifier: compile the FRESH harness + the agent's solution, grade with a random seed.
|
| 3 |
+
set -uo pipefail
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
SEED=$(( (RANDOM << 15) ^ RANDOM ))
|
| 6 |
+
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
|
| 7 |
+
if [ ! -x /tmp/grade ]; then
|
| 8 |
+
echo "COMPILE FAILED:"; tail -20 /tmp/nvcc.log
|
| 9 |
+
echo "0.0" > /logs/verifier/reward.txt
|
| 10 |
+
echo '{"reward": 0.0, "error": "compile_failed"}' > /logs/verifier/reward.json
|
| 11 |
+
exit 0
|
| 12 |
+
fi
|
| 13 |
+
/tmp/grade "$SEED" # the harness writes /logs/verifier/reward.{txt,json}
|
| 14 |
+
cat /logs/verifier/reward.json 2>/dev/null || true
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/Dockerfile
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CUDA kernel-generation task: write a fast per-token FP8 quantisation kernel in solution.cu.
|
| 2 |
+
# Toolchain only: nvcc / CUDA / CUTLASS / flashinfer + ncu/nsys. NO PyTorch, NO Triton.
|
| 3 |
+
FROM nvidia/cuda:12.8.1-devel-ubuntu24.04
|
| 4 |
+
|
| 5 |
+
# ncu ships in the devel image (/usr/local/cuda/bin/ncu); add nsys + build/firewall deps.
|
| 6 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
+
git ca-certificates curl iptables iproute2 nsight-compute nsight-systems && \
|
| 8 |
+
rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Header-only deps the agent's kernel may use (cloned at build time; runtime is firewalled).
|
| 11 |
+
# Keep only flashinfer's include/ — its python source (which contains a triton submodule) isn't needed,
|
| 12 |
+
# and dropping it keeps the environment free of any torch/triton files.
|
| 13 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git && \
|
| 14 |
+
git clone --depth 1 https://github.com/flashinfer-ai/flashinfer /tmp/fi && \
|
| 15 |
+
mkdir -p /opt/flashinfer && mv /tmp/fi/include /opt/flashinfer/include && rm -rf /tmp/fi
|
| 16 |
+
|
| 17 |
+
# Pre-bake the agent (the offline firewall blocks installing it at run time).
|
| 18 |
+
RUN curl -LsSf https://astral.sh/uv/install.sh | sh && /root/.local/bin/uv tool install mini-swe-agent
|
| 19 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 20 |
+
|
| 21 |
+
# Task workspace: the stub the agent edits, a dev copy of the grading harness, and a build helper.
|
| 22 |
+
WORKDIR /app
|
| 23 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 24 |
+
COPY solution.cu /app/solution.cu
|
| 25 |
+
COPY harness.cu /app/harness.cu
|
| 26 |
+
COPY build.sh /app/build.sh
|
| 27 |
+
RUN chmod +x /app/build.sh
|
| 28 |
+
|
| 29 |
+
# Offline firewall (allow the LLM API, block github/pypi/HF so reference kernels can't be fetched).
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
|
| 33 |
+
# Strip apt sources so harbor's base apt-setup is a no-op under the firewall.
|
| 34 |
+
RUN rm -rf /etc/apt/sources.list /etc/apt/sources.list.d /var/lib/apt/lists/*
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/build.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Compile your solution against the harness and run one seed (the grader uses a different seed).
|
| 3 |
+
set -e
|
| 4 |
+
nvcc -O3 -arch=native /app/harness.cu /app/solution.cu -I/opt/flashinfer/include -I/opt/cutlass/include -o /app/run
|
| 5 |
+
/app/run 0
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall + profiling caps, merged on top of Harbor's base compose.
|
| 2 |
+
# NET_ADMIN: restrict-network.sh installs the outbound allowlist (LLM API only; github/pypi/HF blocked).
|
| 3 |
+
# SYS_ADMIN: lets the agent run ncu (GPU performance counters) inside the container (the host has
|
| 4 |
+
# NVreg_RestrictProfilingToAdminUsers=0). network_mode stays "public" — the firewall enforces it.
|
| 5 |
+
services:
|
| 6 |
+
main:
|
| 7 |
+
cap_add:
|
| 8 |
+
- NET_ADMIN
|
| 9 |
+
- SYS_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 14 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 15 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 16 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 17 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/harness.cu
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Grading harness for cuda-fp8-cast-pack.
|
| 2 |
+
// Per-row (per-token) FP8 e4m3 activation quantisation:
|
| 3 |
+
// scale[m] = max( max_n |x[m,n]| , 1e-12f ) / 448.0f
|
| 4 |
+
// q[m,n] = fp8_e4m3( x[m,n] / scale[m] ) (round-to-nearest-even, saturating)
|
| 5 |
+
// x[M,N] bfloat16 row-major in; q[M,N] fp8_e4m3 + scale[M] float32 out.
|
| 6 |
+
// Inputs are generated ON DEVICE from the seed (deterministic, and fast enough to iterate on).
|
| 7 |
+
// The naive reference is one thread per row, two sequential passes over the row.
|
| 8 |
+
// Correctness: scales must agree to 1e-6 relative, and the DEQUANTISED values (q*scale) to 5e-3
|
| 9 |
+
// relative Frobenius -- which tolerates the odd 1-ulp code flip but not a wrong rounding rule.
|
| 10 |
+
#include <cuda_runtime.h>
|
| 11 |
+
#include <cuda_bf16.h>
|
| 12 |
+
#include <cuda_fp8.h>
|
| 13 |
+
#include <cstdio>
|
| 14 |
+
#include <cstdlib>
|
| 15 |
+
#include <cmath>
|
| 16 |
+
#include <vector>
|
| 17 |
+
#include <algorithm>
|
| 18 |
+
|
| 19 |
+
#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)
|
| 20 |
+
|
| 21 |
+
static const int M = 32768, N = 16384; // 5.4e8 elements: 1.07 GB in, 537 MB + 128 KB out
|
| 22 |
+
static const float FP8_MAX = 448.0f;
|
| 23 |
+
static const float TOL_DEQ = 5e-3f; // relative Frobenius on dequantised values
|
| 24 |
+
static const float TOL_SCALE = 1e-6f; // relative, per row
|
| 25 |
+
#ifndef R_BAR
|
| 26 |
+
#define R_BAR 20.0f
|
| 27 |
+
#endif
|
| 28 |
+
|
| 29 |
+
// ---- the agent's kernel ------------------------------------------------------------------------
|
| 30 |
+
void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M_, int N_);
|
| 31 |
+
|
| 32 |
+
// ---- deterministic device-side input generation -------------------------------------------------
|
| 33 |
+
__device__ __forceinline__ unsigned mix(unsigned a){
|
| 34 |
+
a ^= a >> 16; a *= 0x7feb352du; a ^= a >> 15; a *= 0x846ca68bu; a ^= a >> 16; return a;
|
| 35 |
+
}
|
| 36 |
+
__device__ __forceinline__ float unif(unsigned s){ return (mix(s) >> 8) * (1.0f / 16777216.0f); }
|
| 37 |
+
|
| 38 |
+
// gaussian-ish (Box-Muller) times a per-row magnitude that spans ~30x, so row scales really differ
|
| 39 |
+
__global__ void gen_kernel(__nv_bfloat16* x, long n, int N_, unsigned seed){
|
| 40 |
+
for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){
|
| 41 |
+
unsigned s = mix((unsigned)(i ^ (i >> 32)) * 2654435761u + seed);
|
| 42 |
+
float u1 = fmaxf(unif(s), 1e-7f), u2 = unif(s + 12345u);
|
| 43 |
+
float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2);
|
| 44 |
+
int row = (int)(i / N_);
|
| 45 |
+
float rs = expf(unif(mix(row * 9781u + seed)) * 3.4f - 1.7f);
|
| 46 |
+
x[i] = __float2bfloat16(g * rs);
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
// ---- naive reference: one thread per row, two sequential passes ----------------------------------
|
| 51 |
+
__global__ void naive_kernel(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M_, int N_){
|
| 52 |
+
for(long r = (long)blockIdx.x * blockDim.x + threadIdx.x; r < M_; r += (long)gridDim.x * blockDim.x){
|
| 53 |
+
const __nv_bfloat16* xr = x + r * (long)N_;
|
| 54 |
+
float amax = 0.f;
|
| 55 |
+
for(int j = 0; j < N_; j++) amax = fmaxf(amax, fabsf(__bfloat162float(xr[j])));
|
| 56 |
+
float s = fmaxf(amax, 1e-12f) / FP8_MAX;
|
| 57 |
+
scale[r] = s;
|
| 58 |
+
__nv_fp8_e4m3* qr = q + r * (long)N_;
|
| 59 |
+
for(int j = 0; j < N_; j++) qr[j] = __nv_fp8_e4m3(__bfloat162float(xr[j]) / s);
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
// ---- comparison ---------------------------------------------------------------------------------
|
| 64 |
+
__global__ void cmp_kernel(const __nv_fp8_e4m3* a, const float* sa, const __nv_fp8_e4m3* b,
|
| 65 |
+
const float* sb, long n, int N_, double* acc){
|
| 66 |
+
__shared__ double sn[256], sd[256];
|
| 67 |
+
double num = 0.0, den = 0.0;
|
| 68 |
+
for(long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (long)gridDim.x * blockDim.x){
|
| 69 |
+
int row = (int)(i / N_);
|
| 70 |
+
double va = (double)__half2float(__nv_cvt_fp8_to_halfraw(a[i].__x, __NV_E4M3)) * sa[row];
|
| 71 |
+
double vb = (double)__half2float(__nv_cvt_fp8_to_halfraw(b[i].__x, __NV_E4M3)) * sb[row];
|
| 72 |
+
num += (va - vb) * (va - vb);
|
| 73 |
+
den += vb * vb;
|
| 74 |
+
}
|
| 75 |
+
sn[threadIdx.x] = num; sd[threadIdx.x] = den;
|
| 76 |
+
__syncthreads();
|
| 77 |
+
for(int o = blockDim.x >> 1; o; o >>= 1){
|
| 78 |
+
if(threadIdx.x < o){ sn[threadIdx.x] += sn[threadIdx.x + o]; sd[threadIdx.x] += sd[threadIdx.x + o]; }
|
| 79 |
+
__syncthreads();
|
| 80 |
+
}
|
| 81 |
+
if(threadIdx.x == 0){ atomicAdd(acc, sn[0]); atomicAdd(acc + 1, sd[0]); }
|
| 82 |
+
}
|
| 83 |
+
__global__ void cmp_scale(const float* a, const float* b, int m, float* worst){
|
| 84 |
+
for(int i = blockIdx.x * blockDim.x + threadIdx.x; i < m; i += gridDim.x * blockDim.x){
|
| 85 |
+
float e = fabsf(a[i] - b[i]) / fmaxf(fabsf(b[i]), 1e-30f);
|
| 86 |
+
atomicMax((int*)worst, __float_as_int(e)); // all values are >= 0
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
typedef void(*Fn)(const __nv_bfloat16*, __nv_fp8_e4m3*, float*);
|
| 91 |
+
static float time_ms(Fn run, const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s, int warm, int iters){
|
| 92 |
+
cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b));
|
| 93 |
+
for(int i = 0; i < warm; i++) run(x, q, s);
|
| 94 |
+
CK(cudaDeviceSynchronize());
|
| 95 |
+
std::vector<float> ts;
|
| 96 |
+
for(int i = 0; i < iters; i++){
|
| 97 |
+
CK(cudaEventRecord(a)); run(x, q, s); CK(cudaEventRecord(b));
|
| 98 |
+
CK(cudaEventSynchronize(b)); float ms; CK(cudaEventElapsedTime(&ms, a, b)); ts.push_back(ms);
|
| 99 |
+
}
|
| 100 |
+
std::sort(ts.begin(), ts.end()); return ts[ts.size() / 2];
|
| 101 |
+
}
|
| 102 |
+
static void run_naive(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s){ naive_kernel<<<256, 128>>>(x, q, s, M, N); }
|
| 103 |
+
static void run_agent(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* s){ fp8_row_quant(x, q, s, M, N); }
|
| 104 |
+
|
| 105 |
+
int main(int argc, char** argv){
|
| 106 |
+
unsigned seed = argc > 1 ? (unsigned)atoi(argv[1]) : 1234u;
|
| 107 |
+
long n = (long)M * N;
|
| 108 |
+
__nv_bfloat16* x; __nv_fp8_e4m3 *qr, *qa; float *sr, *sa; double* acc; float* worst;
|
| 109 |
+
CK(cudaMalloc(&x, n * 2)); CK(cudaMalloc(&qr, n)); CK(cudaMalloc(&qa, n));
|
| 110 |
+
CK(cudaMalloc(&sr, M * 4)); CK(cudaMalloc(&sa, M * 4));
|
| 111 |
+
CK(cudaMalloc(&acc, 16)); CK(cudaMalloc(&worst, 4));
|
| 112 |
+
CK(cudaMemset(acc, 0, 16)); CK(cudaMemset(worst, 0, 4));
|
| 113 |
+
CK(cudaMemset(qa, 0, n)); CK(cudaMemset(sa, 0, M * 4));
|
| 114 |
+
gen_kernel<<<1024, 256>>>(x, n, N, seed);
|
| 115 |
+
CK(cudaDeviceSynchronize());
|
| 116 |
+
|
| 117 |
+
run_naive(x, qr, sr); CK(cudaDeviceSynchronize());
|
| 118 |
+
run_agent(x, qa, sa); CK(cudaDeviceSynchronize());
|
| 119 |
+
cudaError_t ge = cudaGetLastError();
|
| 120 |
+
|
| 121 |
+
cmp_kernel<<<1024, 256>>>(qa, sa, qr, sr, n, N, acc);
|
| 122 |
+
cmp_scale<<<64, 256>>>(sa, sr, M, worst);
|
| 123 |
+
CK(cudaDeviceSynchronize());
|
| 124 |
+
double h[2]; float ws;
|
| 125 |
+
CK(cudaMemcpy(h, acc, 16, cudaMemcpyDeviceToHost));
|
| 126 |
+
CK(cudaMemcpy(&ws, worst, 4, cudaMemcpyDeviceToHost));
|
| 127 |
+
double rel = sqrt(h[0] / (h[1] + 1e-30));
|
| 128 |
+
|
| 129 |
+
float tn = time_ms(run_naive, x, qr, sr, 1, 5);
|
| 130 |
+
float ta = time_ms(run_agent, x, qa, sa, 5, 30);
|
| 131 |
+
float sp = tn / ta;
|
| 132 |
+
bool correct = (ge == cudaSuccess) && (rel < TOL_DEQ) && (ws < TOL_SCALE);
|
| 133 |
+
bool fast = sp >= R_BAR;
|
| 134 |
+
double reward = (correct && fast) ? 1.0 : 0.0;
|
| 135 |
+
printf("rel_deq=%.3e scale_err=%.3e | naive=%.3f ms agent=%.3f ms speedup=%.2fx (bar %.2f) | "
|
| 136 |
+
"correct=%d fast=%d -> reward=%.1f\n", rel, ws, tn, ta, sp, (float)R_BAR, correct, fast, reward);
|
| 137 |
+
if(ge != cudaSuccess) printf("agent kernel error: %s\n", cudaGetErrorString(ge));
|
| 138 |
+
system("mkdir -p /logs/verifier");
|
| 139 |
+
FILE* f = fopen("/logs/verifier/reward.json", "w");
|
| 140 |
+
if(f){ fprintf(f, "{\"reward\": %.1f, \"correct\": %d, \"fast\": %d, \"rel_deq\": %.3e, "
|
| 141 |
+
"\"scale_err\": %.3e, \"naive_ms\": %.3f, \"agent_ms\": %.3f, \"speedup\": %.3f}\n",
|
| 142 |
+
reward, correct, fast, rel, ws, tn, ta, sp); fclose(f); }
|
| 143 |
+
FILE* ft = fopen("/logs/verifier/reward.txt", "w"); if(ft){ fprintf(ft, "%.1f\n", reward); fclose(ft); }
|
| 144 |
+
return 0;
|
| 145 |
+
}
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot fetch sglang's own Gemma4 implementation (`pip install sglang`, `git clone
|
| 5 |
+
# sgl-project/sglang`, HF) and copy it. The model is already staged in the image, and mini-swe-agent is
|
| 6 |
+
# pre-installed (harbor's patched installer skips the network install when it is already present), so no
|
| 7 |
+
# package index is needed at run time.
|
| 8 |
+
#
|
| 9 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they
|
| 10 |
+
# also apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 11 |
+
set -uo pipefail
|
| 12 |
+
|
| 13 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 14 |
+
API_HOSTS=(
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/raw-cuda/cuda-fp8-cast-pack/environment/solution.cu
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// solution.cu — implement the per-row FP8 quantisation described in the instruction.
|
| 2 |
+
// scale[m] = max( max_n |x[m,n]| , 1e-12f ) / 448.0f
|
| 3 |
+
// q[m,n] = fp8_e4m3( x[m,n] / scale[m] ) round-to-nearest-even, saturating
|
| 4 |
+
// x[M,N] is bfloat16 row-major; q[M,N] is float8_e4m3 row-major; scale[M] is float32.
|
| 5 |
+
// M = 32768, N = 16384 (fixed). Reductions and the division must be done in fp32.
|
| 6 |
+
// This stub writes zeros (it compiles and runs, but is incorrect — reward 0).
|
| 7 |
+
#include <cuda_runtime.h>
|
| 8 |
+
#include <cuda_bf16.h>
|
| 9 |
+
#include <cuda_fp8.h>
|
| 10 |
+
|
| 11 |
+
__global__ void stub_k(__nv_fp8_e4m3* q, float* s, long n, int m){
|
| 12 |
+
long i = (long)blockIdx.x * blockDim.x + threadIdx.x;
|
| 13 |
+
if(i < n) q[i] = __nv_fp8_e4m3(0.f);
|
| 14 |
+
if(i < m) s[i] = 1.f;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M, int N){
|
| 18 |
+
long n = (long)M * N;
|
| 19 |
+
stub_k<<<(n + 255) / 256, 256>>>(q, scale, n, M);
|
| 20 |
+
}
|
tasks/raw-cuda/cuda-fp8-cast-pack/instruction.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast CUDA kernel for per-token FP8 activation quantisation
|
| 2 |
+
|
| 3 |
+
Implement a high-performance CUDA kernel in `/app/solution.cu` that quantises a `bfloat16` activation matrix
|
| 4 |
+
to **float8_e4m3** with one scale per row — the step every FP8-served transformer runs in front of every GEMM.
|
| 5 |
+
|
| 6 |
+
Input: `x` of shape `[M, N]` (`__nv_bfloat16`, row-major). Outputs: `q` of shape `[M, N]` (`__nv_fp8_e4m3`,
|
| 7 |
+
row-major) and `scale` of shape `[M]` (`float`). For each row `m`:
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
amax = max over n of |x[m, n]| # computed in fp32
|
| 11 |
+
scale[m] = max(amax, 1e-12f) / 448.0f # 448 = max finite e4m3 magnitude
|
| 12 |
+
q[m, n] = fp8_e4m3( x[m, n] / scale[m] ) # round-to-nearest-even, saturating
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
so that `q[m,n] * scale[m]` reconstructs `x[m,n]` to FP8 accuracy. The sizes are fixed:
|
| 16 |
+
**M = 32768, N = 16384** — 1.07 GB in, 537 MB + 128 KB out.
|
| 17 |
+
|
| 18 |
+
The function signature (fixed) is in `/app/solution.cu`:
|
| 19 |
+
```cpp
|
| 20 |
+
void fp8_row_quant(const __nv_bfloat16* x, __nv_fp8_e4m3* q, float* scale, int M, int N);
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## How success is decided
|
| 24 |
+
|
| 25 |
+
The grader compiles your `solution.cu` against a fixed harness, generates seeded inputs on the device, and
|
| 26 |
+
checks:
|
| 27 |
+
1. **Correctness** — every `scale[m]` matches the reference to `1e-6` relative (the absmax is an exact
|
| 28 |
+
reduction, so a correct kernel matches it essentially exactly), and the dequantised values `q*scale` match
|
| 29 |
+
to `5e-3` relative Frobenius error. That tolerance absorbs the odd 1-ulp code flip — multiplying by
|
| 30 |
+
`1/scale` instead of dividing by `scale` measures `2e-3` and passes — but not a wrong rounding rule:
|
| 31 |
+
truncating instead of rounding to nearest scores about `4e-2`.
|
| 32 |
+
2. **Performance** — your kernel is at least **R×** faster than a straightforward reference (CUDA-event
|
| 33 |
+
timed, warmup + median; the exact bar is printed when you build).
|
| 34 |
+
|
| 35 |
+
Both must pass for reward 1.0.
|
| 36 |
+
|
| 37 |
+
## Notes
|
| 38 |
+
|
| 39 |
+
- This is a **pure bandwidth** problem: 1.07 GB has to come in and 537 MB has to go out, and the arithmetic
|
| 40 |
+
is one `fabsf`, one multiply and one conversion per element. Work out the roofline from the bandwidth you
|
| 41 |
+
measure (a large device-to-device copy is a good yardstick — do not trust a datasheet number), and treat
|
| 42 |
+
anything below it as a bug in your memory access pattern.
|
| 43 |
+
- The reference the bar is measured against is **one thread per row**, walking the row twice. Every element
|
| 44 |
+
it touches is uncoalesced, which is exactly the trap: the fix is to give each row a *block* (or a warp) so
|
| 45 |
+
that consecutive lanes read consecutive addresses.
|
| 46 |
+
- The scale for a row is not known until the whole row has been seen, so the obvious structure is two passes.
|
| 47 |
+
A row is `N * 2 = 32 KB`, which is small enough that it does **not** have to be re-read from HBM — think
|
| 48 |
+
about where you can keep it between the two passes, and how many rows a block should own.
|
| 49 |
+
- Access width matters on both sides: `x` is 2 bytes/element and `q` is 1, so a 128-bit load covers 8 inputs
|
| 50 |
+
while a 128-bit store covers 16 outputs. Getting the store side wrong is the most common way to leave
|
| 51 |
+
bandwidth on the table. `__nv_cvt_float2_to_fp8x2` converts two values per instruction.
|
| 52 |
+
- Available: `nvcc`, header-only **CUTLASS** (`/opt/cutlass/include`) and **flashinfer**
|
| 53 |
+
(`/opt/flashinfer/include`), **CUB/Thrust** (ship with CUDA), and the profilers **`ncu`** and **`nsys`**
|
| 54 |
+
(use them — `ncu` will tell you your achieved DRAM throughput directly). There is **no PyTorch and no
|
| 55 |
+
Triton**; this is a pure CUDA task.
|
| 56 |
+
- Query the device you actually get with `cudaGetDeviceProperties` (SM count, shared memory per block, L2
|
| 57 |
+
size) and size your launch from that rather than from constants.
|
| 58 |
+
- Build + test locally: **`bash /app/build.sh`** (compiles against the harness and runs one seed; the grader
|
| 59 |
+
uses a different seed). `/app/harness.cu` is the same harness used for grading — read it to see exactly how
|
| 60 |
+
you are measured; you only edit `solution.cu`.
|
| 61 |
+
- **No internet access.**
|