diff --git a/tasks/kfc/jit-source-arch-cache-key/task/.dockerignore b/tasks/kfc/jit-source-arch-cache-key/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/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/jit-source-arch-cache-key/task/environment/Dockerfile b/tasks/kfc/jit-source-arch-cache-key/task/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2ef93d08a240ccb445e7a46f175baa6e28682168 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/Dockerfile @@ -0,0 +1,161 @@ +# syntax=docker/dockerfile:1 +# ============================================================================= +# jit-source-arch-cache-key — 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/identity_key.py +# +# 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/insea-jit-source-arch-cache-key-loop16:loop-20260721T021500Z@sha256:b6e1405e15730a4d2605a010e43a832c62e79d533833700356bd01e7e77fea6d +# 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 <...>/jit-source-arch-cache-key/task +# docker build -f environment/Dockerfile -t fai/kfc-jit-source-arch-cache-key:oss . +# +# RUN docker run --rm -it fai/kfc-jit-source-arch-cache-key:oss +# SCORE docker run --rm -v "$PWD/tests:/tests:ro" fai/kfc-jit-source-arch-cache-key: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 = 4.0 . +# 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-jit-source-arch-cache-key: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 +# 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 + +# ---- 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 +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/identity_key.py" "/opt/verifier-baseline/identity_key.py" \ + && cmp "/app/repo/identity_key.py" "/opt/verifier-baseline/identity_key.py" \ + && chmod 0444 "/opt/verifier-baseline/identity_key.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/identity_key.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 ('identity_key.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/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/compute_reward.py b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..d544d3abb2809add146c425d2effa408753940cf --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/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/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/count_bench.py b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/count_bench.py new file mode 100644 index 0000000000000000000000000000000000000000..3676238dc20f5885897485c9fd1b1aa507ea755f --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/count_bench.py @@ -0,0 +1,92 @@ +"""Distinct-identity count for the build-spec identity task. + +The metric is a deterministic count: over a fixed labeled workload of build-specs, +how many DISTINCT identities does a module's ``identity_key`` produce? A conservative +identity treats every incidental spelling as different and emits many identities; a +normalizing identity collapses the equivalent spellings of each class down toward the +number of true classes. The score is the ratio baseline_count / candidate_count, so +fewer identities (for the same workload) is better -- but only while no two +genuinely-different specs share an identity. + +Invoked one MODE per process. ``test.sh`` runs candidate and the frozen baseline and +takes the ratio. No profiler / no numerics library -- it is a pure count. + +Modes: + candidate count distinct identities from /app/repo/identity_key.py; print COUNT= + baseline same, using the frozen baseline module (KB_BASELINE_MODULE) + verify (safety) confirm the candidate NEVER gives two different-class specs + the same identity; print VERIFY_OK / VERIFY_FAIL +""" + +import os +import sys + +from kb_identity_harness import ( + build_labeled_workload, + count_distinct_keys, + find_false_merges, + load_candidate, + load_module, + true_class_count, +) + + +def _baseline_module(): + path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/identity_key.py") + return load_module(path) + + +def mode_candidate(): + workload = build_labeled_workload() + print(f"COUNT={count_distinct_keys(load_candidate(), workload)}") + return 0 + + +def mode_baseline(): + workload = build_labeled_workload() + print(f"COUNT={count_distinct_keys(_baseline_module(), workload)}") + return 0 + + +def mode_verify(): + workload = build_labeled_workload() + classes = true_class_count(workload) + cand = load_candidate() + base = _baseline_module() + + cand_bad = find_false_merges(cand, workload) + if cand_bad: + sample = sorted((sorted(v), k) for k, v in cand_bad.items())[:3] + print(f"VERIFY_FAIL candidate false-merges distinct classes: {sample}") + return 1 + # sanity: the frozen baseline must itself be false-merge free. + base_bad = find_false_merges(base, workload) + if base_bad: + print(f"VERIFY_FAIL baseline unexpectedly false-merges: {sorted(base_bad.values())[:3]}") + return 1 + + cand_count = count_distinct_keys(cand, workload) + base_count = count_distinct_keys(base, workload) + # work-evidence: the baseline emits (base_count - classes) identities more than + # there are true classes; a full normalizer removes those redundant identities. + redundant = base_count - classes + print(f"VERIFY_OK signatures={len(workload)} true_classes={classes} " + f"candidate_identities={cand_count} baseline_identities={base_count} " + f"baseline_redundant_identities={redundant}") + return 0 + + +MODES = {"candidate": mode_candidate, "baseline": mode_baseline, "verify": mode_verify} + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "candidate" + fn = MODES.get(mode) + if fn is None: + print(f"unknown mode {mode!r}; expected one of {sorted(MODES)}") + sys.exit(2) + sys.exit(fn()) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/kb_identity_harness.py b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/kb_identity_harness.py new file mode 100644 index 0000000000000000000000000000000000000000..c0436e0566992d233c3d35f74eec5a53c6cdac54 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/kb_identity_harness.py @@ -0,0 +1,185 @@ +"""Shared harness for the build-spec identity task (CPU, pure Python). + +Provides: the candidate loader, the equivalence-rule tables (source normalization, +no-op option tokens), a deterministic *labeled* workload of build-specs grouped into +true equivalence classes, and helpers that turn a candidate ``identity_key`` into a +partition of that workload so the verifier can count distinct identities and detect a +false merge (two genuinely-different specs sharing an identity). Standard library +only, so the metric -- the number of distinct identities produced over the workload -- +is a deterministic count that is identical on any machine. + +The ground truth is the class LABEL attached to every spec when the workload is built: +two specs share a class iff they were generated as equivalent spellings of the same +base. candidate / baseline / oracle are all judged against these labels, never against +each other. +""" + +import hashlib +import importlib.util +import os +import re + + +# --------------------------------------------------------------------------- # +# Equivalence rules (also disclosed to the solver in instruction.md). +# --------------------------------------------------------------------------- # +# Source text: comments and surrounding whitespace do not change the built artifact, +# so they are incidental. Everything else in the source text is meaningful. +_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL) +_LINE_COMMENT = re.compile(r"//[^\n]*") + +# Option tokens equal to a build default; each is equivalent to the token being absent. +NOOP_OPTIONS = {"o0", "dbgoff", "std0"} + + +def canon_source(text): + """Canonical form of a source text: strip comments, collapse whitespace runs.""" + text = _BLOCK_COMMENT.sub(" ", text) + text = _LINE_COMMENT.sub(" ", text) + return " ".join(text.split()) + + +def canon_options(options): + """Canonical option set: drop no-op defaults, de-duplicate, sort (order-free).""" + kept = {o for o in (options or []) if o not in NOOP_OPTIONS} + return sorted(kept) + + +def _with_line_comment(source): + return source + " // tuned build\n" + + +def _with_block_comment(source): + return "/* rev2 */\n" + source + "\n\n " + + +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(), "identity_key.py") + spec = importlib.util.spec_from_file_location("candidate_identity_key", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + if not hasattr(mod, "identity_key"): + raise AttributeError(f"{path} does not define identity_key") + return mod + + +def load_module(path): + # deterministic module name derived from the path (no salted builtin hash()). + digest = hashlib.sha1(path.encode("utf-8")).hexdigest()[:12] + spec = importlib.util.spec_from_file_location("kb_identity_mod_" + digest, path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +# --------------------------------------------------------------------------- # +# Labeled workload: 12 true classes, each emitted as 4 equivalent spellings. +# Distinct classes differ in at least one meaning-bearing field (source text / +# target profile / effective option / toolchain tag / requested variant set). +# classes 0 and 1 differ ONLY in target profile -- a normalizer that drops the target +# merges them, which is a false merge (a wrong-target artifact would be reused). +# --------------------------------------------------------------------------- # +SRC_A = "o[i] = a[i] * b[i];" +SRC_B = "o[i] = a[i] + b[i];" +SRC_C = "o[i] = a[i] - b[i];" +SRC_D = "acc = acc + a[k] * b[k];" +SRC_E = "o[i] = a[i] > 0 ? a[i] : 0;" +SRC_F = "o[i] = a[i] / b[i];" + +# base = (source, target, effective_options, toolchain, variants) +CLASS_BASES = [ + (SRC_A, "p80", (), "v1", ()), # 0 (target-trap A) + (SRC_A, "p90", (), "v1", ()), # 1 (target-trap B: only target differs from 0) + (SRC_B, "p80", (), "v1", ()), # 2 distinct source + (SRC_C, "p80", (), "v1", ()), # 3 + (SRC_C, "p80", ("fast",), "v1", ()), # 4 effective option vs 3 + (SRC_D, "p80", ("o3",), "v1", ()), # 5 + (SRC_D, "p80", ("o2",), "v1", ()), # 6 different effective option value vs 5 + (SRC_D, "p80", ("o3",), "v2", ()), # 7 different toolchain tag vs 5 + (SRC_E, "p80", (), "v1", ()), # 8 + (SRC_E, "p80", (), "v1", ("kA",)), # 9 variant present vs 8 + (SRC_E, "p80", (), "v1", ("kB", "kC")), # 10 different variant set vs 9 + (SRC_F, "p86", ("fast", "o3"), "v1", ()), # 11 third target + two options +] + + +def _spellings(base): + """Return four equivalent-but-differently-spelled specs for one class. + + All four normalize to the same spec (they differ only in source comments/whitespace, + option order, redundant no-op options, incidental build annotations, and requested + variant order), yet all four are byte-distinct so a conservative identity produces + four identities. + """ + source, target, options, toolchain, variants = base + opts = list(options) + vs = list(variants) + + def build_spec(src, opt_list, build=None, var_list=None): + d = {"source": src, "target": target, "options": list(opt_list), "toolchain": toolchain} + if var_list: + d["variants"] = list(var_list) + if build is not None: + d["build"] = build + return d + + # S0: canonical source, options sorted, variants sorted, no build annotations. + s0 = build_spec(source, sorted(opts), var_list=sorted(vs)) + # S1: source carries a trailing line comment + reflowed spacing (ignored). + s1 = build_spec(_with_line_comment(source), sorted(opts), var_list=sorted(vs)) + # S2: options in a different ORDER + a redundant no-op token; a non-semantic build + # annotation block; requested variants in a different order. + s2 = build_spec(source, list(reversed(opts)) + ["o0"], + build={"tmpdir": "/tmp/b_" + target, "ts": 1700000000}, + var_list=list(reversed(vs))) + # S3: source with a block comment + extra newlines; options reversed with a DUPLICATE + # of the first option (when present) + a different no-op token; a different build. + dup = [opts[0]] if opts else [] + s3 = build_spec(_with_block_comment(source), list(reversed(opts)) + dup + ["dbgoff"], + build={"tmpdir": "/tmp/x", "ts": 1700000001, "host": "node7"}, + var_list=list(reversed(vs))) + return [s0, s1, s2, s3] + + +def build_labeled_workload(): + """Deterministic list of ``(class_id, spec)`` pairs (48 = 12 classes x 4).""" + workload = [] + for class_id, base in enumerate(CLASS_BASES): + for spec in _spellings(base): + workload.append((class_id, spec)) + return workload + + +def true_class_count(workload): + return len({class_id for class_id, _ in workload}) + + +# --------------------------------------------------------------------------- # +# Turn a candidate identity function into a partition of the workload. +# --------------------------------------------------------------------------- # +def key_to_classes(module, workload): + """Map each produced identity -> the set of true class ids that landed on it.""" + mapping = {} + for class_id, spec in workload: + key = module.identity_key(spec) + mapping.setdefault(key, set()).add(class_id) + return mapping + + +def find_false_merges(module, workload): + """Return {identity: {class_ids}} for identities shared by >1 true class. + + A non-empty result is a correctness failure: two genuinely different specs were + given the same identity. + """ + return {k: v for k, v in key_to_classes(module, workload).items() if len(v) > 1} + + +def count_distinct_keys(module, workload): + """Number of distinct identities the candidate produces over the workload.""" + return len({module.identity_key(spec) for _, spec in workload}) diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/ref_speedup.txt b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..5186d07068cfed4c3f4705df79c73e115dd35c43 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/ref_speedup.txt @@ -0,0 +1 @@ +4.0 diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test.sh b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..51e7d3ed2756dcf8b1ff20b8f3b331b396c8e6b4 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Verifier for jit-source-arch-cache-key (stable identity for a build-spec). +# Pattern A, ACCELERATION lane. Deterministic value axis = recompile_count = number of +# DISTINCT identities produced over a fixed labeled workload of build-specs. speedup = +# baseline_recompiles / candidate_recompiles (= baseline_distinct_identities / +# candidate_distinct_identities). Pure-Python stdlib -> a plain count, no profiler +# needed. A false merge (two different-class specs sharing an identity -- e.g. two specs +# differing only in target profile) is a hard correctness failure -> reward 0. +# Modes: candidate|noop|oracle|negative +set -uo pipefail +# The harness may exec this in a NON-login shell; pin PATH so python3 +# resolves regardless of the base's default profile. +export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/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/identity_key.py" +export KB_CANDIDATE_MODULE="$CAND_FILE" +export KB_BASELINE_MODULE=/opt/verifier-baseline/identity_key.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="cpu"; cand_keys=0; base_keys=0 + +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 identity_key.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 + identity_key.py) : ;; + *__pycache__*) : ;; + *) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;; + esac +done < "$LOG/anti_cheat_changed_files.txt" + +# anti-cheat: the normalization must be implemented in plain Python. Forbid pulling +# in a tensor/graph framework or reading the hidden workload/reference harness. +if [ -f "$CAND_FILE" ] && grep -Eq "cupy|jax|jaxlib|torch|triton|tensorflow|kb_identity_harness|test_identity_key|import[[:space:]]+tests|from[[:space:]]+tests" "$CAND_FILE"; then + anti_cheat_ok=false; add_hard "forbidden_framework_or_harness_reference" +fi + +# trusted restore: hidden suite ships in tests/ payload (fresh at scoring) +for f in test_identity_key.py count_bench.py kb_identity_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="cpu:$(uname -m 2>/dev/null || echo unknown)" + +# correctness gate (pure python; no GPU): stable string + no false merge properties. +if [ "$correctness_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 test_identity_key.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 + +# benchmark: (1) confirm the candidate never gives two different-class signatures the +# same identity (safety), then (2) count distinct identities for candidate vs the +# frozen baseline over the fixed workload; speedup = base_keys / cand_keys. +parse_count(){ sed -n 's/^COUNT=//p' "$1" 2>/dev/null | head -1; } +if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then + ( cd "$TESTS_DIR" && python3 count_bench.py verify ) > "$LOG/verify.log" 2>&1 + if [ $? -ne 0 ] || ! grep -q '^VERIFY_OK' "$LOG/verify.log"; then + benchmark_ok=false; add_hard "candidate_false_merge" + fi + if [ "$benchmark_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 count_bench.py candidate ) > "$LOG/cand.out.log" 2>&1 + ( cd "$TESTS_DIR" && python3 count_bench.py baseline ) > "$LOG/base.out.log" 2>&1 + cand_keys=$(parse_count "$LOG/cand.out.log"); cand_keys=${cand_keys:-0} + base_keys=$(parse_count "$LOG/base.out.log"); base_keys=${base_keys:-0} + if [ -z "$cand_keys" ] || [ "$cand_keys" -le 0 ] 2>/dev/null || [ -z "$base_keys" ] || [ "$base_keys" -le 0 ] 2>/dev/null; then + benchmark_ok=false; add_hard "distinct_identity_count_unparsed" + else + speedup=$(python3 -c "print(f'{$base_keys/$cand_keys:.5f}')") + fi + 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 cand_recompiles=$cand_keys base_recompiles=$base_keys speedup=$speedup ref=$ref_speedup hw=$hw reward=$REW" +[ -n "$REW" ] && exit 0 || exit 1 diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test_identity_key.py b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test_identity_key.py new file mode 100644 index 0000000000000000000000000000000000000000..38c53167dfa6c040bd5cffa857f664cbbfaaf76d --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test_identity_key.py @@ -0,0 +1,184 @@ +"""Correctness suite for the build-spec identity contract. + +Each case prints "CASE_PASS " or "CASE_FAIL : ". The runner counts +CASE_PASS lines. Pure standard library. + +Every case tests a *safety* / determinism property that any acceptable identity must +satisfy: it returns a stable string, and it NEVER gives two genuinely-different specs +the same identity. (Collapsing equivalent spellings is rewarded by the distinct-identity +count, not gated here -- the conservative baseline, which collapses nothing, is still +correct.) +""" + +import sys +import traceback + +from kb_identity_harness import ( + build_labeled_workload, + find_false_merges, + load_candidate, +) + +CASES = [] + + +def case(fn): + CASES.append(fn) + return fn + + +def spec(source, target, options=None, toolchain="v1", variants=None, build=None): + d = {"source": source, "target": target, "toolchain": toolchain} + if options is not None: + d["options"] = list(options) + if variants is not None: + d["variants"] = list(variants) + if build is not None: + d["build"] = dict(build) + return d + + +def _key(mod, s): + k = mod.identity_key(s) + if not isinstance(k, str) or not k: + raise AssertionError(f"identity_key must return a non-empty str, got {k!r}") + return k + + +@case +def returns_string_for_various(mod): + samples = [ + spec("o[i]=a[i]*b[i];", "p80"), + spec("o[i]=a[i]+b[i];", "p90", options=["fast"], variants=["kA"]), + spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2", build={"tmpdir": "/tmp/x"}), + {"source": "x=y;", "target": "p80"}, # minimal spec (no options/toolchain/variants/build) + ] + for s in samples: + _key(mod, s) + + +@case +def deterministic_repeat_same_object(mod): + s = spec("o[i]=a[i]*b[i];", "p80", options=["o3"]) + if _key(mod, s) != _key(mod, s): + raise AssertionError("identity not stable across repeated calls on the same object") + + +@case +def deterministic_fresh_build(mod): + a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"]) + b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"]) + if _key(mod, a) != _key(mod, b): + raise AssertionError("two independently built identical specs got different identities") + + +@case +def distinct_source_distinct_keys(mod): + a = spec("o[i]=a[i]*b[i];", "p80") + b = spec("o[i]=a[i]+b[i];", "p80") + if _key(mod, a) == _key(mod, b): + raise AssertionError("different source text collided") + + +@case +def distinct_target_distinct_keys(mod): + # same source + options + toolchain, different target profile -> a different artifact. + a = spec("o[i]=a[i]*b[i];", "p80", options=["o3"]) + b = spec("o[i]=a[i]*b[i];", "p90", options=["o3"]) + if _key(mod, a) == _key(mod, b): + raise AssertionError("specs for different target profiles collided (target dropped?)") + + +@case +def distinct_effective_option_distinct_keys(mod): + a = spec("o[i]=a[i]*b[i];", "p80", options=["fast"]) + b = spec("o[i]=a[i]*b[i];", "p80", options=[]) + if _key(mod, a) == _key(mod, b): + raise AssertionError("an effective (non-default) option was ignored") + + +@case +def distinct_option_value_distinct_keys(mod): + a = spec("acc+=a[k]*b[k];", "p80", options=["o3"]) + b = spec("acc+=a[k]*b[k];", "p80", options=["o2"]) + if _key(mod, a) == _key(mod, b): + raise AssertionError("two different option values were merged") + + +@case +def distinct_toolchain_distinct_keys(mod): + a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v1") + b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2") + if _key(mod, a) == _key(mod, b): + raise AssertionError("different toolchain tags were merged (a stale artifact would be reused)") + + +@case +def distinct_variant_set_distinct_keys(mod): + a = spec("o[i]=a[i]>0?a[i]:0;", "p80") # no variants + b = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]) # one variant + c = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kB", "kC"]) # a different variant set + keys = {_key(mod, a), _key(mod, b), _key(mod, c)} + if len(keys) != 3: + raise AssertionError("the requested variant set was ignored") + + +@case +def no_false_merge_full_workload(mod): + workload = build_labeled_workload() + bad = find_false_merges(mod, workload) + if bad: + sample = sorted((sorted(v), k) for k, v in bad.items())[:3] + raise AssertionError(f"identity shared by >1 true class (false merge): {sample}") + + +@case +def handles_edge_schema(mod): + empty_opts = spec("x=y;", "p80", options=[]) # explicit empty option set + no_opts = {"source": "x=y;", "target": "p80"} # no options/toolchain/variants keys + with_build = spec("x=y;", "p80", build={"ts": 1}) # only an incidental build annotation + for s in (empty_opts, no_opts, with_build): + _key(mod, s) + # even at the degenerate schema, two specs for different targets must stay distinct. + other_target = {"source": "x=y;", "target": "p90"} + if _key(mod, no_opts) == _key(mod, other_target): + raise AssertionError("degenerate specs for different targets collided") + + +@case +def many_distinct_specs_pairwise_distinct(mod): + specs = [ + spec("o[i]=a[i]*b[i];", "p80"), + spec("o[i]=a[i]+b[i];", "p80"), + spec("o[i]=a[i]*b[i];", "p90"), # target differs from #0 + spec("acc+=a[k]*b[k];", "p80", options=["o3"]), + spec("acc+=a[k]*b[k];", "p80", options=["o2"]), # option value differs + spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2"), # toolchain differs + spec("o[i]=a[i]/b[i];", "p86", options=["fast", "o3"]), + spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]), + ] + keys = [_key(mod, s) for s in specs] + if len(set(keys)) != len(specs): + raise AssertionError(f"expected {len(specs)} distinct identities, got {len(set(keys))}") + + +def main(): + mod = load_candidate() + passed = 0 + for fn_case in CASES: + name = fn_case.__name__ + try: + fn_case(mod) + 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/jit-source-arch-cache-key/task/environment/loop/private/manifest.json b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..a47a49adde4cb6e94ad5b1867ec043315f5a7e05 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/manifest.json @@ -0,0 +1,11 @@ +{ + "base_task_id": "jit-source-arch-cache-key", + "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": 4.0, + "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": "jit-source-arch-cache-key" +} diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/sanitize_feedback.py b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/sanitize_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8a0d1bb885be09f1cb9986cd55109548cea0a5 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/sanitize_feedback.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Sanitized feedback emitter (0700 root-owned) for jit-source-arch-cache-key. + +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 = 'identity_key(spec: dict) -> str returning a stable identity string for a build-spec; do NOT change the public signature' +PRIMITIVE_HINT = 'compute the identity from the spec content yourself with the Python standard library only; do not import a tensor / graph / array framework (torch / jax / jaxlib / cupy / tensorflow / triton) and do not read or import the test harness or its workload; do not reference those tokens even in comments (the scan is textual)' + + +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/jit-source-arch-cache-key/task/environment/loop/score_engine.sh b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/score_engine.sh new file mode 100644 index 0000000000000000000000000000000000000000..9bcfa8c851772ede7d9131a80fe7f8818df0a712 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/score_engine.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# DEV scoring engine (0700 root:root) for jit-source-arch-cache-key. 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/jit-source-arch-cache-key/task/environment/loop/submit.sh b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/submit.sh new file mode 100644 index 0000000000000000000000000000000000000000..9cea4923c24f750d61c9c94d66e8404704518d10 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/loop/submit.sh @@ -0,0 +1,232 @@ +#!/usr/bin/env bash +# Per-task 3-to-16-submission loop harness for +# jit-source-arch-cache-key. +# +# 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': 'jit-source-arch-cache-key', + '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/jit-source-arch-cache-key/task/environment/repo/identity_key.py b/tasks/kfc/jit-source-arch-cache-key/task/environment/repo/identity_key.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2a70120f13063ddbd2fc6cf86da1412024f70c --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/repo/identity_key.py @@ -0,0 +1,57 @@ +"""Stable identity for a build-spec. + +Public entry point: + ``identity_key(spec: dict) -> str`` + +A downstream stage keeps a table of already-produced *identities* and skips the +expensive step for a build-spec whose identity it has already seen. So the identity +must satisfy two properties: + +* two specs that are **equivalent** (they describe the same build, differing only in + incidental spelling) should map to the **same** identity, and +* two specs that are **genuinely different** must map to **different** identities -- a + collision between two different specs would let the wrong prior artifact be reused, + which is never acceptable. + +Build-spec shape +---------------- +A spec is a mapping with: + +* ``"source"``: the source text (a string). +* ``"target"``: the target-profile tag (a string) the artifact is produced for. +* ``"options"`` (optional): a list of build-option tokens (an unordered set). +* ``"toolchain"`` (optional): the toolchain-version tag (a string). +* ``"variants"`` (optional): a list of requested variant names (an unordered set). +* ``"build"`` (optional): a mapping of incidental build annotations. + +This starting implementation is **correct but conservative**: it derives the identity +from the spec almost verbatim (only the field order of a mapping is neutralized). It +never merges two different specs, but specs that are merely spelled differently are +treated as separate identities, so the downstream table holds more entries than there +are truly distinct builds and the expensive step is repeated once per spelling. +Reducing the number of distinct identities -- without ever merging two genuinely +different specs -- is the goal. +""" + +import json + + +def _fnv1a_64(text): + """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted).""" + h = 0xCBF29CE484222325 + for byte in text.encode("utf-8"): + h ^= byte + h = (h * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + return format(h, "016x") + + +def identity_key(spec): + """Return a stable string identity for ``spec``. + + Conservative baseline: serialize the spec with a fixed field order and digest it. + Only mapping-field order is neutralized; every other incidental difference (source + comments/whitespace, option order, redundant no-op options, annotation fields) + still yields a new identity. + """ + text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr) + return _fnv1a_64(text) diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/entrypoint.sh b/tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..5583a5916172b43f392c376334e4ea7dfc105ac7 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/entrypoint.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Canonical entrypoint: 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). CPU task: no +# GPU/venv assumptions — pin a portable PATH that resolves python3. +set -euo pipefail +export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/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/jit-source-arch-cache-key/task/environment/runtime/run_dev_bench.sh b/tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/run_dev_bench.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8fd282c68152c7e280b7ec95fbd37885d141587 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/run_dev_bench.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/bin:$PATH +printf '%s\n' 'Public development feedback only. Final verification runs additional trusted and hidden workloads.' +exit 0 diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/timer.sh b/tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/timer.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab6beb2f74e65a65c6dbda706b8e74b02d6ff5d9 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/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:/usr/local/bin:/usr/bin:/bin:$PATH +mkdir -p /app/.timer +echo 10800 > /app/.timer/remaining_secs +echo 10800 > /app/.timer/budget_secs diff --git a/tasks/kfc/jit-source-arch-cache-key/task/environment/verifier-correctness-manifest.json b/tasks/kfc/jit-source-arch-cache-key/task/environment/verifier-correctness-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..c265c4151f77ad6e96f11e16e2695d11d53ea348 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/environment/verifier-correctness-manifest.json @@ -0,0 +1,32 @@ +{ + "schema_version": "kernelbench_correctness_manifest_v1", + "task_id": "jit-source-arch-cache-key", + "task_kind": "acceleration", + "expected_case_count": 12, + "primary_workload": "buildspec-identity-count", + "ref_speedup": 1.0, + "ref_speedup_note": "Anchor 4.0 calibrated in oracle mode on the authoring CPU lane (Intel Sapphire Rapids). 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": "recompile_count", + "direction": "higher_is_better", + "target_hardware": "cpu (x86-64 Sapphire Rapids; pure-Python stdlib, fixed FNV-1a/sha1 hash -> deterministic count, no profiler)", + "value_axis": "recompile_count = number of DISTINCT identities produced by identity_key over a fixed labeled workload of build-specs; the naive baseline emits one identity per spelling (more identities than true classes), a full normalizer emits one per true equivalence class", + "correctness_axes": [ + "returns_string_for_various", + "deterministic_repeat_same_object", + "deterministic_fresh_build", + "distinct_source_distinct_keys", + "distinct_target_distinct_keys", + "distinct_effective_option_distinct_keys", + "distinct_option_value_distinct_keys", + "distinct_toolchain_distinct_keys", + "distinct_variant_set_distinct_keys", + "no_false_merge_full_workload", + "handles_edge_schema", + "many_distinct_specs_pairwise_distinct" + ], + "safety_gate": "no false merge: over the whole labeled workload no identity may be shared by two DIFFERENT true equivalence classes (checked by count_bench.py verify and by the no_false_merge_full_workload case); two specs differing only in target profile are DIFFERENT classes, so dropping the target profile from the identity is a false merge = correctness failure -> reward 0", + "public_symbol": "identity_key", + "primary_edit_paths": [ + "/app/repo/identity_key.py" + ] +} diff --git a/tasks/kfc/jit-source-arch-cache-key/task/instruction.md b/tasks/kfc/jit-source-arch-cache-key/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e5bf082f0ec42959f812705750eff59bfc36bd20 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/instruction.md @@ -0,0 +1,162 @@ +# Performance Optimization Task + +You are working on the work-reuse layer of a batch build service. The service receives +a stream of **build-specs**. Before running an expensive step for a spec, it computes a +short string **identity** for that spec and looks the identity up in a table of +already-produced identities; a hit means the prior artifact can be reused and the +expensive step is skipped. The file `identity_key.py` implements this identity as a +single function, `identity_key`. It is correct but produces far more distinct identities +than necessary. + +## Behavioral contract + +```python +def identity_key(spec: dict) -> str: + ... +``` + +A **build-spec** is a mapping describing one build request: + +- `"source"`: the source text — a string. +- `"target"`: the target-profile tag — a string. The produced artifact is specific to + this profile. +- `"options"` (optional): a list of build-option tokens (strings). The list is an + **unordered set** of options. +- `"toolchain"` (optional): the toolchain-version tag — a string. +- `"variants"` (optional): a list of requested variant names (strings), also an + **unordered set**. +- `"build"` (optional): a mapping of incidental build annotations. + +`identity_key(spec)` returns a **string**. It must be **deterministic and reproducible**: +the same spec (and any spec equivalent to it, see below) always yields the same string, +on every run and every machine — so derive it from the spec's content with a fixed rule, +not from anything process- or run-dependent. + +### When are two build-specs equivalent? + +Two specs are **equivalent** (they describe the same build and must receive the **same** +identity) when they are equal after applying **all** of the following normalizations. Any +difference that survives all of them makes the specs **distinct**, and distinct specs +must receive **different** identities. + +1. **Incidental build annotations are ignored.** The `"build"` mapping never affects the + identity — two specs that differ only in `"build"` (or in whether `"build"` is present + at all) are equivalent. +2. **Field order is irrelevant.** The order in which the keys of any mapping are written + does not matter. +3. **Source comments and whitespace are ignored.** Within `"source"`, line comments + (`// …` to end of line) and block comments (`/* … */`) carry no meaning, and runs of + whitespace are insignificant (any run of spaces/tabs/newlines is equivalent to a + single space; leading and trailing whitespace is insignificant). Two source texts that + are equal after removing comments and collapsing whitespace are equivalent. **Every + other difference in the source text is meaningful.** +4. **Options are an unordered set with no-op defaults folded.** The order of `"options"` + does not matter, and duplicate tokens are redundant. The tokens `"o0"`, `"dbgoff"`, + and `"std0"` are **no-op defaults**: each is equivalent to the token being absent. Any + **other** option token is meaningful and must be kept. +5. **Requested variants are an unordered set.** The order of `"variants"` does not matter + and duplicates are redundant, but **which** variant names are present is meaningful. + +Everything not listed above is **meaningful**: the source text (beyond comments and +whitespace), the target-profile tag, each effective (non-default) option token, the +toolchain-version tag, and the set of requested variant names. Specs that differ in any of +these are **distinct** and must not share an identity. + +## Why the current implementation is wasteful + +The current code derives the identity from the spec almost verbatim: it only neutralizes +the order of a mapping's keys. So two specs that are equivalent but merely spelled +differently — the same source with a comment added or reflowed whitespace, the same +options in a different order or with a no-op default written out, a stray build +annotation, the same variants listed in a different order — are treated as **different** +identities. The reuse table then holds one entry per spelling instead of one entry per +genuinely distinct build, and the expensive step is repeated for every spelling of the +same build. + +Make the identity **collapse the equivalent spellings** so that equivalent specs map to +one identity and the reuse table holds as few entries as there are genuinely distinct +builds — while **never** giving two genuinely different specs the same identity. + +## Correctness comes first + +A single **collision between two genuinely different specs** — for example treating two +different target profiles, two different source texts, two different effective option +values, two different toolchain tags, or two different variant sets as the same — is a +hard failure and scores **zero**, no matter how few identities you produce. In +particular, two specs that share everything but the **target profile** describe different +artifacts and must never collide. Merging spellings that are only *incidentally* different +is the goal; merging builds that are *actually* different is never allowed. The verifier +checks both a suite of correctness cases and, over the whole workload, that no identity is +shared by two genuinely different builds. + +## Forbidden + +Do **not** import a tensor / graph / array framework, and do **not** import or read the +test harness or its workload. Compute the identity yourself from the spec content using +the standard library only. The scoring harness scans your submitted file for those +references and scores the task `0` (do not reference them even in comments). + +## Scope + +Optimize the product implementation in `identity_key.py` only. Do **not** edit tests, +harnesses, workloads, or dependency/build files. The final submitted diff must contain +only product-code changes. Public/dev feedback, when present, is representative only; +final verification runs additional trusted and hidden workloads. + +## How this task is scored — ONE single submission (READ CAREFULLY) + +You get **exactly one** submission. There is no iterative loop, no budget of +retries, and no per-round feedback to improve against: the moment you submit, the +task is over. + +1. Read and profile the current implementation in `/app/repo/identity_key.py`, work out + what is slow, and make it faster — taking as long as you need. Test your work + yourself as much as you like *before* submitting: write your own scratch + benchmarks and your own correctness checks in a scratch directory you create. +2. When — and only when — you are confident the solution is both correct and as + fast as you can make it, submit it **once**: + + ``` + bash /opt/loop/submit.sh + ``` + +3. **Submitting ends the task.** That single call scores the current state of + `/app/repo`, records it as your final answer, and finalizes immediately. You + will not get a second attempt, and you will not get feedback you could iterate + on. A second call to `submit.sh` is refused. + +Because there is no second chance, spend your effort *before* the submission: +convince yourself the contract holds on every case you can think of (the shapes, +dtypes, boundary and error cases described above), and verify your own timing +shows a real improvement over the shipped implementation. A fast but incorrect +submission scores zero, and there is no round in which to repair it. + +The grade is produced by a full, trusted end-of-session verifier over more +workloads than anything you can see, so make the one submission you have a +genuinely correct one. + +## 🔴 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` 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. + +## 提交方式 + +本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。 +改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。 diff --git a/tasks/kfc/jit-source-arch-cache-key/task/pre_artifacts.sh b/tasks/kfc/jit-source-arch-cache-key/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..d91c4643cea4022fc202d5f9b3556b7234ce1ce7 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/pre_artifacts.sh @@ -0,0 +1,162 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/jit-source-arch-cache-key +# +# 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:127: WORKDIR /app/repo +# evidence Dockerfile:76: && cd /app/repo \ +# evidence Dockerfile:83: && test "$(git rev-list --count HEAD)" = "1" \ +# evidence test.sh:15: 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/jit-source-arch-cache-key/task/solution/README.md b/tasks/kfc/jit-source-arch-cache-key/task/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a396725758ac7cd86373fbfcf1556957f5f1753a --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/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/jit-source-arch-cache-key/task/solution/baseline2.patch b/tasks/kfc/jit-source-arch-cache-key/task/solution/baseline2.patch new file mode 100644 index 0000000000000000000000000000000000000000..1974b990aad4f68d27ea93dbdbb81fddd491ceb6 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/solution/baseline2.patch @@ -0,0 +1,88 @@ +diff --git a/identity_key.py b/identity_key.py +index 9e2a701..f9c4328 100644 +--- a/identity_key.py ++++ b/identity_key.py +@@ -1,57 +1,33 @@ +-"""Stable identity for a build-spec. +- +-Public entry point: +- ``identity_key(spec: dict) -> str`` +- +-A downstream stage keeps a table of already-produced *identities* and skips the +-expensive step for a build-spec whose identity it has already seen. So the identity +-must satisfy two properties: +- +-* two specs that are **equivalent** (they describe the same build, differing only in +- incidental spelling) should map to the **same** identity, and +-* two specs that are **genuinely different** must map to **different** identities -- a +- collision between two different specs would let the wrong prior artifact be reused, +- which is never acceptable. +- +-Build-spec shape +----------------- +-A spec is a mapping with: +- +-* ``"source"``: the source text (a string). +-* ``"target"``: the target-profile tag (a string) the artifact is produced for. +-* ``"options"`` (optional): a list of build-option tokens (an unordered set). +-* ``"toolchain"`` (optional): the toolchain-version tag (a string). +-* ``"variants"`` (optional): a list of requested variant names (an unordered set). +-* ``"build"`` (optional): a mapping of incidental build annotations. +- +-This starting implementation is **correct but conservative**: it derives the identity +-from the spec almost verbatim (only the field order of a mapping is neutralized). It +-never merges two different specs, but specs that are merely spelled differently are +-treated as separate identities, so the downstream table holds more entries than there +-are truly distinct builds and the expensive step is repeated once per spelling. +-Reducing the number of distinct identities -- without ever merging two genuinely +-different specs -- is the goal. ++"""baseline2 for jit-source-arch-cache-key (reviewer-only; NOT baked in image). ++ ++Same canonicalization SEMANTICS as the oracle (normalize source text, drop no-op ++options + de-dup + order-free, sort the variant set, drop build annotations, keep ++target profile + toolchain tag) but a DIFFERENT mechanism: build a canonical nested ++TUPLE and digest its ``repr`` with sha1, instead of the oracle's json + FNV-1a. It ++induces the same partition and the same identity count (~12) as the oracle -> the same ++speedup -- which proves the verifier scores the identity PARTITION, not a byte-match ++against oracle code. + """ + +-import json ++import hashlib ++import re + ++_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL) ++_LINE_COMMENT = re.compile(r"//[^\n]*") ++NOOP_OPTIONS = {"o0", "dbgoff", "std0"} + +-def _fnv1a_64(text): +- """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted).""" +- h = 0xCBF29CE484222325 +- for byte in text.encode("utf-8"): +- h ^= byte +- h = (h * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF +- return format(h, "016x") + ++def _canon_source(text): ++ text = _BLOCK_COMMENT.sub(" ", text or "") ++ text = _LINE_COMMENT.sub(" ", text) ++ return " ".join(text.split()) + +-def identity_key(spec): +- """Return a stable string identity for ``spec``. + +- Conservative baseline: serialize the spec with a fixed field order and digest it. +- Only mapping-field order is neutralized; every other incidental difference (source +- comments/whitespace, option order, redundant no-op options, annotation fields) +- still yields a new identity. +- """ +- text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr) +- return _fnv1a_64(text) ++def identity_key(spec): ++ source = _canon_source(spec.get("source", "")) ++ target = spec.get("target") ++ toolchain = spec.get("toolchain") ++ options = tuple(sorted({o for o in (spec.get("options") or []) if o not in NOOP_OPTIONS})) ++ variants = tuple(sorted(spec.get("variants") or [])) ++ canon = (source, target, toolchain, options, variants) ++ return hashlib.sha1(repr(canon).encode("utf-8")).hexdigest() diff --git a/tasks/kfc/jit-source-arch-cache-key/task/solution/negative.patch b/tasks/kfc/jit-source-arch-cache-key/task/solution/negative.patch new file mode 100644 index 0000000000000000000000000000000000000000..966563daa7a286492100323529ecca34b23d199d --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/solution/negative.patch @@ -0,0 +1,96 @@ +diff --git a/identity_key.py b/identity_key.py +index 9e2a701..98ec768 100644 +--- a/identity_key.py ++++ b/identity_key.py +@@ -1,43 +1,25 @@ +-"""Stable identity for a build-spec. +- +-Public entry point: +- ``identity_key(spec: dict) -> str`` +- +-A downstream stage keeps a table of already-produced *identities* and skips the +-expensive step for a build-spec whose identity it has already seen. So the identity +-must satisfy two properties: +- +-* two specs that are **equivalent** (they describe the same build, differing only in +- incidental spelling) should map to the **same** identity, and +-* two specs that are **genuinely different** must map to **different** identities -- a +- collision between two different specs would let the wrong prior artifact be reused, +- which is never acceptable. +- +-Build-spec shape +----------------- +-A spec is a mapping with: +- +-* ``"source"``: the source text (a string). +-* ``"target"``: the target-profile tag (a string) the artifact is produced for. +-* ``"options"`` (optional): a list of build-option tokens (an unordered set). +-* ``"toolchain"`` (optional): the toolchain-version tag (a string). +-* ``"variants"`` (optional): a list of requested variant names (an unordered set). +-* ``"build"`` (optional): a mapping of incidental build annotations. +- +-This starting implementation is **correct but conservative**: it derives the identity +-from the spec almost verbatim (only the field order of a mapping is neutralized). It +-never merges two different specs, but specs that are merely spelled differently are +-treated as separate identities, so the downstream table holds more entries than there +-are truly distinct builds and the expensive step is repeated once per spelling. +-Reducing the number of distinct identities -- without ever merging two genuinely +-different specs -- is the goal. ++"""Negative for jit-source-arch-cache-key (reviewer-only; NOT baked in image). ++ ++Over-canonicalizes: it DROPS the target-profile field (treats every target as the same). ++So two specs that differ ONLY in target profile -- e.g. the SAME source built for target ++``p80`` vs ``p90`` -- collapse to the SAME identity. That is a FALSE MERGE of two ++genuinely different builds: it would let an artifact produced for one target be reused ++for another (a wrong-target artifact). This must score reward 0 -- it fails ++distinct_target_distinct_keys, the whole-workload no_false_merge gate, and ++count_bench.py verify. It is otherwise a plausible full normalizer (source/options/ ++toolchain/variants all handled), which is exactly why the false-merge safety gate has ++to catch it. + """ + + import json ++import re ++ ++_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL) ++_LINE_COMMENT = re.compile(r"//[^\n]*") ++NOOP_OPTIONS = {"o0", "dbgoff", "std0"} + + + def _fnv1a_64(text): +- """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted).""" + h = 0xCBF29CE484222325 + for byte in text.encode("utf-8"): + h ^= byte +@@ -45,13 +27,22 @@ def _fnv1a_64(text): + return format(h, "016x") + + ++def _canon_source(text): ++ text = _BLOCK_COMMENT.sub(" ", text or "") ++ text = _LINE_COMMENT.sub(" ", text) ++ return " ".join(text.split()) ++ ++ + def identity_key(spec): +- """Return a stable string identity for ``spec``. +- +- Conservative baseline: serialize the spec with a fixed field order and digest it. +- Only mapping-field order is neutralized; every other incidental difference (source +- comments/whitespace, option order, redundant no-op options, annotation fields) +- still yields a new identity. +- """ +- text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr) +- return _fnv1a_64(text) ++ source = _canon_source(spec.get("source", "")) ++ toolchain = spec.get("toolchain") ++ options = sorted({o for o in (spec.get("options") or []) if o not in NOOP_OPTIONS}) ++ variants = sorted(spec.get("variants") or []) ++ # BUG (intentional): the target-profile field is dropped -> different targets collide. ++ canon = { ++ "source": source, ++ "toolchain": toolchain, ++ "options": options, ++ "variants": variants, ++ } ++ return _fnv1a_64(json.dumps(canon, sort_keys=True, separators=(",", ":"), default=repr)) diff --git a/tasks/kfc/jit-source-arch-cache-key/task/solution/oracle.patch b/tasks/kfc/jit-source-arch-cache-key/task/solution/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..25b9545278c9b848736d64d049a29dfc530d755a --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/solution/oracle.patch @@ -0,0 +1,97 @@ +diff --git a/identity_key.py b/identity_key.py +index 9e2a701..2f759db 100644 +--- a/identity_key.py ++++ b/identity_key.py +@@ -1,43 +1,25 @@ +-"""Stable identity for a build-spec. +- +-Public entry point: +- ``identity_key(spec: dict) -> str`` +- +-A downstream stage keeps a table of already-produced *identities* and skips the +-expensive step for a build-spec whose identity it has already seen. So the identity +-must satisfy two properties: +- +-* two specs that are **equivalent** (they describe the same build, differing only in +- incidental spelling) should map to the **same** identity, and +-* two specs that are **genuinely different** must map to **different** identities -- a +- collision between two different specs would let the wrong prior artifact be reused, +- which is never acceptable. +- +-Build-spec shape +----------------- +-A spec is a mapping with: +- +-* ``"source"``: the source text (a string). +-* ``"target"``: the target-profile tag (a string) the artifact is produced for. +-* ``"options"`` (optional): a list of build-option tokens (an unordered set). +-* ``"toolchain"`` (optional): the toolchain-version tag (a string). +-* ``"variants"`` (optional): a list of requested variant names (an unordered set). +-* ``"build"`` (optional): a mapping of incidental build annotations. +- +-This starting implementation is **correct but conservative**: it derives the identity +-from the spec almost verbatim (only the field order of a mapping is neutralized). It +-never merges two different specs, but specs that are merely spelled differently are +-treated as separate identities, so the downstream table holds more entries than there +-are truly distinct builds and the expensive step is repeated once per spelling. +-Reducing the number of distinct identities -- without ever merging two genuinely +-different specs -- is the goal. ++"""Oracle for jit-source-arch-cache-key (reviewer-only; NOT baked in image). ++ ++Full canonicalization: normalize the source text (strip comments, collapse whitespace), ++canonicalize the option set (drop no-op defaults, de-duplicate, sort for order-freedom), ++sort the requested variant set, drop the incidental build annotations, and KEEP every ++binary-affecting field (source, target profile, effective options, toolchain tag, ++variant set). Equivalent spellings collapse to one identity, so the number of distinct ++identities over the labeled workload equals the number of true equivalence classes ++(12) -- the fewest possible. speedup = baseline_recompiles / oracle_recompiles ++(~48 / ~12 = ~4.0). Never merges two genuinely different specs -- in particular two ++specs that differ only in target profile keep distinct identities. + """ + + import json ++import re ++ ++_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL) ++_LINE_COMMENT = re.compile(r"//[^\n]*") ++NOOP_OPTIONS = {"o0", "dbgoff", "std0"} + + + def _fnv1a_64(text): +- """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted).""" + h = 0xCBF29CE484222325 + for byte in text.encode("utf-8"): + h ^= byte +@@ -45,13 +27,23 @@ def _fnv1a_64(text): + return format(h, "016x") + + ++def _canon_source(text): ++ text = _BLOCK_COMMENT.sub(" ", text or "") ++ text = _LINE_COMMENT.sub(" ", text) ++ return " ".join(text.split()) ++ ++ + def identity_key(spec): +- """Return a stable string identity for ``spec``. +- +- Conservative baseline: serialize the spec with a fixed field order and digest it. +- Only mapping-field order is neutralized; every other incidental difference (source +- comments/whitespace, option order, redundant no-op options, annotation fields) +- still yields a new identity. +- """ +- text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr) +- return _fnv1a_64(text) ++ source = _canon_source(spec.get("source", "")) ++ target = spec.get("target") ++ toolchain = spec.get("toolchain") ++ options = sorted({o for o in (spec.get("options") or []) if o not in NOOP_OPTIONS}) ++ variants = sorted(spec.get("variants") or []) ++ canon = { ++ "source": source, ++ "target": target, ++ "toolchain": toolchain, ++ "options": options, ++ "variants": variants, ++ } ++ return _fnv1a_64(json.dumps(canon, sort_keys=True, separators=(",", ":"), default=repr)) diff --git a/tasks/kfc/jit-source-arch-cache-key/task/solution/solve.sh b/tasks/kfc/jit-source-arch-cache-key/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b2613b8114aab6ed5b6833a9e50926e729fd3ecb --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/solution/solve.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/jit-source-arch-cache-key +# 把本题的参考实现落成「与 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/identity_key.py +# 来源:tests/test.sh 的 CAND_FILE="$REPO/identity_key.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/jit-source-arch-cache-key/task +# IMG=fai/kfc-jit-source-arch-cache-key: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="jit-source-arch-cache-key" +REPO="${KFC_REPO_DIR:-/app/repo}" +SCOPE=("identity_key.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 '^identity_key\.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/jit-source-arch-cache-key/task/task.toml b/tasks/kfc/jit-source-arch-cache-key/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7ec0e5d7fab341df8737e8b6ff6a5944e2347dd6 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/task.toml @@ -0,0 +1,81 @@ +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "jit-source-arch-cache-key" +bench = "kfc" +kind = "performance" +language = "python" +title = "You are working on the work-reuse layer of a batch build service." +instruction = "instruction.md" + +[agent] +timeout_sec = 21600 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/insea-jit-source-arch-cache-key-loop16:loop-20260721T021500Z@sha256:b6e1405e15730a4d2605a010e43a832c62e79d533833700356bd01e7e77fea6d +# Open-source build: `cd && docker build -f environment/Dockerfile -t fai/kfc-jit-source-arch-cache-key:oss .` +[environment] +docker_image = "fai/kfc-jit-source-arch-cache-key:oss" +dockerfile = "environment/Dockerfile" +build_timeout_sec = 3600 +cpus = 8 +memory_mb = 16000 +gpus = 0 +allow_internet = false + +[verifier] +entrypoint = "tests/test.sh" +mode = "shared" +timeout_sec = 3600 +task_kind = "acceleration" +contract_pattern = "A" +timing_metric = "recompile_count" +candidate_source_root = "/app/repo" +primary_edit_paths = ["/app/repo/identity_key.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 = "buildspec_identity_recompile_count_speedup" +goal = "maximize" +metric_kind = "recompile_count" +reward_formula = "acceleration: reward = measured speedup = baseline_recompiles / candidate_recompiles, where recompile_count = the number of DISTINCT identities a module's identity_key produces over a fixed labeled workload of build-specs (48 specs = 12 true equivalence classes x 4 spellings). Deterministic and hardware-portable (pure-Python stdlib, fixed FNV-1a/sha1 hash; no profiler). The frozen baseline emits one identity per spelling (~48) so its own speedup is ~1.0; a full normalizer emits one per true class (~12) -> speedup ~4.0. The 12-case hidden correctness suite, the whole-workload no-false-merge safety gate (any identity shared by two DIFFERENT true classes = correctness failure -> reward 0; two specs differing only in target profile are DIFFERENT classes), and the anti-cheat (only identity_key.py may change; no tensor/graph framework or harness import) are hard gates." +ref_speedup = 4.0 +ref_speedup_source = "tests/ref_speedup.txt" +calibrated_on = "Intel Sapphire Rapids CPU lane" +correctness_gates = [ + "hidden_case_suite", + "returns_string_for_various", + "deterministic_repeat_same_object", + "deterministic_fresh_build", + "distinct_source_distinct_keys", + "distinct_target_distinct_keys", + "distinct_effective_option_distinct_keys", + "distinct_option_value_distinct_keys", + "distinct_toolchain_distinct_keys", + "distinct_variant_set_distinct_keys", + "no_false_merge_full_workload", + "handles_edge_schema", + "many_distinct_specs_pairwise_distinct", + "candidate_false_merge", + "anti_cheat_forbidden_edit", + "forbidden_framework_or_harness_reference", +] + +[loop] +min_submissions = 1 +max_submissions = 1 +submit = "bash /opt/loop/submit.sh" +mode = "baked" +feedback_surface = "/opt/loop/submit.sh" +# single-submission — 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/jit-source-arch-cache-key/task/tests/compute_reward.py b/tasks/kfc/jit-source-arch-cache-key/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..293f6a76688fe59762696f006ba93f8aa54d5ec0 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/tests/compute_reward.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Canonical kernelbench reward writer (task-agnostic; do NOT special-case a task here). + +Reward definition: + + performance (acceleration): + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + -> matching the oracle (speedup == ref_speedup) scores 0.5 + -> reaching ref_speedup**2 caps at 1.0 + value range is strictly [0.0, 1.0] + HARD PRE-GATES (any one hit => reward 0, the formula is never evaluated): + build/import failure, ANY correctness case fail, cheating, forbidden + edit path, speedup <= 1, ref_speedup <= 1. + implementation (correctness): + reward = 1.0 iff EVERY test case passes and no cheating, else 0.0 (binary). + +Reads: /logs/verifier/verifier_state.json, /logs/verifier/benchmark_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" +REWARD = LOG / "reward.json" +TEXT = LOG / "reward.txt" + +# Every gate below is a HARD gate: build/import origin, correctness (visible AND +# hidden), baseline sanity, benchmark validity, anti-cheat / forbidden-path. +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 _case_counts(state, bench): + """(passed, total) test cases when the verifier reports them; else (None, None).""" + exp = state.get("expected_case_count") + act = state.get("actual_case_count") + try: + exp = int(exp); act = int(act) + except Exception: + return (None, None) + if exp <= 0: + return (None, None) + return (act, exp) + + +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) + + passed, total = _case_counts(state, bench) + # A short test suite is a correctness FAIL, not a partial credit: reward.md + # requires EVERY case to pass (implementation) / no case to fail (performance). + all_cases_ok = True + if passed is not None and total is not None and passed < total: + all_cases_ok = False + if not any("case" in str(h) or "correctness" in str(h) for h in hard): + hard.append("correctness_cases_incomplete") + + speedup = ref = 1.0 + reward = 0.0 + + if task_kind == "correctness": + # ---- implementation class: BINARY. All cases pass + no cheating -> 1.0, else 0.0. + reward = 1.0 if (gates_ok and all_cases_ok and not hard) else 0.0 + if reward == 0.0 and not hard: + hard.append("correctness_or_validation_incomplete") + else: + # ---- performance class: log-ratio reward, behind the hard pre-gates. + 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") + + if not (math.isfinite(speedup) and speedup > 0.0): + hard.append("invalid_primary_metric_value") + # pre-gate 5: the candidate must actually beat the baseline + elif speedup <= 1.0: + hard.append("speedup_not_above_baseline") + # pre-gate 6: the reference anchor must be a real speedup + if not (math.isfinite(ref) and ref > 1.0): + hard.append("ref_speedup_invalid") + + if gates_ok and all_cases_ok and not hard: + reward = min(1.0, max(0.0, min(1.0, math.log(speedup) / math.log(ref) - 1.0))) + # value range is strictly [0.0, 1.0] + reward = max(0.0, min(1.0, reward)) + else: + reward = 0.0 + if not hard: + hard.append("validation_incomplete_or_bad_speedup") + + out = { + "schema_version": "kernelbench_reward_v2_logratio", + # reward.md result-JSON field: "performance" | "implementation" + "task_type": "implementation" if task_kind == "correctness" else "performance", + "task_kind": task_kind, + "reward": reward, + "speedup": speedup, + "ref_speedup": ref, + "reward_formula": ("binary: 1.0 iff all cases pass and no cheating, else 0.0" + if task_kind == "correctness" + else "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; 0 if any hard pre-gate hit"), + "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.md result-JSON contract: performance always carries `cv`, + # implementation always carries `tests{passed,total}`. + if out["task_type"] == "performance": + out["cv"] = bench.get("cv") # None when this harness does not measure dispersion + if passed is not None and total is not None: + out["tests"] = {"passed": passed, "total": total} + else: + out["tests"] = ({"passed": passed, "total": total} + if (passed is not None and total is not None) + else {"passed": 0 if hard else 1, "total": 1}) + 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/jit-source-arch-cache-key/task/tests/count_bench.py b/tasks/kfc/jit-source-arch-cache-key/task/tests/count_bench.py new file mode 100644 index 0000000000000000000000000000000000000000..3676238dc20f5885897485c9fd1b1aa507ea755f --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/tests/count_bench.py @@ -0,0 +1,92 @@ +"""Distinct-identity count for the build-spec identity task. + +The metric is a deterministic count: over a fixed labeled workload of build-specs, +how many DISTINCT identities does a module's ``identity_key`` produce? A conservative +identity treats every incidental spelling as different and emits many identities; a +normalizing identity collapses the equivalent spellings of each class down toward the +number of true classes. The score is the ratio baseline_count / candidate_count, so +fewer identities (for the same workload) is better -- but only while no two +genuinely-different specs share an identity. + +Invoked one MODE per process. ``test.sh`` runs candidate and the frozen baseline and +takes the ratio. No profiler / no numerics library -- it is a pure count. + +Modes: + candidate count distinct identities from /app/repo/identity_key.py; print COUNT= + baseline same, using the frozen baseline module (KB_BASELINE_MODULE) + verify (safety) confirm the candidate NEVER gives two different-class specs + the same identity; print VERIFY_OK / VERIFY_FAIL +""" + +import os +import sys + +from kb_identity_harness import ( + build_labeled_workload, + count_distinct_keys, + find_false_merges, + load_candidate, + load_module, + true_class_count, +) + + +def _baseline_module(): + path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/identity_key.py") + return load_module(path) + + +def mode_candidate(): + workload = build_labeled_workload() + print(f"COUNT={count_distinct_keys(load_candidate(), workload)}") + return 0 + + +def mode_baseline(): + workload = build_labeled_workload() + print(f"COUNT={count_distinct_keys(_baseline_module(), workload)}") + return 0 + + +def mode_verify(): + workload = build_labeled_workload() + classes = true_class_count(workload) + cand = load_candidate() + base = _baseline_module() + + cand_bad = find_false_merges(cand, workload) + if cand_bad: + sample = sorted((sorted(v), k) for k, v in cand_bad.items())[:3] + print(f"VERIFY_FAIL candidate false-merges distinct classes: {sample}") + return 1 + # sanity: the frozen baseline must itself be false-merge free. + base_bad = find_false_merges(base, workload) + if base_bad: + print(f"VERIFY_FAIL baseline unexpectedly false-merges: {sorted(base_bad.values())[:3]}") + return 1 + + cand_count = count_distinct_keys(cand, workload) + base_count = count_distinct_keys(base, workload) + # work-evidence: the baseline emits (base_count - classes) identities more than + # there are true classes; a full normalizer removes those redundant identities. + redundant = base_count - classes + print(f"VERIFY_OK signatures={len(workload)} true_classes={classes} " + f"candidate_identities={cand_count} baseline_identities={base_count} " + f"baseline_redundant_identities={redundant}") + return 0 + + +MODES = {"candidate": mode_candidate, "baseline": mode_baseline, "verify": mode_verify} + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "candidate" + fn = MODES.get(mode) + if fn is None: + print(f"unknown mode {mode!r}; expected one of {sorted(MODES)}") + sys.exit(2) + sys.exit(fn()) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/jit-source-arch-cache-key/task/tests/kb_identity_harness.py b/tasks/kfc/jit-source-arch-cache-key/task/tests/kb_identity_harness.py new file mode 100644 index 0000000000000000000000000000000000000000..c0436e0566992d233c3d35f74eec5a53c6cdac54 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/tests/kb_identity_harness.py @@ -0,0 +1,185 @@ +"""Shared harness for the build-spec identity task (CPU, pure Python). + +Provides: the candidate loader, the equivalence-rule tables (source normalization, +no-op option tokens), a deterministic *labeled* workload of build-specs grouped into +true equivalence classes, and helpers that turn a candidate ``identity_key`` into a +partition of that workload so the verifier can count distinct identities and detect a +false merge (two genuinely-different specs sharing an identity). Standard library +only, so the metric -- the number of distinct identities produced over the workload -- +is a deterministic count that is identical on any machine. + +The ground truth is the class LABEL attached to every spec when the workload is built: +two specs share a class iff they were generated as equivalent spellings of the same +base. candidate / baseline / oracle are all judged against these labels, never against +each other. +""" + +import hashlib +import importlib.util +import os +import re + + +# --------------------------------------------------------------------------- # +# Equivalence rules (also disclosed to the solver in instruction.md). +# --------------------------------------------------------------------------- # +# Source text: comments and surrounding whitespace do not change the built artifact, +# so they are incidental. Everything else in the source text is meaningful. +_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL) +_LINE_COMMENT = re.compile(r"//[^\n]*") + +# Option tokens equal to a build default; each is equivalent to the token being absent. +NOOP_OPTIONS = {"o0", "dbgoff", "std0"} + + +def canon_source(text): + """Canonical form of a source text: strip comments, collapse whitespace runs.""" + text = _BLOCK_COMMENT.sub(" ", text) + text = _LINE_COMMENT.sub(" ", text) + return " ".join(text.split()) + + +def canon_options(options): + """Canonical option set: drop no-op defaults, de-duplicate, sort (order-free).""" + kept = {o for o in (options or []) if o not in NOOP_OPTIONS} + return sorted(kept) + + +def _with_line_comment(source): + return source + " // tuned build\n" + + +def _with_block_comment(source): + return "/* rev2 */\n" + source + "\n\n " + + +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(), "identity_key.py") + spec = importlib.util.spec_from_file_location("candidate_identity_key", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + if not hasattr(mod, "identity_key"): + raise AttributeError(f"{path} does not define identity_key") + return mod + + +def load_module(path): + # deterministic module name derived from the path (no salted builtin hash()). + digest = hashlib.sha1(path.encode("utf-8")).hexdigest()[:12] + spec = importlib.util.spec_from_file_location("kb_identity_mod_" + digest, path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +# --------------------------------------------------------------------------- # +# Labeled workload: 12 true classes, each emitted as 4 equivalent spellings. +# Distinct classes differ in at least one meaning-bearing field (source text / +# target profile / effective option / toolchain tag / requested variant set). +# classes 0 and 1 differ ONLY in target profile -- a normalizer that drops the target +# merges them, which is a false merge (a wrong-target artifact would be reused). +# --------------------------------------------------------------------------- # +SRC_A = "o[i] = a[i] * b[i];" +SRC_B = "o[i] = a[i] + b[i];" +SRC_C = "o[i] = a[i] - b[i];" +SRC_D = "acc = acc + a[k] * b[k];" +SRC_E = "o[i] = a[i] > 0 ? a[i] : 0;" +SRC_F = "o[i] = a[i] / b[i];" + +# base = (source, target, effective_options, toolchain, variants) +CLASS_BASES = [ + (SRC_A, "p80", (), "v1", ()), # 0 (target-trap A) + (SRC_A, "p90", (), "v1", ()), # 1 (target-trap B: only target differs from 0) + (SRC_B, "p80", (), "v1", ()), # 2 distinct source + (SRC_C, "p80", (), "v1", ()), # 3 + (SRC_C, "p80", ("fast",), "v1", ()), # 4 effective option vs 3 + (SRC_D, "p80", ("o3",), "v1", ()), # 5 + (SRC_D, "p80", ("o2",), "v1", ()), # 6 different effective option value vs 5 + (SRC_D, "p80", ("o3",), "v2", ()), # 7 different toolchain tag vs 5 + (SRC_E, "p80", (), "v1", ()), # 8 + (SRC_E, "p80", (), "v1", ("kA",)), # 9 variant present vs 8 + (SRC_E, "p80", (), "v1", ("kB", "kC")), # 10 different variant set vs 9 + (SRC_F, "p86", ("fast", "o3"), "v1", ()), # 11 third target + two options +] + + +def _spellings(base): + """Return four equivalent-but-differently-spelled specs for one class. + + All four normalize to the same spec (they differ only in source comments/whitespace, + option order, redundant no-op options, incidental build annotations, and requested + variant order), yet all four are byte-distinct so a conservative identity produces + four identities. + """ + source, target, options, toolchain, variants = base + opts = list(options) + vs = list(variants) + + def build_spec(src, opt_list, build=None, var_list=None): + d = {"source": src, "target": target, "options": list(opt_list), "toolchain": toolchain} + if var_list: + d["variants"] = list(var_list) + if build is not None: + d["build"] = build + return d + + # S0: canonical source, options sorted, variants sorted, no build annotations. + s0 = build_spec(source, sorted(opts), var_list=sorted(vs)) + # S1: source carries a trailing line comment + reflowed spacing (ignored). + s1 = build_spec(_with_line_comment(source), sorted(opts), var_list=sorted(vs)) + # S2: options in a different ORDER + a redundant no-op token; a non-semantic build + # annotation block; requested variants in a different order. + s2 = build_spec(source, list(reversed(opts)) + ["o0"], + build={"tmpdir": "/tmp/b_" + target, "ts": 1700000000}, + var_list=list(reversed(vs))) + # S3: source with a block comment + extra newlines; options reversed with a DUPLICATE + # of the first option (when present) + a different no-op token; a different build. + dup = [opts[0]] if opts else [] + s3 = build_spec(_with_block_comment(source), list(reversed(opts)) + dup + ["dbgoff"], + build={"tmpdir": "/tmp/x", "ts": 1700000001, "host": "node7"}, + var_list=list(reversed(vs))) + return [s0, s1, s2, s3] + + +def build_labeled_workload(): + """Deterministic list of ``(class_id, spec)`` pairs (48 = 12 classes x 4).""" + workload = [] + for class_id, base in enumerate(CLASS_BASES): + for spec in _spellings(base): + workload.append((class_id, spec)) + return workload + + +def true_class_count(workload): + return len({class_id for class_id, _ in workload}) + + +# --------------------------------------------------------------------------- # +# Turn a candidate identity function into a partition of the workload. +# --------------------------------------------------------------------------- # +def key_to_classes(module, workload): + """Map each produced identity -> the set of true class ids that landed on it.""" + mapping = {} + for class_id, spec in workload: + key = module.identity_key(spec) + mapping.setdefault(key, set()).add(class_id) + return mapping + + +def find_false_merges(module, workload): + """Return {identity: {class_ids}} for identities shared by >1 true class. + + A non-empty result is a correctness failure: two genuinely different specs were + given the same identity. + """ + return {k: v for k, v in key_to_classes(module, workload).items() if len(v) > 1} + + +def count_distinct_keys(module, workload): + """Number of distinct identities the candidate produces over the workload.""" + return len({module.identity_key(spec) for _, spec in workload}) diff --git a/tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.caveat.md b/tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..2c1288aa9fe793a856bd4d9a8f2a55226d09498c --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +`ref_speedup.txt` 里的 **4.0** 是 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-jit-source-arch-cache-key: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/jit-source-arch-cache-key/task/tests/ref_speedup.txt b/tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..5186d07068cfed4c3f4705df79c73e115dd35c43 --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.txt @@ -0,0 +1 @@ +4.0 diff --git a/tasks/kfc/jit-source-arch-cache-key/task/tests/test.sh b/tasks/kfc/jit-source-arch-cache-key/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aecf0b43fda4d590c2b2d249a1e4b34259c83bfc --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/tests/test.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Verifier for jit-source-arch-cache-key (stable identity for a build-spec). +# Pattern A, ACCELERATION lane. Deterministic value axis = recompile_count = number of +# DISTINCT identities produced over a fixed labeled workload of build-specs. speedup = +# baseline_recompiles / candidate_recompiles (= baseline_distinct_identities / +# candidate_distinct_identities). Pure-Python stdlib -> a plain count, no profiler +# needed. A false merge (two different-class specs sharing an identity -- e.g. two specs +# differing only in target profile) is a hard correctness failure -> reward 0. +# Modes: candidate|noop|oracle|negative +set -uo pipefail +# The harness may exec this in a NON-login shell; pin PATH so python3 +# resolves regardless of the base's default profile. +export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/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/identity_key.py" +export KB_CANDIDATE_MODULE="$CAND_FILE" +export KB_BASELINE_MODULE=/opt/verifier-baseline/identity_key.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="cpu"; cand_keys=0; base_keys=0 + +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 identity_key.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 + identity_key.py) : ;; + *__pycache__*) : ;; + *) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;; + esac +done < "$LOG/anti_cheat_changed_files.txt" + +# anti-cheat: the normalization must be implemented in plain Python. Forbid pulling +# in a tensor/graph framework or reading the hidden workload/reference harness. +if [ -f "$CAND_FILE" ] && grep -Eq "cupy|jax|jaxlib|torch|triton|tensorflow|kb_identity_harness|test_identity_key|import[[:space:]]+tests|from[[:space:]]+tests" "$CAND_FILE"; then + anti_cheat_ok=false; add_hard "forbidden_framework_or_harness_reference" +fi + +# trusted restore: hidden suite ships in tests/ payload (fresh at scoring) +for f in test_identity_key.py count_bench.py kb_identity_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="cpu:$(uname -m 2>/dev/null || echo unknown)" + +# correctness gate (pure python; no GPU): stable string + no false merge properties. +if [ "$correctness_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 test_identity_key.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 + +# benchmark: (1) confirm the candidate never gives two different-class signatures the +# same identity (safety), then (2) count distinct identities for candidate vs the +# frozen baseline over the fixed workload; speedup = base_keys / cand_keys. +parse_count(){ sed -n 's/^COUNT=//p' "$1" 2>/dev/null | head -1; } +if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then + ( cd "$TESTS_DIR" && python3 count_bench.py verify ) > "$LOG/verify.log" 2>&1 + if [ $? -ne 0 ] || ! grep -q '^VERIFY_OK' "$LOG/verify.log"; then + benchmark_ok=false; add_hard "candidate_false_merge" + fi + if [ "$benchmark_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 count_bench.py candidate ) > "$LOG/cand.out.log" 2>&1 + ( cd "$TESTS_DIR" && python3 count_bench.py baseline ) > "$LOG/base.out.log" 2>&1 + cand_keys=$(parse_count "$LOG/cand.out.log"); cand_keys=${cand_keys:-0} + base_keys=$(parse_count "$LOG/base.out.log"); base_keys=${base_keys:-0} + if [ -z "$cand_keys" ] || [ "$cand_keys" -le 0 ] 2>/dev/null || [ -z "$base_keys" ] || [ "$base_keys" -le 0 ] 2>/dev/null; then + benchmark_ok=false; add_hard "distinct_identity_count_unparsed" + else + speedup=$(python3 -c "print(f'{$base_keys/$cand_keys:.5f}')") + fi + 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 cand_recompiles=$cand_keys base_recompiles=$base_keys speedup=$speedup ref=$ref_speedup hw=$hw reward=$REW" +[ -n "$REW" ] && exit 0 || exit 1 diff --git a/tasks/kfc/jit-source-arch-cache-key/task/tests/test_identity_key.py b/tasks/kfc/jit-source-arch-cache-key/task/tests/test_identity_key.py new file mode 100644 index 0000000000000000000000000000000000000000..38c53167dfa6c040bd5cffa857f664cbbfaaf76d --- /dev/null +++ b/tasks/kfc/jit-source-arch-cache-key/task/tests/test_identity_key.py @@ -0,0 +1,184 @@ +"""Correctness suite for the build-spec identity contract. + +Each case prints "CASE_PASS " or "CASE_FAIL : ". The runner counts +CASE_PASS lines. Pure standard library. + +Every case tests a *safety* / determinism property that any acceptable identity must +satisfy: it returns a stable string, and it NEVER gives two genuinely-different specs +the same identity. (Collapsing equivalent spellings is rewarded by the distinct-identity +count, not gated here -- the conservative baseline, which collapses nothing, is still +correct.) +""" + +import sys +import traceback + +from kb_identity_harness import ( + build_labeled_workload, + find_false_merges, + load_candidate, +) + +CASES = [] + + +def case(fn): + CASES.append(fn) + return fn + + +def spec(source, target, options=None, toolchain="v1", variants=None, build=None): + d = {"source": source, "target": target, "toolchain": toolchain} + if options is not None: + d["options"] = list(options) + if variants is not None: + d["variants"] = list(variants) + if build is not None: + d["build"] = dict(build) + return d + + +def _key(mod, s): + k = mod.identity_key(s) + if not isinstance(k, str) or not k: + raise AssertionError(f"identity_key must return a non-empty str, got {k!r}") + return k + + +@case +def returns_string_for_various(mod): + samples = [ + spec("o[i]=a[i]*b[i];", "p80"), + spec("o[i]=a[i]+b[i];", "p90", options=["fast"], variants=["kA"]), + spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2", build={"tmpdir": "/tmp/x"}), + {"source": "x=y;", "target": "p80"}, # minimal spec (no options/toolchain/variants/build) + ] + for s in samples: + _key(mod, s) + + +@case +def deterministic_repeat_same_object(mod): + s = spec("o[i]=a[i]*b[i];", "p80", options=["o3"]) + if _key(mod, s) != _key(mod, s): + raise AssertionError("identity not stable across repeated calls on the same object") + + +@case +def deterministic_fresh_build(mod): + a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"]) + b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"]) + if _key(mod, a) != _key(mod, b): + raise AssertionError("two independently built identical specs got different identities") + + +@case +def distinct_source_distinct_keys(mod): + a = spec("o[i]=a[i]*b[i];", "p80") + b = spec("o[i]=a[i]+b[i];", "p80") + if _key(mod, a) == _key(mod, b): + raise AssertionError("different source text collided") + + +@case +def distinct_target_distinct_keys(mod): + # same source + options + toolchain, different target profile -> a different artifact. + a = spec("o[i]=a[i]*b[i];", "p80", options=["o3"]) + b = spec("o[i]=a[i]*b[i];", "p90", options=["o3"]) + if _key(mod, a) == _key(mod, b): + raise AssertionError("specs for different target profiles collided (target dropped?)") + + +@case +def distinct_effective_option_distinct_keys(mod): + a = spec("o[i]=a[i]*b[i];", "p80", options=["fast"]) + b = spec("o[i]=a[i]*b[i];", "p80", options=[]) + if _key(mod, a) == _key(mod, b): + raise AssertionError("an effective (non-default) option was ignored") + + +@case +def distinct_option_value_distinct_keys(mod): + a = spec("acc+=a[k]*b[k];", "p80", options=["o3"]) + b = spec("acc+=a[k]*b[k];", "p80", options=["o2"]) + if _key(mod, a) == _key(mod, b): + raise AssertionError("two different option values were merged") + + +@case +def distinct_toolchain_distinct_keys(mod): + a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v1") + b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2") + if _key(mod, a) == _key(mod, b): + raise AssertionError("different toolchain tags were merged (a stale artifact would be reused)") + + +@case +def distinct_variant_set_distinct_keys(mod): + a = spec("o[i]=a[i]>0?a[i]:0;", "p80") # no variants + b = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]) # one variant + c = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kB", "kC"]) # a different variant set + keys = {_key(mod, a), _key(mod, b), _key(mod, c)} + if len(keys) != 3: + raise AssertionError("the requested variant set was ignored") + + +@case +def no_false_merge_full_workload(mod): + workload = build_labeled_workload() + bad = find_false_merges(mod, workload) + if bad: + sample = sorted((sorted(v), k) for k, v in bad.items())[:3] + raise AssertionError(f"identity shared by >1 true class (false merge): {sample}") + + +@case +def handles_edge_schema(mod): + empty_opts = spec("x=y;", "p80", options=[]) # explicit empty option set + no_opts = {"source": "x=y;", "target": "p80"} # no options/toolchain/variants keys + with_build = spec("x=y;", "p80", build={"ts": 1}) # only an incidental build annotation + for s in (empty_opts, no_opts, with_build): + _key(mod, s) + # even at the degenerate schema, two specs for different targets must stay distinct. + other_target = {"source": "x=y;", "target": "p90"} + if _key(mod, no_opts) == _key(mod, other_target): + raise AssertionError("degenerate specs for different targets collided") + + +@case +def many_distinct_specs_pairwise_distinct(mod): + specs = [ + spec("o[i]=a[i]*b[i];", "p80"), + spec("o[i]=a[i]+b[i];", "p80"), + spec("o[i]=a[i]*b[i];", "p90"), # target differs from #0 + spec("acc+=a[k]*b[k];", "p80", options=["o3"]), + spec("acc+=a[k]*b[k];", "p80", options=["o2"]), # option value differs + spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2"), # toolchain differs + spec("o[i]=a[i]/b[i];", "p86", options=["fast", "o3"]), + spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]), + ] + keys = [_key(mod, s) for s in specs] + if len(set(keys)) != len(specs): + raise AssertionError(f"expected {len(specs)} distinct identities, got {len(set(keys))}") + + +def main(): + mod = load_candidate() + passed = 0 + for fn_case in CASES: + name = fn_case.__name__ + try: + fn_case(mod) + 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/s4-fft-longconv/task/.dockerignore b/tasks/kfc/s4-fft-longconv/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/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/s4-fft-longconv/task/environment/Dockerfile b/tasks/kfc/s4-fft-longconv/task/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ac3505c00f7932d7f64f3ad5eeaee7f924c19950 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/environment/Dockerfile @@ -0,0 +1,153 @@ +# syntax=docker/dockerfile:1 +# ============================================================================= +# s4-fft-longconv — 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. +# 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/wre-arch-s4-fft-longconv:v1@sha256:4215533296f1f970d093257f96b14d5cada8925b220966c41471b23d78c36542 +# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in +# manifest order; .git and any .wh..wh..opq marker dropped. +# verification: this task ships no oracle.patch (its reference exists only as a single-file variant), so the tree is pinned by the image digest above; the scope files and the import-origin gate are asserted at build. +## +# ----------------------------------------------------------------------------- +# BUILD (needs outbound network for PyPI only — the working tree ships in this package) +# cd <...>/s4-fft-longconv/task +# docker build -f environment/Dockerfile -t fai/kfc-s4-fft-longconv:oss . +# +# RUN docker run --rm --gpus all -it fai/kfc-s4-fft-longconv:oss +# SCORE docker run --rm --gpus all -v "$PWD/tests:/tests:ro" fai/kfc-s4-fft-longconv:oss bash /tests/test.sh +# # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative) +# +# 🔴 NO ANCHOR TO RE-CALIBRATE (binary reward) +# IMPLEMENTATION-CLASS TASK: reward is binary 0/1 (all correctness cases pass and no +# cheating -> 1.0, else 0.0). There is NO ref_speedup anchor, so nothing to re-calibrate. +# tests/test.sh scores correctness only; no ref_speedup.txt ships with this task and +# none is read. Timing IS still recorded as diagnostic metadata (and the in-image +# manifest keeps an oracle_ms record from the H20 validation run) but it never enters +# the reward. The reference implementation is solution/kernel_oracle.py, applied by +# copying it over the editable file; solution/kernel_negative.py is the known-bad +# control that MUST score 0. See tests/ref_speedup.caveat.md. +# +# 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 + +# ---- 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. ---- +RUN python - <<'PY' +import os, subprocess, sys +sys.path.insert(0, "/app/repo") +for f in (): + 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") +print("NOTE: no importable scope module for this task; tests/test.sh owns the\n import-origin gate at scoring time") +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/s4-fft-longconv/task/environment/repo/.gitignore b/tasks/kfc/s4-fft-longconv/task/environment/repo/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7a60b85e148f80966a550e5ab6a762a907c69ca6 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/environment/repo/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/tasks/kfc/s4-fft-longconv/task/environment/repo/gated_gelu.py b/tasks/kfc/s4-fft-longconv/task/environment/repo/gated_gelu.py new file mode 100644 index 0000000000000000000000000000000000000000..73b1ca790df94c1fcbfa7d45d377ae891fe17839 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/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/s4-fft-longconv/task/environment/repo/submission/kernel.py b/tasks/kfc/s4-fft-longconv/task/environment/repo/submission/kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..43a35777e9d6b081150c1a155fb51533dfd916e0 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/environment/repo/submission/kernel.py @@ -0,0 +1,39 @@ +# Performance Optimization Task — submission entry point. +# +# Implement `causal_conv` to the contract in instruction.md, then make it as fast as possible. +# This is the ONLY file you edit. The verifier grades numerical correctness first (bf16 output +# within rtol=atol=2e-2 of a seeded fp32 reference), then latency on GPU (H20). A submission that +# leaves NotImplementedError in place scores 0. + +import torch + + +def causal_conv(u, k): + """Causal (non-circular) 1-D convolution of each input sequence with its channel's kernel. + + Args: + u: bfloat16 tensor, shape [B, H, L] (B sequences, H channels, length L). + k: bfloat16 tensor, shape [H, L] (per-channel causal kernel, full length L). + + For every (b, h) and output position t in [0, L): + + y[b, h, t] = sum_{s=0}^{t} k[h, t - s] * u[b, h, s] + + i.e. the linear convolution of u[b,h] with k[h], truncated to the first L samples (a causal + system: output t depends only on inputs s <= t; no wrap-around from the tail of the sequence). + Compute the accumulation in fp32, then cast the result back to bf16. + + Returns: + bfloat16 tensor, shape [B, H, L]. + """ + raise NotImplementedError("implement causal_conv to the contract in instruction.md") + + +def custom_kernel(data): + """Entry point the verifier calls. + + data = (u, k, config) where config = {"L": int}. Already wired to call causal_conv and return + the convolved sequences. + """ + u, k, config = data + return causal_conv(u, k) diff --git a/tasks/kfc/s4-fft-longconv/task/environment/runtime/entrypoint.sh b/tasks/kfc/s4-fft-longconv/task/environment/runtime/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ad0137c7a85f94eeb880a755d3730bfbebf1e3a --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/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/s4-fft-longconv/task/environment/runtime/run_dev_bench.sh b/tasks/kfc/s4-fft-longconv/task/environment/runtime/run_dev_bench.sh new file mode 100644 index 0000000000000000000000000000000000000000..d627a61218d501ea69bdc3323afeb5284accd071 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/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/s4-fft-longconv/task/environment/runtime/timer.sh b/tasks/kfc/s4-fft-longconv/task/environment/runtime/timer.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3e45be674fb4a8218ca84d9cb4dc0f451395652 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/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/s4-fft-longconv/task/environment/verifier-correctness-manifest.json b/tasks/kfc/s4-fft-longconv/task/environment/verifier-correctness-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..d5dfbd2bf105add3bf2d19fe88ccc55b813ad080 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/environment/verifier-correctness-manifest.json @@ -0,0 +1 @@ +{"oracle_ms": 0.11348799988627434} diff --git a/tasks/kfc/s4-fft-longconv/task/instruction.md b/tasks/kfc/s4-fft-longconv/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f051ca91039e0ecb0fa058007f1718299d4913fa --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/instruction.md @@ -0,0 +1,84 @@ +# Performance Optimization Task + +You are given a clean Python workspace with a single editable file: + +``` +submission/kernel.py +``` + +This is the **only** file you may edit. Editing any other file (or importing an +implementation from anywhere else) causes the whole task to score 0. + +## Objective + +`submission/kernel.py` ships a required function `causal_conv` whose body is **not implemented** +(it raises `NotImplementedError`). Implement it to the contract below so it is numerically +correct, then make it as fast as possible on the hidden benchmark workloads. Reward is measured on +GPU (H20). Correctness is a hard prerequisite: a fast-but-wrong implementation, or one that still +raises `NotImplementedError`, scores 0. + +## Interface contract (implement exactly this) + +### `causal_conv(u, k) -> y` + +A **causal** (non-circular) 1-D convolution of each input sequence with its channel's full-length +kernel — the "convolution mode" of a long-kernel sequence layer. + +- `u`: `bfloat16` tensor, shape `[B, H, L]` (`B` sequences, `H` channels, length `L`). +- `k`: `bfloat16` tensor, shape `[H, L]` (a per-channel causal kernel, full length `L`). + +For every `(b, h)` and output position `t` in `[0, L)`: + +``` +y[b, h, t] = sum_{s=0}^{t} k[h, t - s] * u[b, h, s] +``` + +This is the linear convolution of `u[b,h]` with `k[h]`, **truncated to the first `L` samples**. The +system is causal: output `t` depends only on inputs `s <= t`. There is **no wrap-around** — the tail +of the sequence must not fold back into early outputs (that would be a circular convolution, which +is wrong). Accumulate in **fp32**, then cast the result back to `bf16`. + +### `custom_kernel(data) -> y` + +`data = (u, k, config)` where `config = {"L": int}`. Already wired to call `causal_conv(u, k)` and +return `y`. You implement the primitive. + +## Correctness + +Outputs are compared against a seeded fp32 reference within `rtol = atol = 2e-2` across a hidden +set of shapes spanning `L=1` (single tap), tiny `L`, odd / non-power-of-two `L`, odd channel +counts, and a large regime (`L` up to ~2048). The causal boundary must be exact — a submission +that reads future samples (e.g. a circular convolution with no zero-padding) fails the gate. +Outputs must genuinely depend on the inputs (the grader runs the op on two different inputs of the +same shape and rejects identical outputs). + +## Latency + +Once correct, the function is timed on GPU with CUDA events (block of medians, the `u` input +regenerated every timed iteration; a warmup window is discarded). The primary benchmark uses a +**long** sequence length `L`. Evaluating the convolution directly — an `O(L^2)` sum per output +position, or equivalently a dense lower-triangular Toeplitz matrix apply — is correct but its cost +grows with `L^2`. A full-length convolution can instead be evaluated in `O(L log L)`; expressing it +so the work grows as `L log L` rather than `L^2` is the reference point. The score is dominated by +the largest `L`. + +## Workload shape (what the hidden benchmark covers) + +- `bfloat16` `u [B, H, L]` and `k [H, L]`, with `L` up to ~2048, modest `B` and `H`, single GPU. +- `L=1`, tiny, odd, and non-power-of-two shapes as well as large ones. +- The score is dominated by the largest shapes, so a fast tiny case cannot offset a slow large one. + +## Rules + +- Edit only `submission/kernel.py`, and keep the `causal_conv` and `custom_kernel` signatures. Any + other change (or importing the answer from another module/file/package) scores 0. +- Solve independently. Do **not** download, clone, fetch, or `pip install` any external + repository, kernel library, or reference implementation to obtain the answer; do **not** attempt + to bypass or disable the environment's network isolation (e.g. by unsetting proxy environment + variables or opening raw sockets). Any such action scores the whole task 0, regardless of + measured speed. +- You may use `torch` and `triton` (both are installed). You do not need any other package. + +## 提交方式 + +本题为**实现类,只有一次评分**。把改动**留在工作树里**即可 —— 直接编辑允许的文件,不需要 `bash /opt/loop/submit.sh`,也不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上;评分由结束后的 `tests/test.sh` 一次性给出)。 diff --git a/tasks/kfc/s4-fft-longconv/task/pre_artifacts.sh b/tasks/kfc/s4-fft-longconv/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a1edf9e124415865a4e7455d3ac5faad5afc963 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/pre_artifacts.sh @@ -0,0 +1,157 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/s4-fft-longconv +# +# 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:134: WORKDIR /app/repo +# evidence Dockerfile:88: && cd /app/repo \ +# evidence Dockerfile:95: && test "$(git rev-list --count HEAD)" = "1" \ +# evidence test.sh:17: 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. +# ============================================================================ +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/s4-fft-longconv/task/solution/README.md b/tasks/kfc/s4-fft-longconv/task/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a396725758ac7cd86373fbfcf1556957f5f1753a --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/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/s4-fft-longconv/task/solution/kernel_negative.py b/tasks/kfc/s4-fft-longconv/task/solution/kernel_negative.py new file mode 100644 index 0000000000000000000000000000000000000000..936de8a717f2cc60e8407607421ae7180ed365d7 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/solution/kernel_negative.py @@ -0,0 +1,19 @@ +# Reviewer-only NEGATIVE (not baked into the image): fast but WRONG. Uses a CIRCULAR convolution (FFT at +# length L with no zero-padding) instead of the causal linear convolution. The missing zero-pad +# lets the tail of the sequence wrap around into early outputs, so a position t reads "future" +# samples via the wrap -- it violates causality and disagrees with the reference for any L > 1. +# It is a single fast FFT pass, so it must FAIL the correctness gate (not the timing). +import torch + + +def causal_conv(u, k): + B, H, L = u.shape + uf = torch.fft.rfft(u.float(), n=L, dim=-1) # WRONG: n=L -> circular, no padding + kf = torch.fft.rfft(k.float(), n=L, dim=-1).unsqueeze(0) + y = torch.fft.irfft(uf * kf, n=L, dim=-1)[..., :L] + return y.to(torch.bfloat16) + + +def custom_kernel(data): + u, k, config = data + return causal_conv(u, k) diff --git a/tasks/kfc/s4-fft-longconv/task/solution/kernel_oracle.py b/tasks/kfc/s4-fft-longconv/task/solution/kernel_oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..aca07cdc9e67816cc33ca341d9a67ac3aabcdcca --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/solution/kernel_oracle.py @@ -0,0 +1,24 @@ +# Reviewer-only ORACLE (not baked into the image): the fast form. A causal 1-D convolution with a full-length +# kernel is evaluated in O(L log L) via the FFT: zero-pad both operands to length >= 2L-1, take +# the real FFT, multiply in the frequency domain, inverse-FFT, and keep the first L samples (the +# zero-padding makes the circular convolution equal the causal linear convolution). Grounded in +# TRAIN.ARCH.SSM: state-spaces/s4 — the S4/S4D "convolution mode" materializes the SSM kernel of +# length L and applies it to the sequence with an FFT (the global long convolution), instead of +# stepping the O(L^2) recurrence/direct sum. Never baked; calibrates oracle_ms + proves headroom. +import torch + + +def causal_conv(u, k): + B, H, L = u.shape + n = 1 + while n < 2 * L: + n <<= 1 + uf = torch.fft.rfft(u.float(), n=n, dim=-1) + kf = torch.fft.rfft(k.float(), n=n, dim=-1).unsqueeze(0) # [1,H,.] + y = torch.fft.irfft(uf * kf, n=n, dim=-1)[..., :L] + return y.to(torch.bfloat16) + + +def custom_kernel(data): + u, k, config = data + return causal_conv(u, k) diff --git a/tasks/kfc/s4-fft-longconv/task/solution/solve.sh b/tasks/kfc/s4-fft-longconv/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b50b88a97a32caf19d30cca523c6375933e606e3 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/solution/solve.sh @@ -0,0 +1,146 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/s4-fft-longconv +# 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量 +# 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。 +# +# oracle 形态 : 单文件变体(file)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_FILE 槽位: +# cp "$KERNELBENCH_ORACLE_FILE" "$REPO/$SUB" +# 产物(reviewer-only;本脚本只读,一个字节都不改): +# solution/kernel_negative.py, solution/kernel_oracle.py +# $REPO : /app/repo (tests/test.sh: REPO=/app/repo) +# 被计分单元 : /app/repo/submission/kernel.py +# 来源:tests/test.sh 的 SUB="submission/kernel.py" +# 落地方式 : cp <变体> $REPO/submission/kernel.py —— 只改工作树,不 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/s4-fft-longconv/task +# IMG=fai/kfc-s4-fft-longconv: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(挖洞基线过不了正确性门)。 +# ────────────────────────────────────────────────────────────────────────── +# +# 用法(规范 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="s4-fft-longconv" +REPO="${KFC_REPO_DIR:-/app/repo}" +SUB="submission/kernel.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; } +GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; } + +usage(){ cat <<'USAGE' +usage: bash solve.sh [--oracle | --negative | --noop] + (无参数) 落地 oracle 参考实现(kernel_oracle.py) + --negative 落地 negative 已知坏例(kernel_negative.py) + --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="kernel_oracle.py" ;; + negative) ART="kernel_negative.py" ;; + *) die "本题没有 $WHICH 变体(solution/ 里只有:kernel_oracle.py, kernel_negative.py)" ;; +esac + +GIT rev-parse --git-dir >/dev/null 2>&1 \ + || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)" +[ -f "$REPO/$SUB" ] || die "被计分单元不存在:$REPO/$SUB(REPO 不对?可用 KFC_REPO_DIR 覆盖)" +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 值。scope 文件在 git 树里,所以 checkout 就够。 + DIRTY_BEFORE="$(GIT status --porcelain -- "$SUB" | sed '/^$/d')" + GIT checkout -q HEAD -- "$SUB" || die "复位被计分单元失败($SUB)" + DIRTY_AFTER="$(GIT status --porcelain -- "$SUB" | 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:已把可编辑面复位到烤入基线的 stub;原先这些是脏的:" + printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |" + else + say "--noop:可编辑面本来就是干净的烤入基线 stub,无需复位" + fi + say "--noop 完成:$SUB = 烤入基线 stub(HEAD 未动 @ ${HEAD_BEFORE:0:12})" + exit 0 +fi + +VAR="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)" + +# ---- 幂等:先复位到挖洞基线的 stub,再整文件覆盖(cp 保留目标文件原有权限) ---- +GIT checkout -q HEAD -- "$SUB" || die "复位被计分单元失败($SUB)" +cp -f "$VAR" "$REPO/$SUB" || die "写入失败:$REPO/$SUB" + +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 "$VAR") -> $SUB(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})" +GIT status --porcelain -- "$SUB" | sed "s|^|[solve.sh $TASK_ID] |" + +STRAY="$(GIT status --porcelain | awk '{print $NF}' \ + | grep -v -e '__pycache__' -e '\.pyc$' -e "^$SUB\$" || 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/s4-fft-longconv/task/task.toml b/tasks/kfc/s4-fft-longconv/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..919bfd230e63532e10cebc77bfc746624471bf0a --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/task.toml @@ -0,0 +1,53 @@ +# Reconstructed: the source package shipped a 0-byte task.toml; +# the values below mirror the task metadata. + +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "s4-fft-longconv" +bench = "kfc" +kind = "implementation" +language = "python" +title = "submission/kernel.py ships a required function causal_conv whose body is not implemented (it raises NotImplementedError)." +instruction = "instruction.md" + +[agent] +timeout_sec = 5400 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/wre-arch-s4-fft-longconv:v1@sha256:4215533296f1f970d093257f96b14d5cada8925b220966c41471b23d78c36542 +# 🔁 LOOP16: the shipped image is the loop16 overlay (`crane append` onto the :oss base, purely +# additive — /opt/loop only, NOTHING under tests/ changed). Build it in two steps: +# docker build -f environment/Dockerfile -t fai/kfc-s4-fft-longconv:oss . +# docker build -f environment/loop_overlay/Dockerfile -t fai/kfc-s4-fft-longconv:oss-loop16 environment/loop_overlay +# The single-shot form (:oss) is a valid alternative; the graded surface (tests/) is identical in both. +[environment] +docker_image = "fai/kfc-s4-fft-longconv:oss" +build_timeout_sec = 3600 +cpus = 8 +memory_mb = 32768 +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" +primary_edit_paths = ["submission/kernel.py"] +result_paths = ["/logs/verifier/reward.json"] + +[primary_metric] +name = "reward" +goal = "maximize" +calibrated_on = "NVIDIA H20" + +# loop16: the shipped image bakes /opt/loop; the in-session dev proxy re-runs THIS task's own +# verifier (candidate mode) on the live /app/repo. This is an IMPLEMENTATION-class task (binary +# reward), so best-of-k ranks on the dual-emitted RAW vs_oracle speed signal to prefer the fastest +# correctness-passing kernel. At most 16 submissions, at least 1; the model decides when to stop +# (min=1 so --finalize works any time). NO calibrated anchor is baked. The graded score is the +# runner's fresh end-of-session tests/ grade (binary correctness over hidden shapes). diff --git a/tasks/kfc/s4-fft-longconv/task/tests/compute_reward.py b/tasks/kfc/s4-fft-longconv/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..cfcd23326f3a777cff36dc027e922974823883dd --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/tests/compute_reward.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""compute_reward for s4-fft-longconv (IMPLEMENTATION class). + +reward = 1.0 iff every test case passes and there is no cheat / scope violation, +reward = 0.0 otherwise [implementation class] + +The authoritative verdict is written by test.sh, which owns the correctness / +scope-diff / import-origin / anti-cheat HARD gates (the baked hollow stub raises +NotImplementedError, so the starter fails correctness and scores 0). This CLI +mirrors the same binary rule and reports the measured vs_oracle ratio as +DIAGNOSTIC METADATA only — never as the reward. + +Why binary rather than the performance log formula: this task has NO timeable +baseline (the starter does not run), and its only timing anchor is the oracle +itself, so ref_speedup ~= 1.0 and min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 is +degenerate/undefined. reward.md's legality rule for the starter package +("implementation class must fail at least one testcase") is what this satisfies. +""" +import json +import sys + +TOKEN = "WRE_RESULT " + + +def load(path): + for line in open(path): + if line.startswith(TOKEN): + return json.loads(line[len(TOKEN):]) + raise SystemExit(f"no {TOKEN.strip()} in {path}") + + +def main(): + cand = load(sys.argv[1]) + oracle_ms = float(sys.argv[2]) if len(sys.argv) > 2 else -1.0 + cm = cand.get("timing_ms", -1) + + # correctness is the AND of every case; the workload reports it as one flag. + correctness_ok = bool(cand.get("correctness_ok", False)) + hard = [] if correctness_ok else ["correctness_failed"] + reward = 1.0 if (correctness_ok and not hard) else 0.0 + + vs_oracle = (oracle_ms / cm) if (cm and cm > 0 and oracle_ms > 0) else 0.0 + print(json.dumps({ + "task_type": "implementation", + "reward": reward, + "reward_formula": "implementation: 1.0 iff every case passes and no cheat, else 0.0", + "hard_fail_reasons": hard, + "tests": {"passed": (1 if correctness_ok else 0), "total": 1, + "note": "correctness_ok is the AND over every hidden case"}, + "metadata": {"vs_oracle": round(vs_oracle, 6), "oracle_ms": oracle_ms, + "candidate_ms": cm, + "note": "vs_oracle is diagnostic metadata only, never the reward"}, + "vs_oracle": round(vs_oracle, 6), + "oracle_ms": oracle_ms, + "candidate_ms": cm, + })) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/s4-fft-longconv/task/tests/ref_speedup.caveat.md b/tasks/kfc/s4-fft-longconv/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..4120922ae64d5d2b063db61fa9bec6412e2e317e --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +本题是**实现类**任务:reward 为二值 0/1(全部正确性用例通过且无作弊 -> 1.0,否则 0.0),**不使用 ref_speedup 锚点**,因此无需重标定。下方公式仅对性能类任务适用: + + reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + +本题不随包提供 `tests/ref_speedup.txt`,判分也不读它 —— 二值 reward 与锚点无关。 +`environment/verifier-correctness-manifest.json` 里的 `oracle_ms` 仅作诊断记录,不参与判分。 + +## 标定条件 + +- 硬件:**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) + +## 换硬件时要做什么 + +**不需要重标定** —— 本题 reward 是二值的,与硬件无关。上面的「标定条件」只是记录 +参考实现当初被验证的环境;换卡后正确性用例应当照常全过。 + +参考实现与反例是**单文件形式**(不是 patch),覆盖到可编辑文件上即可: + +- `solution/kernel_oracle.py` —— 参考实现,应当得 1.0 +- `solution/kernel_negative.py` —— 已知坏例,**必须**得 0.0 + +两者都不进镜像(已被 `.dockerignore` 排除),判分时也从不运行。 + +计时仍会作为诊断元数据记录(`environment/verifier-correctness-manifest.json` +的 `oracle_ms` 是 H20 验证时的记录值),但不参与 reward。 diff --git a/tasks/kfc/s4-fft-longconv/task/tests/test.sh b/tasks/kfc/s4-fft-longconv/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..38824e6b771a4f0058bcf542a8f35db47e131ce7 --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/tests/test.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Verifier for s4-fft-longconv. GPU task (anchor calibrated on H20). +# Scope = submission/kernel.py (the ONLY solver-editable file). The solver implements a causal +# long 1-D convolution (S4 convolution mode) to the disclosed contract, then optimizes it. +# +# reward = vs_oracle = oracle_ms / candidate_ms (raw, uncapped; oracle=1.0, naive<1, faster>1), +# behind a HARD correctness gate (fp32 reference, rtol=atol=2e-2). oracle_ms is a calibrated +# held-out constant (the empty/stub start cannot be timed). noop(stub)=NotImplementedError -> 0. +# +# Modes: candidate | noop | oracle | negative | baseline2. loop16 calls candidate only. +# Emits ONE single-line JSON verdict: {gates, hard_fails, reward, speedup, ...} (score_engine §X). +set -uo pipefail +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 +git config --global --add safe.directory '*' 2>/dev/null || true # root-owned /app/repo + +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +SUB="submission/kernel.py" +LOG=/logs/verifier; mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true +speedup=0.0; oracle_ms=-1; cand_ms=-1 + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +# ---- oracle_ms: calibrated held-out constant (baked at build; draft default pre-calibration) ---- +if [ -f /opt/verifier-correctness-manifest.json ]; then + oracle_ms=$(python3 -c "import json;print(json.load(open('/opt/verifier-correctness-manifest.json')).get('oracle_ms',-1))" 2>/dev/null || echo -1) +fi + +# ---- mode dispatch: swap the reviewer variant over the scope file (NEVER in candidate/noop) ---- +case "$MODE" in + oracle) [ -n "${KERNELBENCH_ORACLE_FILE:-}" ] && cp "$KERNELBENCH_ORACLE_FILE" "$REPO/$SUB" ;; + negative) [ -n "${KERNELBENCH_NEGATIVE_FILE:-}" ] && cp "$KERNELBENCH_NEGATIVE_FILE" "$REPO/$SUB" ;; + baseline2) [ -n "${KERNELBENCH_BASELINE2_FILE:-}" ] && cp "$KERNELBENCH_BASELINE2_FILE" "$REPO/$SUB" ;; + candidate|noop) : ;; # score the live tree (candidate=solver edit, noop=baked stub) +esac + +# ---- (1) scope-diff HARD GATE: only submission/kernel.py may change vs the baked baseline ---- +if git -C "$REPO" rev-parse --git-dir >/dev/null 2>&1; then + git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt" + while IFS= read -r f; do + [ -z "$f" ] && continue + case "$f" in + "$SUB") : ;; + *__pycache__*|*.pyc) : ;; + *) scope_ok=false; add_hard "out_of_scope_edit:$f" ;; + esac + done < "$LOG/changed_files.txt" +fi + +# ---- (2) import-origin assert: the scored kernel must be the baked /app/repo copy ---- +python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import importlib.util, os, sys +p = "/app/repo/submission/kernel.py" +print("KERNEL_PATH", os.path.realpath(p)) +sys.exit(0 if os.path.realpath(p).startswith("/app/repo") and os.path.exists(p) else 3) +PY +[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; } + +# ---- (3) trusted-restore: harness uploaded fresh (never baked into the solver-visible tree) ---- +for f in workload.py compute_reward.py; do + [ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; } +done + +# ---- (4) CORRECTNESS GATE (HARD): scope output must match the fp32 reference. noop/negative FAIL. ---- +if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1 + cok=$(grep WRE_RESULT "$LOG/correctness.out" | tail -1 | python3 -c "import json,sys +try: print(json.loads(sys.stdin.read().split('WRE_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 (only if correct): candidate_ms; speedup = oracle_ms / candidate_ms ---- +if [ "$correctness_ok" = true ] && [ "${#HARD[@]}" -eq 0 ]; then + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed" + read cand_ms flat_ok stable_ok < <(grep WRE_RESULT "$LOG/cand_timing.out" | tail -1 | python3 -c "import json,sys +try: + d=json.loads(sys.stdin.read().split('WRE_RESULT ',1)[1]); print(d.get('timing_ms',-1), d.get('flat_ok',False), d.get('stable_ok',False)) +except Exception: print('-1 False False')" 2>/dev/null || echo "-1 False False") + # NOTE: flat_ok/stable_ok are RECORDED diagnostics, not a hard gate — the CSPRNG cache-probe + # in the correctness stage is the real anti-cache gate (it subsumes constant-output cheats). + # Only an invalid measurement (candidate_ms<=0) hard-fails timing. + if [ "$(python3 -c "print(1 if $cand_ms>0 and $oracle_ms>0 else 0)")" = "1" ]; then + speedup=$(python3 -c "print(round($oracle_ms/$cand_ms,6))") + else benchmark_ok=false; add_hard "timing_invalid"; fi +fi + +# ---- verdict (SINGLE-LINE JSON; §X score_engine parses the last {gates,hard_fails} line) ---- +# reward (the reward specification, IMPLEMENTATION class -> BINARY): +# reward = 1.0 iff every correctness case passes AND no cheat / scope / +# import-origin violation; +# reward = 0.0 otherwise (a single failing case scores 0). +# task_class is 实现类: this is implement-from-empty (the starter raises +# NotImplementedError, noop=0), so there is NO timeable baseline and the only +# timing anchor is the oracle itself (ref ~= 1.0 -> ln(ref) ~= 0), which makes the +# performance log formula degenerate. vs_oracle stays as diagnostic metadata. +nhard="${#HARD[@]}" +hard_str=""; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}" +export WRE_MODE="$MODE" WRE_SPEEDUP="$speedup" \ + WRE_ORACLE_MS="$oracle_ms" WRE_CAND_MS="$cand_ms" \ + WRE_HARD="$hard_str" WRE_SCOPE="$scope_ok" WRE_IMP="$import_origin_ok" \ + WRE_CORR="$correctness_ok" WRE_BENCH="$benchmark_ok" +python3 - > "$LOG/reward.json" <<'PY' +import os, json +def f(x): + try: return float(x) + except Exception: return -1.0 +sp = f(os.environ.get("WRE_SPEEDUP","0")) +hard = os.environ.get("WRE_HARD","").split() +gates = {"scope_ok": os.environ.get("WRE_SCOPE")=="true", + "import_origin_ok": os.environ.get("WRE_IMP")=="true", + "correctness_ok": os.environ.get("WRE_CORR")=="true", + "benchmark_ok": os.environ.get("WRE_BENCH")=="true"} +# Timing-only infra failures are RECORDED but must not zero a fully-correct solve +# (timing is not the metric for an implementation-class task). EVERY correctness / +# scope / import-origin / anti-cheat failure still hard-zeroes the reward. +TIMING_ONLY = {"timing_invalid", "candidate_timing_failed", "no_oracle_anchor", + "oracle_timing_failed", "baseline_timing_failed"} +blocking = [h for h in hard if h.split(":",1)[0] not in TIMING_ONLY] +correctness_ok = gates["correctness_ok"] and gates["scope_ok"] and gates["import_origin_ok"] +reward = 1.0 if (correctness_ok and not blocking) else 0.0 +if reward == 0.0 and not hard: + hard = ["correctness_or_validation_incomplete"] +v = { + "task_type": "implementation", + "mode": os.environ.get("WRE_MODE"), + "reward": reward, + "reward_formula": "implementation: 1.0 iff every case passes and no cheat, else 0.0", + "tests": {"passed": (1 if correctness_ok else 0), "total": 1, + "note": "correctness_ok is the AND over every correctness shape + the cache probe"}, + "hard_fail_reasons": hard, + "hard_fails": hard, + "blocking_hard_fails": blocking, + "metadata": {"vs_oracle": sp, "oracle_ms": f(os.environ.get("WRE_ORACLE_MS")), + "candidate_ms": f(os.environ.get("WRE_CAND_MS")), + "note": "vs_oracle is diagnostic metadata only, never the reward"}, + "speedup": sp, + "vs_oracle": sp, + "oracle_ms": f(os.environ.get("WRE_ORACLE_MS")), + "candidate_ms": f(os.environ.get("WRE_CAND_MS")), + "gates": gates} +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/s4-fft-longconv/task/tests/workload.py b/tasks/kfc/s4-fft-longconv/task/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9d0ae841348e94759b757723e8f10057f2851f --- /dev/null +++ b/tasks/kfc/s4-fft-longconv/task/tests/workload.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Verifier workload for s4-fft-longconv. GPU task (anchor calibrated on H20). + +Drives the solver's /app/repo/submission/kernel.py `custom_kernel` on hidden causal long-conv +workloads. Correctness = match a SEEDED fp32 reference (the direct causal-convolution definition, +re-derived here as a lower-triangular Toeplitz apply, NOT the FFT oracle) within rtol=atol=2e-2. + +Modes: + correctness -> CSPRNG anti-cache probe + hidden shapes (L=1 edge, odd/non-pow2 L, large L) vs ref. + timing -> block-of-medians CUDA-event latency on the primary shape (long L, where an O(L^2) + direct/Toeplitz apply is far slower than an O(L log L) FFT) + a per-shape-spread + diagnostic. Emits WRE_RESULT {"mode":"timing","timing_ms":float,...}. +""" +import json +import math +import secrets +import sys + +import torch + +KERNEL_PATH = "/app/repo/submission/kernel.py" +RTOL = 2e-2 +ATOL = 2e-2 + +PRIMARY = {"B": 16, "H": 16, "L": 1024} + +CORRECTNESS_SHAPES = [ + {"B": 1, "H": 1, "L": 1, "seed": 101}, # L=1 edge (y = k[:,0]*u[:,:,0]) + {"B": 1, "H": 1, "L": 2, "seed": 102}, # tiny + {"B": 2, "H": 3, "L": 17, "seed": 103}, # odd L + {"B": 2, "H": 2, "L": 64, "seed": 104}, + {"B": 4, "H": 4, "L": 255, "seed": 105}, # non-pow2 L + {"B": 3, "H": 5, "L": 100, "seed": 106}, # odd L, odd H + {"B": 2, "H": 2, "L": 1024, "seed": 107}, # large L +] + +SPREAD_SHAPES = [ + {"B": 8, "H": 8, "L": 512, "seed": 201}, + {"B": 8, "H": 8, "L": 1024, "seed": 202}, + {"B": 8, "H": 8, "L": 2048, "seed": 203}, +] + +_PER_SHAPE_SPREAD_MIN = 1.5 +_LATENCY_STABILITY_MAX = 8.0 +_STABILITY_NOISE_FLOOR_MS = 0.12 + + +def _gen(shape, seed, device="cuda"): + g = torch.Generator(device=device).manual_seed(seed) + B, H, L = shape["B"], shape["H"], shape["L"] + u = torch.randn(B, H, L, device=device, dtype=torch.bfloat16, generator=g) + # a decaying (stable) SSM-style kernel: randn * exp(-l/tau), tau ~ L/8, so outputs stay O(1). + l = torch.arange(L, device=device, dtype=torch.float32) + decay = torch.exp(-l / max(1.0, L / 8.0)) + k = (torch.randn(H, L, device=device, dtype=torch.float32, generator=g) * decay).to(torch.bfloat16) + return (u, k, {"L": L}) + + +def _reference(data): + """fp32 ground truth: direct causal convolution (lower-triangular Toeplitz apply).""" + u, k, config = data + B, H, L = u.shape + uf = u.float() + kf = k.float() + idx = torch.arange(L, device=u.device) + d = idx[:, None] - idx[None, :] + mask = (d >= 0) + dc = d.clamp(min=0) + T = kf[:, dc] * mask # [H, L, L] + return torch.einsum("h t s, b h s -> b h t", T, uf) + + +def _clone(data): + u, k, config = data + return (u.clone(), k.clone(), dict(config)) + + +def _load_kernel(): + import importlib.util + spec = importlib.util.spec_from_file_location("submission_kernel", KERNEL_PATH) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod.custom_kernel + + +def _check(out, ref): + if not torch.is_tensor(out): + return False, f"output is not a tensor: {type(out)}" + o = out.float() + if o.shape != ref.shape: + return False, f"shape {tuple(o.shape)} != {tuple(ref.shape)}" + if not torch.isfinite(o).all(): + return False, "output has non-finite values" + diff = (o - ref).abs() + tol = ATOL + RTOL * ref.abs() + nbad = int((diff > tol).sum()) + if nbad > 0: + return False, f"{nbad} elems exceed rtol=atol={RTOL} (max {float(diff.max()):.4g})" + return True, "ok" + + +def run_correctness(custom_kernel): + probe = {"B": 4, "H": 4, "L": 128} + da, db = _gen(probe, secrets.randbits(62)), _gen(probe, secrets.randbits(62)) + oa = custom_kernel(_clone(da)); torch.cuda.synchronize(); oa = oa.detach().clone() + ob = custom_kernel(_clone(db)); torch.cuda.synchronize(); ob = ob.detach().clone() + ok_a, msg_a = _check(oa, _reference(da)) + if not ok_a: + return False, f"cache-probe: first call wrong: {msg_a}" + ok_b, msg_b = _check(ob, _reference(db)) + if not ok_b: + return False, f"cache-probe: second call wrong (output caching?): {msg_b}" + if oa.shape == ob.shape and torch.equal(oa, ob): + return False, "cache-probe: bit-identical outputs for different inputs (caching cheat)" + for spec in CORRECTNESS_SHAPES: + shape = {k: spec[k] for k in ("B", "H", "L")} + data = _gen(shape, spec["seed"]) + out = custom_kernel(_clone(data)); torch.cuda.synchronize() + ok, msg = _check(out, _reference(data)) + if not ok: + return False, f"shape {shape} seed {spec['seed']}: {msg}" + return True, "all correctness passed" + + +def _median(v): + s = sorted(v); n = len(s); m = n // 2 + return s[m] if n % 2 else (s[m - 1] + s[m]) / 2.0 + + +def _time_shape(custom_kernel, shape, seed): + base = _gen(shape, seed) + _, k, config = base + warm = _gen(shape, seed - 1)[0] + for _ in range(10): + custom_kernel((warm.clone(), k.clone(), dict(config))) + torch.cuda.synchronize() + B, H, L = shape["B"], shape["H"], shape["L"] + durs = [] + for i in range(60): + g = torch.Generator(device="cuda").manual_seed(seed + 1000 + i) + ui = torch.randn(B, H, L, device="cuda", dtype=torch.bfloat16, generator=g) + data = (ui, k, dict(config)) + torch.cuda.synchronize() + s = torch.cuda.Event(enable_timing=True); e = torch.cuda.Event(enable_timing=True) + s.record(); custom_kernel(data); e.record(); torch.cuda.synchronize() + durs.append(s.elapsed_time(e)) + med = _median(durs) + ss = sorted(durs); n = len(ss) + p5 = ss[max(0, n // 20)]; p95 = ss[min(n - 1, n - 1 - n // 20)] + ratio = (p95 / p5) if p5 > 0 else float("inf") + return med, ratio + + +def run_timing(custom_kernel): + med, stab = _time_shape(custom_kernel, PRIMARY, seed=202) + spread = [] + for spec in SPREAD_SHAPES: + shape = {k: spec[k] for k in ("B", "H", "L")} + m, _ = _time_shape(custom_kernel, shape, spec["seed"]) + spread.append(m) + spread_ratio = max(spread) / min(spread) if min(spread) > 0 else float("inf") + return med, stab, spread_ratio + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "correctness" + if not torch.cuda.is_available(): + print("WRE_RESULT " + json.dumps({"error": "no_cuda"})); sys.exit(2) + torch.cuda.synchronize() + try: + custom_kernel = _load_kernel() + except Exception as exc: + print("WRE_RESULT " + json.dumps({"mode": mode, "correctness_ok": False, + "error": f"load_failed: {type(exc).__name__}: {exc}"})); sys.exit(3) + + if mode == "correctness": + try: + ok, msg = run_correctness(custom_kernel) + except NotImplementedError as exc: + print("WRE_RESULT " + json.dumps({"mode": "correctness", "correctness_ok": False, + "error": f"not_implemented: {exc}"})); sys.exit(3) + except Exception as exc: + import traceback + print("WRE_RESULT " + json.dumps({"mode": "correctness", "correctness_ok": False, + "error": f"{type(exc).__name__}: {exc}", "tb": traceback.format_exc()[-800:]})); sys.exit(3) + print("WRE_RESULT " + json.dumps({"mode": "correctness", "correctness_ok": bool(ok), "detail": msg})) + sys.exit(0 if ok else 3) + + elif mode == "timing": + try: + med, stab, spread = run_timing(custom_kernel) + except Exception as exc: + print("WRE_RESULT " + json.dumps({"mode": "timing", "timing_ms": -1, + "error": f"{type(exc).__name__}: {exc}"})); sys.exit(3) + flat_ok = spread >= _PER_SHAPE_SPREAD_MIN + stable_ok = (stab <= _LATENCY_STABILITY_MAX) or (med < _STABILITY_NOISE_FLOOR_MS) + print("WRE_RESULT " + json.dumps({"mode": "timing", "timing_ms": med, + "per_iter_max_min": stab, "per_shape_spread": spread, + "flat_ok": bool(flat_ok), "stable_ok": bool(stable_ok), "primary": PRIMARY})) + valid = (med > 0) and math.isfinite(med) + sys.exit(0 if valid else 4) + else: + print("WRE_RESULT " + json.dumps({"error": "bad_mode"})); sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/.dockerignore b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-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/wre-tp-allreduce-bias-fuse-loop16/task/environment/Dockerfile b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8a4dd0699af4ae79a1662accbaab8b83160887d3 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/Dockerfile @@ -0,0 +1,161 @@ +# syntax=docker/dockerfile:1 +# ============================================================================= +# wre-tp-allreduce-bias-fuse-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. +# 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/wre-tp-allreduce-bias-fuse-loop16:v1@sha256:44dc9499f9f5e1050e4676b41f8bc6962c0d78195eba7cdfa64f32056043f8f6 +# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in +# manifest order; .git and any .wh..wh..opq marker dropped. +# verification: this task ships no oracle.patch (its reference exists only as a single-file variant), so the tree is pinned by the image digest above; the scope files and the import-origin gate are asserted at build. +## +# ----------------------------------------------------------------------------- +# BUILD (needs outbound network for PyPI only — the working tree ships in this package) +# cd <...>/wre-tp-allreduce-bias-fuse-loop16/task +# docker build -f environment/Dockerfile -t fai/kfc-wre-tp-allreduce-bias-fuse-loop16:oss . +# +# RUN docker run --rm --gpus all -it fai/kfc-wre-tp-allreduce-bias-fuse-loop16:oss +# SCORE docker run --rm --gpus all -v "$PWD/tests:/tests:ro" fai/kfc-wre-tp-allreduce-bias-fuse-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.8501 . +# 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-wre-tp-allreduce-bias-fuse-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 "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 + +# ---- 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 ---- +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. ---- +RUN python - <<'PY' +import os, subprocess, sys +sys.path.insert(0, "/app/repo") +for f in (): + 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") +print("NOTE: no importable scope module for this task; tests/test.sh owns the\n import-origin gate at scoring time") +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/wre-tp-allreduce-bias-fuse-loop16/task/environment/repo/gated_gelu.py b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/repo/gated_gelu.py new file mode 100644 index 0000000000000000000000000000000000000000..73b1ca790df94c1fcbfa7d45d377ae891fe17839 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-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/wre-tp-allreduce-bias-fuse-loop16/task/environment/runtime/entrypoint.sh b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/runtime/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ad0137c7a85f94eeb880a755d3730bfbebf1e3a --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-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/wre-tp-allreduce-bias-fuse-loop16/task/environment/runtime/run_dev_bench.sh b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/runtime/run_dev_bench.sh new file mode 100644 index 0000000000000000000000000000000000000000..d627a61218d501ea69bdc3323afeb5284accd071 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-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/wre-tp-allreduce-bias-fuse-loop16/task/environment/runtime/timer.sh b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/runtime/timer.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3e45be674fb4a8218ca84d9cb4dc0f451395652 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-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/wre-tp-allreduce-bias-fuse-loop16/task/environment/verifier-correctness-manifest.json b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/verifier-correctness-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f28aa417bc1d3c35bbabfb1c14aaed632cb7b775 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/environment/verifier-correctness-manifest.json @@ -0,0 +1 @@ +{"oracle_ms": 0.3401760011911392} \ No newline at end of file diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/instruction.md b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b152b89bd6f6ef3b7de2896991e98ca649d52413 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/instruction.md @@ -0,0 +1,94 @@ +# Performance Optimization Task + +You are given a clean Python workspace with a single editable file: + +``` +submission/kernel.py +``` + +This is the **only** file you may edit. Editing any other file (or importing an +implementation from anywhere else) causes the whole task to score 0. + +## Objective + +`submission/kernel.py` ships a required function `reduce_partials` whose body is **not +implemented** (it raises `NotImplementedError`). Implement it to the contract below so it is +numerically correct, then make it as fast as possible on the hidden benchmark workloads. +Reward is measured on GPU (H20). Correctness is a hard prerequisite: a fast-but-wrong +implementation, or one that still raises `NotImplementedError`, scores 0. + +## Interface contract (implement exactly this) + +### `reduce_partials(partials, bias) -> out` + +The "all-reduce + bias" epilogue of a tensor-parallel **row-parallel linear**: a row-parallel +layer splits its input dimension across `R` ranks, each rank produces a partial output over the +same `[T, D]` shape, and the final result is the sum of those partials across ranks with the bias +added exactly **once**. + +- `partials`: `bfloat16` CUDA tensor, shape `[R, T, D]` — `partials[r]` is rank `r`'s partial + output. `R` is the tensor-parallel world size. +- `bias`: `bfloat16` CUDA tensor, shape `[D]` — added once to the reduced result (broadcast over + the `T` rows). + +Compute (accumulate in **fp32** for numerical stability, then cast back to `bfloat16`): + +``` +acc = sum over r in [0, R) of partials[r] # reduce over the rank axis, fp32 [T, D] +out = acc + bias # bias added ONCE (broadcast over rows), fp32 +return out.to(bfloat16) # [T, D] +``` + +- The bias is added a **single** time to the reduced sum — **not** once per rank. +- For `R == 1` the result is just `partials[0] + bias`. + +Return `out`: a `bfloat16` tensor of shape `[T, D]`. + +### `custom_kernel(data) -> out` + +`data = (partials, bias, config)`, `config = {"R": int, "T": int, "D": int}`. Already wired to call +`reduce_partials` and return the reduced `[T, D]` output. You implement the primitive. + +## Correctness + +The output is compared against a seeded fp32 reference (sum the partials over the rank axis, add +the bias once) across a hidden set of shapes spanning a single row (`T=1`), odd `T`, +non-power-of-two `D`, the `D=1` edge, `R=1`, and large (`R=16, T=4096, D=4096`) regimes. The +`bfloat16` output must match within `rtol = atol = 2e-2`. Outputs must genuinely depend on the +inputs (the grader calls the primitive on different inputs of the same shape and rejects identical +outputs). A submission that adds the bias once **per rank** (so it is counted `R` times) fails. +Your implementation must be correct across the full domain before latency is measured. + +## Latency + +Once correct, the function is timed on GPU with CUDA events (block of medians, the input +regenerated every timed iteration; a warmup window is discarded). The benchmark drives many ranks +(`R` up to 16). A fused implementation that reduces the whole `[R, T, D]` stack over the rank axis +in a single bandwidth pass and writes the `[T, D]` result once is the reference point; a version +that accumulates one rank at a time in a Python loop is correct but issues `R` separate kernels and +re-reads/writes the full accumulator `R` times, moving several times the memory traffic (and the +gap grows with `R`). + +## Workload shape (what the hidden benchmark covers) + +- `[R, T, D]` `bfloat16` partial stacks with `R` up to 16, `T` up to a few thousand, and `D` up to + 4096, on a single GPU, plus a `[D]` bias. +- Single-row, odd, non-power-of-two, `D=1`, and `R=1` shapes as well as large ones. +- The score is dominated by the largest shapes. + +## Rules + +- Edit only `submission/kernel.py`, and keep the `reduce_partials` and `custom_kernel` + signatures. Any other change (or importing the answer from another module/file/package) + scores 0. +- Solve independently. Do **not** download, clone, fetch, or `pip install` any external + repository, kernel library, or reference implementation to obtain the answer; do **not** + attempt to bypass or disable the environment's network isolation (e.g. by unsetting proxy + environment variables or opening raw sockets). Any such action scores the whole task 0, + regardless of measured speed. +- You may use `torch` and `triton` (both are installed). You do not need any other package. + +## 提交方式 + +本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。 +改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。 diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/pre_artifacts.sh b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..c2ecd15c01a626a6f9b83ae48d74ed4ae844e4c4 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/pre_artifacts.sh @@ -0,0 +1,162 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/wre-tp-allreduce-bias-fuse-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:22: 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/wre-tp-allreduce-bias-fuse-loop16/task/solution/README.md b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7591dea9875e908ed7c9df761d63462b2994013f --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/README.md @@ -0,0 +1,18 @@ +# solution/ — 参考实现(不参与判分) + +本目录里的文件**不进镜像**(已被上下文根的 `.dockerignore` 排除,且 Dockerfile 的 +ANTI-LEAK 断言会在 build 期检查 `kernel_oracle.py` 之类没有被烤进任何一层)、 +**判分不运行**,只在两种场合用: + +1. **重标定锚点**(换硬件/换解释器后):见 `../tests/ref_speedup.caveat.md` + ``` + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_FILE=/patches/kernel_oracle.py + ``` +2. **自证判分有效**:`negative` 必须得 0、`noop` 应 ≈1.0 被门到 0。 + +本题是**单文件提交**形制,所以参考实现是整份文件的变体而不是补丁: + +| 文件 | 用途 | +|---|---| +| `kernel_negative.py` | 已知坏例,**必须得 0** | +| `kernel_oracle.py` | oracle 参考实现,用于标定锚点(打平锚点 = reward 0.5) | diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/kernel_negative.py b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/kernel_negative.py new file mode 100644 index 0000000000000000000000000000000000000000..7ab354970194804e4a06138206ea3ea8defcbdd5 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/kernel_negative.py @@ -0,0 +1,18 @@ +# Reviewer-only NEGATIVE (not baked into the image): fast but WRONG. Adds the bias to EVERY rank's partial +# before the reduction, so the bias is summed R times instead of once. The row-parallel "all-reduce +# + bias" epilogue requires the bias added exactly once (nano-vllm/TGI add it only on rank 0); this +# counts it R times, so for R > 1 (and any non-zero bias) the result is off by (R-1)*bias and it +# FAILS the correctness gate. It is still a single fast fused pass -- fast but wrong. +import torch + + +def reduce_partials(partials, bias): + R, T, D = partials.shape + biased = partials.float() + bias.float() # BUG: bias added to all R ranks + acc = biased.sum(dim=0) # -> bias counted R times + return acc.to(torch.bfloat16) + + +def custom_kernel(data): + partials, bias, config = data + return reduce_partials(partials, bias) diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/kernel_oracle.py b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/kernel_oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..948146ce4c628c8c9714b183de450d5c4dbb2523 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/kernel_oracle.py @@ -0,0 +1,20 @@ +# Reviewer-only ORACLE (not baked into the image): fused single-pass all-reduce + bias. Used only +# to (a) calibrate the oracle_ms latency constant on the authoring lane and (b) prove the correctness + headroom +# gradient. Grounded in SERVE.PARALLEL.TP: nano-vllm RowParallelLinear.forward (linear.py:131, +# all_reduce(y)), litgpt all_reduce_output (generate/tp.py:78), and TGI TensorParallelRowLinear +# (tensor_parallel.py:202) — the row-parallel outputs are summed across ranks and the bias is +# added once. torch reduces the whole [R, T, D] over the rank axis in ONE fused pass (fp32 +# accumulate) and writes the [T, D] result once -> far less HBM traffic and one launch, vs the +# per-rank python accumulate (baseline2). The gap grows with R (the tensor-parallel world size). +import torch + + +def reduce_partials(partials, bias): + acc = partials.sum(dim=0, dtype=torch.float32) # fused reduction over the rank axis (fp32) + acc = acc + bias.float() # bias added once (broadcast over T rows) + return acc.to(torch.bfloat16) + + +def custom_kernel(data): + partials, bias, config = data + return reduce_partials(partials, bias) diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/solve.sh b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..913b4e1134cc20b908c53e56ac4b6e761fe1f242 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/solution/solve.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/wre-tp-allreduce-bias-fuse-loop16 +# 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量 +# 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。 +# +# oracle 形态 : 单文件变体(file)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_FILE 槽位: +# cp "$KERNELBENCH_ORACLE_FILE" "$REPO/$SUB" +# 产物(reviewer-only;本脚本只读,一个字节都不改): +# solution/kernel_negative.py, solution/kernel_oracle.py +# $REPO : /app/repo (tests/test.sh: REPO=/app/repo) +# 被计分单元 : /app/repo/submission/kernel.py +# 来源:tests/test.sh 的 SUB="submission/kernel.py" +# 落地方式 : cp <变体> $REPO/submission/kernel.py —— 只改工作树,不 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/wre-tp-allreduce-bias-fuse-loop16/task +# IMG=fai/kfc-wre-tp-allreduce-bias-fuse-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="wre-tp-allreduce-bias-fuse-loop16" +REPO="${KFC_REPO_DIR:-/app/repo}" +SUB="submission/kernel.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; } +GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; } + +usage(){ cat <<'USAGE' +usage: bash solve.sh [--oracle | --negative | --noop] + (无参数) 落地 oracle 参考实现(kernel_oracle.py) + --negative 落地 negative 已知坏例(kernel_negative.py) + --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="kernel_oracle.py" ;; + negative) ART="kernel_negative.py" ;; + *) die "本题没有 $WHICH 变体(solution/ 里只有:kernel_oracle.py, kernel_negative.py)" ;; +esac + +GIT rev-parse --git-dir >/dev/null 2>&1 \ + || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)" +[ -f "$REPO/$SUB" ] || die "被计分单元不存在:$REPO/$SUB(REPO 不对?可用 KFC_REPO_DIR 覆盖)" +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 值。scope 文件在 git 树里,所以 checkout 就够。 + DIRTY_BEFORE="$(GIT status --porcelain -- "$SUB" | sed '/^$/d')" + GIT checkout -q HEAD -- "$SUB" || die "复位被计分单元失败($SUB)" + DIRTY_AFTER="$(GIT status --porcelain -- "$SUB" | 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:已把可编辑面复位到烤入基线的 stub;原先这些是脏的:" + printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |" + else + say "--noop:可编辑面本来就是干净的烤入基线 stub,无需复位" + fi + say "--noop 完成:$SUB = 烤入基线 stub(HEAD 未动 @ ${HEAD_BEFORE:0:12})" + exit 0 +fi + +VAR="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)" + +# ---- 幂等:先复位到挖洞基线的 stub,再整文件覆盖(cp 保留目标文件原有权限) ---- +GIT checkout -q HEAD -- "$SUB" || die "复位被计分单元失败($SUB)" +cp -f "$VAR" "$REPO/$SUB" || die "写入失败:$REPO/$SUB" + +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 "$VAR") -> $SUB(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})" +GIT status --porcelain -- "$SUB" | sed "s|^|[solve.sh $TASK_ID] |" + +STRAY="$(GIT status --porcelain | awk '{print $NF}' \ + | grep -v -e '__pycache__' -e '\.pyc$' -e "^$SUB\$" || 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/wre-tp-allreduce-bias-fuse-loop16/task/task.toml b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7b3afd7ad8e4270fbc6b0134edb45cd0b58d83d2 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/task.toml @@ -0,0 +1,51 @@ +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "wre-tp-allreduce-bias-fuse-loop16" +bench = "kfc" +kind = "performance" +language = "python" +title = "submission/kernel.py ships a required function reduce_partials whose body is not implemented (it raises NotImplementedError)." +instruction = "instruction.md" + +[agent] +timeout_sec = 5400 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/wre-tp-allreduce-bias-fuse-loop16:v1@sha256:44dc9499f9f5e1050e4676b41f8bc6962c0d78195eba7cdfa64f32056043f8f6 +# Open-source build: `cd && docker build -f environment/Dockerfile -t fai/kfc-wre-tp-allreduce-bias-fuse-loop16:oss .` +[environment] +docker_image = "fai/kfc-wre-tp-allreduce-bias-fuse-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" +timing_metric = "speedup" +primary_edit_paths = ["submission/kernel.py"] +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; measured metric is vs_oracle = speedup/ref_speedup; ref_speedup from tests/ref_speedup.txt; 0 on any hard gate, speedup<=1 or ref_speedup<=1" +ref_speedup = 7.8501 +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" +declared_submission_policy = "single_submission" diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/compute_reward.py b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..80604a898ec99fd5d9b5b738fa705fbb36753f43 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/compute_reward.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""compute_reward for wre-tp-allreduce-bias-fuse-loop16 — standalone reward helper. + +reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 + +This lane measures vs_oracle = oracle_ms / candidate_ms, i.e. speedup / ref_speedup, where +ref_speedup is the ORACLE's speedup over the naive baseline. So equivalently + reward = min(1.0, ln(vs_oracle) / ln(ref_speedup)) + matching the oracle (vs_oracle = 1) -> 0.0 (must EXCEED it) + vs_oracle = ref_speedup (i.e. speedup = ref_speedup^2) -> 1.0 cap + at or below the oracle (speedup <= ref_speedup) -> 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 failing the reference match scores 0 there), speedup <= 1, ref_speedup <= 1, +bad timings. oracle_ms is a calibrated held-out constant. + +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 = "WRE_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__)) + try: + return float(open(os.path.join(here, "ref_speedup.txt")).read().strip()) + except Exception: + pass + try: + v = float(json.load(open("/opt/verifier-correctness-manifest.json")).get("ref_speedup", 0) or 0) + return v + 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]) + oracle_ms = float(sys.argv[2]) if len(sys.argv) > 2 else -1.0 + cand_ms = float(cand.get("timing_ms", -1)) + ref = read_ref(sys.argv) + vs_oracle = (oracle_ms / cand_ms) if (oracle_ms > 0 and cand_ms > 0) else 0.0 + speedup = vs_oracle * ref if (vs_oracle > 0 and ref > 0) else 0.0 + + hard = [] + if not (oracle_ms > 0 and cand_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": {}, + "vs_oracle": round(vs_oracle, 6), + "candidate_ms": round(cand_ms, 4), + "oracle_ms": round(oracle_ms, 4) if oracle_ms > 0 else None, + })) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup.caveat.md b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..a4cc3629f50dfa2ab0213b83a7c1439e84272f80 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +`ref_speedup.txt` 里的 **7.8501** 是 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 "$PWD/solution:/patches:ro" \ + -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_FILE=/patches/kernel_oracle.py \ + fai/kfc-wre-tp-allreduce-bias-fuse-loop16:oss bash /tests/test.sh +# 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt +``` + +自证:`noop`(不覆盖 submission)应 ≈1.0 → 被门到 0;`negative`(`-e KERNELBENCH_VERIFY_MODE=negative -e KERNELBENCH_NEGATIVE_FILE=/patches/kernel_negative.py`)必须 0。 + +✅ 本题**随包提供**参考实现的单文件变体(`solution/kernel_oracle.py`),所以重标定通路是**可直接执行**的(verifier 按文件而不是按补丁分派模式)。 diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup.txt b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c466709e20defc779e963c8a476d016a1418fd8 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup.txt @@ -0,0 +1 @@ +7.8501 diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup_provenance.json b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup_provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d177c03561a5e9aa01f273040de910aeb6083ed3 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/ref_speedup_provenance.json @@ -0,0 +1,5 @@ +{ + "ref_speedup": 7.8501, + "derivation": "1/baseline2_vs_oracle=1/0.127387 (recorded 5-mode validation anchors)", + "meaning": "oracle speedup over the naive (baseline2) reference; the ref_speedup anchor. Derived from the RECORDED 5-mode validation anchors, not measured locally." +} diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/test.sh b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7f16fefb892cf400aa40972ce50dc3ea6113c2e --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/test.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Verifier for wre-tp-allreduce-bias-fuse-loop16. +# Scope = submission/kernel.py (the ONLY solver-editable file). The solver implements the +# tensor-parallel row-parallel all-reduce + bias-once combine to the disclosed contract, then optimizes. +# +# PERFORMANCE reward: +# reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0, range [0.0, 1.0] +# The measured metric is vs_oracle = oracle_ms/candidate_ms = speedup/ref_speedup, so +# equivalently reward = min(1.0, ln(vs_oracle) / ln(ref_speedup)): matching the +# oracle (vs_oracle=1) -> 0.5; ref_speedup^2 (vs_oracle=ref_speedup) -> 1.0 cap; at or below +# the naive baseline (speedup<=1) -> 0. ref_speedup is read from tests/ref_speedup.txt, +# behind a HARD correctness gate (fp32 reference, rtol=atol=2e-2). oracle_ms is a calibrated +# held-out constant (the empty/stub start cannot be timed). noop(stub)=NotImplementedError -> 0. +# +# Modes: candidate | noop | oracle | negative | baseline2. loop16 calls candidate only. +# Emits ONE single-line JSON verdict: {gates, hard_fails, reward, speedup, ...} (score_engine §X). +set -uo pipefail +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 +git config --global --add safe.directory '*' 2>/dev/null || true # §N crane/root-owned /app/repo + +TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO=/app/repo +SUB="submission/kernel.py" +LOG=/logs/verifier; mkdir -p "$LOG" +MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true +speedup=0.0; oracle_ms=-1; cand_ms=-1; ref_speedup=1.0 + +cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; } + +# ---- oracle_ms: calibrated held-out constant (baked at build; draft default pre-calibration) ---- +if [ -f /opt/verifier-correctness-manifest.json ]; then + oracle_ms=$(python3 -c "import json;print(json.load(open('/opt/verifier-correctness-manifest.json')).get('oracle_ms',-1))" 2>/dev/null || echo -1) +fi + +# ---- ref_speedup: the ORACLE's speedup over the naive baseline (the reward anchor). +# Prefer the tests/-local override (uploaded fresh -> recalibrate without an image 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 +ref_speedup=${ref_speedup:-1.0} + +# ---- mode dispatch: swap the reviewer variant over the scope file (NEVER in candidate/noop) ---- +case "$MODE" in + oracle) [ -n "${KERNELBENCH_ORACLE_FILE:-}" ] && cp "$KERNELBENCH_ORACLE_FILE" "$REPO/$SUB" ;; + negative) [ -n "${KERNELBENCH_NEGATIVE_FILE:-}" ] && cp "$KERNELBENCH_NEGATIVE_FILE" "$REPO/$SUB" ;; + baseline2) [ -n "${KERNELBENCH_BASELINE2_FILE:-}" ] && cp "$KERNELBENCH_BASELINE2_FILE" "$REPO/$SUB" ;; + candidate|noop) : ;; # score the live tree (candidate=solver edit, noop=baked stub) +esac + +# ---- (1) scope-diff HARD GATE: only submission/kernel.py may change vs the baked baseline ---- +if git -C "$REPO" rev-parse --git-dir >/dev/null 2>&1; then + git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/changed_files.txt" + while IFS= read -r f; do + [ -z "$f" ] && continue + case "$f" in + "$SUB") : ;; + *__pycache__*|*.pyc) : ;; + *) scope_ok=false; add_hard "out_of_scope_edit:$f" ;; + esac + done < "$LOG/changed_files.txt" +fi + +# ---- (2) import-origin assert: the scored kernel must be the baked /app/repo copy ---- +python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import importlib.util, os, sys +p = "/app/repo/submission/kernel.py" +print("KERNEL_PATH", os.path.realpath(p)) +sys.exit(0 if os.path.realpath(p).startswith("/app/repo") and os.path.exists(p) else 3) +PY +[ $? -eq 0 ] || { import_origin_ok=false; add_hard "import_origin_not_app_repo"; } + +# ---- (3) trusted-restore: harness uploaded fresh (never baked into the solver-visible tree) ---- +for f in workload.py compute_reward.py; do + [ -f "$TESTS_DIR/$f" ] || { add_hard "hidden_supplement_missing:$f"; correctness_ok=false; } +done + +# ---- (4) CORRECTNESS GATE (HARD): scope output must match the fp32 reference. noop/negative FAIL. ---- +if [ "$scope_ok" = true ] && [ "$import_origin_ok" = true ]; then + ( cd "$TESTS_DIR" && python3 workload.py correctness ) > "$LOG/correctness.out" 2>&1 + cok=$(grep WRE_RESULT "$LOG/correctness.out" | tail -1 | python3 -c "import json,sys +try: print(json.loads(sys.stdin.read().split('WRE_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 (only if correct): candidate_ms; speedup = oracle_ms / candidate_ms ---- +if [ "$correctness_ok" = true ] && [ "${#HARD[@]}" -eq 0 ]; then + ( cd "$TESTS_DIR" && python3 workload.py timing ) > "$LOG/cand_timing.out" 2>&1 || add_hard "candidate_timing_failed" + read cand_ms flat_ok stable_ok < <(grep WRE_RESULT "$LOG/cand_timing.out" | tail -1 | python3 -c "import json,sys +try: + d=json.loads(sys.stdin.read().split('WRE_RESULT ',1)[1]); print(d.get('timing_ms',-1), d.get('flat_ok',False), d.get('stable_ok',False)) +except Exception: print('-1 False False')" 2>/dev/null || echo "-1 False False") + # NOTE: flat_ok/stable_ok are RECORDED diagnostics, not a hard gate — the CSPRNG cache-probe + # in the correctness stage is the real anti-cache gate (it subsumes constant-output cheats). + # Only an invalid measurement (candidate_ms<=0) hard-fails timing. + if [ "$(python3 -c "print(1 if $cand_ms>0 and $oracle_ms>0 else 0)")" = "1" ]; then + speedup=$(python3 -c "print(round($oracle_ms/$cand_ms,6))") + else benchmark_ok=false; add_hard "timing_invalid"; fi +fi + +# ---- verdict (SINGLE-LINE JSON; §X score_engine parses the last {gates,hard_fails} line) ---- +# reward = min(1.0, ln(absolute_speedup/ref_speedup)/ln(ref_speedup)) if absolute_speedup > ref_speedup else 0.0, computed +# in python below from vs_oracle x ref_speedup. Every hard gate is preserved verbatim. +hard_str=""; nhard="${#HARD[@]}"; [ "$nhard" -gt 0 ] && hard_str="${HARD[*]}" +export WRE_MODE="$MODE" WRE_SPEEDUP="$speedup" WRE_REF="$ref_speedup" \ + WRE_ORACLE_MS="$oracle_ms" WRE_CAND_MS="$cand_ms" \ + WRE_HARD="$hard_str" WRE_SCOPE="$scope_ok" WRE_IMP="$import_origin_ok" \ + WRE_CORR="$correctness_ok" WRE_BENCH="$benchmark_ok" +python3 - > "$LOG/reward.json" <<'PY' +import os, json, math +def f(x): + try: return float(x) + except Exception: return -1.0 +vs_oracle = f(os.environ.get("WRE_SPEEDUP", "0")) # oracle_ms / candidate_ms +ref = f(os.environ.get("WRE_REF", "1")) # oracle speedup over the naive baseline +hard = os.environ.get("WRE_HARD", "").split() +gates = {"scope_ok": os.environ.get("WRE_SCOPE") == "true", + "import_origin_ok": os.environ.get("WRE_IMP") == "true", + "correctness_ok": os.environ.get("WRE_CORR") == "true", + "benchmark_ok": os.environ.get("WRE_BENCH") == "true"} +# absolute speedup vs the naive baseline = vs_oracle * ref_speedup +speedup = vs_oracle * ref if (vs_oracle > 0 and ref > 0) else 0.0 +# ---- 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(speedup) or speedup <= 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(speedup) / math.log(ref) - 1.0)))) + except Exception: + reward = 0.0 + hard.append("reward_computation_failed") +v = { + "task_type": "performance", + "mode": os.environ.get("WRE_MODE"), + "reward": reward, + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0", + "speedup": speedup, # ABSOLUTE, vs the naive baseline + "ref_speedup": ref, + "vs_oracle": vs_oracle, # speedup / ref_speedup; dev_speedup reads this (§X) + "cv": {}, + "oracle_ms": f(os.environ.get("WRE_ORACLE_MS")), + "candidate_ms": f(os.environ.get("WRE_CAND_MS")), + "hard_fails": hard, + "hard_fail_reasons": hard, + "gates": gates} +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/workload.py b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..719e33603babd7d7f7b3861fbf91f77976ff95d9 --- /dev/null +++ b/tasks/kfc/wre-tp-allreduce-bias-fuse-loop16/task/tests/workload.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Verifier workload for wre-tp-allreduce-bias-fuse. + +Drives the solver's /app/repo/submission/kernel.py `custom_kernel` on hidden tensor-parallel +row-parallel "all-reduce + bias" combine workloads: reduce R rank-partial [T, D] outputs over the +rank axis and add the bias once. Correctness = match a SEEDED fp32 reference within rtol=atol=2e-2, +computed independently here (NOT the oracle, which is never baked into the image). + +Modes: + correctness -> CSPRNG anti-cache probe + all hidden shapes vs the fp32 reference. + timing -> block-of-medians CUDA-event latency on the primary shape + a per-shape-spread + diagnostic. Emits WRE_RESULT {"mode":"timing","timing_ms":float,...} +""" +import json +import math +import secrets +import sys + +import torch + +KERNEL_PATH = "/app/repo/submission/kernel.py" +RTOL = 2e-2 +ATOL = 2e-2 + +PRIMARY = {"R": 16, "T": 4096, "D": 4096} + +CORRECTNESS_SHAPES = [ + {"R": 2, "T": 1, "D": 128, "seed": 101}, # single row + {"R": 3, "T": 17, "D": 8191, "seed": 102}, # odd T, non-pow2 D + {"R": 8, "T": 512, "D": 2048, "seed": 103}, + {"R": 5, "T": 333, "D": 1, "seed": 104}, # D=1 edge + {"R": 16, "T": 1024, "D": 4096, "seed": 105}, + {"R": 1, "T": 256, "D": 512, "seed": 106}, # R=1 (reduce of a single rank -> just +bias) +] + +SPREAD_SHAPES = [ + {"R": 4, "T": 512, "D": 1024, "seed": 201}, + {"R": 8, "T": 2048, "D": 2048, "seed": 202}, + {"R": 16, "T": 4096, "D": 4096, "seed": 203}, +] + +_PER_SHAPE_SPREAD_MIN = 3.0 +_LATENCY_STABILITY_MAX = 8.0 +_STABILITY_NOISE_FLOOR_MS = 0.12 + + +def _gen(shape, seed, device="cuda"): + g = torch.Generator(device=device).manual_seed(seed) + R, T, D = shape["R"], shape["T"], shape["D"] + partials = torch.randn(R, T, D, device=device, dtype=torch.bfloat16, generator=g) * 0.5 + bias = torch.randn(D, device=device, dtype=torch.bfloat16, generator=g) * 0.5 + return (partials, bias, {"R": R, "T": T, "D": D}) + + +def _reference(data): + """fp32 ground truth: sum the partials over the rank axis, add the bias once (the contract).""" + partials, bias, config = data + acc = partials.float().sum(dim=0) + acc = acc + bias.float() + return acc.to(torch.bfloat16) + + +def _clone(data): + partials, bias, config = data + return (partials.clone(), bias.clone(), dict(config)) + + +def _load_kernel(): + import importlib.util + spec = importlib.util.spec_from_file_location("submission_kernel", KERNEL_PATH) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod.custom_kernel + + +def _check(out, ref): + if not torch.is_tensor(out): + return False, f"output is not a tensor: {type(out)}" + o = out.float() + if o.shape != ref.shape: + return False, f"shape {tuple(o.shape)} != {tuple(ref.shape)}" + if not torch.isfinite(o).all(): + return False, "output has non-finite values" + diff = (o - ref).abs() + tol = ATOL + RTOL * ref.abs() + nbad = int((diff > tol).sum()) + if nbad > 0: + return False, f"{nbad} elems exceed rtol=atol={RTOL} (max {float(diff.max()):.4g})" + return True, "ok" + + +def run_correctness(custom_kernel): + probe = {"R": 8, "T": 256, "D": 4096} + da, db = _gen(probe, secrets.randbits(62)), _gen(probe, secrets.randbits(62)) + oa = custom_kernel(_clone(da)); torch.cuda.synchronize(); oa = oa.detach().clone() + ob = custom_kernel(_clone(db)); torch.cuda.synchronize(); ob = ob.detach().clone() + ok_a, msg_a = _check(oa, _reference(da)) + if not ok_a: + return False, f"cache-probe: first call wrong: {msg_a}" + ok_b, msg_b = _check(ob, _reference(db)) + if not ok_b: + return False, f"cache-probe: second call wrong (output caching?): {msg_b}" + if oa.shape == ob.shape and torch.equal(oa, ob): + return False, "cache-probe: bit-identical outputs for different inputs (caching cheat)" + for spec in CORRECTNESS_SHAPES: + shape = {k: spec[k] for k in ("R", "T", "D")} + data = _gen(shape, spec["seed"]) + out = custom_kernel(_clone(data)); torch.cuda.synchronize() + ok, msg = _check(out, _reference(data)) + if not ok: + return False, f"shape {shape} seed {spec['seed']}: {msg}" + return True, "all correctness passed" + + +def _median(v): + s = sorted(v); n = len(s); m = n // 2 + return s[m] if n % 2 else (s[m - 1] + s[m]) / 2.0 + + +def _time_shape(custom_kernel, shape, seed): + base = _gen(shape, seed) + _, _, config = base + warm = _gen(shape, seed - 1) + for _ in range(10): + custom_kernel(_clone(warm)) + torch.cuda.synchronize() + durs = [] + for i in range(60): + data = _gen(shape, seed + 1000 + i) + torch.cuda.synchronize() + s = torch.cuda.Event(enable_timing=True); e = torch.cuda.Event(enable_timing=True) + s.record(); custom_kernel(data); e.record(); torch.cuda.synchronize() + durs.append(s.elapsed_time(e)) + med = _median(durs) + ss = sorted(durs); n = len(ss) + p5 = ss[max(0, n // 20)]; p95 = ss[min(n - 1, n - 1 - n // 20)] + ratio = (p95 / p5) if p5 > 0 else float("inf") + return med, ratio + + +def run_timing(custom_kernel): + med, stab = _time_shape(custom_kernel, PRIMARY, seed=203) + spread = [] + for spec in SPREAD_SHAPES: + shape = {k: spec[k] for k in ("R", "T", "D")} + m, _ = _time_shape(custom_kernel, shape, spec["seed"]) + spread.append(m) + spread_ratio = max(spread) / min(spread) if min(spread) > 0 else float("inf") + return med, stab, spread_ratio + + +def main(): + mode = sys.argv[1] if len(sys.argv) > 1 else "correctness" + if not torch.cuda.is_available(): + print("WRE_RESULT " + json.dumps({"error": "no_cuda"})); sys.exit(2) + torch.cuda.synchronize() + try: + custom_kernel = _load_kernel() + except Exception as exc: + print("WRE_RESULT " + json.dumps({"mode": mode, "correctness_ok": False, + "error": f"load_failed: {type(exc).__name__}: {exc}"})); sys.exit(3) + + if mode == "correctness": + try: + ok, msg = run_correctness(custom_kernel) + except NotImplementedError as exc: + print("WRE_RESULT " + json.dumps({"mode": "correctness", "correctness_ok": False, + "error": f"not_implemented: {exc}"})); sys.exit(3) + except Exception as exc: + import traceback + print("WRE_RESULT " + json.dumps({"mode": "correctness", "correctness_ok": False, + "error": f"{type(exc).__name__}: {exc}", "tb": traceback.format_exc()[-800:]})); sys.exit(3) + print("WRE_RESULT " + json.dumps({"mode": "correctness", "correctness_ok": bool(ok), "detail": msg})) + sys.exit(0 if ok else 3) + + elif mode == "timing": + try: + med, stab, spread = run_timing(custom_kernel) + except Exception as exc: + print("WRE_RESULT " + json.dumps({"mode": "timing", "timing_ms": -1, + "error": f"{type(exc).__name__}: {exc}"})); sys.exit(3) + flat_ok = spread >= _PER_SHAPE_SPREAD_MIN + stable_ok = (stab <= _LATENCY_STABILITY_MAX) or (med < _STABILITY_NOISE_FLOOR_MS) + print("WRE_RESULT " + json.dumps({"mode": "timing", "timing_ms": med, + "per_iter_max_min": stab, "per_shape_spread": spread, + "flat_ok": bool(flat_ok), "stable_ok": bool(stable_ok), "primary": PRIMARY})) + valid = (med > 0) and math.isfinite(med) + sys.exit(0 if valid else 4) + else: + print("WRE_RESULT " + json.dumps({"error": "bad_mode"})); sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/.dockerignore b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c69cdf9ec6a974152235f3eb4a144d91f050035b --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/Dockerfile b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..371205b5caf612cfd3718f2e9fe83216db914ab7 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/Dockerfile @@ -0,0 +1,158 @@ +# syntax=docker/dockerfile:1 +# ============================================================================= +# wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16:v1@sha256:9a3ddd4847b739838e272e95b21059875089f43a96af39fdc962eaf1222dbe40 +# method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in +# manifest order; .git and any .wh..wh..opq marker dropped. +# verification: this task ships no oracle.patch (its reference exists only as a single-file variant), so the tree is pinned by the image digest above; the scope files and the import-origin gate are asserted at build. +## +# ----------------------------------------------------------------------------- +# BUILD (needs outbound network for PyPI only — the working tree ships in this package) +# cd <...>/wro-offload-layer-prefetch-ring-pipeline-loop16/task +# docker build -f environment/Dockerfile -t fai/kfc-wro-offload-layer-prefetch-ring-pipeline-loop16:oss . +# +# RUN docker run --rm -it fai/kfc-wro-offload-layer-prefetch-ring-pipeline-loop16:oss +# SCORE docker run --rm -v "$PWD/tests:/tests:ro" fai/kfc-wro-offload-layer-prefetch-ring-pipeline-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 = 32.230499 . +# 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-offload-layer-prefetch-ring-pipeline-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 + +# ---- 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 ---- +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 ('prefetch_ring.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 ('prefetch_ring',): + 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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/manifest.json b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..9a03aa995f6b83b36aaf1a48abcf432a16dabf7e --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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": [ + "prefetch_ring.py" + ], + "scoring": "task tests/test.sh in candidate mode on the live /app/repo", + "task_id": "wro-offload-layer-prefetch-ring-pipeline-loop16" +} diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/compute_reward.py b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..9495872264533f137c837452cf724e9b29064155 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/compute_reward.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""compute_reward for wro-offload-layer-prefetch-ring-pipeline (acceleration). +reward = base_ms / candidate_ms (raw wall speedup vs the frozen degraded baseline), +gated by correctness in test.sh (wrong output -> reward 0 there).""" +import json +import sys + +TOKEN = "WRO_PREFETCHRING_RESULT " + + +def load(path): + for line in open(path): + if line.startswith(TOKEN): + return json.loads(line[len(TOKEN):]) + raise SystemExit(f"no WRO_PREFETCHRING_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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/test.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6c5152e5087b10db84aa99cd87cce2b51800f221 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/test.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# Verifier for wro-offload-layer-prefetch-ring-pipeline. +# layer-wise weight prefetch over a pinned staging ring: chunking, lookahead window, ring conflicts, arrivals, stall profile +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=("prefetch_ring.py") +MODNAME="prefetch_ring" +TOKEN="WRO_PREFETCHRING_RESULT" + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true + +# ---- 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 ---- +MODNAME="$MODNAME" python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import os, sys, importlib +sys.path.insert(0, "/app/repo") +m = importlib.import_module(os.environ["MODNAME"]) +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 + +speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1 +[ -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 "$TOKEN" "$LOG/correctness.out" | TOKEN="$TOKEN" python3 -c "import json,os,sys +try: print(json.loads(sys.stdin.read().split(os.environ['TOKEN']+' ',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 "$TOKEN" "$LOG/cand_timing.out" | TOKEN="$TOKEN" python3 -c "import json,os,sys;print(json.loads(sys.stdin.read().split(os.environ['TOKEN']+' ',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 "$TOKEN" "$LOG/base_timing.out" | TOKEN="$TOKEN" python3 -c "import json,os,sys;print(json.loads(sys.stdin.read().split(os.environ['TOKEN']+' ',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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/verifier-correctness-manifest.json b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/verifier-correctness-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..78ff4640a599af4f49781d50c14b8886ef27cc70 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/verifier-correctness-manifest.json @@ -0,0 +1,11 @@ +{ + "task_id": "wro-offload-layer-prefetch-ring-pipeline", + "perf_metric": "speedup", + "ref_speedup": 32.230499, + "oracle_candidate_ms": 3.8421, + "baseline_ms": 123.8328, + "noop_speedup": 1.023921, + "baseline2_speedup": 1.885342, + "anchor_source": "4-mode validation run on the authoring CPU lane (Intel Sapphire Rapids)", + "notes": "ref_speedup is the oracle anchor measured on the authoring lane, not a locally re-measured number." +} diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/workload.py b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c635a63840477db5f09f2de623ebd605f29326 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/private/tests/workload.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python3 +"""Verifier workload for the layer-wise weight-prefetch ring scope. + +correctness: 24 scenarios checked against an INDEPENDENT pure-python reference + written here in the harness (never imported from /app/repo). + Everything is integer, so every comparison is EXACT. +timing: 768 layers chunked at 16 KiB (~166k chunks) over a 192-slot ring + with a 2-layer lookahead; CPU time via time.process_time (exp §6.52), + min of 3, after a fixed 400 ms CPU warm-up that makes the measurement + immune to the idle-clock ramp. +""" +import importlib +import json +import os +import sys +import time + +import numpy as np + +sys.path.insert(0, "/app/repo") +TOKEN = "WRO_PREFETCHRING_RESULT" + + +def scope_module(): + return importlib.import_module("prefetch_ring") + + +# ---------------------------------------------------------------- reference +def r_chunks(lb, cb): + c_layer, c_size, ptr = [], [], [0] + for l, nb in enumerate(lb): + rem = nb + while rem > 0: + take = cb if rem > cb else rem + c_layer.append(l) + c_size.append(take) + rem -= take + ptr.append(len(c_layer)) + return c_layer, c_size, ptr + + +def r_window(ptr, la, rs): + L = len(ptr) - 1 + out = [] + for l in range(L): + far = min(l + 1 + la, L) + out.append(min(ptr[far], ptr[l] + rs)) + return out + + +def r_ring(cs, rs): + slot, ev = [], [] + reuse = [0] * rs + for i in range(len(cs)): + s = i % rs + slot.append(s) + ev.append(i - rs if i >= rs else -1) + reuse[s] += 1 + return slot, ev, reuse + + +def r_arr(cs, bw, fx, t0): + start, done = [], [] + t = t0 + for v in cs: + cost = (v + bw - 1) // bw + fx + start.append(t) + t += cost + done.append(t) + return start, done + + +def r_stall(ptr, cd, cu): + L = len(ptr) - 1 + start, end, stall = [], [], [] + prev = 0 + for l in range(L): + ready = 0 + for j in range(ptr[l], ptr[l + 1]): + if cd[j] > ready: + ready = cd[j] + s = ready if ready > prev else prev + start.append(s) + stall.append(s - prev) + prev = s + cu[l] + end.append(prev) + return start, end, stall + + +def r_pipe(lb, cb, rs, sb, la, bw, fx, cu, t0): + c_layer, c_size, ptr = r_chunks(lb, cb) + wnd = r_window(ptr, la, rs) + slot, ev, reuse = r_ring(c_size, rs) + s_c, d_c = r_arr(c_size, bw, fx, t0) + l_s, l_e, l_st = r_stall(ptr, d_c, cu) + C = len(c_size) + L = len(lb) + conf = [] + for i in range(C): + if ev[i] >= 0 and s_c[i] < l_e[c_layer[ev[i]]]: + conf.append(i) + cost = [(v + bw - 1) // bw + fx for v in c_size] + return {"n_chunks": C, "n_layers": L, "bytes_total": sum(lb), + "total_us": l_e[L - 1] if L else 0, + "stall_us": sum(l_st), "bubbles": sum(1 for v in l_st if v > 0), + "conflicts": len(conf), "link_busy_us": sum(cost), + "last_arrival_us": d_c[C - 1] if C else 0, + "window": wnd, "layer_stall": l_st, "layer_start": l_s, + "slot_reuse": reuse, "conflict_chunks": conf} + + +def eq(got, exp, tag): + g = np.asarray(got, dtype=np.int64) + e = np.asarray(exp, dtype=np.int64) + if e.size == 0 and g.size == 0: + return + assert g.shape == e.shape, "%s shape %r != %r" % (tag, g.shape, e.shape) + assert np.array_equal(g, e), "%s mismatch" % tag + + +# ---------------------------------------------------------------- scenarios +def mk_case(seed, L, kind): + rng = np.random.default_rng(seed) + lb = (rng.integers(4, 40, size=L).astype(np.int64) * 4096) + cu = rng.integers(20, 200, size=L).astype(np.int64) + if kind == "zero_layers": + lb = np.zeros(L, dtype=np.int64) + elif kind == "some_empty" and L >= 4: + lb[1] = 0 + lb[L - 1] = 0 + elif kind == "compute_free": + cu = np.zeros(L, dtype=np.int64) + elif kind == "compute_heavy": + cu = cu * 500 + elif kind == "lopsided" and L >= 3: + lb[0] = 400 * 4096 + return lb, cu + + +CASES = [ + # name, L, kind, chunk, slots, slot_bytes, lookahead, bw, fixed, issue + ("plain", 24, "plain", 16384, 12, 16384, 2, 512, 5, 0), + ("some_empty", 24, "some_empty", 16384, 12, 16384, 2, 512, 5, 0), + ("zero_layers", 12, "zero_layers", 16384, 8, 16384, 2, 512, 5, 0), + ("compute_free", 20, "compute_free", 16384, 10, 16384, 2, 512, 5, 0), + ("compute_heavy", 20, "compute_heavy", 16384, 10, 16384, 2, 512, 5, 0), + ("lopsided", 18, "lopsided", 16384, 9, 16384, 2, 512, 5, 0), + ("chunk_huge", 16, "plain", 1 << 24, 6, 1 << 24, 2, 512, 5, 0), + ("chunk_tiny", 6, "plain", 4096, 8, 4096, 2, 512, 5, 0), + ("slots_1", 16, "plain", 16384, 1, 16384, 2, 512, 5, 0), + ("slots_huge", 16, "plain", 16384, 999, 16384, 2, 512, 5, 0), + ("look_0", 20, "plain", 16384, 10, 16384, 0, 512, 5, 0), + ("look_huge", 20, "plain", 16384, 10, 16384, 99, 512, 5, 0), + ("bw_1", 8, "plain", 16384, 6, 16384, 2, 1, 5, 0), + ("bw_huge", 20, "plain", 16384, 10, 16384, 2, 1 << 26, 5, 0), + ("fixed_0", 20, "plain", 16384, 10, 16384, 2, 512, 0, 0), + ("fixed_big", 20, "plain", 16384, 10, 16384, 2, 512, 900, 0), + ("issue_late", 20, "plain", 16384, 10, 16384, 2, 512, 5, 7777), + ("slot_slack", 18, "plain", 16384, 9, 1 << 20, 2, 512, 5, 0), + ("one_layer", 1, "plain", 16384, 4, 16384, 2, 512, 5, 0), + ("no_layers", 0, "plain", 16384, 4, 16384, 2, 512, 5, 0), + ("deep", 64, "plain", 8192, 16, 8192, 3, 512, 5, 0), + ("deep_tight", 64, "compute_free", 8192, 2, 8192, 1, 512, 5, 0), + ("wide_chunks", 30, "lopsided", 32768, 20, 32768, 4, 256, 9, 3), +] + + +def do_correctness(): + m = scope_module() + ok = 0 + bad = [] + try: + lb, cu = mk_case(11, 14, "plain") + cl, cs, ptr = m.layer_chunk_table(lb, 16384) + rcl, rcs, rptr = r_chunks(lb.tolist(), 16384) + eq(cl, rcl, "chunk_layer") + eq(cs, rcs, "chunk_size") + eq(ptr, rptr, "layer_ptr") + assert np.asarray(cs).dtype == np.int64, "chunk dtype" + e0 = m.layer_chunk_table(np.zeros(0, dtype=np.int64), 4096) + assert np.asarray(e0[0]).shape == (0,) and np.asarray(e0[2]).tolist() == [0], \ + "empty chunk table" + eq(m.layer_chunk_table(np.zeros(3, dtype=np.int64), 4096)[2], [0, 0, 0, 0], + "all-empty ptr") + for la, rs in ((0, 4), (2, 4), (99, 3), (1, 1), (2, 10 ** 6)): + eq(m.prefetch_window(np.asarray(rptr, dtype=np.int64), la, rs), + r_window(rptr, la, rs), "window la=%d rs=%d" % (la, rs)) + assert np.asarray(m.prefetch_window(np.zeros(1, dtype=np.int64), 2, 4)).shape \ + == (0,), "empty window" + for rs in (1, 5, 4096): + gs, ge, gr = m.ring_assign(np.asarray(rcs, dtype=np.int64), rs, 1 << 24) + es, ee, er = r_ring(rcs, rs) + eq(gs, es, "ring slot rs=%d" % rs) + eq(ge, ee, "ring evict rs=%d" % rs) + eq(gr, er, "ring reuse rs=%d" % rs) + assert np.asarray(m.ring_assign(np.zeros(0, dtype=np.int64), 3, + 4096)[2]).shape == (3,), "empty ring reuse" + for bw, fx, t0 in ((512, 5, 0), (1, 0, 0), (1 << 26, 900, 1234)): + gs, gd = m.chunk_arrivals(np.asarray(rcs, dtype=np.int64), bw, fx, t0) + es, ed = r_arr(rcs, bw, fx, t0) + eq(gs, es, "arr start bw=%d" % bw) + eq(gd, ed, "arr done bw=%d" % bw) + assert np.asarray(m.chunk_arrivals(np.zeros(0, dtype=np.int64), 4, 0, + 0)[0]).shape == (0,), "empty arrivals" + _s, dc = m.chunk_arrivals(np.asarray(rcs, dtype=np.int64), 512, 5, 0) + for cvec in (cu, np.zeros(14, dtype=np.int64), cu * 400): + gs, ge, gt = m.stall_profile(np.asarray(rptr, dtype=np.int64), dc, cvec) + es, ee, et = r_stall(rptr, np.asarray(dc).tolist(), cvec.tolist()) + eq(gs, es, "stall start") + eq(ge, ee, "stall end") + eq(gt, et, "stall stall") + z = m.stall_profile(np.zeros(1, dtype=np.int64), np.zeros(0, dtype=np.int64), + np.zeros(0, dtype=np.int64)) + assert all(np.asarray(x).shape == (0,) for x in z), "empty stall profile" + # error paths + for f, args in ((m.layer_chunk_table, (lb.reshape(-1, 2), 4096)), + (m.layer_chunk_table, (lb, 0)), + (m.layer_chunk_table, (-lb - 1, 4096)), + (m.prefetch_window, (np.zeros(0, dtype=np.int64), 2, 4)), + (m.prefetch_window, (np.array([1, 2], dtype=np.int64), 2, 4)), + (m.prefetch_window, (np.array([0, 5, 3], dtype=np.int64), 2, 4)), + (m.prefetch_window, (np.array([0, 3], dtype=np.int64), -1, 4)), + (m.prefetch_window, (np.array([0, 3], dtype=np.int64), 2, 0)), + (m.ring_assign, (np.asarray(rcs).reshape(-1, 1), 4, 1 << 24)), + (m.ring_assign, (np.asarray(rcs), 0, 1 << 24)), + (m.ring_assign, (np.asarray(rcs), 4, 0)), + (m.ring_assign, (np.asarray(rcs), 4, 8)), + (m.chunk_arrivals, (np.asarray(rcs).reshape(-1, 1), 4, 0, 0)), + (m.chunk_arrivals, (-np.asarray(rcs) - 1, 4, 0, 0)), + (m.chunk_arrivals, (np.asarray(rcs), 0, 0, 0)), + (m.chunk_arrivals, (np.asarray(rcs), 4, -1, 0)), + (m.chunk_arrivals, (np.asarray(rcs), 4, 0, -1)), + (m.stall_profile, (np.zeros(0, dtype=np.int64), dc, cu)), + (m.stall_profile, (np.asarray(rptr, dtype=np.int64), dc, + cu[:3])), + (m.stall_profile, (np.asarray(rptr, dtype=np.int64), dc, + -cu - 1)), + (m.stall_profile, (np.asarray(rptr, dtype=np.int64), + dc[:-1], cu)), + (m.run_pipeline, (lb, 0, 4, 1 << 24, 2, 512, 5, cu)), + (m.run_pipeline, (lb, 16384, 4, 8, 2, 512, 5, cu)), + (m.run_pipeline, (lb, 16384, 4, 1 << 24, 2, 512, 5, cu[:2]))): + try: + f(*args) + raise AssertionError("no ValueError from %s" % f.__name__) + except ValueError: + pass + # no input mutation + klb, kcu = lb.copy(), cu.copy() + m.run_pipeline(lb, 16384, 8, 16384, 2, 512, 5, cu) + assert np.array_equal(lb, klb), "layer_bytes mutated" + assert np.array_equal(cu, kcu), "compute_us mutated" + ok += 1 + except Exception as exc: # noqa: BLE001 + bad.append("units:%s" % exc) + for (name, L, kind, cb, rs, sb, la, bw, fx, t0) in CASES: + try: + lb, cu = mk_case(abs(hash(name)) % 99991, L, kind) + got = m.run_pipeline(lb, cb, rs, sb, la, bw, fx, cu, t0) + exp = r_pipe(lb.tolist(), cb, rs, sb, la, bw, fx, cu.tolist(), t0) + for k in ("n_chunks", "n_layers", "bytes_total", "total_us", "stall_us", + "bubbles", "conflicts", "link_busy_us", "last_arrival_us"): + assert int(got[k]) == int(exp[k]), "%s %r != %r" % (k, got[k], exp[k]) + for k in ("window", "layer_stall", "layer_start", "slot_reuse", + "conflict_chunks"): + eq(got[k], exp[k], k) + assert np.asarray(got["layer_stall"]).dtype == np.int64, "stall dtype" + ok += 1 + except Exception as exc: # noqa: BLE001 + bad.append("%s:%s" % (name, exc)) + total = len(CASES) + 1 + print("%s %s" % (TOKEN, json.dumps({ + "correctness_ok": ok == total, + "correctness_frac": round(ok / float(total), 6), + "cases": total, "passed": ok, "failures": bad[:6]}))) + + +def _warm_cpu(target_ms=400.0): + """Burn a FIXED amount of CPU, independent of the candidate, before timing. + + An idle box parks its cores at the minimum clock, and the first few hundred + milliseconds of real work are billed at that clock -- `time.process_time` was + measured up to 25x too large for the first ~5 iterations of an otherwise + steady 3 ms workload. Burning the same fixed budget in every mode puts the + governor at full clock before anything that counts is measured. + """ + x = np.arange(8192, dtype=np.int64) + t0 = time.process_time() + while (time.process_time() - t0) * 1000.0 < target_ms: + for _ in range(40): + x = (x * 1103515245 + 12345) % 2147483647 + return int(x[0]) + + +def do_timing(): + m = scope_module() + L = int(os.environ.get("WRO_LAYERS", "768")) + cb = int(os.environ.get("WRO_CHUNK", "16384")) + rs = int(os.environ.get("WRO_SLOTS", "192")) + la = int(os.environ.get("WRO_LOOKAHEAD", "2")) + bw = int(os.environ.get("WRO_BW", "24000")) + rng = np.random.default_rng(20260726) + lb = rng.integers(12, 96, size=L).astype(np.int64) * 65536 + lb[::17] = 0 + cu = rng.integers(120, 900, size=L).astype(np.int64) + cu[3::11] *= 4 + + _warm_cpu(float(os.environ.get("WRO_WARM_MS", "400"))) + m.run_pipeline(lb[:4], cb, rs, cb, la, bw, 7, cu[:4], 0) + r = m.run_pipeline(lb, cb, rs, cb, la, bw, 7, cu, 0) + best = None + for _ in range(3): + t0 = time.process_time() + r = m.run_pipeline(lb, cb, rs, cb, la, bw, 7, cu, 0) + dt = (time.process_time() - t0) * 1000.0 + best = dt if best is None else min(best, dt) + print("%s %s" % (TOKEN, json.dumps({ + "timing_ms": round(best, 4), "layers": L, "chunk": cb, "slots": rs, + "lookahead": la, "n_chunks": int(r["n_chunks"]), + "total_us": int(r["total_us"]), "stall_us": int(r["stall_us"]), + "bubbles": int(r["bubbles"]), "conflicts": int(r["conflicts"]), + "link_busy_us": int(r["link_busy_us"]), + "window_sum": int(np.asarray(r["window"], dtype=np.int64).sum()), + "reuse_sum": int(np.asarray(r["slot_reuse"], dtype=np.int64).sum()), + "start_sum": int(np.asarray(r["layer_start"], dtype=np.int64).sum())}))) + + +if __name__ == "__main__": + cmd = sys.argv[1] if len(sys.argv) > 1 else "correctness" + if cmd == "correctness": + do_correctness() + elif cmd == "timing": + do_timing() + else: + raise SystemExit("usage: workload.py {correctness|timing}") diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/sanitize_feedback.py b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/sanitize_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..d70a722c566c5b3eeaeaa0205cf0b4884fbba7a6 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/score_engine.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/score_engine.sh new file mode 100644 index 0000000000000000000000000000000000000000..400d64db5fa4b2cbc66fc0dc643a6976cba4323a --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/submit.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/loop/submit.sh new file mode 100644 index 0000000000000000000000000000000000000000..1515f082ded46f5698489d7ece29ddd0cac320c0 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/repo/gated_gelu.py b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/repo/gated_gelu.py new file mode 100644 index 0000000000000000000000000000000000000000..73b1ca790df94c1fcbfa7d45d377ae891fe17839 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/repo/prefetch_ring.py b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/repo/prefetch_ring.py new file mode 100644 index 0000000000000000000000000000000000000000..581eb7005a0c3f3ab10ce26a1ccd5f9781dd40c5 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/repo/prefetch_ring.py @@ -0,0 +1,283 @@ +"""Layer-wise weight prefetch over a pinned staging ring. + +Running a model whose weights do not fit in device memory means streaming them in +while the previous layers compute. The scheduler that does this has to answer, in +this order: + +1. how each layer's weight bytes split into fixed-size **transfer chunks**; +2. how far ahead of the layer being computed the prefetcher is allowed to run -- + the **lookahead window**, bounded both by a layer count and by the number of + staging slots; +3. which **pinned ring slot** each chunk lands in, which chunk it evicts, and how + often each slot is reused; +4. when each chunk **arrives**, given that all transfers share one link with a + fixed per-transfer overhead; +5. the per-layer **stall profile**: when a layer can start, when it ends, and how + long compute sat idle waiting for weights; +6. the whole **pipeline report**, including the slots that were overwritten before + their previous occupant had been consumed. + +Conventions that apply to the whole module: + +* Every array is ``int64`` and every division is **integer** division. ``ceil`` is + ``(a + b - 1) // b`` on non-negative integers. Times are microseconds, sizes are + bytes; both are non-negative. +* Chunks are numbered globally in **ascending (layer, offset-within-layer)** order, + which is also the order they are issued on the link. +* A layer with zero weight bytes contributes zero chunks. It is legal, and it is + ready immediately. +* No function may modify any of its inputs. +""" + +import numpy as np +def layer_chunk_table(layer_bytes, chunk_bytes): + """Split every layer's weight bytes into transfer chunks. + + Layer ``l`` of ``layer_bytes`` contributes + ``ceil(layer_bytes[l] / chunk_bytes)`` chunks, all of size ``chunk_bytes`` + except the last one, which carries the remainder. Chunks are numbered globally + in ascending ``(layer, offset)`` order. + + Returns ``(chunk_layer, chunk_size, layer_ptr)``: ``int64 (C,)`` owning layer + per chunk, ``int64 (C,)`` chunk sizes, and ``int64 (L + 1,)`` prefix offsets so + that layer ``l`` owns chunks ``layer_ptr[l] : layer_ptr[l + 1]``. An empty + ``layer_bytes`` yields two empty arrays and ``layer_ptr == [0]``. Raises + ``ValueError`` if ``layer_bytes`` is not 1-D, if any entry is negative, or if + ``chunk_bytes`` is not positive. + """ + lb = np.asarray(layer_bytes, dtype=np.int64) + cb = int(chunk_bytes) + if lb.ndim != 1: + raise ValueError("layer_bytes must be 1-D") + if cb <= 0: + raise ValueError("chunk_bytes must be positive") + if lb.size and int(lb.min()) < 0: + raise ValueError("layer_bytes must be non-negative") + # SLOW-BUT-CORRECT reference path: one python step per chunk, plus a scalar numpy read per layer. + L = int(lb.shape[0]) + c_layer = [] + c_size = [] + ptr = [0] + for l in range(L): + rem = int(lb[l]) + while rem > 0: + take = cb if rem > cb else rem + c_layer.append(l) + c_size.append(take) + rem -= take + ptr.append(len(c_layer)) + return (np.asarray(c_layer, dtype=np.int64).reshape(-1), + np.asarray(c_size, dtype=np.int64).reshape(-1), + np.asarray(ptr, dtype=np.int64)) + +def prefetch_window(layer_ptr, lookahead, ring_slots): + """Exclusive chunk bound the prefetcher may reach while layer ``l`` computes. + + While layer ``l`` is being computed the prefetcher may have fetched any chunk + below ``window[l] = min(layer_ptr[min(l + 1 + lookahead, L)], + layer_ptr[l] + ring_slots)`` -- it may run ``lookahead`` whole layers past the + layer that follows the current one, but never more than ``ring_slots`` chunks + past the first chunk of the current layer, because that is all the staging + space there is. + + Returns ``int64 (L,)``; ``L == 0`` yields an empty array. Raises ``ValueError`` + if ``layer_ptr`` is not 1-D, is empty, is not non-decreasing, does not start at + zero, if ``lookahead`` is negative, or if ``ring_slots`` is not positive. + """ + ptr = np.asarray(layer_ptr, dtype=np.int64) + la = int(lookahead) + rs = int(ring_slots) + if ptr.ndim != 1 or ptr.shape[0] == 0: + raise ValueError("layer_ptr must be a non-empty 1-D array") + if int(ptr[0]) != 0: + raise ValueError("layer_ptr must start at zero") + if ptr.shape[0] > 1 and int(np.diff(ptr).min()) < 0: + raise ValueError("layer_ptr must be non-decreasing") + if la < 0: + raise ValueError("lookahead must be non-negative") + if rs <= 0: + raise ValueError("ring_slots must be positive") + # SLOW-BUT-CORRECT reference path: one python step per layer with scalar numpy indexing. + L = int(ptr.shape[0]) - 1 + out = np.zeros(L, dtype=np.int64) + for l in range(L): + far = l + 1 + la + if far > L: + far = L + a = int(ptr[far]) + b = int(ptr[l]) + rs + out[l] = a if a < b else b + return out + +def ring_assign(chunk_size, ring_slots, slot_bytes): + """Assign chunks to pinned ring slots, round-robin. + + Chunk ``i`` lands in slot ``i % ring_slots`` and evicts chunk + ``i - ring_slots`` (``-1`` for the first pass over the ring). + + Returns ``(slot, evicted, reuse)``: ``int64 (C,)``, ``int64 (C,)`` and + ``int64 (ring_slots,)`` where ``reuse[s]`` counts the chunks assigned to slot + ``s``. Raises ``ValueError`` if ``chunk_size`` is not 1-D, if ``ring_slots`` or + ``slot_bytes`` is not positive, or if any chunk is larger than ``slot_bytes``. + """ + cs = np.asarray(chunk_size, dtype=np.int64) + rs = int(ring_slots) + sb = int(slot_bytes) + if cs.ndim != 1: + raise ValueError("chunk_size must be 1-D") + if rs <= 0: + raise ValueError("ring_slots must be positive") + if sb <= 0: + raise ValueError("slot_bytes must be positive") + if cs.size and int(cs.max()) > sb: + raise ValueError("a chunk does not fit in a staging slot") + # SLOW-BUT-CORRECT reference path: one python step per chunk. + C = int(cs.shape[0]) + slot = np.zeros(C, dtype=np.int64) + ev = np.zeros(C, dtype=np.int64) + reuse = np.zeros(rs, dtype=np.int64) + for i in range(C): + s = i % rs + slot[i] = s + ev[i] = i - rs if i >= rs else -1 + reuse[s] += 1 + return slot, ev, reuse + +def chunk_arrivals(chunk_size, bw_bytes_per_us, fixed_us, issue_us): + """When each chunk finishes landing in its staging slot. + + All chunks share one link and are issued back to back in chunk order. Chunk + ``i`` costs ``ceil(chunk_size[i] / bw_bytes_per_us) + fixed_us`` microseconds, + the first one starts at ``issue_us``, and each subsequent one starts when its + predecessor finished. + + Returns ``(start, done)``, both ``int64 (C,)``. An empty input yields two empty + arrays. Raises ``ValueError`` if ``chunk_size`` is not 1-D, if any entry is + negative, if ``bw_bytes_per_us`` is not positive, or if ``fixed_us`` or + ``issue_us`` is negative. + """ + cs = np.asarray(chunk_size, dtype=np.int64) + bw = int(bw_bytes_per_us) + fx = int(fixed_us) + t0 = int(issue_us) + if cs.ndim != 1: + raise ValueError("chunk_size must be 1-D") + if cs.size and int(cs.min()) < 0: + raise ValueError("chunk_size must be non-negative") + if bw <= 0: + raise ValueError("bw_bytes_per_us must be positive") + if fx < 0: + raise ValueError("fixed_us must be non-negative") + if t0 < 0: + raise ValueError("issue_us must be non-negative") + # SLOW-BUT-CORRECT reference path: a python loop that walks the link queue one transfer at a time. + C = int(cs.shape[0]) + start = np.zeros(C, dtype=np.int64) + done = np.zeros(C, dtype=np.int64) + t = t0 + for i in range(C): + cost = (int(cs[i]) + bw - 1) // bw + fx + start[i] = t + t += cost + done[i] = t + return start, done + +def stall_profile(layer_ptr, chunk_done, compute_us): + """When each layer runs, and how long compute waited for its weights. + + Layer ``l`` is ready at ``ready[l] = max(chunk_done[layer_ptr[l] : + layer_ptr[l + 1]])``, or ``0`` when the layer owns no chunks. Layers run in + order on one device, so ``start[l] = max(ready[l], end[l - 1])`` with + ``end[-1] = 0``, ``end[l] = start[l] + compute_us[l]`` and + ``stall[l] = start[l] - end[l - 1]``. + + Returns ``(start, end, stall)``, all ``int64 (L,)``. Raises ``ValueError`` if + ``layer_ptr`` is not 1-D or empty, if ``compute_us`` is not 1-D of length + ``len(layer_ptr) - 1``, if any compute time is negative, or if ``layer_ptr`` + does not index ``chunk_done`` exactly (``layer_ptr[0] == 0`` and + ``layer_ptr[-1] == len(chunk_done)``). + """ + ptr = np.asarray(layer_ptr, dtype=np.int64) + cd = np.asarray(chunk_done, dtype=np.int64) + cu = np.asarray(compute_us, dtype=np.int64) + if ptr.ndim != 1 or ptr.shape[0] == 0: + raise ValueError("layer_ptr must be a non-empty 1-D array") + L = int(ptr.shape[0]) - 1 + if cu.ndim != 1 or int(cu.shape[0]) != L: + raise ValueError("compute_us must be 1-D of length len(layer_ptr) - 1") + if cu.size and int(cu.min()) < 0: + raise ValueError("compute_us must be non-negative") + if cd.ndim != 1: + raise ValueError("chunk_done must be 1-D") + if int(ptr[0]) != 0 or int(ptr[L]) != int(cd.shape[0]): + raise ValueError("layer_ptr does not index chunk_done") + # SLOW-BUT-CORRECT reference path: a python loop per layer that re-scans the layer's chunk arrivals. + start = np.zeros(L, dtype=np.int64) + end = np.zeros(L, dtype=np.int64) + stall = np.zeros(L, dtype=np.int64) + prev = 0 + for l in range(L): + lo = int(ptr[l]) + hi = int(ptr[l + 1]) + ready = 0 + for j in range(lo, hi): + v = int(cd[j]) + if v > ready: + ready = v + s = ready if ready > prev else prev + start[l] = s + stall[l] = s - prev + prev = s + int(cu[l]) + end[l] = prev + return start, end, stall + +def run_pipeline(layer_bytes, chunk_bytes, ring_slots, slot_bytes, lookahead, + bw_bytes_per_us, fixed_us, compute_us, issue_us=0): + """Plan and score a whole layer-wise weight-prefetch pipeline. + + Chunks the layers, assigns the ring, computes the arrivals and the stall + profile, and then reports the two things a capacity planner asks for: how much + of the wall time was a **bubble** (compute idle, waiting on the link), and how + many ring slots were **overwritten too early** -- a chunk whose transfer starts + before the chunk it evicts has been consumed. A chunk is consumed when the + layer that owns it finishes computing, i.e. at ``end[chunk_layer[i]]``. + + Returns a dict with the python ints ``n_chunks``, ``n_layers``, + ``bytes_total``, ``total_us`` (``end[-1]``, or ``0`` with no layers), + ``stall_us`` (the sum of the per-layer stalls), ``bubbles`` (how many layers + stalled at all), ``conflicts``, ``link_busy_us`` (the sum of the per-chunk + transfer costs) and ``last_arrival_us``; plus the arrays ``window`` + (``int64 (L,)``), ``layer_stall`` (``int64 (L,)``), ``layer_start`` + (``int64 (L,)``), ``slot_reuse`` (``int64 (ring_slots,)``) and + ``conflict_chunks`` (``int64``, the chunk indices whose eviction was early, in + ascending order). + + Raises ``ValueError`` whenever any of the callees would. + """ + c_layer, c_size, ptr = layer_chunk_table(layer_bytes, chunk_bytes) + window = prefetch_window(ptr, lookahead, ring_slots) + slot, ev, reuse = ring_assign(c_size, ring_slots, slot_bytes) + start_c, done_c = chunk_arrivals(c_size, bw_bytes_per_us, fixed_us, issue_us) + cu = np.asarray(compute_us, dtype=np.int64) + l_start, l_end, l_stall = stall_profile(ptr, done_c, cu) + L = int(ptr.shape[0]) - 1 + C = int(c_size.shape[0]) + if C: + consume = l_end[c_layer] + early = (ev >= 0) & (start_c < consume[ev]) + conflict_chunks = np.nonzero(early)[0].astype(np.int64) + else: + conflict_chunks = np.zeros(0, dtype=np.int64) + bw = int(bw_bytes_per_us) + cost = (c_size + bw - 1) // bw + int(fixed_us) if C else np.zeros(0, np.int64) + return {"n_chunks": C, "n_layers": L, + "bytes_total": int(np.asarray(layer_bytes, dtype=np.int64).sum()), + "total_us": int(l_end[L - 1]) if L else 0, + "stall_us": int(l_stall.sum()) if L else 0, + "bubbles": int((l_stall > 0).sum()) if L else 0, + "conflicts": int(conflict_chunks.shape[0]), + "link_busy_us": int(cost.sum()) if C else 0, + "last_arrival_us": int(done_c[C - 1]) if C else 0, + "window": window, "layer_stall": l_stall, "layer_start": l_start, + "slot_reuse": reuse, "conflict_chunks": conflict_chunks} + diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/runtime/entrypoint.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/runtime/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ad0137c7a85f94eeb880a755d3730bfbebf1e3a --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/runtime/run_dev_bench.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/runtime/run_dev_bench.sh new file mode 100644 index 0000000000000000000000000000000000000000..d627a61218d501ea69bdc3323afeb5284accd071 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/runtime/timer.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/runtime/timer.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3e45be674fb4a8218ca84d9cb4dc0f451395652 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-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-offload-layer-prefetch-ring-pipeline-loop16/task/environment/verifier-correctness-manifest.json b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/verifier-correctness-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..78ff4640a599af4f49781d50c14b8886ef27cc70 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/environment/verifier-correctness-manifest.json @@ -0,0 +1,11 @@ +{ + "task_id": "wro-offload-layer-prefetch-ring-pipeline", + "perf_metric": "speedup", + "ref_speedup": 32.230499, + "oracle_candidate_ms": 3.8421, + "baseline_ms": 123.8328, + "noop_speedup": 1.023921, + "baseline2_speedup": 1.885342, + "anchor_source": "4-mode validation run on the authoring CPU lane (Intel Sapphire Rapids)", + "notes": "ref_speedup is the oracle anchor measured on the authoring lane, not a locally re-measured number." +} diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/instruction.md b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ef6ccdd2b769e6729dfb59e060de071b5ed1ae7 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/instruction.md @@ -0,0 +1,172 @@ +# Layer-Wise Weight Prefetch over a Pinned Staging Ring — Performance Task + +## Objective + +`prefetch_ring.py` is the scheduler that lets a model whose weights do not fit in +device memory run anyway: while layer `l` computes, the weights of layers `l + 1` +and beyond are streamed in over a link into a small pool of **pinned staging +slots**. Planning that stream means answering, in this order: + +1. how each layer's weight bytes split into fixed-size **transfer chunks**; +2. how far ahead of the layer being computed the prefetcher may run — the + **lookahead window**, bounded both by a layer count and by the number of + staging slots; +3. which **ring slot** each chunk lands in, which chunk it evicts, and how often + each slot is reused; +4. when each chunk **arrives**, given that all transfers share one link with a + fixed per-transfer overhead; +5. the per-layer **stall profile**: when a layer can start, when it ends, and how + long compute sat idle waiting for weights; +6. the whole **pipeline report** — the bubble budget, and the slots that were + overwritten before their previous occupant had been consumed. + +The current implementation is **functionally correct but slow**: it is a literal +transcription of the specification, so every stage runs in the Python interpreter +one chunk at a time: + +1. the **chunk table** is built by appending to Python lists inside a + `while rem > 0` loop per layer — one interpreter step per chunk; +2. the **lookahead window** is a per-layer loop with scalar numpy indexing; +3. the **ring assignment** walks every chunk to compute `i % ring_slots`, its + evicted predecessor and a per-slot counter; +4. the **link queue** is walked one transfer at a time, accumulating a running + clock — one of the two dominant costs; +5. the **stall profile** re-scans every chunk of a layer to find the layer's last + arrival, and then carries a running `end` forward — the other dominant cost; +6. the **driver** just calls all five in order. + +Your job: **make the planner faster on the benchmark workload while producing +exactly the same output.** You may reorganize everything inside the scope file as +long as the observable contract below is preserved. + +There is real structure to exploit, and finding it is the task. Two of the stages +*look* sequential and are not: the link queue is a running clock, but its cost per +chunk does not depend on the clock, and the stall profile is a running maximum of +`ready[k]` offset by the compute time between `k` and `l`. Both have closed forms +over the whole array. The chunk table looks like an unbounded `while` loop, but the +number of chunks per layer is known before the loop starts. + +## Editable scope (only this file may change) + +``` +prefetch_ring.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. + +## Behavioral contract (what the grader checks) + +All six public entry points must keep their signatures and their behaviour: + +```python +layer_chunk_table(layer_bytes, chunk_bytes) -> (int64 (C,), int64 (C,), int64 (L+1,)) +prefetch_window(layer_ptr, lookahead, ring_slots) -> int64 (L,) +ring_assign(chunk_size, ring_slots, slot_bytes) -> (int64 (C,), int64 (C,), int64 (ring_slots,)) +chunk_arrivals(chunk_size, bw_bytes_per_us, fixed_us, issue_us) -> (int64 (C,), int64 (C,)) +stall_profile(layer_ptr, chunk_done, compute_us) -> (int64 (L,), int64 (L,), int64 (L,)) +run_pipeline(layer_bytes, chunk_bytes, ring_slots, slot_bytes, lookahead, + bw_bytes_per_us, fixed_us, compute_us, issue_us=0) -> dict +``` + +The per-function docstrings in the scope file are normative. The load-bearing +clauses, restated because they are the ones that break: + +1. **Everything is integer.** Every array is `int64`, every division is integer + division, `ceil` is `(a + b - 1) // b` on non-negative integers, times are + microseconds and sizes are bytes. Every comparison the grader makes is exact. +2. **Chunking is per layer, and the remainder is last.** Layer `l` contributes + `ceil(layer_bytes[l] / chunk_bytes)` chunks, all of size `chunk_bytes` except + the final one, which carries `layer_bytes[l] % chunk_bytes` when that is + non-zero. Chunks are numbered globally in ascending `(layer, offset)` order, + which is also the order they are issued on the link. **A zero-byte layer + contributes no chunks** and `layer_ptr` still records its (empty) range. +3. **The window bound is `min(layer_ptr[min(l + 1 + lookahead, L)], layer_ptr[l] + + ring_slots)`** — `lookahead` whole layers past the layer *after* the current + one, and never more than `ring_slots` chunks past the current layer's first + chunk. It is an **exclusive** bound. +4. **The ring is plain round-robin:** chunk `i` occupies slot `i % ring_slots` and + evicts chunk `i - ring_slots`, or `-1` on the first pass. `reuse[s]` counts the + chunks assigned to slot `s`, and its length is `ring_slots` even when no chunk + exists. +5. **The link is serial and its per-chunk cost is fixed:** + `cost[i] = ceil(chunk_size[i] / bw_bytes_per_us) + fixed_us`, the first transfer + starts at `issue_us`, and `start[i] = done[i-1]`. The overhead is added *after* + the ceiling division, not before. +6. **A layer's readiness is the maximum arrival over its own chunks**, and `0` when + it owns none. Compute is serialised on one device, so + `start[l] = max(ready[l], end[l-1])` with `end[-1] = 0`, + `end[l] = start[l] + compute_us[l]` and `stall[l] = start[l] - end[l-1]`. + Dropping the `end[l-1]` term is the classic mistake — it is what a naive + vectorisation produces, and it is checked. +7. **A conflict is an early eviction:** chunk `i` conflicts when + `ev[i] >= 0 and start[i] < end[chunk_layer[ev[i]]]` — its transfer began before + the chunk it overwrites had been consumed, and a chunk is consumed when the + layer owning it finishes computing. `conflict_chunks` lists those indices in + ascending order. +8. **Shapes, dtypes and keys are fixed.** `run_pipeline` returns exactly the python + ints `n_chunks`, `n_layers`, `bytes_total`, `total_us` (the last layer's `end`, + or `0` with no layers), `stall_us`, `bubbles` (how many layers stalled at all), + `conflicts`, `link_busy_us` (the sum of the per-chunk costs) and + `last_arrival_us`, plus the arrays `window`, `layer_stall`, `layer_start`, + `slot_reuse` and `conflict_chunks`. +9. **No input may be modified**, and every documented input-validation + `ValueError` must still fire: a non-1-D array, a negative byte count or compute + time, a non-positive `chunk_bytes` / `ring_slots` / `slot_bytes` / + `bw_bytes_per_us`, a negative `lookahead` / `fixed_us` / `issue_us`, a chunk + larger than a staging slot, a `layer_ptr` that is empty, does not start at zero, + is not non-decreasing, or does not index `chunk_done` exactly, and a + `compute_us` whose length is not `len(layer_ptr) - 1`. + +The grader compares every returned value against an independent reference over +curated cases that between them exercise a plain model, layers with zero bytes, an +all-zero model, free compute, compute-bound compute, one huge layer, a chunk size +larger than any layer, a tiny chunk size, a one-slot ring, a ring larger than the +model, `lookahead` of 0 and 99, a one-byte-per-microsecond link, an effectively +infinite link, zero and large per-transfer overhead, a late issue time, slots with +slack, a single layer, no layers at all, and two deep models. Any deviation scores +zero. + +## Correctness & how you are scored + +- Correctness is a hard gate: any mismatch against the reference, any mutated + input, any missing error contract, or any edit outside the scope file scores + **0**. +- Subject to that gate, the score is a bounded log curve on the speedup of the whole + planner over the frozen slow baseline on the benchmark workload: a correct but + unimproved submission scores **0**, matching the reference-grade implementation's + speed scores **0.5**, and going substantially beyond it approaches the **1.0** + ceiling. Partial progress scores partially — vectorising the chunk table and the + link queue while leaving the ring walk and the stall scan in Python gets only a + small fraction of the way up the curve. +- The benchmark workload plans **768 layers chunked at 16 KiB (about 150 thousand + chunks) over a 192-slot ring**, so every per-chunk stage matters and the + per-layer stages do not. +- Timing is CPU time (`time.process_time`), min of 3 runs, taken after a fixed CPU + warm-up, so the score is robust to machine state. + +## Notes + +- `numpy` is available. There is no GPU and no torch in this task. +- Because every quantity is an integer, there is no tolerance to hide behind: a + reassociated sum is either the same integer or a failure. +- Nothing forbids computing an intermediate once and sharing it between the driver + and its callees, as long as every function is still correct when called on its + own and no input array is written to. + +## Solve independently — prohibited actions (any one => the whole task scores 0) + +- Do **not** read, modify, or reverse-engineer the hidden verifier / grader / + timing harness, and do not fabricate a reward. +- Do **not** fetch an upstream reference implementation (`accelerate`, + DeepSpeed ZeRO-Inference, vLLM weight streaming or any other offload stack) for + the scoped planner, in any form. +- Do **not** edit anything outside the declared scope `prefetch_ring.py`, and do + not bypass the scope or network isolation. +- Only legitimate optimization of the in-scope code counts. + +## 提交方式 + +本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。 +改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。 diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/pre_artifacts.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/pre_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..32a654de34d90704087531b600689dde6367a29d --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/pre_artifacts.sh @@ -0,0 +1,163 @@ +#!/bin/bash +# ============================================================================ +# pre_artifacts.sh — kfc/wro-offload-layer-prefetch-ring-pipeline-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:128: WORKDIR /app/repo +# evidence Dockerfile:77: && cd /app/repo \ +# evidence Dockerfile:84: && test "$(git rev-list --count HEAD)" = "1" \ +# evidence test.sh:6: export PYTHONPATH="/app/repo:${PYTHONPATH:-}" +# evidence test.sh:9: 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-offload-layer-prefetch-ring-pipeline-loop16/task/solution/README.md b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8172d8d62e328fd9d9c6ada2f759d0477ac4878a --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/solution/README.md @@ -0,0 +1,13 @@ +# solution/ — 参考实现(不参与判分) + +⚠️ **本目录不随包提供参考实现。** + +本题的参考实现只存在于单文件变体形式,未随本包发布,因此: + +- **没有可直接执行的锚点重标定通路** —— `tests/ref_speedup.txt` 里的锚点是在建题环境 + 标定的(见 `../tests/ref_speedup.caveat.md` 的「标定条件」),换硬件后该值不可比, + 请谨慎使用或自行用一份等价的参考实现重新标定; +- 起始树 `../environment/repo/` 是**已被降级的起始实现**,判分即以它为 diff 基准。 + +verifier 本身仍原生支持 `oracle` / `negative` / `noop` 模式分派(参考实现按路径传入、 +从不烤进镜像),所以你补上自己的参考实现后重标定流程可直接跑通。 diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/solution/solve.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1e5d119e1af033f8fbd7b00d4707d40626834e92 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/solution/solve.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# solution/solve.sh — kfc/wro-offload-layer-prefetch-ring-pipeline-loop16 +# 🔴 本题不随包提供参考实现 —— 本脚本只负责把这件事说清楚,并以 exit 2 表明 +# 「无法落地」。它不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。 +# +# oracle 形态 : 🔴 无 —— 本题不随包提供参考实现(solution/ 下只有 README.md)。 +# $REPO : /app/repo (tests/test.sh: REPO=/app/repo) +# 被计分单元 : /app/repo/prefetch_ring.py +# 来源:tests/test.sh 的 SCOPE=("prefetch_ring.py") +# 本脚本行为 : 落地类模式只打印说明并 exit 2;--noop 例外 —— 它照统一语义把 +# 可编辑面复位到烤入基线后 exit 0(这一步本题是做得到的)。 +# +# ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)──────────────────────── +# PKG=/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task +# IMG=fai/kfc-wro-offload-layer-prefetch-ring-pipeline-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) 🔴 本题无参考实现可落地 —— solve.sh 会打印说明并 exit 2。这条通路只能用来 +# # 判 agent 的候选树,或(纯净容器里直接跳到第 3 步)判 no-op 基线。 +# # 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 +# +# 期望:--noop(纯净容器)→ 0(挖洞基线过不了正确性门);oracle/negative 无从验证。 +# 本题带 loop16 harness:`bash /opt/loop/submit.sh` 判的也是同一棵工作树、 +# 同样走 candidate 模式(口径一致)。 +# ────────────────────────────────────────────────────────────────────────── +# +# 用法: bash solution/solve.sh [--oracle|--negative|--baseline2|--noop] +# --noop 之外的任何模式都只打印说明并 exit 2(本题没有参考实现产物)。 +# +# --noop 语义(与其余 53 题一致):把可编辑面复位到烤入基线(与 verifier 取基线的 +# 方式一致 —— `git checkout HEAD -- `,HEAD 不动),使对照组能量到真正的 +# no-op 值,然后 exit 0。本题唯一缺的是「落地参考实现」这一步。 +set -uo pipefail + +TASK_ID="wro-offload-layer-prefetch-ring-pipeline-loop16" +REPO="${KFC_REPO_DIR:-/app/repo}" +SCOPE=("prefetch_ring.py") + +say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; } +die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; } +GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; } + +# --noop 仍然支持:本题虽然没有参考实现可落地,但「把可编辑面复位到烤入基线」是可满足的, +# 且 runner 需要它来量 no-op 对照值,所以照 D 任务的统一语义实现并 exit 0。 +if [ "${1:-}" = "--noop" ]; then + GIT rev-parse --git-dir >/dev/null 2>&1 \ + || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑" + for f in "${SCOPE[@]}"; do + [ -e "$REPO/$f" ] || die "被计分单元不存在:$REPO/$f(REPO 不对?可用 KFC_REPO_DIR 覆盖)" + done + HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD" + N_BEFORE="$(GIT rev-list --count HEAD)" + 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 + +cat >&2 <<'EOF' +本题**不随包提供参考实现** —— solution/ 下只有 README.md,没有 oracle / negative / +baseline2 产物(见 solution/README.md:参考实现只存在于单文件变体形式,未随本包发布)。 + +因此本脚本无法落地任何参考实现: + · 被计分单元 : /app/repo/prefetch_ring.py + (来源 tests/test.sh 的 SCOPE=("prefetch_ring.py"),$REPO=/app/repo) + · verifier 本身仍原生支持 oracle / negative / noop 模式分派 —— 参考实现按路径传入、 + 从不烤进镜像。你补上一份等价实现后,重标定通路可直接跑通: + docker exec -e KERNELBENCH_VERIFY_MODE=oracle \ + -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \ + <容器> bash /tests/test.sh + · tests/ref_speedup.txt 里的锚点是建题环境标定的(见 tests/ref_speedup.caveat.md), + 换硬件后不可比,且没有可直接执行的重标定通路。 + +exit 2 = 本题不支持 solve.sh 落地参考实现(不是脚本出错);--noop 仍然 exit 0。 +EOF +exit 2 diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/task.toml b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ea3b14a65a63d61d34185931f8bce906e3cc08e --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/task.toml @@ -0,0 +1,46 @@ +schema_version = "2.0" + +# 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1) +artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"] + +[task] +id = "wro-offload-layer-prefetch-ring-pipeline-loop16" +bench = "kfc" +kind = "performance" +language = "python" +title = "Layer-Wise Weight Prefetch over a Pinned Staging Ring — Performance Task" +instruction = "instruction.md" + +[agent] +timeout_sec = 5400 + +# carved-tree provenance (environment/repo/ recovered from): /kernelbench/wro-offload-layer-prefetch-ring-pipeline-loop16:v1@sha256:9a3ddd4847b739838e272e95b21059875089f43a96af39fdc962eaf1222dbe40 +# Open-source build: `cd && docker build -f environment/Dockerfile -t fai/kfc-wro-offload-layer-prefetch-ring-pipeline-loop16:oss .` +[environment] +docker_image = "fai/kfc-wro-offload-layer-prefetch-ring-pipeline-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 = ["prefetch_ring.py"] +result_paths = ["/logs/verifier/reward.json"] + +[primary_metric] +name = "speedup" +goal = "maximize" +reward_formula = "performance: reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 — 0.5 at parity with the oracle, capped 1.0 at oracle^2; 0 if a hard gate fails or speedup <= 1. ref_speedup source unchanged (tests/ref_speedup.txt or the in-image manifest)." +ref_speedup = 32.230499 +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" diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/compute_reward.py b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..6d195098fbb5d4754baf2b8ca568dc8006ac3f5b --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/compute_reward.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""compute_reward for wro-offload-layer-prefetch-ring-pipeline-loop16 — PERFORMANCE reward formula. + +reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 in [0.0, 1.0] + speedup = base_ms / candidate_ms (raw wall speedup vs the frozen degraded baseline) + ref_speedup = the oracle's median speedup in the same image (unchanged source) + parity with the oracle -> 0.5 ; oracle^2 or better -> capped 1.0 + +PRE-GATES (any hit -> reward 0, the formula is NOT entered): the correctness / +scope / import-origin / anti-cheat gates live in test.sh and score 0 there; +here the remaining pre-gates are speedup <= 1 and ref_speedup <= 1. + +NOTE: test.sh computes the authoritative reward inline with the identical +formula. This module is the standalone/argv entry point kept for parity. +""" +import json +import math +import sys + +TOKEN = "WRO_PREFETCHRING_RESULT " + + +def load(path): + for line in open(path): + if line.startswith(TOKEN): + return json.loads(line[len(TOKEN):]) + raise SystemExit(f"no WRO_PREFETCHRING_RESULT in {path}") + + +def log_reward(speedup, ref_speedup): + """The performance reward curve + its numeric pre-gates. Returns (reward, reasons).""" + reasons = [] + if not (isinstance(speedup, (int, float)) and math.isfinite(speedup)): + return 0.0, ["invalid_primary_metric_value"] + if not (isinstance(ref_speedup, (int, float)) and math.isfinite(ref_speedup)): + return 0.0, ["invalid_ref_speedup"] + if speedup <= 1.0: + return 0.0, ["speedup_not_above_baseline"] + if ref_speedup <= 1.0: + return 0.0, ["ref_speedup_invalid"] + return max(0.0, min(1.0, max(0.0, min(1.0, math.log(speedup) / math.log(ref_speedup) - 1.0)))), reasons + + +def main(): + # argv: candidate_timing_out baseline_ms [ref_speedup] + 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 + ref_speedup = float(sys.argv[3]) if len(sys.argv) > 3 else 1.0 + reward, reasons = log_reward(speedup, ref_speedup) + out = { + "task_type": "performance", + "reward": round(reward, 6), + "hard_fail_reasons": reasons, + "speedup": round(speedup, 6), + "ref_speedup": ref_speedup, + "cv": {"baseline": None, "candidate": None}, + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0", + "baseline_ms": base_ms, + "candidate_ms": cm, + } + print(json.dumps(out)) + + +if __name__ == "__main__": + main() diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.caveat.md b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.caveat.md new file mode 100644 index 0000000000000000000000000000000000000000..0e0a343dc99fa2402521256a8260f38597eda02a --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.caveat.md @@ -0,0 +1,29 @@ +# ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑) + +`ref_speedup.txt` 里的 **32.230499** 是 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-offload-layer-prefetch-ring-pipeline-loop16:oss bash /tests/test.sh +# 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt +``` + +自证:`noop`(不打补丁)应 ≈1.0 → 被门到 0;`negative`(`KERNELBENCH_NEGATIVE_PATCH=`)必须 0。 + +⚠️ 本题**不随包提供 oracle.patch**(其参考实现只有单文件变体形式),因此没有可直接执行的重标定通路;换硬件时该锚点不可比,请谨慎使用或自行标定。 diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.note.txt b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.note.txt new file mode 100644 index 0000000000000000000000000000000000000000..a60a56e6014fa1d11fa50737fd91732b1f627c53 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.note.txt @@ -0,0 +1,8 @@ +ref_speedup = 32.230499 (the oracle's measured median speedup over the frozen degraded baseline +in the SAME image). Source: the recorded oracle-mode measurement for this task, copied verbatim; +no new measurement was taken. + +Why this file exists: the shipped image does NOT carry /opt/verifier-correctness-manifest.json, +so test.sh's ref_speedup fell back to 1.0. Under the old raw-speedup reward that was harmless; +under the log-curve reward formula, ref_speedup<=1 is a hard pre-gate and zeroed every run. tests/ is +uploaded fresh at scoring time, so this override needs NO image rebuild. diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.txt b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ad3ddf9a966fa89136f6f7970fd8b4043a3d8d5 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/ref_speedup.txt @@ -0,0 +1 @@ +32.230499 diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/test.sh b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f8db252a3438079865d9eacc70b122257522226f --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/test.sh @@ -0,0 +1,149 @@ +#!/usr/bin/env bash +# Verifier for wro-offload-layer-prefetch-ring-pipeline. +# layer-wise weight prefetch over a pinned staging ring: chunking, lookahead window, ring conflicts, arrivals, stall profile +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=("prefetch_ring.py") +MODNAME="prefetch_ring" +TOKEN="WRO_PREFETCHRING_RESULT" + +HARD=(); add_hard(){ HARD+=("$1"); } +correctness_ok=true; scope_ok=true; import_origin_ok=true; benchmark_ok=true + +# ---- 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 ---- +MODNAME="$MODNAME" python3 - > "$LOG/import_origin.log" 2>&1 <<'PY' +import os, sys, importlib +sys.path.insert(0, "/app/repo") +m = importlib.import_module(os.environ["MODNAME"]) +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 + +speedup=0.0; ref_speedup=1.0; base_ms=-1; cand_ms=-1 +# ---- ref_speedup (oracle-calibrated anchor; the log reward curve needs it) ---- +# Prefer the tests/-local override: tests/ is uploaded fresh at scoring time, so the +# anchor can be recalibrated with NO image rebuild. Fall back to the in-image manifest. +if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then + ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt") + [ -n "$ref_speedup" ] || ref_speedup=1.0 +elif [ -f "$TESTS_DIR/verifier-correctness-manifest.json" ]; then + ref_speedup=$(TD="$TESTS_DIR" python3 -c "import json,os;print(json.load(open(os.environ['TD']+'/verifier-correctness-manifest.json')).get('ref_speedup',1.0))" 2>/dev/null || echo 1.0) +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 "$TOKEN" "$LOG/correctness.out" | TOKEN="$TOKEN" python3 -c "import json,os,sys +try: print(json.loads(sys.stdin.read().split(os.environ['TOKEN']+' ',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 "$TOKEN" "$LOG/cand_timing.out" | TOKEN="$TOKEN" python3 -c "import json,os,sys;print(json.loads(sys.stdin.read().split(os.environ['TOKEN']+' ',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 "$TOKEN" "$LOG/base_timing.out" | TOKEN="$TOKEN" python3 -c "import json,os,sys;print(json.loads(sys.stdin.read().split(os.environ['TOKEN']+' ',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 ---- +# The HARD PRE-GATES are unchanged and still decide 0 first: any hard_fail reason, +# a false correctness gate, speedup <= 1 or ref_speedup <= 1 => reward 0 and the +# formula is NEVER entered. Only a clean, above-baseline run reaches the log curve +# (parity with the oracle scores 0.5; oracle^2 or better caps at 1.0). +reward=0.0 +if [ "${#HARD[@]}" -eq 0 ] && [ "$correctness_ok" = true ]; then + REW_OUT=$(REW_SP="$speedup" REW_REF="$ref_speedup" python3 - <<'PYR' +import math, os +def f(x): + try: return float(x) + except Exception: return float("nan") +sp, ref = f(os.environ.get("REW_SP")), f(os.environ.get("REW_REF")) +if not (math.isfinite(sp) and math.isfinite(ref)): + print("0.0 invalid_primary_metric_value") +elif sp <= 1.0: + print("0.0 speedup_not_above_baseline") +elif ref <= 1.0: + print("0.0 ref_speedup_invalid") +else: + print("%.6f -" % max(0.0, min(1.0, max(0.0, min(1.0, math.log(sp) / math.log(ref) - 1.0))))) +PYR +) + reward=$(printf '%s\n' "$REW_OUT" | awk 'NR==1{print $1}') + RGATE=$(printf '%s\n' "$REW_OUT" | awk 'NR==1{print $2}') + [ -n "${reward:-}" ] || reward=0.0 + if [ -n "${RGATE:-}" ] && [ "$RGATE" != "-" ]; then add_hard "$RGATE"; fi +fi +nhard="${#HARD[@]}" +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, + "task_type": "performance", + "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0", + "cv": {"baseline": None, "candidate": None}, + "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"}} +v["hard_fail_reasons"] = v["hard_fails"] # canonical field name (alias) +print(json.dumps(v)) +PY +cat "$LOG/reward.json" diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/verifier-correctness-manifest.json b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/verifier-correctness-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..78ff4640a599af4f49781d50c14b8886ef27cc70 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/verifier-correctness-manifest.json @@ -0,0 +1,11 @@ +{ + "task_id": "wro-offload-layer-prefetch-ring-pipeline", + "perf_metric": "speedup", + "ref_speedup": 32.230499, + "oracle_candidate_ms": 3.8421, + "baseline_ms": 123.8328, + "noop_speedup": 1.023921, + "baseline2_speedup": 1.885342, + "anchor_source": "4-mode validation run on the authoring CPU lane (Intel Sapphire Rapids)", + "notes": "ref_speedup is the oracle anchor measured on the authoring lane, not a locally re-measured number." +} diff --git a/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/workload.py b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/workload.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c635a63840477db5f09f2de623ebd605f29326 --- /dev/null +++ b/tasks/kfc/wro-offload-layer-prefetch-ring-pipeline-loop16/task/tests/workload.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python3 +"""Verifier workload for the layer-wise weight-prefetch ring scope. + +correctness: 24 scenarios checked against an INDEPENDENT pure-python reference + written here in the harness (never imported from /app/repo). + Everything is integer, so every comparison is EXACT. +timing: 768 layers chunked at 16 KiB (~166k chunks) over a 192-slot ring + with a 2-layer lookahead; CPU time via time.process_time (exp §6.52), + min of 3, after a fixed 400 ms CPU warm-up that makes the measurement + immune to the idle-clock ramp. +""" +import importlib +import json +import os +import sys +import time + +import numpy as np + +sys.path.insert(0, "/app/repo") +TOKEN = "WRO_PREFETCHRING_RESULT" + + +def scope_module(): + return importlib.import_module("prefetch_ring") + + +# ---------------------------------------------------------------- reference +def r_chunks(lb, cb): + c_layer, c_size, ptr = [], [], [0] + for l, nb in enumerate(lb): + rem = nb + while rem > 0: + take = cb if rem > cb else rem + c_layer.append(l) + c_size.append(take) + rem -= take + ptr.append(len(c_layer)) + return c_layer, c_size, ptr + + +def r_window(ptr, la, rs): + L = len(ptr) - 1 + out = [] + for l in range(L): + far = min(l + 1 + la, L) + out.append(min(ptr[far], ptr[l] + rs)) + return out + + +def r_ring(cs, rs): + slot, ev = [], [] + reuse = [0] * rs + for i in range(len(cs)): + s = i % rs + slot.append(s) + ev.append(i - rs if i >= rs else -1) + reuse[s] += 1 + return slot, ev, reuse + + +def r_arr(cs, bw, fx, t0): + start, done = [], [] + t = t0 + for v in cs: + cost = (v + bw - 1) // bw + fx + start.append(t) + t += cost + done.append(t) + return start, done + + +def r_stall(ptr, cd, cu): + L = len(ptr) - 1 + start, end, stall = [], [], [] + prev = 0 + for l in range(L): + ready = 0 + for j in range(ptr[l], ptr[l + 1]): + if cd[j] > ready: + ready = cd[j] + s = ready if ready > prev else prev + start.append(s) + stall.append(s - prev) + prev = s + cu[l] + end.append(prev) + return start, end, stall + + +def r_pipe(lb, cb, rs, sb, la, bw, fx, cu, t0): + c_layer, c_size, ptr = r_chunks(lb, cb) + wnd = r_window(ptr, la, rs) + slot, ev, reuse = r_ring(c_size, rs) + s_c, d_c = r_arr(c_size, bw, fx, t0) + l_s, l_e, l_st = r_stall(ptr, d_c, cu) + C = len(c_size) + L = len(lb) + conf = [] + for i in range(C): + if ev[i] >= 0 and s_c[i] < l_e[c_layer[ev[i]]]: + conf.append(i) + cost = [(v + bw - 1) // bw + fx for v in c_size] + return {"n_chunks": C, "n_layers": L, "bytes_total": sum(lb), + "total_us": l_e[L - 1] if L else 0, + "stall_us": sum(l_st), "bubbles": sum(1 for v in l_st if v > 0), + "conflicts": len(conf), "link_busy_us": sum(cost), + "last_arrival_us": d_c[C - 1] if C else 0, + "window": wnd, "layer_stall": l_st, "layer_start": l_s, + "slot_reuse": reuse, "conflict_chunks": conf} + + +def eq(got, exp, tag): + g = np.asarray(got, dtype=np.int64) + e = np.asarray(exp, dtype=np.int64) + if e.size == 0 and g.size == 0: + return + assert g.shape == e.shape, "%s shape %r != %r" % (tag, g.shape, e.shape) + assert np.array_equal(g, e), "%s mismatch" % tag + + +# ---------------------------------------------------------------- scenarios +def mk_case(seed, L, kind): + rng = np.random.default_rng(seed) + lb = (rng.integers(4, 40, size=L).astype(np.int64) * 4096) + cu = rng.integers(20, 200, size=L).astype(np.int64) + if kind == "zero_layers": + lb = np.zeros(L, dtype=np.int64) + elif kind == "some_empty" and L >= 4: + lb[1] = 0 + lb[L - 1] = 0 + elif kind == "compute_free": + cu = np.zeros(L, dtype=np.int64) + elif kind == "compute_heavy": + cu = cu * 500 + elif kind == "lopsided" and L >= 3: + lb[0] = 400 * 4096 + return lb, cu + + +CASES = [ + # name, L, kind, chunk, slots, slot_bytes, lookahead, bw, fixed, issue + ("plain", 24, "plain", 16384, 12, 16384, 2, 512, 5, 0), + ("some_empty", 24, "some_empty", 16384, 12, 16384, 2, 512, 5, 0), + ("zero_layers", 12, "zero_layers", 16384, 8, 16384, 2, 512, 5, 0), + ("compute_free", 20, "compute_free", 16384, 10, 16384, 2, 512, 5, 0), + ("compute_heavy", 20, "compute_heavy", 16384, 10, 16384, 2, 512, 5, 0), + ("lopsided", 18, "lopsided", 16384, 9, 16384, 2, 512, 5, 0), + ("chunk_huge", 16, "plain", 1 << 24, 6, 1 << 24, 2, 512, 5, 0), + ("chunk_tiny", 6, "plain", 4096, 8, 4096, 2, 512, 5, 0), + ("slots_1", 16, "plain", 16384, 1, 16384, 2, 512, 5, 0), + ("slots_huge", 16, "plain", 16384, 999, 16384, 2, 512, 5, 0), + ("look_0", 20, "plain", 16384, 10, 16384, 0, 512, 5, 0), + ("look_huge", 20, "plain", 16384, 10, 16384, 99, 512, 5, 0), + ("bw_1", 8, "plain", 16384, 6, 16384, 2, 1, 5, 0), + ("bw_huge", 20, "plain", 16384, 10, 16384, 2, 1 << 26, 5, 0), + ("fixed_0", 20, "plain", 16384, 10, 16384, 2, 512, 0, 0), + ("fixed_big", 20, "plain", 16384, 10, 16384, 2, 512, 900, 0), + ("issue_late", 20, "plain", 16384, 10, 16384, 2, 512, 5, 7777), + ("slot_slack", 18, "plain", 16384, 9, 1 << 20, 2, 512, 5, 0), + ("one_layer", 1, "plain", 16384, 4, 16384, 2, 512, 5, 0), + ("no_layers", 0, "plain", 16384, 4, 16384, 2, 512, 5, 0), + ("deep", 64, "plain", 8192, 16, 8192, 3, 512, 5, 0), + ("deep_tight", 64, "compute_free", 8192, 2, 8192, 1, 512, 5, 0), + ("wide_chunks", 30, "lopsided", 32768, 20, 32768, 4, 256, 9, 3), +] + + +def do_correctness(): + m = scope_module() + ok = 0 + bad = [] + try: + lb, cu = mk_case(11, 14, "plain") + cl, cs, ptr = m.layer_chunk_table(lb, 16384) + rcl, rcs, rptr = r_chunks(lb.tolist(), 16384) + eq(cl, rcl, "chunk_layer") + eq(cs, rcs, "chunk_size") + eq(ptr, rptr, "layer_ptr") + assert np.asarray(cs).dtype == np.int64, "chunk dtype" + e0 = m.layer_chunk_table(np.zeros(0, dtype=np.int64), 4096) + assert np.asarray(e0[0]).shape == (0,) and np.asarray(e0[2]).tolist() == [0], \ + "empty chunk table" + eq(m.layer_chunk_table(np.zeros(3, dtype=np.int64), 4096)[2], [0, 0, 0, 0], + "all-empty ptr") + for la, rs in ((0, 4), (2, 4), (99, 3), (1, 1), (2, 10 ** 6)): + eq(m.prefetch_window(np.asarray(rptr, dtype=np.int64), la, rs), + r_window(rptr, la, rs), "window la=%d rs=%d" % (la, rs)) + assert np.asarray(m.prefetch_window(np.zeros(1, dtype=np.int64), 2, 4)).shape \ + == (0,), "empty window" + for rs in (1, 5, 4096): + gs, ge, gr = m.ring_assign(np.asarray(rcs, dtype=np.int64), rs, 1 << 24) + es, ee, er = r_ring(rcs, rs) + eq(gs, es, "ring slot rs=%d" % rs) + eq(ge, ee, "ring evict rs=%d" % rs) + eq(gr, er, "ring reuse rs=%d" % rs) + assert np.asarray(m.ring_assign(np.zeros(0, dtype=np.int64), 3, + 4096)[2]).shape == (3,), "empty ring reuse" + for bw, fx, t0 in ((512, 5, 0), (1, 0, 0), (1 << 26, 900, 1234)): + gs, gd = m.chunk_arrivals(np.asarray(rcs, dtype=np.int64), bw, fx, t0) + es, ed = r_arr(rcs, bw, fx, t0) + eq(gs, es, "arr start bw=%d" % bw) + eq(gd, ed, "arr done bw=%d" % bw) + assert np.asarray(m.chunk_arrivals(np.zeros(0, dtype=np.int64), 4, 0, + 0)[0]).shape == (0,), "empty arrivals" + _s, dc = m.chunk_arrivals(np.asarray(rcs, dtype=np.int64), 512, 5, 0) + for cvec in (cu, np.zeros(14, dtype=np.int64), cu * 400): + gs, ge, gt = m.stall_profile(np.asarray(rptr, dtype=np.int64), dc, cvec) + es, ee, et = r_stall(rptr, np.asarray(dc).tolist(), cvec.tolist()) + eq(gs, es, "stall start") + eq(ge, ee, "stall end") + eq(gt, et, "stall stall") + z = m.stall_profile(np.zeros(1, dtype=np.int64), np.zeros(0, dtype=np.int64), + np.zeros(0, dtype=np.int64)) + assert all(np.asarray(x).shape == (0,) for x in z), "empty stall profile" + # error paths + for f, args in ((m.layer_chunk_table, (lb.reshape(-1, 2), 4096)), + (m.layer_chunk_table, (lb, 0)), + (m.layer_chunk_table, (-lb - 1, 4096)), + (m.prefetch_window, (np.zeros(0, dtype=np.int64), 2, 4)), + (m.prefetch_window, (np.array([1, 2], dtype=np.int64), 2, 4)), + (m.prefetch_window, (np.array([0, 5, 3], dtype=np.int64), 2, 4)), + (m.prefetch_window, (np.array([0, 3], dtype=np.int64), -1, 4)), + (m.prefetch_window, (np.array([0, 3], dtype=np.int64), 2, 0)), + (m.ring_assign, (np.asarray(rcs).reshape(-1, 1), 4, 1 << 24)), + (m.ring_assign, (np.asarray(rcs), 0, 1 << 24)), + (m.ring_assign, (np.asarray(rcs), 4, 0)), + (m.ring_assign, (np.asarray(rcs), 4, 8)), + (m.chunk_arrivals, (np.asarray(rcs).reshape(-1, 1), 4, 0, 0)), + (m.chunk_arrivals, (-np.asarray(rcs) - 1, 4, 0, 0)), + (m.chunk_arrivals, (np.asarray(rcs), 0, 0, 0)), + (m.chunk_arrivals, (np.asarray(rcs), 4, -1, 0)), + (m.chunk_arrivals, (np.asarray(rcs), 4, 0, -1)), + (m.stall_profile, (np.zeros(0, dtype=np.int64), dc, cu)), + (m.stall_profile, (np.asarray(rptr, dtype=np.int64), dc, + cu[:3])), + (m.stall_profile, (np.asarray(rptr, dtype=np.int64), dc, + -cu - 1)), + (m.stall_profile, (np.asarray(rptr, dtype=np.int64), + dc[:-1], cu)), + (m.run_pipeline, (lb, 0, 4, 1 << 24, 2, 512, 5, cu)), + (m.run_pipeline, (lb, 16384, 4, 8, 2, 512, 5, cu)), + (m.run_pipeline, (lb, 16384, 4, 1 << 24, 2, 512, 5, cu[:2]))): + try: + f(*args) + raise AssertionError("no ValueError from %s" % f.__name__) + except ValueError: + pass + # no input mutation + klb, kcu = lb.copy(), cu.copy() + m.run_pipeline(lb, 16384, 8, 16384, 2, 512, 5, cu) + assert np.array_equal(lb, klb), "layer_bytes mutated" + assert np.array_equal(cu, kcu), "compute_us mutated" + ok += 1 + except Exception as exc: # noqa: BLE001 + bad.append("units:%s" % exc) + for (name, L, kind, cb, rs, sb, la, bw, fx, t0) in CASES: + try: + lb, cu = mk_case(abs(hash(name)) % 99991, L, kind) + got = m.run_pipeline(lb, cb, rs, sb, la, bw, fx, cu, t0) + exp = r_pipe(lb.tolist(), cb, rs, sb, la, bw, fx, cu.tolist(), t0) + for k in ("n_chunks", "n_layers", "bytes_total", "total_us", "stall_us", + "bubbles", "conflicts", "link_busy_us", "last_arrival_us"): + assert int(got[k]) == int(exp[k]), "%s %r != %r" % (k, got[k], exp[k]) + for k in ("window", "layer_stall", "layer_start", "slot_reuse", + "conflict_chunks"): + eq(got[k], exp[k], k) + assert np.asarray(got["layer_stall"]).dtype == np.int64, "stall dtype" + ok += 1 + except Exception as exc: # noqa: BLE001 + bad.append("%s:%s" % (name, exc)) + total = len(CASES) + 1 + print("%s %s" % (TOKEN, json.dumps({ + "correctness_ok": ok == total, + "correctness_frac": round(ok / float(total), 6), + "cases": total, "passed": ok, "failures": bad[:6]}))) + + +def _warm_cpu(target_ms=400.0): + """Burn a FIXED amount of CPU, independent of the candidate, before timing. + + An idle box parks its cores at the minimum clock, and the first few hundred + milliseconds of real work are billed at that clock -- `time.process_time` was + measured up to 25x too large for the first ~5 iterations of an otherwise + steady 3 ms workload. Burning the same fixed budget in every mode puts the + governor at full clock before anything that counts is measured. + """ + x = np.arange(8192, dtype=np.int64) + t0 = time.process_time() + while (time.process_time() - t0) * 1000.0 < target_ms: + for _ in range(40): + x = (x * 1103515245 + 12345) % 2147483647 + return int(x[0]) + + +def do_timing(): + m = scope_module() + L = int(os.environ.get("WRO_LAYERS", "768")) + cb = int(os.environ.get("WRO_CHUNK", "16384")) + rs = int(os.environ.get("WRO_SLOTS", "192")) + la = int(os.environ.get("WRO_LOOKAHEAD", "2")) + bw = int(os.environ.get("WRO_BW", "24000")) + rng = np.random.default_rng(20260726) + lb = rng.integers(12, 96, size=L).astype(np.int64) * 65536 + lb[::17] = 0 + cu = rng.integers(120, 900, size=L).astype(np.int64) + cu[3::11] *= 4 + + _warm_cpu(float(os.environ.get("WRO_WARM_MS", "400"))) + m.run_pipeline(lb[:4], cb, rs, cb, la, bw, 7, cu[:4], 0) + r = m.run_pipeline(lb, cb, rs, cb, la, bw, 7, cu, 0) + best = None + for _ in range(3): + t0 = time.process_time() + r = m.run_pipeline(lb, cb, rs, cb, la, bw, 7, cu, 0) + dt = (time.process_time() - t0) * 1000.0 + best = dt if best is None else min(best, dt) + print("%s %s" % (TOKEN, json.dumps({ + "timing_ms": round(best, 4), "layers": L, "chunk": cb, "slots": rs, + "lookahead": la, "n_chunks": int(r["n_chunks"]), + "total_us": int(r["total_us"]), "stall_us": int(r["stall_us"]), + "bubbles": int(r["bubbles"]), "conflicts": int(r["conflicts"]), + "link_busy_us": int(r["link_busy_us"]), + "window_sum": int(np.asarray(r["window"], dtype=np.int64).sum()), + "reuse_sum": int(np.asarray(r["slot_reuse"], dtype=np.int64).sum()), + "start_sum": int(np.asarray(r["layer_start"], dtype=np.int64).sum())}))) + + +if __name__ == "__main__": + cmd = sys.argv[1] if len(sys.argv) > 1 else "correctness" + if cmd == "correctness": + do_correctness() + elif cmd == "timing": + do_timing() + else: + raise SystemExit("usage: workload.py {correctness|timing}")