hyttyh111222333 commited on
Commit
533174a
·
verified ·
1 Parent(s): 9e670e7

Upload FAI-Bench task files batch 54

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/kfc/jit-source-arch-cache-key/task/.dockerignore +24 -0
  2. tasks/kfc/jit-source-arch-cache-key/task/environment/Dockerfile +161 -0
  3. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/compute_reward.py +86 -0
  4. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/count_bench.py +92 -0
  5. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/kb_identity_harness.py +185 -0
  6. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/ref_speedup.txt +1 -0
  7. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test.sh +137 -0
  8. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test_identity_key.py +184 -0
  9. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/manifest.json +11 -0
  10. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/sanitize_feedback.py +131 -0
  11. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/score_engine.sh +41 -0
  12. tasks/kfc/jit-source-arch-cache-key/task/environment/loop/submit.sh +232 -0
  13. tasks/kfc/jit-source-arch-cache-key/task/environment/repo/identity_key.py +57 -0
  14. tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/entrypoint.sh +13 -0
  15. tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/run_dev_bench.sh +5 -0
  16. tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/timer.sh +7 -0
  17. tasks/kfc/jit-source-arch-cache-key/task/environment/verifier-correctness-manifest.json +32 -0
  18. tasks/kfc/jit-source-arch-cache-key/task/instruction.md +162 -0
  19. tasks/kfc/jit-source-arch-cache-key/task/pre_artifacts.sh +162 -0
  20. tasks/kfc/jit-source-arch-cache-key/task/solution/README.md +13 -0
  21. tasks/kfc/jit-source-arch-cache-key/task/solution/baseline2.patch +88 -0
  22. tasks/kfc/jit-source-arch-cache-key/task/solution/negative.patch +96 -0
  23. tasks/kfc/jit-source-arch-cache-key/task/solution/oracle.patch +97 -0
  24. tasks/kfc/jit-source-arch-cache-key/task/solution/solve.sh +159 -0
  25. tasks/kfc/jit-source-arch-cache-key/task/task.toml +81 -0
  26. tasks/kfc/jit-source-arch-cache-key/task/tests/compute_reward.py +144 -0
  27. tasks/kfc/jit-source-arch-cache-key/task/tests/count_bench.py +92 -0
  28. tasks/kfc/jit-source-arch-cache-key/task/tests/kb_identity_harness.py +185 -0
  29. tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.caveat.md +29 -0
  30. tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.txt +1 -0
  31. tasks/kfc/jit-source-arch-cache-key/task/tests/test.sh +137 -0
  32. tasks/kfc/jit-source-arch-cache-key/task/tests/test_identity_key.py +184 -0
  33. tasks/kfc/s4-fft-longconv/task/.dockerignore +24 -0
  34. tasks/kfc/s4-fft-longconv/task/environment/Dockerfile +153 -0
  35. tasks/kfc/s4-fft-longconv/task/environment/repo/.gitignore +2 -0
  36. tasks/kfc/s4-fft-longconv/task/environment/repo/gated_gelu.py +23 -0
  37. tasks/kfc/s4-fft-longconv/task/environment/repo/submission/kernel.py +39 -0
  38. tasks/kfc/s4-fft-longconv/task/environment/runtime/entrypoint.sh +13 -0
  39. tasks/kfc/s4-fft-longconv/task/environment/runtime/run_dev_bench.sh +4 -0
  40. tasks/kfc/s4-fft-longconv/task/environment/runtime/timer.sh +12 -0
  41. tasks/kfc/s4-fft-longconv/task/environment/verifier-correctness-manifest.json +1 -0
  42. tasks/kfc/s4-fft-longconv/task/instruction.md +84 -0
  43. tasks/kfc/s4-fft-longconv/task/pre_artifacts.sh +157 -0
  44. tasks/kfc/s4-fft-longconv/task/solution/README.md +13 -0
  45. tasks/kfc/s4-fft-longconv/task/solution/kernel_negative.py +19 -0
  46. tasks/kfc/s4-fft-longconv/task/solution/kernel_oracle.py +24 -0
  47. tasks/kfc/s4-fft-longconv/task/solution/solve.sh +146 -0
  48. tasks/kfc/s4-fft-longconv/task/task.toml +53 -0
  49. tasks/kfc/s4-fft-longconv/task/tests/compute_reward.py +60 -0
  50. tasks/kfc/s4-fft-longconv/task/tests/ref_speedup.caveat.md +29 -0
tasks/kfc/jit-source-arch-cache-key/task/.dockerignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does
2
+ # NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile .
3
+ # The reference implementation and every authoring artefact MUST NOT reach an image layer.
4
+ *.patch
5
+ oracle*
6
+ negative*
7
+ baseline2*
8
+ scope_card.json
9
+ degradation_manifest.json
10
+ task_meta.json
11
+ loop_map_entry.json
12
+ job.yaml
13
+ intermediates/
14
+ _retrofit*
15
+ sr_validate*
16
+ leak_audit/
17
+ self_check/
18
+ variants/
19
+ **/__pycache__/
20
+ **/*.pyc
21
+ *.bak
22
+ *.bak_*
23
+ *.pre_*
24
+ **/*.pre_*
tasks/kfc/jit-source-arch-cache-key/task/environment/Dockerfile ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # =============================================================================
3
+ # jit-source-arch-cache-key — OPEN-SOURCE, self-contained task image
4
+ #
5
+ # Task: make the declared scope faster while preserving its observable behaviour exactly.
6
+ # Editable scope (the ONLY files the scope gate allows to change):
7
+ ## - /app/repo/identity_key.py
8
+ #
9
+ # FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image.
10
+ # CPU ONLY — task.toml declares gpus = 0.
11
+ # Platform: linux/amd64 or arm64.
12
+ # Build context = this task directory (the Dockerfile lives in environment/).
13
+ #
14
+ # PROVENANCE of environment/repo/ (so anyone can re-derive it independently)
15
+ # recovered from: <internal registry>/kernelbench/insea-jit-source-arch-cache-key-loop16:loop-20260721T021500Z@sha256:b6e1405e15730a4d2605a010e43a832c62e79d533833700356bd01e7e77fea6d
16
+ # method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in
17
+ # manifest order; .git and any .wh..wh..opq marker dropped.
18
+ # verification: `git apply --check -p1 oracle.patch` succeeds against these bytes and `-R` does NOT — i.e. this tree is the exact baseline tree the reference patch was generated against.
19
+ ##
20
+ # -----------------------------------------------------------------------------
21
+ # BUILD (needs outbound network for PyPI only — the working tree ships in this package)
22
+ # cd <...>/jit-source-arch-cache-key/task
23
+ # docker build -f environment/Dockerfile -t fai/kfc-jit-source-arch-cache-key:oss .
24
+ #
25
+ # RUN docker run --rm -it fai/kfc-jit-source-arch-cache-key:oss
26
+ # SCORE docker run --rm -v "$PWD/tests:/tests:ro" fai/kfc-jit-source-arch-cache-key:oss bash /tests/test.sh
27
+ # # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative)
28
+ #
29
+ # 🔴 RE-CALIBRATE THE ANCHOR ON YOUR HARDWARE
30
+ # reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; ref_speedup = 4.0 .
31
+ # tests/test.sh resolves it from tests/ref_speedup.txt FIRST, then falls back to
32
+ # /opt/verifier-correctness-manifest.json, then to 1.0 (which would make every reward 0).
33
+ # The value was calibrated on the authoring CPU lane (Intel Sapphire Rapids). The verifier supports mode dispatch natively, so
34
+ # re-measuring is ONE command (the reference patch is passed BY PATH and never baked):
35
+ # docker run --rm -v "$PWD/tests:/tests:ro" -v "<dir holding oracle.patch>:/patches:ro" \
36
+ # -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \
37
+ # fai/kfc-jit-source-arch-cache-key:oss bash /tests/test.sh
38
+ # then write the measured speedup into tests/ref_speedup.txt. See tests/ref_speedup.caveat.md.
39
+ # Sanity: noop (no patch) ~= 1.0 -> gated to 0; negative MUST score 0.
40
+ #
41
+ # VERSION ANCHORS
42
+ # Python 3.11 · standard library
43
+ # The original private base declared torch 2.5.1 / triton 3.1.0 and the task overlay then ran
44
+ # `pip install torch==2.7.0` — 2.7.0 is therefore the version the anchor was calibrated under.
45
+ # =============================================================================
46
+ FROM python:3.11-slim-bookworm
47
+
48
+ ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \
49
+ PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1
50
+
51
+ RUN apt-get update && apt-get install -y --no-install-recommends \
52
+ build-essential git ca-certificates curl procps coreutils tar gzip vim less file jq \
53
+ && rm -rf /var/lib/apt/lists/*
54
+
55
+ # ---- venv at this EXACT path: tests/test.sh puts /opt/kernelbench-venv/bin at the head of PATH. ----
56
+ ENV VENV=/opt/kernelbench-venv
57
+ RUN python3 -m venv "$VENV"
58
+ ENV PATH=$VENV/bin:$PATH
59
+ RUN pip install --no-cache-dir -U pip setuptools wheel
60
+
61
+ # ---- the graded working tree. A REAL directory (not a symlink): the scope gate runs
62
+ # `git -C /app/repo status --porcelain`, which cannot see through a symlink. ----
63
+ RUN mkdir -p /app/repo /app/.timer /app/workspace /logs/verifier /logs/agent /logs/artifacts
64
+ COPY environment/repo/ /app/repo/
65
+ COPY instruction.md /app/instruction.md
66
+
67
+ # ---- the baseline commit = the diff base the scope gate compares against.
68
+ # 🔴 core.fileMode=false is LOAD-BEARING, not hygiene: a shipped image in this corpus had
69
+ # core.fileMode=true while some files were 0775 on disk but 100644 in the index, so
70
+ # `git status --porcelain` reported phantom out-of-scope paths in EVERY mode and forced
71
+ # reward to 0. Setting it false at creation makes that class of defect impossible. ----
72
+ RUN git config --global user.email "reviewer@fai-bench.local" \
73
+ && git config --global user.name "fai-bench" \
74
+ && git config --global init.defaultBranch main \
75
+ && git config --global --add safe.directory /app/repo \
76
+ && cd /app/repo \
77
+ && git init -q \
78
+ && git config core.fileMode false \
79
+ && printf '__pycache__/\n*.pyc\n' >> .gitignore \
80
+ && git add -A \
81
+ && git commit -qm "baseline (graded starting point)" \
82
+ && rm -rf .git/logs \
83
+ && test "$(git rev-list --count HEAD)" = "1" \
84
+ && test -z "$(git remote)" \
85
+ && test "$(git config --get core.fileMode)" = "false" \
86
+ && test -z "$(git status --porcelain)" \
87
+ && echo "[build] /app/repo: 1 commit, no remote, fileMode=false, clean tree"
88
+
89
+ # ---- runtime contract (copied verbatim from the shipped image) ----
90
+ COPY environment/runtime/entrypoint.sh /app/entrypoint.sh
91
+ COPY environment/runtime/timer.sh /app/timer.sh
92
+ RUN chmod 0755 /app/entrypoint.sh /app/timer.sh && chown root:root /app/entrypoint.sh /app/timer.sh
93
+ COPY environment/runtime/run_dev_bench.sh /app/workspace/run_dev_bench.sh
94
+ RUN chmod 0755 /app/workspace/run_dev_bench.sh
95
+ COPY environment/loop/ /opt/loop/
96
+ RUN if [ -f /opt/loop/submit.sh ]; then chmod 0755 /opt/loop/submit.sh; fi \
97
+ && chown -R root:root /opt/loop \
98
+ && if [ -f /opt/loop/score_engine.sh ]; then chmod 0700 /opt/loop/score_engine.sh; fi \
99
+ && if [ -f /opt/loop/sanitize_feedback.py ]; then chmod 0700 /opt/loop/sanitize_feedback.py; fi \
100
+ && if [ -d /opt/loop/private ]; then chmod -R go-rwx /opt/loop/private; fi
101
+
102
+ # ---- the FROZEN anchor fallback. tests/test.sh prefers tests/ref_speedup.txt (mounted) and falls
103
+ # back to THIS path; keeping both consistent makes the resolution explicit. Only the constant. ----
104
+ COPY environment/verifier-correctness-manifest.json /opt/verifier-correctness-manifest.json
105
+
106
+ # ---- OPEN grading suite is NOT baked: tests/ (test.sh + compute_reward.py + the workload/harness
107
+ # + ref_speedup.txt) is MOUNTED FRESH at /tests when scoring. It ships in this package —
108
+ # open-source, but outside the image so the graded harness cannot be edited from the session.
109
+
110
+ # ---- 🔴 ANTI-LEAK ASSERTS (author-side artifact denylist) ----
111
+ RUN set -eu; rc=0; \
112
+ hits="$(find / -xdev -type f \( -name 'oracle*.patch' -o -name 'negative*.patch' \
113
+ -o -name 'baseline2*.patch' -o -name 'scope_card.json' -o -name 'kernel_oracle.py' \
114
+ -o -name 'degradation_manifest.json' \) 2>/dev/null | head -10)"; \
115
+ if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: a reference/authoring file is baked:"; echo "$hits"; rc=1; fi; \
116
+ for p in /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling /tests; do \
117
+ if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path baked: $p"; rc=1; fi; \
118
+ done; \
119
+ test "$rc" = 0; \
120
+ echo "[build] ANTI-LEAK ASSERTS PASS"
121
+
122
+ ENV PYTHONPATH=/app/repo \
123
+ PYTHONDONTWRITEBYTECODE=1 \
124
+ OMP_NUM_THREADS=1 \
125
+ MKL_NUM_THREADS=1 \
126
+ OPENBLAS_NUM_THREADS=1
127
+ WORKDIR /app/repo
128
+
129
+ # ---- build-time smoke: the graded module imports FROM /app/repo (the verifier asserts the same
130
+ # thing at scoring time via its import-origin gate) and the scope files are present. ----
131
+ # ---- frozen naive baseline for the verifier's SPEED DENOMINATOR.
132
+ # tests/test.sh resolves KB_BASELINE_MODULE=/opt/verifier-baseline/<file>; when that file
133
+ # is absent the whole benchmark block is SKIPPED and the run hard-fails with
134
+ # `validation_incomplete` (reward 0) no matter how good the submission is.
135
+ # It is a pristine copy of the shipped, pre-edit scope file, taken here at build time —
136
+ # exactly what the original task image baked. `cmp` proves the copy is byte-identical.
137
+ RUN mkdir -p /opt/verifier-baseline \
138
+ && cp "/app/repo/identity_key.py" "/opt/verifier-baseline/identity_key.py" \
139
+ && cmp "/app/repo/identity_key.py" "/opt/verifier-baseline/identity_key.py" \
140
+ && chmod 0444 "/opt/verifier-baseline/identity_key.py" \
141
+ && echo "frozen baseline(s) baked: $(ls -l /opt/verifier-baseline | tail -n +2 | wc -l) file(s)"
142
+
143
+ RUN python - <<'PY'
144
+ import os, subprocess, sys
145
+ sys.path.insert(0, "/app/repo")
146
+ for f in ('/app/repo/identity_key.py',):
147
+ p = os.path.join("/app/repo", f)
148
+ assert os.path.isfile(p), f"scope file missing: {p}"
149
+ print("scope file present:", f, os.path.getsize(p), "B")
150
+ for _b in ('identity_key.py',):
151
+ _p = os.path.join('/opt/verifier-baseline', _b)
152
+ assert os.path.isfile(_p), f"frozen baseline missing: {_p} (tests/test.sh would skip the benchmark and hard-fail validation_incomplete)"
153
+ print('frozen baseline:', _p, os.path.getsize(_p), 'B')
154
+ n = subprocess.run(["git","-C","/app/repo","rev-list","--count","HEAD"],
155
+ capture_output=True, text=True).stdout.strip()
156
+ assert n == "1", f"git diff base broken (commits={n!r})"
157
+ print("OK: scope files, import origin and git base all in place")
158
+ PY
159
+
160
+ ENTRYPOINT ["/app/entrypoint.sh"]
161
+ CMD ["tail","-f","/dev/null"]
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/compute_reward.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Canonical kernelbench reward writer (reused verbatim from the ready-task
3
+ template kernel-opt-p0a4-003). Task-agnostic; do NOT special-case a task here.
4
+
5
+ Dual-mode:
6
+ - correctness task (verifier_state.task_kind == "correctness"):
7
+ reward = 1.0 iff all hard gates true and no hard_fail_reasons, else 0.0; no timing.
8
+ - acceleration task:
9
+ reward = speedup (raw measured speedup — no cap, no log, no ref anchor)
10
+ iff all gates pass and speedup is finite and > 0; else 0.0.
11
+
12
+ Reads: /logs/loop/dev/verifier_state.json, /logs/loop/dev/benchmark_results.json
13
+ Writes: /logs/loop/dev/reward.json, /logs/loop/dev/reward.txt
14
+ """
15
+ import json, math
16
+ from pathlib import Path
17
+
18
+ LOG = Path("/logs/loop/dev")
19
+ STATE = LOG / "verifier_state.json"
20
+ BENCH = LOG / "benchmark_results.json"
21
+ REWARD = LOG / "reward.json"
22
+ TEXT = LOG / "reward.txt"
23
+
24
+ GATES = [
25
+ "correctness_ok",
26
+ "trusted_restore_ok",
27
+ "hidden_correctness_ok",
28
+ "baseline_ok",
29
+ "benchmark_ok",
30
+ "anti_cheat_ok",
31
+ ]
32
+
33
+
34
+ def read_json(path, default):
35
+ try:
36
+ return json.loads(path.read_text(encoding="utf-8"))
37
+ except Exception:
38
+ return default
39
+
40
+
41
+ def main():
42
+ LOG.mkdir(parents=True, exist_ok=True)
43
+ state = read_json(STATE, {})
44
+ bench = read_json(BENCH, {})
45
+ hard = list(state.get("hard_fail_reasons") or [])
46
+ task_kind = state.get("task_kind") or bench.get("task_kind") or "acceleration"
47
+ gates_ok = all(bool(state.get(g)) for g in GATES)
48
+
49
+ speedup = ref = 1.0
50
+ reward = 0.0
51
+ if task_kind == "correctness":
52
+ reward = 1.0 if (gates_ok and not hard) else 0.0
53
+ if reward == 0.0 and not hard:
54
+ hard.append("correctness_or_validation_incomplete")
55
+ else:
56
+ try:
57
+ speedup = float(bench.get("aggregate_speedup") or bench.get("primary_metric_value") or 1.0)
58
+ ref = float(bench.get("ref_speedup") or bench.get("reference_metric_value") or 1.0)
59
+ except Exception:
60
+ speedup = ref = 1.0
61
+ hard.append("invalid_primary_metric_value")
62
+ # reward IS the raw measured speedup (no cap, no log, no ref anchor);
63
+ # ref_speedup is kept as calibration metadata only. reward is 0 only when a
64
+ # gate fails (correctness/anti-cheat) or the measured speedup is unusable.
65
+ if gates_ok and not hard and math.isfinite(speedup) and speedup > 0.0:
66
+ reward = speedup
67
+ if reward == 0.0 and not hard:
68
+ hard.append("validation_incomplete_or_bad_speedup")
69
+
70
+ out = {
71
+ "schema_version": "kernelbench_reward_v1",
72
+ "task_kind": task_kind,
73
+ "reward": reward,
74
+ "speedup": speedup,
75
+ "ref_speedup": ref,
76
+ "actual_hardware_type": state.get("actual_hardware_type", "") or bench.get("actual_hardware_type", ""),
77
+ "hard_fail_reasons": hard,
78
+ "state_path": str(STATE),
79
+ "benchmark_path": str(BENCH),
80
+ }
81
+ REWARD.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n", encoding="utf-8")
82
+ TEXT.write_text(f"{reward}\n", encoding="utf-8")
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main()
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/count_bench.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distinct-identity count for the build-spec identity task.
2
+
3
+ The metric is a deterministic count: over a fixed labeled workload of build-specs,
4
+ how many DISTINCT identities does a module's ``identity_key`` produce? A conservative
5
+ identity treats every incidental spelling as different and emits many identities; a
6
+ normalizing identity collapses the equivalent spellings of each class down toward the
7
+ number of true classes. The score is the ratio baseline_count / candidate_count, so
8
+ fewer identities (for the same workload) is better -- but only while no two
9
+ genuinely-different specs share an identity.
10
+
11
+ Invoked one MODE per process. ``test.sh`` runs candidate and the frozen baseline and
12
+ takes the ratio. No profiler / no numerics library -- it is a pure count.
13
+
14
+ Modes:
15
+ candidate count distinct identities from /app/repo/identity_key.py; print COUNT=<n>
16
+ baseline same, using the frozen baseline module (KB_BASELINE_MODULE)
17
+ verify (safety) confirm the candidate NEVER gives two different-class specs
18
+ the same identity; print VERIFY_OK / VERIFY_FAIL
19
+ """
20
+
21
+ import os
22
+ import sys
23
+
24
+ from kb_identity_harness import (
25
+ build_labeled_workload,
26
+ count_distinct_keys,
27
+ find_false_merges,
28
+ load_candidate,
29
+ load_module,
30
+ true_class_count,
31
+ )
32
+
33
+
34
+ def _baseline_module():
35
+ path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/identity_key.py")
36
+ return load_module(path)
37
+
38
+
39
+ def mode_candidate():
40
+ workload = build_labeled_workload()
41
+ print(f"COUNT={count_distinct_keys(load_candidate(), workload)}")
42
+ return 0
43
+
44
+
45
+ def mode_baseline():
46
+ workload = build_labeled_workload()
47
+ print(f"COUNT={count_distinct_keys(_baseline_module(), workload)}")
48
+ return 0
49
+
50
+
51
+ def mode_verify():
52
+ workload = build_labeled_workload()
53
+ classes = true_class_count(workload)
54
+ cand = load_candidate()
55
+ base = _baseline_module()
56
+
57
+ cand_bad = find_false_merges(cand, workload)
58
+ if cand_bad:
59
+ sample = sorted((sorted(v), k) for k, v in cand_bad.items())[:3]
60
+ print(f"VERIFY_FAIL candidate false-merges distinct classes: {sample}")
61
+ return 1
62
+ # sanity: the frozen baseline must itself be false-merge free.
63
+ base_bad = find_false_merges(base, workload)
64
+ if base_bad:
65
+ print(f"VERIFY_FAIL baseline unexpectedly false-merges: {sorted(base_bad.values())[:3]}")
66
+ return 1
67
+
68
+ cand_count = count_distinct_keys(cand, workload)
69
+ base_count = count_distinct_keys(base, workload)
70
+ # work-evidence: the baseline emits (base_count - classes) identities more than
71
+ # there are true classes; a full normalizer removes those redundant identities.
72
+ redundant = base_count - classes
73
+ print(f"VERIFY_OK signatures={len(workload)} true_classes={classes} "
74
+ f"candidate_identities={cand_count} baseline_identities={base_count} "
75
+ f"baseline_redundant_identities={redundant}")
76
+ return 0
77
+
78
+
79
+ MODES = {"candidate": mode_candidate, "baseline": mode_baseline, "verify": mode_verify}
80
+
81
+
82
+ def main():
83
+ mode = sys.argv[1] if len(sys.argv) > 1 else "candidate"
84
+ fn = MODES.get(mode)
85
+ if fn is None:
86
+ print(f"unknown mode {mode!r}; expected one of {sorted(MODES)}")
87
+ sys.exit(2)
88
+ sys.exit(fn())
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/kb_identity_harness.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared harness for the build-spec identity task (CPU, pure Python).
2
+
3
+ Provides: the candidate loader, the equivalence-rule tables (source normalization,
4
+ no-op option tokens), a deterministic *labeled* workload of build-specs grouped into
5
+ true equivalence classes, and helpers that turn a candidate ``identity_key`` into a
6
+ partition of that workload so the verifier can count distinct identities and detect a
7
+ false merge (two genuinely-different specs sharing an identity). Standard library
8
+ only, so the metric -- the number of distinct identities produced over the workload --
9
+ is a deterministic count that is identical on any machine.
10
+
11
+ The ground truth is the class LABEL attached to every spec when the workload is built:
12
+ two specs share a class iff they were generated as equivalent spellings of the same
13
+ base. candidate / baseline / oracle are all judged against these labels, never against
14
+ each other.
15
+ """
16
+
17
+ import hashlib
18
+ import importlib.util
19
+ import os
20
+ import re
21
+
22
+
23
+ # --------------------------------------------------------------------------- #
24
+ # Equivalence rules (also disclosed to the solver in instruction.md).
25
+ # --------------------------------------------------------------------------- #
26
+ # Source text: comments and surrounding whitespace do not change the built artifact,
27
+ # so they are incidental. Everything else in the source text is meaningful.
28
+ _BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
29
+ _LINE_COMMENT = re.compile(r"//[^\n]*")
30
+
31
+ # Option tokens equal to a build default; each is equivalent to the token being absent.
32
+ NOOP_OPTIONS = {"o0", "dbgoff", "std0"}
33
+
34
+
35
+ def canon_source(text):
36
+ """Canonical form of a source text: strip comments, collapse whitespace runs."""
37
+ text = _BLOCK_COMMENT.sub(" ", text)
38
+ text = _LINE_COMMENT.sub(" ", text)
39
+ return " ".join(text.split())
40
+
41
+
42
+ def canon_options(options):
43
+ """Canonical option set: drop no-op defaults, de-duplicate, sort (order-free)."""
44
+ kept = {o for o in (options or []) if o not in NOOP_OPTIONS}
45
+ return sorted(kept)
46
+
47
+
48
+ def _with_line_comment(source):
49
+ return source + " // tuned build\n"
50
+
51
+
52
+ def _with_block_comment(source):
53
+ return "/* rev2 */\n" + source + "\n\n "
54
+
55
+
56
+ def repo_dir():
57
+ return os.environ.get("KB_REPO_DIR", "/app/repo")
58
+
59
+
60
+ def load_candidate():
61
+ """Import the candidate module from the repo under test."""
62
+ path = os.path.join(repo_dir(), "identity_key.py")
63
+ spec = importlib.util.spec_from_file_location("candidate_identity_key", path)
64
+ mod = importlib.util.module_from_spec(spec)
65
+ spec.loader.exec_module(mod)
66
+ if not hasattr(mod, "identity_key"):
67
+ raise AttributeError(f"{path} does not define identity_key")
68
+ return mod
69
+
70
+
71
+ def load_module(path):
72
+ # deterministic module name derived from the path (no salted builtin hash()).
73
+ digest = hashlib.sha1(path.encode("utf-8")).hexdigest()[:12]
74
+ spec = importlib.util.spec_from_file_location("kb_identity_mod_" + digest, path)
75
+ mod = importlib.util.module_from_spec(spec)
76
+ spec.loader.exec_module(mod)
77
+ return mod
78
+
79
+
80
+ # --------------------------------------------------------------------------- #
81
+ # Labeled workload: 12 true classes, each emitted as 4 equivalent spellings.
82
+ # Distinct classes differ in at least one meaning-bearing field (source text /
83
+ # target profile / effective option / toolchain tag / requested variant set).
84
+ # classes 0 and 1 differ ONLY in target profile -- a normalizer that drops the target
85
+ # merges them, which is a false merge (a wrong-target artifact would be reused).
86
+ # --------------------------------------------------------------------------- #
87
+ SRC_A = "o[i] = a[i] * b[i];"
88
+ SRC_B = "o[i] = a[i] + b[i];"
89
+ SRC_C = "o[i] = a[i] - b[i];"
90
+ SRC_D = "acc = acc + a[k] * b[k];"
91
+ SRC_E = "o[i] = a[i] > 0 ? a[i] : 0;"
92
+ SRC_F = "o[i] = a[i] / b[i];"
93
+
94
+ # base = (source, target, effective_options, toolchain, variants)
95
+ CLASS_BASES = [
96
+ (SRC_A, "p80", (), "v1", ()), # 0 (target-trap A)
97
+ (SRC_A, "p90", (), "v1", ()), # 1 (target-trap B: only target differs from 0)
98
+ (SRC_B, "p80", (), "v1", ()), # 2 distinct source
99
+ (SRC_C, "p80", (), "v1", ()), # 3
100
+ (SRC_C, "p80", ("fast",), "v1", ()), # 4 effective option vs 3
101
+ (SRC_D, "p80", ("o3",), "v1", ()), # 5
102
+ (SRC_D, "p80", ("o2",), "v1", ()), # 6 different effective option value vs 5
103
+ (SRC_D, "p80", ("o3",), "v2", ()), # 7 different toolchain tag vs 5
104
+ (SRC_E, "p80", (), "v1", ()), # 8
105
+ (SRC_E, "p80", (), "v1", ("kA",)), # 9 variant present vs 8
106
+ (SRC_E, "p80", (), "v1", ("kB", "kC")), # 10 different variant set vs 9
107
+ (SRC_F, "p86", ("fast", "o3"), "v1", ()), # 11 third target + two options
108
+ ]
109
+
110
+
111
+ def _spellings(base):
112
+ """Return four equivalent-but-differently-spelled specs for one class.
113
+
114
+ All four normalize to the same spec (they differ only in source comments/whitespace,
115
+ option order, redundant no-op options, incidental build annotations, and requested
116
+ variant order), yet all four are byte-distinct so a conservative identity produces
117
+ four identities.
118
+ """
119
+ source, target, options, toolchain, variants = base
120
+ opts = list(options)
121
+ vs = list(variants)
122
+
123
+ def build_spec(src, opt_list, build=None, var_list=None):
124
+ d = {"source": src, "target": target, "options": list(opt_list), "toolchain": toolchain}
125
+ if var_list:
126
+ d["variants"] = list(var_list)
127
+ if build is not None:
128
+ d["build"] = build
129
+ return d
130
+
131
+ # S0: canonical source, options sorted, variants sorted, no build annotations.
132
+ s0 = build_spec(source, sorted(opts), var_list=sorted(vs))
133
+ # S1: source carries a trailing line comment + reflowed spacing (ignored).
134
+ s1 = build_spec(_with_line_comment(source), sorted(opts), var_list=sorted(vs))
135
+ # S2: options in a different ORDER + a redundant no-op token; a non-semantic build
136
+ # annotation block; requested variants in a different order.
137
+ s2 = build_spec(source, list(reversed(opts)) + ["o0"],
138
+ build={"tmpdir": "/tmp/b_" + target, "ts": 1700000000},
139
+ var_list=list(reversed(vs)))
140
+ # S3: source with a block comment + extra newlines; options reversed with a DUPLICATE
141
+ # of the first option (when present) + a different no-op token; a different build.
142
+ dup = [opts[0]] if opts else []
143
+ s3 = build_spec(_with_block_comment(source), list(reversed(opts)) + dup + ["dbgoff"],
144
+ build={"tmpdir": "/tmp/x", "ts": 1700000001, "host": "node7"},
145
+ var_list=list(reversed(vs)))
146
+ return [s0, s1, s2, s3]
147
+
148
+
149
+ def build_labeled_workload():
150
+ """Deterministic list of ``(class_id, spec)`` pairs (48 = 12 classes x 4)."""
151
+ workload = []
152
+ for class_id, base in enumerate(CLASS_BASES):
153
+ for spec in _spellings(base):
154
+ workload.append((class_id, spec))
155
+ return workload
156
+
157
+
158
+ def true_class_count(workload):
159
+ return len({class_id for class_id, _ in workload})
160
+
161
+
162
+ # --------------------------------------------------------------------------- #
163
+ # Turn a candidate identity function into a partition of the workload.
164
+ # --------------------------------------------------------------------------- #
165
+ def key_to_classes(module, workload):
166
+ """Map each produced identity -> the set of true class ids that landed on it."""
167
+ mapping = {}
168
+ for class_id, spec in workload:
169
+ key = module.identity_key(spec)
170
+ mapping.setdefault(key, set()).add(class_id)
171
+ return mapping
172
+
173
+
174
+ def find_false_merges(module, workload):
175
+ """Return {identity: {class_ids}} for identities shared by >1 true class.
176
+
177
+ A non-empty result is a correctness failure: two genuinely different specs were
178
+ given the same identity.
179
+ """
180
+ return {k: v for k, v in key_to_classes(module, workload).items() if len(v) > 1}
181
+
182
+
183
+ def count_distinct_keys(module, workload):
184
+ """Number of distinct identities the candidate produces over the workload."""
185
+ return len({module.identity_key(spec) for _, spec in workload})
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/ref_speedup.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 4.0
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test.sh ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Verifier for jit-source-arch-cache-key (stable identity for a build-spec).
3
+ # Pattern A, ACCELERATION lane. Deterministic value axis = recompile_count = number of
4
+ # DISTINCT identities produced over a fixed labeled workload of build-specs. speedup =
5
+ # baseline_recompiles / candidate_recompiles (= baseline_distinct_identities /
6
+ # candidate_distinct_identities). Pure-Python stdlib -> a plain count, no profiler
7
+ # needed. A false merge (two different-class specs sharing an identity -- e.g. two specs
8
+ # differing only in target profile) is a hard correctness failure -> reward 0.
9
+ # Modes: candidate|noop|oracle|negative
10
+ set -uo pipefail
11
+ # The harness may exec this in a NON-login shell; pin PATH so python3
12
+ # resolves regardless of the base's default profile.
13
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/bin:$PATH
14
+ TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
15
+ REPO=/app/repo
16
+ LOG=/logs/loop/dev
17
+ mkdir -p "$LOG"
18
+ MODE="${KERNELBENCH_VERIFY_MODE:-candidate}"
19
+ CAND_FILE="$REPO/identity_key.py"
20
+ export KB_CANDIDATE_MODULE="$CAND_FILE"
21
+ export KB_BASELINE_MODULE=/opt/verifier-baseline/identity_key.py
22
+
23
+ HARD=(); add_hard(){ HARD+=("$1"); }
24
+ correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true
25
+ baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true
26
+ expected_cases=12; actual_cases=0
27
+ speedup=1.0; ref_speedup=1.0; hw="cpu"; cand_keys=0; base_keys=0
28
+
29
+ cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; }
30
+
31
+ if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then
32
+ # reviewer-only mode: reset the working tree to the frozen baseline so several
33
+ # modes running back-to-back in one container session each start clean. candidate/noop
34
+ # NEVER resets (this branch is skipped for them), so a solver session is untouched.
35
+ git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
36
+ git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"
37
+ fi
38
+ if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then
39
+ git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
40
+ git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true
41
+ fi
42
+
43
+ # anti-cheat: only identity_key.py may change
44
+ git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt"
45
+ while IFS= read -r f; do
46
+ [ -z "$f" ] && continue
47
+ case "$f" in
48
+ identity_key.py) : ;;
49
+ *__pycache__*) : ;;
50
+ *) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;;
51
+ esac
52
+ done < "$LOG/anti_cheat_changed_files.txt"
53
+
54
+ # anti-cheat: the normalization must be implemented in plain Python. Forbid pulling
55
+ # in a tensor/graph framework or reading the hidden workload/reference harness.
56
+ 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
57
+ anti_cheat_ok=false; add_hard "forbidden_framework_or_harness_reference"
58
+ fi
59
+
60
+ # trusted restore: hidden suite ships in tests/ payload (fresh at scoring)
61
+ for f in test_identity_key.py count_bench.py kb_identity_harness.py; do
62
+ [ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; }
63
+ done
64
+
65
+ # ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild)
66
+ if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then
67
+ ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt")
68
+ elif [ -f /opt/verifier-correctness-manifest.json ]; then
69
+ 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)
70
+ fi
71
+ hw="cpu:$(uname -m 2>/dev/null || echo unknown)"
72
+
73
+ # correctness gate (pure python; no GPU): stable string + no false merge properties.
74
+ if [ "$correctness_ok" = true ]; then
75
+ ( cd "$TESTS_DIR" && python3 test_identity_key.py ) > "$LOG/correctness.log" 2>&1
76
+ crc=$?
77
+ actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0}
78
+ if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then
79
+ hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed"
80
+ fi
81
+ fi
82
+
83
+ # benchmark: (1) confirm the candidate never gives two different-class signatures the
84
+ # same identity (safety), then (2) count distinct identities for candidate vs the
85
+ # frozen baseline over the fixed workload; speedup = base_keys / cand_keys.
86
+ parse_count(){ sed -n 's/^COUNT=//p' "$1" 2>/dev/null | head -1; }
87
+ if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then
88
+ ( cd "$TESTS_DIR" && python3 count_bench.py verify ) > "$LOG/verify.log" 2>&1
89
+ if [ $? -ne 0 ] || ! grep -q '^VERIFY_OK' "$LOG/verify.log"; then
90
+ benchmark_ok=false; add_hard "candidate_false_merge"
91
+ fi
92
+ if [ "$benchmark_ok" = true ]; then
93
+ ( cd "$TESTS_DIR" && python3 count_bench.py candidate ) > "$LOG/cand.out.log" 2>&1
94
+ ( cd "$TESTS_DIR" && python3 count_bench.py baseline ) > "$LOG/base.out.log" 2>&1
95
+ cand_keys=$(parse_count "$LOG/cand.out.log"); cand_keys=${cand_keys:-0}
96
+ base_keys=$(parse_count "$LOG/base.out.log"); base_keys=${base_keys:-0}
97
+ if [ -z "$cand_keys" ] || [ "$cand_keys" -le 0 ] 2>/dev/null || [ -z "$base_keys" ] || [ "$base_keys" -le 0 ] 2>/dev/null; then
98
+ benchmark_ok=false; add_hard "distinct_identity_count_unparsed"
99
+ else
100
+ speedup=$(python3 -c "print(f'{$base_keys/$cand_keys:.5f}')")
101
+ fi
102
+ fi
103
+ else
104
+ benchmark_ok=false
105
+ fi
106
+
107
+ HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi
108
+ DIAG_TAIL=""
109
+ if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then
110
+ DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g')
111
+ fi
112
+ cat > "$LOG/verifier_state.json" <<JSON
113
+ {"schema_version":"kernelbench_verifier_state_v1","task_kind":"acceleration",
114
+ "correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,
115
+ "hidden_correctness_ok":$hidden_correctness_ok,"baseline_ok":$baseline_ok,
116
+ "benchmark_ok":$benchmark_ok,"anti_cheat_ok":$anti_cheat_ok,
117
+ "hard_fail_reasons":$HARD_JSON,
118
+ "expected_case_count":$expected_cases,"actual_case_count":$actual_cases,
119
+ "expected_benchmark_count":1,"actual_benchmark_count":1,
120
+ "actual_hardware_type":"$hw","mode":"$MODE",
121
+ "work_evidence_notes":["identity suite $actual_cases/$expected_cases ok","distinct identities candidate=$cand_keys baseline=$base_keys speedup=$speedup","correctness_tail:${DIAG_TAIL}"]}
122
+ JSON
123
+ cat > "$LOG/correctness_results.json" <<JSON
124
+ {"schema_version":"kernelbench_correctness_results_v1",
125
+ "suites":[{"name":"hidden-identity-suite","visibility_class":"hidden_supplement","expected_case_count":$expected_cases,"actual_case_count":$actual_cases,"passed":$actual_cases,"failed":$((expected_cases-actual_cases)),"hard_fail_reasons":$HARD_JSON}],
126
+ "correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,"hidden_correctness_ok":$hidden_correctness_ok}
127
+ JSON
128
+ cat > "$LOG/benchmark_results.json" <<JSON
129
+ {"schema_version":"kernelbench_benchmark_results_v1","task_kind":"acceleration","metric":"recompile_count",
130
+ "direction":"higher_is_better",
131
+ "workloads":[{"name":"buildspec-identity-count","speedup":$speedup,"candidate_recompiles":$cand_keys,"baseline_recompiles":$base_keys,"completion_counters":{"cases":"$actual_cases/$expected_cases"}}],
132
+ "aggregate_speedup":$speedup,"ref_speedup":$ref_speedup,"actual_hardware_type":"$hw"}
133
+ JSON
134
+ python3 "$TESTS_DIR/compute_reward.py" 2>/dev/null || python3 /tests/compute_reward.py 2>/dev/null || true
135
+ REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null)
136
+ 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"
137
+ [ -n "$REW" ] && exit 0 || exit 1
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/dev_tests/test_identity_key.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Correctness suite for the build-spec identity contract.
2
+
3
+ Each case prints "CASE_PASS <name>" or "CASE_FAIL <name>: <reason>". The runner counts
4
+ CASE_PASS lines. Pure standard library.
5
+
6
+ Every case tests a *safety* / determinism property that any acceptable identity must
7
+ satisfy: it returns a stable string, and it NEVER gives two genuinely-different specs
8
+ the same identity. (Collapsing equivalent spellings is rewarded by the distinct-identity
9
+ count, not gated here -- the conservative baseline, which collapses nothing, is still
10
+ correct.)
11
+ """
12
+
13
+ import sys
14
+ import traceback
15
+
16
+ from kb_identity_harness import (
17
+ build_labeled_workload,
18
+ find_false_merges,
19
+ load_candidate,
20
+ )
21
+
22
+ CASES = []
23
+
24
+
25
+ def case(fn):
26
+ CASES.append(fn)
27
+ return fn
28
+
29
+
30
+ def spec(source, target, options=None, toolchain="v1", variants=None, build=None):
31
+ d = {"source": source, "target": target, "toolchain": toolchain}
32
+ if options is not None:
33
+ d["options"] = list(options)
34
+ if variants is not None:
35
+ d["variants"] = list(variants)
36
+ if build is not None:
37
+ d["build"] = dict(build)
38
+ return d
39
+
40
+
41
+ def _key(mod, s):
42
+ k = mod.identity_key(s)
43
+ if not isinstance(k, str) or not k:
44
+ raise AssertionError(f"identity_key must return a non-empty str, got {k!r}")
45
+ return k
46
+
47
+
48
+ @case
49
+ def returns_string_for_various(mod):
50
+ samples = [
51
+ spec("o[i]=a[i]*b[i];", "p80"),
52
+ spec("o[i]=a[i]+b[i];", "p90", options=["fast"], variants=["kA"]),
53
+ spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2", build={"tmpdir": "/tmp/x"}),
54
+ {"source": "x=y;", "target": "p80"}, # minimal spec (no options/toolchain/variants/build)
55
+ ]
56
+ for s in samples:
57
+ _key(mod, s)
58
+
59
+
60
+ @case
61
+ def deterministic_repeat_same_object(mod):
62
+ s = spec("o[i]=a[i]*b[i];", "p80", options=["o3"])
63
+ if _key(mod, s) != _key(mod, s):
64
+ raise AssertionError("identity not stable across repeated calls on the same object")
65
+
66
+
67
+ @case
68
+ def deterministic_fresh_build(mod):
69
+ a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"])
70
+ b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"])
71
+ if _key(mod, a) != _key(mod, b):
72
+ raise AssertionError("two independently built identical specs got different identities")
73
+
74
+
75
+ @case
76
+ def distinct_source_distinct_keys(mod):
77
+ a = spec("o[i]=a[i]*b[i];", "p80")
78
+ b = spec("o[i]=a[i]+b[i];", "p80")
79
+ if _key(mod, a) == _key(mod, b):
80
+ raise AssertionError("different source text collided")
81
+
82
+
83
+ @case
84
+ def distinct_target_distinct_keys(mod):
85
+ # same source + options + toolchain, different target profile -> a different artifact.
86
+ a = spec("o[i]=a[i]*b[i];", "p80", options=["o3"])
87
+ b = spec("o[i]=a[i]*b[i];", "p90", options=["o3"])
88
+ if _key(mod, a) == _key(mod, b):
89
+ raise AssertionError("specs for different target profiles collided (target dropped?)")
90
+
91
+
92
+ @case
93
+ def distinct_effective_option_distinct_keys(mod):
94
+ a = spec("o[i]=a[i]*b[i];", "p80", options=["fast"])
95
+ b = spec("o[i]=a[i]*b[i];", "p80", options=[])
96
+ if _key(mod, a) == _key(mod, b):
97
+ raise AssertionError("an effective (non-default) option was ignored")
98
+
99
+
100
+ @case
101
+ def distinct_option_value_distinct_keys(mod):
102
+ a = spec("acc+=a[k]*b[k];", "p80", options=["o3"])
103
+ b = spec("acc+=a[k]*b[k];", "p80", options=["o2"])
104
+ if _key(mod, a) == _key(mod, b):
105
+ raise AssertionError("two different option values were merged")
106
+
107
+
108
+ @case
109
+ def distinct_toolchain_distinct_keys(mod):
110
+ a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v1")
111
+ b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2")
112
+ if _key(mod, a) == _key(mod, b):
113
+ raise AssertionError("different toolchain tags were merged (a stale artifact would be reused)")
114
+
115
+
116
+ @case
117
+ def distinct_variant_set_distinct_keys(mod):
118
+ a = spec("o[i]=a[i]>0?a[i]:0;", "p80") # no variants
119
+ b = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]) # one variant
120
+ c = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kB", "kC"]) # a different variant set
121
+ keys = {_key(mod, a), _key(mod, b), _key(mod, c)}
122
+ if len(keys) != 3:
123
+ raise AssertionError("the requested variant set was ignored")
124
+
125
+
126
+ @case
127
+ def no_false_merge_full_workload(mod):
128
+ workload = build_labeled_workload()
129
+ bad = find_false_merges(mod, workload)
130
+ if bad:
131
+ sample = sorted((sorted(v), k) for k, v in bad.items())[:3]
132
+ raise AssertionError(f"identity shared by >1 true class (false merge): {sample}")
133
+
134
+
135
+ @case
136
+ def handles_edge_schema(mod):
137
+ empty_opts = spec("x=y;", "p80", options=[]) # explicit empty option set
138
+ no_opts = {"source": "x=y;", "target": "p80"} # no options/toolchain/variants keys
139
+ with_build = spec("x=y;", "p80", build={"ts": 1}) # only an incidental build annotation
140
+ for s in (empty_opts, no_opts, with_build):
141
+ _key(mod, s)
142
+ # even at the degenerate schema, two specs for different targets must stay distinct.
143
+ other_target = {"source": "x=y;", "target": "p90"}
144
+ if _key(mod, no_opts) == _key(mod, other_target):
145
+ raise AssertionError("degenerate specs for different targets collided")
146
+
147
+
148
+ @case
149
+ def many_distinct_specs_pairwise_distinct(mod):
150
+ specs = [
151
+ spec("o[i]=a[i]*b[i];", "p80"),
152
+ spec("o[i]=a[i]+b[i];", "p80"),
153
+ spec("o[i]=a[i]*b[i];", "p90"), # target differs from #0
154
+ spec("acc+=a[k]*b[k];", "p80", options=["o3"]),
155
+ spec("acc+=a[k]*b[k];", "p80", options=["o2"]), # option value differs
156
+ spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2"), # toolchain differs
157
+ spec("o[i]=a[i]/b[i];", "p86", options=["fast", "o3"]),
158
+ spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]),
159
+ ]
160
+ keys = [_key(mod, s) for s in specs]
161
+ if len(set(keys)) != len(specs):
162
+ raise AssertionError(f"expected {len(specs)} distinct identities, got {len(set(keys))}")
163
+
164
+
165
+ def main():
166
+ mod = load_candidate()
167
+ passed = 0
168
+ for fn_case in CASES:
169
+ name = fn_case.__name__
170
+ try:
171
+ fn_case(mod)
172
+ passed += 1
173
+ print(f"CASE_PASS {name}")
174
+ except Exception as exc: # noqa: BLE001
175
+ reason = f"{type(exc).__name__}: {exc}"
176
+ print(f"CASE_FAIL {name}: {reason.splitlines()[0][:300]}")
177
+ traceback.print_exc(file=sys.stderr)
178
+ total = len(CASES)
179
+ print(f"CASES_PASSED={passed}/{total}")
180
+ sys.exit(0 if passed == total else 1)
181
+
182
+
183
+ if __name__ == "__main__":
184
+ main()
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/private/manifest.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_task_id": "jit-source-arch-cache-key",
3
+ "dev_engine": "private/dev_tests/test.sh (= the task verifier VERBATIM, output redirected to /logs/loop/dev, candidate mode)",
4
+ "max_submissions": 1,
5
+ "min_submissions": 1,
6
+ "note": "root-only (0700). ref_speedup is a protected secret; the sanitizer never emits it.",
7
+ "ref_speedup": 4.0,
8
+ "reward_formula": "acceleration: reward = speedup (raw measured ratio, uncapped; 0 if a gate fails). Matches the base compute_reward.py verbatim.",
9
+ "schema_version": "kernelbench_loop_manifest_v1",
10
+ "task_id": "jit-source-arch-cache-key"
11
+ }
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/sanitize_feedback.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sanitized feedback emitter (0700 root-owned) for jit-source-arch-cache-key.
3
+
4
+ Invoked ONLY by /opt/loop/submit.sh. Reads the DEV engine products under
5
+ /logs/loop/dev/ and the loop accounting under /logs/loop/, and prints ONLY a
6
+ leak-free summary.
7
+
8
+ Emits (nothing else, ever):
9
+ submission k/16
10
+ correctness: PASS | FAIL
11
+ [FAIL only] failing_invariant: <name from a fixed allow-list>
12
+ [FAIL only] diagnostic: <short, actionable, leak-free>
13
+ dev_speedup: <x> (relative performance ratio vs the reference baseline; higher is better)
14
+ dev_reward: <r> (= dev_speedup when correct, else 0; an in-session PROXY)
15
+ best_so_far: submission <j>, dev_speedup <x>, dev_reward <r>
16
+ remaining: <16 - k>
17
+ finalize_allowed: <true|false>
18
+ [harness path] harness_error: <message> (candidate not at fault; budget not consumed)
19
+
20
+ NEVER emits: verifier / test.sh / compute_reward contents; hidden workload
21
+ names / seeds / counts / shapes; any threshold; ref_speedup; absolute timings or
22
+ byte counts; actual_hardware_type.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ LOOP = Path("/logs/loop")
31
+ DEV = LOOP / "dev"
32
+ MIN_SUBMISSIONS = 3
33
+ MAX_SUBMISSIONS = 16
34
+
35
+ SIGNATURE = 'identity_key(spec: dict) -> str returning a stable identity string for a build-spec; do NOT change the public signature'
36
+ 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)'
37
+
38
+
39
+ def _read_json(path: Path, default):
40
+ try:
41
+ return json.loads(path.read_text(encoding="utf-8"))
42
+ except Exception:
43
+ return default
44
+
45
+
46
+ def _fmt(x, nd=4):
47
+ try:
48
+ return f"{float(x):.{nd}g}"
49
+ except Exception:
50
+ return str(x)
51
+
52
+
53
+ def _named_invariant(state: dict):
54
+ hard = [str(r) for r in (state.get("hard_fail_reasons") or [])]
55
+
56
+ def has(*subs):
57
+ return any(any(s in h for s in subs) for h in hard)
58
+
59
+ if has("forbidden_edit_path", "forbidden_source"):
60
+ return ("edit_scope",
61
+ "only the single product file may change and it must not reference any "
62
+ "scoring / verifier path — keep your edits to the product implementation only")
63
+ if has("_primitive", "_operator"):
64
+ return ("allowed_ops", PRIMITIVE_HINT)
65
+ if has("product_file_missing", "candidate_load_failed", "repo_missing"):
66
+ return ("product_present_and_importable",
67
+ f"the product could not be found or imported — keep the public {SIGNATURE} intact")
68
+ if has("hidden_correctness_failed"):
69
+ return ("output_matches_reference",
70
+ "your output disagreed with the reference on at least one case (numeric tolerance, "
71
+ "dtype / shape / device, an error-contract probe that must raise, or a metamorphic "
72
+ f"invariant) — verify the contract of {SIGNATURE}")
73
+ if has("benchmark_execution_failed"):
74
+ return ("runs_without_error",
75
+ "the measurement could not complete — your implementation likely raised, produced "
76
+ "non-finite values, or disagreed with the baseline while being measured")
77
+ return ("verifier_completed",
78
+ "the check did not complete cleanly — re-check that your last change did not cause an early crash")
79
+
80
+
81
+ def main() -> int:
82
+ try:
83
+ k = int((LOOP / "count").read_text(encoding="utf-8").strip())
84
+ except Exception:
85
+ k = 0
86
+
87
+ he = DEV / "harness_error.txt"
88
+ if he.exists():
89
+ try:
90
+ msg = he.read_text(encoding="utf-8").strip().splitlines()[0]
91
+ except Exception:
92
+ msg = "dev engine infrastructure error"
93
+ print(f"submission {k}/{MAX_SUBMISSIONS}")
94
+ print(f"harness_error: {msg} — this is NOT a defect in your code; do not debug the "
95
+ f"harness. Retry or continue optimizing (this attempt was not counted).")
96
+ return 0
97
+
98
+ state = _read_json(DEV / "verifier_state.json", {})
99
+ bench = _read_json(DEV / "benchmark_results.json", {})
100
+ reward = _read_json(DEV / "reward.json", {})
101
+
102
+ corr_ok = bool(state.get("correctness_ok"))
103
+ speedup = bench.get("aggregate_speedup", None)
104
+ r = reward.get("reward", 0.0)
105
+
106
+ print(f"submission {k}/{MAX_SUBMISSIONS}")
107
+ if corr_ok:
108
+ print("correctness: PASS")
109
+ else:
110
+ print("correctness: FAIL")
111
+ inv, hint = _named_invariant(state)
112
+ print(f"failing_invariant: {inv}")
113
+ print(f"diagnostic: {hint}")
114
+
115
+ print(f"dev_speedup: {_fmt(speedup) if speedup is not None else 'n/a'}")
116
+ print(f"dev_reward: {_fmt(r)}")
117
+
118
+ best = _read_json(LOOP / "best.json", None)
119
+ if best and isinstance(best, dict) and best.get("submission"):
120
+ print(f"best_so_far: submission {best.get('submission')}, "
121
+ f"dev_speedup {_fmt(best.get('speedup'))}, dev_reward {_fmt(best.get('reward'))}")
122
+ else:
123
+ print("best_so_far: (none — no correctness-passing submission yet)")
124
+
125
+ print(f"remaining: {max(0, MAX_SUBMISSIONS - k)}")
126
+ print(f"finalize_allowed: {'true' if k >= MIN_SUBMISSIONS else 'false'}")
127
+ return 0
128
+
129
+
130
+ if __name__ == "__main__":
131
+ sys.exit(main())
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/score_engine.sh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # DEV scoring engine (0700 root:root) for jit-source-arch-cache-key. Invoked ONLY by
3
+ # /opt/loop/submit.sh — never by the solver.
4
+ #
5
+ # It reuses the task verifier VERBATIM: it runs the baked copy of the base
6
+ # task's tests/test.sh (byte-identical except its output dir is /logs/loop/dev
7
+ # instead of /logs/verifier) against the LIVE /app/repo in the default candidate
8
+ # mode (which scores /app/repo AS-IS and never clobbers it). The base
9
+ # compute_reward.py writes reward = speedup (uncapped). The authoritative reward
10
+ # still comes from the runner's end-of-session /tests/ run, NOT from here.
11
+ #
12
+ # PATH-pin: the agent shell + runner verifier exec are
13
+ # NON-login; bare python3 has no torch. Pin the venv FIRST.
14
+ export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
15
+ set -uo pipefail
16
+
17
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
18
+ DEV_OUT="${LOOP_DEV_OUT:-/logs/loop/dev}"
19
+ mkdir -p "$DEV_OUT"
20
+ # fresh run: clear any stale harness marker
21
+ rm -f "$DEV_OUT/harness_error.txt" 2>/dev/null || true
22
+
23
+ # Run the baked task verifier (candidate mode). Suppress its stdout entirely
24
+ # (the base test.sh echoes a summary line carrying ref_speedup / hardware / raw
25
+ # speedup — that MUST NOT reach the solver; only sanitize_feedback.py emits).
26
+ KERNELBENCH_VERIFY_MODE=candidate bash "$HERE/private/dev_tests/test.sh" \
27
+ > "$DEV_OUT/dev_engine_stdout.log" 2>&1
28
+ rc=$?
29
+
30
+ # If the base verifier could not even write a reward (infra/torch/cuda failure),
31
+ # it exits non-zero WITHOUT a reward.json. Synthesize a harness marker so
32
+ # submit.sh treats it as infra (does not consume the solver's budget) rather than
33
+ # a silent candidate FAIL.
34
+ if [ "$rc" -ne 0 ] && [ ! -f "$DEV_OUT/reward.json" ] && [ ! -f "$DEV_OUT/harness_error.txt" ]; then
35
+ {
36
+ echo "dev_engine_exit_${rc}"
37
+ tail -n 40 "$DEV_OUT/dev_engine_stdout.log" 2>/dev/null
38
+ } > "$DEV_OUT/harness_error.txt"
39
+ exit 3
40
+ fi
41
+ exit 0
tasks/kfc/jit-source-arch-cache-key/task/environment/loop/submit.sh ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Per-task 3-to-16-submission loop harness for
3
+ # jit-source-arch-cache-key.
4
+ #
5
+ # The solver's ONLY sanctioned interface to scoring during the session
6
+ # (0755 root:root; the engine + private assets it calls are 0700 root-owned).
7
+ # Baked at /opt/loop/submit.sh so it is present from the first turn — unlike
8
+ # /tests/, which the runner creates only AFTER the agent finishes.
9
+ #
10
+ # Usage:
11
+ # bash /opt/loop/submit.sh # score current /app/repo, get feedback
12
+ # bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best iterate, end loop
13
+ #
14
+ # Each `submit`:
15
+ # 1. runs the baked DEV engine (visible-subset correctness + dev timing) on
16
+ # the LIVE /app/repo and returns SANITIZED feedback;
17
+ # 2. snapshots the candidate tree (git stash-create tree hash + binary diff)
18
+ # to /logs/loop/submissions/<k>/;
19
+ # 3. updates /logs/loop/best.json (best correctness-passing dev_reward);
20
+ # 4. enforces min=3 / max=16.
21
+ # On --finalize (>=3) or auto at k=16 it restores /app/repo's WORKING TREE to
22
+ # the best correctness-passing snapshot (HEAD stays at the baseline commit so
23
+ # the runner's end-of-session verifier still sees a product-only modification)
24
+ # and writes /logs/loop/finalize.json for the audit.
25
+ #
26
+ # 🔴 PATH-pin: the agent shell + runner verifier exec are
27
+ # NON-login; bare python3 has no torch. Pin the venv FIRST.
28
+ export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
29
+ set -uo pipefail
30
+
31
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
32
+ REPO=/app/repo
33
+ LOOP=/logs/loop
34
+ DEV="$LOOP/dev"
35
+ mkdir -p "$LOOP" "$LOOP/submissions" "$DEV"
36
+
37
+ MIN_SUBMISSIONS=1
38
+ MAX_SUBMISSIONS=1
39
+ COUNT_FILE="$LOOP/count"
40
+ BEST_FILE="$LOOP/best.json"
41
+ STATE_JSONL="$LOOP/state.jsonl"
42
+ FINALIZE_JSON="$LOOP/finalize.json"
43
+
44
+ _read_count() {
45
+ if [ -f "$COUNT_FILE" ]; then
46
+ awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE"
47
+ else
48
+ echo 0
49
+ fi
50
+ }
51
+
52
+ # Non-mutating snapshot of the current working tree -> a git tree hash.
53
+ # `git stash create` builds dangling objects without touching HEAD/index/WT.
54
+ _snapshot_tree() {
55
+ local c
56
+ c="$(git -C "$REPO" stash create 2>/dev/null || true)"
57
+ if [ -n "$c" ]; then
58
+ git -C "$REPO" rev-parse "$c^{tree}" 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null
59
+ else
60
+ git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null
61
+ fi
62
+ }
63
+
64
+ # ------------------- argument parsing -------------------
65
+ MODE=submit
66
+ REASON=""
67
+ while [ "$#" -gt 0 ]; do
68
+ case "$1" in
69
+ --finalize) MODE=finalize; shift ;;
70
+ --reason) REASON="${2:-}"; shift 2 ;;
71
+ --reason=*) REASON="${1#--reason=}"; shift ;;
72
+ *) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"<text>\"]]" >&2; exit 2 ;;
73
+ esac
74
+ done
75
+
76
+ # ------------------- finalize -------------------
77
+ if [ "$MODE" = finalize ]; then
78
+ CUR="$(_read_count)"; CUR="${CUR:-0}"
79
+ if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then
80
+ echo "minimum $MIN_SUBMISSIONS submission(s) required before finalize (you have $CUR/$MIN_SUBMISSIONS)"
81
+ exit 1
82
+ fi
83
+ # Restore /app/repo working tree to the best correctness-passing snapshot.
84
+ git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true
85
+ git -C "$REPO" clean -qfd 2>/dev/null || true
86
+ WIN_DIFF=""
87
+ WIN_SUB=""
88
+ if [ -f "$BEST_FILE" ]; then
89
+ WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)"
90
+ fi
91
+ if [ -n "$WIN_SUB" ] && [ -f "$LOOP/submissions/$WIN_SUB/candidate.diff" ]; then
92
+ WIN_DIFF="$LOOP/submissions/$WIN_SUB/candidate.diff"
93
+ if [ -s "$WIN_DIFF" ]; then
94
+ git -C "$REPO" apply --whitespace=nowarn "$WIN_DIFF" 2>"$LOOP/finalize_apply.log" || \
95
+ echo "WARNING: could not re-apply the winning diff cleanly; see /logs/loop/finalize_apply.log" >&2
96
+ fi
97
+ fi
98
+ # Write finalize.json (winning index, k, dev_speedup trajectory, reason) for audit.
99
+ REASON="$REASON" WIN_SUB="$WIN_SUB" CUR="$CUR" python3 - <<'PY'
100
+ import json, os
101
+ from pathlib import Path
102
+ LOOP = Path('/logs/loop')
103
+ best = {}
104
+ try:
105
+ best = json.loads((LOOP / 'best.json').read_text())
106
+ except Exception:
107
+ best = {}
108
+ traj = []
109
+ try:
110
+ for line in (LOOP / 'state.jsonl').read_text().splitlines():
111
+ line = line.strip()
112
+ if not line:
113
+ continue
114
+ row = json.loads(line)
115
+ traj.append({'submission': row.get('submission'),
116
+ 'dev_speedup': row.get('speedup'),
117
+ 'dev_reward': row.get('reward'),
118
+ 'correctness_ok': row.get('correctness_ok')})
119
+ except Exception:
120
+ pass
121
+ win = best.get('submission') if best else None
122
+ out = {
123
+ 'schema_version': 'kernelbench_loop_finalize_v1',
124
+ 'task_id': 'jit-source-arch-cache-key',
125
+ 'mode': 'baked',
126
+ 'submissions_used': int(os.environ.get('CUR') or 0),
127
+ 'min_submissions': 1, 'max_submissions': 1,
128
+ 'winning_submission': win,
129
+ 'winning_dev_speedup': best.get('speedup') if best else None,
130
+ 'winning_dev_reward': best.get('reward') if best else None,
131
+ 'winning_tree': best.get('tree') if best else None,
132
+ 'dev_speedup_trajectory': traj,
133
+ 'termination_reason': os.environ.get('REASON') or '',
134
+ 'note': 'dev_reward is an in-session proxy; meta.reward is the runner end-of-session score of /app/repo.',
135
+ }
136
+ (LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n')
137
+ PY
138
+ # Integrity: recompute the restored tree hash for the audit trail.
139
+ RESTORED_TREE="$(_snapshot_tree)"
140
+ echo "restored_tree=$RESTORED_TREE" >> "$LOOP/finalize_apply.log" 2>/dev/null || true
141
+ if [ -n "$WIN_SUB" ]; then
142
+ WR="$(python3 -c 'import json,sys;b=json.load(open(sys.argv[1]));print(f"{b.get(\"speedup\")}", f"{b.get(\"reward\")}")' "$BEST_FILE" 2>/dev/null || echo "? ?")"
143
+ echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (dev_speedup ${WR% *}, dev_reward ${WR#* }); the grader will now score /app/repo"
144
+ else
145
+ echo "finalized: no correctness-passing submission in $CUR tries — /app/repo restored to the starting baseline; final reward will be 0 (no_improvement). the grader will now score /app/repo"
146
+ fi
147
+ exit 0
148
+ fi
149
+
150
+ # ------------------- submit -------------------
151
+ CUR="$(_read_count)"; CUR="${CUR:-0}"
152
+ if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then
153
+ echo "submission $CUR/$MAX_SUBMISSIONS"
154
+ echo "budget exhausted — call 'bash /opt/loop/submit.sh --finalize' to grade your best submission"
155
+ # Auto-finalize as a safety net.
156
+ echo "--- auto-finalizing best-of-$MAX_SUBMISSIONS ---"
157
+ exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
158
+ fi
159
+
160
+ # Run the DEV engine on the LIVE /app/repo.
161
+ bash "$HERE/score_engine.sh"
162
+ engine_rc=$?
163
+
164
+ # HARNESS error path: the engine flagged an infra failure (rc=3 or a marker).
165
+ # Do NOT consume the solver's budget for our bug.
166
+ if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then
167
+ python3 "$HERE/sanitize_feedback.py"
168
+ exit 0
169
+ fi
170
+
171
+ # Consume one submission.
172
+ NEXT=$((CUR + 1))
173
+ echo "$NEXT" > "$COUNT_FILE"
174
+
175
+ # Snapshot the candidate: tree hash (non-mutating) + binary diff vs baseline HEAD.
176
+ SNAP="$LOOP/submissions/$NEXT"
177
+ mkdir -p "$SNAP"
178
+ TREE="$(_snapshot_tree)"
179
+ git -C "$REPO" diff --binary HEAD > "$SNAP/candidate.diff" 2>/dev/null || true
180
+ echo "${TREE:-}" > "$SNAP/tree.txt"
181
+ for f in verifier_state.json correctness_results.json benchmark_results.json reward.json; do
182
+ [ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true
183
+ done
184
+
185
+ # Update best-of-k (only correctness-passing, strictly-greater dev_reward) and
186
+ # append the per-submission audit row.
187
+ NEXT="$NEXT" TREE="$TREE" python3 - <<'PY'
188
+ import json, os, time
189
+ from pathlib import Path
190
+ LOOP = Path('/logs/loop'); DEV = LOOP / 'dev'
191
+ k = int(os.environ['NEXT']); tree = os.environ.get('TREE') or ''
192
+ try:
193
+ state = json.loads((DEV / 'verifier_state.json').read_text())
194
+ except Exception:
195
+ state = {}
196
+ try:
197
+ reward = json.loads((DEV / 'reward.json').read_text())
198
+ except Exception:
199
+ reward = {}
200
+ corr_ok = bool(state.get('correctness_ok'))
201
+ r = float(reward.get('reward') or 0.0)
202
+ s = float(reward.get('speedup') or 0.0)
203
+ # append audit row
204
+ row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok,
205
+ 'reward': r, 'speedup': s, 'tree': tree,
206
+ 'hard_fail_reasons': list(state.get('hard_fail_reasons') or [])}
207
+ with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f:
208
+ f.write(json.dumps(row) + '\n')
209
+ # update best
210
+ if corr_ok:
211
+ best_p = LOOP / 'best.json'
212
+ try:
213
+ best = json.loads(best_p.read_text())
214
+ except Exception:
215
+ best = None
216
+ if best is None or r > float(best.get('reward') or -1.0):
217
+ best_p.write_text(json.dumps(
218
+ {'submission': k, 'reward': r, 'speedup': s, 'tree': tree},
219
+ indent=2, sort_keys=True) + '\n')
220
+ PY
221
+
222
+ # Print sanitized feedback.
223
+ python3 "$HERE/sanitize_feedback.py"
224
+
225
+ # Auto-finalize on the ceiling.
226
+ if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then
227
+ echo ""
228
+ echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---"
229
+ exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
230
+ fi
231
+
232
+ exit 0
tasks/kfc/jit-source-arch-cache-key/task/environment/repo/identity_key.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable identity for a build-spec.
2
+
3
+ Public entry point:
4
+ ``identity_key(spec: dict) -> str``
5
+
6
+ A downstream stage keeps a table of already-produced *identities* and skips the
7
+ expensive step for a build-spec whose identity it has already seen. So the identity
8
+ must satisfy two properties:
9
+
10
+ * two specs that are **equivalent** (they describe the same build, differing only in
11
+ incidental spelling) should map to the **same** identity, and
12
+ * two specs that are **genuinely different** must map to **different** identities -- a
13
+ collision between two different specs would let the wrong prior artifact be reused,
14
+ which is never acceptable.
15
+
16
+ Build-spec shape
17
+ ----------------
18
+ A spec is a mapping with:
19
+
20
+ * ``"source"``: the source text (a string).
21
+ * ``"target"``: the target-profile tag (a string) the artifact is produced for.
22
+ * ``"options"`` (optional): a list of build-option tokens (an unordered set).
23
+ * ``"toolchain"`` (optional): the toolchain-version tag (a string).
24
+ * ``"variants"`` (optional): a list of requested variant names (an unordered set).
25
+ * ``"build"`` (optional): a mapping of incidental build annotations.
26
+
27
+ This starting implementation is **correct but conservative**: it derives the identity
28
+ from the spec almost verbatim (only the field order of a mapping is neutralized). It
29
+ never merges two different specs, but specs that are merely spelled differently are
30
+ treated as separate identities, so the downstream table holds more entries than there
31
+ are truly distinct builds and the expensive step is repeated once per spelling.
32
+ Reducing the number of distinct identities -- without ever merging two genuinely
33
+ different specs -- is the goal.
34
+ """
35
+
36
+ import json
37
+
38
+
39
+ def _fnv1a_64(text):
40
+ """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted)."""
41
+ h = 0xCBF29CE484222325
42
+ for byte in text.encode("utf-8"):
43
+ h ^= byte
44
+ h = (h * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF
45
+ return format(h, "016x")
46
+
47
+
48
+ def identity_key(spec):
49
+ """Return a stable string identity for ``spec``.
50
+
51
+ Conservative baseline: serialize the spec with a fixed field order and digest it.
52
+ Only mapping-field order is neutralized; every other incidental difference (source
53
+ comments/whitespace, option order, redundant no-op options, annotation fields)
54
+ still yields a new identity.
55
+ """
56
+ text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr)
57
+ return _fnv1a_64(text)
tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/entrypoint.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Canonical entrypoint: start the timer in the background and hand the container to
3
+ # a login shell so the orchestrator can keep it alive and exec /tests/test.sh into it.
4
+ # `exec "$@"` is honored when a command is passed (e.g. local smoke). CPU task: no
5
+ # GPU/venv assumptions — pin a portable PATH that resolves python3.
6
+ set -euo pipefail
7
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/bin:$PATH
8
+ mkdir -p /app/.timer
9
+ /app/timer.sh >/tmp/task-timer.log 2>&1 &
10
+ if [ "$#" -gt 0 ]; then
11
+ exec "$@"
12
+ fi
13
+ exec /bin/bash -l
tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/run_dev_bench.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/bin:$PATH
4
+ printf '%s\n' 'Public development feedback only. Final verification runs additional trusted and hidden workloads.'
5
+ exit 0
tasks/kfc/jit-source-arch-cache-key/task/environment/runtime/timer.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Minimal global timer stub; the harness replaces it with the real budget timer.
3
+ set -euo pipefail
4
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/bin:$PATH
5
+ mkdir -p /app/.timer
6
+ echo 10800 > /app/.timer/remaining_secs
7
+ echo 10800 > /app/.timer/budget_secs
tasks/kfc/jit-source-arch-cache-key/task/environment/verifier-correctness-manifest.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "kernelbench_correctness_manifest_v1",
3
+ "task_id": "jit-source-arch-cache-key",
4
+ "task_kind": "acceleration",
5
+ "expected_case_count": 12,
6
+ "primary_workload": "buildspec-identity-count",
7
+ "ref_speedup": 1.0,
8
+ "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.",
9
+ "metric": "recompile_count",
10
+ "direction": "higher_is_better",
11
+ "target_hardware": "cpu (x86-64 Sapphire Rapids; pure-Python stdlib, fixed FNV-1a/sha1 hash -> deterministic count, no profiler)",
12
+ "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",
13
+ "correctness_axes": [
14
+ "returns_string_for_various",
15
+ "deterministic_repeat_same_object",
16
+ "deterministic_fresh_build",
17
+ "distinct_source_distinct_keys",
18
+ "distinct_target_distinct_keys",
19
+ "distinct_effective_option_distinct_keys",
20
+ "distinct_option_value_distinct_keys",
21
+ "distinct_toolchain_distinct_keys",
22
+ "distinct_variant_set_distinct_keys",
23
+ "no_false_merge_full_workload",
24
+ "handles_edge_schema",
25
+ "many_distinct_specs_pairwise_distinct"
26
+ ],
27
+ "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",
28
+ "public_symbol": "identity_key",
29
+ "primary_edit_paths": [
30
+ "/app/repo/identity_key.py"
31
+ ]
32
+ }
tasks/kfc/jit-source-arch-cache-key/task/instruction.md ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Performance Optimization Task
2
+
3
+ You are working on the work-reuse layer of a batch build service. The service receives
4
+ a stream of **build-specs**. Before running an expensive step for a spec, it computes a
5
+ short string **identity** for that spec and looks the identity up in a table of
6
+ already-produced identities; a hit means the prior artifact can be reused and the
7
+ expensive step is skipped. The file `identity_key.py` implements this identity as a
8
+ single function, `identity_key`. It is correct but produces far more distinct identities
9
+ than necessary.
10
+
11
+ ## Behavioral contract
12
+
13
+ ```python
14
+ def identity_key(spec: dict) -> str:
15
+ ...
16
+ ```
17
+
18
+ A **build-spec** is a mapping describing one build request:
19
+
20
+ - `"source"`: the source text — a string.
21
+ - `"target"`: the target-profile tag — a string. The produced artifact is specific to
22
+ this profile.
23
+ - `"options"` (optional): a list of build-option tokens (strings). The list is an
24
+ **unordered set** of options.
25
+ - `"toolchain"` (optional): the toolchain-version tag — a string.
26
+ - `"variants"` (optional): a list of requested variant names (strings), also an
27
+ **unordered set**.
28
+ - `"build"` (optional): a mapping of incidental build annotations.
29
+
30
+ `identity_key(spec)` returns a **string**. It must be **deterministic and reproducible**:
31
+ the same spec (and any spec equivalent to it, see below) always yields the same string,
32
+ on every run and every machine — so derive it from the spec's content with a fixed rule,
33
+ not from anything process- or run-dependent.
34
+
35
+ ### When are two build-specs equivalent?
36
+
37
+ Two specs are **equivalent** (they describe the same build and must receive the **same**
38
+ identity) when they are equal after applying **all** of the following normalizations. Any
39
+ difference that survives all of them makes the specs **distinct**, and distinct specs
40
+ must receive **different** identities.
41
+
42
+ 1. **Incidental build annotations are ignored.** The `"build"` mapping never affects the
43
+ identity — two specs that differ only in `"build"` (or in whether `"build"` is present
44
+ at all) are equivalent.
45
+ 2. **Field order is irrelevant.** The order in which the keys of any mapping are written
46
+ does not matter.
47
+ 3. **Source comments and whitespace are ignored.** Within `"source"`, line comments
48
+ (`// …` to end of line) and block comments (`/* … */`) carry no meaning, and runs of
49
+ whitespace are insignificant (any run of spaces/tabs/newlines is equivalent to a
50
+ single space; leading and trailing whitespace is insignificant). Two source texts that
51
+ are equal after removing comments and collapsing whitespace are equivalent. **Every
52
+ other difference in the source text is meaningful.**
53
+ 4. **Options are an unordered set with no-op defaults folded.** The order of `"options"`
54
+ does not matter, and duplicate tokens are redundant. The tokens `"o0"`, `"dbgoff"`,
55
+ and `"std0"` are **no-op defaults**: each is equivalent to the token being absent. Any
56
+ **other** option token is meaningful and must be kept.
57
+ 5. **Requested variants are an unordered set.** The order of `"variants"` does not matter
58
+ and duplicates are redundant, but **which** variant names are present is meaningful.
59
+
60
+ Everything not listed above is **meaningful**: the source text (beyond comments and
61
+ whitespace), the target-profile tag, each effective (non-default) option token, the
62
+ toolchain-version tag, and the set of requested variant names. Specs that differ in any of
63
+ these are **distinct** and must not share an identity.
64
+
65
+ ## Why the current implementation is wasteful
66
+
67
+ The current code derives the identity from the spec almost verbatim: it only neutralizes
68
+ the order of a mapping's keys. So two specs that are equivalent but merely spelled
69
+ differently — the same source with a comment added or reflowed whitespace, the same
70
+ options in a different order or with a no-op default written out, a stray build
71
+ annotation, the same variants listed in a different order — are treated as **different**
72
+ identities. The reuse table then holds one entry per spelling instead of one entry per
73
+ genuinely distinct build, and the expensive step is repeated for every spelling of the
74
+ same build.
75
+
76
+ Make the identity **collapse the equivalent spellings** so that equivalent specs map to
77
+ one identity and the reuse table holds as few entries as there are genuinely distinct
78
+ builds — while **never** giving two genuinely different specs the same identity.
79
+
80
+ ## Correctness comes first
81
+
82
+ A single **collision between two genuinely different specs** — for example treating two
83
+ different target profiles, two different source texts, two different effective option
84
+ values, two different toolchain tags, or two different variant sets as the same — is a
85
+ hard failure and scores **zero**, no matter how few identities you produce. In
86
+ particular, two specs that share everything but the **target profile** describe different
87
+ artifacts and must never collide. Merging spellings that are only *incidentally* different
88
+ is the goal; merging builds that are *actually* different is never allowed. The verifier
89
+ checks both a suite of correctness cases and, over the whole workload, that no identity is
90
+ shared by two genuinely different builds.
91
+
92
+ ## Forbidden
93
+
94
+ Do **not** import a tensor / graph / array framework, and do **not** import or read the
95
+ test harness or its workload. Compute the identity yourself from the spec content using
96
+ the standard library only. The scoring harness scans your submitted file for those
97
+ references and scores the task `0` (do not reference them even in comments).
98
+
99
+ ## Scope
100
+
101
+ Optimize the product implementation in `identity_key.py` only. Do **not** edit tests,
102
+ harnesses, workloads, or dependency/build files. The final submitted diff must contain
103
+ only product-code changes. Public/dev feedback, when present, is representative only;
104
+ final verification runs additional trusted and hidden workloads.
105
+
106
+ ## How this task is scored — ONE single submission (READ CAREFULLY)
107
+
108
+ You get **exactly one** submission. There is no iterative loop, no budget of
109
+ retries, and no per-round feedback to improve against: the moment you submit, the
110
+ task is over.
111
+
112
+ 1. Read and profile the current implementation in `/app/repo/identity_key.py`, work out
113
+ what is slow, and make it faster — taking as long as you need. Test your work
114
+ yourself as much as you like *before* submitting: write your own scratch
115
+ benchmarks and your own correctness checks in a scratch directory you create.
116
+ 2. When — and only when — you are confident the solution is both correct and as
117
+ fast as you can make it, submit it **once**:
118
+
119
+ ```
120
+ bash /opt/loop/submit.sh
121
+ ```
122
+
123
+ 3. **Submitting ends the task.** That single call scores the current state of
124
+ `/app/repo`, records it as your final answer, and finalizes immediately. You
125
+ will not get a second attempt, and you will not get feedback you could iterate
126
+ on. A second call to `submit.sh` is refused.
127
+
128
+ Because there is no second chance, spend your effort *before* the submission:
129
+ convince yourself the contract holds on every case you can think of (the shapes,
130
+ dtypes, boundary and error cases described above), and verify your own timing
131
+ shows a real improvement over the shipped implementation. A fast but incorrect
132
+ submission scores zero, and there is no round in which to repair it.
133
+
134
+ The grade is produced by a full, trusted end-of-session verifier over more
135
+ workloads than anything you can see, so make the one submission you have a
136
+ genuinely correct one.
137
+
138
+ ## 🔴 Red line (hard — ANY one of these makes the whole task score 0)
139
+
140
+ The scoring machinery is off-limits. Solve this task **independently**, using
141
+ ONLY the code in `/app/repo` and your own knowledge and reasoning.
142
+
143
+ - Do **NOT** read, `cat`, `open`, `less`, `head`/`tail`, `grep`, `find`, or edit
144
+ ANY verifier / correctness / timing / scoring / hidden-test file or directory,
145
+ wherever it may live. Running `bash /opt/loop/submit.sh` is the ONLY sanctioned
146
+ interaction with the scoring machinery.
147
+ - Do **NOT** run any verifier directly or try to reproduce or reverse-engineer it
148
+ — score ONLY by calling `bash /opt/loop/submit.sh`.
149
+ - Do **NOT** search for, print, or infer the hidden workloads, seeds, thresholds,
150
+ the metric name, or the reference speedup from any source.
151
+ - Do **NOT** fetch or look up the source PR, the upstream repository, or a
152
+ reference solution (no web search, no `git` remote fetch, no network to the
153
+ source), whether the internet is on or off.
154
+ - Do **NOT** use, quote, or condition your code on any verifier / scoring / source
155
+ material, however you might have come to see it.
156
+
157
+ Stay inside `/app/repo` and scratch directories you create yourself.
158
+
159
+ ## 提交方式
160
+
161
+ 本题只有**一次**评分提交(kfc 全子集单次)。改完后运行一次 `bash /opt/loop/submit.sh`:它给当前 `/app/repo` 评分并**立即定稿**(无需再单独调 `--finalize`,也没有第二次机会 —— 再次调用只会重新定稿同一份已记录的最佳快照,不给新改动评分)。请先用你自己的脚本充分自测再提交。
162
+ 改动留在工作树里,不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上)。
tasks/kfc/jit-source-arch-cache-key/task/pre_artifacts.sh ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ============================================================================
3
+ # pre_artifacts.sh — kfc/jit-source-arch-cache-key
4
+ #
5
+ # Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE
6
+ # grading (spec §1.1). It turns whatever the agent left behind into a portable artifact:
7
+ #
8
+ # /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit
9
+ # /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line
10
+ #
11
+ # 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one
12
+ # place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs <base>..HEAD).
13
+ # Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate,
14
+ # `git checkout -q HEAD -- <scope>` re-materialises the baseline for the paired timing,
15
+ # and loop16's `submit.sh --finalize` plants the best iterate with read-tree +
16
+ # checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope
17
+ # gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the
18
+ # "baseline" — and a correct solve scores 0.
19
+ # `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages
20
+ # names only, writes no tree, creates no commit and leaves HEAD exactly where it was.
21
+ #
22
+ # EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier
23
+ # scores the container on its own terms and gives 0 by itself.
24
+ #
25
+ # READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index
26
+ # (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the
27
+ # verifier — which runs after us — sees exactly the `git status --porcelain` it would have
28
+ # seen if this script had never run. No commit, no HEAD move, no working-tree write.
29
+ #
30
+ # CAPTURE ROOTS for THIS task — derived from the package, never assumed:
31
+ # /app/repo git repo, HEAD == the 1-commit carved baseline
32
+ # evidence Dockerfile:127: WORKDIR /app/repo
33
+ # evidence Dockerfile:76: && cd /app/repo \
34
+ # evidence Dockerfile:83: && test "$(git rev-list --count HEAD)" = "1" \
35
+ # evidence test.sh:15: REPO=/app/repo
36
+ #
37
+ # Single root => model.patch is a bare `git diff --binary <baseline>` (no banner).
38
+ # model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable
39
+ # by one reader.
40
+ #
41
+ # loop16 task (environment/loop/ -> /opt/loop in the image): the harness auto-finalizes
42
+ # at k=16 and `submit.sh --finalize` plants the best iterate in the WORKING TREE while
43
+ # HEAD stays on the baked baseline — which is exactly what this script captures. Running
44
+ # it after a finalize therefore yields the GRADED artifact, not the last raw edit.
45
+ # ============================================================================
46
+ set -uo pipefail
47
+
48
+ OUT=/logs/artifacts
49
+ PATCH="$OUT/model.patch"
50
+ LIST="$OUT/model_files.txt"
51
+ MULTI=0 # 1 => several capture roots => each diff gets a banner line
52
+ MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane)
53
+
54
+ mkdir -p "$OUT" 2>/dev/null || true
55
+ : > "$PATCH" 2>/dev/null || true
56
+ : > "$LIST" 2>/dev/null || true
57
+ git config --global --add safe.directory '*' >/dev/null 2>&1 || true
58
+
59
+ banner() { # $1=root $2=mode ; only when there is more than one root
60
+ if [ "$MULTI" = 1 ]; then
61
+ printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null
62
+ fi
63
+ return 0
64
+ }
65
+
66
+ list_add() { # stdin: paths relative to $1 -> absolute, one per line
67
+ sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true
68
+ return 0
69
+ }
70
+
71
+ capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline
72
+ root=$1
73
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
74
+ if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
75
+ echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot"
76
+ capture_tree "$root"
77
+ return 0
78
+ fi
79
+ # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and
80
+ # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could
81
+ # flip a scope gate either way. So copy the repo's index aside and stage into the COPY —
82
+ # the repo's own .git/index is byte-identical when we are done.
83
+ tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi=""
84
+ gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true)
85
+ if [ -z "$gd" ]; then
86
+ gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true)
87
+ case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac
88
+ fi
89
+ if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then
90
+ GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE
91
+ else
92
+ echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index"
93
+ fi
94
+ git -C "$root" add -AN . >/dev/null 2>&1 || true
95
+ base=HEAD
96
+ if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then
97
+ base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null)
98
+ echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree"
99
+ else
100
+ n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0)
101
+ case "$n" in ''|*[!0-9]*) n=0 ;; esac
102
+ if [ "$n" -gt 1 ]; then
103
+ base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1)
104
+ echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:"
105
+ echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so"
106
+ echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved"
107
+ echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve."
108
+ fi
109
+ fi
110
+ [ -n "${base:-}" ] || base=HEAD
111
+ banner "$root" "git-diff-vs-baseline"
112
+ git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true
113
+ names=$(git -C "$root" diff --name-only "$base" 2>/dev/null)
114
+ echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)"
115
+ unset GIT_INDEX_FILE
116
+ [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null
117
+ printf '%s\n' "$names" | grep -v '^$' | list_add "$root"
118
+ return 0
119
+ }
120
+
121
+ capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot
122
+ root=$1
123
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
124
+ tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0
125
+ if git init -q "$tmp/snap" >/dev/null 2>&1; then
126
+ GD="$tmp/snap/.git"
127
+ empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null)
128
+ ( cd "$root" 2>/dev/null || exit 0
129
+ find . -name .git -prune -o -name __pycache__ -prune -o \
130
+ -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \
131
+ 2>/dev/null \
132
+ | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true
133
+ banner "$root" "tree-snapshot-not-a-git-repo"
134
+ GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \
135
+ >> "$PATCH" 2>/dev/null || true
136
+ else
137
+ echo "[pre_artifacts] WARN could not stage a snapshot index for $root"
138
+ fi
139
+ rm -rf "$tmp" 2>/dev/null || true
140
+ all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \
141
+ -type f -print 2>/dev/null | sed 's|^\./||' )
142
+ printf '%s\n' "$all" | grep -v '^$' | list_add "$root"
143
+ big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \
144
+ -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . )
145
+ echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)"
146
+ if [ "${big:-0}" != 0 ]; then
147
+ echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in"
148
+ echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch."
149
+ fi
150
+ return 0
151
+ }
152
+
153
+ capture_git "/app/repo"
154
+ bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0)
155
+ case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac
156
+ echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)"
157
+ if [ "$bytes" -gt 67108864 ]; then
158
+ echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build"
159
+ echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also"
160
+ echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish."
161
+ fi
162
+ exit 0
tasks/kfc/jit-source-arch-cache-key/task/solution/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # solution/ — reviewer-only 参考实现
2
+
3
+ 本目录里的补丁**不进镜像**(已被上下文根的 `.dockerignore` 排除)、**判分不运行**,
4
+ 只在两种场合用:
5
+
6
+ 1. **重标定锚点**(换硬件后):见 `../tests/ref_speedup.caveat.md`
7
+ ```
8
+ -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch
9
+ ```
10
+ 2. **自证挖洞树的正确性**:`git apply --check -p1 oracle.patch` 必须能干净打在
11
+ `../environment/repo/` 上(正向可、反向不可),这证明该树就是被计分的起始点。
12
+
13
+ `negative.patch` 是已知坏例(必须得 0),`baseline2.patch` 是中间基线(若有)。
tasks/kfc/jit-source-arch-cache-key/task/solution/baseline2.patch ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/identity_key.py b/identity_key.py
2
+ index 9e2a701..f9c4328 100644
3
+ --- a/identity_key.py
4
+ +++ b/identity_key.py
5
+ @@ -1,57 +1,33 @@
6
+ -"""Stable identity for a build-spec.
7
+ -
8
+ -Public entry point:
9
+ - ``identity_key(spec: dict) -> str``
10
+ -
11
+ -A downstream stage keeps a table of already-produced *identities* and skips the
12
+ -expensive step for a build-spec whose identity it has already seen. So the identity
13
+ -must satisfy two properties:
14
+ -
15
+ -* two specs that are **equivalent** (they describe the same build, differing only in
16
+ - incidental spelling) should map to the **same** identity, and
17
+ -* two specs that are **genuinely different** must map to **different** identities -- a
18
+ - collision between two different specs would let the wrong prior artifact be reused,
19
+ - which is never acceptable.
20
+ -
21
+ -Build-spec shape
22
+ -----------------
23
+ -A spec is a mapping with:
24
+ -
25
+ -* ``"source"``: the source text (a string).
26
+ -* ``"target"``: the target-profile tag (a string) the artifact is produced for.
27
+ -* ``"options"`` (optional): a list of build-option tokens (an unordered set).
28
+ -* ``"toolchain"`` (optional): the toolchain-version tag (a string).
29
+ -* ``"variants"`` (optional): a list of requested variant names (an unordered set).
30
+ -* ``"build"`` (optional): a mapping of incidental build annotations.
31
+ -
32
+ -This starting implementation is **correct but conservative**: it derives the identity
33
+ -from the spec almost verbatim (only the field order of a mapping is neutralized). It
34
+ -never merges two different specs, but specs that are merely spelled differently are
35
+ -treated as separate identities, so the downstream table holds more entries than there
36
+ -are truly distinct builds and the expensive step is repeated once per spelling.
37
+ -Reducing the number of distinct identities -- without ever merging two genuinely
38
+ -different specs -- is the goal.
39
+ +"""baseline2 for jit-source-arch-cache-key (reviewer-only; NOT baked in image).
40
+ +
41
+ +Same canonicalization SEMANTICS as the oracle (normalize source text, drop no-op
42
+ +options + de-dup + order-free, sort the variant set, drop build annotations, keep
43
+ +target profile + toolchain tag) but a DIFFERENT mechanism: build a canonical nested
44
+ +TUPLE and digest its ``repr`` with sha1, instead of the oracle's json + FNV-1a. It
45
+ +induces the same partition and the same identity count (~12) as the oracle -> the same
46
+ +speedup -- which proves the verifier scores the identity PARTITION, not a byte-match
47
+ +against oracle code.
48
+ """
49
+
50
+ -import json
51
+ +import hashlib
52
+ +import re
53
+
54
+ +_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
55
+ +_LINE_COMMENT = re.compile(r"//[^\n]*")
56
+ +NOOP_OPTIONS = {"o0", "dbgoff", "std0"}
57
+
58
+ -def _fnv1a_64(text):
59
+ - """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted)."""
60
+ - h = 0xCBF29CE484222325
61
+ - for byte in text.encode("utf-8"):
62
+ - h ^= byte
63
+ - h = (h * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF
64
+ - return format(h, "016x")
65
+
66
+ +def _canon_source(text):
67
+ + text = _BLOCK_COMMENT.sub(" ", text or "")
68
+ + text = _LINE_COMMENT.sub(" ", text)
69
+ + return " ".join(text.split())
70
+
71
+ -def identity_key(spec):
72
+ - """Return a stable string identity for ``spec``.
73
+
74
+ - Conservative baseline: serialize the spec with a fixed field order and digest it.
75
+ - Only mapping-field order is neutralized; every other incidental difference (source
76
+ - comments/whitespace, option order, redundant no-op options, annotation fields)
77
+ - still yields a new identity.
78
+ - """
79
+ - text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr)
80
+ - return _fnv1a_64(text)
81
+ +def identity_key(spec):
82
+ + source = _canon_source(spec.get("source", ""))
83
+ + target = spec.get("target")
84
+ + toolchain = spec.get("toolchain")
85
+ + options = tuple(sorted({o for o in (spec.get("options") or []) if o not in NOOP_OPTIONS}))
86
+ + variants = tuple(sorted(spec.get("variants") or []))
87
+ + canon = (source, target, toolchain, options, variants)
88
+ + return hashlib.sha1(repr(canon).encode("utf-8")).hexdigest()
tasks/kfc/jit-source-arch-cache-key/task/solution/negative.patch ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/identity_key.py b/identity_key.py
2
+ index 9e2a701..98ec768 100644
3
+ --- a/identity_key.py
4
+ +++ b/identity_key.py
5
+ @@ -1,43 +1,25 @@
6
+ -"""Stable identity for a build-spec.
7
+ -
8
+ -Public entry point:
9
+ - ``identity_key(spec: dict) -> str``
10
+ -
11
+ -A downstream stage keeps a table of already-produced *identities* and skips the
12
+ -expensive step for a build-spec whose identity it has already seen. So the identity
13
+ -must satisfy two properties:
14
+ -
15
+ -* two specs that are **equivalent** (they describe the same build, differing only in
16
+ - incidental spelling) should map to the **same** identity, and
17
+ -* two specs that are **genuinely different** must map to **different** identities -- a
18
+ - collision between two different specs would let the wrong prior artifact be reused,
19
+ - which is never acceptable.
20
+ -
21
+ -Build-spec shape
22
+ -----------------
23
+ -A spec is a mapping with:
24
+ -
25
+ -* ``"source"``: the source text (a string).
26
+ -* ``"target"``: the target-profile tag (a string) the artifact is produced for.
27
+ -* ``"options"`` (optional): a list of build-option tokens (an unordered set).
28
+ -* ``"toolchain"`` (optional): the toolchain-version tag (a string).
29
+ -* ``"variants"`` (optional): a list of requested variant names (an unordered set).
30
+ -* ``"build"`` (optional): a mapping of incidental build annotations.
31
+ -
32
+ -This starting implementation is **correct but conservative**: it derives the identity
33
+ -from the spec almost verbatim (only the field order of a mapping is neutralized). It
34
+ -never merges two different specs, but specs that are merely spelled differently are
35
+ -treated as separate identities, so the downstream table holds more entries than there
36
+ -are truly distinct builds and the expensive step is repeated once per spelling.
37
+ -Reducing the number of distinct identities -- without ever merging two genuinely
38
+ -different specs -- is the goal.
39
+ +"""Negative for jit-source-arch-cache-key (reviewer-only; NOT baked in image).
40
+ +
41
+ +Over-canonicalizes: it DROPS the target-profile field (treats every target as the same).
42
+ +So two specs that differ ONLY in target profile -- e.g. the SAME source built for target
43
+ +``p80`` vs ``p90`` -- collapse to the SAME identity. That is a FALSE MERGE of two
44
+ +genuinely different builds: it would let an artifact produced for one target be reused
45
+ +for another (a wrong-target artifact). This must score reward 0 -- it fails
46
+ +distinct_target_distinct_keys, the whole-workload no_false_merge gate, and
47
+ +count_bench.py verify. It is otherwise a plausible full normalizer (source/options/
48
+ +toolchain/variants all handled), which is exactly why the false-merge safety gate has
49
+ +to catch it.
50
+ """
51
+
52
+ import json
53
+ +import re
54
+ +
55
+ +_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
56
+ +_LINE_COMMENT = re.compile(r"//[^\n]*")
57
+ +NOOP_OPTIONS = {"o0", "dbgoff", "std0"}
58
+
59
+
60
+ def _fnv1a_64(text):
61
+ - """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted)."""
62
+ h = 0xCBF29CE484222325
63
+ for byte in text.encode("utf-8"):
64
+ h ^= byte
65
+ @@ -45,13 +27,22 @@ def _fnv1a_64(text):
66
+ return format(h, "016x")
67
+
68
+
69
+ +def _canon_source(text):
70
+ + text = _BLOCK_COMMENT.sub(" ", text or "")
71
+ + text = _LINE_COMMENT.sub(" ", text)
72
+ + return " ".join(text.split())
73
+ +
74
+ +
75
+ def identity_key(spec):
76
+ - """Return a stable string identity for ``spec``.
77
+ -
78
+ - Conservative baseline: serialize the spec with a fixed field order and digest it.
79
+ - Only mapping-field order is neutralized; every other incidental difference (source
80
+ - comments/whitespace, option order, redundant no-op options, annotation fields)
81
+ - still yields a new identity.
82
+ - """
83
+ - text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr)
84
+ - return _fnv1a_64(text)
85
+ + source = _canon_source(spec.get("source", ""))
86
+ + toolchain = spec.get("toolchain")
87
+ + options = sorted({o for o in (spec.get("options") or []) if o not in NOOP_OPTIONS})
88
+ + variants = sorted(spec.get("variants") or [])
89
+ + # BUG (intentional): the target-profile field is dropped -> different targets collide.
90
+ + canon = {
91
+ + "source": source,
92
+ + "toolchain": toolchain,
93
+ + "options": options,
94
+ + "variants": variants,
95
+ + }
96
+ + return _fnv1a_64(json.dumps(canon, sort_keys=True, separators=(",", ":"), default=repr))
tasks/kfc/jit-source-arch-cache-key/task/solution/oracle.patch ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/identity_key.py b/identity_key.py
2
+ index 9e2a701..2f759db 100644
3
+ --- a/identity_key.py
4
+ +++ b/identity_key.py
5
+ @@ -1,43 +1,25 @@
6
+ -"""Stable identity for a build-spec.
7
+ -
8
+ -Public entry point:
9
+ - ``identity_key(spec: dict) -> str``
10
+ -
11
+ -A downstream stage keeps a table of already-produced *identities* and skips the
12
+ -expensive step for a build-spec whose identity it has already seen. So the identity
13
+ -must satisfy two properties:
14
+ -
15
+ -* two specs that are **equivalent** (they describe the same build, differing only in
16
+ - incidental spelling) should map to the **same** identity, and
17
+ -* two specs that are **genuinely different** must map to **different** identities -- a
18
+ - collision between two different specs would let the wrong prior artifact be reused,
19
+ - which is never acceptable.
20
+ -
21
+ -Build-spec shape
22
+ -----------------
23
+ -A spec is a mapping with:
24
+ -
25
+ -* ``"source"``: the source text (a string).
26
+ -* ``"target"``: the target-profile tag (a string) the artifact is produced for.
27
+ -* ``"options"`` (optional): a list of build-option tokens (an unordered set).
28
+ -* ``"toolchain"`` (optional): the toolchain-version tag (a string).
29
+ -* ``"variants"`` (optional): a list of requested variant names (an unordered set).
30
+ -* ``"build"`` (optional): a mapping of incidental build annotations.
31
+ -
32
+ -This starting implementation is **correct but conservative**: it derives the identity
33
+ -from the spec almost verbatim (only the field order of a mapping is neutralized). It
34
+ -never merges two different specs, but specs that are merely spelled differently are
35
+ -treated as separate identities, so the downstream table holds more entries than there
36
+ -are truly distinct builds and the expensive step is repeated once per spelling.
37
+ -Reducing the number of distinct identities -- without ever merging two genuinely
38
+ -different specs -- is the goal.
39
+ +"""Oracle for jit-source-arch-cache-key (reviewer-only; NOT baked in image).
40
+ +
41
+ +Full canonicalization: normalize the source text (strip comments, collapse whitespace),
42
+ +canonicalize the option set (drop no-op defaults, de-duplicate, sort for order-freedom),
43
+ +sort the requested variant set, drop the incidental build annotations, and KEEP every
44
+ +binary-affecting field (source, target profile, effective options, toolchain tag,
45
+ +variant set). Equivalent spellings collapse to one identity, so the number of distinct
46
+ +identities over the labeled workload equals the number of true equivalence classes
47
+ +(12) -- the fewest possible. speedup = baseline_recompiles / oracle_recompiles
48
+ +(~48 / ~12 = ~4.0). Never merges two genuinely different specs -- in particular two
49
+ +specs that differ only in target profile keep distinct identities.
50
+ """
51
+
52
+ import json
53
+ +import re
54
+ +
55
+ +_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
56
+ +_LINE_COMMENT = re.compile(r"//[^\n]*")
57
+ +NOOP_OPTIONS = {"o0", "dbgoff", "std0"}
58
+
59
+
60
+ def _fnv1a_64(text):
61
+ - """Deterministic 64-bit FNV-1a digest of ``text`` (fixed, not process-salted)."""
62
+ h = 0xCBF29CE484222325
63
+ for byte in text.encode("utf-8"):
64
+ h ^= byte
65
+ @@ -45,13 +27,23 @@ def _fnv1a_64(text):
66
+ return format(h, "016x")
67
+
68
+
69
+ +def _canon_source(text):
70
+ + text = _BLOCK_COMMENT.sub(" ", text or "")
71
+ + text = _LINE_COMMENT.sub(" ", text)
72
+ + return " ".join(text.split())
73
+ +
74
+ +
75
+ def identity_key(spec):
76
+ - """Return a stable string identity for ``spec``.
77
+ -
78
+ - Conservative baseline: serialize the spec with a fixed field order and digest it.
79
+ - Only mapping-field order is neutralized; every other incidental difference (source
80
+ - comments/whitespace, option order, redundant no-op options, annotation fields)
81
+ - still yields a new identity.
82
+ - """
83
+ - text = json.dumps(spec, sort_keys=True, separators=(",", ":"), default=repr)
84
+ - return _fnv1a_64(text)
85
+ + source = _canon_source(spec.get("source", ""))
86
+ + target = spec.get("target")
87
+ + toolchain = spec.get("toolchain")
88
+ + options = sorted({o for o in (spec.get("options") or []) if o not in NOOP_OPTIONS})
89
+ + variants = sorted(spec.get("variants") or [])
90
+ + canon = {
91
+ + "source": source,
92
+ + "target": target,
93
+ + "toolchain": toolchain,
94
+ + "options": options,
95
+ + "variants": variants,
96
+ + }
97
+ + return _fnv1a_64(json.dumps(canon, sort_keys=True, separators=(",", ":"), default=repr))
tasks/kfc/jit-source-arch-cache-key/task/solution/solve.sh ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # solution/solve.sh — kfc/jit-source-arch-cache-key
3
+ # 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量
4
+ # 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。
5
+ #
6
+ # oracle 形态 : 补丁式(patch)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_PATCH 槽位:
7
+ # git -C "$REPO" apply -p1 "$KERNELBENCH_ORACLE_PATCH"
8
+ # 产物(reviewer-only;本脚本只读,一个字节都不改):
9
+ # solution/baseline2.patch, solution/negative.patch, solution/oracle.patch
10
+ # $REPO : /app/repo (tests/test.sh: REPO=/app/repo)
11
+ # 被计分单元 : /app/repo/identity_key.py
12
+ # 来源:tests/test.sh 的 CAND_FILE="$REPO/identity_key.py"
13
+ # 落地方式 : git -C $REPO apply -p1 <patch> —— 只改工作树,不 commit
14
+ #
15
+ # 🔴 为什么绝不 commit(规范 H3):判分读**工作树** —— `git status --porcelain` 是 scope
16
+ # 硬闸门,`git checkout -q HEAD -- <scope>` 取基线,且镜像自证 /app/repo 的 HEAD 恰好
17
+ # 只有 1 个 commit(那就是挖洞基线)。一旦 commit,HEAD 前移 → 闸门看不到改动、
18
+ # `checkout HEAD -- scope` 把 candidate 当成基线 → 正确解被判 0。
19
+ # 本脚本落地后会自己断言 HEAD 与 commit 数没变。
20
+ #
21
+ # ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)────────────────────────
22
+ # PKG=<fai_bench>/tasks/kfc/jit-source-arch-cache-key/task
23
+ # IMG=fai/kfc-jit-source-arch-cache-key:oss
24
+ # # 1) 起容器。判分容器始终 --network=none;tests/ 和 solution/ 都**没有**烤进镜像
25
+ # # (Dockerfile 里没有一条 COPY 取它们),所以这两个目录必须挂进来。
26
+ # # 该题 task.toml 声明 gpus=0;锚点的标定硬件/运行栈见 tests/ref_speedup.caveat.md
27
+ # docker run -d --name kfc-solve --network=none \
28
+ # -v "$PKG/tests":/tests -v "$PKG/solution":/solution "$IMG"
29
+ # # 2) 落地参考实现到工作树(本脚本;不 commit)
30
+ # docker exec kfc-solve bash /solution/solve.sh
31
+ # # 3) 判分。KERNELBENCH_VERIFY_MODE 必须留在默认的 candidate —— 这就是 agent 的
32
+ # # 真实评分路径;设成 oracle/negative 会让 test.sh 自己再落地一遍,绕过本脚本。
33
+ # docker exec -e KERNELBENCH_VERIFY_MODE=candidate kfc-solve bash /tests/test.sh
34
+ # docker exec kfc-solve cat /logs/verifier/reward.json # 判分结果
35
+ # docker rm -f kfc-solve
36
+ #
37
+ # 期望:oracle → 性能题得 0(它就是锚点本身; min(1, ln(speedup/ref_speedup)/ln(ref_speedup))(speedup ≤ ref_speedup 时为 0)
38
+ # 在 speedup≈ref_speedup 处 = 0 —— 打平 oracle 不得分,必须超过。
39
+ # 所以"oracle 跑对了"的判据不是 reward>0,而是 speedup≈ref_speedup 且
40
+ # hard_fail_reasons 为空;实现类二值题 = 1.0 —— 权威公式是
41
+ # tests/test.sh 写出的 reward_formula 字段);--negative → 0;
42
+ # --noop(在纯净容器里)→ 0(挖洞基线过不了正确性门)。
43
+ # 本题带 loop16 harness:`bash /opt/loop/submit.sh` 判的也是同一棵工作树、
44
+ # 同样走 candidate 模式(口径一致),所以落地后直接自评也成立。
45
+ # ──────────────────────────────────────────────────────────────────────────
46
+ #
47
+ # 用法(规范 2 的统一 CLI):
48
+ # bash solution/solve.sh # 落地 oracle(参考实现)
49
+ # bash solution/solve.sh --negative # 落地 negative(已知坏例,必须得 0)
50
+ # bash solution/solve.sh --baseline2 # 落地 baseline2(中间基线)
51
+ # bash solution/solve.sh --noop # 把可编辑面复位到烤入基线(对照组)
52
+ #
53
+ # --noop 语义:把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 ——
54
+ # `git checkout HEAD -- <scope>`,HEAD 不动),使对照组能量到真正的 no-op 值。
55
+ # runner 在同一个容器里连着跑 oracle → noop 做对照时,靠它把上一轮落地归零。
56
+ #
57
+ # 幂等:每次落地前先把被计分单元 `git checkout HEAD --` 复位,重复执行结果一致。
58
+ # 失败一律非 0 退出并打印原因(补丁打不上 / 变体文件缺失 / scope 路径不存在 / HEAD 被移动)。
59
+ set -uo pipefail
60
+
61
+ TASK_ID="jit-source-arch-cache-key"
62
+ REPO="${KFC_REPO_DIR:-/app/repo}"
63
+ SCOPE=("identity_key.py")
64
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
65
+
66
+ say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; }
67
+ die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; }
68
+ # 每次调用单独带 safe.directory,不去改容器里的全局 gitconfig
69
+ GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; }
70
+
71
+ usage(){ cat <<'USAGE'
72
+ usage: bash solve.sh [--oracle | --negative | --baseline2 | --noop]
73
+ (无参数) 落地 oracle 参考实现(oracle.patch)
74
+ --negative 落地 negative 已知坏���(negative.patch)
75
+ --baseline2 落地 baseline2 中间基线(baseline2.patch)
76
+ --noop 把可编辑面复位到烤入基线(与 verifier 取基线一致,HEAD 不动)
77
+ USAGE
78
+ }
79
+
80
+ WHICH=oracle
81
+ case "${1:-}" in
82
+ ""|--oracle) WHICH=oracle ;;
83
+ --negative) WHICH=negative ;;
84
+ --baseline2) WHICH=baseline2 ;;
85
+ --noop) WHICH=noop ;;
86
+ -h|--help) usage; exit 0 ;;
87
+ *) usage >&2; die "未知参数 '$1'" ;;
88
+ esac
89
+
90
+ # ---- 产物定位:脚本同目录优先,其次容器里的常见挂载点 ----
91
+ artifact(){
92
+ local n="$1" c
93
+ for c in "$HERE/$n" "/solution/$n" "${KFC_SOLUTION_DIR:-/nonexistent}/$n"; do
94
+ [ -f "$c" ] && { printf '%s\n' "$c"; return 0; }
95
+ done
96
+ return 1
97
+ }
98
+
99
+ case "$WHICH" in
100
+ noop) ART="" ;;
101
+ oracle) ART="oracle.patch" ;;
102
+ negative) ART="negative.patch" ;;
103
+ baseline2) ART="baseline2.patch" ;;
104
+ *) die "本题没有 $WHICH 变体(solution/ 里只有:oracle.patch, negative.patch, baseline2.patch)" ;;
105
+ esac
106
+
107
+ # ---- 环境前置检查 ----
108
+ GIT rev-parse --git-dir >/dev/null 2>&1 \
109
+ || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)"
110
+ for s in "${SCOPE[@]}"; do
111
+ [ -e "$REPO/$s" ] || die "被计分单元不存在:$REPO/$s(REPO 不对?可用 KFC_REPO_DIR 覆盖)"
112
+ done
113
+ HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD"
114
+ N_BEFORE="$(GIT rev-list --count HEAD)"
115
+
116
+ if [ "$WHICH" = noop ]; then
117
+ # --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— `git checkout HEAD -- <scope>`,
118
+ # HEAD 不动),使对照组能量到真正的 no-op 值。runner 在同一个容器里连着跑 oracle → noop 时靠它归零。
119
+ DIRTY_BEFORE="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')"
120
+ GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})"
121
+ DIRTY_AFTER="$(GIT status --porcelain -- "${SCOPE[@]}" | sed '/^$/d')"
122
+ if [ -n "$DIRTY_AFTER" ]; then
123
+ printf '%s\n' "$DIRTY_AFTER" | sed "s|^|[solve.sh $TASK_ID] |" >&2
124
+ die "复位后被计分单元仍不干净(见上)—— 量不到真正的 no-op 值"
125
+ fi
126
+ [ "$HEAD_BEFORE" = "$(GIT rev-parse HEAD)" ] || die "HEAD 被移动了,判分会把 candidate 当基线"
127
+ [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线"
128
+ if [ -n "$DIRTY_BEFORE" ]; then
129
+ say "--noop:已把可编辑面复位到烤入基线;原先这些是脏的:"
130
+ printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |"
131
+ else
132
+ say "--noop:可编辑面本来就是干净的烤入基线,无需复位"
133
+ fi
134
+ say "--noop 完成:${SCOPE[*]} = 烤入基线(HEAD 未动 @ ${HEAD_BEFORE:0:12})"
135
+ exit 0
136
+ fi
137
+
138
+ PATCH="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)"
139
+
140
+ # ---- 幂等:先把被计分单元退回挖洞基线,再打补丁(否则二次 apply 必然失败) ----
141
+ GIT checkout -q HEAD -- "${SCOPE[@]}" || die "复位被计分单元失败(${SCOPE[*]})"
142
+ GIT apply -p1 --check "$PATCH" \
143
+ || die "补丁打不上:$PATCH —— 挖洞树与该补丁不匹配,或工作树被别的改动污染了"
144
+ GIT apply -p1 "$PATCH" || die "git apply 失败:$PATCH"
145
+
146
+ # ---- 硬要求:HEAD 一步都不能动(规范 H3) ----
147
+ HEAD_AFTER="$(GIT rev-parse HEAD)"
148
+ [ "$HEAD_BEFORE" = "$HEAD_AFTER" ] || die "HEAD 被移动了($HEAD_BEFORE -> $HEAD_AFTER),判分会把 candidate 当基线"
149
+ [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线"
150
+
151
+ say "已落地 $WHICH:$(basename "$PATCH") -> ${SCOPE[*]}(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})"
152
+ GIT status --porcelain -- "${SCOPE[@]}" | sed "s|^|[solve.sh $TASK_ID] |"
153
+
154
+ # ---- 顺手体检 scope 闸门:工作树里除了被计分单元不该有别的改动 ----
155
+ STRAY="$(GIT status --porcelain | awk '{print $NF}' \
156
+ | grep -v -e '__pycache__' -e '\.pyc$' -e '^identity_key\.py$' || true)"
157
+ [ -z "$STRAY" ] || { say "⚠ 工作树里还有 scope 外的改动,判分会 out_of_scope_edit 直接归 0:"; \
158
+ printf '%s\n' "$STRAY" | sed "s|^|[solve.sh $TASK_ID] |"; }
159
+ exit 0
tasks/kfc/jit-source-arch-cache-key/task/task.toml ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "2.0"
2
+
3
+ # 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1)
4
+ artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"]
5
+
6
+ [task]
7
+ id = "jit-source-arch-cache-key"
8
+ bench = "kfc"
9
+ kind = "performance"
10
+ language = "python"
11
+ title = "You are working on the work-reuse layer of a batch build service."
12
+ instruction = "instruction.md"
13
+
14
+ [agent]
15
+ timeout_sec = 21600
16
+
17
+ # carved-tree provenance (environment/repo/ recovered from): <internal registry>/kernelbench/insea-jit-source-arch-cache-key-loop16:loop-20260721T021500Z@sha256:b6e1405e15730a4d2605a010e43a832c62e79d533833700356bd01e7e77fea6d
18
+ # Open-source build: `cd <this dir> && docker build -f environment/Dockerfile -t fai/kfc-jit-source-arch-cache-key:oss .`
19
+ [environment]
20
+ docker_image = "fai/kfc-jit-source-arch-cache-key:oss"
21
+ dockerfile = "environment/Dockerfile"
22
+ build_timeout_sec = 3600
23
+ cpus = 8
24
+ memory_mb = 16000
25
+ gpus = 0
26
+ allow_internet = false
27
+
28
+ [verifier]
29
+ entrypoint = "tests/test.sh"
30
+ mode = "shared"
31
+ timeout_sec = 3600
32
+ task_kind = "acceleration"
33
+ contract_pattern = "A"
34
+ timing_metric = "recompile_count"
35
+ candidate_source_root = "/app/repo"
36
+ primary_edit_paths = ["/app/repo/identity_key.py"]
37
+ forbidden_edit_paths = ["/app/repo/tests/**", "/opt/verifier-*", "/tests/**", "/opt/loop/**"]
38
+ result_paths = [
39
+ "/logs/verifier/verifier_state.json",
40
+ "/logs/verifier/correctness_results.json",
41
+ "/logs/verifier/benchmark_results.json",
42
+ "/logs/verifier/reward.json",
43
+ "/logs/verifier/reward.txt",
44
+ ]
45
+
46
+ [primary_metric]
47
+ name = "buildspec_identity_recompile_count_speedup"
48
+ goal = "maximize"
49
+ metric_kind = "recompile_count"
50
+ 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."
51
+ ref_speedup = 4.0
52
+ ref_speedup_source = "tests/ref_speedup.txt"
53
+ calibrated_on = "Intel Sapphire Rapids CPU lane"
54
+ correctness_gates = [
55
+ "hidden_case_suite",
56
+ "returns_string_for_various",
57
+ "deterministic_repeat_same_object",
58
+ "deterministic_fresh_build",
59
+ "distinct_source_distinct_keys",
60
+ "distinct_target_distinct_keys",
61
+ "distinct_effective_option_distinct_keys",
62
+ "distinct_option_value_distinct_keys",
63
+ "distinct_toolchain_distinct_keys",
64
+ "distinct_variant_set_distinct_keys",
65
+ "no_false_merge_full_workload",
66
+ "handles_edge_schema",
67
+ "many_distinct_specs_pairwise_distinct",
68
+ "candidate_false_merge",
69
+ "anti_cheat_forbidden_edit",
70
+ "forbidden_framework_or_harness_reference",
71
+ ]
72
+
73
+ [loop]
74
+ min_submissions = 1
75
+ max_submissions = 1
76
+ submit = "bash /opt/loop/submit.sh"
77
+ mode = "baked"
78
+ feedback_surface = "/opt/loop/submit.sh"
79
+ # single-submission — min=max=1; the first
80
+ # `bash /opt/loop/submit.sh` IS the final graded submission (submit == finalize).
81
+ declared_submission_policy = "single_submission"
tasks/kfc/jit-source-arch-cache-key/task/tests/compute_reward.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Canonical kernelbench reward writer (task-agnostic; do NOT special-case a task here).
3
+
4
+ Reward definition:
5
+
6
+ performance (acceleration):
7
+ reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0
8
+ -> matching the oracle (speedup == ref_speedup) scores 0.5
9
+ -> reaching ref_speedup**2 caps at 1.0
10
+ value range is strictly [0.0, 1.0]
11
+ HARD PRE-GATES (any one hit => reward 0, the formula is never evaluated):
12
+ build/import failure, ANY correctness case fail, cheating, forbidden
13
+ edit path, speedup <= 1, ref_speedup <= 1.
14
+ implementation (correctness):
15
+ reward = 1.0 iff EVERY test case passes and no cheating, else 0.0 (binary).
16
+
17
+ Reads: /logs/verifier/verifier_state.json, /logs/verifier/benchmark_results.json
18
+ Writes: /logs/verifier/reward.json, /logs/verifier/reward.txt
19
+ """
20
+ import json, math
21
+ from pathlib import Path
22
+
23
+ LOG = Path("/logs/verifier")
24
+ STATE = LOG / "verifier_state.json"
25
+ BENCH = LOG / "benchmark_results.json"
26
+ REWARD = LOG / "reward.json"
27
+ TEXT = LOG / "reward.txt"
28
+
29
+ # Every gate below is a HARD gate: build/import origin, correctness (visible AND
30
+ # hidden), baseline sanity, benchmark validity, anti-cheat / forbidden-path.
31
+ GATES = [
32
+ "correctness_ok",
33
+ "trusted_restore_ok",
34
+ "hidden_correctness_ok",
35
+ "baseline_ok",
36
+ "benchmark_ok",
37
+ "anti_cheat_ok",
38
+ ]
39
+
40
+
41
+ def read_json(path, default):
42
+ try:
43
+ return json.loads(path.read_text(encoding="utf-8"))
44
+ except Exception:
45
+ return default
46
+
47
+
48
+ def _case_counts(state, bench):
49
+ """(passed, total) test cases when the verifier reports them; else (None, None)."""
50
+ exp = state.get("expected_case_count")
51
+ act = state.get("actual_case_count")
52
+ try:
53
+ exp = int(exp); act = int(act)
54
+ except Exception:
55
+ return (None, None)
56
+ if exp <= 0:
57
+ return (None, None)
58
+ return (act, exp)
59
+
60
+
61
+ def main():
62
+ LOG.mkdir(parents=True, exist_ok=True)
63
+ state = read_json(STATE, {})
64
+ bench = read_json(BENCH, {})
65
+ hard = list(state.get("hard_fail_reasons") or [])
66
+ task_kind = state.get("task_kind") or bench.get("task_kind") or "acceleration"
67
+ gates_ok = all(bool(state.get(g)) for g in GATES)
68
+
69
+ passed, total = _case_counts(state, bench)
70
+ # A short test suite is a correctness FAIL, not a partial credit: reward.md
71
+ # requires EVERY case to pass (implementation) / no case to fail (performance).
72
+ all_cases_ok = True
73
+ if passed is not None and total is not None and passed < total:
74
+ all_cases_ok = False
75
+ if not any("case" in str(h) or "correctness" in str(h) for h in hard):
76
+ hard.append("correctness_cases_incomplete")
77
+
78
+ speedup = ref = 1.0
79
+ reward = 0.0
80
+
81
+ if task_kind == "correctness":
82
+ # ---- implementation class: BINARY. All cases pass + no cheating -> 1.0, else 0.0.
83
+ reward = 1.0 if (gates_ok and all_cases_ok and not hard) else 0.0
84
+ if reward == 0.0 and not hard:
85
+ hard.append("correctness_or_validation_incomplete")
86
+ else:
87
+ # ---- performance class: log-ratio reward, behind the hard pre-gates.
88
+ try:
89
+ speedup = float(bench.get("aggregate_speedup") or bench.get("primary_metric_value") or 1.0)
90
+ ref = float(bench.get("ref_speedup") or bench.get("reference_metric_value") or 1.0)
91
+ except Exception:
92
+ speedup = ref = 1.0
93
+ hard.append("invalid_primary_metric_value")
94
+
95
+ if not (math.isfinite(speedup) and speedup > 0.0):
96
+ hard.append("invalid_primary_metric_value")
97
+ # pre-gate 5: the candidate must actually beat the baseline
98
+ elif speedup <= 1.0:
99
+ hard.append("speedup_not_above_baseline")
100
+ # pre-gate 6: the reference anchor must be a real speedup
101
+ if not (math.isfinite(ref) and ref > 1.0):
102
+ hard.append("ref_speedup_invalid")
103
+
104
+ if gates_ok and all_cases_ok and not hard:
105
+ reward = min(1.0, max(0.0, min(1.0, math.log(speedup) / math.log(ref) - 1.0)))
106
+ # value range is strictly [0.0, 1.0]
107
+ reward = max(0.0, min(1.0, reward))
108
+ else:
109
+ reward = 0.0
110
+ if not hard:
111
+ hard.append("validation_incomplete_or_bad_speedup")
112
+
113
+ out = {
114
+ "schema_version": "kernelbench_reward_v2_logratio",
115
+ # reward.md result-JSON field: "performance" | "implementation"
116
+ "task_type": "implementation" if task_kind == "correctness" else "performance",
117
+ "task_kind": task_kind,
118
+ "reward": reward,
119
+ "speedup": speedup,
120
+ "ref_speedup": ref,
121
+ "reward_formula": ("binary: 1.0 iff all cases pass and no cheating, else 0.0"
122
+ if task_kind == "correctness"
123
+ 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"),
124
+ "actual_hardware_type": state.get("actual_hardware_type", "") or bench.get("actual_hardware_type", ""),
125
+ "hard_fail_reasons": hard,
126
+ "state_path": str(STATE),
127
+ "benchmark_path": str(BENCH),
128
+ }
129
+ # reward.md result-JSON contract: performance always carries `cv`,
130
+ # implementation always carries `tests{passed,total}`.
131
+ if out["task_type"] == "performance":
132
+ out["cv"] = bench.get("cv") # None when this harness does not measure dispersion
133
+ if passed is not None and total is not None:
134
+ out["tests"] = {"passed": passed, "total": total}
135
+ else:
136
+ out["tests"] = ({"passed": passed, "total": total}
137
+ if (passed is not None and total is not None)
138
+ else {"passed": 0 if hard else 1, "total": 1})
139
+ REWARD.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n", encoding="utf-8")
140
+ TEXT.write_text(f"{reward}\n", encoding="utf-8")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
tasks/kfc/jit-source-arch-cache-key/task/tests/count_bench.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distinct-identity count for the build-spec identity task.
2
+
3
+ The metric is a deterministic count: over a fixed labeled workload of build-specs,
4
+ how many DISTINCT identities does a module's ``identity_key`` produce? A conservative
5
+ identity treats every incidental spelling as different and emits many identities; a
6
+ normalizing identity collapses the equivalent spellings of each class down toward the
7
+ number of true classes. The score is the ratio baseline_count / candidate_count, so
8
+ fewer identities (for the same workload) is better -- but only while no two
9
+ genuinely-different specs share an identity.
10
+
11
+ Invoked one MODE per process. ``test.sh`` runs candidate and the frozen baseline and
12
+ takes the ratio. No profiler / no numerics library -- it is a pure count.
13
+
14
+ Modes:
15
+ candidate count distinct identities from /app/repo/identity_key.py; print COUNT=<n>
16
+ baseline same, using the frozen baseline module (KB_BASELINE_MODULE)
17
+ verify (safety) confirm the candidate NEVER gives two different-class specs
18
+ the same identity; print VERIFY_OK / VERIFY_FAIL
19
+ """
20
+
21
+ import os
22
+ import sys
23
+
24
+ from kb_identity_harness import (
25
+ build_labeled_workload,
26
+ count_distinct_keys,
27
+ find_false_merges,
28
+ load_candidate,
29
+ load_module,
30
+ true_class_count,
31
+ )
32
+
33
+
34
+ def _baseline_module():
35
+ path = os.environ.get("KB_BASELINE_MODULE", "/opt/verifier-baseline/identity_key.py")
36
+ return load_module(path)
37
+
38
+
39
+ def mode_candidate():
40
+ workload = build_labeled_workload()
41
+ print(f"COUNT={count_distinct_keys(load_candidate(), workload)}")
42
+ return 0
43
+
44
+
45
+ def mode_baseline():
46
+ workload = build_labeled_workload()
47
+ print(f"COUNT={count_distinct_keys(_baseline_module(), workload)}")
48
+ return 0
49
+
50
+
51
+ def mode_verify():
52
+ workload = build_labeled_workload()
53
+ classes = true_class_count(workload)
54
+ cand = load_candidate()
55
+ base = _baseline_module()
56
+
57
+ cand_bad = find_false_merges(cand, workload)
58
+ if cand_bad:
59
+ sample = sorted((sorted(v), k) for k, v in cand_bad.items())[:3]
60
+ print(f"VERIFY_FAIL candidate false-merges distinct classes: {sample}")
61
+ return 1
62
+ # sanity: the frozen baseline must itself be false-merge free.
63
+ base_bad = find_false_merges(base, workload)
64
+ if base_bad:
65
+ print(f"VERIFY_FAIL baseline unexpectedly false-merges: {sorted(base_bad.values())[:3]}")
66
+ return 1
67
+
68
+ cand_count = count_distinct_keys(cand, workload)
69
+ base_count = count_distinct_keys(base, workload)
70
+ # work-evidence: the baseline emits (base_count - classes) identities more than
71
+ # there are true classes; a full normalizer removes those redundant identities.
72
+ redundant = base_count - classes
73
+ print(f"VERIFY_OK signatures={len(workload)} true_classes={classes} "
74
+ f"candidate_identities={cand_count} baseline_identities={base_count} "
75
+ f"baseline_redundant_identities={redundant}")
76
+ return 0
77
+
78
+
79
+ MODES = {"candidate": mode_candidate, "baseline": mode_baseline, "verify": mode_verify}
80
+
81
+
82
+ def main():
83
+ mode = sys.argv[1] if len(sys.argv) > 1 else "candidate"
84
+ fn = MODES.get(mode)
85
+ if fn is None:
86
+ print(f"unknown mode {mode!r}; expected one of {sorted(MODES)}")
87
+ sys.exit(2)
88
+ sys.exit(fn())
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
tasks/kfc/jit-source-arch-cache-key/task/tests/kb_identity_harness.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared harness for the build-spec identity task (CPU, pure Python).
2
+
3
+ Provides: the candidate loader, the equivalence-rule tables (source normalization,
4
+ no-op option tokens), a deterministic *labeled* workload of build-specs grouped into
5
+ true equivalence classes, and helpers that turn a candidate ``identity_key`` into a
6
+ partition of that workload so the verifier can count distinct identities and detect a
7
+ false merge (two genuinely-different specs sharing an identity). Standard library
8
+ only, so the metric -- the number of distinct identities produced over the workload --
9
+ is a deterministic count that is identical on any machine.
10
+
11
+ The ground truth is the class LABEL attached to every spec when the workload is built:
12
+ two specs share a class iff they were generated as equivalent spellings of the same
13
+ base. candidate / baseline / oracle are all judged against these labels, never against
14
+ each other.
15
+ """
16
+
17
+ import hashlib
18
+ import importlib.util
19
+ import os
20
+ import re
21
+
22
+
23
+ # --------------------------------------------------------------------------- #
24
+ # Equivalence rules (also disclosed to the solver in instruction.md).
25
+ # --------------------------------------------------------------------------- #
26
+ # Source text: comments and surrounding whitespace do not change the built artifact,
27
+ # so they are incidental. Everything else in the source text is meaningful.
28
+ _BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
29
+ _LINE_COMMENT = re.compile(r"//[^\n]*")
30
+
31
+ # Option tokens equal to a build default; each is equivalent to the token being absent.
32
+ NOOP_OPTIONS = {"o0", "dbgoff", "std0"}
33
+
34
+
35
+ def canon_source(text):
36
+ """Canonical form of a source text: strip comments, collapse whitespace runs."""
37
+ text = _BLOCK_COMMENT.sub(" ", text)
38
+ text = _LINE_COMMENT.sub(" ", text)
39
+ return " ".join(text.split())
40
+
41
+
42
+ def canon_options(options):
43
+ """Canonical option set: drop no-op defaults, de-duplicate, sort (order-free)."""
44
+ kept = {o for o in (options or []) if o not in NOOP_OPTIONS}
45
+ return sorted(kept)
46
+
47
+
48
+ def _with_line_comment(source):
49
+ return source + " // tuned build\n"
50
+
51
+
52
+ def _with_block_comment(source):
53
+ return "/* rev2 */\n" + source + "\n\n "
54
+
55
+
56
+ def repo_dir():
57
+ return os.environ.get("KB_REPO_DIR", "/app/repo")
58
+
59
+
60
+ def load_candidate():
61
+ """Import the candidate module from the repo under test."""
62
+ path = os.path.join(repo_dir(), "identity_key.py")
63
+ spec = importlib.util.spec_from_file_location("candidate_identity_key", path)
64
+ mod = importlib.util.module_from_spec(spec)
65
+ spec.loader.exec_module(mod)
66
+ if not hasattr(mod, "identity_key"):
67
+ raise AttributeError(f"{path} does not define identity_key")
68
+ return mod
69
+
70
+
71
+ def load_module(path):
72
+ # deterministic module name derived from the path (no salted builtin hash()).
73
+ digest = hashlib.sha1(path.encode("utf-8")).hexdigest()[:12]
74
+ spec = importlib.util.spec_from_file_location("kb_identity_mod_" + digest, path)
75
+ mod = importlib.util.module_from_spec(spec)
76
+ spec.loader.exec_module(mod)
77
+ return mod
78
+
79
+
80
+ # --------------------------------------------------------------------------- #
81
+ # Labeled workload: 12 true classes, each emitted as 4 equivalent spellings.
82
+ # Distinct classes differ in at least one meaning-bearing field (source text /
83
+ # target profile / effective option / toolchain tag / requested variant set).
84
+ # classes 0 and 1 differ ONLY in target profile -- a normalizer that drops the target
85
+ # merges them, which is a false merge (a wrong-target artifact would be reused).
86
+ # --------------------------------------------------------------------------- #
87
+ SRC_A = "o[i] = a[i] * b[i];"
88
+ SRC_B = "o[i] = a[i] + b[i];"
89
+ SRC_C = "o[i] = a[i] - b[i];"
90
+ SRC_D = "acc = acc + a[k] * b[k];"
91
+ SRC_E = "o[i] = a[i] > 0 ? a[i] : 0;"
92
+ SRC_F = "o[i] = a[i] / b[i];"
93
+
94
+ # base = (source, target, effective_options, toolchain, variants)
95
+ CLASS_BASES = [
96
+ (SRC_A, "p80", (), "v1", ()), # 0 (target-trap A)
97
+ (SRC_A, "p90", (), "v1", ()), # 1 (target-trap B: only target differs from 0)
98
+ (SRC_B, "p80", (), "v1", ()), # 2 distinct source
99
+ (SRC_C, "p80", (), "v1", ()), # 3
100
+ (SRC_C, "p80", ("fast",), "v1", ()), # 4 effective option vs 3
101
+ (SRC_D, "p80", ("o3",), "v1", ()), # 5
102
+ (SRC_D, "p80", ("o2",), "v1", ()), # 6 different effective option value vs 5
103
+ (SRC_D, "p80", ("o3",), "v2", ()), # 7 different toolchain tag vs 5
104
+ (SRC_E, "p80", (), "v1", ()), # 8
105
+ (SRC_E, "p80", (), "v1", ("kA",)), # 9 variant present vs 8
106
+ (SRC_E, "p80", (), "v1", ("kB", "kC")), # 10 different variant set vs 9
107
+ (SRC_F, "p86", ("fast", "o3"), "v1", ()), # 11 third target + two options
108
+ ]
109
+
110
+
111
+ def _spellings(base):
112
+ """Return four equivalent-but-differently-spelled specs for one class.
113
+
114
+ All four normalize to the same spec (they differ only in source comments/whitespace,
115
+ option order, redundant no-op options, incidental build annotations, and requested
116
+ variant order), yet all four are byte-distinct so a conservative identity produces
117
+ four identities.
118
+ """
119
+ source, target, options, toolchain, variants = base
120
+ opts = list(options)
121
+ vs = list(variants)
122
+
123
+ def build_spec(src, opt_list, build=None, var_list=None):
124
+ d = {"source": src, "target": target, "options": list(opt_list), "toolchain": toolchain}
125
+ if var_list:
126
+ d["variants"] = list(var_list)
127
+ if build is not None:
128
+ d["build"] = build
129
+ return d
130
+
131
+ # S0: canonical source, options sorted, variants sorted, no build annotations.
132
+ s0 = build_spec(source, sorted(opts), var_list=sorted(vs))
133
+ # S1: source carries a trailing line comment + reflowed spacing (ignored).
134
+ s1 = build_spec(_with_line_comment(source), sorted(opts), var_list=sorted(vs))
135
+ # S2: options in a different ORDER + a redundant no-op token; a non-semantic build
136
+ # annotation block; requested variants in a different order.
137
+ s2 = build_spec(source, list(reversed(opts)) + ["o0"],
138
+ build={"tmpdir": "/tmp/b_" + target, "ts": 1700000000},
139
+ var_list=list(reversed(vs)))
140
+ # S3: source with a block comment + extra newlines; options reversed with a DUPLICATE
141
+ # of the first option (when present) + a different no-op token; a different build.
142
+ dup = [opts[0]] if opts else []
143
+ s3 = build_spec(_with_block_comment(source), list(reversed(opts)) + dup + ["dbgoff"],
144
+ build={"tmpdir": "/tmp/x", "ts": 1700000001, "host": "node7"},
145
+ var_list=list(reversed(vs)))
146
+ return [s0, s1, s2, s3]
147
+
148
+
149
+ def build_labeled_workload():
150
+ """Deterministic list of ``(class_id, spec)`` pairs (48 = 12 classes x 4)."""
151
+ workload = []
152
+ for class_id, base in enumerate(CLASS_BASES):
153
+ for spec in _spellings(base):
154
+ workload.append((class_id, spec))
155
+ return workload
156
+
157
+
158
+ def true_class_count(workload):
159
+ return len({class_id for class_id, _ in workload})
160
+
161
+
162
+ # --------------------------------------------------------------------------- #
163
+ # Turn a candidate identity function into a partition of the workload.
164
+ # --------------------------------------------------------------------------- #
165
+ def key_to_classes(module, workload):
166
+ """Map each produced identity -> the set of true class ids that landed on it."""
167
+ mapping = {}
168
+ for class_id, spec in workload:
169
+ key = module.identity_key(spec)
170
+ mapping.setdefault(key, set()).add(class_id)
171
+ return mapping
172
+
173
+
174
+ def find_false_merges(module, workload):
175
+ """Return {identity: {class_ids}} for identities shared by >1 true class.
176
+
177
+ A non-empty result is a correctness failure: two genuinely different specs were
178
+ given the same identity.
179
+ """
180
+ return {k: v for k, v in key_to_classes(module, workload).items() if len(v) > 1}
181
+
182
+
183
+ def count_distinct_keys(module, workload):
184
+ """Number of distinct identities the candidate produces over the workload."""
185
+ return len({module.identity_key(spec) for _, spec in workload})
tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.caveat.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑)
2
+
3
+ `ref_speedup.txt` 里的 **4.0** 是 oracle 标定常量,判分时只读、不重跑 oracle:
4
+
5
+ reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0
6
+
7
+ `tests/test.sh` 的解析顺序是 **`tests/ref_speedup.txt` → `/opt/verifier-correctness-manifest.json` → 1.0**;
8
+ 回落到 1.0 会让所有 reward 归 0,所以这个文件必须存在且 > 1。
9
+
10
+ ## 标定条件
11
+
12
+ - 硬件:**the authoring CPU lane (Intel Sapphire Rapids)**
13
+ - 运行栈:`torch 2.7.0`(原始私有基座声明 torch 2.5.1/triton 3.1.0,任务 overlay 又 `pip install torch==2.7.0`,锚点即在 2.7.0 下标定)
14
+ - 线程:`OMP/MKL/OPENBLAS_NUM_THREADS=1`(计时稳定性的一部分,已写进镜像 ENV)
15
+
16
+ ## 硬件不一致时如何重标
17
+
18
+ verifier 原生支持模式分派,参考实现**按路径传入、从不烤进镜像**:
19
+
20
+ ```bash
21
+ docker run --rm -v "$PWD/tests:/tests:ro" -v "<放 oracle.patch 的目录>:/patches:ro" \
22
+ -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch \
23
+ fai/kfc-jit-source-arch-cache-key:oss bash /tests/test.sh
24
+ # 从 /logs/verifier/ 读实测 speedup(建议 >=3 次取中位数),写回 tests/ref_speedup.txt
25
+ ```
26
+
27
+ 自证:`noop`(不打补丁)应 ≈1.0 → 被门到 0;`negative`(`KERNELBENCH_NEGATIVE_PATCH=`)必须 0。
28
+
29
+ 参考实现:见本包 `solution/oracle.patch`(reviewer-only,已被 `.dockerignore` 排除,不进镜像)。
tasks/kfc/jit-source-arch-cache-key/task/tests/ref_speedup.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 4.0
tasks/kfc/jit-source-arch-cache-key/task/tests/test.sh ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Verifier for jit-source-arch-cache-key (stable identity for a build-spec).
3
+ # Pattern A, ACCELERATION lane. Deterministic value axis = recompile_count = number of
4
+ # DISTINCT identities produced over a fixed labeled workload of build-specs. speedup =
5
+ # baseline_recompiles / candidate_recompiles (= baseline_distinct_identities /
6
+ # candidate_distinct_identities). Pure-Python stdlib -> a plain count, no profiler
7
+ # needed. A false merge (two different-class specs sharing an identity -- e.g. two specs
8
+ # differing only in target profile) is a hard correctness failure -> reward 0.
9
+ # Modes: candidate|noop|oracle|negative
10
+ set -uo pipefail
11
+ # The harness may exec this in a NON-login shell; pin PATH so python3
12
+ # resolves regardless of the base's default profile.
13
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/bin:/usr/bin:/bin:$PATH
14
+ TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
15
+ REPO=/app/repo
16
+ LOG=/logs/verifier
17
+ mkdir -p "$LOG"
18
+ MODE="${KERNELBENCH_VERIFY_MODE:-candidate}"
19
+ CAND_FILE="$REPO/identity_key.py"
20
+ export KB_CANDIDATE_MODULE="$CAND_FILE"
21
+ export KB_BASELINE_MODULE=/opt/verifier-baseline/identity_key.py
22
+
23
+ HARD=(); add_hard(){ HARD+=("$1"); }
24
+ correctness_ok=true; trusted_restore_ok=true; hidden_correctness_ok=true
25
+ baseline_ok=true; benchmark_ok=true; anti_cheat_ok=true
26
+ expected_cases=12; actual_cases=0
27
+ speedup=1.0; ref_speedup=1.0; hw="cpu"; cand_keys=0; base_keys=0
28
+
29
+ cd "$REPO" 2>/dev/null || { add_hard "repo_missing"; correctness_ok=false; }
30
+
31
+ if [ "$MODE" = "oracle" ] && [ -n "${KERNELBENCH_ORACLE_PATCH:-}" ]; then
32
+ # reviewer-only mode: reset the working tree to the frozen baseline so several
33
+ # modes running back-to-back in one container session each start clean. candidate/noop
34
+ # NEVER resets (this branch is skipped for them), so a solver session is untouched.
35
+ git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
36
+ git -C "$REPO" apply "$KERNELBENCH_ORACLE_PATCH" 2>"$LOG/oracle_apply.log" || add_hard "oracle_apply_failed"
37
+ fi
38
+ if [ "$MODE" = "negative" ] && [ -n "${KERNELBENCH_NEGATIVE_PATCH:-}" ]; then
39
+ git -C "$REPO" checkout -- . 2>/dev/null || true; git -C "$REPO" clean -fdq 2>/dev/null || true
40
+ git -C "$REPO" apply "$KERNELBENCH_NEGATIVE_PATCH" 2>"$LOG/negative_apply.log" || true
41
+ fi
42
+
43
+ # anti-cheat: only identity_key.py may change
44
+ git -C "$REPO" status --porcelain 2>/dev/null | awk '{print $2}' > "$LOG/anti_cheat_changed_files.txt"
45
+ while IFS= read -r f; do
46
+ [ -z "$f" ] && continue
47
+ case "$f" in
48
+ identity_key.py) : ;;
49
+ *__pycache__*) : ;;
50
+ *) anti_cheat_ok=false; add_hard "forbidden_edit_path:$f" ;;
51
+ esac
52
+ done < "$LOG/anti_cheat_changed_files.txt"
53
+
54
+ # anti-cheat: the normalization must be implemented in plain Python. Forbid pulling
55
+ # in a tensor/graph framework or reading the hidden workload/reference harness.
56
+ 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
57
+ anti_cheat_ok=false; add_hard "forbidden_framework_or_harness_reference"
58
+ fi
59
+
60
+ # trusted restore: hidden suite ships in tests/ payload (fresh at scoring)
61
+ for f in test_identity_key.py count_bench.py kb_identity_harness.py; do
62
+ [ -f "$TESTS_DIR/$f" ] || { trusted_restore_ok=false; add_hard "hidden_supplement_missing:$f"; }
63
+ done
64
+
65
+ # ref_speedup: prefer the tests/-local override (uploaded fresh -> recalibrate without rebuild)
66
+ if [ -f "$TESTS_DIR/ref_speedup.txt" ]; then
67
+ ref_speedup=$(tr -dc '0-9.' < "$TESTS_DIR/ref_speedup.txt")
68
+ elif [ -f /opt/verifier-correctness-manifest.json ]; then
69
+ 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)
70
+ fi
71
+ hw="cpu:$(uname -m 2>/dev/null || echo unknown)"
72
+
73
+ # correctness gate (pure python; no GPU): stable string + no false merge properties.
74
+ if [ "$correctness_ok" = true ]; then
75
+ ( cd "$TESTS_DIR" && python3 test_identity_key.py ) > "$LOG/correctness.log" 2>&1
76
+ crc=$?
77
+ actual_cases=$(grep -cE '^CASE_PASS ' "$LOG/correctness.log" 2>/dev/null); actual_cases=${actual_cases:-0}
78
+ if [ "$crc" -ne 0 ] || [ "$actual_cases" -lt "$expected_cases" ]; then
79
+ hidden_correctness_ok=false; correctness_ok=false; add_hard "hidden_correctness_failed"
80
+ fi
81
+ fi
82
+
83
+ # benchmark: (1) confirm the candidate never gives two different-class signatures the
84
+ # same identity (safety), then (2) count distinct identities for candidate vs the
85
+ # frozen baseline over the fixed workload; speedup = base_keys / cand_keys.
86
+ parse_count(){ sed -n 's/^COUNT=//p' "$1" 2>/dev/null | head -1; }
87
+ if [ "$correctness_ok" = true ] && [ -f "$KB_BASELINE_MODULE" ]; then
88
+ ( cd "$TESTS_DIR" && python3 count_bench.py verify ) > "$LOG/verify.log" 2>&1
89
+ if [ $? -ne 0 ] || ! grep -q '^VERIFY_OK' "$LOG/verify.log"; then
90
+ benchmark_ok=false; add_hard "candidate_false_merge"
91
+ fi
92
+ if [ "$benchmark_ok" = true ]; then
93
+ ( cd "$TESTS_DIR" && python3 count_bench.py candidate ) > "$LOG/cand.out.log" 2>&1
94
+ ( cd "$TESTS_DIR" && python3 count_bench.py baseline ) > "$LOG/base.out.log" 2>&1
95
+ cand_keys=$(parse_count "$LOG/cand.out.log"); cand_keys=${cand_keys:-0}
96
+ base_keys=$(parse_count "$LOG/base.out.log"); base_keys=${base_keys:-0}
97
+ if [ -z "$cand_keys" ] || [ "$cand_keys" -le 0 ] 2>/dev/null || [ -z "$base_keys" ] || [ "$base_keys" -le 0 ] 2>/dev/null; then
98
+ benchmark_ok=false; add_hard "distinct_identity_count_unparsed"
99
+ else
100
+ speedup=$(python3 -c "print(f'{$base_keys/$cand_keys:.5f}')")
101
+ fi
102
+ fi
103
+ else
104
+ benchmark_ok=false
105
+ fi
106
+
107
+ HARD_JSON="[]"; if [ ${#HARD[@]} -gt 0 ]; then HARD_JSON=$(printf '"%s",' "${HARD[@]}"); HARD_JSON="[${HARD_JSON%,}]"; fi
108
+ DIAG_TAIL=""
109
+ if [ "$correctness_ok" = false ] && [ -f "$LOG/correctness.log" ]; then
110
+ DIAG_TAIL=$(tail -60 "$LOG/correctness.log" | sed 's/"/\\"/g' | tr '\n' '\t' | sed 's/\t/\\n/g')
111
+ fi
112
+ cat > "$LOG/verifier_state.json" <<JSON
113
+ {"schema_version":"kernelbench_verifier_state_v1","task_kind":"acceleration",
114
+ "correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,
115
+ "hidden_correctness_ok":$hidden_correctness_ok,"baseline_ok":$baseline_ok,
116
+ "benchmark_ok":$benchmark_ok,"anti_cheat_ok":$anti_cheat_ok,
117
+ "hard_fail_reasons":$HARD_JSON,
118
+ "expected_case_count":$expected_cases,"actual_case_count":$actual_cases,
119
+ "expected_benchmark_count":1,"actual_benchmark_count":1,
120
+ "actual_hardware_type":"$hw","mode":"$MODE",
121
+ "work_evidence_notes":["identity suite $actual_cases/$expected_cases ok","distinct identities candidate=$cand_keys baseline=$base_keys speedup=$speedup","correctness_tail:${DIAG_TAIL}"]}
122
+ JSON
123
+ cat > "$LOG/correctness_results.json" <<JSON
124
+ {"schema_version":"kernelbench_correctness_results_v1",
125
+ "suites":[{"name":"hidden-identity-suite","visibility_class":"hidden_supplement","expected_case_count":$expected_cases,"actual_case_count":$actual_cases,"passed":$actual_cases,"failed":$((expected_cases-actual_cases)),"hard_fail_reasons":$HARD_JSON}],
126
+ "correctness_ok":$correctness_ok,"trusted_restore_ok":$trusted_restore_ok,"hidden_correctness_ok":$hidden_correctness_ok}
127
+ JSON
128
+ cat > "$LOG/benchmark_results.json" <<JSON
129
+ {"schema_version":"kernelbench_benchmark_results_v1","task_kind":"acceleration","metric":"recompile_count",
130
+ "direction":"higher_is_better",
131
+ "workloads":[{"name":"buildspec-identity-count","speedup":$speedup,"candidate_recompiles":$cand_keys,"baseline_recompiles":$base_keys,"completion_counters":{"cases":"$actual_cases/$expected_cases"}}],
132
+ "aggregate_speedup":$speedup,"ref_speedup":$ref_speedup,"actual_hardware_type":"$hw"}
133
+ JSON
134
+ python3 "$TESTS_DIR/compute_reward.py" 2>/dev/null || python3 /tests/compute_reward.py 2>/dev/null || true
135
+ REW=$(tr -d '[:space:]' < "$LOG/reward.txt" 2>/dev/null)
136
+ 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"
137
+ [ -n "$REW" ] && exit 0 || exit 1
tasks/kfc/jit-source-arch-cache-key/task/tests/test_identity_key.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Correctness suite for the build-spec identity contract.
2
+
3
+ Each case prints "CASE_PASS <name>" or "CASE_FAIL <name>: <reason>". The runner counts
4
+ CASE_PASS lines. Pure standard library.
5
+
6
+ Every case tests a *safety* / determinism property that any acceptable identity must
7
+ satisfy: it returns a stable string, and it NEVER gives two genuinely-different specs
8
+ the same identity. (Collapsing equivalent spellings is rewarded by the distinct-identity
9
+ count, not gated here -- the conservative baseline, which collapses nothing, is still
10
+ correct.)
11
+ """
12
+
13
+ import sys
14
+ import traceback
15
+
16
+ from kb_identity_harness import (
17
+ build_labeled_workload,
18
+ find_false_merges,
19
+ load_candidate,
20
+ )
21
+
22
+ CASES = []
23
+
24
+
25
+ def case(fn):
26
+ CASES.append(fn)
27
+ return fn
28
+
29
+
30
+ def spec(source, target, options=None, toolchain="v1", variants=None, build=None):
31
+ d = {"source": source, "target": target, "toolchain": toolchain}
32
+ if options is not None:
33
+ d["options"] = list(options)
34
+ if variants is not None:
35
+ d["variants"] = list(variants)
36
+ if build is not None:
37
+ d["build"] = dict(build)
38
+ return d
39
+
40
+
41
+ def _key(mod, s):
42
+ k = mod.identity_key(s)
43
+ if not isinstance(k, str) or not k:
44
+ raise AssertionError(f"identity_key must return a non-empty str, got {k!r}")
45
+ return k
46
+
47
+
48
+ @case
49
+ def returns_string_for_various(mod):
50
+ samples = [
51
+ spec("o[i]=a[i]*b[i];", "p80"),
52
+ spec("o[i]=a[i]+b[i];", "p90", options=["fast"], variants=["kA"]),
53
+ spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2", build={"tmpdir": "/tmp/x"}),
54
+ {"source": "x=y;", "target": "p80"}, # minimal spec (no options/toolchain/variants/build)
55
+ ]
56
+ for s in samples:
57
+ _key(mod, s)
58
+
59
+
60
+ @case
61
+ def deterministic_repeat_same_object(mod):
62
+ s = spec("o[i]=a[i]*b[i];", "p80", options=["o3"])
63
+ if _key(mod, s) != _key(mod, s):
64
+ raise AssertionError("identity not stable across repeated calls on the same object")
65
+
66
+
67
+ @case
68
+ def deterministic_fresh_build(mod):
69
+ a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"])
70
+ b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], variants=["kA"])
71
+ if _key(mod, a) != _key(mod, b):
72
+ raise AssertionError("two independently built identical specs got different identities")
73
+
74
+
75
+ @case
76
+ def distinct_source_distinct_keys(mod):
77
+ a = spec("o[i]=a[i]*b[i];", "p80")
78
+ b = spec("o[i]=a[i]+b[i];", "p80")
79
+ if _key(mod, a) == _key(mod, b):
80
+ raise AssertionError("different source text collided")
81
+
82
+
83
+ @case
84
+ def distinct_target_distinct_keys(mod):
85
+ # same source + options + toolchain, different target profile -> a different artifact.
86
+ a = spec("o[i]=a[i]*b[i];", "p80", options=["o3"])
87
+ b = spec("o[i]=a[i]*b[i];", "p90", options=["o3"])
88
+ if _key(mod, a) == _key(mod, b):
89
+ raise AssertionError("specs for different target profiles collided (target dropped?)")
90
+
91
+
92
+ @case
93
+ def distinct_effective_option_distinct_keys(mod):
94
+ a = spec("o[i]=a[i]*b[i];", "p80", options=["fast"])
95
+ b = spec("o[i]=a[i]*b[i];", "p80", options=[])
96
+ if _key(mod, a) == _key(mod, b):
97
+ raise AssertionError("an effective (non-default) option was ignored")
98
+
99
+
100
+ @case
101
+ def distinct_option_value_distinct_keys(mod):
102
+ a = spec("acc+=a[k]*b[k];", "p80", options=["o3"])
103
+ b = spec("acc+=a[k]*b[k];", "p80", options=["o2"])
104
+ if _key(mod, a) == _key(mod, b):
105
+ raise AssertionError("two different option values were merged")
106
+
107
+
108
+ @case
109
+ def distinct_toolchain_distinct_keys(mod):
110
+ a = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v1")
111
+ b = spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2")
112
+ if _key(mod, a) == _key(mod, b):
113
+ raise AssertionError("different toolchain tags were merged (a stale artifact would be reused)")
114
+
115
+
116
+ @case
117
+ def distinct_variant_set_distinct_keys(mod):
118
+ a = spec("o[i]=a[i]>0?a[i]:0;", "p80") # no variants
119
+ b = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]) # one variant
120
+ c = spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kB", "kC"]) # a different variant set
121
+ keys = {_key(mod, a), _key(mod, b), _key(mod, c)}
122
+ if len(keys) != 3:
123
+ raise AssertionError("the requested variant set was ignored")
124
+
125
+
126
+ @case
127
+ def no_false_merge_full_workload(mod):
128
+ workload = build_labeled_workload()
129
+ bad = find_false_merges(mod, workload)
130
+ if bad:
131
+ sample = sorted((sorted(v), k) for k, v in bad.items())[:3]
132
+ raise AssertionError(f"identity shared by >1 true class (false merge): {sample}")
133
+
134
+
135
+ @case
136
+ def handles_edge_schema(mod):
137
+ empty_opts = spec("x=y;", "p80", options=[]) # explicit empty option set
138
+ no_opts = {"source": "x=y;", "target": "p80"} # no options/toolchain/variants keys
139
+ with_build = spec("x=y;", "p80", build={"ts": 1}) # only an incidental build annotation
140
+ for s in (empty_opts, no_opts, with_build):
141
+ _key(mod, s)
142
+ # even at the degenerate schema, two specs for different targets must stay distinct.
143
+ other_target = {"source": "x=y;", "target": "p90"}
144
+ if _key(mod, no_opts) == _key(mod, other_target):
145
+ raise AssertionError("degenerate specs for different targets collided")
146
+
147
+
148
+ @case
149
+ def many_distinct_specs_pairwise_distinct(mod):
150
+ specs = [
151
+ spec("o[i]=a[i]*b[i];", "p80"),
152
+ spec("o[i]=a[i]+b[i];", "p80"),
153
+ spec("o[i]=a[i]*b[i];", "p90"), # target differs from #0
154
+ spec("acc+=a[k]*b[k];", "p80", options=["o3"]),
155
+ spec("acc+=a[k]*b[k];", "p80", options=["o2"]), # option value differs
156
+ spec("acc+=a[k]*b[k];", "p80", options=["o3"], toolchain="v2"), # toolchain differs
157
+ spec("o[i]=a[i]/b[i];", "p86", options=["fast", "o3"]),
158
+ spec("o[i]=a[i]>0?a[i]:0;", "p80", variants=["kA"]),
159
+ ]
160
+ keys = [_key(mod, s) for s in specs]
161
+ if len(set(keys)) != len(specs):
162
+ raise AssertionError(f"expected {len(specs)} distinct identities, got {len(set(keys))}")
163
+
164
+
165
+ def main():
166
+ mod = load_candidate()
167
+ passed = 0
168
+ for fn_case in CASES:
169
+ name = fn_case.__name__
170
+ try:
171
+ fn_case(mod)
172
+ passed += 1
173
+ print(f"CASE_PASS {name}")
174
+ except Exception as exc: # noqa: BLE001
175
+ reason = f"{type(exc).__name__}: {exc}"
176
+ print(f"CASE_FAIL {name}: {reason.splitlines()[0][:300]}")
177
+ traceback.print_exc(file=sys.stderr)
178
+ total = len(CASES)
179
+ print(f"CASES_PASSED={passed}/{total}")
180
+ sys.exit(0 if passed == total else 1)
181
+
182
+
183
+ if __name__ == "__main__":
184
+ main()
tasks/kfc/s4-fft-longconv/task/.dockerignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .dockerignore MUST live at the BUILD CONTEXT ROOT (this directory) — docker/BuildKit does
2
+ # NOT read environment/.dockerignore. Build with: docker build -f environment/Dockerfile .
3
+ # The reference implementation and every authoring artefact MUST NOT reach an image layer.
4
+ *.patch
5
+ oracle*
6
+ negative*
7
+ baseline2*
8
+ scope_card.json
9
+ degradation_manifest.json
10
+ task_meta.json
11
+ loop_map_entry.json
12
+ job.yaml
13
+ intermediates/
14
+ _retrofit*
15
+ sr_validate*
16
+ leak_audit/
17
+ self_check/
18
+ variants/
19
+ **/__pycache__/
20
+ **/*.pyc
21
+ *.bak
22
+ *.bak_*
23
+ *.pre_*
24
+ **/*.pre_*
tasks/kfc/s4-fft-longconv/task/environment/Dockerfile ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # =============================================================================
3
+ # s4-fft-longconv — OPEN-SOURCE, self-contained task image
4
+ #
5
+ # Task: make the declared scope faster while preserving its observable behaviour exactly.
6
+ # Editable scope (the ONLY files the scope gate allows to change):
7
+ ## (declared in tests/test.sh)
8
+ #
9
+ # FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image.
10
+ # Needs 1 NVIDIA GPU to RUN (task.toml: gpus = 1, anchor calibrated on H20); no GPU to BUILD.
11
+ # Platform: linux/amd64 ONLY (official torch wheels are manylinux x86_64).
12
+ # Build context = this task directory (the Dockerfile lives in environment/).
13
+ #
14
+ # PROVENANCE of environment/repo/ (so anyone can re-derive it independently)
15
+ # recovered from: <internal registry>/kernelbench/wre-arch-s4-fft-longconv:v1@sha256:4215533296f1f970d093257f96b14d5cada8925b220966c41471b23d78c36542
16
+ # method: `crane manifest` -> the layers under 80 MB -> `crane blob` + tar, overlaid in
17
+ # manifest order; .git and any .wh..wh..opq marker dropped.
18
+ # verification: 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.
19
+ ##
20
+ # -----------------------------------------------------------------------------
21
+ # BUILD (needs outbound network for PyPI only — the working tree ships in this package)
22
+ # cd <...>/s4-fft-longconv/task
23
+ # docker build -f environment/Dockerfile -t fai/kfc-s4-fft-longconv:oss .
24
+ #
25
+ # RUN docker run --rm --gpus all -it fai/kfc-s4-fft-longconv:oss
26
+ # SCORE docker run --rm --gpus all -v "$PWD/tests:/tests:ro" fai/kfc-s4-fft-longconv:oss bash /tests/test.sh
27
+ # # -> /logs/verifier/reward.json (modes: candidate | noop | oracle | negative)
28
+ #
29
+ # 🔴 NO ANCHOR TO RE-CALIBRATE (binary reward)
30
+ # IMPLEMENTATION-CLASS TASK: reward is binary 0/1 (all correctness cases pass and no
31
+ # cheating -> 1.0, else 0.0). There is NO ref_speedup anchor, so nothing to re-calibrate.
32
+ # tests/test.sh scores correctness only; no ref_speedup.txt ships with this task and
33
+ # none is read. Timing IS still recorded as diagnostic metadata (and the in-image
34
+ # manifest keeps an oracle_ms record from the H20 validation run) but it never enters
35
+ # the reward. The reference implementation is solution/kernel_oracle.py, applied by
36
+ # copying it over the editable file; solution/kernel_negative.py is the known-bad
37
+ # control that MUST score 0. See tests/ref_speedup.caveat.md.
38
+ #
39
+ # VERSION ANCHORS
40
+ # CUDA 12.6 · Python 3.10 · torch 2.7.0 (cu126, brings its matching triton 3.3.x)
41
+ # The original private base declared torch 2.5.1 / triton 3.1.0 and the task overlay then ran
42
+ # `pip install torch==2.7.0` — 2.7.0 is therefore the version the anchor was calibrated under.
43
+ # =============================================================================
44
+ FROM nvidia/cuda:12.6.2-devel-ubuntu22.04
45
+
46
+ # Compute capability you will RUN on (Triton JITs for the live device; this only affects
47
+ # hand-built CUDA extensions): 8.0 A100 / 8.9 L40S-4090 / 9.0 H100-H20 / 10.0 B200
48
+ ARG TORCH_CUDA_ARCH_LIST="9.0"
49
+ ARG TORCH_VERSION=2.7.0
50
+
51
+ ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \
52
+ PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1
53
+
54
+ RUN apt-get update && apt-get install -y --no-install-recommends \
55
+ build-essential gcc-10 g++-10 cmake ninja-build pkg-config \
56
+ python3.10 python3.10-dev python3.10-venv python3-pip python-is-python3 \
57
+ git ca-certificates curl procps coreutils tar gzip vim less file jq \
58
+ && update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 \
59
+ && update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 100 \
60
+ && rm -rf /var/lib/apt/lists/*
61
+
62
+ # ---- venv at this EXACT path: tests/test.sh puts /opt/kernelbench-venv/bin at the head of PATH,
63
+ # and a bare python3 from anywhere else would not have torch. ----
64
+ ENV VENV=/opt/kernelbench-venv
65
+ RUN python3.10 -m venv "$VENV"
66
+ ENV PATH=$VENV/bin:/usr/local/cuda/bin:$PATH \
67
+ TORCH_CUDA_ARCH_LIST=${TORCH_CUDA_ARCH_LIST}
68
+ RUN pip install --no-cache-dir -U pip setuptools wheel
69
+ RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cu126 \
70
+ "torch==${TORCH_VERSION}" \
71
+ && python -c "import torch, triton; print('torch', torch.__version__, '| triton', triton.__version__); assert torch.__version__.startswith('2.7.0'), torch.__version__"
72
+
73
+ # ---- the graded working tree. A REAL directory (not a symlink): the scope gate runs
74
+ # `git -C /app/repo status --porcelain`, which cannot see through a symlink. ----
75
+ RUN mkdir -p /app/repo /app/.timer /app/workspace /logs/verifier /logs/agent /logs/artifacts
76
+ COPY environment/repo/ /app/repo/
77
+ COPY instruction.md /app/instruction.md
78
+
79
+ # ---- the baseline commit = the diff base the scope gate compares against.
80
+ # 🔴 core.fileMode=false is LOAD-BEARING, not hygiene: a shipped image in this corpus had
81
+ # core.fileMode=true while some files were 0775 on disk but 100644 in the index, so
82
+ # `git status --porcelain` reported phantom out-of-scope paths in EVERY mode and forced
83
+ # reward to 0. Setting it false at creation makes that class of defect impossible. ----
84
+ RUN git config --global user.email "reviewer@fai-bench.local" \
85
+ && git config --global user.name "fai-bench" \
86
+ && git config --global init.defaultBranch main \
87
+ && git config --global --add safe.directory /app/repo \
88
+ && cd /app/repo \
89
+ && git init -q \
90
+ && git config core.fileMode false \
91
+ && printf '__pycache__/\n*.pyc\n' >> .gitignore \
92
+ && git add -A \
93
+ && git commit -qm "baseline (graded starting point)" \
94
+ && rm -rf .git/logs \
95
+ && test "$(git rev-list --count HEAD)" = "1" \
96
+ && test -z "$(git remote)" \
97
+ && test "$(git config --get core.fileMode)" = "false" \
98
+ && test -z "$(git status --porcelain)" \
99
+ && echo "[build] /app/repo: 1 commit, no remote, fileMode=false, clean tree"
100
+
101
+ # ---- runtime contract (copied verbatim from the shipped image) ----
102
+ COPY environment/runtime/entrypoint.sh /app/entrypoint.sh
103
+ COPY environment/runtime/timer.sh /app/timer.sh
104
+ RUN chmod 0755 /app/entrypoint.sh /app/timer.sh && chown root:root /app/entrypoint.sh /app/timer.sh
105
+ COPY environment/runtime/run_dev_bench.sh /app/workspace/run_dev_bench.sh
106
+ RUN chmod 0755 /app/workspace/run_dev_bench.sh
107
+
108
+ # ---- the FROZEN anchor fallback. tests/test.sh prefers tests/ref_speedup.txt (mounted) and falls
109
+ # back to THIS path; keeping both consistent makes the resolution explicit. Only the constant. ----
110
+ COPY environment/verifier-correctness-manifest.json /opt/verifier-correctness-manifest.json
111
+
112
+ # ---- OPEN grading suite is NOT baked: tests/ (test.sh + compute_reward.py + the workload/harness
113
+ # + ref_speedup.txt) is MOUNTED FRESH at /tests when scoring. It ships in this package —
114
+ # open-source, but outside the image so the graded harness cannot be edited from the session.
115
+
116
+ # ---- 🔴 ANTI-LEAK ASSERTS (author-side artifact denylist) ----
117
+ RUN set -eu; rc=0; \
118
+ hits="$(find / -xdev -type f \( -name 'oracle*.patch' -o -name 'negative*.patch' \
119
+ -o -name 'baseline2*.patch' -o -name 'scope_card.json' -o -name 'kernel_oracle.py' \
120
+ -o -name 'degradation_manifest.json' \) 2>/dev/null | head -10)"; \
121
+ if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: a reference/authoring file is baked:"; echo "$hits"; rc=1; fi; \
122
+ for p in /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling /tests; do \
123
+ if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path baked: $p"; rc=1; fi; \
124
+ done; \
125
+ test "$rc" = 0; \
126
+ echo "[build] ANTI-LEAK ASSERTS PASS"
127
+
128
+ ENV PYTHONPATH=/app/repo \
129
+ PYTHONDONTWRITEBYTECODE=1 \
130
+ OMP_NUM_THREADS=1 \
131
+ MKL_NUM_THREADS=1 \
132
+ OPENBLAS_NUM_THREADS=1 \
133
+ LD_LIBRARY_PATH=/opt/kernelbench-venv/lib/python3.10/site-packages/torch/lib:/usr/local/cuda/lib64:/usr/local/nvidia/lib64
134
+ WORKDIR /app/repo
135
+
136
+ # ---- build-time smoke: the graded module imports FROM /app/repo (the verifier asserts the same
137
+ # thing at scoring time via its import-origin gate) and the scope files are present. ----
138
+ RUN python - <<'PY'
139
+ import os, subprocess, sys
140
+ sys.path.insert(0, "/app/repo")
141
+ for f in ():
142
+ p = os.path.join("/app/repo", f)
143
+ assert os.path.isfile(p), f"scope file missing: {p}"
144
+ print("scope file present:", f, os.path.getsize(p), "B")
145
+ print("NOTE: no importable scope module for this task; tests/test.sh owns the\n import-origin gate at scoring time")
146
+ n = subprocess.run(["git","-C","/app/repo","rev-list","--count","HEAD"],
147
+ capture_output=True, text=True).stdout.strip()
148
+ assert n == "1", f"git diff base broken (commits={n!r})"
149
+ print("OK: scope files, import origin and git base all in place")
150
+ PY
151
+
152
+ ENTRYPOINT ["/app/entrypoint.sh"]
153
+ CMD ["tail","-f","/dev/null"]
tasks/kfc/s4-fft-longconv/task/environment/repo/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ *.pyc
tasks/kfc/s4-fft-longconv/task/environment/repo/gated_gelu.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+
7
+ def gated_gelu(x: torch.Tensor, approximate: str = "none") -> torch.Tensor:
8
+ """Apply a gated GELU activation over the last dimension.
9
+
10
+ The input's last dimension is split in half. GELU is applied to the first
11
+ half and multiplied by the second half. This straightforward implementation
12
+ intentionally relies on ordinary PyTorch tensor operations.
13
+ """
14
+ if approximate not in ("none", "tanh"):
15
+ raise ValueError("approximate must be 'none' or 'tanh'")
16
+ if not x.is_cuda:
17
+ raise ValueError("x must be a CUDA tensor")
18
+ if x.dim() < 1:
19
+ raise ValueError("x must have at least one dimension")
20
+ if x.shape[-1] % 2 != 0:
21
+ raise ValueError("last dimension must be even")
22
+ d = x.shape[-1] // 2
23
+ return F.gelu(x[..., :d], approximate=approximate) * x[..., d:]
tasks/kfc/s4-fft-longconv/task/environment/repo/submission/kernel.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Performance Optimization Task — submission entry point.
2
+ #
3
+ # Implement `causal_conv` to the contract in instruction.md, then make it as fast as possible.
4
+ # This is the ONLY file you edit. The verifier grades numerical correctness first (bf16 output
5
+ # within rtol=atol=2e-2 of a seeded fp32 reference), then latency on GPU (H20). A submission that
6
+ # leaves NotImplementedError in place scores 0.
7
+
8
+ import torch
9
+
10
+
11
+ def causal_conv(u, k):
12
+ """Causal (non-circular) 1-D convolution of each input sequence with its channel's kernel.
13
+
14
+ Args:
15
+ u: bfloat16 tensor, shape [B, H, L] (B sequences, H channels, length L).
16
+ k: bfloat16 tensor, shape [H, L] (per-channel causal kernel, full length L).
17
+
18
+ For every (b, h) and output position t in [0, L):
19
+
20
+ y[b, h, t] = sum_{s=0}^{t} k[h, t - s] * u[b, h, s]
21
+
22
+ i.e. the linear convolution of u[b,h] with k[h], truncated to the first L samples (a causal
23
+ system: output t depends only on inputs s <= t; no wrap-around from the tail of the sequence).
24
+ Compute the accumulation in fp32, then cast the result back to bf16.
25
+
26
+ Returns:
27
+ bfloat16 tensor, shape [B, H, L].
28
+ """
29
+ raise NotImplementedError("implement causal_conv to the contract in instruction.md")
30
+
31
+
32
+ def custom_kernel(data):
33
+ """Entry point the verifier calls.
34
+
35
+ data = (u, k, config) where config = {"L": int}. Already wired to call causal_conv and return
36
+ the convolved sequences.
37
+ """
38
+ u, k, config = data
39
+ return causal_conv(u, k)
tasks/kfc/s4-fft-longconv/task/environment/runtime/entrypoint.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
4
+
5
+ if [ -x /app/timer.sh ]; then
6
+ /app/timer.sh >/app/.timer/timer.log 2>&1 &
7
+ fi
8
+
9
+ if [ "$#" -gt 0 ]; then
10
+ exec "$@"
11
+ fi
12
+
13
+ exec /bin/bash -l
tasks/kfc/s4-fft-longconv/task/environment/runtime/run_dev_bench.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
4
+ KERNELBENCH_VERIFY_MODE="${KERNELBENCH_VERIFY_MODE:-candidate}" bash /tests/test.sh
tasks/kfc/s4-fft-longconv/task/environment/runtime/timer.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PATH=/opt/kernelbench-venv/bin:/root/.cargo/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
4
+ mkdir -p /app/.timer
5
+ date -u +%FT%TZ > /app/.timer/start.txt
6
+ remaining=${FRONTIER_REMAINING_SECS:-21600}
7
+ printf '%s\n' "$remaining" > /app/.timer/remaining_secs
8
+ printf '%s\n' "$remaining" > /app/.timer/budget_secs
9
+ printf '%s\n' "$$" > /app/.timer/timer.pid
10
+ while true; do
11
+ sleep 60
12
+ done
tasks/kfc/s4-fft-longconv/task/environment/verifier-correctness-manifest.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"oracle_ms": 0.11348799988627434}
tasks/kfc/s4-fft-longconv/task/instruction.md ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Performance Optimization Task
2
+
3
+ You are given a clean Python workspace with a single editable file:
4
+
5
+ ```
6
+ submission/kernel.py
7
+ ```
8
+
9
+ This is the **only** file you may edit. Editing any other file (or importing an
10
+ implementation from anywhere else) causes the whole task to score 0.
11
+
12
+ ## Objective
13
+
14
+ `submission/kernel.py` ships a required function `causal_conv` whose body is **not implemented**
15
+ (it raises `NotImplementedError`). Implement it to the contract below so it is numerically
16
+ correct, then make it as fast as possible on the hidden benchmark workloads. Reward is measured on
17
+ GPU (H20). Correctness is a hard prerequisite: a fast-but-wrong implementation, or one that still
18
+ raises `NotImplementedError`, scores 0.
19
+
20
+ ## Interface contract (implement exactly this)
21
+
22
+ ### `causal_conv(u, k) -> y`
23
+
24
+ A **causal** (non-circular) 1-D convolution of each input sequence with its channel's full-length
25
+ kernel — the "convolution mode" of a long-kernel sequence layer.
26
+
27
+ - `u`: `bfloat16` tensor, shape `[B, H, L]` (`B` sequences, `H` channels, length `L`).
28
+ - `k`: `bfloat16` tensor, shape `[H, L]` (a per-channel causal kernel, full length `L`).
29
+
30
+ For every `(b, h)` and output position `t` in `[0, L)`:
31
+
32
+ ```
33
+ y[b, h, t] = sum_{s=0}^{t} k[h, t - s] * u[b, h, s]
34
+ ```
35
+
36
+ This is the linear convolution of `u[b,h]` with `k[h]`, **truncated to the first `L` samples**. The
37
+ system is causal: output `t` depends only on inputs `s <= t`. There is **no wrap-around** — the tail
38
+ of the sequence must not fold back into early outputs (that would be a circular convolution, which
39
+ is wrong). Accumulate in **fp32**, then cast the result back to `bf16`.
40
+
41
+ ### `custom_kernel(data) -> y`
42
+
43
+ `data = (u, k, config)` where `config = {"L": int}`. Already wired to call `causal_conv(u, k)` and
44
+ return `y`. You implement the primitive.
45
+
46
+ ## Correctness
47
+
48
+ Outputs are compared against a seeded fp32 reference within `rtol = atol = 2e-2` across a hidden
49
+ set of shapes spanning `L=1` (single tap), tiny `L`, odd / non-power-of-two `L`, odd channel
50
+ counts, and a large regime (`L` up to ~2048). The causal boundary must be exact — a submission
51
+ that reads future samples (e.g. a circular convolution with no zero-padding) fails the gate.
52
+ Outputs must genuinely depend on the inputs (the grader runs the op on two different inputs of the
53
+ same shape and rejects identical outputs).
54
+
55
+ ## Latency
56
+
57
+ Once correct, the function is timed on GPU with CUDA events (block of medians, the `u` input
58
+ regenerated every timed iteration; a warmup window is discarded). The primary benchmark uses a
59
+ **long** sequence length `L`. Evaluating the convolution directly — an `O(L^2)` sum per output
60
+ position, or equivalently a dense lower-triangular Toeplitz matrix apply — is correct but its cost
61
+ grows with `L^2`. A full-length convolution can instead be evaluated in `O(L log L)`; expressing it
62
+ so the work grows as `L log L` rather than `L^2` is the reference point. The score is dominated by
63
+ the largest `L`.
64
+
65
+ ## Workload shape (what the hidden benchmark covers)
66
+
67
+ - `bfloat16` `u [B, H, L]` and `k [H, L]`, with `L` up to ~2048, modest `B` and `H`, single GPU.
68
+ - `L=1`, tiny, odd, and non-power-of-two shapes as well as large ones.
69
+ - The score is dominated by the largest shapes, so a fast tiny case cannot offset a slow large one.
70
+
71
+ ## Rules
72
+
73
+ - Edit only `submission/kernel.py`, and keep the `causal_conv` and `custom_kernel` signatures. Any
74
+ other change (or importing the answer from another module/file/package) scores 0.
75
+ - Solve independently. Do **not** download, clone, fetch, or `pip install` any external
76
+ repository, kernel library, or reference implementation to obtain the answer; do **not** attempt
77
+ to bypass or disable the environment's network isolation (e.g. by unsetting proxy environment
78
+ variables or opening raw sockets). Any such action scores the whole task 0, regardless of
79
+ measured speed.
80
+ - You may use `torch` and `triton` (both are installed). You do not need any other package.
81
+
82
+ ## 提交方式
83
+
84
+ 本题为**实现类,只有一次评分**。把改动**留在工作树里**即可 —— 直接编辑允许的文件,不需要 `bash /opt/loop/submit.sh`,也不需要 `git commit`(判分读工作树,仓库 HEAD 必须停在初始基线 commit 上;评分由结束后的 `tests/test.sh` 一次性给出)。
tasks/kfc/s4-fft-longconv/task/pre_artifacts.sh ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ============================================================================
3
+ # pre_artifacts.sh — kfc/s4-fft-longconv
4
+ #
5
+ # Run by the runner INSIDE this task's container AFTER the agent session ends and BEFORE
6
+ # grading (spec §1.1). It turns whatever the agent left behind into a portable artifact:
7
+ #
8
+ # /logs/artifacts/model.patch unified diff: WORKING TREE vs the baked baseline commit
9
+ # /logs/artifacts/model_files.txt one changed/added ABSOLUTE path per line
10
+ #
11
+ # 🔴 IT NEVER COMMITS, and the task statement never asks the agent to (spec H3 — the one
12
+ # place we deliberately differ from deep-swe, whose pre_artifacts.sh diffs <base>..HEAD).
13
+ # Reason: grading reads the WORKING TREE. `git status --porcelain` is the scope gate,
14
+ # `git checkout -q HEAD -- <scope>` re-materialises the baseline for the paired timing,
15
+ # and loop16's `submit.sh --finalize` plants the best iterate with read-tree +
16
+ # checkout-index while HEAD stays on the baked baseline. A commit moves HEAD, the scope
17
+ # gate then sees nothing, `checkout HEAD -- scope` hands the CANDIDATE back as the
18
+ # "baseline" — and a correct solve scores 0.
19
+ # `git add -AN` (intent-to-add) is what makes NEW files appear in `git diff`: it stages
20
+ # names only, writes no tree, creates no commit and leaves HEAD exactly where it was.
21
+ #
22
+ # EXIT CODE IS ALWAYS 0. A missing or empty artifact must not fail the round; the verifier
23
+ # scores the container on its own terms and gives 0 by itself.
24
+ #
25
+ # READ-ONLY ON THE GRADED STATE. `add -AN` is done against a COPY of the repo's index
26
+ # (GIT_INDEX_FILE), so after this script the repo's .git/index is byte-identical and the
27
+ # verifier — which runs after us — sees exactly the `git status --porcelain` it would have
28
+ # seen if this script had never run. No commit, no HEAD move, no working-tree write.
29
+ #
30
+ # CAPTURE ROOTS for THIS task — derived from the package, never assumed:
31
+ # /app/repo git repo, HEAD == the 1-commit carved baseline
32
+ # evidence Dockerfile:134: WORKDIR /app/repo
33
+ # evidence Dockerfile:88: && cd /app/repo \
34
+ # evidence Dockerfile:95: && test "$(git rev-list --count HEAD)" = "1" \
35
+ # evidence test.sh:17: REPO=/app/repo
36
+ #
37
+ # Single root => model.patch is a bare `git diff --binary <baseline>` (no banner).
38
+ # model_files.txt carries ABSOLUTE paths, corpus-wide, so the two forms stay parseable
39
+ # by one reader.
40
+ # ============================================================================
41
+ set -uo pipefail
42
+
43
+ OUT=/logs/artifacts
44
+ PATCH="$OUT/model.patch"
45
+ LIST="$OUT/model_files.txt"
46
+ MULTI=0 # 1 => several capture roots => each diff gets a banner line
47
+ MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane)
48
+
49
+ mkdir -p "$OUT" 2>/dev/null || true
50
+ : > "$PATCH" 2>/dev/null || true
51
+ : > "$LIST" 2>/dev/null || true
52
+ git config --global --add safe.directory '*' >/dev/null 2>&1 || true
53
+
54
+ banner() { # $1=root $2=mode ; only when there is more than one root
55
+ if [ "$MULTI" = 1 ]; then
56
+ printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null
57
+ fi
58
+ return 0
59
+ }
60
+
61
+ list_add() { # stdin: paths relative to $1 -> absolute, one per line
62
+ sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true
63
+ return 0
64
+ }
65
+
66
+ capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline
67
+ root=$1
68
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
69
+ if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
70
+ echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot"
71
+ capture_tree "$root"
72
+ return 0
73
+ fi
74
+ # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and
75
+ # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could
76
+ # flip a scope gate either way. So copy the repo's index aside and stage into the COPY —
77
+ # the repo's own .git/index is byte-identical when we are done.
78
+ tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi=""
79
+ gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true)
80
+ if [ -z "$gd" ]; then
81
+ gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true)
82
+ case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac
83
+ fi
84
+ if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then
85
+ GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE
86
+ else
87
+ echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index"
88
+ fi
89
+ git -C "$root" add -AN . >/dev/null 2>&1 || true
90
+ base=HEAD
91
+ if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then
92
+ base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null)
93
+ echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree"
94
+ else
95
+ n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0)
96
+ case "$n" in ''|*[!0-9]*) n=0 ;; esac
97
+ if [ "$n" -gt 1 ]; then
98
+ base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1)
99
+ echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:"
100
+ echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so"
101
+ echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved"
102
+ echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve."
103
+ fi
104
+ fi
105
+ [ -n "${base:-}" ] || base=HEAD
106
+ banner "$root" "git-diff-vs-baseline"
107
+ git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true
108
+ names=$(git -C "$root" diff --name-only "$base" 2>/dev/null)
109
+ echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)"
110
+ unset GIT_INDEX_FILE
111
+ [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null
112
+ printf '%s\n' "$names" | grep -v '^$' | list_add "$root"
113
+ return 0
114
+ }
115
+
116
+ capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot
117
+ root=$1
118
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
119
+ tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0
120
+ if git init -q "$tmp/snap" >/dev/null 2>&1; then
121
+ GD="$tmp/snap/.git"
122
+ empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null)
123
+ ( cd "$root" 2>/dev/null || exit 0
124
+ find . -name .git -prune -o -name __pycache__ -prune -o \
125
+ -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \
126
+ 2>/dev/null \
127
+ | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true
128
+ banner "$root" "tree-snapshot-not-a-git-repo"
129
+ GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \
130
+ >> "$PATCH" 2>/dev/null || true
131
+ else
132
+ echo "[pre_artifacts] WARN could not stage a snapshot index for $root"
133
+ fi
134
+ rm -rf "$tmp" 2>/dev/null || true
135
+ all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \
136
+ -type f -print 2>/dev/null | sed 's|^\./||' )
137
+ printf '%s\n' "$all" | grep -v '^$' | list_add "$root"
138
+ big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \
139
+ -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . )
140
+ echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)"
141
+ if [ "${big:-0}" != 0 ]; then
142
+ echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in"
143
+ echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch."
144
+ fi
145
+ return 0
146
+ }
147
+
148
+ capture_git "/app/repo"
149
+ bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0)
150
+ case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac
151
+ echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)"
152
+ if [ "$bytes" -gt 67108864 ]; then
153
+ echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build"
154
+ echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also"
155
+ echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish."
156
+ fi
157
+ exit 0
tasks/kfc/s4-fft-longconv/task/solution/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # solution/ — reviewer-only 参考实现
2
+
3
+ 本目录里的补丁**不进镜像**(已被上下文根的 `.dockerignore` 排除)、**判分不运行**,
4
+ 只在两种场合用:
5
+
6
+ 1. **重标定锚点**(换硬件后):见 `../tests/ref_speedup.caveat.md`
7
+ ```
8
+ -e KERNELBENCH_VERIFY_MODE=oracle -e KERNELBENCH_ORACLE_PATCH=/patches/oracle.patch
9
+ ```
10
+ 2. **自证挖洞树的正确性**:`git apply --check -p1 oracle.patch` 必须能干净打在
11
+ `../environment/repo/` 上(正向可、反向不可),这证明该树就是被计分的起始点。
12
+
13
+ `negative.patch` 是已知坏例(必须得 0),`baseline2.patch` 是中间基线(若有)。
tasks/kfc/s4-fft-longconv/task/solution/kernel_negative.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reviewer-only NEGATIVE (not baked into the image): fast but WRONG. Uses a CIRCULAR convolution (FFT at
2
+ # length L with no zero-padding) instead of the causal linear convolution. The missing zero-pad
3
+ # lets the tail of the sequence wrap around into early outputs, so a position t reads "future"
4
+ # samples via the wrap -- it violates causality and disagrees with the reference for any L > 1.
5
+ # It is a single fast FFT pass, so it must FAIL the correctness gate (not the timing).
6
+ import torch
7
+
8
+
9
+ def causal_conv(u, k):
10
+ B, H, L = u.shape
11
+ uf = torch.fft.rfft(u.float(), n=L, dim=-1) # WRONG: n=L -> circular, no padding
12
+ kf = torch.fft.rfft(k.float(), n=L, dim=-1).unsqueeze(0)
13
+ y = torch.fft.irfft(uf * kf, n=L, dim=-1)[..., :L]
14
+ return y.to(torch.bfloat16)
15
+
16
+
17
+ def custom_kernel(data):
18
+ u, k, config = data
19
+ return causal_conv(u, k)
tasks/kfc/s4-fft-longconv/task/solution/kernel_oracle.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reviewer-only ORACLE (not baked into the image): the fast form. A causal 1-D convolution with a full-length
2
+ # kernel is evaluated in O(L log L) via the FFT: zero-pad both operands to length >= 2L-1, take
3
+ # the real FFT, multiply in the frequency domain, inverse-FFT, and keep the first L samples (the
4
+ # zero-padding makes the circular convolution equal the causal linear convolution). Grounded in
5
+ # TRAIN.ARCH.SSM: state-spaces/s4 — the S4/S4D "convolution mode" materializes the SSM kernel of
6
+ # length L and applies it to the sequence with an FFT (the global long convolution), instead of
7
+ # stepping the O(L^2) recurrence/direct sum. Never baked; calibrates oracle_ms + proves headroom.
8
+ import torch
9
+
10
+
11
+ def causal_conv(u, k):
12
+ B, H, L = u.shape
13
+ n = 1
14
+ while n < 2 * L:
15
+ n <<= 1
16
+ uf = torch.fft.rfft(u.float(), n=n, dim=-1)
17
+ kf = torch.fft.rfft(k.float(), n=n, dim=-1).unsqueeze(0) # [1,H,.]
18
+ y = torch.fft.irfft(uf * kf, n=n, dim=-1)[..., :L]
19
+ return y.to(torch.bfloat16)
20
+
21
+
22
+ def custom_kernel(data):
23
+ u, k, config = data
24
+ return causal_conv(u, k)
tasks/kfc/s4-fft-longconv/task/solution/solve.sh ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # solution/solve.sh — kfc/s4-fft-longconv
3
+ # 把本题的参考实现落成「与 agent 提交等价」的形态,让 oracle 验证从手工传环境变量
4
+ # 变成一条命令。本文件不进镜像(没有任何 COPY 取 solution/),判分器也不会运行它。
5
+ #
6
+ # oracle 形态 : 单文件变体(file)。tests/test.sh 的模式分派走 KERNELBENCH_ORACLE_FILE 槽位:
7
+ # cp "$KERNELBENCH_ORACLE_FILE" "$REPO/$SUB"
8
+ # 产物(reviewer-only;本脚本只读,一个字节都不改):
9
+ # solution/kernel_negative.py, solution/kernel_oracle.py
10
+ # $REPO : /app/repo (tests/test.sh: REPO=/app/repo)
11
+ # 被计分单元 : /app/repo/submission/kernel.py
12
+ # 来源:tests/test.sh 的 SUB="submission/kernel.py"
13
+ # 落地方式 : cp <变体> $REPO/submission/kernel.py —— 只改工作树,不 commit
14
+ #
15
+ # 🔴 为什么绝不 commit(规范 H3):判分读**工作树** —— `git status --porcelain` 是 scope
16
+ # 硬闸门,`git checkout -q HEAD -- <scope>` 取基线,且镜像自证 /app/repo 的 HEAD 恰好
17
+ # 只有 1 个 commit(那就是挖洞基线)。一旦 commit,HEAD 前移 → 闸门看不到改动、
18
+ # `checkout HEAD -- scope` 把 candidate 当成基线 → 正确解被判 0。
19
+ # 本脚本落地后会自己断言 HEAD 与 commit 数没变。
20
+ #
21
+ # ── 落地后判分的那条完整命令(同一个容器里跑完 3 步)────────────────────────
22
+ # PKG=<fai_bench>/tasks/kfc/s4-fft-longconv/task
23
+ # IMG=fai/kfc-s4-fft-longconv:oss
24
+ # # 1) 起容器。判分容器始终 --network=none;tests/ 和 solution/ 都**没有**烤进镜像
25
+ # # (Dockerfile 里没有一条 COPY 取它们),所以这两个目录必须挂进来。
26
+ # # 该题 task.toml 声明 gpus=1;锚点的标定硬件/运行栈见 tests/ref_speedup.caveat.md
27
+ # docker run -d --name kfc-solve --network=none --gpus all \
28
+ # -v "$PKG/tests":/tests -v "$PKG/solution":/solution "$IMG"
29
+ # # 2) 落地参考实现到工作树(本脚本;不 commit)
30
+ # docker exec kfc-solve bash /solution/solve.sh
31
+ # # 3) 判分。KERNELBENCH_VERIFY_MODE 必须留在默认的 candidate —— 这就是 agent 的
32
+ # # 真实评分路径;设成 oracle/negative 会让 test.sh 自己再落地一遍,绕过本脚本。
33
+ # docker exec -e KERNELBENCH_VERIFY_MODE=candidate kfc-solve bash /tests/test.sh
34
+ # docker exec kfc-solve cat /logs/verifier/reward.json # 判分结果
35
+ # docker rm -f kfc-solve
36
+ #
37
+ # 期望:oracle → 性能题得 0(它就是锚点本身; min(1, ln(speedup/ref_speedup)/ln(ref_speedup))(speedup ≤ ref_speedup 时为 0)
38
+ # 在 speedup≈ref_speedup 处 = 0 —— 打平 oracle 不得分,必须超过。
39
+ # 所以"oracle 跑对了"的判据不是 reward>0,而是 speedup≈ref_speedup 且
40
+ # hard_fail_reasons 为空;实现类二值题 = 1.0 —— 权威公式是
41
+ # tests/test.sh 写出的 reward_formula 字段);--negative → 0;
42
+ # --noop(在纯净容器里)→ 0(挖洞基线过不了正确性门)。
43
+ # ──────────────────────────────────────────────────────────────────────────
44
+ #
45
+ # 用法(规范 2 的统一 CLI):
46
+ # bash solution/solve.sh # 落地 oracle(参考实现)
47
+ # bash solution/solve.sh --negative # 落地 negative(已知坏例,必须得 0)
48
+ # bash solution/solve.sh --baseline2 # 落地 baseline2(中间基线)
49
+ # bash solution/solve.sh --noop # 把可编辑面复位到烤入基线(对照组)
50
+ #
51
+ # --noop 语义:把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 ——
52
+ # `git checkout HEAD -- <scope>`,HEAD 不动),使对照组能量到真正的 no-op 值。
53
+ # runner 在同一个容器里连着跑 oracle → noop 做对照时,靠它把上一轮落地归零。
54
+ #
55
+ # 幂等:每次落地前先把被计分单元 `git checkout HEAD --` 复位,重复执行结果一致。
56
+ # 失败一律非 0 退出并打印原因(补丁打不上 / 变体文件缺失 / scope 路径不存在 / HEAD 被移动)。
57
+ set -uo pipefail
58
+
59
+ TASK_ID="s4-fft-longconv"
60
+ REPO="${KFC_REPO_DIR:-/app/repo}"
61
+ SUB="submission/kernel.py"
62
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
63
+
64
+ say(){ printf '[solve.sh %s] %s\n' "$TASK_ID" "$*"; }
65
+ die(){ printf '[solve.sh %s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; }
66
+ GIT(){ git -c safe.directory='*' -C "$REPO" "$@"; }
67
+
68
+ usage(){ cat <<'USAGE'
69
+ usage: bash solve.sh [--oracle | --negative | --noop]
70
+ (无参数) 落地 oracle 参考实现(kernel_oracle.py)
71
+ --negative 落地 negative 已知坏例(kernel_negative.py)
72
+ --noop 把可编辑面复位到烤入基线(与 verifier 取基线一致,HEAD 不动)
73
+ USAGE
74
+ }
75
+
76
+ WHICH=oracle
77
+ case "${1:-}" in
78
+ ""|--oracle) WHICH=oracle ;;
79
+ --negative) WHICH=negative ;;
80
+ --baseline2) WHICH=baseline2 ;;
81
+ --noop) WHICH=noop ;;
82
+ -h|--help) usage; exit 0 ;;
83
+ *) usage >&2; die "未知参数 '$1'" ;;
84
+ esac
85
+
86
+ artifact(){
87
+ local n="$1" c
88
+ for c in "$HERE/$n" "/solution/$n" "${KFC_SOLUTION_DIR:-/nonexistent}/$n"; do
89
+ [ -f "$c" ] && { printf '%s\n' "$c"; return 0; }
90
+ done
91
+ return 1
92
+ }
93
+
94
+ case "$WHICH" in
95
+ noop) ART="" ;;
96
+ oracle) ART="kernel_oracle.py" ;;
97
+ negative) ART="kernel_negative.py" ;;
98
+ *) die "本题没有 $WHICH 变体(solution/ 里只有:kernel_oracle.py, kernel_negative.py)" ;;
99
+ esac
100
+
101
+ GIT rev-parse --git-dir >/dev/null 2>&1 \
102
+ || die "$REPO 不是 git 工作树 —— 本脚本必须在题目容器里跑(镜像在 build 时才 git init 挖洞基线)"
103
+ [ -f "$REPO/$SUB" ] || die "被计分单元不存在:$REPO/$SUB(REPO 不对?可用 KFC_REPO_DIR 覆盖)"
104
+ HEAD_BEFORE="$(GIT rev-parse HEAD)" || die "读不到 $REPO 的 HEAD"
105
+ N_BEFORE="$(GIT rev-list --count HEAD)"
106
+
107
+ if [ "$WHICH" = noop ]; then
108
+ # --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致 —— `git checkout HEAD -- <scope>`,
109
+ # HEAD 不动),使对照组能量到真正的 no-op 值。scope 文件在 git 树里,所以 checkout 就够。
110
+ DIRTY_BEFORE="$(GIT status --porcelain -- "$SUB" | sed '/^$/d')"
111
+ GIT checkout -q HEAD -- "$SUB" || die "复位被计分单元失败($SUB)"
112
+ DIRTY_AFTER="$(GIT status --porcelain -- "$SUB" | sed '/^$/d')"
113
+ if [ -n "$DIRTY_AFTER" ]; then
114
+ printf '%s\n' "$DIRTY_AFTER" | sed "s|^|[solve.sh $TASK_ID] |" >&2
115
+ die "复位后被计分单元仍不干净(见上)—— 量不到真正的 no-op 值"
116
+ fi
117
+ [ "$HEAD_BEFORE" = "$(GIT rev-parse HEAD)" ] || die "HEAD 被移动了,判分会把 candidate 当基线"
118
+ [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线"
119
+ if [ -n "$DIRTY_BEFORE" ]; then
120
+ say "--noop:已把可编辑面复位到烤入基线的 stub;原先这些是脏的:"
121
+ printf '%s\n' "$DIRTY_BEFORE" | sed "s|^|[solve.sh $TASK_ID] |"
122
+ else
123
+ say "--noop:可编辑面本来就是干净的烤入基线 stub,无需复位"
124
+ fi
125
+ say "--noop 完成:$SUB = 烤入基线 stub(HEAD 未动 @ ${HEAD_BEFORE:0:12})"
126
+ exit 0
127
+ fi
128
+
129
+ VAR="$(artifact "$ART")" || die "找不到参考产物 $ART(查过 $HERE/、/solution/、\$KFC_SOLUTION_DIR/)"
130
+
131
+ # ---- 幂等:先复位到挖洞基线的 stub,再整文件覆盖(cp 保留目标文件原有权限) ----
132
+ GIT checkout -q HEAD -- "$SUB" || die "复位被计分单元失败($SUB)"
133
+ cp -f "$VAR" "$REPO/$SUB" || die "写入失败:$REPO/$SUB"
134
+
135
+ HEAD_AFTER="$(GIT rev-parse HEAD)"
136
+ [ "$HEAD_BEFORE" = "$HEAD_AFTER" ] || die "HEAD 被移动了($HEAD_BEFORE -> $HEAD_AFTER),判分会把 candidate 当基线"
137
+ [ "$N_BEFORE" = "$(GIT rev-list --count HEAD)" ] || die "commit 数变了,HEAD 不再是唯一的挖洞基线"
138
+
139
+ say "已落地 $WHICH:$(basename "$VAR") -> $SUB(工作树改动,HEAD 未动 @ ${HEAD_AFTER:0:12})"
140
+ GIT status --porcelain -- "$SUB" | sed "s|^|[solve.sh $TASK_ID] |"
141
+
142
+ STRAY="$(GIT status --porcelain | awk '{print $NF}' \
143
+ | grep -v -e '__pycache__' -e '\.pyc$' -e "^$SUB\$" || true)"
144
+ [ -z "$STRAY" ] || { say "⚠ 工作树里还有 scope 外的改动,判分会 out_of_scope_edit 直接归 0:"; \
145
+ printf '%s\n' "$STRAY" | sed "s|^|[solve.sh $TASK_ID] |"; }
146
+ exit 0
tasks/kfc/s4-fft-longconv/task/task.toml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reconstructed: the source package shipped a 0-byte task.toml;
2
+ # the values below mirror the task metadata.
3
+
4
+ schema_version = "2.0"
5
+
6
+ # 提交产物(pre_artifacts.sh 在判分前于同一容器内产出;规范 §1)
7
+ artifacts = ["/logs/artifacts/model.patch", "/logs/artifacts/model_files.txt"]
8
+
9
+ [task]
10
+ id = "s4-fft-longconv"
11
+ bench = "kfc"
12
+ kind = "implementation"
13
+ language = "python"
14
+ title = "submission/kernel.py ships a required function causal_conv whose body is not implemented (it raises NotImplementedError)."
15
+ instruction = "instruction.md"
16
+
17
+ [agent]
18
+ timeout_sec = 5400
19
+
20
+ # carved-tree provenance (environment/repo/ recovered from): <internal registry>/kernelbench/wre-arch-s4-fft-longconv:v1@sha256:4215533296f1f970d093257f96b14d5cada8925b220966c41471b23d78c36542
21
+ # 🔁 LOOP16: the shipped image is the loop16 overlay (`crane append` onto the :oss base, purely
22
+ # additive — /opt/loop only, NOTHING under tests/ changed). Build it in two steps:
23
+ # docker build -f environment/Dockerfile -t fai/kfc-s4-fft-longconv:oss .
24
+ # docker build -f environment/loop_overlay/Dockerfile -t fai/kfc-s4-fft-longconv:oss-loop16 environment/loop_overlay
25
+ # The single-shot form (:oss) is a valid alternative; the graded surface (tests/) is identical in both.
26
+ [environment]
27
+ docker_image = "fai/kfc-s4-fft-longconv:oss"
28
+ build_timeout_sec = 3600
29
+ cpus = 8
30
+ memory_mb = 32768
31
+ gpus = 1
32
+ # H20 只是**锚点标定用卡**,不是硬性限制。换卡时:①按 tests/ref_speedup.caveat.md 重标锚点;
33
+ # ②用 --build-arg TORCH_CUDA_ARCH_LIST=<你的算力> 构建镜像。
34
+ gpu_types = ["H20"]
35
+ allow_internet = false
36
+
37
+ [verifier]
38
+ entrypoint = "tests/test.sh"
39
+ mode = "shared"
40
+ primary_edit_paths = ["submission/kernel.py"]
41
+ result_paths = ["/logs/verifier/reward.json"]
42
+
43
+ [primary_metric]
44
+ name = "reward"
45
+ goal = "maximize"
46
+ calibrated_on = "NVIDIA H20"
47
+
48
+ # loop16: the shipped image bakes /opt/loop; the in-session dev proxy re-runs THIS task's own
49
+ # verifier (candidate mode) on the live /app/repo. This is an IMPLEMENTATION-class task (binary
50
+ # reward), so best-of-k ranks on the dual-emitted RAW vs_oracle speed signal to prefer the fastest
51
+ # correctness-passing kernel. At most 16 submissions, at least 1; the model decides when to stop
52
+ # (min=1 so --finalize works any time). NO calibrated anchor is baked. The graded score is the
53
+ # runner's fresh end-of-session tests/ grade (binary correctness over hidden shapes).
tasks/kfc/s4-fft-longconv/task/tests/compute_reward.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """compute_reward for s4-fft-longconv (IMPLEMENTATION class).
3
+
4
+ reward = 1.0 iff every test case passes and there is no cheat / scope violation,
5
+ reward = 0.0 otherwise [implementation class]
6
+
7
+ The authoritative verdict is written by test.sh, which owns the correctness /
8
+ scope-diff / import-origin / anti-cheat HARD gates (the baked hollow stub raises
9
+ NotImplementedError, so the starter fails correctness and scores 0). This CLI
10
+ mirrors the same binary rule and reports the measured vs_oracle ratio as
11
+ DIAGNOSTIC METADATA only — never as the reward.
12
+
13
+ Why binary rather than the performance log formula: this task has NO timeable
14
+ baseline (the starter does not run), and its only timing anchor is the oracle
15
+ 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
16
+ degenerate/undefined. reward.md's legality rule for the starter package
17
+ ("implementation class must fail at least one testcase") is what this satisfies.
18
+ """
19
+ import json
20
+ import sys
21
+
22
+ TOKEN = "WRE_RESULT "
23
+
24
+
25
+ def load(path):
26
+ for line in open(path):
27
+ if line.startswith(TOKEN):
28
+ return json.loads(line[len(TOKEN):])
29
+ raise SystemExit(f"no {TOKEN.strip()} in {path}")
30
+
31
+
32
+ def main():
33
+ cand = load(sys.argv[1])
34
+ oracle_ms = float(sys.argv[2]) if len(sys.argv) > 2 else -1.0
35
+ cm = cand.get("timing_ms", -1)
36
+
37
+ # correctness is the AND of every case; the workload reports it as one flag.
38
+ correctness_ok = bool(cand.get("correctness_ok", False))
39
+ hard = [] if correctness_ok else ["correctness_failed"]
40
+ reward = 1.0 if (correctness_ok and not hard) else 0.0
41
+
42
+ vs_oracle = (oracle_ms / cm) if (cm and cm > 0 and oracle_ms > 0) else 0.0
43
+ print(json.dumps({
44
+ "task_type": "implementation",
45
+ "reward": reward,
46
+ "reward_formula": "implementation: 1.0 iff every case passes and no cheat, else 0.0",
47
+ "hard_fail_reasons": hard,
48
+ "tests": {"passed": (1 if correctness_ok else 0), "total": 1,
49
+ "note": "correctness_ok is the AND over every hidden case"},
50
+ "metadata": {"vs_oracle": round(vs_oracle, 6), "oracle_ms": oracle_ms,
51
+ "candidate_ms": cm,
52
+ "note": "vs_oracle is diagnostic metadata only, never the reward"},
53
+ "vs_oracle": round(vs_oracle, 6),
54
+ "oracle_ms": oracle_ms,
55
+ "candidate_ms": cm,
56
+ }))
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
tasks/kfc/s4-fft-longconv/task/tests/ref_speedup.caveat.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ref_speedup 硬件/环境 caveat(开源版新增,不改变判分逻辑)
2
+
3
+ 本题是**实现类**任务:reward 为二值 0/1(全部正确性用例通过且无作弊 -> 1.0,否则 0.0),**不使用 ref_speedup 锚点**,因此无需重标定。下方公式仅对性能类任务适用:
4
+
5
+ reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0
6
+
7
+ 本题不随包提供 `tests/ref_speedup.txt`,判分也不读它 —— 二值 reward 与锚点无关。
8
+ `environment/verifier-correctness-manifest.json` 里的 `oracle_ms` 仅作诊断记录,不参与判分。
9
+
10
+ ## 标定条件
11
+
12
+ - 硬件:**NVIDIA H20**
13
+ - 运行栈:`torch 2.7.0`(原始私有基座声明 torch 2.5.1/triton 3.1.0,任务 overlay 又 `pip install torch==2.7.0`,锚点即在 2.7.0 下标定)
14
+ - 线程:`OMP/MKL/OPENBLAS_NUM_THREADS=1`(计时稳定性的一部分,已写进镜像 ENV)
15
+
16
+ ## 换硬件时要做什么
17
+
18
+ **不需要重标定** —— 本题 reward 是二值的,与硬件无关。上面的「标定条件」只是记录
19
+ 参考实现当初被验证的环境;换卡后正确性用例应当照常全过。
20
+
21
+ 参考实现与反例是**单文件形式**(不是 patch),覆盖到可编辑文件上即可:
22
+
23
+ - `solution/kernel_oracle.py` —— 参考实现,应当得 1.0
24
+ - `solution/kernel_negative.py` —— 已知坏例,**必须**得 0.0
25
+
26
+ 两者都不进镜像(已被 `.dockerignore` 排除),判分时也从不运行。
27
+
28
+ 计时仍会作为诊断元数据记录(`environment/verifier-correctness-manifest.json`
29
+ 的 `oracle_ms` 是 H20 验证时的记录值),但不参与 reward。