Upload FAI-Bench task files batch 45
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/.dockerignore +24 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/Dockerfile +176 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/compute_reward.py +86 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/gpu_peakmem.py +127 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/kb_ce_harness.py +185 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt +1 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test.sh +127 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test_cross_entropy_grad.py +222 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/manifest.json +11 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/sanitize_feedback.py +131 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/score_engine.sh +41 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/submit.sh +232 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/repo/cross_entropy_grad.py +106 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/entrypoint.sh +13 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/run_dev_bench.sh +5 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/timer.sh +7 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/verifier-correctness-manifest.json +31 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/instruction.md +143 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/pre_artifacts.sh +162 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/README.md +13 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/baseline2.patch +150 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/negative.patch +134 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/oracle.patch +279 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/solve.sh +159 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/task.toml +80 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/compute_reward.py +147 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/gpu_peakmem.py +127 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/kb_ce_harness.py +185 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.caveat.md +29 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.txt +1 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test.sh +127 -0
- tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test_cross_entropy_grad.py +222 -0
- tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt +1 -0
- tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/test.sh +128 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/.dockerignore +24 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/Dockerfile +154 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/manifest.json +13 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/compute_reward.py +30 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/test.sh +118 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/workload.py +167 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/sanitize_feedback.py +131 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/score_engine.sh +100 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/submit.sh +210 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/curriculum_cluster.py +112 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/gated_gelu.py +23 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/entrypoint.sh +13 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/run_dev_bench.sh +4 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/timer.sh +12 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/instruction.md +98 -0
- tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/pre_artifacts.sh +163 -0
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/.dockerignore
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does
|
| 2 |
+
# NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile .
|
| 3 |
+
# The reference implementation and every authoring artefact MUST NOT reach an image layer.
|
| 4 |
+
*.patch
|
| 5 |
+
oracle*
|
| 6 |
+
negative*
|
| 7 |
+
baseline2*
|
| 8 |
+
scope_card.json
|
| 9 |
+
degradation_manifest.json
|
| 10 |
+
task_meta.json
|
| 11 |
+
loop_map_entry.json
|
| 12 |
+
job.yaml
|
| 13 |
+
intermediates/
|
| 14 |
+
_retrofit*
|
| 15 |
+
sr_validate*
|
| 16 |
+
leak_audit/
|
| 17 |
+
self_check/
|
| 18 |
+
variants/
|
| 19 |
+
**/__pycache__/
|
| 20 |
+
**/*.pyc
|
| 21 |
+
*.bak
|
| 22 |
+
*.bak_*
|
| 23 |
+
*.pre_*
|
| 24 |
+
**/*.pre_*
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/Dockerfile
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# insea-fused-softmax-cross-entropy-grad-loop16 — OPEN-SOURCE, self-contained task image
|
| 4 |
+
#
|
| 5 |
+
# Task: make the declared scope faster while preserving its observable behaviour exactly.
|
| 6 |
+
# Editable scope (the ONLY files the scope gate allows to change):
|
| 7 |
+
## - /app/repo/cross_entropy_grad.py
|
| 8 |
+
#
|
| 9 |
+
# FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image.
|
| 10 |
+
# Needs 1 NVIDIA GPU to RUN (task.toml: gpus = 1, anchor calibrated on H20); no GPU to BUILD.
|
| 11 |
+
# Platform: linux/amd64 ONLY (official torch wheels are manylinux x86_64).
|
| 12 |
+
# Build context = this task directory (the Dockerfile lives in environment/).
|
| 13 |
+
#
|
| 14 |
+
# PROVENANCE of environment/repo/ (so anyone can re-derive it independently)
|
| 15 |
+
# recovered from: <internal registry>/kernelbench/insea-fused-softmax-cross-entropy-grad-loop16:loop-20260720T021136Z@sha256:dbd2b4dbf93aa3621d94de371a783ff2d77d7978cc4b93a6c19819d36a68a7f9
|
| 16 |
+
# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in
|
| 17 |
+
# manifest order; .git and any .wh..wh..opq marker dropped.
|
| 18 |
+
# verification: `git apply --check -p1 oracle.patch` succeeds against these bytes and `-R` does NOT — i.e. this tree is the exact baseline tree the reference patch was generated against.
|
| 19 |
+
##
|
| 20 |
+
# -----------------------------------------------------------------------------
|
| 21 |
+
# BUILD (needs outbound network for PyPI only — the working tree ships in this package)
|
| 22 |
+
# cd <...>/insea-fused-softmax-cross-entropy-grad-loop16/task
|
| 23 |
+
# docker build -f environment/Dockerfile -t fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss .
|
| 24 |
+
#
|
| 25 |
+
# RUN docker run --rm --gpus all -it fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss
|
| 26 |
+
# SCORE docker run --rm --gpus all -v "$PWD/tests:/tests:ro" fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss bash /tests/test.sh
|
| 27 |
+
# # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative)
|
| 28 |
+
#
|
| 29 |
+
# 🔴 RE-CALIBRATE THE ANCHOR ON YOUR HARDWARE
|
| 30 |
+
# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; ref_speedup = 7.4157 .
|
| 31 |
+
# tests/test.sh resolves it from tests/ref_speedup.txt FIRST, then falls back to
|
| 32 |
+
# /opt/verifier-correctness-manifest.json, then to 1.0 (which would make every reward 0).
|
| 33 |
+
# The value was calibrated on NVIDIA H20. The verifier supports mode dispatch natively, so
|
| 34 |
+
# re-measuring is ONE command (the reference patch is passed BY PATH and never baked):
|
| 35 |
+
# docker run --rm --gpus all -v "$PWD/tests:/tests:ro" -v "<dir holding oracle.patch>:/patches:ro" \
|
| 36 |
+
# -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \
|
| 37 |
+
# fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss bash /tests/test.sh
|
| 38 |
+
# then write the measured speedup into tests/ref_speedup.txt. See tests/ref_speedup.caveat.md.
|
| 39 |
+
# Sanity: noop (no patch) ~= 1.0 -> gated to 0; negative MUST score 0.
|
| 40 |
+
#
|
| 41 |
+
# VERSION ANCHORS
|
| 42 |
+
# CUDA 12.6 · Python 3.10 · torch 2.7.0 (cu126, brings its matching triton 3.3.x)
|
| 43 |
+
# The original private base declared torch 2.5.1 / triton 3.1.0 and the task overlay then ran
|
| 44 |
+
# `pip install torch==2.7.0` — 2.7.0 is therefore the version the anchor was calibrated under.
|
| 45 |
+
# =============================================================================
|
| 46 |
+
FROM nvidia/cuda:12.6.2-devel-ubuntu22.04
|
| 47 |
+
|
| 48 |
+
# Compute capability you will RUN on (Triton JITs for the live device; this only affects
|
| 49 |
+
# hand-built CUDA extensions): 8.0 A100 / 8.9 L40S-4090 / 9.0 H100-H20 / 10.0 B200
|
| 50 |
+
ARG TORCH_CUDA_ARCH_LIST="9.0"
|
| 51 |
+
ARG TORCH_VERSION=2.7.0
|
| 52 |
+
|
| 53 |
+
ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \
|
| 54 |
+
PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1
|
| 55 |
+
|
| 56 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 57 |
+
build-essential gcc-10 g++-10 cmake ninja-build pkg-config \
|
| 58 |
+
python3.10 python3.10-dev python3.10-venv python3-pip python-is-python3 \
|
| 59 |
+
git ca-certificates curl procps coreutils tar gzip vim less file jq \
|
| 60 |
+
&& update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 \
|
| 61 |
+
&& update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 100 \
|
| 62 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 63 |
+
|
| 64 |
+
# ---- venv at this EXACT path: tests/test.sh puts /opt/kernelbench-venv/bin at the head of PATH,
|
| 65 |
+
# and a bare python3 from anywhere else would not have torch. ----
|
| 66 |
+
ENV VENV=/opt/kernelbench-venv
|
| 67 |
+
RUN python3.10 -m venv "$VENV"
|
| 68 |
+
ENV PATH=$VENV/bin:/usr/local/cuda/bin:$PATH \
|
| 69 |
+
TORCH_CUDA_ARCH_LIST=${TORCH_CUDA_ARCH_LIST}
|
| 70 |
+
RUN pip install --no-cache-dir -U pip setuptools wheel
|
| 71 |
+
RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cu126 \
|
| 72 |
+
"torch==${TORCH_VERSION}" \
|
| 73 |
+
&& python -c "import torch, triton; print('torch', torch.__version__, '| triton', triton.__version__); assert torch.__version__.startswith('2.7.0'), torch.__version__"
|
| 74 |
+
|
| 75 |
+
# ---- the graded working tree. A REAL directory (not a symlink): the scope gate runs
|
| 76 |
+
# `git -C /app/repo status --porcelain`, which cannot see through a symlink. ----
|
| 77 |
+
RUN mkdir -p /app/repo /app/.timer /app/workspace /logs/verifier /logs/agent /logs/artifacts
|
| 78 |
+
COPY environment/repo/ /app/repo/
|
| 79 |
+
COPY instruction.md /app/instruction.md
|
| 80 |
+
|
| 81 |
+
# ---- the baseline commit = the diff base the scope gate compares against.
|
| 82 |
+
# 🔴 core.fileMode=false is LOAD-BEARING, not hygiene: a shipped image in this corpus had
|
| 83 |
+
# core.fileMode=true while some files were 0775 on disk but 100644 in the index, so
|
| 84 |
+
# `git status --porcelain` reported phantom out-of-scope paths in EVERY mode and forced
|
| 85 |
+
# reward to 0. Setting it false at creation makes that class of defect impossible. ----
|
| 86 |
+
RUN git config --global user.email "reviewer@fai-bench.local" \
|
| 87 |
+
&& git config --global user.name "fai-bench" \
|
| 88 |
+
&& git config --global init.defaultBranch main \
|
| 89 |
+
&& git config --global --add safe.directory /app/repo \
|
| 90 |
+
&& cd /app/repo \
|
| 91 |
+
&& git init -q \
|
| 92 |
+
&& git config core.fileMode false \
|
| 93 |
+
&& printf '__pycache__/\n*.pyc\n' >> .gitignore \
|
| 94 |
+
&& git add -A \
|
| 95 |
+
&& git commit -qm "baseline (graded starting point)" \
|
| 96 |
+
&& rm -rf .git/logs \
|
| 97 |
+
&& test "$(git rev-list --count HEAD)" = "1" \
|
| 98 |
+
&& test -z "$(git remote)" \
|
| 99 |
+
&& test "$(git config --get core.fileMode)" = "false" \
|
| 100 |
+
&& test -z "$(git status --porcelain)" \
|
| 101 |
+
&& echo "[build] /app/repo: 1 commit, no remote, fileMode=false, clean tree"
|
| 102 |
+
|
| 103 |
+
# ---- runtime contract (copied verbatim from the shipped image) ----
|
| 104 |
+
COPY environment/runtime/entrypoint.sh /app/entrypoint.sh
|
| 105 |
+
COPY environment/runtime/timer.sh /app/timer.sh
|
| 106 |
+
RUN chmod 0755 /app/entrypoint.sh /app/timer.sh && chown root:root /app/entrypoint.sh /app/timer.sh
|
| 107 |
+
COPY environment/runtime/run_dev_bench.sh /app/workspace/run_dev_bench.sh
|
| 108 |
+
RUN chmod 0755 /app/workspace/run_dev_bench.sh
|
| 109 |
+
COPY environment/loop/ /opt/loop/
|
| 110 |
+
RUN if [ -f /opt/loop/submit.sh ]; then chmod 0755 /opt/loop/submit.sh; fi \
|
| 111 |
+
&& chown -R root:root /opt/loop \
|
| 112 |
+
&& if [ -f /opt/loop/score_engine.sh ]; then chmod 0700 /opt/loop/score_engine.sh; fi \
|
| 113 |
+
&& if [ -f /opt/loop/sanitize_feedback.py ]; then chmod 0700 /opt/loop/sanitize_feedback.py; fi \
|
| 114 |
+
&& if [ -d /opt/loop/private ]; then chmod -R go-rwx /opt/loop/private; fi
|
| 115 |
+
|
| 116 |
+
# ---- the FROZEN anchor fallback. tests/test.sh prefers tests/ref_speedup.txt (mounted) and falls
|
| 117 |
+
# back to THIS path; keeping both consistent makes the resolution explicit. Only the constant. ----
|
| 118 |
+
COPY environment/verifier-correctness-manifest.json /opt/verifier-correctness-manifest.json
|
| 119 |
+
|
| 120 |
+
# ---- OPEN grading suite is NOT baked: tests/ (test.sh + compute_reward.py + the workload/harness
|
| 121 |
+
# + ref_speedup.txt) is MOUNTED FRESH at /tests when scoring. It ships in this package —
|
| 122 |
+
# open-source, but outside the image so the graded harness cannot be edited from the session.
|
| 123 |
+
|
| 124 |
+
# ---- 🔴 ANTI-LEAK ASSERTS (author-side artifact denylist) ----
|
| 125 |
+
RUN set -eu; rc=0; \
|
| 126 |
+
hits="$(find / -xdev -type f \( -name 'oracle*.patch' -o -name 'negative*.patch' \
|
| 127 |
+
-o -name 'baseline2*.patch' -o -name 'scope_card.json' -o -name 'kernel_oracle.py' \
|
| 128 |
+
-o -name 'degradation_manifest.json' \) 2>/dev/null | head -10)"; \
|
| 129 |
+
if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: a reference/authoring file is baked:"; echo "$hits"; rc=1; fi; \
|
| 130 |
+
for p in /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling /tests; do \
|
| 131 |
+
if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path baked: $p"; rc=1; fi; \
|
| 132 |
+
done; \
|
| 133 |
+
test "$rc" = 0; \
|
| 134 |
+
echo "[build] ANTI-LEAK ASSERTS PASS"
|
| 135 |
+
|
| 136 |
+
ENV PYTHONPATH=/app/repo \
|
| 137 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 138 |
+
OMP_NUM_THREADS=1 \
|
| 139 |
+
MKL_NUM_THREADS=1 \
|
| 140 |
+
OPENBLAS_NUM_THREADS=1 \
|
| 141 |
+
LD_LIBRARY_PATH=/opt/kernelbench-venv/lib/python3.10/site-packages/torch/lib:/usr/local/cuda/lib64:/usr/local/nvidia/lib64
|
| 142 |
+
WORKDIR /app/repo
|
| 143 |
+
|
| 144 |
+
# ---- build-time smoke: the graded module imports FROM /app/repo (the verifier asserts the same
|
| 145 |
+
# thing at scoring time via its import-origin gate) and the scope files are present. ----
|
| 146 |
+
# ---- frozen naive baseline for the verifier's SPEED DENOMINATOR.
|
| 147 |
+
# tests/test.sh resolves KB_BASELINE_MODULE=/opt/verifier-baseline/<file>; when that file
|
| 148 |
+
# is absent the whole benchmark block is SKIPPED and the run hard-fails with
|
| 149 |
+
# `validation_incomplete` (reward 0) no matter how good the submission is.
|
| 150 |
+
# It is a pristine copy of the shipped, pre-edit scope file, taken here at build time —
|
| 151 |
+
# exactly what the original task image baked. `cmp` proves the copy is byte-identical.
|
| 152 |
+
RUN mkdir -p /opt/verifier-baseline \
|
| 153 |
+
&& cp "/app/repo/cross_entropy_grad.py" "/opt/verifier-baseline/cross_entropy_grad.py" \
|
| 154 |
+
&& cmp "/app/repo/cross_entropy_grad.py" "/opt/verifier-baseline/cross_entropy_grad.py" \
|
| 155 |
+
&& chmod 0444 "/opt/verifier-baseline/cross_entropy_grad.py" \
|
| 156 |
+
&& echo "frozen baseline(s) baked: $(ls -l /opt/verifier-baseline | tail -n +2 | wc -l) file(s)"
|
| 157 |
+
|
| 158 |
+
RUN python - <<'PY'
|
| 159 |
+
import os, subprocess, sys
|
| 160 |
+
sys.path.insert(0, "/app/repo")
|
| 161 |
+
for f in ('/app/repo/cross_entropy_grad.py',):
|
| 162 |
+
p = os.path.join("/app/repo", f)
|
| 163 |
+
assert os.path.isfile(p), f"scope file missing: {p}"
|
| 164 |
+
print("scope file present:", f, os.path.getsize(p), "B")
|
| 165 |
+
for _b in ('cross_entropy_grad.py',):
|
| 166 |
+
_p = os.path.join('/opt/verifier-baseline', _b)
|
| 167 |
+
assert os.path.isfile(_p), f"frozen baseline missing: {_p} (tests/test.sh would skip the benchmark and hard-fail validation_incomplete)"
|
| 168 |
+
print('frozen baseline:', _p, os.path.getsize(_p), 'B')
|
| 169 |
+
n = subprocess.run(["git","-C","/app/repo","rev-list","--count","HEAD"],
|
| 170 |
+
capture_output=True, text=True).stdout.strip()
|
| 171 |
+
assert n == "1", f"git diff base broken (commits={n!r})"
|
| 172 |
+
print("OK: scope files, import origin and git base all in place")
|
| 173 |
+
PY
|
| 174 |
+
|
| 175 |
+
ENTRYPOINT ["/app/entrypoint.sh"]
|
| 176 |
+
CMD ["tail","-f","/dev/null"]
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/compute_reward.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Canonical kernelbench reward writer (reused verbatim from the ready-task
|
| 3 |
+
template kernel-opt-p0a4-003). Task-agnostic; do NOT special-case a task here.
|
| 4 |
+
|
| 5 |
+
Dual-mode:
|
| 6 |
+
- correctness task (verifier_state.task_kind == "correctness"):
|
| 7 |
+
reward = 1.0 iff all hard gates true and no hard_fail_reasons, else 0.0; no timing.
|
| 8 |
+
- acceleration task:
|
| 9 |
+
reward = speedup (raw measured speedup — no cap, no log, no ref anchor)
|
| 10 |
+
iff all gates pass and speedup is finite and > 0; else 0.0.
|
| 11 |
+
|
| 12 |
+
Reads: /logs/loop/dev/verifier_state.json, /logs/loop/dev/benchmark_results.json
|
| 13 |
+
Writes: /logs/loop/dev/reward.json, /logs/loop/dev/reward.txt
|
| 14 |
+
"""
|
| 15 |
+
import json, math
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
LOG = Path("/logs/loop/dev")
|
| 19 |
+
STATE = LOG / "verifier_state.json"
|
| 20 |
+
BENCH = LOG / "benchmark_results.json"
|
| 21 |
+
REWARD = LOG / "reward.json"
|
| 22 |
+
TEXT = LOG / "reward.txt"
|
| 23 |
+
|
| 24 |
+
GATES = [
|
| 25 |
+
"correctness_ok",
|
| 26 |
+
"trusted_restore_ok",
|
| 27 |
+
"hidden_correctness_ok",
|
| 28 |
+
"baseline_ok",
|
| 29 |
+
"benchmark_ok",
|
| 30 |
+
"anti_cheat_ok",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def read_json(path, default):
|
| 35 |
+
try:
|
| 36 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 37 |
+
except Exception:
|
| 38 |
+
return default
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
LOG.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
state = read_json(STATE, {})
|
| 44 |
+
bench = read_json(BENCH, {})
|
| 45 |
+
hard = list(state.get("hard_fail_reasons") or [])
|
| 46 |
+
task_kind = state.get("task_kind") or bench.get("task_kind") or "acceleration"
|
| 47 |
+
gates_ok = all(bool(state.get(g)) for g in GATES)
|
| 48 |
+
|
| 49 |
+
speedup = ref = 1.0
|
| 50 |
+
reward = 0.0
|
| 51 |
+
if task_kind == "correctness":
|
| 52 |
+
reward = 1.0 if (gates_ok and not hard) else 0.0
|
| 53 |
+
if reward == 0.0 and not hard:
|
| 54 |
+
hard.append("correctness_or_validation_incomplete")
|
| 55 |
+
else:
|
| 56 |
+
try:
|
| 57 |
+
speedup = float(bench.get("aggregate_speedup") or bench.get("primary_metric_value") or 1.0)
|
| 58 |
+
ref = float(bench.get("ref_speedup") or bench.get("reference_metric_value") or 1.0)
|
| 59 |
+
except Exception:
|
| 60 |
+
speedup = ref = 1.0
|
| 61 |
+
hard.append("invalid_primary_metric_value")
|
| 62 |
+
# reward IS the raw measured speedup (no cap, no log, no ref anchor);
|
| 63 |
+
# ref_speedup is kept as calibration metadata only. reward is 0 only when a
|
| 64 |
+
# gate fails (correctness/anti-cheat) or the measured speedup is unusable.
|
| 65 |
+
if gates_ok and not hard and math.isfinite(speedup) and speedup > 0.0:
|
| 66 |
+
reward = speedup
|
| 67 |
+
if reward == 0.0 and not hard:
|
| 68 |
+
hard.append("validation_incomplete_or_bad_speedup")
|
| 69 |
+
|
| 70 |
+
out = {
|
| 71 |
+
"schema_version": "kernelbench_reward_v1",
|
| 72 |
+
"task_kind": task_kind,
|
| 73 |
+
"reward": reward,
|
| 74 |
+
"speedup": speedup,
|
| 75 |
+
"ref_speedup": ref,
|
| 76 |
+
"actual_hardware_type": state.get("actual_hardware_type", "") or bench.get("actual_hardware_type", ""),
|
| 77 |
+
"hard_fail_reasons": hard,
|
| 78 |
+
"state_path": str(STATE),
|
| 79 |
+
"benchmark_path": str(BENCH),
|
| 80 |
+
}
|
| 81 |
+
REWARD.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
| 82 |
+
TEXT.write_text(f"{reward}\n", encoding="utf-8")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
main()
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/gpu_peakmem.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Peak-GPU-memory measurement for the cross-entropy loss+gradient task.
|
| 2 |
+
|
| 3 |
+
VALUE AXIS = PEAK MEMORY, not wall-time. The naive baseline materialises several
|
| 4 |
+
full ``(N, V)`` buffers (log-probs, probabilities, gradient); a memory-frugal
|
| 5 |
+
implementation keeps only per-row running state and can overwrite the logits
|
| 6 |
+
buffer with the gradient in place, so its peak ``max_memory_allocated`` is far
|
| 7 |
+
lower at large ``V``. Latency may be ~1.0x -- that is EXPECTED and is NOT scored.
|
| 8 |
+
|
| 9 |
+
Per shape:
|
| 10 |
+
1. correctness agreement: candidate output must match the frozen baseline
|
| 11 |
+
within tolerance (on a fresh clone; the candidate may mutate in place);
|
| 12 |
+
2. peak = ``torch.cuda.max_memory_allocated`` measured over a single call, with
|
| 13 |
+
only the freshly generated inputs resident at reset (the input buffer is the
|
| 14 |
+
shared floor for both); ratio = baseline_peak / candidate_peak.
|
| 15 |
+
Final metric = geometric mean of the per-shape peak-memory ratios. Prints
|
| 16 |
+
"speedup=X" (the peak-memory ratio; a no-op candidate == frozen baseline ties at
|
| 17 |
+
~1.0). The baseline is loaded from the protected frozen copy (KB_BASELINE_MODULE).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import importlib.util
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
from kb_ce_harness import (
|
| 27 |
+
assert_grad_close,
|
| 28 |
+
assert_loss_close,
|
| 29 |
+
forbidden_ce_guard,
|
| 30 |
+
geomean,
|
| 31 |
+
load_candidate,
|
| 32 |
+
make_labels,
|
| 33 |
+
make_logits,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
IGN = -100
|
| 37 |
+
LS = 0.0
|
| 38 |
+
IGNORE_FRAC = 0.1
|
| 39 |
+
|
| 40 |
+
# (tag, N, V, dtype). Vocab large enough that the baseline's (N,V) materialisation
|
| 41 |
+
# dominates peak memory (false-negative checklist item #3: a path-exercising workload).
|
| 42 |
+
SHAPES = [
|
| 43 |
+
("v32k_fp32", 8192, 32768, torch.float32),
|
| 44 |
+
("v128k_fp32", 8192, 128256, torch.float32),
|
| 45 |
+
("v64k_bf16", 8192, 65536, torch.bfloat16),
|
| 46 |
+
("v128k_bf16", 8192, 128256, torch.bfloat16),
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _load(path):
|
| 51 |
+
spec = importlib.util.spec_from_file_location("kb_ce_mod_" + str(abs(hash(path))), path)
|
| 52 |
+
mod = importlib.util.module_from_spec(spec)
|
| 53 |
+
spec.loader.exec_module(mod)
|
| 54 |
+
return mod
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _baseline_fn():
|
| 58 |
+
path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/cross_entropy_grad.py")
|
| 59 |
+
return _load(path).cross_entropy_loss_grad
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _peak_of(fn, N, V, dtype, seed, guard):
|
| 63 |
+
"""max_memory_allocated over one call, inputs freshly generated (only they
|
| 64 |
+
are resident at reset, so the input buffer is the shared floor)."""
|
| 65 |
+
torch.cuda.empty_cache()
|
| 66 |
+
torch.cuda.synchronize()
|
| 67 |
+
logits = make_logits(N, V, seed, dtype=dtype)
|
| 68 |
+
labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN)
|
| 69 |
+
torch.cuda.synchronize()
|
| 70 |
+
torch.cuda.reset_peak_memory_stats()
|
| 71 |
+
if guard:
|
| 72 |
+
with forbidden_ce_guard():
|
| 73 |
+
loss, grad = fn(logits, labels, IGN, LS)
|
| 74 |
+
else:
|
| 75 |
+
loss, grad = fn(logits, labels, IGN, LS)
|
| 76 |
+
torch.cuda.synchronize()
|
| 77 |
+
peak = torch.cuda.max_memory_allocated()
|
| 78 |
+
del logits, labels, loss, grad
|
| 79 |
+
torch.cuda.empty_cache()
|
| 80 |
+
return int(peak)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _agree(candidate, baseline, N, V, dtype, seed):
|
| 84 |
+
"""Candidate must match baseline within tolerance before its peak counts."""
|
| 85 |
+
logits = make_logits(N, V, seed, dtype=dtype)
|
| 86 |
+
labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN)
|
| 87 |
+
b_loss, b_grad = baseline(logits.clone(), labels, IGN, LS)
|
| 88 |
+
with forbidden_ce_guard():
|
| 89 |
+
c_loss, c_grad = candidate(logits.clone(), labels, IGN, LS)
|
| 90 |
+
bf16 = dtype == torch.bfloat16
|
| 91 |
+
assert_loss_close(c_loss, b_loss, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]")
|
| 92 |
+
assert_grad_close(c_grad, b_grad, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]")
|
| 93 |
+
del logits, labels, b_loss, b_grad, c_loss, c_grad
|
| 94 |
+
torch.cuda.empty_cache()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def main():
|
| 98 |
+
if not torch.cuda.is_available():
|
| 99 |
+
print("CUDA_UNAVAILABLE")
|
| 100 |
+
sys.exit(2)
|
| 101 |
+
torch.cuda.init()
|
| 102 |
+
candidate = load_candidate().cross_entropy_loss_grad
|
| 103 |
+
baseline = _baseline_fn()
|
| 104 |
+
|
| 105 |
+
ratios = []
|
| 106 |
+
seed = 5000
|
| 107 |
+
for tag, N, V, dtype in SHAPES:
|
| 108 |
+
try:
|
| 109 |
+
_agree(candidate, baseline, N, V, dtype, seed)
|
| 110 |
+
except AssertionError as exc:
|
| 111 |
+
print(f"BENCH_FAIL {tag}: {exc}")
|
| 112 |
+
print("speedup=0.0")
|
| 113 |
+
sys.exit(1)
|
| 114 |
+
cand_peak = _peak_of(candidate, N, V, dtype, seed, guard=True)
|
| 115 |
+
base_peak = _peak_of(baseline, N, V, dtype, seed, guard=False)
|
| 116 |
+
ratio = base_peak / max(cand_peak, 1)
|
| 117 |
+
ratios.append(ratio)
|
| 118 |
+
print(f"shape={tag} N={N} V={V} dtype={dtype} "
|
| 119 |
+
f"baseline_peak={base_peak} candidate_peak={cand_peak} ratio={ratio:.4f}")
|
| 120 |
+
seed += 100
|
| 121 |
+
|
| 122 |
+
print(f"speedup={geomean(ratios):.4f}")
|
| 123 |
+
sys.exit(0)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
main()
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/kb_ce_harness.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared harness for the cross-entropy loss+gradient contract.
|
| 2 |
+
|
| 3 |
+
Provides:
|
| 4 |
+
* ``load_candidate`` — import the candidate module from /app/repo,
|
| 5 |
+
* deterministic input generation (``make_logits`` / ``make_labels``),
|
| 6 |
+
* a high-precision float32 reference (``ref_ce``) — the ground truth for both
|
| 7 |
+
loss and gradient,
|
| 8 |
+
* ``assert_loss_close`` / ``assert_grad_close`` tolerance comparisons,
|
| 9 |
+
* ``count_nonzero_rows`` — the work-evidence signal,
|
| 10 |
+
* ``geomean``,
|
| 11 |
+
* ``forbidden_ce_guard`` — a runtime guard that blocks the framework's
|
| 12 |
+
single-call fused cross-entropy loss while the candidate runs, so the
|
| 13 |
+
candidate cannot delegate the whole computation to the vendor primitive it
|
| 14 |
+
is meant to build.
|
| 15 |
+
|
| 16 |
+
The reference materialises full-size buffers on purpose (it is only the
|
| 17 |
+
correctness oracle, not scored on memory).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import contextlib
|
| 21 |
+
import importlib.util
|
| 22 |
+
import math
|
| 23 |
+
import os
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
# candidate-vs-reference tolerances
|
| 28 |
+
LOSS_ATOL = 1e-4
|
| 29 |
+
LOSS_ATOL_BF16 = 3e-2
|
| 30 |
+
LOSS_RTOL = 1e-3
|
| 31 |
+
# bf16 loss carries the dtype's own ~2^-8 (~0.4%) quantization; at a large-vocab
|
| 32 |
+
# loss magnitude (~19) that is ~0.075 absolute, which a 1e-3 relative term cannot
|
| 33 |
+
# represent. Comparing a correctly bf16-cast loss (reference/oracle) against the
|
| 34 |
+
# fp32 baseline loss must tolerate that quantization, so bf16 uses a relative term
|
| 35 |
+
# above bf16's resolution. The (N,V) gradient parity check remains the tight,
|
| 36 |
+
# authoritative correctness signal.
|
| 37 |
+
LOSS_RTOL_BF16 = 8e-3
|
| 38 |
+
GRAD_ATOL = 1e-4
|
| 39 |
+
GRAD_RTOL = 1e-3
|
| 40 |
+
GRAD_ATOL_BF16 = 8e-3
|
| 41 |
+
GRAD_RTOL_BF16 = 1e-2
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def repo_dir():
|
| 45 |
+
return os.environ.get("KB_REPO_DIR", "/app/repo")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_candidate():
|
| 49 |
+
"""Import the candidate module from the repo under test."""
|
| 50 |
+
path = os.path.join(repo_dir(), "cross_entropy_grad.py")
|
| 51 |
+
spec = importlib.util.spec_from_file_location("candidate_ce_grad", path)
|
| 52 |
+
mod = importlib.util.module_from_spec(spec)
|
| 53 |
+
spec.loader.exec_module(mod)
|
| 54 |
+
if not hasattr(mod, "cross_entropy_loss_grad"):
|
| 55 |
+
raise AttributeError(f"{path} does not define cross_entropy_loss_grad()")
|
| 56 |
+
return mod
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# --------------------------------------------------------------------------- #
|
| 60 |
+
# Deterministic input generation
|
| 61 |
+
# --------------------------------------------------------------------------- #
|
| 62 |
+
def make_logits(N, V, seed, dtype=torch.float32, scale=4.0, device="cuda"):
|
| 63 |
+
g = torch.Generator(device="cpu").manual_seed(seed)
|
| 64 |
+
x = torch.randn(N, V, generator=g, dtype=torch.float32) * scale
|
| 65 |
+
return x.to(device).to(dtype)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def make_labels(N, V, seed, ignore_frac=0.0, ignore_index=-100, device="cuda"):
|
| 69 |
+
g = torch.Generator(device="cpu").manual_seed(seed)
|
| 70 |
+
lab = torch.randint(0, V, (N,), generator=g, dtype=torch.int64)
|
| 71 |
+
if ignore_frac > 0.0:
|
| 72 |
+
mask = torch.rand(N, generator=g) < ignore_frac
|
| 73 |
+
lab[mask] = ignore_index
|
| 74 |
+
return lab.to(device)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# --------------------------------------------------------------------------- #
|
| 78 |
+
# High-precision float32 reference (ground truth for loss + grad)
|
| 79 |
+
# --------------------------------------------------------------------------- #
|
| 80 |
+
def ref_ce(logits, labels, ignore_index=-100, label_smoothing=0.0):
|
| 81 |
+
N, V = logits.shape
|
| 82 |
+
s = float(label_smoothing)
|
| 83 |
+
valid = labels != ignore_index
|
| 84 |
+
n_valid = int(valid.sum().item())
|
| 85 |
+
denom = max(n_valid, 1)
|
| 86 |
+
safe = labels.clamp(min=0).long()
|
| 87 |
+
idx = torch.arange(N, device=logits.device)
|
| 88 |
+
|
| 89 |
+
lf = logits.to(torch.float32)
|
| 90 |
+
logp = torch.log_softmax(lf, dim=-1)
|
| 91 |
+
logp_y = logp[idx, safe]
|
| 92 |
+
nll = -logp_y
|
| 93 |
+
smooth = -logp.mean(dim=1)
|
| 94 |
+
row_loss = (1.0 - s) * nll + s * smooth
|
| 95 |
+
row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss))
|
| 96 |
+
loss = row_loss.sum() / denom
|
| 97 |
+
|
| 98 |
+
prob = logp.exp()
|
| 99 |
+
grad = prob.clone()
|
| 100 |
+
if s != 0.0:
|
| 101 |
+
grad = grad - (s / V)
|
| 102 |
+
grad[idx, safe] = grad[idx, safe] - (1.0 - s)
|
| 103 |
+
grad = grad / denom
|
| 104 |
+
grad[~valid] = 0.0
|
| 105 |
+
return loss.to(logits.dtype), grad.to(logits.dtype)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# --------------------------------------------------------------------------- #
|
| 109 |
+
# Comparisons
|
| 110 |
+
# --------------------------------------------------------------------------- #
|
| 111 |
+
def assert_loss_close(cand_loss, ref_loss, bf16=False, msg=""):
|
| 112 |
+
cl = torch.as_tensor(cand_loss).to(torch.float32).reshape(())
|
| 113 |
+
rl = torch.as_tensor(ref_loss).to(torch.float32).reshape(())
|
| 114 |
+
if not torch.isfinite(cl):
|
| 115 |
+
raise AssertionError(f"candidate loss is non-finite {msg}")
|
| 116 |
+
atol = LOSS_ATOL_BF16 if bf16 else LOSS_ATOL
|
| 117 |
+
rtol = LOSS_RTOL_BF16 if bf16 else LOSS_RTOL
|
| 118 |
+
d = float((cl - rl).abs())
|
| 119 |
+
tol = atol + rtol * float(rl.abs())
|
| 120 |
+
if d > tol:
|
| 121 |
+
raise AssertionError(f"loss mismatch: |{float(cl):.6f}-{float(rl):.6f}|={d:.6f} > {tol:.6f} {msg}")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def assert_grad_close(cand_grad, ref_grad, bf16=False, msg=""):
|
| 125 |
+
if tuple(cand_grad.shape) != tuple(ref_grad.shape):
|
| 126 |
+
raise AssertionError(f"grad shape {tuple(cand_grad.shape)} vs {tuple(ref_grad.shape)} {msg}")
|
| 127 |
+
if cand_grad.dtype != ref_grad.dtype:
|
| 128 |
+
raise AssertionError(f"grad dtype {cand_grad.dtype} vs {ref_grad.dtype} {msg}")
|
| 129 |
+
c = cand_grad.to(torch.float32)
|
| 130 |
+
r = ref_grad.to(torch.float32)
|
| 131 |
+
if not torch.isfinite(c).all():
|
| 132 |
+
raise AssertionError(f"candidate grad has non-finite values {msg}")
|
| 133 |
+
atol = GRAD_ATOL_BF16 if bf16 else GRAD_ATOL
|
| 134 |
+
rtol = GRAD_RTOL_BF16 if bf16 else GRAD_RTOL
|
| 135 |
+
diff = (c - r).abs()
|
| 136 |
+
tol = atol + rtol * r.abs()
|
| 137 |
+
bad = diff > tol
|
| 138 |
+
if bad.any():
|
| 139 |
+
raise AssertionError(
|
| 140 |
+
f"{int(bad.sum())}/{c.numel()} grad elements out of tolerance "
|
| 141 |
+
f"(worst excess {float((diff - tol).max()):.5f}) {msg}")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def count_nonzero_rows(grad):
|
| 145 |
+
"""Work-evidence: number of rows whose gradient is not all-zero."""
|
| 146 |
+
return int((grad.to(torch.float32).abs().sum(dim=1) > 0).sum().item())
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# --------------------------------------------------------------------------- #
|
| 150 |
+
# Runtime guard: block the framework's single-call fused cross-entropy loss
|
| 151 |
+
# while the candidate runs (the candidate must compute loss + grad itself).
|
| 152 |
+
# --------------------------------------------------------------------------- #
|
| 153 |
+
@contextlib.contextmanager
|
| 154 |
+
def forbidden_ce_guard():
|
| 155 |
+
def _blocked(*args, **kwargs):
|
| 156 |
+
raise RuntimeError("forbidden fused cross-entropy primitive called during scoring")
|
| 157 |
+
|
| 158 |
+
class _BlockedModule:
|
| 159 |
+
def __init__(self, *a, **k):
|
| 160 |
+
raise RuntimeError("forbidden fused cross-entropy primitive called during scoring")
|
| 161 |
+
|
| 162 |
+
saved = []
|
| 163 |
+
for obj, name, repl in [
|
| 164 |
+
(torch.nn.functional, "cross_entropy", _blocked),
|
| 165 |
+
(torch.nn, "CrossEntropyLoss", _BlockedModule),
|
| 166 |
+
]:
|
| 167 |
+
if hasattr(obj, name):
|
| 168 |
+
saved.append((obj, name, getattr(obj, name)))
|
| 169 |
+
try:
|
| 170 |
+
setattr(obj, name, repl)
|
| 171 |
+
except Exception:
|
| 172 |
+
saved.pop()
|
| 173 |
+
try:
|
| 174 |
+
yield
|
| 175 |
+
finally:
|
| 176 |
+
for obj, name, val in reversed(saved):
|
| 177 |
+
try:
|
| 178 |
+
setattr(obj, name, val)
|
| 179 |
+
except Exception:
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def geomean(values):
|
| 184 |
+
vals = [max(float(v), 1e-12) for v in values]
|
| 185 |
+
return math.exp(sum(math.log(v) for v in vals) / len(vals))
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
4.68
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test.sh
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Verifier for insea-fused-softmax-cross-entropy-grad-loop16 (cross-entropy loss + input
|
| 3 |
+
# gradient; value axis = PEAK MEMORY, not wall-time). Pattern A, ACCELERATION lane,
|
| 4 |
+
# scored on torch.cuda.max_memory_allocated on H20. Modes: candidate|noop|oracle|negative
|
| 5 |
+
set -uo pipefail
|
| 6 |
+
# Never trust the exec context — the harness may exec this in a
|
| 7 |
+
# NON-login shell where bare python3 has no torch. Pin the venv first.
|
| 8 |
+
export PATH=/opt/kernelbench-venv/bin:$PATH
|
| 9 |
+
TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 10 |
+
REPO=/app/repo
|
| 11 |
+
LOG=/logs/loop/dev
|
| 12 |
+
mkdir -p "$LOG"
|
| 13 |
+
MODE="${KERNELBENCH_VERIFY_MODE:-candidate}"
|
| 14 |
+
CAND_FILE="$REPO/cross_entropy_grad.py"
|
| 15 |
+
export KB_CANDIDATE_MODULE="$CAND_FILE"
|
| 16 |
+
export KB_BASELINE_MODULE=/opt/verifier-baseline/cross_entropy_grad.py
|
| 17 |
+
|
| 18 |
+
HARD=(); add_hard(){ HARD+=("$1"); }
|
| 19 |
+
correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true
|
| 20 |
+
baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true
|
| 21 |
+
expected_cases=12; actual_cases=0
|
| 22 |
+
speedup=1.0; ref_speedup=1.0; hw="unknown"
|
| 23 |
+
|
| 24 |
+
cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; }
|
| 25 |
+
|
| 26 |
+
if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then
|
| 27 |
+
# reviewer-only mode: reset the working tree to the frozen baseline so several
|
| 28 |
+
# modes running back-to-back in one container session each start clean. candidate/noop
|
| 29 |
+
# NEVER resets (this branch is skipped for them), so a solver session is untouched.
|
| 30 |
+
git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
|
| 31 |
+
git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"
|
| 32 |
+
fi
|
| 33 |
+
if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then
|
| 34 |
+
git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
|
| 35 |
+
git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true
|
| 36 |
+
fi
|
| 37 |
+
|
| 38 |
+
# anti-cheat: only cross_entropy_grad.py may change
|
| 39 |
+
git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt"
|
| 40 |
+
while IFS= read -r f; do
|
| 41 |
+
[ -z "$f" ] && continue
|
| 42 |
+
case "$f" in
|
| 43 |
+
cross_entropy_grad.py) : ;;
|
| 44 |
+
*__pycache__*) : ;;
|
| 45 |
+
*) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;;
|
| 46 |
+
esac
|
| 47 |
+
done < "$LOG/anti_cheat_changed_files.txt"
|
| 48 |
+
|
| 49 |
+
# anti-cheat: the framework's single-call fused cross-entropy loss is out of scope
|
| 50 |
+
# (the candidate must compute the loss + gradient itself). Textual scan of the file.
|
| 51 |
+
if [ -f "$CAND_FILE" ] && grep -Eq "torch\.nn\.functional\.cross_entropy|F\.cross_entropy|torch\.nn\.CrossEntropyLoss|nn\.CrossEntropyLoss|functional\.cross_entropy" "$CAND_FILE"; then
|
| 52 |
+
anti_cheat_ok=false; add_hard "forbidden_fused_ce_primitive"
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
# trusted restore: hidden suite ships in tests/ payload (fresh at scoring)
|
| 56 |
+
for f in test_cross_entropy_grad.py gpu_peakmem.py kb_ce_harness.py; do
|
| 57 |
+
[ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; }
|
| 58 |
+
done
|
| 59 |
+
|
| 60 |
+
# ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild)
|
| 61 |
+
if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then
|
| 62 |
+
ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt")
|
| 63 |
+
elif [ -f /opt/verifier-correctness-manifest.json ]; then
|
| 64 |
+
ref_speedup=$(python3 -c "import json;print(json.load(open('/opt/verifier-correctness-manifest.json')).get('ref_speedup',1.0))" 2>/dev/null || echo 1.0)
|
| 65 |
+
fi
|
| 66 |
+
hw=$(python3 -c "import torch;print(torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'no_cuda')" 2>/dev/null || echo unknown)
|
| 67 |
+
|
| 68 |
+
# correctness gate (needs CUDA)
|
| 69 |
+
if [ "$correctness_ok" = true ]; then
|
| 70 |
+
( cd "$TESTS_DIR" && python3 test_cross_entropy_grad.py ) > "$LOG/correctness.log" 2>&1
|
| 71 |
+
crc=$?
|
| 72 |
+
actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0}
|
| 73 |
+
if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then
|
| 74 |
+
hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed"
|
| 75 |
+
fi
|
| 76 |
+
fi
|
| 77 |
+
|
| 78 |
+
# measurement: PEAK MEMORY ratio (baseline_peak/candidate_peak), median over 3 runs
|
| 79 |
+
# (deterministic metric; median guards against allocator jitter). Only if correct.
|
| 80 |
+
if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then
|
| 81 |
+
: > "$LOG/bench.log"
|
| 82 |
+
sp_list=""
|
| 83 |
+
for r in 1 2 3; do
|
| 84 |
+
line=$( cd "$TESTS_DIR" && python3 gpu_peakmem.py 2>>"$LOG/bench.log" )
|
| 85 |
+
echo "$line" >> "$LOG/bench.log"
|
| 86 |
+
sp=$(echo "$line" | sed -n 's/.*speedup=\([0-9.-]*\).*/\1/p')
|
| 87 |
+
[ -n "$sp" ] && sp_list="$sp_list $sp"
|
| 88 |
+
done
|
| 89 |
+
speedup=$(python3 -c "v=sorted(float(x) for x in '$sp_list'.split());print(f'{v[len(v)//2]:.5f}' if v else '-1')")
|
| 90 |
+
if [ -z "$sp_list" ] || python3 -c "import sys;sys.exit(0 if float('$speedup')<=0 else 1)"; then
|
| 91 |
+
benchmark_ok=false; add_hard "benchmark_execution_failed"
|
| 92 |
+
fi
|
| 93 |
+
else
|
| 94 |
+
benchmark_ok=false
|
| 95 |
+
fi
|
| 96 |
+
|
| 97 |
+
HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi
|
| 98 |
+
DIAG_TAIL=""
|
| 99 |
+
if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then
|
| 100 |
+
DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g')
|
| 101 |
+
fi
|
| 102 |
+
cat > "$LOG/verifier_state.json" <<JSON
|
| 103 |
+
{"schema_version":"kernelbench_verifier_state_v1","task_kind":"acceleration",
|
| 104 |
+
"correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,
|
| 105 |
+
"hidden_correctness_ok":$hidden_correctness_ok,"baseline_ok":$baseline_ok,
|
| 106 |
+
"benchmark_ok":$benchmark_ok,"anti_cheat_ok":$anti_cheat_ok,
|
| 107 |
+
"hard_fail_reasons":$HARD_JSON,
|
| 108 |
+
"expected_case_count":$expected_cases,"actual_case_count":$actual_cases,
|
| 109 |
+
"expected_benchmark_count":1,"actual_benchmark_count":1,
|
| 110 |
+
"actual_hardware_type":"$hw","mode":"$MODE",
|
| 111 |
+
"work_evidence_notes":["cross-entropy loss+grad suite $actual_cases/$expected_cases ok","median peak-memory ratio (baseline_peak/candidate_peak)=$speedup on $hw","correctness_tail:${DIAG_TAIL}"]}
|
| 112 |
+
JSON
|
| 113 |
+
cat > "$LOG/correctness_results.json" <<JSON
|
| 114 |
+
{"schema_version":"kernelbench_correctness_results_v1",
|
| 115 |
+
"suites":[{"name":"hidden-cross-entropy-grad-suite","visibility_class":"hidden_supplement","expected_case_count":$expected_cases,"actual_case_count":$actual_cases,"passed":$actual_cases,"failed":$((expected_cases-actual_cases)),"hard_fail_reasons":$HARD_JSON}],
|
| 116 |
+
"correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,"hidden_correctness_ok":$hidden_correctness_ok}
|
| 117 |
+
JSON
|
| 118 |
+
cat > "$LOG/benchmark_results.json" <<JSON
|
| 119 |
+
{"schema_version":"kernelbench_benchmark_results_v1","task_kind":"acceleration","metric":"peak_memory_bytes",
|
| 120 |
+
"direction":"higher_is_better",
|
| 121 |
+
"workloads":[{"name":"ce-peakmem-geomean-4shapes","speedup":$speedup,"completion_counters":{"cases":"$actual_cases/$expected_cases"}}],
|
| 122 |
+
"aggregate_speedup":$speedup,"ref_speedup":$ref_speedup,"actual_hardware_type":"$hw"}
|
| 123 |
+
JSON
|
| 124 |
+
python3 "$TESTS_DIR/compute_reward.py" 2>/dev/null || python3 /tests/compute_reward.py 2>/dev/null || true
|
| 125 |
+
REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null)
|
| 126 |
+
echo "MODE=$MODE cases=$actual_cases/$expected_cases peakmem_ratio=$speedup ref=$ref_speedup hw=$hw reward=$REW"
|
| 127 |
+
[ -n "$REW" ] && exit 0 || exit 1
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test_cross_entropy_grad.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Correctness suite for the cross-entropy loss+gradient contract — 12 cases.
|
| 2 |
+
|
| 3 |
+
Each case prints "CASE_PASS <name>" or "CASE_FAIL <name>: <reason>".
|
| 4 |
+
The runner greps the number of CASE_PASS lines (expects 12).
|
| 5 |
+
|
| 6 |
+
The candidate may overwrite its ``logits`` argument in place, so every case
|
| 7 |
+
passes the candidate a fresh clone and computes the reference from the pristine
|
| 8 |
+
tensor first.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import traceback
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
from kb_ce_harness import (
|
| 17 |
+
assert_grad_close,
|
| 18 |
+
assert_loss_close,
|
| 19 |
+
count_nonzero_rows,
|
| 20 |
+
forbidden_ce_guard,
|
| 21 |
+
load_candidate,
|
| 22 |
+
make_labels,
|
| 23 |
+
make_logits,
|
| 24 |
+
ref_ce,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
IGN = -100
|
| 28 |
+
CASES = []
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def case(fn):
|
| 32 |
+
CASES.append(fn)
|
| 33 |
+
return fn
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _run(fn, N, V, seed, dtype=torch.float32, ls=0.0, ignore_frac=0.0):
|
| 37 |
+
logits = make_logits(N, V, seed, dtype=dtype)
|
| 38 |
+
labels = make_labels(N, V, seed + 1, ignore_frac=ignore_frac, ignore_index=IGN)
|
| 39 |
+
ref_loss, ref_grad = ref_ce(logits, labels, ignore_index=IGN, label_smoothing=ls)
|
| 40 |
+
with forbidden_ce_guard():
|
| 41 |
+
c_loss, c_grad = fn(logits.clone(), labels, IGN, ls)
|
| 42 |
+
bf16 = dtype == torch.bfloat16
|
| 43 |
+
tag = f"[N={N} V={V} dtype={dtype} ls={ls} ign={ignore_frac}]"
|
| 44 |
+
assert_loss_close(c_loss, ref_loss, bf16=bf16, msg=tag)
|
| 45 |
+
assert_grad_close(c_grad, ref_grad, bf16=bf16, msg=tag)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@case
|
| 49 |
+
def normal_fp32(fn):
|
| 50 |
+
_run(fn, 256, 4096, seed=100)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@case
|
| 54 |
+
def normal_bf16(fn):
|
| 55 |
+
_run(fn, 256, 4096, seed=150, dtype=torch.bfloat16)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@case
|
| 59 |
+
def mean_with_ignore(fn):
|
| 60 |
+
_run(fn, 320, 3072, seed=200, ignore_frac=0.35)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@case
|
| 64 |
+
def all_ignore(fn):
|
| 65 |
+
# every row ignored -> loss 0, grad all zero
|
| 66 |
+
N, V = 128, 2048
|
| 67 |
+
logits = make_logits(N, V, 300)
|
| 68 |
+
labels = torch.full((N,), IGN, dtype=torch.int64, device="cuda")
|
| 69 |
+
with forbidden_ce_guard():
|
| 70 |
+
c_loss, c_grad = fn(logits.clone(), labels, IGN, 0.0)
|
| 71 |
+
if abs(float(c_loss)) > 1e-5:
|
| 72 |
+
raise AssertionError(f"all-ignore loss should be 0, got {float(c_loss)}")
|
| 73 |
+
if c_grad.shape != (N, V):
|
| 74 |
+
raise AssertionError(f"bad grad shape {tuple(c_grad.shape)}")
|
| 75 |
+
if not (c_grad.to(torch.float32) == 0).all():
|
| 76 |
+
raise AssertionError("all-ignore grad should be exactly zero")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@case
|
| 80 |
+
def single_class(fn):
|
| 81 |
+
# V == 1: softmax is 1, loss is 0, grad is 0
|
| 82 |
+
_run(fn, 64, 1, seed=400)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@case
|
| 86 |
+
def single_row(fn):
|
| 87 |
+
_run(fn, 1, 2048, seed=500)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@case
|
| 91 |
+
def nontile_vocab(fn):
|
| 92 |
+
# V not a multiple of any common chunk size
|
| 93 |
+
_run(fn, 128, 4099, seed=600)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@case
|
| 97 |
+
def label_smoothing(fn):
|
| 98 |
+
_run(fn, 256, 2048, seed=700, ls=0.1)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@case
|
| 102 |
+
def error_contract(fn):
|
| 103 |
+
N, V = 32, 512
|
| 104 |
+
logits = make_logits(N, V, 800)
|
| 105 |
+
labels = make_labels(N, V, 801)
|
| 106 |
+
# integer logits -> TypeError
|
| 107 |
+
try:
|
| 108 |
+
fn(logits.to(torch.int32), labels, IGN, 0.0)
|
| 109 |
+
raise AssertionError("integer logits did not raise TypeError")
|
| 110 |
+
except TypeError:
|
| 111 |
+
pass
|
| 112 |
+
# float labels -> TypeError
|
| 113 |
+
try:
|
| 114 |
+
fn(logits.clone(), labels.to(torch.float32), IGN, 0.0)
|
| 115 |
+
raise AssertionError("float labels did not raise TypeError")
|
| 116 |
+
except TypeError:
|
| 117 |
+
pass
|
| 118 |
+
# 1-D logits -> ValueError
|
| 119 |
+
try:
|
| 120 |
+
fn(logits.reshape(-1).clone(), labels, IGN, 0.0)
|
| 121 |
+
raise AssertionError("1-D logits did not raise ValueError")
|
| 122 |
+
except ValueError:
|
| 123 |
+
pass
|
| 124 |
+
# labels wrong length -> ValueError
|
| 125 |
+
try:
|
| 126 |
+
fn(logits.clone(), labels[:-1], IGN, 0.0)
|
| 127 |
+
raise AssertionError("wrong-length labels did not raise ValueError")
|
| 128 |
+
except ValueError:
|
| 129 |
+
pass
|
| 130 |
+
# negative label_smoothing -> ValueError
|
| 131 |
+
try:
|
| 132 |
+
fn(logits.clone(), labels, IGN, -0.1)
|
| 133 |
+
raise AssertionError("negative label_smoothing did not raise ValueError")
|
| 134 |
+
except ValueError:
|
| 135 |
+
pass
|
| 136 |
+
# a non-ignored label out of range [0, V) -> ValueError
|
| 137 |
+
bad = labels.clone()
|
| 138 |
+
bad[0] = V # out of range, not the ignore sentinel
|
| 139 |
+
try:
|
| 140 |
+
fn(logits.clone(), bad, IGN, 0.0)
|
| 141 |
+
raise AssertionError("out-of-range label did not raise ValueError")
|
| 142 |
+
except ValueError:
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@case
|
| 147 |
+
def metamorphic_const_shift(fn):
|
| 148 |
+
"""Adding a per-row constant to all logits leaves loss AND grad unchanged."""
|
| 149 |
+
N, V = 192, 2048
|
| 150 |
+
logits = make_logits(N, V, 900)
|
| 151 |
+
labels = make_labels(N, V, 901)
|
| 152 |
+
with forbidden_ce_guard():
|
| 153 |
+
loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0)
|
| 154 |
+
g = torch.Generator(device="cpu").manual_seed(902)
|
| 155 |
+
# a large positive per-row shift: a numerically stable softmax is invariant,
|
| 156 |
+
# while a non-stable one (no max subtraction) overflows -> NaN -> fails here.
|
| 157 |
+
shift = (torch.rand(N, generator=g) * 40.0 + 80.0).to(logits.device).to(logits.dtype)
|
| 158 |
+
logits_b = logits + shift[:, None]
|
| 159 |
+
with forbidden_ce_guard():
|
| 160 |
+
loss_b, grad_b = fn(logits_b.clone(), labels, IGN, 0.0)
|
| 161 |
+
assert_loss_close(loss_b, loss_a, msg="[const-shift loss]")
|
| 162 |
+
assert_grad_close(grad_b, grad_a, msg="[const-shift grad]")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@case
|
| 166 |
+
def metamorphic_permute_rows(fn):
|
| 167 |
+
"""Permuting the rows permutes the gradient rows and leaves the mean loss unchanged."""
|
| 168 |
+
N, V = 256, 2048
|
| 169 |
+
logits = make_logits(N, V, 1000)
|
| 170 |
+
labels = make_labels(N, V, 1001, ignore_frac=0.2, ignore_index=IGN)
|
| 171 |
+
with forbidden_ce_guard():
|
| 172 |
+
loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0)
|
| 173 |
+
g = torch.Generator(device="cpu").manual_seed(1002)
|
| 174 |
+
perm = torch.randperm(N, generator=g).to(logits.device)
|
| 175 |
+
with forbidden_ce_guard():
|
| 176 |
+
loss_b, grad_b = fn(logits[perm].clone(), labels[perm], IGN, 0.0)
|
| 177 |
+
assert_loss_close(loss_b, loss_a, msg="[permute loss]")
|
| 178 |
+
assert_grad_close(grad_b, grad_a[perm], msg="[permute grad]")
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@case
|
| 182 |
+
def work_evidence(fn):
|
| 183 |
+
"""Exactly the non-ignored rows carry a nonzero gradient; ignored rows are zero."""
|
| 184 |
+
N, V = 384, 2048
|
| 185 |
+
logits = make_logits(N, V, 1100)
|
| 186 |
+
labels = make_labels(N, V, 1101, ignore_frac=0.5, ignore_index=IGN)
|
| 187 |
+
n_valid = int((labels != IGN).sum().item())
|
| 188 |
+
with forbidden_ce_guard():
|
| 189 |
+
_, c_grad = fn(logits.clone(), labels, IGN, 0.0)
|
| 190 |
+
nz = count_nonzero_rows(c_grad)
|
| 191 |
+
if nz != n_valid:
|
| 192 |
+
raise AssertionError(f"nonzero-grad rows {nz} != valid labels {n_valid}")
|
| 193 |
+
ignored = (labels == IGN)
|
| 194 |
+
if ignored.any() and not (c_grad[ignored].to(torch.float32) == 0).all():
|
| 195 |
+
raise AssertionError("ignored rows have nonzero gradient")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def main():
|
| 199 |
+
if not torch.cuda.is_available():
|
| 200 |
+
print("CUDA_UNAVAILABLE")
|
| 201 |
+
sys.exit(2)
|
| 202 |
+
mod = load_candidate()
|
| 203 |
+
fn = mod.cross_entropy_loss_grad
|
| 204 |
+
passed = 0
|
| 205 |
+
for fn_case in CASES:
|
| 206 |
+
name = fn_case.__name__
|
| 207 |
+
try:
|
| 208 |
+
fn_case(fn)
|
| 209 |
+
torch.cuda.synchronize()
|
| 210 |
+
passed += 1
|
| 211 |
+
print(f"CASE_PASS {name}")
|
| 212 |
+
except Exception as exc: # noqa: BLE001
|
| 213 |
+
reason = f"{type(exc).__name__}: {exc}"
|
| 214 |
+
print(f"CASE_FAIL {name}: {reason.splitlines()[0][:300]}")
|
| 215 |
+
traceback.print_exc(file=sys.stderr)
|
| 216 |
+
total = len(CASES)
|
| 217 |
+
print(f"CASES_PASSED={passed}/{total}")
|
| 218 |
+
sys.exit(0 if passed == total else 1)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/manifest.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"base_task_id": "insea-fused-softmax-cross-entropy-grad-loop16",
|
| 3 |
+
"dev_engine": "private/dev_tests/test.sh (= the task verifier VERBATIM, output redirected to /logs/loop/dev, candidate mode)",
|
| 4 |
+
"max_submissions": 1,
|
| 5 |
+
"min_submissions": 1,
|
| 6 |
+
"note": "root-only (0700). ref_speedup is a protected secret; the sanitizer never emits it.",
|
| 7 |
+
"ref_speedup": 7.4157,
|
| 8 |
+
"reward_formula": "acceleration: reward = speedup (raw measured ratio, uncapped; 0 if a gate fails). Matches the base compute_reward.py verbatim.",
|
| 9 |
+
"schema_version": "kernelbench_loop_manifest_v1",
|
| 10 |
+
"task_id": "insea-fused-softmax-cross-entropy-grad-loop16"
|
| 11 |
+
}
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/sanitize_feedback.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Sanitized feedback emitter (0700 root-owned) for insea-fused-softmax-cross-entropy-grad-loop16.
|
| 3 |
+
|
| 4 |
+
Invoked ONLY by /opt/loop/submit.sh. Reads the DEV engine products under
|
| 5 |
+
/logs/loop/dev/ and the loop accounting under /logs/loop/, and prints ONLY a
|
| 6 |
+
leak-free summary.
|
| 7 |
+
|
| 8 |
+
Emits (nothing else, ever):
|
| 9 |
+
submission k/16
|
| 10 |
+
correctness: PASS | FAIL
|
| 11 |
+
[FAIL only] failing_invariant: <name from a fixed allow-list>
|
| 12 |
+
[FAIL only] diagnostic: <short, actionable, leak-free>
|
| 13 |
+
dev_speedup: <x> (relative performance ratio vs the reference baseline; higher is better)
|
| 14 |
+
dev_reward: <r> (= dev_speedup when correct, else 0; an in-session PROXY)
|
| 15 |
+
best_so_far: submission <j>, dev_speedup <x>, dev_reward <r>
|
| 16 |
+
remaining: <16 - k>
|
| 17 |
+
finalize_allowed: <true|false>
|
| 18 |
+
[harness path] harness_error: <message> (candidate not at fault; budget not consumed)
|
| 19 |
+
|
| 20 |
+
NEVER emits: verifier / test.sh / compute_reward contents; hidden workload
|
| 21 |
+
names / seeds / counts / shapes; any threshold; ref_speedup; absolute timings or
|
| 22 |
+
byte counts; actual_hardware_type.
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import json
|
| 27 |
+
import sys
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
LOOP = Path("/logs/loop")
|
| 31 |
+
DEV = LOOP / "dev"
|
| 32 |
+
MIN_SUBMISSIONS = 3
|
| 33 |
+
MAX_SUBMISSIONS = 16
|
| 34 |
+
|
| 35 |
+
SIGNATURE = 'cross_entropy_loss_grad(logits, labels, ignore_index, label_smoothing) -> (loss, grad)'
|
| 36 |
+
PRIMITIVE_HINT = 'your implementation references a forbidden fused cross-entropy primitive (F.cross_entropy / CrossEntropyLoss) — compute the loss and input gradient yourself'
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _read_json(path: Path, default):
|
| 40 |
+
try:
|
| 41 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 42 |
+
except Exception:
|
| 43 |
+
return default
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _fmt(x, nd=4):
|
| 47 |
+
try:
|
| 48 |
+
return f"{float(x):.{nd}g}"
|
| 49 |
+
except Exception:
|
| 50 |
+
return str(x)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _named_invariant(state: dict):
|
| 54 |
+
hard = [str(r) for r in (state.get("hard_fail_reasons") or [])]
|
| 55 |
+
|
| 56 |
+
def has(*subs):
|
| 57 |
+
return any(any(s in h for s in subs) for h in hard)
|
| 58 |
+
|
| 59 |
+
if has("forbidden_edit_path", "forbidden_source"):
|
| 60 |
+
return ("edit_scope",
|
| 61 |
+
"only the single product file may change and it must not reference any "
|
| 62 |
+
"scoring / verifier path — keep your edits to the product implementation only")
|
| 63 |
+
if has("_primitive", "_operator"):
|
| 64 |
+
return ("allowed_ops", PRIMITIVE_HINT)
|
| 65 |
+
if has("product_file_missing", "candidate_load_failed", "repo_missing"):
|
| 66 |
+
return ("product_present_and_importable",
|
| 67 |
+
f"the product could not be found or imported — keep the public {SIGNATURE} intact")
|
| 68 |
+
if has("hidden_correctness_failed"):
|
| 69 |
+
return ("output_matches_reference",
|
| 70 |
+
"your output disagreed with the reference on at least one case (numeric tolerance, "
|
| 71 |
+
"dtype / shape / device, an error-contract probe that must raise, or a metamorphic "
|
| 72 |
+
f"invariant) — verify the contract of {SIGNATURE}")
|
| 73 |
+
if has("benchmark_execution_failed"):
|
| 74 |
+
return ("runs_without_error",
|
| 75 |
+
"the measurement could not complete — your implementation likely raised, produced "
|
| 76 |
+
"non-finite values, or disagreed with the baseline while being measured")
|
| 77 |
+
return ("verifier_completed",
|
| 78 |
+
"the check did not complete cleanly — re-check that your last change did not cause an early crash")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def main() -> int:
|
| 82 |
+
try:
|
| 83 |
+
k = int((LOOP / "count").read_text(encoding="utf-8").strip())
|
| 84 |
+
except Exception:
|
| 85 |
+
k = 0
|
| 86 |
+
|
| 87 |
+
he = DEV / "harness_error.txt"
|
| 88 |
+
if he.exists():
|
| 89 |
+
try:
|
| 90 |
+
msg = he.read_text(encoding="utf-8").strip().splitlines()[0]
|
| 91 |
+
except Exception:
|
| 92 |
+
msg = "dev engine infrastructure error"
|
| 93 |
+
print(f"submission {k}/{MAX_SUBMISSIONS}")
|
| 94 |
+
print(f"harness_error: {msg} — this is NOT a defect in your code; do not debug the "
|
| 95 |
+
f"harness. Retry or continue optimizing (this attempt was not counted).")
|
| 96 |
+
return 0
|
| 97 |
+
|
| 98 |
+
state = _read_json(DEV / "verifier_state.json", {})
|
| 99 |
+
bench = _read_json(DEV / "benchmark_results.json", {})
|
| 100 |
+
reward = _read_json(DEV / "reward.json", {})
|
| 101 |
+
|
| 102 |
+
corr_ok = bool(state.get("correctness_ok"))
|
| 103 |
+
speedup = bench.get("aggregate_speedup", None)
|
| 104 |
+
r = reward.get("reward", 0.0)
|
| 105 |
+
|
| 106 |
+
print(f"submission {k}/{MAX_SUBMISSIONS}")
|
| 107 |
+
if corr_ok:
|
| 108 |
+
print("correctness: PASS")
|
| 109 |
+
else:
|
| 110 |
+
print("correctness: FAIL")
|
| 111 |
+
inv, hint = _named_invariant(state)
|
| 112 |
+
print(f"failing_invariant: {inv}")
|
| 113 |
+
print(f"diagnostic: {hint}")
|
| 114 |
+
|
| 115 |
+
print(f"dev_speedup: {_fmt(speedup) if speedup is not None else 'n/a'}")
|
| 116 |
+
print(f"dev_reward: {_fmt(r)}")
|
| 117 |
+
|
| 118 |
+
best = _read_json(LOOP / "best.json", None)
|
| 119 |
+
if best and isinstance(best, dict) and best.get("submission"):
|
| 120 |
+
print(f"best_so_far: submission {best.get('submission')}, "
|
| 121 |
+
f"dev_speedup {_fmt(best.get('speedup'))}, dev_reward {_fmt(best.get('reward'))}")
|
| 122 |
+
else:
|
| 123 |
+
print("best_so_far: (none — no correctness-passing submission yet)")
|
| 124 |
+
|
| 125 |
+
print(f"remaining: {max(0, MAX_SUBMISSIONS - k)}")
|
| 126 |
+
print(f"finalize_allowed: {'true' if k >= MIN_SUBMISSIONS else 'false'}")
|
| 127 |
+
return 0
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
sys.exit(main())
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/score_engine.sh
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# DEV scoring engine (0700 root:root) for insea-fused-softmax-cross-entropy-grad-loop16. Invoked ONLY by
|
| 3 |
+
# /opt/loop/submit.sh — never by the solver.
|
| 4 |
+
#
|
| 5 |
+
# It reuses the task verifier VERBATIM: it runs the baked copy of the base
|
| 6 |
+
# task's tests/test.sh (byte-identical except its output dir is /logs/loop/dev
|
| 7 |
+
# instead of /logs/verifier) against the LIVE /app/repo in the default candidate
|
| 8 |
+
# mode (which scores /app/repo AS-IS and never clobbers it). The base
|
| 9 |
+
# compute_reward.py writes reward = speedup (uncapped). The authoritative reward
|
| 10 |
+
# still comes from the runner's end-of-session /tests/ run, NOT from here.
|
| 11 |
+
#
|
| 12 |
+
# PATH-pin: the agent shell + runner verifier exec are
|
| 13 |
+
# NON-login; bare python3 has no torch. Pin the venv FIRST.
|
| 14 |
+
export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
| 15 |
+
set -uo pipefail
|
| 16 |
+
|
| 17 |
+
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 18 |
+
DEV_OUT="${LOOP_DEV_OUT:-/logs/loop/dev}"
|
| 19 |
+
mkdir -p "$DEV_OUT"
|
| 20 |
+
# fresh run: clear any stale harness marker
|
| 21 |
+
rm -f "$DEV_OUT/harness_error.txt" 2>/dev/null || true
|
| 22 |
+
|
| 23 |
+
# Run the baked task verifier (candidate mode). Suppress its stdout entirely
|
| 24 |
+
# (the base test.sh echoes a summary line carrying ref_speedup / hardware / raw
|
| 25 |
+
# speedup — that MUST NOT reach the solver; only sanitize_feedback.py emits).
|
| 26 |
+
KERNELBENCH_VERIFY_MODE=candidate bash "$HERE/private/dev_tests/test.sh" \
|
| 27 |
+
> "$DEV_OUT/dev_engine_stdout.log" 2>&1
|
| 28 |
+
rc=$?
|
| 29 |
+
|
| 30 |
+
# If the base verifier could not even write a reward (infra/torch/cuda failure),
|
| 31 |
+
# it exits non-zero WITHOUT a reward.json. Synthesize a harness marker so
|
| 32 |
+
# submit.sh treats it as infra (does not consume the solver's budget) rather than
|
| 33 |
+
# a silent candidate FAIL.
|
| 34 |
+
if [ "$rc" -ne 0 ] && [ ! -f "$DEV_OUT/reward.json" ] && [ ! -f "$DEV_OUT/harness_error.txt" ]; then
|
| 35 |
+
{
|
| 36 |
+
echo "dev_engine_exit_${rc}"
|
| 37 |
+
tail -n 40 "$DEV_OUT/dev_engine_stdout.log" 2>/dev/null
|
| 38 |
+
} > "$DEV_OUT/harness_error.txt"
|
| 39 |
+
exit 3
|
| 40 |
+
fi
|
| 41 |
+
exit 0
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/submit.sh
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Per-task 3-to-16-submission loop harness for
|
| 3 |
+
# insea-fused-softmax-cross-entropy-grad-loop16.
|
| 4 |
+
#
|
| 5 |
+
# The solver's ONLY sanctioned interface to scoring during the session
|
| 6 |
+
# (0755 root:root; the engine + private assets it calls are 0700 root-owned).
|
| 7 |
+
# Baked at /opt/loop/submit.sh so it is present from the first turn — unlike
|
| 8 |
+
# /tests/, which the runner creates only AFTER the agent finishes.
|
| 9 |
+
#
|
| 10 |
+
# Usage:
|
| 11 |
+
# bash /opt/loop/submit.sh # score current /app/repo, get feedback
|
| 12 |
+
# bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best iterate, end loop
|
| 13 |
+
#
|
| 14 |
+
# Each `submit`:
|
| 15 |
+
# 1. runs the baked DEV engine (visible-subset correctness + dev timing) on
|
| 16 |
+
# the LIVE /app/repo and returns SANITIZED feedback;
|
| 17 |
+
# 2. snapshots the candidate tree (git stash-create tree hash + binary diff)
|
| 18 |
+
# to /logs/loop/submissions/<k>/;
|
| 19 |
+
# 3. updates /logs/loop/best.json (best correctness-passing dev_reward);
|
| 20 |
+
# 4. enforces min=3 / max=16.
|
| 21 |
+
# On --finalize (>=3) or auto at k=16 it restores /app/repo's WORKING TREE to
|
| 22 |
+
# the best correctness-passing snapshot (HEAD stays at the baseline commit so
|
| 23 |
+
# the runner's end-of-session verifier still sees a product-only modification)
|
| 24 |
+
# and writes /logs/loop/finalize.json for the audit.
|
| 25 |
+
#
|
| 26 |
+
# 🔴 PATH-pin: the agent shell + runner verifier exec are
|
| 27 |
+
# NON-login; bare python3 has no torch. Pin the venv FIRST.
|
| 28 |
+
export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
| 29 |
+
set -uo pipefail
|
| 30 |
+
|
| 31 |
+
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 32 |
+
REPO=/app/repo
|
| 33 |
+
LOOP=/logs/loop
|
| 34 |
+
DEV="$LOOP/dev"
|
| 35 |
+
mkdir -p "$LOOP" "$LOOP/submissions" "$DEV"
|
| 36 |
+
|
| 37 |
+
MIN_SUBMISSIONS=1
|
| 38 |
+
MAX_SUBMISSIONS=1
|
| 39 |
+
COUNT_FILE="$LOOP/count"
|
| 40 |
+
BEST_FILE="$LOOP/best.json"
|
| 41 |
+
STATE_JSONL="$LOOP/state.jsonl"
|
| 42 |
+
FINALIZE_JSON="$LOOP/finalize.json"
|
| 43 |
+
|
| 44 |
+
_read_count() {
|
| 45 |
+
if [ -f "$COUNT_FILE" ]; then
|
| 46 |
+
awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE"
|
| 47 |
+
else
|
| 48 |
+
echo 0
|
| 49 |
+
fi
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
# Non-mutating snapshot of the current working tree -> a git tree hash.
|
| 53 |
+
# `git stash create` builds dangling objects without touching HEAD/index/WT.
|
| 54 |
+
_snapshot_tree() {
|
| 55 |
+
local c
|
| 56 |
+
c="$(git -C "$REPO" stash create 2>/dev/null || true)"
|
| 57 |
+
if [ -n "$c" ]; then
|
| 58 |
+
git -C "$REPO" rev-parse "$c^{tree}" 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null
|
| 59 |
+
else
|
| 60 |
+
git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null
|
| 61 |
+
fi
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
# ------------------- argument parsing -------------------
|
| 65 |
+
MODE=submit
|
| 66 |
+
REASON=""
|
| 67 |
+
while [ "$#" -gt 0 ]; do
|
| 68 |
+
case "$1" in
|
| 69 |
+
--finalize) MODE=finalize; shift ;;
|
| 70 |
+
--reason) REASON="${2:-}"; shift 2 ;;
|
| 71 |
+
--reason=*) REASON="${1#--reason=}"; shift ;;
|
| 72 |
+
*) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"<text>\"]]" >&2; exit 2 ;;
|
| 73 |
+
esac
|
| 74 |
+
done
|
| 75 |
+
|
| 76 |
+
# ------------------- finalize -------------------
|
| 77 |
+
if [ "$MODE" = finalize ]; then
|
| 78 |
+
CUR="$(_read_count)"; CUR="${CUR:-0}"
|
| 79 |
+
if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then
|
| 80 |
+
echo "minimum $MIN_SUBMISSIONS submission(s) required before finalize (you have $CUR/$MIN_SUBMISSIONS)"
|
| 81 |
+
exit 1
|
| 82 |
+
fi
|
| 83 |
+
# Restore /app/repo working tree to the best correctness-passing snapshot.
|
| 84 |
+
git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true
|
| 85 |
+
git -C "$REPO" clean -qfd 2>/dev/null || true
|
| 86 |
+
WIN_DIFF=""
|
| 87 |
+
WIN_SUB=""
|
| 88 |
+
if [ -f "$BEST_FILE" ]; then
|
| 89 |
+
WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)"
|
| 90 |
+
fi
|
| 91 |
+
if [ -n "$WIN_SUB" ] && [ -f "$LOOP/submissions/$WIN_SUB/candidate.diff" ]; then
|
| 92 |
+
WIN_DIFF="$LOOP/submissions/$WIN_SUB/candidate.diff"
|
| 93 |
+
if [ -s "$WIN_DIFF" ]; then
|
| 94 |
+
git -C "$REPO" apply --whitespace=nowarn "$WIN_DIFF" 2>"$LOOP/finalize_apply.log" || \
|
| 95 |
+
echo "WARNING: could not re-apply the winning diff cleanly; see /logs/loop/finalize_apply.log" >&2
|
| 96 |
+
fi
|
| 97 |
+
fi
|
| 98 |
+
# Write finalize.json (winning index, k, dev_speedup trajectory, reason) for audit.
|
| 99 |
+
REASON="$REASON" WIN_SUB="$WIN_SUB" CUR="$CUR" python3 - <<'PY'
|
| 100 |
+
import json, os
|
| 101 |
+
from pathlib import Path
|
| 102 |
+
LOOP = Path('/logs/loop')
|
| 103 |
+
best = {}
|
| 104 |
+
try:
|
| 105 |
+
best = json.loads((LOOP / 'best.json').read_text())
|
| 106 |
+
except Exception:
|
| 107 |
+
best = {}
|
| 108 |
+
traj = []
|
| 109 |
+
try:
|
| 110 |
+
for line in (LOOP / 'state.jsonl').read_text().splitlines():
|
| 111 |
+
line = line.strip()
|
| 112 |
+
if not line:
|
| 113 |
+
continue
|
| 114 |
+
row = json.loads(line)
|
| 115 |
+
traj.append({'submission': row.get('submission'),
|
| 116 |
+
'dev_speedup': row.get('speedup'),
|
| 117 |
+
'dev_reward': row.get('reward'),
|
| 118 |
+
'correctness_ok': row.get('correctness_ok')})
|
| 119 |
+
except Exception:
|
| 120 |
+
pass
|
| 121 |
+
win = best.get('submission') if best else None
|
| 122 |
+
out = {
|
| 123 |
+
'schema_version': 'kernelbench_loop_finalize_v1',
|
| 124 |
+
'task_id': 'insea-fused-softmax-cross-entropy-grad-loop16',
|
| 125 |
+
'mode': 'baked',
|
| 126 |
+
'submissions_used': int(os.environ.get('CUR') or 0),
|
| 127 |
+
'min_submissions': 1, 'max_submissions': 1,
|
| 128 |
+
'winning_submission': win,
|
| 129 |
+
'winning_dev_speedup': best.get('speedup') if best else None,
|
| 130 |
+
'winning_dev_reward': best.get('reward') if best else None,
|
| 131 |
+
'winning_tree': best.get('tree') if best else None,
|
| 132 |
+
'dev_speedup_trajectory': traj,
|
| 133 |
+
'termination_reason': os.environ.get('REASON') or '',
|
| 134 |
+
'note': 'dev_reward is an in-session proxy; meta.reward is the runner end-of-session score of /app/repo.',
|
| 135 |
+
}
|
| 136 |
+
(LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n')
|
| 137 |
+
PY
|
| 138 |
+
# Integrity: recompute the restored tree hash for the audit trail.
|
| 139 |
+
RESTORED_TREE="$(_snapshot_tree)"
|
| 140 |
+
echo "restored_tree=$RESTORED_TREE" >> "$LOOP/finalize_apply.log" 2>/dev/null || true
|
| 141 |
+
if [ -n "$WIN_SUB" ]; then
|
| 142 |
+
WR="$(python3 -c 'import json,sys;b=json.load(open(sys.argv[1]));print(f"{b.get(\"speedup\")}", f"{b.get(\"reward\")}")' "$BEST_FILE" 2>/dev/null || echo "? ?")"
|
| 143 |
+
echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (dev_speedup ${WR% *}, dev_reward ${WR#* }); the grader will now score /app/repo"
|
| 144 |
+
else
|
| 145 |
+
echo "finalized: no correctness-passing submission in $CUR tries — /app/repo restored to the starting baseline; final reward will be 0 (no_improvement). the grader will now score /app/repo"
|
| 146 |
+
fi
|
| 147 |
+
exit 0
|
| 148 |
+
fi
|
| 149 |
+
|
| 150 |
+
# ------------------- submit -------------------
|
| 151 |
+
CUR="$(_read_count)"; CUR="${CUR:-0}"
|
| 152 |
+
if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then
|
| 153 |
+
echo "submission $CUR/$MAX_SUBMISSIONS"
|
| 154 |
+
echo "budget exhausted — call 'bash /opt/loop/submit.sh --finalize' to grade your best submission"
|
| 155 |
+
# Auto-finalize as a safety net.
|
| 156 |
+
echo "--- auto-finalizing best-of-$MAX_SUBMISSIONS ---"
|
| 157 |
+
exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
|
| 158 |
+
fi
|
| 159 |
+
|
| 160 |
+
# Run the DEV engine on the LIVE /app/repo.
|
| 161 |
+
bash "$HERE/score_engine.sh"
|
| 162 |
+
engine_rc=$?
|
| 163 |
+
|
| 164 |
+
# HARNESS error path: the engine flagged an infra failure (rc=3 or a marker).
|
| 165 |
+
# Do NOT consume the solver's budget for our bug.
|
| 166 |
+
if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then
|
| 167 |
+
python3 "$HERE/sanitize_feedback.py"
|
| 168 |
+
exit 0
|
| 169 |
+
fi
|
| 170 |
+
|
| 171 |
+
# Consume one submission.
|
| 172 |
+
NEXT=$((CUR + 1))
|
| 173 |
+
echo "$NEXT" > "$COUNT_FILE"
|
| 174 |
+
|
| 175 |
+
# Snapshot the candidate: tree hash (non-mutating) + binary diff vs baseline HEAD.
|
| 176 |
+
SNAP="$LOOP/submissions/$NEXT"
|
| 177 |
+
mkdir -p "$SNAP"
|
| 178 |
+
TREE="$(_snapshot_tree)"
|
| 179 |
+
git -C "$REPO" diff --binary HEAD > "$SNAP/candidate.diff" 2>/dev/null || true
|
| 180 |
+
echo "${TREE:-}" > "$SNAP/tree.txt"
|
| 181 |
+
for f in verifier_state.json correctness_results.json benchmark_results.json reward.json; do
|
| 182 |
+
[ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true
|
| 183 |
+
done
|
| 184 |
+
|
| 185 |
+
# Update best-of-k (only correctness-passing, strictly-greater dev_reward) and
|
| 186 |
+
# append the per-submission audit row.
|
| 187 |
+
NEXT="$NEXT" TREE="$TREE" python3 - <<'PY'
|
| 188 |
+
import json, os, time
|
| 189 |
+
from pathlib import Path
|
| 190 |
+
LOOP = Path('/logs/loop'); DEV = LOOP / 'dev'
|
| 191 |
+
k = int(os.environ['NEXT']); tree = os.environ.get('TREE') or ''
|
| 192 |
+
try:
|
| 193 |
+
state = json.loads((DEV / 'verifier_state.json').read_text())
|
| 194 |
+
except Exception:
|
| 195 |
+
state = {}
|
| 196 |
+
try:
|
| 197 |
+
reward = json.loads((DEV / 'reward.json').read_text())
|
| 198 |
+
except Exception:
|
| 199 |
+
reward = {}
|
| 200 |
+
corr_ok = bool(state.get('correctness_ok'))
|
| 201 |
+
r = float(reward.get('reward') or 0.0)
|
| 202 |
+
s = float(reward.get('speedup') or 0.0)
|
| 203 |
+
# append audit row
|
| 204 |
+
row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok,
|
| 205 |
+
'reward': r, 'speedup': s, 'tree': tree,
|
| 206 |
+
'hard_fail_reasons': list(state.get('hard_fail_reasons') or [])}
|
| 207 |
+
with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f:
|
| 208 |
+
f.write(json.dumps(row) + '\n')
|
| 209 |
+
# update best
|
| 210 |
+
if corr_ok:
|
| 211 |
+
best_p = LOOP / 'best.json'
|
| 212 |
+
try:
|
| 213 |
+
best = json.loads(best_p.read_text())
|
| 214 |
+
except Exception:
|
| 215 |
+
best = None
|
| 216 |
+
if best is None or r > float(best.get('reward') or -1.0):
|
| 217 |
+
best_p.write_text(json.dumps(
|
| 218 |
+
{'submission': k, 'reward': r, 'speedup': s, 'tree': tree},
|
| 219 |
+
indent=2, sort_keys=True) + '\n')
|
| 220 |
+
PY
|
| 221 |
+
|
| 222 |
+
# Print sanitized feedback.
|
| 223 |
+
python3 "$HERE/sanitize_feedback.py"
|
| 224 |
+
|
| 225 |
+
# Auto-finalize on the ceiling.
|
| 226 |
+
if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then
|
| 227 |
+
echo ""
|
| 228 |
+
echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---"
|
| 229 |
+
exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
|
| 230 |
+
fi
|
| 231 |
+
|
| 232 |
+
exit 0
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/repo/cross_entropy_grad.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cross-entropy loss and input-gradient over a batch of logit rows.
|
| 2 |
+
|
| 3 |
+
Public entry point:
|
| 4 |
+
``cross_entropy_loss_grad(logits, labels, ignore_index=-100,
|
| 5 |
+
label_smoothing=0.0) -> (loss, grad)``
|
| 6 |
+
|
| 7 |
+
Given a batch of ``N`` rows of class scores (``logits``) and one integer target
|
| 8 |
+
class per row (``labels``), compute the mean cross-entropy loss over the
|
| 9 |
+
non-ignored rows and the gradient of that loss with respect to ``logits``.
|
| 10 |
+
|
| 11 |
+
Contract
|
| 12 |
+
--------
|
| 13 |
+
- ``logits``: shape ``(N, V)``, a floating-point CUDA tensor (``float32`` or
|
| 14 |
+
``bfloat16``). ``N`` is the number of rows (batch * sequence), ``V`` the
|
| 15 |
+
number of classes (vocabulary size).
|
| 16 |
+
- ``labels``: shape ``(N,)``, an integer CUDA tensor. Each entry is a class
|
| 17 |
+
index in ``[0, V)``, or equals ``ignore_index`` to mark the row as ignored.
|
| 18 |
+
- ``ignore_index``: int. Rows whose label equals this value contribute zero to
|
| 19 |
+
the loss and zero to the gradient.
|
| 20 |
+
- ``label_smoothing``: float ``>= 0``. ``0.0`` is ordinary cross entropy.
|
| 21 |
+
|
| 22 |
+
Returns
|
| 23 |
+
-------
|
| 24 |
+
- ``loss``: a scalar tensor — the mean cross-entropy (with optional label
|
| 25 |
+
smoothing) over the non-ignored rows. If every row is ignored, the loss is
|
| 26 |
+
``0``.
|
| 27 |
+
- ``grad``: shape ``(N, V)``, same dtype as ``logits`` — the gradient of
|
| 28 |
+
``loss`` w.r.t. ``logits``. Ignored rows are exactly zero.
|
| 29 |
+
|
| 30 |
+
Definition (per non-ignored row with target ``y``, over ``n`` non-ignored rows):
|
| 31 |
+
``p = softmax(logits)``
|
| 32 |
+
``loss_row = -(1 - s) * log p[y] - (s / V) * sum_k log p[k]``
|
| 33 |
+
``grad_row[j] = ( p[j] - s / V - (1 - s) * [j == y] ) / n``
|
| 34 |
+
where ``s = label_smoothing``. All reductions are computed in float32; the
|
| 35 |
+
gradient is returned in the input dtype.
|
| 36 |
+
|
| 37 |
+
Error contract
|
| 38 |
+
--------------
|
| 39 |
+
- ``TypeError`` if ``logits`` is not a floating-point tensor, or ``labels`` is
|
| 40 |
+
not an integer tensor.
|
| 41 |
+
- ``ValueError`` if ``logits`` is not 2-D; if ``labels`` is not 1-D of length
|
| 42 |
+
``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies
|
| 43 |
+
outside ``[0, V)``.
|
| 44 |
+
|
| 45 |
+
Note on the current implementation
|
| 46 |
+
----------------------------------
|
| 47 |
+
This straightforward implementation forms the full log-probability tensor, the
|
| 48 |
+
full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers
|
| 49 |
+
in addition to the input. It is correct but holds several full-size copies of
|
| 50 |
+
the logits at once, which is expensive at large ``V``.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
import torch
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _validate(logits, labels, label_smoothing):
|
| 57 |
+
if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor):
|
| 58 |
+
raise TypeError("logits and labels must be torch.Tensor")
|
| 59 |
+
if not torch.is_floating_point(logits):
|
| 60 |
+
raise TypeError(f"logits must be a floating-point tensor, got {logits.dtype}")
|
| 61 |
+
if labels.dtype not in (torch.int32, torch.int64):
|
| 62 |
+
raise TypeError(f"labels must be an integer tensor, got {labels.dtype}")
|
| 63 |
+
if logits.dim() != 2:
|
| 64 |
+
raise ValueError(f"logits must be 2-D (N, V), got {logits.dim()}-D")
|
| 65 |
+
N, V = logits.shape
|
| 66 |
+
if labels.dim() != 1 or labels.shape[0] != N:
|
| 67 |
+
raise ValueError(f"labels must be 1-D of length N={N}, got shape {tuple(labels.shape)}")
|
| 68 |
+
if float(label_smoothing) < 0.0:
|
| 69 |
+
raise ValueError(f"label_smoothing must be >= 0, got {label_smoothing}")
|
| 70 |
+
return N, V
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0):
|
| 74 |
+
"""See module docstring for the full contract."""
|
| 75 |
+
N, V = _validate(logits, labels, label_smoothing)
|
| 76 |
+
s = float(label_smoothing)
|
| 77 |
+
|
| 78 |
+
valid = labels != ignore_index
|
| 79 |
+
# non-ignored labels must be inside [0, V)
|
| 80 |
+
if valid.any():
|
| 81 |
+
vlab = labels[valid]
|
| 82 |
+
if int(vlab.max()) >= V or int(vlab.min()) < 0:
|
| 83 |
+
raise ValueError(f"a non-ignored label is out of range [0, {V})")
|
| 84 |
+
n_valid = int(valid.sum().item())
|
| 85 |
+
denom = max(n_valid, 1)
|
| 86 |
+
|
| 87 |
+
safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later)
|
| 88 |
+
idx = torch.arange(N, device=logits.device)
|
| 89 |
+
|
| 90 |
+
lf = logits.to(torch.float32)
|
| 91 |
+
logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer
|
| 92 |
+
logp_y = logp[idx, safe] # (N,)
|
| 93 |
+
nll = -logp_y
|
| 94 |
+
smooth = -logp.mean(dim=1) # -mean_k log p[k]
|
| 95 |
+
row_loss = (1.0 - s) * nll + s * smooth
|
| 96 |
+
row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss))
|
| 97 |
+
loss = row_loss.sum() / denom
|
| 98 |
+
|
| 99 |
+
prob = logp.exp() # (N, V) softmax
|
| 100 |
+
grad = prob.clone() # (N, V) gradient buffer
|
| 101 |
+
if s != 0.0:
|
| 102 |
+
grad = grad - (s / V)
|
| 103 |
+
grad[idx, safe] = grad[idx, safe] - (1.0 - s)
|
| 104 |
+
grad = grad / denom
|
| 105 |
+
grad[~valid] = 0.0 # ignored rows -> exactly zero
|
| 106 |
+
return loss, grad.to(logits.dtype)
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/entrypoint.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Matches the proven ready-task entrypoint (kernel-opt-p0a4-003): start the timer
|
| 3 |
+
# in the background and hand the container to a login shell so the orchestrator can
|
| 4 |
+
# keep it alive and exec /tests/test.sh into it. `exec "$@"` is honored when a
|
| 5 |
+
# command is passed (e.g. local smoke).
|
| 6 |
+
set -euo pipefail
|
| 7 |
+
export PATH=/opt/kernelbench-venv/bin:$PATH
|
| 8 |
+
mkdir -p /app/.timer
|
| 9 |
+
/app/timer.sh >/tmp/task-timer.log 2>&1 &
|
| 10 |
+
if [ "$#" -gt 0 ]; then
|
| 11 |
+
exec "$@"
|
| 12 |
+
fi
|
| 13 |
+
exec /bin/bash -l
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/run_dev_bench.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
export PATH=/opt/kernelbench-venv/bin:$PATH
|
| 4 |
+
printf '%s\n' 'Public development feedback only. Final verification runs additional trusted and hidden workloads.'
|
| 5 |
+
exit 0
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/timer.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Minimal global timer stub; the harness replaces it with the real budget timer.
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
export PATH=/opt/kernelbench-venv/bin:$PATH
|
| 5 |
+
mkdir -p /app/.timer
|
| 6 |
+
echo 10800 > /app/.timer/remaining_secs
|
| 7 |
+
echo 10800 > /app/.timer/budget_secs
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/verifier-correctness-manifest.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "kernelbench_correctness_manifest_v1",
|
| 3 |
+
"task_id": "insea-fused-softmax-cross-entropy-grad-loop16",
|
| 4 |
+
"task_kind": "acceleration",
|
| 5 |
+
"expected_case_count": 12,
|
| 6 |
+
"primary_workload": "ce-peakmem-geomean-4shapes",
|
| 7 |
+
"ref_speedup": 1.0,
|
| 8 |
+
"ref_speedup_note": "Anchor 7.4157 calibrated in oracle mode on NVIDIA H20. tests/ref_speedup.txt is authoritative at scoring; this file is only the in-image fallback. See tests/ref_speedup.caveat.md to re-measure on your hardware.",
|
| 9 |
+
"metric": "peak_memory_bytes",
|
| 10 |
+
"metric_note": "SCORE PEAK MEMORY, NOT WALL-TIME. speedup = torch.cuda.max_memory_allocated(baseline)/max_memory_allocated(candidate), geomean over 4 large-vocab shapes on H20. Latency may be ~1.0x — expected for a memory-frugal op (false-negative checklist item #2).",
|
| 11 |
+
"direction": "higher_is_better",
|
| 12 |
+
"target_hardware": "H20",
|
| 13 |
+
"correctness_axes": [
|
| 14 |
+
"normal",
|
| 15 |
+
"boundary",
|
| 16 |
+
"all_ignore",
|
| 17 |
+
"single_class",
|
| 18 |
+
"single_row",
|
| 19 |
+
"nontile_vocab",
|
| 20 |
+
"label_smoothing",
|
| 21 |
+
"degenerate",
|
| 22 |
+
"error",
|
| 23 |
+
"metamorphic",
|
| 24 |
+
"work_evidence",
|
| 25 |
+
"anti_hacking"
|
| 26 |
+
],
|
| 27 |
+
"public_symbol": "cross_entropy_loss_grad",
|
| 28 |
+
"primary_edit_paths": [
|
| 29 |
+
"/app/repo/cross_entropy_grad.py"
|
| 30 |
+
]
|
| 31 |
+
}
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/instruction.md
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Performance Optimization Task
|
| 2 |
+
|
| 3 |
+
You are working on the loss stage of a large language model's training step. The
|
| 4 |
+
file `cross_entropy_grad.py` implements `cross_entropy_loss_grad` — it takes a
|
| 5 |
+
batch of per-row class scores (`logits`) and one integer target class per row
|
| 6 |
+
(`labels`) and returns the mean cross-entropy loss together with the gradient of
|
| 7 |
+
that loss with respect to `logits`.
|
| 8 |
+
|
| 9 |
+
## Behavioral contract
|
| 10 |
+
|
| 11 |
+
For a batch of `N` rows over `V` classes, each non-ignored row contributes the
|
| 12 |
+
**cross entropy between a smoothed target distribution and that row's softmax over
|
| 13 |
+
the `V` classes**, in the standard PyTorch label-smoothing convention: with
|
| 14 |
+
`s = label_smoothing`, the target distribution places weight `1 - s` on the row's own
|
| 15 |
+
label and spreads the remaining `s` **uniformly across all `V` classes, the label
|
| 16 |
+
included**. The returned `loss` is the mean of those per-row losses over the
|
| 17 |
+
non-ignored rows only (ignored rows enter neither the sum nor the row count). The
|
| 18 |
+
returned `grad` is the exact gradient of that returned mean loss with respect to
|
| 19 |
+
`logits`, one row per input row, with ignored rows carrying an all-zero gradient row.
|
| 20 |
+
|
| 21 |
+
1. `logits`: shape `(N, V)`, a floating-point CUDA tensor (`torch.float32` or
|
| 22 |
+
`torch.bfloat16`). `N` is the number of rows (batch times sequence length),
|
| 23 |
+
`V` the number of classes (vocabulary size).
|
| 24 |
+
2. `labels`: shape `(N,)`, an integer CUDA tensor. Each entry is a class index in
|
| 25 |
+
`[0, V)`, **or** equals `ignore_index` to mark that row as ignored. Ignored
|
| 26 |
+
rows contribute **zero** loss and **zero** gradient.
|
| 27 |
+
3. `ignore_index`: int (default `-100`).
|
| 28 |
+
4. `label_smoothing`: float `>= 0` (default `0.0`; `0.0` is ordinary cross
|
| 29 |
+
entropy).
|
| 30 |
+
|
| 31 |
+
Reductions are computed in float32; the gradient is returned in the input dtype.
|
| 32 |
+
|
| 33 |
+
Public signature (do NOT change):
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
def cross_entropy_loss_grad(
|
| 37 |
+
logits: torch.Tensor, # (N, V) float32/bfloat16 CUDA
|
| 38 |
+
labels: torch.Tensor, # (N,) integer CUDA; ignore_index marks ignored rows
|
| 39 |
+
ignore_index: int = -100,
|
| 40 |
+
label_smoothing: float = 0.0,
|
| 41 |
+
) -> tuple: # (loss: scalar tensor, grad: (N, V) same dtype as logits)
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Error contract: non-floating-point `logits`, or non-integer `labels` →
|
| 45 |
+
`TypeError`; `logits` not 2-D, `labels` not 1-D of length `N`, negative
|
| 46 |
+
`label_smoothing`, or any non-ignored label outside `[0, V)` → `ValueError`.
|
| 47 |
+
|
| 48 |
+
## What to improve
|
| 49 |
+
|
| 50 |
+
The current implementation is **correct but wasteful with intermediate state**: at
|
| 51 |
+
large vocabulary sizes the intermediates it keeps resident dominate the memory
|
| 52 |
+
footprint. Read it yourself and work out which buffers are alive at the same time.
|
| 53 |
+
|
| 54 |
+
Your goal is to produce the **same** loss and gradient while holding a far smaller
|
| 55 |
+
retained set — the extra working set beyond the input `logits` buffer should stay
|
| 56 |
+
small (on the order of `O(N)` plus a bounded working set, not another `O(N * V)`).
|
| 57 |
+
You are permitted to write the gradient into the `logits` buffer in place (the caller
|
| 58 |
+
passes a buffer you are free to overwrite). Use any GPU technique available in the
|
| 59 |
+
image as long as the contract above holds and the result stays within the verifier's
|
| 60 |
+
tolerance.
|
| 61 |
+
|
| 62 |
+
**Forbidden:** the framework's single-call fused cross-entropy loss —
|
| 63 |
+
`torch.nn.functional.cross_entropy` / `F.cross_entropy` and
|
| 64 |
+
`torch.nn.CrossEntropyLoss`. The scoring harness blocks these at runtime and
|
| 65 |
+
scans your submitted file for them (do not reference them even in comments — the
|
| 66 |
+
scan is textual and scores the task 0). Compute the loss and gradient yourself.
|
| 67 |
+
|
| 68 |
+
## Correctness comes first
|
| 69 |
+
|
| 70 |
+
The verifier compares your `loss` and full `grad` against a high-precision
|
| 71 |
+
reference on multiple workloads — ordinary and label-smoothed, rows with the
|
| 72 |
+
ignore sentinel (including an all-ignored batch), a single class (`V = 1`), a
|
| 73 |
+
single row, a vocabulary size that is not a round multiple, degenerate inputs,
|
| 74 |
+
error-contract probes, metamorphic checks (adding a per-row constant to all
|
| 75 |
+
logits leaves loss and gradient unchanged; permuting rows permutes the gradient
|
| 76 |
+
rows), and a work-evidence check (exactly the non-ignored rows carry a nonzero
|
| 77 |
+
gradient) — within a fixed tolerance. A result outside tolerance on even one case
|
| 78 |
+
scores zero.
|
| 79 |
+
|
| 80 |
+
## Scope
|
| 81 |
+
|
| 82 |
+
Optimize the product implementation in `cross_entropy_grad.py` only. Do **not**
|
| 83 |
+
edit tests, benchmark harnesses, workloads, or dependency/build files. The final
|
| 84 |
+
submitted diff must contain only product-code changes.
|
| 85 |
+
|
| 86 |
+
## How this task is scored — ONE single graded submission (READ CAREFULLY)
|
| 87 |
+
|
| 88 |
+
You get **exactly one** graded submission. There is no iteration loop, no budget
|
| 89 |
+
of retries, and no feedback round you can act on: **submitting ends the task.**
|
| 90 |
+
|
| 91 |
+
1. Work on `/app/repo/cross_entropy_grad.py` until you believe it is both **correct** and as
|
| 92 |
+
memory-frugal as you can make it. Test it yourself as much as you like —
|
| 93 |
+
your own scratch scripts, your own timing harnesses, your own reasoning about
|
| 94 |
+
the code path. None of that costs you anything.
|
| 95 |
+
2. When — and only when — you are done, submit **once**:
|
| 96 |
+
|
| 97 |
+
```
|
| 98 |
+
bash /opt/loop/submit.sh
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
3. **That call is final.** It scores the current state of `/app/repo`, records it,
|
| 102 |
+
and closes the task. A second call to `submit.sh` is refused and exits non-zero.
|
| 103 |
+
You will not get another attempt, and you will not get iterative feedback you
|
| 104 |
+
can use to improve — whatever `/app/repo` contains at that moment is what is
|
| 105 |
+
graded.
|
| 106 |
+
|
| 107 |
+
Because you cannot iterate, **think the design through before you submit** and
|
| 108 |
+
self-test thoroughly: read the current implementation, decide on the change,
|
| 109 |
+
convince yourself the contract still holds on the normal, boundary, degenerate and
|
| 110 |
+
error-path cases described above, and only then submit. A submission that is fast
|
| 111 |
+
but wrong on even one case scores zero, and you cannot repair it afterwards.
|
| 112 |
+
|
| 113 |
+
The grade is produced by a full, trusted end-of-session verifier (more workloads
|
| 114 |
+
than anything you can see), so the submitted state must be genuinely correct — not
|
| 115 |
+
just correct on the cases you happened to try.
|
| 116 |
+
|
| 117 |
+
## 🔴 Red line (hard — ANY one of these makes the whole task score 0)
|
| 118 |
+
|
| 119 |
+
The scoring machinery is off-limits. Solve this task **independently**, using
|
| 120 |
+
ONLY the code in `/app/repo`, the sanitized feedback that `submit.sh` returns,
|
| 121 |
+
and your own knowledge and reasoning.
|
| 122 |
+
|
| 123 |
+
- Do **NOT** read, `cat`, `open`, `less`, `head`/`tail`, `grep`, `find`, or edit
|
| 124 |
+
ANY verifier / correctness / timing / scoring / hidden-test file or directory,
|
| 125 |
+
wherever it may live. Running `bash /opt/loop/submit.sh` is the ONLY sanctioned
|
| 126 |
+
interaction with the scoring machinery.
|
| 127 |
+
- Do **NOT** run any verifier directly or try to reproduce or reverse-engineer it
|
| 128 |
+
— score ONLY by calling `bash /opt/loop/submit.sh`.
|
| 129 |
+
- Do **NOT** search for, print, or infer the hidden workloads, seeds, thresholds,
|
| 130 |
+
the metric name, or the reference speedup from any source.
|
| 131 |
+
- Do **NOT** fetch or look up the source PR, the upstream repository, or a
|
| 132 |
+
reference solution (no web search, no `git` remote fetch, no network to the
|
| 133 |
+
source), whether the internet is on or off.
|
| 134 |
+
- Do **NOT** use, quote, or condition your code on any verifier / scoring / source
|
| 135 |
+
material, however you might have come to see it.
|
| 136 |
+
|
| 137 |
+
Stay inside `/app/repo` and scratch directories you create yourself; use only
|
| 138 |
+
what `submit.sh` returns for scoring signal.
|
| 139 |
+
|
| 140 |
+
## 提交方式
|
| 141 |
+
|
| 142 |
+
本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。
|
| 143 |
+
改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/pre_artifacts.sh
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# ============================================================================
|
| 3 |
+
# pre_artifacts.sh — kfc/insea-fused-softmax-cross-entropy-grad-loop16
|
| 4 |
+
#
|
| 5 |
+
# Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE
|
| 6 |
+
# grading (spec §1.1). It turns whatever the agent left behind into a portable artifact:
|
| 7 |
+
#
|
| 8 |
+
# /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit
|
| 9 |
+
# /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line
|
| 10 |
+
#
|
| 11 |
+
# 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one
|
| 12 |
+
# place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs <base>..HEAD).
|
| 13 |
+
# Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate,
|
| 14 |
+
# `git checkout -q HEAD -- <scope>` re-materialises the baseline for the paired timing,
|
| 15 |
+
# and loop16's `submit.sh --finalize` plants the best iterate with read-tree +
|
| 16 |
+
# checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope
|
| 17 |
+
# gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the
|
| 18 |
+
# "baseline" — and a correct solve scores 0.
|
| 19 |
+
# `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages
|
| 20 |
+
# names only, writes no tree, creates no commit and leaves HEAD exactly where it was.
|
| 21 |
+
#
|
| 22 |
+
# EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier
|
| 23 |
+
# scores the container on its own terms and gives 0 by itself.
|
| 24 |
+
#
|
| 25 |
+
# READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index
|
| 26 |
+
# (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the
|
| 27 |
+
# verifier — which runs after us — sees exactly the `git status --porcelain` it would have
|
| 28 |
+
# seen if this script had never run. No commit, no HEAD move, no working-tree write.
|
| 29 |
+
#
|
| 30 |
+
# CAPTURE ROOTS for THIS task — derived from the package, never assumed:
|
| 31 |
+
# /app/repo git repo, HEAD == the 1-commit carved baseline
|
| 32 |
+
# evidence Dockerfile:142: WORKDIR /app/repo
|
| 33 |
+
# evidence Dockerfile:90: && cd /app/repo \
|
| 34 |
+
# evidence Dockerfile:97: && test "$(git rev-list --count HEAD)" = "1" \
|
| 35 |
+
# evidence test.sh:10: REPO=/app/repo
|
| 36 |
+
#
|
| 37 |
+
# Single root => model.patch is a bare `git diff --binary <baseline>` (no banner).
|
| 38 |
+
# model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable
|
| 39 |
+
# by one reader.
|
| 40 |
+
#
|
| 41 |
+
# loop16 task (environment/loop/ -> /opt/loop in the image): the harness auto-finalizes
|
| 42 |
+
# at k=16 and `submit.sh --finalize` plants the best iterate in the WORKING TREE while
|
| 43 |
+
# HEAD stays on the baked baseline — which is exactly what this script captures. Running
|
| 44 |
+
# it after a finalize therefore yields the GRADED artifact, not the last raw edit.
|
| 45 |
+
# ============================================================================
|
| 46 |
+
set -uo pipefail
|
| 47 |
+
|
| 48 |
+
OUT=/logs/artifacts
|
| 49 |
+
PATCH="$OUT/model.patch"
|
| 50 |
+
LIST="$OUT/model_files.txt"
|
| 51 |
+
MULTI=0 # 1 => several capture roots => each diff gets a banner line
|
| 52 |
+
MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane)
|
| 53 |
+
|
| 54 |
+
mkdir -p "$OUT" 2>/dev/null || true
|
| 55 |
+
: > "$PATCH" 2>/dev/null || true
|
| 56 |
+
: > "$LIST" 2>/dev/null || true
|
| 57 |
+
git config --global --add safe.directory '*' >/dev/null 2>&1 || true
|
| 58 |
+
|
| 59 |
+
banner() { # $1=root $2=mode ; only when there is more than one root
|
| 60 |
+
if [ "$MULTI" = 1 ]; then
|
| 61 |
+
printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null
|
| 62 |
+
fi
|
| 63 |
+
return 0
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
list_add() { # stdin: paths relative to $1 -> absolute, one per line
|
| 67 |
+
sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true
|
| 68 |
+
return 0
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline
|
| 72 |
+
root=$1
|
| 73 |
+
if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
|
| 74 |
+
if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
| 75 |
+
echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot"
|
| 76 |
+
capture_tree "$root"
|
| 77 |
+
return 0
|
| 78 |
+
fi
|
| 79 |
+
# 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and
|
| 80 |
+
# reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could
|
| 81 |
+
# flip a scope gate either way. So copy the repo's index aside and stage into the COPY —
|
| 82 |
+
# the repo's own .git/index is byte-identical when we are done.
|
| 83 |
+
tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi=""
|
| 84 |
+
gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true)
|
| 85 |
+
if [ -z "$gd" ]; then
|
| 86 |
+
gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true)
|
| 87 |
+
case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac
|
| 88 |
+
fi
|
| 89 |
+
if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then
|
| 90 |
+
GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE
|
| 91 |
+
else
|
| 92 |
+
echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index"
|
| 93 |
+
fi
|
| 94 |
+
git -C "$root" add -AN . >/dev/null 2>&1 || true
|
| 95 |
+
base=HEAD
|
| 96 |
+
if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then
|
| 97 |
+
base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null)
|
| 98 |
+
echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree"
|
| 99 |
+
else
|
| 100 |
+
n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0)
|
| 101 |
+
case "$n" in ''|*[!0-9]*) n=0 ;; esac
|
| 102 |
+
if [ "$n" -gt 1 ]; then
|
| 103 |
+
base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1)
|
| 104 |
+
echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:"
|
| 105 |
+
echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so"
|
| 106 |
+
echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved"
|
| 107 |
+
echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve."
|
| 108 |
+
fi
|
| 109 |
+
fi
|
| 110 |
+
[ -n "${base:-}" ] || base=HEAD
|
| 111 |
+
banner "$root" "git-diff-vs-baseline"
|
| 112 |
+
git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true
|
| 113 |
+
names=$(git -C "$root" diff --name-only "$base" 2>/dev/null)
|
| 114 |
+
echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)"
|
| 115 |
+
unset GIT_INDEX_FILE
|
| 116 |
+
[ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null
|
| 117 |
+
printf '%s\n' "$names" | grep -v '^$' | list_add "$root"
|
| 118 |
+
return 0
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot
|
| 122 |
+
root=$1
|
| 123 |
+
if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
|
| 124 |
+
tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0
|
| 125 |
+
if git init -q "$tmp/snap" >/dev/null 2>&1; then
|
| 126 |
+
GD="$tmp/snap/.git"
|
| 127 |
+
empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null)
|
| 128 |
+
( cd "$root" 2>/dev/null || exit 0
|
| 129 |
+
find . -name .git -prune -o -name __pycache__ -prune -o \
|
| 130 |
+
-type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \
|
| 131 |
+
2>/dev/null \
|
| 132 |
+
| GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true
|
| 133 |
+
banner "$root" "tree-snapshot-not-a-git-repo"
|
| 134 |
+
GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \
|
| 135 |
+
>> "$PATCH" 2>/dev/null || true
|
| 136 |
+
else
|
| 137 |
+
echo "[pre_artifacts] WARN could not stage a snapshot index for $root"
|
| 138 |
+
fi
|
| 139 |
+
rm -rf "$tmp" 2>/dev/null || true
|
| 140 |
+
all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \
|
| 141 |
+
-type f -print 2>/dev/null | sed 's|^\./||' )
|
| 142 |
+
printf '%s\n' "$all" | grep -v '^$' | list_add "$root"
|
| 143 |
+
big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \
|
| 144 |
+
-size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . )
|
| 145 |
+
echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)"
|
| 146 |
+
if [ "${big:-0}" != 0 ]; then
|
| 147 |
+
echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in"
|
| 148 |
+
echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch."
|
| 149 |
+
fi
|
| 150 |
+
return 0
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
capture_git "/app/repo"
|
| 154 |
+
bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0)
|
| 155 |
+
case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac
|
| 156 |
+
echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)"
|
| 157 |
+
if [ "$bytes" -gt 67108864 ]; then
|
| 158 |
+
echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build"
|
| 159 |
+
echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also"
|
| 160 |
+
echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish."
|
| 161 |
+
fi
|
| 162 |
+
exit 0
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# solution/ — reviewer-only 参考实现
|
| 2 |
+
|
| 3 |
+
本目录里的补丁**不进镜像**(已被上下文根的 `.dockerignore` 排除)、**判分不运行**,
|
| 4 |
+
只在两种场合用:
|
| 5 |
+
|
| 6 |
+
1. **重标定锚点**(换硬件后):见 `../tests/ref_speedup.caveat.md`
|
| 7 |
+
```
|
| 8 |
+
-e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch
|
| 9 |
+
```
|
| 10 |
+
2. **自证挖洞树的正确性**:`git apply --check -p1 oracle.patch` 必须能干净打在
|
| 11 |
+
`../environment/repo/` 上(正向可、反向不可),这证明该树就是被计分的起始点。
|
| 12 |
+
|
| 13 |
+
`negative.patch` 是已知坏例(必须得 0),`baseline2.patch` 是中间基线(若有)。
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/baseline2.patch
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/cross_entropy_grad.py b/cross_entropy_grad.py
|
| 2 |
+
index ff781cc..dd7f96a 100644
|
| 3 |
+
--- a/cross_entropy_grad.py
|
| 4 |
+
+++ b/cross_entropy_grad.py
|
| 5 |
+
@@ -1,57 +1,20 @@
|
| 6 |
+
-"""Cross-entropy loss and input-gradient over a batch of logit rows.
|
| 7 |
+
-
|
| 8 |
+
-Public entry point:
|
| 9 |
+
- ``cross_entropy_loss_grad(logits, labels, ignore_index=-100,
|
| 10 |
+
- label_smoothing=0.0) -> (loss, grad)``
|
| 11 |
+
-
|
| 12 |
+
-Given a batch of ``N`` rows of class scores (``logits``) and one integer target
|
| 13 |
+
-class per row (``labels``), compute the mean cross-entropy loss over the
|
| 14 |
+
-non-ignored rows and the gradient of that loss with respect to ``logits``.
|
| 15 |
+
-
|
| 16 |
+
-Contract
|
| 17 |
+
---------
|
| 18 |
+
-- ``logits``: shape ``(N, V)``, a floating-point CUDA tensor (``float32`` or
|
| 19 |
+
- ``bfloat16``). ``N`` is the number of rows (batch * sequence), ``V`` the
|
| 20 |
+
- number of classes (vocabulary size).
|
| 21 |
+
-- ``labels``: shape ``(N,)``, an integer CUDA tensor. Each entry is a class
|
| 22 |
+
- index in ``[0, V)``, or equals ``ignore_index`` to mark the row as ignored.
|
| 23 |
+
-- ``ignore_index``: int. Rows whose label equals this value contribute zero to
|
| 24 |
+
- the loss and zero to the gradient.
|
| 25 |
+
-- ``label_smoothing``: float ``>= 0``. ``0.0`` is ordinary cross entropy.
|
| 26 |
+
-
|
| 27 |
+
-Returns
|
| 28 |
+
--------
|
| 29 |
+
-- ``loss``: a scalar tensor — the mean cross-entropy (with optional label
|
| 30 |
+
- smoothing) over the non-ignored rows. If every row is ignored, the loss is
|
| 31 |
+
- ``0``.
|
| 32 |
+
-- ``grad``: shape ``(N, V)``, same dtype as ``logits`` — the gradient of
|
| 33 |
+
- ``loss`` w.r.t. ``logits``. Ignored rows are exactly zero.
|
| 34 |
+
-
|
| 35 |
+
-Definition (per non-ignored row with target ``y``, over ``n`` non-ignored rows):
|
| 36 |
+
- ``p = softmax(logits)``
|
| 37 |
+
- ``loss_row = -(1 - s) * log p[y] - (s / V) * sum_k log p[k]``
|
| 38 |
+
- ``grad_row[j] = ( p[j] - s / V - (1 - s) * [j == y] ) / n``
|
| 39 |
+
-where ``s = label_smoothing``. All reductions are computed in float32; the
|
| 40 |
+
-gradient is returned in the input dtype.
|
| 41 |
+
-
|
| 42 |
+
-Error contract
|
| 43 |
+
---------------
|
| 44 |
+
-- ``TypeError`` if ``logits`` is not a floating-point tensor, or ``labels`` is
|
| 45 |
+
- not an integer tensor.
|
| 46 |
+
-- ``ValueError`` if ``logits`` is not 2-D; if ``labels`` is not 1-D of length
|
| 47 |
+
- ``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies
|
| 48 |
+
- outside ``[0, V)``.
|
| 49 |
+
-
|
| 50 |
+
-Note on the current implementation
|
| 51 |
+
-----------------------------------
|
| 52 |
+
-This straightforward implementation forms the full log-probability tensor, the
|
| 53 |
+
-full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers
|
| 54 |
+
-in addition to the input. It is correct but holds several full-size copies of
|
| 55 |
+
-the logits at once, which is expensive at large ``V``.
|
| 56 |
+
+"""REVIEWER-ONLY baseline2 (Deriving-test-cases Step 6 soundness probe).
|
| 57 |
+
+
|
| 58 |
+
+A CORRECT implementation that is STRUCTURALLY DIFFERENT from the oracle: instead
|
| 59 |
+
+of the oracle's single-pass online-softmax recurrence, it does an explicit
|
| 60 |
+
+THREE-pass safe softmax over vocab chunks -- (1) global per-row max, (2) exp-sum
|
| 61 |
+
+given that max, (3) gradient written in place. Still memory-frugal (only
|
| 62 |
+
+(N, chunk) transients; no full (N, V) buffer), so it must earn a POSITIVE
|
| 63 |
+
+peak-memory reward on its own merit -- if the verifier can only reward the exact
|
| 64 |
+
+oracle code, it is oracle-overfit and must be fixed. This is also the
|
| 65 |
+
+loop-eligibility soundness check: a different-correct submission scores, so 16
|
| 66 |
+
+iterations have real signal.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
import torch
|
| 70 |
+
|
| 71 |
+
+CHUNK = 8192
|
| 72 |
+
+
|
| 73 |
+
|
| 74 |
+
def _validate(logits, labels, label_smoothing):
|
| 75 |
+
if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor):
|
| 76 |
+
@@ -71,36 +34,49 @@ def _validate(logits, labels, label_smoothing):
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0):
|
| 80 |
+
- """See module docstring for the full contract."""
|
| 81 |
+
N, V = _validate(logits, labels, label_smoothing)
|
| 82 |
+
s = float(label_smoothing)
|
| 83 |
+
-
|
| 84 |
+
+ device = logits.device
|
| 85 |
+
valid = labels != ignore_index
|
| 86 |
+
- # non-ignored labels must be inside [0, V)
|
| 87 |
+
if valid.any():
|
| 88 |
+
vlab = labels[valid]
|
| 89 |
+
if int(vlab.max()) >= V or int(vlab.min()) < 0:
|
| 90 |
+
raise ValueError(f"a non-ignored label is out of range [0, {V})")
|
| 91 |
+
- n_valid = int(valid.sum().item())
|
| 92 |
+
- denom = max(n_valid, 1)
|
| 93 |
+
-
|
| 94 |
+
- safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later)
|
| 95 |
+
- idx = torch.arange(N, device=logits.device)
|
| 96 |
+
-
|
| 97 |
+
- lf = logits.to(torch.float32)
|
| 98 |
+
- logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer
|
| 99 |
+
- logp_y = logp[idx, safe] # (N,)
|
| 100 |
+
- nll = -logp_y
|
| 101 |
+
- smooth = -logp.mean(dim=1) # -mean_k log p[k]
|
| 102 |
+
- row_loss = (1.0 - s) * nll + s * smooth
|
| 103 |
+
+ denom = max(int(valid.sum().item()), 1)
|
| 104 |
+
+ safe = labels.clamp(min=0).long()
|
| 105 |
+
+ idx = torch.arange(N, device=device)
|
| 106 |
+
+
|
| 107 |
+
+ # Pass 1: global per-row max
|
| 108 |
+
+ m = torch.full((N,), float("-inf"), device=device, dtype=torch.float32)
|
| 109 |
+
+ for c0 in range(0, V, CHUNK):
|
| 110 |
+
+ blk = logits[:, c0:c0 + CHUNK].to(torch.float32)
|
| 111 |
+
+ m = torch.maximum(m, blk.max(dim=1).values)
|
| 112 |
+
+ # Pass 2: exp-sum given the max (+ logit sum for smoothing)
|
| 113 |
+
+ d = torch.zeros(N, device=device, dtype=torch.float32)
|
| 114 |
+
+ x_sum = torch.zeros(N, device=device, dtype=torch.float32) if s != 0.0 else None
|
| 115 |
+
+ for c0 in range(0, V, CHUNK):
|
| 116 |
+
+ blk = logits[:, c0:c0 + CHUNK].to(torch.float32)
|
| 117 |
+
+ d += torch.exp(blk - m[:, None]).sum(dim=1)
|
| 118 |
+
+ if s != 0.0:
|
| 119 |
+
+ x_sum += blk.sum(dim=1)
|
| 120 |
+
+ lse = m + torch.log(d)
|
| 121 |
+
+ x_y = logits[idx, safe].to(torch.float32)
|
| 122 |
+
+ row_loss = lse - x_y if s == 0.0 else (1.0 - s) * (lse - x_y) + s * (lse - x_sum / V)
|
| 123 |
+
row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss))
|
| 124 |
+
- loss = row_loss.sum() / denom
|
| 125 |
+
-
|
| 126 |
+
- prob = logp.exp() # (N, V) softmax
|
| 127 |
+
- grad = prob.clone() # (N, V) gradient buffer
|
| 128 |
+
- if s != 0.0:
|
| 129 |
+
- grad = grad - (s / V)
|
| 130 |
+
- grad[idx, safe] = grad[idx, safe] - (1.0 - s)
|
| 131 |
+
- grad = grad / denom
|
| 132 |
+
- grad[~valid] = 0.0 # ignored rows -> exactly zero
|
| 133 |
+
- return loss, grad.to(logits.dtype)
|
| 134 |
+
+ loss = (row_loss.sum() / denom).to(logits.dtype)
|
| 135 |
+
+
|
| 136 |
+
+ # Pass 3: gradient in place
|
| 137 |
+
+ inv = 1.0 / denom
|
| 138 |
+
+ for c0 in range(0, V, CHUNK):
|
| 139 |
+
+ c1 = min(c0 + CHUNK, V)
|
| 140 |
+
+ blk = logits[:, c0:c1].to(torch.float32)
|
| 141 |
+
+ gblk = torch.exp(blk - m[:, None]) / d[:, None]
|
| 142 |
+
+ if s != 0.0:
|
| 143 |
+
+ gblk = gblk - (s / V)
|
| 144 |
+
+ in_chunk = valid & (safe >= c0) & (safe < c1)
|
| 145 |
+
+ if bool(in_chunk.any()):
|
| 146 |
+
+ gblk[idx[in_chunk], safe[in_chunk] - c0] -= (1.0 - s)
|
| 147 |
+
+ gblk = gblk * inv
|
| 148 |
+
+ gblk[~valid] = 0.0
|
| 149 |
+
+ logits[:, c0:c1] = gblk.to(logits.dtype)
|
| 150 |
+
+ return loss, logits
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/negative.patch
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/cross_entropy_grad.py b/cross_entropy_grad.py
|
| 2 |
+
index ff781cc..10dc004 100644
|
| 3 |
+
--- a/cross_entropy_grad.py
|
| 4 |
+
+++ b/cross_entropy_grad.py
|
| 5 |
+
@@ -1,57 +1,16 @@
|
| 6 |
+
-"""Cross-entropy loss and input-gradient over a batch of logit rows.
|
| 7 |
+
+"""REVIEWER-ONLY negative control (known-bad). MUST score reward 0.
|
| 8 |
+
|
| 9 |
+
-Public entry point:
|
| 10 |
+
- ``cross_entropy_loss_grad(logits, labels, ignore_index=-100,
|
| 11 |
+
- label_smoothing=0.0) -> (loss, grad)``
|
| 12 |
+
-
|
| 13 |
+
-Given a batch of ``N`` rows of class scores (``logits``) and one integer target
|
| 14 |
+
-class per row (``labels``), compute the mean cross-entropy loss over the
|
| 15 |
+
-non-ignored rows and the gradient of that loss with respect to ``logits``.
|
| 16 |
+
-
|
| 17 |
+
-Contract
|
| 18 |
+
---------
|
| 19 |
+
-- ``logits``: shape ``(N, V)``, a floating-point CUDA tensor (``float32`` or
|
| 20 |
+
- ``bfloat16``). ``N`` is the number of rows (batch * sequence), ``V`` the
|
| 21 |
+
- number of classes (vocabulary size).
|
| 22 |
+
-- ``labels``: shape ``(N,)``, an integer CUDA tensor. Each entry is a class
|
| 23 |
+
- index in ``[0, V)``, or equals ``ignore_index`` to mark the row as ignored.
|
| 24 |
+
-- ``ignore_index``: int. Rows whose label equals this value contribute zero to
|
| 25 |
+
- the loss and zero to the gradient.
|
| 26 |
+
-- ``label_smoothing``: float ``>= 0``. ``0.0`` is ordinary cross entropy.
|
| 27 |
+
-
|
| 28 |
+
-Returns
|
| 29 |
+
--------
|
| 30 |
+
-- ``loss``: a scalar tensor — the mean cross-entropy (with optional label
|
| 31 |
+
- smoothing) over the non-ignored rows. If every row is ignored, the loss is
|
| 32 |
+
- ``0``.
|
| 33 |
+
-- ``grad``: shape ``(N, V)``, same dtype as ``logits`` — the gradient of
|
| 34 |
+
- ``loss`` w.r.t. ``logits``. Ignored rows are exactly zero.
|
| 35 |
+
-
|
| 36 |
+
-Definition (per non-ignored row with target ``y``, over ``n`` non-ignored rows):
|
| 37 |
+
- ``p = softmax(logits)``
|
| 38 |
+
- ``loss_row = -(1 - s) * log p[y] - (s / V) * sum_k log p[k]``
|
| 39 |
+
- ``grad_row[j] = ( p[j] - s / V - (1 - s) * [j == y] ) / n``
|
| 40 |
+
-where ``s = label_smoothing``. All reductions are computed in float32; the
|
| 41 |
+
-gradient is returned in the input dtype.
|
| 42 |
+
-
|
| 43 |
+
-Error contract
|
| 44 |
+
---------------
|
| 45 |
+
-- ``TypeError`` if ``logits`` is not a floating-point tensor, or ``labels`` is
|
| 46 |
+
- not an integer tensor.
|
| 47 |
+
-- ``ValueError`` if ``logits`` is not 2-D; if ``labels`` is not 1-D of length
|
| 48 |
+
- ``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies
|
| 49 |
+
- outside ``[0, V)``.
|
| 50 |
+
-
|
| 51 |
+
-Note on the current implementation
|
| 52 |
+
-----------------------------------
|
| 53 |
+
-This straightforward implementation forms the full log-probability tensor, the
|
| 54 |
+
-full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers
|
| 55 |
+
-in addition to the input. It is correct but holds several full-size copies of
|
| 56 |
+
-the logits at once, which is expensive at large ``V``.
|
| 57 |
+
+Bug: the gradient omits the one-hot subtraction at the target class -- it returns
|
| 58 |
+
+softmax / n_nonignore only, never subtracting (1 - label_smoothing) at the label
|
| 59 |
+
+column. It is memory-frugal (would win the peak-memory metric) but WRONG, so it
|
| 60 |
+
+must fail the `normal`/`work-evidence` grad-parity gate and score 0. This is the
|
| 61 |
+
+SPEC known_bad (b): forgetting the target-class term of the gradient.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
import torch
|
| 65 |
+
|
| 66 |
+
+CHUNK = 8192
|
| 67 |
+
+
|
| 68 |
+
|
| 69 |
+
def _validate(logits, labels, label_smoothing):
|
| 70 |
+
if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor):
|
| 71 |
+
@@ -71,36 +30,33 @@ def _validate(logits, labels, label_smoothing):
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0):
|
| 75 |
+
- """See module docstring for the full contract."""
|
| 76 |
+
N, V = _validate(logits, labels, label_smoothing)
|
| 77 |
+
s = float(label_smoothing)
|
| 78 |
+
-
|
| 79 |
+
+ device = logits.device
|
| 80 |
+
valid = labels != ignore_index
|
| 81 |
+
- # non-ignored labels must be inside [0, V)
|
| 82 |
+
- if valid.any():
|
| 83 |
+
- vlab = labels[valid]
|
| 84 |
+
- if int(vlab.max()) >= V or int(vlab.min()) < 0:
|
| 85 |
+
- raise ValueError(f"a non-ignored label is out of range [0, {V})")
|
| 86 |
+
- n_valid = int(valid.sum().item())
|
| 87 |
+
- denom = max(n_valid, 1)
|
| 88 |
+
-
|
| 89 |
+
- safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later)
|
| 90 |
+
- idx = torch.arange(N, device=logits.device)
|
| 91 |
+
-
|
| 92 |
+
- lf = logits.to(torch.float32)
|
| 93 |
+
- logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer
|
| 94 |
+
- logp_y = logp[idx, safe] # (N,)
|
| 95 |
+
- nll = -logp_y
|
| 96 |
+
- smooth = -logp.mean(dim=1) # -mean_k log p[k]
|
| 97 |
+
- row_loss = (1.0 - s) * nll + s * smooth
|
| 98 |
+
- row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss))
|
| 99 |
+
- loss = row_loss.sum() / denom
|
| 100 |
+
-
|
| 101 |
+
- prob = logp.exp() # (N, V) softmax
|
| 102 |
+
- grad = prob.clone() # (N, V) gradient buffer
|
| 103 |
+
- if s != 0.0:
|
| 104 |
+
- grad = grad - (s / V)
|
| 105 |
+
- grad[idx, safe] = grad[idx, safe] - (1.0 - s)
|
| 106 |
+
- grad = grad / denom
|
| 107 |
+
- grad[~valid] = 0.0 # ignored rows -> exactly zero
|
| 108 |
+
- return loss, grad.to(logits.dtype)
|
| 109 |
+
+ denom = max(int(valid.sum().item()), 1)
|
| 110 |
+
+ safe = labels.clamp(min=0).long()
|
| 111 |
+
+ idx = torch.arange(N, device=device)
|
| 112 |
+
+
|
| 113 |
+
+ m = torch.full((N,), float("-inf"), device=device, dtype=torch.float32)
|
| 114 |
+
+ d = torch.zeros(N, device=device, dtype=torch.float32)
|
| 115 |
+
+ for c0 in range(0, V, CHUNK):
|
| 116 |
+
+ blk = logits[:, c0:c0 + CHUNK].to(torch.float32)
|
| 117 |
+
+ m_new = torch.maximum(m, blk.max(dim=1).values)
|
| 118 |
+
+ d = d * torch.exp(m - m_new) + torch.exp(blk - m_new[:, None]).sum(dim=1)
|
| 119 |
+
+ m = m_new
|
| 120 |
+
+ lse = m + torch.log(d)
|
| 121 |
+
+ x_y = logits[idx, safe].to(torch.float32)
|
| 122 |
+
+ row_loss = torch.where(valid, lse - x_y, torch.zeros_like(lse))
|
| 123 |
+
+ loss = (row_loss.sum() / denom).to(logits.dtype)
|
| 124 |
+
+
|
| 125 |
+
+ inv = 1.0 / denom
|
| 126 |
+
+ for c0 in range(0, V, CHUNK):
|
| 127 |
+
+ c1 = min(c0 + CHUNK, V)
|
| 128 |
+
+ blk = logits[:, c0:c1].to(torch.float32)
|
| 129 |
+
+ gblk = torch.exp(blk - m[:, None]) / d[:, None]
|
| 130 |
+
+ # BUG: no `- (1 - s)` at the label column -> wrong gradient.
|
| 131 |
+
+ gblk = gblk * inv
|
| 132 |
+
+ gblk[~valid] = 0.0
|
| 133 |
+
+ logits[:, c0:c1] = gblk.to(logits.dtype)
|
| 134 |
+
+ return loss, logits
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/oracle.patch
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/cross_entropy_grad.py b/cross_entropy_grad.py
|
| 2 |
+
index ff781cc..429b935 100644
|
| 3 |
+
--- a/cross_entropy_grad.py
|
| 4 |
+
+++ b/cross_entropy_grad.py
|
| 5 |
+
@@ -42,16 +42,27 @@ Error contract
|
| 6 |
+
``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies
|
| 7 |
+
outside ``[0, V)``.
|
| 8 |
+
|
| 9 |
+
-Note on the current implementation
|
| 10 |
+
-----------------------------------
|
| 11 |
+
-This straightforward implementation forms the full log-probability tensor, the
|
| 12 |
+
-full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers
|
| 13 |
+
-in addition to the input. It is correct but holds several full-size copies of
|
| 14 |
+
-the logits at once, which is expensive at large ``V``.
|
| 15 |
+
+Implementation note
|
| 16 |
+
+-------------------
|
| 17 |
+
+A single fused kernel computes both the loss and the gradient. Each program
|
| 18 |
+
+handles one row: a first streaming pass performs an online softmax (running
|
| 19 |
+
+max, running sum of exponentials, sum of logits, target logit — O(1) state per
|
| 20 |
+
+row), and a second pass recomputes the probabilities block-by-block and writes
|
| 21 |
+
+the gradient in place into the ``logits`` buffer. The only extra device memory
|
| 22 |
+
+is an ``(N,)`` float32 buffer of per-row losses; no full-size ``(N, V)``
|
| 23 |
+
+intermediate is ever materialized.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
+try:
|
| 29 |
+
+ import triton
|
| 30 |
+
+ import triton.language as tl
|
| 31 |
+
+
|
| 32 |
+
+ _HAS_TRITON = True
|
| 33 |
+
+except Exception: # pragma: no cover - triton is expected to be available
|
| 34 |
+
+ _HAS_TRITON = False
|
| 35 |
+
+
|
| 36 |
+
|
| 37 |
+
def _validate(logits, labels, label_smoothing):
|
| 38 |
+
if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor):
|
| 39 |
+
@@ -70,37 +81,211 @@ def _validate(logits, labels, label_smoothing):
|
| 40 |
+
return N, V
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
+if _HAS_TRITON:
|
| 44 |
+
+
|
| 45 |
+
+ @triton.jit
|
| 46 |
+
+ def _count_valid_bad_kernel(
|
| 47 |
+
+ lab_ptr, # (N,) int32/int64
|
| 48 |
+
+ stats_ptr, # (2,) int64: [n_valid, n_bad] accumulated with exact integer atomics
|
| 49 |
+
+ N,
|
| 50 |
+
+ V,
|
| 51 |
+
+ ignore_index,
|
| 52 |
+
+ BLOCK: tl.constexpr,
|
| 53 |
+
+ ):
|
| 54 |
+
+ pid = tl.program_id(0)
|
| 55 |
+
+ offs = pid * BLOCK + tl.arange(0, BLOCK)
|
| 56 |
+
+ mask = offs < N
|
| 57 |
+
+ lab = tl.load(lab_ptr + offs, mask=mask, other=ignore_index)
|
| 58 |
+
+ is_valid = (lab != ignore_index) & mask
|
| 59 |
+
+ is_bad = is_valid & ((lab < 0) | (lab >= V))
|
| 60 |
+
+ tl.atomic_add(stats_ptr, tl.sum(is_valid.to(tl.int64), axis=0))
|
| 61 |
+
+ tl.atomic_add(stats_ptr + 1, tl.sum(is_bad.to(tl.int64), axis=0))
|
| 62 |
+
+
|
| 63 |
+
+ @triton.jit
|
| 64 |
+
+ def _ce_loss_grad_reg_kernel(
|
| 65 |
+
+ x_ptr, # (N, V) in: logits, out: gradient (overwritten in place)
|
| 66 |
+
+ lab_ptr, # (N,) int32/int64
|
| 67 |
+
+ loss_ptr, # (N,) float32 per-row loss, 0 for ignored rows
|
| 68 |
+
+ V,
|
| 69 |
+
+ ignore_index,
|
| 70 |
+
+ s,
|
| 71 |
+
+ inv_denom,
|
| 72 |
+
+ BLOCK_V: tl.constexpr, # >= V: the whole row stays resident in registers
|
| 73 |
+
+ ):
|
| 74 |
+
+ row = tl.program_id(0)
|
| 75 |
+
+ base = x_ptr + row.to(tl.int64) * V
|
| 76 |
+
+ cols = tl.arange(0, BLOCK_V)
|
| 77 |
+
+ mask = cols < V
|
| 78 |
+
+ lab = tl.load(lab_ptr + row)
|
| 79 |
+
+
|
| 80 |
+
+ if lab == ignore_index:
|
| 81 |
+
+ tl.store(loss_ptr + row, 0.0)
|
| 82 |
+
+ z = tl.zeros([BLOCK_V], dtype=tl.float32)
|
| 83 |
+
+ tl.store(base + cols, z.to(x_ptr.dtype.element_ty), mask=mask)
|
| 84 |
+
+ else:
|
| 85 |
+
+ x = tl.load(base + cols, mask=mask, other=-float("inf")).to(tl.float32)
|
| 86 |
+
+ m = tl.max(x, axis=0)
|
| 87 |
+
+ e = tl.exp(x - m)
|
| 88 |
+
+ l = tl.sum(e, axis=0)
|
| 89 |
+
+ sum_x = tl.sum(tl.where(mask, x, 0.0), axis=0)
|
| 90 |
+
+ x_y = tl.sum(tl.where(cols == lab, x, 0.0), axis=0)
|
| 91 |
+
+ log_z = m + tl.log(l)
|
| 92 |
+
+ row_loss = (1.0 - s) * (log_z - x_y) + s * (log_z - sum_x / V)
|
| 93 |
+
+ tl.store(loss_ptr + row, row_loss * inv_denom)
|
| 94 |
+
+ g = e * (1.0 / l) - s / V
|
| 95 |
+
+ g = tl.where(cols == lab, g - (1.0 - s), g)
|
| 96 |
+
+ g = g * inv_denom
|
| 97 |
+
+ tl.store(base + cols, g.to(x_ptr.dtype.element_ty), mask=mask)
|
| 98 |
+
+
|
| 99 |
+
+ @triton.jit
|
| 100 |
+
+ def _ce_loss_grad_kernel(
|
| 101 |
+
+ x_ptr, # (N, V) in: logits, out: gradient (overwritten in place)
|
| 102 |
+
+ lab_ptr, # (N,) int32/int64
|
| 103 |
+
+ loss_ptr, # (N,) float32 per-row loss, 0 for ignored rows
|
| 104 |
+
+ V,
|
| 105 |
+
+ ignore_index,
|
| 106 |
+
+ s,
|
| 107 |
+
+ inv_denom,
|
| 108 |
+
+ BLOCK_V: tl.constexpr,
|
| 109 |
+
+ ):
|
| 110 |
+
+ row = tl.program_id(0)
|
| 111 |
+
+ base = x_ptr + row.to(tl.int64) * V
|
| 112 |
+
+ cols0 = tl.arange(0, BLOCK_V)
|
| 113 |
+
+ lab = tl.load(lab_ptr + row)
|
| 114 |
+
+
|
| 115 |
+
+ if lab == ignore_index:
|
| 116 |
+
+ tl.store(loss_ptr + row, 0.0)
|
| 117 |
+
+ z = tl.zeros([BLOCK_V], dtype=tl.float32)
|
| 118 |
+
+ for off in range(0, V, BLOCK_V):
|
| 119 |
+
+ cols = off + cols0
|
| 120 |
+
+ mask = cols < V
|
| 121 |
+
+ tl.store(base + cols, z.to(x_ptr.dtype.element_ty), mask=mask)
|
| 122 |
+
+ else:
|
| 123 |
+
+ m = -float("inf")
|
| 124 |
+
+ l = 0.0
|
| 125 |
+
+ sum_x = 0.0
|
| 126 |
+
+ x_y = 0.0
|
| 127 |
+
+ for off in range(0, V, BLOCK_V):
|
| 128 |
+
+ cols = off + cols0
|
| 129 |
+
+ mask = cols < V
|
| 130 |
+
+ x = tl.load(base + cols, mask=mask, other=-float("inf")).to(tl.float32)
|
| 131 |
+
+ bmax = tl.max(x, axis=0)
|
| 132 |
+
+ new_m = tl.maximum(m, bmax)
|
| 133 |
+
+ l = l * tl.exp(m - new_m) + tl.sum(tl.exp(x - new_m), axis=0)
|
| 134 |
+
+ m = new_m
|
| 135 |
+
+ sum_x += tl.sum(tl.where(mask, x, 0.0), axis=0)
|
| 136 |
+
+ x_y += tl.sum(tl.where(cols == lab, x, 0.0), axis=0)
|
| 137 |
+
+
|
| 138 |
+
+ log_z = m + tl.log(l)
|
| 139 |
+
+ row_loss = (1.0 - s) * (log_z - x_y) + s * (log_z - sum_x / V)
|
| 140 |
+
+ tl.store(loss_ptr + row, row_loss * inv_denom)
|
| 141 |
+
+
|
| 142 |
+
+ inv_l = 1.0 / l
|
| 143 |
+
+ s_over_v = s / V
|
| 144 |
+
+ om_s = 1.0 - s
|
| 145 |
+
+ for off in range(0, V, BLOCK_V):
|
| 146 |
+
+ cols = off + cols0
|
| 147 |
+
+ mask = cols < V
|
| 148 |
+
+ x = tl.load(base + cols, mask=mask, other=0.0).to(tl.float32)
|
| 149 |
+
+ g = tl.exp(x - m) * inv_l - s_over_v
|
| 150 |
+
+ g = tl.where(cols == lab, g - om_s, g)
|
| 151 |
+
+ g = g * inv_denom
|
| 152 |
+
+ tl.store(base + cols, g.to(x_ptr.dtype.element_ty), mask=mask)
|
| 153 |
+
+
|
| 154 |
+
+
|
| 155 |
+
+def _chunked_fallback(logits, labels, valid, s, inv_denom, loss_buf):
|
| 156 |
+
+ """Memory-bounded pure-torch path (non-CUDA tensors or missing triton)."""
|
| 157 |
+
+ N, V = logits.shape
|
| 158 |
+
+ chunk = max(1, min(N, (1 << 22) // max(V, 1)))
|
| 159 |
+
+ for c0 in range(0, N, chunk):
|
| 160 |
+
+ c1 = min(N, c0 + chunk)
|
| 161 |
+
+ x = logits[c0:c1]
|
| 162 |
+
+ xf = x.to(torch.float32)
|
| 163 |
+
+ m = xf.max(dim=1, keepdim=True).values
|
| 164 |
+
+ e = torch.exp(xf - m)
|
| 165 |
+
+ l = e.sum(dim=1, keepdim=True)
|
| 166 |
+
+ log_z = m + torch.log(l)
|
| 167 |
+
+ lab = labels[c0:c1].clamp(min=0).long()
|
| 168 |
+
+ idx = torch.arange(c1 - c0, device=logits.device)
|
| 169 |
+
+ x_y = xf[idx, lab].unsqueeze(1)
|
| 170 |
+
+ sum_x = xf.sum(dim=1, keepdim=True)
|
| 171 |
+
+ row_loss = ((1.0 - s) * (log_z - x_y) + s * (log_z - sum_x / V)).squeeze(1)
|
| 172 |
+
+ v = valid[c0:c1]
|
| 173 |
+
+ loss_buf[c0:c1] = torch.where(v, row_loss * inv_denom, torch.zeros_like(row_loss))
|
| 174 |
+
+ g = e / l - (s / V)
|
| 175 |
+
+ g[idx, lab] = g[idx, lab] - (1.0 - s)
|
| 176 |
+
+ g = g * inv_denom
|
| 177 |
+
+ g = torch.where(v.unsqueeze(1), g, torch.zeros_like(g))
|
| 178 |
+
+ x.copy_(g.to(logits.dtype))
|
| 179 |
+
+ return logits
|
| 180 |
+
+
|
| 181 |
+
+
|
| 182 |
+
def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0):
|
| 183 |
+
"""See module docstring for the full contract."""
|
| 184 |
+
N, V = _validate(logits, labels, label_smoothing)
|
| 185 |
+
s = float(label_smoothing)
|
| 186 |
+
|
| 187 |
+
- valid = labels != ignore_index
|
| 188 |
+
- # non-ignored labels must be inside [0, V)
|
| 189 |
+
- if valid.any():
|
| 190 |
+
- vlab = labels[valid]
|
| 191 |
+
- if int(vlab.max()) >= V or int(vlab.min()) < 0:
|
| 192 |
+
- raise ValueError(f"a non-ignored label is out of range [0, {V})")
|
| 193 |
+
- n_valid = int(valid.sum().item())
|
| 194 |
+
- denom = max(n_valid, 1)
|
| 195 |
+
-
|
| 196 |
+
- safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later)
|
| 197 |
+
- idx = torch.arange(N, device=logits.device)
|
| 198 |
+
-
|
| 199 |
+
- lf = logits.to(torch.float32)
|
| 200 |
+
- logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer
|
| 201 |
+
- logp_y = logp[idx, safe] # (N,)
|
| 202 |
+
- nll = -logp_y
|
| 203 |
+
- smooth = -logp.mean(dim=1) # -mean_k log p[k]
|
| 204 |
+
- row_loss = (1.0 - s) * nll + s * smooth
|
| 205 |
+
- row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss))
|
| 206 |
+
- loss = row_loss.sum() / denom
|
| 207 |
+
-
|
| 208 |
+
- prob = logp.exp() # (N, V) softmax
|
| 209 |
+
- grad = prob.clone() # (N, V) gradient buffer
|
| 210 |
+
- if s != 0.0:
|
| 211 |
+
- grad = grad - (s / V)
|
| 212 |
+
- grad[idx, safe] = grad[idx, safe] - (1.0 - s)
|
| 213 |
+
- grad = grad / denom
|
| 214 |
+
- grad[~valid] = 0.0 # ignored rows -> exactly zero
|
| 215 |
+
- return loss, grad.to(logits.dtype)
|
| 216 |
+
+ if not labels.is_contiguous():
|
| 217 |
+
+ labels = labels.contiguous()
|
| 218 |
+
+
|
| 219 |
+
+ use_triton = _HAS_TRITON and logits.is_cuda
|
| 220 |
+
+ if use_triton:
|
| 221 |
+
+ stats = torch.zeros(2, device=logits.device, dtype=torch.int64)
|
| 222 |
+
+ if N > 0:
|
| 223 |
+
+ _count_valid_bad_kernel[(triton.cdiv(N, 4096),)](
|
| 224 |
+
+ labels, stats, N, V, int(ignore_index), BLOCK=4096, num_warps=4
|
| 225 |
+
+ )
|
| 226 |
+
+ n_valid, n_bad = (int(v) for v in stats.tolist())
|
| 227 |
+
+ else:
|
| 228 |
+
+ valid = labels != ignore_index
|
| 229 |
+
+ bad = ((labels < 0) | (labels >= V)) & valid
|
| 230 |
+
+ n_valid, n_bad = (int(v) for v in torch.stack([valid.sum(), bad.sum()]).tolist())
|
| 231 |
+
+ if n_bad:
|
| 232 |
+
+ raise ValueError(f"a non-ignored label is out of range [0, {V})")
|
| 233 |
+
+ denom = n_valid if n_valid > 0 else 1
|
| 234 |
+
+ inv_denom = 1.0 / denom
|
| 235 |
+
+
|
| 236 |
+
+ if not logits.is_contiguous():
|
| 237 |
+
+ logits = logits.contiguous()
|
| 238 |
+
+
|
| 239 |
+
+ loss_buf = torch.empty(N, device=logits.device, dtype=torch.float32)
|
| 240 |
+
+
|
| 241 |
+
+ if use_triton and N > 0:
|
| 242 |
+
+ if V <= 8192:
|
| 243 |
+
+ block_v = triton.next_power_of_2(V)
|
| 244 |
+
+ if block_v <= 512:
|
| 245 |
+
+ num_warps = 1
|
| 246 |
+
+ elif block_v <= 4096:
|
| 247 |
+
+ num_warps = 2
|
| 248 |
+
+ else:
|
| 249 |
+
+ num_warps = 4
|
| 250 |
+
+ _ce_loss_grad_reg_kernel[(N,)](
|
| 251 |
+
+ logits,
|
| 252 |
+
+ labels,
|
| 253 |
+
+ loss_buf,
|
| 254 |
+
+ V,
|
| 255 |
+
+ int(ignore_index),
|
| 256 |
+
+ s,
|
| 257 |
+
+ inv_denom,
|
| 258 |
+
+ BLOCK_V=block_v,
|
| 259 |
+
+ num_warps=num_warps,
|
| 260 |
+
+ )
|
| 261 |
+
+ else:
|
| 262 |
+
+ _ce_loss_grad_kernel[(N,)](
|
| 263 |
+
+ logits,
|
| 264 |
+
+ labels,
|
| 265 |
+
+ loss_buf,
|
| 266 |
+
+ V,
|
| 267 |
+
+ int(ignore_index),
|
| 268 |
+
+ s,
|
| 269 |
+
+ inv_denom,
|
| 270 |
+
+ BLOCK_V=2048,
|
| 271 |
+
+ num_warps=4,
|
| 272 |
+
+ )
|
| 273 |
+
+ grad = logits
|
| 274 |
+
+ else:
|
| 275 |
+
+ valid = labels != ignore_index
|
| 276 |
+
+ grad = _chunked_fallback(logits, labels, valid, s, inv_denom, loss_buf)
|
| 277 |
+
+
|
| 278 |
+
+ loss = loss_buf.sum(dtype=torch.float64).to(torch.float32)
|
| 279 |
+
+ return loss, grad
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/solve.sh
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# solution/solve.sh — kfc/insea-fused-softmax-cross-entropy-grad-loop16
|
| 3 |
+
# 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量
|
| 4 |
+
# 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。
|
| 5 |
+
#
|
| 6 |
+
# oracle 形态 : 补丁式(patch)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_PATCH 槽位:
|
| 7 |
+
# git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH"
|
| 8 |
+
# 产物(reviewer-only;本脚本只读,一个字节都不改):
|
| 9 |
+
# solution/baseline2.patch, solution/negative.patch, solution/oracle.patch
|
| 10 |
+
# $REPO : /app/repo (tests/test.sh: REPO=/app/repo)
|
| 11 |
+
# 被计分单元 : /app/repo/cross_entropy_grad.py
|
| 12 |
+
# 来源:tests/test.sh 的 CAND_FILE="$REPO/cross_entropy_grad.py"
|
| 13 |
+
# 落地方式 : git -C $REPO apply -p1 <patch> —— 只改工作树,不 commit
|
| 14 |
+
#
|
| 15 |
+
# 🔴 为什么绝不 commit(规范 H3):判分读**工作树** —— `git status --porcelain` 是 scope
|
| 16 |
+
# 硬闸门,`git checkout -q HEAD -- <scope>` 取基线,且镜像自证 /app/repo 的 HEAD 恰好
|
| 17 |
+
# 只有 1 个 commit(那就是挖洞基线)。一旦 commit,HEAD 前移 → 闸门看不到改动、
|
| 18 |
+
# `checkout HEAD -- scope` 把 candidate 当成基线 → 正确解被判 0。
|
| 19 |
+
# 本脚本落地后会自己断言 HEAD 与 commit 数没变。
|
| 20 |
+
#
|
| 21 |
+
# ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)────────────────────────
|
| 22 |
+
# PKG=<fai_bench>/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task
|
| 23 |
+
# IMG=fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss
|
| 24 |
+
# # 1) 起容器。判分容器始终 --network=none;tests/ 和 solution/ 都**没有**烤进镜像
|
| 25 |
+
# # (Dockerfile 里没有一条 COPY 取它们),所以这两个目录必须挂进来。
|
| 26 |
+
# # 该题 task.toml 声明 gpus=1;锚点的标定硬件/运行栈见 tests/ref_speedup.caveat.md
|
| 27 |
+
# docker run -d --name kfc-solve --network=none --gpus all \
|
| 28 |
+
# -v "$PKG/tests":/tests -v "$PKG/solution":/solution "$IMG"
|
| 29 |
+
# # 2) 落地参考实现到工作树(本脚本;不 commit)
|
| 30 |
+
# docker exec kfc-solve bash /solution/solve.sh
|
| 31 |
+
# # 3) 判分。KERNELBENCH_VERIFY_MODE 必须留在默认的 candidate —— 这就是 agent 的
|
| 32 |
+
# # 真实评分路径;设成 oracle/negative 会让 test.sh 自己再落地一遍,绕过本脚本。
|
| 33 |
+
# docker exec -e KERNELBENCH_VERIFY_MODE=candidate kfc-solve bash /tests/test.sh
|
| 34 |
+
# docker exec kfc-solve cat /logs/verifier/reward.json # 判分结果
|
| 35 |
+
# docker rm -f kfc-solve
|
| 36 |
+
#
|
| 37 |
+
# 期望:oracle → 性能题得 0(它就是锚点本身; min(1, ln(speedup/ref_speedup)/ln(ref_speedup))(speedup ≤ ref_speedup 时为 0)
|
| 38 |
+
# 在 speedup≈ref_speedup 处 = 0 —— 打平 oracle 不得分,必须超过。
|
| 39 |
+
# 所以"oracle 跑对了"的判据不是 reward>0,而是 speedup≈ref_speedup 且
|
| 40 |
+
# hard_fail_reasons 为空;实现类二值题 = 1.0 —— 权威公式是
|
| 41 |
+
# tests/test.sh 写出的 reward_formula 字段);--negative → 0;
|
| 42 |
+
# --noop(在纯净容器里)→ 0(挖洞基线过不了正确性门)。
|
| 43 |
+
# 本题带 loop16 harness:`bash /opt/loop/submit.sh` 判的也是同一棵工作树、
|
| 44 |
+
# 同样走 candidate 模式(口径一致),所以落地后直接自评也成立。
|
| 45 |
+
# ──────────────────────────────────────────────────────────────────────────
|
| 46 |
+
#
|
| 47 |
+
# 用法(规范 2 的统一 CLI):
|
| 48 |
+
# bash solution/solve.sh # 落地 oracle(参考实现)
|
| 49 |
+
# bash solution/solve.sh --negative # 落地 negative(已知坏例,必须得 0)
|
| 50 |
+
# bash solution/solve.sh --baseline2 # 落地 baseline2(中间基线)
|
| 51 |
+
# bash solution/solve.sh --noop # 把可编辑面复位到烤入基线(对照组)
|
| 52 |
+
#
|
| 53 |
+
# --noop 语义:把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 ——
|
| 54 |
+
# `git checkout HEAD -- <scope>`,HEAD 不动),使对照组能量到真正的 no-op 值。
|
| 55 |
+
# runner 在同一个容器里连着跑 oracle → noop 做对照时,靠它把上一轮落地归零。
|
| 56 |
+
#
|
| 57 |
+
# 幂等:每次落地前先把被计分单元 `git checkout HEAD --` 复位,重复执行结果一致。
|
| 58 |
+
# 失败一律非 0 退出并打印原因(补丁打不上 / 变体文件缺失 / scope 路径不存在 / HEAD 被移动)。
|
| 59 |
+
set -uo pipefail
|
| 60 |
+
|
| 61 |
+
TASK_ID="insea-fused-softmax-cross-entropy-grad-loop16"
|
| 62 |
+
REPO="${KFC_REPO_DIR:-/app/repo}"
|
| 63 |
+
SCOPE=("cross_entropy_grad.py")
|
| 64 |
+
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 65 |
+
|
| 66 |
+
say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; }
|
| 67 |
+
die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; }
|
| 68 |
+
# 每次调用单独带 safe.directory,不去改容器里的全局 gitconfig
|
| 69 |
+
GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; }
|
| 70 |
+
|
| 71 |
+
usage(){ cat <<'USAGE'
|
| 72 |
+
usage: bash solve.sh [--oracle | --negative | --baseline2 | --noop]
|
| 73 |
+
(无参数) 落地 oracle 参考实现(oracle.patch)
|
| 74 |
+
--negative 落地 negative 已知坏例(negative.patch)
|
| 75 |
+
--baseline2 落地 baseline2 中间基线(baseline2.patch)
|
| 76 |
+
--noop 把可编辑面复位到烤入基线(与 verifier 取基线一致,HEAD 不动)
|
| 77 |
+
USAGE
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
WHICH=oracle
|
| 81 |
+
case "${1:-}" in
|
| 82 |
+
""|--oracle) WHICH=oracle ;;
|
| 83 |
+
--negative) WHICH=negative ;;
|
| 84 |
+
--baseline2) WHICH=baseline2 ;;
|
| 85 |
+
--noop) WHICH=noop ;;
|
| 86 |
+
-h|--help) usage; exit 0 ;;
|
| 87 |
+
*) usage >&2; die "未知参数 '$1'" ;;
|
| 88 |
+
esac
|
| 89 |
+
|
| 90 |
+
# ---- 产物定位:脚本同目录优先,其次容器里的常见挂载点 ----
|
| 91 |
+
artifact(){
|
| 92 |
+
local n="$1" c
|
| 93 |
+
for c in "$HERE/$n" "/solution/$n" "${KFC_SOLUTION_DIR:-/nonexistent}/$n"; do
|
| 94 |
+
[ -f "$c" ] && { printf '%s\n' "$c"; return 0; }
|
| 95 |
+
done
|
| 96 |
+
return 1
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
case "$WHICH" in
|
| 100 |
+
noop) ART="" ;;
|
| 101 |
+
oracle) ART="oracle.patch" ;;
|
| 102 |
+
negative) ART="negative.patch" ;;
|
| 103 |
+
baseline2) ART="baseline2.patch" ;;
|
| 104 |
+
*) die "本题没有 $WHICH 变体(solution/ 里只有:oracle.patch, negative.patch, baseline2.patch)" ;;
|
| 105 |
+
esac
|
| 106 |
+
|
| 107 |
+
# ---- 环境前置检查 ----
|
| 108 |
+
GIT rev-parse --git-dir >/dev/null 2>&1 \
|
| 109 |
+
|| die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)"
|
| 110 |
+
for s in "${SCOPE[@]}"; do
|
| 111 |
+
[ -e "$REPO/$s" ] || die "被计分单元不存在:$REPO/$s(REPO 不对?可用 KFC_REPO_DIR 覆盖)"
|
| 112 |
+
done
|
| 113 |
+
HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD"
|
| 114 |
+
N_BEFORE="$(GIT rev-list --count HEAD)"
|
| 115 |
+
|
| 116 |
+
if [ "$WHICH" = noop ]; then
|
| 117 |
+
# --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— `git checkout HEAD -- <scope>`,
|
| 118 |
+
# HEAD 不动),使对照组能量到真正的 no-op 值。runner 在同一个容器里连着跑 oracle → noop 时靠它归零。
|
| 119 |
+
DIRTY_BEFORE="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')"
|
| 120 |
+
GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})"
|
| 121 |
+
DIRTY_AFTER="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')"
|
| 122 |
+
if [ -n "$DIRTY_AFTER" ]; then
|
| 123 |
+
printf '%s\n' "$DIRTY_AFTER" | sed "s|^|[solve.sh $TASK_ID] |" >&2
|
| 124 |
+
die "复位后被计分单元仍不干净(见上)—— 量不到真正的 no-op 值"
|
| 125 |
+
fi
|
| 126 |
+
[ "$HEAD_BEFORE" = "$(GIT rev-parse HEAD)" ] || die "HEAD 被移动了,判分会把 candidate 当基线"
|
| 127 |
+
[ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线"
|
| 128 |
+
if [ -n "$DIRTY_BEFORE" ]; then
|
| 129 |
+
say "--noop:已把可编辑面复位到烤入基线;原先这些是脏的:"
|
| 130 |
+
printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |"
|
| 131 |
+
else
|
| 132 |
+
say "--noop:可编辑面本来就是干净的烤入基线,无需复位"
|
| 133 |
+
fi
|
| 134 |
+
say "--noop 完成:${SCOPE[*]} = 烤入基线(HEAD 未动 @ ${HEAD_BEFORE:0:12})"
|
| 135 |
+
exit 0
|
| 136 |
+
fi
|
| 137 |
+
|
| 138 |
+
PATCH="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)"
|
| 139 |
+
|
| 140 |
+
# ---- 幂等:先把被计分单元退回挖洞基线,再打补丁(否则二次 apply 必然失败) ----
|
| 141 |
+
GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})"
|
| 142 |
+
GIT apply -p1 --check "$PATCH" \
|
| 143 |
+
|| die "补丁打不上:$PATCH —— 挖洞树与该补丁不匹配,或工作树被别的改动污染了"
|
| 144 |
+
GIT apply -p1 "$PATCH" || die "git apply 失败:$PATCH"
|
| 145 |
+
|
| 146 |
+
# ---- 硬要求:HEAD 一步都不能动(规范 H3) ----
|
| 147 |
+
HEAD_AFTER="$(GIT rev-parse HEAD)"
|
| 148 |
+
[ "$HEAD_BEFORE" = "$HEAD_AFTER" ] || die "HEAD 被移动了($HEAD_BEFORE -> $HEAD_AFTER),判分会把 candidate 当基线"
|
| 149 |
+
[ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线"
|
| 150 |
+
|
| 151 |
+
say "已落地 $WHICH:$(basename "$PATCH") -> ${SCOPE[*]}(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})"
|
| 152 |
+
GIT status --porcelain -- "${SCOPE[@]}" | sed "s|^|[solve.sh $TASK_ID] |"
|
| 153 |
+
|
| 154 |
+
# ---- 顺手体检 scope 闸门:工作树里除了被计分单元不该有别的改动 ----
|
| 155 |
+
STRAY="$(GIT status --porcelain | awk '{print $NF}' \
|
| 156 |
+
| grep -v -e '__pycache__' -e '\.pyc$' -e '^cross_entropy_grad\.py$' || true)"
|
| 157 |
+
[ -z "$STRAY" ] || { say "⚠ 工作树里还有 scope 外的改动,判分会 out_of_scope_edit 直接归 0:"; \
|
| 158 |
+
printf '%s\n' "$STRAY" | sed "s|^|[solve.sh $TASK_ID] |"; }
|
| 159 |
+
exit 0
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/task.toml
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "2.0"
|
| 2 |
+
|
| 3 |
+
# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1)
|
| 4 |
+
artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"]
|
| 5 |
+
|
| 6 |
+
[task]
|
| 7 |
+
id = "insea-fused-softmax-cross-entropy-grad-loop16"
|
| 8 |
+
bench = "kfc"
|
| 9 |
+
kind = "performance"
|
| 10 |
+
language = "python"
|
| 11 |
+
title = "You are working on the loss stage of a large language model's training step."
|
| 12 |
+
instruction = "instruction.md"
|
| 13 |
+
|
| 14 |
+
[agent]
|
| 15 |
+
timeout_sec = 21600
|
| 16 |
+
|
| 17 |
+
# carved-tree provenance (environment/repo/ recovered from): <internal registry>/kernelbench/insea-fused-softmax-cross-entropy-grad-loop16:loop-20260720T021136Z@sha256:dbd2b4dbf93aa3621d94de371a783ff2d77d7978cc4b93a6c19819d36a68a7f9
|
| 18 |
+
# Open-source build: `cd <this dir> && docker build -f environment/Dockerfile -t fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss .`
|
| 19 |
+
[environment]
|
| 20 |
+
docker_image = "fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss"
|
| 21 |
+
dockerfile = "environment/Dockerfile"
|
| 22 |
+
build_timeout_sec = 3600
|
| 23 |
+
cpus = 8
|
| 24 |
+
memory_mb = 32000
|
| 25 |
+
gpus = 1
|
| 26 |
+
# H20 只是**锚点标定用卡**,不是硬性限制。换卡时:①按 tests/ref_speedup.caveat.md 重标锚点;
|
| 27 |
+
# ②用 --build-arg TORCH_CUDA_ARCH_LIST=<你的算力> 构建镜像。
|
| 28 |
+
gpu_types = ["H20"]
|
| 29 |
+
gpu_memory_gb = 96
|
| 30 |
+
allow_internet = false
|
| 31 |
+
|
| 32 |
+
[verifier]
|
| 33 |
+
entrypoint = "tests/test.sh"
|
| 34 |
+
mode = "shared"
|
| 35 |
+
timeout_sec = 3600
|
| 36 |
+
task_kind = "acceleration"
|
| 37 |
+
contract_pattern = "A"
|
| 38 |
+
timing_metric = "peak_memory_bytes"
|
| 39 |
+
candidate_source_root = "/app/repo"
|
| 40 |
+
primary_edit_paths = ["/app/repo/cross_entropy_grad.py"]
|
| 41 |
+
forbidden_edit_paths = ["/app/repo/tests/**", "/opt/verifier-*", "/tests/**", "/opt/loop/**"]
|
| 42 |
+
result_paths = [
|
| 43 |
+
"/logs/verifier/verifier_state.json",
|
| 44 |
+
"/logs/verifier/correctness_results.json",
|
| 45 |
+
"/logs/verifier/benchmark_results.json",
|
| 46 |
+
"/logs/verifier/reward.json",
|
| 47 |
+
"/logs/verifier/reward.txt",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
[primary_metric]
|
| 51 |
+
name = "cross_entropy_grad_peak_memory_ratio"
|
| 52 |
+
goal = "maximize"
|
| 53 |
+
metric_kind = "peak_memory"
|
| 54 |
+
reward_formula = "reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 per the reward specification (speedup == ref_speedup -> 0.0 (must EXCEED it to score); speedup>=ref_speedup^2 -> 1.0 cap; range [0,1]); reward = 0 on any hard gate, on speedup<=1, or on ref_speedup<=1. acceleration: measured PEAK-MEMORY speedup = torch.cuda.max_memory_allocated(baseline)/max_memory_allocated(candidate), geomean over 4 large-vocab shapes on H20 (NOT wall-time; latency may be ~1.0x). The 12-case hidden correctness suite, anti-cheat (only cross_entropy_grad.py may change) and the fused-cross-entropy-primitive ban are hard gates; reward is 0 on any correctness/anti-cheat failure."
|
| 55 |
+
ref_speedup = 7.4157
|
| 56 |
+
ref_speedup_source = "tests/ref_speedup.txt"
|
| 57 |
+
calibrated_on = "NVIDIA H20"
|
| 58 |
+
correctness_gates = [
|
| 59 |
+
"hidden_parity_suite",
|
| 60 |
+
"all_ignore_rows",
|
| 61 |
+
"single_class",
|
| 62 |
+
"single_row",
|
| 63 |
+
"nontile_vocab",
|
| 64 |
+
"label_smoothing",
|
| 65 |
+
"degenerate",
|
| 66 |
+
"error_reject",
|
| 67 |
+
"metamorphic",
|
| 68 |
+
"work_evidence_nonzero_rows",
|
| 69 |
+
"trusted_restore",
|
| 70 |
+
"anti_cheat_forbidden_edit",
|
| 71 |
+
"forbidden_fused_ce_primitive",
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
[loop]
|
| 75 |
+
min_submissions = 1
|
| 76 |
+
max_submissions = 1
|
| 77 |
+
submit = "bash /opt/loop/submit.sh"
|
| 78 |
+
mode = "baked"
|
| 79 |
+
feedback_surface = "/opt/loop/submit.sh"
|
| 80 |
+
declared_submission_policy = "single_submission"
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/compute_reward.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Canonical kernelbench reward writer. Task-agnostic; do NOT special-case a task here.
|
| 3 |
+
|
| 4 |
+
Reward definition (the reward specification):
|
| 5 |
+
|
| 6 |
+
performance / acceleration task:
|
| 7 |
+
reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0
|
| 8 |
+
- speedup == ref_speedup -> 0.0 (must EXCEED it to score) (matching the oracle)
|
| 9 |
+
- speedup >= ref_speedup**2 -> 1.0 (capped)
|
| 10 |
+
- value range strictly [0.0, 1.0]
|
| 11 |
+
HARD pre-gates (any one hit => reward = 0, formula NOT entered):
|
| 12 |
+
build/import failure, ANY correctness case fail, cheating,
|
| 13 |
+
forbidden_edit_paths touched, speedup <= 1, ref_speedup <= 1.
|
| 14 |
+
|
| 15 |
+
implementation / correctness task:
|
| 16 |
+
reward = 1.0 iff EVERY visible case passes and no cheat / forbidden-path
|
| 17 |
+
condition fired; 0.0 otherwise. BINARY — never a pass-fraction.
|
| 18 |
+
|
| 19 |
+
Reads: /logs/verifier/verifier_state.json, /logs/verifier/benchmark_results.json,
|
| 20 |
+
/logs/verifier/correctness_results.json
|
| 21 |
+
Writes: /logs/verifier/reward.json, /logs/verifier/reward.txt
|
| 22 |
+
"""
|
| 23 |
+
import json, math
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
LOG = Path("/logs/verifier")
|
| 27 |
+
STATE = LOG / "verifier_state.json"
|
| 28 |
+
BENCH = LOG / "benchmark_results.json"
|
| 29 |
+
CORR = LOG / "correctness_results.json"
|
| 30 |
+
REWARD = LOG / "reward.json"
|
| 31 |
+
TEXT = LOG / "reward.txt"
|
| 32 |
+
|
| 33 |
+
GATES = [
|
| 34 |
+
"correctness_ok",
|
| 35 |
+
"trusted_restore_ok",
|
| 36 |
+
"hidden_correctness_ok",
|
| 37 |
+
"baseline_ok",
|
| 38 |
+
"benchmark_ok",
|
| 39 |
+
"anti_cheat_ok",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def read_json(path, default):
|
| 44 |
+
try:
|
| 45 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 46 |
+
except Exception:
|
| 47 |
+
return default
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def log_reward(speedup, ref):
|
| 51 |
+
"""reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0, clamped to [0.0, 1.0]."""
|
| 52 |
+
try:
|
| 53 |
+
num = math.log(float(speedup))
|
| 54 |
+
den = math.log(float(ref))
|
| 55 |
+
except Exception:
|
| 56 |
+
return 0.0
|
| 57 |
+
if not math.isfinite(num) or not math.isfinite(den) or den <= 0.0:
|
| 58 |
+
return 0.0
|
| 59 |
+
r = max(0.0, min(1.0, num / den - 1.0))
|
| 60 |
+
if not math.isfinite(r):
|
| 61 |
+
return 0.0
|
| 62 |
+
return max(0.0, min(1.0, r))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def case_counts(state, corr):
|
| 66 |
+
total = state.get("expected_case_count")
|
| 67 |
+
passed = state.get("actual_case_count")
|
| 68 |
+
suites = corr.get("suites") or []
|
| 69 |
+
if suites:
|
| 70 |
+
try:
|
| 71 |
+
p = sum(int(s.get("passed") or 0) for s in suites)
|
| 72 |
+
t = sum(int(s.get("expected_case_count") or 0) for s in suites)
|
| 73 |
+
if t > 0:
|
| 74 |
+
passed, total = p, t
|
| 75 |
+
except Exception:
|
| 76 |
+
pass
|
| 77 |
+
return passed, total
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main():
|
| 81 |
+
LOG.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
state = read_json(STATE, {})
|
| 83 |
+
bench = read_json(BENCH, {})
|
| 84 |
+
corr = read_json(CORR, {})
|
| 85 |
+
hard = list(state.get("hard_fail_reasons") or [])
|
| 86 |
+
task_kind = state.get("task_kind") or bench.get("task_kind") or "acceleration"
|
| 87 |
+
gates_ok = all(bool(state.get(g)) for g in GATES)
|
| 88 |
+
passed, total = case_counts(state, corr)
|
| 89 |
+
|
| 90 |
+
speedup = ref = 1.0
|
| 91 |
+
reward = 0.0
|
| 92 |
+
if task_kind == "correctness":
|
| 93 |
+
# IMPLEMENTATION task -> BINARY. Any single case short of the expected
|
| 94 |
+
# count zeroes the reward (no partial / graded fraction credit).
|
| 95 |
+
cases_ok = True
|
| 96 |
+
if total is not None and passed is not None:
|
| 97 |
+
try:
|
| 98 |
+
cases_ok = int(passed) >= int(total)
|
| 99 |
+
except Exception:
|
| 100 |
+
cases_ok = False
|
| 101 |
+
if not cases_ok and "case_count_short" not in hard:
|
| 102 |
+
hard.append("case_count_short")
|
| 103 |
+
reward = 1.0 if (gates_ok and cases_ok and not hard) else 0.0
|
| 104 |
+
if reward == 0.0 and not hard:
|
| 105 |
+
hard.append("correctness_or_validation_incomplete")
|
| 106 |
+
else:
|
| 107 |
+
try:
|
| 108 |
+
speedup = float(bench.get("aggregate_speedup") or bench.get("primary_metric_value") or 1.0)
|
| 109 |
+
ref = float(bench.get("ref_speedup") or bench.get("reference_metric_value") or 1.0)
|
| 110 |
+
except Exception:
|
| 111 |
+
speedup = ref = 1.0
|
| 112 |
+
if "invalid_primary_metric_value" not in hard:
|
| 113 |
+
hard.append("invalid_primary_metric_value")
|
| 114 |
+
# Correctness / anti-cheat / forbidden-path pre-gates arrive via gates_ok +
|
| 115 |
+
# hard (unchanged, never weakened). The two metric pre-gates are explicit.
|
| 116 |
+
if not math.isfinite(speedup) or speedup <= 1.0:
|
| 117 |
+
if "speedup_not_above_baseline" not in hard:
|
| 118 |
+
hard.append("speedup_not_above_baseline")
|
| 119 |
+
if not math.isfinite(ref) or ref <= 1.0:
|
| 120 |
+
if "ref_speedup_invalid" not in hard:
|
| 121 |
+
hard.append("ref_speedup_invalid")
|
| 122 |
+
if gates_ok and not hard:
|
| 123 |
+
reward = log_reward(speedup, ref)
|
| 124 |
+
|
| 125 |
+
out = {
|
| 126 |
+
"schema_version": "kernelbench_reward_v2",
|
| 127 |
+
"task_kind": task_kind,
|
| 128 |
+
"task_type": "implementation" if task_kind == "correctness" else "performance",
|
| 129 |
+
"reward": reward,
|
| 130 |
+
"reward_formula": ("binary: 1.0 iff every visible case passes and no cheat/forbidden path"
|
| 131 |
+
if task_kind == "correctness"
|
| 132 |
+
else "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0"),
|
| 133 |
+
"speedup": speedup,
|
| 134 |
+
"ref_speedup": ref,
|
| 135 |
+
"cv": bench.get("cv") or {},
|
| 136 |
+
"tests": {"passed": passed, "total": total},
|
| 137 |
+
"actual_hardware_type": state.get("actual_hardware_type", "") or bench.get("actual_hardware_type", ""),
|
| 138 |
+
"hard_fail_reasons": hard,
|
| 139 |
+
"state_path": str(STATE),
|
| 140 |
+
"benchmark_path": str(BENCH),
|
| 141 |
+
}
|
| 142 |
+
REWARD.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
| 143 |
+
TEXT.write_text(f"{reward}\n", encoding="utf-8")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
main()
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/gpu_peakmem.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Peak-GPU-memory measurement for the cross-entropy loss+gradient task.
|
| 2 |
+
|
| 3 |
+
VALUE AXIS = PEAK MEMORY, not wall-time. The naive baseline materialises several
|
| 4 |
+
full ``(N, V)`` buffers (log-probs, probabilities, gradient); a memory-frugal
|
| 5 |
+
implementation keeps only per-row running state and can overwrite the logits
|
| 6 |
+
buffer with the gradient in place, so its peak ``max_memory_allocated`` is far
|
| 7 |
+
lower at large ``V``. Latency may be ~1.0x -- that is EXPECTED and is NOT scored.
|
| 8 |
+
|
| 9 |
+
Per shape:
|
| 10 |
+
1. correctness agreement: candidate output must match the frozen baseline
|
| 11 |
+
within tolerance (on a fresh clone; the candidate may mutate in place);
|
| 12 |
+
2. peak = ``torch.cuda.max_memory_allocated`` measured over a single call, with
|
| 13 |
+
only the freshly generated inputs resident at reset (the input buffer is the
|
| 14 |
+
shared floor for both); ratio = baseline_peak / candidate_peak.
|
| 15 |
+
Final metric = geometric mean of the per-shape peak-memory ratios. Prints
|
| 16 |
+
"speedup=X" (the peak-memory ratio; a no-op candidate == frozen baseline ties at
|
| 17 |
+
~1.0). The baseline is loaded from the protected frozen copy (KB_BASELINE_MODULE).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import importlib.util
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
from kb_ce_harness import (
|
| 27 |
+
assert_grad_close,
|
| 28 |
+
assert_loss_close,
|
| 29 |
+
forbidden_ce_guard,
|
| 30 |
+
geomean,
|
| 31 |
+
load_candidate,
|
| 32 |
+
make_labels,
|
| 33 |
+
make_logits,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
IGN = -100
|
| 37 |
+
LS = 0.0
|
| 38 |
+
IGNORE_FRAC = 0.1
|
| 39 |
+
|
| 40 |
+
# (tag, N, V, dtype). Vocab large enough that the baseline's (N,V) materialisation
|
| 41 |
+
# dominates peak memory (false-negative checklist item #3: a path-exercising workload).
|
| 42 |
+
SHAPES = [
|
| 43 |
+
("v32k_fp32", 8192, 32768, torch.float32),
|
| 44 |
+
("v128k_fp32", 8192, 128256, torch.float32),
|
| 45 |
+
("v64k_bf16", 8192, 65536, torch.bfloat16),
|
| 46 |
+
("v128k_bf16", 8192, 128256, torch.bfloat16),
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _load(path):
|
| 51 |
+
spec = importlib.util.spec_from_file_location("kb_ce_mod_" + str(abs(hash(path))), path)
|
| 52 |
+
mod = importlib.util.module_from_spec(spec)
|
| 53 |
+
spec.loader.exec_module(mod)
|
| 54 |
+
return mod
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _baseline_fn():
|
| 58 |
+
path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/cross_entropy_grad.py")
|
| 59 |
+
return _load(path).cross_entropy_loss_grad
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _peak_of(fn, N, V, dtype, seed, guard):
|
| 63 |
+
"""max_memory_allocated over one call, inputs freshly generated (only they
|
| 64 |
+
are resident at reset, so the input buffer is the shared floor)."""
|
| 65 |
+
torch.cuda.empty_cache()
|
| 66 |
+
torch.cuda.synchronize()
|
| 67 |
+
logits = make_logits(N, V, seed, dtype=dtype)
|
| 68 |
+
labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN)
|
| 69 |
+
torch.cuda.synchronize()
|
| 70 |
+
torch.cuda.reset_peak_memory_stats()
|
| 71 |
+
if guard:
|
| 72 |
+
with forbidden_ce_guard():
|
| 73 |
+
loss, grad = fn(logits, labels, IGN, LS)
|
| 74 |
+
else:
|
| 75 |
+
loss, grad = fn(logits, labels, IGN, LS)
|
| 76 |
+
torch.cuda.synchronize()
|
| 77 |
+
peak = torch.cuda.max_memory_allocated()
|
| 78 |
+
del logits, labels, loss, grad
|
| 79 |
+
torch.cuda.empty_cache()
|
| 80 |
+
return int(peak)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _agree(candidate, baseline, N, V, dtype, seed):
|
| 84 |
+
"""Candidate must match baseline within tolerance before its peak counts."""
|
| 85 |
+
logits = make_logits(N, V, seed, dtype=dtype)
|
| 86 |
+
labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN)
|
| 87 |
+
b_loss, b_grad = baseline(logits.clone(), labels, IGN, LS)
|
| 88 |
+
with forbidden_ce_guard():
|
| 89 |
+
c_loss, c_grad = candidate(logits.clone(), labels, IGN, LS)
|
| 90 |
+
bf16 = dtype == torch.bfloat16
|
| 91 |
+
assert_loss_close(c_loss, b_loss, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]")
|
| 92 |
+
assert_grad_close(c_grad, b_grad, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]")
|
| 93 |
+
del logits, labels, b_loss, b_grad, c_loss, c_grad
|
| 94 |
+
torch.cuda.empty_cache()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def main():
|
| 98 |
+
if not torch.cuda.is_available():
|
| 99 |
+
print("CUDA_UNAVAILABLE")
|
| 100 |
+
sys.exit(2)
|
| 101 |
+
torch.cuda.init()
|
| 102 |
+
candidate = load_candidate().cross_entropy_loss_grad
|
| 103 |
+
baseline = _baseline_fn()
|
| 104 |
+
|
| 105 |
+
ratios = []
|
| 106 |
+
seed = 5000
|
| 107 |
+
for tag, N, V, dtype in SHAPES:
|
| 108 |
+
try:
|
| 109 |
+
_agree(candidate, baseline, N, V, dtype, seed)
|
| 110 |
+
except AssertionError as exc:
|
| 111 |
+
print(f"BENCH_FAIL {tag}: {exc}")
|
| 112 |
+
print("speedup=0.0")
|
| 113 |
+
sys.exit(1)
|
| 114 |
+
cand_peak = _peak_of(candidate, N, V, dtype, seed, guard=True)
|
| 115 |
+
base_peak = _peak_of(baseline, N, V, dtype, seed, guard=False)
|
| 116 |
+
ratio = base_peak / max(cand_peak, 1)
|
| 117 |
+
ratios.append(ratio)
|
| 118 |
+
print(f"shape={tag} N={N} V={V} dtype={dtype} "
|
| 119 |
+
f"baseline_peak={base_peak} candidate_peak={cand_peak} ratio={ratio:.4f}")
|
| 120 |
+
seed += 100
|
| 121 |
+
|
| 122 |
+
print(f"speedup={geomean(ratios):.4f}")
|
| 123 |
+
sys.exit(0)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
main()
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/kb_ce_harness.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared harness for the cross-entropy loss+gradient contract.
|
| 2 |
+
|
| 3 |
+
Provides:
|
| 4 |
+
* ``load_candidate`` — import the candidate module from /app/repo,
|
| 5 |
+
* deterministic input generation (``make_logits`` / ``make_labels``),
|
| 6 |
+
* a high-precision float32 reference (``ref_ce``) — the ground truth for both
|
| 7 |
+
loss and gradient,
|
| 8 |
+
* ``assert_loss_close`` / ``assert_grad_close`` tolerance comparisons,
|
| 9 |
+
* ``count_nonzero_rows`` — the work-evidence signal,
|
| 10 |
+
* ``geomean``,
|
| 11 |
+
* ``forbidden_ce_guard`` — a runtime guard that blocks the framework's
|
| 12 |
+
single-call fused cross-entropy loss while the candidate runs, so the
|
| 13 |
+
candidate cannot delegate the whole computation to the vendor primitive it
|
| 14 |
+
is meant to build.
|
| 15 |
+
|
| 16 |
+
The reference materialises full-size buffers on purpose (it is only the
|
| 17 |
+
correctness oracle, not scored on memory).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import contextlib
|
| 21 |
+
import importlib.util
|
| 22 |
+
import math
|
| 23 |
+
import os
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
# candidate-vs-reference tolerances
|
| 28 |
+
LOSS_ATOL = 1e-4
|
| 29 |
+
LOSS_ATOL_BF16 = 3e-2
|
| 30 |
+
LOSS_RTOL = 1e-3
|
| 31 |
+
# bf16 loss carries the dtype's own ~2^-8 (~0.4%) quantization; at a large-vocab
|
| 32 |
+
# loss magnitude (~19) that is ~0.075 absolute, which a 1e-3 relative term cannot
|
| 33 |
+
# represent. Comparing a correctly bf16-cast loss (reference/oracle) against the
|
| 34 |
+
# fp32 baseline loss must tolerate that quantization, so bf16 uses a relative term
|
| 35 |
+
# above bf16's resolution. The (N,V) gradient parity check remains the tight,
|
| 36 |
+
# authoritative correctness signal.
|
| 37 |
+
LOSS_RTOL_BF16 = 8e-3
|
| 38 |
+
GRAD_ATOL = 1e-4
|
| 39 |
+
GRAD_RTOL = 1e-3
|
| 40 |
+
GRAD_ATOL_BF16 = 8e-3
|
| 41 |
+
GRAD_RTOL_BF16 = 1e-2
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def repo_dir():
|
| 45 |
+
return os.environ.get("KB_REPO_DIR", "/app/repo")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_candidate():
|
| 49 |
+
"""Import the candidate module from the repo under test."""
|
| 50 |
+
path = os.path.join(repo_dir(), "cross_entropy_grad.py")
|
| 51 |
+
spec = importlib.util.spec_from_file_location("candidate_ce_grad", path)
|
| 52 |
+
mod = importlib.util.module_from_spec(spec)
|
| 53 |
+
spec.loader.exec_module(mod)
|
| 54 |
+
if not hasattr(mod, "cross_entropy_loss_grad"):
|
| 55 |
+
raise AttributeError(f"{path} does not define cross_entropy_loss_grad()")
|
| 56 |
+
return mod
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# --------------------------------------------------------------------------- #
|
| 60 |
+
# Deterministic input generation
|
| 61 |
+
# --------------------------------------------------------------------------- #
|
| 62 |
+
def make_logits(N, V, seed, dtype=torch.float32, scale=4.0, device="cuda"):
|
| 63 |
+
g = torch.Generator(device="cpu").manual_seed(seed)
|
| 64 |
+
x = torch.randn(N, V, generator=g, dtype=torch.float32) * scale
|
| 65 |
+
return x.to(device).to(dtype)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def make_labels(N, V, seed, ignore_frac=0.0, ignore_index=-100, device="cuda"):
|
| 69 |
+
g = torch.Generator(device="cpu").manual_seed(seed)
|
| 70 |
+
lab = torch.randint(0, V, (N,), generator=g, dtype=torch.int64)
|
| 71 |
+
if ignore_frac > 0.0:
|
| 72 |
+
mask = torch.rand(N, generator=g) < ignore_frac
|
| 73 |
+
lab[mask] = ignore_index
|
| 74 |
+
return lab.to(device)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# --------------------------------------------------------------------------- #
|
| 78 |
+
# High-precision float32 reference (ground truth for loss + grad)
|
| 79 |
+
# --------------------------------------------------------------------------- #
|
| 80 |
+
def ref_ce(logits, labels, ignore_index=-100, label_smoothing=0.0):
|
| 81 |
+
N, V = logits.shape
|
| 82 |
+
s = float(label_smoothing)
|
| 83 |
+
valid = labels != ignore_index
|
| 84 |
+
n_valid = int(valid.sum().item())
|
| 85 |
+
denom = max(n_valid, 1)
|
| 86 |
+
safe = labels.clamp(min=0).long()
|
| 87 |
+
idx = torch.arange(N, device=logits.device)
|
| 88 |
+
|
| 89 |
+
lf = logits.to(torch.float32)
|
| 90 |
+
logp = torch.log_softmax(lf, dim=-1)
|
| 91 |
+
logp_y = logp[idx, safe]
|
| 92 |
+
nll = -logp_y
|
| 93 |
+
smooth = -logp.mean(dim=1)
|
| 94 |
+
row_loss = (1.0 - s) * nll + s * smooth
|
| 95 |
+
row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss))
|
| 96 |
+
loss = row_loss.sum() / denom
|
| 97 |
+
|
| 98 |
+
prob = logp.exp()
|
| 99 |
+
grad = prob.clone()
|
| 100 |
+
if s != 0.0:
|
| 101 |
+
grad = grad - (s / V)
|
| 102 |
+
grad[idx, safe] = grad[idx, safe] - (1.0 - s)
|
| 103 |
+
grad = grad / denom
|
| 104 |
+
grad[~valid] = 0.0
|
| 105 |
+
return loss.to(logits.dtype), grad.to(logits.dtype)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# --------------------------------------------------------------------------- #
|
| 109 |
+
# Comparisons
|
| 110 |
+
# --------------------------------------------------------------------------- #
|
| 111 |
+
def assert_loss_close(cand_loss, ref_loss, bf16=False, msg=""):
|
| 112 |
+
cl = torch.as_tensor(cand_loss).to(torch.float32).reshape(())
|
| 113 |
+
rl = torch.as_tensor(ref_loss).to(torch.float32).reshape(())
|
| 114 |
+
if not torch.isfinite(cl):
|
| 115 |
+
raise AssertionError(f"candidate loss is non-finite {msg}")
|
| 116 |
+
atol = LOSS_ATOL_BF16 if bf16 else LOSS_ATOL
|
| 117 |
+
rtol = LOSS_RTOL_BF16 if bf16 else LOSS_RTOL
|
| 118 |
+
d = float((cl - rl).abs())
|
| 119 |
+
tol = atol + rtol * float(rl.abs())
|
| 120 |
+
if d > tol:
|
| 121 |
+
raise AssertionError(f"loss mismatch: |{float(cl):.6f}-{float(rl):.6f}|={d:.6f} > {tol:.6f} {msg}")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def assert_grad_close(cand_grad, ref_grad, bf16=False, msg=""):
|
| 125 |
+
if tuple(cand_grad.shape) != tuple(ref_grad.shape):
|
| 126 |
+
raise AssertionError(f"grad shape {tuple(cand_grad.shape)} vs {tuple(ref_grad.shape)} {msg}")
|
| 127 |
+
if cand_grad.dtype != ref_grad.dtype:
|
| 128 |
+
raise AssertionError(f"grad dtype {cand_grad.dtype} vs {ref_grad.dtype} {msg}")
|
| 129 |
+
c = cand_grad.to(torch.float32)
|
| 130 |
+
r = ref_grad.to(torch.float32)
|
| 131 |
+
if not torch.isfinite(c).all():
|
| 132 |
+
raise AssertionError(f"candidate grad has non-finite values {msg}")
|
| 133 |
+
atol = GRAD_ATOL_BF16 if bf16 else GRAD_ATOL
|
| 134 |
+
rtol = GRAD_RTOL_BF16 if bf16 else GRAD_RTOL
|
| 135 |
+
diff = (c - r).abs()
|
| 136 |
+
tol = atol + rtol * r.abs()
|
| 137 |
+
bad = diff > tol
|
| 138 |
+
if bad.any():
|
| 139 |
+
raise AssertionError(
|
| 140 |
+
f"{int(bad.sum())}/{c.numel()} grad elements out of tolerance "
|
| 141 |
+
f"(worst excess {float((diff - tol).max()):.5f}) {msg}")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def count_nonzero_rows(grad):
|
| 145 |
+
"""Work-evidence: number of rows whose gradient is not all-zero."""
|
| 146 |
+
return int((grad.to(torch.float32).abs().sum(dim=1) > 0).sum().item())
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# --------------------------------------------------------------------------- #
|
| 150 |
+
# Runtime guard: block the framework's single-call fused cross-entropy loss
|
| 151 |
+
# while the candidate runs (the candidate must compute loss + grad itself).
|
| 152 |
+
# --------------------------------------------------------------------------- #
|
| 153 |
+
@contextlib.contextmanager
|
| 154 |
+
def forbidden_ce_guard():
|
| 155 |
+
def _blocked(*args, **kwargs):
|
| 156 |
+
raise RuntimeError("forbidden fused cross-entropy primitive called during scoring")
|
| 157 |
+
|
| 158 |
+
class _BlockedModule:
|
| 159 |
+
def __init__(self, *a, **k):
|
| 160 |
+
raise RuntimeError("forbidden fused cross-entropy primitive called during scoring")
|
| 161 |
+
|
| 162 |
+
saved = []
|
| 163 |
+
for obj, name, repl in [
|
| 164 |
+
(torch.nn.functional, "cross_entropy", _blocked),
|
| 165 |
+
(torch.nn, "CrossEntropyLoss", _BlockedModule),
|
| 166 |
+
]:
|
| 167 |
+
if hasattr(obj, name):
|
| 168 |
+
saved.append((obj, name, getattr(obj, name)))
|
| 169 |
+
try:
|
| 170 |
+
setattr(obj, name, repl)
|
| 171 |
+
except Exception:
|
| 172 |
+
saved.pop()
|
| 173 |
+
try:
|
| 174 |
+
yield
|
| 175 |
+
finally:
|
| 176 |
+
for obj, name, val in reversed(saved):
|
| 177 |
+
try:
|
| 178 |
+
setattr(obj, name, val)
|
| 179 |
+
except Exception:
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def geomean(values):
|
| 184 |
+
vals = [max(float(v), 1e-12) for v in values]
|
| 185 |
+
return math.exp(sum(math.log(v) for v in vals) / len(vals))
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.caveat.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑)
|
| 2 |
+
|
| 3 |
+
`ref_speedup.txt` 里的 **7.4157** 是 oracle 标定常量,判分时只读、不重跑 oracle:
|
| 4 |
+
|
| 5 |
+
reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0
|
| 6 |
+
|
| 7 |
+
`tests/test.sh` 的解析顺序是 **`tests/ref_speedup.txt` → `/opt/verifier-correctness-manifest.json` → 1.0**;
|
| 8 |
+
回落到 1.0 会让所有 reward 归 0,所以这个文件必须存在且 > 1。
|
| 9 |
+
|
| 10 |
+
## 标定条件
|
| 11 |
+
|
| 12 |
+
- 硬件:**NVIDIA H20**
|
| 13 |
+
- 运行栈:`torch 2.7.0`(原始私有基座声明 torch 2.5.1/triton 3.1.0,任务 overlay 又 `pip install torch==2.7.0`,锚点即在 2.7.0 下标定)
|
| 14 |
+
- 线程:`OMP/MKL/OPENBLAS_NUM_THREADS=1`(计时稳定性的一部分,已写进镜像 ENV)
|
| 15 |
+
|
| 16 |
+
## 硬件不一致时如何重标
|
| 17 |
+
|
| 18 |
+
verifier 原生支持模式分派,参考实现**按路径传入、从不烤进镜像**:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
docker run --rm --gpus all -v "$PWD/tests:/tests:ro" -v "<放 oracle.patch 的目录>:/patches:ro" \
|
| 22 |
+
-e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \
|
| 23 |
+
fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss bash /tests/test.sh
|
| 24 |
+
# 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
自证:`noop`(不打补丁)应 ≈1.0 → 被门到 0;`negative`(`KERNELBENCH_NEGATIVE_PATCH=`)必须 0。
|
| 28 |
+
|
| 29 |
+
参考实现:见本包 `solution/oracle.patch`(reviewer-only,已被 `.dockerignore` 排除,不进镜像)。
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
7.4157
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test.sh
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Verifier for insea-fused-softmax-cross-entropy-grad-loop16 (cross-entropy loss + input
|
| 3 |
+
# gradient; value axis = PEAK MEMORY, not wall-time). Pattern A, ACCELERATION lane,
|
| 4 |
+
# scored on torch.cuda.max_memory_allocated on H20. Modes: candidate|noop|oracle|negative
|
| 5 |
+
set -uo pipefail
|
| 6 |
+
# Never trust the exec context — the harness may exec this in a
|
| 7 |
+
# NON-login shell where bare python3 has no torch. Pin the venv first.
|
| 8 |
+
export PATH=/opt/kernelbench-venv/bin:$PATH
|
| 9 |
+
TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 10 |
+
REPO=/app/repo
|
| 11 |
+
LOG=/logs/verifier
|
| 12 |
+
mkdir -p "$LOG"
|
| 13 |
+
MODE="${KERNELBENCH_VERIFY_MODE:-candidate}"
|
| 14 |
+
CAND_FILE="$REPO/cross_entropy_grad.py"
|
| 15 |
+
export KB_CANDIDATE_MODULE="$CAND_FILE"
|
| 16 |
+
export KB_BASELINE_MODULE=/opt/verifier-baseline/cross_entropy_grad.py
|
| 17 |
+
|
| 18 |
+
HARD=(); add_hard(){ HARD+=("$1"); }
|
| 19 |
+
correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true
|
| 20 |
+
baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true
|
| 21 |
+
expected_cases=12; actual_cases=0
|
| 22 |
+
speedup=1.0; ref_speedup=1.0; hw="unknown"
|
| 23 |
+
|
| 24 |
+
cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; }
|
| 25 |
+
|
| 26 |
+
if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then
|
| 27 |
+
# reviewer-only mode: reset the working tree to the frozen baseline so several
|
| 28 |
+
# modes running back-to-back in one container session each start clean. candidate/noop
|
| 29 |
+
# NEVER resets (this branch is skipped for them), so a solver session is untouched.
|
| 30 |
+
git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
|
| 31 |
+
git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"
|
| 32 |
+
fi
|
| 33 |
+
if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then
|
| 34 |
+
git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
|
| 35 |
+
git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true
|
| 36 |
+
fi
|
| 37 |
+
|
| 38 |
+
# anti-cheat: only cross_entropy_grad.py may change
|
| 39 |
+
git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt"
|
| 40 |
+
while IFS= read -r f; do
|
| 41 |
+
[ -z "$f" ] && continue
|
| 42 |
+
case "$f" in
|
| 43 |
+
cross_entropy_grad.py) : ;;
|
| 44 |
+
*__pycache__*) : ;;
|
| 45 |
+
*) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;;
|
| 46 |
+
esac
|
| 47 |
+
done < "$LOG/anti_cheat_changed_files.txt"
|
| 48 |
+
|
| 49 |
+
# anti-cheat: the framework's single-call fused cross-entropy loss is out of scope
|
| 50 |
+
# (the candidate must compute the loss + gradient itself). Textual scan of the file.
|
| 51 |
+
if [ -f "$CAND_FILE" ] && grep -Eq "torch\.nn\.functional\.cross_entropy|F\.cross_entropy|torch\.nn\.CrossEntropyLoss|nn\.CrossEntropyLoss|functional\.cross_entropy" "$CAND_FILE"; then
|
| 52 |
+
anti_cheat_ok=false; add_hard "forbidden_fused_ce_primitive"
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
# trusted restore: hidden suite ships in tests/ payload (fresh at scoring)
|
| 56 |
+
for f in test_cross_entropy_grad.py gpu_peakmem.py kb_ce_harness.py; do
|
| 57 |
+
[ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; }
|
| 58 |
+
done
|
| 59 |
+
|
| 60 |
+
# ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild)
|
| 61 |
+
if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then
|
| 62 |
+
ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt")
|
| 63 |
+
elif [ -f /opt/verifier-correctness-manifest.json ]; then
|
| 64 |
+
ref_speedup=$(python3 -c "import json;print(json.load(open('/opt/verifier-correctness-manifest.json')).get('ref_speedup',1.0))" 2>/dev/null || echo 1.0)
|
| 65 |
+
fi
|
| 66 |
+
hw=$(python3 -c "import torch;print(torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'no_cuda')" 2>/dev/null || echo unknown)
|
| 67 |
+
|
| 68 |
+
# correctness gate (needs CUDA)
|
| 69 |
+
if [ "$correctness_ok" = true ]; then
|
| 70 |
+
( cd "$TESTS_DIR" && python3 test_cross_entropy_grad.py ) > "$LOG/correctness.log" 2>&1
|
| 71 |
+
crc=$?
|
| 72 |
+
actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0}
|
| 73 |
+
if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then
|
| 74 |
+
hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed"
|
| 75 |
+
fi
|
| 76 |
+
fi
|
| 77 |
+
|
| 78 |
+
# measurement: PEAK MEMORY ratio (baseline_peak/candidate_peak), median over 3 runs
|
| 79 |
+
# (deterministic metric; median guards against allocator jitter). Only if correct.
|
| 80 |
+
if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then
|
| 81 |
+
: > "$LOG/bench.log"
|
| 82 |
+
sp_list=""
|
| 83 |
+
for r in 1 2 3; do
|
| 84 |
+
line=$( cd "$TESTS_DIR" && python3 gpu_peakmem.py 2>>"$LOG/bench.log" )
|
| 85 |
+
echo "$line" >> "$LOG/bench.log"
|
| 86 |
+
sp=$(echo "$line" | sed -n 's/.*speedup=\([0-9.-]*\).*/\1/p')
|
| 87 |
+
[ -n "$sp" ] && sp_list="$sp_list $sp"
|
| 88 |
+
done
|
| 89 |
+
speedup=$(python3 -c "v=sorted(float(x) for x in '$sp_list'.split());print(f'{v[len(v)//2]:.5f}' if v else '-1')")
|
| 90 |
+
if [ -z "$sp_list" ] || python3 -c "import sys;sys.exit(0 if float('$speedup')<=0 else 1)"; then
|
| 91 |
+
benchmark_ok=false; add_hard "benchmark_execution_failed"
|
| 92 |
+
fi
|
| 93 |
+
else
|
| 94 |
+
benchmark_ok=false
|
| 95 |
+
fi
|
| 96 |
+
|
| 97 |
+
HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi
|
| 98 |
+
DIAG_TAIL=""
|
| 99 |
+
if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then
|
| 100 |
+
DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g')
|
| 101 |
+
fi
|
| 102 |
+
cat > "$LOG/verifier_state.json" <<JSON
|
| 103 |
+
{"schema_version":"kernelbench_verifier_state_v1","task_kind":"acceleration",
|
| 104 |
+
"correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,
|
| 105 |
+
"hidden_correctness_ok":$hidden_correctness_ok,"baseline_ok":$baseline_ok,
|
| 106 |
+
"benchmark_ok":$benchmark_ok,"anti_cheat_ok":$anti_cheat_ok,
|
| 107 |
+
"hard_fail_reasons":$HARD_JSON,
|
| 108 |
+
"expected_case_count":$expected_cases,"actual_case_count":$actual_cases,
|
| 109 |
+
"expected_benchmark_count":1,"actual_benchmark_count":1,
|
| 110 |
+
"actual_hardware_type":"$hw","mode":"$MODE",
|
| 111 |
+
"work_evidence_notes":["cross-entropy loss+grad suite $actual_cases/$expected_cases ok","median peak-memory ratio (baseline_peak/candidate_peak)=$speedup on $hw","correctness_tail:${DIAG_TAIL}"]}
|
| 112 |
+
JSON
|
| 113 |
+
cat > "$LOG/correctness_results.json" <<JSON
|
| 114 |
+
{"schema_version":"kernelbench_correctness_results_v1",
|
| 115 |
+
"suites":[{"name":"hidden-cross-entropy-grad-suite","visibility_class":"hidden_supplement","expected_case_count":$expected_cases,"actual_case_count":$actual_cases,"passed":$actual_cases,"failed":$((expected_cases-actual_cases)),"hard_fail_reasons":$HARD_JSON}],
|
| 116 |
+
"correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,"hidden_correctness_ok":$hidden_correctness_ok}
|
| 117 |
+
JSON
|
| 118 |
+
cat > "$LOG/benchmark_results.json" <<JSON
|
| 119 |
+
{"schema_version":"kernelbench_benchmark_results_v1","task_kind":"acceleration","metric":"peak_memory_bytes",
|
| 120 |
+
"direction":"higher_is_better",
|
| 121 |
+
"workloads":[{"name":"ce-peakmem-geomean-4shapes","speedup":$speedup,"completion_counters":{"cases":"$actual_cases/$expected_cases"}}],
|
| 122 |
+
"aggregate_speedup":$speedup,"ref_speedup":$ref_speedup,"actual_hardware_type":"$hw"}
|
| 123 |
+
JSON
|
| 124 |
+
python3 "$TESTS_DIR/compute_reward.py" 2>/dev/null || python3 /tests/compute_reward.py 2>/dev/null || true
|
| 125 |
+
REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null)
|
| 126 |
+
echo "MODE=$MODE cases=$actual_cases/$expected_cases peakmem_ratio=$speedup ref=$ref_speedup hw=$hw reward=$REW"
|
| 127 |
+
[ -n "$REW" ] && exit 0 || exit 1
|
tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test_cross_entropy_grad.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Correctness suite for the cross-entropy loss+gradient contract — 12 cases.
|
| 2 |
+
|
| 3 |
+
Each case prints "CASE_PASS <name>" or "CASE_FAIL <name>: <reason>".
|
| 4 |
+
The runner greps the number of CASE_PASS lines (expects 12).
|
| 5 |
+
|
| 6 |
+
The candidate may overwrite its ``logits`` argument in place, so every case
|
| 7 |
+
passes the candidate a fresh clone and computes the reference from the pristine
|
| 8 |
+
tensor first.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import traceback
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
from kb_ce_harness import (
|
| 17 |
+
assert_grad_close,
|
| 18 |
+
assert_loss_close,
|
| 19 |
+
count_nonzero_rows,
|
| 20 |
+
forbidden_ce_guard,
|
| 21 |
+
load_candidate,
|
| 22 |
+
make_labels,
|
| 23 |
+
make_logits,
|
| 24 |
+
ref_ce,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
IGN = -100
|
| 28 |
+
CASES = []
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def case(fn):
|
| 32 |
+
CASES.append(fn)
|
| 33 |
+
return fn
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _run(fn, N, V, seed, dtype=torch.float32, ls=0.0, ignore_frac=0.0):
|
| 37 |
+
logits = make_logits(N, V, seed, dtype=dtype)
|
| 38 |
+
labels = make_labels(N, V, seed + 1, ignore_frac=ignore_frac, ignore_index=IGN)
|
| 39 |
+
ref_loss, ref_grad = ref_ce(logits, labels, ignore_index=IGN, label_smoothing=ls)
|
| 40 |
+
with forbidden_ce_guard():
|
| 41 |
+
c_loss, c_grad = fn(logits.clone(), labels, IGN, ls)
|
| 42 |
+
bf16 = dtype == torch.bfloat16
|
| 43 |
+
tag = f"[N={N} V={V} dtype={dtype} ls={ls} ign={ignore_frac}]"
|
| 44 |
+
assert_loss_close(c_loss, ref_loss, bf16=bf16, msg=tag)
|
| 45 |
+
assert_grad_close(c_grad, ref_grad, bf16=bf16, msg=tag)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@case
|
| 49 |
+
def normal_fp32(fn):
|
| 50 |
+
_run(fn, 256, 4096, seed=100)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@case
|
| 54 |
+
def normal_bf16(fn):
|
| 55 |
+
_run(fn, 256, 4096, seed=150, dtype=torch.bfloat16)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@case
|
| 59 |
+
def mean_with_ignore(fn):
|
| 60 |
+
_run(fn, 320, 3072, seed=200, ignore_frac=0.35)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@case
|
| 64 |
+
def all_ignore(fn):
|
| 65 |
+
# every row ignored -> loss 0, grad all zero
|
| 66 |
+
N, V = 128, 2048
|
| 67 |
+
logits = make_logits(N, V, 300)
|
| 68 |
+
labels = torch.full((N,), IGN, dtype=torch.int64, device="cuda")
|
| 69 |
+
with forbidden_ce_guard():
|
| 70 |
+
c_loss, c_grad = fn(logits.clone(), labels, IGN, 0.0)
|
| 71 |
+
if abs(float(c_loss)) > 1e-5:
|
| 72 |
+
raise AssertionError(f"all-ignore loss should be 0, got {float(c_loss)}")
|
| 73 |
+
if c_grad.shape != (N, V):
|
| 74 |
+
raise AssertionError(f"bad grad shape {tuple(c_grad.shape)}")
|
| 75 |
+
if not (c_grad.to(torch.float32) == 0).all():
|
| 76 |
+
raise AssertionError("all-ignore grad should be exactly zero")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@case
|
| 80 |
+
def single_class(fn):
|
| 81 |
+
# V == 1: softmax is 1, loss is 0, grad is 0
|
| 82 |
+
_run(fn, 64, 1, seed=400)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@case
|
| 86 |
+
def single_row(fn):
|
| 87 |
+
_run(fn, 1, 2048, seed=500)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@case
|
| 91 |
+
def nontile_vocab(fn):
|
| 92 |
+
# V not a multiple of any common chunk size
|
| 93 |
+
_run(fn, 128, 4099, seed=600)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@case
|
| 97 |
+
def label_smoothing(fn):
|
| 98 |
+
_run(fn, 256, 2048, seed=700, ls=0.1)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@case
|
| 102 |
+
def error_contract(fn):
|
| 103 |
+
N, V = 32, 512
|
| 104 |
+
logits = make_logits(N, V, 800)
|
| 105 |
+
labels = make_labels(N, V, 801)
|
| 106 |
+
# integer logits -> TypeError
|
| 107 |
+
try:
|
| 108 |
+
fn(logits.to(torch.int32), labels, IGN, 0.0)
|
| 109 |
+
raise AssertionError("integer logits did not raise TypeError")
|
| 110 |
+
except TypeError:
|
| 111 |
+
pass
|
| 112 |
+
# float labels -> TypeError
|
| 113 |
+
try:
|
| 114 |
+
fn(logits.clone(), labels.to(torch.float32), IGN, 0.0)
|
| 115 |
+
raise AssertionError("float labels did not raise TypeError")
|
| 116 |
+
except TypeError:
|
| 117 |
+
pass
|
| 118 |
+
# 1-D logits -> ValueError
|
| 119 |
+
try:
|
| 120 |
+
fn(logits.reshape(-1).clone(), labels, IGN, 0.0)
|
| 121 |
+
raise AssertionError("1-D logits did not raise ValueError")
|
| 122 |
+
except ValueError:
|
| 123 |
+
pass
|
| 124 |
+
# labels wrong length -> ValueError
|
| 125 |
+
try:
|
| 126 |
+
fn(logits.clone(), labels[:-1], IGN, 0.0)
|
| 127 |
+
raise AssertionError("wrong-length labels did not raise ValueError")
|
| 128 |
+
except ValueError:
|
| 129 |
+
pass
|
| 130 |
+
# negative label_smoothing -> ValueError
|
| 131 |
+
try:
|
| 132 |
+
fn(logits.clone(), labels, IGN, -0.1)
|
| 133 |
+
raise AssertionError("negative label_smoothing did not raise ValueError")
|
| 134 |
+
except ValueError:
|
| 135 |
+
pass
|
| 136 |
+
# a non-ignored label out of range [0, V) -> ValueError
|
| 137 |
+
bad = labels.clone()
|
| 138 |
+
bad[0] = V # out of range, not the ignore sentinel
|
| 139 |
+
try:
|
| 140 |
+
fn(logits.clone(), bad, IGN, 0.0)
|
| 141 |
+
raise AssertionError("out-of-range label did not raise ValueError")
|
| 142 |
+
except ValueError:
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@case
|
| 147 |
+
def metamorphic_const_shift(fn):
|
| 148 |
+
"""Adding a per-row constant to all logits leaves loss AND grad unchanged."""
|
| 149 |
+
N, V = 192, 2048
|
| 150 |
+
logits = make_logits(N, V, 900)
|
| 151 |
+
labels = make_labels(N, V, 901)
|
| 152 |
+
with forbidden_ce_guard():
|
| 153 |
+
loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0)
|
| 154 |
+
g = torch.Generator(device="cpu").manual_seed(902)
|
| 155 |
+
# a large positive per-row shift: a numerically stable softmax is invariant,
|
| 156 |
+
# while a non-stable one (no max subtraction) overflows -> NaN -> fails here.
|
| 157 |
+
shift = (torch.rand(N, generator=g) * 40.0 + 80.0).to(logits.device).to(logits.dtype)
|
| 158 |
+
logits_b = logits + shift[:, None]
|
| 159 |
+
with forbidden_ce_guard():
|
| 160 |
+
loss_b, grad_b = fn(logits_b.clone(), labels, IGN, 0.0)
|
| 161 |
+
assert_loss_close(loss_b, loss_a, msg="[const-shift loss]")
|
| 162 |
+
assert_grad_close(grad_b, grad_a, msg="[const-shift grad]")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@case
|
| 166 |
+
def metamorphic_permute_rows(fn):
|
| 167 |
+
"""Permuting the rows permutes the gradient rows and leaves the mean loss unchanged."""
|
| 168 |
+
N, V = 256, 2048
|
| 169 |
+
logits = make_logits(N, V, 1000)
|
| 170 |
+
labels = make_labels(N, V, 1001, ignore_frac=0.2, ignore_index=IGN)
|
| 171 |
+
with forbidden_ce_guard():
|
| 172 |
+
loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0)
|
| 173 |
+
g = torch.Generator(device="cpu").manual_seed(1002)
|
| 174 |
+
perm = torch.randperm(N, generator=g).to(logits.device)
|
| 175 |
+
with forbidden_ce_guard():
|
| 176 |
+
loss_b, grad_b = fn(logits[perm].clone(), labels[perm], IGN, 0.0)
|
| 177 |
+
assert_loss_close(loss_b, loss_a, msg="[permute loss]")
|
| 178 |
+
assert_grad_close(grad_b, grad_a[perm], msg="[permute grad]")
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@case
|
| 182 |
+
def work_evidence(fn):
|
| 183 |
+
"""Exactly the non-ignored rows carry a nonzero gradient; ignored rows are zero."""
|
| 184 |
+
N, V = 384, 2048
|
| 185 |
+
logits = make_logits(N, V, 1100)
|
| 186 |
+
labels = make_labels(N, V, 1101, ignore_frac=0.5, ignore_index=IGN)
|
| 187 |
+
n_valid = int((labels != IGN).sum().item())
|
| 188 |
+
with forbidden_ce_guard():
|
| 189 |
+
_, c_grad = fn(logits.clone(), labels, IGN, 0.0)
|
| 190 |
+
nz = count_nonzero_rows(c_grad)
|
| 191 |
+
if nz != n_valid:
|
| 192 |
+
raise AssertionError(f"nonzero-grad rows {nz} != valid labels {n_valid}")
|
| 193 |
+
ignored = (labels == IGN)
|
| 194 |
+
if ignored.any() and not (c_grad[ignored].to(torch.float32) == 0).all():
|
| 195 |
+
raise AssertionError("ignored rows have nonzero gradient")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def main():
|
| 199 |
+
if not torch.cuda.is_available():
|
| 200 |
+
print("CUDA_UNAVAILABLE")
|
| 201 |
+
sys.exit(2)
|
| 202 |
+
mod = load_candidate()
|
| 203 |
+
fn = mod.cross_entropy_loss_grad
|
| 204 |
+
passed = 0
|
| 205 |
+
for fn_case in CASES:
|
| 206 |
+
name = fn_case.__name__
|
| 207 |
+
try:
|
| 208 |
+
fn_case(fn)
|
| 209 |
+
torch.cuda.synchronize()
|
| 210 |
+
passed += 1
|
| 211 |
+
print(f"CASE_PASS {name}")
|
| 212 |
+
except Exception as exc: # noqa: BLE001
|
| 213 |
+
reason = f"{type(exc).__name__}: {exc}"
|
| 214 |
+
print(f"CASE_FAIL {name}: {reason.splitlines()[0][:300]}")
|
| 215 |
+
traceback.print_exc(file=sys.stderr)
|
| 216 |
+
total = len(CASES)
|
| 217 |
+
print(f"CASES_PASSED={passed}/{total}")
|
| 218 |
+
sys.exit(0 if passed == total else 1)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|
tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
1.60
|
tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/test.sh
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Verifier for insea-h2d-prefetch-compute-overlap-loop16 (chunked H2D transfer overlapped with compute).
|
| 3 |
+
# Pattern A, ACCELERATION lane, wall-time on H20 (transfer latency hidden behind compute).
|
| 4 |
+
# Modes: candidate|noop|oracle|negative
|
| 5 |
+
set -uo pipefail
|
| 6 |
+
# Never trust the exec context — the harness may exec this in a
|
| 7 |
+
# NON-login shell where bare python3 has no torch. Pin the venv first.
|
| 8 |
+
export PATH=/opt/kernelbench-venv/bin:$PATH
|
| 9 |
+
TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 10 |
+
REPO=/app/repo
|
| 11 |
+
LOG=/logs/loop/dev
|
| 12 |
+
mkdir -p "$LOG"
|
| 13 |
+
MODE="${KERNELBENCH_VERIFY_MODE:-candidate}"
|
| 14 |
+
CAND_FILE="$REPO/streamed_apply.py"
|
| 15 |
+
export KB_CANDIDATE_MODULE="$CAND_FILE"
|
| 16 |
+
export KB_BASELINE_MODULE=/opt/verifier-baseline/streamed_apply.py
|
| 17 |
+
|
| 18 |
+
HARD=(); add_hard(){ HARD+=("$1"); }
|
| 19 |
+
correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true
|
| 20 |
+
baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true
|
| 21 |
+
expected_cases=12; actual_cases=0
|
| 22 |
+
speedup=1.0; ref_speedup=1.0; hw="unknown"
|
| 23 |
+
|
| 24 |
+
cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; }
|
| 25 |
+
|
| 26 |
+
if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then
|
| 27 |
+
# reviewer-only mode: reset the working tree to the frozen baseline so several
|
| 28 |
+
# modes running back-to-back in one container session each start clean. candidate/noop
|
| 29 |
+
# NEVER resets (this branch is skipped for them), so a solver session is untouched.
|
| 30 |
+
git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
|
| 31 |
+
git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"
|
| 32 |
+
fi
|
| 33 |
+
if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then
|
| 34 |
+
git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
|
| 35 |
+
git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true
|
| 36 |
+
fi
|
| 37 |
+
|
| 38 |
+
# anti-cheat: only streamed_apply.py may change
|
| 39 |
+
git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt"
|
| 40 |
+
while IFS= read -r f; do
|
| 41 |
+
[ -z "$f" ] && continue
|
| 42 |
+
case "$f" in
|
| 43 |
+
streamed_apply.py) : ;;
|
| 44 |
+
*__pycache__*) : ;;
|
| 45 |
+
*) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;;
|
| 46 |
+
esac
|
| 47 |
+
done < "$LOG/anti_cheat_changed_files.txt"
|
| 48 |
+
|
| 49 |
+
# anti-cheat: framework auto-overlap / graph-capture conveniences are forbidden in the
|
| 50 |
+
# candidate file (the overlap must be built explicitly with streams + events). The
|
| 51 |
+
# candidate symbol is `streamed_chunk_apply` so these patterns never self-match; explicit
|
| 52 |
+
# torch.cuda.Stream / Event / pinned / non_blocking copies are the intended tool and pass.
|
| 53 |
+
if [ -f "$CAND_FILE" ] && grep -Eq "CUDAGraph|make_graphed_callables|cuda\.graph" "$CAND_FILE"; then
|
| 54 |
+
anti_cheat_ok=false; add_hard "forbidden_overlap_helper"
|
| 55 |
+
fi
|
| 56 |
+
|
| 57 |
+
# trusted restore: hidden suite ships in tests/ payload (fresh at scoring)
|
| 58 |
+
for f in test_streamed_apply.py gpu_bench.py kb_overlap_harness.py; do
|
| 59 |
+
[ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; }
|
| 60 |
+
done
|
| 61 |
+
|
| 62 |
+
# ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild)
|
| 63 |
+
if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then
|
| 64 |
+
ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt")
|
| 65 |
+
elif [ -f /opt/verifier-correctness-manifest.json ]; then
|
| 66 |
+
ref_speedup=$(python3 -c "import json;print(json.load(open('/opt/verifier-correctness-manifest.json')).get('ref_speedup',1.0))" 2>/dev/null || echo 1.0)
|
| 67 |
+
fi
|
| 68 |
+
hw=$(python3 -c "import torch;print(torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'no_cuda')" 2>/dev/null || echo unknown)
|
| 69 |
+
|
| 70 |
+
# correctness gate (needs CUDA)
|
| 71 |
+
if [ "$correctness_ok" = true ]; then
|
| 72 |
+
( cd "$TESTS_DIR" && python3 test_streamed_apply.py ) > "$LOG/correctness.log" 2>&1
|
| 73 |
+
crc=$?
|
| 74 |
+
actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0}
|
| 75 |
+
if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then
|
| 76 |
+
hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed"
|
| 77 |
+
fi
|
| 78 |
+
fi
|
| 79 |
+
|
| 80 |
+
# timing: median speedup over 3 runs (only if correct)
|
| 81 |
+
if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then
|
| 82 |
+
: > "$LOG/bench.log"
|
| 83 |
+
sp_list=""
|
| 84 |
+
for r in 1 2 3; do
|
| 85 |
+
line=$( cd "$TESTS_DIR" && python3 gpu_bench.py 2>>"$LOG/bench.log" )
|
| 86 |
+
echo "$line" >> "$LOG/bench.log"
|
| 87 |
+
sp=$(echo "$line" | sed -n 's/.*speedup=\([0-9.-]*\).*/\1/p')
|
| 88 |
+
[ -n "$sp" ] && sp_list="$sp_list $sp"
|
| 89 |
+
done
|
| 90 |
+
speedup=$(python3 -c "v=sorted(float(x) for x in '$sp_list'.split());print(f'{v[len(v)//2]:.5f}' if v else '-1')")
|
| 91 |
+
if [ -z "$sp_list" ] || python3 -c "import sys;sys.exit(0 if float('$speedup')<=0 else 1)"; then
|
| 92 |
+
benchmark_ok=false; add_hard "benchmark_execution_failed"
|
| 93 |
+
fi
|
| 94 |
+
else
|
| 95 |
+
benchmark_ok=false
|
| 96 |
+
fi
|
| 97 |
+
|
| 98 |
+
HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi
|
| 99 |
+
DIAG_TAIL=""
|
| 100 |
+
if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then
|
| 101 |
+
DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g')
|
| 102 |
+
fi
|
| 103 |
+
cat > "$LOG/verifier_state.json" <<JSON
|
| 104 |
+
{"schema_version":"kernelbench_verifier_state_v1","task_kind":"acceleration",
|
| 105 |
+
"correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,
|
| 106 |
+
"hidden_correctness_ok":$hidden_correctness_ok,"baseline_ok":$baseline_ok,
|
| 107 |
+
"benchmark_ok":$benchmark_ok,"anti_cheat_ok":$anti_cheat_ok,
|
| 108 |
+
"hard_fail_reasons":$HARD_JSON,
|
| 109 |
+
"expected_case_count":$expected_cases,"actual_case_count":$actual_cases,
|
| 110 |
+
"expected_benchmark_count":1,"actual_benchmark_count":1,
|
| 111 |
+
"actual_hardware_type":"$hw","mode":"$MODE",
|
| 112 |
+
"work_evidence_notes":["h2d-prefetch-overlap suite $actual_cases/$expected_cases ok","median wall-time speedup=$speedup on $hw","correctness_tail:${DIAG_TAIL}"]}
|
| 113 |
+
JSON
|
| 114 |
+
cat > "$LOG/correctness_results.json" <<JSON
|
| 115 |
+
{"schema_version":"kernelbench_correctness_results_v1",
|
| 116 |
+
"suites":[{"name":"hidden-h2d-prefetch-overlap-suite","visibility_class":"hidden_supplement","expected_case_count":$expected_cases,"actual_case_count":$actual_cases,"passed":$actual_cases,"failed":$((expected_cases-actual_cases)),"hard_fail_reasons":$HARD_JSON}],
|
| 117 |
+
"correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,"hidden_correctness_ok":$hidden_correctness_ok}
|
| 118 |
+
JSON
|
| 119 |
+
cat > "$LOG/benchmark_results.json" <<JSON
|
| 120 |
+
{"schema_version":"kernelbench_benchmark_results_v1","task_kind":"acceleration","metric":"wall_time_ms",
|
| 121 |
+
"direction":"higher_is_better",
|
| 122 |
+
"workloads":[{"name":"h2d-prefetch-overlap-geomean-4configs","speedup":$speedup,"completion_counters":{"cases":"$actual_cases/$expected_cases"}}],
|
| 123 |
+
"aggregate_speedup":$speedup,"ref_speedup":$ref_speedup,"actual_hardware_type":"$hw"}
|
| 124 |
+
JSON
|
| 125 |
+
python3 "$TESTS_DIR/compute_reward.py" 2>/dev/null || python3 /tests/compute_reward.py 2>/dev/null || true
|
| 126 |
+
REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null)
|
| 127 |
+
echo "MODE=$MODE cases=$actual_cases/$expected_cases speedup=$speedup ref=$ref_speedup hw=$hw reward=$REW"
|
| 128 |
+
[ -n "$REW" ] && exit 0 || exit 1
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/.dockerignore
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does
|
| 2 |
+
# NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile .
|
| 3 |
+
# The reference implementation and every authoring artefact MUST NOT reach an image layer.
|
| 4 |
+
*.patch
|
| 5 |
+
oracle*
|
| 6 |
+
negative*
|
| 7 |
+
baseline2*
|
| 8 |
+
scope_card.json
|
| 9 |
+
degradation_manifest.json
|
| 10 |
+
task_meta.json
|
| 11 |
+
loop_map_entry.json
|
| 12 |
+
job.yaml
|
| 13 |
+
intermediates/
|
| 14 |
+
_retrofit*
|
| 15 |
+
sr_validate*
|
| 16 |
+
leak_audit/
|
| 17 |
+
self_check/
|
| 18 |
+
variants/
|
| 19 |
+
**/__pycache__/
|
| 20 |
+
**/*.pyc
|
| 21 |
+
*.bak
|
| 22 |
+
*.bak_*
|
| 23 |
+
*.pre_*
|
| 24 |
+
**/*.pre_*
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/Dockerfile
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# wro-deepspeed-curriculum-cluster-select-loop16 — OPEN-SOURCE, self-contained task image
|
| 4 |
+
#
|
| 5 |
+
# Task: make the declared scope faster while preserving its observable behaviour exactly.
|
| 6 |
+
# Editable scope (the ONLY files the scope gate allows to change):
|
| 7 |
+
## (declared in tests/test.sh)
|
| 8 |
+
#
|
| 9 |
+
# FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image.
|
| 10 |
+
# CPU ONLY — task.toml declares gpus = 0.
|
| 11 |
+
# Platform: linux/amd64 or arm64.
|
| 12 |
+
# Build context = this task directory (the Dockerfile lives in environment/).
|
| 13 |
+
#
|
| 14 |
+
# PROVENANCE of environment/repo/ (so anyone can re-derive it independently)
|
| 15 |
+
# recovered from: <internal registry>/kernelbench/wro-deepspeed-curriculum-cluster-select-loop16:v1@sha256:a544e9d3a324523f6d852c174c92b6ae1ebe40c5accb62e0bdab1658c3ae3603
|
| 16 |
+
# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in
|
| 17 |
+
# manifest order; .git and any .wh..wh..opq marker dropped.
|
| 18 |
+
# verification: `git apply --check -p1 oracle.patch` succeeds against these bytes and `-R` does NOT — i.e. this tree is the exact carved baseline the reference patch was generated against.
|
| 19 |
+
##
|
| 20 |
+
# -----------------------------------------------------------------------------
|
| 21 |
+
# BUILD (needs outbound network for PyPI only — the working tree ships in this package)
|
| 22 |
+
# cd <...>/wro-deepspeed-curriculum-cluster-select-loop16/task
|
| 23 |
+
# docker build -f environment/Dockerfile -t fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss .
|
| 24 |
+
#
|
| 25 |
+
# RUN docker run --rm -it fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss
|
| 26 |
+
# SCORE docker run --rm -v "$PWD/tests:/tests:ro" fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss bash /tests/test.sh
|
| 27 |
+
# # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative)
|
| 28 |
+
#
|
| 29 |
+
# 🔴 RE-CALIBRATE THE ANCHOR ON YOUR HARDWARE
|
| 30 |
+
# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; ref_speedup = 20.777027 .
|
| 31 |
+
# tests/test.sh resolves it from tests/ref_speedup.txt FIRST, then falls back to
|
| 32 |
+
# /opt/verifier-correctness-manifest.json, then to 1.0 (which would make every reward 0).
|
| 33 |
+
# The value was calibrated on the authoring CPU lane (Intel Sapphire Rapids). The verifier supports mode dispatch natively, so
|
| 34 |
+
# re-measuring is ONE command (the reference patch is passed BY PATH and never baked):
|
| 35 |
+
# docker run --rm -v "$PWD/tests:/tests:ro" -v "<dir holding oracle.patch>:/patches:ro" \
|
| 36 |
+
# -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \
|
| 37 |
+
# fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss bash /tests/test.sh
|
| 38 |
+
# then write the measured speedup into tests/ref_speedup.txt. See tests/ref_speedup.caveat.md.
|
| 39 |
+
# Sanity: noop (no patch) ~= 1.0 -> gated to 0; negative MUST score 0.
|
| 40 |
+
#
|
| 41 |
+
# VERSION ANCHORS
|
| 42 |
+
# Python 3.11 · standard library + numpy
|
| 43 |
+
# The original private base declared torch 2.5.1 / triton 3.1.0 and the task overlay then ran
|
| 44 |
+
# `pip install torch==2.7.0` — 2.7.0 is therefore the version the anchor was calibrated under.
|
| 45 |
+
# =============================================================================
|
| 46 |
+
FROM python:3.11-slim-bookworm
|
| 47 |
+
|
| 48 |
+
ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \
|
| 49 |
+
PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1
|
| 50 |
+
|
| 51 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 52 |
+
build-essential git ca-certificates curl procps coreutils tar gzip vim less file jq \
|
| 53 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 54 |
+
|
| 55 |
+
# ---- venv at this EXACT path: tests/test.sh puts /opt/kernelbench-venv/bin at the head of PATH. ----
|
| 56 |
+
ENV VENV=/opt/kernelbench-venv
|
| 57 |
+
RUN python3 -m venv "$VENV"
|
| 58 |
+
ENV PATH=$VENV/bin:$PATH
|
| 59 |
+
RUN pip install --no-cache-dir -U pip setuptools wheel
|
| 60 |
+
RUN pip install --no-cache-dir "numpy>=1.26,<3"
|
| 61 |
+
|
| 62 |
+
# ---- the graded working tree. A REAL directory (not a symlink): the scope gate runs
|
| 63 |
+
# `git -C /app/repo status --porcelain`, which cannot see through a symlink. ----
|
| 64 |
+
RUN mkdir -p /app/repo /app/.timer /app/workspace /logs/verifier /logs/agent /logs/artifacts
|
| 65 |
+
COPY environment/repo/ /app/repo/
|
| 66 |
+
COPY instruction.md /app/instruction.md
|
| 67 |
+
|
| 68 |
+
# ---- the baseline commit = the diff base the scope gate compares against.
|
| 69 |
+
# 🔴 core.fileMode=false is LOAD-BEARING, not hygiene: a shipped image in this corpus had
|
| 70 |
+
# core.fileMode=true while some files were 0775 on disk but 100644 in the index, so
|
| 71 |
+
# `git status --porcelain` reported phantom out-of-scope paths in EVERY mode and forced
|
| 72 |
+
# reward to 0. Setting it false at creation makes that class of defect impossible. ----
|
| 73 |
+
RUN git config --global user.email "reviewer@fai-bench.local" \
|
| 74 |
+
&& git config --global user.name "fai-bench" \
|
| 75 |
+
&& git config --global init.defaultBranch main \
|
| 76 |
+
&& git config --global --add safe.directory /app/repo \
|
| 77 |
+
&& cd /app/repo \
|
| 78 |
+
&& git init -q \
|
| 79 |
+
&& git config core.fileMode false \
|
| 80 |
+
&& printf '__pycache__/\n*.pyc\n' >> .gitignore \
|
| 81 |
+
&& git add -A \
|
| 82 |
+
&& git commit -qm "carved baseline (graded starting point)" \
|
| 83 |
+
&& rm -rf .git/logs \
|
| 84 |
+
&& test "$(git rev-list --count HEAD)" = "1" \
|
| 85 |
+
&& test -z "$(git remote)" \
|
| 86 |
+
&& test "$(git config --get core.fileMode)" = "false" \
|
| 87 |
+
&& test -z "$(git status --porcelain)" \
|
| 88 |
+
&& echo "[build] /app/repo: 1 commit, no remote, fileMode=false, clean tree"
|
| 89 |
+
|
| 90 |
+
# ---- runtime contract (copied verbatim from the shipped image) ----
|
| 91 |
+
COPY environment/runtime/entrypoint.sh /app/entrypoint.sh
|
| 92 |
+
COPY environment/runtime/timer.sh /app/timer.sh
|
| 93 |
+
RUN chmod 0755 /app/entrypoint.sh /app/timer.sh && chown root:root /app/entrypoint.sh /app/timer.sh
|
| 94 |
+
COPY environment/runtime/run_dev_bench.sh /app/workspace/run_dev_bench.sh
|
| 95 |
+
RUN chmod 0755 /app/workspace/run_dev_bench.sh
|
| 96 |
+
COPY environment/loop/ /opt/loop/
|
| 97 |
+
RUN if [ -f /opt/loop/submit.sh ]; then chmod 0755 /opt/loop/submit.sh; fi \
|
| 98 |
+
&& chown -R root:root /opt/loop \
|
| 99 |
+
&& if [ -f /opt/loop/score_engine.sh ]; then chmod 0700 /opt/loop/score_engine.sh; fi \
|
| 100 |
+
&& if [ -f /opt/loop/sanitize_feedback.py ]; then chmod 0700 /opt/loop/sanitize_feedback.py; fi \
|
| 101 |
+
&& if [ -d /opt/loop/private ]; then chmod -R go-rwx /opt/loop/private; fi
|
| 102 |
+
|
| 103 |
+
# ---- OPEN grading suite is NOT baked: tests/ (test.sh + compute_reward.py + the workload/harness
|
| 104 |
+
# + ref_speedup.txt) is MOUNTED FRESH at /tests when scoring. It ships in this package —
|
| 105 |
+
# open-source, but outside the image so the graded harness cannot be edited from the session.
|
| 106 |
+
|
| 107 |
+
# ---- 🔴 ANTI-LEAK ASSERTS ----
|
| 108 |
+
RUN set -eu; rc=0; \
|
| 109 |
+
hits="$(find / -xdev -type f \( -name 'oracle*.patch' -o -name 'negative*.patch' \
|
| 110 |
+
-o -name 'baseline2*.patch' -o -name 'scope_card.json' -o -name 'kernel_oracle.py' \
|
| 111 |
+
-o -name 'degradation_manifest.json' \) 2>/dev/null | head -10)"; \
|
| 112 |
+
if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: a reference/authoring file is baked:"; echo "$hits"; rc=1; fi; \
|
| 113 |
+
for p in /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling /tests; do \
|
| 114 |
+
if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path baked: $p"; rc=1; fi; \
|
| 115 |
+
done; \
|
| 116 |
+
test "$rc" = 0; \
|
| 117 |
+
echo "[build] ANTI-LEAK ASSERTS PASS"
|
| 118 |
+
|
| 119 |
+
ENV PYTHONPATH=/app/repo \
|
| 120 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 121 |
+
OMP_NUM_THREADS=1 \
|
| 122 |
+
MKL_NUM_THREADS=1 \
|
| 123 |
+
OPENBLAS_NUM_THREADS=1
|
| 124 |
+
WORKDIR /app/repo
|
| 125 |
+
|
| 126 |
+
# ---- build-time smoke: the graded module imports FROM /app/repo (the verifier asserts the same
|
| 127 |
+
# thing at scoring time via its import-origin gate) and the scope files are present. ----
|
| 128 |
+
RUN python - <<'PY'
|
| 129 |
+
import os, subprocess, sys
|
| 130 |
+
sys.path.insert(0, "/app/repo")
|
| 131 |
+
for f in ('curriculum_cluster.py',):
|
| 132 |
+
p = os.path.join("/app/repo", f)
|
| 133 |
+
assert os.path.isfile(p), f"scope file missing: {p}"
|
| 134 |
+
print("scope file present:", f, os.path.getsize(p), "B")
|
| 135 |
+
import importlib.util
|
| 136 |
+
for _mod in ('curriculum_cluster',):
|
| 137 |
+
try:
|
| 138 |
+
_spec = importlib.util.find_spec(_mod)
|
| 139 |
+
except Exception as _e:
|
| 140 |
+
print("NOTE: import-origin probe skipped for", _mod, "->", repr(_e),
|
| 141 |
+
"(tests/test.sh re-asserts this at scoring time)")
|
| 142 |
+
continue
|
| 143 |
+
_loc = (getattr(_spec, "origin", "") or "") if _spec else ""
|
| 144 |
+
print("resolves:", _mod, "->", _loc or "<not found>")
|
| 145 |
+
assert not _loc or _loc.startswith("/app/repo"), \
|
| 146 |
+
f"{_mod} resolves OUTSIDE the graded tree: {_loc}"
|
| 147 |
+
n = subprocess.run(["git","-C","/app/repo","rev-list","--count","HEAD"],
|
| 148 |
+
capture_output=True, text=True).stdout.strip()
|
| 149 |
+
assert n == "1", f"git diff base broken (commits={n!r})"
|
| 150 |
+
print("OK: scope files, import origin and git base all in place")
|
| 151 |
+
PY
|
| 152 |
+
|
| 153 |
+
ENTRYPOINT ["/app/entrypoint.sh"]
|
| 154 |
+
CMD ["tail","-f","/dev/null"]
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/manifest.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"max_submissions": 1,
|
| 3 |
+
"min_submissions": 1,
|
| 4 |
+
"note": "dev reward is an in-session proxy; the runner end-of-session /tests score is authoritative.",
|
| 5 |
+
"perf_metric": "speedup",
|
| 6 |
+
"reward_form": "raw_speedup(base_ms/cand_ms); no-op ~= 1.0",
|
| 7 |
+
"schema_version": "kernelbench_loop_manifest_v1",
|
| 8 |
+
"scope": [
|
| 9 |
+
"curriculum_cluster.py"
|
| 10 |
+
],
|
| 11 |
+
"scoring": "task tests/test.sh in candidate mode on the live /app/repo",
|
| 12 |
+
"task_id": "wro-deepspeed-curriculum-cluster-select-loop16"
|
| 13 |
+
}
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/compute_reward.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""compute_reward for wro-deepspeed-curriculum-cluster-select.
|
| 3 |
+
reward = baseline_ms / candidate_ms (wall-clock speedup; noop ~ 1.0), gated by
|
| 4 |
+
correctness in test.sh (wrong selected sample-ids -> reward 0 there). Records
|
| 5 |
+
vs_oracle_ratio as metadata only."""
|
| 6 |
+
import json
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load(path):
|
| 11 |
+
for line in open(path):
|
| 12 |
+
if line.startswith("WRO_CURRIC_RESULT "):
|
| 13 |
+
return json.loads(line[len("WRO_CURRIC_RESULT "):])
|
| 14 |
+
raise SystemExit(f"no WRO_CURRIC_RESULT in {path}")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
cand = load(sys.argv[1]); base = load(sys.argv[2])
|
| 19 |
+
ref = float(sys.argv[3]) if len(sys.argv) > 3 else None
|
| 20 |
+
cm = cand.get("timing_ms", -1); bm = base.get("timing_ms", -1)
|
| 21 |
+
speedup = (bm / cm) if (cm and cm > 0 and bm > 0) else 0.0
|
| 22 |
+
out = {"reward": round(speedup, 6), "baseline_ms": bm, "candidate_ms": cm,
|
| 23 |
+
"speedup": round(speedup, 6)}
|
| 24 |
+
if ref:
|
| 25 |
+
out["metadata"] = {"vs_oracle_ratio": round(speedup / ref, 4), "ref_speedup": ref}
|
| 26 |
+
print(json.dumps(out))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
main()
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/test.sh
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Verifier for wro-deepspeed-curriculum-cluster-select (curriculum-learning
|
| 3 |
+
# difficulty-cluster selection for large-scale training stability).
|
| 4 |
+
# ACCELERATION, CPU (host logic; no GPU).
|
| 5 |
+
# Scope = curriculum_cluster.py (select_curriculum_cluster).
|
| 6 |
+
# Modes: candidate | noop | oracle | negative | baseline2.
|
| 7 |
+
# reward = raw wall speedup (base_ms/cand_ms); noop ~ 1.0 (degraded vs itself);
|
| 8 |
+
# oracle >> 1 (vectorized boundary-search selection vs O(rows^2) per-row Python
|
| 9 |
+
# concatenate); baseline2 in between (block-buffered concat, still row-walked);
|
| 10 |
+
# negative = 0 (whole-row shortcut mis-selects the partial boundary rows).
|
| 11 |
+
set -uo pipefail
|
| 12 |
+
export PATH="/opt/kernelbench-venv/bin:/opt/venv/bin:/usr/local/bin:$PATH"
|
| 13 |
+
export PYTHONPATH="/app/repo:${PYTHONPATH:-}"
|
| 14 |
+
git config --global --add safe.directory '*' 2>/dev/null || true
|
| 15 |
+
TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 16 |
+
REPO=/app/repo
|
| 17 |
+
LOG=/logs/verifier; mkdir -p "$LOG"
|
| 18 |
+
MODE="${KERNELBENCH_VERIFY_MODE:-candidate}"
|
| 19 |
+
SCOPE=("curriculum_cluster.py")
|
| 20 |
+
|
| 21 |
+
HARD=(); add_hard(){ HARD+=("$1"); }
|
| 22 |
+
correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true
|
| 23 |
+
speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1
|
| 24 |
+
|
| 25 |
+
cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; }
|
| 26 |
+
|
| 27 |
+
# ---- apply oracle / baseline2 / negative patch by mode (candidate & noop: no patch) ----
|
| 28 |
+
if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then
|
| 29 |
+
git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"; fi
|
| 30 |
+
if [ "$MODE" = "baseline2" ] && [ -n "${KERNELBENCH_BASELINE2_PATCH:-}" ]; then
|
| 31 |
+
git -C "$REPO" apply -p1 "$KERNELBENCH_BASELINE2_PATCH" 2>"$LOG/baseline2_apply.log" || add_hard "baseline2_apply_failed"; fi
|
| 32 |
+
if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then
|
| 33 |
+
git -C "$REPO" apply -p1 "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true; fi
|
| 34 |
+
|
| 35 |
+
# ---- (1) scope-diff HARD GATE: only the scope file may change in /app/repo ----
|
| 36 |
+
git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt"
|
| 37 |
+
while IFS= read -r f; do
|
| 38 |
+
[ -z "$f" ] && continue
|
| 39 |
+
keep=false
|
| 40 |
+
for s in "${SCOPE[@]}"; do [ "$f" = "$s" ] && keep=true; done
|
| 41 |
+
case "$f" in *__pycache__*|*.pyc) keep=true;; esac
|
| 42 |
+
[ "$keep" = true ] || { scope_ok=false; add_hard "out_of_scope_edit:$f"; }
|
| 43 |
+
done < "$LOG/changed_files.txt"
|
| 44 |
+
|
| 45 |
+
# ---- (2) import-origin assert: the scope module resolves to the baked /app/repo tree ----
|
| 46 |
+
python3 - > "$LOG/import_origin.log" 2>&1 <<'PY'
|
| 47 |
+
import os, sys
|
| 48 |
+
sys.path.insert(0, "/app/repo")
|
| 49 |
+
import curriculum_cluster as m
|
| 50 |
+
loc = os.path.realpath(m.__file__)
|
| 51 |
+
print("SCOPE_LOC", loc)
|
| 52 |
+
sys.exit(0 if loc.startswith("/app/repo") else 3)
|
| 53 |
+
PY
|
| 54 |
+
[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; }
|
| 55 |
+
|
| 56 |
+
# ---- (3) trusted-restore: harness uploaded fresh (never baked) ----
|
| 57 |
+
for f in workload.py compute_reward.py; do
|
| 58 |
+
[ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; }
|
| 59 |
+
done
|
| 60 |
+
|
| 61 |
+
# ---- ref_speedup (oracle-calibrated; metadata only) ----
|
| 62 |
+
[ -f /opt/verifier-correctness-manifest.json ] && \
|
| 63 |
+
ref_speedup=$(python3 -c "import json;print(json.load(open('/opt/verifier-correctness-manifest.json')).get('ref_speedup',1.0))" 2>/dev/null || echo 1.0)
|
| 64 |
+
|
| 65 |
+
# ---- (4) CORRECTNESS GATE: scope output must match the independent reference ----
|
| 66 |
+
if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then
|
| 67 |
+
( cd "$TESTS_DIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1
|
| 68 |
+
cok=$(grep WRO_CURRIC_RESULT "$LOG/correctness.out" | python3 -c "import json,sys
|
| 69 |
+
try: print(json.loads(sys.stdin.read().split('WRO_CURRIC_RESULT ',1)[1]).get('correctness_ok'))
|
| 70 |
+
except Exception: print('False')" 2>/dev/null || echo False)
|
| 71 |
+
if [ "$cok" != "True" ]; then correctness_ok=false; add_hard "correctness_failed"; fi
|
| 72 |
+
fi
|
| 73 |
+
|
| 74 |
+
# ---- (5) TIMING: candidate wall + baseline (frozen degraded tree at HEAD) ----
|
| 75 |
+
if [ "$correctness_ok" = true ] && { [ "${#HARD[@]}" -eq 0 ] || [ -z "${HARD[*]:-}" ]; }; then
|
| 76 |
+
( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed"
|
| 77 |
+
cand_ms=$(grep WRO_CURRIC_RESULT "$LOG/cand_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_CURRIC_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1)
|
| 78 |
+
cp "$REPO/${SCOPE[0]}" /tmp/wro_cand_scope.py 2>/dev/null || true
|
| 79 |
+
git -C "$REPO" checkout -q HEAD -- "${SCOPE[@]}" 2>/dev/null || true
|
| 80 |
+
( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/base_timing.out" 2>&1 || add_hard "baseline_timing_failed"
|
| 81 |
+
base_ms=$(grep WRO_CURRIC_RESULT "$LOG/base_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_CURRIC_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1)
|
| 82 |
+
cp /tmp/wro_cand_scope.py "$REPO/${SCOPE[0]}" 2>/dev/null || true
|
| 83 |
+
if [ "$(python3 -c "print(1 if $cand_ms>0 and $base_ms>0 else 0)")" = "1" ]; then
|
| 84 |
+
speedup=$(python3 -c "print(round($base_ms/$cand_ms,6))")
|
| 85 |
+
else benchmark_ok=false; add_hard "timing_invalid"; fi
|
| 86 |
+
fi
|
| 87 |
+
|
| 88 |
+
# ---- verdict ----
|
| 89 |
+
reward=0.0
|
| 90 |
+
nhard="${#HARD[@]}"
|
| 91 |
+
if [ "$nhard" -eq 0 ] && [ "$correctness_ok" = true ]; then reward="$speedup"; fi
|
| 92 |
+
hard_str=""; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}"
|
| 93 |
+
export WRO_MODE="$MODE" WRO_REWARD="$reward" WRO_SPEEDUP="$speedup" \
|
| 94 |
+
WRO_BASE_MS="$base_ms" WRO_CAND_MS="$cand_ms" WRO_REF="$ref_speedup" \
|
| 95 |
+
WRO_HARD="$hard_str" WRO_SCOPE="$scope_ok" WRO_IMP="$import_origin_ok" \
|
| 96 |
+
WRO_CORR="$correctness_ok" WRO_BENCH="$benchmark_ok"
|
| 97 |
+
python3 - > "$LOG/reward.json" <<'PY'
|
| 98 |
+
import os, json
|
| 99 |
+
def f(x):
|
| 100 |
+
try: return float(x)
|
| 101 |
+
except: return -1.0
|
| 102 |
+
ref = f(os.environ.get("WRO_REF", "1")); sp = f(os.environ.get("WRO_SPEEDUP", "0"))
|
| 103 |
+
v = {
|
| 104 |
+
"mode": os.environ.get("WRO_MODE"),
|
| 105 |
+
"reward": f(os.environ.get("WRO_REWARD")),
|
| 106 |
+
"speedup": sp,
|
| 107 |
+
"baseline_ms": f(os.environ.get("WRO_BASE_MS")),
|
| 108 |
+
"candidate_ms": f(os.environ.get("WRO_CAND_MS")),
|
| 109 |
+
"ref_speedup": ref,
|
| 110 |
+
"metadata": {"vs_oracle_ratio": (sp/ref) if ref > 0 else None},
|
| 111 |
+
"hard_fails": os.environ.get("WRO_HARD", "").split(),
|
| 112 |
+
"gates": {"scope_ok": os.environ.get("WRO_SCOPE") == "true",
|
| 113 |
+
"import_origin_ok": os.environ.get("WRO_IMP") == "true",
|
| 114 |
+
"correctness_ok": os.environ.get("WRO_CORR") == "true",
|
| 115 |
+
"benchmark_ok": os.environ.get("WRO_BENCH") == "true"}}
|
| 116 |
+
print(json.dumps(v))
|
| 117 |
+
PY
|
| 118 |
+
cat "$LOG/reward.json"
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/workload.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Standalone verifier workload for the curriculum difficulty-cluster subsystem
|
| 3 |
+
(scope: /app/repo/curriculum_cluster.py :: select_curriculum_cluster).
|
| 4 |
+
|
| 5 |
+
Drives the scope function on CPU (no torch, no GPU): given per-difficulty-row
|
| 6 |
+
sample-id buckets + row metric values, it selects the flat cluster of sample-ids for
|
| 7 |
+
a curriculum difficulty window, in VALUE mode (metric window) and PERCENTILE mode
|
| 8 |
+
(equal-count percentile band with partial boundary-row slicing).
|
| 9 |
+
|
| 10 |
+
correctness : compare the scope's output against an INDEPENDENT reference computed
|
| 11 |
+
here (NOT in the editable scope) for BOTH modes. The percentile case
|
| 12 |
+
is built with a non-aligned window so the two boundary rows must be
|
| 13 |
+
sliced PARTIALLY -- a whole-row shortcut selects the wrong sample-ids.
|
| 14 |
+
timing : warmup + timed repeats over a large row set with a wide percentile
|
| 15 |
+
window, so the naive per-row growing concatenate dominates and
|
| 16 |
+
separates from a vectorized boundary-search selection. The gap GROWS
|
| 17 |
+
with the number of rows.
|
| 18 |
+
|
| 19 |
+
Emits one line ``WRO_CURRIC_RESULT {json}``. Timing uses process_time (CPU time) so
|
| 20 |
+
the reward band is robust to OS descheduling under fleet load.
|
| 21 |
+
"""
|
| 22 |
+
import json
|
| 23 |
+
import statistics
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
REPO = "/app/repo"
|
| 30 |
+
if REPO not in sys.path:
|
| 31 |
+
sys.path.insert(0, REPO)
|
| 32 |
+
|
| 33 |
+
# correctness: modest rows; percentile window deliberately non-bin-aligned.
|
| 34 |
+
C_SEED = 11
|
| 35 |
+
C_ROWS = 240
|
| 36 |
+
C_BINS = 20
|
| 37 |
+
C_PS = 3
|
| 38 |
+
C_PE = 17
|
| 39 |
+
# timing: many rows + wide percentile window so the naive per-row concat dominates.
|
| 40 |
+
T_SEED = 4
|
| 41 |
+
T_ROWS = 12000
|
| 42 |
+
T_BINS = 100
|
| 43 |
+
T_PS = 5
|
| 44 |
+
T_PE = 95
|
| 45 |
+
WARMUP = 1
|
| 46 |
+
ITERS = 3
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_scope():
|
| 50 |
+
import curriculum_cluster as m
|
| 51 |
+
return m
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _gen(n_rows, seed, max_metric, min_k, max_k):
|
| 55 |
+
rng = np.random.default_rng(seed)
|
| 56 |
+
metric = np.sort(rng.integers(0, max_metric, size=n_rows)).astype(np.float64)
|
| 57 |
+
idx_to_sample = []
|
| 58 |
+
sid = 0
|
| 59 |
+
for _ in range(n_rows):
|
| 60 |
+
k = int(rng.integers(min_k, max_k))
|
| 61 |
+
idx_to_sample.append(np.arange(sid, sid + k, dtype=np.int64))
|
| 62 |
+
sid += k
|
| 63 |
+
return idx_to_sample, metric
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _ref_value(index_to_sample, metric, lo, hi):
|
| 67 |
+
new = None
|
| 68 |
+
for row in range(len(index_to_sample)):
|
| 69 |
+
if metric[row] <= hi and metric[row] > lo:
|
| 70 |
+
rs = np.copy(np.asarray(index_to_sample[row]))
|
| 71 |
+
new = rs if new is None else np.concatenate((new, rs), axis=None)
|
| 72 |
+
return np.array([], dtype=np.int64) if new is None else new.astype(np.int64)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _ref_percentile(index_to_sample, metric, lo, hi, num_bins):
|
| 76 |
+
one_epoch = sum(len(x) for x in index_to_sample)
|
| 77 |
+
per = one_epoch // num_bins
|
| 78 |
+
start_count = per * lo
|
| 79 |
+
end_count = one_epoch if hi == num_bins else per * hi
|
| 80 |
+
new = None
|
| 81 |
+
cur = 0
|
| 82 |
+
for row in range(len(index_to_sample)):
|
| 83 |
+
rsz = len(index_to_sample[row])
|
| 84 |
+
if cur + rsz > start_count:
|
| 85 |
+
rstart = max(0, start_count - cur)
|
| 86 |
+
rend = rsz if cur + rsz <= end_count else end_count - cur
|
| 87 |
+
rs = np.copy(np.asarray(index_to_sample[row])[rstart:rend])
|
| 88 |
+
new = rs if new is None else np.concatenate((new, rs), axis=None)
|
| 89 |
+
cur += rsz
|
| 90 |
+
if cur >= end_count:
|
| 91 |
+
break
|
| 92 |
+
return np.array([], dtype=np.int64) if new is None else new.astype(np.int64)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _eq(a, b):
|
| 96 |
+
a = np.asarray(a, dtype=np.int64)
|
| 97 |
+
b = np.asarray(b, dtype=np.int64)
|
| 98 |
+
return a.shape == b.shape and bool(np.array_equal(a, b))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _correctness_case(m):
|
| 102 |
+
idx, metric = _gen(C_ROWS, C_SEED, 600, 2, 18)
|
| 103 |
+
# VALUE mode over a mid metric window.
|
| 104 |
+
v_lo, v_hi = 100.0, 400.0
|
| 105 |
+
got_v = m.select_curriculum_cluster(idx, metric, "value", v_lo, v_hi)
|
| 106 |
+
ref_v = _ref_value(idx, metric, v_lo, v_hi)
|
| 107 |
+
value_ok = _eq(got_v, ref_v)
|
| 108 |
+
# PERCENTILE mode, non-aligned window -> partial boundary rows.
|
| 109 |
+
got_p = m.select_curriculum_cluster(idx, metric, "percentile", C_PS, C_PE, num_bins=C_BINS)
|
| 110 |
+
ref_p = _ref_percentile(idx, metric, C_PS, C_PE, C_BINS)
|
| 111 |
+
pct_ok = _eq(got_p, ref_p)
|
| 112 |
+
# nontrivial: the percentile window must actually slice boundary rows partially
|
| 113 |
+
# (else a whole-row shortcut would coincide with the reference).
|
| 114 |
+
per = sum(len(x) for x in idx) // C_BINS
|
| 115 |
+
start_count = per * C_PS
|
| 116 |
+
cum = 0
|
| 117 |
+
partial_boundary = False
|
| 118 |
+
for row in range(len(idx)):
|
| 119 |
+
rsz = len(idx[row])
|
| 120 |
+
if cum < start_count < cum + rsz:
|
| 121 |
+
partial_boundary = True
|
| 122 |
+
break
|
| 123 |
+
cum += rsz
|
| 124 |
+
nontrivial = bool(partial_boundary and len(ref_p) > 0)
|
| 125 |
+
return {"correctness_ok": bool(value_ok and pct_ok),
|
| 126 |
+
"value_ok": bool(value_ok), "pct_ok": bool(pct_ok),
|
| 127 |
+
"ref_value_len": int(len(ref_v)), "ref_pct_len": int(len(ref_p)),
|
| 128 |
+
"nontrivial": nontrivial, "module": m.__file__}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _timing_case(m):
|
| 132 |
+
idx, metric = _gen(T_ROWS, T_SEED, T_ROWS, 1, 10)
|
| 133 |
+
|
| 134 |
+
def once():
|
| 135 |
+
m.select_curriculum_cluster(idx, metric, "percentile", T_PS, T_PE, num_bins=T_BINS)
|
| 136 |
+
|
| 137 |
+
for _ in range(WARMUP):
|
| 138 |
+
once()
|
| 139 |
+
ts = []
|
| 140 |
+
for _ in range(ITERS):
|
| 141 |
+
t0 = time.process_time()
|
| 142 |
+
once()
|
| 143 |
+
ts.append((time.process_time() - t0) * 1000.0)
|
| 144 |
+
return statistics.median(ts)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def main():
|
| 148 |
+
mode = sys.argv[1] if len(sys.argv) > 1 else "correctness"
|
| 149 |
+
m = load_scope()
|
| 150 |
+
if mode == "correctness":
|
| 151 |
+
res = _correctness_case(m)
|
| 152 |
+
res["mode"] = "correctness"
|
| 153 |
+
print("WRO_CURRIC_RESULT " + json.dumps(res))
|
| 154 |
+
sys.exit(0 if res["correctness_ok"] else 3)
|
| 155 |
+
elif mode == "timing":
|
| 156 |
+
ms = _timing_case(m)
|
| 157 |
+
print("WRO_CURRIC_RESULT " + json.dumps({
|
| 158 |
+
"mode": "timing", "timing_ms": ms, "iters": ITERS,
|
| 159 |
+
"rows": T_ROWS, "num_bins": T_BINS, "module": m.__file__}))
|
| 160 |
+
sys.exit(0)
|
| 161 |
+
else:
|
| 162 |
+
print("WRO_CURRIC_RESULT " + json.dumps({"error": "bad_mode"}))
|
| 163 |
+
sys.exit(2)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
main()
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/sanitize_feedback.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# ============================================================================
|
| 3 |
+
# wro loop16 finalizer — sanitize_feedback.py (REUSABLE, task-agnostic) 0700 root
|
| 4 |
+
# ============================================================================
|
| 5 |
+
"""Leak-free per-round feedback. Invoked ONLY by /opt/loop/submit.sh. Reads the
|
| 6 |
+
normalized DEV products under /logs/loop/dev/ and the loop accounting under
|
| 7 |
+
/logs/loop/, and prints ONLY a sanitized summary:
|
| 8 |
+
|
| 9 |
+
submission k/16
|
| 10 |
+
correctness: PASS | FAIL
|
| 11 |
+
[FAIL only] failing_invariant: <named, leak-free>
|
| 12 |
+
dev_speedup: <x>
|
| 13 |
+
dev_reward: <r>
|
| 14 |
+
best_so_far: submission <j>, dev_speedup <x>, dev_reward <r>
|
| 15 |
+
remaining: <16 - k>
|
| 16 |
+
finalize_allowed: <true|false>
|
| 17 |
+
[harness path] harness_error: <message> (candidate not at fault)
|
| 18 |
+
|
| 19 |
+
NEVER emits: verifier/test.sh/compute_reward contents; hidden workload
|
| 20 |
+
names/seeds/counts/shapes; any threshold; ref_speedup; absolute timings.
|
| 21 |
+
MAY emit: pass/fail; a named invariant; relative dev_speedup; dev_reward;
|
| 22 |
+
submission index; best-so-far; remaining budget; finalize_allowed.
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
import json
|
| 26 |
+
import sys
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
LOOP = Path("/logs/loop")
|
| 30 |
+
DEV = LOOP / "dev"
|
| 31 |
+
MIN_SUBMISSIONS = 3
|
| 32 |
+
MAX_SUBMISSIONS = 16
|
| 33 |
+
|
| 34 |
+
# Map a raw hard-fail reason (leak-free by construction) to a friendly, actionable
|
| 35 |
+
# invariant name. Reasons the wro verifier emits: out_of_scope_edit:<f>,
|
| 36 |
+
# import_origin_not_app_repo, correctness_trace_mismatch, timing_invalid,
|
| 37 |
+
# candidate_timing_failed, baseline_timing_failed, repo_missing,
|
| 38 |
+
# hidden_supplement_missing:<f>, oracle_apply_failed/baseline2_apply_failed.
|
| 39 |
+
_HINTS = {
|
| 40 |
+
"edit_scope": "your diff changed a file outside the declared editable scope — "
|
| 41 |
+
"keep edits to the in-scope product file(s) only",
|
| 42 |
+
"import_origin": "the module under test did not resolve to the in-repo tree — "
|
| 43 |
+
"do not shadow it with a copy elsewhere",
|
| 44 |
+
"correctness": "your output no longer matches the reference behavior exactly — "
|
| 45 |
+
"the change must be speed-only, behavior-identical",
|
| 46 |
+
"benchmark": "the timing run did not produce a valid measurement — check your "
|
| 47 |
+
"change does not crash or hang the benchmarked path",
|
| 48 |
+
"verifier_completed": "the check did not complete — re-check your last edit "
|
| 49 |
+
"did not cause an early crash",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _named_invariant(hard: list[str]) -> str:
|
| 54 |
+
h0 = (hard[0] if hard else "")
|
| 55 |
+
def startswith(*p): return any(any(x.startswith(pp) for pp in p) for x in hard)
|
| 56 |
+
if startswith("out_of_scope_edit", "forbidden_edit_path", "forbidden_source_reference"):
|
| 57 |
+
return f"edit_scope: {_HINTS['edit_scope']}"
|
| 58 |
+
if startswith("import_origin"):
|
| 59 |
+
return f"import_origin: {_HINTS['import_origin']}"
|
| 60 |
+
if startswith("correctness_trace_mismatch", "correctness_failed", "correctness"):
|
| 61 |
+
return f"output_matches_reference: {_HINTS['correctness']}"
|
| 62 |
+
if startswith("timing_invalid", "candidate_timing_failed", "baseline_timing_failed", "benchmark"):
|
| 63 |
+
return f"runs_without_error: {_HINTS['benchmark']}"
|
| 64 |
+
if h0:
|
| 65 |
+
return f"verifier_completed: {_HINTS['verifier_completed']}"
|
| 66 |
+
return f"verifier_completed: {_HINTS['verifier_completed']}"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _read_json(path: Path, default):
|
| 70 |
+
try:
|
| 71 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 72 |
+
except Exception:
|
| 73 |
+
return default
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _fmt(x, nd=4):
|
| 77 |
+
try:
|
| 78 |
+
return f"{float(x):.{nd}g}"
|
| 79 |
+
except Exception:
|
| 80 |
+
return str(x)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main() -> int:
|
| 84 |
+
try:
|
| 85 |
+
k = int((LOOP / "count").read_text(encoding="utf-8").strip())
|
| 86 |
+
except Exception:
|
| 87 |
+
k = 0
|
| 88 |
+
|
| 89 |
+
he = DEV / "harness_error.txt"
|
| 90 |
+
if he.exists():
|
| 91 |
+
try:
|
| 92 |
+
msg = he.read_text(encoding="utf-8").strip().splitlines()[0]
|
| 93 |
+
except Exception:
|
| 94 |
+
msg = "dev engine infrastructure error"
|
| 95 |
+
print(f"submission {k}/{MAX_SUBMISSIONS}")
|
| 96 |
+
print(f"harness_error: {msg} — this is NOT a defect in your code; do not "
|
| 97 |
+
f"debug the harness. Retry or continue optimizing (this attempt was "
|
| 98 |
+
f"not counted).")
|
| 99 |
+
return 0
|
| 100 |
+
|
| 101 |
+
state = _read_json(DEV / "verifier_state.json", {})
|
| 102 |
+
reward = _read_json(DEV / "reward.json", {})
|
| 103 |
+
corr_ok = bool(state.get("correctness_ok"))
|
| 104 |
+
hard = [str(r) for r in (state.get("hard_fail_reasons") or [])]
|
| 105 |
+
speedup = reward.get("speedup", None)
|
| 106 |
+
r = reward.get("reward", 0.0)
|
| 107 |
+
|
| 108 |
+
print(f"submission {k}/{MAX_SUBMISSIONS}")
|
| 109 |
+
if corr_ok:
|
| 110 |
+
print("correctness: PASS")
|
| 111 |
+
else:
|
| 112 |
+
print("correctness: FAIL")
|
| 113 |
+
print(f"failing_invariant: {_named_invariant(hard)}")
|
| 114 |
+
|
| 115 |
+
print(f"dev_speedup: {_fmt(speedup) if speedup is not None else 'n/a'}")
|
| 116 |
+
print(f"dev_reward: {_fmt(r)}")
|
| 117 |
+
|
| 118 |
+
best = _read_json(LOOP / "best.json", None)
|
| 119 |
+
if best and isinstance(best, dict) and best.get("submission"):
|
| 120 |
+
print(f"best_so_far: submission {best.get('submission')}, "
|
| 121 |
+
f"dev_speedup {_fmt(best.get('speedup'))}, dev_reward {_fmt(best.get('reward'))}")
|
| 122 |
+
else:
|
| 123 |
+
print("best_so_far: (none — no correctness-passing submission yet)")
|
| 124 |
+
|
| 125 |
+
print(f"remaining: {max(0, MAX_SUBMISSIONS - k)}")
|
| 126 |
+
print(f"finalize_allowed: {'true' if k >= MIN_SUBMISSIONS else 'false'}")
|
| 127 |
+
return 0
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
sys.exit(main())
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/score_engine.sh
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# ============================================================================
|
| 3 |
+
# wro loop16 finalizer — score_engine.sh (REUSABLE, task-agnostic) 0700 root
|
| 4 |
+
# ============================================================================
|
| 5 |
+
# Invoked ONLY by /opt/loop/submit.sh. Scores the LIVE /app/repo by running the
|
| 6 |
+
# task's OWN verifier in candidate mode against the solver's in-scope edits, then
|
| 7 |
+
# normalizes its standard wro JSON verdict into the dev files submit.sh/sanitize read.
|
| 8 |
+
#
|
| 9 |
+
# The wro verifier (tests/test.sh, baked into /opt/loop/private/tests/) already
|
| 10 |
+
# performs the whole scoring contract in candidate mode: scope-diff gate,
|
| 11 |
+
# import-origin assert, exact-correctness gate vs the baked golden, and paired
|
| 12 |
+
# candidate-vs-baseline timing -> a single JSON line:
|
| 13 |
+
# {"mode","reward","speedup","baseline_ms","candidate_ms","ref_speedup",
|
| 14 |
+
# "metadata",{...},"hard_fails":[...],
|
| 15 |
+
# "gates":{"scope_ok","import_origin_ok","correctness_ok","benchmark_ok"}}
|
| 16 |
+
# reward = speedup when there are no hard fails and correctness holds, else 0.
|
| 17 |
+
#
|
| 18 |
+
# This engine is generic across every wro task: the only per-task content is the
|
| 19 |
+
# baked verifier itself (test.sh + workload.py + compute_reward.py), staged into
|
| 20 |
+
# /opt/loop/private/tests/ at image build time.
|
| 21 |
+
export PATH=/opt/kernelbench-venv/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
| 22 |
+
set -uo pipefail
|
| 23 |
+
git config --global --add safe.directory '*' 2>/dev/null || true
|
| 24 |
+
|
| 25 |
+
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 26 |
+
DEV_OUT="${LOOP_DEV_OUT:-/logs/loop/dev}"; export LOOP_DEV_OUT="$DEV_OUT"; mkdir -p "$DEV_OUT"
|
| 27 |
+
TESTS="$HERE/private/tests"
|
| 28 |
+
rm -f "$DEV_OUT/harness_error.txt" "$DEV_OUT/verdict.json" 2>/dev/null || true
|
| 29 |
+
|
| 30 |
+
if [ ! -f "$TESTS/test.sh" ]; then
|
| 31 |
+
echo "baked verifier missing at $TESTS/test.sh" > "$DEV_OUT/harness_error.txt"
|
| 32 |
+
exit 3
|
| 33 |
+
fi
|
| 34 |
+
|
| 35 |
+
# The loop16 image bakes a committed /app/repo/.git at the degraded baseline (built
|
| 36 |
+
# offline; its files carry a different owner/mtime than the image working tree). Refresh
|
| 37 |
+
# the index so the task's git scope/timing gates compare CONTENT, not stale stat — a real
|
| 38 |
+
# in-scope edit still shows as modified; only content-identical stat noise is cleared.
|
| 39 |
+
git -C /app/repo update-index -q --refresh >/dev/null 2>&1 || true
|
| 40 |
+
|
| 41 |
+
# Run the task's verifier in candidate mode against the live /app/repo.
|
| 42 |
+
KERNELBENCH_VERIFY_MODE=candidate bash "$TESTS/test.sh" > "$DEV_OUT/verdict.raw" 2>"$DEV_OUT/verdict.err"
|
| 43 |
+
vr=$?
|
| 44 |
+
|
| 45 |
+
# Normalize the wro verdict JSON -> dev files. A genuine harness failure (no
|
| 46 |
+
# parseable verdict) is reported as harness_error (submit.sh refunds the budget).
|
| 47 |
+
python3 - "$DEV_OUT" "$vr" <<'PY'
|
| 48 |
+
import json, sys
|
| 49 |
+
from pathlib import Path
|
| 50 |
+
DEV = Path(sys.argv[1]); vr = sys.argv[2]
|
| 51 |
+
raw = ""
|
| 52 |
+
try: raw = (DEV / "verdict.raw").read_text(encoding="utf-8", errors="replace")
|
| 53 |
+
except Exception: raw = ""
|
| 54 |
+
|
| 55 |
+
# grab the LAST line that parses as a wro verdict (has a "gates" key)
|
| 56 |
+
verdict = None
|
| 57 |
+
for line in reversed(raw.splitlines()):
|
| 58 |
+
line = line.strip()
|
| 59 |
+
if not line or not line.startswith("{"):
|
| 60 |
+
continue
|
| 61 |
+
try:
|
| 62 |
+
obj = json.loads(line)
|
| 63 |
+
except Exception:
|
| 64 |
+
continue
|
| 65 |
+
if isinstance(obj, dict) and "gates" in obj and "hard_fails" in obj:
|
| 66 |
+
verdict = obj; break
|
| 67 |
+
|
| 68 |
+
if verdict is None:
|
| 69 |
+
err = (DEV / "verdict.err").read_text(errors="replace")[:400] if (DEV / "verdict.err").exists() else ""
|
| 70 |
+
(DEV / "harness_error.txt").write_text(
|
| 71 |
+
f"verifier produced no parseable verdict (exit {vr}); "
|
| 72 |
+
f"stderr head: {err.splitlines()[0] if err.strip() else '(none)'}\n")
|
| 73 |
+
# still write empty dev files so downstream reads don't crash
|
| 74 |
+
(DEV / "verifier_state.json").write_text(json.dumps({"correctness_ok": False, "hard_fail_reasons": ["harness_error"]}))
|
| 75 |
+
(DEV / "reward.json").write_text(json.dumps({"reward": 0.0, "speedup": 0.0}))
|
| 76 |
+
(DEV / "benchmark_results.json").write_text(json.dumps({"aggregate_speedup": 0.0}))
|
| 77 |
+
sys.exit(3)
|
| 78 |
+
|
| 79 |
+
hard = list(verdict.get("hard_fails") or [])
|
| 80 |
+
gates = verdict.get("gates") or {}
|
| 81 |
+
# A submission is check-passing iff the verifier assigned NO hard fail (which
|
| 82 |
+
# already covers scope / import-origin / correctness / timing failures).
|
| 83 |
+
correctness_ok = (len(hard) == 0) and bool(gates.get("correctness_ok", True))
|
| 84 |
+
reward = float(verdict.get("reward") or 0.0)
|
| 85 |
+
speedup = float(verdict.get("speedup") or 0.0)
|
| 86 |
+
|
| 87 |
+
(DEV / "verifier_state.json").write_text(json.dumps({
|
| 88 |
+
"correctness_ok": correctness_ok,
|
| 89 |
+
"hard_fail_reasons": hard,
|
| 90 |
+
"gates": gates,
|
| 91 |
+
}, sort_keys=True))
|
| 92 |
+
(DEV / "reward.json").write_text(json.dumps({"reward": reward, "speedup": speedup}, sort_keys=True))
|
| 93 |
+
(DEV / "benchmark_results.json").write_text(json.dumps({"aggregate_speedup": speedup}, sort_keys=True))
|
| 94 |
+
sys.exit(0)
|
| 95 |
+
PY
|
| 96 |
+
rc=$?
|
| 97 |
+
if [ "$rc" -ne 0 ] && [ "$rc" -ne 3 ] && [ ! -f "$DEV_OUT/harness_error.txt" ]; then
|
| 98 |
+
{ echo "score_engine_exit_${rc}"; tail -n 20 "$DEV_OUT/verdict.err" 2>/dev/null; } > "$DEV_OUT/harness_error.txt"
|
| 99 |
+
fi
|
| 100 |
+
exit "$rc"
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/submit.sh
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# ============================================================================
|
| 3 |
+
# wro loop16 finalizer — submit.sh (REUSABLE, task-agnostic)
|
| 4 |
+
# ============================================================================
|
| 5 |
+
# The solver's ONLY sanctioned scoring interface during a session
|
| 6 |
+
# (0755 root:root; the engine + private assets it calls are 0700 root-owned).
|
| 7 |
+
# Baked at /opt/loop/submit.sh so it exists from the first turn — unlike
|
| 8 |
+
# /tests/, which the grading harness creates only AFTER the agent finishes.
|
| 9 |
+
#
|
| 10 |
+
# bash /opt/loop/submit.sh # score current /app/repo, get feedback
|
| 11 |
+
# bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best iterate, end loop
|
| 12 |
+
#
|
| 13 |
+
# A wro submission is the solver's EDITS to the declared /app/repo scope files,
|
| 14 |
+
# scored by the task's own tests/test.sh in candidate mode -> perf_metric.
|
| 15 |
+
# Budget: exactly ONE graded submission (kfc is single-submission). The first
|
| 16 |
+
# submit.sh scores and immediately auto-finalizes; there is no second scored attempt.
|
| 17 |
+
# end-of-session /tests/test.sh scores the best-of-k iterate. HEAD stays at the
|
| 18 |
+
# baked baseline commit, so the anti-cheat scope-diff sees a product-only change.
|
| 19 |
+
#
|
| 20 |
+
# 🔴 git-safe-directory: a root-owned /app/repo is
|
| 21 |
+
# root-owned; without this every git op inside test.sh fails "dubious ownership"
|
| 22 |
+
# and silently returns a false 1.0. MUST be the first effective line.
|
| 23 |
+
git config --global --add safe.directory '*' 2>/dev/null || true
|
| 24 |
+
|
| 25 |
+
# 🔴 PATH-pin: the agent shell + runner verifier exec are NON-login; bare python3
|
| 26 |
+
# may lack the task's numpy/torch. Pin the venv (if present) first, then system.
|
| 27 |
+
export PATH=/opt/kernelbench-venv/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
| 28 |
+
set -uo pipefail
|
| 29 |
+
|
| 30 |
+
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 31 |
+
REPO=/app/repo
|
| 32 |
+
LOOP=/logs/loop
|
| 33 |
+
DEV="$LOOP/dev"
|
| 34 |
+
mkdir -p "$LOOP" "$LOOP/submissions" "$DEV"
|
| 35 |
+
|
| 36 |
+
MIN_SUBMISSIONS=1
|
| 37 |
+
MAX_SUBMISSIONS=1
|
| 38 |
+
COUNT_FILE="$LOOP/count"
|
| 39 |
+
BEST_FILE="$LOOP/best.json"
|
| 40 |
+
STATE_JSONL="$LOOP/state.jsonl"
|
| 41 |
+
|
| 42 |
+
# task_id for the finalize record — read from the baked private manifest (generic).
|
| 43 |
+
TASK_ID="$(python3 -c 'import json;print(json.load(open("/opt/loop/private/manifest.json")).get("task_id",""))' 2>/dev/null || true)"
|
| 44 |
+
[ -n "$TASK_ID" ] || TASK_ID="wro-loop16"
|
| 45 |
+
|
| 46 |
+
_read_count() {
|
| 47 |
+
if [ -f "$COUNT_FILE" ]; then
|
| 48 |
+
awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE"
|
| 49 |
+
else
|
| 50 |
+
echo 0
|
| 51 |
+
fi
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# Non-mutating snapshot of the current working tree -> a git tree hash.
|
| 55 |
+
_snapshot_tree() {
|
| 56 |
+
local c
|
| 57 |
+
c="$(git -C "$REPO" stash create 2>/dev/null || true)"
|
| 58 |
+
if [ -n "$c" ]; then
|
| 59 |
+
git -C "$REPO" rev-parse "$c^{tree}" 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null
|
| 60 |
+
else
|
| 61 |
+
git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null
|
| 62 |
+
fi
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
# ------------------- argument parsing -------------------
|
| 66 |
+
MODE=submit
|
| 67 |
+
REASON=""
|
| 68 |
+
while [ "$#" -gt 0 ]; do
|
| 69 |
+
case "$1" in
|
| 70 |
+
--finalize) MODE=finalize; shift ;;
|
| 71 |
+
--reason) REASON="${2:-}"; shift 2 ;;
|
| 72 |
+
--reason=*) REASON="${1#--reason=}"; shift ;;
|
| 73 |
+
*) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"<text>\"]]" >&2; exit 2 ;;
|
| 74 |
+
esac
|
| 75 |
+
done
|
| 76 |
+
|
| 77 |
+
# ------------------- finalize -------------------
|
| 78 |
+
if [ "$MODE" = finalize ]; then
|
| 79 |
+
CUR="$(_read_count)"; CUR="${CUR:-0}"
|
| 80 |
+
if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then
|
| 81 |
+
echo "minimum $MIN_SUBMISSIONS submission(s) required before finalize (you have $CUR/$MIN_SUBMISSIONS)"
|
| 82 |
+
exit 1
|
| 83 |
+
fi
|
| 84 |
+
# Reset the working tree to the baked baseline (HEAD), then plant the winner.
|
| 85 |
+
git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true
|
| 86 |
+
git -C "$REPO" clean -qfd 2>/dev/null || true
|
| 87 |
+
WIN_SUB=""; WIN_TREE=""
|
| 88 |
+
if [ -f "$BEST_FILE" ]; then
|
| 89 |
+
WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)"
|
| 90 |
+
WIN_TREE="$(python3 -c 'import json,sys;b=json.load(open(sys.argv[1]));print(b.get("tree_hash") or b.get("tree") or "")' "$BEST_FILE" 2>/dev/null || true)"
|
| 91 |
+
fi
|
| 92 |
+
PLANTED="none"
|
| 93 |
+
if [ -n "$WIN_TREE" ] && git -C "$REPO" read-tree "$WIN_TREE" 2>"$LOOP/finalize_apply.log"; then
|
| 94 |
+
# read-tree loaded the winning tree into the index; write it to the worktree.
|
| 95 |
+
# HEAD is unchanged (still the baseline commit) -> anti-cheat sees product-only diff.
|
| 96 |
+
git -C "$REPO" checkout-index -f -a 2>>"$LOOP/finalize_apply.log" && PLANTED="read-tree"
|
| 97 |
+
fi
|
| 98 |
+
if [ "$PLANTED" = "none" ] && [ -n "$WIN_SUB" ] && [ -s "$LOOP/submissions/$WIN_SUB/candidate.diff" ]; then
|
| 99 |
+
# fallback: re-apply the winning binary diff onto the baseline.
|
| 100 |
+
git -C "$REPO" apply --whitespace=nowarn "$LOOP/submissions/$WIN_SUB/candidate.diff" 2>>"$LOOP/finalize_apply.log" \
|
| 101 |
+
&& PLANTED="diff-apply" \
|
| 102 |
+
|| echo "WARNING: could not plant the winning submission; see /logs/loop/finalize_apply.log" >&2
|
| 103 |
+
fi
|
| 104 |
+
REASON="$REASON" WIN_SUB="$WIN_SUB" WIN_TREE="$WIN_TREE" CUR="$CUR" PLANTED="$PLANTED" TASK_ID="$TASK_ID" python3 - <<'PY'
|
| 105 |
+
import json, os
|
| 106 |
+
from pathlib import Path
|
| 107 |
+
LOOP = Path('/logs/loop')
|
| 108 |
+
try: best = json.loads((LOOP / 'best.json').read_text())
|
| 109 |
+
except Exception: best = {}
|
| 110 |
+
traj = []
|
| 111 |
+
try:
|
| 112 |
+
for line in (LOOP / 'state.jsonl').read_text().splitlines():
|
| 113 |
+
line = line.strip()
|
| 114 |
+
if not line: continue
|
| 115 |
+
row = json.loads(line)
|
| 116 |
+
traj.append({'submission': row.get('submission'), 'dev_speedup': row.get('speedup'),
|
| 117 |
+
'dev_reward': row.get('reward'), 'correctness_ok': row.get('correctness_ok')})
|
| 118 |
+
except Exception: pass
|
| 119 |
+
out = {
|
| 120 |
+
'schema_version': 'kernelbench_loop_finalize_v1',
|
| 121 |
+
'task_id': os.environ.get('TASK_ID') or 'wro-loop16',
|
| 122 |
+
'mode': 'baked', 'plant_method': os.environ.get('PLANTED'),
|
| 123 |
+
'submissions_used': int(os.environ.get('CUR') or 0),
|
| 124 |
+
'min_submissions': 1, 'max_submissions': 1,
|
| 125 |
+
'winning_submission': (best.get('submission') if best else None),
|
| 126 |
+
'winning_tree': os.environ.get('WIN_TREE') or None,
|
| 127 |
+
'winning_dev_speedup': (best.get('speedup') if best else None),
|
| 128 |
+
'winning_dev_reward': (best.get('reward') if best else None),
|
| 129 |
+
'dev_speedup_trajectory': traj,
|
| 130 |
+
'termination_reason': os.environ.get('REASON') or '',
|
| 131 |
+
'note': 'dev_reward is an in-session proxy; meta.reward is the runner end-of-session score of /app/repo.',
|
| 132 |
+
}
|
| 133 |
+
(LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n')
|
| 134 |
+
PY
|
| 135 |
+
RESTORED_TREE="$(_snapshot_tree)"
|
| 136 |
+
echo "restored_tree=$RESTORED_TREE plant=$PLANTED" >> "$LOOP/finalize_apply.log" 2>/dev/null || true
|
| 137 |
+
if [ -n "$WIN_SUB" ] && [ "$PLANTED" != "none" ]; then
|
| 138 |
+
echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (planted via $PLANTED); the grader will now score /app/repo"
|
| 139 |
+
else
|
| 140 |
+
echo "finalized: no correctness-passing submission in $CUR tries — /app/repo restored to the starting baseline; final reward will be the unchanged-baseline score (~1.0). the grader will now score /app/repo"
|
| 141 |
+
fi
|
| 142 |
+
exit 0
|
| 143 |
+
fi
|
| 144 |
+
|
| 145 |
+
# ------------------- submit -------------------
|
| 146 |
+
CUR="$(_read_count)"; CUR="${CUR:-0}"
|
| 147 |
+
if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then
|
| 148 |
+
echo "submission $CUR/$MAX_SUBMISSIONS"
|
| 149 |
+
echo "budget exhausted — call 'bash /opt/loop/submit.sh --finalize' to grade your best submission"
|
| 150 |
+
echo "--- auto-finalizing best-of-$MAX_SUBMISSIONS ---"
|
| 151 |
+
exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
|
| 152 |
+
fi
|
| 153 |
+
|
| 154 |
+
# Run the DEV engine on the LIVE /app/repo.
|
| 155 |
+
bash "$HERE/score_engine.sh"
|
| 156 |
+
engine_rc=$?
|
| 157 |
+
|
| 158 |
+
# HARNESS error path: infra failure (rc=3 or a marker). Do NOT consume budget.
|
| 159 |
+
if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then
|
| 160 |
+
python3 "$HERE/sanitize_feedback.py"
|
| 161 |
+
exit 0
|
| 162 |
+
fi
|
| 163 |
+
|
| 164 |
+
NEXT=$((CUR + 1))
|
| 165 |
+
echo "$NEXT" > "$COUNT_FILE"
|
| 166 |
+
|
| 167 |
+
SNAP="$LOOP/submissions/$NEXT"
|
| 168 |
+
mkdir -p "$SNAP"
|
| 169 |
+
TREE="$(_snapshot_tree)"
|
| 170 |
+
git -C "$REPO" diff --binary HEAD > "$SNAP/candidate.diff" 2>/dev/null || true
|
| 171 |
+
echo "${TREE:-}" > "$SNAP/tree_hash.txt"
|
| 172 |
+
echo "${TREE:-}" > "$SNAP/tree.txt"
|
| 173 |
+
for f in verifier_state.json reward.json benchmark_results.json; do
|
| 174 |
+
[ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true
|
| 175 |
+
done
|
| 176 |
+
|
| 177 |
+
NEXT="$NEXT" TREE="$TREE" python3 - <<'PY'
|
| 178 |
+
import json, os, time
|
| 179 |
+
from pathlib import Path
|
| 180 |
+
LOOP = Path('/logs/loop'); DEV = LOOP / 'dev'
|
| 181 |
+
k = int(os.environ['NEXT']); tree = os.environ.get('TREE') or ''
|
| 182 |
+
try: state = json.loads((DEV / 'verifier_state.json').read_text())
|
| 183 |
+
except Exception: state = {}
|
| 184 |
+
try: reward = json.loads((DEV / 'reward.json').read_text())
|
| 185 |
+
except Exception: reward = {}
|
| 186 |
+
corr_ok = bool(state.get('correctness_ok'))
|
| 187 |
+
r = float(reward.get('reward') or 0.0); s = float(reward.get('speedup') or 0.0)
|
| 188 |
+
row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok,
|
| 189 |
+
'reward': r, 'speedup': s, 'tree': tree,
|
| 190 |
+
'hard_fail_reasons': list(state.get('hard_fail_reasons') or [])}
|
| 191 |
+
with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f:
|
| 192 |
+
f.write(json.dumps(row) + '\n')
|
| 193 |
+
if corr_ok:
|
| 194 |
+
best_p = LOOP / 'best.json'
|
| 195 |
+
try: best = json.loads(best_p.read_text())
|
| 196 |
+
except Exception: best = None
|
| 197 |
+
if best is None or r > float(best.get('reward') or -1.0):
|
| 198 |
+
best_p.write_text(json.dumps({'submission': k, 'reward': r, 'speedup': s, 'tree': tree, 'tree_hash': tree},
|
| 199 |
+
indent=2, sort_keys=True) + '\n')
|
| 200 |
+
PY
|
| 201 |
+
|
| 202 |
+
python3 "$HERE/sanitize_feedback.py"
|
| 203 |
+
|
| 204 |
+
if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then
|
| 205 |
+
echo ""
|
| 206 |
+
echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---"
|
| 207 |
+
exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
|
| 208 |
+
fi
|
| 209 |
+
|
| 210 |
+
exit 0
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/curriculum_cluster.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Curriculum-learning difficulty-cluster selection for large-scale training stability.
|
| 2 |
+
|
| 3 |
+
DeepSpeed's data-efficiency curriculum learning stabilises very-large-scale
|
| 4 |
+
pretraining by feeding samples in an easy-to-hard order: samples are pre-bucketed
|
| 5 |
+
by a difficulty *metric* into per-difficulty-value rows (``index_to_sample[v]`` =
|
| 6 |
+
the array of sample-ids whose metric value is ``index_to_metric[v]``), sorted by
|
| 7 |
+
increasing difficulty. At each curriculum step the trainer selects the flat set of
|
| 8 |
+
sample-ids that fall inside a difficulty window, either
|
| 9 |
+
|
| 10 |
+
* VALUE-based: every row whose metric value is in ``(value_start, value_end]``, or
|
| 11 |
+
* PERCENTILE-based: the contiguous slice of samples covering the fraction of the
|
| 12 |
+
one-epoch population in ``[pct_start, pct_end)`` of ``num_bins``
|
| 13 |
+
equal-count percentile bands (with a running-count walk that
|
| 14 |
+
slices the two boundary rows partially and takes whole interior
|
| 15 |
+
rows, stopping once the end count is reached).
|
| 16 |
+
|
| 17 |
+
``select_curriculum_cluster`` returns the concatenated 1-D int array of selected
|
| 18 |
+
sample-ids (in row-then-within-row order). This is the functionally-correct but slow
|
| 19 |
+
reference: it walks the rows in a Python loop and grows the result with a fresh
|
| 20 |
+
``numpy.concatenate`` per matching row (each append re-copies the whole running
|
| 21 |
+
buffer, so the row walk is quadratic in the number of selected rows) and re-sums the
|
| 22 |
+
one-epoch population from scratch. The public signature and the returned array are
|
| 23 |
+
the behavioural contract.
|
| 24 |
+
|
| 25 |
+
Mirrors DeepSpeed ``deepspeed/runtime/data_pipeline/data_sampling/data_sampler.py``
|
| 26 |
+
``DeepSpeedDataSampler.get_sample_based_on_metric_value`` /
|
| 27 |
+
``get_sample_based_on_metric_percentile`` (Apache-2.0).
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def select_curriculum_cluster(
|
| 34 |
+
index_to_sample,
|
| 35 |
+
index_to_metric,
|
| 36 |
+
mode,
|
| 37 |
+
lo,
|
| 38 |
+
hi,
|
| 39 |
+
num_bins=None,
|
| 40 |
+
):
|
| 41 |
+
"""Select the flat cluster of sample-ids for one curriculum difficulty window.
|
| 42 |
+
|
| 43 |
+
:param index_to_sample: list of 1-D numpy int arrays; ``index_to_sample[r]`` holds
|
| 44 |
+
the sample-ids bucketed at difficulty-row ``r`` (rows sorted easy->hard).
|
| 45 |
+
:param index_to_metric: 1-D numpy array; ``index_to_metric[r]`` is the difficulty
|
| 46 |
+
metric value of row ``r`` (non-decreasing in ``r``).
|
| 47 |
+
:param mode: ``"value"`` or ``"percentile"``.
|
| 48 |
+
:param lo: window lower bound. VALUE mode: exclusive metric lower bound
|
| 49 |
+
(``value_start``). PERCENTILE mode: inclusive percentile-band start
|
| 50 |
+
(``pct_start``, an int in ``[0, num_bins]``).
|
| 51 |
+
:param hi: window upper bound. VALUE mode: inclusive metric upper bound
|
| 52 |
+
(``value_end``). PERCENTILE mode: exclusive percentile-band end
|
| 53 |
+
(``pct_end``, an int in ``[0, num_bins]``); when ``hi == num_bins`` the band
|
| 54 |
+
extends to the exact end of the population.
|
| 55 |
+
:param num_bins: number of equal-count percentile bands (PERCENTILE mode only).
|
| 56 |
+
:returns: 1-D numpy int64 array of the selected sample-ids (row-then-within-row
|
| 57 |
+
order), or an empty int64 array when nothing is selected.
|
| 58 |
+
"""
|
| 59 |
+
metric = np.asarray(index_to_metric)
|
| 60 |
+
n_rows = len(index_to_sample)
|
| 61 |
+
|
| 62 |
+
if mode == "value":
|
| 63 |
+
# NAIVE_VALUE_ROWWALK: Python loop, re-copy+concat the running buffer per hit.
|
| 64 |
+
new_samples = None
|
| 65 |
+
for row in range(n_rows):
|
| 66 |
+
if metric[row] <= hi and metric[row] > lo:
|
| 67 |
+
row_samples = np.copy(np.asarray(index_to_sample[row]))
|
| 68 |
+
new_samples = (
|
| 69 |
+
row_samples
|
| 70 |
+
if new_samples is None
|
| 71 |
+
else np.concatenate((new_samples, row_samples), axis=None)
|
| 72 |
+
)
|
| 73 |
+
if new_samples is None:
|
| 74 |
+
return np.array([], dtype=np.int64)
|
| 75 |
+
return new_samples.astype(np.int64, copy=False)
|
| 76 |
+
|
| 77 |
+
if mode == "percentile":
|
| 78 |
+
# NAIVE_PERCENTILE_ROWWALK: re-sum the epoch population, then a running-count
|
| 79 |
+
# walk that partially slices the two boundary rows and re-copies+concats each.
|
| 80 |
+
one_epoch_size = 0
|
| 81 |
+
for row in range(n_rows):
|
| 82 |
+
one_epoch_size += len(index_to_sample[row])
|
| 83 |
+
sample_per_pct = one_epoch_size // num_bins
|
| 84 |
+
start_count = sample_per_pct * lo
|
| 85 |
+
end_count = sample_per_pct * hi
|
| 86 |
+
if hi == num_bins:
|
| 87 |
+
end_count = one_epoch_size
|
| 88 |
+
|
| 89 |
+
new_samples = None
|
| 90 |
+
current_count = 0
|
| 91 |
+
for row in range(n_rows):
|
| 92 |
+
row_size = len(index_to_sample[row])
|
| 93 |
+
if current_count + row_size > start_count:
|
| 94 |
+
row_start = max(0, start_count - current_count)
|
| 95 |
+
if current_count + row_size <= end_count:
|
| 96 |
+
row_end = row_size
|
| 97 |
+
else:
|
| 98 |
+
row_end = end_count - current_count
|
| 99 |
+
row_samples = np.copy(np.asarray(index_to_sample[row])[row_start:row_end])
|
| 100 |
+
new_samples = (
|
| 101 |
+
row_samples
|
| 102 |
+
if new_samples is None
|
| 103 |
+
else np.concatenate((new_samples, row_samples), axis=None)
|
| 104 |
+
)
|
| 105 |
+
current_count += row_size
|
| 106 |
+
if current_count >= end_count:
|
| 107 |
+
break
|
| 108 |
+
if new_samples is None:
|
| 109 |
+
return np.array([], dtype=np.int64)
|
| 110 |
+
return new_samples.astype(np.int64, copy=False)
|
| 111 |
+
|
| 112 |
+
raise ValueError("mode must be 'value' or 'percentile'")
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/gated_gelu.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def gated_gelu(x: torch.Tensor, approximate: str = "none") -> torch.Tensor:
|
| 8 |
+
"""Apply a gated GELU activation over the last dimension.
|
| 9 |
+
|
| 10 |
+
The input's last dimension is split in half. GELU is applied to the first
|
| 11 |
+
half and multiplied by the second half. This straightforward implementation
|
| 12 |
+
intentionally relies on ordinary PyTorch tensor operations.
|
| 13 |
+
"""
|
| 14 |
+
if approximate not in ("none", "tanh"):
|
| 15 |
+
raise ValueError("approximate must be 'none' or 'tanh'")
|
| 16 |
+
if not x.is_cuda:
|
| 17 |
+
raise ValueError("x must be a CUDA tensor")
|
| 18 |
+
if x.dim() < 1:
|
| 19 |
+
raise ValueError("x must have at least one dimension")
|
| 20 |
+
if x.shape[-1] % 2 != 0:
|
| 21 |
+
raise ValueError("last dimension must be even")
|
| 22 |
+
d = x.shape[-1] // 2
|
| 23 |
+
return F.gelu(x[..., :d], approximate=approximate) * x[..., d:]
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/entrypoint.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
| 4 |
+
|
| 5 |
+
if [ -x /app/timer.sh ]; then
|
| 6 |
+
/app/timer.sh >/app/.timer/timer.log 2>&1 &
|
| 7 |
+
fi
|
| 8 |
+
|
| 9 |
+
if [ "$#" -gt 0 ]; then
|
| 10 |
+
exec "$@"
|
| 11 |
+
fi
|
| 12 |
+
|
| 13 |
+
exec /bin/bash -l
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/run_dev_bench.sh
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
| 4 |
+
KERNELBENCH_VERIFY_MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" bash /tests/test.sh
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/timer.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
| 4 |
+
mkdir -p /app/.timer
|
| 5 |
+
date -u +%FT%TZ > /app/.timer/start.txt
|
| 6 |
+
remaining=${FRONTIER_REMAINING_SECS:-21600}
|
| 7 |
+
printf '%s\n' "$remaining" > /app/.timer/remaining_secs
|
| 8 |
+
printf '%s\n' "$remaining" > /app/.timer/budget_secs
|
| 9 |
+
printf '%s\n' "$$" > /app/.timer/timer.pid
|
| 10 |
+
while true; do
|
| 11 |
+
sleep 60
|
| 12 |
+
done
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/instruction.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Performance Optimization Task
|
| 2 |
+
|
| 3 |
+
## Scope
|
| 4 |
+
|
| 5 |
+
You may modify **only** this file:
|
| 6 |
+
|
| 7 |
+
```
|
| 8 |
+
curriculum_cluster.py
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
Everything else is **out of scope**. Any change to a file outside the scope above
|
| 12 |
+
causes the submission to score zero. Find where the slowness is *inside the scope*
|
| 13 |
+
by reading and profiling the code — that is part of the task.
|
| 14 |
+
|
| 15 |
+
## Objective
|
| 16 |
+
|
| 17 |
+
`curriculum_cluster.py` implements **curriculum-learning difficulty-cluster
|
| 18 |
+
selection**, the step that stabilises very-large-scale pretraining by feeding
|
| 19 |
+
samples in an easy-to-hard order. Samples are pre-bucketed by a difficulty *metric*
|
| 20 |
+
into per-difficulty rows (`index_to_sample[r]` is the array of sample-ids whose
|
| 21 |
+
metric value is `index_to_metric[r]`, rows sorted easy→hard). At each curriculum
|
| 22 |
+
step the trainer selects the flat set of sample-ids that fall inside a difficulty
|
| 23 |
+
window, in one of two modes:
|
| 24 |
+
|
| 25 |
+
- **VALUE**: every row whose metric value is in `(lo, hi]`;
|
| 26 |
+
- **PERCENTILE**: the contiguous slice of samples covering the population fraction in
|
| 27 |
+
`[lo, hi)` of `num_bins` equal-count percentile bands, where the two boundary rows
|
| 28 |
+
are sliced **partially** (a running-count walk takes whole interior rows and the
|
| 29 |
+
correct partial prefix/suffix of the two edge rows), stopping once the end count is
|
| 30 |
+
reached.
|
| 31 |
+
|
| 32 |
+
The current implementation is **functionally correct but slow**: it walks the rows
|
| 33 |
+
in a Python loop and grows the result with a fresh `numpy.concatenate` on every
|
| 34 |
+
matching row (each append re-copies the entire running buffer, so the row walk is
|
| 35 |
+
quadratic in the number of selected rows), and it re-sums the one-epoch population
|
| 36 |
+
from scratch.
|
| 37 |
+
|
| 38 |
+
Your job: **make `select_curriculum_cluster` faster on the benchmark workload while
|
| 39 |
+
returning exactly the same selected sample-ids.** You may reorganize the logic
|
| 40 |
+
within the scope file however you like (e.g. a cumulative row-size prefix plus a
|
| 41 |
+
boundary search to locate the two edge rows, then a single concatenation of the
|
| 42 |
+
interior rows and the two partial edge slices), as long as the observable output
|
| 43 |
+
below is preserved.
|
| 44 |
+
|
| 45 |
+
## Behavioral contract (what the grader checks)
|
| 46 |
+
|
| 47 |
+
The grader calls the public entry point:
|
| 48 |
+
|
| 49 |
+
```python
|
| 50 |
+
select_curriculum_cluster(index_to_sample, index_to_metric, mode, lo, hi, num_bins=None) -> numpy.ndarray
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
- `index_to_sample`: list of 1-D `numpy` int arrays; `index_to_sample[r]` holds the
|
| 54 |
+
sample-ids at difficulty-row `r`;
|
| 55 |
+
- `index_to_metric`: 1-D `numpy` array; `index_to_metric[r]` is the metric value of
|
| 56 |
+
row `r` (non-decreasing in `r`);
|
| 57 |
+
- `mode`: `"value"` or `"percentile"`;
|
| 58 |
+
- `lo`, `hi`: window bounds — VALUE: exclusive-lower / inclusive-upper metric bounds;
|
| 59 |
+
PERCENTILE: inclusive-start / exclusive-end percentile-band indices in
|
| 60 |
+
`[0, num_bins]` (when `hi == num_bins` the band extends to the exact end of the
|
| 61 |
+
population);
|
| 62 |
+
- `num_bins`: number of equal-count percentile bands (PERCENTILE mode only).
|
| 63 |
+
|
| 64 |
+
The returned 1-D `numpy` int array must equal, **element-for-element and in the same
|
| 65 |
+
order** (row-then-within-row), the independent reference the grader computes for both
|
| 66 |
+
modes. In PERCENTILE mode the two boundary rows must be sliced at the exact
|
| 67 |
+
running-count offsets — a whole-row shortcut that ignores the partial edges selects
|
| 68 |
+
the wrong sample-ids and scores zero. The public signature must remain unchanged.
|
| 69 |
+
|
| 70 |
+
The reward increases as the wall-clock time of `select_curriculum_cluster` decreases
|
| 71 |
+
on the benchmark workload, subject to the correctness requirement above. A correct
|
| 72 |
+
submission that changes nothing scores about 1.0.
|
| 73 |
+
|
| 74 |
+
## Notes
|
| 75 |
+
|
| 76 |
+
- The workload runs on CPU; no GPU is required. Only `numpy` and the Python
|
| 77 |
+
standard library are available.
|
| 78 |
+
- Determinism: given the same inputs, your implementation must produce the same
|
| 79 |
+
output on every run.
|
| 80 |
+
|
| 81 |
+
## Solve independently — prohibited actions (any one ⇒ the whole task scores 0)
|
| 82 |
+
|
| 83 |
+
- Reading, printing, copying, `cat`/`grep`/`find`-ing, editing, or reproducing ANY
|
| 84 |
+
verifier / scoring / hidden-test / golden file, wherever it lives; or inferring
|
| 85 |
+
hidden inputs/thresholds.
|
| 86 |
+
- Downloading or cloning the upstream project or looking up its reference
|
| 87 |
+
implementation in ANY form — `git clone`/`fetch`/`pull`, adding a git remote,
|
| 88 |
+
`pip download`/`pip install` of the same package, `wget`/`curl` of upstream files,
|
| 89 |
+
checking out a different commit, or web lookup — whether the network appears to work
|
| 90 |
+
or not.
|
| 91 |
+
- Bypassing or disabling the network isolation (unsetting/overriding
|
| 92 |
+
`http_proxy`/`https_proxy`/`all_proxy`, opening raw sockets, or any other
|
| 93 |
+
circumvention).
|
| 94 |
+
|
| 95 |
+
## 提交方式
|
| 96 |
+
|
| 97 |
+
本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。
|
| 98 |
+
改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。
|
tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/pre_artifacts.sh
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# ============================================================================
|
| 3 |
+
# pre_artifacts.sh — kfc/wro-deepspeed-curriculum-cluster-select-loop16
|
| 4 |
+
#
|
| 5 |
+
# Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE
|
| 6 |
+
# grading (spec §1.1). It turns whatever the agent left behind into a portable artifact:
|
| 7 |
+
#
|
| 8 |
+
# /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit
|
| 9 |
+
# /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line
|
| 10 |
+
#
|
| 11 |
+
# 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one
|
| 12 |
+
# place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs <base>..HEAD).
|
| 13 |
+
# Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate,
|
| 14 |
+
# `git checkout -q HEAD -- <scope>` re-materialises the baseline for the paired timing,
|
| 15 |
+
# and loop16's `submit.sh --finalize` plants the best iterate with read-tree +
|
| 16 |
+
# checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope
|
| 17 |
+
# gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the
|
| 18 |
+
# "baseline" — and a correct solve scores 0.
|
| 19 |
+
# `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages
|
| 20 |
+
# names only, writes no tree, creates no commit and leaves HEAD exactly where it was.
|
| 21 |
+
#
|
| 22 |
+
# EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier
|
| 23 |
+
# scores the container on its own terms and gives 0 by itself.
|
| 24 |
+
#
|
| 25 |
+
# READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index
|
| 26 |
+
# (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the
|
| 27 |
+
# verifier — which runs after us — sees exactly the `git status --porcelain` it would have
|
| 28 |
+
# seen if this script had never run. No commit, no HEAD move, no working-tree write.
|
| 29 |
+
#
|
| 30 |
+
# CAPTURE ROOTS for THIS task — derived from the package, never assumed:
|
| 31 |
+
# /app/repo git repo, HEAD == the 1-commit carved baseline
|
| 32 |
+
# evidence Dockerfile:124: WORKDIR /app/repo
|
| 33 |
+
# evidence Dockerfile:77: && cd /app/repo \
|
| 34 |
+
# evidence Dockerfile:84: && test "$(git rev-list --count HEAD)" = "1" \
|
| 35 |
+
# evidence test.sh:16: export PYTHONPATH="/app/repo:${PYTHONPATH:-}"
|
| 36 |
+
# evidence test.sh:19: REPO=/app/repo
|
| 37 |
+
#
|
| 38 |
+
# Single root => model.patch is a bare `git diff --binary <baseline>` (no banner).
|
| 39 |
+
# model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable
|
| 40 |
+
# by one reader.
|
| 41 |
+
#
|
| 42 |
+
# loop16 task (environment/loop/ -> /opt/loop in the image): the harness auto-finalizes
|
| 43 |
+
# at k=16 and `submit.sh --finalize` plants the best iterate in the WORKING TREE while
|
| 44 |
+
# HEAD stays on the baked baseline — which is exactly what this script captures. Running
|
| 45 |
+
# it after a finalize therefore yields the GRADED artifact, not the last raw edit.
|
| 46 |
+
# ============================================================================
|
| 47 |
+
set -uo pipefail
|
| 48 |
+
|
| 49 |
+
OUT=/logs/artifacts
|
| 50 |
+
PATCH="$OUT/model.patch"
|
| 51 |
+
LIST="$OUT/model_files.txt"
|
| 52 |
+
MULTI=0 # 1 => several capture roots => each diff gets a banner line
|
| 53 |
+
MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane)
|
| 54 |
+
|
| 55 |
+
mkdir -p "$OUT" 2>/dev/null || true
|
| 56 |
+
: > "$PATCH" 2>/dev/null || true
|
| 57 |
+
: > "$LIST" 2>/dev/null || true
|
| 58 |
+
git config --global --add safe.directory '*' >/dev/null 2>&1 || true
|
| 59 |
+
|
| 60 |
+
banner() { # $1=root $2=mode ; only when there is more than one root
|
| 61 |
+
if [ "$MULTI" = 1 ]; then
|
| 62 |
+
printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null
|
| 63 |
+
fi
|
| 64 |
+
return 0
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
list_add() { # stdin: paths relative to $1 -> absolute, one per line
|
| 68 |
+
sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true
|
| 69 |
+
return 0
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline
|
| 73 |
+
root=$1
|
| 74 |
+
if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
|
| 75 |
+
if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
| 76 |
+
echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot"
|
| 77 |
+
capture_tree "$root"
|
| 78 |
+
return 0
|
| 79 |
+
fi
|
| 80 |
+
# 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and
|
| 81 |
+
# reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could
|
| 82 |
+
# flip a scope gate either way. So copy the repo's index aside and stage into the COPY —
|
| 83 |
+
# the repo's own .git/index is byte-identical when we are done.
|
| 84 |
+
tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi=""
|
| 85 |
+
gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true)
|
| 86 |
+
if [ -z "$gd" ]; then
|
| 87 |
+
gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true)
|
| 88 |
+
case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac
|
| 89 |
+
fi
|
| 90 |
+
if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then
|
| 91 |
+
GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE
|
| 92 |
+
else
|
| 93 |
+
echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index"
|
| 94 |
+
fi
|
| 95 |
+
git -C "$root" add -AN . >/dev/null 2>&1 || true
|
| 96 |
+
base=HEAD
|
| 97 |
+
if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then
|
| 98 |
+
base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null)
|
| 99 |
+
echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree"
|
| 100 |
+
else
|
| 101 |
+
n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0)
|
| 102 |
+
case "$n" in ''|*[!0-9]*) n=0 ;; esac
|
| 103 |
+
if [ "$n" -gt 1 ]; then
|
| 104 |
+
base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1)
|
| 105 |
+
echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:"
|
| 106 |
+
echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so"
|
| 107 |
+
echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved"
|
| 108 |
+
echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve."
|
| 109 |
+
fi
|
| 110 |
+
fi
|
| 111 |
+
[ -n "${base:-}" ] || base=HEAD
|
| 112 |
+
banner "$root" "git-diff-vs-baseline"
|
| 113 |
+
git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true
|
| 114 |
+
names=$(git -C "$root" diff --name-only "$base" 2>/dev/null)
|
| 115 |
+
echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)"
|
| 116 |
+
unset GIT_INDEX_FILE
|
| 117 |
+
[ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null
|
| 118 |
+
printf '%s\n' "$names" | grep -v '^$' | list_add "$root"
|
| 119 |
+
return 0
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot
|
| 123 |
+
root=$1
|
| 124 |
+
if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
|
| 125 |
+
tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0
|
| 126 |
+
if git init -q "$tmp/snap" >/dev/null 2>&1; then
|
| 127 |
+
GD="$tmp/snap/.git"
|
| 128 |
+
empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null)
|
| 129 |
+
( cd "$root" 2>/dev/null || exit 0
|
| 130 |
+
find . -name .git -prune -o -name __pycache__ -prune -o \
|
| 131 |
+
-type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \
|
| 132 |
+
2>/dev/null \
|
| 133 |
+
| GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true
|
| 134 |
+
banner "$root" "tree-snapshot-not-a-git-repo"
|
| 135 |
+
GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \
|
| 136 |
+
>> "$PATCH" 2>/dev/null || true
|
| 137 |
+
else
|
| 138 |
+
echo "[pre_artifacts] WARN could not stage a snapshot index for $root"
|
| 139 |
+
fi
|
| 140 |
+
rm -rf "$tmp" 2>/dev/null || true
|
| 141 |
+
all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \
|
| 142 |
+
-type f -print 2>/dev/null | sed 's|^\./||' )
|
| 143 |
+
printf '%s\n' "$all" | grep -v '^$' | list_add "$root"
|
| 144 |
+
big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \
|
| 145 |
+
-size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . )
|
| 146 |
+
echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)"
|
| 147 |
+
if [ "${big:-0}" != 0 ]; then
|
| 148 |
+
echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in"
|
| 149 |
+
echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch."
|
| 150 |
+
fi
|
| 151 |
+
return 0
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
capture_git "/app/repo"
|
| 155 |
+
bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0)
|
| 156 |
+
case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac
|
| 157 |
+
echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)"
|
| 158 |
+
if [ "$bytes" -gt 67108864 ]; then
|
| 159 |
+
echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build"
|
| 160 |
+
echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also"
|
| 161 |
+
echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish."
|
| 162 |
+
fi
|
| 163 |
+
exit 0
|