hyttyh111222333 commited on
Commit
fea549a
·
1 Parent(s): 8a39ced

Upload remaining expanded FAI-Bench tasks

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. tasks/e2e/a3-moe-train-budget/task/.dockerignore +12 -0
  3. tasks/e2e/a3-moe-train-budget/task/environment/Dockerfile +308 -0
  4. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/Dockerfile +52 -0
  5. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/instruction_loop16.md +76 -0
  6. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/baseline_submission/run_training.sh +15 -0
  7. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/baseline_submission/train_gpt.py +180 -0
  8. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/private/dev_eval.py +444 -0
  9. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/private/manifest.json +25 -0
  10. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/sanitize_feedback.py +89 -0
  11. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/score_engine.sh +47 -0
  12. tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/submit.sh +238 -0
  13. tasks/e2e/a3-moe-train-budget/task/environment/submission/run_training.sh +15 -0
  14. tasks/e2e/a3-moe-train-budget/task/environment/submission/train_gpt.py +180 -0
  15. tasks/e2e/a3-moe-train-budget/task/instruction.md +161 -0
  16. tasks/e2e/a3-moe-train-budget/task/pre_artifacts.sh +166 -0
  17. tasks/e2e/a3-moe-train-budget/task/solution/baseline_dense_floor/run_training.sh +15 -0
  18. tasks/e2e/a3-moe-train-budget/task/solution/baseline_dense_floor/train_gpt.py +180 -0
  19. tasks/e2e/a3-moe-train-budget/task/solution/mid_naive_moe/run_training.sh +12 -0
  20. tasks/e2e/a3-moe-train-budget/task/solution/mid_naive_moe/train_gpt.py +268 -0
  21. tasks/e2e/a3-moe-train-budget/task/solution/oracle_grouped_moe/RECIPE_RECORD.json +27 -0
  22. tasks/e2e/a3-moe-train-budget/task/solution/oracle_grouped_moe/run_training.sh +12 -0
  23. tasks/e2e/a3-moe-train-budget/task/solution/oracle_grouped_moe/train_gpt.py +347 -0
  24. tasks/e2e/a3-moe-train-budget/task/solution/probe_budget_bite/run_training.sh +15 -0
  25. tasks/e2e/a3-moe-train-budget/task/solution/probe_budget_bite/train_gpt.py +153 -0
  26. tasks/e2e/a3-moe-train-budget/task/solution/probe_no_checkpoint/run_training.sh +15 -0
  27. tasks/e2e/a3-moe-train-budget/task/solution/probe_no_checkpoint/train_gpt.py +9 -0
  28. tasks/e2e/a3-moe-train-budget/task/solution/probe_tamper_frozen/run_training.sh +15 -0
  29. tasks/e2e/a3-moe-train-budget/task/solution/probe_tamper_frozen/train_gpt.py +108 -0
  30. tasks/e2e/a3-moe-train-budget/task/solution/solve.sh +183 -0
  31. tasks/e2e/a3-moe-train-budget/task/task.toml +111 -0
  32. tasks/e2e/a3-moe-train-budget/task/tests/compute_reward.py +762 -0
  33. tasks/e2e/a3-moe-train-budget/task/tests/holdout_corpus.txt +0 -0
  34. tasks/e2e/a3-moe-train-budget/task/tests/test.sh +248 -0
  35. tasks/e2e/a3-moe-train-budget/task/tests/timer.sh +134 -0
  36. tasks/e2e/a3-moe-train-budget/task/tests/verifier-correctness-manifest.json +89 -0
  37. tasks/e2e/a4-token-efficiency-budget/task/.dockerignore +12 -0
  38. tasks/e2e/a4-token-efficiency-budget/task/environment/Dockerfile +305 -0
  39. tasks/e2e/a4-token-efficiency-budget/task/environment/Dockerfile.loop16 +100 -0
  40. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/Dockerfile +52 -0
  41. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/instruction_loop16.md +218 -0
  42. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/baseline_submission/train_gpt.py +221 -0
  43. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/private/dev_eval.py +489 -0
  44. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/private/manifest.json +27 -0
  45. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/sanitize_feedback.py +89 -0
  46. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/score_engine.sh +47 -0
  47. tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/submit.sh +238 -0
  48. tasks/e2e/a4-token-efficiency-budget/task/environment/submission/train_gpt.py +221 -0
  49. tasks/e2e/a4-token-efficiency-budget/task/instruction.md +156 -0
  50. tasks/e2e/a4-token-efficiency-budget/task/pre_artifacts.sh +171 -0
.gitattributes CHANGED
@@ -58,5 +58,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
61
  tasks/kfc/wro-colossalai-devicemesh-rank-collate-loop16/task/environment/repo/applications/ColossalQA/data/tests/sample-pdf-file.pdf filter=lfs diff=lfs merge=lfs -text
62
  tasks/kfc/wli-fla-retention-chunkscan-loop16/task/environment/repo/fla/ops/gated_oja_rule/OJA.pdf filter=lfs diff=lfs merge=lfs -text
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ *.pdf filter=lfs diff=lfs merge=lfs -text
62
+ tasks/e2e/eval-scoring-throughput/task/tests/heldout_samples.jsonl filter=lfs diff=lfs merge=lfs -text
63
  tasks/kfc/wro-colossalai-devicemesh-rank-collate-loop16/task/environment/repo/applications/ColossalQA/data/tests/sample-pdf-file.pdf filter=lfs diff=lfs merge=lfs -text
64
  tasks/kfc/wli-fla-retention-chunkscan-loop16/task/environment/repo/fla/ops/gated_oja_rule/OJA.pdf filter=lfs diff=lfs merge=lfs -text
tasks/e2e/a3-moe-train-budget/task/.dockerignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # build context is task/ ; never send the reviewer-only reference implementations or the
4
+ # grading suite (held-out corpus + calibrated anchors) into the docker build.
5
+ solution/
6
+ tests/
7
+ loop_overlay/
8
+ **/__pycache__/
9
+ **/*.pyc
10
+ *.bak_*
11
+ *.orig_*
12
+ Dockerfile.orig_private_base
tasks/e2e/a3-moe-train-budget/task/environment/Dockerfile ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # =============================================================================
3
+ # e2e-a3-moe-train-budget — OPEN-SOURCE, self-contained task image
4
+ #
5
+ # Task: beat a dense nanoGPT baseline at a FIXED compute budget (e.g. with a sparse MoE FFN).
6
+ # The agent edits /app/submission/{train_gpt.py,run_training.sh}; the OPEN verifier under /tests
7
+ # trains it under a FIXED budget and scores held-out quality (bits/byte).
8
+ #
9
+ # FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image.
10
+ # Platform: linux/amd64 ONLY (official torch wheels are manylinux x86_64).
11
+ # Build context = the task/ directory (this Dockerfile lives in task/environment/).
12
+ #
13
+ # -----------------------------------------------------------------------------
14
+ # BUILD (needs outbound network: PyPI + github.com + huggingface.co)
15
+ # cd <...>/a3-moe-train-budget/task
16
+ # docker build -f environment/Dockerfile -t fai/e2e-a3-moe-train-budget:oss .
17
+ # No GPU is needed to build. Building the corpus (below) takes ~15-30 min and the
18
+ # resulting image is ~10 GB (torch + CUDA base + the tokenised corpus).
19
+ # Non-H20 GPUs: pass your compute capability so self-built kernels target it:
20
+ # docker build --build-arg TORCH_CUDA_ARCH_LIST=8.0 ... # A100
21
+ # docker build --build-arg TORCH_CUDA_ARCH_LIST=8.9 ... # L40S / 4090
22
+ # docker build --build-arg TORCH_CUDA_ARCH_LIST=9.0 ... # H100 / H20 (default)
23
+ #
24
+ # RUN (needs 1 NVIDIA GPU, driver >= 535)
25
+ # docker run --rm --gpus all --shm-size=8g -it fai/e2e-a3-moe-train-budget:oss
26
+ #
27
+ # SCORE (inside the container; tests/ is MOUNTED, never baked into the image)
28
+ # docker run --rm --gpus all --shm-size=8g \
29
+ # -v "$PWD/tests:/tests:ro" fai/e2e-a3-moe-train-budget:oss bash /tests/test.sh # -> /logs/verifier/reward.json
30
+ #
31
+ # 🔴 RE-CALIBRATE THE FROZEN ANCHORS ON YOUR BUILD (read this before trusting a reward)
32
+ # reward = min(1.0, ln((baseline_bpb / your_val_bpb) / ref_speedup) / ln(ref_speedup))
33
+ # and 0 unless (baseline_bpb / your_val_bpb) > ref_speedup — you must BEAT the anchor
34
+ # with the FROZEN constants in tests/verifier-correctness-manifest.json:
35
+ # baseline_bpb = 1.9550684328299388 , ref_speedup = 1.533747535323529
36
+ # Both were measured on H20 **on the corpus built by the recipe below**. They are
37
+ # valid for YOUR build only if (a) the GPU matches and (b) the corpus reproduces.
38
+ # The scored path deliberately refuses VERIFIER_MODE (anti-cheat), so re-calibrate by
39
+ # scoring the SHIPPED reference recipes AS THE CANDIDATE:
40
+ # # 1) the strong baseline -> new baseline_bpb
41
+ # docker run --rm --gpus all --shm-size=8g \
42
+ # -v "$PWD/solution/baseline_dense_floor:/app/submission:ro" \
43
+ # -v "$PWD/tests:/tests:ro" fai/e2e-a3-moe-train-budget:oss bash /tests/test.sh
44
+ # # 2) the oracle -> new oracle_bpb ; ref_speedup = baseline_bpb / oracle_bpb
45
+ # docker run --rm --gpus all --shm-size=8g \
46
+ # -v "$PWD/solution/oracle_grouped_moe:/app/submission:ro" \
47
+ # -v "$PWD/tests:/tests:ro" fai/e2e-a3-moe-train-budget:oss bash /tests/test.sh
48
+ # Read val_bpb from /logs/verifier/benchmark_results.json (median of >=3 runs) and write
49
+ # both numbers into tests/verifier-correctness-manifest.json -> reward_model.
50
+ # (ref_speedup <= 1 or missing => HARD FAIL 0 by design.)
51
+ #
52
+ # VERSION ANCHORS (reproduce the original runtime; see task.toml)
53
+ # CUDA 12.6 · Python 3.10 · torch 2.7.0 (cu126) · sentencepiece 0.2.1 · numpy>=1.26,<3
54
+ #
55
+ # WORKING TREE: /app/repo = nanoGPT + a vendored torchao package (~650 files)
56
+ # The original private base materialised this tree; the task package ships no vendored
57
+ # copy, so it is reconstructed here with `git clone` (nanoGPT for the training system,
58
+ # pytorch/ao for the low-precision ops). Both are pure Python at this layer, so the tree
59
+ # is a REAL directory (not a symlink) and edits inside it take effect directly — the
60
+ # symlink trick is only needed for packages with compiled extensions.
61
+ #
62
+ # The original private overlay is kept beside this file as Dockerfile.orig_private_base.
63
+ # =============================================================================
64
+ FROM nvidia/cuda:12.6.2-devel-ubuntu22.04
65
+
66
+ ARG TORCH_CUDA_ARCH_LIST="9.0"
67
+ # Pinned to a concrete commit (nanoGPT publishes no tags) so the graded training system is
68
+ # byte-reproducible; a floating `master` would drift and make scores incomparable over time.
69
+ ARG NANOGPT_REF="3adf61e154c3fe3fca428ad6bc3818b27a3b8291"
70
+ ARG TORCHAO_REF="v0.9.0"
71
+ ARG WIKITEXT_REPO="Salesforce/wikitext"
72
+ ARG WIKITEXT_CONFIG="wikitext-103-raw-v1"
73
+
74
+ ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \
75
+ PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1
76
+
77
+ RUN apt-get update && apt-get install -y --no-install-recommends \
78
+ build-essential gcc-10 g++-10 cmake ninja-build pkg-config \
79
+ python3.10 python3.10-dev python3.10-venv python3-pip python-is-python3 \
80
+ git git-lfs curl wget ca-certificates procps psmisc coreutils \
81
+ tar gzip unzip xz-utils vim less file jq tini \
82
+ && update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 \
83
+ && update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 100 \
84
+ && rm -rf /var/lib/apt/lists/*
85
+
86
+ # ---- venv. Keep this exact path: tests/test.sh pins /opt/kernelbench-venv/bin ----
87
+ ENV VENV=/opt/kernelbench-venv
88
+ RUN python3.10 -m venv "$VENV"
89
+ ENV PATH=$VENV/bin:/usr/local/cuda/bin:$PATH \
90
+ TORCH_CUDA_ARCH_LIST=${TORCH_CUDA_ARCH_LIST} \
91
+ PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
92
+ TORCH_EXTENSIONS_DIR=/app/.cache/torch_extensions
93
+ RUN pip install --no-cache-dir -U pip setuptools wheel
94
+
95
+ # ---- DL stack + the exact support libraries the training path imports, from PUBLIC indexes ----
96
+ RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cu126 \
97
+ "torch==2.7.0" \
98
+ && python -c "import torch; assert torch.__version__.startswith('2.7.0'), torch.__version__; print('torch', torch.__version__)"
99
+ RUN printf 'torch==2.7.0\n' > /tmp/constraints.txt \
100
+ && pip install --no-cache-dir --constraint /tmp/constraints.txt \
101
+ "sentencepiece==0.2.1" "pyarrow==17.0.0" "numpy>=1.26,<3" "einops==0.8.0" \
102
+ "tqdm==4.66.5" "psutil" "huggingface_hub>=0.24,<1" \
103
+ && python -c "import torch; assert torch.__version__.startswith('2.7.0'), torch.__version__"
104
+
105
+ # ---- /app/repo: the nanoGPT training system + a vendored torchao package.
106
+ # Pinned by ARG so a future user can move either ref without editing this file.
107
+ # No `|| true` anywhere: a silently empty /app/repo would destroy the task. ----
108
+ RUN set -eu; \
109
+ mkdir -p /app/repo; cd /app/repo; git init -q; \
110
+ git remote add origin https://github.com/karpathy/nanoGPT.git; \
111
+ git fetch -q --depth 1 origin "${NANOGPT_REF}"; \
112
+ git checkout -q FETCH_HEAD; \
113
+ rm -rf /app/repo/.git /app/repo/assets; \
114
+ git clone --depth 1 --branch "${TORCHAO_REF}" https://github.com/pytorch/ao.git /tmp/ao; \
115
+ mv /tmp/ao/torchao /app/repo/torchao; \
116
+ rm -rf /tmp/ao; \
117
+ for m in /app/repo/model.py /app/repo/train.py /app/repo/configurator.py /app/repo/bench.py; do \
118
+ test -f "$m" || { echo "BUILD_ASSERT_FATAL: /app/repo marker missing: $m"; exit 1; }; \
119
+ done; \
120
+ test -f /app/repo/torchao/__init__.py || { echo "BUILD_ASSERT_FATAL: torchao package missing"; exit 1; }; \
121
+ n=$(find /app/repo -type f -not -path '*/.git/*' | wc -l); \
122
+ echo "[build] /app/repo non-.git file count = $n (original base shipped ~650)"; \
123
+ test "$n" -ge 300 || { echo "BUILD_ASSERT_FATAL: /app/repo has only $n files - clone mutilated"; exit 1; }; \
124
+ t=$(find /app/repo -maxdepth 2 -type f -not -path '*/torchao/*' | wc -l); \
125
+ test "$t" -ge 15 || { echo "BUILD_ASSERT_FATAL: only $t nanoGPT top-level files (<15)"; exit 1; }; \
126
+ python -c 'import sys;sys.path.insert(0,"/app/repo");import model;print("[build] nanoGPT import OK",model.__file__)'
127
+
128
+ # ---- THE CORPUS. The original private base shipped /data/datasets/wikitext_bpe8k/{train,val}.bin
129
+ # and /data/tokenizers/wikitext_bpe8k.model as opaque blobs. Shipping them in a public task
130
+ # package is not an option (hundreds of MB), so they are REBUILT here from the public
131
+ # WikiText-103-raw dataset with a deterministic recipe: fixed source revision, fixed
132
+ # SentencePiece BPE settings (vocab 8192 -> fits uint16), single thread, no input shuffle.
133
+ # The frozen reward anchors were calibrated on this corpus; the fingerprints printed at the
134
+ # end let you confirm your rebuild matches (if it does not, re-calibrate — see the header).
135
+ RUN python - <<'PY'
136
+ import hashlib, os, pathlib, sys
137
+ import numpy as np, pyarrow.parquet as pq, sentencepiece as spm
138
+ from huggingface_hub import snapshot_download
139
+
140
+ REPO = os.environ.get("WIKITEXT_REPO", "Salesforce/wikitext")
141
+ CFG = os.environ.get("WIKITEXT_CONFIG", "wikitext-103-raw-v1")
142
+ DATA, TOK = "/data/datasets/wikitext_bpe8k", "/data/tokenizers"
143
+ os.makedirs(DATA, exist_ok=True); os.makedirs(TOK, exist_ok=True)
144
+ EOS = 2
145
+
146
+ local = snapshot_download(repo_id=REPO, repo_type="dataset", allow_patterns=[f"{CFG}/*"])
147
+ root = pathlib.Path(local, CFG)
148
+
149
+ def split(name):
150
+ files = sorted(root.glob(f"{name}-*.parquet")) or sorted(root.glob(f"*{name}*.parquet"))
151
+ if not files:
152
+ sys.exit(f"BUILD_ASSERT_FATAL: no parquet for split {name!r} under {root}")
153
+ out = []
154
+ for f in files:
155
+ out.extend(pq.read_table(f).column("text").to_pylist())
156
+ return out
157
+
158
+ train, val = split("train"), split("validation")
159
+ print(f"[corpus] raw lines: train={len(train)} val={len(val)}")
160
+
161
+ spm_in = "/tmp/spm_input.txt"
162
+ with open(spm_in, "w", encoding="utf-8") as fh:
163
+ for line in train:
164
+ line = line.strip()
165
+ if line:
166
+ fh.write(line + "\n")
167
+
168
+ spm.SentencePieceTrainer.train(
169
+ input=spm_in, model_prefix=f"{TOK}/wikitext_bpe8k",
170
+ vocab_size=8192, model_type="bpe", character_coverage=0.9995,
171
+ input_sentence_size=2000000, shuffle_input_sentence=False,
172
+ num_threads=1, seed_sentencepiece_size=1000000,
173
+ unk_id=0, bos_id=1, eos_id=2, pad_id=-1,
174
+ )
175
+ os.remove(spm_in)
176
+ sp = spm.SentencePieceProcessor(model_file=f"{TOK}/wikitext_bpe8k.model")
177
+ assert sp.get_piece_size() == 8192, sp.get_piece_size()
178
+
179
+ def encode(lines, out, chunk=20000, flush=8_000_000):
180
+ total, buf = 0, []
181
+ with open(out, "wb") as fh:
182
+ for i in range(0, len(lines), chunk):
183
+ batch = [t.strip() for t in lines[i:i + chunk] if t.strip()]
184
+ if not batch:
185
+ continue
186
+ for ids in sp.encode(batch):
187
+ buf.extend(ids); buf.append(EOS)
188
+ if len(buf) >= flush:
189
+ np.asarray(buf, dtype=np.uint16).tofile(fh); total += len(buf); buf = []
190
+ if buf:
191
+ np.asarray(buf, dtype=np.uint16).tofile(fh); total += len(buf)
192
+ return total
193
+
194
+ n_tr = encode(train, f"{DATA}/train.bin")
195
+ n_va = encode(val, f"{DATA}/val.bin")
196
+ print(f"[corpus] tokens: train={n_tr:,} val={n_va:,}")
197
+ if n_tr < 30_000_000:
198
+ sys.exit(f"BUILD_ASSERT_FATAL: train corpus only {n_tr} tokens - the graded token budget needs more")
199
+ if n_va < 100_000:
200
+ sys.exit(f"BUILD_ASSERT_FATAL: val corpus only {n_va} tokens")
201
+
202
+ def sha(p, cap=None):
203
+ h = hashlib.sha256()
204
+ with open(p, "rb") as fh:
205
+ h.update(fh.read() if cap is None else fh.read(cap))
206
+ return h.hexdigest()
207
+
208
+ print("[corpus] FINGERPRINTS (compare against a known-good build before trusting the anchors)")
209
+ print(" tokenizer.model sha256 =", sha(f"{TOK}/wikitext_bpe8k.model"))
210
+ print(" train.bin first 1MiB sha256 =", sha(f"{DATA}/train.bin", 1 << 20))
211
+ print(" val.bin sha256 =", sha(f"{DATA}/val.bin"))
212
+ print(" train tokens =", n_tr, "| val tokens =", n_va)
213
+ PY
214
+
215
+ # ---- solver-owned submission: the working-but-beatable STARTER (not the answer) ----
216
+ RUN rm -rf /app/submission && mkdir -p /app/submission /app/.cache/torch_extensions /logs/verifier /logs/artifacts /app/.timer
217
+ COPY environment/submission/ /app/submission/
218
+ COPY instruction.md /app/instruction.md
219
+ RUN chmod +x /app/submission/run_training.sh
220
+
221
+ # ---- git baseline for the editable tree: ONE commit as the diff base, no remote, no reflog ----
222
+ RUN git config --global user.email "reviewer@fai-bench.local" \
223
+ && git config --global user.name "fai-bench" \
224
+ && git config --global init.defaultBranch main \
225
+ && git config --global --add safe.directory /app/repo \
226
+ && git config --global --add safe.directory /app/submission \
227
+ && cd /app/repo \
228
+ && printf '__pycache__/\n*.pyc\nmodel_ckpt.pt\n*.tmp\n' > /app/repo/.gitignore \
229
+ && git init -q . \
230
+ && git add -A && git commit -qm "nanoGPT baseline system" \
231
+ && rm -rf /app/repo/.git/logs \
232
+ && test "$(git rev-list --count HEAD)" = "1" \
233
+ && test -z "$(git remote)" \
234
+ && test ! -e /app/repo/.git/logs \
235
+ && echo "[build] /app/repo: fresh 1-commit git, no remote, no reflog"
236
+
237
+ # ---- OPEN grading suite is NOT baked into the image (by design).
238
+ # tests/ (test.sh + compute_reward.py + the held-out corpus + the frozen manifest carrying
239
+ # baseline_bpb / ref_speedup) is MOUNTED FRESH at /tests when scoring. It ships in this
240
+ # package — open-source, but deliberately outside the image so the solver can neither read
241
+ # the held-out text nor the calibrated anchors while solving.
242
+
243
+ # ---- ANTI-LEAK ASSERTS: the anchors and the held-out surface must NOT be visible to the
244
+ # solver. Any regression that re-introduces them dies here, at build time. ----
245
+ RUN set -eu; rc=0; \
246
+ for p in /opt/verifier /opt/strong_baseline /opt/naive /opt/negative /opt/ceiling \
247
+ /opt/oracle /opt/solution /app/solution /app/tests; do \
248
+ if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: leak path present: $p"; rc=1; fi; \
249
+ done; \
250
+ if [ -d /tests ] && [ -n "$(find /tests -mindepth 1 -type f 2>/dev/null | head -1)" ]; then \
251
+ echo "BUILD_ASSERT_FAIL: /tests contains baked files"; rc=1; \
252
+ fi; \
253
+ for f in verifier-correctness-manifest.json compute_reward.py; do \
254
+ hits=$(find / -xdev -name "$f" -not -path '/proc/*' -not -path '/sys/*' 2>/dev/null | head -3); \
255
+ if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface file baked: $hits"; rc=1; fi; \
256
+ done; \
257
+ if grep -rslE 'ref_speedup|baseline_bpb|strong_baseline_bpb' /app 2>/dev/null | head -3 | grep -q .; then \
258
+ echo "BUILD_ASSERT_FAIL: a calibrated anchor token is visible under /app"; rc=1; \
259
+ fi; \
260
+ test "$rc" = 0; \
261
+ echo "[build] ANTI-LEAK ASSERTS PASS: no frozen surface, no reference recipe, no anchor under /app"
262
+
263
+ # ---- runtime contract: entrypoint + elapsed-time daemon ----
264
+ RUN printf '#!/bin/bash\nset -e\nmkdir -p /app/.timer\nnohup /app/timer.sh >/app/.timer/timer.log 2>&1 &\nif [ "$#" -gt 0 ]; then exec "$@"; fi\nexec /bin/bash -l\n' > /app/entrypoint.sh \
265
+ && chmod +x /app/entrypoint.sh \
266
+ && printf '#!/bin/bash\nmkdir -p /app/.timer\nSTART=$(date +%%s)\nwhile true; do echo $(( $(date +%%s) - START )) > /app/.timer/elapsed; sleep 5; done\n' > /app/timer.sh \
267
+ && chmod 755 /app/timer.sh
268
+
269
+ ENV NANOGPT_REPO=/app/repo \
270
+ PYTHONPATH=/app/repo \
271
+ SUBMISSION_DIR=/app/submission \
272
+ REPO_DIR=/app/repo \
273
+ DATA_PATH=/data/datasets/wikitext_bpe8k \
274
+ TOKENIZER_PATH=/data/tokenizers/wikitext_bpe8k.model \
275
+ LD_LIBRARY_PATH=/opt/kernelbench-venv/lib/python3.10/site-packages/torch/lib:/usr/local/cuda/lib64:/usr/local/nvidia/lib64
276
+ WORKDIR /app
277
+
278
+ # ---- build-time smoke.
279
+ # HARD: torch pin, nanoGPT + torchao import, the corpus is present and readable as
280
+ # uint16, the tokenizer loads with 8192 pieces, the starter entry exists,
281
+ # /app/repo has exactly one commit.
282
+ # SOFT: nothing GPU-dependent is asserted (the build host has no card).
283
+ RUN python - <<'PY'
284
+ import os, subprocess, sys
285
+ import numpy as np, torch, sentencepiece as spm
286
+ sys.path.insert(0, "/app/repo")
287
+ print("torch", torch.__version__)
288
+ assert torch.__version__.startswith("2.7.0"), torch.__version__
289
+ import model as nanogpt_model, torchao
290
+ print("nanoGPT", nanogpt_model.__file__, "| torchao", torchao.__file__)
291
+
292
+ d = np.memmap("/data/datasets/wikitext_bpe8k/train.bin", dtype=np.uint16, mode="r")
293
+ v = np.memmap("/data/datasets/wikitext_bpe8k/val.bin", dtype=np.uint16, mode="r")
294
+ print("corpus tokens: train", f"{d.size:,}", "| val", f"{v.size:,}", "| max id", int(d[:1_000_000].max()))
295
+ assert d.size > 30_000_000 and v.size > 100_000
296
+ sp = spm.SentencePieceProcessor(model_file="/data/tokenizers/wikitext_bpe8k.model")
297
+ assert sp.get_piece_size() == 8192
298
+
299
+ for f in ("/app/submission/train_gpt.py", "/app/submission/run_training.sh"):
300
+ assert os.path.isfile(f), f"submission entry missing: {f}"
301
+ n = subprocess.run(["git", "-C", "/app/repo", "rev-list", "--count", "HEAD"],
302
+ capture_output=True, text=True).stdout.strip()
303
+ assert n == "1", f"git diff base broken (commits={n!r})"
304
+ print("OK: env, working tree, corpus and starter all in place")
305
+ PY
306
+
307
+ ENTRYPOINT ["/app/entrypoint.sh"]
308
+ CMD ["tail","-f","/dev/null"]
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/Dockerfile ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # -loop16 overlay for e2e-a3-moe-train-budget (a4-token-efficiency-budget's sibling).
3
+ # FROM the de-leaked single-shot base image; add /opt/loop/ (submit + score_engine + sanitize +
4
+ # private dev-training proxy + baked pristine starter) and swap /app/instruction.md for the loop16
5
+ # combined statement. Pure additive layer — NO dependency change, NO change to /tests,
6
+ # compute_reward.py, or ANY graded code path. Preferably applied with `crane append` (~8s, zero GPU);
7
+ # this Dockerfile is the docker-build fallback and the authoritative description of the layer. No GPU
8
+ # is needed to BUILD the overlay; the base needs 1 NVIDIA GPU to RUN/score.
9
+ #
10
+ # BUILD (context = THIS directory, environment/loop_overlay/):
11
+ # cd <...>/a3-moe-train-budget/task
12
+ # docker build -f environment/Dockerfile -t fai/e2e-a3-moe-train-budget:oss .
13
+ # docker build -f environment/loop_overlay/Dockerfile -t fai/e2e-a3-moe-train-budget:oss-loop16 environment/loop_overlay
14
+ #
15
+ # 🔴 Structural red-line (modes MUST also be baked into the crane tar header, since `crane append`
16
+ # runs no RUN): submit.sh 0755 root; score_engine.sh + everything under /opt/loop/private/ +
17
+ # /opt/loop/baseline_submission/ is 0700/0600 root (unreadable by the solver's dropped uid). The
18
+ # private dir carries NO held-out corpus, NO reference recipe and NO calibrated anchor — only public
19
+ # dev-proxy constants (a SHORT dev wall-clock + a SMALL public dev shard + a fixed dev seed).
20
+ ARG BASE_IMAGE=fai/e2e-a3-moe-train-budget:oss
21
+ FROM ${BASE_IMAGE}
22
+ SHELL ["/bin/bash","-c"]
23
+
24
+ RUN test ! -e /opt/loop || { echo "BUILD_ASSERT_FAIL: base already has /opt/loop"; exit 1; }
25
+
26
+ COPY opt_loop/ /opt/loop/
27
+ COPY instruction_loop16.md /app/instruction.md
28
+
29
+ RUN chown -R root:root /opt/loop \
30
+ && chmod 0755 /opt/loop \
31
+ && chmod 0755 /opt/loop/submit.sh \
32
+ && chmod 0700 /opt/loop/score_engine.sh \
33
+ && chmod -R go-rwx /opt/loop/private /opt/loop/baseline_submission \
34
+ && chmod 0700 /opt/loop/private /opt/loop/baseline_submission \
35
+ && find /opt/loop/private /opt/loop/baseline_submission -type f -exec chmod 0600 {} \; \
36
+ && find /opt/loop/private /opt/loop/baseline_submission -type d -exec chmod 0700 {} \; \
37
+ && chmod 0644 /app/instruction.md
38
+
39
+ # /logs/loop is created world-writable at runtime by submit.sh; nothing to bake.
40
+
41
+ # 🔴 build-time assert: the overlay must carry NO calibrated anchor VALUE (baseline_bpb / ref_speedup
42
+ # / oracle_bpb) and NO reference recipe. Prose that NAMES baseline_bpb/ref_speedup to explain their
43
+ # ABSENCE is fine; a VALUE is not.
44
+ RUN set -eu; rc=0; \
45
+ if grep -rIEq "1\.9550684328299388|1\.533747535323529|1\.2747002931075853|1\.95506|1\.53374" /opt/loop; then \
46
+ echo "BUILD_ASSERT_FAIL: calibrated anchor VALUE present in /opt/loop"; rc=1; fi; \
47
+ hits="$(find /opt/loop -type f \( -name 'oracle_grouped_moe*' -o -name 'baseline_dense_floor*' \
48
+ -o -name 'holdout_corpus*' -o -name 'verifier-correctness-manifest.json' \) 2>/dev/null | head -10)"; \
49
+ if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: reference/anchor/held-out file baked into /opt/loop:"; echo "$hits"; rc=1; fi; \
50
+ test -f /opt/loop/submit.sh && test -x /opt/loop/submit.sh || { echo "submit.sh missing/not exec"; rc=1; }; \
51
+ test -f /opt/loop/private/dev_eval.py || { echo "dev-proxy dev_eval.py missing"; rc=1; }; \
52
+ test "$rc" = 0 && echo "[build] loop16 overlay asserts PASS"
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/instruction_loop16.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Train the best Mixture-of-Experts language model you can within a fixed budget — loop16 protocol
2
+
3
+ You are given the full [nanoGPT](https://github.com/karpathy/nanoGPT) training system at `/app/repo`
4
+ (fully editable) and a tokenized WikiText-103 corpus on ONE **NVIDIA H20** GPU. Train the best
5
+ language model you can within a fixed **wall-clock budget**, subject to a **hard total-parameter
6
+ FLOOR** (the grader re-counts your model's total parameters and rejects a sub-floor model), then the
7
+ grader scores its **bits-per-byte (`val_bpb`) on a held-out split you never see** — lower is better.
8
+
9
+ At the required capacity a DENSE model is too compute-heavy to train well in the budget; a sparse
10
+ top-k Mixture-of-Experts trains far more steps at the same total capacity — IF you realize the
11
+ sparsity as real single-card throughput (sorted/grouped-GEMM token dispatch) with a balanced router
12
+ (load-balancing aux loss) and a tuned top-k / experts / capacity frontier. The shipped starter is a
13
+ plain dense model at the floor and is the bar to beat.
14
+
15
+ ## Entry contract (start from the shipped files)
16
+
17
+ - `/app/submission/run_training.sh` — the harness runs it under a harness-owned wall-clock timer with
18
+ `SEED`, `PARAM_FLOOR`, `WALLCLOCK_SEC`, `OUT_CKPT`, `DATA_PATH`, `TOKENIZER_PATH`,
19
+ `NANOGPT_REPO=/app/repo` set. It MUST write a checkpoint to `$OUT_CKPT` within the budget (save
20
+ periodically — the timer can stop you at any moment).
21
+ - `/app/submission/train_gpt.py` — must keep `load_model_for_verification(checkpoint_path, device)`
22
+ importable, returning a model whose `model(x) -> logits (B,T,V)` and `model(x,y) -> scalar CE loss`
23
+ (keep any load-balancing aux loss INSIDE your training loop, not in this forward). All of
24
+ `/app/repo` (nanoGPT) and `/app/submission` is editable. Leave changes in the working tree; do not
25
+ `git commit`.
26
+
27
+ ---
28
+
29
+ ## How you are graded (loop16: iterate in-session, at most 16 self-scored submissions)
30
+
31
+ This task uses the **loop16 protocol**: in your session you may score your current recipe and get
32
+ feedback **at most 16 times, at least once — you decide when to stop** (you need not use all 16).
33
+
34
+ ### 1. Each round
35
+ After editing, run
36
+
37
+ ```
38
+ bash /opt/loop/submit.sh
39
+ ```
40
+
41
+ It trains your recipe on a **SMALL PUBLIC dev shard** of the corpus for a **SHORT dev wall-clock**
42
+ (far below the graded budget), under the same uid-drop the grade uses, then reloads the checkpoint
43
+ and runs a first-principles self-check (total-param floor, forward CE agreement, logits vary,
44
+ plausible band) and reports a **dev `val_bpb`** on the PUBLIC val split, best_so_far and the remaining
45
+ budget.
46
+
47
+ 🔴 **That dev `val_bpb` is a PUBLIC proxy, not your graded score.** The overlay contains NO held-out
48
+ corpus and NO calibrated anchor. Unlike some siblings, this task's budget is WALL-CLOCK, so the dev
49
+ `val_bpb` depends on both your recipe AND this node's speed and is only a COARSE **direction** signal
50
+ (a more efficient recipe should reach a lower `val_bpb` in the short dev budget). The graded run trains
51
+ at the FULL budget on the HIDDEN split with the calibrated anchor. Do not overfit to the dev shard.
52
+
53
+ ### 2. Finalize
54
+ When satisfied (or at the 16th round, which auto-finalizes) run
55
+
56
+ ```
57
+ bash /opt/loop/submit.sh --finalize --reason "<one sentence on why you are stopping>"
58
+ ```
59
+
60
+ `--reason` is mandatory and audited. The graded submission is your **best** correctness-passing round
61
+ (best-of-k, chosen by dev `val_bpb` and planted for grading; `/app/repo` HEAD stays at the baked
62
+ baseline commit). A justified stop at k=1 scores the same as using all 16; there is no minimum and no
63
+ "keep going until N rounds without gain" rule.
64
+
65
+ ## Red line (any one makes the whole task score 0)
66
+
67
+ - Do **not** read, `cat`, `grep`, `find`, copy or edit any verifier / hidden-test / evaluation file
68
+ (under `/tests`, `/opt/loop/private`), and do not try to infer their contents — `bash
69
+ /opt/loop/submit.sh` is the only sanctioned way to score.
70
+ - Do **not** run the grader directly, reproduce or reverse-engineer it.
71
+ - Do **not** search for / print / infer the hidden test split, the fixed seeds, the wall-clock budget,
72
+ any threshold, the baseline `val_bpb` or the reference score.
73
+ - Do **not** forge the loss, smuggle a pre-built checkpoint, train on anything other than the shard at
74
+ `DATA_PATH`, or tamper with the parameter / budget / uid guards.
75
+ - Do **not** fetch an upstream reference solution or access the internet at runtime. The public method
76
+ (modded-nanogpt, Muon, MoE routing literature) is allowed; the MEASUREMENT is protected.
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/baseline_submission/run_training.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; fully editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR, WALLCLOCK_SEC,
4
+ # OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ #
6
+ # It MUST write a checkpoint to $OUT_CKPT within the budget (save periodically — the timer can
7
+ # stop you at any moment) and leave load_model_for_verification(checkpoint_path, device)
8
+ # importable from /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
9
+ # (the grader re-counts it).
10
+ #
11
+ # This starting version runs the provided dense baseline. Change anything you like — nanoGPT
12
+ # under /app/repo is fully editable too.
13
+ set -e
14
+ cd /app/submission
15
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/baseline_submission/train_gpt.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # e2e-a3-moe-train-budget — the provided STARTING POINT (fully editable, NOT a contract).
2
+ #
3
+ # This is a plain DENSE nanoGPT sized to clear the task's hard total-parameter FLOOR, trained
4
+ # with a straightforward AdamW recipe until the harness's wall-clock timer stops it. It is a
5
+ # complete, working, honest baseline: real data loading, bf16 autocast, warmup + cosine decay,
6
+ # gradient clipping, and an atomic periodic checkpoint save so a timer kill always leaves a
7
+ # valid artifact. It satisfies the verifier's entry contract as-is.
8
+ #
9
+ # It is also DELIBERATELY the thing you have to beat. Because it is dense, every token pays
10
+ # the full ~2*P_total FLOPs, so it fits comparatively few optimizer steps into the budget and
11
+ # converges to a mediocre held-out bits-per-byte. Submitting it unchanged scores 0.
12
+ #
13
+ # You may change anything: the model, the router, the dispatch, the optimizer, the schedule,
14
+ # the data loading, the precision — everything under /app/repo (nanoGPT) and /app/submission.
15
+ #
16
+ # VERIFIER CONTRACT (enforced): the grader loads the checkpoint via
17
+ # load_model_for_verification(checkpoint_path, device) and requires a model whose
18
+ # * model(input_ids) -> float logits (batch, seq, vocab), position-dependent
19
+ # * model(input_ids, target_ids) -> scalar loss == CE(logits.view(-1,V), targets.view(-1))
20
+ # i.e. the PURE cross-entropy of those logits. If you add an auxiliary training objective
21
+ # (for example a load-balancing loss), keep it inside your training loop — do NOT fold it into
22
+ # the loss this forward returns. An OOD probe enforces loss(real_text) < 0.7 * loss(arbitrary
23
+ # ids), and the model must clear the total-parameter floor.
24
+ from __future__ import annotations
25
+
26
+ import math
27
+ import os
28
+ import sys
29
+ import time
30
+ from pathlib import Path
31
+
32
+ import numpy as np
33
+ import torch
34
+ import torch.nn as nn
35
+
36
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
37
+ if REPO not in sys.path:
38
+ sys.path.insert(0, REPO)
39
+ from model import GPT, GPTConfig # noqa: E402 (from /app/repo/model.py)
40
+
41
+
42
+ class Hyperparameters:
43
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
44
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
45
+ seed = int(os.environ.get("SEED", "1337"))
46
+ out_ckpt = os.environ.get("OUT_CKPT", "/app/submission/model_ckpt.pt")
47
+ wallclock_sec = float(os.environ.get("WALLCLOCK_SEC", "600"))
48
+
49
+ vocab_size = 8192
50
+ train_seq_len = 512
51
+ block_size = 512
52
+ val_batch_size = 32_768
53
+
54
+ # DENSE model sized to clear the 150M floor: n_embd=1024,n_layer=12 nanoGPT
55
+ # transformer ~= 12*(12*1024^2) = 151.0M + tied wte 8.4M + wpe 0.5M ~= 160M.
56
+ n_layer = 12
57
+ n_head = 16
58
+ n_embd = 1024
59
+ dropout = 0.0
60
+ bias = False
61
+
62
+ # SAME recipe as the strong MoE baseline (fair comparison; only dense-vs-sparse differs)
63
+ micro_batch = 16
64
+ grad_accum = 2
65
+ learning_rate = 3e-3
66
+ weight_decay = 0.1
67
+ beta1, beta2 = 0.9, 0.95
68
+ grad_clip = 1.0
69
+ warmup_frac = 0.05
70
+ min_lr_frac = 0.1
71
+ save_every_sec = 20.0
72
+
73
+
74
+ class _VerifierAdapter(nn.Module):
75
+ def __init__(self, gpt: GPT):
76
+ super().__init__()
77
+ self.gpt = gpt
78
+
79
+ def forward(self, idx, targets=None):
80
+ logits, loss = self.gpt(idx, idx if targets is None else targets)
81
+ return logits if targets is None else loss
82
+
83
+
84
+ def _cfg(args: Hyperparameters) -> GPTConfig:
85
+ return GPTConfig(block_size=args.block_size, vocab_size=args.vocab_size,
86
+ n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd,
87
+ dropout=args.dropout, bias=args.bias)
88
+
89
+
90
+ def load_model_for_verification(checkpoint_path, device):
91
+ args = Hyperparameters()
92
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
93
+ cfg_kwargs = obj.get("config", {})
94
+ cfg = GPTConfig(**cfg_kwargs) if cfg_kwargs else _cfg(args)
95
+ gpt = GPT(cfg)
96
+ gpt.load_state_dict(obj["model"], strict=True)
97
+ args.train_seq_len = cfg.block_size
98
+ args.vocab_size = cfg.vocab_size
99
+ return args, _VerifierAdapter(gpt).to(device).eval()
100
+
101
+
102
+ def _save(model: GPT, cfg: GPTConfig, out_ckpt: str) -> None:
103
+ tmp = out_ckpt + ".tmp"
104
+ torch.save({"model": model.state_dict(),
105
+ "config": dict(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
106
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
107
+ dropout=0.0, bias=cfg.bias)}, tmp)
108
+ os.replace(tmp, out_ckpt)
109
+
110
+
111
+ class _MemmapLoader:
112
+ def __init__(self, data_path: str, seq_len: int, device: torch.device, seed: int):
113
+ self.data = np.memmap(Path(data_path) / "train.bin", dtype=np.uint16, mode="r")
114
+ self.seq_len = seq_len
115
+ self.device = device
116
+ self.rng = np.random.default_rng(seed)
117
+
118
+ def batch(self, n: int):
119
+ ix = self.rng.integers(0, len(self.data) - self.seq_len - 1, size=n)
120
+ x = torch.from_numpy(np.stack([self.data[i:i + self.seq_len].astype(np.int64) for i in ix]))
121
+ y = torch.from_numpy(np.stack([self.data[i + 1:i + 1 + self.seq_len].astype(np.int64) for i in ix]))
122
+ return (x.pin_memory().to(self.device, non_blocking=True),
123
+ y.pin_memory().to(self.device, non_blocking=True))
124
+
125
+
126
+ def main() -> None:
127
+ args = Hyperparameters()
128
+ torch.manual_seed(args.seed)
129
+ np.random.seed(args.seed)
130
+ torch.backends.cuda.matmul.allow_tf32 = True
131
+ torch.backends.cudnn.allow_tf32 = True
132
+ device = torch.device("cuda", 0)
133
+ torch.cuda.set_device(device)
134
+
135
+ cfg = _cfg(args)
136
+ model = GPT(cfg).to(device)
137
+ n_params = sum(p.numel() for p in model.parameters())
138
+ print(f"[train] DENSE {n_params/1e6:.1f}M params | layers={args.n_layer} "
139
+ f"d={args.n_embd} | micro={args.micro_batch} accum={args.grad_accum} "
140
+ f"seq={args.train_seq_len}", flush=True)
141
+
142
+ loader = _MemmapLoader(args.data_path, args.train_seq_len, device, args.seed)
143
+ opt = torch.optim.AdamW(model.parameters(), lr=args.learning_rate,
144
+ weight_decay=args.weight_decay, betas=(args.beta1, args.beta2),
145
+ fused=True)
146
+
147
+ start = time.time()
148
+ deadline = start + args.wallclock_sec * 0.94
149
+ est_total_steps = 6000
150
+ warmup = max(1, int(args.warmup_frac * est_total_steps))
151
+ last_save = start
152
+ step = 0
153
+ model.train()
154
+ while time.time() < deadline:
155
+ lr = (args.learning_rate * (step + 1) / warmup if step < warmup
156
+ else args.learning_rate * (args.min_lr_frac + (1 - args.min_lr_frac) *
157
+ 0.5 * (1 + math.cos(math.pi * min(1.0, (step - warmup) / max(1, est_total_steps - warmup))))))
158
+ for g in opt.param_groups:
159
+ g["lr"] = lr
160
+ opt.zero_grad(set_to_none=True)
161
+ for _ in range(args.grad_accum):
162
+ x, y = loader.batch(args.micro_batch)
163
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
164
+ _, loss = model(x, y)
165
+ (loss / args.grad_accum).backward()
166
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
167
+ opt.step()
168
+ step += 1
169
+ if step % 25 == 0:
170
+ print(f"[train] step {step} lr {lr:.2e} loss {loss.item():.4f} "
171
+ f"peakGB {torch.cuda.max_memory_allocated()/1e9:.2f} t {time.time()-start:.0f}s", flush=True)
172
+ if time.time() - last_save >= args.save_every_sec:
173
+ _save(model, cfg, args.out_ckpt)
174
+ last_save = time.time()
175
+ _save(model, cfg, args.out_ckpt)
176
+ print(f"[train] done: {step} steps in {time.time()-start:.0f}s -> {args.out_ckpt}", flush=True)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/private/dev_eval.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """/opt/loop/private/dev_eval.py — the per-round DEV proxy for e2e-a3-moe-train-budget.
3
+
4
+ Root-owned 0600, called ONLY by /opt/loop/score_engine.sh (0700). The solver's uid cannot read it.
5
+ Adapted from the a4-token-efficiency-budget dev_eval (its sibling); the ONLY substantive difference
6
+ is the entry contract: a3's training is wall-clock-budgeted and launched via run_training.sh, whereas
7
+ a4's is token-budgeted via train_for_budget().
8
+
9
+ WHAT IT DOES (a faithful, CHEAP mirror of the graded path, on PUBLIC data):
10
+ 1. Slices a SMALL public token shard out of the PUBLIC corpus the solver already has
11
+ (/data/datasets/wikitext_bpe8k/train.bin) into an isolated dev DATA_PATH.
12
+ 2. Runs the candidate's run_training.sh from an ISOLATED staging dir (source only; weight/data
13
+ blobs stripped) UNDER THE uid-65534 PRIVILEGE DROP the graded path uses, with a SHORT dev
14
+ wall-clock budget (dev_wallclock_sec) and a fixed dev seed.
15
+ 3. Reloads the checkpoint via the candidate's load_model_for_verification and runs a
16
+ FIRST-PRINCIPLES correctness self-check (total-param floor in the SAME [floor] the grade
17
+ enforces, forward(x)/forward(x,y) CE agreement, logits vary across positions, a plausible
18
+ val_bpb band) — no reference recipe and no anchor are needed to decide pass/fail.
19
+ 4. Computes val_bpb on the PUBLIC val split (/data/datasets/wikitext_bpe8k/val.bin) using the same
20
+ SentencePiece byte-LUT machinery as the grade, so the number is comparable.
21
+
22
+ WHAT IT NEVER TOUCHES: /tests, the held-out corpus, the calibrated baseline_bpb / ref_speedup, or ANY
23
+ environment-supplied threshold. The dev signal is an ABSOLUTE val_bpb, never normalised against the
24
+ graded anchor. Constants come from /opt/loop/private/manifest.json ONLY.
25
+
26
+ 🔴 GPU/REDUCED-WORKLOAD + FIDELITY NOTE: unlike a4 (whose budget is TOKENS and is therefore
27
+ node-speed-immune), a3's budget is WALL-CLOCK. The dev proxy runs a SHORT dev wall-clock
28
+ (dev_wallclock_sec, far below the graded budget) so a per-round pass is minutes not the full graded
29
+ run — but that makes the dev val_bpb a function of BOTH the recipe AND this node's speed. So the dev
30
+ val_bpb is only a COARSE direction signal: a recipe that trains more efficiently should reach a lower
31
+ val_bpb in the short dev budget, but the absolute number is not comparable across nodes and is not the
32
+ graded score. best-of-k still prefers the lower-dev-val_bpb correctness-passing snapshot; the
33
+ authoritative score is the runner end-of-session grade at the full budget with the calibrated anchor.
34
+
35
+ OUTPUT: /logs/loop/dev/{verifier_state.json, reward.json}; on infra failure, harness_error.txt.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import json
40
+ import math
41
+ import os
42
+ import shutil
43
+ import signal
44
+ import subprocess
45
+ import sys
46
+ import time
47
+ from pathlib import Path
48
+
49
+ LOOP_PRIVATE = Path("/opt/loop/private")
50
+ MANIFEST = LOOP_PRIVATE / "manifest.json"
51
+ DEV_OUT = Path("/logs/loop/dev")
52
+ DEV_OUT.mkdir(parents=True, exist_ok=True)
53
+
54
+ INV_SUBMISSION_MISSING = "submission_missing"
55
+ INV_NO_CHECKPOINT = "no_checkpoint_produced"
56
+ INV_PARAM_FLOOR = "param_below_floor"
57
+ INV_CE_AGREE = "forward_ce_disagreement"
58
+ INV_LOGITS_CONST = "logits_constant_across_positions"
59
+ INV_VAL_IMPLAUSIBLE = "val_bpb_implausible"
60
+ INV_VAL_FLOOR = "val_bpb_above_quality_floor"
61
+ INV_LOAD = "load_model_for_verification_failed"
62
+ INV_HARNESS = "harness_error"
63
+
64
+ _WEIGHT_EXT = {".pt", ".pth", ".ptz", ".bin", ".safetensors", ".ckpt", ".npz",
65
+ ".npy", ".pkl", ".pickle", ".h5", ".onnx", ".gguf", ".pt2"}
66
+
67
+
68
+ def _cfg() -> dict:
69
+ return json.loads(MANIFEST.read_text(encoding="utf-8"))
70
+
71
+
72
+ def _write_state(correctness_ok, failing_invariant, dev_val_bpb, dev_reward,
73
+ uid_dropped, observed_euid, extra=None):
74
+ reasons = [] if correctness_ok else ([failing_invariant] if failing_invariant else ["unknown"])
75
+ state = {"correctness_ok": bool(correctness_ok), "hard_fail_reasons": reasons,
76
+ "failing_invariant": failing_invariant or "",
77
+ "dev_uid_dropped": uid_dropped, "observed_euid": observed_euid}
78
+ if extra:
79
+ state.update(extra)
80
+ reward = {"dev_score": float(dev_reward),
81
+ "dev_metric": "val_bpb (PUBLIC dev proxy; lower is better; NOT your graded score)",
82
+ "dev_val_bpb": dev_val_bpb, "correctness_ok": bool(correctness_ok)}
83
+ (DEV_OUT / "verifier_state.json").write_text(json.dumps(state, sort_keys=True, indent=2) + "\n")
84
+ (DEV_OUT / "reward.json").write_text(json.dumps(reward, sort_keys=True, indent=2) + "\n")
85
+
86
+
87
+ def _harness_error(msg: str) -> None:
88
+ (DEV_OUT / "harness_error.txt").write_text(msg + "\n")
89
+ _write_state(False, INV_HARNESS, None, 0.0, None, None, {"harness_message": msg})
90
+
91
+
92
+ def build_dev_shard(corpus_dir: Path, shard_dir: Path, n_tokens: int, offset: int) -> bool:
93
+ import numpy as np
94
+ shard_dir.mkdir(parents=True, exist_ok=True)
95
+ src = corpus_dir / "train.bin"
96
+ if not src.exists():
97
+ return False
98
+ d = np.memmap(src, dtype=np.uint16, mode="r")
99
+ have = int(d.shape[0])
100
+ if have < n_tokens:
101
+ return False
102
+ off = offset if (0 <= offset <= have - n_tokens) else 0
103
+ np.asarray(d[off:off + n_tokens], dtype=np.uint16).tofile(shard_dir / "train.bin")
104
+ for extra in ("val.bin", "meta.pkl"):
105
+ sp = corpus_dir / extra
106
+ if sp.exists():
107
+ shutil.copy2(sp, shard_dir / extra)
108
+ return (shard_dir / "train.bin").stat().st_size // 2 == n_tokens
109
+
110
+
111
+ def train_candidate(cfg: dict, submission_dir: Path, shard_dir: Path, out_dir: Path):
112
+ """Run the candidate's run_training.sh on the dev shard under the uid drop and a SHORT dev
113
+ wall-clock budget. Returns (checkpoint_or_None, uid_dropped, observed_euid, note, stderr_tail)."""
114
+ out_dir.mkdir(parents=True, exist_ok=True)
115
+ stage = out_dir / "_stage_src"
116
+ stage.mkdir(parents=True, exist_ok=True)
117
+ src_root = submission_dir
118
+ try:
119
+ for p in src_root.rglob("*"):
120
+ if not p.is_file() or "_stage_src" in p.parts:
121
+ continue
122
+ if p.suffix.lower() in _WEIGHT_EXT or p.stat().st_size > 8 * 1024 * 1024:
123
+ continue
124
+ rel = p.relative_to(src_root)
125
+ (stage / rel).parent.mkdir(parents=True, exist_ok=True)
126
+ shutil.copy2(p, stage / rel)
127
+ except Exception:
128
+ pass
129
+ if not (stage / "run_training.sh").exists():
130
+ return None, False, None, "run_training.sh missing", ""
131
+
132
+ guard = float(cfg["dev_wallclock_sec"])
133
+ grace = float(cfg.get("dev_guard_grace_seconds", 30.0))
134
+ env = dict(os.environ)
135
+ env.pop("PYTHONPATH", None)
136
+ env.pop("PYTHONHOME", None)
137
+ env["SEED"] = str(int(cfg["dev_seed"]))
138
+ env["PARAM_FLOOR"] = str(int(cfg["dev_param_floor"]))
139
+ env["WALLCLOCK_SEC"] = str(guard)
140
+ env["OUT_CKPT"] = str(out_dir / "model_ckpt.pt")
141
+ env["DATA_PATH"] = str(shard_dir)
142
+ env["TOKENIZER_PATH"] = str(cfg["tokenizer_path"])
143
+ env["NANOGPT_REPO"] = str(cfg["nanogpt_repo"])
144
+ env["PATH"] = "/opt/kernelbench-venv/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/bin:/bin"
145
+
146
+ train_uid = cfg.get("dev_uid")
147
+ def preexec_plain():
148
+ os.setsid()
149
+ preexec = preexec_plain
150
+ if train_uid:
151
+ try:
152
+ anc = out_dir.resolve()
153
+ while str(anc) not in ("/", str(anc.parent)):
154
+ try:
155
+ if anc.stat().st_uid == os.getuid():
156
+ os.chmod(anc, 0o755)
157
+ except Exception:
158
+ pass
159
+ anc = anc.parent
160
+ os.chmod(stage, 0o777)
161
+ os.chmod(out_dir, 0o777)
162
+ for p in stage.rglob("*"):
163
+ try:
164
+ os.chmod(p, 0o777 if p.is_dir() else 0o666)
165
+ except Exception:
166
+ pass
167
+ os.chmod(shard_dir, 0o755)
168
+ for p in shard_dir.iterdir():
169
+ try:
170
+ os.chmod(p, 0o644)
171
+ except Exception:
172
+ pass
173
+ except Exception:
174
+ pass
175
+ home = out_dir / "_devhome"
176
+ home.mkdir(parents=True, exist_ok=True)
177
+ try:
178
+ os.chmod(home, 0o777)
179
+ except Exception:
180
+ pass
181
+ env["HOME"] = str(home)
182
+ env["TMPDIR"] = str(home)
183
+ env["XDG_CACHE_HOME"] = str(home / ".cache")
184
+ env["TRITON_CACHE_DIR"] = str(home / ".triton")
185
+ env["TORCHINDUCTOR_CACHE_DIR"] = str(home / ".inductor")
186
+ env["DEV_UID_REPORT"] = str(out_dir / "_dev_uid.txt")
187
+ _uid = int(train_uid)
188
+ def preexec_drop():
189
+ os.setsid()
190
+ try:
191
+ os.setgroups([])
192
+ os.setgid(_uid)
193
+ os.setuid(_uid)
194
+ except Exception:
195
+ pass
196
+ preexec = preexec_drop
197
+
198
+ # record euid via a tiny wrapper the child writes before exec'ing run_training.sh
199
+ proc = subprocess.Popen(
200
+ ["bash", "-c",
201
+ 'if [ -n "${DEV_UID_REPORT:-}" ]; then id -u >/dev/null; python3 -c "import os;open(os.environ[\'DEV_UID_REPORT\'],\'w\').write(\'%d %d\'%(os.getuid(),os.geteuid()))" 2>/dev/null || true; fi; '
202
+ 'exec bash "$0"', str(stage / "run_training.sh")],
203
+ cwd=str(stage), env=env, preexec_fn=preexec,
204
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
205
+ note = "completed"
206
+ stderr_tail = b""
207
+ try:
208
+ _, stderr_tail = proc.communicate(timeout=guard + grace)
209
+ except subprocess.TimeoutExpired:
210
+ note = "hard-killed at dev guard+grace"
211
+ for sg in (signal.SIGTERM, signal.SIGKILL):
212
+ try:
213
+ os.killpg(os.getpgid(proc.pid), sg)
214
+ except ProcessLookupError:
215
+ pass
216
+ time.sleep(3)
217
+ try:
218
+ _, stderr_tail = proc.communicate(timeout=20)
219
+ except Exception:
220
+ pass
221
+ observed_euid = None
222
+ try:
223
+ observed_euid = (out_dir / "_dev_uid.txt").read_text().split()[1]
224
+ except Exception:
225
+ observed_euid = None
226
+ uid_dropped = bool(train_uid) and observed_euid == str(int(train_uid)) if train_uid else False
227
+ ckpt = out_dir / "model_ckpt.pt"
228
+ try:
229
+ if ckpt.exists():
230
+ os.chmod(ckpt, 0o644)
231
+ except Exception:
232
+ pass
233
+ stderr_txt = (stderr_tail or b"").decode("utf-8", "ignore")
234
+ return (ckpt if ckpt.exists() else None), uid_dropped, observed_euid, note, stderr_txt
235
+
236
+
237
+ def evaluate(cfg: dict, submission_dir: Path, ckpt: Path):
238
+ import importlib.util
239
+ import numpy as np
240
+ import sentencepiece as spm
241
+ import torch
242
+ import torch.nn.functional as F
243
+ import inspect
244
+
245
+ device = torch.device("cuda", 0)
246
+ torch.cuda.set_device(device)
247
+ train_gpt = submission_dir / "train_gpt.py"
248
+ spec = importlib.util.spec_from_file_location("dev_reload_train_gpt", train_gpt)
249
+ module = importlib.util.module_from_spec(spec)
250
+ sys.modules["dev_reload_train_gpt"] = module
251
+ sub_parent = str(submission_dir.resolve())
252
+ if sub_parent not in sys.path:
253
+ sys.path.insert(0, sub_parent)
254
+ if str(cfg["nanogpt_repo"]) not in sys.path:
255
+ sys.path.insert(0, str(cfg["nanogpt_repo"]))
256
+ spec.loader.exec_module(module)
257
+
258
+ loader = getattr(module, "load_model_for_verification", None)
259
+ if loader is None:
260
+ return False, INV_LOAD, None, "load_model_for_verification missing"
261
+ args = module.Hyperparameters() if hasattr(module, "Hyperparameters") else None
262
+ try:
263
+ sig = inspect.signature(loader)
264
+ kwargs, positional = {}, []
265
+ for name, par in sig.parameters.items():
266
+ if name in {"checkpoint_path", "path", "model_path"}:
267
+ kwargs[name] = ckpt
268
+ elif name == "device":
269
+ kwargs[name] = device
270
+ elif par.default is inspect._empty:
271
+ if not positional:
272
+ positional.append(ckpt)
273
+ elif len(positional) == 1:
274
+ positional.append(device)
275
+ loaded = loader(*positional, **kwargs)
276
+ except Exception as exc:
277
+ return False, INV_LOAD, None, f"{type(exc).__name__}: {exc}"
278
+ if isinstance(loaded, tuple) and len(loaded) == 2:
279
+ loaded_args, model = loaded
280
+ if loaded_args is not None:
281
+ args = loaded_args
282
+ else:
283
+ model = loaded
284
+ if not isinstance(model, torch.nn.Module):
285
+ return False, INV_LOAD, None, "loader did not return an nn.Module / (args, model)"
286
+ model = model.to(device).eval()
287
+
288
+ # total-parameter FLOOR — the SAME capacity floor the grade re-counts (weight-tie deduplicated).
289
+ seen, unique_params = set(), 0
290
+ for p in model.parameters():
291
+ key = p.data_ptr()
292
+ if key in seen:
293
+ continue
294
+ seen.add(key)
295
+ unique_params += int(p.numel())
296
+ floor = int(cfg["dev_param_floor"])
297
+ if unique_params < floor:
298
+ return False, INV_PARAM_FLOOR, None, f"{unique_params:,} < floor {floor:,}"
299
+
300
+ seq_len = int(getattr(args, "train_seq_len", 512) or 512)
301
+ seq_len = max(seq_len, 16)
302
+ vocab_size = int(getattr(args, "vocab_size", 8192) or 8192)
303
+
304
+ arange = torch.arange(seq_len, device=device, dtype=torch.int64)
305
+ x_ar = (arange % vocab_size).reshape(1, -1)
306
+ y_ar = ((arange + 1) % vocab_size).reshape(1, -1)
307
+ with torch.inference_mode():
308
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
309
+ logits = model(x_ar)
310
+ loss_xy = model(x_ar, y_ar)
311
+ if not isinstance(logits, torch.Tensor) or logits.ndim != 3 or not logits.dtype.is_floating_point:
312
+ return False, INV_CE_AGREE, None, "forward(x) did not return float logits (B,T,V)"
313
+ lf = logits.float()
314
+ pos_var = float(lf.var(dim=1).mean().item())
315
+ if not math.isfinite(pos_var) or pos_var <= float(cfg["dev_logits_position_variance_floor"]):
316
+ return False, INV_LOGITS_CONST, None, f"logits constant across positions (var={pos_var:.2e})"
317
+ real_vocab = logits.shape[-1]
318
+ ce = float(F.cross_entropy(lf.reshape(-1, real_vocab),
319
+ y_ar.reshape(-1).clamp_max(real_vocab - 1), reduction="mean").item())
320
+ lxy = float(loss_xy.detach().to(torch.float64).item()) if isinstance(loss_xy, torch.Tensor) else float(loss_xy)
321
+ if not math.isfinite(lxy) or abs(lxy - ce) > float(cfg["dev_logits_loss_agreement_tol"]):
322
+ return False, INV_CE_AGREE, None, f"forward(x,y)={lxy:.4f} != CE(forward(x),y)={ce:.4f}"
323
+
324
+ tok_path = Path(str(getattr(args, "tokenizer_path", cfg["tokenizer_path"])))
325
+ if not tok_path.exists():
326
+ tok_path = Path(cfg["tokenizer_path"])
327
+ sp = spm.SentencePieceProcessor(model_file=str(tok_path))
328
+ sp_v = int(sp.vocab_size())
329
+ table = max(sp_v, vocab_size)
330
+ base_bytes = np.zeros((table,), dtype=np.int32)
331
+ has_lead = np.zeros((table,), dtype=np.bool_)
332
+ is_bound = np.ones((table,), dtype=np.bool_)
333
+ for tid in range(sp_v):
334
+ if sp.is_control(tid) or sp.is_unknown(tid) or sp.is_unused(tid):
335
+ continue
336
+ is_bound[tid] = False
337
+ if sp.is_byte(tid):
338
+ base_bytes[tid] = 1
339
+ continue
340
+ piece = sp.id_to_piece(tid)
341
+ if piece.startswith("▁"):
342
+ has_lead[tid] = True
343
+ piece = piece[1:]
344
+ base_bytes[tid] = len(piece.encode("utf-8"))
345
+ base_bytes_lut = torch.tensor(base_bytes, dtype=torch.int32, device=device)
346
+ has_lead_lut = torch.tensor(has_lead, dtype=torch.bool, device=device)
347
+ is_bound_lut = torch.tensor(is_bound, dtype=torch.bool, device=device)
348
+
349
+ val_path = Path(cfg["corpus_dir"]) / "val.bin"
350
+ if not val_path.exists():
351
+ return False, INV_VAL_IMPLAUSIBLE, None, f"public val split missing at {val_path}"
352
+ vd = np.memmap(val_path, dtype=np.uint16, mode="r")
353
+ cap_tok = int(cfg["dev_val_tokens"])
354
+ ids = np.asarray(vd[: min(len(vd), cap_tok + 1)], dtype=np.int64)
355
+ usable = ((ids.size - 1) // seq_len) * seq_len
356
+ if usable <= 0:
357
+ return False, INV_VAL_IMPLAUSIBLE, None, "public val split too short for seq_len"
358
+ val_tokens = torch.from_numpy(ids[: usable + 1]).contiguous()
359
+ batch_seqs = max(32768 // seq_len, 1)
360
+ total_seqs = usable // seq_len
361
+ loss_sum = torch.zeros((), device=device, dtype=torch.float64)
362
+ tok_count = torch.zeros((), device=device, dtype=torch.float64)
363
+ byte_count = torch.zeros((), device=device, dtype=torch.float64)
364
+ with torch.inference_mode():
365
+ for s0 in range(0, total_seqs, batch_seqs):
366
+ s1 = min(s0 + batch_seqs, total_seqs)
367
+ r0, r1 = s0 * seq_len, s1 * seq_len + 1
368
+ local = val_tokens[r0:r1].to(device=device, dtype=torch.int64)
369
+ x = local[:-1].reshape(-1, seq_len)
370
+ y = local[1:].reshape(-1, seq_len)
371
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
372
+ out = model(x, y)
373
+ if isinstance(out, torch.Tensor) and out.numel() != 1:
374
+ lg = out.float().reshape(-1, out.shape[-1])
375
+ bl = F.cross_entropy(lg, y.reshape(-1).clamp_max(lg.shape[-1] - 1), reduction="mean")
376
+ else:
377
+ bl = out
378
+ ntok = float(y.numel())
379
+ loss_sum += bl.detach().to(torch.float64) * ntok
380
+ tok_count += ntok
381
+ prev = x.reshape(-1)
382
+ tgt = y.reshape(-1)
383
+ tb = base_bytes_lut[tgt].to(torch.int32)
384
+ tb = tb + (has_lead_lut[tgt] & ~is_bound_lut[prev]).to(torch.int32)
385
+ byte_count += tb.to(torch.float64).sum()
386
+ val_loss = (loss_sum / tok_count).item()
387
+ bpb = float((val_loss / math.log(2.0)) * (tok_count.item() / byte_count.item()))
388
+ if not math.isfinite(bpb) or bpb < float(cfg["dev_min_plausible_val_bpb"]):
389
+ return False, INV_VAL_IMPLAUSIBLE, bpb if math.isfinite(bpb) else None, \
390
+ f"val_bpb={bpb} below plausibility floor (forged loss / contamination)"
391
+ if bpb > float(cfg["dev_quality_floor_val_bpb"]):
392
+ return False, INV_VAL_FLOOR, bpb, f"val_bpb={bpb:.4f} above dev quality floor"
393
+ return True, None, bpb, f"ok params={unique_params:,} val_bpb={bpb:.4f}"
394
+
395
+
396
+ def main() -> int:
397
+ try:
398
+ cfg = _cfg()
399
+ except Exception as exc:
400
+ _harness_error(f"could not read dev manifest: {type(exc).__name__}: {exc}")
401
+ return 0
402
+ submission_dir = Path(cfg["submission_dir"])
403
+ if not (submission_dir / "run_training.sh").exists() or not (submission_dir / "train_gpt.py").exists():
404
+ _write_state(False, INV_SUBMISSION_MISSING, None, 0.0, None, None,
405
+ {"detail": f"run_training.sh / train_gpt.py missing under {submission_dir}"})
406
+ return 0
407
+ import tempfile
408
+ run_root = Path(tempfile.mkdtemp(prefix="a3_devloop_"))
409
+ try:
410
+ shard_dir = run_root / "_dev_shard"
411
+ if not build_dev_shard(Path(cfg["corpus_dir"]), shard_dir,
412
+ int(cfg["dev_train_tokens"]), int(cfg["dev_train_offset"])):
413
+ _harness_error("could not build the public dev shard (corpus missing/too small)")
414
+ return 0
415
+ out_dir = run_root / "dev_seed"
416
+ ckpt, uid_dropped, observed_euid, note, stderr_txt = train_candidate(
417
+ cfg, submission_dir, shard_dir, out_dir)
418
+ if ckpt is None:
419
+ infra = any(s in (stderr_txt or "") for s in
420
+ ("ModuleNotFoundError", "ImportError", "Traceback (most recent call last)"))
421
+ if infra and "run_training.sh missing" not in (stderr_txt or ""):
422
+ _harness_error("dev training subprocess raised an infra error before producing a "
423
+ f"checkpoint: {(stderr_txt or '').strip().splitlines()[-1:]}")
424
+ return 0
425
+ _write_state(False, INV_NO_CHECKPOINT, None, 0.0, uid_dropped, observed_euid, {"note": note})
426
+ return 0
427
+ try:
428
+ ok, inv, bpb, detail = evaluate(cfg, submission_dir, ckpt)
429
+ except Exception as exc:
430
+ _harness_error(f"dev evaluate() raised: {type(exc).__name__}: {exc}")
431
+ return 0
432
+ # dev_score: HIGHER is better for best-of-k; val_bpb is lower-is-better, so use 1/bpb.
433
+ dev_reward = (1.0 / bpb) if (ok and bpb and bpb > 0) else 0.0
434
+ _write_state(ok, inv, bpb, dev_reward, uid_dropped, observed_euid, {"detail": detail})
435
+ return 0
436
+ finally:
437
+ try:
438
+ shutil.rmtree(run_root, ignore_errors=True)
439
+ except Exception:
440
+ pass
441
+
442
+
443
+ if __name__ == "__main__":
444
+ raise SystemExit(main())
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/private/manifest.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "kb_loop_dev_manifest_v1",
3
+ "task_id": "e2e-a3-moe-train-budget-loop16",
4
+ "note": "DEV-ONLY proxy constants for the per-round loop. BAKED here (root:root 0600, unreadable by the solver's dropped uid) and read from THIS FILE ONLY, never from the environment. Contains NO calibrated anchor (baseline_bpb), NO ref_speedup and NO held-out corpus: the per-round signal is an ABSOLUTE public-proxy val_bpb on the PUBLIC /data/datasets/wikitext_bpe8k val split, never normalised against the graded anchor. The graded score is produced after the session by the runner from a freshly-uploaded /tests over the HIDDEN test split at the FULL wall-clock budget; this loop only decides WHICH snapshot is graded.",
5
+ "dev_wallclock_sec": 90.0,
6
+ "dev_wallclock_note": "the per-round proxy trains the candidate recipe for a SHORT dev wall-clock (90 s vs the graded 600 s) so a per-round pass is minutes, not the full run. 🔴 UNLIKE the token-budgeted a4 sibling, a3's budget is WALL-CLOCK, so this dev val_bpb depends on BOTH the recipe AND this node's speed and is only a COARSE direction signal — a more sample/throughput-efficient recipe should reach a lower val_bpb in the short dev budget, but the absolute number is not node-portable and is NOT the graded score.",
7
+ "dev_guard_grace_seconds": 30.0,
8
+ "dev_seed": 4242,
9
+ "dev_seed_note": "a FIXED dev seed distinct from every graded seed (1337/2027/90101) so the proxy cannot be seed-matched to the grade.",
10
+ "dev_train_tokens": 6000000,
11
+ "dev_train_offset": 3000000,
12
+ "dev_val_tokens": 131072,
13
+ "dev_param_floor": 150000000,
14
+ "dev_param_note": "the SAME total-parameter capacity FLOOR the graded scorer re-counts (weight-tie deduplicated). Enforced in the per-round self-check so the public proxy does not coach the solver toward a sub-floor model the grade would reject.",
15
+ "dev_min_plausible_val_bpb": 0.90,
16
+ "dev_quality_floor_val_bpb": 5.0,
17
+ "dev_logits_position_variance_floor": 0.0001,
18
+ "dev_logits_loss_agreement_tol": 0.05,
19
+ "dev_uid": 65534,
20
+ "dev_uid_note": "the candidate's per-round proxy training runs as uid 65534 (nobody), NOT root — the SAME privilege drop the graded path uses, for fidelity and to keep the loop engine from being turned into a root-training oracle. Set to null to disable (NOT recommended). The child reports the euid it actually ran under.",
21
+ "corpus_dir": "/data/datasets/wikitext_bpe8k",
22
+ "tokenizer_path": "/data/tokenizers/wikitext_bpe8k.model",
23
+ "nanogpt_repo": "/app/repo",
24
+ "submission_dir": "/app/submission"
25
+ }
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/sanitize_feedback.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """/opt/loop/sanitize_feedback.py — emit ONLY the leak-free per-round feedback for
3
+ e2e-a3-moe-train-budget.
4
+
5
+ Reads /logs/loop/dev/{verifier_state.json,reward.json,harness_error.txt} and
6
+ /logs/loop/{count,best.json}; prints the sanitized block the solver reads.
7
+
8
+ NEVER emits: the held-out corpus, the calibrated baseline_bpb / ref_speedup, the hidden
9
+ seeds / token budget / thresholds, or any /tests content — NONE of which is even in this
10
+ container. Emits: submission index + remaining, correctness pass/fail (+ the NAMED failing
11
+ invariant on fail), the ABSOLUTE public-proxy dev_val_bpb (explicitly NOT the graded score),
12
+ best_so_far, and finalize_allowed. The dev signal is a public proxy on a small public token
13
+ budget; the graded score is computed after the session over the hidden test split.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from pathlib import Path
19
+
20
+ LOOP = Path("/logs/loop")
21
+ DEV = LOOP / "dev"
22
+ MIN_SUB = 1
23
+ MAX_SUB = 16
24
+
25
+
26
+ def _load(p: Path) -> dict:
27
+ try:
28
+ return json.loads(p.read_text())
29
+ except Exception:
30
+ return {}
31
+
32
+
33
+ def main() -> int:
34
+ count = 0
35
+ cf = LOOP / "count"
36
+ if cf.is_file():
37
+ try:
38
+ count = int("".join(ch for ch in cf.read_text() if ch.isdigit()) or "0")
39
+ except Exception:
40
+ count = 0
41
+
42
+ # harness_error path: submit.sh has already refunded; say so and stop.
43
+ he = DEV / "harness_error.txt"
44
+ if he.is_file() and he.stat().st_size > 0:
45
+ print(f"submission {count}/{MAX_SUB} — harness_error")
46
+ print("harness_error: the DEV scoring engine itself failed — this is NOT a defect in your")
47
+ print("code and this attempt was REFUNDED (your budget is unchanged). Do NOT debug the")
48
+ print("harness; just retry submit, or keep optimizing and retry.")
49
+ return 0
50
+
51
+ state = _load(DEV / "verifier_state.json")
52
+ reward = _load(DEV / "reward.json")
53
+ best = _load(LOOP / "best.json")
54
+
55
+ correctness_ok = bool(state.get("correctness_ok"))
56
+ failing_inv = state.get("failing_invariant") or ""
57
+ dev_val_bpb = reward.get("dev_val_bpb")
58
+ remaining = max(0, MAX_SUB - count)
59
+ finalize_allowed = count >= MIN_SUB
60
+
61
+ print(f"submission {count}/{MAX_SUB}")
62
+ if correctness_ok:
63
+ print("correctness: PASS")
64
+ if isinstance(dev_val_bpb, (int, float)):
65
+ print(f"dev_val_bpb: {float(dev_val_bpb):.4f} "
66
+ "(PUBLIC dev proxy — lower is better — NOT your graded score)")
67
+ else:
68
+ print("correctness: FAIL")
69
+ print(f" failing_invariant: {failing_inv or 'unknown'}")
70
+ # uid-drop transparency: the per-round training runs unprivileged, same as the grade.
71
+ if state.get("dev_uid_dropped") is not None:
72
+ print(f"dev_training_uid_dropped: {'true' if state.get('dev_uid_dropped') else 'false'}"
73
+ f" (observed euid {state.get('observed_euid')})")
74
+
75
+ if best and best.get("submission"):
76
+ bb = best.get("dev_val_bpb")
77
+ bb_s = f"{float(bb):.4f}" if isinstance(bb, (int, float)) else "n/a"
78
+ print(f"best_so_far: submission {best.get('submission')}, dev_val_bpb {bb_s}")
79
+ else:
80
+ print("best_so_far: (no correctness-passing submission yet)")
81
+
82
+ print(f"remaining: {remaining}")
83
+ print(f"finalize_allowed: {'true' if finalize_allowed else 'false'} "
84
+ f"(you may --finalize at any k>=1; there is no minimum and no 'k rounds without gain' rule)")
85
+ return 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/score_engine.sh ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # /opt/loop/score_engine.sh — the baked in-session DEV scoring engine for
3
+ # e2e-a3-moe-train-budget. Runs the candidate recipe on a SMALL public token
4
+ # shard under the uid-65534 drop and scores an ABSOLUTE public-proxy val_bpb.
5
+ # Called ONLY by /opt/loop/submit.sh. 0700 root-owned; the solver's dropped uid cannot
6
+ # read this file or /opt/loop/private/**.
7
+ #
8
+ # 🔴 It reads its constants from /opt/loop/private/manifest.json ONLY — never from the
9
+ # environment. The loop runs in the solver-writable session shell, so anything read from
10
+ # env is attacker-controlled; in particular the reward's anchor is NOT in this container
11
+ # at all (it is uploaded fresh to /tests at grading), and this engine never reads /tests.
12
+ set -uo pipefail
13
+ # The agent invokes submit.sh from a NON-login shell, so bare python3 has no torch.
14
+ # Pin the kernelbench venv onto PATH so python AND the training subprocess have torch.
15
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
16
+
17
+ DEV_OUT=/logs/loop/dev
18
+ mkdir -p "$DEV_OUT"
19
+ # clear the previous round's artifacts so a stale file never masquerades as this round
20
+ rm -f "$DEV_OUT/verifier_state.json" "$DEV_OUT/reward.json" "$DEV_OUT/harness_error.txt" 2>/dev/null || true
21
+
22
+ PY="$(command -v python3 || command -v python)"
23
+ if [ -z "$PY" ]; then
24
+ echo "harness_error: no python on PATH" > "$DEV_OUT/harness_error.txt"
25
+ exit 3
26
+ fi
27
+
28
+ # Pin thread counts so the (cheap) eval does not depend on node core-count.
29
+ export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}"
30
+ export MKL_NUM_THREADS="${MKL_NUM_THREADS:-8}"
31
+ export OPENBLAS_NUM_THREADS="${OPENBLAS_NUM_THREADS:-8}"
32
+
33
+ "$PY" /opt/loop/private/dev_eval.py
34
+ rc=$?
35
+
36
+ # dev_eval writes its own JSON on every path it reaches. If the interpreter itself died
37
+ # (missing dep / OOM / SIGKILL) nothing was written -> classify as harness_error so the
38
+ # round is refunded rather than mis-scored as a candidate defect.
39
+ if [ ! -s "$DEV_OUT/verifier_state.json" ] && [ ! -s "$DEV_OUT/harness_error.txt" ]; then
40
+ echo "harness_error: dev_eval.py died before writing a result (rc=$rc)" > "$DEV_OUT/harness_error.txt"
41
+ exit 3
42
+ fi
43
+ # propagate the refund signal if dev_eval flagged an infra failure
44
+ if [ -s "$DEV_OUT/harness_error.txt" ]; then
45
+ exit 3
46
+ fi
47
+ exit 0
tasks/e2e/a3-moe-train-budget/task/environment/loop_overlay/opt_loop/submit.sh ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # e2e-a3-moe-train-budget — loop16 submit.sh (protocol 1..16, model decides)
4
+ # ============================================================================
5
+ # The solver's ONLY sanctioned in-session scoring interface. 0755 root:root; the engine
6
+ # and private dev assets it calls are 0700 root-owned (unreadable by the solver's uid).
7
+ #
8
+ # bash /opt/loop/submit.sh # score current state, get feedback
9
+ # bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best-of-k, end the loop
10
+ #
11
+ # Budget: min=1, max=16. --finalize is accepted at ANY k>=1 (there is no minimum and no
12
+ # "k consecutive rounds without gain" rule); at k=16 the harness auto-finalizes.
13
+ #
14
+ # Each round is scored by /opt/loop/score_engine.sh on a PUBLIC dev proxy (a small public
15
+ # token budget + a first-principles correctness self-check): the overlay contains NO held-out
16
+ # corpus, NO reference recipe and NO calibrated anchor, so the per-round dev_val_bpb is a
17
+ # PUBLIC PROXY, not the graded score. The GRADED score is produced after the session by the
18
+ # runner from a freshly-uploaded /tests over the HIDDEN test split, against whatever this
19
+ # script plants.
20
+ #
21
+ # a4 has TWO editable graded surfaces — /app/submission (the entry contract the grader loads)
22
+ # and /app/repo (the nanoGPT the recipe imports LIVE at grading). Best-of-k therefore snapshots
23
+ # and plants BOTH: /app/repo via git tree-hash (read-tree + checkout-index), /app/submission via
24
+ # a per-round tarball. On finalize the BEST correctness-passing snapshot (not the last edit) is
25
+ # planted; /app/repo HEAD stays at the baked baseline commit.
26
+
27
+ # git-safe-directory: a crane-appended /app/repo is root-owned; without this every git op
28
+ # fails "dubious ownership". MUST be first.
29
+ git config --global --add safe.directory '*' 2>/dev/null || true
30
+
31
+ # PATH-pin: agent shell + runner exec are NON-login; pin the venv so python has torch.
32
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
33
+ set -uo pipefail
34
+
35
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
36
+ REPO=/app/repo
37
+ SUBM=/app/submission
38
+ BASE_SUBM=/opt/loop/baseline_submission # pristine shipped starter (baked)
39
+ LOOP=/logs/loop
40
+ DEV="$LOOP/dev"
41
+ SUBS="$LOOP/submissions"
42
+ mkdir -p "$LOOP" "$SUBS" "$DEV"
43
+
44
+ MIN_SUBMISSIONS=1
45
+ MAX_SUBMISSIONS=16
46
+ COUNT_FILE="$LOOP/count"
47
+ BEST_FILE="$LOOP/best.json"
48
+ STATE_JSONL="$LOOP/state.jsonl"
49
+
50
+ TASK_ID="$(python3 -c 'import json;print(json.load(open("/opt/loop/private/manifest.json")).get("task_id",""))' 2>/dev/null || true)"
51
+ [ -n "$TASK_ID" ] || TASK_ID="e2e-a3-moe-train-budget"
52
+
53
+ _read_count() {
54
+ if [ -f "$COUNT_FILE" ]; then
55
+ awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE"
56
+ else
57
+ echo 0
58
+ fi
59
+ }
60
+
61
+ # git tree-hash of the current /app/repo working tree (non-mutating index add).
62
+ _repo_tree() {
63
+ git -C "$REPO" add -A >/dev/null 2>&1 || true
64
+ git -C "$REPO" write-tree 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null || echo ""
65
+ }
66
+
67
+ # ------------------- argument parsing -------------------
68
+ MODE=submit
69
+ REASON=""
70
+ while [ "$#" -gt 0 ]; do
71
+ case "$1" in
72
+ --finalize) MODE=finalize; shift ;;
73
+ --reason) REASON="${2:-}"; shift 2 ;;
74
+ --reason=*) REASON="${1#--reason=}"; shift ;;
75
+ *) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"<text>\"]]" >&2; exit 2 ;;
76
+ esac
77
+ done
78
+
79
+ # ------------------- finalize -------------------
80
+ if [ "$MODE" = finalize ]; then
81
+ CUR="$(_read_count)"; CUR="${CUR:-0}"
82
+ if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then
83
+ echo "nothing to finalize yet: score at least $MIN_SUBMISSIONS submission first (you have $CUR)."
84
+ echo "Run: bash /opt/loop/submit.sh"
85
+ exit 1
86
+ fi
87
+
88
+ WIN_SUB=""; WIN_REPO_TREE=""
89
+ if [ -f "$BEST_FILE" ]; then
90
+ WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)"
91
+ WIN_REPO_TREE="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("repo_tree","") or "")' "$BEST_FILE" 2>/dev/null || true)"
92
+ fi
93
+
94
+ # --- plant /app/repo: reset to baked baseline HEAD, then load the winning tree ---
95
+ git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true
96
+ git -C "$REPO" clean -qfd 2>/dev/null || true
97
+ PLANT_REPO="none"
98
+ if [ -n "$WIN_REPO_TREE" ] && git -C "$REPO" read-tree "$WIN_REPO_TREE" 2>"$LOOP/finalize_apply.log"; then
99
+ git -C "$REPO" checkout-index -f -a 2>>"$LOOP/finalize_apply.log" && PLANT_REPO="read-tree"
100
+ fi
101
+ if [ "$PLANT_REPO" = "none" ] && [ -n "$WIN_SUB" ] && [ -s "$SUBS/$WIN_SUB/repo.diff" ]; then
102
+ git -C "$REPO" apply --whitespace=nowarn "$SUBS/$WIN_SUB/repo.diff" 2>>"$LOOP/finalize_apply.log" \
103
+ && PLANT_REPO="diff-apply" || true
104
+ fi
105
+
106
+ # --- plant /app/submission: extract the winning tarball (or restore pristine starter) ---
107
+ PLANT_SUBM="none"
108
+ if [ -n "$WIN_SUB" ] && [ -s "$SUBS/$WIN_SUB/submission.tgz" ]; then
109
+ rm -rf "${SUBM:?}/"* 2>/dev/null || true
110
+ mkdir -p "$SUBM"
111
+ if tar xzf "$SUBS/$WIN_SUB/submission.tgz" -C "$SUBM" 2>>"$LOOP/finalize_apply.log"; then
112
+ PLANT_SUBM="tar"
113
+ fi
114
+ fi
115
+ if [ "$PLANT_SUBM" = "none" ]; then
116
+ # no correctness-passing snapshot -> restore the pristine shipped starter
117
+ rm -rf "${SUBM:?}/"* 2>/dev/null || true
118
+ mkdir -p "$SUBM"
119
+ if [ -d "$BASE_SUBM" ]; then
120
+ cp -a "$BASE_SUBM/." "$SUBM/" 2>>"$LOOP/finalize_apply.log" && PLANT_SUBM="baseline_restore"
121
+ fi
122
+ fi
123
+
124
+ REASON="$REASON" WIN_SUB="$WIN_SUB" WIN_REPO_TREE="$WIN_REPO_TREE" CUR="$CUR" \
125
+ PLANT_REPO="$PLANT_REPO" PLANT_SUBM="$PLANT_SUBM" TASK_ID="$TASK_ID" python3 - <<'PY'
126
+ import json, os, hashlib
127
+ from pathlib import Path
128
+ LOOP = Path('/logs/loop')
129
+ try: best = json.loads((LOOP / 'best.json').read_text())
130
+ except Exception: best = {}
131
+ traj = []
132
+ try:
133
+ for line in (LOOP / 'state.jsonl').read_text().splitlines():
134
+ line = line.strip()
135
+ if not line: continue
136
+ r = json.loads(line)
137
+ traj.append({'submission': r.get('submission'),
138
+ 'dev_val_bpb': r.get('dev_val_bpb'),
139
+ 'correctness_ok': r.get('correctness_ok')})
140
+ except Exception: pass
141
+ # sha of the planted entry, so best-of-k can be PROVEN (not just claimed)
142
+ planted_sha = None
143
+ try:
144
+ planted_sha = hashlib.sha256(Path('/app/submission/train_gpt.py').read_bytes()).hexdigest()
145
+ except Exception:
146
+ planted_sha = None
147
+ out = {
148
+ 'schema_version': 'kb_loop_finalize_v1',
149
+ 'task_id': os.environ.get('TASK_ID') or 'e2e-a3-moe-train-budget',
150
+ 'mode': 'baked',
151
+ 'plant_method': {'submission': os.environ.get('PLANT_SUBM'), 'repo': os.environ.get('PLANT_REPO')},
152
+ 'submissions_used': int(os.environ.get('CUR') or 0),
153
+ 'min_submissions': 1, 'max_submissions': 16,
154
+ 'winning_submission': (best.get('submission') if best else None),
155
+ 'winning_repo_tree': os.environ.get('WIN_REPO_TREE') or None,
156
+ 'winning_dev_val_bpb': (best.get('dev_val_bpb') if best else None),
157
+ 'planted_train_gpt_sha256': planted_sha,
158
+ 'dev_public_proxy_trajectory': traj,
159
+ 'termination_reason': os.environ.get('REASON') or '',
160
+ 'note': 'dev_val_bpb is an in-session PUBLIC-proxy on a small public token budget, used ONLY to rank best-of-k; the authoritative score is the runner end-of-session grade of /app/submission + /app/repo over the hidden test split.',
161
+ }
162
+ (LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n')
163
+ PY
164
+
165
+ if [ -n "$WIN_SUB" ] && { [ "$PLANT_SUBM" = "tar" ] || [ "$PLANT_REPO" != "none" ]; }; then
166
+ echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (submission planted via $PLANT_SUBM, repo via $PLANT_REPO); the grader will now score /app/submission + /app/repo"
167
+ else
168
+ echo "finalized: no correctness-passing submission in $CUR tries — the shipped starter was restored; the grader will now score it (under this task's bounded reward, a model that does not beat the dense-at-floor starter scores 0)"
169
+ fi
170
+ exit 0
171
+ fi
172
+
173
+ # ------------------- submit -------------------
174
+ CUR="$(_read_count)"; CUR="${CUR:-0}"
175
+ if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then
176
+ echo "submission $CUR/$MAX_SUBMISSIONS"
177
+ echo "budget exhausted — auto-finalizing best-of-$MAX_SUBMISSIONS"
178
+ exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
179
+ fi
180
+
181
+ # Run the DEV engine on the LIVE surfaces.
182
+ bash "$HERE/score_engine.sh"
183
+ engine_rc=$?
184
+
185
+ # HARNESS-ERROR refund: infra failure (rc=3 or marker) -> do NOT consume budget.
186
+ if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then
187
+ python3 "$HERE/sanitize_feedback.py"
188
+ exit 0
189
+ fi
190
+
191
+ NEXT=$((CUR + 1))
192
+ echo "$NEXT" > "$COUNT_FILE"
193
+
194
+ SNAP="$SUBS/$NEXT"
195
+ mkdir -p "$SNAP"
196
+ REPO_TREE="$(_repo_tree)"
197
+ echo "${REPO_TREE:-}" > "$SNAP/repo_tree.txt"
198
+ git -C "$REPO" diff --binary HEAD > "$SNAP/repo.diff" 2>/dev/null || true
199
+ tar czf "$SNAP/submission.tgz" -C "$SUBM" . 2>/dev/null || true
200
+ for f in verifier_state.json reward.json; do
201
+ [ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true
202
+ done
203
+
204
+ NEXT="$NEXT" REPO_TREE="$REPO_TREE" python3 - <<'PY'
205
+ import json, os, time
206
+ from pathlib import Path
207
+ LOOP = Path('/logs/loop'); DEV = LOOP / 'dev'
208
+ k = int(os.environ['NEXT']); repo_tree = os.environ.get('REPO_TREE') or ''
209
+ try: state = json.loads((DEV / 'verifier_state.json').read_text())
210
+ except Exception: state = {}
211
+ try: reward = json.loads((DEV / 'reward.json').read_text())
212
+ except Exception: reward = {}
213
+ corr_ok = bool(state.get('correctness_ok'))
214
+ dev_reward = float(reward.get('dev_score') or 0.0) # higher is better (= 1/val_bpb)
215
+ dev_val_bpb = reward.get('dev_val_bpb')
216
+ row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok,
217
+ 'dev_score': dev_reward, 'dev_val_bpb': dev_val_bpb, 'repo_tree': repo_tree,
218
+ 'failing_invariant': state.get('failing_invariant') or ''}
219
+ with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f:
220
+ f.write(json.dumps(row) + '\n')
221
+ if corr_ok:
222
+ bp = LOOP / 'best.json'
223
+ try: best = json.loads(bp.read_text())
224
+ except Exception: best = None
225
+ if best is None or dev_reward > float(best.get('dev_score') or -1.0):
226
+ bp.write_text(json.dumps({'submission': k, 'dev_score': dev_reward,
227
+ 'dev_val_bpb': dev_val_bpb, 'repo_tree': repo_tree},
228
+ indent=2, sort_keys=True) + '\n')
229
+ PY
230
+
231
+ python3 "$HERE/sanitize_feedback.py"
232
+
233
+ if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then
234
+ echo ""
235
+ echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---"
236
+ exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
237
+ fi
238
+ exit 0
tasks/e2e/a3-moe-train-budget/task/environment/submission/run_training.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; fully editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR, WALLCLOCK_SEC,
4
+ # OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ #
6
+ # It MUST write a checkpoint to $OUT_CKPT within the budget (save periodically — the timer can
7
+ # stop you at any moment) and leave load_model_for_verification(checkpoint_path, device)
8
+ # importable from /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
9
+ # (the grader re-counts it).
10
+ #
11
+ # This starting version runs the provided dense baseline. Change anything you like — nanoGPT
12
+ # under /app/repo is fully editable too.
13
+ set -e
14
+ cd /app/submission
15
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/environment/submission/train_gpt.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # e2e-a3-moe-train-budget — the provided STARTING POINT (fully editable, NOT a contract).
2
+ #
3
+ # This is a plain DENSE nanoGPT sized to clear the task's hard total-parameter FLOOR, trained
4
+ # with a straightforward AdamW recipe until the harness's wall-clock timer stops it. It is a
5
+ # complete, working, honest baseline: real data loading, bf16 autocast, warmup + cosine decay,
6
+ # gradient clipping, and an atomic periodic checkpoint save so a timer kill always leaves a
7
+ # valid artifact. It satisfies the verifier's entry contract as-is.
8
+ #
9
+ # It is also DELIBERATELY the thing you have to beat. Because it is dense, every token pays
10
+ # the full ~2*P_total FLOPs, so it fits comparatively few optimizer steps into the budget and
11
+ # converges to a mediocre held-out bits-per-byte. Submitting it unchanged scores 0.
12
+ #
13
+ # You may change anything: the model, the router, the dispatch, the optimizer, the schedule,
14
+ # the data loading, the precision — everything under /app/repo (nanoGPT) and /app/submission.
15
+ #
16
+ # VERIFIER CONTRACT (enforced): the grader loads the checkpoint via
17
+ # load_model_for_verification(checkpoint_path, device) and requires a model whose
18
+ # * model(input_ids) -> float logits (batch, seq, vocab), position-dependent
19
+ # * model(input_ids, target_ids) -> scalar loss == CE(logits.view(-1,V), targets.view(-1))
20
+ # i.e. the PURE cross-entropy of those logits. If you add an auxiliary training objective
21
+ # (for example a load-balancing loss), keep it inside your training loop — do NOT fold it into
22
+ # the loss this forward returns. An OOD probe enforces loss(real_text) < 0.7 * loss(arbitrary
23
+ # ids), and the model must clear the total-parameter floor.
24
+ from __future__ import annotations
25
+
26
+ import math
27
+ import os
28
+ import sys
29
+ import time
30
+ from pathlib import Path
31
+
32
+ import numpy as np
33
+ import torch
34
+ import torch.nn as nn
35
+
36
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
37
+ if REPO not in sys.path:
38
+ sys.path.insert(0, REPO)
39
+ from model import GPT, GPTConfig # noqa: E402 (from /app/repo/model.py)
40
+
41
+
42
+ class Hyperparameters:
43
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
44
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
45
+ seed = int(os.environ.get("SEED", "1337"))
46
+ out_ckpt = os.environ.get("OUT_CKPT", "/app/submission/model_ckpt.pt")
47
+ wallclock_sec = float(os.environ.get("WALLCLOCK_SEC", "600"))
48
+
49
+ vocab_size = 8192
50
+ train_seq_len = 512
51
+ block_size = 512
52
+ val_batch_size = 32_768
53
+
54
+ # DENSE model sized to clear the 150M floor: n_embd=1024,n_layer=12 nanoGPT
55
+ # transformer ~= 12*(12*1024^2) = 151.0M + tied wte 8.4M + wpe 0.5M ~= 160M.
56
+ n_layer = 12
57
+ n_head = 16
58
+ n_embd = 1024
59
+ dropout = 0.0
60
+ bias = False
61
+
62
+ # SAME recipe as the strong MoE baseline (fair comparison; only dense-vs-sparse differs)
63
+ micro_batch = 16
64
+ grad_accum = 2
65
+ learning_rate = 3e-3
66
+ weight_decay = 0.1
67
+ beta1, beta2 = 0.9, 0.95
68
+ grad_clip = 1.0
69
+ warmup_frac = 0.05
70
+ min_lr_frac = 0.1
71
+ save_every_sec = 20.0
72
+
73
+
74
+ class _VerifierAdapter(nn.Module):
75
+ def __init__(self, gpt: GPT):
76
+ super().__init__()
77
+ self.gpt = gpt
78
+
79
+ def forward(self, idx, targets=None):
80
+ logits, loss = self.gpt(idx, idx if targets is None else targets)
81
+ return logits if targets is None else loss
82
+
83
+
84
+ def _cfg(args: Hyperparameters) -> GPTConfig:
85
+ return GPTConfig(block_size=args.block_size, vocab_size=args.vocab_size,
86
+ n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd,
87
+ dropout=args.dropout, bias=args.bias)
88
+
89
+
90
+ def load_model_for_verification(checkpoint_path, device):
91
+ args = Hyperparameters()
92
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
93
+ cfg_kwargs = obj.get("config", {})
94
+ cfg = GPTConfig(**cfg_kwargs) if cfg_kwargs else _cfg(args)
95
+ gpt = GPT(cfg)
96
+ gpt.load_state_dict(obj["model"], strict=True)
97
+ args.train_seq_len = cfg.block_size
98
+ args.vocab_size = cfg.vocab_size
99
+ return args, _VerifierAdapter(gpt).to(device).eval()
100
+
101
+
102
+ def _save(model: GPT, cfg: GPTConfig, out_ckpt: str) -> None:
103
+ tmp = out_ckpt + ".tmp"
104
+ torch.save({"model": model.state_dict(),
105
+ "config": dict(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
106
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
107
+ dropout=0.0, bias=cfg.bias)}, tmp)
108
+ os.replace(tmp, out_ckpt)
109
+
110
+
111
+ class _MemmapLoader:
112
+ def __init__(self, data_path: str, seq_len: int, device: torch.device, seed: int):
113
+ self.data = np.memmap(Path(data_path) / "train.bin", dtype=np.uint16, mode="r")
114
+ self.seq_len = seq_len
115
+ self.device = device
116
+ self.rng = np.random.default_rng(seed)
117
+
118
+ def batch(self, n: int):
119
+ ix = self.rng.integers(0, len(self.data) - self.seq_len - 1, size=n)
120
+ x = torch.from_numpy(np.stack([self.data[i:i + self.seq_len].astype(np.int64) for i in ix]))
121
+ y = torch.from_numpy(np.stack([self.data[i + 1:i + 1 + self.seq_len].astype(np.int64) for i in ix]))
122
+ return (x.pin_memory().to(self.device, non_blocking=True),
123
+ y.pin_memory().to(self.device, non_blocking=True))
124
+
125
+
126
+ def main() -> None:
127
+ args = Hyperparameters()
128
+ torch.manual_seed(args.seed)
129
+ np.random.seed(args.seed)
130
+ torch.backends.cuda.matmul.allow_tf32 = True
131
+ torch.backends.cudnn.allow_tf32 = True
132
+ device = torch.device("cuda", 0)
133
+ torch.cuda.set_device(device)
134
+
135
+ cfg = _cfg(args)
136
+ model = GPT(cfg).to(device)
137
+ n_params = sum(p.numel() for p in model.parameters())
138
+ print(f"[train] DENSE {n_params/1e6:.1f}M params | layers={args.n_layer} "
139
+ f"d={args.n_embd} | micro={args.micro_batch} accum={args.grad_accum} "
140
+ f"seq={args.train_seq_len}", flush=True)
141
+
142
+ loader = _MemmapLoader(args.data_path, args.train_seq_len, device, args.seed)
143
+ opt = torch.optim.AdamW(model.parameters(), lr=args.learning_rate,
144
+ weight_decay=args.weight_decay, betas=(args.beta1, args.beta2),
145
+ fused=True)
146
+
147
+ start = time.time()
148
+ deadline = start + args.wallclock_sec * 0.94
149
+ est_total_steps = 6000
150
+ warmup = max(1, int(args.warmup_frac * est_total_steps))
151
+ last_save = start
152
+ step = 0
153
+ model.train()
154
+ while time.time() < deadline:
155
+ lr = (args.learning_rate * (step + 1) / warmup if step < warmup
156
+ else args.learning_rate * (args.min_lr_frac + (1 - args.min_lr_frac) *
157
+ 0.5 * (1 + math.cos(math.pi * min(1.0, (step - warmup) / max(1, est_total_steps - warmup))))))
158
+ for g in opt.param_groups:
159
+ g["lr"] = lr
160
+ opt.zero_grad(set_to_none=True)
161
+ for _ in range(args.grad_accum):
162
+ x, y = loader.batch(args.micro_batch)
163
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
164
+ _, loss = model(x, y)
165
+ (loss / args.grad_accum).backward()
166
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
167
+ opt.step()
168
+ step += 1
169
+ if step % 25 == 0:
170
+ print(f"[train] step {step} lr {lr:.2e} loss {loss.item():.4f} "
171
+ f"peakGB {torch.cuda.max_memory_allocated()/1e9:.2f} t {time.time()-start:.0f}s", flush=True)
172
+ if time.time() - last_save >= args.save_every_sec:
173
+ _save(model, cfg, args.out_ckpt)
174
+ last_save = time.time()
175
+ _save(model, cfg, args.out_ckpt)
176
+ print(f"[train] done: {step} steps in {time.time()-start:.0f}s -> {args.out_ckpt}", flush=True)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
tasks/e2e/a3-moe-train-budget/task/instruction.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Train the best Mixture-of-Experts language model you can within a fixed budget
2
+
3
+ You are given the full [nanoGPT](https://github.com/karpathy/nanoGPT) training
4
+ system at `/app/repo` (fully editable) and a tokenized WikiText-103 corpus. Your
5
+ job is to **train the best language model you can on ONE H20 GPU within a fixed
6
+ wall-clock budget, subject to a hard total-parameter floor**, then let the grader
7
+ score it:
8
+
9
+ - a **hard total-parameter FLOOR** — your model must have at least a required
10
+ number of total parameters. The grader **re-counts your model's parameters** from
11
+ the checkpoint and **rejects the run (score 0) if it is below the floor**. (A tiny
12
+ model cannot win by being fast.)
13
+ - a **hard wall-clock budget** — the grader starts your training, runs it under a
14
+ timer it owns, and stops the whole process group at the budget. Your training must
15
+ periodically save its checkpoint so the latest save is scored.
16
+
17
+ The grader then loads the checkpoint your training produced and measures its
18
+ **bits-per-byte (`val_bpb`) on a held-out WikiText-103 split you never see**.
19
+ **Lower `val_bpb` is better.**
20
+
21
+ ## How you are scored
22
+
23
+ Scoring is **bounded between 0.0 and 1.0**, and it is measured against **the
24
+ starting recipe you were given**:
25
+
26
+ - The provided starter is a **plain dense** model at the parameter floor. It is a
27
+ real, complete, working training recipe — and it is the bar. **Submitting it, or
28
+ anything that does not strictly improve on its held-out `val_bpb`, scores 0.**
29
+ - Beyond that, your score rises **continuously** with how much of the achievable
30
+ `val_bpb` gap you close. Reaching the quality of a strong reference recipe
31
+ measured at this same budget scores **0.5**; pushing further keeps earning more,
32
+ up to the 1.0 ceiling. Coming close to the starter without passing it earns
33
+ nothing — you have to actually beat it.
34
+ - Any hard-gate failure — below the parameter floor, no checkpoint inside the
35
+ budget, a degenerate or forged-loss model, or touching the grader's files — scores
36
+ **0**, whatever the `val_bpb`.
37
+
38
+ So a mediocre-but-safe tweak of the starter is worth exactly as much as no
39
+ submission at all. The whole game is pushing `val_bpb` as low as you can inside the
40
+ budget.
41
+
42
+ ## Why this is hard (the MoE lever)
43
+
44
+ The parameter floor puts you at a capacity where a **dense** model spends its full
45
+ compute on every token — so in a fixed wall-clock budget a dense model of that size
46
+ takes far too few optimizer steps and converges poorly. That is exactly what the
47
+ provided starter does, and it is why beating it is possible at all. The way to
48
+ train a floor-sized model well in the budget is a **sparse Mixture-of-Experts
49
+ (MoE)**: many expert feed-forward networks, but only a few (top-k) active per token,
50
+ so the compute per token — and therefore the number of steps you fit in the budget —
51
+ is governed by the **active** parameters, not the total.
52
+
53
+ But sparsity only helps if you **realize it as real single-card throughput**. The
54
+ levers that matter:
55
+
56
+ - **efficient token dispatch** — route each token to its top-k experts and compute
57
+ each expert only on its routed tokens (sorted/grouped/batched GEMM, a per-expert
58
+ capacity buffer). A naive loop that runs *every* expert on *every* token has dense
59
+ FLOPs and gives no speedup — it will barely beat the dense starter. This is where
60
+ most of the throughput is won or lost.
61
+ - **load balancing** — without a load-balancing objective the router collapses onto
62
+ a few experts, wasting the floor capacity and overflowing expert buffers; a
63
+ balancing auxiliary loss keeps experts utilized.
64
+ - **the routing frontier** — number of experts, top-k, and capacity factor trade
65
+ quality against throughput and drop rate.
66
+
67
+ The design space is wide: you may change the model, router, dispatch, optimizer, LR
68
+ schedule, attention, data loading, precision — anything under `/app/repo` (nanoGPT)
69
+ and `/app/submission`. Public references (nanoGPT, the MoE literature — Switch
70
+ Transformer, GShard, MegaBlocks/dropless MoE, Tutel) are fair game.
71
+
72
+ ## Data
73
+
74
+ - Train on `/data/datasets/wikitext_bpe8k/train.bin` (flat `uint16`, nanoGPT
75
+ layout). `/data/datasets/wikitext_bpe8k/val.bin` is your **local progress
76
+ monitor** (the WikiText-103 *validation* split); the grader scores on the
77
+ held-out *test* split, same distribution, so your local `val_bpb` tracks the
78
+ grader's within a small margin.
79
+ - Tokenizer: SentencePiece **BPE-8K** at `/data/tokenizers/wikitext_bpe8k.model`
80
+ (`vocab_size = 8192`). `meta.pkl` in the data dir carries `vocab_size`.
81
+ - The grader pins `DATA_PATH` and `TOKENIZER_PATH` itself; they are not taken from
82
+ your environment.
83
+
84
+ ## What to submit (the entry contract)
85
+
86
+ Everything the grader needs must live under `/app/submission/`:
87
+
88
+ 1. **`/app/submission/run_training.sh`** — your training entry. The grader runs it
89
+ with `SEED`, `PARAM_FLOOR`, `WALLCLOCK_SEC`, `OUT_CKPT`, `DATA_PATH`,
90
+ `TOKENIZER_PATH`, `NANOGPT_REPO` in the environment. It **must write a checkpoint
91
+ to `$OUT_CKPT`** within the budget (save periodically — the timer can stop you at
92
+ any moment, and it stops your whole process group, so a detached background
93
+ trainer buys you nothing).
94
+ 2. **`/app/submission/train_gpt.py`** — must define
95
+ `load_model_for_verification(checkpoint_path, device)` returning either an
96
+ `nn.Module` or `(args, model)`. The loaded model's `forward` must satisfy:
97
+ - `model(input_ids)` → floating-point logits `(batch, seq_len, vocab_size)` that
98
+ depend on token position;
99
+ - `model(input_ids, target_ids)` → a **scalar** loss equal (within a small
100
+ tolerance) to `F.cross_entropy(logits.reshape(-1, V), target_ids.reshape(-1))`
101
+ on those same logits. This is the **pure** cross-entropy of the logits — do
102
+ **not** fold an MoE auxiliary (load-balancing) loss into this returned loss;
103
+ add the auxiliary loss inside your training loop only.
104
+
105
+ A working starting `train_gpt.py` — the dense-at-floor recipe described above —
106
+ is provided. It is a starting point, **not** a contract; you may replace all of
107
+ it.
108
+
109
+ The grader also enforces that your model is a **real LM**: it scores real held-out
110
+ text noticeably better than arbitrary token IDs, has at least the floor number of
111
+ parameters, its `forward(x,y)` loss agrees with the cross-entropy of its
112
+ `forward(x)` logits, and its `val_bpb` falls inside a plausible band. A degenerate
113
+ or forged-loss model scores 0.
114
+
115
+ ## Rules
116
+
117
+ - **How you submit:** there is no submit command and no submission budget — edit the
118
+ allowed files under `/app/submission/` (and `/app/repo` if you like) and **leave your
119
+ changes in the working tree**. Do not `git commit`: grading diffs your working tree
120
+ against the baked baseline commit, so the repo HEAD must stay on that initial commit.
121
+ - The training seed is fixed by the grader (you cannot seed-shop).
122
+ - You do **not** have internet access; all packages you need are pre-installed.
123
+ - **Do not** read, copy, grep, or edit any grader / held-out / timer file
124
+ (`/tests/*`); do **not** disable or tamper with the wall-clock timer; do **not**
125
+ try to read the held-out corpus or infer the reference score. The grader
126
+ fingerprints its own files around your run, so any of these scores the whole task
127
+ **0**. (Consulting the public nanoGPT repo and the public MoE literature is
128
+ allowed — what is protected is the grader's measurement, not the method.)
129
+
130
+ ---
131
+
132
+ ## How you are graded
133
+
134
+ Grading is **single-shot**: after you finish, the grader runs your
135
+ `/app/submission/run_training.sh` **once** under its own wall-clock timer, then loads the
136
+ resulting checkpoint and measures held-out `val_bpb`. There is no interactive dev proxy and
137
+ no submission budget — only your final working-tree state is scored.
138
+
139
+ You can still monitor progress yourself. `val.bin` (the public validation split) is your
140
+ local `val_bpb` proxy and tracks the grader within a small margin. At a fixed capacity
141
+ your real lever is **throughput** — how many optimizer steps you fit in the fixed
142
+ wall-clock budget — so watch tokens/sec as the primary signal that a
143
+ dispatch/precision/batching change made training faster, and use local `val_bpb` only for
144
+ coarse "is it still learning?" direction. The graded budget is wall-clock, so the number
145
+ of steps it buys drifts with GPU node contention; do not read much into a tiny `val_bpb`
146
+ change. `val.bin` is a PUBLIC proxy, NOT the graded score (the grade uses a held-out
147
+ split) — do not overfit it.
148
+
149
+ ### 🔴 Red line (hard — ANY one ⇒ the whole task scores 0)
150
+
151
+ 1. Do **NOT deliberately** read/`cat`/`grep`/`find`/edit ANY verifier / timing / scoring
152
+ / hidden-test / held-out file or dir, wherever it lives. Leaving your edits in the
153
+ working tree is the only submission — do not run or reverse-engineer the verifier.
154
+ 2. Do **NOT** run the grader directly or reproduce/reverse-engineer it.
155
+ 3. Do **NOT** search for, print, or infer the held-out corpus, the grader's seed, the
156
+ parameter-floor value, the wall-clock budget value, the metric thresholds, or the
157
+ reference score.
158
+ 4. Do **NOT** fetch an upstream implementation or reference solution (no web search, no
159
+ git remote fetch, no network). Public nanoGPT + MoE knowledge you already have is fine.
160
+ 5. Do **NOT** use, quote, or condition your code on any verifier / scoring / held-out
161
+ material, however you saw it.
tasks/e2e/a3-moe-train-budget/task/pre_artifacts.sh ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ============================================================================
3
+ # pre_artifacts.sh — e2e/a3-moe-train-budget
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:263: ENV NANOGPT_REPO=/app/repo \
33
+ # evidence Dockerfile:266: REPO_DIR=/app/repo \
34
+ # evidence Dockerfile:221: && cd /app/repo \
35
+ # evidence Dockerfile:226: && test "$(git rev-list --count HEAD)" = "1" \
36
+ # evidence test.sh:149: export NANOGPT_REPO=/app/repo
37
+ # evidence test.sh:150: export PYTHONPATH=/app/repo
38
+ # /app/submission NOT a git repo -> full tree snapshot
39
+ # evidence Dockerfile:265: SUBMISSION_DIR=/app/submission \
40
+ # evidence Dockerfile:211: COPY environment/submission/ /app/submission/
41
+ # evidence test.sh:37: SUBMISSION_DIR=/app/submission
42
+ #
43
+ # MULTI-ROOT FORMAT: this task has more than one capture root, so each root's diff in
44
+ # model.patch is introduced by a one-line banner
45
+ # # ==== pre_artifacts root=<dir> mode=<git-diff-vs-baseline|tree-snapshot...> ====
46
+ # and every path in model_files.txt is ABSOLUTE, so the roots can never be confused.
47
+ # Single-root tasks in this corpus emit a bare diff with no banner.
48
+ # ============================================================================
49
+ set -uo pipefail
50
+
51
+ OUT=/logs/artifacts
52
+ PATCH="$OUT/model.patch"
53
+ LIST="$OUT/model_files.txt"
54
+ MULTI=1 # 1 => several capture roots => each diff gets a banner line
55
+ MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane)
56
+
57
+ mkdir -p "$OUT" 2>/dev/null || true
58
+ : > "$PATCH" 2>/dev/null || true
59
+ : > "$LIST" 2>/dev/null || true
60
+ git config --global --add safe.directory '*' >/dev/null 2>&1 || true
61
+
62
+ banner() { # $1=root $2=mode ; only when there is more than one root
63
+ if [ "$MULTI" = 1 ]; then
64
+ printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null
65
+ fi
66
+ return 0
67
+ }
68
+
69
+ list_add() { # stdin: paths relative to $1 -> absolute, one per line
70
+ sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true
71
+ return 0
72
+ }
73
+
74
+ capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline
75
+ root=$1
76
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
77
+ if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
78
+ echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot"
79
+ capture_tree "$root"
80
+ return 0
81
+ fi
82
+ # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and
83
+ # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could
84
+ # flip a scope gate either way. So copy the repo's index aside and stage into the COPY —
85
+ # the repo's own .git/index is byte-identical when we are done.
86
+ tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi=""
87
+ gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true)
88
+ if [ -z "$gd" ]; then
89
+ gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true)
90
+ case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac
91
+ fi
92
+ if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then
93
+ GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE
94
+ else
95
+ echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index"
96
+ fi
97
+ git -C "$root" add -AN . >/dev/null 2>&1 || true
98
+ base=HEAD
99
+ if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then
100
+ base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null)
101
+ echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree"
102
+ else
103
+ n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0)
104
+ case "$n" in ''|*[!0-9]*) n=0 ;; esac
105
+ if [ "$n" -gt 1 ]; then
106
+ base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1)
107
+ echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:"
108
+ echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so"
109
+ echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved"
110
+ echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve."
111
+ fi
112
+ fi
113
+ [ -n "${base:-}" ] || base=HEAD
114
+ banner "$root" "git-diff-vs-baseline"
115
+ git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true
116
+ names=$(git -C "$root" diff --name-only "$base" 2>/dev/null)
117
+ echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)"
118
+ unset GIT_INDEX_FILE
119
+ [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null
120
+ printf '%s\n' "$names" | grep -v '^$' | list_add "$root"
121
+ return 0
122
+ }
123
+
124
+ capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot
125
+ root=$1
126
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
127
+ tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0
128
+ if git init -q "$tmp/snap" >/dev/null 2>&1; then
129
+ GD="$tmp/snap/.git"
130
+ empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null)
131
+ ( cd "$root" 2>/dev/null || exit 0
132
+ find . -name .git -prune -o -name __pycache__ -prune -o \
133
+ -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \
134
+ 2>/dev/null \
135
+ | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true
136
+ banner "$root" "tree-snapshot-not-a-git-repo"
137
+ GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \
138
+ >> "$PATCH" 2>/dev/null || true
139
+ else
140
+ echo "[pre_artifacts] WARN could not stage a snapshot index for $root"
141
+ fi
142
+ rm -rf "$tmp" 2>/dev/null || true
143
+ all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \
144
+ -type f -print 2>/dev/null | sed 's|^\./||' )
145
+ printf '%s\n' "$all" | grep -v '^$' | list_add "$root"
146
+ big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \
147
+ -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . )
148
+ echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)"
149
+ if [ "${big:-0}" != 0 ]; then
150
+ echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in"
151
+ echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch."
152
+ fi
153
+ return 0
154
+ }
155
+
156
+ capture_git "/app/repo"
157
+ capture_tree "/app/submission"
158
+ bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0)
159
+ case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac
160
+ echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)"
161
+ if [ "$bytes" -gt 67108864 ]; then
162
+ echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build"
163
+ echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also"
164
+ echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish."
165
+ fi
166
+ exit 0
tasks/e2e/a3-moe-train-budget/task/solution/baseline_dense_floor/run_training.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; fully editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR, WALLCLOCK_SEC,
4
+ # OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ #
6
+ # It MUST write a checkpoint to $OUT_CKPT within the budget (save periodically — the timer can
7
+ # stop you at any moment) and leave load_model_for_verification(checkpoint_path, device)
8
+ # importable from /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
9
+ # (the grader re-counts it).
10
+ #
11
+ # This starting version runs the provided dense baseline. Change anything you like — nanoGPT
12
+ # under /app/repo is fully editable too.
13
+ set -e
14
+ cd /app/submission
15
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/solution/baseline_dense_floor/train_gpt.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # e2e-a3-moe-train-budget — the provided STARTING POINT (fully editable, NOT a contract).
2
+ #
3
+ # This is a plain DENSE nanoGPT sized to clear the task's hard total-parameter FLOOR, trained
4
+ # with a straightforward AdamW recipe until the harness's wall-clock timer stops it. It is a
5
+ # complete, working, honest baseline: real data loading, bf16 autocast, warmup + cosine decay,
6
+ # gradient clipping, and an atomic periodic checkpoint save so a timer kill always leaves a
7
+ # valid artifact. It satisfies the verifier's entry contract as-is.
8
+ #
9
+ # It is also DELIBERATELY the thing you have to beat. Because it is dense, every token pays
10
+ # the full ~2*P_total FLOPs, so it fits comparatively few optimizer steps into the budget and
11
+ # converges to a mediocre held-out bits-per-byte. Submitting it unchanged scores 0.
12
+ #
13
+ # You may change anything: the model, the router, the dispatch, the optimizer, the schedule,
14
+ # the data loading, the precision — everything under /app/repo (nanoGPT) and /app/submission.
15
+ #
16
+ # VERIFIER CONTRACT (enforced): the grader loads the checkpoint via
17
+ # load_model_for_verification(checkpoint_path, device) and requires a model whose
18
+ # * model(input_ids) -> float logits (batch, seq, vocab), position-dependent
19
+ # * model(input_ids, target_ids) -> scalar loss == CE(logits.view(-1,V), targets.view(-1))
20
+ # i.e. the PURE cross-entropy of those logits. If you add an auxiliary training objective
21
+ # (for example a load-balancing loss), keep it inside your training loop — do NOT fold it into
22
+ # the loss this forward returns. An OOD probe enforces loss(real_text) < 0.7 * loss(arbitrary
23
+ # ids), and the model must clear the total-parameter floor.
24
+ from __future__ import annotations
25
+
26
+ import math
27
+ import os
28
+ import sys
29
+ import time
30
+ from pathlib import Path
31
+
32
+ import numpy as np
33
+ import torch
34
+ import torch.nn as nn
35
+
36
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
37
+ if REPO not in sys.path:
38
+ sys.path.insert(0, REPO)
39
+ from model import GPT, GPTConfig # noqa: E402 (from /app/repo/model.py)
40
+
41
+
42
+ class Hyperparameters:
43
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
44
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
45
+ seed = int(os.environ.get("SEED", "1337"))
46
+ out_ckpt = os.environ.get("OUT_CKPT", "/app/submission/model_ckpt.pt")
47
+ wallclock_sec = float(os.environ.get("WALLCLOCK_SEC", "600"))
48
+
49
+ vocab_size = 8192
50
+ train_seq_len = 512
51
+ block_size = 512
52
+ val_batch_size = 32_768
53
+
54
+ # DENSE model sized to clear the 150M floor: n_embd=1024,n_layer=12 nanoGPT
55
+ # transformer ~= 12*(12*1024^2) = 151.0M + tied wte 8.4M + wpe 0.5M ~= 160M.
56
+ n_layer = 12
57
+ n_head = 16
58
+ n_embd = 1024
59
+ dropout = 0.0
60
+ bias = False
61
+
62
+ # SAME recipe as the strong MoE baseline (fair comparison; only dense-vs-sparse differs)
63
+ micro_batch = 16
64
+ grad_accum = 2
65
+ learning_rate = 3e-3
66
+ weight_decay = 0.1
67
+ beta1, beta2 = 0.9, 0.95
68
+ grad_clip = 1.0
69
+ warmup_frac = 0.05
70
+ min_lr_frac = 0.1
71
+ save_every_sec = 20.0
72
+
73
+
74
+ class _VerifierAdapter(nn.Module):
75
+ def __init__(self, gpt: GPT):
76
+ super().__init__()
77
+ self.gpt = gpt
78
+
79
+ def forward(self, idx, targets=None):
80
+ logits, loss = self.gpt(idx, idx if targets is None else targets)
81
+ return logits if targets is None else loss
82
+
83
+
84
+ def _cfg(args: Hyperparameters) -> GPTConfig:
85
+ return GPTConfig(block_size=args.block_size, vocab_size=args.vocab_size,
86
+ n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd,
87
+ dropout=args.dropout, bias=args.bias)
88
+
89
+
90
+ def load_model_for_verification(checkpoint_path, device):
91
+ args = Hyperparameters()
92
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
93
+ cfg_kwargs = obj.get("config", {})
94
+ cfg = GPTConfig(**cfg_kwargs) if cfg_kwargs else _cfg(args)
95
+ gpt = GPT(cfg)
96
+ gpt.load_state_dict(obj["model"], strict=True)
97
+ args.train_seq_len = cfg.block_size
98
+ args.vocab_size = cfg.vocab_size
99
+ return args, _VerifierAdapter(gpt).to(device).eval()
100
+
101
+
102
+ def _save(model: GPT, cfg: GPTConfig, out_ckpt: str) -> None:
103
+ tmp = out_ckpt + ".tmp"
104
+ torch.save({"model": model.state_dict(),
105
+ "config": dict(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
106
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
107
+ dropout=0.0, bias=cfg.bias)}, tmp)
108
+ os.replace(tmp, out_ckpt)
109
+
110
+
111
+ class _MemmapLoader:
112
+ def __init__(self, data_path: str, seq_len: int, device: torch.device, seed: int):
113
+ self.data = np.memmap(Path(data_path) / "train.bin", dtype=np.uint16, mode="r")
114
+ self.seq_len = seq_len
115
+ self.device = device
116
+ self.rng = np.random.default_rng(seed)
117
+
118
+ def batch(self, n: int):
119
+ ix = self.rng.integers(0, len(self.data) - self.seq_len - 1, size=n)
120
+ x = torch.from_numpy(np.stack([self.data[i:i + self.seq_len].astype(np.int64) for i in ix]))
121
+ y = torch.from_numpy(np.stack([self.data[i + 1:i + 1 + self.seq_len].astype(np.int64) for i in ix]))
122
+ return (x.pin_memory().to(self.device, non_blocking=True),
123
+ y.pin_memory().to(self.device, non_blocking=True))
124
+
125
+
126
+ def main() -> None:
127
+ args = Hyperparameters()
128
+ torch.manual_seed(args.seed)
129
+ np.random.seed(args.seed)
130
+ torch.backends.cuda.matmul.allow_tf32 = True
131
+ torch.backends.cudnn.allow_tf32 = True
132
+ device = torch.device("cuda", 0)
133
+ torch.cuda.set_device(device)
134
+
135
+ cfg = _cfg(args)
136
+ model = GPT(cfg).to(device)
137
+ n_params = sum(p.numel() for p in model.parameters())
138
+ print(f"[train] DENSE {n_params/1e6:.1f}M params | layers={args.n_layer} "
139
+ f"d={args.n_embd} | micro={args.micro_batch} accum={args.grad_accum} "
140
+ f"seq={args.train_seq_len}", flush=True)
141
+
142
+ loader = _MemmapLoader(args.data_path, args.train_seq_len, device, args.seed)
143
+ opt = torch.optim.AdamW(model.parameters(), lr=args.learning_rate,
144
+ weight_decay=args.weight_decay, betas=(args.beta1, args.beta2),
145
+ fused=True)
146
+
147
+ start = time.time()
148
+ deadline = start + args.wallclock_sec * 0.94
149
+ est_total_steps = 6000
150
+ warmup = max(1, int(args.warmup_frac * est_total_steps))
151
+ last_save = start
152
+ step = 0
153
+ model.train()
154
+ while time.time() < deadline:
155
+ lr = (args.learning_rate * (step + 1) / warmup if step < warmup
156
+ else args.learning_rate * (args.min_lr_frac + (1 - args.min_lr_frac) *
157
+ 0.5 * (1 + math.cos(math.pi * min(1.0, (step - warmup) / max(1, est_total_steps - warmup))))))
158
+ for g in opt.param_groups:
159
+ g["lr"] = lr
160
+ opt.zero_grad(set_to_none=True)
161
+ for _ in range(args.grad_accum):
162
+ x, y = loader.batch(args.micro_batch)
163
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
164
+ _, loss = model(x, y)
165
+ (loss / args.grad_accum).backward()
166
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
167
+ opt.step()
168
+ step += 1
169
+ if step % 25 == 0:
170
+ print(f"[train] step {step} lr {lr:.2e} loss {loss.item():.4f} "
171
+ f"peakGB {torch.cuda.max_memory_allocated()/1e9:.2f} t {time.time()-start:.0f}s", flush=True)
172
+ if time.time() - last_save >= args.save_every_sec:
173
+ _save(model, cfg, args.out_ckpt)
174
+ last_save = time.time()
175
+ _save(model, cfg, args.out_ckpt)
176
+ print(f"[train] done: {step} steps in {time.time()-start:.0f}s -> {args.out_ckpt}", flush=True)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
tasks/e2e/a3-moe-train-budget/task/solution/mid_naive_moe/run_training.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR,
4
+ # WALLCLOCK_SEC, OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ # It MUST write a checkpoint to $OUT_CKPT within the budget and leave a
6
+ # load_model_for_verification(checkpoint_path, device) importable from
7
+ # /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
8
+ # (the grader re-counts it). This starting version runs the strong single-card
9
+ # MoE recipe; change anything you like (nanoGPT under /app/repo is fully editable).
10
+ set -e
11
+ cd /app/submission
12
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/solution/mid_naive_moe/train_gpt.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # e2e-a3-moe-train-budget : REVIEWER-ONLY MID-RUNG control (a partially-correct MoE).
2
+ #
3
+ # 🔴 NOT SHIPPED. Same MoE MODEL as the oracle (same total params -> clears the capacity floor
4
+ # and the anti-spoof kit) but a NAIVE per-expert dispatch that runs EVERY expert on EVERY token
5
+ # and then masks. That is DENSE FLOPs (n_experts * expert_cost per token, not top_k), so it
6
+ # fits far fewer optimizer steps into the wall-clock budget; it also omits the load-balancing
7
+ # auxiliary loss, so the router tends to collapse. Result: it does beat the dense starter but
8
+ # lands well short of the oracle -> a reward strictly between 0 and 0.5.
9
+ #
10
+ # This is the discrimination probe: it proves the bounded reward grades PARTIAL MoE work
11
+ # instead of collapsing to pass/fail.
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ import os
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+
25
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
26
+ if REPO not in sys.path:
27
+ sys.path.insert(0, REPO)
28
+ from model import CausalSelfAttention, LayerNorm, GPTConfig # noqa: E402
29
+
30
+
31
+ class Hyperparameters:
32
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
33
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
34
+ seed = int(os.environ.get("SEED", "1337"))
35
+ out_ckpt = os.environ.get("OUT_CKPT", "/app/submission/model_ckpt.pt")
36
+ wallclock_sec = float(os.environ.get("WALLCLOCK_SEC", "600"))
37
+
38
+ vocab_size = 8192
39
+ train_seq_len = 512
40
+ block_size = 512
41
+ val_batch_size = 32_768
42
+
43
+ n_layer = 8
44
+ n_head = 8
45
+ n_embd = 512
46
+ dropout = 0.0
47
+ bias = False
48
+ n_experts = 16
49
+ top_k = 2
50
+ ffn_mult = 4
51
+ capacity_factor = 1.25 # unused by the naive dispatch (kept for cfg-dict parity)
52
+ aux_loss_coef = 0.0 # NAIVE: no load-balancing loss (router can collapse)
53
+ router_z_coef = 0.0
54
+
55
+ micro_batch = 16
56
+ grad_accum = 2
57
+ learning_rate = 3e-3
58
+ weight_decay = 0.1
59
+ beta1, beta2 = 0.9, 0.95
60
+ grad_clip = 1.0
61
+ warmup_frac = 0.05
62
+ min_lr_frac = 0.1
63
+ save_every_sec = 20.0
64
+
65
+
66
+ class MoEMLP(nn.Module):
67
+ """NAIVE dispatch: run every expert on every token, then combine with the
68
+ top-k gate mask. Correct MoE math, but DENSE compute -> the sparsity is NOT
69
+ realized as throughput. This is exactly the anti-pattern the task rewards
70
+ replacing with a real sorted/grouped dispatch."""
71
+
72
+ def __init__(self, cfg: "Hyperparameters"):
73
+ super().__init__()
74
+ self.d = cfg.n_embd
75
+ self.hdim = cfg.ffn_mult * cfg.n_embd
76
+ self.E = cfg.n_experts
77
+ self.top_k = cfg.top_k
78
+ self.router = nn.Linear(self.d, self.E, bias=False)
79
+ self.w1 = nn.Parameter(torch.empty(self.E, self.d, self.hdim))
80
+ self.w2 = nn.Parameter(torch.empty(self.E, self.hdim, self.d))
81
+ nn.init.normal_(self.w1, mean=0.0, std=0.02)
82
+ nn.init.normal_(self.w2, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer))
83
+ self.last_aux = torch.zeros(())
84
+ self.last_z = torch.zeros(())
85
+
86
+ def forward(self, x):
87
+ B, T, d = x.shape
88
+ N = B * T
89
+ xf = x.reshape(N, d)
90
+ logits = self.router(xf)
91
+ probs = F.softmax(logits.float(), dim=-1).to(xf.dtype) # [N, E]
92
+ topv, topi = probs.topk(self.top_k, dim=-1)
93
+ topv = topv / (topv.sum(dim=-1, keepdim=True) + 1e-9)
94
+ # gate weight matrix [N, E]: nonzero only at the top_k experts
95
+ gate = xf.new_zeros(N, self.E)
96
+ gate.scatter_(1, topi, topv)
97
+ self.last_aux = torch.zeros((), device=x.device)
98
+ self.last_z = torch.zeros((), device=x.device)
99
+
100
+ # NAIVE: every expert computes every token (DENSE FLOPs), then weight by gate.
101
+ y = xf.new_zeros(N, d)
102
+ for e in range(self.E):
103
+ he = F.gelu(xf @ self.w1[e]) # [N, hdim] -- ALL tokens
104
+ oe = he @ self.w2[e] # [N, d]
105
+ y = y + gate[:, e:e + 1] * oe
106
+ return y.reshape(B, T, d)
107
+
108
+
109
+ class MoEBlock(nn.Module):
110
+ def __init__(self, cfg, gptcfg):
111
+ super().__init__()
112
+ self.ln_1 = LayerNorm(cfg.n_embd, bias=cfg.bias)
113
+ self.attn = CausalSelfAttention(gptcfg)
114
+ self.ln_2 = LayerNorm(cfg.n_embd, bias=cfg.bias)
115
+ self.moe = MoEMLP(cfg)
116
+
117
+ def forward(self, x):
118
+ x = x + self.attn(self.ln_1(x))
119
+ x = x + self.moe(self.ln_2(x))
120
+ return x
121
+
122
+
123
+ class MoEGPT(nn.Module):
124
+ def __init__(self, cfg):
125
+ super().__init__()
126
+ self.cfg = cfg
127
+ gptcfg = GPTConfig(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
128
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
129
+ dropout=cfg.dropout, bias=cfg.bias)
130
+ self.wte = nn.Embedding(cfg.vocab_size, cfg.n_embd)
131
+ self.wpe = nn.Embedding(cfg.block_size, cfg.n_embd)
132
+ self.drop = nn.Dropout(cfg.dropout)
133
+ self.h = nn.ModuleList([MoEBlock(cfg, gptcfg) for _ in range(cfg.n_layer)])
134
+ self.ln_f = LayerNorm(cfg.n_embd, bias=cfg.bias)
135
+ self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)
136
+ self.wte.weight = self.lm_head.weight
137
+ self.apply(self._init)
138
+
139
+ def _init(self, m):
140
+ if isinstance(m, nn.Linear):
141
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
142
+ if m.bias is not None:
143
+ nn.init.zeros_(m.bias)
144
+ elif isinstance(m, nn.Embedding):
145
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
146
+
147
+ def aux_losses(self):
148
+ z = torch.zeros((), device=self.lm_head.weight.device)
149
+ return z, z
150
+
151
+ def forward(self, idx, targets=None):
152
+ b, t = idx.size()
153
+ pos = torch.arange(0, t, dtype=torch.long, device=idx.device)
154
+ x = self.drop(self.wte(idx) + self.wpe(pos))
155
+ for blk in self.h:
156
+ x = blk(x)
157
+ x = self.ln_f(x)
158
+ logits = self.lm_head(x)
159
+ if targets is not None:
160
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
161
+ return logits, loss
162
+ return logits, None
163
+
164
+
165
+ class _VerifierAdapter(nn.Module):
166
+ def __init__(self, moe):
167
+ super().__init__()
168
+ self.moe = moe
169
+
170
+ def forward(self, idx, targets=None):
171
+ logits, loss = self.moe(idx, idx if targets is None else targets)
172
+ return logits if targets is None else loss
173
+
174
+
175
+ def _cfg_dict(cfg):
176
+ return dict(vocab_size=cfg.vocab_size, block_size=cfg.block_size,
177
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
178
+ dropout=0.0, bias=cfg.bias, n_experts=cfg.n_experts,
179
+ top_k=cfg.top_k, ffn_mult=cfg.ffn_mult, capacity_factor=cfg.capacity_factor)
180
+
181
+
182
+ def _cfg_from_dict(d):
183
+ c = Hyperparameters()
184
+ for k, v in d.items():
185
+ setattr(c, k, v)
186
+ c.train_seq_len = d.get("block_size", c.block_size)
187
+ return c
188
+
189
+
190
+ def load_model_for_verification(checkpoint_path, device):
191
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
192
+ cfg = _cfg_from_dict(obj.get("config", {}))
193
+ moe = MoEGPT(cfg)
194
+ moe.load_state_dict(obj["model"], strict=True)
195
+ return cfg, _VerifierAdapter(moe).to(device).eval()
196
+
197
+
198
+ def _save(model, cfg, out_ckpt):
199
+ tmp = out_ckpt + ".tmp"
200
+ torch.save({"model": model.state_dict(), "config": _cfg_dict(cfg)}, tmp)
201
+ os.replace(tmp, out_ckpt)
202
+
203
+
204
+ class _MemmapLoader:
205
+ def __init__(self, data_path, seq_len, device, seed):
206
+ self.data = np.memmap(Path(data_path) / "train.bin", dtype=np.uint16, mode="r")
207
+ self.seq_len = seq_len
208
+ self.device = device
209
+ self.rng = np.random.default_rng(seed)
210
+
211
+ def batch(self, n):
212
+ ix = self.rng.integers(0, len(self.data) - self.seq_len - 1, size=n)
213
+ x = torch.from_numpy(np.stack([self.data[i:i + self.seq_len].astype(np.int64) for i in ix]))
214
+ y = torch.from_numpy(np.stack([self.data[i + 1:i + 1 + self.seq_len].astype(np.int64) for i in ix]))
215
+ return (x.pin_memory().to(self.device, non_blocking=True),
216
+ y.pin_memory().to(self.device, non_blocking=True))
217
+
218
+
219
+ def main():
220
+ args = Hyperparameters()
221
+ torch.manual_seed(args.seed)
222
+ np.random.seed(args.seed)
223
+ torch.backends.cuda.matmul.allow_tf32 = True
224
+ torch.backends.cudnn.allow_tf32 = True
225
+ device = torch.device("cuda", 0)
226
+ torch.cuda.set_device(device)
227
+
228
+ model = MoEGPT(args).to(device)
229
+ n_params = sum(p.numel() for p in model.parameters())
230
+ print(f"[naive] MoE {n_params/1e6:.1f}M total params | DENSE per-expert loop dispatch (no throughput win)", flush=True)
231
+
232
+ loader = _MemmapLoader(args.data_path, args.train_seq_len, device, args.seed)
233
+ opt = torch.optim.AdamW(model.parameters(), lr=args.learning_rate,
234
+ weight_decay=args.weight_decay, betas=(args.beta1, args.beta2), fused=True)
235
+ start = time.time()
236
+ deadline = start + args.wallclock_sec * 0.94
237
+ est_total_steps = 6000
238
+ warmup = max(1, int(args.warmup_frac * est_total_steps))
239
+ last_save = start
240
+ step = 0
241
+ model.train()
242
+ while time.time() < deadline:
243
+ lr = (args.learning_rate * (step + 1) / warmup if step < warmup
244
+ else args.learning_rate * (args.min_lr_frac + (1 - args.min_lr_frac) *
245
+ 0.5 * (1 + math.cos(math.pi * min(1.0, (step - warmup) / max(1, est_total_steps - warmup))))))
246
+ for g in opt.param_groups:
247
+ g["lr"] = lr
248
+ opt.zero_grad(set_to_none=True)
249
+ for _ in range(args.grad_accum):
250
+ x, y = loader.batch(args.micro_batch)
251
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
252
+ _, ce = model(x, y)
253
+ (ce / args.grad_accum).backward()
254
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
255
+ opt.step()
256
+ step += 1
257
+ if step % 25 == 0:
258
+ print(f"[naive] step {step} lr {lr:.2e} ce {ce.item():.4f} "
259
+ f"peakGB {torch.cuda.max_memory_allocated()/1e9:.2f} t {time.time()-start:.0f}s", flush=True)
260
+ if time.time() - last_save >= args.save_every_sec:
261
+ _save(model, args, args.out_ckpt)
262
+ last_save = time.time()
263
+ _save(model, args, args.out_ckpt)
264
+ print(f"[naive] done: {step} steps in {time.time()-start:.0f}s -> {args.out_ckpt}", flush=True)
265
+
266
+
267
+ if __name__ == "__main__":
268
+ main()
tasks/e2e/a3-moe-train-budget/task/solution/oracle_grouped_moe/RECIPE_RECORD.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "note": "REVIEWER-ONLY record of the ORACLE recipe (the reward's 0.5 point). 🔴 NOT harmless if seen and NOT shipped: the shipped starter is the DENSE-at-floor baseline, so this recipe is the answer. It must never enter the image and must never be placed in tests/ (tests/ is uploaded INTO the scored container, where the solver's own training code runs). A REAL strong single-card MoE recipe, never a degraded path.",
3
+ "recipe": {
4
+ "model": "single-card MoE-GPT: n_layer=8 n_head=8 n_embd=512 vocab=8192 block=512; per-layer MoE FFN with n_experts=16, top_k=2, ffn_mult=4 (expert hidden=2048). Total params well above the capacity floor; ACTIVE params (top_k=2 experts) keep FLOPs/token low.",
5
+ "moe_dispatch": "sorted token dispatch + per-expert capacity buffer + batched (grouped) GEMM via torch.bmm over [n_experts, capacity, d] — each expert computes only its routed tokens (real single-card sparsity->throughput).",
6
+ "load_balancing": "Switch-style auxiliary loss (E * sum_i f_i * P_i) with coef 0.01 + router z-loss coef 1e-3, added to CE at TRAIN time only (the verifier's forward-loss is pure CE).",
7
+ "capacity_factor": 1.25,
8
+ "effective_batch": "micro_batch=16 x grad_accum=2 = 32 sequences x 512 tokens (~16k tok/step)",
9
+ "precision": "bf16 autocast",
10
+ "optimizer": "fused AdamW lr=3e-3 wd=0.1 betas=(0.9,0.95) grad_clip=1.0",
11
+ "schedule": "5% warmup then cosine to 0.1x, time-bounded (stops at 0.94*wallclock; the harness timer is the hard cap)",
12
+ "checkpointing_io": "atomic periodic save every 20s so a timer-kill leaves a valid checkpoint"
13
+ },
14
+ "calibration": {
15
+ "status": "CALIBRATED (frozen in tests/verifier-correctness-manifest.json -> reward_model)",
16
+ "protocol": ">=5 runs of BOTH the shipped dense starter (=> baseline_bpb) and this oracle (=> oracle_bpb_median) on an NVIDIA H20 through the shipped harness at the frozen wallclock budget; ref_speedup = median(baseline)/median(oracle); the bench reward spec requires ref_speedup >= 1.15.",
17
+ "baseline_bpb": 1.9550684328299388,
18
+ "oracle_bpb_median": 1.2747002931075853,
19
+ "ref_speedup": 1.533747535323529,
20
+ "hardware": "NVIDIA H20; see reward_model.hardware_and_data_caveat in the frozen manifest before scoring on other hardware"
21
+ },
22
+ "gradient_probe": {
23
+ "naive_negative": "solution/naive: SAME MoE model (clears the floor + anti-spoof) but a NAIVE per-expert loop that runs every expert on every token (DENSE FLOPs) + no load-balancing loss -> far fewer steps in the budget + router collapse -> higher val_bpb -> reward < 1.0.",
24
+ "expected": "naive_val_bpb > strong_baseline_bpb (reward<1) ; a stronger candidate (better grouped-GEMM/dispatch, tuned top_k/capacity/aux, bigger effective batch from the throughput headroom) < strong_baseline_bpb (reward>1). MEASURED before shipping."
25
+ },
26
+ "role": "oracle (ref_speedup denominator)"
27
+ }
tasks/e2e/a3-moe-train-budget/task/solution/oracle_grouped_moe/run_training.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR,
4
+ # WALLCLOCK_SEC, OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ # It MUST write a checkpoint to $OUT_CKPT within the budget and leave a
6
+ # load_model_for_verification(checkpoint_path, device) importable from
7
+ # /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
8
+ # (the grader re-counts it). This starting version runs the strong single-card
9
+ # MoE recipe; change anything you like (nanoGPT under /app/repo is fully editable).
10
+ set -e
11
+ cd /app/submission
12
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/solution/oracle_grouped_moe/train_gpt.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # e2e-a3-moe-train-budget : REVIEWER-ONLY ORACLE (the ref_speedup numerator's denominator).
2
+ #
3
+ # 🔴 NOT SHIPPED. This file is the answer: a real single-card sparse Mixture-of-Experts recipe
4
+ # (sorted grouped-GEMM token dispatch + a Switch-style load-balancing auxiliary loss + a tuned
5
+ # top-k / n_experts / capacity frontier) that clears the total-parameter FLOOR and converts the
6
+ # sparsity into real throughput, so it fits far more optimizer steps into the fixed wall-clock
7
+ # budget than the dense starter and reaches a much lower held-out val_bpb.
8
+ #
9
+ # It defines the reward's 0.5 point: ref_speedup = baseline_bpb / oracle_val_bpb, a FROZEN
10
+ # constant calibrated on NVIDIA H20 and carried in the frozen manifest. The oracle is never present
11
+ # in the task image and is never executed at scoring time — only the constant is read.
12
+ #
13
+ # The SHIPPED starting point is the dense-at-floor recipe in environment/submission/, which is
14
+ # what `baseline_bpb` is calibrated against.
15
+ #
16
+ # VERIFIER CONTRACT (enforced): model(x) -> float logits (B,T,V), position-dependent;
17
+ # model(x,y) -> scalar loss == CE(logits.view(-1,V), y.view(-1)), i.e. the PURE cross-entropy of
18
+ # those logits — the MoE auxiliary loss is a TRAINING-time side channel and must NOT be folded
19
+ # into the forward-loss. An OOD probe enforces loss(real) < 0.7 * loss(arbitrary ids), and the
20
+ # model must clear the total-parameter floor.
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ import os
25
+ import sys
26
+ import time
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+ # nanoGPT (the baked, editable system) lives at /app/repo. We reuse its attention
35
+ # + LayerNorm + config so the repo is load-bearing (you may edit those too).
36
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
37
+ if REPO not in sys.path:
38
+ sys.path.insert(0, REPO)
39
+ from model import CausalSelfAttention, LayerNorm, GPTConfig # noqa: E402 (from /app/repo/model.py)
40
+
41
+
42
+ # ---- Hyperparameters (starting point; nothing here is required by scoring) ----
43
+ class Hyperparameters:
44
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
45
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
46
+ seed = int(os.environ.get("SEED", "1337"))
47
+ out_ckpt = os.environ.get("OUT_CKPT", "/app/submission/model_ckpt.pt")
48
+ wallclock_sec = float(os.environ.get("WALLCLOCK_SEC", "600"))
49
+
50
+ vocab_size = 8192
51
+ train_seq_len = 512 # verifier reads this as seq_len
52
+ block_size = 512
53
+ val_batch_size = 32_768 # verifier eval batch (tokens)
54
+
55
+ # MoE model: many small experts, few active per token -> P_floor total
56
+ # capacity at ACTIVE-param compute cost. These sizes put total params well
57
+ # above the floor while keeping active params (hence FLOPs/token) small.
58
+ n_layer = 8
59
+ n_head = 8
60
+ n_embd = 512
61
+ dropout = 0.0
62
+ bias = False
63
+ # --- MoE FFN config (the lever) ---
64
+ n_experts = 16 # experts per MoE FFN
65
+ top_k = 2 # experts active per token
66
+ ffn_mult = 4 # expert hidden = ffn_mult * n_embd
67
+ capacity_factor = 1.25 # per-expert buffer = capacity_factor * top_k * tokens / n_experts
68
+ aux_loss_coef = 0.01 # load-balancing auxiliary loss weight (Switch-style)
69
+ router_z_coef = 1e-3 # router z-loss (keeps logits from blowing up)
70
+
71
+ # training recipe
72
+ micro_batch = 16 # sequences per forward
73
+ grad_accum = 2 # effective batch = micro_batch * grad_accum
74
+ learning_rate = 3e-3
75
+ weight_decay = 0.1
76
+ beta1, beta2 = 0.9, 0.95
77
+ grad_clip = 1.0
78
+ warmup_frac = 0.05
79
+ min_lr_frac = 0.1
80
+ save_every_sec = 20.0 # periodic checkpoint so a timer-kill keeps the latest
81
+
82
+
83
+ # ============================ the single-card MoE ============================
84
+ class MoEMLP(nn.Module):
85
+ """A single-card top-k Mixture-of-Experts feed-forward layer.
86
+
87
+ STRONG-BASELINE dispatch: sort the (token, expert) assignments by expert, drop
88
+ per-expert overflow beyond `capacity`, and compute all experts as a BATCHED
89
+ matmul (torch.bmm over [n_experts, capacity, d]) so each expert only touches
90
+ its routed tokens. This realizes the MoE sparsity as real single-card
91
+ throughput (grouped-GEMM style). The load-balancing aux loss + router z-loss
92
+ are exposed via `self.last_aux` / `self.last_z` for the training loop to add;
93
+ they are NOT part of the forward output (the verifier checks pure CE).
94
+ """
95
+
96
+ def __init__(self, cfg: "Hyperparameters"):
97
+ super().__init__()
98
+ self.d = cfg.n_embd
99
+ self.hdim = cfg.ffn_mult * cfg.n_embd
100
+ self.E = cfg.n_experts
101
+ self.top_k = cfg.top_k
102
+ self.capacity_factor = cfg.capacity_factor
103
+ self.router = nn.Linear(self.d, self.E, bias=False)
104
+ # expert weights as batched parameters [E, in, out]
105
+ self.w1 = nn.Parameter(torch.empty(self.E, self.d, self.hdim))
106
+ self.w2 = nn.Parameter(torch.empty(self.E, self.hdim, self.d))
107
+ nn.init.normal_(self.w1, mean=0.0, std=0.02)
108
+ nn.init.normal_(self.w2, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer))
109
+ self.last_aux = torch.zeros(())
110
+ self.last_z = torch.zeros(())
111
+
112
+ def forward(self, x):
113
+ # x: [B, T, d]
114
+ B, T, d = x.shape
115
+ N = B * T
116
+ xf = x.reshape(N, d)
117
+ logits = self.router(xf) # [N, E]
118
+ probs = F.softmax(logits.float(), dim=-1).to(xf.dtype) # [N, E]
119
+
120
+ # load-balancing aux (Switch): f_i = fraction of tokens whose TOP-1 is i;
121
+ # P_i = mean router prob to i; aux = E * sum_i f_i * P_i.
122
+ if self.training:
123
+ top1 = probs.argmax(dim=-1)
124
+ f = torch.zeros(self.E, device=x.device, dtype=probs.dtype)
125
+ f.scatter_add_(0, top1, torch.ones_like(top1, dtype=probs.dtype))
126
+ f = f / max(N, 1)
127
+ P = probs.mean(dim=0)
128
+ self.last_aux = self.E * torch.sum(f * P)
129
+ self.last_z = torch.mean(torch.logsumexp(logits.float(), dim=-1) ** 2)
130
+ else:
131
+ self.last_aux = torch.zeros((), device=x.device)
132
+ self.last_z = torch.zeros((), device=x.device)
133
+
134
+ topv, topi = probs.topk(self.top_k, dim=-1) # [N, k]
135
+ topv = topv / (topv.sum(dim=-1, keepdim=True) + 1e-9)
136
+
137
+ capacity = max(1, int(self.capacity_factor * self.top_k * N / self.E))
138
+ flat_e = topi.reshape(-1) # [N*k]
139
+ flat_g = topv.reshape(-1) # [N*k]
140
+ flat_src = torch.arange(N, device=x.device).repeat_interleave(self.top_k) # token id
141
+
142
+ # sort assignments by expert -> contiguous per-expert groups
143
+ sort_e, order = torch.sort(flat_e)
144
+ src_sorted = flat_src[order]
145
+ g_sorted = flat_g[order]
146
+ counts = torch.bincount(flat_e, minlength=self.E) # [E]
147
+ starts = torch.cumsum(counts, 0) - counts # start index per expert
148
+ pos_within = torch.arange(flat_e.numel(), device=x.device) - starts[sort_e]
149
+ keep = pos_within < capacity # drop per-expert overflow
150
+
151
+ e_sel = sort_e[keep]
152
+ slot_sel = pos_within[keep]
153
+ tok_sel = src_sorted[keep]
154
+ g_sel = g_sorted[keep]
155
+
156
+ # scatter kept tokens into a padded [E, capacity, d] dispatch buffer
157
+ disp = xf.new_zeros(self.E, capacity, d)
158
+ disp[e_sel, slot_sel] = xf[tok_sel]
159
+
160
+ # batched expert compute (grouped GEMM): [E,C,d] @ [E,d,h] -> gelu -> @ [E,h,d]
161
+ hpre = torch.bmm(disp, self.w1)
162
+ hact = F.gelu(hpre)
163
+ out = torch.bmm(hact, self.w2) # [E, C, d]
164
+
165
+ # combine back to tokens, weighted by the (renormalized) gate
166
+ y = xf.new_zeros(N, d)
167
+ contrib = out[e_sel, slot_sel] * g_sel.unsqueeze(-1)
168
+ y.index_add_(0, tok_sel, contrib)
169
+ return y.reshape(B, T, d)
170
+
171
+
172
+ class MoEBlock(nn.Module):
173
+ def __init__(self, cfg: "Hyperparameters", gptcfg: GPTConfig):
174
+ super().__init__()
175
+ self.ln_1 = LayerNorm(cfg.n_embd, bias=cfg.bias)
176
+ self.attn = CausalSelfAttention(gptcfg) # nanoGPT attention (repo is load-bearing)
177
+ self.ln_2 = LayerNorm(cfg.n_embd, bias=cfg.bias)
178
+ self.moe = MoEMLP(cfg)
179
+
180
+ def forward(self, x):
181
+ x = x + self.attn(self.ln_1(x))
182
+ x = x + self.moe(self.ln_2(x))
183
+ return x
184
+
185
+
186
+ class MoEGPT(nn.Module):
187
+ def __init__(self, cfg: "Hyperparameters"):
188
+ super().__init__()
189
+ self.cfg = cfg
190
+ gptcfg = GPTConfig(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
191
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
192
+ dropout=cfg.dropout, bias=cfg.bias)
193
+ self.gptcfg = gptcfg
194
+ self.wte = nn.Embedding(cfg.vocab_size, cfg.n_embd)
195
+ self.wpe = nn.Embedding(cfg.block_size, cfg.n_embd)
196
+ self.drop = nn.Dropout(cfg.dropout)
197
+ self.h = nn.ModuleList([MoEBlock(cfg, gptcfg) for _ in range(cfg.n_layer)])
198
+ self.ln_f = LayerNorm(cfg.n_embd, bias=cfg.bias)
199
+ self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)
200
+ self.wte.weight = self.lm_head.weight # weight tying (nanoGPT)
201
+ self.apply(self._init)
202
+
203
+ def _init(self, m):
204
+ if isinstance(m, nn.Linear):
205
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
206
+ if m.bias is not None:
207
+ nn.init.zeros_(m.bias)
208
+ elif isinstance(m, nn.Embedding):
209
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
210
+
211
+ def aux_losses(self):
212
+ aux = torch.zeros((), device=self.lm_head.weight.device)
213
+ z = torch.zeros((), device=self.lm_head.weight.device)
214
+ for blk in self.h:
215
+ aux = aux + blk.moe.last_aux
216
+ z = z + blk.moe.last_z
217
+ n = max(len(self.h), 1)
218
+ return aux / n, z / n
219
+
220
+ def forward(self, idx, targets=None):
221
+ b, t = idx.size()
222
+ pos = torch.arange(0, t, dtype=torch.long, device=idx.device)
223
+ x = self.drop(self.wte(idx) + self.wpe(pos))
224
+ for blk in self.h:
225
+ x = blk(x)
226
+ x = self.ln_f(x)
227
+ logits = self.lm_head(x)
228
+ if targets is not None:
229
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
230
+ return logits, loss # PURE CE (aux is a side channel via aux_losses())
231
+ return logits, None
232
+
233
+
234
+ # ---- Verifier hook: reconstruct + adapt to the forward(x)/forward(x,y) contract ----
235
+ class _VerifierAdapter(nn.Module):
236
+ def __init__(self, moe: MoEGPT):
237
+ super().__init__()
238
+ self.moe = moe
239
+
240
+ def forward(self, idx, targets=None):
241
+ logits, loss = self.moe(idx, idx if targets is None else targets)
242
+ return logits if targets is None else loss
243
+
244
+
245
+ def _cfg_dict(cfg: "Hyperparameters") -> dict:
246
+ return dict(vocab_size=cfg.vocab_size, block_size=cfg.block_size,
247
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
248
+ dropout=0.0, bias=cfg.bias, n_experts=cfg.n_experts,
249
+ top_k=cfg.top_k, ffn_mult=cfg.ffn_mult,
250
+ capacity_factor=cfg.capacity_factor)
251
+
252
+
253
+ def _cfg_from_dict(d: dict) -> "Hyperparameters":
254
+ c = Hyperparameters()
255
+ for k, v in d.items():
256
+ setattr(c, k, v)
257
+ c.train_seq_len = d.get("block_size", c.block_size)
258
+ return c
259
+
260
+
261
+ def load_model_for_verification(checkpoint_path, device):
262
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
263
+ cfg = _cfg_from_dict(obj.get("config", {}))
264
+ moe = MoEGPT(cfg)
265
+ moe.load_state_dict(obj["model"], strict=True)
266
+ return cfg, _VerifierAdapter(moe).to(device).eval()
267
+
268
+
269
+ def _save(model: MoEGPT, cfg: "Hyperparameters", out_ckpt: str) -> None:
270
+ tmp = out_ckpt + ".tmp"
271
+ torch.save({"model": model.state_dict(), "config": _cfg_dict(cfg)}, tmp)
272
+ os.replace(tmp, out_ckpt) # atomic: a timer-kill never leaves a half-written ckpt
273
+
274
+
275
+ class _MemmapLoader:
276
+ """nanoGPT-style flat uint16 shard loader (frozen train shard bytes)."""
277
+
278
+ def __init__(self, data_path: str, seq_len: int, device: torch.device, seed: int):
279
+ self.data = np.memmap(Path(data_path) / "train.bin", dtype=np.uint16, mode="r")
280
+ self.seq_len = seq_len
281
+ self.device = device
282
+ self.rng = np.random.default_rng(seed)
283
+
284
+ def batch(self, n: int):
285
+ ix = self.rng.integers(0, len(self.data) - self.seq_len - 1, size=n)
286
+ x = torch.from_numpy(np.stack([self.data[i:i + self.seq_len].astype(np.int64) for i in ix]))
287
+ y = torch.from_numpy(np.stack([self.data[i + 1:i + 1 + self.seq_len].astype(np.int64) for i in ix]))
288
+ return (x.pin_memory().to(self.device, non_blocking=True),
289
+ y.pin_memory().to(self.device, non_blocking=True))
290
+
291
+
292
+ def main() -> None:
293
+ args = Hyperparameters()
294
+ torch.manual_seed(args.seed)
295
+ np.random.seed(args.seed)
296
+ torch.backends.cuda.matmul.allow_tf32 = True
297
+ torch.backends.cudnn.allow_tf32 = True
298
+ device = torch.device("cuda", 0)
299
+ torch.cuda.set_device(device)
300
+
301
+ model = MoEGPT(args).to(device)
302
+ n_params = sum(p.numel() for p in model.parameters())
303
+ print(f"[train] MoE {n_params/1e6:.1f}M total params | E={args.n_experts} top_k={args.top_k} "
304
+ f"layers={args.n_layer} d={args.n_embd} | micro={args.micro_batch} accum={args.grad_accum} "
305
+ f"seq={args.train_seq_len}", flush=True)
306
+
307
+ loader = _MemmapLoader(args.data_path, args.train_seq_len, device, args.seed)
308
+ opt = torch.optim.AdamW(model.parameters(), lr=args.learning_rate,
309
+ weight_decay=args.weight_decay, betas=(args.beta1, args.beta2),
310
+ fused=True)
311
+
312
+ start = time.time()
313
+ deadline = start + args.wallclock_sec * 0.94 # soft self-stop; external timer is the hard cap
314
+ est_total_steps = 6000
315
+ warmup = max(1, int(args.warmup_frac * est_total_steps))
316
+ last_save = start
317
+ step = 0
318
+ model.train()
319
+ while time.time() < deadline:
320
+ lr = (args.learning_rate * (step + 1) / warmup if step < warmup
321
+ else args.learning_rate * (args.min_lr_frac + (1 - args.min_lr_frac) *
322
+ 0.5 * (1 + math.cos(math.pi * min(1.0, (step - warmup) / max(1, est_total_steps - warmup))))))
323
+ for g in opt.param_groups:
324
+ g["lr"] = lr
325
+ opt.zero_grad(set_to_none=True)
326
+ for _ in range(args.grad_accum):
327
+ x, y = loader.batch(args.micro_batch)
328
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
329
+ _, ce = model(x, y)
330
+ aux, z = model.aux_losses()
331
+ loss = ce + args.aux_loss_coef * aux + args.router_z_coef * z
332
+ (loss / args.grad_accum).backward()
333
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
334
+ opt.step()
335
+ step += 1
336
+ if step % 25 == 0:
337
+ print(f"[train] step {step} lr {lr:.2e} ce {ce.item():.4f} aux {float(aux):.4f} "
338
+ f"peakGB {torch.cuda.max_memory_allocated()/1e9:.2f} t {time.time()-start:.0f}s", flush=True)
339
+ if time.time() - last_save >= args.save_every_sec:
340
+ _save(model, args, args.out_ckpt)
341
+ last_save = time.time()
342
+ _save(model, args, args.out_ckpt)
343
+ print(f"[train] done: {step} steps in {time.time()-start:.0f}s -> {args.out_ckpt}", flush=True)
344
+
345
+
346
+ if __name__ == "__main__":
347
+ main()
tasks/e2e/a3-moe-train-budget/task/solution/probe_budget_bite/run_training.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; fully editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR, WALLCLOCK_SEC,
4
+ # OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ #
6
+ # It MUST write a checkpoint to $OUT_CKPT within the budget (save periodically — the timer can
7
+ # stop you at any moment) and leave load_model_for_verification(checkpoint_path, device)
8
+ # importable from /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
9
+ # (the grader re-counts it).
10
+ #
11
+ # This starting version runs the provided dense baseline. Change anything you like — nanoGPT
12
+ # under /app/repo is fully editable too.
13
+ set -e
14
+ cd /app/submission
15
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/solution/probe_budget_bite/train_gpt.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # REVIEWER-ONLY BUDGET-BITE PROBE for e2e-a3-moe-train-budget. 🔴 NOT SHIPPED, NOT a solution.
2
+ #
3
+ # A gate that no plausible submission can fail contributes nothing, and a SELF-REPORTED budget is
4
+ # worse than none. This probe exists to prove the wall-clock budget gate actually BITES, by
5
+ # attacking it three ways at once and reporting what the harness did about each:
6
+ #
7
+ # 1. IGNORE THE CAP — it never stops on its own; only the harness timer can end it.
8
+ # 2. OUTLIVE THE CAP — it forks a DETACHED grandchild (new session) that keeps writing the
9
+ # scored checkpoint after the parent is signalled. If the harness only killed the direct
10
+ # child, this would keep training into the eval phase.
11
+ # 3. READ THE HELD-OUT SET — it tries to open /tests/holdout_corpus.txt and the frozen manifest.
12
+ # Under the privilege drop this must fail with EACCES/EPERM; as root it would succeed, which
13
+ # is exactly why the drop exists.
14
+ #
15
+ # It writes a probe report to $OUT_CKPT.probe.json (the harness log carries it), then a REAL
16
+ # (deliberately tiny/awful) checkpoint so the run still reaches the scorer.
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import sys
22
+ import time
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn as nn
28
+
29
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
30
+ if REPO not in sys.path:
31
+ sys.path.insert(0, REPO)
32
+ from model import GPT, GPTConfig # noqa: E402
33
+
34
+
35
+ class Hyperparameters:
36
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
37
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
38
+ seed = int(os.environ.get("SEED", "1337"))
39
+ out_ckpt = os.environ.get("OUT_CKPT", "/app/submission/model_ckpt.pt")
40
+ wallclock_sec = float(os.environ.get("WALLCLOCK_SEC", "600"))
41
+ vocab_size = 8192
42
+ train_seq_len = 512
43
+ block_size = 512
44
+ val_batch_size = 32_768
45
+ n_layer = 12
46
+ n_head = 16
47
+ n_embd = 1024
48
+ dropout = 0.0
49
+ bias = False
50
+
51
+
52
+ class _VerifierAdapter(nn.Module):
53
+ def __init__(self, gpt: GPT):
54
+ super().__init__()
55
+ self.gpt = gpt
56
+
57
+ def forward(self, idx, targets=None):
58
+ logits, loss = self.gpt(idx, idx if targets is None else targets)
59
+ return logits if targets is None else loss
60
+
61
+
62
+ def _cfg(a):
63
+ return GPTConfig(block_size=a.block_size, vocab_size=a.vocab_size, n_layer=a.n_layer,
64
+ n_head=a.n_head, n_embd=a.n_embd, dropout=a.dropout, bias=a.bias)
65
+
66
+
67
+ def load_model_for_verification(checkpoint_path, device):
68
+ a = Hyperparameters()
69
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
70
+ cfg = GPTConfig(**obj["config"]) if obj.get("config") else _cfg(a)
71
+ gpt = GPT(cfg)
72
+ gpt.load_state_dict(obj["model"], strict=True)
73
+ a.train_seq_len, a.vocab_size = cfg.block_size, cfg.vocab_size
74
+ return a, _VerifierAdapter(gpt).to(device).eval()
75
+
76
+
77
+ def _probe_frozen_surface() -> dict:
78
+ """Attempt exactly what the rules forbid, and record the OS's answer."""
79
+ out = {}
80
+ for target in ("/tests/holdout_corpus.txt", "/tests/verifier-correctness-manifest.json",
81
+ "/tests/compute_reward.py", "/tests"):
82
+ try:
83
+ if target == "/tests":
84
+ out[target] = {"listdir": sorted(os.listdir(target))[:8]}
85
+ else:
86
+ with open(target, "rb") as fh:
87
+ head = fh.read(64)
88
+ out[target] = {"READ_SUCCEEDED": True, "first_bytes": head[:32].decode("utf-8", "replace")}
89
+ except Exception as exc:
90
+ out[target] = {"READ_SUCCEEDED": False, "error": f"{type(exc).__name__}: {exc}"}
91
+ return out
92
+
93
+
94
+ def _spawn_detached_writer(out_ckpt: str, cfg_dict: dict, state: dict) -> int:
95
+ """Fork a grandchild in its OWN session that keeps rewriting the scored checkpoint. The
96
+ harness must kill the whole process group, not just the direct child."""
97
+ pid = os.fork()
98
+ if pid != 0:
99
+ return pid
100
+ try:
101
+ os.setsid()
102
+ marker = out_ckpt + ".detached_writes"
103
+ for i in range(4000):
104
+ with open(marker, "a") as fh:
105
+ fh.write(f"{time.time():.3f} detached_write {i}\n")
106
+ try:
107
+ torch.save({"model": state, "config": cfg_dict}, out_ckpt + ".tmp")
108
+ os.replace(out_ckpt + ".tmp", out_ckpt)
109
+ except Exception:
110
+ pass
111
+ time.sleep(2.0)
112
+ except Exception:
113
+ pass
114
+ finally:
115
+ os._exit(0)
116
+
117
+
118
+ def main() -> None:
119
+ a = Hyperparameters()
120
+ torch.manual_seed(a.seed)
121
+ device = torch.device("cuda", 0)
122
+ torch.cuda.set_device(device)
123
+ probe = {"euid": os.geteuid(), "uid": os.getuid(), "pid": os.getpid(),
124
+ "wallclock_sec_env": a.wallclock_sec, "started": time.time()}
125
+ probe["frozen_surface_access"] = _probe_frozen_surface()
126
+ # can it read MORE training data than the harness pointed it at?
127
+ try:
128
+ full = Path("/data/datasets/wikitext_bpe8k/train.bin")
129
+ probe["full_corpus_read"] = {"path": str(full),
130
+ "READ_SUCCEEDED": bool(np.memmap(full, dtype=np.uint16, mode="r").shape[0])}
131
+ except Exception as exc:
132
+ probe["full_corpus_read"] = {"READ_SUCCEEDED": False, "error": f"{type(exc).__name__}: {exc}"}
133
+
134
+ cfg = _cfg(a)
135
+ model = GPT(cfg).to(device)
136
+ cfg_dict = dict(block_size=cfg.block_size, vocab_size=cfg.vocab_size, n_layer=cfg.n_layer,
137
+ n_head=cfg.n_head, n_embd=cfg.n_embd, dropout=0.0, bias=cfg.bias)
138
+ torch.save({"model": model.state_dict(), "config": cfg_dict}, a.out_ckpt + ".tmp")
139
+ os.replace(a.out_ckpt + ".tmp", a.out_ckpt)
140
+ probe["detached_child_pid"] = _spawn_detached_writer(a.out_ckpt, cfg_dict, model.state_dict())
141
+ probe["self_reported_steps"] = 999_999_999 # a lie the harness must not believe
142
+ probe["self_reported_wallclock_used"] = 1.0
143
+ Path(a.out_ckpt + ".probe.json").write_text(json.dumps(probe, indent=2, default=str))
144
+ print("[probe] report:", json.dumps(probe, default=str), flush=True)
145
+ # never stop voluntarily: only the harness timer may end this run
146
+ while True:
147
+ time.sleep(5)
148
+ print(f"[probe] still alive at t={time.time() - probe['started']:.0f}s "
149
+ f"(budget was {a.wallclock_sec}s)", flush=True)
150
+
151
+
152
+ if __name__ == "__main__":
153
+ main()
tasks/e2e/a3-moe-train-budget/task/solution/probe_no_checkpoint/run_training.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; fully editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR, WALLCLOCK_SEC,
4
+ # OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ #
6
+ # It MUST write a checkpoint to $OUT_CKPT within the budget (save periodically — the timer can
7
+ # stop you at any moment) and leave load_model_for_verification(checkpoint_path, device)
8
+ # importable from /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
9
+ # (the grader re-counts it).
10
+ #
11
+ # This starting version runs the provided dense baseline. Change anything you like — nanoGPT
12
+ # under /app/repo is fully editable too.
13
+ set -e
14
+ cd /app/submission
15
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/solution/probe_no_checkpoint/train_gpt.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # REVIEWER-ONLY zeroing witness: a recipe that never writes a checkpoint inside the budget.
2
+ # Must score exactly 0.0 with reason `build_or_entry_contract_failed`. 🔴 NOT SHIPPED.
3
+ import os, sys, time
4
+ def load_model_for_verification(checkpoint_path, device):
5
+ raise RuntimeError("no checkpoint was produced")
6
+ if __name__ == "__main__":
7
+ print("[probe] sleeping past the whole budget without ever saving", flush=True)
8
+ while True:
9
+ time.sleep(10)
tasks/e2e/a3-moe-train-budget/task/solution/probe_tamper_frozen/run_training.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entry contract (solver-owned; fully editable). The harness invokes this under a
3
+ # harness-owned wall-clock timer with these env set: SEED, PARAM_FLOOR, WALLCLOCK_SEC,
4
+ # OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO(=/app/repo).
5
+ #
6
+ # It MUST write a checkpoint to $OUT_CKPT within the budget (save periodically — the timer can
7
+ # stop you at any moment) and leave load_model_for_verification(checkpoint_path, device)
8
+ # importable from /app/submission/train_gpt.py. The model must clear the total-parameter FLOOR
9
+ # (the grader re-counts it).
10
+ #
11
+ # This starting version runs the provided dense baseline. Change anything you like — nanoGPT
12
+ # under /app/repo is fully editable too.
13
+ set -e
14
+ cd /app/submission
15
+ python3 train_gpt.py
tasks/e2e/a3-moe-train-budget/task/solution/probe_tamper_frozen/train_gpt.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # REVIEWER-ONLY TAMPER witness for e2e-a3-moe-train-budget. 🔴 NOT SHIPPED, NOT a solution.
2
+ #
3
+ # Proves the frozen-surface DETECTION path fires with named reasons. It appends one byte to
4
+ # /tests/holdout_corpus.txt and rewrites the calibrated anchor in the frozen manifest during its
5
+ # own training run — exactly the attack the sha256 fingerprint exists to catch.
6
+ #
7
+ # Run it with the manifest's anti_tamper.training_uid set to null (root) so the write SUCCEEDS and
8
+ # the DETECTION path is what gets exercised. With the privilege drop in force the same writes fail
9
+ # with EACCES, which is the PREVENTION proof instead.
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import sys
15
+ import time
16
+ from pathlib import Path
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
22
+ if REPO not in sys.path:
23
+ sys.path.insert(0, REPO)
24
+ from model import GPT, GPTConfig # noqa: E402
25
+
26
+
27
+ class Hyperparameters:
28
+ out_ckpt = os.environ.get("OUT_CKPT", "/app/submission/model_ckpt.pt")
29
+ vocab_size = 8192
30
+ train_seq_len = 512
31
+ block_size = 512
32
+ val_batch_size = 32_768
33
+ n_layer = 12
34
+ n_head = 16
35
+ n_embd = 1024
36
+ dropout = 0.0
37
+ bias = False
38
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
39
+
40
+
41
+ class _VerifierAdapter(nn.Module):
42
+ def __init__(self, gpt: GPT):
43
+ super().__init__()
44
+ self.gpt = gpt
45
+
46
+ def forward(self, idx, targets=None):
47
+ logits, loss = self.gpt(idx, idx if targets is None else targets)
48
+ return logits if targets is None else loss
49
+
50
+
51
+ def _cfg(a):
52
+ return GPTConfig(block_size=a.block_size, vocab_size=a.vocab_size, n_layer=a.n_layer,
53
+ n_head=a.n_head, n_embd=a.n_embd, dropout=a.dropout, bias=a.bias)
54
+
55
+
56
+ def load_model_for_verification(checkpoint_path, device):
57
+ a = Hyperparameters()
58
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
59
+ cfg = GPTConfig(**obj["config"]) if obj.get("config") else _cfg(a)
60
+ gpt = GPT(cfg)
61
+ gpt.load_state_dict(obj["model"], strict=True)
62
+ a.train_seq_len, a.vocab_size = cfg.block_size, cfg.vocab_size
63
+ return a, _VerifierAdapter(gpt).to(device).eval()
64
+
65
+
66
+ def main() -> None:
67
+ a = Hyperparameters()
68
+ report = {"euid": os.geteuid()}
69
+ # 1) mutate the held-out corpus
70
+ try:
71
+ with open("/tests/holdout_corpus.txt", "a") as fh:
72
+ fh.write("\ntampered\n")
73
+ report["holdout_append"] = "SUCCEEDED"
74
+ except Exception as exc:
75
+ report["holdout_append"] = f"FAILED {type(exc).__name__}: {exc}"
76
+ # 2) rewrite the reward's own anchor
77
+ try:
78
+ p = Path("/tests/verifier-correctness-manifest.json")
79
+ d = json.loads(p.read_text())
80
+ d.setdefault("reward_model", {})["baseline_bpb"] = 99.0
81
+ d["reward_model"]["ref_speedup"] = 99.0
82
+ p.write_text(json.dumps(d))
83
+ report["anchor_rewrite"] = "SUCCEEDED"
84
+ except Exception as exc:
85
+ report["anchor_rewrite"] = f"FAILED {type(exc).__name__}: {exc}"
86
+ # 3) chmod the quarantine back open
87
+ try:
88
+ os.chmod("/tests", 0o755)
89
+ report["chmod_tests"] = "SUCCEEDED"
90
+ except Exception as exc:
91
+ report["chmod_tests"] = f"FAILED {type(exc).__name__}: {exc}"
92
+ print("[tamper-probe]", json.dumps(report), flush=True)
93
+ Path(a.out_ckpt + ".tamper.json").write_text(json.dumps(report, indent=2))
94
+
95
+ # produce a real checkpoint so the run reaches the scorer and the reasons can be read
96
+ torch.manual_seed(1337)
97
+ device = torch.device("cuda", 0)
98
+ cfg = _cfg(a)
99
+ model = GPT(cfg).to(device)
100
+ torch.save({"model": model.state_dict(),
101
+ "config": dict(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
102
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
103
+ dropout=0.0, bias=cfg.bias)}, a.out_ckpt)
104
+ print("[tamper-probe] wrote checkpoint; exiting early on purpose", flush=True)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
tasks/e2e/a3-moe-train-budget/task/solution/solve.sh ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # =============================================================================
3
+ # solve.sh -- e2e/a3-moe-train-budget
4
+ # MoE pretraining under a harness-owned wall-clock budget (nanoGPT, H20)
5
+ #
6
+ # ORACLE FORM : DIRECTORY. solution/<variant>/ holds a complete 2-file recipe
7
+ # (run_training.sh + train_gpt.py) that is copied into the submission dir.
8
+ # EDITABLE SURFACE : $SUBMISSION_DIR (default /app/submission)
9
+ # GRADED UNIT : /app/submission/run_training.sh + /app/submission/train_gpt.py
10
+ # (the verifier runs run_training.sh under its own timer and grades the
11
+ # checkpoint it writes to $SUBMISSION_DIR/model_ckpt.pt)
12
+ # PRIMARY METRIC : val_bpb ratio at a fixed wall-clock budget -> min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0
13
+ # MODE VARIABLE : NONE. tests/test.sh has NO mode dispatch: it strips every inherited E2E_*
14
+ # variable and unsets VERIFIER_MODE / KERNELBENCH_VERIFY_MODE, then grades
15
+ # /app/submission and nothing else. So the ONLY way to score a reference is to
16
+ # land it into the submission dir -- which is exactly what this script does.
17
+ # REFERENCE ASSETS : solution/{oracle_grouped_moe,mid_naive_moe,baseline_dense_floor,
18
+ # probe_budget_bite,probe_no_checkpoint,probe_tamper_frozen}/
19
+ # SHA-PINNED PATHS : tests/verifier-correctness-manifest.json:frozen_surface = /tests/{compute_reward.py,
20
+ # test.sh,holdout_corpus.txt,timer.sh,verifier-correctness-manifest.json} +
21
+ # compute_reward_sha256. test.sh sha256s EVERY file in /tests before the training
22
+ # and re-checks after. solve.sh writes ONLY under $SUBMISSION_DIR -- it never
23
+ # touches /tests, so no pin is disturbed.
24
+ #
25
+ # GRADE AFTER LANDING (one command, run from the task/ dir of the package):
26
+ # docker run --rm --gpus all -v "$PWD:/task:ro" -v "$PWD/tests:/tests:ro" \
27
+ # fai/e2e-a3-moe-train-budget:oss bash -lc '
28
+ # bash /task/solution/solve.sh && bash /tests/test.sh'
29
+ # -> /logs/verifier/reward.json
30
+ #
31
+ # CLI: (default)=oracle | --baseline2 | --noop | --variant <name> | --list | --help
32
+ #
33
+ # --noop SEMANTICS : --noop 把可编辑面复位到烤入基线(与 verifier 取基线的方式一致,HEAD 不动),
34
+ # 使对照组能量到真正的 no-op 值。
35
+ # (`--noop` resets the editable surface to the baked baseline -- the same way the verifier
36
+ # materialises its own timing/scoring baseline -- with HEAD untouched, so the control arm
37
+ # measures the REAL no-op value instead of whatever a previous arm left behind.)
38
+ # HOW, here: rm -f $SUB/model_ckpt.pt, then restore run_training.sh + train_gpt.py from
39
+ # the pre-landing snapshot under ${SOLVE_BACKUP_DIR:-/tmp/.fai_solve_baseline}/<task-id>/
40
+ # (here /app/submission is NOT git-tracked -- only /app/repo is).
41
+ #
42
+ # HEAD MUST NOT MOVE. solve.sh only writes files into the editable surface -- no git add,
43
+ # no commit, no branch. The verifier grades the WORK TREE and (where that surface is a git
44
+ # tree) gates on `git status --porcelain`, so a commit turns a correct solution into
45
+ # reward 0 (RUNNABLE_SPEC H3). HEAD is re-read after landing; the script aborts if it moved.
46
+ #
47
+ # NOTE: the harness runs run_training.sh under an unprivileged uid with /tests chmod-000, so the
48
+ # recipe must not depend on anything under /tests. RECIPE_RECORD.json in the oracle dir is
49
+ # documentation only and is deliberately NOT landed (it would add an untracked file to the
50
+ # submission surface for no scoring benefit).
51
+ # =============================================================================
52
+ set -uo pipefail
53
+
54
+ TASK_ID='a3-moe-train-budget'
55
+ SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
56
+ PKG="$(dirname "$SELF")"
57
+ BK="${SOLVE_BACKUP_DIR:-/tmp/.fai_solve_baseline}/${TASK_ID}"
58
+
59
+ say() { printf '[solve:%s] %s\n' "$TASK_ID" "$*"; }
60
+ warn() { printf '[solve:%s] WARN: %s\n' "$TASK_ID" "$*" >&2; }
61
+ die() { printf '[solve:%s] ERROR: %s\n' "$TASK_ID" "$*" >&2; exit 1; }
62
+
63
+ # Reference assets live OUTSIDE the image on purpose. Look for them wherever the
64
+ # operator may have mounted the package; SOLVE_ASSET_DIR overrides everything.
65
+ ASSET_ROOTS=("${SOLVE_ASSET_DIR:-}" "$SELF" "$PKG" "$PKG/tests" "$PKG/solution" \
66
+ /solution /solution/tests /task /task/solution /task/tests /tests /opt/solution)
67
+ asset() { local rel="$1" r
68
+ for r in "${ASSET_ROOTS[@]}"; do [ -n "$r" ] || continue
69
+ [ -e "$r/$rel" ] && { printf '%s\n' "$r/$rel"; return 0; }
70
+ done
71
+ return 1
72
+ }
73
+ need() { asset "$1" || die "reference asset '$1' not found.
74
+ searched: ${ASSET_ROOTS[*]}
75
+ mount the task package (e.g. -v <pkg>:/task:ro) or set SOLVE_ASSET_DIR=<dir>."; }
76
+
77
+ # Pristine snapshot, kept OUTSIDE every graded surface (/tmp), so --noop can undo a
78
+ # landing inside a long-lived container. Taken once, right before the first overwrite.
79
+ _k() { printf '%s' "$1" | tr '/' '_'; }
80
+ snap() { local f="$1" k; k="$(_k "$1")"; mkdir -p "$BK" 2>/dev/null || return 0
81
+ [ -e "$BK/$k" ] || [ -e "$BK/$k.ABSENT" ] || {
82
+ if [ -e "$f" ]; then cp -p "$f" "$BK/$k" 2>/dev/null || true
83
+ else : > "$BK/$k.ABSENT" 2>/dev/null || true; fi; }; }
84
+ unsnap() { local f="$1" k; k="$(_k "$1")"
85
+ if [ -e "$BK/$k" ]; then cp -p "$BK/$k" "$f" && say "restored $f from the pristine snapshot"
86
+ elif [ -e "$BK/$k.ABSENT" ]; then rm -f "$f" && say "removed $f (absent in the pristine image)"
87
+ else return 1; fi; }
88
+
89
+ put() { # put <src> <dst> : idempotent copy, snapshots the pristine <dst> first
90
+ local s="$1" d="$2"
91
+ [ -f "$s" ] || die "missing reference file: $s"
92
+ mkdir -p "$(dirname "$d")" || die "cannot create $(dirname "$d")"
93
+ snap "$d"
94
+ if cmp -s "$s" "$d"; then say "already landed (identical): $d"
95
+ else cp -f "$s" "$d" || die "copy failed: $s -> $d"; say "landed $(basename "$s") -> $d"; fi
96
+ [ -x "$s" ] && { chmod +x "$d" 2>/dev/null || true; }
97
+ return 0
98
+ }
99
+
100
+ head_of() { git -C "$1" rev-parse HEAD 2>/dev/null || echo NO_GIT; }
101
+ assert_head() { # assert_head <dir> <before>
102
+ local now; now="$(head_of "$1")"
103
+ [ "$now" = "$2" ] || die "HEAD of $1 moved ($2 -> $now).
104
+ The verifier grades the WORK TREE and asserts HEAD is still the single baked baseline
105
+ commit (RUNNABLE_SPEC H3) -- a commit makes a correct solution score 0."
106
+ [ "$now" = NO_GIT ] || say "HEAD unchanged: $1 @ $(printf '%.12s' "$now")"
107
+ }
108
+
109
+ MODE=oracle
110
+ while [ $# -gt 0 ]; do
111
+ case "$1" in
112
+ --oracle) MODE=oracle ;;
113
+ --negative) MODE=negative ;;
114
+ --baseline2) MODE=baseline2 ;;
115
+ --noop) MODE=noop ;;
116
+ --variant) shift; [ $# -gt 0 ] || die "--variant needs a name"; MODE="$1" ;;
117
+ --list) MODE=__list ;;
118
+ -h|--help) MODE=__help ;;
119
+ *) die "unknown argument '$1' (try --help)" ;;
120
+ esac
121
+ shift
122
+ done
123
+
124
+ list_variants() {
125
+ printf 'variants for %s:\n' "$TASK_ID"
126
+ printf ' %-26s %s\n' '(default) / --oracle' 'oracle_grouped_moe -- the in-budget ceiling (ref_speedup anchor)'
127
+ printf ' %-26s %s\n' '--baseline2' 'baseline_dense_floor -- the dense 1.0 anchor (scores ~0)'
128
+ printf ' %-26s %s\n' '--variant mid_naive_moe' 'the naive MoE mid-tier arm'
129
+ printf ' %-26s %s\n' '--variant probe_budget_bite' 'probe: does the wall-clock kill really bite?'
130
+ printf ' %-26s %s\n' '--variant probe_no_checkpoint' 'probe: no checkpoint -> entry-contract hard fail'
131
+ printf ' %-26s %s\n' '--variant probe_tamper_frozen' 'probe: touches /tests -> anti_cheat_triggered'
132
+ printf ' %-26s %s\n' '--noop' 'reset to the baked starter recipe -- the TRUE no-op arm'
133
+ }
134
+ if [ "$MODE" = __list ]; then list_variants; exit 0; fi
135
+ if [ "$MODE" = __help ]; then
136
+ sed -n '2,/^set -uo pipefail$/p' "${BASH_SOURCE[0]}" | sed '$d'
137
+ list_variants
138
+ exit 0
139
+ fi
140
+
141
+ SUB="${SUBMISSION_DIR:-/app/submission}"
142
+ GITDIR='NONE'
143
+
144
+ land() { # land <asset-relpath=>dest-name> ...
145
+ local before spec s d
146
+ [ -d "$SUB" ] || mkdir -p "$SUB" || die "cannot create $SUB"
147
+ before="$(head_of "$GITDIR")"
148
+ for spec in "$@"; do
149
+ s="${spec%%=>*}"; d="${spec##*=>}"
150
+ put "$(need "$s")" "$SUB/$d"
151
+ done
152
+ assert_head "$GITDIR" "$before"
153
+ [ "$before" = NO_GIT ] || { say "work-tree state of $GITDIR:"
154
+ git -C "$GITDIR" status --porcelain 2>/dev/null | sed 's/^/ /'; }
155
+ }
156
+
157
+ restore() { # restore <dest-name> ...
158
+ local before f; before="$(head_of "$GITDIR")"
159
+ for f in "$@"; do
160
+ if [ "$before" != NO_GIT ] \
161
+ && git -C "$GITDIR" ls-files --error-unmatch -- "$SUB/$f" >/dev/null 2>&1; then
162
+ git -C "$GITDIR" checkout -- "$SUB/$f" \
163
+ && say "restored $SUB/$f from the baked baseline commit"
164
+ elif ! unsnap "$SUB/$f"; then
165
+ warn "no pristine copy of $SUB/$f is recoverable here -- use a fresh container for a true no-op arm"
166
+ fi
167
+ done
168
+ assert_head "$GITDIR" "$before"
169
+ }
170
+
171
+ case "$MODE" in
172
+ oracle) land 'solution/oracle_grouped_moe/run_training.sh=>run_training.sh' \
173
+ 'solution/oracle_grouped_moe/train_gpt.py=>train_gpt.py' ;;
174
+ baseline2) land 'solution/baseline_dense_floor/run_training.sh=>run_training.sh' \
175
+ 'solution/baseline_dense_floor/train_gpt.py=>train_gpt.py' ;;
176
+ mid_naive_moe|probe_budget_bite|probe_no_checkpoint|probe_tamper_frozen)
177
+ land "solution/$MODE/run_training.sh=>run_training.sh" \
178
+ "solution/$MODE/train_gpt.py=>train_gpt.py" ;;
179
+ noop) rm -f "$SUB/model_ckpt.pt"; restore run_training.sh train_gpt.py ;;
180
+ *) die "no such variant: $MODE (see --list)" ;;
181
+ esac
182
+ say "done. GRADE WITH:"
183
+ say ' bash /tests/test.sh # no mode variable; test.sh strips E2E_*/VERIFIER_MODE itself'
tasks/e2e/a3-moe-train-budget/task/task.toml ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "a3-moe-train-budget"
8
+ bench = "e2e"
9
+ kind = "performance"
10
+ language = "python"
11
+ title = "Train the best Mixture-of-Experts language model you can within a fixed budget"
12
+ ext_id = "e2e-a3-moe-train-budget"
13
+ difficulty = "hard"
14
+ category = "ml_training"
15
+ lane = "e2e_task"
16
+ family = "A_training"
17
+ author = "fai-bench"
18
+ tags = [
19
+ "python",
20
+ "pytorch",
21
+ "nanogpt",
22
+ "mixture-of-experts",
23
+ "moe",
24
+ "language-model",
25
+ "training",
26
+ "expert-routing",
27
+ "grouped-gemm",
28
+ "load-balancing",
29
+ "budget",
30
+ "h20",
31
+ "e2e-optimization",
32
+ ]
33
+ description = "A3 MoE training system. Train the best language model you can on ONE H20 within a harness-owned wall-clock budget, scored on held-out WikiText-103 val_bpb, subject to a HARD total-parameter FLOOR (the grader re-counts your model's parameters). At that capacity a DENSE model is too compute-heavy to train well in the budget; a sparse top-k Mixture-of-Experts trains far more steps at the same total capacity — IF you realize the sparsity as real single-card throughput (efficient sorted/grouped-GEMM token dispatch) with a balanced router (load-balancing aux loss) and a tuned top-k/experts/capacity frontier. The SHIPPED starter is a plain dense model at the floor, and it is the bar: BOUNDED reward in [0,1] where matching the starter scores 0 and matching a strong reference MoE recipe measured at the same budget scores 0.5. Whole nanoGPT repo editable except a small frozen eval surface."
34
+ instruction = "instruction.md"
35
+
36
+ [agent]
37
+ # The solver iterates its recipe locally in its session; scoring runs the budgeted training once
38
+ # (single-shot). 5 h budgets many honest iteration cycles.
39
+ timeout_sec = 18000
40
+
41
+ # Open-source build: `cd task && docker build -f environment/Dockerfile -t fai/e2e-a3-moe-train-budget:oss .`
42
+ # provenance (original internal image, not publicly pullable): <internal registry>/kernelbench/e2e-a3-moe-train-budget:v2-deleak@sha256:7145859f8af6bcd4b561ccb00f1f128e6314d2d1bbc5ae1c092e860f49d63afa
43
+ # 🔁 LOOP16: the shipped image is the loop16 overlay (`crane append` onto the :oss base, purely
44
+ # additive — /opt/loop + /app/instruction.md only, NOTHING under tests/ changed). Build in two steps:
45
+ # docker build -f environment/Dockerfile -t fai/e2e-a3-moe-train-budget:oss .
46
+ # docker build -f environment/loop_overlay/Dockerfile -t fai/e2e-a3-moe-train-budget:oss-loop16 environment/loop_overlay
47
+ # The single-shot form (:oss) is a valid alternative; the graded surface (tests/) is identical in both.
48
+ [environment]
49
+ docker_image = "fai/e2e-a3-moe-train-budget:oss-loop16"
50
+ dockerfile = "environment/loop_overlay/Dockerfile"
51
+ dockerfile_single_shot = "environment/Dockerfile"
52
+ build_timeout_sec = 2400
53
+ cpus = 8
54
+ memory_mb = 32768
55
+ gpus = 1
56
+ # H20 只是**锚点标定用卡**,不是硬性限制。换卡时:
57
+ # 1) 按 tests/verifier-correctness-manifest.json 的 recalibrate_howto 重新标定锚点;
58
+ # 2) 用 --build-arg TORCH_CUDA_ARCH_LIST=<你的算力> 构建镜像(8.0 A100 / 8.9 L40S·4090 / 9.0 H100·H20 / 10.0 B200)。
59
+ gpu_types = ["H20"]
60
+ storage_mb = 30720
61
+ allow_internet = false
62
+
63
+ [verifier]
64
+ entrypoint = "tests/test.sh"
65
+ mode = "shared"
66
+ # test.sh RUNS the solver's training under the harness-owned wall-clock timer (external
67
+ # process-group kill), then evals the checkpoint: re-counts total params for the capacity floor,
68
+ # runs the anti-spoof kit, and computes the held-out bpb. Timeout covers training + eval.
69
+ timeout_sec = 1000
70
+ task_kind = "e2e_optimization"
71
+ submission_root = "/app/submission"
72
+ # The whole /app/repo (nanoGPT) + /app/submission is editable EXCEPT the frozen eval surface.
73
+ forbidden_edit_paths = [
74
+ "tests/compute_reward.py",
75
+ "tests/test.sh",
76
+ "tests/holdout_corpus.txt",
77
+ "tests/timer.sh",
78
+ "tests/verifier-correctness-manifest.json",
79
+ "/tests",
80
+ ]
81
+ result_paths = [
82
+ "/logs/verifier/metrics.json",
83
+ "/logs/verifier/reward.json",
84
+ "/logs/verifier/reward.txt",
85
+ "/logs/verifier/verifier_state.json",
86
+ "/logs/verifier/correctness_results.json",
87
+ "/logs/verifier/benchmark_results.json",
88
+ ]
89
+
90
+ [verifier.frozen]
91
+ note = "v1 声明不出 primary_edit_paths:整个 repo 可编辑,被计分的交付物在 [verifier].submission_root 下;评分面靠 [verifier].forbidden_edit_paths + tests/test.sh 里的 sha256 门冻结。"
92
+
93
+ [primary_metric]
94
+ name = "reward"
95
+ goal = "maximize"
96
+ description = "BOUNDED [0,1] reward.md performance envelope: reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 with speedup = baseline_bpb / candidate_val_bpb, where baseline_bpb is the SHIPPED dense-at-floor starter's calibrated held-out bpb and ref_speedup is a FROZEN authoring-time constant (baseline_bpb / oracle_val_bpb). 0 at or below the starter, 0.5 at the demonstrated in-budget ceiling, 1.0 only at speedup = ref_speedup**2. 0 on any hard-fail (capacity floor / no checkpoint in budget / anti-spoof / frozen-surface tamper). NOTE: `speedup` is a QUALITY ratio (bits-per-byte at a fixed wall-clock training budget), not a wall-clock ratio — nothing in the reward is timed; the wall-clock is the fixed RESOURCE. The scorer never runs the oracle or the baseline: it reads two frozen constants."
97
+ source = "/logs/verifier/metrics.json"
98
+ ref_speedup = 1.533747535323529
99
+ ref_speedup_source = "tests/verifier-correctness-manifest.json"
100
+ calibrated_on = "NVIDIA H20"
101
+
102
+ # loop16: the shipped image bakes /opt/loop; the in-session dev proxy trains the candidate recipe on
103
+ # a SMALL PUBLIC dev shard for a SHORT dev wall-clock (under the uid drop), reloads + self-checks +
104
+ # reports a dev val_bpb on the public val split as a COARSE best-of-k ranking signal (NO held-out
105
+ # corpus, NO calibrated anchor baked). At most 16 submissions, at least 1; the model decides when to
106
+ # stop (min=1 so --finalize works any time). The graded score is the runner's fresh end-of-session
107
+ # tests/ grade at the FULL wall-clock budget over the hidden split with the calibrated anchor.
108
+ [loop]
109
+ min_submissions = 1
110
+ max_submissions = 16
111
+ submit = "bash /opt/loop/submit.sh"
tasks/e2e/a3-moe-train-budget/task/tests/compute_reward.py ADDED
@@ -0,0 +1,762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """e2e-a3-moe-train-budget verifier (FROZEN eval surface).
2
+
3
+ REWARD MODEL (the bench reward spec — performance class, BOUNDED log form):
4
+
5
+ speedup = baseline_bpb / candidate_val_bpb # quality ratio at a FIXED budget
6
+ ref_speedup = baseline_bpb / oracle_val_bpb # FROZEN authoring constant
7
+ reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 in [0, 1]
8
+
9
+ `baseline_bpb` and `ref_speedup` are **frozen constants** carried in the frozen manifest
10
+ (`reward_model` block) and calibrated at authoring time on NVIDIA H20. This scorer NEVER runs
11
+ the oracle and NEVER runs the baseline: it reads the two constants and measures only the
12
+ candidate. There is no oracle/reference recipe anywhere in the task image.
13
+
14
+ Semantics: `speedup == ref_speedup => 0.0 (must EXCEED it to score) ; `speedup >= ref_speedup**2` => capped 1.0 ;
15
+ `speedup <= 1` (did not beat the baseline recipe it started from) => 0 via pre-gate 5.
16
+ Matching the *baseline* therefore scores **0**, not 1.0 — the old open-ended
17
+ "matching the baseline scores 1.0, no upper cap" reading is retired.
18
+
19
+ The metric is a *quality* metric at a fixed training budget, not a latency measurement:
20
+ no wall-clock timing enters the reward (`timing_measured: false`). `"speedup"` is kept as
21
+ the field name for schema compatibility with the rest of the bench and is described by the
22
+ companion fields `metric_kind` / `metric_name` / `metric_direction`.
23
+
24
+ EVAL-ONLY. `test.sh` has already run the solver's training under the harness-owned
25
+ wall-clock timer (external process-group kill — never a cooperative in-loop timer, never a
26
+ self-reported step/token count) and produced a checkpoint. This script:
27
+ 1. loads that checkpoint via the solver's `load_model_for_verification(path, device)`
28
+ hook in an isolated process (never re-trains, never trusts a self-reported number);
29
+ 2. RE-COUNTS the model's TOTAL parameters and enforces the hard capacity FLOOR
30
+ (P_total >= param_floor) — the MoE-forcing constraint, re-measured by the harness
31
+ from the loaded module;
32
+ 3. runs the parameter-golf anti-spoof kit (forward(x)/forward(x,y) CE agreement,
33
+ position-variance floor, OOD real-vs-arbitrary);
34
+ 4. computes a stabilized median-of-3-shifts val_bpb on the HIDDEN WikiText-103 TEST
35
+ split (`/tests/holdout_corpus.txt`, uploaded fresh at scoring — NOT baked);
36
+ 5. applies the six reward.md performance pre-gates with NAMED reasons and emits the
37
+ bounded reward plus the 5-file `/logs/verifier` contract.
38
+ """
39
+ from __future__ import annotations
40
+
41
+ import argparse
42
+ import importlib.util
43
+ import inspect
44
+ import json
45
+ import math
46
+ import os
47
+ import statistics
48
+ import sys
49
+ from pathlib import Path
50
+ from typing import Any
51
+
52
+ SUBMISSION_DIR = Path(os.environ.get("SUBMISSION_DIR", "/app/submission"))
53
+ CKPT_PATH = Path(os.environ.get("OUT_CKPT", str(SUBMISSION_DIR / "model_ckpt.pt")))
54
+
55
+ # The frozen surface lives at /tests ONLY. There is deliberately NO /opt/verifier fallback:
56
+ # a baked fallback copy is (a) a stale-scoring hazard and (b) an in-image leak of the
57
+ # held-out corpus and the calibrated constants.
58
+ FROZEN_DIR = Path("/tests")
59
+ MANIFEST_PATH = FROZEN_DIR / "verifier-correctness-manifest.json"
60
+ HOLDOUT_CORPUS_PATH = FROZEN_DIR / "holdout_corpus.txt"
61
+ DEFAULT_TOKENIZER_PATH = Path("/data/tokenizers/wikitext_bpe8k.model")
62
+ DEFAULT_SEQ_LEN = 512
63
+ DEFAULT_VAL_BATCH_TOKENS = 32_768
64
+
65
+ VERIFIER_DIR = Path("/logs/verifier")
66
+ # The verifier output contract ("5-file contract" — 6 files in the corrected bench-wide form,
67
+ # identical to the embed-compress-golf sibling). Emitted on EVERY exit path, hard fails and
68
+ # crashes included.
69
+ RESULT_FILES = (
70
+ "reward.txt",
71
+ "reward.json",
72
+ "metrics.json",
73
+ "verifier_state.json",
74
+ "correctness_results.json",
75
+ "benchmark_results.json",
76
+ )
77
+
78
+ # ---- named hard-fail reasons (reward.md performance pre-gates 1..6) ----
79
+ # Vocabulary shared with the embed-compress-golf / quant-golf siblings so downstream audits
80
+ # can group reasons across the bench.
81
+ R_BUILD = "build_or_entry_contract_failed" # gate 1
82
+ R_CORRECT = "correctness_failed" # gate 2
83
+ R_CHEAT = "anti_cheat_triggered" # gate 3
84
+ R_FORBIDDEN = "forbidden_edit_path" # gate 4
85
+ R_NO_GAIN = "speedup_not_above_baseline" # gate 5 (speedup <= 1)
86
+ R_BAD_REF = "ref_speedup_invalid_or_missing" # gate 6 (ref_speedup <= 1 / missing)
87
+ R_CRASH = "verifier_crashed"
88
+ R_UNNAMED = "zero_without_named_reason" # backstop: reward 0 must always be explained
89
+ R_INCOMPLETE = "gate_suite_incomplete" # a truncated suite can never pass
90
+
91
+ REF_SPEEDUP_AUTHORING_FLOOR = 1.15 # reward.md authoring legality floor
92
+
93
+ # A truncated check suite (early return after a missing checkpoint / an unloadable model /
94
+ # a probe exception) yields FEWER checks than this and can never score above 0.
95
+ # 1 import+reload, 2 real-LM param floor, 3 A3 capacity floor, 4 CE agreement,
96
+ # 5 plausibility band, 6 OOD real-vs-arbitrary
97
+ EXPECTED_TOTAL_CHECKS = 6
98
+
99
+
100
+ # -----------------------------------------------------------------------------
101
+ # frozen manifest (constants only — never an oracle run)
102
+ # -----------------------------------------------------------------------------
103
+ def load_manifest() -> tuple[dict[str, Any], list[str]]:
104
+ problems: list[str] = []
105
+ if not MANIFEST_PATH.exists():
106
+ problems.append(f"frozen manifest missing at {MANIFEST_PATH}")
107
+ return {}, problems
108
+ try:
109
+ return json.loads(MANIFEST_PATH.read_text(encoding="utf-8")), problems
110
+ except Exception as exc:
111
+ problems.append(f"frozen manifest unreadable: {type(exc).__name__}: {exc}")
112
+ return {}, problems
113
+
114
+
115
+ _MAN, _MAN_PROBLEMS = load_manifest()
116
+ _RM: dict[str, Any] = _MAN.get("reward_model") or {}
117
+ _QG: dict[str, Any] = _MAN.get("quality_gate") or {}
118
+
119
+ # FROZEN reward constants. `None` => fail closed with a named reason; never defaulted to a
120
+ # guess, never recomputed by running a reference recipe.
121
+ BASELINE_BPB = _RM.get("baseline_bpb")
122
+ REF_SPEEDUP = _RM.get("ref_speedup")
123
+ BASELINE_CV = _RM.get("baseline_cv")
124
+
125
+ PARAM_FLOOR = int(_QG.get("param_floor", _MAN.get("param_floor", 150_000_000)))
126
+ MIN_PARAM_COUNT = int(_QG.get("min_param_count", 1_000_000))
127
+ MIN_PLAUSIBLE_VAL_BPB = float(_QG.get("min_plausible_val_bpb", 0.90))
128
+ MAX_PLAUSIBLE_VAL_BPB = float(_QG.get("max_plausible_val_bpb", 3.0))
129
+ OOD_LOSS_RATIO = float(_QG.get("ood_loss_ratio", 0.7))
130
+ LOGITS_POSITION_VARIANCE_FLOOR = float(_QG.get("logits_position_variance_floor", 1e-4))
131
+ LOGITS_LOSS_AGREEMENT_TOL = float(_QG.get("logits_loss_agreement_tol", 5e-2))
132
+
133
+
134
+ class Check:
135
+ def __init__(self, name, passed, message, details=None, gate=R_CORRECT):
136
+ self.name, self.passed, self.message = name, passed, message
137
+ self.details = details or {}
138
+ self.gate = gate
139
+
140
+
141
+ def result(name, passed, message, gate=R_CORRECT, **details):
142
+ return Check(name, passed, message, details, gate)
143
+
144
+
145
+ # -----------------------------------------------------------------------------
146
+ # 5-file emitter (single writer, so hard-fail and success paths cannot diverge)
147
+ # -----------------------------------------------------------------------------
148
+ def emit(reward: float,
149
+ hard_fail_reasons: list[str],
150
+ checks: list[Check] | None = None,
151
+ speedup: float | None = None,
152
+ val_bpb: float | None = None,
153
+ bpb_passes: list[float] | None = None,
154
+ extra: dict[str, Any] | None = None) -> None:
155
+ checks = checks or []
156
+ reward = float(reward)
157
+ if not math.isfinite(reward):
158
+ reward = 0.0
159
+ hard_fail_reasons = list(hard_fail_reasons) + [R_UNNAMED]
160
+ reward = min(1.0, max(0.0, reward)) # reward MUST stay in [0, 1]
161
+ reasons = [r for i, r in enumerate(hard_fail_reasons) if r not in hard_fail_reasons[:i]]
162
+ if reward == 0.0 and not reasons:
163
+ reasons = [R_UNNAMED] # never a silent zero
164
+ if reasons:
165
+ reward = 0.0
166
+
167
+ npass = sum(1 for c in checks if c.passed)
168
+ total = len(checks)
169
+ cand_cv = None
170
+ if bpb_passes and len(bpb_passes) >= 2:
171
+ m = statistics.fmean(bpb_passes)
172
+ if m > 0:
173
+ cand_cv = statistics.pstdev(bpb_passes) / m
174
+
175
+ reward_json = {
176
+ "task_type": "performance",
177
+ "reward": reward,
178
+ "hard_fail_reasons": reasons,
179
+ "speedup": speedup,
180
+ "ref_speedup": REF_SPEEDUP,
181
+ "cv": {"baseline": BASELINE_CV, "candidate": cand_cv},
182
+ # descriptive companions: this is a QUALITY ratio at a fixed training budget, and
183
+ # no wall-clock timing enters the reward. "speedup" is retained for schema
184
+ # compatibility with the rest of the bench.
185
+ "metric_kind": "quality_at_fixed_budget",
186
+ "metric_name": "val_bpb",
187
+ "metric_direction": "lower_is_better",
188
+ "timing_measured": False,
189
+ }
190
+ correctness = {
191
+ "passed": npass,
192
+ "total": total,
193
+ "expected_total": EXPECTED_TOTAL_CHECKS,
194
+ "all_passed": total == EXPECTED_TOTAL_CHECKS and npass == total,
195
+ "hard_fail_reasons": reasons,
196
+ "checks": [{"name": c.name, "passed": c.passed, "message": c.message,
197
+ "gate": c.gate, "details": c.details} for c in checks],
198
+ }
199
+ benchmark = {
200
+ "metric_kind": "quality_at_fixed_budget",
201
+ "metric_name": "val_bpb",
202
+ "metric_direction": "lower_is_better",
203
+ "timing_measured": False,
204
+ "candidate_val_bpb": val_bpb,
205
+ "candidate_val_bpb_shift_passes": bpb_passes,
206
+ "baseline_bpb_frozen": BASELINE_BPB,
207
+ "oracle_bpb_frozen": (
208
+ None if (not isinstance(BASELINE_BPB, (int, float)) or not isinstance(REF_SPEEDUP, (int, float))
209
+ or not REF_SPEEDUP) else float(BASELINE_BPB) / float(REF_SPEEDUP)),
210
+ "ref_speedup_frozen": REF_SPEEDUP,
211
+ "speedup": speedup,
212
+ "oracle_executed_by_scorer": False,
213
+ "baseline_executed_by_scorer": False,
214
+ }
215
+ metrics = {
216
+ "reward": reward,
217
+ "task_type": "performance",
218
+ "reward_formula": "min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0",
219
+ "reward_spec": "the bench reward spec (performance class, bounded log form)",
220
+ "reward_form": (
221
+ "reward.md 性能类: min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 in [0,1]; "
222
+ "speedup = baseline_bpb / candidate_val_bpb at a FIXED wall-clock training budget; "
223
+ "ref_speedup is a FROZEN authoring-time constant (baseline_bpb / oracle_val_bpb) and the "
224
+ "oracle is NEVER run at scoring. 0 at or below the baseline recipe, 0.5 at the "
225
+ "demonstrated in-budget ceiling, 1.0 only at speedup = ref_speedup**2."),
226
+ "speedup_semantics": (
227
+ "the `speedup` field carries baseline_bpb / candidate_val_bpb at a FIXED wall-clock "
228
+ "training budget -- a QUALITY ratio (bits-per-byte, lower is better), not a wall-clock "
229
+ "ratio. Nothing in the reward is timed; there is no baseline_ms. reward.md's bounded log "
230
+ "form is applied to that ratio (it is ratio-agnostic; only the variable's name says "
231
+ "latency)."),
232
+ "hard_fail_reasons": reasons,
233
+ "speedup": speedup,
234
+ "ref_speedup": REF_SPEEDUP,
235
+ "baseline_bpb": BASELINE_BPB,
236
+ "candidate_val_bpb": val_bpb,
237
+ "param_floor": PARAM_FLOOR,
238
+ "passed": npass,
239
+ "total": total,
240
+ "tests": {"passed": npass, "total": total},
241
+ "tests_expected_total": EXPECTED_TOTAL_CHECKS,
242
+ "pass_rate": (npass / total if total else 0.0),
243
+ "cv": reward_json["cv"],
244
+ "metric_kind": "quality_at_fixed_budget",
245
+ "metric_name": "val_bpb",
246
+ "metric_direction": "lower_is_better",
247
+ "timing_measured": False,
248
+ "checks": correctness["checks"],
249
+ "failed_checks": [c for c in correctness["checks"] if not c["passed"]],
250
+ }
251
+ verifier_state = {
252
+ "task_id": "e2e-a3-moe-train-budget",
253
+ "task_type": "performance",
254
+ "reward": reward,
255
+ "hard_fail_reasons": reasons,
256
+ "speedup": speedup,
257
+ "ref_speedup": REF_SPEEDUP,
258
+ "baseline_bpb": BASELINE_BPB,
259
+ "candidate_val_bpb": val_bpb,
260
+ "passed": npass,
261
+ "total": total,
262
+ "expected_total": EXPECTED_TOTAL_CHECKS,
263
+ }
264
+ if extra:
265
+ metrics.update(extra)
266
+ verifier_state["detail"] = {k: v for k, v in extra.items()}
267
+
268
+ VERIFIER_DIR.mkdir(parents=True, exist_ok=True)
269
+ payloads = {
270
+ "reward.txt": f"{reward:.6f}\n",
271
+ "reward.json": json.dumps(reward_json, indent=2, sort_keys=True, default=str) + "\n",
272
+ "metrics.json": json.dumps(metrics, indent=2, sort_keys=True, default=str) + "\n",
273
+ "verifier_state.json": json.dumps(verifier_state, indent=2, sort_keys=True, default=str) + "\n",
274
+ "correctness_results.json": json.dumps(correctness, indent=2, sort_keys=True, default=str) + "\n",
275
+ "benchmark_results.json": json.dumps(benchmark, indent=2, sort_keys=True, default=str) + "\n",
276
+ }
277
+ for name in RESULT_FILES:
278
+ try:
279
+ (VERIFIER_DIR / name).write_text(payloads[name], encoding="utf-8")
280
+ except Exception:
281
+ pass
282
+ for c in checks:
283
+ print(f"[{'PASS' if c.passed else 'FAIL'}] {c.name}: {c.message}")
284
+ print(f"REWARD={reward:.6f} speedup={speedup} ref_speedup={REF_SPEEDUP} "
285
+ f"baseline_bpb={BASELINE_BPB} val_bpb={val_bpb} hard_fail_reasons={reasons}")
286
+
287
+
288
+ # -----------------------------------------------------------------------------
289
+ # anti-tamper: the frozen-surface state test.sh recorded around the training run
290
+ # -----------------------------------------------------------------------------
291
+ def frozen_surface_verdict() -> tuple[list[str], dict[str, Any]]:
292
+ """Read the before/after frozen-surface fingerprint test.sh recorded around the
293
+ solver's training run. Any change to a frozen file (verifier, timer, manifest,
294
+ held-out corpus) is gate 3 + gate 4. A missing record is itself gate 3: the scored
295
+ path always produces one."""
296
+ reasons: list[str] = []
297
+ info: dict[str, Any] = {}
298
+ p = os.environ.get("E2E_FROZEN_STATE", "")
299
+ if not p or not Path(p).is_file():
300
+ return [R_CHEAT], {"frozen_surface": "state record missing (expected from test.sh)"}
301
+ try:
302
+ st = json.loads(Path(p).read_text(encoding="utf-8"))
303
+ except Exception as exc:
304
+ return [R_CHEAT], {"frozen_surface": f"state record unreadable: {type(exc).__name__}: {exc}"}
305
+ changed = list(st.get("changed") or [])
306
+ mode_changed = list(st.get("mode_changed") or [])
307
+ unexpected = list(st.get("unexpected_files") or [])
308
+ info["frozen_surface"] = {"changed": changed, "mode_changed": mode_changed,
309
+ "unexpected_files": unexpected,
310
+ "files_fingerprinted": st.get("n_files")}
311
+ if changed:
312
+ reasons += [R_CHEAT, R_FORBIDDEN]
313
+ if mode_changed or unexpected:
314
+ reasons += [R_CHEAT]
315
+ obs = os.environ.get("E2E_OBSERVED_TRAIN_UID", "")
316
+ req = os.environ.get("E2E_REQUESTED_TRAIN_UID", "")
317
+ info["training_privileges"] = {
318
+ "requested_uid": req or None,
319
+ "observed_euid": obs or None,
320
+ "dropped": bool(req) and obs == req,
321
+ "note": ("the candidate's training ran under this euid; chmod 0000 on /tests only bites "
322
+ "for a non-root uid, so `dropped: false` means the held-out quarantine was "
323
+ "nominal for that run"),
324
+ }
325
+ if req and obs != req:
326
+ # not a cheat by the candidate, but the run's quarantine was weaker than designed:
327
+ # surface it loudly instead of silently scoring as if it had held.
328
+ info["training_privileges"]["WARNING"] = (
329
+ f"requested uid {req} but training ran as euid {obs or 'unknown'}")
330
+ if st.get("overrides_seen"):
331
+ info["frozen_surface"]["overrides_seen"] = st["overrides_seen"]
332
+ reasons += [R_CHEAT]
333
+ return reasons, info
334
+
335
+
336
+ # -----------------------------------------------------------------------------
337
+ # model loading / eval (machinery lifted verbatim from parameter-golf)
338
+ # -----------------------------------------------------------------------------
339
+ def sanitize_python_path(*extra_blocked: Path) -> None:
340
+ blocked = {Path.cwd().resolve()} | {p.resolve() for p in extra_blocked}
341
+ clean = []
342
+ for entry in sys.path:
343
+ if not entry:
344
+ continue
345
+ try:
346
+ r = Path(entry).resolve()
347
+ except OSError:
348
+ continue
349
+ if r in blocked:
350
+ continue
351
+ clean.append(entry)
352
+ sys.path[:] = clean
353
+
354
+
355
+ def import_solution(path: Path):
356
+ spec = importlib.util.spec_from_file_location("submitted_train_gpt", path)
357
+ if spec is None or spec.loader is None:
358
+ raise RuntimeError(f"Could not import {path}")
359
+ module = importlib.util.module_from_spec(spec)
360
+ sys.modules["submitted_train_gpt"] = module
361
+ ws = str(path.parent.resolve())
362
+ inserted = ws not in sys.path
363
+ if inserted:
364
+ sys.path.insert(0, ws)
365
+ try:
366
+ spec.loader.exec_module(module)
367
+ finally:
368
+ if inserted:
369
+ try:
370
+ sys.path.remove(ws)
371
+ except ValueError:
372
+ pass
373
+ return module
374
+
375
+
376
+ def call_model_loader(module: Any, ckpt: Path, device):
377
+ import torch
378
+ args = module.Hyperparameters() if hasattr(module, "Hyperparameters") else None
379
+ loader = getattr(module, "load_model_for_verification", None)
380
+ if loader is None:
381
+ raise RuntimeError("train_gpt.py must define load_model_for_verification(checkpoint_path, device)")
382
+ sig = inspect.signature(loader)
383
+ kwargs, positional = {}, []
384
+ for name, p in sig.parameters.items():
385
+ if name in {"checkpoint_path", "path", "model_path"}:
386
+ kwargs[name] = ckpt
387
+ elif name == "device":
388
+ kwargs[name] = device
389
+ elif p.default is inspect._empty:
390
+ if not positional:
391
+ positional.append(ckpt)
392
+ elif len(positional) == 1:
393
+ positional.append(device)
394
+ loaded = loader(*positional, **kwargs)
395
+ if isinstance(loaded, tuple) and len(loaded) == 2:
396
+ loaded_args, model = loaded
397
+ if loaded_args is not None:
398
+ args = loaded_args
399
+ else:
400
+ model = loaded
401
+ if not isinstance(model, torch.nn.Module):
402
+ raise TypeError("load_model_for_verification must return an nn.Module or (args, model)")
403
+ return args, model.to(device).eval()
404
+
405
+
406
+ def build_sentencepiece_luts(sp, vocab_size, device):
407
+ import numpy as np
408
+ import torch
409
+ sp_vocab_size = int(sp.vocab_size())
410
+ table_size = max(sp_vocab_size, vocab_size)
411
+ base_bytes_np = np.zeros((table_size,), dtype=np.int32)
412
+ has_leading_space_np = np.zeros((table_size,), dtype=np.bool_)
413
+ is_boundary_token_np = np.ones((table_size,), dtype=np.bool_)
414
+ for tid in range(sp_vocab_size):
415
+ if sp.is_control(tid) or sp.is_unknown(tid) or sp.is_unused(tid):
416
+ continue
417
+ is_boundary_token_np[tid] = False
418
+ if sp.is_byte(tid):
419
+ base_bytes_np[tid] = 1
420
+ continue
421
+ piece = sp.id_to_piece(tid)
422
+ if piece.startswith("▁"):
423
+ has_leading_space_np[tid] = True
424
+ piece = piece[1:]
425
+ base_bytes_np[tid] = len(piece.encode("utf-8"))
426
+ return (torch.tensor(base_bytes_np, dtype=torch.int32, device=device),
427
+ torch.tensor(has_leading_space_np, dtype=torch.bool, device=device),
428
+ torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device))
429
+
430
+
431
+ def _resolve_tokenizer(args) -> Path:
432
+ cand = Path(str(getattr(args, "tokenizer_path", DEFAULT_TOKENIZER_PATH)))
433
+ if cand.exists():
434
+ return cand
435
+ if DEFAULT_TOKENIZER_PATH.exists():
436
+ return DEFAULT_TOKENIZER_PATH
437
+ raise FileNotFoundError(f"No tokenizer at {cand} or {DEFAULT_TOKENIZER_PATH}")
438
+
439
+
440
+ def hidden_validation_tokens(args, device):
441
+ import numpy as np
442
+ import sentencepiece as spm
443
+ import torch
444
+ if not HOLDOUT_CORPUS_PATH.exists():
445
+ raise FileNotFoundError(f"Held-out corpus not found at {HOLDOUT_CORPUS_PATH}")
446
+ sp = spm.SentencePieceProcessor(model_file=str(_resolve_tokenizer(args)))
447
+ raw = HOLDOUT_CORPUS_PATH.read_text(encoding="utf-8")
448
+ text = "\n".join(ln for ln in raw.splitlines() if not ln.startswith("# provenance-marker"))
449
+ ids = np.array(sp.encode(text), dtype=np.int64)
450
+ seq_len = int(getattr(args, "train_seq_len", DEFAULT_SEQ_LEN) or DEFAULT_SEQ_LEN)
451
+ if ids.size <= seq_len + 1:
452
+ ids = np.tile(ids, (seq_len + 2) // max(ids.size, 1) + 1)
453
+ usable = ((ids.size - 1) // seq_len) * seq_len
454
+ val_tokens = torch.from_numpy(ids[: usable + 1]).contiguous()
455
+ vocab_size = int(getattr(args, "vocab_size", sp.vocab_size()) or sp.vocab_size())
456
+ return val_tokens, build_sentencepiece_luts(sp, vocab_size, device), sp
457
+
458
+
459
+ def _eval_val_one_pass(model, val_tokens, luts, device, seq_len, val_batch_tokens, offset):
460
+ import torch
461
+ import torch.nn.functional as F
462
+ base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = luts
463
+ val_batch_tokens = max(val_batch_tokens, seq_len)
464
+ batch_seqs = max(val_batch_tokens // seq_len, 1)
465
+ n = val_tokens.numel()
466
+ if offset < 0 or offset >= n - 1:
467
+ raise ValueError("offset out of range")
468
+ usable = ((n - offset - 1) // seq_len) * seq_len
469
+ total_seqs = usable // seq_len
470
+ if total_seqs <= 0:
471
+ raise ValueError("corpus too short")
472
+ val_loss_sum = torch.zeros((), device=device, dtype=torch.float64)
473
+ val_token_count = torch.zeros((), device=device, dtype=torch.float64)
474
+ val_byte_count = torch.zeros((), device=device, dtype=torch.float64)
475
+ for seq_start in range(0, total_seqs, batch_seqs):
476
+ seq_end = min(seq_start + batch_seqs, total_seqs)
477
+ raw_start = offset + seq_start * seq_len
478
+ raw_end = offset + seq_end * seq_len + 1
479
+ local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True)
480
+ x = local[:-1].reshape(-1, seq_len)
481
+ y = local[1:].reshape(-1, seq_len)
482
+ try:
483
+ out = model(x, y)
484
+ except Exception:
485
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
486
+ out = model(x, y)
487
+ if isinstance(out, torch.Tensor) and out.ndim >= 1 and out.numel() != 1:
488
+ logits = out.float().reshape(-1, out.shape[-1])
489
+ batch_loss = F.cross_entropy(logits, y.reshape(-1), reduction="mean")
490
+ else:
491
+ batch_loss = out
492
+ btc = float(y.numel())
493
+ val_loss_sum += batch_loss.detach().to(torch.float64) * btc
494
+ val_token_count += btc
495
+ prev_ids = x.reshape(-1)
496
+ tgt_ids = y.reshape(-1)
497
+ token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int32)
498
+ token_bytes = token_bytes + (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int32)
499
+ val_byte_count += token_bytes.to(torch.float64).sum()
500
+ val_loss = (val_loss_sum / val_token_count).item()
501
+ bits_per_token = val_loss / math.log(2.0)
502
+ tokens_per_byte = val_token_count.item() / val_byte_count.item()
503
+ return float(val_loss), float(bits_per_token * tokens_per_byte)
504
+
505
+
506
+ def eval_val(model, val_tokens, luts, device, seq_len, val_batch_tokens):
507
+ import torch
508
+ model.eval()
509
+ offsets = (0, seq_len // 3, (2 * seq_len) // 3)
510
+ losses, bpbs = [], []
511
+ with torch.inference_mode():
512
+ for off in offsets:
513
+ try:
514
+ loss, bpb = _eval_val_one_pass(model, val_tokens, luts, device, seq_len, val_batch_tokens, off)
515
+ except ValueError:
516
+ continue
517
+ losses.append(loss)
518
+ bpbs.append(bpb)
519
+ if not bpbs:
520
+ raise RuntimeError("corpus too short for any shifted pass")
521
+ passes = sorted(bpbs)
522
+ losses_sorted = sorted(losses)
523
+ mid = len(passes) // 2
524
+ return float(losses_sorted[mid]), float(passes[mid]), passes
525
+
526
+
527
+ def _probe_shapes(args):
528
+ seq_len = int(getattr(args, "train_seq_len", DEFAULT_SEQ_LEN) or DEFAULT_SEQ_LEN)
529
+ vocab_size = int(getattr(args, "vocab_size", 0) or 0) or 8192
530
+ return max(seq_len, 16), vocab_size
531
+
532
+
533
+ def _logits_and_loss_probe(model, args, device):
534
+ import torch
535
+ import torch.nn.functional as F
536
+ seq_len, vocab_size = _probe_shapes(args)
537
+ arange = torch.arange(seq_len, device=device, dtype=torch.int64)
538
+ x = (arange % vocab_size).reshape(1, -1)
539
+ y = ((arange + 1) % vocab_size).reshape(1, -1)
540
+ with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
541
+ logits = model(x)
542
+ loss_xy = model(x, y)
543
+ if not isinstance(logits, torch.Tensor):
544
+ raise AssertionError(f"forward(x) returned {type(logits).__name__}, expected logits")
545
+ if logits.ndim != 3 or logits.shape[0] != 1 or logits.shape[1] != seq_len:
546
+ raise AssertionError(f"forward(x) shape {tuple(logits.shape)}, expected (1,{seq_len},V)")
547
+ if not logits.dtype.is_floating_point:
548
+ raise AssertionError(f"forward(x) dtype {logits.dtype} not floating-point")
549
+ lf = logits.float()
550
+ pos_var = float(lf.var(dim=1).mean().item())
551
+ if not math.isfinite(pos_var) or pos_var <= LOGITS_POSITION_VARIANCE_FLOOR:
552
+ raise AssertionError(f"forward(x) logits constant across positions (var={pos_var:.2e})")
553
+ V = logits.shape[-1]
554
+ ref = float(F.cross_entropy(lf.reshape(-1, V), y.reshape(-1).clamp_max(V - 1), reduction="mean").item())
555
+ lxy = float(loss_xy.detach().to(torch.float64).item()) if isinstance(loss_xy, torch.Tensor) else float(loss_xy)
556
+ if not math.isfinite(lxy) or not math.isfinite(ref):
557
+ raise AssertionError(f"non-finite probe losses xy={lxy} ce={ref}")
558
+ if abs(lxy - ref) > LOGITS_LOSS_AGREEMENT_TOL:
559
+ raise AssertionError(f"forward(x,y)={lxy:.4f} disagrees with CE(forward(x),y)={ref:.4f}")
560
+ return lxy, ref, pos_var, V
561
+
562
+
563
+ def check_validation(workspace: Path):
564
+ """Correctness / anti-spoof suite. Returns (checks, val_bpb, bpb_passes)."""
565
+ import torch
566
+ checks: list[Check] = []
567
+ if not torch.cuda.is_available():
568
+ return [result("CUDA available", False, "CUDA required", gate=R_BUILD)], None, None
569
+ if not CKPT_PATH.exists():
570
+ return [result("Checkpoint present", False, f"no checkpoint at {CKPT_PATH}", gate=R_BUILD)], None, None
571
+ try:
572
+ module = import_solution(SUBMISSION_DIR / "train_gpt.py")
573
+ except Exception as exc:
574
+ return [result("Import submission", False, f"{type(exc).__name__}: {exc}", gate=R_BUILD)], None, None
575
+ device = torch.device("cuda", 0)
576
+ torch.cuda.set_device(device)
577
+ try:
578
+ args, model = call_model_loader(module, CKPT_PATH, device)
579
+ except Exception as exc:
580
+ return [result("load_model_for_verification", False, f"{type(exc).__name__}: {exc}", gate=R_BUILD)], None, None
581
+ checks.append(result("Import + checkpoint reload", True, "loader returned an nn.Module", gate=R_BUILD))
582
+
583
+ n_params = sum(int(p.numel()) for p in model.parameters())
584
+ checks.append(result("Model parameter count", n_params >= MIN_PARAM_COUNT,
585
+ f"{n_params:,} params (real-LM floor {MIN_PARAM_COUNT:,})", n_params=n_params))
586
+ if n_params < MIN_PARAM_COUNT:
587
+ return checks, None, None
588
+
589
+ # A3 CAPACITY FLOOR — harness-recounted total params, weight-tie deduplicated.
590
+ seen, unique_params = set(), 0
591
+ for p in model.parameters():
592
+ key = p.data_ptr()
593
+ if key in seen:
594
+ continue
595
+ seen.add(key)
596
+ unique_params += int(p.numel())
597
+ checks.append(result("A3 capacity floor (total params >= floor)", unique_params >= PARAM_FLOOR,
598
+ f"{unique_params:,} unique params (floor {PARAM_FLOOR:,})",
599
+ total_params=unique_params, param_floor=PARAM_FLOOR))
600
+ if unique_params < PARAM_FLOOR:
601
+ return checks, None, None
602
+
603
+ try:
604
+ loss_ar, ce_ar, pos_var, V = _logits_and_loss_probe(model, args, device)
605
+ except Exception as exc:
606
+ checks.append(result("forward(x)/forward(x,y) CE agreement", False, f"{type(exc).__name__}: {exc}"))
607
+ return checks, None, None
608
+ checks.append(result("forward(x)/forward(x,y) CE agreement", True,
609
+ f"loss_xy={loss_ar:.4f} ce={ce_ar:.4f} pos_var={pos_var:.2e}",
610
+ loss_xy=loss_ar, ce_loss=ce_ar, position_variance=pos_var))
611
+
612
+ try:
613
+ val_tokens, luts, sp = hidden_validation_tokens(args, device)
614
+ except Exception as exc:
615
+ checks.append(result("Held-out corpus available", False, f"{type(exc).__name__}: {exc}", gate=R_BUILD))
616
+ return checks, None, None
617
+ seq_len, _ = _probe_shapes(args)
618
+ vbt = int(getattr(args, "val_batch_size", DEFAULT_VAL_BATCH_TOKENS) or DEFAULT_VAL_BATCH_TOKENS)
619
+ try:
620
+ val_loss, val_bpb, bpb_passes = eval_val(model, val_tokens, luts, device, seq_len, vbt)
621
+ except Exception as exc:
622
+ checks.append(result("Held-out evaluation", False, f"{type(exc).__name__}: {exc}"))
623
+ return checks, None, None
624
+
625
+ # Plausibility band. The LOWER edge is an anti-spoof / anti-contamination gate: no
626
+ # honest recipe trained inside this budget can reach it, so a value below it means a
627
+ # forged loss or held-out contamination, not a better model.
628
+ plausible = math.isfinite(val_bpb) and MIN_PLAUSIBLE_VAL_BPB <= val_bpb <= MAX_PLAUSIBLE_VAL_BPB
629
+ checks.append(result("Held-out val_bpb plausible (anti-spoof band)", plausible,
630
+ f"val_bpb={val_bpb:.4f} in [{MIN_PLAUSIBLE_VAL_BPB},{MAX_PLAUSIBLE_VAL_BPB}]",
631
+ gate=(R_CHEAT if (math.isfinite(val_bpb) and val_bpb < MIN_PLAUSIBLE_VAL_BPB) else R_CORRECT),
632
+ val_bpb=val_bpb, val_loss=val_loss, shift_passes=bpb_passes))
633
+
634
+ if val_tokens.numel() >= seq_len + 1:
635
+ import torch.nn.functional as F
636
+ rx = val_tokens[:seq_len].reshape(1, -1).to(device=device, dtype=torch.int64).clamp_max(V - 1)
637
+ ry = val_tokens[1:seq_len + 1].reshape(1, -1).to(device=device, dtype=torch.int64).clamp_max(V - 1)
638
+ try:
639
+ with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
640
+ out = model(rx, ry)
641
+ if isinstance(out, torch.Tensor) and out.numel() != 1:
642
+ loss_real = float(F.cross_entropy(out.float().reshape(-1, out.shape[-1]), ry.reshape(-1), reduction="mean").item())
643
+ else:
644
+ loss_real = float(out.detach().to(torch.float64).item())
645
+ except Exception as exc:
646
+ checks.append(result("OOD: loss(real) < ratio*loss(arange)", False, f"{type(exc).__name__}: {exc}"))
647
+ return checks, val_bpb, bpb_passes
648
+ thr = OOD_LOSS_RATIO * loss_ar
649
+ checks.append(result("OOD: loss(real) < ratio*loss(arange)",
650
+ math.isfinite(loss_real) and loss_real < thr,
651
+ f"loss(real)={loss_real:.4f} vs {OOD_LOSS_RATIO}*loss(arange)={thr:.4f}",
652
+ loss_real=loss_real, loss_arange=loss_ar))
653
+ return checks, val_bpb, bpb_passes
654
+
655
+
656
+ # -----------------------------------------------------------------------------
657
+ # reward.md performance pre-gates + bounded reward
658
+ # -----------------------------------------------------------------------------
659
+ def score(checks: list[Check], val_bpb, bpb_passes, pre_reasons: list[str], extra: dict[str, Any]):
660
+ reasons = list(pre_reasons)
661
+
662
+ # gate 6 — reference solution invalid / uncalibrated. Fail CLOSED: never default the
663
+ # constant, never silently treat a missing anchor as 1.0.
664
+ ref_ok = isinstance(REF_SPEEDUP, (int, float)) and math.isfinite(float(REF_SPEEDUP)) and float(REF_SPEEDUP) > 1.0
665
+ base_ok = isinstance(BASELINE_BPB, (int, float)) and math.isfinite(float(BASELINE_BPB)) and float(BASELINE_BPB) > 0
666
+ if not ref_ok or not base_ok:
667
+ reasons.append(R_BAD_REF)
668
+ extra["ref_speedup_status"] = (
669
+ "ANCHOR_NOT_CALIBRATED: reward_model.baseline_bpb / reward_model.ref_speedup absent or <= 1 "
670
+ "in the frozen manifest")
671
+ elif float(REF_SPEEDUP) < REF_SPEEDUP_AUTHORING_FLOOR:
672
+ reasons.append(R_BAD_REF)
673
+ extra["ref_speedup_status"] = (
674
+ f"ref_speedup={float(REF_SPEEDUP):.6f} < authoring floor {REF_SPEEDUP_AUTHORING_FLOOR} "
675
+ "(reward.md legality): task must be reclassified, not scored")
676
+
677
+ # gate 1/2/3 — build/import, correctness suite, anti-cheat. Each failing check contributes
678
+ # its own named gate reason.
679
+ for c in checks:
680
+ if not c.passed:
681
+ reasons.append(c.gate)
682
+ if not checks:
683
+ reasons.append(R_BUILD)
684
+ # a TRUNCATED suite (early return) can never score above 0 — the full suite must be
685
+ # present as well as green.
686
+ if len(checks) < EXPECTED_TOTAL_CHECKS:
687
+ reasons.append(R_INCOMPLETE)
688
+
689
+ speedup = None
690
+ if base_ok and isinstance(val_bpb, (int, float)) and math.isfinite(val_bpb) and val_bpb > 0:
691
+ speedup = float(BASELINE_BPB) / float(val_bpb)
692
+
693
+ # gate 5 — did not beat the baseline recipe it started from
694
+ if speedup is None:
695
+ reasons.append(R_NO_GAIN)
696
+ elif speedup <= 1.0:
697
+ reasons.append(R_NO_GAIN)
698
+
699
+ if reasons:
700
+ emit(0.0, reasons, checks, speedup, val_bpb, bpb_passes, extra)
701
+ return 0.0, reasons
702
+
703
+ reward = min(1.0, max(0.0, min(1.0, math.log(speedup) / math.log(float(REF_SPEEDUP)) - 1.0)))
704
+ reward = min(1.0, max(0.0, reward))
705
+ emit(reward, [], checks, speedup, val_bpb, bpb_passes, extra)
706
+ return reward, []
707
+
708
+
709
+ def main() -> int:
710
+ ap = argparse.ArgumentParser()
711
+ ap.add_argument("--emit-zero", metavar="REASON", default=None,
712
+ help="named reason from the shared vocabulary; emits the full output contract "
713
+ "with reward 0")
714
+ ap.add_argument("--detail", default="", help="human-readable detail for --emit-zero")
715
+ ns, _ = ap.parse_known_args()
716
+ if ns.emit_zero:
717
+ known = {R_BUILD, R_CORRECT, R_CHEAT, R_FORBIDDEN, R_NO_GAIN, R_BAD_REF,
718
+ R_CRASH, R_UNNAMED, R_INCOMPLETE}
719
+ reason = ns.emit_zero.strip()
720
+ if reason not in known:
721
+ reason = R_BUILD
722
+ detail = ns.detail or ns.emit_zero
723
+ emit(0.0, [reason], [result("Harness pre-flight", False, detail, gate=reason)],
724
+ extra={"harness_message": detail})
725
+ return 1
726
+
727
+ extra: dict[str, Any] = {}
728
+ pre_reasons: list[str] = []
729
+ if _MAN_PROBLEMS:
730
+ pre_reasons.append(R_BUILD)
731
+ extra["manifest_problems"] = _MAN_PROBLEMS
732
+ # Refuse to score against an in-image (solver-reachable) evaluation surface: after the
733
+ # de-leak rebuild there is no /opt/verifier at all, so its presence means a stale image.
734
+ if Path("/opt/verifier").exists():
735
+ pre_reasons.append(R_FORBIDDEN)
736
+ extra["stale_baked_verifier"] = (
737
+ "/opt/verifier exists in this image — the frozen evaluation surface must be uploaded "
738
+ "fresh at /tests only; refusing to score against a solver-reachable copy")
739
+ tamper_reasons, tamper_info = frozen_surface_verdict()
740
+ pre_reasons += tamper_reasons
741
+ extra.update(tamper_info)
742
+
743
+ sanitize_python_path(SUBMISSION_DIR)
744
+ try:
745
+ checks, val_bpb, bpb_passes = check_validation(SUBMISSION_DIR)
746
+ except Exception as exc:
747
+ checks = [result("Verifier error", False, f"{type(exc).__name__}: {exc}", gate=R_BUILD)]
748
+ val_bpb, bpb_passes = None, None
749
+ reward, reasons = score(checks, val_bpb, bpb_passes, pre_reasons, extra)
750
+ return 0 if (reward > 0.0 and not reasons) else 1
751
+
752
+
753
+ if __name__ == "__main__":
754
+ try:
755
+ raise SystemExit(main())
756
+ except SystemExit:
757
+ raise
758
+ except BaseException as exc: # never exit without the output contract
759
+ try:
760
+ emit(0.0, [R_CRASH], [result("Verifier crashed", False, f"{type(exc).__name__}: {exc}", gate=R_CRASH)])
761
+ finally:
762
+ raise SystemExit(1)
tasks/e2e/a3-moe-train-budget/task/tests/holdout_corpus.txt ADDED
The diff for this file is too large to render. See raw diff
 
tasks/e2e/a3-moe-train-budget/task/tests/test.sh ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # e2e-a3-moe-train-budget verifier orchestration (FROZEN eval surface).
3
+ #
4
+ # Single-shot family-A: run the solver's training UNDER a harness-owned wall-clock timer
5
+ # (external process-group kill — never a cooperative in-loop timer, never a self-reported
6
+ # step/token count), then eval the produced checkpoint.
7
+ #
8
+ # REWARD (the bench reward spec, performance class, BOUNDED):
9
+ # speedup = baseline_bpb / candidate_val_bpb (quality ratio at a FIXED budget)
10
+ # ref_speedup = baseline_bpb / oracle_val_bpb (FROZEN authoring constant)
11
+ # reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0 in [0, 1]
12
+ # Matching the BASELINE recipe scores 0 (pre-gate 5); matching the demonstrated in-budget
13
+ # ceiling scores 0.5. The scorer reads the two constants from the frozen manifest and NEVER
14
+ # runs the oracle or the baseline.
15
+ #
16
+ # The whole /app/repo (nanoGPT) + /app/submission is editable; the eval surface (/tests/*) is
17
+ # frozen and uploaded FRESH at scoring (nothing is baked into the image).
18
+ set -o pipefail
19
+
20
+ # Lead PATH with the base image's uv venv (/opt/kernelbench-venv has torch + sentencepiece; a
21
+ # bare system python3 does NOT). the harness may exec login-style and resets PATH, so pin it.
22
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
23
+ # Pin BLAS/OMP thread counts so runtime does not depend on node topology (measured: a 145-core
24
+ # node let torch open 96 threads and ran 4.3x SLOWER than a pinned single-thread host loop).
25
+ export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}"
26
+ export MKL_NUM_THREADS="${MKL_NUM_THREADS:-8}"
27
+ export OPENBLAS_NUM_THREADS="${OPENBLAS_NUM_THREADS:-8}"
28
+
29
+ # 🔴 Strip every inherited E2E_* variable FIRST. The container entrypoint is a LOGIN shell that
30
+ # sources the solver-owned ~/.bashrc, so anything E2E_* arriving from the environment is
31
+ # solver-controlled. Only values this script derives from the FROZEN manifest are honoured.
32
+ for v in $(env | sed -n 's/^\(E2E_[A-Z0-9_]*\)=.*/\1/p'); do unset "$v"; done
33
+ unset VERIFIER_MODE KERNELBENCH_VERIFY_MODE
34
+
35
+ FROZEN=/tests
36
+ MANIFEST="$FROZEN/verifier-correctness-manifest.json"
37
+ SUBMISSION_DIR=/app/submission
38
+ VDIR=/logs/verifier
39
+ mkdir -p "$VDIR" /logs/artifacts
40
+ rm -f "$VDIR"/reward.txt "$VDIR"/reward.json "$VDIR"/metrics.json \
41
+ "$VDIR"/verifier_state.json "$VDIR"/correctness_results.json "$VDIR"/benchmark_results.json
42
+ cd / # a deleted CWD kills torch's dlopen; anchor somewhere that always exists
43
+
44
+ # The complete verifier output contract on EVERY hard-fail path. Delegated to the frozen
45
+ # scorer's --emit-zero so the hard-fail schema can never drift from the success schema; the
46
+ # inline fallback covers the case where python itself cannot start.
47
+ PY=/opt/kernelbench-venv/bin/python3
48
+ [ -x "$PY" ] || PY=python3
49
+ emit_zero() { # $1 = human message, $2 = named reason
50
+ _r="${2:-build_or_entry_contract_failed}"
51
+ _msg=$(printf '%s' "$1" | tr -d '"\\')
52
+ echo "HARD-FAIL[$_r]: $1"
53
+ if [ -f "$FROZEN/compute_reward.py" ] && "$PY" "$FROZEN/compute_reward.py" \
54
+ --emit-zero "$_r" --detail "$_msg" >/dev/null 2>&1; then
55
+ return 0
56
+ fi
57
+ echo "{\"task_type\":\"performance\",\"reward\":0.0,\"partial_score\":0.0,\"hard_fail_reasons\":[\"${_r}\"],\"speedup\":null,\"ref_speedup\":null,\"passed\":0,\"total\":0,\"tests\":{\"passed\":0,\"total\":0},\"metric_kind\":\"quality_at_fixed_budget\",\"metric_name\":\"val_bpb\",\"metric_direction\":\"lower_is_better\",\"timing_measured\":false,\"error\":\"${_msg}\"}" > "$VDIR/metrics.json"
58
+ echo "{\"task_type\":\"performance\",\"reward\":0.0,\"hard_fail_reasons\":[\"${_r}\"],\"speedup\":null,\"ref_speedup\":null,\"cv\":{},\"metric_kind\":\"quality_at_fixed_budget\",\"metric_name\":\"val_bpb\",\"metric_direction\":\"lower_is_better\",\"timing_measured\":false}" > "$VDIR/reward.json"
59
+ echo "{\"task_id\":\"e2e-a3-moe-train-budget\",\"task_type\":\"performance\",\"reward\":0.0,\"hard_fail_reasons\":[\"${_r}\"],\"detail\":\"${_msg}\"}" > "$VDIR/verifier_state.json"
60
+ echo "{\"passed\":0,\"total\":0,\"expected_total\":6,\"all_passed\":false,\"hard_fail_reasons\":[\"${_r}\"],\"checks\":[{\"name\":\"harness pre-flight\",\"passed\":false,\"message\":\"${_msg}\",\"gate\":\"${_r}\"}]}" > "$VDIR/correctness_results.json"
61
+ echo "{\"metric_kind\":\"quality_at_fixed_budget\",\"metric_name\":\"val_bpb\",\"metric_direction\":\"lower_is_better\",\"timing_measured\":false,\"candidate_val_bpb\":null,\"speedup\":null,\"metric_void_on_hard_fail\":true,\"oracle_executed_by_scorer\":false,\"baseline_executed_by_scorer\":false,\"hard_fail_reasons\":[\"${_r}\"]}" > "$VDIR/benchmark_results.json"
62
+ echo 0.000000 > "$VDIR/reward.txt"
63
+ }
64
+
65
+ save_artifacts() {
66
+ for p in "$SUBMISSION_DIR/train_gpt.py" "$SUBMISSION_DIR/run_training.sh" "$VDIR/train.log"; do
67
+ [ -e "$p" ] && cp -r "$p" "/logs/artifacts/$(basename "$p")" 2>/dev/null || true
68
+ done
69
+ }
70
+ trap save_artifacts EXIT
71
+
72
+ # --- the frozen surface must be the FRESH /tests upload, and ONLY that -------------------
73
+ # There is deliberately no baked /opt/verifier fallback any more: a baked copy leaks the
74
+ # held-out corpus and the calibrated constants into the solver's own container, and lets a
75
+ # stale scorer decide a run.
76
+ FROZEN_SET="compute_reward.py test.sh timer.sh holdout_corpus.txt verifier-correctness-manifest.json"
77
+ if [ ! -f "$FROZEN/compute_reward.py" ]; then
78
+ if [ -e /opt/verifier ]; then
79
+ emit_zero "frozen surface not mounted at /tests and an in-image /opt/verifier copy is present — refusing to score against a solver-reachable evaluation surface" "forbidden_edit_path"
80
+ exit 1
81
+ fi
82
+ emit_zero "frozen evaluation surface missing: /tests/compute_reward.py not mounted — failing closed" "build_or_entry_contract_failed"
83
+ exit 1
84
+ fi
85
+ for f in $FROZEN_SET; do
86
+ [ -f "$FROZEN/$f" ] || { emit_zero "frozen evaluation surface incomplete: /tests/$f not mounted" "build_or_entry_contract_failed"; exit 1; }
87
+ done
88
+ if [ -e /opt/verifier ]; then
89
+ emit_zero "an in-image /opt/verifier evaluation surface is present (image is stale / re-leaked)" "forbidden_edit_path"; exit 1
90
+ fi
91
+
92
+ # verifier self-integrity against the manifest pin
93
+ EXP_SHA=$("$PY" -c "import json;print(json.load(open('$MANIFEST')).get('compute_reward_sha256',''))" 2>/dev/null)
94
+ GOT_SHA=$(sha256sum "$FROZEN/compute_reward.py" | awk '{print $1}')
95
+ if [ -n "$EXP_SHA" ] && [ "$EXP_SHA" != "$GOT_SHA" ]; then
96
+ emit_zero "verifier sha256 mismatch (frozen surface tampered): expected $EXP_SHA got $GOT_SHA" "forbidden_edit_path"; exit 1
97
+ fi
98
+
99
+ # --- read the frozen budget from the manifest -------------------------------------------
100
+ read_man() { "$PY" -c "import json;d=json.load(open('$MANIFEST'));print(d.get('budget',{}).get('$1', d.get('$1','$2')))"; }
101
+ WALLCLOCK_SEC=$(read_man wallclock_sec 600)
102
+ SEED=$("$PY" -c "import json;print(json.load(open('$MANIFEST')).get('harness_seed',1337))")
103
+ PARAM_FLOOR=$("$PY" -c "import json;d=json.load(open('$MANIFEST'));print((d.get('quality_gate') or {}).get('param_floor', d.get('param_floor',150000000)))")
104
+ OUT_CKPT="$SUBMISSION_DIR/model_ckpt.pt"
105
+ echo "[test] budget: wallclock=${WALLCLOCK_SEC}s param_floor=${PARAM_FLOOR} seed=${SEED} (harness-fixed)"
106
+
107
+ # --- entry contract ---------------------------------------------------------------------
108
+ [ -f "$SUBMISSION_DIR/run_training.sh" ] || { emit_zero "missing entry contract $SUBMISSION_DIR/run_training.sh" "build_or_entry_contract_failed"; exit 1; }
109
+ [ -f "$SUBMISSION_DIR/train_gpt.py" ] || { emit_zero "missing $SUBMISSION_DIR/train_gpt.py (needs load_model_for_verification)" "build_or_entry_contract_failed"; exit 1; }
110
+ rm -f "$OUT_CKPT"
111
+
112
+ # --- fingerprint the frozen surface, then QUARANTINE it for the training phase -----------
113
+ # The training entry runs as root in this container, so /tests cannot be made cryptographically
114
+ # unreachable; what the harness CAN do is (a) make the held-out corpus and the calibrated
115
+ # constants unreadable for the duration of the run and (b) detect any change to them. Both a
116
+ # content change and a mode change are red lines -> reward 0 with a named reason.
117
+ STATE_DIR=$(mktemp -d /tmp/.e2e_a3_state.XXXXXXXX)
118
+ chmod 0700 "$STATE_DIR"
119
+ "$PY" - "$FROZEN" "$STATE_DIR/before.json" <<'PYFP'
120
+ import hashlib, json, os, sys
121
+ root, out = sys.argv[1], sys.argv[2]
122
+ rec = {}
123
+ for name in sorted(os.listdir(root)):
124
+ p = os.path.join(root, name)
125
+ if not os.path.isfile(p):
126
+ continue
127
+ h = hashlib.sha256()
128
+ with open(p, "rb") as fh:
129
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
130
+ h.update(chunk)
131
+ st = os.stat(p)
132
+ rec[name] = {"sha256": h.hexdigest(), "mode": st.st_mode & 0o7777, "size": st.st_size}
133
+ json.dump({"dir_mode": os.stat(root).st_mode & 0o7777, "files": rec}, open(out, "w"))
134
+ PYFP
135
+ [ -s "$STATE_DIR/before.json" ] || { emit_zero "could not fingerprint the frozen surface" "build_or_entry_contract_failed"; exit 1; }
136
+ # Copy the harness-owned timer OUT of /tests before quarantining, so launching the training
137
+ # does not depend on /tests being readable.
138
+ cp "$FROZEN/timer.sh" "$STATE_DIR/timer.sh" && chmod 0700 "$STATE_DIR/timer.sh"
139
+ SAVED_DIR_MODE=$(stat -c %a "$FROZEN")
140
+ chmod 0000 "$FROZEN" 2>/dev/null || true
141
+
142
+ # --- run the solver's training under the hard wall-clock cap ----------------------------
143
+ # DATA_PATH / TOKENIZER_PATH are PINNED by the harness (not inherited from the environment):
144
+ # the scored corpus must not be selectable by anything the solver can set (a login shell
145
+ # sources ~/.bashrc, so an inherited value is solver-controllable).
146
+ export SEED PARAM_FLOOR WALLCLOCK_SEC OUT_CKPT SUBMISSION_DIR
147
+ export DATA_PATH=/data/datasets/wikitext_bpe8k
148
+ export TOKENIZER_PATH=/data/tokenizers/wikitext_bpe8k.model
149
+ export NANOGPT_REPO=/app/repo
150
+ export PYTHONPATH=/app/repo
151
+ # --- PRIVILEGE DROP for the training phase ------------------------------------------------
152
+ # chmod 0000 on /tests means NOTHING to uid 0. Running the candidate's training under an
153
+ # unprivileged uid is what makes the held-out quarantine real instead of nominal. Everything the
154
+ # training legitimately needs is made accessible to that uid first; the frozen surface is not.
155
+ TRAIN_UID=$("$PY" -c "import json;print((json.load(open('$MANIFEST')).get('anti_tamper') or {}).get('training_uid') or '')" 2>/dev/null)
156
+ if [ -n "$TRAIN_UID" ]; then
157
+ export E2E_TRAIN_UID="$TRAIN_UID"
158
+ chmod 0777 "$SUBMISSION_DIR" 2>/dev/null || true
159
+ find "$SUBMISSION_DIR" -type f -exec chmod a+r {} + 2>/dev/null || true
160
+ find "$SUBMISSION_DIR" -type d -exec chmod a+rx {} + 2>/dev/null || true
161
+ chmod -R a+rX /app/repo 2>/dev/null || true
162
+ chmod a+rX /data /data/datasets /data/datasets/wikitext_bpe8k /data/tokenizers 2>/dev/null || true
163
+ find /data/datasets/wikitext_bpe8k /data/tokenizers -type f -exec chmod a+r {} + 2>/dev/null || true
164
+ HOMEDIR="$STATE_DIR/trainhome"; mkdir -p "$HOMEDIR"; chmod 0777 "$HOMEDIR" "$STATE_DIR"
165
+ export HOME="$HOMEDIR" TMPDIR="$HOMEDIR" XDG_CACHE_HOME="$HOMEDIR/.cache" \
166
+ TRITON_CACHE_DIR="$HOMEDIR/.triton" TORCHINDUCTOR_CACHE_DIR="$HOMEDIR/.inductor"
167
+ rm -f /app/.timer/train_uid
168
+ echo "[test] training will run as uid $TRAIN_UID (held-out quarantine is enforced by the uid, not just by chmod)"
169
+ fi
170
+
171
+ echo "[test] launching training (SEED=$SEED) ..."
172
+ # 🔴 Write the training log to a FILE, not through `| tee`: a surviving detached grandchild that
173
+ # holds the pipe open would block this shell forever (MEASURED — the run hung instead of scoring).
174
+ bash "$STATE_DIR/timer.sh" "$WALLCLOCK_SEC" bash "$SUBMISSION_DIR/run_training.sh" > "$VDIR/train.log" 2>&1
175
+ TRAIN_RC=$?
176
+ tail -40 "$VDIR/train.log" 2>/dev/null || true
177
+ echo "[test] training returned rc=$TRAIN_RC"
178
+ ACTUAL_TRAIN_UID=$(cat /app/.timer/train_uid 2>/dev/null | awk '{print $2}')
179
+ echo "[test] training ran as euid=${ACTUAL_TRAIN_UID:-unknown} (requested ${TRAIN_UID:-root})"
180
+ # the checkpoint is written by the unprivileged uid; make it readable for the eval phase
181
+ chmod a+r "$OUT_CKPT" 2>/dev/null || true
182
+
183
+ # --- un-quarantine and re-fingerprint ---------------------------------------------------
184
+ chmod "$SAVED_DIR_MODE" "$FROZEN" 2>/dev/null || true
185
+ "$PY" - "$FROZEN" "$STATE_DIR/before.json" "$STATE_DIR/frozen_state.json" "$SAVED_DIR_MODE" <<'PYCMP'
186
+ import hashlib, json, os, sys
187
+ root, before_p, out_p, saved_mode = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
188
+ before = json.load(open(before_p))
189
+ changed, mode_changed, unexpected = [], [], []
190
+ for name, rec in before["files"].items():
191
+ p = os.path.join(root, name)
192
+ if not os.path.isfile(p):
193
+ changed.append(name); continue
194
+ h = hashlib.sha256()
195
+ with open(p, "rb") as fh:
196
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
197
+ h.update(chunk)
198
+ if h.hexdigest() != rec["sha256"]:
199
+ changed.append(name)
200
+ if (os.stat(p).st_mode & 0o7777) != rec["mode"]:
201
+ mode_changed.append(name)
202
+ for name in sorted(os.listdir(root)):
203
+ if os.path.isfile(os.path.join(root, name)) and name not in before["files"]:
204
+ unexpected.append(name)
205
+ overrides = sorted(k for k in os.environ if k.startswith("E2E_") and k.endswith("_OVERRIDE"))
206
+ json.dump({"n_files": len(before["files"]), "changed": changed, "mode_changed": mode_changed,
207
+ "unexpected_files": unexpected, "overrides_seen": overrides,
208
+ "dir_mode_restored": saved_mode}, open(out_p, "w"))
209
+ PYCMP
210
+
211
+ # --- checkpoint present within the budget? ---------------------------------------------
212
+ if [ ! -f "$OUT_CKPT" ]; then
213
+ emit_zero "training produced no checkpoint at $OUT_CKPT within the ${WALLCLOCK_SEC}s budget (rc=$TRAIN_RC)" "build_or_entry_contract_failed"
214
+ exit 1
215
+ fi
216
+ if [ "$TRAIN_RC" -ne 0 ] && [ "$TRAIN_RC" -ne 124 ]; then
217
+ echo "[test] WARN training rc=$TRAIN_RC (non-timeout); a checkpoint exists, proceeding to eval"
218
+ fi
219
+
220
+ # --- EVAL + bounded reward (isolated process; cannot be shadowed by the submission) -----
221
+ # Every E2E_*_OVERRIDE is stripped: on the scored path no environment variable may influence
222
+ # the budget, the seed count or the frozen reward constants (a login shell sources ~/.bashrc,
223
+ # which the solver owns). Overrides remain available to the AUTHOR's calibration driver,
224
+ # which invokes compute_reward.py directly rather than through this script.
225
+ for v in $(env | sed -n 's/^\(E2E_[A-Z0-9_]*\)=.*/\1/p'); do unset "$v"; done
226
+ cp "$FROZEN/compute_reward.py" "$STATE_DIR/compute_reward.py"
227
+ unset PYTHONPATH PYTHONHOME
228
+ SUBMISSION_DIR="$SUBMISSION_DIR" OUT_CKPT="$OUT_CKPT" \
229
+ E2E_FROZEN_STATE="$STATE_DIR/frozen_state.json" \
230
+ E2E_OBSERVED_TRAIN_UID="${ACTUAL_TRAIN_UID:-}" E2E_REQUESTED_TRAIN_UID="${TRAIN_UID:-}" \
231
+ PYTHONSAFEPATH=1 "$PY" -I "$STATE_DIR/compute_reward.py"
232
+ EVAL_RC=$?
233
+
234
+ # --- output-contract guarantee ----------------------------------------------------------
235
+ # The scorer writes all six itself on every path it reaches (its own crash handler included),
236
+ # but if the interpreter dies first (missing dep / OOM / SIGKILL) nothing would be written.
237
+ CONTRACT_MISSING=false
238
+ for f in reward.txt reward.json metrics.json verifier_state.json correctness_results.json benchmark_results.json; do
239
+ [ -s "$VDIR/$f" ] || CONTRACT_MISSING=true
240
+ done
241
+ if [ "$CONTRACT_MISSING" = true ]; then
242
+ emit_zero "verifier process died before writing the result contract (exit $EVAL_RC)" "verifier_crashed"
243
+ rm -rf "$STATE_DIR"
244
+ exit 1
245
+ fi
246
+ echo "[test] compute_reward rc=$EVAL_RC ; reward=$(cat "$VDIR/reward.txt" 2>/dev/null)"
247
+ rm -rf "$STATE_DIR"
248
+ exit "$EVAL_RC"
tasks/e2e/a3-moe-train-budget/task/tests/timer.sh ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # FROZEN harness-owned wall-clock timer. Runs the solver's training under a HARD wall-clock cap
3
+ # the solver cannot disable or self-report: the child is started in its OWN SESSION and the
4
+ # whole PROCESS GROUP is signalled at the cap, so a daemonised background trainer cannot keep
5
+ # running (and keep overwriting the scored checkpoint) past the budget.
6
+ # usage: timer.sh <seconds> <cmd> [args...]
7
+ # SIGTERM at the cap so the training's periodic atomic checkpoint is the scored artifact, then
8
+ # SIGKILL after a grace period.
9
+ set -u
10
+ SECS="$1"; shift
11
+ mkdir -p /app/.timer
12
+ date +%s > /app/.timer/start
13
+ echo "$SECS" > /app/.timer/budget_sec
14
+ # background elapsed/remaining publisher (read-only to the solver)
15
+ (
16
+ start=$(date +%s)
17
+ while :; do
18
+ now=$(date +%s); el=$((now-start)); rem=$((SECS-el))
19
+ echo "$el" > /app/.timer/elapsed; echo "$rem" > /app/.timer/remaining
20
+ [ "$rem" -le 0 ] && break
21
+ sleep 2
22
+ done
23
+ ) &
24
+ PUB=$!
25
+
26
+ # --- hard cap, external and process-group wide + PRIVILEGE DROP --------------------------
27
+ # The child must be in its OWN process group so the whole group can be signalled, and it is
28
+ # launched under an UNPRIVILEGED uid when E2E_TRAIN_UID is set by test.sh.
29
+ #
30
+ # 🔴 WHY THE UID MATTERS. The frozen surface (/tests: the held-out corpus, the calibrated
31
+ # constants) is quarantined chmod 0000 while the training runs — but chmod means NOTHING to
32
+ # uid 0, which bypasses DAC entirely. Running the candidate's training as a non-root uid is what
33
+ # turns "quarantined" from nominal into real: only then can the candidate not read the held-out
34
+ # split it is scored on. The drop is verified from inside the child (it writes its euid to
35
+ # /app/.timer/train_uid) so the harness records the TRUTH rather than the intent.
36
+ TRAIN_UID="${E2E_TRAIN_UID:-}"
37
+ MYPGID=$(ps -o pgid= -p $$ 2>/dev/null | tr -d ' ')
38
+ python3 - "$TRAIN_UID" "$@" <<'PYLAUNCH' &
39
+ import os, sys
40
+ uid = sys.argv[1].strip()
41
+ cmd = sys.argv[2:]
42
+ # fork FIRST so setsid() can never fail with EPERM (it does when the caller is already a process
43
+ # group leader). MEASURED on NVIDIA H20 2026-07-27: if setsid silently failed, the training shared the
44
+ # HARNESS's process group and the timer's group-wide kill took test.sh down with it -- the run
45
+ # produced ZERO result files and looked like a training hang.
46
+ if os.fork() != 0:
47
+ os._exit(0)
48
+ os.setsid()
49
+ try:
50
+ os.makedirs("/app/.timer", exist_ok=True)
51
+ except Exception:
52
+ pass
53
+ if uid:
54
+ try:
55
+ u = int(uid)
56
+ os.setgroups([])
57
+ os.setgid(u)
58
+ os.setuid(u)
59
+ except Exception as exc:
60
+ sys.stderr.write("[timer] privilege drop to uid %s FAILED: %s\n" % (uid, exc))
61
+ try:
62
+ with open("/app/.timer/train_uid", "w") as fh:
63
+ fh.write("%d %d\n" % (os.getuid(), os.geteuid()))
64
+ except Exception:
65
+ pass
66
+ os.execvp(cmd[0], cmd)
67
+ PYLAUNCH
68
+ LAUNCHER=$!
69
+ wait "$LAUNCHER" 2>/dev/null || true # the launcher forks and exits; the grandchild trains
70
+ sleep 1
71
+ # locate the training's OWN session leader (pgid == sid) outside the harness's group
72
+ CHILD=$(ps -eo pid,pgid,sid,args 2>/dev/null | awk -v me="$MYPGID" '$2==$3 && $2!=me && /run_training/ {print $1; exit}')
73
+ [ -n "$CHILD" ] || CHILD=$(ps -eo pid,pgid,sid,args 2>/dev/null | awk -v me="$MYPGID" '$2==$3 && $2!=me && /train_gpt/ {print $1; exit}')
74
+ PGID=""
75
+ [ -n "$CHILD" ] && PGID=$(ps -o pgid= -p "$CHILD" 2>/dev/null | tr -d ' ')
76
+ # 🔴 SELF-KILL GUARD: never signal our own process group.
77
+ if [ -n "$PGID" ] && [ "$PGID" = "$MYPGID" ]; then
78
+ echo "[timer] WARNING: training shares the harness process group; using per-pid signals"
79
+ PGID=""
80
+ fi
81
+ echo "[timer] training pid=${CHILD:-unknown} pgid=${PGID:-none} harness_pgid=$MYPGID"
82
+ rc=0
83
+ deadline=$(( $(date +%s) + SECS ))
84
+ timed_out=0
85
+ while :; do
86
+ if [ -z "$CHILD" ] || ! kill -0 "$CHILD" 2>/dev/null; then
87
+ rc=0
88
+ break
89
+ fi
90
+ if [ "$(date +%s)" -ge "$deadline" ]; then
91
+ timed_out=1
92
+ echo "[timer] wall-clock budget ${SECS}s reached; stopping the training process group (checkpoint = latest atomic save)"
93
+ if [ -n "$PGID" ]; then kill -TERM -"$PGID" 2>/dev/null || true
94
+ else kill -TERM "$CHILD" 2>/dev/null || true; fi
95
+ sleep 8
96
+ if [ -n "$PGID" ]; then kill -KILL -"$PGID" 2>/dev/null || true
97
+ else kill -KILL "$CHILD" 2>/dev/null || true; fi
98
+ rc=0
99
+ break
100
+ fi
101
+ sleep 1
102
+ done
103
+ # --- reap EVERY straggler ------------------------------------------------------------------
104
+ # 🔴 MEASURED on NVIDIA H20 2026-07-28 with solution/probe_budget_bite: a process-group kill is NOT
105
+ # enough. The probe forks a grandchild that calls setsid() ITSELF, so the grandchild lands in a NEW
106
+ # session/group that `kill -- -$PGID` never reaches. It outlived the budget, kept rewriting the
107
+ # scored checkpoint into the eval phase, AND held the harness's log pipe open so test.sh never
108
+ # finished — the run HUNG instead of scoring.
109
+ # The reliable reaper is BY UID: the training runs unprivileged (E2E_TRAIN_UID), so killing every
110
+ # process owned by that uid reaches any descendant regardless of session or group. This is a
111
+ # second, independent payoff from the privilege drop.
112
+ if [ -n "$PGID" ]; then kill -KILL -"$PGID" 2>/dev/null || true; fi
113
+ if [ -n "${E2E_TRAIN_UID:-}" ]; then
114
+ for _ in 1 2 3; do
115
+ pkill -KILL -u "$E2E_TRAIN_UID" 2>/dev/null || true
116
+ sleep 1
117
+ # count only LIVE processes: a killed child sits as <defunct> (state Z) until its parent
118
+ # reaps it, and a zombie holds no resources and cannot touch the checkpoint. Counting zombies
119
+ # produced a spurious "survived the reaper" warning on the first measured run.
120
+ _live=$(ps -o stat= -u "$E2E_TRAIN_UID" 2>/dev/null | grep -cv '^[[:space:]]*Z' || true)
121
+ [ "${_live:-0}" -eq 0 ] && break
122
+ done
123
+ _live=$(ps -o stat= -u "$E2E_TRAIN_UID" 2>/dev/null | grep -cv '^[[:space:]]*Z' || true)
124
+ if [ "${_live:-0}" -gt 0 ]; then
125
+ echo "[timer] WARNING: processes owned by uid $E2E_TRAIN_UID survived the reaper:"
126
+ ps -o pid,pgid,sid,stat,args -u "$E2E_TRAIN_UID" 2>/dev/null | head -5
127
+ else
128
+ echo "[timer] reaped every LIVE process owned by uid $E2E_TRAIN_UID (zombies ignored)"
129
+ fi
130
+ fi
131
+ kill "$PUB" 2>/dev/null || true
132
+ # timing out is EXPECTED when the recipe uses the full budget; the periodic checkpoint is valid.
133
+ [ "$timed_out" -eq 1 ] && exit 0
134
+ exit "$rc"
tasks/e2e/a3-moe-train-budget/task/tests/verifier-correctness-manifest.json ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "e2e_verifier_correctness_manifest_v2",
3
+ "task_id": "e2e-a3-moe-train-budget",
4
+ "family": "A_training",
5
+ "reward_model": {
6
+ "spec": "the bench reward spec — performance class, BOUNDED log form",
7
+ "name": "reward_md_log_speedup_v2_oracle_zero",
8
+ "formula": "reward = min(1.0, ln(speedup/ref_speedup)/ln(ref_speedup)) if speedup > ref_speedup else 0.0; range [0,1]",
9
+ "speedup_definition": "baseline_bpb / candidate_val_bpb (held-out bits-per-byte at a FIXED wall-clock training budget; lower bpb is better, so the ratio is >1 only when the candidate beats the baseline recipe)",
10
+ "metric_kind": "quality_at_fixed_budget",
11
+ "metric_name": "val_bpb",
12
+ "metric_direction": "lower_is_better",
13
+ "timing_measured": false,
14
+ "semantic_caveat": "`speedup` / `ref_speedup` carry a QUALITY ratio, not a wall-clock ratio. Nothing in the reward is timed (the wall-clock is the fixed RESOURCE, not the metric). reward.md's bounded log envelope is ratio-agnostic; only the variable name says latency. The field names are kept for schema compatibility and are described by metric_kind / metric_name / metric_direction / timing_measured.",
15
+ "baseline_bpb": 1.9550684328299388,
16
+ "baseline_bpb_status": "CALIBRATED ON H20 2026-07-27: median of 5 runs of the SHIPPED starter through the shipped harness (values [1.962770085976607, 1.9510982056023425, 1.9526446798517447, 1.9550684328299388, 1.986950471502198]), spread 0.035852 bpb (1.834%), cv 0.00755. FROZEN constant; the scorer never runs the baseline.",
17
+ "baseline_cv": 0.007548522919998558,
18
+ "baseline_runs": 5,
19
+ "ref_speedup": 1.533747535323529,
20
+ "ref_speedup_status": "CALIBRATED ON H20 2026-07-27: baseline median / oracle median = 1.533748 from 5 baseline and 5 oracle runs, INTERLEAVED A/B in one session. Oracle values [1.277821048895357, 1.2779210097368356, 1.2681276407338593, 1.2747002931075853, 1.263267699635585], spread 0.014653 bpb (1.150%), cv 0.00508. Clears reward.md's 1.15 authoring floor; worst-case pairing under the observed spread is 1.526775. FROZEN constant; the oracle is NOT in the image and is NEVER run at scoring time.",
21
+ "ref_speedup_authoring_floor": 1.15,
22
+ "oracle_runs": 5,
23
+ "oracle_bpb_median": 1.2747002931075853,
24
+ "oracle_in_image": false,
25
+ "fail_closed": "when baseline_bpb or ref_speedup is absent / <= 1 / below the authoring floor the run is a HARD FAIL with reason `ref_speedup_invalid_or_missing`; it is NEVER silently treated as 1.0.",
26
+ "baseline_spread_abs": 0.03585226589985546,
27
+ "oracle_cv": 0.00507533872459635,
28
+ "oracle_spread_abs": 0.014653310101250705,
29
+ "ref_speedup_worst_case_pairing": 1.5267752785472517,
30
+ "hardware_and_data_caveat": "baseline_bpb=1.9550684328299388 与 ref_speedup=1.533747535323529 均在 H20 上、且在 task/environment/Dockerfile 里那份 WikiText-103-raw + SentencePiece-BPE-8192 语料上标定。 若你的 GPU 不是 H20,或重建语料的指纹(build 日志里打印的 tokenizer.model / train.bin sha256)与已知良好构建不一致,这两个常量就不再可比 —— 请按 recalibrate_howto 重新标定后再计分。 参考实现:强基线 task/solution/baseline_dense_floor/,oracle task/solution/oracle_grouped_moe/(reviewer-only,不进镜像)。",
31
+ "recalibrate_howto": {
32
+ "why": "reward = min(1, ln((baseline_bpb/val_bpb)/ref_speedup)/ln(ref_speedup)), 且 (baseline_bpb/val_bpb) <= ref_speedup 时为 0;两个常量是标定值,判分时只读、不重跑参考实现。",
33
+ "note": "计分路径故意不接受 VERIFIER_MODE(反作弊),因此重标定的做法是把参考实现挂成 candidate 来跑。",
34
+ "step1_baseline": "docker run --rm --gpus all --shm-size=8g -v \"$PWD/solution/baseline_dense_floor:/app/submission:ro\" -v \"$PWD/tests:/tests:ro\" fai/e2e-a3-moe-train-budget:oss bash /tests/test.sh",
35
+ "step2_oracle": "docker run --rm --gpus all --shm-size=8g -v \"$PWD/solution/oracle_grouped_moe:/app/submission:ro\" -v \"$PWD/tests:/tests:ro\" fai/e2e-a3-moe-train-budget:oss bash /tests/test.sh",
36
+ "step3_read": "从 /logs/verifier/benchmark_results.json 取 val_bpb(建议各跑 >=3 次取中位数)",
37
+ "step4_write": "写回本文件 reward_model.baseline_bpb = 强基线中位数;reward_model.ref_speedup = baseline_bpb / oracle 中位数",
38
+ "guard": "ref_speedup <= 1 或缺失 => 设计上 HARD FAIL 0;authoring floor 为 1.15"
39
+ }
40
+ },
41
+ "budget": {
42
+ "wallclock_sec": 600,
43
+ "kind": "WALL-CLOCK SECONDS of training (the fixed RESOURCE, not the metric). Enforced EXTERNALLY by tests/timer.sh: the training entry is started in its own session and the whole PROCESS GROUP is SIGTERM'd at the cap and SIGKILL'd 8 s later, so a detached background trainer cannot outlive the budget. Nothing is trusted from the candidate — no in-loop timer, no self-reported step or token count.",
44
+ "note": "The wall-clock is the resource under which MoE throughput becomes the lever: more optimizer steps in T => lower bpb."
45
+ },
46
+ "harness_seed": 1337,
47
+ "seed_policy": "The harness FIXES the training seed (not solver-selectable) -> kills the seed lottery. Formal scoring MAY run 3 harness seeds and take the median reward; single-shot validation uses the one fixed seed.",
48
+ "quality_gate": {
49
+ "param_floor": 150000000,
50
+ "param_floor_note": "The A3 CAPACITY FLOOR (the MoE-forcing constraint). The model MUST have >= param_floor TOTAL parameters, re-counted by the harness from the loaded module with weight-tie deduplication. At this capacity a DENSE model costs ~2*P_total FLOPs/token and is step-starved in T, while a sparse top-k MoE trains far more steps at the SAME total capacity — IF the sparsity is realized as real single-card throughput.",
51
+ "min_param_count": 1000000,
52
+ "min_plausible_val_bpb": 0.9,
53
+ "min_plausible_val_bpb_note": "ANTI-SPOOF / ANTI-CONTAMINATION floor, tightened from 0.50. No honest recipe trained from scratch inside this wall-clock budget at this capacity reaches 0.90 bpb on the held-out split (the demonstrated in-budget ceiling is ~1.22), so a value below the floor means a forged loss or held-out contamination, not a better model. Firing this check is reported as `anti_cheat_triggered`.",
54
+ "max_plausible_val_bpb": 3.0,
55
+ "ood_loss_ratio": 0.7,
56
+ "logits_position_variance_floor": 0.0001,
57
+ "logits_loss_agreement_tol": 0.05,
58
+ "expected_total_checks": 6,
59
+ "note": "capacity floor (A3 MoE-forcing) + anti-spoof kit lifted verbatim from the parameter-golf task family: a real LM scores real held-out text << arbitrary ids, forward(x,y) loss == CE(forward(x),y), logits vary across positions, >=1M params, val_bpb inside a plausibility band. A TRUNCATED suite (fewer than expected_total_checks) can never score above 0 (`gate_suite_incomplete`)."
60
+ },
61
+ "held_out": {
62
+ "corpus": "/tests/holdout_corpus.txt",
63
+ "identity": "canonical WikiText-103 TEST split (60 articles), uploaded FRESH at scoring and NOT baked into the image; disjoint from the baked train shard (/data/datasets/wikitext_bpe8k/train.bin) and from the solver's val monitor (/data/datasets/wikitext_bpe8k/val.bin = the WikiText-103 VALIDATION split)",
64
+ "eval": "stabilized median-of-3-shifted-passes, fp32 cross-entropy, bits-per-byte via SentencePiece byte-LUTs (parameter-golf eval machinery)"
65
+ },
66
+ "anti_tamper": {
67
+ "frozen_surface_fingerprint": "tests/test.sh sha256s EVERY file in /tests before launching the training and re-checks after it returns. Any content change => `anti_cheat_triggered` + `forbidden_edit_path`; any mode change or unexpected new file in /tests => `anti_cheat_triggered`.",
68
+ "quarantine": "/tests is chmod 0000 for the duration of the training phase so the held-out corpus and the calibrated constants are unreadable while the solver's code runs.",
69
+ "env_override_strip": "every E2E_*_OVERRIDE variable is unset before the scorer runs, so no environment variable on the scored path can influence the budget, the seed set or the frozen reward constants (a login shell sources ~/.bashrc, which the solver owns). The overrides remain usable by the author's calibration driver, which invokes compute_reward.py directly.",
70
+ "residual": "With training_uid set, a candidate cannot read /tests during its own run. Residual: the scoring harness itself and any interactive session are root, and the SOLVER's own iteration session (outside scoring) is root — but /tests does not exist in the image at all any more, so there is nothing to read there until scoring, when the drop is in force.",
71
+ "training_uid": 65534,
72
+ "training_uid_note": "The candidate's training entry runs as uid 65534 (nobody), NOT root. This is what makes the /tests quarantine real: chmod 0000 is ignored by uid 0, so without the drop a root solver could simply read the held-out corpus it is scored on and train on it. test.sh grants the unprivileged uid access to /app/submission (write), /app/repo and the training corpus (read) and to nothing else, and records the euid the training ACTUALLY ran under (observed_train_uid in metrics.json) rather than the intent. Set to null to disable.",
73
+ "timer_process_group": "tests/timer.sh starts the training in its OWN session (fork-then-setsid so setsid can never fail with EPERM) and signals the whole PROCESS GROUP at the cap, with a SELF-KILL GUARD that refuses to signal the harness's own group. MEASURED on NVIDIA H20 2026-07-27: without the guard, a silently-failed setsid put the training in the harness's group and the group kill took test.sh down right after the training finished — the run produced ZERO result files and looked like a training hang. The gate suite caught it; it is fixed and re-verified.",
74
+ "straggler_reaper": "After the wall-clock cap timer.sh kills the training's process group AND then every process owned by the unprivileged training uid. MEASURED 2026-07-28 with solution/probe_budget_bite: a group kill ALONE is insufficient, because a grandchild that calls setsid() itself lands in a new session the group kill never reaches — it outlived the budget, kept rewriting the scored checkpoint, and held the harness's log pipe open so the run HUNG instead of scoring. The uid-wide reaper reaches any descendant regardless of session; the training log is now written to a file rather than through a pipe a survivor could hold open."
75
+ },
76
+ "entry_contract": {
77
+ "training": "/app/submission/run_training.sh (harness env: SEED, PARAM_FLOOR, WALLCLOCK_SEC, OUT_CKPT, DATA_PATH, TOKENIZER_PATH, NANOGPT_REPO); must write $OUT_CKPT within the budget. DATA_PATH/TOKENIZER_PATH are PINNED by the harness, not inherited from the environment.",
78
+ "reload": "/app/submission/train_gpt.py :: load_model_for_verification(checkpoint_path, device) -> nn.Module or (args, model) honoring model(x)->logits (B,T,V) and model(x,y)->scalar CE loss (pure CE; any MoE auxiliary loss is a train-time side channel)"
79
+ },
80
+ "frozen_surface": [
81
+ "/tests/compute_reward.py",
82
+ "/tests/test.sh",
83
+ "/tests/holdout_corpus.txt",
84
+ "/tests/timer.sh",
85
+ "/tests/verifier-correctness-manifest.json"
86
+ ],
87
+ "compute_reward_sha256": "a482fd5ed86af2f906017d4539d64bad39e6d117840db052621e2ecd8422a85e",
88
+ "editable_area": "the whole /app/repo (nanoGPT) + /app/submission, minus the frozen surface"
89
+ }
tasks/e2e/a4-token-efficiency-budget/task/.dockerignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # build context is task/ ; never send the reviewer-only reference implementations or the
4
+ # grading suite (held-out corpus + calibrated anchors) into the docker build.
5
+ solution/
6
+ tests/
7
+ loop_overlay/
8
+ **/__pycache__/
9
+ **/*.pyc
10
+ *.bak_*
11
+ *.orig_*
12
+ Dockerfile.orig_private_base
tasks/e2e/a4-token-efficiency-budget/task/environment/Dockerfile ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # =============================================================================
3
+ # e2e-a4-token-efficiency-budget — OPEN-SOURCE, self-contained task image
4
+ #
5
+ # Task: reach the lowest held-out bits/byte within a FIXED 24M-token training budget.
6
+ # The agent edits /app/submission/train_gpt.py; the OPEN verifier under /tests
7
+ # trains it under a FIXED budget and scores held-out quality (bits/byte).
8
+ #
9
+ # FULLY PUBLIC — no internal mirror, no private base image, no prebuilt image.
10
+ # Platform: linux/amd64 ONLY (official torch wheels are manylinux x86_64).
11
+ # Build context = the task/ directory (this Dockerfile lives in task/environment/).
12
+ #
13
+ # -----------------------------------------------------------------------------
14
+ # BUILD (needs outbound network: PyPI + github.com + huggingface.co)
15
+ # cd <...>/a4-token-efficiency-budget/task
16
+ # docker build -f environment/Dockerfile -t fai/e2e-a4-token-efficiency-budget:oss .
17
+ # No GPU is needed to build. Building the corpus (below) takes ~15-30 min and the
18
+ # resulting image is ~10 GB (torch + CUDA base + the tokenised corpus).
19
+ # Non-H20 GPUs: pass your compute capability so self-built kernels target it:
20
+ # docker build --build-arg TORCH_CUDA_ARCH_LIST=8.0 ... # A100
21
+ # docker build --build-arg TORCH_CUDA_ARCH_LIST=8.9 ... # L40S / 4090
22
+ # docker build --build-arg TORCH_CUDA_ARCH_LIST=9.0 ... # H100 / H20 (default)
23
+ #
24
+ # RUN (needs 1 NVIDIA GPU, driver >= 535)
25
+ # docker run --rm --gpus all --shm-size=8g -it fai/e2e-a4-token-efficiency-budget:oss
26
+ #
27
+ # SCORE (inside the container; tests/ is MOUNTED, never baked into the image)
28
+ # docker run --rm --gpus all --shm-size=8g \
29
+ # -v "$PWD/tests:/tests:ro" fai/e2e-a4-token-efficiency-budget:oss bash /tests/test.sh # -> /logs/verifier/reward.json
30
+ #
31
+ # 🔴 RE-CALIBRATE THE FROZEN ANCHORS ON YOUR BUILD (read this before trusting a reward)
32
+ # reward = min(1.0, ln((baseline_bpb / your_val_bpb) / ref_speedup) / ln(ref_speedup))
33
+ # and 0 unless (baseline_bpb / your_val_bpb) > ref_speedup — you must BEAT the anchor
34
+ # with the FROZEN constants in tests/verifier-correctness-manifest.json:
35
+ # baseline_bpb = 1.7021411251584952 , ref_speedup = 1.204527530540146
36
+ # Both were measured on H20 **on the corpus built by the recipe below**. They are
37
+ # valid for YOUR build only if (a) the GPU matches and (b) the corpus reproduces.
38
+ # The scored path deliberately refuses VERIFIER_MODE (anti-cheat), so re-calibrate by
39
+ # scoring the SHIPPED reference recipes AS THE CANDIDATE:
40
+ # # 1) the strong baseline -> new baseline_bpb
41
+ # docker run --rm --gpus all --shm-size=8g \
42
+ # -v "$PWD/solution/strong_baseline:/app/submission:ro" \
43
+ # -v "$PWD/tests:/tests:ro" fai/e2e-a4-token-efficiency-budget:oss bash /tests/test.sh
44
+ # # 2) the oracle -> new oracle_bpb ; ref_speedup = baseline_bpb / oracle_bpb
45
+ # docker run --rm --gpus all --shm-size=8g \
46
+ # -v "$PWD/solution/ceiling:/app/submission:ro" \
47
+ # -v "$PWD/tests:/tests:ro" fai/e2e-a4-token-efficiency-budget:oss bash /tests/test.sh
48
+ # Read val_bpb from /logs/verifier/benchmark_results.json (median of >=3 runs) and write
49
+ # both numbers into tests/verifier-correctness-manifest.json -> reward_model.
50
+ # (ref_speedup <= 1 or missing => HARD FAIL 0 by design.)
51
+ #
52
+ # VERSION ANCHORS (reproduce the original runtime; see task.toml)
53
+ # CUDA 12.6 · Python 3.10 · torch 2.7.0 (cu126) · sentencepiece 0.2.1 · numpy>=1.26,<3
54
+ #
55
+ # WORKING TREE: /app/repo = nanoGPT + a vendored torchao package (~650 files)
56
+ # The original private base materialised this tree; the task package ships no vendored
57
+ # copy, so it is reconstructed here with `git clone` (nanoGPT for the training system,
58
+ # pytorch/ao for the low-precision ops). Both are pure Python at this layer, so the tree
59
+ # is a REAL directory (not a symlink) and edits inside it take effect directly — the
60
+ # symlink trick is only needed for packages with compiled extensions.
61
+ #
62
+ # The original private overlay is kept beside this file as Dockerfile.orig_private_base.
63
+ # =============================================================================
64
+ FROM nvidia/cuda:12.6.2-devel-ubuntu22.04
65
+
66
+ ARG TORCH_CUDA_ARCH_LIST="9.0"
67
+ ARG NANOGPT_REF="3adf61e154c3fe3fca428ad6bc3818b27a3b8291"
68
+ ARG TORCHAO_REF="v0.9.0"
69
+ ARG WIKITEXT_REPO="Salesforce/wikitext"
70
+ ARG WIKITEXT_CONFIG="wikitext-103-raw-v1"
71
+
72
+ ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \
73
+ PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1
74
+
75
+ RUN apt-get update && apt-get install -y --no-install-recommends \
76
+ build-essential gcc-10 g++-10 cmake ninja-build pkg-config \
77
+ python3.10 python3.10-dev python3.10-venv python3-pip python-is-python3 \
78
+ git git-lfs curl wget ca-certificates procps psmisc coreutils \
79
+ tar gzip unzip xz-utils vim less file jq tini \
80
+ && update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 \
81
+ && update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 100 \
82
+ && rm -rf /var/lib/apt/lists/*
83
+
84
+ # ---- venv. Keep this exact path: tests/test.sh pins /opt/kernelbench-venv/bin ----
85
+ ENV VENV=/opt/kernelbench-venv
86
+ RUN python3.10 -m venv "$VENV"
87
+ ENV PATH=$VENV/bin:/usr/local/cuda/bin:$PATH \
88
+ TORCH_CUDA_ARCH_LIST=${TORCH_CUDA_ARCH_LIST} \
89
+ PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
90
+ TORCH_EXTENSIONS_DIR=/app/.cache/torch_extensions
91
+ RUN pip install --no-cache-dir -U pip setuptools wheel
92
+
93
+ # ---- DL stack + the exact support libraries the training path imports, from PUBLIC indexes ----
94
+ RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cu126 \
95
+ "torch==2.7.0" \
96
+ && python -c "import torch; assert torch.__version__.startswith('2.7.0'), torch.__version__; print('torch', torch.__version__)"
97
+ RUN printf 'torch==2.7.0\n' > /tmp/constraints.txt \
98
+ && pip install --no-cache-dir --constraint /tmp/constraints.txt \
99
+ "sentencepiece==0.2.1" "pyarrow==17.0.0" "numpy>=1.26,<3" "einops==0.8.0" \
100
+ "tqdm==4.66.5" "psutil" "huggingface_hub>=0.24,<1" \
101
+ && python -c "import torch; assert torch.__version__.startswith('2.7.0'), torch.__version__"
102
+
103
+ # ---- /app/repo: the nanoGPT training system + a vendored torchao package.
104
+ # Pinned by ARG so a future user can move either ref without editing this file.
105
+ # No `|| true` anywhere: a silently empty /app/repo would destroy the task. ----
106
+ RUN set -eu; \
107
+ mkdir -p /app/repo; cd /app/repo; git init -q; \
108
+ git remote add origin https://github.com/karpathy/nanoGPT.git; \
109
+ git fetch -q --depth 1 origin "${NANOGPT_REF}"; \
110
+ git checkout -q FETCH_HEAD; \
111
+ rm -rf /app/repo/.git /app/repo/assets; \
112
+ git clone --depth 1 --branch "${TORCHAO_REF}" https://github.com/pytorch/ao.git /tmp/ao; \
113
+ mv /tmp/ao/torchao /app/repo/torchao; \
114
+ rm -rf /tmp/ao; \
115
+ for m in /app/repo/model.py /app/repo/train.py /app/repo/configurator.py /app/repo/bench.py; do \
116
+ test -f "$m" || { echo "BUILD_ASSERT_FATAL: /app/repo marker missing: $m"; exit 1; }; \
117
+ done; \
118
+ test -f /app/repo/torchao/__init__.py || { echo "BUILD_ASSERT_FATAL: torchao package missing"; exit 1; }; \
119
+ n=$(find /app/repo -type f -not -path '*/.git/*' | wc -l); \
120
+ echo "[build] /app/repo non-.git file count = $n (original base shipped ~650)"; \
121
+ test "$n" -ge 300 || { echo "BUILD_ASSERT_FATAL: /app/repo has only $n files - clone mutilated"; exit 1; }; \
122
+ t=$(find /app/repo -maxdepth 2 -type f -not -path '*/torchao/*' | wc -l); \
123
+ test "$t" -ge 15 || { echo "BUILD_ASSERT_FATAL: only $t nanoGPT top-level files (<15)"; exit 1; }; \
124
+ python -c 'import sys;sys.path.insert(0,"/app/repo");import model;print("[build] nanoGPT import OK",model.__file__)'
125
+
126
+ # ---- THE CORPUS. The original private base shipped /data/datasets/wikitext_bpe8k/{train,val}.bin
127
+ # and /data/tokenizers/wikitext_bpe8k.model as opaque blobs. Shipping them in a public task
128
+ # package is not an option (hundreds of MB), so they are REBUILT here from the public
129
+ # WikiText-103-raw dataset with a deterministic recipe: fixed source revision, fixed
130
+ # SentencePiece BPE settings (vocab 8192 -> fits uint16), single thread, no input shuffle.
131
+ # The frozen reward anchors were calibrated on this corpus; the fingerprints printed at the
132
+ # end let you confirm your rebuild matches (if it does not, re-calibrate — see the header).
133
+ RUN python - <<'PY'
134
+ import hashlib, os, pathlib, sys
135
+ import numpy as np, pyarrow.parquet as pq, sentencepiece as spm
136
+ from huggingface_hub import snapshot_download
137
+
138
+ REPO = os.environ.get("WIKITEXT_REPO", "Salesforce/wikitext")
139
+ CFG = os.environ.get("WIKITEXT_CONFIG", "wikitext-103-raw-v1")
140
+ DATA, TOK = "/data/datasets/wikitext_bpe8k", "/data/tokenizers"
141
+ os.makedirs(DATA, exist_ok=True); os.makedirs(TOK, exist_ok=True)
142
+ EOS = 2
143
+
144
+ local = snapshot_download(repo_id=REPO, repo_type="dataset", allow_patterns=[f"{CFG}/*"])
145
+ root = pathlib.Path(local, CFG)
146
+
147
+ def split(name):
148
+ files = sorted(root.glob(f"{name}-*.parquet")) or sorted(root.glob(f"*{name}*.parquet"))
149
+ if not files:
150
+ sys.exit(f"BUILD_ASSERT_FATAL: no parquet for split {name!r} under {root}")
151
+ out = []
152
+ for f in files:
153
+ out.extend(pq.read_table(f).column("text").to_pylist())
154
+ return out
155
+
156
+ train, val = split("train"), split("validation")
157
+ print(f"[corpus] raw lines: train={len(train)} val={len(val)}")
158
+
159
+ spm_in = "/tmp/spm_input.txt"
160
+ with open(spm_in, "w", encoding="utf-8") as fh:
161
+ for line in train:
162
+ line = line.strip()
163
+ if line:
164
+ fh.write(line + "\n")
165
+
166
+ spm.SentencePieceTrainer.train(
167
+ input=spm_in, model_prefix=f"{TOK}/wikitext_bpe8k",
168
+ vocab_size=8192, model_type="bpe", character_coverage=0.9995,
169
+ input_sentence_size=2000000, shuffle_input_sentence=False,
170
+ num_threads=1, seed_sentencepiece_size=1000000,
171
+ unk_id=0, bos_id=1, eos_id=2, pad_id=-1,
172
+ )
173
+ os.remove(spm_in)
174
+ sp = spm.SentencePieceProcessor(model_file=f"{TOK}/wikitext_bpe8k.model")
175
+ assert sp.get_piece_size() == 8192, sp.get_piece_size()
176
+
177
+ def encode(lines, out, chunk=20000, flush=8_000_000):
178
+ total, buf = 0, []
179
+ with open(out, "wb") as fh:
180
+ for i in range(0, len(lines), chunk):
181
+ batch = [t.strip() for t in lines[i:i + chunk] if t.strip()]
182
+ if not batch:
183
+ continue
184
+ for ids in sp.encode(batch):
185
+ buf.extend(ids); buf.append(EOS)
186
+ if len(buf) >= flush:
187
+ np.asarray(buf, dtype=np.uint16).tofile(fh); total += len(buf); buf = []
188
+ if buf:
189
+ np.asarray(buf, dtype=np.uint16).tofile(fh); total += len(buf)
190
+ return total
191
+
192
+ n_tr = encode(train, f"{DATA}/train.bin")
193
+ n_va = encode(val, f"{DATA}/val.bin")
194
+ print(f"[corpus] tokens: train={n_tr:,} val={n_va:,}")
195
+ if n_tr < 30_000_000:
196
+ sys.exit(f"BUILD_ASSERT_FATAL: train corpus only {n_tr} tokens - the graded token budget needs more")
197
+ if n_va < 100_000:
198
+ sys.exit(f"BUILD_ASSERT_FATAL: val corpus only {n_va} tokens")
199
+
200
+ def sha(p, cap=None):
201
+ h = hashlib.sha256()
202
+ with open(p, "rb") as fh:
203
+ h.update(fh.read() if cap is None else fh.read(cap))
204
+ return h.hexdigest()
205
+
206
+ print("[corpus] FINGERPRINTS (compare against a known-good build before trusting the anchors)")
207
+ print(" tokenizer.model sha256 =", sha(f"{TOK}/wikitext_bpe8k.model"))
208
+ print(" train.bin first 1MiB sha256 =", sha(f"{DATA}/train.bin", 1 << 20))
209
+ print(" val.bin sha256 =", sha(f"{DATA}/val.bin"))
210
+ print(" train tokens =", n_tr, "| val tokens =", n_va)
211
+ PY
212
+
213
+ # ---- solver-owned submission: the working-but-beatable STARTER (not the answer) ----
214
+ RUN rm -rf /app/submission && mkdir -p /app/submission /app/.cache/torch_extensions /logs/verifier /logs/artifacts /app/.timer
215
+ COPY environment/submission/train_gpt.py /app/submission/train_gpt.py
216
+ COPY instruction.md /app/instruction.md
217
+
218
+ # ---- git baseline for the editable tree: ONE commit as the diff base, no remote, no reflog ----
219
+ RUN git config --global user.email "reviewer@fai-bench.local" \
220
+ && git config --global user.name "fai-bench" \
221
+ && git config --global init.defaultBranch main \
222
+ && git config --global --add safe.directory /app/repo \
223
+ && git config --global --add safe.directory /app/submission \
224
+ && cd /app/repo \
225
+ && printf '__pycache__/\n*.pyc\nmodel_ckpt.pt\n*.tmp\n' > /app/repo/.gitignore \
226
+ && git init -q . \
227
+ && git add -A && git commit -qm "nanoGPT baseline system" \
228
+ && rm -rf /app/repo/.git/logs \
229
+ && test "$(git rev-list --count HEAD)" = "1" \
230
+ && test -z "$(git remote)" \
231
+ && test ! -e /app/repo/.git/logs \
232
+ && echo "[build] /app/repo: fresh 1-commit git, no remote, no reflog"
233
+
234
+ # ---- OPEN grading suite is NOT baked into the image (by design).
235
+ # tests/ (test.sh + compute_reward.py + the held-out corpus + the frozen manifest carrying
236
+ # baseline_bpb / ref_speedup) is MOUNTED FRESH at /tests when scoring. It ships in this
237
+ # package — open-source, but deliberately outside the image so the solver can neither read
238
+ # the held-out text nor the calibrated anchors while solving.
239
+
240
+ # ---- ANTI-LEAK ASSERTS: the anchors and the held-out surface must NOT be visible to the
241
+ # solver. Any regression that re-introduces them dies here, at build time. ----
242
+ RUN set -eu; rc=0; \
243
+ for p in /opt/verifier /opt/strong_baseline /opt/naive /opt/negative /opt/ceiling \
244
+ /opt/oracle /opt/solution /app/solution /app/tests; do \
245
+ if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: leak path present: $p"; rc=1; fi; \
246
+ done; \
247
+ if [ -d /tests ] && [ -n "$(find /tests -mindepth 1 -type f 2>/dev/null | head -1)" ]; then \
248
+ echo "BUILD_ASSERT_FAIL: /tests contains baked files"; rc=1; \
249
+ fi; \
250
+ for f in verifier-correctness-manifest.json compute_reward.py; do \
251
+ hits=$(find / -xdev -name "$f" -not -path '/proc/*' -not -path '/sys/*' 2>/dev/null | head -3); \
252
+ if [ -n "$hits" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface file baked: $hits"; rc=1; fi; \
253
+ done; \
254
+ if grep -rslE 'ref_speedup|baseline_bpb|strong_baseline_bpb' /app 2>/dev/null | head -3 | grep -q .; then \
255
+ echo "BUILD_ASSERT_FAIL: a calibrated anchor token is visible under /app"; rc=1; \
256
+ fi; \
257
+ test "$rc" = 0; \
258
+ echo "[build] ANTI-LEAK ASSERTS PASS: no frozen surface, no reference recipe, no anchor under /app"
259
+
260
+ # ---- runtime contract: entrypoint + elapsed-time daemon ----
261
+ RUN printf '#!/bin/bash\nset -e\nmkdir -p /app/.timer\nnohup /app/timer.sh >/app/.timer/timer.log 2>&1 &\nif [ "$#" -gt 0 ]; then exec "$@"; fi\nexec /bin/bash -l\n' > /app/entrypoint.sh \
262
+ && chmod +x /app/entrypoint.sh \
263
+ && printf '#!/bin/bash\nmkdir -p /app/.timer\nSTART=$(date +%%s)\nwhile true; do echo $(( $(date +%%s) - START )) > /app/.timer/elapsed; sleep 5; done\n' > /app/timer.sh \
264
+ && chmod 755 /app/timer.sh
265
+
266
+ ENV NANOGPT_REPO=/app/repo \
267
+ PYTHONPATH=/app/repo \
268
+ SUBMISSION_DIR=/app/submission \
269
+ REPO_DIR=/app/repo \
270
+ DATA_PATH=/data/datasets/wikitext_bpe8k \
271
+ TOKENIZER_PATH=/data/tokenizers/wikitext_bpe8k.model \
272
+ LD_LIBRARY_PATH=/opt/kernelbench-venv/lib/python3.10/site-packages/torch/lib:/usr/local/cuda/lib64:/usr/local/nvidia/lib64
273
+ WORKDIR /app
274
+
275
+ # ---- build-time smoke.
276
+ # HARD: torch pin, nanoGPT + torchao import, the corpus is present and readable as
277
+ # uint16, the tokenizer loads with 8192 pieces, the starter entry exists,
278
+ # /app/repo has exactly one commit.
279
+ # SOFT: nothing GPU-dependent is asserted (the build host has no card).
280
+ RUN python - <<'PY'
281
+ import os, subprocess, sys
282
+ import numpy as np, torch, sentencepiece as spm
283
+ sys.path.insert(0, "/app/repo")
284
+ print("torch", torch.__version__)
285
+ assert torch.__version__.startswith("2.7.0"), torch.__version__
286
+ import model as nanogpt_model, torchao
287
+ print("nanoGPT", nanogpt_model.__file__, "| torchao", torchao.__file__)
288
+
289
+ d = np.memmap("/data/datasets/wikitext_bpe8k/train.bin", dtype=np.uint16, mode="r")
290
+ v = np.memmap("/data/datasets/wikitext_bpe8k/val.bin", dtype=np.uint16, mode="r")
291
+ print("corpus tokens: train", f"{d.size:,}", "| val", f"{v.size:,}", "| max id", int(d[:1_000_000].max()))
292
+ assert d.size > 30_000_000 and v.size > 100_000
293
+ sp = spm.SentencePieceProcessor(model_file="/data/tokenizers/wikitext_bpe8k.model")
294
+ assert sp.get_piece_size() == 8192
295
+
296
+ for f in ("/app/submission/train_gpt.py",):
297
+ assert os.path.isfile(f), f"submission entry missing: {f}"
298
+ n = subprocess.run(["git", "-C", "/app/repo", "rev-list", "--count", "HEAD"],
299
+ capture_output=True, text=True).stdout.strip()
300
+ assert n == "1", f"git diff base broken (commits={n!r})"
301
+ print("OK: env, working tree, corpus and starter all in place")
302
+ PY
303
+
304
+ ENTRYPOINT ["/app/entrypoint.sh"]
305
+ CMD ["tail","-f","/dev/null"]
tasks/e2e/a4-token-efficiency-budget/task/environment/Dockerfile.loop16 ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # =============================================================================
3
+ # e2e-a4-token-efficiency-budget — OPEN-SOURCE **loop16** overlay
4
+ #
5
+ # THIS is the form the published scores were produced with. The task's original graded image
6
+ # was e2e-a4-token-efficiency-budget:v3-deleak-loop16 — a 16-round self-improvement protocol,
7
+ # not a single shot. environment/Dockerfile builds the SINGLE-SHOT base; this file adds the
8
+ # /opt/loop harness on top, exactly as the private overlay did (its recipe is preserved beside
9
+ # this file as environment/loop_overlay/Dockerfile).
10
+ #
11
+ # Pick the form you want:
12
+ # * single shot -> environment/Dockerfile (one submission, scored by /tests)
13
+ # * 16 rounds -> this file (matches the reported leaderboard runs)
14
+ # The GRADED surface is identical in both: /tests is mounted fresh and nothing here touches
15
+ # compute_reward.py, the held-out corpus or the calibrated anchors.
16
+ #
17
+ # -----------------------------------------------------------------------------
18
+ # BUILD (two steps — this is an overlay, exactly like the original)
19
+ # cd <...>/a4-token-efficiency-budget/task
20
+ # docker build -f environment/Dockerfile -t fai/e2e-a4-token-efficiency-budget:oss .
21
+ # docker build -f environment/Dockerfile.loop16 -t fai/e2e-a4-token-efficiency-budget:oss-loop16 .
22
+ # (override the base with --build-arg BASE_IMAGE=... if you tagged it differently)
23
+ #
24
+ # RUN docker run --rm --gpus all --shm-size=8g -it fai/e2e-a4-token-efficiency-budget:oss-loop16
25
+ # # in-session, per round: bash /opt/loop/submit.sh
26
+ # # when done: bash /opt/loop/submit.sh --finalize
27
+ #
28
+ # SCORE (unchanged; tests/ is MOUNTED, never baked)
29
+ # docker run --rm --gpus all --shm-size=8g \
30
+ # -v "$PWD/tests:/tests:ro" fai/e2e-a4-token-efficiency-budget:oss-loop16 bash /tests/test.sh
31
+ #
32
+ # WHAT THE HARNESS IS (and what it deliberately is NOT)
33
+ # /opt/loop/submit.sh solver-callable: score the current state, get sanitised feedback;
34
+ # --finalize plants the best-of-k snapshot and ends the loop.
35
+ # /opt/loop/score_engine.sh the in-session DEV proxy scorer. Trains the candidate recipe on a
36
+ # SMALL PUBLIC token shard (3M vs the graded 24M) sliced from the
37
+ # /data/datasets/wikitext_bpe8k the solver already has, under the
38
+ # same uid-65534 drop the graded path uses, and reports an ABSOLUTE
39
+ # public-proxy val_bpb.
40
+ # /opt/loop/private/manifest.json dev-only constants (dev seed 1234 — distinct from every
41
+ # graded seed; dev token budget; the same param [floor, cap] the
42
+ # graded scorer re-counts).
43
+ # /opt/loop/baseline_submission/ the pristine shipped starter, kept so --finalize can restore it.
44
+ # It carries NO held-out corpus, NO reference recipe and NO calibrated anchor: the per-round
45
+ # signal is an absolute public-proxy val_bpb, never normalised against baseline_bpb/ref_speedup.
46
+ # Because the budget is TOKENS (not wall-clock), the proxy is node-speed-immune, which is what
47
+ # makes a stable per-round signal possible for this task.
48
+ #
49
+ # Modes/ownership are root 0700/0600 for score_engine.sh, sanitize_feedback.py, private/ and
50
+ # baseline_submission/ — mirroring both the private overlay's stated red-line and the modes
51
+ # observed in the shipped sibling images. NOTE this is a structural convention, not a security
52
+ # boundary: when the session runs as uid 0, root-0700 is readable. The real protection is that
53
+ # the reference recipe and the anchors are NOT IN THIS IMAGE AT ALL.
54
+ # =============================================================================
55
+ ARG BASE_IMAGE=fai/e2e-a4-token-efficiency-budget:oss
56
+ FROM ${BASE_IMAGE}
57
+ SHELL ["/bin/bash","-c"]
58
+
59
+ # ---- the base must not already carry /opt/loop: a layer union over an existing tree would let
60
+ # stale content show through (the original overlay asserted the same thing). ----
61
+ RUN test ! -e /opt/loop || { echo "BUILD_ASSERT_FAIL: base already has /opt/loop"; exit 1; }
62
+
63
+ COPY environment/loop_overlay/opt_loop/ /opt/loop/
64
+ COPY environment/loop_overlay/instruction_loop16.md /app/instruction.md
65
+
66
+ RUN chown -R root:root /opt/loop \
67
+ && chmod 0755 /opt/loop \
68
+ && chmod 0755 /opt/loop/submit.sh \
69
+ && chmod 0700 /opt/loop/score_engine.sh \
70
+ && chmod 0700 /opt/loop/sanitize_feedback.py \
71
+ && chmod -R go-rwx /opt/loop/private /opt/loop/baseline_submission \
72
+ && chmod 0700 /opt/loop/private /opt/loop/baseline_submission \
73
+ && find /opt/loop/private /opt/loop/baseline_submission -type f -exec chmod 0600 {} \; \
74
+ && find /opt/loop/private /opt/loop/baseline_submission -type d -exec chmod 0700 {} \; \
75
+ && chmod 0644 /app/instruction.md \
76
+ && echo "[build] /opt/loop staged with the overlay's declared ownership/modes"
77
+
78
+ # ---- 🔴 the original overlay's two regression tripwires, preserved verbatim in intent:
79
+ # (1) no calibrated anchor VALUE may appear anywhere under /opt/loop — prose that NAMES
80
+ # baseline_bpb / ref_speedup to explain their ABSENCE is fine, a NUMBER is not;
81
+ # (2) no old-protocol token (the 3-16 / min_submissions=3 wording) may survive.
82
+ # NOTE: no inline `#` inside this RUN — shell-form RUN joins the \-continued lines into ONE
83
+ # command, where a `#` would comment out everything after it. ----
84
+ RUN set -eu; rc=0; \
85
+ if grep -rIEq "1\.70214|1\.7034|1\.20452|1\.41311|1\.4094|1\.4131" /opt/loop; then \
86
+ echo "BUILD_ASSERT_FAIL: calibrated anchor VALUE present in /opt/loop"; rc=1; fi; \
87
+ if grep -rIEq "3-16|3 consecutive|min_submissions[ =]*3|MIN_SUB(MISSIONS)?=3" /opt/loop /app/instruction.md; then \
88
+ echo "BUILD_ASSERT_FAIL: old-protocol token present"; rc=1; fi; \
89
+ test -f /opt/loop/submit.sh && test -x /opt/loop/submit.sh || { echo "BUILD_ASSERT_FAIL: submit.sh missing or not executable"; rc=1; }; \
90
+ test -f /opt/loop/private/manifest.json || { echo "BUILD_ASSERT_FAIL: dev manifest missing"; rc=1; }; \
91
+ test -f /opt/loop/baseline_submission/train_gpt.py || { echo "BUILD_ASSERT_FAIL: pristine starter missing"; rc=1; }; \
92
+ for p in /tests /opt/verifier /opt/strong_baseline /opt/negative /opt/ceiling; do \
93
+ if [ -e "$p" ]; then echo "BUILD_ASSERT_FAIL: frozen-surface path present: $p"; rc=1; fi; \
94
+ done; \
95
+ if find /opt/loop -type f -name '*.patch' | grep -q .; then \
96
+ echo "BUILD_ASSERT_FAIL: a patch file is baked under /opt/loop"; rc=1; fi; \
97
+ test "$rc" = 0; \
98
+ echo "[build] loop16 overlay asserts PASS: no anchor value, no stale protocol wording, no reference impl"
99
+
100
+ # /logs/loop is created world-writable at runtime by submit.sh — nothing to bake.
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/Dockerfile ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # -loop16 overlay for e2e-a4-token-efficiency-budget.
3
+ # FROM the de-leaked single-shot base image; add /opt/loop/ (submit + score_engine + sanitize +
4
+ # private dev-training proxy + baked pristine starter) and swap /app/instruction.md for the
5
+ # loop16 combined statement. Pure additive layer — NO dependency change, NO change to /tests,
6
+ # compute_reward.py, or ANY graded code path. The overlay is preferably applied with
7
+ # `crane append` (~8s, zero GPU); this Dockerfile is the docker-build fallback and the
8
+ # authoritative description of what the layer contains.
9
+ #
10
+ # 🔴 Structural red-line enforcement (modes MUST also be baked into the crane tar header, since
11
+ # `crane append` runs no RUN): submit.sh 0755 root; score_engine.sh + sanitize_feedback.py +
12
+ # everything under /opt/loop/private/ + /opt/loop/baseline_submission/ is 0700/0600 root
13
+ # (unreadable by the solver's dropped uid). The private dir carries NO held-out corpus, NO
14
+ # reference recipe and NO calibrated anchor — only public dev-proxy constants.
15
+ ARG BASE_IMAGE=<internal registry>/kernelbench/e2e-a4-token-efficiency-budget:v3-deleak@sha256:28bbf1300c4cd9123faf5c66f4fa74c4347437f622d8094e0431c14121af3145
16
+ FROM ${BASE_IMAGE}
17
+ SHELL ["/bin/bash","-c"]
18
+
19
+ # assert the base has NO /opt/loop (crane append is a layer union; overlaying an existing
20
+ # /opt/loop would let stale content show through).
21
+ RUN test ! -e /opt/loop || { echo "BUILD_ASSERT_FAIL: base already has /opt/loop"; exit 1; }
22
+
23
+ # bake the /opt/loop tree
24
+ COPY opt_loop/ /opt/loop/
25
+
26
+ # swap in the loop16 combined instruction (the runner ships /app/instruction.md)
27
+ COPY instruction_loop16.md /app/instruction.md
28
+
29
+ # ownership + modes: root-owned; the solver runs unprivileged, so 0700/0600 are structurally
30
+ # unreadable to it.
31
+ RUN chown -R root:root /opt/loop \
32
+ && chmod 0755 /opt/loop \
33
+ && chmod 0755 /opt/loop/submit.sh \
34
+ && chmod 0700 /opt/loop/score_engine.sh \
35
+ && chmod -R go-rwx /opt/loop/private /opt/loop/baseline_submission \
36
+ && chmod 0700 /opt/loop/private /opt/loop/baseline_submission \
37
+ && find /opt/loop/private /opt/loop/baseline_submission -type f -exec chmod 0600 {} \; \
38
+ && find /opt/loop/private /opt/loop/baseline_submission -type d -exec chmod 0700 {} \; \
39
+ && chmod 0644 /app/instruction.md
40
+
41
+ # /logs/loop is created world-writable at runtime by submit.sh; nothing to bake.
42
+
43
+ # 🔴 build-time assert: the overlay must carry NO calibrated anchor VALUE and NO old-protocol
44
+ # token. (Prose that NAMES baseline_bpb/ref_speedup to explain their ABSENCE is fine; a VALUE is
45
+ # not.) Fails the build if a regression re-introduces either.
46
+ RUN set -eu; rc=0; \
47
+ if grep -rIEq "1\.70214|1\.7034|1\.20452|1\.41311|1\.4094|1\.4131" /opt/loop; then \
48
+ echo "BUILD_ASSERT_FAIL: calibrated anchor VALUE present in /opt/loop"; rc=1; fi; \
49
+ if grep -rIEq "3-16|3 consecutive|min_submissions[ =]*3|MIN_SUB(MISSIONS)?=3" /opt/loop /app/instruction.md; then \
50
+ echo "BUILD_ASSERT_FAIL: old-protocol token present"; rc=1; fi; \
51
+ test -f /opt/loop/submit.sh && test -x /opt/loop/submit.sh || { echo "submit.sh missing/not exec"; rc=1; }; \
52
+ test "$rc" = 0 && echo "[build] loop16 overlay asserts PASS"
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/instruction_loop16.md ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Train the best language model you can from a FIXED NUMBER OF TRAINING TOKENS
2
+
3
+ You are given the full [nanoGPT](https://github.com/karpathy/nanoGPT) training system at
4
+ `/app/repo` (fully editable) and a tokenized WikiText-103 corpus. Your job is to **train the
5
+ best language model you can on ONE H20 GPU while consuming no more than a fixed budget of
6
+ training tokens**, then let the grader score it.
7
+
8
+ The grader then loads the checkpoint your training produced and measures its
9
+ **bits-per-byte (`val_bpb`) on a held-out WikiText-103 split you never see**. **Lower
10
+ `val_bpb` is better.**
11
+
12
+ ## How you are scored
13
+
14
+ Scoring is **bounded between 0.0 and 1.0**, and it is measured against **the starting recipe you
15
+ were given**:
16
+
17
+ - The provided starter is a **well-tuned AdamW** recipe at this token budget. It is a real,
18
+ complete, working recipe — and it is the bar. **Submitting it, or anything that does not
19
+ strictly improve on its held-out `val_bpb`, scores 0.**
20
+ - Beyond that, your score rises **continuously** with how much of the achievable `val_bpb` gap
21
+ you close. Reaching the quality of a strong reference recipe measured at this same token
22
+ budget scores **0.5**; pushing further keeps earning more, up to the 1.0 ceiling. Coming
23
+ close to the starter without passing it earns nothing — you have to actually beat it.
24
+ - Any hard-gate failure — over the parameter cap, a missing checkpoint, byte-identical weights
25
+ across seeds, a degenerate or forged-loss model, or touching the grader's files — scores
26
+ **0**, whatever the `val_bpb`.
27
+
28
+ So a mediocre-but-safe re-tune of the starter is worth exactly as much as no submission at all.
29
+ The whole game is pushing `val_bpb` as low as you can inside the token budget.
30
+
31
+ ## The budget is TOKENS, not time — read this carefully
32
+
33
+ This is what makes this task different from a throughput task:
34
+
35
+ - The grader **counts the training tokens your run consumes** and enforces a hard cap. The
36
+ count is taken by the grader from outside your process; it is not a number your code
37
+ reports.
38
+ - **Wall-clock is NOT the budget and speed earns you NOTHING here.** Making your training
39
+ step faster — mixed precision, `torch.compile`, a bigger batch, a faster data loader,
40
+ fusing kernels — does not let you consume more tokens, so it cannot improve your score.
41
+ (A generous wall-clock ceiling exists purely as a feasibility guard; see *Limits* below.)
42
+ - Therefore the only way to a lower loss is to **extract more learning from each token** —
43
+ i.e. real **sample efficiency**.
44
+
45
+ ## Why this is hard
46
+
47
+ The starting recipe is already a **well-tuned AdamW baseline** (tuned peak LR, warmup +
48
+ trapezoidal decay, gradient clipping, a batch size chosen at this token budget). The shallow
49
+ configuration wins are already taken: sweeping the batch size or the learning rate around this
50
+ point does **not** help — the reference was selected as the best of such a sweep. To beat it
51
+ you need to change **what the training algorithm actually is**, for example:
52
+
53
+ - **the optimizer / update rule** — e.g. spectral / orthogonalized updates for the hidden
54
+ weight matrices (the `Muon` family), second-order-flavoured preconditioning, per-layer
55
+ update scaling, or a different treatment of embeddings vs hidden layers vs the head;
56
+ - **the architecture** — normalization placement and type, rotary vs learned positions,
57
+ query/key normalization, the MLP nonlinearity, initialization scale (including zero-init of
58
+ residual projections), weight tying, skip/residual structure, logit scaling or softcapping;
59
+ - **the data schedule** — the order, packing, sequence length, and curriculum of the tokens
60
+ you spend, and how the batch size or LR schedule co-varies with it;
61
+ - **the loss / regularization** — auxiliary losses, weight-decay discipline, label smoothing.
62
+
63
+ Public references are fair game: the nanoGPT repo, the
64
+ [modded-nanogpt speedrun](https://github.com/KellerJordan/modded-nanogpt) and its record
65
+ history, the [Muon writeup](https://kellerjordan.github.io/posts/muon/), and the general
66
+ literature on optimizers, architectures and training schedules. **What is protected is the
67
+ grader's measurement, not the method** — reproducing a known good recipe is expected to score
68
+ well, and pushing past it is what earns a high score.
69
+
70
+ ## Data
71
+
72
+ - Train on the token shard the grader hands you at `DATA_PATH` (flat `uint16`, nanoGPT
73
+ layout). In your own session `/data/datasets/wikitext_bpe8k/train.bin` is available so you
74
+ can develop and iterate; at scoring `DATA_PATH` points at the budgeted shard instead.
75
+ - `/data/datasets/wikitext_bpe8k/val.bin` is your **local progress monitor** (the WikiText-103
76
+ *validation* split). The grader scores on the held-out *test* split — same distribution, so
77
+ your local measurement tracks the grader's within a small margin.
78
+ - Tokenizer: SentencePiece **BPE-8K** at `/data/tokenizers/wikitext_bpe8k.model`
79
+ (`vocab_size = 8192`).
80
+ - The corpus bytes are checksum-pinned by the grader, and the scored shard is cut from them.
81
+ Training on anything else — other data, generated data, or a modified copy — is a hard
82
+ failure.
83
+
84
+ ## What to submit (the entry contract)
85
+
86
+ Everything the grader needs must live under `/app/submission/`, and the grader calls **two
87
+ functions** in `/app/submission/train_gpt.py`:
88
+
89
+ 1. **`train_for_budget(seed, out_dir, budget_seconds)`** — your training entry. The grader
90
+ calls it once per scored seed and requires it to write a checkpoint to
91
+ `<out_dir>/model_ckpt.pt`. Save periodically: the grader stops you if you exceed the
92
+ wall-clock guard, and the latest saved checkpoint is what gets scored.
93
+ - The grader sets `DATA_PATH` in the environment to **your token budget** — a shard
94
+ containing *exactly* `TOKEN_BUDGET` tokens. **During scoring this shard is the only
95
+ readable token source** (the full corpus is locked for the duration of the run), so the
96
+ budget is enforced by construction rather than by trusting a counter. `SEED`,
97
+ `TOKEN_BUDGET`, `MAX_WALLCLOCK_SEC`, `MAX_PARAMS`, `TOKENIZER_PATH` and `NANOGPT_REPO`
98
+ are also in the environment.
99
+ - You may read the shard in **any order, packing, sequence length or curriculum**, and you
100
+ may pass over it more than once — the budget is the *number of tokens made available*,
101
+ and how you spend them is a lever. (Repeating tokens invites memorisation, which the
102
+ held-out score punishes; that trade-off is yours to make.)
103
+ - It is run from an isolated working directory that contains a copy of your **source**
104
+ files only. Model-weight blobs are not carried over, and training happens fresh every
105
+ time — so the checkpoint must be produced by this call.
106
+ 2. **`load_model_for_verification(checkpoint_path, device)`** — returns either an `nn.Module`
107
+ or `(args, model)`. The loaded model's `forward` must satisfy:
108
+ - `model(input_ids)` → floating-point logits `(batch, seq_len, vocab_size)` that depend on
109
+ token position;
110
+ - `model(input_ids, target_ids)` → a **scalar** loss equal (within a small tolerance) to
111
+ `F.cross_entropy(logits.reshape(-1, V), target_ids.reshape(-1))` on those same logits.
112
+
113
+ A working starting `train_gpt.py` (the tuned AdamW reference on nanoGPT's model, implementing
114
+ both functions) is provided — it is a starting point, **not** a contract. You may replace all
115
+ of it, and you may edit the nanoGPT source in `/app/repo` your recipe imports.
116
+
117
+ ## Limits (all enforced by the grader — disclosed so nothing surprises you)
118
+
119
+ - **Token budget** — the hard cap named in `TOKEN_BUDGET`, counted by the grader. Exceeding it
120
+ scores 0.
121
+ - **Parameter cap** — the grader re-counts the parameters of your loaded model and enforces the
122
+ cap named in `MAX_PARAMS`. This is why "just make the model enormous" is not the answer; you
123
+ must get more out of each token at a comparable model scale. There is also a minimum
124
+ parameter count, so a degenerate tiny model cannot pass.
125
+ - **Wall-clock ceiling** — `MAX_WALLCLOCK_SEC` is a *feasibility guard*, not the budget. It is
126
+ set generously (well above what the reference recipe needs) so that a slower-but-smarter
127
+ recipe is never penalised; a run that exceeds it is stopped and its latest checkpoint scored.
128
+ - **Fixed seed** — the training seed is fixed by the grader, so you cannot seed-shop. Your
129
+ recipe is scored as the **median over several grader-chosen seeds**, so it must be robust,
130
+ not lucky.
131
+ - **Real-LM checks** — the grader verifies your loaded model is a real language model: it
132
+ scores real held-out text noticeably better than arbitrary token IDs, its `forward(x,y)` loss
133
+ agrees with the cross-entropy of its `forward(x)` logits, its logits vary across positions,
134
+ and its `val_bpb` falls inside a plausible band. A degenerate or forged-loss model scores 0.
135
+ - **Fresh training** — the grader trains from scratch by running your entry; it does not accept
136
+ pre-trained weights. Handing back a checkpoint you built earlier instead of training scores 0.
137
+ - No internet access. All packages you need (including `torch`) are pre-installed.
138
+
139
+ ---
140
+
141
+ ## 🔁 Iterative submission protocol (this task uses a per-task loop)
142
+
143
+ ### 1. Goal + protocol
144
+
145
+ Optimize the held-out `val_bpb` of *this* task as far as you can inside the token budget. You
146
+ have a **submission budget of 1 to 16**: at least **1** submission, at most **16** (hard
147
+ ceiling). Iterate **one round at a time, feedback-driven**. Each round is a single cycle:
148
+
149
+ 1. **Edit** your recipe — `/app/submission/train_gpt.py` and/or the nanoGPT source in
150
+ `/app/repo` it imports — applying ONE concrete change based on your current hypothesis
151
+ (round 1: based on reading the shipped starter).
152
+ 2. **Submit** by running `bash /opt/loop/submit.sh` **once**. It trains your recipe on a
153
+ **small public token budget** and returns, synchronously, a sanitized block:
154
+ `correctness` (PASS/FAIL) · `dev_val_bpb` · `best_so_far` · `remaining` ·
155
+ `finalize_allowed` · and on failure the **named `failing_invariant`**.
156
+ 3. **Read the feedback in full**, then **analyze in writing** (see §4).
157
+ 4. **Edit again** based on that analysis, then go to step 2.
158
+
159
+ Do **NOT** call `submit.sh` in a batch, and do **NOT** plan more than one round ahead — round
160
+ `k+1`'s change must depend on round `k`'s measured outcome.
161
+
162
+ 🔴 **`dev_val_bpb` is a PUBLIC PROXY, not your graded score.** It is measured by training your
163
+ recipe on a *small public* token budget (sliced from the same public `train.bin` you already
164
+ have) and evaluating on the *public* `val.bin` monitor — nothing about the held-out test split
165
+ or the reference recipe lives in this container. Because the proxy budget is **tokens, not
166
+ wall-clock**, the number is stable and does not drift with node speed. Use it for **direction**
167
+ (did this change lower `val_bpb` or not?), not as your grade: your real score is computed after
168
+ the session, over the **hidden** test split at the **full** token budget, with the frozen
169
+ anchor. Do not overfit to the public proxy.
170
+
171
+ If the feedback ever says `harness_error`, that round was **refunded** (your budget is
172
+ unchanged) and the failure is NOT your code's fault — do not debug the harness; retry or
173
+ continue optimizing.
174
+
175
+ ### 2. Termination
176
+
177
+ Two ways to end:
178
+
179
+ - (a) reaching 16 submissions triggers an automatic finalize (a safety net); or
180
+ - (b) at **any k ≥ 1**, once you judge you have reached your practical/theoretical limit (e.g.
181
+ the last few rounds converged within run noise), run
182
+ `bash /opt/loop/submit.sh --finalize --reason "<one concrete sentence on why you are stopping>"`.
183
+
184
+ `--reason` is **mandatory** and is audited. Early exit is a feature: you keep your **best**
185
+ submission (best-of-k, chosen by the public proxy and planted for grading), and a *justified*
186
+ stop at k=1 scores exactly the same as burning all 16. There is **no minimum** number of
187
+ submissions and **no** "keep going until several rounds in a row show no improvement" rule.
188
+
189
+ ### 3. 🔴 Red line (hard — hitting ANY one ⇒ the whole task is audited to 0)
190
+
191
+ 1. Do **NOT deliberately** `cat` / `open` / `less` / `head` / `tail` / `grep` / `find` / edit
192
+ **any** verifier / correctness / timing / scoring / hidden-test file or directory, wherever
193
+ it lives — `bash /opt/loop/submit.sh` is the **only** sanctioned way to interact with the
194
+ scoring machinery.
195
+ 2. Do **NOT** run the grader directly, and do **NOT** reproduce or reverse-engineer it — score
196
+ only by calling `bash /opt/loop/submit.sh`.
197
+ 3. Do **NOT** search for, print, or infer the hidden test split, the fixed seeds, the token
198
+ budget, any threshold, the metric internals, the baseline `val_bpb`, or the reference score.
199
+ 4. Do **NOT** fetch or look up an upstream reference solution (no web fetch, no `git` remote
200
+ fetch, no network), regardless of any internet switch.
201
+ 5. Do **NOT** use, quote, or condition your code on any verifier / scoring / held-out material,
202
+ however you came to see it — and do not forge the loss, smuggle a pre-built checkpoint, train
203
+ on anything other than the shard at `DATA_PATH`, or tamper with the parameter/token/uid
204
+ guards.
205
+ 6. **One round at a time:** do not batch submissions and do not plan more than one round ahead.
206
+ 7. Between rounds you **must** write the analysis in §4.
207
+ 8. `--reason` on `--finalize` is **mandatory** and is audited.
208
+
209
+ Stay inside `/app/submission` + `/app/repo` and scratch directories you create yourself; use
210
+ only what `submit.sh` returns for scoring signal.
211
+
212
+ ### 4. 🎓 Explain for a beginner — per round, not in bulk
213
+
214
+ Before your first edit, state your **hypothesis** (what round 1 tests and why). Then, **after
215
+ every `submit.sh` feedback and BEFORE the next edit**, give a step-by-step analysis an
216
+ undergraduate could follow: (a) what the feedback told you, (b) *why* this round's change had
217
+ that effect on `val_bpb` (mechanistic reasoning about sample efficiency — the optimizer /
218
+ architecture / data schedule), and (c) *what single change* you will try next.
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/baseline_submission/train_gpt.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # e2e-a4-token-efficiency-budget : the STRONG-BASELINE recipe + the solver's starting point.
2
+ #
3
+ # THE TASK. The grader gives you a FIXED NUMBER OF TRAINING TOKENS and scores the held-out
4
+ # val_bpb of the checkpoint your recipe produces. Wall-clock is NOT the budget: making the
5
+ # step faster does not let you consume more tokens, so throughput buys you NOTHING. The only
6
+ # way to a lower loss is to extract MORE LEARNING PER TOKEN -- real sample efficiency.
7
+ #
8
+ # THIS FILE IS BOTH (a) the reviewer's strong baseline (the 1.0 anchor you must beat) and
9
+ # (b) a starting point you may rewrite entirely. It is NOT a contract. The tuned-AdamW recipe
10
+ # below was selected as the BEST of a batch-size/learning-rate sweep at this token budget, so
11
+ # re-tuning those knobs will not move your score -- you have to change what the training
12
+ # ALGORITHM is (optimizer / architecture / data schedule).
13
+ #
14
+ # THE ONLY CONTRACT (both required):
15
+ # train_for_budget(seed, out_dir, budget_seconds) -> writes <out_dir>/model_ckpt.pt
16
+ # load_model_for_verification(checkpoint_path, device) -> nn.Module or (args, model)
17
+ # with model(x) -> logits (B,T,V) position-dependent, and model(x, y) -> scalar loss equal to
18
+ # F.cross_entropy(logits.view(-1,V), y.view(-1)) on those logits.
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ import os
23
+ import sys
24
+ import time
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import torch
29
+ import torch.nn as nn
30
+
31
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
32
+ if REPO not in sys.path:
33
+ sys.path.insert(0, REPO)
34
+ from model import GPT, GPTConfig # noqa: E402 (from /app/repo/model.py -- fully editable)
35
+
36
+
37
+ class Hyperparameters:
38
+ """Starting point. Nothing here is required by scoring."""
39
+ # The grader points DATA_PATH at YOUR TOKEN BUDGET: a shard holding exactly
40
+ # TOKEN_BUDGET tokens. It is the only readable token source during scoring.
41
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
42
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
43
+ seed = int(os.environ.get("SEED", "1337"))
44
+ token_budget = int(os.environ.get("TOKEN_BUDGET", "24000000"))
45
+ max_params = int(os.environ.get("MAX_PARAMS", "45000000"))
46
+
47
+ vocab_size = 8192
48
+ train_seq_len = 512 # the verifier reads this as seq_len
49
+ block_size = 512
50
+ val_batch_size = 32_768
51
+
52
+ # ~34M-parameter model, comfortably inside the parameter cap the grader re-counts.
53
+ n_layer = 8
54
+ n_head = 8
55
+ n_embd = 512
56
+ dropout = 0.0
57
+ bias = False
58
+
59
+ # TUNED AdamW at this token budget: this peak LR was selected as the BEST of a
60
+ # learning-rate / batch-size sweep at this budget, so re-tuning it will not help.
61
+ micro_batch = 8
62
+ grad_accum = 1
63
+ learning_rate = 5.0e-4
64
+ weight_decay = 0.1
65
+ beta1, beta2 = 0.9, 0.95
66
+ grad_clip = 1.0
67
+ warmup_frac = 0.02 # trapezoidal schedule: warmup -> flat -> linear cooldown
68
+ cooldown_frac = 0.40
69
+ min_lr_frac = 0.02
70
+ save_every_sec = 20.0 # save periodically: the grader may stop you at any moment
71
+
72
+
73
+ class TokenStream:
74
+ """Sequential single-epoch reader over the budgeted shard.
75
+
76
+ Reads the shard start-to-end exactly once, so the recipe consumes its token budget and
77
+ no token is repeated (repetition invites memorisation, which the held-out eval punishes).
78
+ The loader implementation is entirely yours to change -- order, packing, curriculum and
79
+ sequence length are all levers."""
80
+
81
+ def __init__(self, data_path: str, seq_len: int, device):
82
+ self.data = np.memmap(Path(data_path) / "train.bin", dtype=np.uint16, mode="r")
83
+ self.seq_len = seq_len
84
+ self.device = device
85
+ self.pos = 0
86
+ self.tokens_served = 0
87
+ self.exhausted = False
88
+
89
+ def batch(self, n: int):
90
+ need = n * self.seq_len + 1
91
+ if self.pos + need >= len(self.data):
92
+ self.pos = 0
93
+ self.exhausted = True # one full pass over the budget completed
94
+ blk = np.asarray(self.data[self.pos:self.pos + need], dtype=np.int64)
95
+ self.pos += n * self.seq_len
96
+ self.tokens_served += n * self.seq_len
97
+ x = torch.from_numpy(blk[:-1].reshape(n, self.seq_len))
98
+ y = torch.from_numpy(blk[1:].reshape(n, self.seq_len))
99
+ return (x.pin_memory().to(self.device, non_blocking=True),
100
+ y.pin_memory().to(self.device, non_blocking=True))
101
+
102
+
103
+ class _VerifierAdapter(nn.Module):
104
+ """nanoGPT's GPT.forward(idx, targets) returns (logits, loss) and only computes full
105
+ logits when targets are supplied; adapt it to the verifier's forward contract."""
106
+
107
+ def __init__(self, gpt: GPT):
108
+ super().__init__()
109
+ self.gpt = gpt
110
+
111
+ def forward(self, idx, targets=None):
112
+ logits, loss = self.gpt(idx, idx if targets is None else targets)
113
+ return logits if targets is None else loss
114
+
115
+
116
+ def _build(args: Hyperparameters, device) -> GPT:
117
+ cfg = GPTConfig(block_size=args.block_size, vocab_size=args.vocab_size,
118
+ n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd,
119
+ dropout=args.dropout, bias=args.bias)
120
+ return GPT(cfg).to(device)
121
+
122
+
123
+ def _save(model: GPT, cfg: GPTConfig, out_ckpt: Path) -> None:
124
+ m = getattr(model, "_orig_mod", model)
125
+ tmp = str(out_ckpt) + ".tmp"
126
+ torch.save({"model": m.state_dict(),
127
+ "config": dict(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
128
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
129
+ dropout=0.0, bias=cfg.bias)}, tmp)
130
+ os.replace(tmp, out_ckpt) # atomic: a hard kill never leaves a half-written ckpt
131
+
132
+
133
+ def load_model_for_verification(checkpoint_path, device):
134
+ args = Hyperparameters()
135
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
136
+ ck = obj.get("config", {})
137
+ cfg = GPTConfig(**ck) if ck else GPTConfig(
138
+ block_size=args.block_size, vocab_size=args.vocab_size, n_layer=args.n_layer,
139
+ n_head=args.n_head, n_embd=args.n_embd, dropout=0.0, bias=args.bias)
140
+ gpt = GPT(cfg)
141
+ sd = obj["model"]
142
+ if any(k.startswith("_orig_mod.") for k in sd):
143
+ sd = {k.replace("_orig_mod.", "", 1): v for k, v in sd.items()}
144
+ gpt.load_state_dict(sd, strict=True)
145
+ args.train_seq_len = cfg.block_size
146
+ args.vocab_size = cfg.vocab_size
147
+ return args, _VerifierAdapter(gpt).to(device).eval()
148
+
149
+
150
+ def train_for_budget(seed: int, out_dir, budget_seconds: float) -> None:
151
+ """Train on the token budget the grader made available at DATA_PATH.
152
+
153
+ `budget_seconds` is only a FEASIBILITY GUARD (generous); the real budget is the tokens.
154
+ """
155
+ args = Hyperparameters()
156
+ args.seed = int(seed)
157
+ out_ckpt = Path(out_dir) / "model_ckpt.pt"
158
+ out_ckpt.parent.mkdir(parents=True, exist_ok=True)
159
+
160
+ torch.manual_seed(args.seed)
161
+ np.random.seed(args.seed)
162
+ torch.backends.cuda.matmul.allow_tf32 = True
163
+ torch.backends.cudnn.allow_tf32 = True
164
+ device = torch.device("cuda", 0)
165
+ torch.cuda.set_device(device)
166
+
167
+ model = _build(args, device)
168
+ cfg = model.config
169
+ stream = TokenStream(args.data_path, args.train_seq_len, device)
170
+ # The shard IS the budget: one pass over it consumes exactly the token budget.
171
+ budget_tokens = int(stream.data.shape[0])
172
+ tokens_per_step = args.micro_batch * args.grad_accum * args.train_seq_len
173
+ total_steps = max(1, budget_tokens // tokens_per_step)
174
+ print(f"[train] seed={seed} params={sum(p.numel() for p in model.parameters())/1e6:.1f}M "
175
+ f"budget={budget_tokens/1e6:.2f}M tokens -> {total_steps} steps "
176
+ f"(micro={args.micro_batch} accum={args.grad_accum} seq={args.train_seq_len})",
177
+ flush=True)
178
+
179
+ opt = torch.optim.AdamW(model.parameters(), lr=args.learning_rate,
180
+ betas=(args.beta1, args.beta2),
181
+ weight_decay=args.weight_decay, fused=True)
182
+ warm = max(1, int(args.warmup_frac * total_steps))
183
+ cool = max(1, int(args.cooldown_frac * total_steps))
184
+ t0 = last_save = time.time()
185
+ guard = float(budget_seconds) * 0.94 if budget_seconds else float("inf")
186
+ model.train()
187
+ for step in range(total_steps):
188
+ if time.time() - t0 > guard: # never get hard-killed mid-save
189
+ break
190
+ if step < warm:
191
+ f = (step + 1) / warm
192
+ elif step > total_steps - cool:
193
+ f = max(args.min_lr_frac, (total_steps - step) / cool)
194
+ else:
195
+ f = 1.0
196
+ for g in opt.param_groups:
197
+ g["lr"] = args.learning_rate * f
198
+ opt.zero_grad(set_to_none=True)
199
+ for _ in range(args.grad_accum):
200
+ x, y = stream.batch(args.micro_batch)
201
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
202
+ _, loss = model(x, y)
203
+ (loss / args.grad_accum).backward()
204
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
205
+ opt.step()
206
+ if step % 200 == 0:
207
+ print(f"[train] step {step}/{total_steps} lr {args.learning_rate*f:.2e} "
208
+ f"loss {float(loss):.4f} tok {stream.tokens_served/1e6:.1f}M "
209
+ f"t {time.time()-t0:.0f}s", flush=True)
210
+ if time.time() - last_save >= args.save_every_sec:
211
+ _save(model, cfg, out_ckpt)
212
+ last_save = time.time()
213
+ _save(model, cfg, out_ckpt)
214
+ print(f"[train] done: {stream.tokens_served/1e6:.2f}M tokens consumed in "
215
+ f"{time.time()-t0:.0f}s -> {out_ckpt}", flush=True)
216
+
217
+
218
+ if __name__ == "__main__":
219
+ train_for_budget(int(os.environ.get("SEED", "1337")),
220
+ os.environ.get("OUT_DIR", "/app/submission"),
221
+ float(os.environ.get("MAX_WALLCLOCK_SEC", "900")))
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/private/dev_eval.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """/opt/loop/private/dev_eval.py — the per-round DEV proxy for e2e-a4-token-efficiency-budget.
3
+
4
+ Root-owned 0600, called ONLY by /opt/loop/score_engine.sh (which is 0700). The solver's
5
+ dropped uid cannot read this file.
6
+
7
+ WHAT IT DOES (a faithful, CHEAP, node-speed-immune mirror of the graded path, on PUBLIC data):
8
+ 1. Slices a SMALL public token shard (dev_train_tokens, deterministic window) out of the
9
+ PUBLIC corpus the solver already has (/data/datasets/wikitext_bpe8k/train.bin) and points
10
+ DATA_PATH at it. The budget is TOKENS, not wall-clock, so the val_bpb it yields is a stable
11
+ function of the recipe+data+seed and does not drift with node speed.
12
+ 2. Runs the candidate's train_for_budget(dev_seed, out_dir, dev_guard) from an ISOLATED
13
+ staging dir (source only; weight/data blobs stripped, so a smuggled checkpoint cannot game
14
+ even the dev signal), UNDER THE uid-65534 PRIVILEGE DROP the graded path uses.
15
+ 3. Reloads the checkpoint via the candidate's load_model_for_verification and runs a
16
+ FIRST-PRINCIPLES correctness self-check (param count in the SAME [floor,cap] the grade
17
+ enforces, forward(x)/forward(x,y) CE agreement, logits vary across positions, a plausible
18
+ val_bpb band) — no reference implementation and no anchor are needed to decide pass/fail.
19
+ 4. Computes val_bpb on the PUBLIC val split (/data/datasets/wikitext_bpe8k/val.bin — the
20
+ "local progress monitor" the task statement already gives the solver), using the same
21
+ SentencePiece byte-LUT machinery as the grade so the number is comparable.
22
+
23
+ WHAT IT NEVER TOUCHES: /tests, the held-out corpus, the calibrated baseline_bpb / ref_speedup,
24
+ or ANY environment-supplied threshold. The dev signal is an ABSOLUTE val_bpb, never normalised
25
+ against the graded anchor. Constants come from /opt/loop/private/manifest.json ONLY.
26
+
27
+ OUTPUT: /logs/loop/dev/{verifier_state.json, reward.json}; on infra failure, harness_error.txt.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import math
33
+ import os
34
+ import shutil
35
+ import signal
36
+ import subprocess
37
+ import sys
38
+ import time
39
+ from pathlib import Path
40
+
41
+ LOOP_PRIVATE = Path("/opt/loop/private")
42
+ MANIFEST = LOOP_PRIVATE / "manifest.json"
43
+ DEV_OUT = Path("/logs/loop/dev")
44
+ DEV_OUT.mkdir(parents=True, exist_ok=True)
45
+
46
+ # ---- named DEV failing-invariants (mirror the graded gate vocabulary, dev-scoped) ----
47
+ INV_SUBMISSION_MISSING = "submission_missing"
48
+ INV_NO_CHECKPOINT = "no_checkpoint_produced"
49
+ INV_PARAM_FLOOR = "param_below_floor"
50
+ INV_PARAM_CAP = "param_above_cap"
51
+ INV_CE_AGREE = "forward_ce_disagreement"
52
+ INV_LOGITS_CONST = "logits_constant_across_positions"
53
+ INV_VAL_IMPLAUSIBLE = "val_bpb_implausible"
54
+ INV_VAL_FLOOR = "val_bpb_above_quality_floor"
55
+ INV_LOAD = "load_model_for_verification_failed"
56
+ INV_HARNESS = "harness_error"
57
+
58
+
59
+ def _cfg() -> dict:
60
+ return json.loads(MANIFEST.read_text(encoding="utf-8"))
61
+
62
+
63
+ def _write_state(correctness_ok: bool, failing_invariant: str | None,
64
+ dev_val_bpb: float | None, dev_reward: float,
65
+ uid_dropped: bool | None, observed_euid, extra: dict | None = None) -> None:
66
+ reasons = [] if correctness_ok else ([failing_invariant] if failing_invariant else ["unknown"])
67
+ state = {
68
+ "correctness_ok": bool(correctness_ok),
69
+ "hard_fail_reasons": reasons,
70
+ "failing_invariant": failing_invariant or "",
71
+ "dev_uid_dropped": uid_dropped,
72
+ "observed_euid": observed_euid,
73
+ }
74
+ if extra:
75
+ state.update(extra)
76
+ reward = {
77
+ # dev_score: higher is better, used ONLY to rank best-of-k. dev_val_bpb is the
78
+ # human-facing absolute proxy (lower is better). NEITHER is the graded reward.
79
+ "dev_score": float(dev_reward),
80
+ "dev_metric": "val_bpb (PUBLIC dev proxy; lower is better; NOT your graded score)",
81
+ "dev_val_bpb": dev_val_bpb,
82
+ "correctness_ok": bool(correctness_ok),
83
+ }
84
+ (DEV_OUT / "verifier_state.json").write_text(json.dumps(state, sort_keys=True, indent=2) + "\n")
85
+ (DEV_OUT / "reward.json").write_text(json.dumps(reward, sort_keys=True, indent=2) + "\n")
86
+
87
+
88
+ def _harness_error(msg: str) -> None:
89
+ (DEV_OUT / "harness_error.txt").write_text(msg + "\n")
90
+ _write_state(False, INV_HARNESS, None, 0.0, None, None, {"harness_message": msg})
91
+
92
+
93
+ # -----------------------------------------------------------------------------
94
+ # dev shard from the PUBLIC corpus (deterministic window; public data, no quarantine needed)
95
+ # -----------------------------------------------------------------------------
96
+ def build_dev_shard(corpus_dir: Path, shard_dir: Path, n_tokens: int, offset: int) -> bool:
97
+ import numpy as np
98
+ shard_dir.mkdir(parents=True, exist_ok=True)
99
+ src = corpus_dir / "train.bin"
100
+ if not src.exists():
101
+ return False
102
+ d = np.memmap(src, dtype=np.uint16, mode="r")
103
+ have = int(d.shape[0])
104
+ if have < n_tokens:
105
+ return False
106
+ off = offset if (0 <= offset <= have - n_tokens) else 0
107
+ np.asarray(d[off:off + n_tokens], dtype=np.uint16).tofile(shard_dir / "train.bin")
108
+ for extra in ("val.bin", "meta.pkl"):
109
+ sp = corpus_dir / extra
110
+ if sp.exists():
111
+ shutil.copy2(sp, shard_dir / extra)
112
+ return (shard_dir / "train.bin").stat().st_size // 2 == n_tokens
113
+
114
+
115
+ _DEV_RUNNER = r'''
116
+ import importlib.util, os, sys
117
+ sub = sys.argv[1]; seed = int(sys.argv[2]); out_dir = sys.argv[3]; budget = float(sys.argv[4])
118
+ rep = os.environ.get("DEV_UID_REPORT")
119
+ if rep:
120
+ try: open(rep, "w").write("%d %d\n" % (os.getuid(), os.geteuid()))
121
+ except Exception: pass
122
+ spec = importlib.util.spec_from_file_location("dev_train_gpt", sub)
123
+ mod = importlib.util.module_from_spec(spec); sys.modules["dev_train_gpt"] = mod
124
+ sys.path.insert(0, os.path.dirname(os.path.abspath(sub)))
125
+ spec.loader.exec_module(mod)
126
+ fn = getattr(mod, "train_for_budget", None)
127
+ if fn is None:
128
+ print("train_for_budget missing", file=sys.stderr); sys.exit(7)
129
+ fn(seed=seed, out_dir=out_dir, budget_seconds=budget)
130
+ '''
131
+
132
+ _WEIGHT_EXT = {".pt", ".pth", ".ptz", ".bin", ".safetensors", ".ckpt", ".npz",
133
+ ".npy", ".pkl", ".pickle", ".h5", ".onnx", ".gguf", ".pt2"}
134
+
135
+
136
+ def train_candidate(cfg: dict, submission_py: Path, shard_dir: Path, out_dir: Path):
137
+ """Train the candidate recipe on the dev shard under the uid drop. Returns
138
+ (checkpoint_path_or_None, uid_dropped, observed_euid, note)."""
139
+ out_dir.mkdir(parents=True, exist_ok=True)
140
+ stage = out_dir / "_stage_src"
141
+ stage.mkdir(parents=True, exist_ok=True)
142
+ src_root = submission_py.parent
143
+ try:
144
+ for p in src_root.rglob("*"):
145
+ if not p.is_file() or "_stage_src" in p.parts or p.name.startswith("_dev_runner"):
146
+ continue
147
+ if p.suffix.lower() in _WEIGHT_EXT or p.stat().st_size > 8 * 1024 * 1024:
148
+ continue
149
+ rel = p.relative_to(src_root)
150
+ (stage / rel).parent.mkdir(parents=True, exist_ok=True)
151
+ shutil.copy2(p, stage / rel)
152
+ except Exception:
153
+ pass
154
+ staged_py = stage / submission_py.name
155
+ if not staged_py.exists():
156
+ shutil.copy2(submission_py, staged_py)
157
+ (stage / "_dev_runner.py").write_text(_DEV_RUNNER, encoding="utf-8")
158
+
159
+ guard = float(cfg["dev_guard_seconds"])
160
+ grace = float(cfg["dev_guard_grace_seconds"])
161
+ env = dict(os.environ)
162
+ env.pop("PYTHONPATH", None)
163
+ env.pop("PYTHONHOME", None)
164
+ env["SEED"] = str(int(cfg["dev_seed"]))
165
+ env["TOKEN_BUDGET"] = str(int(cfg["dev_train_tokens"]))
166
+ env["MAX_WALLCLOCK_SEC"] = str(guard)
167
+ env["MAX_PARAMS"] = str(int(cfg["dev_param_cap"]))
168
+ env["OUT_CKPT"] = str(out_dir / "model_ckpt.pt")
169
+ env["DATA_PATH"] = str(shard_dir)
170
+ env["TOKENIZER_PATH"] = str(cfg["tokenizer_path"])
171
+ env["NANOGPT_REPO"] = str(cfg["nanogpt_repo"])
172
+
173
+ py = sys.executable or shutil.which("python3") or "python3"
174
+ train_uid = cfg.get("dev_uid")
175
+
176
+ def preexec_plain():
177
+ os.setsid()
178
+
179
+ preexec = preexec_plain
180
+ if train_uid:
181
+ # the WHOLE ancestor chain must be traversable by the unprivileged uid (mkdtemp makes a
182
+ # 0700 root parent), then grant it its staging + shard + out_dir and nothing else.
183
+ try:
184
+ anc = out_dir.resolve()
185
+ while str(anc) not in ("/", str(anc.parent)):
186
+ try:
187
+ if anc.stat().st_uid == os.getuid():
188
+ os.chmod(anc, 0o755)
189
+ except Exception:
190
+ pass
191
+ anc = anc.parent
192
+ os.chmod(stage, 0o777)
193
+ os.chmod(out_dir, 0o777)
194
+ for p in stage.rglob("*"):
195
+ try:
196
+ os.chmod(p, 0o777 if p.is_dir() else 0o666)
197
+ except Exception:
198
+ pass
199
+ os.chmod(shard_dir, 0o755)
200
+ for p in shard_dir.iterdir():
201
+ try:
202
+ os.chmod(p, 0o644)
203
+ except Exception:
204
+ pass
205
+ except Exception:
206
+ pass
207
+ home = out_dir / "_devhome"
208
+ home.mkdir(parents=True, exist_ok=True)
209
+ try:
210
+ os.chmod(home, 0o777)
211
+ except Exception:
212
+ pass
213
+ env["HOME"] = str(home)
214
+ env["TMPDIR"] = str(home)
215
+ env["XDG_CACHE_HOME"] = str(home / ".cache")
216
+ env["TRITON_CACHE_DIR"] = str(home / ".triton")
217
+ env["TORCHINDUCTOR_CACHE_DIR"] = str(home / ".inductor")
218
+ env["DEV_UID_REPORT"] = str(out_dir / "_dev_uid.txt")
219
+ _uid = int(train_uid)
220
+
221
+ def preexec_drop():
222
+ os.setsid()
223
+ try:
224
+ os.setgroups([])
225
+ os.setgid(_uid)
226
+ os.setuid(_uid)
227
+ except Exception:
228
+ pass
229
+
230
+ preexec = preexec_drop
231
+
232
+ t0 = time.monotonic()
233
+ proc = subprocess.Popen(
234
+ [py, str(stage / "_dev_runner.py"), str(staged_py), str(cfg["dev_seed"]),
235
+ str(out_dir), str(guard)],
236
+ cwd=str(stage), env=env, preexec_fn=preexec,
237
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
238
+ )
239
+ note = "completed"
240
+ stderr_tail = b""
241
+ try:
242
+ _, stderr_tail = proc.communicate(timeout=guard + grace)
243
+ except subprocess.TimeoutExpired:
244
+ note = "hard-killed at dev guard+grace"
245
+ for sg in (signal.SIGTERM, signal.SIGKILL):
246
+ try:
247
+ os.killpg(os.getpgid(proc.pid), sg)
248
+ except ProcessLookupError:
249
+ pass
250
+ time.sleep(3)
251
+ try:
252
+ _, stderr_tail = proc.communicate(timeout=20)
253
+ except Exception:
254
+ pass
255
+ wall = time.monotonic() - t0
256
+
257
+ observed_euid = None
258
+ try:
259
+ observed_euid = (out_dir / "_dev_uid.txt").read_text().split()[1]
260
+ except Exception:
261
+ observed_euid = None
262
+ uid_dropped = bool(train_uid) and observed_euid == str(int(train_uid)) if train_uid else False
263
+
264
+ ckpt = out_dir / "model_ckpt.pt"
265
+ try:
266
+ if ckpt.exists():
267
+ os.chmod(ckpt, 0o644)
268
+ except Exception:
269
+ pass
270
+ stderr_txt = (stderr_tail or b"").decode("utf-8", "ignore")
271
+ return (ckpt if ckpt.exists() else None), uid_dropped, observed_euid, f"{note} ({wall:.0f}s)", stderr_txt
272
+
273
+
274
+ # -----------------------------------------------------------------------------
275
+ # reload + first-principles self-check + PUBLIC val_bpb (byte-LUT, lifted compact)
276
+ # -----------------------------------------------------------------------------
277
+ def evaluate(cfg: dict, submission_py: Path, ckpt: Path):
278
+ import numpy as np
279
+ import sentencepiece as spm
280
+ import torch
281
+ import torch.nn.functional as F
282
+ import importlib.util
283
+
284
+ device = torch.device("cuda", 0)
285
+ torch.cuda.set_device(device)
286
+
287
+ spec = importlib.util.spec_from_file_location("dev_reload_train_gpt", submission_py)
288
+ module = importlib.util.module_from_spec(spec)
289
+ sys.modules["dev_reload_train_gpt"] = module
290
+ sub_parent = str(submission_py.parent.resolve())
291
+ if sub_parent not in sys.path:
292
+ sys.path.insert(0, sub_parent)
293
+ if str(cfg["nanogpt_repo"]) not in sys.path:
294
+ sys.path.insert(0, str(cfg["nanogpt_repo"]))
295
+ spec.loader.exec_module(module)
296
+
297
+ loader = getattr(module, "load_model_for_verification", None)
298
+ if loader is None:
299
+ return False, INV_LOAD, None, "load_model_for_verification missing"
300
+ import inspect
301
+ args = module.Hyperparameters() if hasattr(module, "Hyperparameters") else None
302
+ try:
303
+ sig = inspect.signature(loader)
304
+ kwargs, positional = {}, []
305
+ for name, par in sig.parameters.items():
306
+ if name in {"checkpoint_path", "path", "model_path", "compressed_checkpoint_path"}:
307
+ kwargs[name] = ckpt
308
+ elif name == "device":
309
+ kwargs[name] = device
310
+ elif par.default is inspect._empty:
311
+ if not positional:
312
+ positional.append(ckpt)
313
+ elif len(positional) == 1:
314
+ positional.append(device)
315
+ loaded = loader(*positional, **kwargs)
316
+ except Exception as exc:
317
+ return False, INV_LOAD, None, f"{type(exc).__name__}: {exc}"
318
+ if isinstance(loaded, tuple) and len(loaded) == 2:
319
+ loaded_args, model = loaded
320
+ if loaded_args is not None:
321
+ args = loaded_args
322
+ else:
323
+ model = loaded
324
+ if not isinstance(model, torch.nn.Module):
325
+ return False, INV_LOAD, None, "loader did not return an nn.Module / (args, model)"
326
+ model = model.to(device).eval()
327
+
328
+ # param cap/floor — the SAME band the grade enforces (does not coach a sub-floor model)
329
+ n_params = int(sum(p.numel() for p in model.parameters()))
330
+ floor = int(cfg["dev_param_floor"])
331
+ cap = int(cfg["dev_param_cap"])
332
+ if n_params < floor:
333
+ return False, INV_PARAM_FLOOR, None, f"{n_params:,} < floor {floor:,}"
334
+ if n_params > cap:
335
+ return False, INV_PARAM_CAP, None, f"{n_params:,} > cap {cap:,}"
336
+
337
+ seq_len = int(getattr(args, "train_seq_len", 1024) or 1024)
338
+ seq_len = max(seq_len, 16)
339
+ vocab_size = int(getattr(args, "vocab_size", 8192) or 8192)
340
+
341
+ # forward(x)/forward(x,y) CE agreement + logits position variance
342
+ arange = torch.arange(seq_len, device=device, dtype=torch.int64)
343
+ x_ar = (arange % vocab_size).reshape(1, -1)
344
+ y_ar = ((arange + 1) % vocab_size).reshape(1, -1)
345
+ with torch.inference_mode():
346
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
347
+ logits = model(x_ar)
348
+ loss_xy = model(x_ar, y_ar)
349
+ if not isinstance(logits, torch.Tensor) or logits.ndim != 3 or not logits.dtype.is_floating_point:
350
+ return False, INV_CE_AGREE, None, "forward(x) did not return float logits (B,T,V)"
351
+ lf = logits.float()
352
+ pos_var = float(lf.var(dim=1).mean().item())
353
+ if not math.isfinite(pos_var) or pos_var <= float(cfg["dev_logits_position_variance_floor"]):
354
+ return False, INV_LOGITS_CONST, None, f"logits constant across positions (var={pos_var:.2e})"
355
+ real_vocab = logits.shape[-1]
356
+ ce = float(F.cross_entropy(lf.reshape(-1, real_vocab),
357
+ y_ar.reshape(-1).clamp_max(real_vocab - 1), reduction="mean").item())
358
+ lxy = float(loss_xy.detach().to(torch.float64).item()) if isinstance(loss_xy, torch.Tensor) else float(loss_xy)
359
+ if not math.isfinite(lxy) or abs(lxy - ce) > float(cfg["dev_logits_loss_agreement_tol"]):
360
+ return False, INV_CE_AGREE, None, f"forward(x,y)={lxy:.4f} != CE(forward(x),y)={ce:.4f}"
361
+
362
+ # ---- val_bpb on the PUBLIC val split (byte-LUT SentencePiece, same as the grade) ----
363
+ tok_path = Path(str(getattr(args, "tokenizer_path", cfg["tokenizer_path"])))
364
+ if not tok_path.exists():
365
+ tok_path = Path(cfg["tokenizer_path"])
366
+ sp = spm.SentencePieceProcessor(model_file=str(tok_path))
367
+ sp_v = int(sp.vocab_size())
368
+ table = max(sp_v, vocab_size)
369
+ base_bytes = np.zeros((table,), dtype=np.int32)
370
+ has_lead = np.zeros((table,), dtype=np.bool_)
371
+ is_bound = np.ones((table,), dtype=np.bool_)
372
+ for tid in range(sp_v):
373
+ if sp.is_control(tid) or sp.is_unknown(tid) or sp.is_unused(tid):
374
+ continue
375
+ is_bound[tid] = False
376
+ if sp.is_byte(tid):
377
+ base_bytes[tid] = 1
378
+ continue
379
+ piece = sp.id_to_piece(tid)
380
+ if piece.startswith("▁"):
381
+ has_lead[tid] = True
382
+ piece = piece[1:]
383
+ base_bytes[tid] = len(piece.encode("utf-8"))
384
+ base_bytes_lut = torch.tensor(base_bytes, dtype=torch.int32, device=device)
385
+ has_lead_lut = torch.tensor(has_lead, dtype=torch.bool, device=device)
386
+ is_bound_lut = torch.tensor(is_bound, dtype=torch.bool, device=device)
387
+
388
+ val_path = Path(cfg["corpus_dir"]) / "val.bin"
389
+ if not val_path.exists():
390
+ return False, INV_VAL_IMPLAUSIBLE, None, f"public val split missing at {val_path}"
391
+ vd = np.memmap(val_path, dtype=np.uint16, mode="r")
392
+ cap_tok = int(cfg["dev_val_tokens"])
393
+ ids = np.asarray(vd[: min(len(vd), cap_tok + 1)], dtype=np.int64)
394
+ usable = ((ids.size - 1) // seq_len) * seq_len
395
+ if usable <= 0:
396
+ return False, INV_VAL_IMPLAUSIBLE, None, "public val split too short for seq_len"
397
+ val_tokens = torch.from_numpy(ids[: usable + 1]).contiguous()
398
+ n = val_tokens.numel()
399
+ batch_seqs = max(32768 // seq_len, 1)
400
+ total_seqs = usable // seq_len
401
+ loss_sum = torch.zeros((), device=device, dtype=torch.float64)
402
+ tok_count = torch.zeros((), device=device, dtype=torch.float64)
403
+ byte_count = torch.zeros((), device=device, dtype=torch.float64)
404
+ with torch.inference_mode():
405
+ for s0 in range(0, total_seqs, batch_seqs):
406
+ s1 = min(s0 + batch_seqs, total_seqs)
407
+ r0, r1 = s0 * seq_len, s1 * seq_len + 1
408
+ local = val_tokens[r0:r1].to(device=device, dtype=torch.int64)
409
+ x = local[:-1].reshape(-1, seq_len)
410
+ y = local[1:].reshape(-1, seq_len)
411
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
412
+ out = model(x, y)
413
+ if isinstance(out, torch.Tensor) and out.numel() != 1:
414
+ lg = out.float().reshape(-1, out.shape[-1])
415
+ bl = F.cross_entropy(lg, y.reshape(-1).clamp_max(lg.shape[-1] - 1), reduction="mean")
416
+ else:
417
+ bl = out
418
+ ntok = float(y.numel())
419
+ loss_sum += bl.detach().to(torch.float64) * ntok
420
+ tok_count += ntok
421
+ prev = x.reshape(-1)
422
+ tgt = y.reshape(-1)
423
+ tb = base_bytes_lut[tgt].to(torch.int32)
424
+ tb = tb + (has_lead_lut[tgt] & ~is_bound_lut[prev]).to(torch.int32)
425
+ byte_count += tb.to(torch.float64).sum()
426
+ val_loss = (loss_sum / tok_count).item()
427
+ bpb = float((val_loss / math.log(2.0)) * (tok_count.item() / byte_count.item()))
428
+
429
+ if not math.isfinite(bpb) or bpb < float(cfg["dev_min_plausible_val_bpb"]):
430
+ return False, INV_VAL_IMPLAUSIBLE, bpb if math.isfinite(bpb) else None, \
431
+ f"val_bpb={bpb} below plausibility floor (forged loss / contamination)"
432
+ if bpb > float(cfg["dev_quality_floor_val_bpb"]):
433
+ return False, INV_VAL_FLOOR, bpb, f"val_bpb={bpb:.4f} above dev quality floor"
434
+ return True, None, bpb, f"ok params={n_params:,} val_bpb={bpb:.4f}"
435
+
436
+
437
+ def main() -> int:
438
+ try:
439
+ cfg = _cfg()
440
+ except Exception as exc:
441
+ _harness_error(f"could not read dev manifest: {type(exc).__name__}: {exc}")
442
+ return 0
443
+
444
+ submission_py = Path(cfg["submission_dir"]) / "train_gpt.py"
445
+ if not submission_py.exists():
446
+ _write_state(False, INV_SUBMISSION_MISSING, None, 0.0, None, None,
447
+ {"detail": f"{submission_py} not found"})
448
+ return 0
449
+
450
+ import tempfile
451
+ run_root = Path(tempfile.mkdtemp(prefix="a4_devloop_"))
452
+ try:
453
+ shard_dir = run_root / "_dev_shard"
454
+ if not build_dev_shard(Path(cfg["corpus_dir"]), shard_dir,
455
+ int(cfg["dev_train_tokens"]), int(cfg["dev_train_offset"])):
456
+ _harness_error("could not build the public dev shard (corpus missing/too small)")
457
+ return 0
458
+ out_dir = run_root / "dev_seed"
459
+ ckpt, uid_dropped, observed_euid, note, stderr_txt = train_candidate(
460
+ cfg, submission_py, shard_dir, out_dir)
461
+ if ckpt is None:
462
+ # distinguish an infra failure (import/traceback, no test ran) from a real
463
+ # "recipe produced no checkpoint" — the former is refunded as harness_error.
464
+ infra = any(s in (stderr_txt or "") for s in
465
+ ("ModuleNotFoundError", "ImportError", "Traceback (most recent call last)"))
466
+ if infra and "train_for_budget missing" not in (stderr_txt or ""):
467
+ _harness_error("dev training subprocess raised an infra error before producing a "
468
+ f"checkpoint: {(stderr_txt or '').strip().splitlines()[-1:] }")
469
+ return 0
470
+ _write_state(False, INV_NO_CHECKPOINT, None, 0.0, uid_dropped, observed_euid,
471
+ {"note": note})
472
+ return 0
473
+ try:
474
+ ok, inv, bpb, detail = evaluate(cfg, submission_py, ckpt)
475
+ except Exception as exc:
476
+ _harness_error(f"dev evaluate() raised: {type(exc).__name__}: {exc}")
477
+ return 0
478
+ dev_reward = (1.0 / bpb) if (ok and bpb and bpb > 0) else 0.0
479
+ _write_state(ok, inv, bpb, dev_reward, uid_dropped, observed_euid, {"detail": detail})
480
+ return 0
481
+ finally:
482
+ try:
483
+ shutil.rmtree(run_root, ignore_errors=True)
484
+ except Exception:
485
+ pass
486
+
487
+
488
+ if __name__ == "__main__":
489
+ raise SystemExit(main())
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/private/manifest.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "kb_loop_dev_manifest_v1",
3
+ "task_id": "e2e-a4-token-efficiency-budget",
4
+ "note": "DEV-ONLY proxy constants for the per-round loop. These are BAKED here (root:root 0600, unreadable by the solver's dropped uid) and are read from THIS FILE ONLY. They are NOT read from the environment, because the loop engine runs in the solver-writable session shell and anything it reads from env is attacker-controlled. This file contains NO calibrated anchor (baseline_bpb), NO ref_speedup, and NO held-out corpus: the per-round signal is an ABSOLUTE public-proxy val_bpb, never normalised against the graded anchor. The graded score is produced after the session by the runner from a freshly-uploaded /tests over the HIDDEN test split; this loop only decides WHICH snapshot is graded.",
5
+ "dev_train_tokens": 3000000,
6
+ "dev_train_tokens_note": "the per-round proxy trains the candidate recipe on a SMALL public token budget (3M vs the graded 24M), sliced deterministically from the PUBLIC /data/datasets/wikitext_bpe8k/train.bin the solver already has. The budget is TOKENS, not wall-clock, so the resulting val_bpb is a stable function of the recipe+data+seed and is IMMUNE to node speed (a fast node and a slow node consume the same tokens and produce ~the same model); this is the property that makes a stable per-round dev signal achievable for this task and not for its wall-clock siblings.",
7
+ "dev_seed": 1234,
8
+ "dev_seed_note": "a FIXED dev seed distinct from every graded seed (1337/2027/90101) so the proxy cannot be seed-matched to the grade.",
9
+ "dev_train_offset": 4000000,
10
+ "dev_guard_seconds": 240.0,
11
+ "dev_guard_grace_seconds": 30.0,
12
+ "dev_guard_note": "wall-clock FEASIBILITY GUARD for the proxy training only, set generously relative to the 3M dev token budget so even a slow node finishes the dev tokens BEFORE the guard fires — this is what keeps the signal node-speed-immune. Enforced by an external setsid process-group kill, never a cooperative in-loop timer.",
13
+ "dev_val_tokens": 131072,
14
+ "dev_param_floor": 20000000,
15
+ "dev_param_cap": 45000000,
16
+ "dev_param_note": "the SAME [floor, cap] the graded scorer re-counts. Enforced in the per-round self-check ON PURPOSE, so the public proxy does NOT coach the solver toward a sub-floor 'shrink to the parameter floor' model that the graded scorer would still reject. (Task-design residual: at a 24M-token budget shrinking toward the 20M floor is itself a real source of reward. Enforcing the same floor in the dev proxy keeps the loop from actively teaching that exploit, but does not remove it from the graded reward surface.)",
17
+ "dev_min_plausible_val_bpb": 1.0,
18
+ "dev_quality_floor_val_bpb": 5.0,
19
+ "dev_logits_position_variance_floor": 0.0001,
20
+ "dev_logits_loss_agreement_tol": 0.05,
21
+ "dev_uid": 65534,
22
+ "dev_uid_note": "the candidate's per-round proxy training runs as uid 65534 (nobody), NOT root — the SAME privilege drop the graded path uses. Kept for the loop for two reasons: (1) fidelity, so the proxy trains under the same constraints as the grade; (2) hardening, so the loop engine (which runs in the solver-writable shell) cannot be turned into a root-training oracle. Set to null to disable (NOT recommended). The child reports the euid it actually ran under.",
23
+ "corpus_dir": "/data/datasets/wikitext_bpe8k",
24
+ "tokenizer_path": "/data/tokenizers/wikitext_bpe8k.model",
25
+ "nanogpt_repo": "/app/repo",
26
+ "submission_dir": "/app/submission"
27
+ }
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/sanitize_feedback.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """/opt/loop/sanitize_feedback.py — emit ONLY the leak-free per-round feedback for
3
+ e2e-a4-token-efficiency-budget.
4
+
5
+ Reads /logs/loop/dev/{verifier_state.json,reward.json,harness_error.txt} and
6
+ /logs/loop/{count,best.json}; prints the sanitized block the solver reads.
7
+
8
+ NEVER emits: the held-out corpus, the calibrated baseline_bpb / ref_speedup, the hidden
9
+ seeds / token budget / thresholds, or any /tests content — NONE of which is even in this
10
+ container. Emits: submission index + remaining, correctness pass/fail (+ the NAMED failing
11
+ invariant on fail), the ABSOLUTE public-proxy dev_val_bpb (explicitly NOT the graded score),
12
+ best_so_far, and finalize_allowed. The dev signal is a public proxy on a small public token
13
+ budget; the graded score is computed after the session over the hidden test split.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from pathlib import Path
19
+
20
+ LOOP = Path("/logs/loop")
21
+ DEV = LOOP / "dev"
22
+ MIN_SUB = 1
23
+ MAX_SUB = 16
24
+
25
+
26
+ def _load(p: Path) -> dict:
27
+ try:
28
+ return json.loads(p.read_text())
29
+ except Exception:
30
+ return {}
31
+
32
+
33
+ def main() -> int:
34
+ count = 0
35
+ cf = LOOP / "count"
36
+ if cf.is_file():
37
+ try:
38
+ count = int("".join(ch for ch in cf.read_text() if ch.isdigit()) or "0")
39
+ except Exception:
40
+ count = 0
41
+
42
+ # harness_error path: submit.sh has already refunded; say so and stop.
43
+ he = DEV / "harness_error.txt"
44
+ if he.is_file() and he.stat().st_size > 0:
45
+ print(f"submission {count}/{MAX_SUB} — harness_error")
46
+ print("harness_error: the DEV scoring engine itself failed — this is NOT a defect in your")
47
+ print("code and this attempt was REFUNDED (your budget is unchanged). Do NOT debug the")
48
+ print("harness; just retry submit, or keep optimizing and retry.")
49
+ return 0
50
+
51
+ state = _load(DEV / "verifier_state.json")
52
+ reward = _load(DEV / "reward.json")
53
+ best = _load(LOOP / "best.json")
54
+
55
+ correctness_ok = bool(state.get("correctness_ok"))
56
+ failing_inv = state.get("failing_invariant") or ""
57
+ dev_val_bpb = reward.get("dev_val_bpb")
58
+ remaining = max(0, MAX_SUB - count)
59
+ finalize_allowed = count >= MIN_SUB
60
+
61
+ print(f"submission {count}/{MAX_SUB}")
62
+ if correctness_ok:
63
+ print("correctness: PASS")
64
+ if isinstance(dev_val_bpb, (int, float)):
65
+ print(f"dev_val_bpb: {float(dev_val_bpb):.4f} "
66
+ "(PUBLIC dev proxy — lower is better — NOT your graded score)")
67
+ else:
68
+ print("correctness: FAIL")
69
+ print(f" failing_invariant: {failing_inv or 'unknown'}")
70
+ # uid-drop transparency: the per-round training runs unprivileged, same as the grade.
71
+ if state.get("dev_uid_dropped") is not None:
72
+ print(f"dev_training_uid_dropped: {'true' if state.get('dev_uid_dropped') else 'false'}"
73
+ f" (observed euid {state.get('observed_euid')})")
74
+
75
+ if best and best.get("submission"):
76
+ bb = best.get("dev_val_bpb")
77
+ bb_s = f"{float(bb):.4f}" if isinstance(bb, (int, float)) else "n/a"
78
+ print(f"best_so_far: submission {best.get('submission')}, dev_val_bpb {bb_s}")
79
+ else:
80
+ print("best_so_far: (no correctness-passing submission yet)")
81
+
82
+ print(f"remaining: {remaining}")
83
+ print(f"finalize_allowed: {'true' if finalize_allowed else 'false'} "
84
+ f"(you may --finalize at any k>=1; there is no minimum and no 'k rounds without gain' rule)")
85
+ return 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/score_engine.sh ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # /opt/loop/score_engine.sh — the baked in-session DEV scoring engine for
3
+ # e2e-a4-token-efficiency-budget. Runs the candidate recipe on a SMALL public token
4
+ # shard under the uid-65534 drop and scores an ABSOLUTE public-proxy val_bpb.
5
+ # Called ONLY by /opt/loop/submit.sh. 0700 root-owned; the solver's dropped uid cannot
6
+ # read this file or /opt/loop/private/**.
7
+ #
8
+ # 🔴 It reads its constants from /opt/loop/private/manifest.json ONLY — never from the
9
+ # environment. The loop runs in the solver-writable session shell, so anything read from
10
+ # env is attacker-controlled; in particular the reward's anchor is NOT in this container
11
+ # at all (it is uploaded fresh to /tests at grading), and this engine never reads /tests.
12
+ set -uo pipefail
13
+ # The agent invokes submit.sh from a NON-login shell, so bare python3 has no torch.
14
+ # Pin the kernelbench venv onto PATH so python AND the training subprocess have torch.
15
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
16
+
17
+ DEV_OUT=/logs/loop/dev
18
+ mkdir -p "$DEV_OUT"
19
+ # clear the previous round's artifacts so a stale file never masquerades as this round
20
+ rm -f "$DEV_OUT/verifier_state.json" "$DEV_OUT/reward.json" "$DEV_OUT/harness_error.txt" 2>/dev/null || true
21
+
22
+ PY="$(command -v python3 || command -v python)"
23
+ if [ -z "$PY" ]; then
24
+ echo "harness_error: no python on PATH" > "$DEV_OUT/harness_error.txt"
25
+ exit 3
26
+ fi
27
+
28
+ # Pin thread counts so the (cheap) eval does not depend on node core-count.
29
+ export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}"
30
+ export MKL_NUM_THREADS="${MKL_NUM_THREADS:-8}"
31
+ export OPENBLAS_NUM_THREADS="${OPENBLAS_NUM_THREADS:-8}"
32
+
33
+ "$PY" /opt/loop/private/dev_eval.py
34
+ rc=$?
35
+
36
+ # dev_eval writes its own JSON on every path it reaches. If the interpreter itself died
37
+ # (missing dep / OOM / SIGKILL) nothing was written -> classify as harness_error so the
38
+ # round is refunded rather than mis-scored as a candidate defect.
39
+ if [ ! -s "$DEV_OUT/verifier_state.json" ] && [ ! -s "$DEV_OUT/harness_error.txt" ]; then
40
+ echo "harness_error: dev_eval.py died before writing a result (rc=$rc)" > "$DEV_OUT/harness_error.txt"
41
+ exit 3
42
+ fi
43
+ # propagate the refund signal if dev_eval flagged an infra failure
44
+ if [ -s "$DEV_OUT/harness_error.txt" ]; then
45
+ exit 3
46
+ fi
47
+ exit 0
tasks/e2e/a4-token-efficiency-budget/task/environment/loop_overlay/opt_loop/submit.sh ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # e2e-a4-token-efficiency-budget — loop16 submit.sh (protocol 1..16, model decides)
4
+ # ============================================================================
5
+ # The solver's ONLY sanctioned in-session scoring interface. 0755 root:root; the engine
6
+ # and private dev assets it calls are 0700 root-owned (unreadable by the solver's uid).
7
+ #
8
+ # bash /opt/loop/submit.sh # score current state, get feedback
9
+ # bash /opt/loop/submit.sh --finalize [--reason "..."] # plant best-of-k, end the loop
10
+ #
11
+ # Budget: min=1, max=16. --finalize is accepted at ANY k>=1 (there is no minimum and no
12
+ # "k consecutive rounds without gain" rule); at k=16 the harness auto-finalizes.
13
+ #
14
+ # Each round is scored by /opt/loop/score_engine.sh on a PUBLIC dev proxy (a small public
15
+ # token budget + a first-principles correctness self-check): the overlay contains NO held-out
16
+ # corpus, NO reference recipe and NO calibrated anchor, so the per-round dev_val_bpb is a
17
+ # PUBLIC PROXY, not the graded score. The GRADED score is produced after the session by the
18
+ # runner from a freshly-uploaded /tests over the HIDDEN test split, against whatever this
19
+ # script plants.
20
+ #
21
+ # a4 has TWO editable graded surfaces — /app/submission (the entry contract the grader loads)
22
+ # and /app/repo (the nanoGPT the recipe imports LIVE at grading). Best-of-k therefore snapshots
23
+ # and plants BOTH: /app/repo via git tree-hash (read-tree + checkout-index), /app/submission via
24
+ # a per-round tarball. On finalize the BEST correctness-passing snapshot (not the last edit) is
25
+ # planted; /app/repo HEAD stays at the baked baseline commit.
26
+
27
+ # git-safe-directory: a crane-appended /app/repo is root-owned; without this every git op
28
+ # fails "dubious ownership". MUST be first.
29
+ git config --global --add safe.directory '*' 2>/dev/null || true
30
+
31
+ # PATH-pin: agent shell + runner exec are NON-login; pin the venv so python has torch.
32
+ export PATH=/opt/kernelbench-venv/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
33
+ set -uo pipefail
34
+
35
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
36
+ REPO=/app/repo
37
+ SUBM=/app/submission
38
+ BASE_SUBM=/opt/loop/baseline_submission # pristine shipped starter (baked)
39
+ LOOP=/logs/loop
40
+ DEV="$LOOP/dev"
41
+ SUBS="$LOOP/submissions"
42
+ mkdir -p "$LOOP" "$SUBS" "$DEV"
43
+
44
+ MIN_SUBMISSIONS=1
45
+ MAX_SUBMISSIONS=16
46
+ COUNT_FILE="$LOOP/count"
47
+ BEST_FILE="$LOOP/best.json"
48
+ STATE_JSONL="$LOOP/state.jsonl"
49
+
50
+ TASK_ID="$(python3 -c 'import json;print(json.load(open("/opt/loop/private/manifest.json")).get("task_id",""))' 2>/dev/null || true)"
51
+ [ -n "$TASK_ID" ] || TASK_ID="e2e-a4-token-efficiency-budget"
52
+
53
+ _read_count() {
54
+ if [ -f "$COUNT_FILE" ]; then
55
+ awk 'NR==1{gsub(/[^0-9]/,""); if($0=="")$0="0"; print; exit}' "$COUNT_FILE"
56
+ else
57
+ echo 0
58
+ fi
59
+ }
60
+
61
+ # git tree-hash of the current /app/repo working tree (non-mutating index add).
62
+ _repo_tree() {
63
+ git -C "$REPO" add -A >/dev/null 2>&1 || true
64
+ git -C "$REPO" write-tree 2>/dev/null || git -C "$REPO" rev-parse "HEAD^{tree}" 2>/dev/null || echo ""
65
+ }
66
+
67
+ # ------------------- argument parsing -------------------
68
+ MODE=submit
69
+ REASON=""
70
+ while [ "$#" -gt 0 ]; do
71
+ case "$1" in
72
+ --finalize) MODE=finalize; shift ;;
73
+ --reason) REASON="${2:-}"; shift 2 ;;
74
+ --reason=*) REASON="${1#--reason=}"; shift ;;
75
+ *) echo "usage: bash /opt/loop/submit.sh [--finalize [--reason \"<text>\"]]" >&2; exit 2 ;;
76
+ esac
77
+ done
78
+
79
+ # ------------------- finalize -------------------
80
+ if [ "$MODE" = finalize ]; then
81
+ CUR="$(_read_count)"; CUR="${CUR:-0}"
82
+ if [ "$CUR" -lt "$MIN_SUBMISSIONS" ]; then
83
+ echo "nothing to finalize yet: score at least $MIN_SUBMISSIONS submission first (you have $CUR)."
84
+ echo "Run: bash /opt/loop/submit.sh"
85
+ exit 1
86
+ fi
87
+
88
+ WIN_SUB=""; WIN_REPO_TREE=""
89
+ if [ -f "$BEST_FILE" ]; then
90
+ WIN_SUB="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("submission",""))' "$BEST_FILE" 2>/dev/null || true)"
91
+ WIN_REPO_TREE="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("repo_tree","") or "")' "$BEST_FILE" 2>/dev/null || true)"
92
+ fi
93
+
94
+ # --- plant /app/repo: reset to baked baseline HEAD, then load the winning tree ---
95
+ git -C "$REPO" reset -q --hard HEAD 2>/dev/null || true
96
+ git -C "$REPO" clean -qfd 2>/dev/null || true
97
+ PLANT_REPO="none"
98
+ if [ -n "$WIN_REPO_TREE" ] && git -C "$REPO" read-tree "$WIN_REPO_TREE" 2>"$LOOP/finalize_apply.log"; then
99
+ git -C "$REPO" checkout-index -f -a 2>>"$LOOP/finalize_apply.log" && PLANT_REPO="read-tree"
100
+ fi
101
+ if [ "$PLANT_REPO" = "none" ] && [ -n "$WIN_SUB" ] && [ -s "$SUBS/$WIN_SUB/repo.diff" ]; then
102
+ git -C "$REPO" apply --whitespace=nowarn "$SUBS/$WIN_SUB/repo.diff" 2>>"$LOOP/finalize_apply.log" \
103
+ && PLANT_REPO="diff-apply" || true
104
+ fi
105
+
106
+ # --- plant /app/submission: extract the winning tarball (or restore pristine starter) ---
107
+ PLANT_SUBM="none"
108
+ if [ -n "$WIN_SUB" ] && [ -s "$SUBS/$WIN_SUB/submission.tgz" ]; then
109
+ rm -rf "${SUBM:?}/"* 2>/dev/null || true
110
+ mkdir -p "$SUBM"
111
+ if tar xzf "$SUBS/$WIN_SUB/submission.tgz" -C "$SUBM" 2>>"$LOOP/finalize_apply.log"; then
112
+ PLANT_SUBM="tar"
113
+ fi
114
+ fi
115
+ if [ "$PLANT_SUBM" = "none" ]; then
116
+ # no correctness-passing snapshot -> restore the pristine shipped starter
117
+ rm -rf "${SUBM:?}/"* 2>/dev/null || true
118
+ mkdir -p "$SUBM"
119
+ if [ -d "$BASE_SUBM" ]; then
120
+ cp -a "$BASE_SUBM/." "$SUBM/" 2>>"$LOOP/finalize_apply.log" && PLANT_SUBM="baseline_restore"
121
+ fi
122
+ fi
123
+
124
+ REASON="$REASON" WIN_SUB="$WIN_SUB" WIN_REPO_TREE="$WIN_REPO_TREE" CUR="$CUR" \
125
+ PLANT_REPO="$PLANT_REPO" PLANT_SUBM="$PLANT_SUBM" TASK_ID="$TASK_ID" python3 - <<'PY'
126
+ import json, os, hashlib
127
+ from pathlib import Path
128
+ LOOP = Path('/logs/loop')
129
+ try: best = json.loads((LOOP / 'best.json').read_text())
130
+ except Exception: best = {}
131
+ traj = []
132
+ try:
133
+ for line in (LOOP / 'state.jsonl').read_text().splitlines():
134
+ line = line.strip()
135
+ if not line: continue
136
+ r = json.loads(line)
137
+ traj.append({'submission': r.get('submission'),
138
+ 'dev_val_bpb': r.get('dev_val_bpb'),
139
+ 'correctness_ok': r.get('correctness_ok')})
140
+ except Exception: pass
141
+ # sha of the planted entry, so best-of-k can be PROVEN (not just claimed)
142
+ planted_sha = None
143
+ try:
144
+ planted_sha = hashlib.sha256(Path('/app/submission/train_gpt.py').read_bytes()).hexdigest()
145
+ except Exception:
146
+ planted_sha = None
147
+ out = {
148
+ 'schema_version': 'kb_loop_finalize_v1',
149
+ 'task_id': os.environ.get('TASK_ID') or 'e2e-a4-token-efficiency-budget',
150
+ 'mode': 'baked',
151
+ 'plant_method': {'submission': os.environ.get('PLANT_SUBM'), 'repo': os.environ.get('PLANT_REPO')},
152
+ 'submissions_used': int(os.environ.get('CUR') or 0),
153
+ 'min_submissions': 1, 'max_submissions': 16,
154
+ 'winning_submission': (best.get('submission') if best else None),
155
+ 'winning_repo_tree': os.environ.get('WIN_REPO_TREE') or None,
156
+ 'winning_dev_val_bpb': (best.get('dev_val_bpb') if best else None),
157
+ 'planted_train_gpt_sha256': planted_sha,
158
+ 'dev_public_proxy_trajectory': traj,
159
+ 'termination_reason': os.environ.get('REASON') or '',
160
+ 'note': 'dev_val_bpb is an in-session PUBLIC-proxy on a small public token budget, used ONLY to rank best-of-k; the authoritative score is the runner end-of-session grade of /app/submission + /app/repo over the hidden test split.',
161
+ }
162
+ (LOOP / 'finalize.json').write_text(json.dumps(out, indent=2, sort_keys=True) + '\n')
163
+ PY
164
+
165
+ if [ -n "$WIN_SUB" ] && { [ "$PLANT_SUBM" = "tar" ] || [ "$PLANT_REPO" != "none" ]; }; then
166
+ echo "finalized: submission $WIN_SUB at k=$CUR/$MAX_SUBMISSIONS (submission planted via $PLANT_SUBM, repo via $PLANT_REPO); the grader will now score /app/submission + /app/repo"
167
+ else
168
+ echo "finalized: no correctness-passing submission in $CUR tries — the shipped starter was restored; the grader will now score it (under this task's bounded reward, an implementation that does not beat the tuned-AdamW starter scores 0)"
169
+ fi
170
+ exit 0
171
+ fi
172
+
173
+ # ------------------- submit -------------------
174
+ CUR="$(_read_count)"; CUR="${CUR:-0}"
175
+ if [ "$CUR" -ge "$MAX_SUBMISSIONS" ]; then
176
+ echo "submission $CUR/$MAX_SUBMISSIONS"
177
+ echo "budget exhausted — auto-finalizing best-of-$MAX_SUBMISSIONS"
178
+ exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
179
+ fi
180
+
181
+ # Run the DEV engine on the LIVE surfaces.
182
+ bash "$HERE/score_engine.sh"
183
+ engine_rc=$?
184
+
185
+ # HARNESS-ERROR refund: infra failure (rc=3 or marker) -> do NOT consume budget.
186
+ if [ "$engine_rc" -eq 3 ] || [ -f "$DEV/harness_error.txt" ]; then
187
+ python3 "$HERE/sanitize_feedback.py"
188
+ exit 0
189
+ fi
190
+
191
+ NEXT=$((CUR + 1))
192
+ echo "$NEXT" > "$COUNT_FILE"
193
+
194
+ SNAP="$SUBS/$NEXT"
195
+ mkdir -p "$SNAP"
196
+ REPO_TREE="$(_repo_tree)"
197
+ echo "${REPO_TREE:-}" > "$SNAP/repo_tree.txt"
198
+ git -C "$REPO" diff --binary HEAD > "$SNAP/repo.diff" 2>/dev/null || true
199
+ tar czf "$SNAP/submission.tgz" -C "$SUBM" . 2>/dev/null || true
200
+ for f in verifier_state.json reward.json; do
201
+ [ -f "$DEV/$f" ] && cp "$DEV/$f" "$SNAP/$f" 2>/dev/null || true
202
+ done
203
+
204
+ NEXT="$NEXT" REPO_TREE="$REPO_TREE" python3 - <<'PY'
205
+ import json, os, time
206
+ from pathlib import Path
207
+ LOOP = Path('/logs/loop'); DEV = LOOP / 'dev'
208
+ k = int(os.environ['NEXT']); repo_tree = os.environ.get('REPO_TREE') or ''
209
+ try: state = json.loads((DEV / 'verifier_state.json').read_text())
210
+ except Exception: state = {}
211
+ try: reward = json.loads((DEV / 'reward.json').read_text())
212
+ except Exception: reward = {}
213
+ corr_ok = bool(state.get('correctness_ok'))
214
+ dev_reward = float(reward.get('dev_score') or 0.0) # higher is better (= 1/val_bpb)
215
+ dev_val_bpb = reward.get('dev_val_bpb')
216
+ row = {'submission': k, 'ts': int(time.time()), 'correctness_ok': corr_ok,
217
+ 'dev_score': dev_reward, 'dev_val_bpb': dev_val_bpb, 'repo_tree': repo_tree,
218
+ 'failing_invariant': state.get('failing_invariant') or ''}
219
+ with (LOOP / 'state.jsonl').open('a', encoding='utf-8') as f:
220
+ f.write(json.dumps(row) + '\n')
221
+ if corr_ok:
222
+ bp = LOOP / 'best.json'
223
+ try: best = json.loads(bp.read_text())
224
+ except Exception: best = None
225
+ if best is None or dev_reward > float(best.get('dev_score') or -1.0):
226
+ bp.write_text(json.dumps({'submission': k, 'dev_score': dev_reward,
227
+ 'dev_val_bpb': dev_val_bpb, 'repo_tree': repo_tree},
228
+ indent=2, sort_keys=True) + '\n')
229
+ PY
230
+
231
+ python3 "$HERE/sanitize_feedback.py"
232
+
233
+ if [ "$NEXT" -ge "$MAX_SUBMISSIONS" ]; then
234
+ echo ""
235
+ echo "--- budget exhausted (submission $MAX_SUBMISSIONS/$MAX_SUBMISSIONS). Auto-finalizing best-of-$MAX_SUBMISSIONS. ---"
236
+ exec bash "$HERE/submit.sh" --finalize --reason "auto-finalize at budget ceiling"
237
+ fi
238
+ exit 0
tasks/e2e/a4-token-efficiency-budget/task/environment/submission/train_gpt.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # e2e-a4-token-efficiency-budget : the STRONG-BASELINE recipe + the solver's starting point.
2
+ #
3
+ # THE TASK. The grader gives you a FIXED NUMBER OF TRAINING TOKENS and scores the held-out
4
+ # val_bpb of the checkpoint your recipe produces. Wall-clock is NOT the budget: making the
5
+ # step faster does not let you consume more tokens, so throughput buys you NOTHING. The only
6
+ # way to a lower loss is to extract MORE LEARNING PER TOKEN -- real sample efficiency.
7
+ #
8
+ # THIS FILE IS BOTH (a) the reviewer's strong baseline (the 1.0 anchor you must beat) and
9
+ # (b) a starting point you may rewrite entirely. It is NOT a contract. The tuned-AdamW recipe
10
+ # below was selected as the BEST of a batch-size/learning-rate sweep at this token budget, so
11
+ # re-tuning those knobs will not move your score -- you have to change what the training
12
+ # ALGORITHM is (optimizer / architecture / data schedule).
13
+ #
14
+ # THE ONLY CONTRACT (both required):
15
+ # train_for_budget(seed, out_dir, budget_seconds) -> writes <out_dir>/model_ckpt.pt
16
+ # load_model_for_verification(checkpoint_path, device) -> nn.Module or (args, model)
17
+ # with model(x) -> logits (B,T,V) position-dependent, and model(x, y) -> scalar loss equal to
18
+ # F.cross_entropy(logits.view(-1,V), y.view(-1)) on those logits.
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ import os
23
+ import sys
24
+ import time
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import torch
29
+ import torch.nn as nn
30
+
31
+ REPO = os.environ.get("NANOGPT_REPO", "/app/repo")
32
+ if REPO not in sys.path:
33
+ sys.path.insert(0, REPO)
34
+ from model import GPT, GPTConfig # noqa: E402 (from /app/repo/model.py -- fully editable)
35
+
36
+
37
+ class Hyperparameters:
38
+ """Starting point. Nothing here is required by scoring."""
39
+ # The grader points DATA_PATH at YOUR TOKEN BUDGET: a shard holding exactly
40
+ # TOKEN_BUDGET tokens. It is the only readable token source during scoring.
41
+ data_path = os.environ.get("DATA_PATH", "/data/datasets/wikitext_bpe8k")
42
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "/data/tokenizers/wikitext_bpe8k.model")
43
+ seed = int(os.environ.get("SEED", "1337"))
44
+ token_budget = int(os.environ.get("TOKEN_BUDGET", "24000000"))
45
+ max_params = int(os.environ.get("MAX_PARAMS", "45000000"))
46
+
47
+ vocab_size = 8192
48
+ train_seq_len = 512 # the verifier reads this as seq_len
49
+ block_size = 512
50
+ val_batch_size = 32_768
51
+
52
+ # ~34M-parameter model, comfortably inside the parameter cap the grader re-counts.
53
+ n_layer = 8
54
+ n_head = 8
55
+ n_embd = 512
56
+ dropout = 0.0
57
+ bias = False
58
+
59
+ # TUNED AdamW at this token budget: this peak LR was selected as the BEST of a
60
+ # learning-rate / batch-size sweep at this budget, so re-tuning it will not help.
61
+ micro_batch = 8
62
+ grad_accum = 1
63
+ learning_rate = 5.0e-4
64
+ weight_decay = 0.1
65
+ beta1, beta2 = 0.9, 0.95
66
+ grad_clip = 1.0
67
+ warmup_frac = 0.02 # trapezoidal schedule: warmup -> flat -> linear cooldown
68
+ cooldown_frac = 0.40
69
+ min_lr_frac = 0.02
70
+ save_every_sec = 20.0 # save periodically: the grader may stop you at any moment
71
+
72
+
73
+ class TokenStream:
74
+ """Sequential single-epoch reader over the budgeted shard.
75
+
76
+ Reads the shard start-to-end exactly once, so the recipe consumes its token budget and
77
+ no token is repeated (repetition invites memorisation, which the held-out eval punishes).
78
+ The loader implementation is entirely yours to change -- order, packing, curriculum and
79
+ sequence length are all levers."""
80
+
81
+ def __init__(self, data_path: str, seq_len: int, device):
82
+ self.data = np.memmap(Path(data_path) / "train.bin", dtype=np.uint16, mode="r")
83
+ self.seq_len = seq_len
84
+ self.device = device
85
+ self.pos = 0
86
+ self.tokens_served = 0
87
+ self.exhausted = False
88
+
89
+ def batch(self, n: int):
90
+ need = n * self.seq_len + 1
91
+ if self.pos + need >= len(self.data):
92
+ self.pos = 0
93
+ self.exhausted = True # one full pass over the budget completed
94
+ blk = np.asarray(self.data[self.pos:self.pos + need], dtype=np.int64)
95
+ self.pos += n * self.seq_len
96
+ self.tokens_served += n * self.seq_len
97
+ x = torch.from_numpy(blk[:-1].reshape(n, self.seq_len))
98
+ y = torch.from_numpy(blk[1:].reshape(n, self.seq_len))
99
+ return (x.pin_memory().to(self.device, non_blocking=True),
100
+ y.pin_memory().to(self.device, non_blocking=True))
101
+
102
+
103
+ class _VerifierAdapter(nn.Module):
104
+ """nanoGPT's GPT.forward(idx, targets) returns (logits, loss) and only computes full
105
+ logits when targets are supplied; adapt it to the verifier's forward contract."""
106
+
107
+ def __init__(self, gpt: GPT):
108
+ super().__init__()
109
+ self.gpt = gpt
110
+
111
+ def forward(self, idx, targets=None):
112
+ logits, loss = self.gpt(idx, idx if targets is None else targets)
113
+ return logits if targets is None else loss
114
+
115
+
116
+ def _build(args: Hyperparameters, device) -> GPT:
117
+ cfg = GPTConfig(block_size=args.block_size, vocab_size=args.vocab_size,
118
+ n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd,
119
+ dropout=args.dropout, bias=args.bias)
120
+ return GPT(cfg).to(device)
121
+
122
+
123
+ def _save(model: GPT, cfg: GPTConfig, out_ckpt: Path) -> None:
124
+ m = getattr(model, "_orig_mod", model)
125
+ tmp = str(out_ckpt) + ".tmp"
126
+ torch.save({"model": m.state_dict(),
127
+ "config": dict(block_size=cfg.block_size, vocab_size=cfg.vocab_size,
128
+ n_layer=cfg.n_layer, n_head=cfg.n_head, n_embd=cfg.n_embd,
129
+ dropout=0.0, bias=cfg.bias)}, tmp)
130
+ os.replace(tmp, out_ckpt) # atomic: a hard kill never leaves a half-written ckpt
131
+
132
+
133
+ def load_model_for_verification(checkpoint_path, device):
134
+ args = Hyperparameters()
135
+ obj = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
136
+ ck = obj.get("config", {})
137
+ cfg = GPTConfig(**ck) if ck else GPTConfig(
138
+ block_size=args.block_size, vocab_size=args.vocab_size, n_layer=args.n_layer,
139
+ n_head=args.n_head, n_embd=args.n_embd, dropout=0.0, bias=args.bias)
140
+ gpt = GPT(cfg)
141
+ sd = obj["model"]
142
+ if any(k.startswith("_orig_mod.") for k in sd):
143
+ sd = {k.replace("_orig_mod.", "", 1): v for k, v in sd.items()}
144
+ gpt.load_state_dict(sd, strict=True)
145
+ args.train_seq_len = cfg.block_size
146
+ args.vocab_size = cfg.vocab_size
147
+ return args, _VerifierAdapter(gpt).to(device).eval()
148
+
149
+
150
+ def train_for_budget(seed: int, out_dir, budget_seconds: float) -> None:
151
+ """Train on the token budget the grader made available at DATA_PATH.
152
+
153
+ `budget_seconds` is only a FEASIBILITY GUARD (generous); the real budget is the tokens.
154
+ """
155
+ args = Hyperparameters()
156
+ args.seed = int(seed)
157
+ out_ckpt = Path(out_dir) / "model_ckpt.pt"
158
+ out_ckpt.parent.mkdir(parents=True, exist_ok=True)
159
+
160
+ torch.manual_seed(args.seed)
161
+ np.random.seed(args.seed)
162
+ torch.backends.cuda.matmul.allow_tf32 = True
163
+ torch.backends.cudnn.allow_tf32 = True
164
+ device = torch.device("cuda", 0)
165
+ torch.cuda.set_device(device)
166
+
167
+ model = _build(args, device)
168
+ cfg = model.config
169
+ stream = TokenStream(args.data_path, args.train_seq_len, device)
170
+ # The shard IS the budget: one pass over it consumes exactly the token budget.
171
+ budget_tokens = int(stream.data.shape[0])
172
+ tokens_per_step = args.micro_batch * args.grad_accum * args.train_seq_len
173
+ total_steps = max(1, budget_tokens // tokens_per_step)
174
+ print(f"[train] seed={seed} params={sum(p.numel() for p in model.parameters())/1e6:.1f}M "
175
+ f"budget={budget_tokens/1e6:.2f}M tokens -> {total_steps} steps "
176
+ f"(micro={args.micro_batch} accum={args.grad_accum} seq={args.train_seq_len})",
177
+ flush=True)
178
+
179
+ opt = torch.optim.AdamW(model.parameters(), lr=args.learning_rate,
180
+ betas=(args.beta1, args.beta2),
181
+ weight_decay=args.weight_decay, fused=True)
182
+ warm = max(1, int(args.warmup_frac * total_steps))
183
+ cool = max(1, int(args.cooldown_frac * total_steps))
184
+ t0 = last_save = time.time()
185
+ guard = float(budget_seconds) * 0.94 if budget_seconds else float("inf")
186
+ model.train()
187
+ for step in range(total_steps):
188
+ if time.time() - t0 > guard: # never get hard-killed mid-save
189
+ break
190
+ if step < warm:
191
+ f = (step + 1) / warm
192
+ elif step > total_steps - cool:
193
+ f = max(args.min_lr_frac, (total_steps - step) / cool)
194
+ else:
195
+ f = 1.0
196
+ for g in opt.param_groups:
197
+ g["lr"] = args.learning_rate * f
198
+ opt.zero_grad(set_to_none=True)
199
+ for _ in range(args.grad_accum):
200
+ x, y = stream.batch(args.micro_batch)
201
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
202
+ _, loss = model(x, y)
203
+ (loss / args.grad_accum).backward()
204
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
205
+ opt.step()
206
+ if step % 200 == 0:
207
+ print(f"[train] step {step}/{total_steps} lr {args.learning_rate*f:.2e} "
208
+ f"loss {float(loss):.4f} tok {stream.tokens_served/1e6:.1f}M "
209
+ f"t {time.time()-t0:.0f}s", flush=True)
210
+ if time.time() - last_save >= args.save_every_sec:
211
+ _save(model, cfg, out_ckpt)
212
+ last_save = time.time()
213
+ _save(model, cfg, out_ckpt)
214
+ print(f"[train] done: {stream.tokens_served/1e6:.2f}M tokens consumed in "
215
+ f"{time.time()-t0:.0f}s -> {out_ckpt}", flush=True)
216
+
217
+
218
+ if __name__ == "__main__":
219
+ train_for_budget(int(os.environ.get("SEED", "1337")),
220
+ os.environ.get("OUT_DIR", "/app/submission"),
221
+ float(os.environ.get("MAX_WALLCLOCK_SEC", "900")))
tasks/e2e/a4-token-efficiency-budget/task/instruction.md ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Train the best language model you can from a FIXED NUMBER OF TRAINING TOKENS
2
+
3
+ You are given the full [nanoGPT](https://github.com/karpathy/nanoGPT) training system at
4
+ `/app/repo` (fully editable) and a tokenized WikiText-103 corpus. Your job is to **train the
5
+ best language model you can on ONE H20 GPU while consuming no more than a fixed budget of
6
+ training tokens**, then let the grader score it.
7
+
8
+ The grader then loads the checkpoint your training produced and measures its
9
+ **bits-per-byte (`val_bpb`) on a held-out WikiText-103 split you never see**. **Lower
10
+ `val_bpb` is better.**
11
+
12
+ ## How you are scored
13
+
14
+ Scoring is **bounded between 0.0 and 1.0**, and it is measured against **the starting recipe you
15
+ were given**:
16
+
17
+ - The provided starter is a **well-tuned AdamW** recipe at this token budget. It is a real,
18
+ complete, working recipe — and it is the bar. **Submitting it, or anything that does not
19
+ strictly improve on its held-out `val_bpb`, scores 0.**
20
+ - Beyond that, your score rises **continuously** with how much of the achievable `val_bpb` gap
21
+ you close. Reaching the quality of a strong reference recipe measured at this same token
22
+ budget scores **0.5**; pushing further keeps earning more, up to the 1.0 ceiling. Coming
23
+ close to the starter without passing it earns nothing — you have to actually beat it.
24
+ - Any hard-gate failure — over the parameter cap, a missing checkpoint, byte-identical weights
25
+ across seeds, a degenerate or forged-loss model, or touching the grader's files — scores
26
+ **0**, whatever the `val_bpb`.
27
+
28
+ So a mediocre-but-safe re-tune of the starter is worth exactly as much as no submission at all.
29
+ The whole game is pushing `val_bpb` as low as you can inside the token budget.
30
+
31
+ ## The budget is TOKENS, not time — read this carefully
32
+
33
+ This is what makes this task different from a throughput task:
34
+
35
+ - The grader **counts the training tokens your run consumes** and enforces a hard cap. The
36
+ count is taken by the grader from outside your process; it is not a number your code
37
+ reports.
38
+ - **Wall-clock is NOT the budget and speed earns you NOTHING here.** Making your training
39
+ step faster — mixed precision, `torch.compile`, a bigger batch, a faster data loader,
40
+ fusing kernels — does not let you consume more tokens, so it cannot improve your score.
41
+ (A generous wall-clock ceiling exists purely as a feasibility guard; see *Limits* below.)
42
+ - Therefore the only way to a lower loss is to **extract more learning from each token** —
43
+ i.e. real **sample efficiency**.
44
+
45
+ ## Why this is hard
46
+
47
+ The starting recipe is already a **well-tuned AdamW baseline** (tuned peak LR, warmup +
48
+ trapezoidal decay, gradient clipping, a batch size chosen at this token budget). The shallow
49
+ configuration wins are already taken: sweeping the batch size or the learning rate around this
50
+ point does **not** help — the reference was selected as the best of such a sweep. To beat it
51
+ you need to change **what the training algorithm actually is**, for example:
52
+
53
+ - **the optimizer / update rule** — e.g. spectral / orthogonalized updates for the hidden
54
+ weight matrices (the `Muon` family), second-order-flavoured preconditioning, per-layer
55
+ update scaling, or a different treatment of embeddings vs hidden layers vs the head;
56
+ - **the architecture** — normalization placement and type, rotary vs learned positions,
57
+ query/key normalization, the MLP nonlinearity, initialization scale (including zero-init of
58
+ residual projections), weight tying, skip/residual structure, logit scaling or softcapping;
59
+ - **the data schedule** — the order, packing, sequence length, and curriculum of the tokens
60
+ you spend, and how the batch size or LR schedule co-varies with it;
61
+ - **the loss / regularization** — auxiliary losses, weight-decay discipline, label smoothing.
62
+
63
+ Public references are fair game: the nanoGPT repo, the
64
+ [modded-nanogpt speedrun](https://github.com/KellerJordan/modded-nanogpt) and its record
65
+ history, the [Muon writeup](https://kellerjordan.github.io/posts/muon/), and the general
66
+ literature on optimizers, architectures and training schedules. **What is protected is the
67
+ grader's measurement, not the method** — reproducing a known good recipe is expected to score
68
+ well, and pushing past it is what earns a high score.
69
+
70
+ ## Data
71
+
72
+ - Train on the token shard the grader hands you at `DATA_PATH` (flat `uint16`, nanoGPT
73
+ layout). In your own session `/data/datasets/wikitext_bpe8k/train.bin` is available so you
74
+ can develop and iterate; at scoring `DATA_PATH` points at the budgeted shard instead.
75
+ - `/data/datasets/wikitext_bpe8k/val.bin` is your **local progress monitor** (the WikiText-103
76
+ *validation* split). The grader scores on the held-out *test* split — same distribution, so
77
+ your local measurement tracks the grader's within a small margin.
78
+ - Tokenizer: SentencePiece **BPE-8K** at `/data/tokenizers/wikitext_bpe8k.model`
79
+ (`vocab_size = 8192`).
80
+ - The corpus bytes are checksum-pinned by the grader, and the scored shard is cut from them.
81
+ Training on anything else — other data, generated data, or a modified copy — is a hard
82
+ failure.
83
+
84
+ ## What to submit (the entry contract)
85
+
86
+ Everything the grader needs must live under `/app/submission/`, and the grader calls **two
87
+ functions** in `/app/submission/train_gpt.py`:
88
+
89
+ 1. **`train_for_budget(seed, out_dir, budget_seconds)`** — your training entry. The grader
90
+ calls it once per scored seed and requires it to write a checkpoint to
91
+ `<out_dir>/model_ckpt.pt`. Save periodically: the grader stops you if you exceed the
92
+ wall-clock guard, and the latest saved checkpoint is what gets scored.
93
+ - The grader sets `DATA_PATH` in the environment to **your token budget** — a shard
94
+ containing *exactly* `TOKEN_BUDGET` tokens. **During scoring this shard is the only
95
+ readable token source** (the full corpus is locked for the duration of the run), so the
96
+ budget is enforced by construction rather than by trusting a counter. `SEED`,
97
+ `TOKEN_BUDGET`, `MAX_WALLCLOCK_SEC`, `MAX_PARAMS`, `TOKENIZER_PATH` and `NANOGPT_REPO`
98
+ are also in the environment.
99
+ - You may read the shard in **any order, packing, sequence length or curriculum**, and you
100
+ may pass over it more than once — the budget is the *number of tokens made available*,
101
+ and how you spend them is a lever. (Repeating tokens invites memorisation, which the
102
+ held-out score punishes; that trade-off is yours to make.)
103
+ - It is run from an isolated working directory that contains a copy of your **source**
104
+ files only. Model-weight blobs are not carried over, and training happens fresh every
105
+ time — so the checkpoint must be produced by this call.
106
+ 2. **`load_model_for_verification(checkpoint_path, device)`** — returns either an `nn.Module`
107
+ or `(args, model)`. The loaded model's `forward` must satisfy:
108
+ - `model(input_ids)` → floating-point logits `(batch, seq_len, vocab_size)` that depend on
109
+ token position;
110
+ - `model(input_ids, target_ids)` → a **scalar** loss equal (within a small tolerance) to
111
+ `F.cross_entropy(logits.reshape(-1, V), target_ids.reshape(-1))` on those same logits.
112
+
113
+ A working starting `train_gpt.py` (the tuned AdamW reference on nanoGPT's model, implementing
114
+ both functions) is provided — it is a starting point, **not** a contract. You may replace all
115
+ of it.
116
+
117
+ ## Limits (all enforced by the grader — disclosed so nothing surprises you)
118
+
119
+ - **Token budget** — the hard cap named in `TOKEN_BUDGET`, counted by the grader. Exceeding it
120
+ scores 0.
121
+ - **Parameter cap** — the grader re-counts the parameters of your loaded model and enforces the
122
+ cap named in `MAX_PARAMS`. This is why "just make the model enormous" is not the answer; you
123
+ must get more out of each token at a comparable model scale. There is also a minimum
124
+ parameter count, so a degenerate tiny model cannot pass.
125
+ - **Wall-clock ceiling** — `MAX_WALLCLOCK_SEC` is a *feasibility guard*, not the budget. It is
126
+ set generously (well above what the reference recipe needs) so that a slower-but-smarter
127
+ recipe is never penalised; a run that exceeds it is stopped and its latest checkpoint scored.
128
+ - **Fixed seed** — the training seed is fixed by the grader, so you cannot seed-shop. Your
129
+ recipe is scored as the **median over several grader-chosen seeds**, so it must be robust,
130
+ not lucky.
131
+ - **Real-LM checks** — the grader verifies your loaded model is a real language model: it
132
+ scores real held-out text noticeably better than arbitrary token IDs, its `forward(x,y)` loss
133
+ agrees with the cross-entropy of its `forward(x)` logits, its logits vary across positions,
134
+ and its `val_bpb` falls inside a plausible band. A degenerate or forged-loss model scores 0.
135
+ - **Fresh training** — the grader trains from scratch by running your entry; it does not accept
136
+ pre-trained weights. Handing back a checkpoint you built earlier instead of training scores 0.
137
+ - No internet access. All packages you need (including `torch`) are pre-installed.
138
+
139
+ ## Rules
140
+
141
+ - **Submission:** this is the **single-shot** form of the task — one recipe is graded in a single
142
+ pass, with no in-session submit command and no multi-round budget. Iterate locally and leave
143
+ your final recipe in place when you stop. (This package also ships a 16-round loop16 form,
144
+ built from `environment/Dockerfile.loop16`; that form has its own instruction with a
145
+ 1-to-16 submission budget and is the one `task.toml`'s `docker_image` points at.)
146
+ - **Do not** read, copy, grep, or edit any grader / held-out / timer file (`/tests/*`); do
147
+ **not** disable or tamper with the grader's token counter or wall-clock guard; do **not**
148
+ try to read the held-out corpus or infer the reference score. The grader fingerprints its own
149
+ files around every training call, so any of these scores the whole task **0**. (Consulting the public nanoGPT / modded-nanogpt / Muon references and the public
150
+ training literature is explicitly allowed — see above.)
151
+ - Solve this independently. Everything needed at scoring must persist under `/app/submission/`.
152
+
153
+ ## 提交方式
154
+
155
+ 把改动**留在工作树里**即可 —— 直接编辑允许的文件,不需要 `git commit`
156
+ (判分读工作树;仓库的 HEAD 必须停在初始基线 commit 上)。
tasks/e2e/a4-token-efficiency-budget/task/pre_artifacts.sh ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ============================================================================
3
+ # pre_artifacts.sh — e2e/a4-token-efficiency-budget
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:262: ENV NANOGPT_REPO=/app/repo \
33
+ # evidence Dockerfile:265: REPO_DIR=/app/repo \
34
+ # evidence Dockerfile:220: && cd /app/repo \
35
+ # evidence Dockerfile:225: && test "$(git rev-list --count HEAD)" = "1" \
36
+ # evidence test.sh:36: SUBMISSION_DIR="${SUBMISSION_DIR:-/app/submission}"
37
+ # evidence test.sh:128: SUBMISSION_DIR="${SUBMISSION_DIR}" PYTHONSAFEPATH=1 "${PY}" "$STAGE/compute_reward.py"
38
+ # /app/submission NOT a git repo -> full tree snapshot
39
+ # evidence Dockerfile:264: SUBMISSION_DIR=/app/submission \
40
+ # evidence Dockerfile:211: COPY environment/submission/train_gpt.py /app/submission/train_gpt.py
41
+ # evidence test.sh:36: SUBMISSION_DIR="${SUBMISSION_DIR:-/app/submission}"
42
+ #
43
+ # MULTI-ROOT FORMAT: this task has more than one capture root, so each root's diff in
44
+ # model.patch is introduced by a one-line banner
45
+ # # ==== pre_artifacts root=<dir> mode=<git-diff-vs-baseline|tree-snapshot...> ====
46
+ # and every path in model_files.txt is ABSOLUTE, so the roots can never be confused.
47
+ # Single-root tasks in this corpus emit a bare diff with no banner.
48
+ #
49
+ # CAVEATS (verified, not guessed):
50
+ # task.toml docker_image points at the loop16 OVERLAY (environment/Dockerfile.loop16, which
51
+ # also swaps /app/instruction.md for environment/loop_overlay/instruction_loop16.md). This
52
+ # script is form-agnostic: the capture roots are identical in both forms.
53
+ # ============================================================================
54
+ set -uo pipefail
55
+
56
+ OUT=/logs/artifacts
57
+ PATCH="$OUT/model.patch"
58
+ LIST="$OUT/model_files.txt"
59
+ MULTI=1 # 1 => several capture roots => each diff gets a banner line
60
+ MAX_BLOB_KB=5120 # per-file cap for the tree-snapshot path (keeps the patch sane)
61
+
62
+ mkdir -p "$OUT" 2>/dev/null || true
63
+ : > "$PATCH" 2>/dev/null || true
64
+ : > "$LIST" 2>/dev/null || true
65
+ git config --global --add safe.directory '*' >/dev/null 2>&1 || true
66
+
67
+ banner() { # $1=root $2=mode ; only when there is more than one root
68
+ if [ "$MULTI" = 1 ]; then
69
+ printf '# ==== pre_artifacts root=%s mode=%s ====\n' "$1" "$2" >> "$PATCH" 2>/dev/null
70
+ fi
71
+ return 0
72
+ }
73
+
74
+ list_add() { # stdin: paths relative to $1 -> absolute, one per line
75
+ sed "s|^|${1%/}/|" >> "$LIST" 2>/dev/null || true
76
+ return 0
77
+ }
78
+
79
+ capture_git() { # $1 = dir whose HEAD is the baked 1-commit baseline
80
+ root=$1
81
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
82
+ if ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
83
+ echo "[pre_artifacts] WARN $root has no .git -> falling back to a tree snapshot"
84
+ capture_tree "$root"
85
+ return 0
86
+ fi
87
+ # 🔴 SCRATCH INDEX. `add -AN` has to touch an index, and the verifier runs AFTER us and
88
+ # reads `git status --porcelain`; turning `?? newdir/` into `A newdir/file` there could
89
+ # flip a scope gate either way. So copy the repo's index aside and stage into the COPY —
90
+ # the repo's own .git/index is byte-identical when we are done.
91
+ tmpi=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || tmpi=""
92
+ gd=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true)
93
+ if [ -z "$gd" ]; then
94
+ gd=$(git -C "$root" rev-parse --git-dir 2>/dev/null || true)
95
+ case "$gd" in /*) ;; ?*) gd="$root/$gd" ;; esac
96
+ fi
97
+ if [ -n "$tmpi" ] && [ -n "$gd" ] && [ -f "$gd/index" ] && cp "$gd/index" "$tmpi/index" 2>/dev/null; then
98
+ GIT_INDEX_FILE="$tmpi/index"; export GIT_INDEX_FILE
99
+ else
100
+ echo "[pre_artifacts] WARN no scratch index for $root; staging into the real index"
101
+ fi
102
+ git -C "$root" add -AN . >/dev/null 2>&1 || true
103
+ base=HEAD
104
+ if ! git -C "$root" rev-parse -q --verify HEAD >/dev/null 2>&1; then
105
+ base=$(git -C "$root" hash-object -w -t tree /dev/null 2>/dev/null)
106
+ echo "[pre_artifacts] WARN $root has no commit; diffing against the empty tree"
107
+ else
108
+ n=$(git -C "$root" rev-list --count HEAD 2>/dev/null || echo 0)
109
+ case "$n" in ''|*[!0-9]*) n=0 ;; esac
110
+ if [ "$n" -gt 1 ]; then
111
+ base=$(git -C "$root" rev-list --max-parents=0 HEAD 2>/dev/null | tail -1)
112
+ echo "[pre_artifacts] 🔴 $root HEAD has $n commits but the contract says 1:"
113
+ echo "[pre_artifacts] the agent committed. Diffing from the ROOT commit ${base} so"
114
+ echo "[pre_artifacts] nothing is lost — but grading reads the WORKING TREE, so a moved"
115
+ echo "[pre_artifacts] HEAD can still zero an otherwise-correct solve."
116
+ fi
117
+ fi
118
+ [ -n "${base:-}" ] || base=HEAD
119
+ banner "$root" "git-diff-vs-baseline"
120
+ git -C "$root" diff --binary "$base" >> "$PATCH" 2>/dev/null || true
121
+ names=$(git -C "$root" diff --name-only "$base" 2>/dev/null)
122
+ echo "[pre_artifacts] $root: baseline $(git -C "$root" rev-parse --short "$base" 2>/dev/null), $(printf '%s\n' "$names" | grep -c . ) changed path(s)"
123
+ unset GIT_INDEX_FILE
124
+ [ -n "$tmpi" ] && rm -rf "$tmpi" 2>/dev/null
125
+ printf '%s\n' "$names" | grep -v '^$' | list_add "$root"
126
+ return 0
127
+ }
128
+
129
+ capture_tree() { # $1 = editable dir that is NOT a git repo -> full snapshot
130
+ root=$1
131
+ if [ ! -d "$root" ]; then echo "[pre_artifacts] SKIP (absent): $root"; return 0; fi
132
+ tmp=$(mktemp -d /tmp/pre_artifacts.XXXXXX 2>/dev/null) || return 0
133
+ if git init -q "$tmp/snap" >/dev/null 2>&1; then
134
+ GD="$tmp/snap/.git"
135
+ empty=$(git --git-dir="$GD" hash-object -w -t tree /dev/null 2>/dev/null)
136
+ ( cd "$root" 2>/dev/null || exit 0
137
+ find . -name .git -prune -o -name __pycache__ -prune -o \
138
+ -type f ! -name '*.pyc' ! -name '*.pyo' -size -"${MAX_BLOB_KB}"k -print0 \
139
+ 2>/dev/null \
140
+ | GIT_DIR="$GD" GIT_WORK_TREE="$root" xargs -0 -r git add -f -- ) >/dev/null 2>&1 || true
141
+ banner "$root" "tree-snapshot-not-a-git-repo"
142
+ GIT_DIR="$GD" GIT_WORK_TREE="$root" git diff --cached --binary "$empty" \
143
+ >> "$PATCH" 2>/dev/null || true
144
+ else
145
+ echo "[pre_artifacts] WARN could not stage a snapshot index for $root"
146
+ fi
147
+ rm -rf "$tmp" 2>/dev/null || true
148
+ all=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -name __pycache__ -prune -o \
149
+ -type f -print 2>/dev/null | sed 's|^\./||' )
150
+ printf '%s\n' "$all" | grep -v '^$' | list_add "$root"
151
+ big=$( cd "$root" 2>/dev/null && find . -name .git -prune -o -type f \
152
+ -size +"${MAX_BLOB_KB}"k -print 2>/dev/null | grep -c . )
153
+ echo "[pre_artifacts] $root: tree snapshot (no git baseline here), $(printf '%s\n' "$all" | grep -c . ) file(s)"
154
+ if [ "${big:-0}" != 0 ]; then
155
+ echo "[pre_artifacts] NOTE $big file(s) under $root exceed ${MAX_BLOB_KB}KB: listed in"
156
+ echo "[pre_artifacts] model_files.txt but their bytes are NOT inlined into model.patch."
157
+ fi
158
+ return 0
159
+ }
160
+
161
+ capture_git "/app/repo"
162
+ capture_tree "/app/submission"
163
+ bytes=$(wc -c < "$PATCH" 2>/dev/null || echo 0)
164
+ case "$bytes" in ''|*[!0-9]*) bytes=0 ;; esac
165
+ echo "[pre_artifacts] captured $bytes bytes, $(wc -l < "$LIST" 2>/dev/null || echo 0) path(s)"
166
+ if [ "$bytes" -gt 67108864 ]; then
167
+ echo "[pre_artifacts] 🔴 NOTE model.patch is $bytes bytes (> 64MiB). Almost certainly a build"
168
+ echo "[pre_artifacts] product or a checkpoint was left inside a capture root — which is also"
169
+ echo "[pre_artifacts] an out-of-scope edit the verifier's scope gate will punish."
170
+ fi
171
+ exit 0