diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/.dockerignore b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/.dockerignore @@ -0,0 +1,24 @@ +# .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does +# NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile . +# The reference implementation and every authoring artefact MUST NOT reach an image layer. +*.patch +oracle* +negative* +baseline2* +scope_card.json +degradation_manifest.json +task_meta.json +loop_map_entry.json +job.yaml +intermediates/ +_retrofit* +sr_validate* +leak_audit/ +self_check/ +variants/ +**/__pycache__/ +**/*.pyc +*.bak +*.bak_* +*.pre_* +**/*.pre_* diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/Dockerfile b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..008ca2da70315e73eb85d8937115fcf90368c80f --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/Dockerfile @@ -0,0 +1,176 @@ +# syntax=docker/dockerfile:1 +# ============================================================================= +# insea-fused-softmax-cross-entropy-grad-loop16 — OPEN-SOURCE, self-contained task image +# +# Task: make the declared scope faster while preserving its observable behaviour exactly. +# Editable scope (the ONLY files the scope gate allows to change): +## - /app/repo/cross_entropy_grad.py +# +# FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image. +# Needs 1 NVIDIA GPU to RUN (task.toml: gpus = 1, anchor calibrated on H20); no GPU to BUILD. +# Platform: linux/amd64 ONLY (official torch wheels are manylinux x86_64). +# Build context = this task directory (the Dockerfile lives in environment/). +# +# PROVENANCE of environment/repo/ (so anyone can re-derive it independently) +# recovered from: /kernelbench/insea-fused-softmax-cross-entropy-grad-loop16:loop-20260720T021136Z@sha256:dbd2b4dbf93aa3621d94de371a783ff2d77d7978cc4b93a6c19819d36a68a7f9 +# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in +# manifest order; .git and any .wh..wh..opq marker dropped. +# 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. +## +# ----------------------------------------------------------------------------- +# BUILD (needs outbound network for PyPI only — the working tree ships in this package) +# cd <...>/insea-fused-softmax-cross-entropy-grad-loop16/task +# docker build -f environment/Dockerfile -t fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss . +# +# RUN docker run --rm --gpus all -it fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss +# 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 +# # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative) +# +# 🔴 RE-CALIBRATE THE ANCHOR ON YOUR HARDWARE +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; ref_speedup = 7.4157 . +# tests/test.sh resolves it from tests/ref_speedup.txt FIRST, then falls back to +# /opt/verifier-correctness-manifest.json, then to 1.0 (which would make every reward 0). +# The value was calibrated on NVIDIA H20. The verifier supports mode dispatch natively, so +# re-measuring is ONE command (the reference patch is passed BY PATH and never baked): +# docker run --rm --gpus all -v "$PWD/tests:/tests:ro" -v ":/patches:ro" \ +# -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ +# fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss bash /tests/test.sh +# then write the measured speedup into tests/ref_speedup.txt. See tests/ref_speedup.caveat.md. +# Sanity: noop (no patch) ~= 1.0 -> gated to 0; negative MUST score 0. +# +# VERSION ANCHORS +# CUDA 12.6 · Python 3.10 · torch 2.7.0 (cu126, brings its matching triton 3.3.x) +# The original private base declared torch 2.5.1 / triton 3.1.0 and the task overlay then ran +# `pip install torch==2.7.0` — 2.7.0 is therefore the version the anchor was calibrated under. +# ============================================================================= +FROM nvidia/cuda:12.6.2-devel-ubuntu22.04 + +# Compute capability you will RUN on (Triton JITs for the live device; this only affects +# hand-built CUDA extensions): 8.0 A100 / 8.9 L40S-4090 / 9.0 H100-H20 / 10.0 B200 +ARG TORCH_CUDA_ARCH_LIST="9.0" +ARG TORCH_VERSION=2.7.0 + +ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \ + PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential gcc-10 g++-10 cmake ninja-build pkg-config \ + python3.10 python3.10-dev python3.10-venv python3-pip python-is-python3 \ + git ca-certificates curl procps coreutils tar gzip vim less file jq \ + && update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 \ + && update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 100 \ + && rm -rf /var/lib/apt/lists/* + +# ---- venv at this EXACT path: tests/test.sh puts /opt/kernelbench-venv/bin at the head of PATH, +# and a bare python3 from anywhere else would not have torch. ---- +ENV VENV=/opt/kernelbench-venv +RUN python3.10 -m venv "$VENV" +ENV PATH=$VENV/bin:/usr/local/cuda/bin:$PATH \ + TORCH_CUDA_ARCH_LIST=${TORCH_CUDA_ARCH_LIST} +RUN pip install --no-cache-dir -U pip setuptools wheel +RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cu126 \ + "torch==${TORCH_VERSION}" \ + && python -c "import torch, triton; print('torch', torch.__version__, '| triton', triton.__version__); assert torch.__version__.startswith('2.7.0'), torch.__version__" + +# ---- the graded working tree. A REAL directory (not a symlink): the scope gate runs +# `git -C /app/repo status --porcelain`, which cannot see through a symlink. ---- +RUN mkdir -p /app/repo /app/.timer /app/workspace /logs/verifier /logs/agent /logs/artifacts +COPY environment/repo/ /app/repo/ +COPY instruction.md /app/instruction.md + +# ---- the baseline commit = the diff base the scope gate compares against. +# 🔴 core.fileMode=false is LOAD-BEARING, not hygiene: a shipped image in this corpus had +# core.fileMode=true while some files were 0775 on disk but 100644 in the index, so +# `git status --porcelain` reported phantom out-of-scope paths in EVERY mode and forced +# reward to 0. Setting it false at creation makes that class of defect impossible. ---- +RUN git config --global user.email "reviewer@fai-bench.local" \ + && git config --global user.name "fai-bench" \ + && git config --global init.defaultBranch main \ + && git config --global --add safe.directory /app/repo \ + && cd /app/repo \ + && git init -q \ + && git config core.fileMode false \ + && printf '__pycache__/\n*.pyc\n' >> .gitignore \ + && git add -A \ + && git commit -qm "baseline (graded starting point)" \ + && rm -rf .git/logs \ + && test "$(git rev-list --count HEAD)" = "1" \ + && test -z "$(git remote)" \ + && test "$(git config --get core.fileMode)" = "false" \ + && test -z "$(git status --porcelain)" \ + && echo "[build] /app/repo: 1 commit, no remote, fileMode=false, clean tree" + +# ---- runtime contract (copied verbatim from the shipped image) ---- +COPY environment/runtime/entrypoint.sh /app/entrypoint.sh +COPY environment/runtime/timer.sh /app/timer.sh +RUN chmod 0755 /app/entrypoint.sh /app/timer.sh && chown root:root /app/entrypoint.sh /app/timer.sh +COPY environment/runtime/run_dev_bench.sh /app/workspace/run_dev_bench.sh +RUN chmod 0755 /app/workspace/run_dev_bench.sh +COPY environment/loop/ /opt/loop/ +RUN if [ -f /opt/loop/submit.sh ]; then chmod 0755 /opt/loop/submit.sh; fi \ + && chown -R root:root /opt/loop \ + && if [ -f /opt/loop/score_engine.sh ]; then chmod 0700 /opt/loop/score_engine.sh; fi \ + && if [ -f /opt/loop/sanitize_feedback.py ]; then chmod 0700 /opt/loop/sanitize_feedback.py; fi \ + && if [ -d /opt/loop/private ]; then chmod -R go-rwx /opt/loop/private; fi + +# ---- the FROZEN anchor fallback. tests/test.sh prefers tests/ref_speedup.txt (mounted) and falls +# back to THIS path; keeping both consistent makes the resolution explicit. Only the constant. ---- +COPY environment/verifier-correctness-manifest.json /opt/verifier-correctness-manifest.json + +# ---- OPEN grading suite is NOT baked: tests/ (test.sh + compute_reward.py + the workload/harness +# + ref_speedup.txt) is MOUNTED FRESH at /tests when scoring. It ships in this package — +# open-source, but outside the image so the graded harness cannot be edited from the session. + +# ---- 🔴 ANTI-LEAK ASSERTS (author-side artifact denylist) ---- +RUN set -eu; rc=0; \ + hits="$(find / -xdev -type f \( -name 'oracle*.patch' -o -name 'negative*.patch' \ + -o -name 'baseline2*.patch' -o -name 'scope_card.json' -o -name 'kernel_oracle.py' \ + -o -name 'degradation_manifest.json' \) 2>/dev/null | head -10)"; \ + if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: a reference/authoring file is baked:"; echo "$hits"; rc=1; fi; \ + for p in /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling /tests; do \ + if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path baked: $p"; rc=1; fi; \ + done; \ + test "$rc" = 0; \ + echo "[build] ANTI-LEAK ASSERTS PASS" + +ENV PYTHONPATH=/app/repo \ + PYTHONDONTWRITEBYTECODE=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + LD_LIBRARY_PATH=/opt/kernelbench-venv/lib/python3.10/site-packages/torch/lib:/usr/local/cuda/lib64:/usr/local/nvidia/lib64 +WORKDIR /app/repo + +# ---- build-time smoke: the graded module imports FROM /app/repo (the verifier asserts the same +# thing at scoring time via its import-origin gate) and the scope files are present. ---- +# ---- frozen naive baseline for the verifier's SPEED DENOMINATOR. +# tests/test.sh resolves KB_BASELINE_MODULE=/opt/verifier-baseline/; when that file +# is absent the whole benchmark block is SKIPPED and the run hard-fails with +# `validation_incomplete` (reward 0) no matter how good the submission is. +# It is a pristine copy of the shipped, pre-edit scope file, taken here at build time — +# exactly what the original task image baked. `cmp` proves the copy is byte-identical. +RUN mkdir -p /opt/verifier-baseline \ + && cp "/app/repo/cross_entropy_grad.py" "/opt/verifier-baseline/cross_entropy_grad.py" \ + && cmp "/app/repo/cross_entropy_grad.py" "/opt/verifier-baseline/cross_entropy_grad.py" \ + && chmod 0444 "/opt/verifier-baseline/cross_entropy_grad.py" \ + && echo "frozen baseline(s) baked: $(ls -l /opt/verifier-baseline | tail -n +2 | wc -l) file(s)" + +RUN python - <<'PY' +import os, subprocess, sys +sys.path.insert(0, "/app/repo") +for f in ('/app/repo/cross_entropy_grad.py',): + p = os.path.join("/app/repo", f) + assert os.path.isfile(p), f"scope file missing: {p}" + print("scope file present:", f, os.path.getsize(p), "B") +for _b in ('cross_entropy_grad.py',): + _p = os.path.join('/opt/verifier-baseline', _b) + assert os.path.isfile(_p), f"frozen baseline missing: {_p} (tests/test.sh would skip the benchmark and hard-fail validation_incomplete)" + print('frozen baseline:', _p, os.path.getsize(_p), 'B') +n = subprocess.run(["git","-C","/app/repo","rev-list","--count","HEAD"], + capture_output=True, text=True).stdout.strip() +assert n == "1", f"git diff base broken (commits={n!r})" +print("OK: scope files, import origin and git base all in place") +PY + +ENTRYPOINT ["/app/entrypoint.sh"] +CMD ["tail","-f","/dev/null"] diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/compute_reward.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..d544d3abb2809add146c425d2effa408753940cf --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/compute_reward.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Canonical kernelbench reward writer (reused verbatim from the ready-task +template kernel-opt-p0a4-003). Task-agnostic; do NOT special-case a task here. + +Dual-mode: + - correctness task (verifier_state.task_kind == "correctness"): + reward = 1.0 iff all hard gates true and no hard_fail_reasons, else 0.0; no timing. + - acceleration task: + reward = speedup (raw measured speedup — no cap, no log, no ref anchor) + iff all gates pass and speedup is finite and > 0; else 0.0. + +Reads: /logs/loop/dev/verifier_state.json, /logs/loop/dev/benchmark_results.json +Writes: /logs/loop/dev/reward.json, /logs/loop/dev/reward.txt +""" +import json, math +from pathlib import Path + +LOG = Path("/logs/loop/dev") +STATE = LOG / "verifier_state.json" +BENCH = LOG / "benchmark_results.json" +REWARD = LOG / "reward.json" +TEXT = LOG / "reward.txt" + +GATES = [ + "correctness_ok", + "trusted_restore_ok", + "hidden_correctness_ok", + "baseline_ok", + "benchmark_ok", + "anti_cheat_ok", +] + + +def read_json(path, default): + try: + return json.loads(path.read_text(encoding="utf-8")) + except Exception: + return default + + +def main(): + LOG.mkdir(parents=True, exist_ok=True) + state = read_json(STATE, {}) + bench = read_json(BENCH, {}) + hard = list(state.get("hard_fail_reasons") or []) + task_kind = state.get("task_kind") or bench.get("task_kind") or "acceleration" + gates_ok = all(bool(state.get(g)) for g in GATES) + + speedup = ref = 1.0 + reward = 0.0 + if task_kind == "correctness": + reward = 1.0 if (gates_ok and not hard) else 0.0 + if reward == 0.0 and not hard: + hard.append("correctness_or_validation_incomplete") + else: + try: + speedup = float(bench.get("aggregate_speedup") or bench.get("primary_metric_value") or 1.0) + ref = float(bench.get("ref_speedup") or bench.get("reference_metric_value") or 1.0) + except Exception: + speedup = ref = 1.0 + hard.append("invalid_primary_metric_value") + # reward IS the raw measured speedup (no cap, no log, no ref anchor); + # ref_speedup is kept as calibration metadata only. reward is 0 only when a + # gate fails (correctness/anti-cheat) or the measured speedup is unusable. + if gates_ok and not hard and math.isfinite(speedup) and speedup > 0.0: + reward = speedup + if reward == 0.0 and not hard: + hard.append("validation_incomplete_or_bad_speedup") + + out = { + "schema_version": "kernelbench_reward_v1", + "task_kind": task_kind, + "reward": reward, + "speedup": speedup, + "ref_speedup": ref, + "actual_hardware_type": state.get("actual_hardware_type", "") or bench.get("actual_hardware_type", ""), + "hard_fail_reasons": hard, + "state_path": str(STATE), + "benchmark_path": str(BENCH), + } + REWARD.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n", encoding="utf-8") + TEXT.write_text(f"{reward}\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/gpu_peakmem.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/gpu_peakmem.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8abaefdaa20c0f6e599320e77d08bec7080dbb --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/gpu_peakmem.py @@ -0,0 +1,127 @@ +"""Peak-GPU-memory measurement for the cross-entropy loss+gradient task. + +VALUE AXIS = PEAK MEMORY, not wall-time. The naive baseline materialises several +full ``(N, V)`` buffers (log-probs, probabilities, gradient); a memory-frugal +implementation keeps only per-row running state and can overwrite the logits +buffer with the gradient in place, so its peak ``max_memory_allocated`` is far +lower at large ``V``. Latency may be ~1.0x -- that is EXPECTED and is NOT scored. + +Per shape: + 1. correctness agreement: candidate output must match the frozen baseline + within tolerance (on a fresh clone; the candidate may mutate in place); + 2. peak = ``torch.cuda.max_memory_allocated`` measured over a single call, with + only the freshly generated inputs resident at reset (the input buffer is the + shared floor for both); ratio = baseline_peak / candidate_peak. +Final metric = geometric mean of the per-shape peak-memory ratios. Prints +"speedup=X" (the peak-memory ratio; a no-op candidate == frozen baseline ties at +~1.0). The baseline is loaded from the protected frozen copy (KB_BASELINE_MODULE). +""" + +import importlib.util +import os +import sys + +import torch + +from kb_ce_harness import ( + assert_grad_close, + assert_loss_close, + forbidden_ce_guard, + geomean, + load_candidate, + make_labels, + make_logits, +) + +IGN = -100 +LS = 0.0 +IGNORE_FRAC = 0.1 + +# (tag, N, V, dtype). Vocab large enough that the baseline's (N,V) materialisation +# dominates peak memory (false-negative checklist item #3: a path-exercising workload). +SHAPES = [ + ("v32k_fp32", 8192, 32768, torch.float32), + ("v128k_fp32", 8192, 128256, torch.float32), + ("v64k_bf16", 8192, 65536, torch.bfloat16), + ("v128k_bf16", 8192, 128256, torch.bfloat16), +] + + +def _load(path): + spec = importlib.util.spec_from_file_location("kb_ce_mod_" + str(abs(hash(path))), path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _baseline_fn(): + path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/cross_entropy_grad.py") + return _load(path).cross_entropy_loss_grad + + +def _peak_of(fn, N, V, dtype, seed, guard): + """max_memory_allocated over one call, inputs freshly generated (only they + are resident at reset, so the input buffer is the shared floor).""" + torch.cuda.empty_cache() + torch.cuda.synchronize() + logits = make_logits(N, V, seed, dtype=dtype) + labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN) + torch.cuda.synchronize() + torch.cuda.reset_peak_memory_stats() + if guard: + with forbidden_ce_guard(): + loss, grad = fn(logits, labels, IGN, LS) + else: + loss, grad = fn(logits, labels, IGN, LS) + torch.cuda.synchronize() + peak = torch.cuda.max_memory_allocated() + del logits, labels, loss, grad + torch.cuda.empty_cache() + return int(peak) + + +def _agree(candidate, baseline, N, V, dtype, seed): + """Candidate must match baseline within tolerance before its peak counts.""" + logits = make_logits(N, V, seed, dtype=dtype) + labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN) + b_loss, b_grad = baseline(logits.clone(), labels, IGN, LS) + with forbidden_ce_guard(): + c_loss, c_grad = candidate(logits.clone(), labels, IGN, LS) + bf16 = dtype == torch.bfloat16 + assert_loss_close(c_loss, b_loss, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]") + assert_grad_close(c_grad, b_grad, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]") + del logits, labels, b_loss, b_grad, c_loss, c_grad + torch.cuda.empty_cache() + + +def main(): + if not torch.cuda.is_available(): + print("CUDA_UNAVAILABLE") + sys.exit(2) + torch.cuda.init() + candidate = load_candidate().cross_entropy_loss_grad + baseline = _baseline_fn() + + ratios = [] + seed = 5000 + for tag, N, V, dtype in SHAPES: + try: + _agree(candidate, baseline, N, V, dtype, seed) + except AssertionError as exc: + print(f"BENCH_FAIL {tag}: {exc}") + print("speedup=0.0") + sys.exit(1) + cand_peak = _peak_of(candidate, N, V, dtype, seed, guard=True) + base_peak = _peak_of(baseline, N, V, dtype, seed, guard=False) + ratio = base_peak / max(cand_peak, 1) + ratios.append(ratio) + print(f"shape={tag} N={N} V={V} dtype={dtype} " + f"baseline_peak={base_peak} candidate_peak={cand_peak} ratio={ratio:.4f}") + seed += 100 + + print(f"speedup={geomean(ratios):.4f}") + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/kb_ce_harness.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/kb_ce_harness.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b8ffe201b463748f8361162d63002528c2f542 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/kb_ce_harness.py @@ -0,0 +1,185 @@ +"""Shared harness for the cross-entropy loss+gradient contract. + +Provides: + * ``load_candidate`` — import the candidate module from /app/repo, + * deterministic input generation (``make_logits`` / ``make_labels``), + * a high-precision float32 reference (``ref_ce``) — the ground truth for both + loss and gradient, + * ``assert_loss_close`` / ``assert_grad_close`` tolerance comparisons, + * ``count_nonzero_rows`` — the work-evidence signal, + * ``geomean``, + * ``forbidden_ce_guard`` — a runtime guard that blocks the framework's + single-call fused cross-entropy loss while the candidate runs, so the + candidate cannot delegate the whole computation to the vendor primitive it + is meant to build. + +The reference materialises full-size buffers on purpose (it is only the +correctness oracle, not scored on memory). +""" + +import contextlib +import importlib.util +import math +import os + +import torch + +# candidate-vs-reference tolerances +LOSS_ATOL = 1e-4 +LOSS_ATOL_BF16 = 3e-2 +LOSS_RTOL = 1e-3 +# bf16 loss carries the dtype's own ~2^-8 (~0.4%) quantization; at a large-vocab +# loss magnitude (~19) that is ~0.075 absolute, which a 1e-3 relative term cannot +# represent. Comparing a correctly bf16-cast loss (reference/oracle) against the +# fp32 baseline loss must tolerate that quantization, so bf16 uses a relative term +# above bf16's resolution. The (N,V) gradient parity check remains the tight, +# authoritative correctness signal. +LOSS_RTOL_BF16 = 8e-3 +GRAD_ATOL = 1e-4 +GRAD_RTOL = 1e-3 +GRAD_ATOL_BF16 = 8e-3 +GRAD_RTOL_BF16 = 1e-2 + + +def repo_dir(): + return os.environ.get("KB_REPO_DIR", "/app/repo") + + +def load_candidate(): + """Import the candidate module from the repo under test.""" + path = os.path.join(repo_dir(), "cross_entropy_grad.py") + spec = importlib.util.spec_from_file_location("candidate_ce_grad", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + if not hasattr(mod, "cross_entropy_loss_grad"): + raise AttributeError(f"{path} does not define cross_entropy_loss_grad()") + return mod + + +# --------------------------------------------------------------------------- # +# Deterministic input generation +# --------------------------------------------------------------------------- # +def make_logits(N, V, seed, dtype=torch.float32, scale=4.0, device="cuda"): + g = torch.Generator(device="cpu").manual_seed(seed) + x = torch.randn(N, V, generator=g, dtype=torch.float32) * scale + return x.to(device).to(dtype) + + +def make_labels(N, V, seed, ignore_frac=0.0, ignore_index=-100, device="cuda"): + g = torch.Generator(device="cpu").manual_seed(seed) + lab = torch.randint(0, V, (N,), generator=g, dtype=torch.int64) + if ignore_frac > 0.0: + mask = torch.rand(N, generator=g) < ignore_frac + lab[mask] = ignore_index + return lab.to(device) + + +# --------------------------------------------------------------------------- # +# High-precision float32 reference (ground truth for loss + grad) +# --------------------------------------------------------------------------- # +def ref_ce(logits, labels, ignore_index=-100, label_smoothing=0.0): + N, V = logits.shape + s = float(label_smoothing) + valid = labels != ignore_index + n_valid = int(valid.sum().item()) + denom = max(n_valid, 1) + safe = labels.clamp(min=0).long() + idx = torch.arange(N, device=logits.device) + + lf = logits.to(torch.float32) + logp = torch.log_softmax(lf, dim=-1) + logp_y = logp[idx, safe] + nll = -logp_y + smooth = -logp.mean(dim=1) + row_loss = (1.0 - s) * nll + s * smooth + row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss)) + loss = row_loss.sum() / denom + + prob = logp.exp() + grad = prob.clone() + if s != 0.0: + grad = grad - (s / V) + grad[idx, safe] = grad[idx, safe] - (1.0 - s) + grad = grad / denom + grad[~valid] = 0.0 + return loss.to(logits.dtype), grad.to(logits.dtype) + + +# --------------------------------------------------------------------------- # +# Comparisons +# --------------------------------------------------------------------------- # +def assert_loss_close(cand_loss, ref_loss, bf16=False, msg=""): + cl = torch.as_tensor(cand_loss).to(torch.float32).reshape(()) + rl = torch.as_tensor(ref_loss).to(torch.float32).reshape(()) + if not torch.isfinite(cl): + raise AssertionError(f"candidate loss is non-finite {msg}") + atol = LOSS_ATOL_BF16 if bf16 else LOSS_ATOL + rtol = LOSS_RTOL_BF16 if bf16 else LOSS_RTOL + d = float((cl - rl).abs()) + tol = atol + rtol * float(rl.abs()) + if d > tol: + raise AssertionError(f"loss mismatch: |{float(cl):.6f}-{float(rl):.6f}|={d:.6f} > {tol:.6f} {msg}") + + +def assert_grad_close(cand_grad, ref_grad, bf16=False, msg=""): + if tuple(cand_grad.shape) != tuple(ref_grad.shape): + raise AssertionError(f"grad shape {tuple(cand_grad.shape)} vs {tuple(ref_grad.shape)} {msg}") + if cand_grad.dtype != ref_grad.dtype: + raise AssertionError(f"grad dtype {cand_grad.dtype} vs {ref_grad.dtype} {msg}") + c = cand_grad.to(torch.float32) + r = ref_grad.to(torch.float32) + if not torch.isfinite(c).all(): + raise AssertionError(f"candidate grad has non-finite values {msg}") + atol = GRAD_ATOL_BF16 if bf16 else GRAD_ATOL + rtol = GRAD_RTOL_BF16 if bf16 else GRAD_RTOL + diff = (c - r).abs() + tol = atol + rtol * r.abs() + bad = diff > tol + if bad.any(): + raise AssertionError( + f"{int(bad.sum())}/{c.numel()} grad elements out of tolerance " + f"(worst excess {float((diff - tol).max()):.5f}) {msg}") + + +def count_nonzero_rows(grad): + """Work-evidence: number of rows whose gradient is not all-zero.""" + return int((grad.to(torch.float32).abs().sum(dim=1) > 0).sum().item()) + + +# --------------------------------------------------------------------------- # +# Runtime guard: block the framework's single-call fused cross-entropy loss +# while the candidate runs (the candidate must compute loss + grad itself). +# --------------------------------------------------------------------------- # +@contextlib.contextmanager +def forbidden_ce_guard(): + def _blocked(*args, **kwargs): + raise RuntimeError("forbidden fused cross-entropy primitive called during scoring") + + class _BlockedModule: + def __init__(self, *a, **k): + raise RuntimeError("forbidden fused cross-entropy primitive called during scoring") + + saved = [] + for obj, name, repl in [ + (torch.nn.functional, "cross_entropy", _blocked), + (torch.nn, "CrossEntropyLoss", _BlockedModule), + ]: + if hasattr(obj, name): + saved.append((obj, name, getattr(obj, name))) + try: + setattr(obj, name, repl) + except Exception: + saved.pop() + try: + yield + finally: + for obj, name, val in reversed(saved): + try: + setattr(obj, name, val) + except Exception: + pass + + +def geomean(values): + vals = [max(float(v), 1e-12) for v in values] + return math.exp(sum(math.log(v) for v in vals) / len(vals)) diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..892b5302eca7645cd5578886abdfd2dedb9ecfc0 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt @@ -0,0 +1 @@ +4.68 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0bbcab67b79c335341dd9a519e47b7d05fe325bb --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# Verifier for insea-fused-softmax-cross-entropy-grad-loop16 (cross-entropy loss + input +# gradient; value axis = PEAK MEMORY, not wall-time). Pattern A, ACCELERATION lane, +# scored on torch.cuda.max_memory_allocated on H20. Modes: candidate|noop|oracle|negative +set -uo pipefail +# Never trust the exec context — the harness may exec this in a +# NON-login shell where bare python3 has no torch. Pin the venv first. +export PATH=/opt/kernelbench-venv/bin:$PATH +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/loop/dev +mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +CAND_FILE="$REPO/cross_entropy_grad.py" +export KB_CANDIDATE_MODULE="$CAND_FILE" +export KB_BASELINE_MODULE=/opt/verifier-baseline/cross_entropy_grad.py + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true +baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true +expected_cases=12; actual_cases=0 +speedup=1.0; ref_speedup=1.0; hw="unknown" + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + # reviewer-only mode: reset the working tree to the frozen baseline so several + # modes running back-to-back in one container session each start clean. candidate/noop + # NEVER resets (this branch is skipped for them), so a solver session is untouched. + git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true + git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed" +fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true + git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true +fi + +# anti-cheat: only cross_entropy_grad.py may change +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + case "$f" in + cross_entropy_grad.py) : ;; + *__pycache__*) : ;; + *) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;; + esac +done < "$LOG/anti_cheat_changed_files.txt" + +# anti-cheat: the framework's single-call fused cross-entropy loss is out of scope +# (the candidate must compute the loss + gradient itself). Textual scan of the file. +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 + anti_cheat_ok=false; add_hard "forbidden_fused_ce_primitive" +fi + +# trusted restore: hidden suite ships in tests/ payload (fresh at scoring) +for f in test_cross_entropy_grad.py gpu_peakmem.py kb_ce_harness.py; do + [ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; } +done + +# ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild) +if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then + ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt") +elif [ -f /opt/verifier-correctness-manifest.json ]; then + 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) +fi +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) + +# correctness gate (needs CUDA) +if [ "$correctness_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 test_cross_entropy_grad.py ) > "$LOG/correctness.log" 2>&1 + crc=$? + actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0} + if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then + hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed" + fi +fi + +# measurement: PEAK MEMORY ratio (baseline_peak/candidate_peak), median over 3 runs +# (deterministic metric; median guards against allocator jitter). Only if correct. +if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then + : > "$LOG/bench.log" + sp_list="" + for r in 1 2 3; do + line=$( cd "$TESTS_DIR" && python3 gpu_peakmem.py 2>>"$LOG/bench.log" ) + echo "$line" >> "$LOG/bench.log" + sp=$(echo "$line" | sed -n 's/.*speedup=\([0-9.-]*\).*/\1/p') + [ -n "$sp" ] && sp_list="$sp_list $sp" + done + speedup=$(python3 -c "v=sorted(float(x) for x in '$sp_list'.split());print(f'{v[len(v)//2]:.5f}' if v else '-1')") + if [ -z "$sp_list" ] || python3 -c "import sys;sys.exit(0 if float('$speedup')<=0 else 1)"; then + benchmark_ok=false; add_hard "benchmark_execution_failed" + fi +else + benchmark_ok=false +fi + +HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi +DIAG_TAIL="" +if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then + DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g') +fi +cat > "$LOG/verifier_state.json" < "$LOG/correctness_results.json" < "$LOG/benchmark_results.json" </dev/null || python3 /tests/compute_reward.py 2>/dev/null || true +REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null) +echo "MODE=$MODE cases=$actual_cases/$expected_cases peakmem_ratio=$speedup ref=$ref_speedup hw=$hw reward=$REW" +[ -n "$REW" ] && exit 0 || exit 1 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test_cross_entropy_grad.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test_cross_entropy_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0b1ff06c8b19d55b240a3db637abfdf7dc1344 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/dev_tests/test_cross_entropy_grad.py @@ -0,0 +1,222 @@ +"""Correctness suite for the cross-entropy loss+gradient contract — 12 cases. + +Each case prints "CASE_PASS " or "CASE_FAIL : ". +The runner greps the number of CASE_PASS lines (expects 12). + +The candidate may overwrite its ``logits`` argument in place, so every case +passes the candidate a fresh clone and computes the reference from the pristine +tensor first. +""" + +import sys +import traceback + +import torch + +from kb_ce_harness import ( + assert_grad_close, + assert_loss_close, + count_nonzero_rows, + forbidden_ce_guard, + load_candidate, + make_labels, + make_logits, + ref_ce, +) + +IGN = -100 +CASES = [] + + +def case(fn): + CASES.append(fn) + return fn + + +def _run(fn, N, V, seed, dtype=torch.float32, ls=0.0, ignore_frac=0.0): + logits = make_logits(N, V, seed, dtype=dtype) + labels = make_labels(N, V, seed + 1, ignore_frac=ignore_frac, ignore_index=IGN) + ref_loss, ref_grad = ref_ce(logits, labels, ignore_index=IGN, label_smoothing=ls) + with forbidden_ce_guard(): + c_loss, c_grad = fn(logits.clone(), labels, IGN, ls) + bf16 = dtype == torch.bfloat16 + tag = f"[N={N} V={V} dtype={dtype} ls={ls} ign={ignore_frac}]" + assert_loss_close(c_loss, ref_loss, bf16=bf16, msg=tag) + assert_grad_close(c_grad, ref_grad, bf16=bf16, msg=tag) + + +@case +def normal_fp32(fn): + _run(fn, 256, 4096, seed=100) + + +@case +def normal_bf16(fn): + _run(fn, 256, 4096, seed=150, dtype=torch.bfloat16) + + +@case +def mean_with_ignore(fn): + _run(fn, 320, 3072, seed=200, ignore_frac=0.35) + + +@case +def all_ignore(fn): + # every row ignored -> loss 0, grad all zero + N, V = 128, 2048 + logits = make_logits(N, V, 300) + labels = torch.full((N,), IGN, dtype=torch.int64, device="cuda") + with forbidden_ce_guard(): + c_loss, c_grad = fn(logits.clone(), labels, IGN, 0.0) + if abs(float(c_loss)) > 1e-5: + raise AssertionError(f"all-ignore loss should be 0, got {float(c_loss)}") + if c_grad.shape != (N, V): + raise AssertionError(f"bad grad shape {tuple(c_grad.shape)}") + if not (c_grad.to(torch.float32) == 0).all(): + raise AssertionError("all-ignore grad should be exactly zero") + + +@case +def single_class(fn): + # V == 1: softmax is 1, loss is 0, grad is 0 + _run(fn, 64, 1, seed=400) + + +@case +def single_row(fn): + _run(fn, 1, 2048, seed=500) + + +@case +def nontile_vocab(fn): + # V not a multiple of any common chunk size + _run(fn, 128, 4099, seed=600) + + +@case +def label_smoothing(fn): + _run(fn, 256, 2048, seed=700, ls=0.1) + + +@case +def error_contract(fn): + N, V = 32, 512 + logits = make_logits(N, V, 800) + labels = make_labels(N, V, 801) + # integer logits -> TypeError + try: + fn(logits.to(torch.int32), labels, IGN, 0.0) + raise AssertionError("integer logits did not raise TypeError") + except TypeError: + pass + # float labels -> TypeError + try: + fn(logits.clone(), labels.to(torch.float32), IGN, 0.0) + raise AssertionError("float labels did not raise TypeError") + except TypeError: + pass + # 1-D logits -> ValueError + try: + fn(logits.reshape(-1).clone(), labels, IGN, 0.0) + raise AssertionError("1-D logits did not raise ValueError") + except ValueError: + pass + # labels wrong length -> ValueError + try: + fn(logits.clone(), labels[:-1], IGN, 0.0) + raise AssertionError("wrong-length labels did not raise ValueError") + except ValueError: + pass + # negative label_smoothing -> ValueError + try: + fn(logits.clone(), labels, IGN, -0.1) + raise AssertionError("negative label_smoothing did not raise ValueError") + except ValueError: + pass + # a non-ignored label out of range [0, V) -> ValueError + bad = labels.clone() + bad[0] = V # out of range, not the ignore sentinel + try: + fn(logits.clone(), bad, IGN, 0.0) + raise AssertionError("out-of-range label did not raise ValueError") + except ValueError: + pass + + +@case +def metamorphic_const_shift(fn): + """Adding a per-row constant to all logits leaves loss AND grad unchanged.""" + N, V = 192, 2048 + logits = make_logits(N, V, 900) + labels = make_labels(N, V, 901) + with forbidden_ce_guard(): + loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0) + g = torch.Generator(device="cpu").manual_seed(902) + # a large positive per-row shift: a numerically stable softmax is invariant, + # while a non-stable one (no max subtraction) overflows -> NaN -> fails here. + shift = (torch.rand(N, generator=g) * 40.0 + 80.0).to(logits.device).to(logits.dtype) + logits_b = logits + shift[:, None] + with forbidden_ce_guard(): + loss_b, grad_b = fn(logits_b.clone(), labels, IGN, 0.0) + assert_loss_close(loss_b, loss_a, msg="[const-shift loss]") + assert_grad_close(grad_b, grad_a, msg="[const-shift grad]") + + +@case +def metamorphic_permute_rows(fn): + """Permuting the rows permutes the gradient rows and leaves the mean loss unchanged.""" + N, V = 256, 2048 + logits = make_logits(N, V, 1000) + labels = make_labels(N, V, 1001, ignore_frac=0.2, ignore_index=IGN) + with forbidden_ce_guard(): + loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0) + g = torch.Generator(device="cpu").manual_seed(1002) + perm = torch.randperm(N, generator=g).to(logits.device) + with forbidden_ce_guard(): + loss_b, grad_b = fn(logits[perm].clone(), labels[perm], IGN, 0.0) + assert_loss_close(loss_b, loss_a, msg="[permute loss]") + assert_grad_close(grad_b, grad_a[perm], msg="[permute grad]") + + +@case +def work_evidence(fn): + """Exactly the non-ignored rows carry a nonzero gradient; ignored rows are zero.""" + N, V = 384, 2048 + logits = make_logits(N, V, 1100) + labels = make_labels(N, V, 1101, ignore_frac=0.5, ignore_index=IGN) + n_valid = int((labels != IGN).sum().item()) + with forbidden_ce_guard(): + _, c_grad = fn(logits.clone(), labels, IGN, 0.0) + nz = count_nonzero_rows(c_grad) + if nz != n_valid: + raise AssertionError(f"nonzero-grad rows {nz} != valid labels {n_valid}") + ignored = (labels == IGN) + if ignored.any() and not (c_grad[ignored].to(torch.float32) == 0).all(): + raise AssertionError("ignored rows have nonzero gradient") + + +def main(): + if not torch.cuda.is_available(): + print("CUDA_UNAVAILABLE") + sys.exit(2) + mod = load_candidate() + fn = mod.cross_entropy_loss_grad + passed = 0 + for fn_case in CASES: + name = fn_case.__name__ + try: + fn_case(fn) + torch.cuda.synchronize() + passed += 1 + print(f"CASE_PASS {name}") + except Exception as exc: # noqa: BLE001 + reason = f"{type(exc).__name__}: {exc}" + print(f"CASE_FAIL {name}: {reason.splitlines()[0][:300]}") + traceback.print_exc(file=sys.stderr) + total = len(CASES) + print(f"CASES_PASSED={passed}/{total}") + sys.exit(0 if passed == total else 1) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/manifest.json b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..85b0145be90f9325234c46872383a6db3df5bbad --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/private/manifest.json @@ -0,0 +1,11 @@ +{ + "base_task_id": "insea-fused-softmax-cross-entropy-grad-loop16", + "dev_engine": "private/dev_tests/test.sh (= the task verifier VERBATIM, output redirected to /logs/loop/dev, candidate mode)", + "max_submissions": 1, + "min_submissions": 1, + "note": "root-only (0700). ref_speedup is a protected secret; the sanitizer never emits it.", + "ref_speedup": 7.4157, + "reward_formula": "acceleration: reward = speedup (raw measured ratio, uncapped; 0 if a gate fails). Matches the base compute_reward.py verbatim.", + "schema_version": "kernelbench_loop_manifest_v1", + "task_id": "insea-fused-softmax-cross-entropy-grad-loop16" +} diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/sanitize_feedback.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/sanitize_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..971cde9125d41748cad56c07d09b16cc68f15156 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/sanitize_feedback.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Sanitized feedback emitter (0700 root-owned) for insea-fused-softmax-cross-entropy-grad-loop16. + +Invoked ONLY by /opt/loop/submit.sh. Reads the DEV engine products under +/logs/loop/dev/ and the loop accounting under /logs/loop/, and prints ONLY a +leak-free summary. + +Emits (nothing else, ever): + submission k/16 + correctness: PASS | FAIL + [FAIL only] failing_invariant: + [FAIL only] diagnostic: + dev_speedup: (relative performance ratio vs the reference baseline; higher is better) + dev_reward: (= dev_speedup when correct, else 0; an in-session PROXY) + best_so_far: submission , dev_speedup , dev_reward + remaining: <16 - k> + finalize_allowed: + [harness path] harness_error: (candidate not at fault; budget not consumed) + +NEVER emits: verifier / test.sh / compute_reward contents; hidden workload +names / seeds / counts / shapes; any threshold; ref_speedup; absolute timings or +byte counts; actual_hardware_type. +""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +LOOP = Path("/logs/loop") +DEV = LOOP / "dev" +MIN_SUBMISSIONS = 3 +MAX_SUBMISSIONS = 16 + +SIGNATURE = 'cross_entropy_loss_grad(logits, labels, ignore_index, label_smoothing) -> (loss, grad)' +PRIMITIVE_HINT = 'your implementation references a forbidden fused cross-entropy primitive (F.cross_entropy / CrossEntropyLoss) — compute the loss and input gradient yourself' + + +def _read_json(path: Path, default): + try: + return json.loads(path.read_text(encoding="utf-8")) + except Exception: + return default + + +def _fmt(x, nd=4): + try: + return f"{float(x):.{nd}g}" + except Exception: + return str(x) + + +def _named_invariant(state: dict): + hard = [str(r) for r in (state.get("hard_fail_reasons") or [])] + + def has(*subs): + return any(any(s in h for s in subs) for h in hard) + + if has("forbidden_edit_path", "forbidden_source"): + return ("edit_scope", + "only the single product file may change and it must not reference any " + "scoring / verifier path — keep your edits to the product implementation only") + if has("_primitive", "_operator"): + return ("allowed_ops", PRIMITIVE_HINT) + if has("product_file_missing", "candidate_load_failed", "repo_missing"): + return ("product_present_and_importable", + f"the product could not be found or imported — keep the public {SIGNATURE} intact") + if has("hidden_correctness_failed"): + return ("output_matches_reference", + "your output disagreed with the reference on at least one case (numeric tolerance, " + "dtype / shape / device, an error-contract probe that must raise, or a metamorphic " + f"invariant) — verify the contract of {SIGNATURE}") + if has("benchmark_execution_failed"): + return ("runs_without_error", + "the measurement could not complete — your implementation likely raised, produced " + "non-finite values, or disagreed with the baseline while being measured") + return ("verifier_completed", + "the check did not complete cleanly — re-check that your last change did not cause an early crash") + + +def main() -> int: + try: + k = int((LOOP / "count").read_text(encoding="utf-8").strip()) + except Exception: + k = 0 + + he = DEV / "harness_error.txt" + if he.exists(): + try: + msg = he.read_text(encoding="utf-8").strip().splitlines()[0] + except Exception: + msg = "dev engine infrastructure error" + print(f"submission {k}/{MAX_SUBMISSIONS}") + print(f"harness_error: {msg} — this is NOT a defect in your code; do not debug the " + f"harness. Retry or continue optimizing (this attempt was not counted).") + return 0 + + state = _read_json(DEV / "verifier_state.json", {}) + bench = _read_json(DEV / "benchmark_results.json", {}) + reward = _read_json(DEV / "reward.json", {}) + + corr_ok = bool(state.get("correctness_ok")) + speedup = bench.get("aggregate_speedup", None) + r = reward.get("reward", 0.0) + + print(f"submission {k}/{MAX_SUBMISSIONS}") + if corr_ok: + print("correctness: PASS") + else: + print("correctness: FAIL") + inv, hint = _named_invariant(state) + print(f"failing_invariant: {inv}") + print(f"diagnostic: {hint}") + + print(f"dev_speedup: {_fmt(speedup) if speedup is not None else 'n/a'}") + print(f"dev_reward: {_fmt(r)}") + + best = _read_json(LOOP / "best.json", None) + if best and isinstance(best, dict) and best.get("submission"): + print(f"best_so_far: submission {best.get('submission')}, " + f"dev_speedup {_fmt(best.get('speedup'))}, dev_reward {_fmt(best.get('reward'))}") + else: + print("best_so_far: (none — no correctness-passing submission yet)") + + print(f"remaining: {max(0, MAX_SUBMISSIONS - k)}") + print(f"finalize_allowed: {'true' if k >= MIN_SUBMISSIONS else 'false'}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/score_engine.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/score_engine.sh new file mode 100644 index 0000000000000000000000000000000000000000..5217b1b9033321583f7784e4d3f0e3c0b05289c1 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/score_engine.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# DEV scoring engine (0700 root:root) for insea-fused-softmax-cross-entropy-grad-loop16. Invoked ONLY by +# /opt/loop/submit.sh — never by the solver. +# +# It reuses the task verifier VERBATIM: it runs the baked copy of the base +# task's tests/test.sh (byte-identical except its output dir is /logs/loop/dev +# instead of /logs/verifier) against the LIVE /app/repo in the default candidate +# mode (which scores /app/repo AS-IS and never clobbers it). The base +# compute_reward.py writes reward = speedup (uncapped). The authoritative reward +# still comes from the runner's end-of-session /tests/ run, NOT from here. +# +# PATH-pin: the agent shell + runner verifier exec are +# NON-login; bare python3 has no torch. Pin the venv FIRST. +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 +set -uo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DEV_OUT="${LOOP_DEV_OUT:-/logs/loop/dev}" +mkdir -p "$DEV_OUT" +# fresh run: clear any stale harness marker +rm -f "$DEV_OUT/harness_error.txt" 2>/dev/null || true + +# Run the baked task verifier (candidate mode). Suppress its stdout entirely +# (the base test.sh echoes a summary line carrying ref_speedup / hardware / raw +# speedup — that MUST NOT reach the solver; only sanitize_feedback.py emits). +KERNELBENCH_VERIFY_MODE=candidate bash "$HERE/private/dev_tests/test.sh" \ + > "$DEV_OUT/dev_engine_stdout.log" 2>&1 +rc=$? + +# If the base verifier could not even write a reward (infra/torch/cuda failure), +# it exits non-zero WITHOUT a reward.json. Synthesize a harness marker so +# submit.sh treats it as infra (does not consume the solver's budget) rather than +# a silent candidate FAIL. +if [ "$rc" -ne 0 ] && [ ! -f "$DEV_OUT/reward.json" ] && [ ! -f "$DEV_OUT/harness_error.txt" ]; then + { + echo "dev_engine_exit_${rc}" + tail -n 40 "$DEV_OUT/dev_engine_stdout.log" 2>/dev/null + } > "$DEV_OUT/harness_error.txt" + exit 3 +fi +exit 0 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/submit.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/submit.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea2c6e2c55f13455d9a5421461799d331d7c7937 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/loop/submit.sh @@ -0,0 +1,232 @@ +#!/usr/bin/env bash +# Per-task 3-to-16-submission loop harness for +# insea-fused-softmax-cross-entropy-grad-loop16. +# +# The solver's ONLY sanctioned interface to scoring during the session +# (0755 root:root; the engine + private assets it calls are 0700 root-owned). +# Baked at /opt/loop/submit.sh so it is present from the first turn — unlike +# /tests/, which the runner creates only AFTER the agent finishes. +# +# Usage: +# bash /opt/loop/submit.sh # score current /app/repo, get feedback +# bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best iterate, end loop +# +# Each `submit`: +# 1. runs the baked DEV engine (visible-subset correctness + dev timing) on +# the LIVE /app/repo and returns SANITIZED feedback; +# 2. snapshots the candidate tree (git stash-create tree hash + binary diff) +# to /logs/loop/submissions//; +# 3. updates /logs/loop/best.json (best correctness-passing dev_reward); +# 4. enforces min=3 / max=16. +# On --finalize (>=3) or auto at k=16 it restores /app/repo's WORKING TREE to +# the best correctness-passing snapshot (HEAD stays at the baseline commit so +# the runner's end-of-session verifier still sees a product-only modification) +# and writes /logs/loop/finalize.json for the audit. +# +# 🔴 PATH-pin: the agent shell + runner verifier exec are +# NON-login; bare python3 has no torch. Pin the venv FIRST. +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 +set -uo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOOP=/logs/loop +DEV="$LOOP/dev" +mkdir -p "$LOOP" "$LOOP/submissions" "$DEV" + +MIN_SUBMISSIONS=1 +MAX_SUBMISSIONS=1 +COUNT_FILE="$LOOP/count" +BEST_FILE="$LOOP/best.json" +STATE_JSONL="$LOOP/state.jsonl" +FINALIZE_JSON="$LOOP/finalize.json" + +_read_count() { + if [ -f "$COUNT_FILE" ]; then + awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE" + else + echo 0 + fi +} + +# Non-mutating snapshot of the current working tree -> a git tree hash. +# `git stash create` builds dangling objects without touching HEAD/index/WT. +_snapshot_tree() { + local c + c="$(git -C "$REPO" stash create 2>/dev/null || true)" + if [ -n "$c" ]; then + git -C "$REPO" rev-parse "$c^{tree}" 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null + else + git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null + fi +} + +# ------------------- argument parsing ------------------- +MODE=submit +REASON="" +while [ "$#" -gt 0 ]; do + case "$1" in + --finalize) MODE=finalize; shift ;; + --reason) REASON="${2:-}"; shift 2 ;; + --reason=*) REASON="${1#--reason=}"; shift ;; + *) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"\"]]" >&2; exit 2 ;; + esac +done + +# ------------------- finalize ------------------- +if [ "$MODE" = finalize ]; then + CUR="$(_read_count)"; CUR="${CUR:-0}" + if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then + echo "minimum $MIN_SUBMISSIONS submission(s) required before finalize (you have $CUR/$MIN_SUBMISSIONS)" + exit 1 + fi + # Restore /app/repo working tree to the best correctness-passing snapshot. + git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true + git -C "$REPO" clean -qfd 2>/dev/null || true + WIN_DIFF="" + WIN_SUB="" + if [ -f "$BEST_FILE" ]; then + WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)" + fi + if [ -n "$WIN_SUB" ] && [ -f "$LOOP/submissions/$WIN_SUB/candidate.diff" ]; then + WIN_DIFF="$LOOP/submissions/$WIN_SUB/candidate.diff" + if [ -s "$WIN_DIFF" ]; then + git -C "$REPO" apply --whitespace=nowarn "$WIN_DIFF" 2>"$LOOP/finalize_apply.log" || \ + echo "WARNING: could not re-apply the winning diff cleanly; see /logs/loop/finalize_apply.log" >&2 + fi + fi + # Write finalize.json (winning index, k, dev_speedup trajectory, reason) for audit. + REASON="$REASON" WIN_SUB="$WIN_SUB" CUR="$CUR" python3 - <<'PY' +import json, os +from pathlib import Path +LOOP = Path('/logs/loop') +best = {} +try: + best = json.loads((LOOP / 'best.json').read_text()) +except Exception: + best = {} +traj = [] +try: + for line in (LOOP / 'state.jsonl').read_text().splitlines(): + line = line.strip() + if not line: + continue + row = json.loads(line) + traj.append({'submission': row.get('submission'), + 'dev_speedup': row.get('speedup'), + 'dev_reward': row.get('reward'), + 'correctness_ok': row.get('correctness_ok')}) +except Exception: + pass +win = best.get('submission') if best else None +out = { + 'schema_version': 'kernelbench_loop_finalize_v1', + 'task_id': 'insea-fused-softmax-cross-entropy-grad-loop16', + 'mode': 'baked', + 'submissions_used': int(os.environ.get('CUR') or 0), + 'min_submissions': 1, 'max_submissions': 1, + 'winning_submission': win, + 'winning_dev_speedup': best.get('speedup') if best else None, + 'winning_dev_reward': best.get('reward') if best else None, + 'winning_tree': best.get('tree') if best else None, + 'dev_speedup_trajectory': traj, + 'termination_reason': os.environ.get('REASON') or '', + 'note': 'dev_reward is an in-session proxy; meta.reward is the runner end-of-session score of /app/repo.', +} +(LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n') +PY + # Integrity: recompute the restored tree hash for the audit trail. + RESTORED_TREE="$(_snapshot_tree)" + echo "restored_tree=$RESTORED_TREE" >> "$LOOP/finalize_apply.log" 2>/dev/null || true + if [ -n "$WIN_SUB" ]; then + 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 "? ?")" + echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (dev_speedup ${WR% *}, dev_reward ${WR#* }); the grader will now score /app/repo" + else + 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" + fi + exit 0 +fi + +# ------------------- submit ------------------- +CUR="$(_read_count)"; CUR="${CUR:-0}" +if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then + echo "submission $CUR/$MAX_SUBMISSIONS" + echo "budget exhausted — call 'bash /opt/loop/submit.sh --finalize' to grade your best submission" + # Auto-finalize as a safety net. + echo "--- auto-finalizing best-of-$MAX_SUBMISSIONS ---" + exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling" +fi + +# Run the DEV engine on the LIVE /app/repo. +bash "$HERE/score_engine.sh" +engine_rc=$? + +# HARNESS error path: the engine flagged an infra failure (rc=3 or a marker). +# Do NOT consume the solver's budget for our bug. +if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then + python3 "$HERE/sanitize_feedback.py" + exit 0 +fi + +# Consume one submission. +NEXT=$((CUR + 1)) +echo "$NEXT" > "$COUNT_FILE" + +# Snapshot the candidate: tree hash (non-mutating) + binary diff vs baseline HEAD. +SNAP="$LOOP/submissions/$NEXT" +mkdir -p "$SNAP" +TREE="$(_snapshot_tree)" +git -C "$REPO" diff --binary HEAD > "$SNAP/candidate.diff" 2>/dev/null || true +echo "${TREE:-}" > "$SNAP/tree.txt" +for f in verifier_state.json correctness_results.json benchmark_results.json reward.json; do + [ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true +done + +# Update best-of-k (only correctness-passing, strictly-greater dev_reward) and +# append the per-submission audit row. +NEXT="$NEXT" TREE="$TREE" python3 - <<'PY' +import json, os, time +from pathlib import Path +LOOP = Path('/logs/loop'); DEV = LOOP / 'dev' +k = int(os.environ['NEXT']); tree = os.environ.get('TREE') or '' +try: + state = json.loads((DEV / 'verifier_state.json').read_text()) +except Exception: + state = {} +try: + reward = json.loads((DEV / 'reward.json').read_text()) +except Exception: + reward = {} +corr_ok = bool(state.get('correctness_ok')) +r = float(reward.get('reward') or 0.0) +s = float(reward.get('speedup') or 0.0) +# append audit row +row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok, + 'reward': r, 'speedup': s, 'tree': tree, + 'hard_fail_reasons': list(state.get('hard_fail_reasons') or [])} +with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f: + f.write(json.dumps(row) + '\n') +# update best +if corr_ok: + best_p = LOOP / 'best.json' + try: + best = json.loads(best_p.read_text()) + except Exception: + best = None + if best is None or r > float(best.get('reward') or -1.0): + best_p.write_text(json.dumps( + {'submission': k, 'reward': r, 'speedup': s, 'tree': tree}, + indent=2, sort_keys=True) + '\n') +PY + +# Print sanitized feedback. +python3 "$HERE/sanitize_feedback.py" + +# Auto-finalize on the ceiling. +if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then + echo "" + echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---" + exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling" +fi + +exit 0 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/repo/cross_entropy_grad.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/repo/cross_entropy_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..ff781cc0899ec84a9be43ed4603f34d4bbb842bb --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/repo/cross_entropy_grad.py @@ -0,0 +1,106 @@ +"""Cross-entropy loss and input-gradient over a batch of logit rows. + +Public entry point: + ``cross_entropy_loss_grad(logits, labels, ignore_index=-100, + label_smoothing=0.0) -> (loss, grad)`` + +Given a batch of ``N`` rows of class scores (``logits``) and one integer target +class per row (``labels``), compute the mean cross-entropy loss over the +non-ignored rows and the gradient of that loss with respect to ``logits``. + +Contract +-------- +- ``logits``: shape ``(N, V)``, a floating-point CUDA tensor (``float32`` or + ``bfloat16``). ``N`` is the number of rows (batch * sequence), ``V`` the + number of classes (vocabulary size). +- ``labels``: shape ``(N,)``, an integer CUDA tensor. Each entry is a class + index in ``[0, V)``, or equals ``ignore_index`` to mark the row as ignored. +- ``ignore_index``: int. Rows whose label equals this value contribute zero to + the loss and zero to the gradient. +- ``label_smoothing``: float ``>= 0``. ``0.0`` is ordinary cross entropy. + +Returns +------- +- ``loss``: a scalar tensor — the mean cross-entropy (with optional label + smoothing) over the non-ignored rows. If every row is ignored, the loss is + ``0``. +- ``grad``: shape ``(N, V)``, same dtype as ``logits`` — the gradient of + ``loss`` w.r.t. ``logits``. Ignored rows are exactly zero. + +Definition (per non-ignored row with target ``y``, over ``n`` non-ignored rows): + ``p = softmax(logits)`` + ``loss_row = -(1 - s) * log p[y] - (s / V) * sum_k log p[k]`` + ``grad_row[j] = ( p[j] - s / V - (1 - s) * [j == y] ) / n`` +where ``s = label_smoothing``. All reductions are computed in float32; the +gradient is returned in the input dtype. + +Error contract +-------------- +- ``TypeError`` if ``logits`` is not a floating-point tensor, or ``labels`` is + not an integer tensor. +- ``ValueError`` if ``logits`` is not 2-D; if ``labels`` is not 1-D of length + ``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies + outside ``[0, V)``. + +Note on the current implementation +---------------------------------- +This straightforward implementation forms the full log-probability tensor, the +full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers +in addition to the input. It is correct but holds several full-size copies of +the logits at once, which is expensive at large ``V``. +""" + +import torch + + +def _validate(logits, labels, label_smoothing): + if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor): + raise TypeError("logits and labels must be torch.Tensor") + if not torch.is_floating_point(logits): + raise TypeError(f"logits must be a floating-point tensor, got {logits.dtype}") + if labels.dtype not in (torch.int32, torch.int64): + raise TypeError(f"labels must be an integer tensor, got {labels.dtype}") + if logits.dim() != 2: + raise ValueError(f"logits must be 2-D (N, V), got {logits.dim()}-D") + N, V = logits.shape + if labels.dim() != 1 or labels.shape[0] != N: + raise ValueError(f"labels must be 1-D of length N={N}, got shape {tuple(labels.shape)}") + if float(label_smoothing) < 0.0: + raise ValueError(f"label_smoothing must be >= 0, got {label_smoothing}") + return N, V + + +def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0): + """See module docstring for the full contract.""" + N, V = _validate(logits, labels, label_smoothing) + s = float(label_smoothing) + + valid = labels != ignore_index + # non-ignored labels must be inside [0, V) + if valid.any(): + vlab = labels[valid] + if int(vlab.max()) >= V or int(vlab.min()) < 0: + raise ValueError(f"a non-ignored label is out of range [0, {V})") + n_valid = int(valid.sum().item()) + denom = max(n_valid, 1) + + safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later) + idx = torch.arange(N, device=logits.device) + + lf = logits.to(torch.float32) + logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer + logp_y = logp[idx, safe] # (N,) + nll = -logp_y + smooth = -logp.mean(dim=1) # -mean_k log p[k] + row_loss = (1.0 - s) * nll + s * smooth + row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss)) + loss = row_loss.sum() / denom + + prob = logp.exp() # (N, V) softmax + grad = prob.clone() # (N, V) gradient buffer + if s != 0.0: + grad = grad - (s / V) + grad[idx, safe] = grad[idx, safe] - (1.0 - s) + grad = grad / denom + grad[~valid] = 0.0 # ignored rows -> exactly zero + return loss, grad.to(logits.dtype) diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/entrypoint.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..afb6b3a676be47747faa41f869854aa68ebaceb6 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/entrypoint.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Matches the proven ready-task entrypoint (kernel-opt-p0a4-003): start the timer +# in the background and hand the container to a login shell so the orchestrator can +# keep it alive and exec /tests/test.sh into it. `exec "$@"` is honored when a +# command is passed (e.g. local smoke). +set -euo pipefail +export PATH=/opt/kernelbench-venv/bin:$PATH +mkdir -p /app/.timer +/app/timer.sh >/tmp/task-timer.log 2>&1 & +if [ "$#" -gt 0 ]; then + exec "$@" +fi +exec /bin/bash -l diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/run_dev_bench.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/run_dev_bench.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac8d5a1eeaed151767461638f6d9d640da582166 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/run_dev_bench.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH=/opt/kernelbench-venv/bin:$PATH +printf '%s\n' 'Public development feedback only. Final verification runs additional trusted and hidden workloads.' +exit 0 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/timer.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/timer.sh new file mode 100644 index 0000000000000000000000000000000000000000..02db7dbf1675f1055bc5d37a6f7e5b79ba66a946 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/runtime/timer.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Minimal global timer stub; the harness replaces it with the real budget timer. +set -euo pipefail +export PATH=/opt/kernelbench-venv/bin:$PATH +mkdir -p /app/.timer +echo 10800 > /app/.timer/remaining_secs +echo 10800 > /app/.timer/budget_secs diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/verifier-correctness-manifest.json b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/verifier-correctness-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..7cdf983fc26504628522793075369be11e6d0aba --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/environment/verifier-correctness-manifest.json @@ -0,0 +1,31 @@ +{ + "schema_version": "kernelbench_correctness_manifest_v1", + "task_id": "insea-fused-softmax-cross-entropy-grad-loop16", + "task_kind": "acceleration", + "expected_case_count": 12, + "primary_workload": "ce-peakmem-geomean-4shapes", + "ref_speedup": 1.0, + "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.", + "metric": "peak_memory_bytes", + "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).", + "direction": "higher_is_better", + "target_hardware": "H20", + "correctness_axes": [ + "normal", + "boundary", + "all_ignore", + "single_class", + "single_row", + "nontile_vocab", + "label_smoothing", + "degenerate", + "error", + "metamorphic", + "work_evidence", + "anti_hacking" + ], + "public_symbol": "cross_entropy_loss_grad", + "primary_edit_paths": [ + "/app/repo/cross_entropy_grad.py" + ] +} diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/instruction.md b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..059f277b5f7245174939cc9f5f63f7b1960cbef8 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/instruction.md @@ -0,0 +1,143 @@ +# Performance Optimization Task + +You are working on the loss stage of a large language model's training step. The +file `cross_entropy_grad.py` implements `cross_entropy_loss_grad` — it takes a +batch of per-row class scores (`logits`) and one integer target class per row +(`labels`) and returns the mean cross-entropy loss together with the gradient of +that loss with respect to `logits`. + +## Behavioral contract + +For a batch of `N` rows over `V` classes, each non-ignored row contributes the +**cross entropy between a smoothed target distribution and that row's softmax over +the `V` classes**, in the standard PyTorch label-smoothing convention: with +`s = label_smoothing`, the target distribution places weight `1 - s` on the row's own +label and spreads the remaining `s` **uniformly across all `V` classes, the label +included**. The returned `loss` is the mean of those per-row losses over the +non-ignored rows only (ignored rows enter neither the sum nor the row count). The +returned `grad` is the exact gradient of that returned mean loss with respect to +`logits`, one row per input row, with ignored rows carrying an all-zero gradient row. + +1. `logits`: shape `(N, V)`, a floating-point CUDA tensor (`torch.float32` or + `torch.bfloat16`). `N` is the number of rows (batch times sequence length), + `V` the number of classes (vocabulary size). +2. `labels`: shape `(N,)`, an integer CUDA tensor. Each entry is a class index in + `[0, V)`, **or** equals `ignore_index` to mark that row as ignored. Ignored + rows contribute **zero** loss and **zero** gradient. +3. `ignore_index`: int (default `-100`). +4. `label_smoothing`: float `>= 0` (default `0.0`; `0.0` is ordinary cross + entropy). + +Reductions are computed in float32; the gradient is returned in the input dtype. + +Public signature (do NOT change): + +```python +def cross_entropy_loss_grad( + logits: torch.Tensor, # (N, V) float32/bfloat16 CUDA + labels: torch.Tensor, # (N,) integer CUDA; ignore_index marks ignored rows + ignore_index: int = -100, + label_smoothing: float = 0.0, +) -> tuple: # (loss: scalar tensor, grad: (N, V) same dtype as logits) +``` + +Error contract: non-floating-point `logits`, or non-integer `labels` → +`TypeError`; `logits` not 2-D, `labels` not 1-D of length `N`, negative +`label_smoothing`, or any non-ignored label outside `[0, V)` → `ValueError`. + +## What to improve + +The current implementation is **correct but wasteful with intermediate state**: at +large vocabulary sizes the intermediates it keeps resident dominate the memory +footprint. Read it yourself and work out which buffers are alive at the same time. + +Your goal is to produce the **same** loss and gradient while holding a far smaller +retained set — the extra working set beyond the input `logits` buffer should stay +small (on the order of `O(N)` plus a bounded working set, not another `O(N * V)`). +You are permitted to write the gradient into the `logits` buffer in place (the caller +passes a buffer you are free to overwrite). Use any GPU technique available in the +image as long as the contract above holds and the result stays within the verifier's +tolerance. + +**Forbidden:** the framework's single-call fused cross-entropy loss — +`torch.nn.functional.cross_entropy` / `F.cross_entropy` and +`torch.nn.CrossEntropyLoss`. The scoring harness blocks these at runtime and +scans your submitted file for them (do not reference them even in comments — the +scan is textual and scores the task 0). Compute the loss and gradient yourself. + +## Correctness comes first + +The verifier compares your `loss` and full `grad` against a high-precision +reference on multiple workloads — ordinary and label-smoothed, rows with the +ignore sentinel (including an all-ignored batch), a single class (`V = 1`), a +single row, a vocabulary size that is not a round multiple, degenerate inputs, +error-contract probes, metamorphic checks (adding a per-row constant to all +logits leaves loss and gradient unchanged; permuting rows permutes the gradient +rows), and a work-evidence check (exactly the non-ignored rows carry a nonzero +gradient) — within a fixed tolerance. A result outside tolerance on even one case +scores zero. + +## Scope + +Optimize the product implementation in `cross_entropy_grad.py` only. Do **not** +edit tests, benchmark harnesses, workloads, or dependency/build files. The final +submitted diff must contain only product-code changes. + +## How this task is scored — ONE single graded submission (READ CAREFULLY) + +You get **exactly one** graded submission. There is no iteration loop, no budget +of retries, and no feedback round you can act on: **submitting ends the task.** + +1. Work on `/app/repo/cross_entropy_grad.py` until you believe it is both **correct** and as + memory-frugal as you can make it. Test it yourself as much as you like — + your own scratch scripts, your own timing harnesses, your own reasoning about + the code path. None of that costs you anything. +2. When — and only when — you are done, submit **once**: + + ``` + bash /opt/loop/submit.sh + ``` + +3. **That call is final.** It scores the current state of `/app/repo`, records it, + and closes the task. A second call to `submit.sh` is refused and exits non-zero. + You will not get another attempt, and you will not get iterative feedback you + can use to improve — whatever `/app/repo` contains at that moment is what is + graded. + +Because you cannot iterate, **think the design through before you submit** and +self-test thoroughly: read the current implementation, decide on the change, +convince yourself the contract still holds on the normal, boundary, degenerate and +error-path cases described above, and only then submit. A submission that is fast +but wrong on even one case scores zero, and you cannot repair it afterwards. + +The grade is produced by a full, trusted end-of-session verifier (more workloads +than anything you can see), so the submitted state must be genuinely correct — not +just correct on the cases you happened to try. + +## 🔴 Red line (hard — ANY one of these makes the whole task score 0) + +The scoring machinery is off-limits. Solve this task **independently**, using +ONLY the code in `/app/repo`, the sanitized feedback that `submit.sh` returns, +and your own knowledge and reasoning. + +- Do **NOT** read, `cat`, `open`, `less`, `head`/`tail`, `grep`, `find`, or edit + ANY verifier / correctness / timing / scoring / hidden-test file or directory, + wherever it may live. Running `bash /opt/loop/submit.sh` is the ONLY sanctioned + interaction with the scoring machinery. +- Do **NOT** run any verifier directly or try to reproduce or reverse-engineer it + — score ONLY by calling `bash /opt/loop/submit.sh`. +- Do **NOT** search for, print, or infer the hidden workloads, seeds, thresholds, + the metric name, or the reference speedup from any source. +- Do **NOT** fetch or look up the source PR, the upstream repository, or a + reference solution (no web search, no `git` remote fetch, no network to the + source), whether the internet is on or off. +- Do **NOT** use, quote, or condition your code on any verifier / scoring / source + material, however you might have come to see it. + +Stay inside `/app/repo` and scratch directories you create yourself; use only +what `submit.sh` returns for scoring signal. + +## 提交方式 + +本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。 +改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/pre_artifacts.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..60dcab5f288fd025127afcae257bdbedac46bf3d --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/pre_artifacts.sh @@ -0,0 +1,162 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/insea-fused-softmax-cross-entropy-grad-loop16 +# +# Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE +# grading (spec §1.1). It turns whatever the agent left behind into a portable artifact: +# +# /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit +# /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line +# +# 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one +# place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs ..HEAD). +# Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate, +# `git checkout -q HEAD -- ` re-materialises the baseline for the paired timing, +# and loop16's `submit.sh --finalize` plants the best iterate with read-tree + +# checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope +# gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the +# "baseline" — and a correct solve scores 0. +# `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages +# names only, writes no tree, creates no commit and leaves HEAD exactly where it was. +# +# EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier +# scores the container on its own terms and gives 0 by itself. +# +# READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index +# (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the +# verifier — which runs after us — sees exactly the `git status --porcelain` it would have +# seen if this script had never run. No commit, no HEAD move, no working-tree write. +# +# CAPTURE ROOTS for THIS task — derived from the package, never assumed: +# /app/repo git repo, HEAD == the 1-commit carved baseline +# evidence Dockerfile:142: WORKDIR /app/repo +# evidence Dockerfile:90: && cd /app/repo \ +# evidence Dockerfile:97: && test "$(git rev-list --count HEAD)" = "1" \ +# evidence test.sh:10: REPO=/app/repo +# +# Single root => model.patch is a bare `git diff --binary ` (no banner). +# model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable +# by one reader. +# +# loop16 task (environment/loop/ -> /opt/loop in the image): the harness auto-finalizes +# at k=16 and `submit.sh --finalize` plants the best iterate in the WORKING TREE while +# HEAD stays on the baked baseline — which is exactly what this script captures. Running +# it after a finalize therefore yields the GRADED artifact, not the last raw edit. +# ============================================================================ +set -uo pipefail + +OUT=/logs/artifacts +PATCH="$OUT/model.patch" +LIST="$OUT/model_files.txt" +MULTI=0 # 1 => several capture roots => each diff gets a banner line +MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane) + +mkdir -p "$OUT" 2>/dev/null || true +: > "$PATCH" 2>/dev/null || true +: > "$LIST" 2>/dev/null || true +git config --global --add safe.directory '*' >/dev/null 2>&1 || true + +banner() { # $1=root $2=mode ; only when there is more than one root + if [ "$MULTI" = 1 ]; then + printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null + fi + return 0 +} + +list_add() { # stdin: paths relative to $1 -> absolute, one per line + sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true + return 0 +} + +capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot" + capture_tree "$root" + return 0 + fi + # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and + # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could + # flip a scope gate either way. So copy the repo's index aside and stage into the COPY — + # the repo's own .git/index is byte-identical when we are done. + tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi="" + gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true) + if [ -z "$gd" ]; then + gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true) + case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac + fi + if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then + GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE + else + echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index" + fi + git -C "$root" add -AN . >/dev/null 2>&1 || true + base=HEAD + if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then + base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null) + echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree" + else + n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0) + case "$n" in ''|*[!0-9]*) n=0 ;; esac + if [ "$n" -gt 1 ]; then + base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1) + echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:" + echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so" + echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved" + echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve." + fi + fi + [ -n "${base:-}" ] || base=HEAD + banner "$root" "git-diff-vs-baseline" + git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true + names=$(git -C "$root" diff --name-only "$base" 2>/dev/null) + echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)" + unset GIT_INDEX_FILE + [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null + printf '%s\n' "$names" | grep -v '^$' | list_add "$root" + return 0 +} + +capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0 + if git init -q "$tmp/snap" >/dev/null 2>&1; then + GD="$tmp/snap/.git" + empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null) + ( cd "$root" 2>/dev/null || exit 0 + find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \ + 2>/dev/null \ + | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true + banner "$root" "tree-snapshot-not-a-git-repo" + GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \ + >> "$PATCH" 2>/dev/null || true + else + echo "[pre_artifacts] WARN could not stage a snapshot index for $root" + fi + rm -rf "$tmp" 2>/dev/null || true + all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f -print 2>/dev/null | sed 's|^\./||' ) + printf '%s\n' "$all" | grep -v '^$' | list_add "$root" + big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \ + -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . ) + echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)" + if [ "${big:-0}" != 0 ]; then + echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in" + echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch." + fi + return 0 +} + +capture_git "/app/repo" +bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0) +case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac +echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)" +if [ "$bytes" -gt 67108864 ]; then + echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build" + echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also" + echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish." +fi +exit 0 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/README.md b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a396725758ac7cd86373fbfcf1556957f5f1753a --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/README.md @@ -0,0 +1,13 @@ +# solution/ — reviewer-only 参考实现 + +本目录里的补丁**不进镜像**(已被上下文根的 `.dockerignore` 排除)、**判分不运行**, +只在两种场合用: + +1. **重标定锚点**(换硬件后):见 `../tests/ref_speedup.caveat.md` + ``` + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch + ``` +2. **自证挖洞树的正确性**:`git apply --check -p1 oracle.patch` 必须能干净打在 + `../environment/repo/` 上(正向可、反向不可),这证明该树就是被计分的起始点。 + +`negative.patch` 是已知坏例(必须得 0),`baseline2.patch` 是中间基线(若有)。 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/baseline2.patch b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/baseline2.patch new file mode 100644 index 0000000000000000000000000000000000000000..9a8f0f2d5750b2da82b788f8f57203ec634e0328 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/baseline2.patch @@ -0,0 +1,150 @@ +diff --git a/cross_entropy_grad.py b/cross_entropy_grad.py +index ff781cc..dd7f96a 100644 +--- a/cross_entropy_grad.py ++++ b/cross_entropy_grad.py +@@ -1,57 +1,20 @@ +-"""Cross-entropy loss and input-gradient over a batch of logit rows. +- +-Public entry point: +- ``cross_entropy_loss_grad(logits, labels, ignore_index=-100, +- label_smoothing=0.0) -> (loss, grad)`` +- +-Given a batch of ``N`` rows of class scores (``logits``) and one integer target +-class per row (``labels``), compute the mean cross-entropy loss over the +-non-ignored rows and the gradient of that loss with respect to ``logits``. +- +-Contract +--------- +-- ``logits``: shape ``(N, V)``, a floating-point CUDA tensor (``float32`` or +- ``bfloat16``). ``N`` is the number of rows (batch * sequence), ``V`` the +- number of classes (vocabulary size). +-- ``labels``: shape ``(N,)``, an integer CUDA tensor. Each entry is a class +- index in ``[0, V)``, or equals ``ignore_index`` to mark the row as ignored. +-- ``ignore_index``: int. Rows whose label equals this value contribute zero to +- the loss and zero to the gradient. +-- ``label_smoothing``: float ``>= 0``. ``0.0`` is ordinary cross entropy. +- +-Returns +-------- +-- ``loss``: a scalar tensor — the mean cross-entropy (with optional label +- smoothing) over the non-ignored rows. If every row is ignored, the loss is +- ``0``. +-- ``grad``: shape ``(N, V)``, same dtype as ``logits`` — the gradient of +- ``loss`` w.r.t. ``logits``. Ignored rows are exactly zero. +- +-Definition (per non-ignored row with target ``y``, over ``n`` non-ignored rows): +- ``p = softmax(logits)`` +- ``loss_row = -(1 - s) * log p[y] - (s / V) * sum_k log p[k]`` +- ``grad_row[j] = ( p[j] - s / V - (1 - s) * [j == y] ) / n`` +-where ``s = label_smoothing``. All reductions are computed in float32; the +-gradient is returned in the input dtype. +- +-Error contract +--------------- +-- ``TypeError`` if ``logits`` is not a floating-point tensor, or ``labels`` is +- not an integer tensor. +-- ``ValueError`` if ``logits`` is not 2-D; if ``labels`` is not 1-D of length +- ``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies +- outside ``[0, V)``. +- +-Note on the current implementation +----------------------------------- +-This straightforward implementation forms the full log-probability tensor, the +-full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers +-in addition to the input. It is correct but holds several full-size copies of +-the logits at once, which is expensive at large ``V``. ++"""REVIEWER-ONLY baseline2 (Deriving-test-cases Step 6 soundness probe). ++ ++A CORRECT implementation that is STRUCTURALLY DIFFERENT from the oracle: instead ++of the oracle's single-pass online-softmax recurrence, it does an explicit ++THREE-pass safe softmax over vocab chunks -- (1) global per-row max, (2) exp-sum ++given that max, (3) gradient written in place. Still memory-frugal (only ++(N, chunk) transients; no full (N, V) buffer), so it must earn a POSITIVE ++peak-memory reward on its own merit -- if the verifier can only reward the exact ++oracle code, it is oracle-overfit and must be fixed. This is also the ++loop-eligibility soundness check: a different-correct submission scores, so 16 ++iterations have real signal. + """ + + import torch + ++CHUNK = 8192 ++ + + def _validate(logits, labels, label_smoothing): + if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor): +@@ -71,36 +34,49 @@ def _validate(logits, labels, label_smoothing): + + + def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0): +- """See module docstring for the full contract.""" + N, V = _validate(logits, labels, label_smoothing) + s = float(label_smoothing) +- ++ device = logits.device + valid = labels != ignore_index +- # non-ignored labels must be inside [0, V) + if valid.any(): + vlab = labels[valid] + if int(vlab.max()) >= V or int(vlab.min()) < 0: + raise ValueError(f"a non-ignored label is out of range [0, {V})") +- n_valid = int(valid.sum().item()) +- denom = max(n_valid, 1) +- +- safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later) +- idx = torch.arange(N, device=logits.device) +- +- lf = logits.to(torch.float32) +- logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer +- logp_y = logp[idx, safe] # (N,) +- nll = -logp_y +- smooth = -logp.mean(dim=1) # -mean_k log p[k] +- row_loss = (1.0 - s) * nll + s * smooth ++ denom = max(int(valid.sum().item()), 1) ++ safe = labels.clamp(min=0).long() ++ idx = torch.arange(N, device=device) ++ ++ # Pass 1: global per-row max ++ m = torch.full((N,), float("-inf"), device=device, dtype=torch.float32) ++ for c0 in range(0, V, CHUNK): ++ blk = logits[:, c0:c0 + CHUNK].to(torch.float32) ++ m = torch.maximum(m, blk.max(dim=1).values) ++ # Pass 2: exp-sum given the max (+ logit sum for smoothing) ++ d = torch.zeros(N, device=device, dtype=torch.float32) ++ x_sum = torch.zeros(N, device=device, dtype=torch.float32) if s != 0.0 else None ++ for c0 in range(0, V, CHUNK): ++ blk = logits[:, c0:c0 + CHUNK].to(torch.float32) ++ d += torch.exp(blk - m[:, None]).sum(dim=1) ++ if s != 0.0: ++ x_sum += blk.sum(dim=1) ++ lse = m + torch.log(d) ++ x_y = logits[idx, safe].to(torch.float32) ++ row_loss = lse - x_y if s == 0.0 else (1.0 - s) * (lse - x_y) + s * (lse - x_sum / V) + row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss)) +- loss = row_loss.sum() / denom +- +- prob = logp.exp() # (N, V) softmax +- grad = prob.clone() # (N, V) gradient buffer +- if s != 0.0: +- grad = grad - (s / V) +- grad[idx, safe] = grad[idx, safe] - (1.0 - s) +- grad = grad / denom +- grad[~valid] = 0.0 # ignored rows -> exactly zero +- return loss, grad.to(logits.dtype) ++ loss = (row_loss.sum() / denom).to(logits.dtype) ++ ++ # Pass 3: gradient in place ++ inv = 1.0 / denom ++ for c0 in range(0, V, CHUNK): ++ c1 = min(c0 + CHUNK, V) ++ blk = logits[:, c0:c1].to(torch.float32) ++ gblk = torch.exp(blk - m[:, None]) / d[:, None] ++ if s != 0.0: ++ gblk = gblk - (s / V) ++ in_chunk = valid & (safe >= c0) & (safe < c1) ++ if bool(in_chunk.any()): ++ gblk[idx[in_chunk], safe[in_chunk] - c0] -= (1.0 - s) ++ gblk = gblk * inv ++ gblk[~valid] = 0.0 ++ logits[:, c0:c1] = gblk.to(logits.dtype) ++ return loss, logits diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/negative.patch b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/negative.patch new file mode 100644 index 0000000000000000000000000000000000000000..5b8115aaacfe8adc23212f97db63e1d003731a6a --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/negative.patch @@ -0,0 +1,134 @@ +diff --git a/cross_entropy_grad.py b/cross_entropy_grad.py +index ff781cc..10dc004 100644 +--- a/cross_entropy_grad.py ++++ b/cross_entropy_grad.py +@@ -1,57 +1,16 @@ +-"""Cross-entropy loss and input-gradient over a batch of logit rows. ++"""REVIEWER-ONLY negative control (known-bad). MUST score reward 0. + +-Public entry point: +- ``cross_entropy_loss_grad(logits, labels, ignore_index=-100, +- label_smoothing=0.0) -> (loss, grad)`` +- +-Given a batch of ``N`` rows of class scores (``logits``) and one integer target +-class per row (``labels``), compute the mean cross-entropy loss over the +-non-ignored rows and the gradient of that loss with respect to ``logits``. +- +-Contract +--------- +-- ``logits``: shape ``(N, V)``, a floating-point CUDA tensor (``float32`` or +- ``bfloat16``). ``N`` is the number of rows (batch * sequence), ``V`` the +- number of classes (vocabulary size). +-- ``labels``: shape ``(N,)``, an integer CUDA tensor. Each entry is a class +- index in ``[0, V)``, or equals ``ignore_index`` to mark the row as ignored. +-- ``ignore_index``: int. Rows whose label equals this value contribute zero to +- the loss and zero to the gradient. +-- ``label_smoothing``: float ``>= 0``. ``0.0`` is ordinary cross entropy. +- +-Returns +-------- +-- ``loss``: a scalar tensor — the mean cross-entropy (with optional label +- smoothing) over the non-ignored rows. If every row is ignored, the loss is +- ``0``. +-- ``grad``: shape ``(N, V)``, same dtype as ``logits`` — the gradient of +- ``loss`` w.r.t. ``logits``. Ignored rows are exactly zero. +- +-Definition (per non-ignored row with target ``y``, over ``n`` non-ignored rows): +- ``p = softmax(logits)`` +- ``loss_row = -(1 - s) * log p[y] - (s / V) * sum_k log p[k]`` +- ``grad_row[j] = ( p[j] - s / V - (1 - s) * [j == y] ) / n`` +-where ``s = label_smoothing``. All reductions are computed in float32; the +-gradient is returned in the input dtype. +- +-Error contract +--------------- +-- ``TypeError`` if ``logits`` is not a floating-point tensor, or ``labels`` is +- not an integer tensor. +-- ``ValueError`` if ``logits`` is not 2-D; if ``labels`` is not 1-D of length +- ``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies +- outside ``[0, V)``. +- +-Note on the current implementation +----------------------------------- +-This straightforward implementation forms the full log-probability tensor, the +-full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers +-in addition to the input. It is correct but holds several full-size copies of +-the logits at once, which is expensive at large ``V``. ++Bug: the gradient omits the one-hot subtraction at the target class -- it returns ++softmax / n_nonignore only, never subtracting (1 - label_smoothing) at the label ++column. It is memory-frugal (would win the peak-memory metric) but WRONG, so it ++must fail the `normal`/`work-evidence` grad-parity gate and score 0. This is the ++SPEC known_bad (b): forgetting the target-class term of the gradient. + """ + + import torch + ++CHUNK = 8192 ++ + + def _validate(logits, labels, label_smoothing): + if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor): +@@ -71,36 +30,33 @@ def _validate(logits, labels, label_smoothing): + + + def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0): +- """See module docstring for the full contract.""" + N, V = _validate(logits, labels, label_smoothing) + s = float(label_smoothing) +- ++ device = logits.device + valid = labels != ignore_index +- # non-ignored labels must be inside [0, V) +- if valid.any(): +- vlab = labels[valid] +- if int(vlab.max()) >= V or int(vlab.min()) < 0: +- raise ValueError(f"a non-ignored label is out of range [0, {V})") +- n_valid = int(valid.sum().item()) +- denom = max(n_valid, 1) +- +- safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later) +- idx = torch.arange(N, device=logits.device) +- +- lf = logits.to(torch.float32) +- logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer +- logp_y = logp[idx, safe] # (N,) +- nll = -logp_y +- smooth = -logp.mean(dim=1) # -mean_k log p[k] +- row_loss = (1.0 - s) * nll + s * smooth +- row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss)) +- loss = row_loss.sum() / denom +- +- prob = logp.exp() # (N, V) softmax +- grad = prob.clone() # (N, V) gradient buffer +- if s != 0.0: +- grad = grad - (s / V) +- grad[idx, safe] = grad[idx, safe] - (1.0 - s) +- grad = grad / denom +- grad[~valid] = 0.0 # ignored rows -> exactly zero +- return loss, grad.to(logits.dtype) ++ denom = max(int(valid.sum().item()), 1) ++ safe = labels.clamp(min=0).long() ++ idx = torch.arange(N, device=device) ++ ++ m = torch.full((N,), float("-inf"), device=device, dtype=torch.float32) ++ d = torch.zeros(N, device=device, dtype=torch.float32) ++ for c0 in range(0, V, CHUNK): ++ blk = logits[:, c0:c0 + CHUNK].to(torch.float32) ++ m_new = torch.maximum(m, blk.max(dim=1).values) ++ d = d * torch.exp(m - m_new) + torch.exp(blk - m_new[:, None]).sum(dim=1) ++ m = m_new ++ lse = m + torch.log(d) ++ x_y = logits[idx, safe].to(torch.float32) ++ row_loss = torch.where(valid, lse - x_y, torch.zeros_like(lse)) ++ loss = (row_loss.sum() / denom).to(logits.dtype) ++ ++ inv = 1.0 / denom ++ for c0 in range(0, V, CHUNK): ++ c1 = min(c0 + CHUNK, V) ++ blk = logits[:, c0:c1].to(torch.float32) ++ gblk = torch.exp(blk - m[:, None]) / d[:, None] ++ # BUG: no `- (1 - s)` at the label column -> wrong gradient. ++ gblk = gblk * inv ++ gblk[~valid] = 0.0 ++ logits[:, c0:c1] = gblk.to(logits.dtype) ++ return loss, logits diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/oracle.patch b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..239de33e16ca9d0e3390a1b4cc9d45981695b337 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/oracle.patch @@ -0,0 +1,279 @@ +diff --git a/cross_entropy_grad.py b/cross_entropy_grad.py +index ff781cc..429b935 100644 +--- a/cross_entropy_grad.py ++++ b/cross_entropy_grad.py +@@ -42,16 +42,27 @@ Error contract + ``N``; if ``label_smoothing`` is negative; or if any non-ignored label lies + outside ``[0, V)``. + +-Note on the current implementation +----------------------------------- +-This straightforward implementation forms the full log-probability tensor, the +-full probability tensor, and a full gradient tensor -- three ``(N, V)`` buffers +-in addition to the input. It is correct but holds several full-size copies of +-the logits at once, which is expensive at large ``V``. ++Implementation note ++------------------- ++A single fused kernel computes both the loss and the gradient. Each program ++handles one row: a first streaming pass performs an online softmax (running ++max, running sum of exponentials, sum of logits, target logit — O(1) state per ++row), and a second pass recomputes the probabilities block-by-block and writes ++the gradient in place into the ``logits`` buffer. The only extra device memory ++is an ``(N,)`` float32 buffer of per-row losses; no full-size ``(N, V)`` ++intermediate is ever materialized. + """ + + import torch + ++try: ++ import triton ++ import triton.language as tl ++ ++ _HAS_TRITON = True ++except Exception: # pragma: no cover - triton is expected to be available ++ _HAS_TRITON = False ++ + + def _validate(logits, labels, label_smoothing): + if not isinstance(logits, torch.Tensor) or not isinstance(labels, torch.Tensor): +@@ -70,37 +81,211 @@ def _validate(logits, labels, label_smoothing): + return N, V + + ++if _HAS_TRITON: ++ ++ @triton.jit ++ def _count_valid_bad_kernel( ++ lab_ptr, # (N,) int32/int64 ++ stats_ptr, # (2,) int64: [n_valid, n_bad] accumulated with exact integer atomics ++ N, ++ V, ++ ignore_index, ++ BLOCK: tl.constexpr, ++ ): ++ pid = tl.program_id(0) ++ offs = pid * BLOCK + tl.arange(0, BLOCK) ++ mask = offs < N ++ lab = tl.load(lab_ptr + offs, mask=mask, other=ignore_index) ++ is_valid = (lab != ignore_index) & mask ++ is_bad = is_valid & ((lab < 0) | (lab >= V)) ++ tl.atomic_add(stats_ptr, tl.sum(is_valid.to(tl.int64), axis=0)) ++ tl.atomic_add(stats_ptr + 1, tl.sum(is_bad.to(tl.int64), axis=0)) ++ ++ @triton.jit ++ def _ce_loss_grad_reg_kernel( ++ x_ptr, # (N, V) in: logits, out: gradient (overwritten in place) ++ lab_ptr, # (N,) int32/int64 ++ loss_ptr, # (N,) float32 per-row loss, 0 for ignored rows ++ V, ++ ignore_index, ++ s, ++ inv_denom, ++ BLOCK_V: tl.constexpr, # >= V: the whole row stays resident in registers ++ ): ++ row = tl.program_id(0) ++ base = x_ptr + row.to(tl.int64) * V ++ cols = tl.arange(0, BLOCK_V) ++ mask = cols < V ++ lab = tl.load(lab_ptr + row) ++ ++ if lab == ignore_index: ++ tl.store(loss_ptr + row, 0.0) ++ z = tl.zeros([BLOCK_V], dtype=tl.float32) ++ tl.store(base + cols, z.to(x_ptr.dtype.element_ty), mask=mask) ++ else: ++ x = tl.load(base + cols, mask=mask, other=-float("inf")).to(tl.float32) ++ m = tl.max(x, axis=0) ++ e = tl.exp(x - m) ++ l = tl.sum(e, axis=0) ++ sum_x = tl.sum(tl.where(mask, x, 0.0), axis=0) ++ x_y = tl.sum(tl.where(cols == lab, x, 0.0), axis=0) ++ log_z = m + tl.log(l) ++ row_loss = (1.0 - s) * (log_z - x_y) + s * (log_z - sum_x / V) ++ tl.store(loss_ptr + row, row_loss * inv_denom) ++ g = e * (1.0 / l) - s / V ++ g = tl.where(cols == lab, g - (1.0 - s), g) ++ g = g * inv_denom ++ tl.store(base + cols, g.to(x_ptr.dtype.element_ty), mask=mask) ++ ++ @triton.jit ++ def _ce_loss_grad_kernel( ++ x_ptr, # (N, V) in: logits, out: gradient (overwritten in place) ++ lab_ptr, # (N,) int32/int64 ++ loss_ptr, # (N,) float32 per-row loss, 0 for ignored rows ++ V, ++ ignore_index, ++ s, ++ inv_denom, ++ BLOCK_V: tl.constexpr, ++ ): ++ row = tl.program_id(0) ++ base = x_ptr + row.to(tl.int64) * V ++ cols0 = tl.arange(0, BLOCK_V) ++ lab = tl.load(lab_ptr + row) ++ ++ if lab == ignore_index: ++ tl.store(loss_ptr + row, 0.0) ++ z = tl.zeros([BLOCK_V], dtype=tl.float32) ++ for off in range(0, V, BLOCK_V): ++ cols = off + cols0 ++ mask = cols < V ++ tl.store(base + cols, z.to(x_ptr.dtype.element_ty), mask=mask) ++ else: ++ m = -float("inf") ++ l = 0.0 ++ sum_x = 0.0 ++ x_y = 0.0 ++ for off in range(0, V, BLOCK_V): ++ cols = off + cols0 ++ mask = cols < V ++ x = tl.load(base + cols, mask=mask, other=-float("inf")).to(tl.float32) ++ bmax = tl.max(x, axis=0) ++ new_m = tl.maximum(m, bmax) ++ l = l * tl.exp(m - new_m) + tl.sum(tl.exp(x - new_m), axis=0) ++ m = new_m ++ sum_x += tl.sum(tl.where(mask, x, 0.0), axis=0) ++ x_y += tl.sum(tl.where(cols == lab, x, 0.0), axis=0) ++ ++ log_z = m + tl.log(l) ++ row_loss = (1.0 - s) * (log_z - x_y) + s * (log_z - sum_x / V) ++ tl.store(loss_ptr + row, row_loss * inv_denom) ++ ++ inv_l = 1.0 / l ++ s_over_v = s / V ++ om_s = 1.0 - s ++ for off in range(0, V, BLOCK_V): ++ cols = off + cols0 ++ mask = cols < V ++ x = tl.load(base + cols, mask=mask, other=0.0).to(tl.float32) ++ g = tl.exp(x - m) * inv_l - s_over_v ++ g = tl.where(cols == lab, g - om_s, g) ++ g = g * inv_denom ++ tl.store(base + cols, g.to(x_ptr.dtype.element_ty), mask=mask) ++ ++ ++def _chunked_fallback(logits, labels, valid, s, inv_denom, loss_buf): ++ """Memory-bounded pure-torch path (non-CUDA tensors or missing triton).""" ++ N, V = logits.shape ++ chunk = max(1, min(N, (1 << 22) // max(V, 1))) ++ for c0 in range(0, N, chunk): ++ c1 = min(N, c0 + chunk) ++ x = logits[c0:c1] ++ xf = x.to(torch.float32) ++ m = xf.max(dim=1, keepdim=True).values ++ e = torch.exp(xf - m) ++ l = e.sum(dim=1, keepdim=True) ++ log_z = m + torch.log(l) ++ lab = labels[c0:c1].clamp(min=0).long() ++ idx = torch.arange(c1 - c0, device=logits.device) ++ x_y = xf[idx, lab].unsqueeze(1) ++ sum_x = xf.sum(dim=1, keepdim=True) ++ row_loss = ((1.0 - s) * (log_z - x_y) + s * (log_z - sum_x / V)).squeeze(1) ++ v = valid[c0:c1] ++ loss_buf[c0:c1] = torch.where(v, row_loss * inv_denom, torch.zeros_like(row_loss)) ++ g = e / l - (s / V) ++ g[idx, lab] = g[idx, lab] - (1.0 - s) ++ g = g * inv_denom ++ g = torch.where(v.unsqueeze(1), g, torch.zeros_like(g)) ++ x.copy_(g.to(logits.dtype)) ++ return logits ++ ++ + def cross_entropy_loss_grad(logits, labels, ignore_index=-100, label_smoothing=0.0): + """See module docstring for the full contract.""" + N, V = _validate(logits, labels, label_smoothing) + s = float(label_smoothing) + +- valid = labels != ignore_index +- # non-ignored labels must be inside [0, V) +- if valid.any(): +- vlab = labels[valid] +- if int(vlab.max()) >= V or int(vlab.min()) < 0: +- raise ValueError(f"a non-ignored label is out of range [0, {V})") +- n_valid = int(valid.sum().item()) +- denom = max(n_valid, 1) +- +- safe = labels.clamp(min=0).long() # ignore rows point at col 0 (masked out later) +- idx = torch.arange(N, device=logits.device) +- +- lf = logits.to(torch.float32) +- logp = torch.log_softmax(lf, dim=-1) # (N, V) full buffer +- logp_y = logp[idx, safe] # (N,) +- nll = -logp_y +- smooth = -logp.mean(dim=1) # -mean_k log p[k] +- row_loss = (1.0 - s) * nll + s * smooth +- row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss)) +- loss = row_loss.sum() / denom +- +- prob = logp.exp() # (N, V) softmax +- grad = prob.clone() # (N, V) gradient buffer +- if s != 0.0: +- grad = grad - (s / V) +- grad[idx, safe] = grad[idx, safe] - (1.0 - s) +- grad = grad / denom +- grad[~valid] = 0.0 # ignored rows -> exactly zero +- return loss, grad.to(logits.dtype) ++ if not labels.is_contiguous(): ++ labels = labels.contiguous() ++ ++ use_triton = _HAS_TRITON and logits.is_cuda ++ if use_triton: ++ stats = torch.zeros(2, device=logits.device, dtype=torch.int64) ++ if N > 0: ++ _count_valid_bad_kernel[(triton.cdiv(N, 4096),)]( ++ labels, stats, N, V, int(ignore_index), BLOCK=4096, num_warps=4 ++ ) ++ n_valid, n_bad = (int(v) for v in stats.tolist()) ++ else: ++ valid = labels != ignore_index ++ bad = ((labels < 0) | (labels >= V)) & valid ++ n_valid, n_bad = (int(v) for v in torch.stack([valid.sum(), bad.sum()]).tolist()) ++ if n_bad: ++ raise ValueError(f"a non-ignored label is out of range [0, {V})") ++ denom = n_valid if n_valid > 0 else 1 ++ inv_denom = 1.0 / denom ++ ++ if not logits.is_contiguous(): ++ logits = logits.contiguous() ++ ++ loss_buf = torch.empty(N, device=logits.device, dtype=torch.float32) ++ ++ if use_triton and N > 0: ++ if V <= 8192: ++ block_v = triton.next_power_of_2(V) ++ if block_v <= 512: ++ num_warps = 1 ++ elif block_v <= 4096: ++ num_warps = 2 ++ else: ++ num_warps = 4 ++ _ce_loss_grad_reg_kernel[(N,)]( ++ logits, ++ labels, ++ loss_buf, ++ V, ++ int(ignore_index), ++ s, ++ inv_denom, ++ BLOCK_V=block_v, ++ num_warps=num_warps, ++ ) ++ else: ++ _ce_loss_grad_kernel[(N,)]( ++ logits, ++ labels, ++ loss_buf, ++ V, ++ int(ignore_index), ++ s, ++ inv_denom, ++ BLOCK_V=2048, ++ num_warps=4, ++ ) ++ grad = logits ++ else: ++ valid = labels != ignore_index ++ grad = _chunked_fallback(logits, labels, valid, s, inv_denom, loss_buf) ++ ++ loss = loss_buf.sum(dtype=torch.float64).to(torch.float32) ++ return loss, grad diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/solve.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4fbe069cdcfeab0ee4a390b7d6c78cc706a85632 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/solution/solve.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/insea-fused-softmax-cross-entropy-grad-loop16 +# 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量 +# 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。 +# +# oracle 形态 : 补丁式(patch)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_PATCH 槽位: +# git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" +# 产物(reviewer-only;本脚本只读,一个字节都不改): +# solution/baseline2.patch, solution/negative.patch, solution/oracle.patch +# $REPO : /app/repo (tests/test.sh: REPO=/app/repo) +# 被计分单元 : /app/repo/cross_entropy_grad.py +# 来源:tests/test.sh 的 CAND_FILE="$REPO/cross_entropy_grad.py" +# 落地方式 : git -C $REPO apply -p1 —— 只改工作树,不 commit +# +# 🔴 为什么绝不 commit(规范 H3):判分读**工作树** —— `git status --porcelain` 是 scope +# 硬闸门,`git checkout -q HEAD -- ` 取基线,且镜像自证 /app/repo 的 HEAD 恰好 +# 只有 1 个 commit(那就是挖洞基线)。一旦 commit,HEAD 前移 → 闸门看不到改动、 +# `checkout HEAD -- scope` 把 candidate 当成基线 → 正确解被判 0。 +# 本脚本落地后会自己断言 HEAD 与 commit 数没变。 +# +# ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)──────────────────────── +# PKG=/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task +# IMG=fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss +# # 1) 起容器。判分容器始终 --network=none;tests/ 和 solution/ 都**没有**烤进镜像 +# # (Dockerfile 里没有一条 COPY 取它们),所以这两个目录必须挂进来。 +# # 该题 task.toml 声明 gpus=1;锚点的标定硬件/运行栈见 tests/ref_speedup.caveat.md +# docker run -d --name kfc-solve --network=none --gpus all \ +# -v "$PKG/tests":/tests -v "$PKG/solution":/solution "$IMG" +# # 2) 落地参考实现到工作树(本脚本;不 commit) +# docker exec kfc-solve bash /solution/solve.sh +# # 3) 判分。KERNELBENCH_VERIFY_MODE 必须留在默认的 candidate —— 这就是 agent 的 +# # 真实评分路径;设成 oracle/negative 会让 test.sh 自己再落地一遍,绕过本脚本。 +# docker exec -e KERNELBENCH_VERIFY_MODE=candidate kfc-solve bash /tests/test.sh +# docker exec kfc-solve cat /logs/verifier/reward.json # 判分结果 +# docker rm -f kfc-solve +# +# 期望:oracle → 性能题得 0(它就是锚点本身; min(1, ln(speedup/ref_speedup)/ln(ref_speedup))(speedup ≤ ref_speedup 时为 0) +# 在 speedup≈ref_speedup 处 = 0 —— 打平 oracle 不得分,必须超过。 +# 所以"oracle 跑对了"的判据不是 reward>0,而是 speedup≈ref_speedup 且 +# hard_fail_reasons 为空;实现类二值题 = 1.0 —— 权威公式是 +# tests/test.sh 写出的 reward_formula 字段);--negative → 0; +# --noop(在纯净容器里)→ 0(挖洞基线过不了正确性门)。 +# 本题带 loop16 harness:`bash /opt/loop/submit.sh` 判的也是同一棵工作树、 +# 同样走 candidate 模式(口径一致),所以落地后直接自评也成立。 +# ────────────────────────────────────────────────────────────────────────── +# +# 用法(规范 2 的统一 CLI): +# bash solution/solve.sh # 落地 oracle(参考实现) +# bash solution/solve.sh --negative # 落地 negative(已知坏例,必须得 0) +# bash solution/solve.sh --baseline2 # 落地 baseline2(中间基线) +# bash solution/solve.sh --noop # 把可编辑面复位到烤入基线(对照组) +# +# --noop 语义:把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— +# `git checkout HEAD -- `,HEAD 不动),使对照组能量到真正的 no-op 值。 +# runner 在同一个容器里连着跑 oracle → noop 做对照时,靠它把上一轮落地归零。 +# +# 幂等:每次落地前先把被计分单元 `git checkout HEAD --` 复位,重复执行结果一致。 +# 失败一律非 0 退出并打印原因(补丁打不上 / 变体文件缺失 / scope 路径不存在 / HEAD 被移动)。 +set -uo pipefail + +TASK_ID="insea-fused-softmax-cross-entropy-grad-loop16" +REPO="${KFC_REPO_DIR:-/app/repo}" +SCOPE=("cross_entropy_grad.py") +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; } +die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; } +# 每次调用单独带 safe.directory,不去改容器里的全局 gitconfig +GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; } + +usage(){ cat <<'USAGE' +usage: bash solve.sh [--oracle | --negative | --baseline2 | --noop] + (无参数) 落地 oracle 参考实现(oracle.patch) + --negative 落地 negative 已知坏例(negative.patch) + --baseline2 落地 baseline2 中间基线(baseline2.patch) + --noop 把可编辑面复位到烤入基线(与 verifier 取基线一致,HEAD 不动) +USAGE +} + +WHICH=oracle +case "${1:-}" in + ""|--oracle) WHICH=oracle ;; + --negative) WHICH=negative ;; + --baseline2) WHICH=baseline2 ;; + --noop) WHICH=noop ;; + -h|--help) usage; exit 0 ;; + *) usage >&2; die "未知参数 '$1'" ;; +esac + +# ---- 产物定位:脚本同目录优先,其次容器里的常见挂载点 ---- +artifact(){ + local n="$1" c + for c in "$HERE/$n" "/solution/$n" "${KFC_SOLUTION_DIR:-/nonexistent}/$n"; do + [ -f "$c" ] && { printf '%s\n' "$c"; return 0; } + done + return 1 +} + +case "$WHICH" in + noop) ART="" ;; + oracle) ART="oracle.patch" ;; + negative) ART="negative.patch" ;; + baseline2) ART="baseline2.patch" ;; + *) die "本题没有 $WHICH 变体(solution/ 里只有:oracle.patch, negative.patch, baseline2.patch)" ;; +esac + +# ---- 环境前置检查 ---- +GIT rev-parse --git-dir >/dev/null 2>&1 \ + || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)" +for s in "${SCOPE[@]}"; do + [ -e "$REPO/$s" ] || die "被计分单元不存在:$REPO/$s(REPO 不对?可用 KFC_REPO_DIR 覆盖)" +done +HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD" +N_BEFORE="$(GIT rev-list --count HEAD)" + +if [ "$WHICH" = noop ]; then + # --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— `git checkout HEAD -- `, + # HEAD 不动),使对照组能量到真正的 no-op 值。runner 在同一个容器里连着跑 oracle → noop 时靠它归零。 + DIRTY_BEFORE="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" + DIRTY_AFTER="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + if [ -n "$DIRTY_AFTER" ]; then + printf '%s\n' "$DIRTY_AFTER" | sed "s|^|[solve.sh $TASK_ID] |" >&2 + die "复位后被计分单元仍不干净(见上)—— 量不到真正的 no-op 值" + fi + [ "$HEAD_BEFORE" = "$(GIT rev-parse HEAD)" ] || die "HEAD 被移动了,判分会把 candidate 当基线" + [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + if [ -n "$DIRTY_BEFORE" ]; then + say "--noop:已把可编辑面复位到烤入基线;原先这些是脏的:" + printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |" + else + say "--noop:可编辑面本来就是干净的烤入基线,无需复位" + fi + say "--noop 完成:${SCOPE[*]} = 烤入基线(HEAD 未动 @ ${HEAD_BEFORE:0:12})" + exit 0 +fi + +PATCH="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)" + +# ---- 幂等:先把被计分单元退回挖洞基线,再打补丁(否则二次 apply 必然失败) ---- +GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" +GIT apply -p1 --check "$PATCH" \ + || die "补丁打不上:$PATCH —— 挖洞树与该补丁不匹配,或工作树被别的改动污染了" +GIT apply -p1 "$PATCH" || die "git apply 失败:$PATCH" + +# ---- 硬要求:HEAD 一步都不能动(规范 H3) ---- +HEAD_AFTER="$(GIT rev-parse HEAD)" +[ "$HEAD_BEFORE" = "$HEAD_AFTER" ] || die "HEAD 被移动了($HEAD_BEFORE -> $HEAD_AFTER),判分会把 candidate 当基线" +[ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + +say "已落地 $WHICH:$(basename "$PATCH") -> ${SCOPE[*]}(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})" +GIT status --porcelain -- "${SCOPE[@]}" | sed "s|^|[solve.sh $TASK_ID] |" + +# ---- 顺手体检 scope 闸门:工作树里除了被计分单元不该有别的改动 ---- +STRAY="$(GIT status --porcelain | awk '{print $NF}' \ + | grep -v -e '__pycache__' -e '\.pyc$' -e '^cross_entropy_grad\.py$' || true)" +[ -z "$STRAY" ] || { say "⚠ 工作树里还有 scope 外的改动,判分会 out_of_scope_edit 直接归 0:"; \ + printf '%s\n' "$STRAY" | sed "s|^|[solve.sh $TASK_ID] |"; } +exit 0 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/task.toml b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..37b28cf839eb1e8479a94ee3d2fabb2a1168eada --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/task.toml @@ -0,0 +1,80 @@ +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "insea-fused-softmax-cross-entropy-grad-loop16" +bench = "kfc" +kind = "performance" +language = "python" +title = "You are working on the loss stage of a large language model's training step." +instruction = "instruction.md" + +[agent] +timeout_sec = 21600 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/insea-fused-softmax-cross-entropy-grad-loop16:loop-20260720T021136Z@sha256:dbd2b4dbf93aa3621d94de371a783ff2d77d7978cc4b93a6c19819d36a68a7f9 +# Open-source build: `cd && docker build -f environment/Dockerfile -t fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss .` +[environment] +docker_image = "fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss" +dockerfile = "environment/Dockerfile" +build_timeout_sec = 3600 +cpus = 8 +memory_mb = 32000 +gpus = 1 +# H20 只是**锚点标定用卡**,不是硬性限制。换卡时:①按 tests/ref_speedup.caveat.md 重标锚点; +# ②用 --build-arg TORCH_CUDA_ARCH_LIST=<你的算力> 构建镜像。 +gpu_types = ["H20"] +gpu_memory_gb = 96 +allow_internet = false + +[verifier] +entrypoint = "tests/test.sh" +mode = "shared" +timeout_sec = 3600 +task_kind = "acceleration" +contract_pattern = "A" +timing_metric = "peak_memory_bytes" +candidate_source_root = "/app/repo" +primary_edit_paths = ["/app/repo/cross_entropy_grad.py"] +forbidden_edit_paths = ["/app/repo/tests/**", "/opt/verifier-*", "/tests/**", "/opt/loop/**"] +result_paths = [ + "/logs/verifier/verifier_state.json", + "/logs/verifier/correctness_results.json", + "/logs/verifier/benchmark_results.json", + "/logs/verifier/reward.json", + "/logs/verifier/reward.txt", +] + +[primary_metric] +name = "cross_entropy_grad_peak_memory_ratio" +goal = "maximize" +metric_kind = "peak_memory" +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." +ref_speedup = 7.4157 +ref_speedup_source = "tests/ref_speedup.txt" +calibrated_on = "NVIDIA H20" +correctness_gates = [ + "hidden_parity_suite", + "all_ignore_rows", + "single_class", + "single_row", + "nontile_vocab", + "label_smoothing", + "degenerate", + "error_reject", + "metamorphic", + "work_evidence_nonzero_rows", + "trusted_restore", + "anti_cheat_forbidden_edit", + "forbidden_fused_ce_primitive", +] + +[loop] +min_submissions = 1 +max_submissions = 1 +submit = "bash /opt/loop/submit.sh" +mode = "baked" +feedback_surface = "/opt/loop/submit.sh" +declared_submission_policy = "single_submission" diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/compute_reward.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..563eeb69a6196a95bdc35757756c8150c2a78cc3 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/compute_reward.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Canonical kernelbench reward writer. Task-agnostic; do NOT special-case a task here. + +Reward definition (the reward specification): + + performance / acceleration task: + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + - speedup == ref_speedup -> 0.0 (must EXCEED it to score) (matching the oracle) + - speedup >= ref_speedup**2 -> 1.0 (capped) + - value range strictly [0.0, 1.0] + HARD pre-gates (any one hit => reward = 0, formula NOT entered): + build/import failure, ANY correctness case fail, cheating, + forbidden_edit_paths touched, speedup <= 1, ref_speedup <= 1. + + implementation / correctness task: + reward = 1.0 iff EVERY visible case passes and no cheat / forbidden-path + condition fired; 0.0 otherwise. BINARY — never a pass-fraction. + +Reads: /logs/verifier/verifier_state.json, /logs/verifier/benchmark_results.json, + /logs/verifier/correctness_results.json +Writes: /logs/verifier/reward.json, /logs/verifier/reward.txt +""" +import json, math +from pathlib import Path + +LOG = Path("/logs/verifier") +STATE = LOG / "verifier_state.json" +BENCH = LOG / "benchmark_results.json" +CORR = LOG / "correctness_results.json" +REWARD = LOG / "reward.json" +TEXT = LOG / "reward.txt" + +GATES = [ + "correctness_ok", + "trusted_restore_ok", + "hidden_correctness_ok", + "baseline_ok", + "benchmark_ok", + "anti_cheat_ok", +] + + +def read_json(path, default): + try: + return json.loads(path.read_text(encoding="utf-8")) + except Exception: + return default + + +def log_reward(speedup, ref): + """reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0, clamped to [0.0, 1.0].""" + try: + num = math.log(float(speedup)) + den = math.log(float(ref)) + except Exception: + return 0.0 + if not math.isfinite(num) or not math.isfinite(den) or den <= 0.0: + return 0.0 + r = max(0.0, min(1.0, num / den - 1.0)) + if not math.isfinite(r): + return 0.0 + return max(0.0, min(1.0, r)) + + +def case_counts(state, corr): + total = state.get("expected_case_count") + passed = state.get("actual_case_count") + suites = corr.get("suites") or [] + if suites: + try: + p = sum(int(s.get("passed") or 0) for s in suites) + t = sum(int(s.get("expected_case_count") or 0) for s in suites) + if t > 0: + passed, total = p, t + except Exception: + pass + return passed, total + + +def main(): + LOG.mkdir(parents=True, exist_ok=True) + state = read_json(STATE, {}) + bench = read_json(BENCH, {}) + corr = read_json(CORR, {}) + hard = list(state.get("hard_fail_reasons") or []) + task_kind = state.get("task_kind") or bench.get("task_kind") or "acceleration" + gates_ok = all(bool(state.get(g)) for g in GATES) + passed, total = case_counts(state, corr) + + speedup = ref = 1.0 + reward = 0.0 + if task_kind == "correctness": + # IMPLEMENTATION task -> BINARY. Any single case short of the expected + # count zeroes the reward (no partial / graded fraction credit). + cases_ok = True + if total is not None and passed is not None: + try: + cases_ok = int(passed) >= int(total) + except Exception: + cases_ok = False + if not cases_ok and "case_count_short" not in hard: + hard.append("case_count_short") + reward = 1.0 if (gates_ok and cases_ok and not hard) else 0.0 + if reward == 0.0 and not hard: + hard.append("correctness_or_validation_incomplete") + else: + try: + speedup = float(bench.get("aggregate_speedup") or bench.get("primary_metric_value") or 1.0) + ref = float(bench.get("ref_speedup") or bench.get("reference_metric_value") or 1.0) + except Exception: + speedup = ref = 1.0 + if "invalid_primary_metric_value" not in hard: + hard.append("invalid_primary_metric_value") + # Correctness / anti-cheat / forbidden-path pre-gates arrive via gates_ok + + # hard (unchanged, never weakened). The two metric pre-gates are explicit. + if not math.isfinite(speedup) or speedup <= 1.0: + if "speedup_not_above_baseline" not in hard: + hard.append("speedup_not_above_baseline") + if not math.isfinite(ref) or ref <= 1.0: + if "ref_speedup_invalid" not in hard: + hard.append("ref_speedup_invalid") + if gates_ok and not hard: + reward = log_reward(speedup, ref) + + out = { + "schema_version": "kernelbench_reward_v2", + "task_kind": task_kind, + "task_type": "implementation" if task_kind == "correctness" else "performance", + "reward": reward, + "reward_formula": ("binary: 1.0 iff every visible case passes and no cheat/forbidden path" + if task_kind == "correctness" + else "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0"), + "speedup": speedup, + "ref_speedup": ref, + "cv": bench.get("cv") or {}, + "tests": {"passed": passed, "total": total}, + "actual_hardware_type": state.get("actual_hardware_type", "") or bench.get("actual_hardware_type", ""), + "hard_fail_reasons": hard, + "state_path": str(STATE), + "benchmark_path": str(BENCH), + } + REWARD.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n", encoding="utf-8") + TEXT.write_text(f"{reward}\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/gpu_peakmem.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/gpu_peakmem.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8abaefdaa20c0f6e599320e77d08bec7080dbb --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/gpu_peakmem.py @@ -0,0 +1,127 @@ +"""Peak-GPU-memory measurement for the cross-entropy loss+gradient task. + +VALUE AXIS = PEAK MEMORY, not wall-time. The naive baseline materialises several +full ``(N, V)`` buffers (log-probs, probabilities, gradient); a memory-frugal +implementation keeps only per-row running state and can overwrite the logits +buffer with the gradient in place, so its peak ``max_memory_allocated`` is far +lower at large ``V``. Latency may be ~1.0x -- that is EXPECTED and is NOT scored. + +Per shape: + 1. correctness agreement: candidate output must match the frozen baseline + within tolerance (on a fresh clone; the candidate may mutate in place); + 2. peak = ``torch.cuda.max_memory_allocated`` measured over a single call, with + only the freshly generated inputs resident at reset (the input buffer is the + shared floor for both); ratio = baseline_peak / candidate_peak. +Final metric = geometric mean of the per-shape peak-memory ratios. Prints +"speedup=X" (the peak-memory ratio; a no-op candidate == frozen baseline ties at +~1.0). The baseline is loaded from the protected frozen copy (KB_BASELINE_MODULE). +""" + +import importlib.util +import os +import sys + +import torch + +from kb_ce_harness import ( + assert_grad_close, + assert_loss_close, + forbidden_ce_guard, + geomean, + load_candidate, + make_labels, + make_logits, +) + +IGN = -100 +LS = 0.0 +IGNORE_FRAC = 0.1 + +# (tag, N, V, dtype). Vocab large enough that the baseline's (N,V) materialisation +# dominates peak memory (false-negative checklist item #3: a path-exercising workload). +SHAPES = [ + ("v32k_fp32", 8192, 32768, torch.float32), + ("v128k_fp32", 8192, 128256, torch.float32), + ("v64k_bf16", 8192, 65536, torch.bfloat16), + ("v128k_bf16", 8192, 128256, torch.bfloat16), +] + + +def _load(path): + spec = importlib.util.spec_from_file_location("kb_ce_mod_" + str(abs(hash(path))), path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _baseline_fn(): + path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/cross_entropy_grad.py") + return _load(path).cross_entropy_loss_grad + + +def _peak_of(fn, N, V, dtype, seed, guard): + """max_memory_allocated over one call, inputs freshly generated (only they + are resident at reset, so the input buffer is the shared floor).""" + torch.cuda.empty_cache() + torch.cuda.synchronize() + logits = make_logits(N, V, seed, dtype=dtype) + labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN) + torch.cuda.synchronize() + torch.cuda.reset_peak_memory_stats() + if guard: + with forbidden_ce_guard(): + loss, grad = fn(logits, labels, IGN, LS) + else: + loss, grad = fn(logits, labels, IGN, LS) + torch.cuda.synchronize() + peak = torch.cuda.max_memory_allocated() + del logits, labels, loss, grad + torch.cuda.empty_cache() + return int(peak) + + +def _agree(candidate, baseline, N, V, dtype, seed): + """Candidate must match baseline within tolerance before its peak counts.""" + logits = make_logits(N, V, seed, dtype=dtype) + labels = make_labels(N, V, seed + 1, ignore_frac=IGNORE_FRAC, ignore_index=IGN) + b_loss, b_grad = baseline(logits.clone(), labels, IGN, LS) + with forbidden_ce_guard(): + c_loss, c_grad = candidate(logits.clone(), labels, IGN, LS) + bf16 = dtype == torch.bfloat16 + assert_loss_close(c_loss, b_loss, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]") + assert_grad_close(c_grad, b_grad, bf16=bf16, msg=f"[agree {N}x{V} {dtype}]") + del logits, labels, b_loss, b_grad, c_loss, c_grad + torch.cuda.empty_cache() + + +def main(): + if not torch.cuda.is_available(): + print("CUDA_UNAVAILABLE") + sys.exit(2) + torch.cuda.init() + candidate = load_candidate().cross_entropy_loss_grad + baseline = _baseline_fn() + + ratios = [] + seed = 5000 + for tag, N, V, dtype in SHAPES: + try: + _agree(candidate, baseline, N, V, dtype, seed) + except AssertionError as exc: + print(f"BENCH_FAIL {tag}: {exc}") + print("speedup=0.0") + sys.exit(1) + cand_peak = _peak_of(candidate, N, V, dtype, seed, guard=True) + base_peak = _peak_of(baseline, N, V, dtype, seed, guard=False) + ratio = base_peak / max(cand_peak, 1) + ratios.append(ratio) + print(f"shape={tag} N={N} V={V} dtype={dtype} " + f"baseline_peak={base_peak} candidate_peak={cand_peak} ratio={ratio:.4f}") + seed += 100 + + print(f"speedup={geomean(ratios):.4f}") + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/kb_ce_harness.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/kb_ce_harness.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b8ffe201b463748f8361162d63002528c2f542 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/kb_ce_harness.py @@ -0,0 +1,185 @@ +"""Shared harness for the cross-entropy loss+gradient contract. + +Provides: + * ``load_candidate`` — import the candidate module from /app/repo, + * deterministic input generation (``make_logits`` / ``make_labels``), + * a high-precision float32 reference (``ref_ce``) — the ground truth for both + loss and gradient, + * ``assert_loss_close`` / ``assert_grad_close`` tolerance comparisons, + * ``count_nonzero_rows`` — the work-evidence signal, + * ``geomean``, + * ``forbidden_ce_guard`` — a runtime guard that blocks the framework's + single-call fused cross-entropy loss while the candidate runs, so the + candidate cannot delegate the whole computation to the vendor primitive it + is meant to build. + +The reference materialises full-size buffers on purpose (it is only the +correctness oracle, not scored on memory). +""" + +import contextlib +import importlib.util +import math +import os + +import torch + +# candidate-vs-reference tolerances +LOSS_ATOL = 1e-4 +LOSS_ATOL_BF16 = 3e-2 +LOSS_RTOL = 1e-3 +# bf16 loss carries the dtype's own ~2^-8 (~0.4%) quantization; at a large-vocab +# loss magnitude (~19) that is ~0.075 absolute, which a 1e-3 relative term cannot +# represent. Comparing a correctly bf16-cast loss (reference/oracle) against the +# fp32 baseline loss must tolerate that quantization, so bf16 uses a relative term +# above bf16's resolution. The (N,V) gradient parity check remains the tight, +# authoritative correctness signal. +LOSS_RTOL_BF16 = 8e-3 +GRAD_ATOL = 1e-4 +GRAD_RTOL = 1e-3 +GRAD_ATOL_BF16 = 8e-3 +GRAD_RTOL_BF16 = 1e-2 + + +def repo_dir(): + return os.environ.get("KB_REPO_DIR", "/app/repo") + + +def load_candidate(): + """Import the candidate module from the repo under test.""" + path = os.path.join(repo_dir(), "cross_entropy_grad.py") + spec = importlib.util.spec_from_file_location("candidate_ce_grad", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + if not hasattr(mod, "cross_entropy_loss_grad"): + raise AttributeError(f"{path} does not define cross_entropy_loss_grad()") + return mod + + +# --------------------------------------------------------------------------- # +# Deterministic input generation +# --------------------------------------------------------------------------- # +def make_logits(N, V, seed, dtype=torch.float32, scale=4.0, device="cuda"): + g = torch.Generator(device="cpu").manual_seed(seed) + x = torch.randn(N, V, generator=g, dtype=torch.float32) * scale + return x.to(device).to(dtype) + + +def make_labels(N, V, seed, ignore_frac=0.0, ignore_index=-100, device="cuda"): + g = torch.Generator(device="cpu").manual_seed(seed) + lab = torch.randint(0, V, (N,), generator=g, dtype=torch.int64) + if ignore_frac > 0.0: + mask = torch.rand(N, generator=g) < ignore_frac + lab[mask] = ignore_index + return lab.to(device) + + +# --------------------------------------------------------------------------- # +# High-precision float32 reference (ground truth for loss + grad) +# --------------------------------------------------------------------------- # +def ref_ce(logits, labels, ignore_index=-100, label_smoothing=0.0): + N, V = logits.shape + s = float(label_smoothing) + valid = labels != ignore_index + n_valid = int(valid.sum().item()) + denom = max(n_valid, 1) + safe = labels.clamp(min=0).long() + idx = torch.arange(N, device=logits.device) + + lf = logits.to(torch.float32) + logp = torch.log_softmax(lf, dim=-1) + logp_y = logp[idx, safe] + nll = -logp_y + smooth = -logp.mean(dim=1) + row_loss = (1.0 - s) * nll + s * smooth + row_loss = torch.where(valid, row_loss, torch.zeros_like(row_loss)) + loss = row_loss.sum() / denom + + prob = logp.exp() + grad = prob.clone() + if s != 0.0: + grad = grad - (s / V) + grad[idx, safe] = grad[idx, safe] - (1.0 - s) + grad = grad / denom + grad[~valid] = 0.0 + return loss.to(logits.dtype), grad.to(logits.dtype) + + +# --------------------------------------------------------------------------- # +# Comparisons +# --------------------------------------------------------------------------- # +def assert_loss_close(cand_loss, ref_loss, bf16=False, msg=""): + cl = torch.as_tensor(cand_loss).to(torch.float32).reshape(()) + rl = torch.as_tensor(ref_loss).to(torch.float32).reshape(()) + if not torch.isfinite(cl): + raise AssertionError(f"candidate loss is non-finite {msg}") + atol = LOSS_ATOL_BF16 if bf16 else LOSS_ATOL + rtol = LOSS_RTOL_BF16 if bf16 else LOSS_RTOL + d = float((cl - rl).abs()) + tol = atol + rtol * float(rl.abs()) + if d > tol: + raise AssertionError(f"loss mismatch: |{float(cl):.6f}-{float(rl):.6f}|={d:.6f} > {tol:.6f} {msg}") + + +def assert_grad_close(cand_grad, ref_grad, bf16=False, msg=""): + if tuple(cand_grad.shape) != tuple(ref_grad.shape): + raise AssertionError(f"grad shape {tuple(cand_grad.shape)} vs {tuple(ref_grad.shape)} {msg}") + if cand_grad.dtype != ref_grad.dtype: + raise AssertionError(f"grad dtype {cand_grad.dtype} vs {ref_grad.dtype} {msg}") + c = cand_grad.to(torch.float32) + r = ref_grad.to(torch.float32) + if not torch.isfinite(c).all(): + raise AssertionError(f"candidate grad has non-finite values {msg}") + atol = GRAD_ATOL_BF16 if bf16 else GRAD_ATOL + rtol = GRAD_RTOL_BF16 if bf16 else GRAD_RTOL + diff = (c - r).abs() + tol = atol + rtol * r.abs() + bad = diff > tol + if bad.any(): + raise AssertionError( + f"{int(bad.sum())}/{c.numel()} grad elements out of tolerance " + f"(worst excess {float((diff - tol).max()):.5f}) {msg}") + + +def count_nonzero_rows(grad): + """Work-evidence: number of rows whose gradient is not all-zero.""" + return int((grad.to(torch.float32).abs().sum(dim=1) > 0).sum().item()) + + +# --------------------------------------------------------------------------- # +# Runtime guard: block the framework's single-call fused cross-entropy loss +# while the candidate runs (the candidate must compute loss + grad itself). +# --------------------------------------------------------------------------- # +@contextlib.contextmanager +def forbidden_ce_guard(): + def _blocked(*args, **kwargs): + raise RuntimeError("forbidden fused cross-entropy primitive called during scoring") + + class _BlockedModule: + def __init__(self, *a, **k): + raise RuntimeError("forbidden fused cross-entropy primitive called during scoring") + + saved = [] + for obj, name, repl in [ + (torch.nn.functional, "cross_entropy", _blocked), + (torch.nn, "CrossEntropyLoss", _BlockedModule), + ]: + if hasattr(obj, name): + saved.append((obj, name, getattr(obj, name))) + try: + setattr(obj, name, repl) + except Exception: + saved.pop() + try: + yield + finally: + for obj, name, val in reversed(saved): + try: + setattr(obj, name, val) + except Exception: + pass + + +def geomean(values): + vals = [max(float(v), 1e-12) for v in values] + return math.exp(sum(math.log(v) for v in vals) / len(vals)) diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.caveat.md b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..26a12451abee48908a2b64732d0f57c5ad1a7123 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +`ref_speedup.txt` 里的 **7.4157** 是 oracle 标定常量,判分时只读、不重跑 oracle: + + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + +`tests/test.sh` 的解析顺序是 **`tests/ref_speedup.txt` → `/opt/verifier-correctness-manifest.json` → 1.0**; +回落到 1.0 会让所有 reward 归 0,所以这个文件必须存在且 > 1。 + +## 标定条件 + +- 硬件:**NVIDIA H20** +- 运行栈:`torch 2.7.0`(原始私有基座声明 torch 2.5.1/triton 3.1.0,任务 overlay 又 `pip install torch==2.7.0`,锚点即在 2.7.0 下标定) +- 线程:`OMP/MKL/OPENBLAS_NUM_THREADS=1`(计时稳定性的一部分,已写进镜像 ENV) + +## 硬件不一致时如何重标 + +verifier 原生支持模式分派,参考实现**按路径传入、从不烤进镜像**: + +```bash +docker run --rm --gpus all -v "$PWD/tests:/tests:ro" -v "<放 oracle.patch 的目录>:/patches:ro" \ + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ + fai/kfc-insea-fused-softmax-cross-entropy-grad-loop16:oss bash /tests/test.sh +# 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt +``` + +自证:`noop`(不打补丁)应 ≈1.0 → 被门到 0;`negative`(`KERNELBENCH_NEGATIVE_PATCH=`)必须 0。 + +参考实现:见本包 `solution/oracle.patch`(reviewer-only,已被 `.dockerignore` 排除,不进镜像)。 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.txt b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..47a6b19f5ca3f5d9ffb6f3bcb60a44b16cc9fac3 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/ref_speedup.txt @@ -0,0 +1 @@ +7.4157 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test.sh b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7d665d3bf4c76bc4bd4f34712480493f339f16c3 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# Verifier for insea-fused-softmax-cross-entropy-grad-loop16 (cross-entropy loss + input +# gradient; value axis = PEAK MEMORY, not wall-time). Pattern A, ACCELERATION lane, +# scored on torch.cuda.max_memory_allocated on H20. Modes: candidate|noop|oracle|negative +set -uo pipefail +# Never trust the exec context — the harness may exec this in a +# NON-login shell where bare python3 has no torch. Pin the venv first. +export PATH=/opt/kernelbench-venv/bin:$PATH +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/verifier +mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +CAND_FILE="$REPO/cross_entropy_grad.py" +export KB_CANDIDATE_MODULE="$CAND_FILE" +export KB_BASELINE_MODULE=/opt/verifier-baseline/cross_entropy_grad.py + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true +baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true +expected_cases=12; actual_cases=0 +speedup=1.0; ref_speedup=1.0; hw="unknown" + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + # reviewer-only mode: reset the working tree to the frozen baseline so several + # modes running back-to-back in one container session each start clean. candidate/noop + # NEVER resets (this branch is skipped for them), so a solver session is untouched. + git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true + git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed" +fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true + git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true +fi + +# anti-cheat: only cross_entropy_grad.py may change +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + case "$f" in + cross_entropy_grad.py) : ;; + *__pycache__*) : ;; + *) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;; + esac +done < "$LOG/anti_cheat_changed_files.txt" + +# anti-cheat: the framework's single-call fused cross-entropy loss is out of scope +# (the candidate must compute the loss + gradient itself). Textual scan of the file. +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 + anti_cheat_ok=false; add_hard "forbidden_fused_ce_primitive" +fi + +# trusted restore: hidden suite ships in tests/ payload (fresh at scoring) +for f in test_cross_entropy_grad.py gpu_peakmem.py kb_ce_harness.py; do + [ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; } +done + +# ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild) +if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then + ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt") +elif [ -f /opt/verifier-correctness-manifest.json ]; then + 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) +fi +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) + +# correctness gate (needs CUDA) +if [ "$correctness_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 test_cross_entropy_grad.py ) > "$LOG/correctness.log" 2>&1 + crc=$? + actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0} + if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then + hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed" + fi +fi + +# measurement: PEAK MEMORY ratio (baseline_peak/candidate_peak), median over 3 runs +# (deterministic metric; median guards against allocator jitter). Only if correct. +if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then + : > "$LOG/bench.log" + sp_list="" + for r in 1 2 3; do + line=$( cd "$TESTS_DIR" && python3 gpu_peakmem.py 2>>"$LOG/bench.log" ) + echo "$line" >> "$LOG/bench.log" + sp=$(echo "$line" | sed -n 's/.*speedup=\([0-9.-]*\).*/\1/p') + [ -n "$sp" ] && sp_list="$sp_list $sp" + done + speedup=$(python3 -c "v=sorted(float(x) for x in '$sp_list'.split());print(f'{v[len(v)//2]:.5f}' if v else '-1')") + if [ -z "$sp_list" ] || python3 -c "import sys;sys.exit(0 if float('$speedup')<=0 else 1)"; then + benchmark_ok=false; add_hard "benchmark_execution_failed" + fi +else + benchmark_ok=false +fi + +HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi +DIAG_TAIL="" +if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then + DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g') +fi +cat > "$LOG/verifier_state.json" < "$LOG/correctness_results.json" < "$LOG/benchmark_results.json" </dev/null || python3 /tests/compute_reward.py 2>/dev/null || true +REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null) +echo "MODE=$MODE cases=$actual_cases/$expected_cases peakmem_ratio=$speedup ref=$ref_speedup hw=$hw reward=$REW" +[ -n "$REW" ] && exit 0 || exit 1 diff --git a/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test_cross_entropy_grad.py b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test_cross_entropy_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0b1ff06c8b19d55b240a3db637abfdf7dc1344 --- /dev/null +++ b/tasks/kfc/insea-fused-softmax-cross-entropy-grad-loop16/task/tests/test_cross_entropy_grad.py @@ -0,0 +1,222 @@ +"""Correctness suite for the cross-entropy loss+gradient contract — 12 cases. + +Each case prints "CASE_PASS " or "CASE_FAIL : ". +The runner greps the number of CASE_PASS lines (expects 12). + +The candidate may overwrite its ``logits`` argument in place, so every case +passes the candidate a fresh clone and computes the reference from the pristine +tensor first. +""" + +import sys +import traceback + +import torch + +from kb_ce_harness import ( + assert_grad_close, + assert_loss_close, + count_nonzero_rows, + forbidden_ce_guard, + load_candidate, + make_labels, + make_logits, + ref_ce, +) + +IGN = -100 +CASES = [] + + +def case(fn): + CASES.append(fn) + return fn + + +def _run(fn, N, V, seed, dtype=torch.float32, ls=0.0, ignore_frac=0.0): + logits = make_logits(N, V, seed, dtype=dtype) + labels = make_labels(N, V, seed + 1, ignore_frac=ignore_frac, ignore_index=IGN) + ref_loss, ref_grad = ref_ce(logits, labels, ignore_index=IGN, label_smoothing=ls) + with forbidden_ce_guard(): + c_loss, c_grad = fn(logits.clone(), labels, IGN, ls) + bf16 = dtype == torch.bfloat16 + tag = f"[N={N} V={V} dtype={dtype} ls={ls} ign={ignore_frac}]" + assert_loss_close(c_loss, ref_loss, bf16=bf16, msg=tag) + assert_grad_close(c_grad, ref_grad, bf16=bf16, msg=tag) + + +@case +def normal_fp32(fn): + _run(fn, 256, 4096, seed=100) + + +@case +def normal_bf16(fn): + _run(fn, 256, 4096, seed=150, dtype=torch.bfloat16) + + +@case +def mean_with_ignore(fn): + _run(fn, 320, 3072, seed=200, ignore_frac=0.35) + + +@case +def all_ignore(fn): + # every row ignored -> loss 0, grad all zero + N, V = 128, 2048 + logits = make_logits(N, V, 300) + labels = torch.full((N,), IGN, dtype=torch.int64, device="cuda") + with forbidden_ce_guard(): + c_loss, c_grad = fn(logits.clone(), labels, IGN, 0.0) + if abs(float(c_loss)) > 1e-5: + raise AssertionError(f"all-ignore loss should be 0, got {float(c_loss)}") + if c_grad.shape != (N, V): + raise AssertionError(f"bad grad shape {tuple(c_grad.shape)}") + if not (c_grad.to(torch.float32) == 0).all(): + raise AssertionError("all-ignore grad should be exactly zero") + + +@case +def single_class(fn): + # V == 1: softmax is 1, loss is 0, grad is 0 + _run(fn, 64, 1, seed=400) + + +@case +def single_row(fn): + _run(fn, 1, 2048, seed=500) + + +@case +def nontile_vocab(fn): + # V not a multiple of any common chunk size + _run(fn, 128, 4099, seed=600) + + +@case +def label_smoothing(fn): + _run(fn, 256, 2048, seed=700, ls=0.1) + + +@case +def error_contract(fn): + N, V = 32, 512 + logits = make_logits(N, V, 800) + labels = make_labels(N, V, 801) + # integer logits -> TypeError + try: + fn(logits.to(torch.int32), labels, IGN, 0.0) + raise AssertionError("integer logits did not raise TypeError") + except TypeError: + pass + # float labels -> TypeError + try: + fn(logits.clone(), labels.to(torch.float32), IGN, 0.0) + raise AssertionError("float labels did not raise TypeError") + except TypeError: + pass + # 1-D logits -> ValueError + try: + fn(logits.reshape(-1).clone(), labels, IGN, 0.0) + raise AssertionError("1-D logits did not raise ValueError") + except ValueError: + pass + # labels wrong length -> ValueError + try: + fn(logits.clone(), labels[:-1], IGN, 0.0) + raise AssertionError("wrong-length labels did not raise ValueError") + except ValueError: + pass + # negative label_smoothing -> ValueError + try: + fn(logits.clone(), labels, IGN, -0.1) + raise AssertionError("negative label_smoothing did not raise ValueError") + except ValueError: + pass + # a non-ignored label out of range [0, V) -> ValueError + bad = labels.clone() + bad[0] = V # out of range, not the ignore sentinel + try: + fn(logits.clone(), bad, IGN, 0.0) + raise AssertionError("out-of-range label did not raise ValueError") + except ValueError: + pass + + +@case +def metamorphic_const_shift(fn): + """Adding a per-row constant to all logits leaves loss AND grad unchanged.""" + N, V = 192, 2048 + logits = make_logits(N, V, 900) + labels = make_labels(N, V, 901) + with forbidden_ce_guard(): + loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0) + g = torch.Generator(device="cpu").manual_seed(902) + # a large positive per-row shift: a numerically stable softmax is invariant, + # while a non-stable one (no max subtraction) overflows -> NaN -> fails here. + shift = (torch.rand(N, generator=g) * 40.0 + 80.0).to(logits.device).to(logits.dtype) + logits_b = logits + shift[:, None] + with forbidden_ce_guard(): + loss_b, grad_b = fn(logits_b.clone(), labels, IGN, 0.0) + assert_loss_close(loss_b, loss_a, msg="[const-shift loss]") + assert_grad_close(grad_b, grad_a, msg="[const-shift grad]") + + +@case +def metamorphic_permute_rows(fn): + """Permuting the rows permutes the gradient rows and leaves the mean loss unchanged.""" + N, V = 256, 2048 + logits = make_logits(N, V, 1000) + labels = make_labels(N, V, 1001, ignore_frac=0.2, ignore_index=IGN) + with forbidden_ce_guard(): + loss_a, grad_a = fn(logits.clone(), labels, IGN, 0.0) + g = torch.Generator(device="cpu").manual_seed(1002) + perm = torch.randperm(N, generator=g).to(logits.device) + with forbidden_ce_guard(): + loss_b, grad_b = fn(logits[perm].clone(), labels[perm], IGN, 0.0) + assert_loss_close(loss_b, loss_a, msg="[permute loss]") + assert_grad_close(grad_b, grad_a[perm], msg="[permute grad]") + + +@case +def work_evidence(fn): + """Exactly the non-ignored rows carry a nonzero gradient; ignored rows are zero.""" + N, V = 384, 2048 + logits = make_logits(N, V, 1100) + labels = make_labels(N, V, 1101, ignore_frac=0.5, ignore_index=IGN) + n_valid = int((labels != IGN).sum().item()) + with forbidden_ce_guard(): + _, c_grad = fn(logits.clone(), labels, IGN, 0.0) + nz = count_nonzero_rows(c_grad) + if nz != n_valid: + raise AssertionError(f"nonzero-grad rows {nz} != valid labels {n_valid}") + ignored = (labels == IGN) + if ignored.any() and not (c_grad[ignored].to(torch.float32) == 0).all(): + raise AssertionError("ignored rows have nonzero gradient") + + +def main(): + if not torch.cuda.is_available(): + print("CUDA_UNAVAILABLE") + sys.exit(2) + mod = load_candidate() + fn = mod.cross_entropy_loss_grad + passed = 0 + for fn_case in CASES: + name = fn_case.__name__ + try: + fn_case(fn) + torch.cuda.synchronize() + passed += 1 + print(f"CASE_PASS {name}") + except Exception as exc: # noqa: BLE001 + reason = f"{type(exc).__name__}: {exc}" + print(f"CASE_FAIL {name}: {reason.splitlines()[0][:300]}") + traceback.print_exc(file=sys.stderr) + total = len(CASES) + print(f"CASES_PASSED={passed}/{total}") + sys.exit(0 if passed == total else 1) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt b/tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..64d00e7d12ffd9b7fa1a764dcbc5e6abf050e013 --- /dev/null +++ b/tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/ref_speedup.txt @@ -0,0 +1 @@ +1.60 diff --git a/tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/test.sh b/tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..94be7d84566e2f0bcbfa4a5c6c97c24532dce5b4 --- /dev/null +++ b/tasks/kfc/insea-h2d-prefetch-compute-overlap-loop16/task/environment/loop/private/dev_tests/test.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +# Verifier for insea-h2d-prefetch-compute-overlap-loop16 (chunked H2D transfer overlapped with compute). +# Pattern A, ACCELERATION lane, wall-time on H20 (transfer latency hidden behind compute). +# Modes: candidate|noop|oracle|negative +set -uo pipefail +# Never trust the exec context — the harness may exec this in a +# NON-login shell where bare python3 has no torch. Pin the venv first. +export PATH=/opt/kernelbench-venv/bin:$PATH +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/loop/dev +mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +CAND_FILE="$REPO/streamed_apply.py" +export KB_CANDIDATE_MODULE="$CAND_FILE" +export KB_BASELINE_MODULE=/opt/verifier-baseline/streamed_apply.py + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true +baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true +expected_cases=12; actual_cases=0 +speedup=1.0; ref_speedup=1.0; hw="unknown" + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + # reviewer-only mode: reset the working tree to the frozen baseline so several + # modes running back-to-back in one container session each start clean. candidate/noop + # NEVER resets (this branch is skipped for them), so a solver session is untouched. + git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true + git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed" +fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true + git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true +fi + +# anti-cheat: only streamed_apply.py may change +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + case "$f" in + streamed_apply.py) : ;; + *__pycache__*) : ;; + *) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;; + esac +done < "$LOG/anti_cheat_changed_files.txt" + +# anti-cheat: framework auto-overlap / graph-capture conveniences are forbidden in the +# candidate file (the overlap must be built explicitly with streams + events). The +# candidate symbol is `streamed_chunk_apply` so these patterns never self-match; explicit +# torch.cuda.Stream / Event / pinned / non_blocking copies are the intended tool and pass. +if [ -f "$CAND_FILE" ] && grep -Eq "CUDAGraph|make_graphed_callables|cuda\.graph" "$CAND_FILE"; then + anti_cheat_ok=false; add_hard "forbidden_overlap_helper" +fi + +# trusted restore: hidden suite ships in tests/ payload (fresh at scoring) +for f in test_streamed_apply.py gpu_bench.py kb_overlap_harness.py; do + [ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; } +done + +# ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild) +if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then + ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt") +elif [ -f /opt/verifier-correctness-manifest.json ]; then + 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) +fi +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) + +# correctness gate (needs CUDA) +if [ "$correctness_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 test_streamed_apply.py ) > "$LOG/correctness.log" 2>&1 + crc=$? + actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0} + if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then + hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed" + fi +fi + +# timing: median speedup over 3 runs (only if correct) +if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then + : > "$LOG/bench.log" + sp_list="" + for r in 1 2 3; do + line=$( cd "$TESTS_DIR" && python3 gpu_bench.py 2>>"$LOG/bench.log" ) + echo "$line" >> "$LOG/bench.log" + sp=$(echo "$line" | sed -n 's/.*speedup=\([0-9.-]*\).*/\1/p') + [ -n "$sp" ] && sp_list="$sp_list $sp" + done + speedup=$(python3 -c "v=sorted(float(x) for x in '$sp_list'.split());print(f'{v[len(v)//2]:.5f}' if v else '-1')") + if [ -z "$sp_list" ] || python3 -c "import sys;sys.exit(0 if float('$speedup')<=0 else 1)"; then + benchmark_ok=false; add_hard "benchmark_execution_failed" + fi +else + benchmark_ok=false +fi + +HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi +DIAG_TAIL="" +if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then + DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g') +fi +cat > "$LOG/verifier_state.json" < "$LOG/correctness_results.json" < "$LOG/benchmark_results.json" </dev/null || python3 /tests/compute_reward.py 2>/dev/null || true +REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null) +echo "MODE=$MODE cases=$actual_cases/$expected_cases speedup=$speedup ref=$ref_speedup hw=$hw reward=$REW" +[ -n "$REW" ] && exit 0 || exit 1 diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/.dockerignore b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/.dockerignore @@ -0,0 +1,24 @@ +# .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does +# NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile . +# The reference implementation and every authoring artefact MUST NOT reach an image layer. +*.patch +oracle* +negative* +baseline2* +scope_card.json +degradation_manifest.json +task_meta.json +loop_map_entry.json +job.yaml +intermediates/ +_retrofit* +sr_validate* +leak_audit/ +self_check/ +variants/ +**/__pycache__/ +**/*.pyc +*.bak +*.bak_* +*.pre_* +**/*.pre_* diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/Dockerfile b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bcc5db155341d11faa189d754c9188b1f6c91862 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/Dockerfile @@ -0,0 +1,154 @@ +# syntax=docker/dockerfile:1 +# ============================================================================= +# wro-deepspeed-curriculum-cluster-select-loop16 — OPEN-SOURCE, self-contained task image +# +# Task: make the declared scope faster while preserving its observable behaviour exactly. +# Editable scope (the ONLY files the scope gate allows to change): +## (declared in tests/test.sh) +# +# FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image. +# CPU ONLY — task.toml declares gpus = 0. +# Platform: linux/amd64 or arm64. +# Build context = this task directory (the Dockerfile lives in environment/). +# +# PROVENANCE of environment/repo/ (so anyone can re-derive it independently) +# recovered from: /kernelbench/wro-deepspeed-curriculum-cluster-select-loop16:v1@sha256:a544e9d3a324523f6d852c174c92b6ae1ebe40c5accb62e0bdab1658c3ae3603 +# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in +# manifest order; .git and any .wh..wh..opq marker dropped. +# 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. +## +# ----------------------------------------------------------------------------- +# BUILD (needs outbound network for PyPI only — the working tree ships in this package) +# cd <...>/wro-deepspeed-curriculum-cluster-select-loop16/task +# docker build -f environment/Dockerfile -t fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss . +# +# RUN docker run --rm -it fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss +# SCORE docker run --rm -v "$PWD/tests:/tests:ro" fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss bash /tests/test.sh +# # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative) +# +# 🔴 RE-CALIBRATE THE ANCHOR ON YOUR HARDWARE +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; ref_speedup = 20.777027 . +# tests/test.sh resolves it from tests/ref_speedup.txt FIRST, then falls back to +# /opt/verifier-correctness-manifest.json, then to 1.0 (which would make every reward 0). +# The value was calibrated on the authoring CPU lane (Intel Sapphire Rapids). The verifier supports mode dispatch natively, so +# re-measuring is ONE command (the reference patch is passed BY PATH and never baked): +# docker run --rm -v "$PWD/tests:/tests:ro" -v ":/patches:ro" \ +# -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ +# fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss bash /tests/test.sh +# then write the measured speedup into tests/ref_speedup.txt. See tests/ref_speedup.caveat.md. +# Sanity: noop (no patch) ~= 1.0 -> gated to 0; negative MUST score 0. +# +# VERSION ANCHORS +# Python 3.11 · standard library + numpy +# The original private base declared torch 2.5.1 / triton 3.1.0 and the task overlay then ran +# `pip install torch==2.7.0` — 2.7.0 is therefore the version the anchor was calibrated under. +# ============================================================================= +FROM python:3.11-slim-bookworm + +ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \ + PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential git ca-certificates curl procps coreutils tar gzip vim less file jq \ + && rm -rf /var/lib/apt/lists/* + +# ---- venv at this EXACT path: tests/test.sh puts /opt/kernelbench-venv/bin at the head of PATH. ---- +ENV VENV=/opt/kernelbench-venv +RUN python3 -m venv "$VENV" +ENV PATH=$VENV/bin:$PATH +RUN pip install --no-cache-dir -U pip setuptools wheel +RUN pip install --no-cache-dir "numpy>=1.26,<3" + +# ---- the graded working tree. A REAL directory (not a symlink): the scope gate runs +# `git -C /app/repo status --porcelain`, which cannot see through a symlink. ---- +RUN mkdir -p /app/repo /app/.timer /app/workspace /logs/verifier /logs/agent /logs/artifacts +COPY environment/repo/ /app/repo/ +COPY instruction.md /app/instruction.md + +# ---- the baseline commit = the diff base the scope gate compares against. +# 🔴 core.fileMode=false is LOAD-BEARING, not hygiene: a shipped image in this corpus had +# core.fileMode=true while some files were 0775 on disk but 100644 in the index, so +# `git status --porcelain` reported phantom out-of-scope paths in EVERY mode and forced +# reward to 0. Setting it false at creation makes that class of defect impossible. ---- +RUN git config --global user.email "reviewer@fai-bench.local" \ + && git config --global user.name "fai-bench" \ + && git config --global init.defaultBranch main \ + && git config --global --add safe.directory /app/repo \ + && cd /app/repo \ + && git init -q \ + && git config core.fileMode false \ + && printf '__pycache__/\n*.pyc\n' >> .gitignore \ + && git add -A \ + && git commit -qm "carved baseline (graded starting point)" \ + && rm -rf .git/logs \ + && test "$(git rev-list --count HEAD)" = "1" \ + && test -z "$(git remote)" \ + && test "$(git config --get core.fileMode)" = "false" \ + && test -z "$(git status --porcelain)" \ + && echo "[build] /app/repo: 1 commit, no remote, fileMode=false, clean tree" + +# ---- runtime contract (copied verbatim from the shipped image) ---- +COPY environment/runtime/entrypoint.sh /app/entrypoint.sh +COPY environment/runtime/timer.sh /app/timer.sh +RUN chmod 0755 /app/entrypoint.sh /app/timer.sh && chown root:root /app/entrypoint.sh /app/timer.sh +COPY environment/runtime/run_dev_bench.sh /app/workspace/run_dev_bench.sh +RUN chmod 0755 /app/workspace/run_dev_bench.sh +COPY environment/loop/ /opt/loop/ +RUN if [ -f /opt/loop/submit.sh ]; then chmod 0755 /opt/loop/submit.sh; fi \ + && chown -R root:root /opt/loop \ + && if [ -f /opt/loop/score_engine.sh ]; then chmod 0700 /opt/loop/score_engine.sh; fi \ + && if [ -f /opt/loop/sanitize_feedback.py ]; then chmod 0700 /opt/loop/sanitize_feedback.py; fi \ + && if [ -d /opt/loop/private ]; then chmod -R go-rwx /opt/loop/private; fi + +# ---- OPEN grading suite is NOT baked: tests/ (test.sh + compute_reward.py + the workload/harness +# + ref_speedup.txt) is MOUNTED FRESH at /tests when scoring. It ships in this package — +# open-source, but outside the image so the graded harness cannot be edited from the session. + +# ---- 🔴 ANTI-LEAK ASSERTS ---- +RUN set -eu; rc=0; \ + hits="$(find / -xdev -type f \( -name 'oracle*.patch' -o -name 'negative*.patch' \ + -o -name 'baseline2*.patch' -o -name 'scope_card.json' -o -name 'kernel_oracle.py' \ + -o -name 'degradation_manifest.json' \) 2>/dev/null | head -10)"; \ + if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: a reference/authoring file is baked:"; echo "$hits"; rc=1; fi; \ + for p in /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling /tests; do \ + if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path baked: $p"; rc=1; fi; \ + done; \ + test "$rc" = 0; \ + echo "[build] ANTI-LEAK ASSERTS PASS" + +ENV PYTHONPATH=/app/repo \ + PYTHONDONTWRITEBYTECODE=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 +WORKDIR /app/repo + +# ---- build-time smoke: the graded module imports FROM /app/repo (the verifier asserts the same +# thing at scoring time via its import-origin gate) and the scope files are present. ---- +RUN python - <<'PY' +import os, subprocess, sys +sys.path.insert(0, "/app/repo") +for f in ('curriculum_cluster.py',): + p = os.path.join("/app/repo", f) + assert os.path.isfile(p), f"scope file missing: {p}" + print("scope file present:", f, os.path.getsize(p), "B") +import importlib.util +for _mod in ('curriculum_cluster',): + try: + _spec = importlib.util.find_spec(_mod) + except Exception as _e: + print("NOTE: import-origin probe skipped for", _mod, "->", repr(_e), + "(tests/test.sh re-asserts this at scoring time)") + continue + _loc = (getattr(_spec, "origin", "") or "") if _spec else "" + print("resolves:", _mod, "->", _loc or "") + assert not _loc or _loc.startswith("/app/repo"), \ + f"{_mod} resolves OUTSIDE the graded tree: {_loc}" +n = subprocess.run(["git","-C","/app/repo","rev-list","--count","HEAD"], + capture_output=True, text=True).stdout.strip() +assert n == "1", f"git diff base broken (commits={n!r})" +print("OK: scope files, import origin and git base all in place") +PY + +ENTRYPOINT ["/app/entrypoint.sh"] +CMD ["tail","-f","/dev/null"] diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/manifest.json b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..bc92bec428bb094e30db5f67c3eab5a3b9fea868 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/manifest.json @@ -0,0 +1,13 @@ +{ + "max_submissions": 1, + "min_submissions": 1, + "note": "dev reward is an in-session proxy; the runner end-of-session /tests score is authoritative.", + "perf_metric": "speedup", + "reward_form": "raw_speedup(base_ms/cand_ms); no-op ~= 1.0", + "schema_version": "kernelbench_loop_manifest_v1", + "scope": [ + "curriculum_cluster.py" + ], + "scoring": "task tests/test.sh in candidate mode on the live /app/repo", + "task_id": "wro-deepspeed-curriculum-cluster-select-loop16" +} diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/compute_reward.py b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1d9681d8d7c607d26bc36ce4a8f5aa671d35a75b --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/compute_reward.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""compute_reward for wro-deepspeed-curriculum-cluster-select. +reward = baseline_ms / candidate_ms (wall-clock speedup; noop ~ 1.0), gated by +correctness in test.sh (wrong selected sample-ids -> reward 0 there). Records +vs_oracle_ratio as metadata only.""" +import json +import sys + + +def load(path): + for line in open(path): + if line.startswith("WRO_CURRIC_RESULT "): + return json.loads(line[len("WRO_CURRIC_RESULT "):]) + raise SystemExit(f"no WRO_CURRIC_RESULT in {path}") + + +def main(): + cand = load(sys.argv[1]); base = load(sys.argv[2]) + ref = float(sys.argv[3]) if len(sys.argv) > 3 else None + cm = cand.get("timing_ms", -1); bm = base.get("timing_ms", -1) + speedup = (bm / cm) if (cm and cm > 0 and bm > 0) else 0.0 + out = {"reward": round(speedup, 6), "baseline_ms": bm, "candidate_ms": cm, + "speedup": round(speedup, 6)} + if ref: + out["metadata"] = {"vs_oracle_ratio": round(speedup / ref, 4), "ref_speedup": ref} + print(json.dumps(out)) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/test.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b438498a42af22c4ea7384275a74732dfe5e40d3 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/test.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# Verifier for wro-deepspeed-curriculum-cluster-select (curriculum-learning +# difficulty-cluster selection for large-scale training stability). +# ACCELERATION, CPU (host logic; no GPU). +# Scope = curriculum_cluster.py (select_curriculum_cluster). +# Modes: candidate | noop | oracle | negative | baseline2. +# reward = raw wall speedup (base_ms/cand_ms); noop ~ 1.0 (degraded vs itself); +# oracle >> 1 (vectorized boundary-search selection vs O(rows^2) per-row Python +# concatenate); baseline2 in between (block-buffered concat, still row-walked); +# negative = 0 (whole-row shortcut mis-selects the partial boundary rows). +set -uo pipefail +export PATH="/opt/kernelbench-venv/bin:/opt/venv/bin:/usr/local/bin:$PATH" +export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +git config --global --add safe.directory '*' 2>/dev/null || true +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/verifier; mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +SCOPE=("curriculum_cluster.py") + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true +speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1 + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +# ---- apply oracle / baseline2 / negative patch by mode (candidate & noop: no patch) ---- +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"; fi +if [ "$MODE" = "baseline2" ] && [ -n "${KERNELBENCH_BASELINE2_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_BASELINE2_PATCH" 2>"$LOG/baseline2_apply.log" || add_hard "baseline2_apply_failed"; fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true; fi + +# ---- (1) scope-diff HARD GATE: only the scope file may change in /app/repo ---- +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + keep=false + for s in "${SCOPE[@]}"; do [ "$f" = "$s" ] && keep=true; done + case "$f" in *__pycache__*|*.pyc) keep=true;; esac + [ "$keep" = true ] || { scope_ok=false; add_hard "out_of_scope_edit:$f"; } +done < "$LOG/changed_files.txt" + +# ---- (2) import-origin assert: the scope module resolves to the baked /app/repo tree ---- +python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import os, sys +sys.path.insert(0, "/app/repo") +import curriculum_cluster as m +loc = os.path.realpath(m.__file__) +print("SCOPE_LOC", loc) +sys.exit(0 if loc.startswith("/app/repo") else 3) +PY +[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; } + +# ---- (3) trusted-restore: harness uploaded fresh (never baked) ---- +for f in workload.py compute_reward.py; do + [ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; } +done + +# ---- ref_speedup (oracle-calibrated; metadata only) ---- +[ -f /opt/verifier-correctness-manifest.json ] && \ + 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) + +# ---- (4) CORRECTNESS GATE: scope output must match the independent reference ---- +if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1 + cok=$(grep WRO_CURRIC_RESULT "$LOG/correctness.out" | python3 -c "import json,sys +try: print(json.loads(sys.stdin.read().split('WRO_CURRIC_RESULT ',1)[1]).get('correctness_ok')) +except Exception: print('False')" 2>/dev/null || echo False) + if [ "$cok" != "True" ]; then correctness_ok=false; add_hard "correctness_failed"; fi +fi + +# ---- (5) TIMING: candidate wall + baseline (frozen degraded tree at HEAD) ---- +if [ "$correctness_ok" = true ] && { [ "${#HARD[@]}" -eq 0 ] || [ -z "${HARD[*]:-}" ]; }; then + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed" + 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) + cp "$REPO/${SCOPE[0]}" /tmp/wro_cand_scope.py 2>/dev/null || true + git -C "$REPO" checkout -q HEAD -- "${SCOPE[@]}" 2>/dev/null || true + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/base_timing.out" 2>&1 || add_hard "baseline_timing_failed" + 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) + cp /tmp/wro_cand_scope.py "$REPO/${SCOPE[0]}" 2>/dev/null || true + if [ "$(python3 -c "print(1 if $cand_ms>0 and $base_ms>0 else 0)")" = "1" ]; then + speedup=$(python3 -c "print(round($base_ms/$cand_ms,6))") + else benchmark_ok=false; add_hard "timing_invalid"; fi +fi + +# ---- verdict ---- +reward=0.0 +nhard="${#HARD[@]}" +if [ "$nhard" -eq 0 ] && [ "$correctness_ok" = true ]; then reward="$speedup"; fi +hard_str=""; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}" +export WRO_MODE="$MODE" WRO_REWARD="$reward" WRO_SPEEDUP="$speedup" \ + WRO_BASE_MS="$base_ms" WRO_CAND_MS="$cand_ms" WRO_REF="$ref_speedup" \ + WRO_HARD="$hard_str" WRO_SCOPE="$scope_ok" WRO_IMP="$import_origin_ok" \ + WRO_CORR="$correctness_ok" WRO_BENCH="$benchmark_ok" +python3 - > "$LOG/reward.json" <<'PY' +import os, json +def f(x): + try: return float(x) + except: return -1.0 +ref = f(os.environ.get("WRO_REF", "1")); sp = f(os.environ.get("WRO_SPEEDUP", "0")) +v = { + "mode": os.environ.get("WRO_MODE"), + "reward": f(os.environ.get("WRO_REWARD")), + "speedup": sp, + "baseline_ms": f(os.environ.get("WRO_BASE_MS")), + "candidate_ms": f(os.environ.get("WRO_CAND_MS")), + "ref_speedup": ref, + "metadata": {"vs_oracle_ratio": (sp/ref) if ref > 0 else None}, + "hard_fails": os.environ.get("WRO_HARD", "").split(), + "gates": {"scope_ok": os.environ.get("WRO_SCOPE") == "true", + "import_origin_ok": os.environ.get("WRO_IMP") == "true", + "correctness_ok": os.environ.get("WRO_CORR") == "true", + "benchmark_ok": os.environ.get("WRO_BENCH") == "true"}} +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/workload.py b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..753f81671668d62e1b74bc0e40a2fbf1ac01aaa4 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/private/tests/workload.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Standalone verifier workload for the curriculum difficulty-cluster subsystem +(scope: /app/repo/curriculum_cluster.py :: select_curriculum_cluster). + +Drives the scope function on CPU (no torch, no GPU): given per-difficulty-row +sample-id buckets + row metric values, it selects the flat cluster of sample-ids for +a curriculum difficulty window, in VALUE mode (metric window) and PERCENTILE mode +(equal-count percentile band with partial boundary-row slicing). + + correctness : compare the scope's output against an INDEPENDENT reference computed + here (NOT in the editable scope) for BOTH modes. The percentile case + is built with a non-aligned window so the two boundary rows must be + sliced PARTIALLY -- a whole-row shortcut selects the wrong sample-ids. + timing : warmup + timed repeats over a large row set with a wide percentile + window, so the naive per-row growing concatenate dominates and + separates from a vectorized boundary-search selection. The gap GROWS + with the number of rows. + +Emits one line ``WRO_CURRIC_RESULT {json}``. Timing uses process_time (CPU time) so +the reward band is robust to OS descheduling under fleet load. +""" +import json +import statistics +import sys +import time + +import numpy as np + +REPO = "/app/repo" +if REPO not in sys.path: + sys.path.insert(0, REPO) + +# correctness: modest rows; percentile window deliberately non-bin-aligned. +C_SEED = 11 +C_ROWS = 240 +C_BINS = 20 +C_PS = 3 +C_PE = 17 +# timing: many rows + wide percentile window so the naive per-row concat dominates. +T_SEED = 4 +T_ROWS = 12000 +T_BINS = 100 +T_PS = 5 +T_PE = 95 +WARMUP = 1 +ITERS = 3 + + +def load_scope(): + import curriculum_cluster as m + return m + + +def _gen(n_rows, seed, max_metric, min_k, max_k): + rng = np.random.default_rng(seed) + metric = np.sort(rng.integers(0, max_metric, size=n_rows)).astype(np.float64) + idx_to_sample = [] + sid = 0 + for _ in range(n_rows): + k = int(rng.integers(min_k, max_k)) + idx_to_sample.append(np.arange(sid, sid + k, dtype=np.int64)) + sid += k + return idx_to_sample, metric + + +def _ref_value(index_to_sample, metric, lo, hi): + new = None + for row in range(len(index_to_sample)): + if metric[row] <= hi and metric[row] > lo: + rs = np.copy(np.asarray(index_to_sample[row])) + new = rs if new is None else np.concatenate((new, rs), axis=None) + return np.array([], dtype=np.int64) if new is None else new.astype(np.int64) + + +def _ref_percentile(index_to_sample, metric, lo, hi, num_bins): + one_epoch = sum(len(x) for x in index_to_sample) + per = one_epoch // num_bins + start_count = per * lo + end_count = one_epoch if hi == num_bins else per * hi + new = None + cur = 0 + for row in range(len(index_to_sample)): + rsz = len(index_to_sample[row]) + if cur + rsz > start_count: + rstart = max(0, start_count - cur) + rend = rsz if cur + rsz <= end_count else end_count - cur + rs = np.copy(np.asarray(index_to_sample[row])[rstart:rend]) + new = rs if new is None else np.concatenate((new, rs), axis=None) + cur += rsz + if cur >= end_count: + break + return np.array([], dtype=np.int64) if new is None else new.astype(np.int64) + + +def _eq(a, b): + a = np.asarray(a, dtype=np.int64) + b = np.asarray(b, dtype=np.int64) + return a.shape == b.shape and bool(np.array_equal(a, b)) + + +def _correctness_case(m): + idx, metric = _gen(C_ROWS, C_SEED, 600, 2, 18) + # VALUE mode over a mid metric window. + v_lo, v_hi = 100.0, 400.0 + got_v = m.select_curriculum_cluster(idx, metric, "value", v_lo, v_hi) + ref_v = _ref_value(idx, metric, v_lo, v_hi) + value_ok = _eq(got_v, ref_v) + # PERCENTILE mode, non-aligned window -> partial boundary rows. + got_p = m.select_curriculum_cluster(idx, metric, "percentile", C_PS, C_PE, num_bins=C_BINS) + ref_p = _ref_percentile(idx, metric, C_PS, C_PE, C_BINS) + pct_ok = _eq(got_p, ref_p) + # nontrivial: the percentile window must actually slice boundary rows partially + # (else a whole-row shortcut would coincide with the reference). + per = sum(len(x) for x in idx) // C_BINS + start_count = per * C_PS + cum = 0 + partial_boundary = False + for row in range(len(idx)): + rsz = len(idx[row]) + if cum < start_count < cum + rsz: + partial_boundary = True + break + cum += rsz + nontrivial = bool(partial_boundary and len(ref_p) > 0) + return {"correctness_ok": bool(value_ok and pct_ok), + "value_ok": bool(value_ok), "pct_ok": bool(pct_ok), + "ref_value_len": int(len(ref_v)), "ref_pct_len": int(len(ref_p)), + "nontrivial": nontrivial, "module": m.__file__} + + +def _timing_case(m): + idx, metric = _gen(T_ROWS, T_SEED, T_ROWS, 1, 10) + + def once(): + m.select_curriculum_cluster(idx, metric, "percentile", T_PS, T_PE, num_bins=T_BINS) + + for _ in range(WARMUP): + once() + ts = [] + for _ in range(ITERS): + t0 = time.process_time() + once() + ts.append((time.process_time() - t0) * 1000.0) + return statistics.median(ts) + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "correctness" + m = load_scope() + if mode == "correctness": + res = _correctness_case(m) + res["mode"] = "correctness" + print("WRO_CURRIC_RESULT " + json.dumps(res)) + sys.exit(0 if res["correctness_ok"] else 3) + elif mode == "timing": + ms = _timing_case(m) + print("WRO_CURRIC_RESULT " + json.dumps({ + "mode": "timing", "timing_ms": ms, "iters": ITERS, + "rows": T_ROWS, "num_bins": T_BINS, "module": m.__file__})) + sys.exit(0) + else: + print("WRO_CURRIC_RESULT " + json.dumps({"error": "bad_mode"})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/sanitize_feedback.py b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/sanitize_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..d70a722c566c5b3eeaeaa0205cf0b4884fbba7a6 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/sanitize_feedback.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +# ============================================================================ +# wro loop16 finalizer — sanitize_feedback.py (REUSABLE, task-agnostic) 0700 root +# ============================================================================ +"""Leak-free per-round feedback. Invoked ONLY by /opt/loop/submit.sh. Reads the +normalized DEV products under /logs/loop/dev/ and the loop accounting under +/logs/loop/, and prints ONLY a sanitized summary: + + submission k/16 + correctness: PASS | FAIL + [FAIL only] failing_invariant: + dev_speedup: + dev_reward: + best_so_far: submission , dev_speedup , dev_reward + remaining: <16 - k> + finalize_allowed: + [harness path] harness_error: (candidate not at fault) + +NEVER emits: verifier/test.sh/compute_reward contents; hidden workload +names/seeds/counts/shapes; any threshold; ref_speedup; absolute timings. +MAY emit: pass/fail; a named invariant; relative dev_speedup; dev_reward; +submission index; best-so-far; remaining budget; finalize_allowed. +""" +from __future__ import annotations +import json +import sys +from pathlib import Path + +LOOP = Path("/logs/loop") +DEV = LOOP / "dev" +MIN_SUBMISSIONS = 3 +MAX_SUBMISSIONS = 16 + +# Map a raw hard-fail reason (leak-free by construction) to a friendly, actionable +# invariant name. Reasons the wro verifier emits: out_of_scope_edit:, +# import_origin_not_app_repo, correctness_trace_mismatch, timing_invalid, +# candidate_timing_failed, baseline_timing_failed, repo_missing, +# hidden_supplement_missing:, oracle_apply_failed/baseline2_apply_failed. +_HINTS = { + "edit_scope": "your diff changed a file outside the declared editable scope — " + "keep edits to the in-scope product file(s) only", + "import_origin": "the module under test did not resolve to the in-repo tree — " + "do not shadow it with a copy elsewhere", + "correctness": "your output no longer matches the reference behavior exactly — " + "the change must be speed-only, behavior-identical", + "benchmark": "the timing run did not produce a valid measurement — check your " + "change does not crash or hang the benchmarked path", + "verifier_completed": "the check did not complete — re-check your last edit " + "did not cause an early crash", +} + + +def _named_invariant(hard: list[str]) -> str: + h0 = (hard[0] if hard else "") + def startswith(*p): return any(any(x.startswith(pp) for pp in p) for x in hard) + if startswith("out_of_scope_edit", "forbidden_edit_path", "forbidden_source_reference"): + return f"edit_scope: {_HINTS['edit_scope']}" + if startswith("import_origin"): + return f"import_origin: {_HINTS['import_origin']}" + if startswith("correctness_trace_mismatch", "correctness_failed", "correctness"): + return f"output_matches_reference: {_HINTS['correctness']}" + if startswith("timing_invalid", "candidate_timing_failed", "baseline_timing_failed", "benchmark"): + return f"runs_without_error: {_HINTS['benchmark']}" + if h0: + return f"verifier_completed: {_HINTS['verifier_completed']}" + return f"verifier_completed: {_HINTS['verifier_completed']}" + + +def _read_json(path: Path, default): + try: + return json.loads(path.read_text(encoding="utf-8")) + except Exception: + return default + + +def _fmt(x, nd=4): + try: + return f"{float(x):.{nd}g}" + except Exception: + return str(x) + + +def main() -> int: + try: + k = int((LOOP / "count").read_text(encoding="utf-8").strip()) + except Exception: + k = 0 + + he = DEV / "harness_error.txt" + if he.exists(): + try: + msg = he.read_text(encoding="utf-8").strip().splitlines()[0] + except Exception: + msg = "dev engine infrastructure error" + print(f"submission {k}/{MAX_SUBMISSIONS}") + print(f"harness_error: {msg} — this is NOT a defect in your code; do not " + f"debug the harness. Retry or continue optimizing (this attempt was " + f"not counted).") + return 0 + + state = _read_json(DEV / "verifier_state.json", {}) + reward = _read_json(DEV / "reward.json", {}) + corr_ok = bool(state.get("correctness_ok")) + hard = [str(r) for r in (state.get("hard_fail_reasons") or [])] + speedup = reward.get("speedup", None) + r = reward.get("reward", 0.0) + + print(f"submission {k}/{MAX_SUBMISSIONS}") + if corr_ok: + print("correctness: PASS") + else: + print("correctness: FAIL") + print(f"failing_invariant: {_named_invariant(hard)}") + + print(f"dev_speedup: {_fmt(speedup) if speedup is not None else 'n/a'}") + print(f"dev_reward: {_fmt(r)}") + + best = _read_json(LOOP / "best.json", None) + if best and isinstance(best, dict) and best.get("submission"): + print(f"best_so_far: submission {best.get('submission')}, " + f"dev_speedup {_fmt(best.get('speedup'))}, dev_reward {_fmt(best.get('reward'))}") + else: + print("best_so_far: (none — no correctness-passing submission yet)") + + print(f"remaining: {max(0, MAX_SUBMISSIONS - k)}") + print(f"finalize_allowed: {'true' if k >= MIN_SUBMISSIONS else 'false'}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/score_engine.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/score_engine.sh new file mode 100644 index 0000000000000000000000000000000000000000..400d64db5fa4b2cbc66fc0dc643a6976cba4323a --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/score_engine.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# ============================================================================ +# wro loop16 finalizer — score_engine.sh (REUSABLE, task-agnostic) 0700 root +# ============================================================================ +# Invoked ONLY by /opt/loop/submit.sh. Scores the LIVE /app/repo by running the +# task's OWN verifier in candidate mode against the solver's in-scope edits, then +# normalizes its standard wro JSON verdict into the dev files submit.sh/sanitize read. +# +# The wro verifier (tests/test.sh, baked into /opt/loop/private/tests/) already +# performs the whole scoring contract in candidate mode: scope-diff gate, +# import-origin assert, exact-correctness gate vs the baked golden, and paired +# candidate-vs-baseline timing -> a single JSON line: +# {"mode","reward","speedup","baseline_ms","candidate_ms","ref_speedup", +# "metadata",{...},"hard_fails":[...], +# "gates":{"scope_ok","import_origin_ok","correctness_ok","benchmark_ok"}} +# reward = speedup when there are no hard fails and correctness holds, else 0. +# +# This engine is generic across every wro task: the only per-task content is the +# baked verifier itself (test.sh + workload.py + compute_reward.py), staged into +# /opt/loop/private/tests/ at image build time. +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 +set -uo pipefail +git config --global --add safe.directory '*' 2>/dev/null || true + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DEV_OUT="${LOOP_DEV_OUT:-/logs/loop/dev}"; export LOOP_DEV_OUT="$DEV_OUT"; mkdir -p "$DEV_OUT" +TESTS="$HERE/private/tests" +rm -f "$DEV_OUT/harness_error.txt" "$DEV_OUT/verdict.json" 2>/dev/null || true + +if [ ! -f "$TESTS/test.sh" ]; then + echo "baked verifier missing at $TESTS/test.sh" > "$DEV_OUT/harness_error.txt" + exit 3 +fi + +# The loop16 image bakes a committed /app/repo/.git at the degraded baseline (built +# offline; its files carry a different owner/mtime than the image working tree). Refresh +# the index so the task's git scope/timing gates compare CONTENT, not stale stat — a real +# in-scope edit still shows as modified; only content-identical stat noise is cleared. +git -C /app/repo update-index -q --refresh >/dev/null 2>&1 || true + +# Run the task's verifier in candidate mode against the live /app/repo. +KERNELBENCH_VERIFY_MODE=candidate bash "$TESTS/test.sh" > "$DEV_OUT/verdict.raw" 2>"$DEV_OUT/verdict.err" +vr=$? + +# Normalize the wro verdict JSON -> dev files. A genuine harness failure (no +# parseable verdict) is reported as harness_error (submit.sh refunds the budget). +python3 - "$DEV_OUT" "$vr" <<'PY' +import json, sys +from pathlib import Path +DEV = Path(sys.argv[1]); vr = sys.argv[2] +raw = "" +try: raw = (DEV / "verdict.raw").read_text(encoding="utf-8", errors="replace") +except Exception: raw = "" + +# grab the LAST line that parses as a wro verdict (has a "gates" key) +verdict = None +for line in reversed(raw.splitlines()): + line = line.strip() + if not line or not line.startswith("{"): + continue + try: + obj = json.loads(line) + except Exception: + continue + if isinstance(obj, dict) and "gates" in obj and "hard_fails" in obj: + verdict = obj; break + +if verdict is None: + err = (DEV / "verdict.err").read_text(errors="replace")[:400] if (DEV / "verdict.err").exists() else "" + (DEV / "harness_error.txt").write_text( + f"verifier produced no parseable verdict (exit {vr}); " + f"stderr head: {err.splitlines()[0] if err.strip() else '(none)'}\n") + # still write empty dev files so downstream reads don't crash + (DEV / "verifier_state.json").write_text(json.dumps({"correctness_ok": False, "hard_fail_reasons": ["harness_error"]})) + (DEV / "reward.json").write_text(json.dumps({"reward": 0.0, "speedup": 0.0})) + (DEV / "benchmark_results.json").write_text(json.dumps({"aggregate_speedup": 0.0})) + sys.exit(3) + +hard = list(verdict.get("hard_fails") or []) +gates = verdict.get("gates") or {} +# A submission is check-passing iff the verifier assigned NO hard fail (which +# already covers scope / import-origin / correctness / timing failures). +correctness_ok = (len(hard) == 0) and bool(gates.get("correctness_ok", True)) +reward = float(verdict.get("reward") or 0.0) +speedup = float(verdict.get("speedup") or 0.0) + +(DEV / "verifier_state.json").write_text(json.dumps({ + "correctness_ok": correctness_ok, + "hard_fail_reasons": hard, + "gates": gates, +}, sort_keys=True)) +(DEV / "reward.json").write_text(json.dumps({"reward": reward, "speedup": speedup}, sort_keys=True)) +(DEV / "benchmark_results.json").write_text(json.dumps({"aggregate_speedup": speedup}, sort_keys=True)) +sys.exit(0) +PY +rc=$? +if [ "$rc" -ne 0 ] && [ "$rc" -ne 3 ] && [ ! -f "$DEV_OUT/harness_error.txt" ]; then + { echo "score_engine_exit_${rc}"; tail -n 20 "$DEV_OUT/verdict.err" 2>/dev/null; } > "$DEV_OUT/harness_error.txt" +fi +exit "$rc" diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/submit.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/submit.sh new file mode 100644 index 0000000000000000000000000000000000000000..1515f082ded46f5698489d7ece29ddd0cac320c0 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/loop/submit.sh @@ -0,0 +1,210 @@ +#!/usr/bin/env bash +# ============================================================================ +# wro loop16 finalizer — submit.sh (REUSABLE, task-agnostic) +# ============================================================================ +# The solver's ONLY sanctioned scoring interface during a session +# (0755 root:root; the engine + private assets it calls are 0700 root-owned). +# Baked at /opt/loop/submit.sh so it exists from the first turn — unlike +# /tests/, which the grading harness creates only AFTER the agent finishes. +# +# bash /opt/loop/submit.sh # score current /app/repo, get feedback +# bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best iterate, end loop +# +# A wro submission is the solver's EDITS to the declared /app/repo scope files, +# scored by the task's own tests/test.sh in candidate mode -> perf_metric. +# Budget: exactly ONE graded submission (kfc is single-submission). The first +# submit.sh scores and immediately auto-finalizes; there is no second scored attempt. +# end-of-session /tests/test.sh scores the best-of-k iterate. HEAD stays at the +# baked baseline commit, so the anti-cheat scope-diff sees a product-only change. +# +# 🔴 git-safe-directory: a root-owned /app/repo is +# root-owned; without this every git op inside test.sh fails "dubious ownership" +# and silently returns a false 1.0. MUST be the first effective line. +git config --global --add safe.directory '*' 2>/dev/null || true + +# 🔴 PATH-pin: the agent shell + runner verifier exec are NON-login; bare python3 +# may lack the task's numpy/torch. Pin the venv (if present) first, then system. +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 +set -uo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOOP=/logs/loop +DEV="$LOOP/dev" +mkdir -p "$LOOP" "$LOOP/submissions" "$DEV" + +MIN_SUBMISSIONS=1 +MAX_SUBMISSIONS=1 +COUNT_FILE="$LOOP/count" +BEST_FILE="$LOOP/best.json" +STATE_JSONL="$LOOP/state.jsonl" + +# task_id for the finalize record — read from the baked private manifest (generic). +TASK_ID="$(python3 -c 'import json;print(json.load(open("/opt/loop/private/manifest.json")).get("task_id",""))' 2>/dev/null || true)" +[ -n "$TASK_ID" ] || TASK_ID="wro-loop16" + +_read_count() { + if [ -f "$COUNT_FILE" ]; then + awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE" + else + echo 0 + fi +} + +# Non-mutating snapshot of the current working tree -> a git tree hash. +_snapshot_tree() { + local c + c="$(git -C "$REPO" stash create 2>/dev/null || true)" + if [ -n "$c" ]; then + git -C "$REPO" rev-parse "$c^{tree}" 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null + else + git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null + fi +} + +# ------------------- argument parsing ------------------- +MODE=submit +REASON="" +while [ "$#" -gt 0 ]; do + case "$1" in + --finalize) MODE=finalize; shift ;; + --reason) REASON="${2:-}"; shift 2 ;; + --reason=*) REASON="${1#--reason=}"; shift ;; + *) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"\"]]" >&2; exit 2 ;; + esac +done + +# ------------------- finalize ------------------- +if [ "$MODE" = finalize ]; then + CUR="$(_read_count)"; CUR="${CUR:-0}" + if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then + echo "minimum $MIN_SUBMISSIONS submission(s) required before finalize (you have $CUR/$MIN_SUBMISSIONS)" + exit 1 + fi + # Reset the working tree to the baked baseline (HEAD), then plant the winner. + git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true + git -C "$REPO" clean -qfd 2>/dev/null || true + WIN_SUB=""; WIN_TREE="" + if [ -f "$BEST_FILE" ]; then + WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)" + 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)" + fi + PLANTED="none" + if [ -n "$WIN_TREE" ] && git -C "$REPO" read-tree "$WIN_TREE" 2>"$LOOP/finalize_apply.log"; then + # read-tree loaded the winning tree into the index; write it to the worktree. + # HEAD is unchanged (still the baseline commit) -> anti-cheat sees product-only diff. + git -C "$REPO" checkout-index -f -a 2>>"$LOOP/finalize_apply.log" && PLANTED="read-tree" + fi + if [ "$PLANTED" = "none" ] && [ -n "$WIN_SUB" ] && [ -s "$LOOP/submissions/$WIN_SUB/candidate.diff" ]; then + # fallback: re-apply the winning binary diff onto the baseline. + git -C "$REPO" apply --whitespace=nowarn "$LOOP/submissions/$WIN_SUB/candidate.diff" 2>>"$LOOP/finalize_apply.log" \ + && PLANTED="diff-apply" \ + || echo "WARNING: could not plant the winning submission; see /logs/loop/finalize_apply.log" >&2 + fi + REASON="$REASON" WIN_SUB="$WIN_SUB" WIN_TREE="$WIN_TREE" CUR="$CUR" PLANTED="$PLANTED" TASK_ID="$TASK_ID" python3 - <<'PY' +import json, os +from pathlib import Path +LOOP = Path('/logs/loop') +try: best = json.loads((LOOP / 'best.json').read_text()) +except Exception: best = {} +traj = [] +try: + for line in (LOOP / 'state.jsonl').read_text().splitlines(): + line = line.strip() + if not line: continue + row = json.loads(line) + traj.append({'submission': row.get('submission'), 'dev_speedup': row.get('speedup'), + 'dev_reward': row.get('reward'), 'correctness_ok': row.get('correctness_ok')}) +except Exception: pass +out = { + 'schema_version': 'kernelbench_loop_finalize_v1', + 'task_id': os.environ.get('TASK_ID') or 'wro-loop16', + 'mode': 'baked', 'plant_method': os.environ.get('PLANTED'), + 'submissions_used': int(os.environ.get('CUR') or 0), + 'min_submissions': 1, 'max_submissions': 1, + 'winning_submission': (best.get('submission') if best else None), + 'winning_tree': os.environ.get('WIN_TREE') or None, + 'winning_dev_speedup': (best.get('speedup') if best else None), + 'winning_dev_reward': (best.get('reward') if best else None), + 'dev_speedup_trajectory': traj, + 'termination_reason': os.environ.get('REASON') or '', + 'note': 'dev_reward is an in-session proxy; meta.reward is the runner end-of-session score of /app/repo.', +} +(LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n') +PY + RESTORED_TREE="$(_snapshot_tree)" + echo "restored_tree=$RESTORED_TREE plant=$PLANTED" >> "$LOOP/finalize_apply.log" 2>/dev/null || true + if [ -n "$WIN_SUB" ] && [ "$PLANTED" != "none" ]; then + echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (planted via $PLANTED); the grader will now score /app/repo" + else + 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" + fi + exit 0 +fi + +# ------------------- submit ------------------- +CUR="$(_read_count)"; CUR="${CUR:-0}" +if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then + echo "submission $CUR/$MAX_SUBMISSIONS" + echo "budget exhausted — call 'bash /opt/loop/submit.sh --finalize' to grade your best submission" + echo "--- auto-finalizing best-of-$MAX_SUBMISSIONS ---" + exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling" +fi + +# Run the DEV engine on the LIVE /app/repo. +bash "$HERE/score_engine.sh" +engine_rc=$? + +# HARNESS error path: infra failure (rc=3 or a marker). Do NOT consume budget. +if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then + python3 "$HERE/sanitize_feedback.py" + exit 0 +fi + +NEXT=$((CUR + 1)) +echo "$NEXT" > "$COUNT_FILE" + +SNAP="$LOOP/submissions/$NEXT" +mkdir -p "$SNAP" +TREE="$(_snapshot_tree)" +git -C "$REPO" diff --binary HEAD > "$SNAP/candidate.diff" 2>/dev/null || true +echo "${TREE:-}" > "$SNAP/tree_hash.txt" +echo "${TREE:-}" > "$SNAP/tree.txt" +for f in verifier_state.json reward.json benchmark_results.json; do + [ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true +done + +NEXT="$NEXT" TREE="$TREE" python3 - <<'PY' +import json, os, time +from pathlib import Path +LOOP = Path('/logs/loop'); DEV = LOOP / 'dev' +k = int(os.environ['NEXT']); tree = os.environ.get('TREE') or '' +try: state = json.loads((DEV / 'verifier_state.json').read_text()) +except Exception: state = {} +try: reward = json.loads((DEV / 'reward.json').read_text()) +except Exception: reward = {} +corr_ok = bool(state.get('correctness_ok')) +r = float(reward.get('reward') or 0.0); s = float(reward.get('speedup') or 0.0) +row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok, + 'reward': r, 'speedup': s, 'tree': tree, + 'hard_fail_reasons': list(state.get('hard_fail_reasons') or [])} +with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f: + f.write(json.dumps(row) + '\n') +if corr_ok: + best_p = LOOP / 'best.json' + try: best = json.loads(best_p.read_text()) + except Exception: best = None + if best is None or r > float(best.get('reward') or -1.0): + best_p.write_text(json.dumps({'submission': k, 'reward': r, 'speedup': s, 'tree': tree, 'tree_hash': tree}, + indent=2, sort_keys=True) + '\n') +PY + +python3 "$HERE/sanitize_feedback.py" + +if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then + echo "" + echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---" + exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling" +fi + +exit 0 diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/curriculum_cluster.py b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/curriculum_cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..b47a4a51b1cbbf35071d98b56d6536ecc42cf433 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/curriculum_cluster.py @@ -0,0 +1,112 @@ +"""Curriculum-learning difficulty-cluster selection for large-scale training stability. + +DeepSpeed's data-efficiency curriculum learning stabilises very-large-scale +pretraining by feeding samples in an easy-to-hard order: samples are pre-bucketed +by a difficulty *metric* into per-difficulty-value rows (``index_to_sample[v]`` = +the array of sample-ids whose metric value is ``index_to_metric[v]``), sorted by +increasing difficulty. At each curriculum step the trainer selects the flat set of +sample-ids that fall inside a difficulty window, either + + * VALUE-based: every row whose metric value is in ``(value_start, value_end]``, or + * PERCENTILE-based: the contiguous slice of samples covering the fraction of the + one-epoch population in ``[pct_start, pct_end)`` of ``num_bins`` + equal-count percentile bands (with a running-count walk that + slices the two boundary rows partially and takes whole interior + rows, stopping once the end count is reached). + +``select_curriculum_cluster`` returns the concatenated 1-D int array of selected +sample-ids (in row-then-within-row order). This is the functionally-correct but slow +reference: it walks the rows in a Python loop and grows the result with a fresh +``numpy.concatenate`` per matching row (each append re-copies the whole running +buffer, so the row walk is quadratic in the number of selected rows) and re-sums the +one-epoch population from scratch. The public signature and the returned array are +the behavioural contract. + +Mirrors DeepSpeed ``deepspeed/runtime/data_pipeline/data_sampling/data_sampler.py`` +``DeepSpeedDataSampler.get_sample_based_on_metric_value`` / +``get_sample_based_on_metric_percentile`` (Apache-2.0). +""" + +import numpy as np + + +def select_curriculum_cluster( + index_to_sample, + index_to_metric, + mode, + lo, + hi, + num_bins=None, +): + """Select the flat cluster of sample-ids for one curriculum difficulty window. + + :param index_to_sample: list of 1-D numpy int arrays; ``index_to_sample[r]`` holds + the sample-ids bucketed at difficulty-row ``r`` (rows sorted easy->hard). + :param index_to_metric: 1-D numpy array; ``index_to_metric[r]`` is the difficulty + metric value of row ``r`` (non-decreasing in ``r``). + :param mode: ``"value"`` or ``"percentile"``. + :param lo: window lower bound. VALUE mode: exclusive metric lower bound + (``value_start``). PERCENTILE mode: inclusive percentile-band start + (``pct_start``, an int in ``[0, num_bins]``). + :param hi: window upper bound. VALUE mode: inclusive metric upper bound + (``value_end``). PERCENTILE mode: exclusive percentile-band end + (``pct_end``, an int in ``[0, num_bins]``); when ``hi == num_bins`` the band + extends to the exact end of the population. + :param num_bins: number of equal-count percentile bands (PERCENTILE mode only). + :returns: 1-D numpy int64 array of the selected sample-ids (row-then-within-row + order), or an empty int64 array when nothing is selected. + """ + metric = np.asarray(index_to_metric) + n_rows = len(index_to_sample) + + if mode == "value": + # NAIVE_VALUE_ROWWALK: Python loop, re-copy+concat the running buffer per hit. + new_samples = None + for row in range(n_rows): + if metric[row] <= hi and metric[row] > lo: + row_samples = np.copy(np.asarray(index_to_sample[row])) + new_samples = ( + row_samples + if new_samples is None + else np.concatenate((new_samples, row_samples), axis=None) + ) + if new_samples is None: + return np.array([], dtype=np.int64) + return new_samples.astype(np.int64, copy=False) + + if mode == "percentile": + # NAIVE_PERCENTILE_ROWWALK: re-sum the epoch population, then a running-count + # walk that partially slices the two boundary rows and re-copies+concats each. + one_epoch_size = 0 + for row in range(n_rows): + one_epoch_size += len(index_to_sample[row]) + sample_per_pct = one_epoch_size // num_bins + start_count = sample_per_pct * lo + end_count = sample_per_pct * hi + if hi == num_bins: + end_count = one_epoch_size + + new_samples = None + current_count = 0 + for row in range(n_rows): + row_size = len(index_to_sample[row]) + if current_count + row_size > start_count: + row_start = max(0, start_count - current_count) + if current_count + row_size <= end_count: + row_end = row_size + else: + row_end = end_count - current_count + row_samples = np.copy(np.asarray(index_to_sample[row])[row_start:row_end]) + new_samples = ( + row_samples + if new_samples is None + else np.concatenate((new_samples, row_samples), axis=None) + ) + current_count += row_size + if current_count >= end_count: + break + if new_samples is None: + return np.array([], dtype=np.int64) + return new_samples.astype(np.int64, copy=False) + + raise ValueError("mode must be 'value' or 'percentile'") diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/gated_gelu.py b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/gated_gelu.py new file mode 100644 index 0000000000000000000000000000000000000000..73b1ca790df94c1fcbfa7d45d377ae891fe17839 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/repo/gated_gelu.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +def gated_gelu(x: torch.Tensor, approximate: str = "none") -> torch.Tensor: + """Apply a gated GELU activation over the last dimension. + + The input's last dimension is split in half. GELU is applied to the first + half and multiplied by the second half. This straightforward implementation + intentionally relies on ordinary PyTorch tensor operations. + """ + if approximate not in ("none", "tanh"): + raise ValueError("approximate must be 'none' or 'tanh'") + if not x.is_cuda: + raise ValueError("x must be a CUDA tensor") + if x.dim() < 1: + raise ValueError("x must have at least one dimension") + if x.shape[-1] % 2 != 0: + raise ValueError("last dimension must be even") + d = x.shape[-1] // 2 + return F.gelu(x[..., :d], approximate=approximate) * x[..., d:] diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/entrypoint.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ad0137c7a85f94eeb880a755d3730bfbebf1e3a --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/entrypoint.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +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 + +if [ -x /app/timer.sh ]; then + /app/timer.sh >/app/.timer/timer.log 2>&1 & +fi + +if [ "$#" -gt 0 ]; then + exec "$@" +fi + +exec /bin/bash -l diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/run_dev_bench.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/run_dev_bench.sh new file mode 100644 index 0000000000000000000000000000000000000000..d627a61218d501ea69bdc3323afeb5284accd071 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/run_dev_bench.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +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 +KERNELBENCH_VERIFY_MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" bash /tests/test.sh diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/timer.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/timer.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3e45be674fb4a8218ca84d9cb4dc0f451395652 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/environment/runtime/timer.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +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 +mkdir -p /app/.timer +date -u +%FT%TZ > /app/.timer/start.txt +remaining=${FRONTIER_REMAINING_SECS:-21600} +printf '%s\n' "$remaining" > /app/.timer/remaining_secs +printf '%s\n' "$remaining" > /app/.timer/budget_secs +printf '%s\n' "$$" > /app/.timer/timer.pid +while true; do + sleep 60 +done diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/instruction.md b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8e00dfd1d9a6134cf7cbe8dadeaf7449b86bdec --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/instruction.md @@ -0,0 +1,98 @@ +# Performance Optimization Task + +## Scope + +You may modify **only** this file: + +``` +curriculum_cluster.py +``` + +Everything else is **out of scope**. Any change to a file outside the scope above +causes the submission to score zero. Find where the slowness is *inside the scope* +by reading and profiling the code — that is part of the task. + +## Objective + +`curriculum_cluster.py` implements **curriculum-learning difficulty-cluster +selection**, the step that stabilises very-large-scale pretraining by feeding +samples in an easy-to-hard order. Samples are pre-bucketed by a difficulty *metric* +into per-difficulty rows (`index_to_sample[r]` is the array of sample-ids whose +metric value is `index_to_metric[r]`, rows sorted easy→hard). At each curriculum +step the trainer selects the flat set of sample-ids that fall inside a difficulty +window, in one of two modes: + +- **VALUE**: every row whose metric value is in `(lo, hi]`; +- **PERCENTILE**: the contiguous slice of samples covering the population fraction in + `[lo, hi)` of `num_bins` equal-count percentile bands, where the two boundary rows + are sliced **partially** (a running-count walk takes whole interior rows and the + correct partial prefix/suffix of the two edge rows), stopping once the end count is + reached. + +The current implementation is **functionally correct but slow**: it walks the rows +in a Python loop and grows the result with a fresh `numpy.concatenate` on every +matching row (each append re-copies the entire running buffer, so the row walk is +quadratic in the number of selected rows), and it re-sums the one-epoch population +from scratch. + +Your job: **make `select_curriculum_cluster` faster on the benchmark workload while +returning exactly the same selected sample-ids.** You may reorganize the logic +within the scope file however you like (e.g. a cumulative row-size prefix plus a +boundary search to locate the two edge rows, then a single concatenation of the +interior rows and the two partial edge slices), as long as the observable output +below is preserved. + +## Behavioral contract (what the grader checks) + +The grader calls the public entry point: + +```python +select_curriculum_cluster(index_to_sample, index_to_metric, mode, lo, hi, num_bins=None) -> numpy.ndarray +``` + +- `index_to_sample`: list of 1-D `numpy` int arrays; `index_to_sample[r]` holds the + sample-ids at difficulty-row `r`; +- `index_to_metric`: 1-D `numpy` array; `index_to_metric[r]` is the metric value of + row `r` (non-decreasing in `r`); +- `mode`: `"value"` or `"percentile"`; +- `lo`, `hi`: window bounds — VALUE: exclusive-lower / inclusive-upper metric bounds; + PERCENTILE: inclusive-start / exclusive-end percentile-band indices in + `[0, num_bins]` (when `hi == num_bins` the band extends to the exact end of the + population); +- `num_bins`: number of equal-count percentile bands (PERCENTILE mode only). + +The returned 1-D `numpy` int array must equal, **element-for-element and in the same +order** (row-then-within-row), the independent reference the grader computes for both +modes. In PERCENTILE mode the two boundary rows must be sliced at the exact +running-count offsets — a whole-row shortcut that ignores the partial edges selects +the wrong sample-ids and scores zero. The public signature must remain unchanged. + +The reward increases as the wall-clock time of `select_curriculum_cluster` decreases +on the benchmark workload, subject to the correctness requirement above. A correct +submission that changes nothing scores about 1.0. + +## Notes + +- The workload runs on CPU; no GPU is required. Only `numpy` and the Python + standard library are available. +- Determinism: given the same inputs, your implementation must produce the same + output on every run. + +## Solve independently — prohibited actions (any one ⇒ the whole task scores 0) + +- Reading, printing, copying, `cat`/`grep`/`find`-ing, editing, or reproducing ANY + verifier / scoring / hidden-test / golden file, wherever it lives; or inferring + hidden inputs/thresholds. +- Downloading or cloning the upstream project or looking up its reference + implementation in ANY form — `git clone`/`fetch`/`pull`, adding a git remote, + `pip download`/`pip install` of the same package, `wget`/`curl` of upstream files, + checking out a different commit, or web lookup — whether the network appears to work + or not. +- Bypassing or disabling the network isolation (unsetting/overriding + `http_proxy`/`https_proxy`/`all_proxy`, opening raw sockets, or any other + circumvention). + +## 提交方式 + +本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。 +改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。 diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/pre_artifacts.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb7bb5a66060c3f933d4e5980f0419e673ceb2a4 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/pre_artifacts.sh @@ -0,0 +1,163 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/wro-deepspeed-curriculum-cluster-select-loop16 +# +# Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE +# grading (spec §1.1). It turns whatever the agent left behind into a portable artifact: +# +# /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit +# /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line +# +# 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one +# place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs ..HEAD). +# Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate, +# `git checkout -q HEAD -- ` re-materialises the baseline for the paired timing, +# and loop16's `submit.sh --finalize` plants the best iterate with read-tree + +# checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope +# gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the +# "baseline" — and a correct solve scores 0. +# `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages +# names only, writes no tree, creates no commit and leaves HEAD exactly where it was. +# +# EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier +# scores the container on its own terms and gives 0 by itself. +# +# READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index +# (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the +# verifier — which runs after us — sees exactly the `git status --porcelain` it would have +# seen if this script had never run. No commit, no HEAD move, no working-tree write. +# +# CAPTURE ROOTS for THIS task — derived from the package, never assumed: +# /app/repo git repo, HEAD == the 1-commit carved baseline +# evidence Dockerfile:124: WORKDIR /app/repo +# evidence Dockerfile:77: && cd /app/repo \ +# evidence Dockerfile:84: && test "$(git rev-list --count HEAD)" = "1" \ +# evidence test.sh:16: export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +# evidence test.sh:19: REPO=/app/repo +# +# Single root => model.patch is a bare `git diff --binary ` (no banner). +# model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable +# by one reader. +# +# loop16 task (environment/loop/ -> /opt/loop in the image): the harness auto-finalizes +# at k=16 and `submit.sh --finalize` plants the best iterate in the WORKING TREE while +# HEAD stays on the baked baseline — which is exactly what this script captures. Running +# it after a finalize therefore yields the GRADED artifact, not the last raw edit. +# ============================================================================ +set -uo pipefail + +OUT=/logs/artifacts +PATCH="$OUT/model.patch" +LIST="$OUT/model_files.txt" +MULTI=0 # 1 => several capture roots => each diff gets a banner line +MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane) + +mkdir -p "$OUT" 2>/dev/null || true +: > "$PATCH" 2>/dev/null || true +: > "$LIST" 2>/dev/null || true +git config --global --add safe.directory '*' >/dev/null 2>&1 || true + +banner() { # $1=root $2=mode ; only when there is more than one root + if [ "$MULTI" = 1 ]; then + printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null + fi + return 0 +} + +list_add() { # stdin: paths relative to $1 -> absolute, one per line + sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true + return 0 +} + +capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot" + capture_tree "$root" + return 0 + fi + # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and + # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could + # flip a scope gate either way. So copy the repo's index aside and stage into the COPY — + # the repo's own .git/index is byte-identical when we are done. + tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi="" + gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true) + if [ -z "$gd" ]; then + gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true) + case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac + fi + if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then + GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE + else + echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index" + fi + git -C "$root" add -AN . >/dev/null 2>&1 || true + base=HEAD + if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then + base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null) + echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree" + else + n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0) + case "$n" in ''|*[!0-9]*) n=0 ;; esac + if [ "$n" -gt 1 ]; then + base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1) + echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:" + echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so" + echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved" + echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve." + fi + fi + [ -n "${base:-}" ] || base=HEAD + banner "$root" "git-diff-vs-baseline" + git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true + names=$(git -C "$root" diff --name-only "$base" 2>/dev/null) + echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)" + unset GIT_INDEX_FILE + [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null + printf '%s\n' "$names" | grep -v '^$' | list_add "$root" + return 0 +} + +capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0 + if git init -q "$tmp/snap" >/dev/null 2>&1; then + GD="$tmp/snap/.git" + empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null) + ( cd "$root" 2>/dev/null || exit 0 + find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \ + 2>/dev/null \ + | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true + banner "$root" "tree-snapshot-not-a-git-repo" + GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \ + >> "$PATCH" 2>/dev/null || true + else + echo "[pre_artifacts] WARN could not stage a snapshot index for $root" + fi + rm -rf "$tmp" 2>/dev/null || true + all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f -print 2>/dev/null | sed 's|^\./||' ) + printf '%s\n' "$all" | grep -v '^$' | list_add "$root" + big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \ + -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . ) + echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)" + if [ "${big:-0}" != 0 ]; then + echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in" + echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch." + fi + return 0 +} + +capture_git "/app/repo" +bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0) +case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac +echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)" +if [ "$bytes" -gt 67108864 ]; then + echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build" + echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also" + echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish." +fi +exit 0 diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/README.md b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..624bfc07273df454ac57ac5c3a8e21bd8bab388d --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/README.md @@ -0,0 +1,17 @@ +# solution/ — 参考实现(不参与判分) + +本目录里的补丁**不进镜像**(已被上下文根的 `.dockerignore` 排除)、**判分不运行**, +只在两种场合用: + +1. **重标定锚点**(换硬件后):见 `../tests/ref_speedup.caveat.md` + ``` + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch + ``` +2. **自证起始树**:`git apply --check -p1 oracle.patch` 必须能干净打在 + `../environment/repo/` 上(正向可、反向不可)。这证明 `../environment/repo/` 就是 + 被计分的、**已被降级的起始实现**,而 oracle 补丁正是把它恢复成参考实现的那一步。 + +| 文件 | 用途 | +|---|---| +| `negative.patch` | 已知坏例,**必须得 0** | +| `oracle.patch` | oracle 参考实现补丁,用于标定锚点(打平锚点 = reward 0.5) | diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/negative.patch b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/negative.patch new file mode 100644 index 0000000000000000000000000000000000000000..867201a7e38bc1b873a1131b2fdea0482174a20e --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/negative.patch @@ -0,0 +1,136 @@ +--- a/curriculum_cluster.py ++++ b/curriculum_cluster.py +@@ -1,30 +1,12 @@ + """Curriculum-learning difficulty-cluster selection for large-scale training stability. + +-DeepSpeed's data-efficiency curriculum learning stabilises very-large-scale +-pretraining by feeding samples in an easy-to-hard order: samples are pre-bucketed +-by a difficulty *metric* into per-difficulty-value rows (``index_to_sample[v]`` = +-the array of sample-ids whose metric value is ``index_to_metric[v]``), sorted by +-increasing difficulty. At each curriculum step the trainer selects the flat set of +-sample-ids that fall inside a difficulty window, either +- +- * VALUE-based: every row whose metric value is in ``(value_start, value_end]``, or +- * PERCENTILE-based: the contiguous slice of samples covering the fraction of the +- one-epoch population in ``[pct_start, pct_end)`` of ``num_bins`` +- equal-count percentile bands (with a running-count walk that +- slices the two boundary rows partially and takes whole interior +- rows, stopping once the end count is reached). +- +-``select_curriculum_cluster`` returns the concatenated 1-D int array of selected +-sample-ids (in row-then-within-row order). This is the functionally-correct but slow +-reference: it walks the rows in a Python loop and grows the result with a fresh +-``numpy.concatenate`` per matching row (each append re-copies the whole running +-buffer, so the row walk is quadratic in the number of selected rows) and re-sums the +-one-epoch population from scratch. The public signature and the returned array are +-the behavioural contract. +- +-Mirrors DeepSpeed ``deepspeed/runtime/data_pipeline/data_sampling/data_sampler.py`` +-``DeepSpeedDataSampler.get_sample_based_on_metric_value`` / +-``get_sample_based_on_metric_percentile`` (Apache-2.0). ++Speed hack that changes results: in PERCENTILE mode it skips the running-count ++boundary bookkeeping and instead takes WHOLE rows whose cumulative midpoint falls in ++the window, so the two boundary rows are never partially sliced. Faster, but the ++returned sample-id set no longer matches the reference (it over- or under-selects the ++exact count at the two window edges). VALUE mode keeps the correct masked selection. ++ ++Mirrors DeepSpeed data_sampler.py curriculum selection (Apache-2.0). + """ + + import numpy as np +@@ -38,75 +20,35 @@ + hi, + num_bins=None, + ): +- """Select the flat cluster of sample-ids for one curriculum difficulty window. +- +- :param index_to_sample: list of 1-D numpy int arrays; ``index_to_sample[r]`` holds +- the sample-ids bucketed at difficulty-row ``r`` (rows sorted easy->hard). +- :param index_to_metric: 1-D numpy array; ``index_to_metric[r]`` is the difficulty +- metric value of row ``r`` (non-decreasing in ``r``). +- :param mode: ``"value"`` or ``"percentile"``. +- :param lo: window lower bound. VALUE mode: exclusive metric lower bound +- (``value_start``). PERCENTILE mode: inclusive percentile-band start +- (``pct_start``, an int in ``[0, num_bins]``). +- :param hi: window upper bound. VALUE mode: inclusive metric upper bound +- (``value_end``). PERCENTILE mode: exclusive percentile-band end +- (``pct_end``, an int in ``[0, num_bins]``); when ``hi == num_bins`` the band +- extends to the exact end of the population. +- :param num_bins: number of equal-count percentile bands (PERCENTILE mode only). +- :returns: 1-D numpy int64 array of the selected sample-ids (row-then-within-row +- order), or an empty int64 array when nothing is selected. +- """ ++ """Build the curriculum cluster (wrong at the partial boundary rows in pct mode).""" + metric = np.asarray(index_to_metric) + n_rows = len(index_to_sample) + + if mode == "value": +- # NAIVE_VALUE_ROWWALK: Python loop, re-copy+concat the running buffer per hit. +- new_samples = None +- for row in range(n_rows): +- if metric[row] <= hi and metric[row] > lo: +- row_samples = np.copy(np.asarray(index_to_sample[row])) +- new_samples = ( +- row_samples +- if new_samples is None +- else np.concatenate((new_samples, row_samples), axis=None) +- ) +- if new_samples is None: ++ sel = np.flatnonzero((metric <= hi) & (metric > lo)) ++ if sel.size == 0: + return np.array([], dtype=np.int64) +- return new_samples.astype(np.int64, copy=False) ++ parts = [np.asarray(index_to_sample[r]) for r in sel.tolist()] ++ return np.concatenate(parts, axis=None).astype(np.int64, copy=False) + + if mode == "percentile": +- # NAIVE_PERCENTILE_ROWWALK: re-sum the epoch population, then a running-count +- # walk that partially slices the two boundary rows and re-copies+concats each. +- one_epoch_size = 0 +- for row in range(n_rows): +- one_epoch_size += len(index_to_sample[row]) ++ row_sizes = np.fromiter( ++ (len(index_to_sample[r]) for r in range(n_rows)), dtype=np.int64, count=n_rows ++ ) ++ one_epoch_size = int(row_sizes.sum()) + sample_per_pct = one_epoch_size // num_bins + start_count = sample_per_pct * lo +- end_count = sample_per_pct * hi +- if hi == num_bins: +- end_count = one_epoch_size +- +- new_samples = None +- current_count = 0 +- for row in range(n_rows): +- row_size = len(index_to_sample[row]) +- if current_count + row_size > start_count: +- row_start = max(0, start_count - current_count) +- if current_count + row_size <= end_count: +- row_end = row_size +- else: +- row_end = end_count - current_count +- row_samples = np.copy(np.asarray(index_to_sample[row])[row_start:row_end]) +- new_samples = ( +- row_samples +- if new_samples is None +- else np.concatenate((new_samples, row_samples), axis=None) +- ) +- current_count += row_size +- if current_count >= end_count: +- break +- if new_samples is None: ++ end_count = one_epoch_size if hi == num_bins else sample_per_pct * hi ++ if end_count <= start_count or one_epoch_size == 0: ++ return np.array([], dtype=np.int64) ++ cum_after = np.cumsum(row_sizes) ++ cum_before = cum_after - row_sizes ++ # WRONG: select whole rows whose MIDPOINT is inside the window (no partial slice). ++ mid = cum_before + row_sizes / 2.0 ++ sel = np.flatnonzero((mid >= start_count) & (mid < end_count)) ++ if sel.size == 0: + return np.array([], dtype=np.int64) +- return new_samples.astype(np.int64, copy=False) ++ parts = [np.asarray(index_to_sample[r]) for r in sel.tolist()] ++ return np.concatenate(parts, axis=None).astype(np.int64, copy=False) + + raise ValueError("mode must be 'value' or 'percentile'") diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/oracle.patch b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bfeff16cdecfead18a5411fa40b2d953c8d60449 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/oracle.patch @@ -0,0 +1,107 @@ +--- a/curriculum_cluster.py ++++ b/curriculum_cluster.py +@@ -15,12 +15,12 @@ + rows, stopping once the end count is reached). + + ``select_curriculum_cluster`` returns the concatenated 1-D int array of selected +-sample-ids (in row-then-within-row order). This is the functionally-correct but slow +-reference: it walks the rows in a Python loop and grows the result with a fresh +-``numpy.concatenate`` per matching row (each append re-copies the whole running +-buffer, so the row walk is quadratic in the number of selected rows) and re-sums the +-one-epoch population from scratch. The public signature and the returned array are +-the behavioural contract. ++sample-ids (in row-then-within-row order). This optimized implementation replaces ++the per-row Python concatenate walk with vectorized row selection: VALUE mode masks ++the qualifying rows and concatenates them once; PERCENTILE mode locates the two ++boundary rows with a cumulative-count prefix + boundary search and concatenates the ++whole interior rows plus the two partial edge slices in a single pass. The returned ++array is byte-identical to the reference. + + Mirrors DeepSpeed ``deepspeed/runtime/data_pipeline/data_sampling/data_sampler.py`` + ``DeepSpeedDataSampler.get_sample_based_on_metric_value`` / +@@ -60,53 +60,43 @@ + n_rows = len(index_to_sample) + + if mode == "value": +- # NAIVE_VALUE_ROWWALK: Python loop, re-copy+concat the running buffer per hit. +- new_samples = None +- for row in range(n_rows): +- if metric[row] <= hi and metric[row] > lo: +- row_samples = np.copy(np.asarray(index_to_sample[row])) +- new_samples = ( +- row_samples +- if new_samples is None +- else np.concatenate((new_samples, row_samples), axis=None) +- ) +- if new_samples is None: ++ # Vectorized row mask: (lo, hi], then one concatenate of the selected rows. ++ sel = np.flatnonzero((metric <= hi) & (metric > lo)) ++ if sel.size == 0: + return np.array([], dtype=np.int64) +- return new_samples.astype(np.int64, copy=False) ++ parts = [np.asarray(index_to_sample[r]) for r in sel.tolist()] ++ return np.concatenate(parts, axis=None).astype(np.int64, copy=False) + + if mode == "percentile": +- # NAIVE_PERCENTILE_ROWWALK: re-sum the epoch population, then a running-count +- # walk that partially slices the two boundary rows and re-copies+concats each. +- one_epoch_size = 0 +- for row in range(n_rows): +- one_epoch_size += len(index_to_sample[row]) ++ # Row-size cumulative prefix; the count window is [start_count, end_count). ++ row_sizes = np.fromiter( ++ (len(index_to_sample[r]) for r in range(n_rows)), dtype=np.int64, count=n_rows ++ ) ++ one_epoch_size = int(row_sizes.sum()) + sample_per_pct = one_epoch_size // num_bins + start_count = sample_per_pct * lo +- end_count = sample_per_pct * hi +- if hi == num_bins: +- end_count = one_epoch_size +- +- new_samples = None +- current_count = 0 +- for row in range(n_rows): +- row_size = len(index_to_sample[row]) +- if current_count + row_size > start_count: +- row_start = max(0, start_count - current_count) +- if current_count + row_size <= end_count: +- row_end = row_size +- else: +- row_end = end_count - current_count +- row_samples = np.copy(np.asarray(index_to_sample[row])[row_start:row_end]) +- new_samples = ( +- row_samples +- if new_samples is None +- else np.concatenate((new_samples, row_samples), axis=None) +- ) +- current_count += row_size +- if current_count >= end_count: +- break +- if new_samples is None: ++ end_count = one_epoch_size if hi == num_bins else sample_per_pct * hi ++ if end_count <= start_count or one_epoch_size == 0: + return np.array([], dtype=np.int64) +- return new_samples.astype(np.int64, copy=False) ++ ++ # Cumulative start offset of each row: cum_before[r] = sum(row_sizes[:r]). ++ cum_after = np.cumsum(row_sizes) # count after including row r ++ cum_before = cum_after - row_sizes # count before row r ++ # A row contributes iff cum_after[r] > start_count and cum_before[r] < end_count. ++ first = int(np.searchsorted(cum_after, start_count, side="right")) ++ last = int(np.searchsorted(cum_before, end_count, side="left")) - 1 ++ if first > last: ++ return np.array([], dtype=np.int64) ++ ++ parts = [] ++ for row in range(first, last + 1): ++ cb = int(cum_before[row]) ++ row_size = int(row_sizes[row]) ++ row_start = max(0, start_count - cb) ++ row_end = row_size if cb + row_size <= end_count else end_count - cb ++ parts.append(np.asarray(index_to_sample[row])[row_start:row_end]) ++ if not parts: ++ return np.array([], dtype=np.int64) ++ return np.concatenate(parts, axis=None).astype(np.int64, copy=False) + + raise ValueError("mode must be 'value' or 'percentile'") diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/solve.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..823ab44a82ff766dec89bb0c9d1ad5d96cc48727 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/solution/solve.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/wro-deepspeed-curriculum-cluster-select-loop16 +# 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量 +# 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。 +# +# oracle 形态 : 补丁式(patch)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_PATCH 槽位: +# git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" +# 产物(reviewer-only;本脚本只读,一个字节都不改): +# solution/negative.patch, solution/oracle.patch +# $REPO : /app/repo (tests/test.sh: REPO=/app/repo) +# 被计分单元 : /app/repo/curriculum_cluster.py +# 来源:tests/test.sh 的 SCOPE=("curriculum_cluster.py") +# 落地方式 : git -C $REPO apply -p1 —— 只改工作树,不 commit +# +# 🔴 为什么绝不 commit(规范 H3):判分读**工作树** —— `git status --porcelain` 是 scope +# 硬闸门,`git checkout -q HEAD -- ` 取基线,且镜像自证 /app/repo 的 HEAD 恰好 +# 只有 1 个 commit(那就是挖洞基线)。一旦 commit,HEAD 前移 → 闸门看不到改动、 +# `checkout HEAD -- scope` 把 candidate 当成基线 → 正确解被判 0。 +# 本脚本落地后会自己断言 HEAD 与 commit 数没变。 +# +# ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)──────────────────────── +# PKG=/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task +# IMG=fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss +# # 1) 起容器。判分容器始终 --network=none;tests/ 和 solution/ 都**没有**烤进镜像 +# # (Dockerfile 里没有一条 COPY 取它们),所以这两个目录必须挂进来。 +# # 该题 task.toml 声明 gpus=0;锚点的标定硬件/运行栈见 tests/ref_speedup.caveat.md +# docker run -d --name kfc-solve --network=none \ +# -v "$PKG/tests":/tests -v "$PKG/solution":/solution "$IMG" +# # 2) 落地参考实现到工作树(本脚本;不 commit) +# docker exec kfc-solve bash /solution/solve.sh +# # 3) 判分。KERNELBENCH_VERIFY_MODE 必须留在默认的 candidate —— 这就是 agent 的 +# # 真实评分路径;设成 oracle/negative 会让 test.sh 自己再落地一遍,绕过本脚本。 +# docker exec -e KERNELBENCH_VERIFY_MODE=candidate kfc-solve bash /tests/test.sh +# docker exec kfc-solve cat /logs/verifier/reward.json # 判分结果 +# docker rm -f kfc-solve +# +# 期望:oracle → 性能题得 0(它就是锚点本身; min(1, ln(speedup/ref_speedup)/ln(ref_speedup))(speedup ≤ ref_speedup 时为 0) +# 在 speedup≈ref_speedup 处 = 0 —— 打平 oracle 不得分,必须超过。 +# 所以"oracle 跑对了"的判据不是 reward>0,而是 speedup≈ref_speedup 且 +# hard_fail_reasons 为空;实现类二值题 = 1.0 —— 权威公式是 +# tests/test.sh 写出的 reward_formula 字段);--negative → 0; +# --noop(在纯净容器里)→ 0(挖洞基线过不了正确性门)。 +# 本题带 loop16 harness:`bash /opt/loop/submit.sh` 判的也是同一棵工作树、 +# 同样走 candidate 模式(口径一致),所以落地后直接自评也成立。 +# ────────────────────────────────────────────────────────────────────────── +# +# 用法(规范 2 的统一 CLI): +# bash solution/solve.sh # 落地 oracle(参考实现) +# bash solution/solve.sh --negative # 落地 negative(已知坏例,必须得 0) +# bash solution/solve.sh --baseline2 # 落地 baseline2(中间基线) +# bash solution/solve.sh --noop # 把可编辑面复位到烤入基线(对照组) +# +# --noop 语义:把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— +# `git checkout HEAD -- `,HEAD 不动),使对照组能量到真正的 no-op 值。 +# runner 在同一个容器里连着跑 oracle → noop 做对照时,靠它把上一轮落地归零。 +# +# 幂等:每次落地前先把被计分单元 `git checkout HEAD --` 复位,重复执行结果一致。 +# 失败一律非 0 退出并打印原因(补丁打不上 / 变体文件缺失 / scope 路径不存在 / HEAD 被移动)。 +set -uo pipefail + +TASK_ID="wro-deepspeed-curriculum-cluster-select-loop16" +REPO="${KFC_REPO_DIR:-/app/repo}" +SCOPE=("curriculum_cluster.py") +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; } +die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; } +# 每次调用单独带 safe.directory,不去改容器里的全局 gitconfig +GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; } + +usage(){ cat <<'USAGE' +usage: bash solve.sh [--oracle | --negative | --noop] + (无参数) 落地 oracle 参考实现(oracle.patch) + --negative 落地 negative 已知坏例(negative.patch) + --noop 把可编辑面复位到烤入基线(与 verifier 取基线一致,HEAD 不动) +USAGE +} + +WHICH=oracle +case "${1:-}" in + ""|--oracle) WHICH=oracle ;; + --negative) WHICH=negative ;; + --baseline2) WHICH=baseline2 ;; + --noop) WHICH=noop ;; + -h|--help) usage; exit 0 ;; + *) usage >&2; die "未知参数 '$1'" ;; +esac + +# ---- 产物定位:脚本同目录优先,其次容器里的常见挂载点 ---- +artifact(){ + local n="$1" c + for c in "$HERE/$n" "/solution/$n" "${KFC_SOLUTION_DIR:-/nonexistent}/$n"; do + [ -f "$c" ] && { printf '%s\n' "$c"; return 0; } + done + return 1 +} + +case "$WHICH" in + noop) ART="" ;; + oracle) ART="oracle.patch" ;; + negative) ART="negative.patch" ;; + *) die "本题没有 $WHICH 变体(solution/ 里只有:oracle.patch, negative.patch)" ;; +esac + +# ---- 环境前置检查 ---- +GIT rev-parse --git-dir >/dev/null 2>&1 \ + || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)" +for s in "${SCOPE[@]}"; do + [ -e "$REPO/$s" ] || die "被计分单元不存在:$REPO/$s(REPO 不对?可用 KFC_REPO_DIR 覆盖)" +done +HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD" +N_BEFORE="$(GIT rev-list --count HEAD)" + +if [ "$WHICH" = noop ]; then + # --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— `git checkout HEAD -- `, + # HEAD 不动),使对照组能量到真正的 no-op 值。runner 在同一个容器里连着跑 oracle → noop 时靠它归零。 + DIRTY_BEFORE="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" + DIRTY_AFTER="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + if [ -n "$DIRTY_AFTER" ]; then + printf '%s\n' "$DIRTY_AFTER" | sed "s|^|[solve.sh $TASK_ID] |" >&2 + die "复位后被计分单元仍不干净(见上)—— 量不到真正的 no-op 值" + fi + [ "$HEAD_BEFORE" = "$(GIT rev-parse HEAD)" ] || die "HEAD 被移动了,判分会把 candidate 当基线" + [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + if [ -n "$DIRTY_BEFORE" ]; then + say "--noop:已把可编辑面复位到烤入基线;原先这些是脏的:" + printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |" + else + say "--noop:可编辑面本来就是干净的烤入基线,无需复位" + fi + say "--noop 完成:${SCOPE[*]} = 烤入基线(HEAD 未动 @ ${HEAD_BEFORE:0:12})" + exit 0 +fi + +PATCH="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)" + +# ---- 幂等:先把被计分单元退回挖洞基线,再打补丁(否则二次 apply 必然失败) ---- +GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" +GIT apply -p1 --check "$PATCH" \ + || die "补丁打不上:$PATCH —— 挖洞树与该补丁不匹配,或工作树被别的改动污染了" +GIT apply -p1 "$PATCH" || die "git apply 失败:$PATCH" + +# ---- 硬要求:HEAD 一步都不能动(规范 H3) ---- +HEAD_AFTER="$(GIT rev-parse HEAD)" +[ "$HEAD_BEFORE" = "$HEAD_AFTER" ] || die "HEAD 被移动了($HEAD_BEFORE -> $HEAD_AFTER),判分会把 candidate 当基线" +[ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + +say "已落地 $WHICH:$(basename "$PATCH") -> ${SCOPE[*]}(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})" +GIT status --porcelain -- "${SCOPE[@]}" | sed "s|^|[solve.sh $TASK_ID] |" + +# ---- 顺手体检 scope 闸门:工作树里除了被计分单元不该有别的改动 ---- +STRAY="$(GIT status --porcelain | awk '{print $NF}' \ + | grep -v -e '__pycache__' -e '\.pyc$' -e '^curriculum_cluster\.py$' || true)" +[ -z "$STRAY" ] || { say "⚠ 工作树里还有 scope 外的改动,判分会 out_of_scope_edit 直接归 0:"; \ + printf '%s\n' "$STRAY" | sed "s|^|[solve.sh $TASK_ID] |"; } +exit 0 diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/task.toml b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0c42fbf0f0b9269e8895b582cec5a06a8947ca18 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/task.toml @@ -0,0 +1,49 @@ +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "wro-deepspeed-curriculum-cluster-select-loop16" +bench = "kfc" +kind = "performance" +language = "python" +title = "curriculum_cluster.py implements curriculum-learning difficulty-cluster selection …" +instruction = "instruction.md" + +[agent] +timeout_sec = 5400 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/wro-deepspeed-curriculum-cluster-select-loop16:v1@sha256:a544e9d3a324523f6d852c174c92b6ae1ebe40c5accb62e0bdab1658c3ae3603 +# Open-source build: `cd && docker build -f environment/Dockerfile -t fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss .` +[environment] +docker_image = "fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss" +dockerfile = "environment/Dockerfile" +build_timeout_sec = 3600 +cpus = 8 +memory_mb = 32768 +gpus = 0 +allow_internet = false + +[verifier] +entrypoint = "tests/test.sh" +mode = "shared" +timing_metric = "speedup" +primary_edit_paths = ["curriculum_cluster.py"] +result_paths = ["/logs/verifier/reward.json"] + +[primary_metric] +name = "speedup" +goal = "maximize" +ref_speedup = 20.777027 +ref_speedup_source = "tests/ref_speedup.txt" +calibrated_on = "Intel Sapphire Rapids CPU lane" + +[loop] +# NOTE: the /opt/loop harness baked into the image applies its own 3/16 in-session budget; for in-session loop scoring the image is authoritative. +min_submissions = 1 +max_submissions = 1 +submit = "bash /opt/loop/submit.sh" +# Single-submission policy — min=max=1; the first +# `bash /opt/loop/submit.sh` IS the final graded submission (submit == finalize). +declared_submission_policy = "single_submission" diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/compute_reward.py b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..24f19875ab177f061fa1e200afc0eee45e937e9a --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/compute_reward.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""compute_reward for wro-deepspeed-curriculum-cluster-select. + +Reward (performance class): + + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 strictly in [0.0, 1.0] + +with speedup = baseline_ms / candidate_ms. Matching the oracle (speedup == +ref_speedup) scores 0.5; reaching ref_speedup**2 caps at 1.0. + +HARD PRE-GATES (any one hit => reward 0.0, the formula is never evaluated): +build/import failure, ANY correctness case fail, cheating, a forbidden edit path, +speedup <= 1, ref_speedup <= 1. The build/import/correctness/anti-cheat/scope +gates are enforced upstream in test.sh (which also computes the authoritative +verdict); this script reproduces the same formula for standalone/offline use and +re-checks the two numeric pre-gates itself. +""" +import json +import math +import sys + +TOKEN = "WRO_CURRIC_RESULT " + + +def load(path): + for line in open(path): + if line.startswith(TOKEN): + return json.loads(line[len(TOKEN):]) + raise SystemExit(f"no WRO_CURRIC_RESULT in {path}") + + +def main(): + # argv: candidate_out baseline_out [ref_speedup] + cand = load(sys.argv[1]) + base = load(sys.argv[2]) + ref = float(sys.argv[3]) if len(sys.argv) > 3 else None + cm = cand.get("timing_ms", -1) + bm = base.get("timing_ms", -1) + hard = [] + speedup = (bm / cm) if (cm and cm > 0 and bm and bm > 0) else 0.0 + if not (math.isfinite(speedup) and speedup > 0.0): + hard.append("timing_invalid") + elif speedup <= 1.0: + hard.append("speedup_not_above_baseline") + if ref is None or not (math.isfinite(ref) and ref > 1.0): + hard.append("ref_speedup_invalid") + + if hard: + reward = 0.0 + else: + reward = max(0.0, min(1.0, max(0.0, min(1.0, math.log(speedup) / math.log(ref) - 1.0)))) + + out = { + "task_type": "performance", + "reward": round(reward, 6), + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; 0 if any hard pre-gate hit", + "hard_fail_reasons": hard, + "speedup": round(speedup, 6), + "ref_speedup": ref, + "cv": None, + "baseline_ms": bm, + "candidate_ms": cm, + } + print(json.dumps(out)) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/ref_speedup.caveat.md b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..0f56ab9640daa27964a63cfa7689ee088a96ebe1 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +`ref_speedup.txt` 里的 **20.777027** 是 oracle 标定常量,判分时只读、不重跑 oracle: + + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + +`tests/test.sh` 的解析顺序是 **`tests/ref_speedup.txt` → `/opt/verifier-correctness-manifest.json` → 1.0**; +回落到 1.0 会让所有 reward 归 0,所以这个文件必须存在且 > 1。 + +## 标定条件 + +- 硬件:**the authoring CPU lane (Intel Sapphire Rapids)** +- 运行栈:`torch 2.7.0`(原始私有基座声明 torch 2.5.1/triton 3.1.0,任务 overlay 又 `pip install torch==2.7.0`,锚点即在 2.7.0 下标定) +- 线程:`OMP/MKL/OPENBLAS_NUM_THREADS=1`(计时稳定性的一部分,已写进镜像 ENV) + +## 硬件不一致时如何重标 + +verifier 原生支持模式分派,参考实现**按路径传入、从不烤进镜像**: + +```bash +docker run --rm -v "$PWD/tests:/tests:ro" -v "<放 oracle.patch 的目录>:/patches:ro" \ + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ + fai/kfc-wro-deepspeed-curriculum-cluster-select-loop16:oss bash /tests/test.sh +# 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt +``` + +自证:`noop`(不打补丁)应 ≈1.0 → 被门到 0;`negative`(`KERNELBENCH_NEGATIVE_PATCH=`)必须 0。 + +✅ 本题**随包提供**参考实现 `solution/oracle.patch`,所以重标定通路是**可直接执行**的。 diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/ref_speedup.txt b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..8074166e426a9d855cc271dcb1420fdba150d94c --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/ref_speedup.txt @@ -0,0 +1 @@ +20.777027 diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/test.sh b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..278d414351ff6e04e5f14f79a4cc83b5100345bd --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/test.sh @@ -0,0 +1,155 @@ +#!/usr/bin/env bash +# Verifier for wro-deepspeed-curriculum-cluster-select (curriculum-learning +# difficulty-cluster selection for large-scale training stability). +# ACCELERATION, CPU (host logic; no GPU). +# Scope = curriculum_cluster.py (select_curriculum_cluster). +# Modes: candidate | noop | oracle | negative | baseline2. +# reward: +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0, speedup = base_ms/cand_ms (raw wall). +# An oracle-grade candidate scores 0.5; noop (speedup ~ 1.0, degraded vs itself) hits the +# speedup<=1 pre-gate -> 0. The 4-mode speedups quoted below are RAW ratios, pre-formula: +# oracle >> 1 (vectorized boundary-search selection vs O(rows^2) per-row Python +# concatenate); baseline2 in between (block-buffered concat, still row-walked); +# negative = 0 (whole-row shortcut mis-selects the partial boundary rows). +set -uo pipefail +export PATH="/opt/kernelbench-venv/bin:/opt/venv/bin:/usr/local/bin:$PATH" +export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +git config --global --add safe.directory '*' 2>/dev/null || true +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/verifier; mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +SCOPE=("curriculum_cluster.py") + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true +speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1 + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +# ---- apply oracle / baseline2 / negative patch by mode (candidate & noop: no patch) ---- +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"; fi +if [ "$MODE" = "baseline2" ] && [ -n "${KERNELBENCH_BASELINE2_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_BASELINE2_PATCH" 2>"$LOG/baseline2_apply.log" || add_hard "baseline2_apply_failed"; fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true; fi + +# ---- (1) scope-diff HARD GATE: only the scope file may change in /app/repo ---- +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + keep=false + for s in "${SCOPE[@]}"; do [ "$f" = "$s" ] && keep=true; done + case "$f" in *__pycache__*|*.pyc) keep=true;; esac + [ "$keep" = true ] || { scope_ok=false; add_hard "out_of_scope_edit:$f"; } +done < "$LOG/changed_files.txt" + +# ---- (2) import-origin assert: the scope module resolves to the baked /app/repo tree ---- +python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import os, sys +sys.path.insert(0, "/app/repo") +import curriculum_cluster as m +loc = os.path.realpath(m.__file__) +print("SCOPE_LOC", loc) +sys.exit(0 if loc.startswith("/app/repo") else 3) +PY +[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; } + +# ---- (3) trusted-restore: harness uploaded fresh (never baked) ---- +for f in workload.py compute_reward.py; do + [ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; } +done + +# ---- ref_speedup (oracle-calibrated; metadata only) ---- +# ---- ref_speedup (oracle-calibrated anchor for the reward formula) ---- +# ref_speedup is LOAD-BEARING (the log-ratio reward formula), +# not metadata. Prefer the tests/-local calibrated value (uploaded fresh at scoring, +# so it can be recalibrated without an image rebuild); fall back to the in-image +# manifest. NOTE: on this lane the baked manifest often carries an UNCALIBRATED 1.0, +# which is why tests/ref_speedup.txt takes precedence. +if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then + ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt") +elif [ -f /opt/verifier-correctness-manifest.json ]; then + 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) +fi + +# ---- (4) CORRECTNESS GATE: scope output must match the independent reference ---- +if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1 + cok=$(grep WRO_CURRIC_RESULT "$LOG/correctness.out" | python3 -c "import json,sys +try: print(json.loads(sys.stdin.read().split('WRO_CURRIC_RESULT ',1)[1]).get('correctness_ok')) +except Exception: print('False')" 2>/dev/null || echo False) + if [ "$cok" != "True" ]; then correctness_ok=false; add_hard "correctness_failed"; fi +fi + +# ---- (5) TIMING: candidate wall + baseline (frozen degraded tree at HEAD) ---- +if [ "$correctness_ok" = true ] && { [ "${#HARD[@]}" -eq 0 ] || [ -z "${HARD[*]:-}" ]; }; then + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed" + 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) + cp "$REPO/${SCOPE[0]}" /tmp/wro_cand_scope.py 2>/dev/null || true + git -C "$REPO" checkout -q HEAD -- "${SCOPE[@]}" 2>/dev/null || true + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/base_timing.out" 2>&1 || add_hard "baseline_timing_failed" + 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) + cp /tmp/wro_cand_scope.py "$REPO/${SCOPE[0]}" 2>/dev/null || true + if [ "$(python3 -c "print(1 if $cand_ms>0 and $base_ms>0 else 0)")" = "1" ]; then + speedup=$(python3 -c "print(round($base_ms/$cand_ms,6))") + else benchmark_ok=false; add_hard "timing_invalid"; fi +fi + +# ---- verdict ---- +# reward (performance class): +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0, strictly in [0.0, 1.0] +# matching the oracle => 0.5; reaching ref_speedup^2 => 1.0 +# HARD PRE-GATES (any one hit => reward 0, formula NOT evaluated): build/import +# failure, ANY correctness case fail, cheating, forbidden edit path, speedup <= 1, +# ref_speedup <= 1. The pre-existing gates below are UNCHANGED; two reward-formula +# pre-gates are added as hard fails (speedup<=1, ref_speedup<=1). +if [ "$correctness_ok" = true ]; then + if [ "$(python3 -c "print(1 if $speedup>1.0 else 0)" 2>/dev/null || echo 0)" != "1" ]; then + add_hard "speedup_not_above_baseline" + fi + if [ "$(python3 -c "print(1 if $ref_speedup>1.0 else 0)" 2>/dev/null || echo 0)" != "1" ]; then + add_hard "ref_speedup_invalid" + fi +fi +reward=0.0 +nhard="${#HARD[@]}" +if [ "$nhard" -eq 0 ] && [ "$correctness_ok" = true ]; then + reward=$(python3 -c " +import math +sp=$speedup; ref=$ref_speedup +print(round(max(0.0, min(1.0, max(0.0, min(1.0, math.log(sp) / math.log(ref) - 1.0)))), 6))" 2>/dev/null || echo 0.0) +fi +hard_str=""; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}" +export WRO_MODE="$MODE" WRO_REWARD="$reward" WRO_SPEEDUP="$speedup" \ + WRO_BASE_MS="$base_ms" WRO_CAND_MS="$cand_ms" WRO_REF="$ref_speedup" \ + WRO_HARD="$hard_str" WRO_SCOPE="$scope_ok" WRO_IMP="$import_origin_ok" \ + WRO_CORR="$correctness_ok" WRO_BENCH="$benchmark_ok" +python3 - > "$LOG/reward.json" <<'PY' +import os, json +def f(x): + try: return float(x) + except: return -1.0 +ref = f(os.environ.get("WRO_REF", "1")); sp = f(os.environ.get("WRO_SPEEDUP", "0")) +v = { + "mode": os.environ.get("WRO_MODE"), + # result-JSON contract (performance class) + "task_type": "performance", + "reward": f(os.environ.get("WRO_REWARD")), + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; 0 if any hard pre-gate hit", + "speedup": sp, + "baseline_ms": f(os.environ.get("WRO_BASE_MS")), + "candidate_ms": f(os.environ.get("WRO_CAND_MS")), + "ref_speedup": ref, + "metadata": {"vs_oracle_ratio": (sp/ref) if ref > 0 else None}, + "hard_fails": os.environ.get("WRO_HARD", "").split(), + "hard_fail_reasons": os.environ.get("WRO_HARD", "").split(), # canonical field name + "cv": None, # this harness reports a median, not dispersion + "gates": {"scope_ok": os.environ.get("WRO_SCOPE") == "true", + "import_origin_ok": os.environ.get("WRO_IMP") == "true", + "correctness_ok": os.environ.get("WRO_CORR") == "true", + "benchmark_ok": os.environ.get("WRO_BENCH") == "true"}} +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/workload.py b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..753f81671668d62e1b74bc0e40a2fbf1ac01aaa4 --- /dev/null +++ b/tasks/kfc/wro-deepspeed-curriculum-cluster-select-loop16/task/tests/workload.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Standalone verifier workload for the curriculum difficulty-cluster subsystem +(scope: /app/repo/curriculum_cluster.py :: select_curriculum_cluster). + +Drives the scope function on CPU (no torch, no GPU): given per-difficulty-row +sample-id buckets + row metric values, it selects the flat cluster of sample-ids for +a curriculum difficulty window, in VALUE mode (metric window) and PERCENTILE mode +(equal-count percentile band with partial boundary-row slicing). + + correctness : compare the scope's output against an INDEPENDENT reference computed + here (NOT in the editable scope) for BOTH modes. The percentile case + is built with a non-aligned window so the two boundary rows must be + sliced PARTIALLY -- a whole-row shortcut selects the wrong sample-ids. + timing : warmup + timed repeats over a large row set with a wide percentile + window, so the naive per-row growing concatenate dominates and + separates from a vectorized boundary-search selection. The gap GROWS + with the number of rows. + +Emits one line ``WRO_CURRIC_RESULT {json}``. Timing uses process_time (CPU time) so +the reward band is robust to OS descheduling under fleet load. +""" +import json +import statistics +import sys +import time + +import numpy as np + +REPO = "/app/repo" +if REPO not in sys.path: + sys.path.insert(0, REPO) + +# correctness: modest rows; percentile window deliberately non-bin-aligned. +C_SEED = 11 +C_ROWS = 240 +C_BINS = 20 +C_PS = 3 +C_PE = 17 +# timing: many rows + wide percentile window so the naive per-row concat dominates. +T_SEED = 4 +T_ROWS = 12000 +T_BINS = 100 +T_PS = 5 +T_PE = 95 +WARMUP = 1 +ITERS = 3 + + +def load_scope(): + import curriculum_cluster as m + return m + + +def _gen(n_rows, seed, max_metric, min_k, max_k): + rng = np.random.default_rng(seed) + metric = np.sort(rng.integers(0, max_metric, size=n_rows)).astype(np.float64) + idx_to_sample = [] + sid = 0 + for _ in range(n_rows): + k = int(rng.integers(min_k, max_k)) + idx_to_sample.append(np.arange(sid, sid + k, dtype=np.int64)) + sid += k + return idx_to_sample, metric + + +def _ref_value(index_to_sample, metric, lo, hi): + new = None + for row in range(len(index_to_sample)): + if metric[row] <= hi and metric[row] > lo: + rs = np.copy(np.asarray(index_to_sample[row])) + new = rs if new is None else np.concatenate((new, rs), axis=None) + return np.array([], dtype=np.int64) if new is None else new.astype(np.int64) + + +def _ref_percentile(index_to_sample, metric, lo, hi, num_bins): + one_epoch = sum(len(x) for x in index_to_sample) + per = one_epoch // num_bins + start_count = per * lo + end_count = one_epoch if hi == num_bins else per * hi + new = None + cur = 0 + for row in range(len(index_to_sample)): + rsz = len(index_to_sample[row]) + if cur + rsz > start_count: + rstart = max(0, start_count - cur) + rend = rsz if cur + rsz <= end_count else end_count - cur + rs = np.copy(np.asarray(index_to_sample[row])[rstart:rend]) + new = rs if new is None else np.concatenate((new, rs), axis=None) + cur += rsz + if cur >= end_count: + break + return np.array([], dtype=np.int64) if new is None else new.astype(np.int64) + + +def _eq(a, b): + a = np.asarray(a, dtype=np.int64) + b = np.asarray(b, dtype=np.int64) + return a.shape == b.shape and bool(np.array_equal(a, b)) + + +def _correctness_case(m): + idx, metric = _gen(C_ROWS, C_SEED, 600, 2, 18) + # VALUE mode over a mid metric window. + v_lo, v_hi = 100.0, 400.0 + got_v = m.select_curriculum_cluster(idx, metric, "value", v_lo, v_hi) + ref_v = _ref_value(idx, metric, v_lo, v_hi) + value_ok = _eq(got_v, ref_v) + # PERCENTILE mode, non-aligned window -> partial boundary rows. + got_p = m.select_curriculum_cluster(idx, metric, "percentile", C_PS, C_PE, num_bins=C_BINS) + ref_p = _ref_percentile(idx, metric, C_PS, C_PE, C_BINS) + pct_ok = _eq(got_p, ref_p) + # nontrivial: the percentile window must actually slice boundary rows partially + # (else a whole-row shortcut would coincide with the reference). + per = sum(len(x) for x in idx) // C_BINS + start_count = per * C_PS + cum = 0 + partial_boundary = False + for row in range(len(idx)): + rsz = len(idx[row]) + if cum < start_count < cum + rsz: + partial_boundary = True + break + cum += rsz + nontrivial = bool(partial_boundary and len(ref_p) > 0) + return {"correctness_ok": bool(value_ok and pct_ok), + "value_ok": bool(value_ok), "pct_ok": bool(pct_ok), + "ref_value_len": int(len(ref_v)), "ref_pct_len": int(len(ref_p)), + "nontrivial": nontrivial, "module": m.__file__} + + +def _timing_case(m): + idx, metric = _gen(T_ROWS, T_SEED, T_ROWS, 1, 10) + + def once(): + m.select_curriculum_cluster(idx, metric, "percentile", T_PS, T_PE, num_bins=T_BINS) + + for _ in range(WARMUP): + once() + ts = [] + for _ in range(ITERS): + t0 = time.process_time() + once() + ts.append((time.process_time() - t0) * 1000.0) + return statistics.median(ts) + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "correctness" + m = load_scope() + if mode == "correctness": + res = _correctness_case(m) + res["mode"] = "correctness" + print("WRO_CURRIC_RESULT " + json.dumps(res)) + sys.exit(0 if res["correctness_ok"] else 3) + elif mode == "timing": + ms = _timing_case(m) + print("WRO_CURRIC_RESULT " + json.dumps({ + "mode": "timing", "timing_ms": ms, "iters": ITERS, + "rows": T_ROWS, "num_bins": T_BINS, "module": m.__file__})) + sys.exit(0) + else: + print("WRO_CURRIC_RESULT " + json.dumps({"error": "bad_mode"})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/.dockerignore b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/.dockerignore @@ -0,0 +1,24 @@ +# .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does +# NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile . +# The reference implementation and every authoring artefact MUST NOT reach an image layer. +*.patch +oracle* +negative* +baseline2* +scope_card.json +degradation_manifest.json +task_meta.json +loop_map_entry.json +job.yaml +intermediates/ +_retrofit* +sr_validate* +leak_audit/ +self_check/ +variants/ +**/__pycache__/ +**/*.pyc +*.bak +*.bak_* +*.pre_* +**/*.pre_* diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/Dockerfile b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5dac0e6bb44316ce910718bf78be5c451eb5f1e4 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/Dockerfile @@ -0,0 +1,154 @@ +# syntax=docker/dockerfile:1 +# ============================================================================= +# wro-gbench-counter-finalize-loop16 — OPEN-SOURCE, self-contained task image +# +# Task: make the declared scope faster while preserving its observable behaviour exactly. +# Editable scope (the ONLY files the scope gate allows to change): +## (declared in tests/test.sh) +# +# FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image. +# CPU ONLY — task.toml declares gpus = 0. +# Platform: linux/amd64 or arm64. +# Build context = this task directory (the Dockerfile lives in environment/). +# +# PROVENANCE of environment/repo/ (so anyone can re-derive it independently) +# recovered from: /kernelbench/wro-gbench-counter-finalize-loop16:v1@sha256:7f71f99f698f361a10d263c0289848804a2db5be62f6fcb796af6f51912d18f2 +# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in +# manifest order; .git and any .wh..wh..opq marker dropped. +# 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. +## +# ----------------------------------------------------------------------------- +# BUILD (needs outbound network for PyPI only — the working tree ships in this package) +# cd <...>/wro-gbench-counter-finalize-loop16/task +# docker build -f environment/Dockerfile -t fai/kfc-wro-gbench-counter-finalize-loop16:oss . +# +# RUN docker run --rm -it fai/kfc-wro-gbench-counter-finalize-loop16:oss +# SCORE docker run --rm -v "$PWD/tests:/tests:ro" fai/kfc-wro-gbench-counter-finalize-loop16:oss bash /tests/test.sh +# # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative) +# +# 🔴 RE-CALIBRATE THE ANCHOR ON YOUR HARDWARE +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; ref_speedup = 15.127159 . +# tests/test.sh resolves it from tests/ref_speedup.txt FIRST, then falls back to +# /opt/verifier-correctness-manifest.json, then to 1.0 (which would make every reward 0). +# The value was calibrated on the authoring CPU lane (Intel Sapphire Rapids). The verifier supports mode dispatch natively, so +# re-measuring is ONE command (the reference patch is passed BY PATH and never baked): +# docker run --rm -v "$PWD/tests:/tests:ro" -v ":/patches:ro" \ +# -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ +# fai/kfc-wro-gbench-counter-finalize-loop16:oss bash /tests/test.sh +# then write the measured speedup into tests/ref_speedup.txt. See tests/ref_speedup.caveat.md. +# Sanity: noop (no patch) ~= 1.0 -> gated to 0; negative MUST score 0. +# +# VERSION ANCHORS +# Python 3.11 · standard library + numpy +# The original private base declared torch 2.5.1 / triton 3.1.0 and the task overlay then ran +# `pip install torch==2.7.0` — 2.7.0 is therefore the version the anchor was calibrated under. +# ============================================================================= +FROM python:3.11-slim-bookworm + +ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \ + PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential git ca-certificates curl procps coreutils tar gzip vim less file jq \ + && rm -rf /var/lib/apt/lists/* + +# ---- venv at this EXACT path: tests/test.sh puts /opt/kernelbench-venv/bin at the head of PATH. ---- +ENV VENV=/opt/kernelbench-venv +RUN python3 -m venv "$VENV" +ENV PATH=$VENV/bin:$PATH +RUN pip install --no-cache-dir -U pip setuptools wheel +RUN pip install --no-cache-dir "numpy>=1.26,<3" + +# ---- the graded working tree. A REAL directory (not a symlink): the scope gate runs +# `git -C /app/repo status --porcelain`, which cannot see through a symlink. ---- +RUN mkdir -p /app/repo /app/.timer /app/workspace /logs/verifier /logs/agent /logs/artifacts +COPY environment/repo/ /app/repo/ +COPY instruction.md /app/instruction.md + +# ---- the baseline commit = the diff base the scope gate compares against. +# 🔴 core.fileMode=false is LOAD-BEARING, not hygiene: a shipped image in this corpus had +# core.fileMode=true while some files were 0775 on disk but 100644 in the index, so +# `git status --porcelain` reported phantom out-of-scope paths in EVERY mode and forced +# reward to 0. Setting it false at creation makes that class of defect impossible. ---- +RUN git config --global user.email "reviewer@fai-bench.local" \ + && git config --global user.name "fai-bench" \ + && git config --global init.defaultBranch main \ + && git config --global --add safe.directory /app/repo \ + && cd /app/repo \ + && git init -q \ + && git config core.fileMode false \ + && printf '__pycache__/\n*.pyc\n' >> .gitignore \ + && git add -A \ + && git commit -qm "carved baseline (graded starting point)" \ + && rm -rf .git/logs \ + && test "$(git rev-list --count HEAD)" = "1" \ + && test -z "$(git remote)" \ + && test "$(git config --get core.fileMode)" = "false" \ + && test -z "$(git status --porcelain)" \ + && echo "[build] /app/repo: 1 commit, no remote, fileMode=false, clean tree" + +# ---- runtime contract (copied verbatim from the shipped image) ---- +COPY environment/runtime/entrypoint.sh /app/entrypoint.sh +COPY environment/runtime/timer.sh /app/timer.sh +RUN chmod 0755 /app/entrypoint.sh /app/timer.sh && chown root:root /app/entrypoint.sh /app/timer.sh +COPY environment/runtime/run_dev_bench.sh /app/workspace/run_dev_bench.sh +RUN chmod 0755 /app/workspace/run_dev_bench.sh +COPY environment/loop/ /opt/loop/ +RUN if [ -f /opt/loop/submit.sh ]; then chmod 0755 /opt/loop/submit.sh; fi \ + && chown -R root:root /opt/loop \ + && if [ -f /opt/loop/score_engine.sh ]; then chmod 0700 /opt/loop/score_engine.sh; fi \ + && if [ -f /opt/loop/sanitize_feedback.py ]; then chmod 0700 /opt/loop/sanitize_feedback.py; fi \ + && if [ -d /opt/loop/private ]; then chmod -R go-rwx /opt/loop/private; fi + +# ---- OPEN grading suite is NOT baked: tests/ (test.sh + compute_reward.py + the workload/harness +# + ref_speedup.txt) is MOUNTED FRESH at /tests when scoring. It ships in this package — +# open-source, but outside the image so the graded harness cannot be edited from the session. + +# ---- 🔴 ANTI-LEAK ASSERTS ---- +RUN set -eu; rc=0; \ + hits="$(find / -xdev -type f \( -name 'oracle*.patch' -o -name 'negative*.patch' \ + -o -name 'baseline2*.patch' -o -name 'scope_card.json' -o -name 'kernel_oracle.py' \ + -o -name 'degradation_manifest.json' \) 2>/dev/null | head -10)"; \ + if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: a reference/authoring file is baked:"; echo "$hits"; rc=1; fi; \ + for p in /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling /tests; do \ + if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path baked: $p"; rc=1; fi; \ + done; \ + test "$rc" = 0; \ + echo "[build] ANTI-LEAK ASSERTS PASS" + +ENV PYTHONPATH=/app/repo \ + PYTHONDONTWRITEBYTECODE=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 +WORKDIR /app/repo + +# ---- build-time smoke: the graded module imports FROM /app/repo (the verifier asserts the same +# thing at scoring time via its import-origin gate) and the scope files are present. ---- +RUN python - <<'PY' +import os, subprocess, sys +sys.path.insert(0, "/app/repo") +for f in ('bench_counter.py',): + p = os.path.join("/app/repo", f) + assert os.path.isfile(p), f"scope file missing: {p}" + print("scope file present:", f, os.path.getsize(p), "B") +import importlib.util +for _mod in ('bench_counter',): + try: + _spec = importlib.util.find_spec(_mod) + except Exception as _e: + print("NOTE: import-origin probe skipped for", _mod, "->", repr(_e), + "(tests/test.sh re-asserts this at scoring time)") + continue + _loc = (getattr(_spec, "origin", "") or "") if _spec else "" + print("resolves:", _mod, "->", _loc or "") + assert not _loc or _loc.startswith("/app/repo"), \ + f"{_mod} resolves OUTSIDE the graded tree: {_loc}" +n = subprocess.run(["git","-C","/app/repo","rev-list","--count","HEAD"], + capture_output=True, text=True).stdout.strip() +assert n == "1", f"git diff base broken (commits={n!r})" +print("OK: scope files, import origin and git base all in place") +PY + +ENTRYPOINT ["/app/entrypoint.sh"] +CMD ["tail","-f","/dev/null"] diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/manifest.json b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f560d5a3e479f565c0601e8e6893df75831c896c --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/manifest.json @@ -0,0 +1,13 @@ +{ + "max_submissions": 1, + "min_submissions": 1, + "note": "dev reward is an in-session proxy; the runner end-of-session /tests score is authoritative.", + "perf_metric": "speedup", + "reward_form": "raw_speedup(base_ms/cand_ms); no-op ~= 1.0", + "schema_version": "kernelbench_loop_manifest_v1", + "scope": [ + "bench_counter.py" + ], + "scoring": "task tests/test.sh in candidate mode on the live /app/repo", + "task_id": "wro-gbench-counter-finalize-loop16" +} diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/compute_reward.py b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..21c7b09137719c8f6be09fd9fe1cddf079adfb90 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/compute_reward.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +"""compute_reward for wro-gbench-counter-finalize (acceleration). +reward = base_ms / candidate_ms (raw wall speedup vs the frozen degraded baseline), +gated by correctness in test.sh (wrong finalized values -> reward 0 there). +noop(degraded)~=1.0; oracle>>1 (vectorized); baseline2 in between; negative=0.""" +import json +import sys + + +def load(path): + for line in open(path): + if line.startswith("WRO_CNT_RESULT "): + return json.loads(line[len("WRO_CNT_RESULT "):]) + raise SystemExit(f"no WRO_CNT_RESULT in {path}") + + +def main(): + cand = load(sys.argv[1]) + base_ms = float(sys.argv[2]) if len(sys.argv) > 2 else -1.0 + cm = cand.get("timing_ms", -1) + speedup = (base_ms / cm) if (cm and cm > 0 and base_ms > 0) else 0.0 + print(json.dumps({"reward": round(speedup, 6), "speedup": round(speedup, 6), + "baseline_ms": base_ms, "candidate_ms": cm})) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/test.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c8b925a53e592707078f9b4865d45d09d2aa66e6 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/test.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# Verifier for wro-gbench-counter-finalize (microbenchmark per-counter finalization: +# flag-driven rate/avg-threads/iteration-invariant/avg-iterations/invert-last scaling +# over a (B,C) counter table, modelled on Google Benchmark's Finish, src/counter.cc + +# include/benchmark/counter.h). +# ACCELERATION, CPU (host logic; no GPU). Scope = bench_counter.py (finalize_counters). +# Modes: candidate | noop | oracle | negative | baseline2. +# reward = raw wall speedup (base_ms/cand_ms); noop ~ 1.0 (degraded vs itself); +# oracle >> 1 (vectorized masked transforms vs per-cell Python loop); baseline2 in between +# (per-benchmark loop, counters vectorized); negative = 0 (inverts out of order -> wrong +# finalized values for kInvert-combined counters). +set -uo pipefail +export PATH="/opt/kernelbench-venv/bin:/opt/venv/bin:/usr/local/bin:$PATH" +export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +git config --global --add safe.directory '*' 2>/dev/null || true +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/verifier; mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +SCOPE=("bench_counter.py") + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true +speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1 + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +# ---- apply oracle / baseline2 / negative patch by mode (candidate & noop: no patch) ---- +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"; fi +if [ "$MODE" = "baseline2" ] && [ -n "${KERNELBENCH_BASELINE2_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_BASELINE2_PATCH" 2>"$LOG/baseline2_apply.log" || add_hard "baseline2_apply_failed"; fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true; fi + +# ---- (1) scope-diff HARD GATE: only the scope file may change in /app/repo ---- +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + keep=false + for s in "${SCOPE[@]}"; do [ "$f" = "$s" ] && keep=true; done + case "$f" in *__pycache__*|*.pyc) keep=true;; esac + [ "$keep" = true ] || { scope_ok=false; add_hard "out_of_scope_edit:$f"; } +done < "$LOG/changed_files.txt" + +# ---- (2) import-origin assert: the scope module resolves to the baked /app/repo tree ---- +python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import os, sys +sys.path.insert(0, "/app/repo") +import bench_counter as m +loc = os.path.realpath(m.__file__) +print("SCOPE_LOC", loc) +sys.exit(0 if loc.startswith("/app/repo") else 3) +PY +[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; } + +# ---- (3) trusted-restore: harness uploaded fresh (never baked) ---- +for f in workload.py compute_reward.py; do + [ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; } +done + +# ---- ref_speedup (oracle-calibrated; metadata only) ---- +[ -f /opt/verifier-correctness-manifest.json ] && \ + 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) + +# ---- (4) CORRECTNESS GATE: scope output must match the independent reference ---- +if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1 + cok=$(grep WRO_CNT_RESULT "$LOG/correctness.out" | python3 -c "import json,sys +try: print(json.loads(sys.stdin.read().split('WRO_CNT_RESULT ',1)[1]).get('correctness_ok')) +except Exception: print('False')" 2>/dev/null || echo False) + if [ "$cok" != "True" ]; then correctness_ok=false; add_hard "correctness_failed"; fi +fi + +# ---- (5) TIMING: candidate wall + baseline (frozen degraded tree at HEAD) ---- +if [ "$correctness_ok" = true ] && { [ "${#HARD[@]}" -eq 0 ] || [ -z "${HARD[*]:-}" ]; }; then + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed" + cand_ms=$(grep WRO_CNT_RESULT "$LOG/cand_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_CNT_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1) + cp "$REPO/${SCOPE[0]}" /tmp/wro_cand_scope.py 2>/dev/null || true + git -C "$REPO" checkout -q HEAD -- "${SCOPE[@]}" 2>/dev/null || true + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/base_timing.out" 2>&1 || add_hard "baseline_timing_failed" + base_ms=$(grep WRO_CNT_RESULT "$LOG/base_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_CNT_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1) + cp /tmp/wro_cand_scope.py "$REPO/${SCOPE[0]}" 2>/dev/null || true + if [ "$(python3 -c "print(1 if $cand_ms>0 and $base_ms>0 else 0)")" = "1" ]; then + speedup=$(python3 -c "print(round($base_ms/$cand_ms,6))") + else benchmark_ok=false; add_hard "timing_invalid"; fi +fi + +# ---- verdict ---- +reward=0.0 +nhard="${#HARD[@]}" +if [ "$nhard" -eq 0 ] && [ "$correctness_ok" = true ]; then reward="$speedup"; fi +hard_str=""; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}" +export WRO_MODE="$MODE" WRO_REWARD="$reward" WRO_SPEEDUP="$speedup" \ + WRO_BASE_MS="$base_ms" WRO_CAND_MS="$cand_ms" WRO_REF="$ref_speedup" \ + WRO_HARD="$hard_str" WRO_SCOPE="$scope_ok" WRO_IMP="$import_origin_ok" \ + WRO_CORR="$correctness_ok" WRO_BENCH="$benchmark_ok" +python3 - > "$LOG/reward.json" <<'PY' +import os, json +def f(x): + try: return float(x) + except: return -1.0 +ref = f(os.environ.get("WRO_REF", "1")); sp = f(os.environ.get("WRO_SPEEDUP", "0")) +v = { + "mode": os.environ.get("WRO_MODE"), + "reward": f(os.environ.get("WRO_REWARD")), + "speedup": sp, + "baseline_ms": f(os.environ.get("WRO_BASE_MS")), + "candidate_ms": f(os.environ.get("WRO_CAND_MS")), + "ref_speedup": ref, + "metadata": {"vs_oracle_ratio": (sp/ref) if ref > 0 else None}, + "hard_fails": os.environ.get("WRO_HARD", "").split(), + "gates": {"scope_ok": os.environ.get("WRO_SCOPE") == "true", + "import_origin_ok": os.environ.get("WRO_IMP") == "true", + "correctness_ok": os.environ.get("WRO_CORR") == "true", + "benchmark_ok": os.environ.get("WRO_BENCH") == "true"}} +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/workload.py b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..709ea410d550901f1cb46c71623aa279f7a5eb5d --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/private/tests/workload.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Standalone verifier workload for the counter-finalization subsystem +(scope: /app/repo/bench_counter.py :: finalize_counters). ACCELERATION. + +Drives the scope on CPU (numpy only, no torch, no GPU). Two modes: + + correctness : call finalize_counters on a curated (B, C) counter table whose + flag set deliberately includes counters that COMBINE kInvert with + a rate / thread / iteration transform, and check the returned + (B, C) array against an INDEPENDENT scalar reference computed here + (NOT part of the editable scope). Because "Invert is always last", + an implementation that inverts out of order produces a different + result for those combined counters and is rejected (gate vs + negative), which is why the table is seeded with such counters. + timing : warmup + timed repeats over a large (B, C) table so the + per-(benchmark, counter) Python cell loop dominates and separates + from the vectorized masked form. The gap grows with B * C. + +Emits one line ``WRO_CNT_RESULT {json}``. Timing uses process_time (CPU time) so +the reward band is robust to OS descheduling under fleet load (exp §6.52). +""" +import json +import statistics +import sys +import time + +import numpy as np + +REPO = "/app/repo" +if REPO not in sys.path: + sys.path.insert(0, REPO) + +kIsRate = 1 << 0 +kAvgThreads = 1 << 1 +kIsIterationInvariant = 1 << 2 +kAvgIterations = 1 << 3 +kInvert = 1 << 31 + +# Flag palette used to build tables. Deliberately rich in kInvert combinations so +# the "invert must be last" rule is exercised. +FLAG_PALETTE = [ + 0, + kIsRate, + kAvgThreads, + kIsIterationInvariant, + kAvgIterations, + kIsRate | kAvgThreads, + kIsRate | kAvgIterations, + kIsIterationInvariant | kAvgThreads, + kInvert, + kIsRate | kInvert, + kAvgThreads | kInvert, + kIsRate | kAvgThreads | kInvert, + kIsRate | kIsIterationInvariant, + kAvgIterations | kAvgThreads, +] + +# correctness: small table; every palette entry appears so the invert-order and +# missing-flag mistakes are all detectable. +C_B = 6 +C_C = 8 +C_SEED = 17 + +# timing: large table so the per-cell Python loop (scalar reads + flag branches) +# dominates vs the vectorized masked form. +T_B = 6000 +T_C = 20 +T_SEED = 5 +WARMUP = 1 +ITERS = 3 + + +def load_scope(): + import bench_counter as m + return m + + +def _gen(B, C, seed, curated): + rng = np.random.default_rng(seed) + values = rng.uniform(1.0, 1000.0, size=(B, C)) + if curated: + # tile the full palette across the table so all combos are present + pal = np.array(FLAG_PALETTE, dtype=np.int64) + flags = pal[np.arange(B * C) % pal.size].reshape(B, C) + else: + idx = rng.integers(0, len(FLAG_PALETTE), size=(B, C)) + flags = np.array(FLAG_PALETTE, dtype=np.int64)[idx] + iterations = rng.integers(1000, 10_000_000, size=B).astype(np.float64) + cpu_time = rng.uniform(1e-4, 2.0, size=B) + num_threads = rng.choice(np.array([1.0, 2.0, 4.0, 8.0]), size=B) + return values, flags, iterations, cpu_time, num_threads + + +def _reference(values, flags, iterations, cpu_time, num_threads): + # Independent, definitional scalar implementation (NOT the editable scope). + values = np.asarray(values, dtype=np.float64) + flags = np.asarray(flags, dtype=np.int64) + B, C = values.shape + out = np.empty((B, C), dtype=np.float64) + for b in range(B): + it_b = float(iterations[b]) + ct_b = float(cpu_time[b]) + nt_b = float(num_threads[b]) + for c in range(C): + v = float(values[b, c]) + f = int(flags[b, c]) + if f & kIsRate: + v /= ct_b + if f & kAvgThreads: + v /= nt_b + if f & kIsIterationInvariant: + v *= it_b + if f & kAvgIterations: + v /= it_b + if f & kInvert: + v = 1.0 / v + out[b, c] = v + return out + + +def _invert_first(values, flags, iterations, cpu_time, num_threads): + # The classic "invert not last" mistake, for the gate-quality signal only. + values = np.asarray(values, dtype=np.float64) + flags = np.asarray(flags, dtype=np.int64) + B, C = values.shape + out = np.empty((B, C), dtype=np.float64) + for b in range(B): + it_b = float(iterations[b]); ct_b = float(cpu_time[b]); nt_b = float(num_threads[b]) + for c in range(C): + v = float(values[b, c]); f = int(flags[b, c]) + if f & kInvert: + v = 1.0 / v + if f & kIsRate: + v /= ct_b + if f & kAvgThreads: + v /= nt_b + if f & kIsIterationInvariant: + v *= it_b + if f & kAvgIterations: + v /= it_b + out[b, c] = v + return out + + +def _correctness_case(m): + args = _gen(C_B, C_C, C_SEED, curated=True) + try: + got = m.finalize_counters(*args) + except NotImplementedError: + return {"correctness_ok": False, "reason": "not_implemented"} + except Exception as e: + return {"correctness_ok": False, "reason": "exception:" + type(e).__name__} + ref = _reference(*args) + got = np.asarray(got, dtype=np.float64) + shape_ok = bool(got.shape == ref.shape) + match_ok = bool(shape_ok and np.allclose(got, ref, rtol=1e-9, atol=1e-12)) + # is the invert-order shortcut detectably wrong on this table? (gate quality) + wrong = _invert_first(*args) + nontrivial = int(not np.allclose(wrong, ref, rtol=1e-9, atol=1e-12)) + return {"correctness_ok": match_ok, "shape_ok": shape_ok, "nontrivial": nontrivial} + + +def _timing_case(m): + args = _gen(T_B, T_C, T_SEED, curated=False) + + def once(): + m.finalize_counters(*args) + + try: + for _ in range(WARMUP): + once() + except NotImplementedError: + return -1.0 + ts = [] + for _ in range(ITERS): + t0 = time.process_time() + once() + ts.append((time.process_time() - t0) * 1000.0) + return statistics.median(ts) + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "correctness" + m = load_scope() + if mode == "correctness": + res = _correctness_case(m) + res["mode"] = "correctness" + print("WRO_CNT_RESULT " + json.dumps(res)) + sys.exit(0 if res.get("correctness_ok") else 3) + elif mode == "timing": + ms = _timing_case(m) + if ms < 0: + print("WRO_CNT_RESULT " + json.dumps({"mode": "timing", "timing_ms": -1, + "reason": "not_implemented"})) + sys.exit(3) + print("WRO_CNT_RESULT " + json.dumps({ + "mode": "timing", "timing_ms": ms, "iters": ITERS, "B": T_B, "C": T_C})) + sys.exit(0) + else: + print("WRO_CNT_RESULT " + json.dumps({"error": "bad_mode"})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/sanitize_feedback.py b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/sanitize_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..d70a722c566c5b3eeaeaa0205cf0b4884fbba7a6 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/sanitize_feedback.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +# ============================================================================ +# wro loop16 finalizer — sanitize_feedback.py (REUSABLE, task-agnostic) 0700 root +# ============================================================================ +"""Leak-free per-round feedback. Invoked ONLY by /opt/loop/submit.sh. Reads the +normalized DEV products under /logs/loop/dev/ and the loop accounting under +/logs/loop/, and prints ONLY a sanitized summary: + + submission k/16 + correctness: PASS | FAIL + [FAIL only] failing_invariant: + dev_speedup: + dev_reward: + best_so_far: submission , dev_speedup , dev_reward + remaining: <16 - k> + finalize_allowed: + [harness path] harness_error: (candidate not at fault) + +NEVER emits: verifier/test.sh/compute_reward contents; hidden workload +names/seeds/counts/shapes; any threshold; ref_speedup; absolute timings. +MAY emit: pass/fail; a named invariant; relative dev_speedup; dev_reward; +submission index; best-so-far; remaining budget; finalize_allowed. +""" +from __future__ import annotations +import json +import sys +from pathlib import Path + +LOOP = Path("/logs/loop") +DEV = LOOP / "dev" +MIN_SUBMISSIONS = 3 +MAX_SUBMISSIONS = 16 + +# Map a raw hard-fail reason (leak-free by construction) to a friendly, actionable +# invariant name. Reasons the wro verifier emits: out_of_scope_edit:, +# import_origin_not_app_repo, correctness_trace_mismatch, timing_invalid, +# candidate_timing_failed, baseline_timing_failed, repo_missing, +# hidden_supplement_missing:, oracle_apply_failed/baseline2_apply_failed. +_HINTS = { + "edit_scope": "your diff changed a file outside the declared editable scope — " + "keep edits to the in-scope product file(s) only", + "import_origin": "the module under test did not resolve to the in-repo tree — " + "do not shadow it with a copy elsewhere", + "correctness": "your output no longer matches the reference behavior exactly — " + "the change must be speed-only, behavior-identical", + "benchmark": "the timing run did not produce a valid measurement — check your " + "change does not crash or hang the benchmarked path", + "verifier_completed": "the check did not complete — re-check your last edit " + "did not cause an early crash", +} + + +def _named_invariant(hard: list[str]) -> str: + h0 = (hard[0] if hard else "") + def startswith(*p): return any(any(x.startswith(pp) for pp in p) for x in hard) + if startswith("out_of_scope_edit", "forbidden_edit_path", "forbidden_source_reference"): + return f"edit_scope: {_HINTS['edit_scope']}" + if startswith("import_origin"): + return f"import_origin: {_HINTS['import_origin']}" + if startswith("correctness_trace_mismatch", "correctness_failed", "correctness"): + return f"output_matches_reference: {_HINTS['correctness']}" + if startswith("timing_invalid", "candidate_timing_failed", "baseline_timing_failed", "benchmark"): + return f"runs_without_error: {_HINTS['benchmark']}" + if h0: + return f"verifier_completed: {_HINTS['verifier_completed']}" + return f"verifier_completed: {_HINTS['verifier_completed']}" + + +def _read_json(path: Path, default): + try: + return json.loads(path.read_text(encoding="utf-8")) + except Exception: + return default + + +def _fmt(x, nd=4): + try: + return f"{float(x):.{nd}g}" + except Exception: + return str(x) + + +def main() -> int: + try: + k = int((LOOP / "count").read_text(encoding="utf-8").strip()) + except Exception: + k = 0 + + he = DEV / "harness_error.txt" + if he.exists(): + try: + msg = he.read_text(encoding="utf-8").strip().splitlines()[0] + except Exception: + msg = "dev engine infrastructure error" + print(f"submission {k}/{MAX_SUBMISSIONS}") + print(f"harness_error: {msg} — this is NOT a defect in your code; do not " + f"debug the harness. Retry or continue optimizing (this attempt was " + f"not counted).") + return 0 + + state = _read_json(DEV / "verifier_state.json", {}) + reward = _read_json(DEV / "reward.json", {}) + corr_ok = bool(state.get("correctness_ok")) + hard = [str(r) for r in (state.get("hard_fail_reasons") or [])] + speedup = reward.get("speedup", None) + r = reward.get("reward", 0.0) + + print(f"submission {k}/{MAX_SUBMISSIONS}") + if corr_ok: + print("correctness: PASS") + else: + print("correctness: FAIL") + print(f"failing_invariant: {_named_invariant(hard)}") + + print(f"dev_speedup: {_fmt(speedup) if speedup is not None else 'n/a'}") + print(f"dev_reward: {_fmt(r)}") + + best = _read_json(LOOP / "best.json", None) + if best and isinstance(best, dict) and best.get("submission"): + print(f"best_so_far: submission {best.get('submission')}, " + f"dev_speedup {_fmt(best.get('speedup'))}, dev_reward {_fmt(best.get('reward'))}") + else: + print("best_so_far: (none — no correctness-passing submission yet)") + + print(f"remaining: {max(0, MAX_SUBMISSIONS - k)}") + print(f"finalize_allowed: {'true' if k >= MIN_SUBMISSIONS else 'false'}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/score_engine.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/score_engine.sh new file mode 100644 index 0000000000000000000000000000000000000000..400d64db5fa4b2cbc66fc0dc643a6976cba4323a --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/score_engine.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# ============================================================================ +# wro loop16 finalizer — score_engine.sh (REUSABLE, task-agnostic) 0700 root +# ============================================================================ +# Invoked ONLY by /opt/loop/submit.sh. Scores the LIVE /app/repo by running the +# task's OWN verifier in candidate mode against the solver's in-scope edits, then +# normalizes its standard wro JSON verdict into the dev files submit.sh/sanitize read. +# +# The wro verifier (tests/test.sh, baked into /opt/loop/private/tests/) already +# performs the whole scoring contract in candidate mode: scope-diff gate, +# import-origin assert, exact-correctness gate vs the baked golden, and paired +# candidate-vs-baseline timing -> a single JSON line: +# {"mode","reward","speedup","baseline_ms","candidate_ms","ref_speedup", +# "metadata",{...},"hard_fails":[...], +# "gates":{"scope_ok","import_origin_ok","correctness_ok","benchmark_ok"}} +# reward = speedup when there are no hard fails and correctness holds, else 0. +# +# This engine is generic across every wro task: the only per-task content is the +# baked verifier itself (test.sh + workload.py + compute_reward.py), staged into +# /opt/loop/private/tests/ at image build time. +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 +set -uo pipefail +git config --global --add safe.directory '*' 2>/dev/null || true + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DEV_OUT="${LOOP_DEV_OUT:-/logs/loop/dev}"; export LOOP_DEV_OUT="$DEV_OUT"; mkdir -p "$DEV_OUT" +TESTS="$HERE/private/tests" +rm -f "$DEV_OUT/harness_error.txt" "$DEV_OUT/verdict.json" 2>/dev/null || true + +if [ ! -f "$TESTS/test.sh" ]; then + echo "baked verifier missing at $TESTS/test.sh" > "$DEV_OUT/harness_error.txt" + exit 3 +fi + +# The loop16 image bakes a committed /app/repo/.git at the degraded baseline (built +# offline; its files carry a different owner/mtime than the image working tree). Refresh +# the index so the task's git scope/timing gates compare CONTENT, not stale stat — a real +# in-scope edit still shows as modified; only content-identical stat noise is cleared. +git -C /app/repo update-index -q --refresh >/dev/null 2>&1 || true + +# Run the task's verifier in candidate mode against the live /app/repo. +KERNELBENCH_VERIFY_MODE=candidate bash "$TESTS/test.sh" > "$DEV_OUT/verdict.raw" 2>"$DEV_OUT/verdict.err" +vr=$? + +# Normalize the wro verdict JSON -> dev files. A genuine harness failure (no +# parseable verdict) is reported as harness_error (submit.sh refunds the budget). +python3 - "$DEV_OUT" "$vr" <<'PY' +import json, sys +from pathlib import Path +DEV = Path(sys.argv[1]); vr = sys.argv[2] +raw = "" +try: raw = (DEV / "verdict.raw").read_text(encoding="utf-8", errors="replace") +except Exception: raw = "" + +# grab the LAST line that parses as a wro verdict (has a "gates" key) +verdict = None +for line in reversed(raw.splitlines()): + line = line.strip() + if not line or not line.startswith("{"): + continue + try: + obj = json.loads(line) + except Exception: + continue + if isinstance(obj, dict) and "gates" in obj and "hard_fails" in obj: + verdict = obj; break + +if verdict is None: + err = (DEV / "verdict.err").read_text(errors="replace")[:400] if (DEV / "verdict.err").exists() else "" + (DEV / "harness_error.txt").write_text( + f"verifier produced no parseable verdict (exit {vr}); " + f"stderr head: {err.splitlines()[0] if err.strip() else '(none)'}\n") + # still write empty dev files so downstream reads don't crash + (DEV / "verifier_state.json").write_text(json.dumps({"correctness_ok": False, "hard_fail_reasons": ["harness_error"]})) + (DEV / "reward.json").write_text(json.dumps({"reward": 0.0, "speedup": 0.0})) + (DEV / "benchmark_results.json").write_text(json.dumps({"aggregate_speedup": 0.0})) + sys.exit(3) + +hard = list(verdict.get("hard_fails") or []) +gates = verdict.get("gates") or {} +# A submission is check-passing iff the verifier assigned NO hard fail (which +# already covers scope / import-origin / correctness / timing failures). +correctness_ok = (len(hard) == 0) and bool(gates.get("correctness_ok", True)) +reward = float(verdict.get("reward") or 0.0) +speedup = float(verdict.get("speedup") or 0.0) + +(DEV / "verifier_state.json").write_text(json.dumps({ + "correctness_ok": correctness_ok, + "hard_fail_reasons": hard, + "gates": gates, +}, sort_keys=True)) +(DEV / "reward.json").write_text(json.dumps({"reward": reward, "speedup": speedup}, sort_keys=True)) +(DEV / "benchmark_results.json").write_text(json.dumps({"aggregate_speedup": speedup}, sort_keys=True)) +sys.exit(0) +PY +rc=$? +if [ "$rc" -ne 0 ] && [ "$rc" -ne 3 ] && [ ! -f "$DEV_OUT/harness_error.txt" ]; then + { echo "score_engine_exit_${rc}"; tail -n 20 "$DEV_OUT/verdict.err" 2>/dev/null; } > "$DEV_OUT/harness_error.txt" +fi +exit "$rc" diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/submit.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/submit.sh new file mode 100644 index 0000000000000000000000000000000000000000..1515f082ded46f5698489d7ece29ddd0cac320c0 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/loop/submit.sh @@ -0,0 +1,210 @@ +#!/usr/bin/env bash +# ============================================================================ +# wro loop16 finalizer — submit.sh (REUSABLE, task-agnostic) +# ============================================================================ +# The solver's ONLY sanctioned scoring interface during a session +# (0755 root:root; the engine + private assets it calls are 0700 root-owned). +# Baked at /opt/loop/submit.sh so it exists from the first turn — unlike +# /tests/, which the grading harness creates only AFTER the agent finishes. +# +# bash /opt/loop/submit.sh # score current /app/repo, get feedback +# bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best iterate, end loop +# +# A wro submission is the solver's EDITS to the declared /app/repo scope files, +# scored by the task's own tests/test.sh in candidate mode -> perf_metric. +# Budget: exactly ONE graded submission (kfc is single-submission). The first +# submit.sh scores and immediately auto-finalizes; there is no second scored attempt. +# end-of-session /tests/test.sh scores the best-of-k iterate. HEAD stays at the +# baked baseline commit, so the anti-cheat scope-diff sees a product-only change. +# +# 🔴 git-safe-directory: a root-owned /app/repo is +# root-owned; without this every git op inside test.sh fails "dubious ownership" +# and silently returns a false 1.0. MUST be the first effective line. +git config --global --add safe.directory '*' 2>/dev/null || true + +# 🔴 PATH-pin: the agent shell + runner verifier exec are NON-login; bare python3 +# may lack the task's numpy/torch. Pin the venv (if present) first, then system. +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 +set -uo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOOP=/logs/loop +DEV="$LOOP/dev" +mkdir -p "$LOOP" "$LOOP/submissions" "$DEV" + +MIN_SUBMISSIONS=1 +MAX_SUBMISSIONS=1 +COUNT_FILE="$LOOP/count" +BEST_FILE="$LOOP/best.json" +STATE_JSONL="$LOOP/state.jsonl" + +# task_id for the finalize record — read from the baked private manifest (generic). +TASK_ID="$(python3 -c 'import json;print(json.load(open("/opt/loop/private/manifest.json")).get("task_id",""))' 2>/dev/null || true)" +[ -n "$TASK_ID" ] || TASK_ID="wro-loop16" + +_read_count() { + if [ -f "$COUNT_FILE" ]; then + awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE" + else + echo 0 + fi +} + +# Non-mutating snapshot of the current working tree -> a git tree hash. +_snapshot_tree() { + local c + c="$(git -C "$REPO" stash create 2>/dev/null || true)" + if [ -n "$c" ]; then + git -C "$REPO" rev-parse "$c^{tree}" 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null + else + git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null + fi +} + +# ------------------- argument parsing ------------------- +MODE=submit +REASON="" +while [ "$#" -gt 0 ]; do + case "$1" in + --finalize) MODE=finalize; shift ;; + --reason) REASON="${2:-}"; shift 2 ;; + --reason=*) REASON="${1#--reason=}"; shift ;; + *) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"\"]]" >&2; exit 2 ;; + esac +done + +# ------------------- finalize ------------------- +if [ "$MODE" = finalize ]; then + CUR="$(_read_count)"; CUR="${CUR:-0}" + if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then + echo "minimum $MIN_SUBMISSIONS submission(s) required before finalize (you have $CUR/$MIN_SUBMISSIONS)" + exit 1 + fi + # Reset the working tree to the baked baseline (HEAD), then plant the winner. + git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true + git -C "$REPO" clean -qfd 2>/dev/null || true + WIN_SUB=""; WIN_TREE="" + if [ -f "$BEST_FILE" ]; then + WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)" + 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)" + fi + PLANTED="none" + if [ -n "$WIN_TREE" ] && git -C "$REPO" read-tree "$WIN_TREE" 2>"$LOOP/finalize_apply.log"; then + # read-tree loaded the winning tree into the index; write it to the worktree. + # HEAD is unchanged (still the baseline commit) -> anti-cheat sees product-only diff. + git -C "$REPO" checkout-index -f -a 2>>"$LOOP/finalize_apply.log" && PLANTED="read-tree" + fi + if [ "$PLANTED" = "none" ] && [ -n "$WIN_SUB" ] && [ -s "$LOOP/submissions/$WIN_SUB/candidate.diff" ]; then + # fallback: re-apply the winning binary diff onto the baseline. + git -C "$REPO" apply --whitespace=nowarn "$LOOP/submissions/$WIN_SUB/candidate.diff" 2>>"$LOOP/finalize_apply.log" \ + && PLANTED="diff-apply" \ + || echo "WARNING: could not plant the winning submission; see /logs/loop/finalize_apply.log" >&2 + fi + REASON="$REASON" WIN_SUB="$WIN_SUB" WIN_TREE="$WIN_TREE" CUR="$CUR" PLANTED="$PLANTED" TASK_ID="$TASK_ID" python3 - <<'PY' +import json, os +from pathlib import Path +LOOP = Path('/logs/loop') +try: best = json.loads((LOOP / 'best.json').read_text()) +except Exception: best = {} +traj = [] +try: + for line in (LOOP / 'state.jsonl').read_text().splitlines(): + line = line.strip() + if not line: continue + row = json.loads(line) + traj.append({'submission': row.get('submission'), 'dev_speedup': row.get('speedup'), + 'dev_reward': row.get('reward'), 'correctness_ok': row.get('correctness_ok')}) +except Exception: pass +out = { + 'schema_version': 'kernelbench_loop_finalize_v1', + 'task_id': os.environ.get('TASK_ID') or 'wro-loop16', + 'mode': 'baked', 'plant_method': os.environ.get('PLANTED'), + 'submissions_used': int(os.environ.get('CUR') or 0), + 'min_submissions': 1, 'max_submissions': 1, + 'winning_submission': (best.get('submission') if best else None), + 'winning_tree': os.environ.get('WIN_TREE') or None, + 'winning_dev_speedup': (best.get('speedup') if best else None), + 'winning_dev_reward': (best.get('reward') if best else None), + 'dev_speedup_trajectory': traj, + 'termination_reason': os.environ.get('REASON') or '', + 'note': 'dev_reward is an in-session proxy; meta.reward is the runner end-of-session score of /app/repo.', +} +(LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n') +PY + RESTORED_TREE="$(_snapshot_tree)" + echo "restored_tree=$RESTORED_TREE plant=$PLANTED" >> "$LOOP/finalize_apply.log" 2>/dev/null || true + if [ -n "$WIN_SUB" ] && [ "$PLANTED" != "none" ]; then + echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (planted via $PLANTED); the grader will now score /app/repo" + else + 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" + fi + exit 0 +fi + +# ------------------- submit ------------------- +CUR="$(_read_count)"; CUR="${CUR:-0}" +if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then + echo "submission $CUR/$MAX_SUBMISSIONS" + echo "budget exhausted — call 'bash /opt/loop/submit.sh --finalize' to grade your best submission" + echo "--- auto-finalizing best-of-$MAX_SUBMISSIONS ---" + exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling" +fi + +# Run the DEV engine on the LIVE /app/repo. +bash "$HERE/score_engine.sh" +engine_rc=$? + +# HARNESS error path: infra failure (rc=3 or a marker). Do NOT consume budget. +if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then + python3 "$HERE/sanitize_feedback.py" + exit 0 +fi + +NEXT=$((CUR + 1)) +echo "$NEXT" > "$COUNT_FILE" + +SNAP="$LOOP/submissions/$NEXT" +mkdir -p "$SNAP" +TREE="$(_snapshot_tree)" +git -C "$REPO" diff --binary HEAD > "$SNAP/candidate.diff" 2>/dev/null || true +echo "${TREE:-}" > "$SNAP/tree_hash.txt" +echo "${TREE:-}" > "$SNAP/tree.txt" +for f in verifier_state.json reward.json benchmark_results.json; do + [ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true +done + +NEXT="$NEXT" TREE="$TREE" python3 - <<'PY' +import json, os, time +from pathlib import Path +LOOP = Path('/logs/loop'); DEV = LOOP / 'dev' +k = int(os.environ['NEXT']); tree = os.environ.get('TREE') or '' +try: state = json.loads((DEV / 'verifier_state.json').read_text()) +except Exception: state = {} +try: reward = json.loads((DEV / 'reward.json').read_text()) +except Exception: reward = {} +corr_ok = bool(state.get('correctness_ok')) +r = float(reward.get('reward') or 0.0); s = float(reward.get('speedup') or 0.0) +row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok, + 'reward': r, 'speedup': s, 'tree': tree, + 'hard_fail_reasons': list(state.get('hard_fail_reasons') or [])} +with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f: + f.write(json.dumps(row) + '\n') +if corr_ok: + best_p = LOOP / 'best.json' + try: best = json.loads(best_p.read_text()) + except Exception: best = None + if best is None or r > float(best.get('reward') or -1.0): + best_p.write_text(json.dumps({'submission': k, 'reward': r, 'speedup': s, 'tree': tree, 'tree_hash': tree}, + indent=2, sort_keys=True) + '\n') +PY + +python3 "$HERE/sanitize_feedback.py" + +if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then + echo "" + echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---" + exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling" +fi + +exit 0 diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/repo/bench_counter.py b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/repo/bench_counter.py new file mode 100644 index 0000000000000000000000000000000000000000..05f2ebd0156db3a04277d062d5980caa085c1f9e --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/repo/bench_counter.py @@ -0,0 +1,78 @@ +"""Per-counter finalization for a microbenchmark harness. + +A microbenchmark records, for every benchmark case, a set of *user counters*. +Each counter carries a raw accumulated ``value`` plus a bitmask of ``flags`` that +describes how the raw value must be finalized once the run's ``iterations``, +``cpu_time`` (seconds) and ``num_threads`` are known. This mirrors Google +Benchmark's ``Finish`` (``src/counter.cc``) together with the flag semantics +declared in ``include/benchmark/counter.h``. + +``finalize_counters`` takes the whole counter table for a run -- ``B`` benchmarks +each with ``C`` counters -- and returns the finalized value of every counter. + +Contract (exactly Google Benchmark's ``Finish`` order; the transforms are applied +in this fixed sequence to each counter's raw value ``v``): + + * ``kIsRate`` (``1 << 0``): ``v /= cpu_time`` + * ``kAvgThreads`` (``1 << 1``): ``v /= num_threads`` + * ``kIsIterationInvariant``(``1 << 2``): ``v *= iterations`` + * ``kAvgIterations`` (``1 << 3``): ``v /= iterations`` + * ``kInvert`` (``1 << 31``): ``v = 1.0 / v`` -- applied *last*, always. + +``cpu_time``, ``num_threads`` and ``iterations`` are supplied per benchmark (one +value per row) and broadcast across that benchmark's counters. The result is a +``float64`` array of shape ``(B, C)``. +""" +# DEGRADED_BASELINE_SCALAR_LOOP: correct but slow reference finalization -- an +# explicit per-(benchmark, counter) Python loop that reads each raw value out of +# the numpy table one cell at a time and applies the five flag transforms with +# scalar Python branches. Behaviour-equivalent to the vectorized form; just slow. +import numpy as np + +kIsRate = 1 << 0 +kAvgThreads = 1 << 1 +kIsIterationInvariant = 1 << 2 +kAvgIterations = 1 << 3 +kInvert = 1 << 31 + + +def finalize_counters(values, flags, iterations, cpu_time, num_threads): + """Finalize a ``(B, C)`` counter table according to per-counter flags. + + :param values: array-like ``(B, C)`` -- raw accumulated counter values. + :param flags: array-like ``(B, C)`` of integer flag bitmasks. + :param iterations: array-like ``(B,)`` -- iteration count per benchmark. + :param cpu_time: array-like ``(B,)`` -- cpu time (seconds) per benchmark. + :param num_threads: array-like ``(B,)`` -- thread count per benchmark. + :returns: ``float64`` ``numpy.ndarray`` of shape ``(B, C)`` with each counter + finalized per the flag order in the module docstring. Inputs are not + mutated. + """ + vals = np.asarray(values, dtype=np.float64) + fl = np.asarray(flags, dtype=np.int64) + if vals.ndim != 2 or fl.shape != vals.shape: + raise ValueError("values and flags must both have shape (B, C)") + B, C = vals.shape + it = np.asarray(iterations, dtype=np.float64) + ct = np.asarray(cpu_time, dtype=np.float64) + nt = np.asarray(num_threads, dtype=np.float64) + out = np.empty((B, C), dtype=np.float64) + for b in range(B): + it_b = float(it[b]) + ct_b = float(ct[b]) + nt_b = float(nt[b]) + for c in range(C): + v = float(vals[b, c]) + f = int(fl[b, c]) + if f & kIsRate: + v = v / ct_b + if f & kAvgThreads: + v = v / nt_b + if f & kIsIterationInvariant: + v = v * it_b + if f & kAvgIterations: + v = v / it_b + if f & kInvert: + v = 1.0 / v + out[b, c] = v + return out diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/repo/gated_gelu.py b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/repo/gated_gelu.py new file mode 100644 index 0000000000000000000000000000000000000000..73b1ca790df94c1fcbfa7d45d377ae891fe17839 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/repo/gated_gelu.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +def gated_gelu(x: torch.Tensor, approximate: str = "none") -> torch.Tensor: + """Apply a gated GELU activation over the last dimension. + + The input's last dimension is split in half. GELU is applied to the first + half and multiplied by the second half. This straightforward implementation + intentionally relies on ordinary PyTorch tensor operations. + """ + if approximate not in ("none", "tanh"): + raise ValueError("approximate must be 'none' or 'tanh'") + if not x.is_cuda: + raise ValueError("x must be a CUDA tensor") + if x.dim() < 1: + raise ValueError("x must have at least one dimension") + if x.shape[-1] % 2 != 0: + raise ValueError("last dimension must be even") + d = x.shape[-1] // 2 + return F.gelu(x[..., :d], approximate=approximate) * x[..., d:] diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/entrypoint.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ad0137c7a85f94eeb880a755d3730bfbebf1e3a --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/entrypoint.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +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 + +if [ -x /app/timer.sh ]; then + /app/timer.sh >/app/.timer/timer.log 2>&1 & +fi + +if [ "$#" -gt 0 ]; then + exec "$@" +fi + +exec /bin/bash -l diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/run_dev_bench.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/run_dev_bench.sh new file mode 100644 index 0000000000000000000000000000000000000000..d627a61218d501ea69bdc3323afeb5284accd071 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/run_dev_bench.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +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 +KERNELBENCH_VERIFY_MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" bash /tests/test.sh diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/timer.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/timer.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3e45be674fb4a8218ca84d9cb4dc0f451395652 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/environment/runtime/timer.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +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 +mkdir -p /app/.timer +date -u +%FT%TZ > /app/.timer/start.txt +remaining=${FRONTIER_REMAINING_SECS:-21600} +printf '%s\n' "$remaining" > /app/.timer/remaining_secs +printf '%s\n' "$remaining" > /app/.timer/budget_secs +printf '%s\n' "$$" > /app/.timer/timer.pid +while true; do + sleep 60 +done diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/instruction.md b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85893bd60bbd48d76a8c70dc8d15256517a2161e --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/instruction.md @@ -0,0 +1,62 @@ +Optimize the per-counter finalization used by a microbenchmark harness. + +## Context + +A microbenchmark records, for every benchmark case, a set of user counters. Each +counter carries a raw accumulated value plus a bitmask of flags describing how the +raw value must be finalized once the run's `iterations`, `cpu_time` (seconds) and +`num_threads` are known. This mirrors Google Benchmark's `Finish` +(`src/counter.cc`) together with the flag semantics in +`include/benchmark/counter.h`. + +The scope file `/app/repo/bench_counter.py` implements +`finalize_counters(values, flags, iterations, cpu_time, num_threads)` over a whole +run's `(B, C)` counter table (`B` benchmarks, `C` counters). It is functionally +correct but slow: it walks every `(benchmark, counter)` cell in a Python loop, +reads each raw value out of the numpy table one element at a time, and applies the +five flag transforms with scalar Python branches. Once `B * C` grows, that +interpreted per-cell finalization dominates. + +## Task + +Make `finalize_counters` fast while keeping its behaviour **exactly**. Only edit +`/app/repo/bench_counter.py`. + +The behavioural contract (checked against an independent reference) — each +counter's raw value `v` is transformed in this FIXED order (per-benchmark +`cpu_time`, `num_threads`, `iterations` broadcast across that benchmark's +counters), returning a `float64` array of shape `(B, C)`: + + * `kIsRate` (`1 << 0`): `v /= cpu_time` + * `kAvgThreads` (`1 << 1`): `v /= num_threads` + * `kIsIterationInvariant` (`1 << 2`): `v *= iterations` + * `kAvgIterations` (`1 << 3`): `v /= iterations` + * `kInvert` (`1 << 31`): `v = 1.0 / v` — applied **last**, always. + +Inputs must not be mutated. The expected direction is to replace the per-cell +Python loop with vectorized array operations — boolean masks built from the flag +bits plus `numpy.where` for each transform, with the per-benchmark scalars +broadcast across the counter axis. The order of the transforms (in particular that +the inversion is applied last) must be preserved exactly. + +## How you are scored + +You get **exactly one** graded submission (`bash /opt/loop/submit.sh`) — submitting ends the task +and a second call is refused. The reward is a log-curve function of the wall-clock **speedup** of +the benchmark workload against the frozen slow baseline that ships in this repository, in `[0, 1]`: +matching the reference (oracle) implementation's speed scores **0.5**, being as far past it again +as it is past the baseline caps the reward at **1.0**, and merely matching the baseline scores +**0.0**. It is **gated on exact correctness** — a single mismatched finalized value scores 0 +regardless of speed. Think the change through and self-test before you submit; you cannot iterate. + +## Anti-cheat red line (A-only) + +Reading or tampering with the verifier/scoring assets, reproducing or importing +the hidden harness, fetching the upstream repository/reference implementation, or +bypassing the runtime network isolation — any of these makes the WHOLE task score +zero. Solve it by editing the scope file only. + +## 提交方式 + +本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。 +改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。 diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/pre_artifacts.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..89d37f52c78ccfb3bca1a30cac77043d6386a742 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/pre_artifacts.sh @@ -0,0 +1,163 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/wro-gbench-counter-finalize-loop16 +# +# Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE +# grading (spec §1.1). It turns whatever the agent left behind into a portable artifact: +# +# /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit +# /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line +# +# 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one +# place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs ..HEAD). +# Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate, +# `git checkout -q HEAD -- ` re-materialises the baseline for the paired timing, +# and loop16's `submit.sh --finalize` plants the best iterate with read-tree + +# checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope +# gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the +# "baseline" — and a correct solve scores 0. +# `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages +# names only, writes no tree, creates no commit and leaves HEAD exactly where it was. +# +# EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier +# scores the container on its own terms and gives 0 by itself. +# +# READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index +# (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the +# verifier — which runs after us — sees exactly the `git status --porcelain` it would have +# seen if this script had never run. No commit, no HEAD move, no working-tree write. +# +# CAPTURE ROOTS for THIS task — derived from the package, never assumed: +# /app/repo git repo, HEAD == the 1-commit carved baseline +# evidence Dockerfile:124: WORKDIR /app/repo +# evidence Dockerfile:77: && cd /app/repo \ +# evidence Dockerfile:84: && test "$(git rev-list --count HEAD)" = "1" \ +# evidence test.sh:15: export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +# evidence test.sh:18: REPO=/app/repo +# +# Single root => model.patch is a bare `git diff --binary ` (no banner). +# model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable +# by one reader. +# +# loop16 task (environment/loop/ -> /opt/loop in the image): the harness auto-finalizes +# at k=16 and `submit.sh --finalize` plants the best iterate in the WORKING TREE while +# HEAD stays on the baked baseline — which is exactly what this script captures. Running +# it after a finalize therefore yields the GRADED artifact, not the last raw edit. +# ============================================================================ +set -uo pipefail + +OUT=/logs/artifacts +PATCH="$OUT/model.patch" +LIST="$OUT/model_files.txt" +MULTI=0 # 1 => several capture roots => each diff gets a banner line +MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane) + +mkdir -p "$OUT" 2>/dev/null || true +: > "$PATCH" 2>/dev/null || true +: > "$LIST" 2>/dev/null || true +git config --global --add safe.directory '*' >/dev/null 2>&1 || true + +banner() { # $1=root $2=mode ; only when there is more than one root + if [ "$MULTI" = 1 ]; then + printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null + fi + return 0 +} + +list_add() { # stdin: paths relative to $1 -> absolute, one per line + sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true + return 0 +} + +capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot" + capture_tree "$root" + return 0 + fi + # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and + # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could + # flip a scope gate either way. So copy the repo's index aside and stage into the COPY — + # the repo's own .git/index is byte-identical when we are done. + tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi="" + gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true) + if [ -z "$gd" ]; then + gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true) + case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac + fi + if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then + GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE + else + echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index" + fi + git -C "$root" add -AN . >/dev/null 2>&1 || true + base=HEAD + if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then + base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null) + echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree" + else + n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0) + case "$n" in ''|*[!0-9]*) n=0 ;; esac + if [ "$n" -gt 1 ]; then + base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1) + echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:" + echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so" + echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved" + echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve." + fi + fi + [ -n "${base:-}" ] || base=HEAD + banner "$root" "git-diff-vs-baseline" + git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true + names=$(git -C "$root" diff --name-only "$base" 2>/dev/null) + echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)" + unset GIT_INDEX_FILE + [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null + printf '%s\n' "$names" | grep -v '^$' | list_add "$root" + return 0 +} + +capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0 + if git init -q "$tmp/snap" >/dev/null 2>&1; then + GD="$tmp/snap/.git" + empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null) + ( cd "$root" 2>/dev/null || exit 0 + find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \ + 2>/dev/null \ + | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true + banner "$root" "tree-snapshot-not-a-git-repo" + GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \ + >> "$PATCH" 2>/dev/null || true + else + echo "[pre_artifacts] WARN could not stage a snapshot index for $root" + fi + rm -rf "$tmp" 2>/dev/null || true + all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f -print 2>/dev/null | sed 's|^\./||' ) + printf '%s\n' "$all" | grep -v '^$' | list_add "$root" + big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \ + -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . ) + echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)" + if [ "${big:-0}" != 0 ]; then + echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in" + echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch." + fi + return 0 +} + +capture_git "/app/repo" +bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0) +case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac +echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)" +if [ "$bytes" -gt 67108864 ]; then + echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build" + echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also" + echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish." +fi +exit 0 diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/README.md b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c09609e11373349d76e812054074d77c471ddb04 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/README.md @@ -0,0 +1,18 @@ +# solution/ — 参考实现(不参与判分) + +本目录里的补丁**不进镜像**(已被上下文根的 `.dockerignore` 排除)、**判分不运行**, +只在两种场合用: + +1. **重标定锚点**(换硬件后):见 `../tests/ref_speedup.caveat.md` + ``` + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch + ``` +2. **自证起始树**:`git apply --check -p1 oracle.patch` 必须能干净打在 + `../environment/repo/` 上(正向可、反向不可)。这证明 `../environment/repo/` 就是 + 被计分的、**已被降级的起始实现**,而 oracle 补丁正是把它恢复成参考实现的那一步。 + +| 文件 | 用途 | +|---|---| +| `baseline2.patch` | 中间基线(正确但朴素),用于交叉核对 | +| `negative.patch` | 已知坏例,**必须得 0** | +| `oracle.patch` | oracle 参考实现补丁,用于标定锚点(打平锚点 = reward 0.5) | diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/baseline2.patch b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/baseline2.patch new file mode 100644 index 0000000000000000000000000000000000000000..07a0996a16eb805862efbbd619970b858f502c85 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/baseline2.patch @@ -0,0 +1,60 @@ +diff --git a/bench_counter.py b/bench_counter.py +index 05f2ebd..a56ce6f 100644 +--- a/bench_counter.py ++++ b/bench_counter.py +@@ -23,10 +23,6 @@ in this fixed sequence to each counter's raw value ``v``): + value per row) and broadcast across that benchmark's counters. The result is a + ``float64`` array of shape ``(B, C)``. + """ +-# DEGRADED_BASELINE_SCALAR_LOOP: correct but slow reference finalization -- an +-# explicit per-(benchmark, counter) Python loop that reads each raw value out of +-# the numpy table one cell at a time and applies the five flag transforms with +-# scalar Python branches. Behaviour-equivalent to the vectorized form; just slow. + import numpy as np + + kIsRate = 1 << 0 +@@ -53,26 +49,21 @@ def finalize_counters(values, flags, iterations, cpu_time, num_threads): + if vals.ndim != 2 or fl.shape != vals.shape: + raise ValueError("values and flags must both have shape (B, C)") + B, C = vals.shape +- it = np.asarray(iterations, dtype=np.float64) +- ct = np.asarray(cpu_time, dtype=np.float64) +- nt = np.asarray(num_threads, dtype=np.float64) +- out = np.empty((B, C), dtype=np.float64) +- for b in range(B): +- it_b = float(it[b]) +- ct_b = float(ct[b]) +- nt_b = float(nt[b]) +- for c in range(C): +- v = float(vals[b, c]) +- f = int(fl[b, c]) +- if f & kIsRate: +- v = v / ct_b +- if f & kAvgThreads: +- v = v / nt_b +- if f & kIsIterationInvariant: +- v = v * it_b +- if f & kAvgIterations: +- v = v / it_b +- if f & kInvert: +- v = 1.0 / v +- out[b, c] = v +- return out ++ it = np.asarray(iterations, dtype=np.float64).reshape(-1, 1) ++ ct = np.asarray(cpu_time, dtype=np.float64).reshape(-1, 1) ++ nt = np.asarray(num_threads, dtype=np.float64).reshape(-1, 1) ++ # The four scaling transforms are vectorized across the whole table, but the ++ # final inversion is resolved with an explicit Python loop over the flattened ++ # table instead of a vectorized mask -- correct, and between the fully-scalar ++ # and fully-vectorized forms in speed. ++ v = vals.copy() ++ v = np.where((fl & kIsRate) != 0, v / ct, v) ++ v = np.where((fl & kAvgThreads) != 0, v / nt, v) ++ v = np.where((fl & kIsIterationInvariant) != 0, v * it, v) ++ v = np.where((fl & kAvgIterations) != 0, v / it, v) ++ flat = v.ravel().tolist() ++ fflat = fl.ravel().tolist() ++ for i in range(len(flat)): ++ if fflat[i] & kInvert: ++ flat[i] = 1.0 / flat[i] ++ return np.array(flat, dtype=np.float64).reshape(B, C) diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/negative.patch b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/negative.patch new file mode 100644 index 0000000000000000000000000000000000000000..ee6d6e81508e94bb92f01d1fa65d5e5833a2be09 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/negative.patch @@ -0,0 +1,71 @@ +diff --git a/bench_counter.py b/bench_counter.py +index 05f2ebd..d48eb6e 100644 +--- a/bench_counter.py ++++ b/bench_counter.py +@@ -23,10 +23,6 @@ in this fixed sequence to each counter's raw value ``v``): + value per row) and broadcast across that benchmark's counters. The result is a + ``float64`` array of shape ``(B, C)``. + """ +-# DEGRADED_BASELINE_SCALAR_LOOP: correct but slow reference finalization -- an +-# explicit per-(benchmark, counter) Python loop that reads each raw value out of +-# the numpy table one cell at a time and applies the five flag transforms with +-# scalar Python branches. Behaviour-equivalent to the vectorized form; just slow. + import numpy as np + + kIsRate = 1 << 0 +@@ -44,35 +40,28 @@ def finalize_counters(values, flags, iterations, cpu_time, num_threads): + :param iterations: array-like ``(B,)`` -- iteration count per benchmark. + :param cpu_time: array-like ``(B,)`` -- cpu time (seconds) per benchmark. + :param num_threads: array-like ``(B,)`` -- thread count per benchmark. +- :returns: ``float64`` ``numpy.ndarray`` of shape ``(B, C)`` with each counter +- finalized per the flag order in the module docstring. Inputs are not +- mutated. ++ :returns: ``float64`` ``numpy.ndarray`` of shape ``(B, C)``. + """ + vals = np.asarray(values, dtype=np.float64) + fl = np.asarray(flags, dtype=np.int64) + if vals.ndim != 2 or fl.shape != vals.shape: + raise ValueError("values and flags must both have shape (B, C)") +- B, C = vals.shape +- it = np.asarray(iterations, dtype=np.float64) +- ct = np.asarray(cpu_time, dtype=np.float64) +- nt = np.asarray(num_threads, dtype=np.float64) +- out = np.empty((B, C), dtype=np.float64) +- for b in range(B): +- it_b = float(it[b]) +- ct_b = float(ct[b]) +- nt_b = float(nt[b]) +- for c in range(C): +- v = float(vals[b, c]) +- f = int(fl[b, c]) +- if f & kIsRate: +- v = v / ct_b +- if f & kAvgThreads: +- v = v / nt_b +- if f & kIsIterationInvariant: +- v = v * it_b +- if f & kAvgIterations: +- v = v / it_b +- if f & kInvert: +- v = 1.0 / v +- out[b, c] = v +- return out ++ it = np.asarray(iterations, dtype=np.float64).reshape(-1, 1) ++ ct = np.asarray(cpu_time, dtype=np.float64).reshape(-1, 1) ++ nt = np.asarray(num_threads, dtype=np.float64).reshape(-1, 1) ++ v = vals.copy() ++ is_rate = (fl & kIsRate) != 0 ++ is_avg_threads = (fl & kAvgThreads) != 0 ++ is_iter_inv = (fl & kIsIterationInvariant) != 0 ++ is_avg_iters = (fl & kAvgIterations) != 0 ++ is_invert = (fl & kInvert) != 0 ++ # incorrect: applies the inversion FIRST instead of last. Google Benchmark's ++ # Finish documents "Invert is *always* last"; doing it before the rate / ++ # thread / iteration transforms yields a different value for any counter whose ++ # flags combine kInvert with another transform. ++ v = np.where(is_invert, 1.0 / np.where(v == 0.0, 1.0, v), v) ++ v = np.where(is_rate, v / ct, v) ++ v = np.where(is_avg_threads, v / nt, v) ++ v = np.where(is_iter_inv, v * it, v) ++ v = np.where(is_avg_iters, v / it, v) ++ return v diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/oracle.patch b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8fdc0a0aadf94a97beaa58894f9ab030ac04c03e --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/oracle.patch @@ -0,0 +1,60 @@ +diff --git a/bench_counter.py b/bench_counter.py +index 05f2ebd..a176022 100644 +--- a/bench_counter.py ++++ b/bench_counter.py +@@ -23,10 +23,6 @@ in this fixed sequence to each counter's raw value ``v``): + value per row) and broadcast across that benchmark's counters. The result is a + ``float64`` array of shape ``(B, C)``. + """ +-# DEGRADED_BASELINE_SCALAR_LOOP: correct but slow reference finalization -- an +-# explicit per-(benchmark, counter) Python loop that reads each raw value out of +-# the numpy table one cell at a time and applies the five flag transforms with +-# scalar Python branches. Behaviour-equivalent to the vectorized form; just slow. + import numpy as np + + kIsRate = 1 << 0 +@@ -52,27 +48,20 @@ def finalize_counters(values, flags, iterations, cpu_time, num_threads): + fl = np.asarray(flags, dtype=np.int64) + if vals.ndim != 2 or fl.shape != vals.shape: + raise ValueError("values and flags must both have shape (B, C)") +- B, C = vals.shape +- it = np.asarray(iterations, dtype=np.float64) +- ct = np.asarray(cpu_time, dtype=np.float64) +- nt = np.asarray(num_threads, dtype=np.float64) +- out = np.empty((B, C), dtype=np.float64) +- for b in range(B): +- it_b = float(it[b]) +- ct_b = float(ct[b]) +- nt_b = float(nt[b]) +- for c in range(C): +- v = float(vals[b, c]) +- f = int(fl[b, c]) +- if f & kIsRate: +- v = v / ct_b +- if f & kAvgThreads: +- v = v / nt_b +- if f & kIsIterationInvariant: +- v = v * it_b +- if f & kAvgIterations: +- v = v / it_b +- if f & kInvert: +- v = 1.0 / v +- out[b, c] = v +- return out ++ it = np.asarray(iterations, dtype=np.float64).reshape(-1, 1) ++ ct = np.asarray(cpu_time, dtype=np.float64).reshape(-1, 1) ++ nt = np.asarray(num_threads, dtype=np.float64).reshape(-1, 1) ++ v = vals.copy() ++ # Boolean masks for each flag bit, broadcast across the counter axis. ++ is_rate = (fl & kIsRate) != 0 ++ is_avg_threads = (fl & kAvgThreads) != 0 ++ is_iter_inv = (fl & kIsIterationInvariant) != 0 ++ is_avg_iters = (fl & kAvgIterations) != 0 ++ is_invert = (fl & kInvert) != 0 ++ # Same fixed order as the scalar Finish; the per-benchmark scalars broadcast. ++ v = np.where(is_rate, v / ct, v) ++ v = np.where(is_avg_threads, v / nt, v) ++ v = np.where(is_iter_inv, v * it, v) ++ v = np.where(is_avg_iters, v / it, v) ++ v = np.where(is_invert, 1.0 / np.where(v == 0.0, 1.0, v), v) ++ return v diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/solve.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c2cfa833312fd38fce7c96e3344a84811d426aaf --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/solution/solve.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/wro-gbench-counter-finalize-loop16 +# 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量 +# 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。 +# +# oracle 形态 : 补丁式(patch)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_PATCH 槽位: +# git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" +# 产物(reviewer-only;本脚本只读,一个字节都不改): +# solution/baseline2.patch, solution/negative.patch, solution/oracle.patch +# $REPO : /app/repo (tests/test.sh: REPO=/app/repo) +# 被计分单元 : /app/repo/bench_counter.py +# 来源:tests/test.sh 的 SCOPE=("bench_counter.py") +# 落地方式 : git -C $REPO apply -p1 —— 只改工作树,不 commit +# +# 🔴 为什么绝不 commit(规范 H3):判分读**工作树** —— `git status --porcelain` 是 scope +# 硬闸门,`git checkout -q HEAD -- ` 取基线,且镜像自证 /app/repo 的 HEAD 恰好 +# 只有 1 个 commit(那就是挖洞基线)。一旦 commit,HEAD 前移 → 闸门看不到改动、 +# `checkout HEAD -- scope` 把 candidate 当成基线 → 正确解被判 0。 +# 本脚本落地后会自己断言 HEAD 与 commit 数没变。 +# +# ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)──────────────────────── +# PKG=/tasks/kfc/wro-gbench-counter-finalize-loop16/task +# IMG=fai/kfc-wro-gbench-counter-finalize-loop16:oss +# # 1) 起容器。判分容器始终 --network=none;tests/ 和 solution/ 都**没有**烤进镜像 +# # (Dockerfile 里没有一条 COPY 取它们),所以这两个目录必须挂进来。 +# # 该题 task.toml 声明 gpus=0;锚点的标定硬件/运行栈见 tests/ref_speedup.caveat.md +# docker run -d --name kfc-solve --network=none \ +# -v "$PKG/tests":/tests -v "$PKG/solution":/solution "$IMG" +# # 2) 落地参考实现到工作树(本脚本;不 commit) +# docker exec kfc-solve bash /solution/solve.sh +# # 3) 判分。KERNELBENCH_VERIFY_MODE 必须留在默认的 candidate —— 这就是 agent 的 +# # 真实评分路径;设成 oracle/negative 会让 test.sh 自己再落地一遍,绕过本脚本。 +# docker exec -e KERNELBENCH_VERIFY_MODE=candidate kfc-solve bash /tests/test.sh +# docker exec kfc-solve cat /logs/verifier/reward.json # 判分结果 +# docker rm -f kfc-solve +# +# 期望:oracle → 性能题得 0(它就是锚点本身; min(1, ln(speedup/ref_speedup)/ln(ref_speedup))(speedup ≤ ref_speedup 时为 0) +# 在 speedup≈ref_speedup 处 = 0 —— 打平 oracle 不得分,必须超过。 +# 所以"oracle 跑对了"的判据不是 reward>0,而是 speedup≈ref_speedup 且 +# hard_fail_reasons 为空;实现类二值题 = 1.0 —— 权威公式是 +# tests/test.sh 写出的 reward_formula 字段);--negative → 0; +# --noop(在纯净容器里)→ 0(挖洞基线过不了正确性门)。 +# 本题带 loop16 harness:`bash /opt/loop/submit.sh` 判的也是同一棵工作树、 +# 同样走 candidate 模式(口径一致),所以落地后直接自评也成立。 +# ────────────────────────────────────────────────────────────────────────── +# +# 用法(规范 2 的统一 CLI): +# bash solution/solve.sh # 落地 oracle(参考实现) +# bash solution/solve.sh --negative # 落地 negative(已知坏例,必须得 0) +# bash solution/solve.sh --baseline2 # 落地 baseline2(中间基线) +# bash solution/solve.sh --noop # 把可编辑面复位到烤入基线(对照组) +# +# --noop 语义:把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— +# `git checkout HEAD -- `,HEAD 不动),使对照组能量到真正的 no-op 值。 +# runner 在同一个容器里连着跑 oracle → noop 做对照时,靠它把上一轮落地归零。 +# +# 幂等:每次落地前先把被计分单元 `git checkout HEAD --` 复位,重复执行结果一致。 +# 失败一律非 0 退出并打印原因(补丁打不上 / 变体文件缺失 / scope 路径不存在 / HEAD 被移动)。 +set -uo pipefail + +TASK_ID="wro-gbench-counter-finalize-loop16" +REPO="${KFC_REPO_DIR:-/app/repo}" +SCOPE=("bench_counter.py") +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; } +die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; } +# 每次调用单独带 safe.directory,不去改容器里的全局 gitconfig +GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; } + +usage(){ cat <<'USAGE' +usage: bash solve.sh [--oracle | --negative | --baseline2 | --noop] + (无参数) 落地 oracle 参考实现(oracle.patch) + --negative 落地 negative 已知坏例(negative.patch) + --baseline2 落地 baseline2 中间基线(baseline2.patch) + --noop 把可编辑面复位到烤入基线(与 verifier 取基线一致,HEAD 不动) +USAGE +} + +WHICH=oracle +case "${1:-}" in + ""|--oracle) WHICH=oracle ;; + --negative) WHICH=negative ;; + --baseline2) WHICH=baseline2 ;; + --noop) WHICH=noop ;; + -h|--help) usage; exit 0 ;; + *) usage >&2; die "未知参数 '$1'" ;; +esac + +# ---- 产物定位:脚本同目录优先,其次容器里的常见挂载点 ---- +artifact(){ + local n="$1" c + for c in "$HERE/$n" "/solution/$n" "${KFC_SOLUTION_DIR:-/nonexistent}/$n"; do + [ -f "$c" ] && { printf '%s\n' "$c"; return 0; } + done + return 1 +} + +case "$WHICH" in + noop) ART="" ;; + oracle) ART="oracle.patch" ;; + negative) ART="negative.patch" ;; + baseline2) ART="baseline2.patch" ;; + *) die "本题没有 $WHICH 变体(solution/ 里只有:oracle.patch, negative.patch, baseline2.patch)" ;; +esac + +# ---- 环境前置检查 ---- +GIT rev-parse --git-dir >/dev/null 2>&1 \ + || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)" +for s in "${SCOPE[@]}"; do + [ -e "$REPO/$s" ] || die "被计分单元不存在:$REPO/$s(REPO 不对?可用 KFC_REPO_DIR 覆盖)" +done +HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD" +N_BEFORE="$(GIT rev-list --count HEAD)" + +if [ "$WHICH" = noop ]; then + # --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— `git checkout HEAD -- `, + # HEAD 不动),使对照组能量到真正的 no-op 值。runner 在同一个容器里连着跑 oracle → noop 时靠它归零。 + DIRTY_BEFORE="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" + DIRTY_AFTER="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + if [ -n "$DIRTY_AFTER" ]; then + printf '%s\n' "$DIRTY_AFTER" | sed "s|^|[solve.sh $TASK_ID] |" >&2 + die "复位后被计分单元仍不干净(见上)—— 量不到真正的 no-op 值" + fi + [ "$HEAD_BEFORE" = "$(GIT rev-parse HEAD)" ] || die "HEAD 被移动了,判分会把 candidate 当基线" + [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + if [ -n "$DIRTY_BEFORE" ]; then + say "--noop:已把可编辑面复位到烤入基线;原先这些是脏的:" + printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |" + else + say "--noop:可编辑面本来就是干净的烤入基线,无需复位" + fi + say "--noop 完成:${SCOPE[*]} = 烤入基线(HEAD 未动 @ ${HEAD_BEFORE:0:12})" + exit 0 +fi + +PATCH="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)" + +# ---- 幂等:先把被计分单元退回挖洞基线,再打补丁(否则二次 apply 必然失败) ---- +GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" +GIT apply -p1 --check "$PATCH" \ + || die "补丁打不上:$PATCH —— 挖洞树与该补丁不匹配,或工作树被别的改动污染了" +GIT apply -p1 "$PATCH" || die "git apply 失败:$PATCH" + +# ---- 硬要求:HEAD 一步都不能动(规范 H3) ---- +HEAD_AFTER="$(GIT rev-parse HEAD)" +[ "$HEAD_BEFORE" = "$HEAD_AFTER" ] || die "HEAD 被移动了($HEAD_BEFORE -> $HEAD_AFTER),判分会把 candidate 当基线" +[ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + +say "已落地 $WHICH:$(basename "$PATCH") -> ${SCOPE[*]}(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})" +GIT status --porcelain -- "${SCOPE[@]}" | sed "s|^|[solve.sh $TASK_ID] |" + +# ---- 顺手体检 scope 闸门:工作树里除了被计分单元不该有别的改动 ---- +STRAY="$(GIT status --porcelain | awk '{print $NF}' \ + | grep -v -e '__pycache__' -e '\.pyc$' -e '^bench_counter\.py$' || true)" +[ -z "$STRAY" ] || { say "⚠ 工作树里还有 scope 外的改动,判分会 out_of_scope_edit 直接归 0:"; \ + printf '%s\n' "$STRAY" | sed "s|^|[solve.sh $TASK_ID] |"; } +exit 0 diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/task.toml b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6f55a31e8d60c3ebb3cf2f50fbbff1f31a89997a --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/task.toml @@ -0,0 +1,49 @@ +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "wro-gbench-counter-finalize-loop16" +bench = "kfc" +kind = "performance" +language = "python" +title = "Optimize the per-counter finalization used by a microbenchmark harness." +instruction = "instruction.md" + +[agent] +timeout_sec = 5400 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/wro-gbench-counter-finalize-loop16:v1@sha256:7f71f99f698f361a10d263c0289848804a2db5be62f6fcb796af6f51912d18f2 +# Open-source build: `cd && docker build -f environment/Dockerfile -t fai/kfc-wro-gbench-counter-finalize-loop16:oss .` +[environment] +docker_image = "fai/kfc-wro-gbench-counter-finalize-loop16:oss" +dockerfile = "environment/Dockerfile" +build_timeout_sec = 3600 +cpus = 8 +memory_mb = 32768 +gpus = 0 +allow_internet = false + +[verifier] +entrypoint = "tests/test.sh" +mode = "shared" +primary_edit_paths = ["bench_counter.py"] +result_paths = ["/logs/verifier/reward.json"] + +[primary_metric] +name = "reward" +goal = "maximize" +reward_formula = "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0" +reward_note = "reward = 0 on any hard gate, on speedup<=1, or on ref_speedup<=1; range [0,1]" +reward_reference = "/opt/verifier-correctness-manifest.json ref_speedup, fallback tests/ref_speedup.txt (oracle speedup over the frozen degraded baseline)" +ref_speedup = 15.127159 +ref_speedup_source = "tests/ref_speedup.txt" +calibrated_on = "Intel Sapphire Rapids CPU lane" + +[loop] +# NOTE: the /opt/loop harness baked into the image applies its own 3/16 in-session budget; for in-session loop scoring the image is authoritative. +min_submissions = 1 +max_submissions = 1 +submit = "bash /opt/loop/submit.sh" +declared_submission_policy = "single_submission" # submit == finalize; the 2nd call is refused diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/compute_reward.py b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fb83e197b747eb61f654a4ce631c735bf91a5997 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/compute_reward.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""compute_reward for wro-gbench-counter-finalize-loop16 — standalone reward helper. + +reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + speedup = baseline_ms / candidate_ms (absolute, vs the frozen degraded baseline) + matching the oracle -> 0.5 ; oracle^2 -> 1.0 cap ; at/below the baseline -> 0.0 + value range strictly [0.0, 1.0] + +HARD pre-gates (any one hit => reward 0, formula NOT entered): the correctness gate in test.sh +(a candidate that fails parity scores 0 there), speedup <= 1, ref_speedup <= 1, bad timings. + +usage: compute_reward.py [ref_speedup] +NOTE: the authoritative verdict is the one test.sh writes to /logs/verifier/reward.json; this +helper exists so the lane's reward definition is reproducible standalone. +""" +import json, math, os, sys + +TOKEN = "WRO_CNT_RESULT " + + +def load(path): + with open(path) as f: + for line in f: + if line.startswith(TOKEN): + return json.loads(line[len(TOKEN):]) + raise SystemExit(f"no {TOKEN.strip()} in {path}") + + +def read_ref(argv): + if len(argv) > 3: + try: + return float(argv[3]) + except Exception: + pass + here = os.path.dirname(os.path.abspath(__file__)) + for p in ("/opt/verifier-correctness-manifest.json",): + try: + v = float(json.load(open(p)).get("ref_speedup", 0) or 0) + if v > 1.0: + return v + except Exception: + pass + try: + return float(open(os.path.join(here, "ref_speedup.txt")).read().strip()) + except Exception: + return 0.0 + + +def log_reward(speedup, ref): + """min(1.0, ln(speedup/ref)/ln(ref)) if speedup > ref else 0.0 clamped to [0,1]; 0 unless speedup>1 and ref>1.""" + if not (math.isfinite(speedup) and math.isfinite(ref)) or speedup <= 1.0 or ref <= 1.0: + return 0.0 + return max(0.0, min(1.0, max(0.0, min(1.0, math.log(speedup) / math.log(ref) - 1.0)))) + + +def main(): + cand = load(sys.argv[1]) + arg2 = sys.argv[2] if len(sys.argv) > 2 else "-1" + try: + base_ms = float(arg2) + except ValueError: + base_ms = float(load(arg2).get("timing_ms", -1)) + cand_ms = float(cand.get("timing_ms", -1)) + ref = read_ref(sys.argv) + speedup = (base_ms / cand_ms) if (cand_ms > 0 and base_ms > 0) else 0.0 + + hard = [] + if not (cand_ms > 0 and base_ms > 0): + hard.append("timing_invalid") + if not math.isfinite(ref) or ref <= 1.0: + hard.append("ref_speedup_invalid") + if not math.isfinite(speedup) or speedup <= 1.0: + hard.append("speedup_not_above_baseline") + reward = 0.0 if hard else log_reward(speedup, ref) + + print(json.dumps({ + "task_type": "performance", + "reward": round(reward, 6), + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0", + "hard_fail_reasons": hard, + "speedup": round(speedup, 6), + "ref_speedup": ref, + "cv": {}, + "baseline_ms": round(base_ms, 4), + "candidate_ms": round(cand_ms, 4), + })) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup.caveat.md b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..656b36c217a0f3a5388faa4a0b0d35bc7586099b --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +`ref_speedup.txt` 里的 **15.127159** 是 oracle 标定常量,判分时只读、不重跑 oracle: + + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + +`tests/test.sh` 的解析顺序是 **`tests/ref_speedup.txt` → `/opt/verifier-correctness-manifest.json` → 1.0**; +回落到 1.0 会让所有 reward 归 0,所以这个文件必须存在且 > 1。 + +## 标定条件 + +- 硬件:**the authoring CPU lane (Intel Sapphire Rapids)** +- 运行栈:`torch 2.7.0`(原始私有基座声明 torch 2.5.1/triton 3.1.0,任务 overlay 又 `pip install torch==2.7.0`,锚点即在 2.7.0 下标定) +- 线程:`OMP/MKL/OPENBLAS_NUM_THREADS=1`(计时稳定性的一部分,已写进镜像 ENV) + +## 硬件不一致时如何重标 + +verifier 原生支持模式分派,参考实现**按路径传入、从不烤进镜像**: + +```bash +docker run --rm -v "$PWD/tests:/tests:ro" -v "<放 oracle.patch 的目录>:/patches:ro" \ + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ + fai/kfc-wro-gbench-counter-finalize-loop16:oss bash /tests/test.sh +# 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt +``` + +自证:`noop`(不打补丁)应 ≈1.0 → 被门到 0;`negative`(`KERNELBENCH_NEGATIVE_PATCH=`)必须 0。 + +✅ 本题**随包提供**参考实现 `solution/oracle.patch`,所以重标定通路是**可直接执行**的。 diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup.txt b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..582471c7524bfb62098ce080f4f1f6ece2be8677 --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup.txt @@ -0,0 +1 @@ +15.127159 diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup_provenance.json b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup_provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ec04fd62e3f35f2a7373232f2ded5abdfa4d638a --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/ref_speedup_provenance.json @@ -0,0 +1,6 @@ +{ + "ref_speedup": 15.127159, + "derivation": "oracle-mode / expected-score ratio from the recorded 4-mode validation (recorded 4-mode validation anchor)", + "meaning": "the ORACLE speedup over the frozen degraded baseline; the ref_speedup anchor", + "precedence": "test.sh prefers the in-image /opt/verifier-correctness-manifest.json ref_speedup; this file is the tests/-local fallback when that key is absent" +} diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/test.sh b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6933a08984225d41566afe550215bbbce554fa2f --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/test.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# Verifier for wro-gbench-counter-finalize (microbenchmark per-counter finalization: +# flag-driven rate/avg-threads/iteration-invariant/avg-iterations/invert-last scaling +# over a (B,C) counter table, modelled on Google Benchmark's Finish, src/counter.cc + +# include/benchmark/counter.h). +# ACCELERATION, CPU (host logic; no GPU). Scope = bench_counter.py (finalize_counters). +# Modes: candidate | noop | oracle | negative | baseline2. +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 over the wall speedup base_ms/cand_ms +# oracle -> 0.5, ref_speedup^2 -> 1.0 cap, noop (~1.0 speedup) -> 0; +# baseline2 in between +# (per-benchmark loop, counters vectorized); negative = 0 (inverts out of order -> wrong +# finalized values for kInvert-combined counters). +set -uo pipefail +export PATH="/opt/kernelbench-venv/bin:/opt/venv/bin:/usr/local/bin:$PATH" +export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +git config --global --add safe.directory '*' 2>/dev/null || true +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/verifier; mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +SCOPE=("bench_counter.py") + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true +speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1 + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +# ---- apply oracle / baseline2 / negative patch by mode (candidate & noop: no patch) ---- +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"; fi +if [ "$MODE" = "baseline2" ] && [ -n "${KERNELBENCH_BASELINE2_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_BASELINE2_PATCH" 2>"$LOG/baseline2_apply.log" || add_hard "baseline2_apply_failed"; fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true; fi + +# ---- (1) scope-diff HARD GATE: only the scope file may change in /app/repo ---- +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + keep=false + for s in "${SCOPE[@]}"; do [ "$f" = "$s" ] && keep=true; done + case "$f" in *__pycache__*|*.pyc) keep=true;; esac + [ "$keep" = true ] || { scope_ok=false; add_hard "out_of_scope_edit:$f"; } +done < "$LOG/changed_files.txt" + +# ---- (2) import-origin assert: the scope module resolves to the baked /app/repo tree ---- +python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import os, sys +sys.path.insert(0, "/app/repo") +import bench_counter as m +loc = os.path.realpath(m.__file__) +print("SCOPE_LOC", loc) +sys.exit(0 if loc.startswith("/app/repo") else 3) +PY +[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; } + +# ---- (3) trusted-restore: harness uploaded fresh (never baked) ---- +for f in workload.py compute_reward.py; do + [ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; } +done + +# ---- ref_speedup: the ORACLE's speedup over the frozen degraded baseline. +# This is the reward anchor: reward = min(1, ln(speedup/ref_speedup)/ln(ref_speedup)). +# The in-image manifest wins; tests/ref_speedup.txt is the uploaded-fresh fallback. +[ -f /opt/verifier-correctness-manifest.json ] && \ + 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) +if [ "$(python3 -c "print(1 if float('${ref_speedup:-1}')<=1.0 else 0)" 2>/dev/null || echo 1)" = "1" ] && [ -f "$TESTS_DIR/ref_speedup.txt" ]; then + ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt") +fi +ref_speedup=${ref_speedup:-1.0} + +# ---- (4) CORRECTNESS GATE: scope output must match the independent reference ---- +if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1 + cok=$(grep WRO_CNT_RESULT "$LOG/correctness.out" | python3 -c "import json,sys +try: print(json.loads(sys.stdin.read().split('WRO_CNT_RESULT ',1)[1]).get('correctness_ok')) +except Exception: print('False')" 2>/dev/null || echo False) + if [ "$cok" != "True" ]; then correctness_ok=false; add_hard "correctness_failed"; fi +fi + +# ---- (5) TIMING: candidate wall + baseline (frozen degraded tree at HEAD) ---- +if [ "$correctness_ok" = true ] && { [ "${#HARD[@]}" -eq 0 ] || [ -z "${HARD[*]:-}" ]; }; then + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed" + cand_ms=$(grep WRO_CNT_RESULT "$LOG/cand_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_CNT_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1) + cp "$REPO/${SCOPE[0]}" /tmp/wro_cand_scope.py 2>/dev/null || true + git -C "$REPO" checkout -q HEAD -- "${SCOPE[@]}" 2>/dev/null || true + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/base_timing.out" 2>&1 || add_hard "baseline_timing_failed" + base_ms=$(grep WRO_CNT_RESULT "$LOG/base_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_CNT_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1) + cp /tmp/wro_cand_scope.py "$REPO/${SCOPE[0]}" 2>/dev/null || true + if [ "$(python3 -c "print(1 if $cand_ms>0 and $base_ms>0 else 0)")" = "1" ]; then + speedup=$(python3 -c "print(round($base_ms/$cand_ms,6))") + else benchmark_ok=false; add_hard "timing_invalid"; fi +fi + +# ---- verdict ---- +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0, computed in +# python below. speedup here is ALREADY absolute (base_ms/cand_ms vs the frozen degraded +# baseline). Every hard gate is preserved verbatim. +hard_str=""; nhard="${#HARD[@]}"; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}" +export WRO_MODE="$MODE" WRO_SPEEDUP="$speedup" \ + WRO_BASE_MS="$base_ms" WRO_CAND_MS="$cand_ms" WRO_REF="$ref_speedup" \ + WRO_HARD="$hard_str" WRO_SCOPE="$scope_ok" WRO_IMP="$import_origin_ok" \ + WRO_CORR="$correctness_ok" WRO_BENCH="$benchmark_ok" +python3 - > "$LOG/reward.json" <<'PY' +import os, json, math +def f(x): + try: return float(x) + except Exception: return -1.0 +ref = f(os.environ.get("WRO_REF", "1")) # oracle speedup over the degraded baseline +sp = f(os.environ.get("WRO_SPEEDUP", "0")) # candidate absolute speedup +hard = os.environ.get("WRO_HARD", "").split() +gates = {"scope_ok": os.environ.get("WRO_SCOPE") == "true", + "import_origin_ok": os.environ.get("WRO_IMP") == "true", + "correctness_ok": os.environ.get("WRO_CORR") == "true", + "benchmark_ok": os.environ.get("WRO_BENCH") == "true"} +# ---- HARD pre-gates: any one hit => reward 0, formula NOT entered ---- +if not all(gates.values()) and not hard: + hard.append("gate_failed") +if not math.isfinite(ref) or ref <= 1.0: + if "ref_speedup_invalid" not in hard: hard.append("ref_speedup_invalid") +if not math.isfinite(sp) or sp <= 1.0: + if "speedup_not_above_baseline" not in hard: hard.append("speedup_not_above_baseline") +reward = 0.0 +if not hard and gates["correctness_ok"]: + try: + reward = max(0.0, min(1.0, max(0.0, min(1.0, math.log(sp) / math.log(ref) - 1.0)))) + except Exception: + reward = 0.0 + hard.append("reward_computation_failed") +v = { + "task_type": "performance", + "mode": os.environ.get("WRO_MODE"), + "reward": reward, + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0", + "speedup": sp, + "ref_speedup": ref, + "cv": {}, + "baseline_ms": f(os.environ.get("WRO_BASE_MS")), + "candidate_ms": f(os.environ.get("WRO_CAND_MS")), + "metadata": {"vs_oracle_ratio": (sp / ref) if ref > 0 else None}, + "hard_fails": hard, + "hard_fail_reasons": hard, + "gates": gates} +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/workload.py b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..709ea410d550901f1cb46c71623aa279f7a5eb5d --- /dev/null +++ b/tasks/kfc/wro-gbench-counter-finalize-loop16/task/tests/workload.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Standalone verifier workload for the counter-finalization subsystem +(scope: /app/repo/bench_counter.py :: finalize_counters). ACCELERATION. + +Drives the scope on CPU (numpy only, no torch, no GPU). Two modes: + + correctness : call finalize_counters on a curated (B, C) counter table whose + flag set deliberately includes counters that COMBINE kInvert with + a rate / thread / iteration transform, and check the returned + (B, C) array against an INDEPENDENT scalar reference computed here + (NOT part of the editable scope). Because "Invert is always last", + an implementation that inverts out of order produces a different + result for those combined counters and is rejected (gate vs + negative), which is why the table is seeded with such counters. + timing : warmup + timed repeats over a large (B, C) table so the + per-(benchmark, counter) Python cell loop dominates and separates + from the vectorized masked form. The gap grows with B * C. + +Emits one line ``WRO_CNT_RESULT {json}``. Timing uses process_time (CPU time) so +the reward band is robust to OS descheduling under fleet load (exp §6.52). +""" +import json +import statistics +import sys +import time + +import numpy as np + +REPO = "/app/repo" +if REPO not in sys.path: + sys.path.insert(0, REPO) + +kIsRate = 1 << 0 +kAvgThreads = 1 << 1 +kIsIterationInvariant = 1 << 2 +kAvgIterations = 1 << 3 +kInvert = 1 << 31 + +# Flag palette used to build tables. Deliberately rich in kInvert combinations so +# the "invert must be last" rule is exercised. +FLAG_PALETTE = [ + 0, + kIsRate, + kAvgThreads, + kIsIterationInvariant, + kAvgIterations, + kIsRate | kAvgThreads, + kIsRate | kAvgIterations, + kIsIterationInvariant | kAvgThreads, + kInvert, + kIsRate | kInvert, + kAvgThreads | kInvert, + kIsRate | kAvgThreads | kInvert, + kIsRate | kIsIterationInvariant, + kAvgIterations | kAvgThreads, +] + +# correctness: small table; every palette entry appears so the invert-order and +# missing-flag mistakes are all detectable. +C_B = 6 +C_C = 8 +C_SEED = 17 + +# timing: large table so the per-cell Python loop (scalar reads + flag branches) +# dominates vs the vectorized masked form. +T_B = 6000 +T_C = 20 +T_SEED = 5 +WARMUP = 1 +ITERS = 3 + + +def load_scope(): + import bench_counter as m + return m + + +def _gen(B, C, seed, curated): + rng = np.random.default_rng(seed) + values = rng.uniform(1.0, 1000.0, size=(B, C)) + if curated: + # tile the full palette across the table so all combos are present + pal = np.array(FLAG_PALETTE, dtype=np.int64) + flags = pal[np.arange(B * C) % pal.size].reshape(B, C) + else: + idx = rng.integers(0, len(FLAG_PALETTE), size=(B, C)) + flags = np.array(FLAG_PALETTE, dtype=np.int64)[idx] + iterations = rng.integers(1000, 10_000_000, size=B).astype(np.float64) + cpu_time = rng.uniform(1e-4, 2.0, size=B) + num_threads = rng.choice(np.array([1.0, 2.0, 4.0, 8.0]), size=B) + return values, flags, iterations, cpu_time, num_threads + + +def _reference(values, flags, iterations, cpu_time, num_threads): + # Independent, definitional scalar implementation (NOT the editable scope). + values = np.asarray(values, dtype=np.float64) + flags = np.asarray(flags, dtype=np.int64) + B, C = values.shape + out = np.empty((B, C), dtype=np.float64) + for b in range(B): + it_b = float(iterations[b]) + ct_b = float(cpu_time[b]) + nt_b = float(num_threads[b]) + for c in range(C): + v = float(values[b, c]) + f = int(flags[b, c]) + if f & kIsRate: + v /= ct_b + if f & kAvgThreads: + v /= nt_b + if f & kIsIterationInvariant: + v *= it_b + if f & kAvgIterations: + v /= it_b + if f & kInvert: + v = 1.0 / v + out[b, c] = v + return out + + +def _invert_first(values, flags, iterations, cpu_time, num_threads): + # The classic "invert not last" mistake, for the gate-quality signal only. + values = np.asarray(values, dtype=np.float64) + flags = np.asarray(flags, dtype=np.int64) + B, C = values.shape + out = np.empty((B, C), dtype=np.float64) + for b in range(B): + it_b = float(iterations[b]); ct_b = float(cpu_time[b]); nt_b = float(num_threads[b]) + for c in range(C): + v = float(values[b, c]); f = int(flags[b, c]) + if f & kInvert: + v = 1.0 / v + if f & kIsRate: + v /= ct_b + if f & kAvgThreads: + v /= nt_b + if f & kIsIterationInvariant: + v *= it_b + if f & kAvgIterations: + v /= it_b + out[b, c] = v + return out + + +def _correctness_case(m): + args = _gen(C_B, C_C, C_SEED, curated=True) + try: + got = m.finalize_counters(*args) + except NotImplementedError: + return {"correctness_ok": False, "reason": "not_implemented"} + except Exception as e: + return {"correctness_ok": False, "reason": "exception:" + type(e).__name__} + ref = _reference(*args) + got = np.asarray(got, dtype=np.float64) + shape_ok = bool(got.shape == ref.shape) + match_ok = bool(shape_ok and np.allclose(got, ref, rtol=1e-9, atol=1e-12)) + # is the invert-order shortcut detectably wrong on this table? (gate quality) + wrong = _invert_first(*args) + nontrivial = int(not np.allclose(wrong, ref, rtol=1e-9, atol=1e-12)) + return {"correctness_ok": match_ok, "shape_ok": shape_ok, "nontrivial": nontrivial} + + +def _timing_case(m): + args = _gen(T_B, T_C, T_SEED, curated=False) + + def once(): + m.finalize_counters(*args) + + try: + for _ in range(WARMUP): + once() + except NotImplementedError: + return -1.0 + ts = [] + for _ in range(ITERS): + t0 = time.process_time() + once() + ts.append((time.process_time() - t0) * 1000.0) + return statistics.median(ts) + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "correctness" + m = load_scope() + if mode == "correctness": + res = _correctness_case(m) + res["mode"] = "correctness" + print("WRO_CNT_RESULT " + json.dumps(res)) + sys.exit(0 if res.get("correctness_ok") else 3) + elif mode == "timing": + ms = _timing_case(m) + if ms < 0: + print("WRO_CNT_RESULT " + json.dumps({"mode": "timing", "timing_ms": -1, + "reason": "not_implemented"})) + sys.exit(3) + print("WRO_CNT_RESULT " + json.dumps({ + "mode": "timing", "timing_ms": ms, "iters": ITERS, "B": T_B, "C": T_C})) + sys.exit(0) + else: + print("WRO_CNT_RESULT " + json.dumps({"error": "bad_mode"})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/.dockerignore b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/.dockerignore @@ -0,0 +1,24 @@ +# .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does +# NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile . +# The reference implementation and every authoring artefact MUST NOT reach an image layer. +*.patch +oracle* +negative* +baseline2* +scope_card.json +degradation_manifest.json +task_meta.json +loop_map_entry.json +job.yaml +intermediates/ +_retrofit* +sr_validate* +leak_audit/ +self_check/ +variants/ +**/__pycache__/ +**/*.pyc +*.bak +*.bak_* +*.pre_* +**/*.pre_* diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/instruction.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5e7e77a8611c064217cf6900b2adbdf2a9681cbc --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/instruction.md @@ -0,0 +1,85 @@ +# Performance Optimization Task + +## Overview + +You are given a working implementation of a **rowwise int8 quantization** primitive +— the routine that, during low-precision / int8 mixed-precision training, converts a +high-precision 2-D tensor into int8 by computing a per-row symmetric absmax scale and +quantizing each row. The implementation in the declared scope is **functionally +correct but slow**: it quantizes one row at a time. + +Your job is to make this subsystem **as fast as possible on the benchmark +workloads**, while preserving its numerical behavior within tolerance. + +## Editable scope (you may modify ONLY this file) + +``` +torchao/prototype/quantized_training/int8.py +``` + +Edits to any file outside this scope are rejected and score zero. You may +restructure, add helpers, and change the internal algorithm within this file, as +long as the public function keeps its signature and behavior. + +## Public entry point + contract + +```python +from torchao.prototype.quantized_training.int8 import quantize_int8_rowwise + +int8_tensor, scale = quantize_int8_rowwise(tensor, stochastic_rounding=False, eps=1e-12) +``` + +- `tensor` is a 2-D high-precision tensor. Returns `(int8_tensor, scale)` where + `scale` is per-row (one entry per leading-dimension index, same dtype as the + input) and `int8_tensor` is the quantized result in `torch.int8`. +- **Correctness contract:** for the same input, the per-row `scale` and the + dequantized result (`int8_tensor * scale`) must match an independent reference + (per-row `scale = |row|.amax()/127`, then `round(row/scale)` clipped to + `[-128, 127]` as int8) within a relative-norm tolerance (relative max-abs ≤ 2e-2, + relative L2 ≤ 1e-2), and the integer codes must match the reference exactly + (no code off by more than 1). A submission that changes the computed result + beyond tolerance, or produces a result not derived from the actual input, fails + correctness and scores zero. +- Behavior must be preserved across the workload axes the benchmark exercises: + **a range of tensor sizes and the (default) round-to-nearest regime.** Do not + special-case the public workload. +- Determinism: given the same input (and `stochastic_rounding=False`), results must + be stable across runs. + +Helper primitives already present in the surrounding package (outside your scope) +are available for you to call. + +## How your work is scored + +Your solution is timed end-to-end through the public function on a set of benchmark +workloads and compared, on wall-clock, against the frozen starting state of the +scope file. The reward is a log-curve function of that speedup, in `[0, 1]`: +matching the reference (oracle) implementation's speed scores **0.5**, being as far +past it again as it is past the frozen baseline caps the reward at **1.0**, and +merely matching the frozen baseline scores **0.0**. Correctness is a hard +prerequisite: an incorrect solution scores zero regardless of speed. + +## 🔴 Rules (violation ⇒ the whole task scores 0) + +Solve this task independently, using only the code in the editable scope, the +surrounding package already present in the environment, and your own knowledge. + +- Do **NOT** read, `cat`, `grep`, `find`, open, or edit any verifier, scoring, + timing, correctness, or hidden-test file or directory, wherever it lives; and + do not run or attempt to reproduce/reverse-engineer the scoring harness. +- Do **NOT** download, clone, fetch, or otherwise obtain the upstream project or + any reference/original implementation of this subsystem in ANY form — no + `git clone`/`git fetch`/`git pull`, no adding a git remote, no + `pip install`/`pip download` of the same package, no `wget`/`curl` of upstream + files, and no web lookup — whether or not the network appears reachable. +- Do **NOT** bypass or disable the environment's network isolation (e.g. + unsetting or repointing `http_proxy`/`https_proxy`/`all_proxy`, opening raw + sockets, or any other circumvention). + +Any one of these actions means the whole task scores 0, regardless of measured +performance. + +## 提交方式 + +本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。 +改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/pre_artifacts.sh b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2087aac50357c2f7719498ca6985f3765b179f1 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/pre_artifacts.sh @@ -0,0 +1,163 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/wro-torchao-int8-rowwise-quant-loop16 +# +# Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE +# grading (spec §1.1). It turns whatever the agent left behind into a portable artifact: +# +# /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit +# /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line +# +# 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one +# place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs ..HEAD). +# Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate, +# `git checkout -q HEAD -- ` re-materialises the baseline for the paired timing, +# and loop16's `submit.sh --finalize` plants the best iterate with read-tree + +# checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope +# gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the +# "baseline" — and a correct solve scores 0. +# `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages +# names only, writes no tree, creates no commit and leaves HEAD exactly where it was. +# +# EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier +# scores the container on its own terms and gives 0 by itself. +# +# READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index +# (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the +# verifier — which runs after us — sees exactly the `git status --porcelain` it would have +# seen if this script had never run. No commit, no HEAD move, no working-tree write. +# +# CAPTURE ROOTS for THIS task — derived from the package, never assumed: +# /app/repo git repo, HEAD == the 1-commit carved baseline +# evidence Dockerfile:138: WORKDIR /app/repo +# evidence Dockerfile:90: && cd /app/repo \ +# evidence Dockerfile:97: && test "$(git rev-list --count HEAD)" = "1" \ +# evidence test.sh:10: export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +# evidence test.sh:13: REPO=/app/repo +# +# Single root => model.patch is a bare `git diff --binary ` (no banner). +# model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable +# by one reader. +# +# loop16 task (environment/loop/ -> /opt/loop in the image): the harness auto-finalizes +# at k=16 and `submit.sh --finalize` plants the best iterate in the WORKING TREE while +# HEAD stays on the baked baseline — which is exactly what this script captures. Running +# it after a finalize therefore yields the GRADED artifact, not the last raw edit. +# ============================================================================ +set -uo pipefail + +OUT=/logs/artifacts +PATCH="$OUT/model.patch" +LIST="$OUT/model_files.txt" +MULTI=0 # 1 => several capture roots => each diff gets a banner line +MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane) + +mkdir -p "$OUT" 2>/dev/null || true +: > "$PATCH" 2>/dev/null || true +: > "$LIST" 2>/dev/null || true +git config --global --add safe.directory '*' >/dev/null 2>&1 || true + +banner() { # $1=root $2=mode ; only when there is more than one root + if [ "$MULTI" = 1 ]; then + printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null + fi + return 0 +} + +list_add() { # stdin: paths relative to $1 -> absolute, one per line + sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true + return 0 +} + +capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot" + capture_tree "$root" + return 0 + fi + # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and + # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could + # flip a scope gate either way. So copy the repo's index aside and stage into the COPY — + # the repo's own .git/index is byte-identical when we are done. + tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi="" + gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true) + if [ -z "$gd" ]; then + gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true) + case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac + fi + if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then + GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE + else + echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index" + fi + git -C "$root" add -AN . >/dev/null 2>&1 || true + base=HEAD + if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then + base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null) + echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree" + else + n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0) + case "$n" in ''|*[!0-9]*) n=0 ;; esac + if [ "$n" -gt 1 ]; then + base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1) + echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:" + echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so" + echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved" + echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve." + fi + fi + [ -n "${base:-}" ] || base=HEAD + banner "$root" "git-diff-vs-baseline" + git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true + names=$(git -C "$root" diff --name-only "$base" 2>/dev/null) + echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)" + unset GIT_INDEX_FILE + [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null + printf '%s\n' "$names" | grep -v '^$' | list_add "$root" + return 0 +} + +capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot + root=$1 + if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi + tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0 + if git init -q "$tmp/snap" >/dev/null 2>&1; then + GD="$tmp/snap/.git" + empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null) + ( cd "$root" 2>/dev/null || exit 0 + find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \ + 2>/dev/null \ + | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true + banner "$root" "tree-snapshot-not-a-git-repo" + GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \ + >> "$PATCH" 2>/dev/null || true + else + echo "[pre_artifacts] WARN could not stage a snapshot index for $root" + fi + rm -rf "$tmp" 2>/dev/null || true + all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \ + -type f -print 2>/dev/null | sed 's|^\./||' ) + printf '%s\n' "$all" | grep -v '^$' | list_add "$root" + big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \ + -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . ) + echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)" + if [ "${big:-0}" != 0 ]; then + echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in" + echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch." + fi + return 0 +} + +capture_git "/app/repo" +bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0) +case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac +echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)" +if [ "$bytes" -gt 67108864 ]; then + echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build" + echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also" + echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish." +fi +exit 0 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/solution/negative.patch b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/solution/negative.patch new file mode 100644 index 0000000000000000000000000000000000000000..652ae98c9d8cbb68ca0e0348ab05e5f0749a46c4 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/solution/negative.patch @@ -0,0 +1,11 @@ +--- a/torchao/prototype/quantized_training/int8.py ++++ b/torchao/prototype/quantized_training/int8.py +@@ -50,7 +50,7 @@ + out = torch.empty_like(tensor, dtype=torch.int8) + for i in range(R): + row = tensor[i] +- s = row.abs().amax() / 127 ++ s = row.abs().mean() / 127 # NEGATIVE known-bad: mean is not absmax + scale[i] = s + inv = 1.0 / s.float().clip(eps) + q = row.float() * inv diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/solution/solve.sh b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7d1084a4e30881b10ee225520ba07023a0cacaea --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/solution/solve.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/wro-torchao-int8-rowwise-quant-loop16 +# 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量 +# 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。 +# +# oracle 形态 : 补丁式(patch)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_PATCH 槽位: +# git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" +# 产物(reviewer-only;本脚本只读,一个字节都不改): +# solution/negative.patch, solution/oracle.patch +# $REPO : /app/repo (tests/test.sh: REPO=/app/repo) +# 被计分单元 : /app/repo/torchao/prototype/quantized_training/int8.py +# 来源:tests/test.sh 的 SCOPE=("torchao/prototype/quantized_training/int8.py") +# 落地方式 : git -C $REPO apply -p1 —— 只改工作树,不 commit +# +# 🔴 为什么绝不 commit(规范 H3):判分读**工作树** —— `git status --porcelain` 是 scope +# 硬闸门,`git checkout -q HEAD -- ` 取基线,且镜像自证 /app/repo 的 HEAD 恰好 +# 只有 1 个 commit(那就是挖洞基线)。一旦 commit,HEAD 前移 → 闸门看不到改动、 +# `checkout HEAD -- scope` 把 candidate 当成基线 → 正确解被判 0。 +# 本脚本落地后会自己断言 HEAD 与 commit 数没变。 +# +# ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)──────────────────────── +# PKG=/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task +# IMG=fai/kfc-wro-torchao-int8-rowwise-quant-loop16:oss +# # 1) 起容器。判分容器始终 --network=none;tests/ 和 solution/ 都**没有**烤进镜像 +# # (Dockerfile 里没有一条 COPY 取它们),所以这两个目录必须挂进来。 +# # 该题 task.toml 声明 gpus=1;锚点的标定硬件/运行栈见 tests/ref_speedup.caveat.md +# docker run -d --name kfc-solve --network=none --gpus all \ +# -v "$PKG/tests":/tests -v "$PKG/solution":/solution "$IMG" +# # 2) 落地参考实现到工作树(本脚本;不 commit) +# docker exec kfc-solve bash /solution/solve.sh +# # 3) 判分。KERNELBENCH_VERIFY_MODE 必须留在默认的 candidate —— 这就是 agent 的 +# # 真实评分路径;设成 oracle/negative 会让 test.sh 自己再落地一遍,绕过本脚本。 +# docker exec -e KERNELBENCH_VERIFY_MODE=candidate kfc-solve bash /tests/test.sh +# docker exec kfc-solve cat /logs/verifier/reward.json # 判分结果 +# docker rm -f kfc-solve +# +# 期望:oracle → 性能题得 0(它就是锚点本身; min(1, ln(speedup/ref_speedup)/ln(ref_speedup))(speedup ≤ ref_speedup 时为 0) +# 在 speedup≈ref_speedup 处 = 0 —— 打平 oracle 不得分,必须超过。 +# 所以"oracle 跑对了"的判据不是 reward>0,而是 speedup≈ref_speedup 且 +# hard_fail_reasons 为空;实现类二值题 = 1.0 —— 权威公式是 +# tests/test.sh 写出的 reward_formula 字段);--negative → 0; +# --noop(在纯净容器里)→ 0(挖洞基线过不了正确性门)。 +# 本题带 loop16 harness:`bash /opt/loop/submit.sh` 判的也是同一棵工作树、 +# 同样走 candidate 模式(口径一致),所以落地后直接自评也成立。 +# ────────────────────────────────────────────────────────────────────────── +# +# 用法(规范 2 的统一 CLI): +# bash solution/solve.sh # 落地 oracle(参考实现) +# bash solution/solve.sh --negative # 落地 negative(已知坏例,必须得 0) +# bash solution/solve.sh --baseline2 # 落地 baseline2(中间基线) +# bash solution/solve.sh --noop # 把可编辑面复位到烤入基线(对照组) +# +# --noop 语义:把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— +# `git checkout HEAD -- `,HEAD 不动),使对照组能量到真正的 no-op 值。 +# runner 在同一个容器里连着跑 oracle → noop 做对照时,靠它把上一轮落地归零。 +# +# 幂等:每次落地前先把被计分单元 `git checkout HEAD --` 复位,重复执行结果一致。 +# 失败一律非 0 退出并打印原因(补丁打不上 / 变体文件缺失 / scope 路径不存在 / HEAD 被移动)。 +set -uo pipefail + +TASK_ID="wro-torchao-int8-rowwise-quant-loop16" +REPO="${KFC_REPO_DIR:-/app/repo}" +SCOPE=("torchao/prototype/quantized_training/int8.py") +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; } +die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; } +# 每次调用单独带 safe.directory,不去改容器里的全局 gitconfig +GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; } + +usage(){ cat <<'USAGE' +usage: bash solve.sh [--oracle | --negative | --noop] + (无参数) 落地 oracle 参考实现(oracle.patch) + --negative 落地 negative 已知坏例(negative.patch) + --noop 把可编辑面复位到烤入基线(与 verifier 取基线一致,HEAD 不动) +USAGE +} + +WHICH=oracle +case "${1:-}" in + ""|--oracle) WHICH=oracle ;; + --negative) WHICH=negative ;; + --baseline2) WHICH=baseline2 ;; + --noop) WHICH=noop ;; + -h|--help) usage; exit 0 ;; + *) usage >&2; die "未知参数 '$1'" ;; +esac + +# ---- 产物定位:脚本同目录优先,其次容器里的常见挂载点 ---- +artifact(){ + local n="$1" c + for c in "$HERE/$n" "/solution/$n" "${KFC_SOLUTION_DIR:-/nonexistent}/$n"; do + [ -f "$c" ] && { printf '%s\n' "$c"; return 0; } + done + return 1 +} + +case "$WHICH" in + noop) ART="" ;; + oracle) ART="oracle.patch" ;; + negative) ART="negative.patch" ;; + *) die "本题没有 $WHICH 变体(solution/ 里只有:oracle.patch, negative.patch)" ;; +esac + +# ---- 环境前置检查 ---- +GIT rev-parse --git-dir >/dev/null 2>&1 \ + || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)" +for s in "${SCOPE[@]}"; do + [ -e "$REPO/$s" ] || die "被计分单元不存在:$REPO/$s(REPO 不对?可用 KFC_REPO_DIR 覆盖)" +done +HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD" +N_BEFORE="$(GIT rev-list --count HEAD)" + +if [ "$WHICH" = noop ]; then + # --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— `git checkout HEAD -- `, + # HEAD 不动),使对照组能量到真正的 no-op 值。runner 在同一个容器里连着跑 oracle → noop 时靠它归零。 + DIRTY_BEFORE="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" + DIRTY_AFTER="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')" + if [ -n "$DIRTY_AFTER" ]; then + printf '%s\n' "$DIRTY_AFTER" | sed "s|^|[solve.sh $TASK_ID] |" >&2 + die "复位后被计分单元仍不干净(见上)—— 量不到真正的 no-op 值" + fi + [ "$HEAD_BEFORE" = "$(GIT rev-parse HEAD)" ] || die "HEAD 被移动了,判分会把 candidate 当基线" + [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + if [ -n "$DIRTY_BEFORE" ]; then + say "--noop:已把可编辑面复位到烤入基线;原先这些是脏的:" + printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |" + else + say "--noop:可编辑面本来就是干净的烤入基线,无需复位" + fi + say "--noop 完成:${SCOPE[*]} = 烤入基线(HEAD 未动 @ ${HEAD_BEFORE:0:12})" + exit 0 +fi + +PATCH="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)" + +# ---- 幂等:先把被计分单元退回挖洞基线,再打补丁(否则二次 apply 必然失败) ---- +GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})" +GIT apply -p1 --check "$PATCH" \ + || die "补丁打不上:$PATCH —— 挖洞树与该补丁不匹配,或工作树被别的改动污染了" +GIT apply -p1 "$PATCH" || die "git apply 失败:$PATCH" + +# ---- 硬要求:HEAD 一步都不能动(规范 H3) ---- +HEAD_AFTER="$(GIT rev-parse HEAD)" +[ "$HEAD_BEFORE" = "$HEAD_AFTER" ] || die "HEAD 被移动了($HEAD_BEFORE -> $HEAD_AFTER),判分会把 candidate 当基线" +[ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线" + +say "已落地 $WHICH:$(basename "$PATCH") -> ${SCOPE[*]}(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})" +GIT status --porcelain -- "${SCOPE[@]}" | sed "s|^|[solve.sh $TASK_ID] |" + +# ---- 顺手体检 scope 闸门:工作树里除了被计分单元不该有别的改动 ---- +STRAY="$(GIT status --porcelain | awk '{print $NF}' \ + | grep -v -e '__pycache__' -e '\.pyc$' -e '^torchao/prototype/quantized_training/int8\.py$' || true)" +[ -z "$STRAY" ] || { say "⚠ 工作树里还有 scope 外的改动,判分会 out_of_scope_edit 直接归 0:"; \ + printf '%s\n' "$STRAY" | sed "s|^|[solve.sh $TASK_ID] |"; } +exit 0 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/task.toml b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1286b6a57433c6abd8c260620a7ff966bd0fbb51 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/task.toml @@ -0,0 +1,57 @@ +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "wro-torchao-int8-rowwise-quant-loop16" +bench = "kfc" +kind = "performance" +language = "python" +title = "You are given a working implementation of a rowwise int8 quantization primitive — the routine that …" +instruction = "instruction.md" + +[agent] +timeout_sec = 5400 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/wro-torchao-int8-rowwise-quant-loop16:v1@sha256:eca5c38506261492ca01d356568c2f08c14d61cab27381ebed22e998bf55a7e2 +# Open-source build: `cd && docker build -f environment/Dockerfile -t fai/kfc-wro-torchao-int8-rowwise-quant-loop16:oss .` +[environment] +docker_image = "fai/kfc-wro-torchao-int8-rowwise-quant-loop16:oss" +dockerfile = "environment/Dockerfile" +build_timeout_sec = 3600 +cpus = 8 +memory_mb = 49152 +gpus = 1 +# H20 只是**锚点标定用卡**,不是硬性限制。换卡时:①按 tests/ref_speedup.caveat.md 重标锚点; +# ②用 --build-arg TORCH_CUDA_ARCH_LIST=<你的算力> 构建镜像。 +gpu_types = ["H20"] +allow_internet = false + +[verifier] +entrypoint = "tests/test.sh" +mode = "shared" +task_kind = "acceleration" +contract_pattern = "repo_scope_speedup" +timing_metric = "speedup" +primary_edit_paths = ["torchao/prototype/quantized_training/int8.py"] +forbidden_edit_paths = ["**"] +result_paths = ["/logs/verifier/reward.json"] + +[primary_metric] +name = "speedup" +goal = "maximize" +reward_formula = "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0" +reward_note = "reward = 0 on any hard gate, on speedup<=1, or on ref_speedup<=1; range [0,1]" +reward_reference = "/opt/verifier-correctness-manifest.json ref_speedup, fallback tests/ref_speedup.txt (oracle speedup over the frozen degraded baseline)" +ref_speedup = 902.116643 +ref_speedup_source = "tests/ref_speedup.txt" +calibrated_on = "NVIDIA H20" + +[loop] +# NOTE: the /opt/loop harness baked into the image applies its own 3/16 in-session budget; for in-session loop scoring the image is authoritative. +min_submissions = 1 +max_submissions = 1 +submit = "bash /opt/loop/submit.sh" +feedback_surface = "/opt/loop/submit.sh" +declared_submission_policy = "single_submission" # submit == finalize; the 2nd call is refused diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/compute_reward.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..399beb197928c15c1d9be3db2f6b45091853c2ca --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/compute_reward.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""compute_reward for wro-torchao-int8-rowwise-quant-loop16 — standalone reward helper. + +reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + speedup = baseline_ms / candidate_ms (absolute, vs the frozen degraded baseline) + matching the oracle -> 0.5 ; oracle^2 -> 1.0 cap ; at/below the baseline -> 0.0 + value range strictly [0.0, 1.0] + +HARD pre-gates (any one hit => reward 0, formula NOT entered): the correctness gate in test.sh +(a candidate that fails parity scores 0 there), speedup <= 1, ref_speedup <= 1, bad timings. + +usage: compute_reward.py [ref_speedup] +NOTE: the authoritative verdict is the one test.sh writes to /logs/verifier/reward.json; this +helper exists so the lane's reward definition is reproducible standalone. +""" +import json, math, os, sys + +TOKEN = "WRO_GDN_RESULT " + + +def load(path): + with open(path) as f: + for line in f: + if line.startswith(TOKEN): + return json.loads(line[len(TOKEN):]) + raise SystemExit(f"no {TOKEN.strip()} in {path}") + + +def read_ref(argv): + if len(argv) > 3: + try: + return float(argv[3]) + except Exception: + pass + here = os.path.dirname(os.path.abspath(__file__)) + for p in ("/opt/verifier-correctness-manifest.json",): + try: + v = float(json.load(open(p)).get("ref_speedup", 0) or 0) + if v > 1.0: + return v + except Exception: + pass + try: + return float(open(os.path.join(here, "ref_speedup.txt")).read().strip()) + except Exception: + return 0.0 + + +def log_reward(speedup, ref): + """min(1.0, ln(speedup/ref)/ln(ref)) if speedup > ref else 0.0 clamped to [0,1]; 0 unless speedup>1 and ref>1.""" + if not (math.isfinite(speedup) and math.isfinite(ref)) or speedup <= 1.0 or ref <= 1.0: + return 0.0 + return max(0.0, min(1.0, max(0.0, min(1.0, math.log(speedup) / math.log(ref) - 1.0)))) + + +def main(): + cand = load(sys.argv[1]) + arg2 = sys.argv[2] if len(sys.argv) > 2 else "-1" + try: + base_ms = float(arg2) + except ValueError: + base_ms = float(load(arg2).get("timing_ms", -1)) + cand_ms = float(cand.get("timing_ms", -1)) + ref = read_ref(sys.argv) + speedup = (base_ms / cand_ms) if (cand_ms > 0 and base_ms > 0) else 0.0 + + hard = [] + if not (cand_ms > 0 and base_ms > 0): + hard.append("timing_invalid") + if not math.isfinite(ref) or ref <= 1.0: + hard.append("ref_speedup_invalid") + if not math.isfinite(speedup) or speedup <= 1.0: + hard.append("speedup_not_above_baseline") + reward = 0.0 if hard else log_reward(speedup, ref) + + print(json.dumps({ + "task_type": "performance", + "reward": round(reward, 6), + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0", + "hard_fail_reasons": hard, + "speedup": round(speedup, 6), + "ref_speedup": ref, + "cv": {}, + "baseline_ms": round(base_ms, 4), + "candidate_ms": round(cand_ms, 4), + })) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup.caveat.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..cf97562768dd0daa5bb86e91882cbb0f004052fd --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +`ref_speedup.txt` 里的 **902.116643** 是 oracle 标定常量,判分时只读、不重跑 oracle: + + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + +`tests/test.sh` 的解析顺序是 **`tests/ref_speedup.txt` → `/opt/verifier-correctness-manifest.json` → 1.0**; +回落到 1.0 会让所有 reward 归 0,所以这个文件必须存在且 > 1。 + +## 标定条件 + +- 硬件:**NVIDIA H20** +- 运行栈:`torch 2.7.0`(原始私有基座声明 torch 2.5.1/triton 3.1.0,任务 overlay 又 `pip install torch==2.7.0`,锚点即在 2.7.0 下标定) +- 线程:`OMP/MKL/OPENBLAS_NUM_THREADS=1`(计时稳定性的一部分,已写进镜像 ENV) + +## 硬件不一致时如何重标 + +verifier 原生支持模式分派,参考实现**按路径传入、从不烤进镜像**: + +```bash +docker run --rm --gpus all -v "$PWD/tests:/tests:ro" -v "<放 oracle.patch 的目录>:/patches:ro" \ + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ + fai/kfc-wro-torchao-int8-rowwise-quant-loop16:oss bash /tests/test.sh +# 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt +``` + +自证:`noop`(不打补丁)应 ≈1.0 → 被门到 0;`negative`(`KERNELBENCH_NEGATIVE_PATCH=`)必须 0。 + +✅ 本题**随包提供**参考实现 `solution/oracle.patch`,所以重标定通路是**可直接执行**的。 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup.txt b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0b671a58fc68cd60ed56718bb4c3847cee398af --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup.txt @@ -0,0 +1 @@ +902.116643 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup_provenance.json b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup_provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d3f73344c0b61bbcec309fbce96494b7bc8b7512 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/ref_speedup_provenance.json @@ -0,0 +1,6 @@ +{ + "ref_speedup": 902.116643, + "derivation": "oracle-mode / expected-score ratio from the recorded 4-mode validation (recorded 4-mode validation anchor)", + "meaning": "the ORACLE speedup over the frozen degraded baseline; the ref_speedup anchor", + "precedence": "test.sh prefers the in-image /opt/verifier-correctness-manifest.json ref_speedup; this file is the tests/-local fallback when that key is absent" +} diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/test.sh b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..77b69be73a030fcca7f242e778a3733235099557 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/test.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# Verifier for wro-torchao-int8-rowwise-quant (torchao rowwise int8 quantization for quantized training). +# Type-2 Long-horizon, ACCELERATION lane. Scope = 1 file: torchao/prototype/quantized_training/int8.py +# Modes: candidate | noop | oracle | negative. +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 over the wall speedup base_ms/cand_ms +# oracle -> 0.5, ref_speedup^2 -> 1.0 cap, noop -> 0. +# (baseline2 = N/A: single algorithmic lever — vectorized reduction/cast; see scope card.) +set -uo pipefail +export PATH="/opt/kernelbench-venv/bin:/opt/venv/bin:/usr/local/bin:$PATH" +export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +git config --global --add safe.directory '*' 2>/dev/null || true +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +LOG=/logs/verifier; mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" +SCOPE=("torchao/prototype/quantized_training/int8.py") + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true +speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1 + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } +RUNDIR="$TESTS_DIR" + +# ---- apply oracle / negative patch by mode (candidate & noop: no patch) ---- +if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"; fi +if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then + git -C "$REPO" apply -p1 "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true; fi + +# ---- (1) scope-diff HARD GATE: only the scope file may change in /app/repo ---- +git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt" +while IFS= read -r f; do + [ -z "$f" ] && continue + keep=false + for s in "${SCOPE[@]}"; do [ "$f" = "$s" ] && keep=true; done + case "$f" in *__pycache__*|*.pyc) keep=true;; esac + [ "$keep" = true ] || { scope_ok=false; add_hard "out_of_scope_edit:$f"; } +done < "$LOG/changed_files.txt" + +# ---- (2) import-origin assert: torchao under test must be the baked /app/repo tree ---- +python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import os, sys; sys.path.insert(0, "/app/repo") +import torchao.prototype.quantized_training.int8 as m +print("I8_LOC", m.__file__) +sys.exit(0 if m.__file__.startswith("/app/repo") else 3) +PY +[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; } + +# ---- (3) trusted-restore: harness uploaded fresh (never baked) ---- +for f in workload.py compute_reward.py; do + [ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; } +done + +# ---- ref_speedup: the ORACLE's speedup over the frozen degraded baseline. +# This is the reward anchor: reward = min(1, ln(speedup/ref_speedup)/ln(ref_speedup)). +# The in-image manifest wins; tests/ref_speedup.txt is the uploaded-fresh fallback. +[ -f /opt/verifier-correctness-manifest.json ] && \ + 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) +if [ "$(python3 -c "print(1 if float('${ref_speedup:-1}')<=1.0 else 0)" 2>/dev/null || echo 1)" = "1" ] && [ -f "$TESTS_DIR/ref_speedup.txt" ]; then + ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt") +fi +ref_speedup=${ref_speedup:-1.0} + +# ---- (4) CORRECTNESS GATE: scope output must match the independent fp32 reference ---- +if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then + ( cd "$RUNDIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1 + cok=$(grep WRO_GDN_RESULT "$LOG/correctness.out" | python3 -c "import json,sys +try: print(json.loads(sys.stdin.read().split('WRO_GDN_RESULT ',1)[1]).get('correctness_ok')) +except Exception: print('False')" 2>/dev/null || echo False) + if [ "$cok" != "True" ]; then correctness_ok=false; add_hard "correctness_failed"; fi +fi + +# ---- (5) TIMING: candidate wall + baseline (frozen degraded tree at HEAD) ---- +if [ "$correctness_ok" = true ] && { [ "${#HARD[@]}" -eq 0 ] || [ -z "${HARD[*]:-}" ]; }; then + ( cd "$RUNDIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed" + cand_ms=$(grep WRO_GDN_RESULT "$LOG/cand_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_GDN_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1) + git -C "$REPO" stash -q 2>/dev/null || true + git -C "$REPO" checkout -q -- "${SCOPE[@]}" 2>/dev/null || true + ( cd "$RUNDIR" && python3 workload.py timing ) > "$LOG/base_timing.out" 2>&1 || add_hard "baseline_timing_failed" + base_ms=$(grep WRO_GDN_RESULT "$LOG/base_timing.out" | python3 -c "import json,sys;print(json.loads(sys.stdin.read().split('WRO_GDN_RESULT ',1)[1]).get('timing_ms',-1))" 2>/dev/null || echo -1) + git -C "$REPO" stash pop -q 2>/dev/null || true + if [ "$(python3 -c "print(1 if $cand_ms>0 and $base_ms>0 else 0)")" = "1" ]; then + speedup=$(python3 -c "print(round($base_ms/$cand_ms,6))") + else benchmark_ok=false; add_hard "timing_invalid"; fi +fi + +# ---- verdict ---- +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0, computed in +# python below. speedup here is ALREADY absolute (base_ms/cand_ms vs the frozen degraded +# baseline). Every hard gate is preserved verbatim. +hard_str=""; nhard="${#HARD[@]}"; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}" +export WRO_MODE="$MODE" WRO_SPEEDUP="$speedup" \ + WRO_BASE_MS="$base_ms" WRO_CAND_MS="$cand_ms" WRO_REF="$ref_speedup" \ + WRO_HARD="$hard_str" WRO_SCOPE="$scope_ok" WRO_IMP="$import_origin_ok" \ + WRO_CORR="$correctness_ok" WRO_BENCH="$benchmark_ok" +python3 - > "$LOG/reward.json" <<'PY' +import os, json, math +def f(x): + try: return float(x) + except Exception: return -1.0 +ref = f(os.environ.get("WRO_REF", "1")) # oracle speedup over the degraded baseline +sp = f(os.environ.get("WRO_SPEEDUP", "0")) # candidate absolute speedup +hard = os.environ.get("WRO_HARD", "").split() +gates = {"scope_ok": os.environ.get("WRO_SCOPE") == "true", + "import_origin_ok": os.environ.get("WRO_IMP") == "true", + "correctness_ok": os.environ.get("WRO_CORR") == "true", + "benchmark_ok": os.environ.get("WRO_BENCH") == "true"} +# ---- HARD pre-gates: any one hit => reward 0, formula NOT entered ---- +if not all(gates.values()) and not hard: + hard.append("gate_failed") +if not math.isfinite(ref) or ref <= 1.0: + if "ref_speedup_invalid" not in hard: hard.append("ref_speedup_invalid") +if not math.isfinite(sp) or sp <= 1.0: + if "speedup_not_above_baseline" not in hard: hard.append("speedup_not_above_baseline") +reward = 0.0 +if not hard and gates["correctness_ok"]: + try: + reward = max(0.0, min(1.0, max(0.0, min(1.0, math.log(sp) / math.log(ref) - 1.0)))) + except Exception: + reward = 0.0 + hard.append("reward_computation_failed") +v = { + "task_type": "performance", + "mode": os.environ.get("WRO_MODE"), + "reward": reward, + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0", + "speedup": sp, + "ref_speedup": ref, + "cv": {}, + "baseline_ms": f(os.environ.get("WRO_BASE_MS")), + "candidate_ms": f(os.environ.get("WRO_CAND_MS")), + "metadata": {"vs_oracle_ratio": (sp / ref) if ref > 0 else None}, + "hard_fails": hard, + "hard_fail_reasons": hard, + "gates": gates} +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/workload.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..8f2a3b1dfb36b2589b2fb69817c4b7d5dbf85f8d --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/tests/workload.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""wro-torchao-int8-rowwise-quant — workload harness (reviewer-authored, uploaded with tests/). + +Scope = torchao/prototype/quantized_training/int8.py (rowwise int8 quantization used in +int8 mixed-precision / quantized training). + +Drives the PUBLIC entry `quantize_int8_rowwise` on a large 2D tensor on ONE GPU: each logical +row gets a symmetric absmax scale (|row|.amax()/127), then the row is quantized to int8. + +Two modes: + correctness : compare (int8 codes, scale) against an INDEPENDENT fp32 reference computed here + (NOT part of the editable scope), by relative-norm tolerance on the dequant + scale. + timing : warmup + timed repeats of the quantization (paired vs the frozen baseline). + +Emits one line `WRO_GDN_RESULT {json}`. The timed regime uses a large row count so the per-row +Python loop of the slow baseline separates clearly from a fused vectorized quantization. +""" +import json +import statistics +import sys + +sys.path.insert(0, "/app/repo") +import torch + +from torchao.prototype.quantized_training.int8 import quantize_int8_rowwise + +DEV = "cuda" +ROWS = 4096 +COLS = 4096 +DTYPE = torch.bfloat16 +REL_MAX_TOL = 2e-2 +REL_L2_TOL = 1e-2 +WARMUP = 3 +ITERS = 10 + + +def build_inputs(seed=0, rows=ROWS, cols=COLS, device=DEV): + g = torch.Generator(device=device).manual_seed(seed) + x = torch.randn(rows, cols, device=device, dtype=DTYPE, generator=g) + row_gain = torch.logspace(-2, 2, rows, device=device, dtype=torch.float32).view(-1, 1) + return (x.float() * row_gain).to(DTYPE) + + +def run_scope(x): + """Call the subsystem-under-test (candidate / degraded baseline code).""" + return quantize_int8_rowwise(x, stochastic_rounding=False) + + +def int8_reference(x, eps=1e-12): + """Independent trusted reference of rowwise int8 quantization (ground truth; NOT in the + editable scope). Mirrors the documented numerics: scale=|x|.amax(1)/127, then + round(x/scale) clipped to [-128,127] as int8. Output scale keeps the input dtype.""" + scale = x.abs().amax(1) / 127 + inv = 1.0 / scale.float().clip(eps) + q = (x.float() * inv.view(-1, 1)).round().clip(-128, 127).to(torch.int8) + return q, scale + + +def _relnorm(out, ref): + diff = (out - ref).abs() + max_abs = float(diff.max()) + denom = float(ref.abs().max().clamp_min(1e-6)) + return max_abs / denom, float(diff.norm() / ref.norm().clamp_min(1e-6)) + + +def correctness(): + x = build_inputs(seed=0, rows=512, cols=1024) + codes, scale = run_scope(x) + ref_codes, ref_scale = int8_reference(x) + torch.cuda.synchronize() + # dequant parity (robust to +/-1 code rounding differences) + scale parity + deq = codes.float() * scale.float().view(-1, 1) + ref_deq = ref_codes.float() * ref_scale.float().view(-1, 1) + rmo, rlo = _relnorm(deq, ref_deq) + rms, rls = _relnorm(scale.float(), ref_scale.float()) + ncode_mismatch = int((codes.long() - ref_codes.long()).abs().gt(1).sum().item()) + ok = (rmo <= REL_MAX_TOL) and (rlo <= REL_L2_TOL) and (rms <= REL_MAX_TOL) and \ + (rls <= REL_L2_TOL) and (ncode_mismatch == 0) + return { + "correctness_ok": bool(ok), "rel_max_deq": rmo, "rel_l2_deq": rlo, + "rel_max_scale": rms, "rel_l2_scale": rls, "n_code_mismatch_gt1": ncode_mismatch, + "codes_shape": list(codes.shape), "scale_shape": list(scale.shape), + } + + +def timing(iters=ITERS, warmup=WARMUP): + x = build_inputs(seed=2) + for _ in range(warmup): + run_scope(x) + torch.cuda.synchronize() + ts = [] + for _ in range(iters): + s = torch.cuda.Event(enable_timing=True); e = torch.cuda.Event(enable_timing=True) + torch.cuda.synchronize(); s.record(); run_scope(x); e.record(); torch.cuda.synchronize() + ts.append(s.elapsed_time(e)) + return statistics.median(ts) + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "correctness" + if not torch.cuda.is_available(): + print("WRO_GDN_RESULT " + json.dumps({"error": "no_cuda"})); sys.exit(2) + torch.cuda.synchronize() + if mode == "correctness": + res = correctness(); res["mode"] = "correctness" + print("WRO_GDN_RESULT " + json.dumps(res)); sys.exit(0 if res["correctness_ok"] else 3) + elif mode == "timing": + ms = timing() + print("WRO_GDN_RESULT " + json.dumps({"mode": "timing", "timing_ms": ms, "iters": ITERS, + "rows": ROWS, "cols": COLS})); sys.exit(0) + else: + print("WRO_GDN_RESULT " + json.dumps({"error": "bad_mode"})); sys.exit(2) + + +if __name__ == "__main__": + main()