halle01 commited on
Commit
78cb49e
·
verified ·
1 Parent(s): ff5aa91

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .claude/settings.local.json +5 -0
  2. .gitignore +17 -0
  3. DEPLOYING_ON_THUNDER.md +159 -0
  4. DEPLOY_A100_AGENT_RUNBOOK.md +224 -0
  5. NEXT_INSTANCE_TRAINING.md +128 -0
  6. README.md +170 -0
  7. SPEEDUP_FINDINGS.md +242 -0
  8. TRAINING_GUIDE.md +153 -0
  9. archive/dpo_manifest.jsonl +0 -0
  10. archive/sft_manifest.jsonl +0 -0
  11. claude-1-faster-at-least-by-100x.txt +0 -0
  12. claude-after-sft-judge-fix-first-run-log1.txt +1205 -0
  13. common.py +218 -0
  14. configs/dpo.yaml +61 -0
  15. configs/kto.yaml +72 -0
  16. configs/kto_unsloth.yaml +47 -0
  17. configs/sft.yaml +70 -0
  18. configs/sft_unsloth.yaml +45 -0
  19. configs/simpo.yaml +68 -0
  20. configs/smoketest_kto.yaml +49 -0
  21. configs/smoketest_sft.yaml +45 -0
  22. data/build_datasets.py +216 -0
  23. data/curate_topvstop.py +111 -0
  24. data/dataset_utils.py +22 -0
  25. data/scrape_duels.py +290 -0
  26. eval/judge_challenge.py +111 -0
  27. eval/self_judge_eval.py +244 -0
  28. logs/pipeline.log +65 -0
  29. muon.py +213 -0
  30. preference-optimization-sft-6000-a100-to-tinker.txt +0 -0
  31. requirements.txt +30 -0
  32. scrape_run.log +61 -0
  33. scripts/run_pipeline.sh +38 -0
  34. scripts/setup_blackwell.sh +92 -0
  35. scripts/setup_env.sh +67 -0
  36. scripts/setup_fast_kernels.sh +54 -0
  37. scripts/setup_unsloth.sh +47 -0
  38. threejs-sft-v1.progress.json +13 -0
  39. tinker/README.md +105 -0
  40. tinker/eval_tinker.py +256 -0
  41. tinker/tinker_data.py +136 -0
  42. tinker/train_dpo_tinker.py +186 -0
  43. tinker/train_sft_tinker.py +198 -0
  44. train_dpo.py +124 -0
  45. train_kto.py +118 -0
  46. train_kto_unsloth.py +108 -0
  47. train_sft.py +107 -0
  48. train_sft_unsloth.py +115 -0
  49. train_simpo.py +109 -0
  50. unsloth_common.py +58 -0
.claude/settings.local.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "worktree": {
3
+ "bgIsolation": "none"
4
+ }
5
+ }
.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data and outputs — transferred via scp, not git (see README.md). archive/
2
+ # alone is 3.2GB, datasets/ 6.5GB; checkpoints will be multi-GB per adapter.
3
+ archive/
4
+ datasets/
5
+ checkpoints/
6
+
7
+ .venv/
8
+ __pycache__/
9
+ *.pyc
10
+ wandb/
11
+ *.log
12
+ .DS_Store
13
+
14
+ # Tinker run progress (resumable state pointers) + local curated datasets
15
+ *.progress.json
16
+ datasets_sft/
17
+ datasets_dpo/
DEPLOYING_ON_THUNDER.md ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deploying this training on a Thunder Compute GPU — bugfixes & runbook
2
+
3
+ Everything here was found by **actually running** the pipeline on a fresh
4
+ Thunder Compute RTX A6000 (48GB) instance, July 2026 — not by inspection.
5
+ It's the companion to `SPEEDUP_FINDINGS.md` (which covers the throughput
6
+ strategy); this doc covers the *operational* reality of getting a run going.
7
+
8
+ ## TL;DR
9
+
10
+ - SFT (stage 1) is **verified working end-to-end** on the curated data: loss
11
+ drops (5.76 → 3.17 over 4 steps), eval runs, a 637MB LoRA adapter checkpoint
12
+ saves. KTO uses the same machinery.
13
+ - Measured throughput on the torch-fallback path: **~49s/example**
14
+ (98.7s per optimizer step at batch=1 × grad-accum=2).
15
+ - **At that pace the full curated run is ~12 days SFT + ~17 days KTO** — see
16
+ "How long will the full run take" below. The data curation got us from
17
+ ~200 days to ~29 days; the `flash-linear-attention` kernel speedup (still
18
+ blocked, see bug #3) is the remaining lever to make it genuinely fast.
19
+
20
+ ## Bugfixes / environment gotchas (all verified live)
21
+
22
+ ### 1. `max_steps` in configs was silently ignored (real code bug)
23
+ The `train_*.py` scripts built their `SFTConfig`/`KTOConfig`/etc. without ever
24
+ passing `max_steps`, so `max_steps:` in a YAML did nothing — a run would always
25
+ go epoch-length. **Fixed**: all four trainers now thread
26
+ `max_steps=t.get("max_steps", -1)` (−1 = disabled = epoch-driven, the default
27
+ for real runs; the smoke configs set it to a small number).
28
+
29
+ ### 2. Paged optimizers crash on Thunder — `cuMemAllocManaged` unsupported
30
+ `paged_adamw_8bit` (our config default, from the QLoRA paper) dies at the first
31
+ optimizer step:
32
+ ```
33
+ error: unsupported function cuMemAllocManaged
34
+ This function is not yet supported by Thunder Compute.
35
+ ```
36
+ Thunder's GPU virtualization doesn't support CUDA managed/unified memory, which
37
+ the *paged* bitsandbytes optimizers require. Thunder hints at an experimental
38
+ flag (`EXPERIMENTAL_THUNDER_UNIFIED_MEMORY_SUPPORT=true`) but the reliable fix
39
+ is to **not use a paged optimizer here**. Use **`optim: adamw_torch`** (verified
40
+ working). With LoRA the optimizer state is tiny (adapter params only) and we
41
+ have huge VRAM headroom — only 17–35GB of 48GB was used — so 32-bit AdamW costs
42
+ nothing meaningful. (`adamw_8bit` non-paged is untested here; `adamw_torch` is
43
+ the known-good choice.) Regular 4-bit weight quantization (bitsandbytes) works
44
+ fine — only the *paging* is unsupported.
45
+
46
+ ### 3. `flash-linear-attention` 0.4.2 HANGS on the first step (unresolved)
47
+ Installing `fla` makes `is_flash_linear_attention_available()` return True and
48
+ the Qwen3.5 fast path engages — but the **first training step then hangs
49
+ forever** (GPU 0%, no CPU, VRAM frozen). Cause: fla 0.4.2's Triton kernels vs
50
+ the very new Triton bundled with `torch 2.13+cu130` (the
51
+ `tl.make_block_ptr is deprecated` warning is the tell). **Uninstall fla to train
52
+ on the torch fallback**, which works. Nuance worth knowing: even *with* fla,
53
+ transformers' `qwen3_5` only routes the cheap `causal_conv1d` to a torch
54
+ fallback; the expensive `chunk_gated_delta_rule` / `fused_recurrent_gated_delta_rule`
55
+ / `FusedRMSNormGated` come from fla. Getting fla's speedup needs a matching
56
+ fla/Triton combo (try a newer fla release, or pin an older Triton) — this is the
57
+ top open item for throughput. nvcc is absent on Thunder, so `causal-conv1d`
58
+ (source-only) can't be built either.
59
+
60
+ ### 4. Detach long runs with `setsid`, not just `nohup`
61
+ `nohup python … &` over SSH still got the training killed when the launching
62
+ channel closed. Launch with **`setsid nohup python … > log 2>&1 </dev/null &`**
63
+ (new session, fully detached) so the run survives SSH disconnects. `tmux` is not
64
+ preinstalled.
65
+
66
+ ### 5. Ship the WHOLE image set before training
67
+ A partial image transfer trains for a step or two then dies with
68
+ `FileNotFoundError` on the first missing PNG (dataset images load lazily, so a
69
+ gap only bites mid-run). Verify `missing: 0` before launching — a one-liner that
70
+ checks every `images` path exists against the transferred `archive/raw/`.
71
+
72
+ ### 6. KTO needs batch >= 2 AND more memory than SFT
73
+ KTO runs BOTH the policy and reference-model forward (for the KL term), so it's
74
+ heavier than SFT, and TRL enforces `per_device_train_batch_size >= 2` (batch=1
75
+ errors: "Actual batch size must be > 1 ... KL term will be equivalent to the
76
+ implied reward"). On a 48GB A6000 that combination OOMs at `max_seq_length:
77
+ 4096`; the working recipe is **batch=2, `max_seq_length: 2048`,
78
+ `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`**. On an 80GB card you can
79
+ keep 4096 — see `DEPLOY_A100_AGENT_RUNBOOK.md`. Verified: KTO steps at ~43s/it
80
+ (batch=2, 2048) with a clean loss on the curated mini set.
81
+
82
+ ### 7. `max_prompt_length` was removed in TRL 1.9.2 (real code bug)
83
+ `KTOConfig`/`DPOConfig` no longer accept `max_prompt_length`; passing it throws
84
+ `TypeError: unexpected keyword argument 'max_prompt_length'`. Removed from all
85
+ preference trainers — total length is bounded by `max_length` (which we still
86
+ pass).
87
+
88
+ ## Runbook — fresh Thunder instance to a running SFT
89
+
90
+ ```bash
91
+ # --- git access (deploy key persists across instance restarts) ---
92
+ ssh-keygen -t ed25519 -N "" -f ~/.ssh/threejstraining_deploy -C "tnr-deploy"
93
+ # add ~/.ssh/threejstraining_deploy.pub as a read-only Deploy Key on the repo
94
+ # (gh api repos/<owner>/threejstraining/keys -f key=... -F read_only=true)
95
+ cat >> ~/.ssh/config <<EOF
96
+ Host github.com
97
+ IdentityFile ~/.ssh/threejstraining_deploy
98
+ IdentitiesOnly yes
99
+ EOF
100
+ git clone git@github.com:karvachiik-lgtm/threejstraining.git ~/coder-training
101
+
102
+ # --- env (keys survive restarts via ~/.profile; ~/.bashrc is read-only) ---
103
+ cat > ~/env.sh <<EOF
104
+ export WANDB_API_KEY=... # new wandb_v1_ format is ~86 chars, not 40
105
+ export HF_TOKEN=...
106
+ export HUGGING_FACE_HUB_TOKEN=\$HF_TOKEN
107
+ EOF
108
+ echo 'source ~/env.sh' >> ~/.profile
109
+
110
+ cd ~/coder-training && bash scripts/setup_env.sh # venv + deps (trl, transformers 5.x, bnb, torchvision…)
111
+
112
+ # --- data: stream the archive (tar+gzip beats scp -r for many small files) ---
113
+ # from your local machine:
114
+ # tar czf - archive | ssh tnr-0 'tar xzf - -C ~/coder-training'
115
+ # then curate to ~10% and build the datasets ON the instance:
116
+ python data/curate_manifest.py --in archive/duels_index.jsonl \
117
+ --out archive/duels_index_curated.jsonl --per-prompt-cap 8
118
+ python data/build_datasets.py --manifest archive/duels_index_curated.jsonl \
119
+ --out-dir ./datasets
120
+ # sanity: every image path must resolve (missing must be 0) before launching.
121
+
122
+ # --- train (torch fallback; adamw_torch; detached) ---
123
+ # edit configs/sft.yaml + kto.yaml: optim: adamw_torch (NOT paged_adamw_8bit)
124
+ source .venv/bin/activate && source ~/env.sh
125
+ setsid nohup python train_sft.py --config configs/sft.yaml > ~/sft.log 2>&1 </dev/null &
126
+ # then, after SFT:
127
+ setsid nohup python train_kto.py --config configs/kto.yaml > ~/kto.log 2>&1 </dev/null &
128
+ ```
129
+
130
+ Smoke-test first with the tiny configs (a few hundred curated rows, `max_steps`
131
+ small) to confirm the loop + eval + checkpoint save before committing to a
132
+ multi-day run.
133
+
134
+ ## How long will the full run take?
135
+
136
+ At the **measured ~49s/example** (torch fallback, batch=1×accum=2, one A6000):
137
+
138
+ | Stage | Rows (curated ~10%) | Passes | Estimate |
139
+ |---|---|---|---|
140
+ | SFT | 10,464 | ×2 epochs | **~12 days** |
141
+ | KTO | 29,150 | ×1 epoch | **~17 days** |
142
+ | _(uncurated, for reference)_ | 37,788 / 285,294 | | ~43d / ~163d |
143
+
144
+ So curation alone cut the pair from ~200 days to **~29 days** — real progress,
145
+ but still not fast enough to iterate. Levers to get to single-digit days on the
146
+ **same GPU**, in order of leverage:
147
+
148
+ 1. **Fix the fla hang (bug #3)** — the delta-rule + MoE torch fallbacks are why
149
+ it's 49s/example; fla is the intended large speedup. Highest leverage.
150
+ 2. **Cut the curated set further** — `--per-prompt-cap 4` roughly halves it
151
+ (~7K duels → ~5K SFT rows → ~6 days SFT); still full prompt coverage.
152
+ 3. **SFT for 1 epoch, not 2** — halves SFT time; validate quality on the
153
+ held-out eval.
154
+ 4. **Skip a separate KTO stage initially** — ship the SFT-only adapter first,
155
+ measure it against the archived winners, add KTO only if SFT alone underperforms.
156
+
157
+ Batch size is NOT a lever here — the GPU is already 100%-utilized at batch=1
158
+ (compute-bound on the fallback kernels), so larger batches don't raise
159
+ throughput; only faster kernels (fla) or fewer examples do.
DEPLOY_A100_AGENT_RUNBOOK.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Agent runbook: deploy this training on an A100 80GB (Thunder Compute)
2
+
3
+ **Audience: an AI agent (Claude) starting cold on this task.** Follow these
4
+ steps in order. Each has a VERIFY gate — do not proceed past a gate until it
5
+ passes. Every command, failure mode, and fix here was validated on a real
6
+ RTX A6000 48GB run (July 2026); the A100-specific deltas are called out. If
7
+ something behaves differently from what's written, STOP and report — don't
8
+ improvise around a failed gate.
9
+
10
+ Why A100 80GB over the A6000 48GB we first used:
11
+ - **More VRAM (80GB):** KTO (which runs policy + reference forwards and
12
+ *requires* batch ≥ 2) fits at the full `max_seq_length: 4096` — no need for
13
+ the 2048 reduction the 48GB card forced. Likely headroom for batch 4.
14
+ - **Faster compute:** A100 BF16 throughput is ~2× the A6000's, so expect
15
+ roughly ~2× fewer s/example than our measured 49s — **measure it, don't
16
+ assume** (the slow path is torch-fallback kernels; see the fla note).
17
+
18
+ ## CRITICAL: the throughput fix is a working Triton stack (read first)
19
+
20
+ Measured on the A6000: **32.8s/step** for one 4096-token example (real training
21
+ ~49s/example incl. data). We proved WHERE it goes:
22
+ - **Backward pass = 77% of the time**; it's the base-model kernels, NOT the
23
+ LoRA (shrinking the adapter 64x — r64/all-linear -> r8/attn-only — saved only
24
+ 7%). The hotspot is the 48 naive Gated-DeltaNet layers' backward (torch
25
+ fallback).
26
+ - The FIX is fused kernels (`flash-linear-attention`, or `torch.compile`).
27
+ On the A6000 both **HANG identically** (0% GPU, frozen) because both generate
28
+ kernels via **Triton, and Triton 3.7.1 / CUDA 13.0 deadlocks on this stack**.
29
+ This is an environment bug, not a model limit.
30
+
31
+ **Therefore, on the A100, the single most important thing is a Triton stack that
32
+ actually works** — that's the ~10x, far bigger than the ~2x from the faster
33
+ card. Do this BEFORE anything else:
34
+
35
+ 1. Check what the instance ships: `python -c "import torch,triton; print(torch.__version__, triton.__version__)"`.
36
+ If it's again `torch 2.13+cu130` / `triton 3.7.x`, **pin a known-good stack
37
+ instead** — a combo fla is actually tested against, e.g.
38
+ `pip install "torch==2.5.1" "triton==3.1.0"` on a CUDA 12.x image (match the
39
+ instance's CUDA; use the cu121/cu124 wheels). Do this in the venv before
40
+ installing fla.
41
+ 2. **Isolation-test fla BEFORE loading the 27B** (fast — no model needed): run a
42
+ tiny `chunk_gated_delta_rule` call with a 30s alarm (see the `fla_test.py`
43
+ pattern used on the A6000). If it returns a time, Triton works -> fla is
44
+ viable, expect a large speedup. If it hangs -> the stack is still broken;
45
+ do NOT install fla, train on the torch fallback, and report that the A100's
46
+ stack also needs downgrading.
47
+ 3. Only if fla passes the isolation test, keep it installed and re-measure
48
+ s/step on the smoke — that number decides the real-run ETA.
49
+
50
+ If Triton cannot be made to work on either card, throughput is bounded by the
51
+ torch fallback (~33s/step → ~12d SFT + ~17d KTO on curated data); the only
52
+ remaining levers are aggressive curation (`--per-prompt-cap 3`), SFT 1 epoch,
53
+ and dropping the separate KTO stage initially. But the Triton fix is the real
54
+ answer — prioritize it.
55
+
56
+ ## 0. Context you need (read before touching anything)
57
+
58
+ - Repo: `github.com/karvachiik-lgtm/threejstraining` (private). Code is small
59
+ and in git; the **data is NOT in git** — it's ~3.2GB of `archive/` that must
60
+ be transferred separately, then curated + built on the instance.
61
+ - The model is `Qwen/Qwen3.6-27B` — HF `model_type: qwen3_5`, a hybrid
62
+ Gated-DeltaNet + MoE VLM. QLoRA 4-bit; base loads to ~17GB.
63
+ - Two-stage training: `train_sft.py` (stage 1) then `train_kto.py` (stage 2).
64
+ - Companion docs in the repo: `DEPLOYING_ON_THUNDER.md` (the A6000 runbook +
65
+ the five original bugfixes), `SPEEDUP_FINDINGS.md` (throughput strategy).
66
+ This doc supersedes them for an A100 run but references their detail.
67
+ - You will need, from the user's local machine: the Thunder SSH alias (e.g.
68
+ `tnr-0`, from `~/.ssh/config` / `tnr connect <N>`), `gh` authenticated with
69
+ `admin:public_key`+`repo` scopes (to add a deploy key), and the wandb + HF
70
+ keys (`~/wandbkey`, `~/hftoken`).
71
+
72
+ ## 1. Confirm the instance
73
+
74
+ ```bash
75
+ ssh <tnr-alias> 'nvidia-smi --query-gpu=name,memory.total --format=csv,noheader; python3 --version; nproc'
76
+ ```
77
+ **VERIFY:** GPU name contains `A100` and memory.total ≈ 81920 MiB. If it's not
78
+ an A100 80GB, stop — the config values below assume it.
79
+
80
+ ## 2. Git access (persists across instance restarts)
81
+
82
+ ```bash
83
+ # on the instance
84
+ ssh <tnr-alias> 'test -f ~/.ssh/threejstraining_deploy || ssh-keygen -t ed25519 -N "" -f ~/.ssh/threejstraining_deploy -C "tnr-a100-deploy"; cat ~/.ssh/threejstraining_deploy.pub'
85
+ # take that pubkey and, from the LOCAL machine (gh is authed there):
86
+ gh api repos/karvachiik-lgtm/threejstraining/keys -f title="tnr-a100-deploy" -f key="<PUBKEY>" -F read_only=true --jq '.id,.verified'
87
+ # back on the instance: point git at the key and clone
88
+ ssh <tnr-alias> 'grep -q "Host github.com" ~/.ssh/config || printf "Host github.com\n IdentityFile ~/.ssh/threejstraining_deploy\n IdentitiesOnly yes\n" >> ~/.ssh/config; chmod 600 ~/.ssh/config; ssh-keyscan -t ed25519 github.com >> ~/.ssh/known_hosts 2>/dev/null; git clone git@github.com:karvachiik-lgtm/threejstraining.git ~/coder-training'
89
+ ```
90
+ **VERIFY:** `ssh <tnr-alias> 'cd ~/coder-training && git log --oneline -1'`
91
+ prints a commit. If clone fails with a key error, the deploy key wasn't
92
+ registered — re-check the `gh api` step returned `verified: true`.
93
+
94
+ ## 3. Persist keys (survive restarts via ~/.profile; ~/.bashrc is read-only)
95
+
96
+ ```bash
97
+ WANDB=$(cat ~/wandbkey | tr -d '\n '); HF=$(cat ~/hftoken | tr -d '\n ')
98
+ ssh <tnr-alias> "cat > ~/env.sh <<EOF
99
+ export WANDB_API_KEY=$WANDB
100
+ export HF_TOKEN=$HF
101
+ export HUGGING_FACE_HUB_TOKEN=$HF
102
+ export WANDB_PROJECT=404-coder-training
103
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
104
+ EOF
105
+ chmod 600 ~/env.sh; grep -q 'source ~/env.sh' ~/.profile || echo 'source ~/env.sh' >> ~/.profile"
106
+ ```
107
+ NOTE: the new wandb key format is `wandb_v1_...` (~86 chars), not the old
108
+ 40-char hex — pass it whole. `expandable_segments` is set globally here because
109
+ KTO benefits from it (reduces fragmentation OOMs).
110
+ **VERIFY:** `ssh <tnr-alias> 'source ~/env.sh; echo ${WANDB_API_KEY:+ok} ${HF_TOKEN:+ok}'` prints `ok ok`.
111
+
112
+ ## 4. Environment
113
+
114
+ ```bash
115
+ ssh <tnr-alias> 'cd ~/coder-training && nohup bash scripts/setup_env.sh > ~/setup_env.log 2>&1 & echo started'
116
+ # poll until done (installs torch, transformers 5.x, trl, peft, bitsandbytes, torchvision)
117
+ ssh <tnr-alias> 'cd ~/coder-training && .venv/bin/python -c "import trl,torch,transformers,peft,bitsandbytes; print(trl.__version__, torch.__version__)"'
118
+ ```
119
+ **VERIFY:** the import line prints versions (we validated trl 1.9.2,
120
+ torch 2.13+cu130, transformers 5.14.1). If it errors, read `~/setup_env.log`.
121
+
122
+ **fla only helps if Triton works — see the CRITICAL section above.** On the
123
+ A6000's cu130/triton-3.7 stack it HANGS (as does torch.compile). If you pinned
124
+ a known-good stack and the isolation test passed, install fla and it should
125
+ give a large speedup on the Gated-DeltaNet backward; otherwise train on the
126
+ torch fallback.
127
+
128
+ ## 5. Transfer + curate + build data
129
+
130
+ ```bash
131
+ # from the LOCAL machine: stream archive/ (tar+gzip >> scp -r for many files)
132
+ cd <local>/404-agent/coder-training
133
+ tar czf - archive | ssh <tnr-alias> 'tar xzf - -C ~/coder-training'
134
+ # on the instance: curate to ~10% then build datasets from the curated manifest
135
+ ssh <tnr-alias> 'cd ~/coder-training && source .venv/bin/activate && \
136
+ python data/curate_manifest.py --in archive/duels_index.jsonl --out archive/duels_index_curated.jsonl --per-prompt-cap 8 && \
137
+ python data/build_datasets.py --manifest archive/duels_index_curated.jsonl --out-dir ./datasets'
138
+ ```
139
+ **VERIFY (critical — a partial image set trains a few steps then dies):**
140
+ ```bash
141
+ ssh <tnr-alias> 'cd ~/coder-training && source .venv/bin/activate && python - <<PY
142
+ import json,os
143
+ miss=tot=0
144
+ for n in ("sft.jsonl","kto.jsonl"):
145
+ for l in open(f"datasets/{n}"):
146
+ for p in json.loads(l).get("images",[]):
147
+ tot+=1; miss+= not os.path.exists(p)
148
+ print("image refs",tot,"missing",miss)
149
+ PY'
150
+ ```
151
+ Missing MUST be 0. Expected sizes (per-prompt-cap 8): SFT ~10.5K rows, KTO
152
+ ~29K, preference ~14.5K. To go smaller/faster, use `--per-prompt-cap 4`.
153
+
154
+ ## 6. A100 config values
155
+
156
+ The repo defaults are tuned for the 48GB A6000. On the 80GB A100 you can relax
157
+ the KTO memory reductions. Edit on the instance:
158
+
159
+ - `configs/sft.yaml`: keep as-is. `optim: adamw_torch` (NOT `paged_adamw_8bit`
160
+ — paged optimizers crash on Thunder: `cuMemAllocManaged` unsupported). SFT is
161
+ batch=1 × grad-accum=16.
162
+ - `configs/kto.yaml`: `per_device_train_batch_size: 2` (KTO REQUIRES actual
163
+ batch > 1 — batch=1 errors: "KL term will be equivalent to the implied
164
+ reward"). On 80GB set **`max_seq_length: 4096`** (the A6000 needed 2048; the
165
+ A100 has room). `optim: adamw_torch`. Try batch 4 / accum 8 if VRAM allows
166
+ (watch `nvidia-smi`).
167
+
168
+ **VERIFY the settings before launching:**
169
+ `ssh <tnr-alias> 'cd ~/coder-training && grep -E "optim|batch_size|max_seq_length" configs/sft.yaml configs/kto.yaml'`
170
+
171
+ ## 7. Smoke-test BOTH stages before the real run (≈20 min, mandatory)
172
+
173
+ Never start a multi-day run without this. It catches env/API/memory issues on a
174
+ tiny slice. Build the smoke configs (tiny `max_steps`, curated data) or reuse
175
+ the repo's `configs/smoke_mini_*.yaml` if present, then:
176
+
177
+ ```bash
178
+ ssh <tnr-alias> 'cd ~/coder-training && source .venv/bin/activate && source ~/env.sh && \
179
+ setsid nohup python train_sft.py --config configs/smoke_mini_sft.yaml > ~/smoke_sft.log 2>&1 </dev/null & echo launched'
180
+ ```
181
+ Use `setsid` (not bare `nohup`) so the run survives SSH disconnects.
182
+ **VERIFY SFT:** poll `~/smoke_sft.log` — loss should DROP across steps
183
+ (we saw 5.76→3.17), then `eval_loss` logs and `adapter saved to
184
+ ./checkpoints/...` appears with an `adapter_model.safetensors` on disk.
185
+ Then the same for `train_kto.py` / `smoke_mini_kto.yaml`.
186
+ **VERIFY KTO:** it reaches a step with a loss line and 100% GPU util, no
187
+ `OutOfMemoryError` and no `batch size must be > 1` error.
188
+
189
+ Known smoke failure modes and fixes (all seen on the A6000):
190
+ | symptom | cause | fix |
191
+ |---|---|---|
192
+ | hang at step 0, GPU 0% forever | fla installed | `pip uninstall -y flash-linear-attention fla-core` |
193
+ | `cuMemAllocManaged ... not supported` | paged optimizer | `optim: adamw_torch` |
194
+ | `max_prompt_length` unexpected kwarg | old code vs TRL 1.9.2 | already fixed in repo (pull latest) |
195
+ | `batch size must be > 1` (KTO) | KTO batch=1 | set KTO batch ≥ 2 |
196
+ | `OutOfMemoryError` (KTO) | batch×seqlen too big | lower `max_seq_length`; ensure `expandable_segments` set |
197
+ | `FileNotFoundError` a PNG mid-run | partial image transfer | re-run the §5 VERIFY; missing must be 0 |
198
+
199
+ ## 8. Launch the real run + monitor
200
+
201
+ ```bash
202
+ ssh <tnr-alias> 'cd ~/coder-training && source .venv/bin/activate && source ~/env.sh && \
203
+ setsid nohup python train_sft.py --config configs/sft.yaml > ~/sft.log 2>&1 </dev/null & echo sft_launched'
204
+ ```
205
+ Watch loss curves in wandb (project `404-coder-training`). When SFT finishes and
206
+ saved `./checkpoints/sft`, launch KTO (it loads the SFT adapter via
207
+ `configs/kto.yaml`'s `sft_adapter`):
208
+ ```bash
209
+ ssh <tnr-alias> 'cd ~/coder-training && source .venv/bin/activate && source ~/env.sh && \
210
+ setsid nohup python train_kto.py --config configs/kto.yaml > ~/kto.log 2>&1 </dev/null & echo kto_launched'
211
+ ```
212
+
213
+ **Measure throughput on the first ~5 logged steps** and compute the ETA:
214
+ per-example seconds = (s/step) ÷ (batch × grad-accum). On the A6000 this was
215
+ ~49s/example → ~12d SFT + ~17d curated KTO. On the A100, re-measure and update
216
+ the estimate; if it's still many days, reduce scope (`--per-prompt-cap 4`,
217
+ SFT 1 epoch) or invest in the fla fast path. Report the measured number to the
218
+ user before committing to the full multi-day run.
219
+
220
+ ## 9. Report back
221
+
222
+ Tell the user: measured s/example on the A100, the projected SFT+KTO wall-clock,
223
+ whether both smokes passed, and the wandb run URLs. Do not silently start a
224
+ multi-day run — surface the ETA and let them decide scope.
NEXT_INSTANCE_TRAINING.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Next-instance training — everything we learned, and the ≤7-hour recipe
2
+
3
+ Master handoff for training the 404-GEN threejs coder on a fresh GPU instance.
4
+ Everything here was VERIFIED by running on a Thunder A6000 (48GB), 2026-07-30/31.
5
+ Companion docs: `DEPLOY_A100_AGENT_RUNBOOK.md` (step-by-step w/ VERIFY gates),
6
+ `DEPLOYING_ON_THUNDER.md` (bugfix detail), `SPEEDUP_FINDINGS.md` (research trail).
7
+
8
+ ## The goal
9
+ Train a coder LoRA that beats the archived competition winners on the real
10
+ judge eval — within **≤ 6–7 hours of training**. This is achievable now; the
11
+ throughput problem is solved (see below).
12
+
13
+ ## THE headline finding: fla works, and it's a Triton VERSION bug
14
+
15
+ - Base model forward/backward is the bottleneck (the **backward = 77%** of the
16
+ step, through the 48 naive Gated-DeltaNet layers). It is **NOT the LoRA** —
17
+ a 64× smaller adapter changed the step by only 7%.
18
+ - The fix is fla's fused Gated-DeltaNet kernel. It appears to "hang" on the
19
+ default stack — but that's **triton 3.7.1 deadlocking**, not a real hang.
20
+ - **FIX: `pip install triton==3.6.0` + `flash-linear-attention==0.5.2`.**
21
+ Verified: fixed-4096 fwd+bwd **32.8s → 9.0s/step (3.6×)**. The fla chunk
22
+ kernel warms to 5.4ms. (Proven safe because vLLM ran the same model's GDN
23
+ kernels fine on triton 3.6.0 — the hardware was never the problem.)
24
+ - torch.compile ALSO hangs on 3.7.1 (it's Triton too); not needed once fla works.
25
+ - Run `scripts/setup_fast_kernels.sh` — it pins the versions and verifies the
26
+ kernel warms before you trust a run.
27
+
28
+ Why 3.6× and not the ~10× the isolated kernel implies: `is_fast_path_available`
29
+ also needs `causal-conv1d` (source-only, needs nvcc which is absent). Without
30
+ it the conv falls back to torch and the MoE stays a Python loop. Optional: try
31
+ `pip install nvidia-cuda-nvcc-cu12` then `causal-conv1d` for the complete path.
32
+
33
+ ## Base checkpoint: AronHorn, not the generic base
34
+ `configs/*.yaml` now use **`Tooony133/Qwen-3.6-27B-AronHorn`** — the winner-
35
+ lineage checkpoint our `miner-submission/` actually runs. Codenames rotate each
36
+ round; re-verify the current leader's checkpoint before a run (see the
37
+ `finetune-base-checkpoint-decision` memory / `past-winner/leader.json`).
38
+
39
+ ## What vLLM is (and isn't) for
40
+ vLLM is INFERENCE only — no backprop, it cannot train. Uses:
41
+ 1. **Diagnostic** — it's how we found the triton 3.6.0 fix.
42
+ 2. **Eval** — serve the trained checkpoint to the judge (Phase 3).
43
+ 3. **Online RL (optional future)** — GRPO/online-DPO would use vLLM for fast
44
+ rollout generation + HF/fla for the gradient step. A potentially better
45
+ method (optimizes the real judge reward) but a strategy change; the backward
46
+ is still HF. Not needed for the SFT/KTO plan below.
47
+ vLLM needs the 27B in 4-bit on 48GB (`quantization=bitsandbytes`, needs
48
+ `bitsandbytes>=0.48.1`) or bf16 on 80GB. Multiprocess engine needs your script
49
+ under `if __name__=="__main__":`.
50
+
51
+ ## The ≤7-hour recipe
52
+
53
+ Measured per-example (real training, incl. data/collator overhead): **~12s on
54
+ the A6000 with fla** (9.0s pure fwd+bwd × ~1.3 overhead). An A100 80GB is ~2×
55
+ faster (~6s) AND lets KTO run at full `max_seq_length: 4096`.
56
+
57
+ Budget math: 7 hrs ≈ 25,000s. At ~12s/ex (A6000) that's ~2,000 example-passes;
58
+ at ~6s/ex (A100) ~4,000. The full curated data (10.5K SFT ×2 epochs, 29K KTO)
59
+ is FAR too big for 7 hrs — so **curate aggressively and do 1 epoch**:
60
+
61
+ 1. **Fast kernels:** `bash scripts/setup_fast_kernels.sh` (triton 3.6.0 + fla).
62
+ 2. **Get the data** — it's on a private HF dataset now, one file (2.6GB), far
63
+ faster than re-transferring from local:
64
+ `hf download reneeice/threejs-duels-archive archive.tar.gz --repo-type dataset --local-dir . && tar xzf archive.tar.gz`
65
+ (needs HF_TOKEN in env; the repo is private). Then **curate hard** — target
66
+ ~2–3K examples/stage, not 10–29K:
67
+ `python data/curate_manifest.py --in archive/duels_index.jsonl \
68
+ --out archive/duels_index_curated.jsonl --per-prompt-cap 2`
69
+ (~1,839 prompts × 2 ≈ 3.7K duels → ~3K SFT rows, ~7K KTO). Drop further to
70
+ `--per-prompt-cap 1` if needed. Curation keeps a reliable-clear/near-boundary
71
+ judge-stage mix (see `SPEEDUP_FINDINGS.md`).
72
+ Then `python data/build_datasets.py --manifest archive/duels_index_curated.jsonl --out-dir ./datasets`.
73
+ 3. **Config:** `num_train_epochs: 1`, `optim: adamw_torch` (paged crashes on
74
+ Thunder), `max_seq_length: 2048` on 48GB / `4096` on 80GB (KTO needs batch≥2
75
+ and OOMs at 4096 on 48GB — set `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`).
76
+ 4. **Budget split (A100 80GB, ~6s/ex):** SFT ~2,500 ex ×1 epoch ≈ 4 hrs; KTO
77
+ ~2,000 pairs ≈ 2.5–3 hrs (KTO's dual forward ~2× cost). Total ≈ 6.5 hrs.
78
+ **On A6000 (~12s/ex): SFT-only ~2,000 ex ≈ 6.5 hrs** — skip KTO, or do a
79
+ tiny KTO pass. SFT-only is a legitimate first submission.
80
+ 5. **Launch detached:** `setsid nohup python train_sft.py --config configs/sft.yaml > sft.log 2>&1 </dev/null &`
81
+ (bare nohup gets killed on SSH close). Then `train_kto.py` if budget allows.
82
+ 6. **Smoke first** (always): `configs/smoke_mini_*.yaml`, `max_steps` small —
83
+ confirm loss drops, eval runs, checkpoint saves, and measure the WARM s/step
84
+ (step 2+, after fla compiles) before committing the multi-hour run.
85
+
86
+ ## Verified vs pending
87
+ - VERIFIED end-to-end on real GPU: data pipeline; SFT (loss 5.76→3.06, eval,
88
+ 637MB adapter saved); KTO (rewards/margins goes positive, eval); the fla
89
+ 3.6× speedup; vLLM serving the model.
90
+ - PENDING: a full real run (only smokes run so far); Phase-3 judge eval of a
91
+ real checkpoint vs the archived winners; causal-conv1d full fast path; the
92
+ AronHorn-vs-base A/B; whether online-RL (GRPO+vLLM) beats SFT/KTO.
93
+
94
+ ## Bugfixes baked into the repo (all found by running)
95
+ max_steps now honored; `optim: adamw_torch` (paged → cuMemAllocManaged crash);
96
+ `max_prompt_length` removed (gone in TRL 1.9.2); KTO batch≥2 + reduced seqlen;
97
+ setsid detachment; full-image-set check; triton 3.6.0 for fla. Working stack:
98
+ **torch 2.13.0+cu130 / triton 3.6.0 / fla 0.5.2 / trl 1.9.2 / transformers 5.14.1**.
99
+
100
+ ## Hardware option: RTX PRO 6000 Blackwell (96GB, sm_120)
101
+
102
+ A strong candidate — 96GB kills the KTO memory juggling (batch 4 at full
103
+ `max_seq_length: 4096`, no `expandable_segments` needed) and the silicon is
104
+ faster than the A6000/A100. `bash scripts/setup_blackwell.sh` sets it up.
105
+
106
+ **The one risk, and why the script gates on it:** our fla fix was
107
+ `triton==3.6.0`, but **Blackwell (sm_120) is NEWER than triton 3.6.0** — its
108
+ sm_120 codegen may be missing, in which case the fla Gated-DeltaNet kernel
109
+ won't compile there. CUDA 13.0 (our cu130 torch) *does* satisfy Blackwell's
110
+ ≥12.8 requirement, so the A6000 stack MIGHT run as-is — but this is unverified
111
+ on sm_120. `setup_blackwell.sh` therefore runs the **30-second fla isolation
112
+ test as a hard gate** (prints `FLA_OK` / `FLA_HANG` / `FLA_SLOW`) before you
113
+ trust a run. Reference stacks (affine's `setup_blackwell.sh` /
114
+ `install_finetune_blackwell.sh`) use **cu128 + nightly torch** for sm_120 — the
115
+ script falls back to that if the cu130 wheel can't see the GPU.
116
+
117
+ **Escalation if the gate fails (`FLA_HANG`/`FLA_SLOW`):**
118
+ 1. Uninstall the 3.6.0 pin and use the triton that ships with this torch
119
+ (`pip install --force-reinstall torch` bundles a matching triton), retest.
120
+ 2. Try `flash-linear-attention` from git main (newer sm_120 support).
121
+ 3. If none work: train on the torch fallback — Blackwell's speed + 96GB (bigger
122
+ batch) partly compensates, and you avoid the A6000's memory limits.
123
+
124
+ **Decision rule:** prefer Blackwell IF `FLA_OK`. Its 96GB + fla + faster silicon
125
+ is the best case (likely < the A100's ~6s/ex, so the ≤7-hour budget buys MORE
126
+ examples). If fla won't compile on sm_120 and the A100's cu12x stack takes
127
+ triton 3.6.0 cleanly, the A100 is the safer pick for the fla speedup. Test the
128
+ gate first; let the number decide.
README.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coder-training — fine-tune our own threejs coder checkpoint
2
+
3
+ Implements `../CODER_TRAINING_PLAN.md` (what data, why, how it was verified)
4
+ using `../CONTRASTIVE_TRAINING_GUIDE.md`'s established format (algorithm
5
+ comparison + hyperparameter tables, see `TRAINING_GUIDE.md`), adapted from a
6
+ custom Gaussian-decoder trainer to a real LLM fine-tune via TRL. This is the
7
+ one lever the competitive-intelligence research in `../past-winner/` and
8
+ `../miner-submission/` identified as untried and highest-leverage: every
9
+ recent leader forks the same architecture and even, in 4 of 5 cases, the
10
+ same underlying coder checkpoint lineage — see `../past-winner/README.md`.
11
+
12
+ **Status: SFT verified end-to-end on a real Thunder A6000** (loss drops, eval runs, LoRA adapter checkpoint saves) on the curated data; KTO uses the same machinery. Throughput and deployment bugfixes documented — see DEPLOYING_ON_THUNDER.md and SPEEDUP_FINDINGS.md. Full multi-day run not yet started. Phase 0/1 (scrape +
13
+ build datasets) has actually been executed — 142,647 usable duel records
14
+ archived, `datasets/{sft,kto,preference}.jsonl` built from them — but that
15
+ data isn't in this git repo (see "Getting this onto an instance" below).
16
+ Training code is written and reviewed for syntax/import correctness, but
17
+ there's no GPU in the environment it was built in — see "Pre-flight
18
+ checklist" below for what to verify before trusting a real training run,
19
+ especially the multimodal model/TRL API surface, which moves fast and
20
+ couldn't be checked against a live install.
21
+
22
+ ## What's here
23
+
24
+ ```
25
+ coder-training/
26
+ data/
27
+ curate_manifest.py THROUGHPUT — subsample the manifest to ~10%
28
+ by prompt-dedup + judge-stage selection before
29
+ build_datasets.py (see SPEEDUP_FINDINGS.md)
30
+ scrape_duels.py Phase 0 — archive the competition's real per-prompt
31
+ duel data before its CDN retention window closes
32
+ (see CODER_TRAINING_PLAN.md — time-sensitive)
33
+ build_datasets.py Phase 1 — shape the archive into sft/preference/kto JSONL
34
+ dataset_utils.py shared HF-Datasets loading (lazy image loading)
35
+ common.py shared model/LoRA/QLoRA/wandb setup
36
+ train_sft.py Stage 1: SFT distillation on winners
37
+ train_kto.py Stage 2, RECOMMENDED — see TRAINING_GUIDE.md
38
+ train_dpo.py Stage 2, alternative
39
+ train_simpo.py Stage 2, alternative (reference-free)
40
+ muon.py opt-in Muon–AdamW hybrid optimizer (experimental)
41
+ train_sft_unsloth.py FALLBACK SFT via Unsloth (see SPEEDUP_FINDINGS.md)
42
+ train_kto_unsloth.py FALLBACK KTO via Unsloth
43
+ unsloth_common.py Unsloth FastVisionModel loading
44
+ configs/{sft,kto,dpo,simpo}.yaml hyperparameters, each cited to a paper
45
+ eval/
46
+ self_judge_eval.py Phase 3 — held-out eval against REAL archived
47
+ winners using the REAL validator judge
48
+ judge_challenge.py vendored copy of that judge (see its docstring)
49
+ scripts/
50
+ setup_env.sh run once on a fresh instance
51
+ setup_fast_kernels.sh THROUGHPUT — fla 0.4.2 + fused MoE kernel + verify
52
+ setup_unsloth.sh FALLBACK training stack (alternative to fla path)
53
+ run_pipeline.sh scrape -> build -> SFT -> preference-tune
54
+ requirements.txt
55
+ NEXT_INSTANCE_TRAINING.md START HERE — master handoff: the fla/triton-3.6
56
+ speedup fix, ≤7-hour recipe, verified vs pending
57
+ DEPLOY_A100_AGENT_RUNBOOK.md step-by-step agent runbook for an A100 80GB
58
+ (self-contained; VERIFY gates + failure table)
59
+ DEPLOYING_ON_THUNDER.md runbook + verified bugfixes for a fresh Thunder
60
+ GPU instance (SFT + KTO both verified end-to-end)
61
+ SPEEDUP_FINDINGS.md why the naive run was ~165 days and how the
62
+ same 48GB GPU gets it to days (research-cited)
63
+ TRAINING_GUIDE.md algorithm choice + hyperparameters, paper-cited
64
+ ```
65
+
66
+ ## Getting this onto an instance
67
+
68
+ Code and data travel separately — code is small (~150KB) and lives in this
69
+ git repo; data is large (archive/ 3.2GB + datasets/ 6.5GB) and is **not**
70
+ committed (see `.gitignore`) — scp it directly instead:
71
+
72
+ ```bash
73
+ # on the instance
74
+ git clone https://github.com/karvachiik-lgtm/threejstraining.git coder-training
75
+ cd coder-training
76
+ bash scripts/setup_env.sh # venv + deps + pre-flight checks; tells you what's next
77
+
78
+ # from your local machine, in a separate step (this is the ~9.7GB part)
79
+ scp -r /Users/xavier/bittensor/404-gen-subnet/404-agent/coder-training/{archive,datasets} \
80
+ you@instance:~/coder-training/
81
+ ```
82
+
83
+ `eval/self_judge_eval.py` additionally imports `RendererModule` from
84
+ `../miner-submission/pipeline_service` (it reuses the real renderer instead
85
+ of reimplementing headless-Chromium rendering) — scp `miner-submission/`
86
+ (2.8MB) over too if you'll run Phase 3 eval, as a sibling of `coder-training/`,
87
+ or pass `--pipeline-service-dir` to point at wherever you put it. Nothing
88
+ else needs it — `scrape_duels.py`, `build_datasets.py`, and all four
89
+ `train_*.py` scripts are fully self-contained.
90
+
91
+ ```bash
92
+ scp -r /Users/xavier/bittensor/404-gen-subnet/404-agent/miner-submission you@instance:~/
93
+ ```
94
+
95
+ ## Running it
96
+
97
+ ```bash
98
+ ssh you@instance
99
+ cd coder-training
100
+ source .venv/bin/activate
101
+ export WANDB_API_KEY=... # wandb login also works
102
+
103
+ # datasets/ already scp'd over (see above) — skip straight to training:
104
+ python train_sft.py --config configs/sft.yaml
105
+ python train_kto.py --config configs/kto.yaml # or train_dpo.py / train_simpo.py — see TRAINING_GUIDE.md
106
+ ```
107
+
108
+ Building the dataset fresh instead of scp'ing it (not needed if you scp'd
109
+ `datasets/` — only relevant for picking up new rounds later):
110
+ ```bash
111
+ python data/scrape_duels.py --rounds-dir <path-to-404-active-competition/rounds> --out-dir ./archive
112
+ python data/build_datasets.py --manifest ./archive/duels_index.jsonl --out-dir ./datasets
113
+ ```
114
+
115
+ Watch progress in wandb (`WANDB_PROJECT` defaults to `404-coder-training`,
116
+ set in each config's `wandb:` block) — loss curves, and once the preference
117
+ stage runs, TRL's own logged reward-accuracy/margin metrics. See
118
+ `TRAINING_GUIDE.md`'s "What to watch in wandb" for what those numbers should
119
+ be doing.
120
+
121
+ Then, once you have a checkpoint served behind an OpenAI-compatible endpoint
122
+ (e.g. point vLLM at `checkpoints/kto/`):
123
+ ```bash
124
+ python eval/self_judge_eval.py \
125
+ --checkpoint-base-url http://localhost:8000/v1 --checkpoint-model <served-name> \
126
+ --judge-base-url https://openrouter.ai/api/v1 --judge-api-key-env OPENROUTER_API_KEY \
127
+ --wandb
128
+ ```
129
+ This is Phase 3 of `CODER_TRAINING_PLAN.md` — the actual bar to clear before
130
+ this is worth putting into `../miner-submission/configuration.yaml` and
131
+ testing further per `../miner-submission/TESTING_WITHOUT_GPU.md`: does the
132
+ new checkpoint beat the REAL archived competition winners on held-out
133
+ prompts, according to the REAL validator judge — not a proxy metric.
134
+
135
+ ## Pre-flight checklist — verify before trusting a real run
136
+
137
+ Nothing below is a known bug — these are the specific places this repo makes
138
+ an assumption about an environment (a live GPU + specific package versions)
139
+ that doesn't exist where it was written, so they're unverified, not wrong:
140
+
141
+ 1. **`transformers` support for the `qwen3_5` architecture.**
142
+ `Tooony133/Qwen-3.6-27B-*` and `Qwen/Qwen3.6-27B` report
143
+ `architectures: ["Qwen3_5ForConditionalGeneration"]` / `model_type:
144
+ "qwen3_5"` (checked via the HF API). `scripts/setup_env.sh` checks for
145
+ this and tells you if you need `transformers` from source.
146
+ 2. **TRL's exact VLM dataset/collator conventions for your installed
147
+ version.** `data/dataset_utils.py` + the chat-message shape in
148
+ `data/build_datasets.py` follow TRL's documented pattern as of when this
149
+ was written, but TRL's vision-language support is newer and moves faster
150
+ than its text-only DPO/SFT — check `python -c "from trl import DPOConfig;
151
+ help(DPOConfig)"` (and `KTOConfig`/`CPOConfig`/`SFTConfig`) against
152
+ whatever version `pip install` actually resolves.
153
+ 3. **The PEFT-adapter-disable trick for the reference model** (`ref_model=
154
+ None` + `peft_config` in `train_dpo.py`/`train_kto.py`) — documented TRL
155
+ behavior, not invented here, but confirm it's actually skipping a second
156
+ full model load (watch VRAM at startup) rather than silently loading a
157
+ full reference copy anyway.
158
+ 4. **`eval/self_judge_eval.py`'s `RendererModule`/`PipelineTask` integration**
159
+ — written by reading `../miner-submission/pipeline_service/modules/
160
+ renderer/module.py` and `pipeline/task.py`'s source, not by running it.
161
+ If `render_js()` raises or `task.rendered_png` stays `None`, that's the
162
+ first place to look — see the docstring at the top of that file.
163
+ 5. **VRAM sizing.** No instance to test against here. `Tooony133/Qwen-3.6-
164
+ 27B-AronHorn` reports ~56GB BF16 weights (HF API `usedStorage`) — QLoRA's
165
+ 4-bit quantization (enabled by default in every config here) should bring
166
+ the base model to ~14-16GB, leaving room for LoRA adapters + activations
167
+ + optimizer states on a single 40-80GB GPU, per QLoRA's own headline
168
+ claim of fitting a 65B model on a single 48GB GPU — but size your actual
169
+ instance against real `nvidia-smi` numbers on a short run before
170
+ committing to a long one.
SPEEDUP_FINDINGS.md ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Making training viable on a single 48GB GPU — research findings & plan
2
+
3
+ **Problem.** A baseline SFT run on a single RTX A6000 (48GB) measured
4
+ **49.7s/example**, GPU-bound at 100% util, 44/49GB VRAM at batch_size=1.
5
+ Extrapolated to the full data that's **~43.5 days for SFT** (37,788 rows ×2
6
+ epochs) and **~165 days for KTO** (285,294 rows) — not viable. The constraint
7
+ is to **stay on this single-48GB-class GPU for cost reasons** (no bigger/multi
8
+ GPU), so every lever below is one that works on the same hardware.
9
+
10
+ This is the synthesis of three parallel research passes (kernel stack, other
11
+ efficiency levers, data-scope reduction). Everything here is grounded in a
12
+ source that was actually read — see the per-section links.
13
+
14
+ ## Root cause: three naive "torch fallback" paths, not one
15
+
16
+ `Tooony133/Qwen-3.6-27B-*` / `Qwen/Qwen3.6-27B` reports `model_type: "qwen3_5"`
17
+ — a **hybrid** architecture: ~75% Gated DeltaNet linear-attention layers, ~25%
18
+ full attention, on top of an **MoE** MLP. Two of those three run unfused unless
19
+ the right kernel package is importable, and we were running the raw dataset:
20
+
21
+ | Lever | What was slow | Fix | Where |
22
+ |---|---|---|---|
23
+ | **Gated DeltaNet (75% of layers)** | unfused torch path — `transformers`' `qwen3_5` gates the fast path behind `is_flash_linear_attention_available()`; without `fla` installed it silently falls back | `pip install flash-linear-attention==0.4.2` (Triton JIT, no nvcc) | `scripts/setup_fast_kernels.sh` |
24
+ | **MoE expert dispatch** | native `qwen3_5_moe` dispatches experts with a **Python for-loop** over experts (verified in source) | community fused grouped-GEMM kernel (`woct0rdho/transformers-qwen3-moe-fused`, bnb-4bit/LoRA compatible) | `scripts/setup_fast_kernels.sh` |
25
+ | **Dataset size** | 142,647 duels but only **1,839 unique prompts** (~78× redundancy) | curate to ~10% by prompt-dedup + judge-stage selection | `data/curate_manifest.py` |
26
+ | **VRAM at bs=1** | maxed at batch_size=1, can't raise batch | `paged_adamw_8bit` + `use_reentrant:false` free VRAM | all `configs/*.yaml` |
27
+
28
+ These stack. Data-cut alone is ~10× (KTO 165d → ~16d). Add even a modest 3×
29
+ from the kernels and KTO lands in **low-single-digit days**, SFT in **well
30
+ under a day** — on the A6000 we already have.
31
+
32
+ ## 1. Attention kernel — `flash-linear-attention`, pinned to **0.4.2**
33
+
34
+ - Installing `fla` flips the Gated DeltaNet layers to fused Triton kernels
35
+ automatically — no model-load flag needed, `transformers` auto-detects it.
36
+ It's mostly Triton (JIT at runtime), so **no nvcc / CUDA-toolkit build** — which
37
+ is exactly why it sidesteps the `causal-conv1d` dead end (source-only wheel,
38
+ untested against this instance's CUDA 13.0).
39
+ - **Pin 0.4.2, not latest, not 0.4.1.** fla **0.5.0 has a confirmed corruption
40
+ bug** (garbage "!!!!" output) that hits the **multimodal generation path**
41
+ specifically — and our model is a VLM, so that's our path. 0.5.1/0.5.2 don't
42
+ document a fix, so treat 0.5.x as unverified for VLM. 0.4.2 is the version a
43
+ reporter explicitly verified (Axolotl's official Qwen3-Next recipe pins 0.4.1;
44
+ 0.4.2 is the same line, verified good).
45
+ - **The one unverified step:** confirm `is_flash_linear_attention_available()`
46
+ returns True after install (the setup script does this) before any long run.
47
+ - Sources: fla issue #792 (multimodal "!!!!" bug) https://github.com/fla-org/flash-linear-attention/issues/792 ·
48
+ releases https://github.com/fla-org/flash-linear-attention/releases ·
49
+ Axolotl Qwen3-Next recipe https://docs.axolotl.ai/docs/models/qwen3-next.html ·
50
+ transformers Qwen3Next/fla gate https://github.com/huggingface/transformers/issues/41732
51
+
52
+ ## 2. MoE dispatch — the second slow path
53
+
54
+ - Independent of attention: `transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py`
55
+ runs a Python for-loop over experts (`@use_experts_implementation` marks the
56
+ swap point). So even after `fla`, MoE routing can still be unfused.
57
+ - Fix: `woct0rdho/transformers-qwen3-moe-fused` (bnb-4bit / LoRA compatible,
58
+ tuned for the thin matrices QLoRA produces). Marked **optional** in the setup
59
+ script — it's a community package; verify it imports and that smoke-test eval
60
+ quality is unchanged before trusting it on a long run. `fla` alone is the bulk
61
+ of the win. Alternative if your `transformers` exposes it: v5's fused-experts
62
+ integration (issue #40582 grouped-GEMM proposal).
63
+ - Sources: qwen3_5_moe source https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py ·
64
+ fused kernel https://github.com/woct0rdho/transformers-qwen3-moe-fused ·
65
+ PEFT discussion https://github.com/huggingface/peft/discussions/2622 ·
66
+ Unsloth faster-MoE https://unsloth.ai/docs/basics/faster-moe
67
+
68
+ ## 3. Data scope — curate to ~10% (biggest single lever)
69
+
70
+ The raw data is **mostly redundant**: 142,647 duels, **1,839 unique prompts**
71
+ (some recur 440×). And the judge's `detail.decided_by` is a real per-duel
72
+ informativeness/label-reliability signal (unlike `match_margin`, which
73
+ build_datasets.py's own comment warns is a coarse whole-MATCH aggregate):
74
+ **S1 ≈ 82%** (decided immediately — cleanest label), **S2/S3 ≈ 18%** (contested,
75
+ near-boundary), **S4 "was draw"** (forced tie-break — least reliable).
76
+
77
+ `data/curate_manifest.py` (validated end-to-end on the real local manifest):
78
+ - dedups the identical (winning-code, losing-code) pairs that recur across a
79
+ prompt's many duels,
80
+ - caps duels per unique prompt (`--per-prompt-cap`, default 8),
81
+ - reserves part of each prompt's cap for contested S2/S3 duels
82
+ (`--contested-reserve`, default 0.25) so we get **both** reliable-clear and
83
+ near-boundary examples — hedging the genuine split in the literature (see
84
+ below), rather than an accidental all-S1 monoculture,
85
+ - drops S4-was-draw + malformed rows as least-reliable labels.
86
+
87
+ **Measured result** (real run, `--per-prompt-cap 8`): 142,647 → **14,575 duels
88
+ (10.2%)**, stage mix 11,300 S1 / 3,113 S2 / 162 S3. Rebuilding datasets from it:
89
+ SFT **37,788 → 10,464**, preference **142,647 → 14,575**, KTO **285,294 →
90
+ 29,150** — with full prompt coverage preserved.
91
+
92
+ Why ~10% should match or beat the full run (all read directly):
93
+ - **KTO paper (2402.01306)**: KTO matches DPO using **up to 90% fewer** desirable
94
+ examples; one setup cut training data 72% and still beat DPO. Ratio guidance:
95
+ default λ_D=λ_U=1; empirically ~4:3 desirable:undesirable best on most sets but
96
+ 1:1 on UltraFeedback — **tune on our data**, don't assume.
97
+ - **"Less is More" / BeeS (2502.14560)**: keeping the **high-margin 10%** of
98
+ preference data *beat the full set* by ~2.2 pts, and the subset transfers to
99
+ KTO/IPO/SLiC. Filters the near-tie "Z-region" and mislabeled negative-margin.
100
+ - **Counterpoint (2508.04149)**: keeps **low-margin (hard, near-boundary)** 10%
101
+ instead — hence our default keeps a mix, not pure high-margin.
102
+ - Corroborating cut-ratios: LESS (2402.04333) — 5% influence-selected beats full;
103
+ LIMA (2305.11206) — 1,000 curated SFT examples; survey 2402.05123.
104
+ - Sources: https://arxiv.org/abs/2402.01306 · https://arxiv.org/html/2502.14560 ·
105
+ https://arxiv.org/abs/2508.04149 · https://arxiv.org/abs/2402.04333 ·
106
+ https://arxiv.org/abs/2305.11206 · https://arxiv.org/abs/2402.05123
107
+
108
+ ## 4. VRAM levers to unlock batch_size > 1
109
+
110
+ - **`paged_adamw_8bit`** — paged optimizers originate in the QLoRA paper (used to
111
+ survive gradient-checkpointing memory spikes); 8-bit cuts optimizer-state
112
+ memory, paging overhead is negligible during stable training. Since we're
113
+ VRAM-maxed at bs=1, the freed VRAM is what lets batch rise — and batch size
114
+ drives throughput far more than the optimizer's own compute. (With LoRA the
115
+ optimizer only covers adapter params, so the absolute saving is modest; the
116
+ value is headroom, not raw footprint.)
117
+ - **`gradient_checkpointing_kwargs: {use_reentrant: false}`** — the documented
118
+ fix for the classic bnb-4bit + gradient-checkpointing "inputs don't require
119
+ grad" RuntimeError (gradient must flow through frozen quantized weights);
120
+ also generally faster, and PyTorch's future default.
121
+ - Both are now set in every `configs/*.yaml` and threaded through all four
122
+ `train_*.py`.
123
+
124
+ ### 4b. Optional: Muon–AdamW hybrid optimizer (experimental, opt-in)
125
+
126
+ Set `optim: "muon_adamw"` in any config to route the 2D LoRA matrices through
127
+ **Muon** (SGD-momentum update orthogonalized via a Newton–Schulz iteration;
128
+ Jordan et al.) while scalars/embeddings stay on AdamW. Implemented in
129
+ `muon.py` (vendored `SingleDeviceMuonWithAuxAdam`, single-GPU) and threaded
130
+ through all four trainers via a `create_optimizer` override; **default stays
131
+ `paged_adamw_8bit`** — nothing runs unless a config asks for it.
132
+
133
+ Why it's worth an A/B here, and the caveat:
134
+ - "Can Muon Fine-tune Adam-Pretrained Models?" (ICML 2026, arXiv 2605.10468)
135
+ finds a real optimizer-mismatch penalty fine-tuning an Adam-pretrained model
136
+ with Muon, **but that LoRA gives implicit robustness** to it — Muon+LoRA is
137
+ "stable and competitive even at suboptimal lr." That's our exact case.
138
+ - CAVEAT: applying Muon to LoRA's A and B as ordinary matrices is
139
+ **parametrization-dependent**, NOT the same as orthogonalizing ΔW=B·A.
140
+ "LoRA meets Riemannion" (ICLR 2026, arXiv 2507.12142) gives the invariant
141
+ version; we implement the common naive form (what the ICML paper evaluates).
142
+ Treat it as an experiment vs paged_adamw_8bit — validate on the smoke test +
143
+ held-out eval, don't assume a win.
144
+ - The implementation's interface was cross-checked against a **production
145
+ Muon+LoRA setup** (an SN102 miner using the same `SingleDeviceMuonWithAuxAdam`
146
+ `use_muon` param-group API); proven reference values: momentum=0.95,
147
+ Muon-group weight_decay=0.1, muon lr≈1e-3 with LoRA r=128.
148
+ - Sources: https://kellerjordan.github.io/posts/muon/ ·
149
+ https://arxiv.org/abs/2605.10468 · https://arxiv.org/abs/2507.12142 ·
150
+ torch.optim.Muon (PyTorch >= 2.9)
151
+ - Sources: QLoRA https://arxiv.org/abs/2305.14314 ·
152
+ use_reentrant/4-bit gradient-checkpointing https://github.com/huggingface/transformers/issues/21381 ,
153
+ https://github.com/huggingface/peft/pull/2398
154
+
155
+ ## Deliberately NOT doing
156
+
157
+ - **Bigger / multi-GPU** — off the table by cost constraint (this doc's premise).
158
+ - **`causal-conv1d` from source** — source-only wheel, untested vs CUDA 13.0; `fla`
159
+ replaces it. Dead end.
160
+ - **`torch.compile` over fla kernels** — no confirmed-working stack for GDN
161
+ training; a related VLM report (transformers #44962) shows FA2 vision attention
162
+ *breaking* compile. Speculative; don't block on it.
163
+ - **flash-attn-2 for the 25% full-attn layers** — marginal (those are only 25% of
164
+ layers, linear-attn dominates), and no official CUDA-13 wheel. `sdpa` is fine.
165
+ - **FlashQLA** (Qwen's TileLang GDN kernels, 2–3× over fla) — **Hopper-only**,
166
+ nothing on Ampere A6000. https://github.com/QwenLM/FlashQLA
167
+ - **Sequence/example packing** — TRL forces `skip_prepare_dataset=True` for VLMs
168
+ and packing lives in the pipeline VLMs bypass; our custom collator is
169
+ structurally incompatible. https://huggingface.co/docs/trl/en/sft_trainer
170
+
171
+ ## The one open decision: TRL vs Unsloth
172
+
173
+ Unsloth now officially supports LoRA **training** (not just GGUF export) for this
174
+ Gated-DeltaNet hybrid, ships its own fused kernels, and claims 1.5× faster / 50%
175
+ less VRAM vs FA2. **But** it explicitly recommends *against* 4-bit QLoRA for this
176
+ family (quantization error too high) and its VRAM table puts 27B bf16 LoRA at
177
+ ~56GB — over our 48GB. So on 48GB we're forced into QLoRA regardless, i.e. we'd
178
+ be using Unsloth's kernels in exactly the config they warn about — a real quality
179
+ risk needing live eval. **Recommendation: stay on TRL + fla + fused-MoE** (proven
180
+ compatible with our existing QLoRA pipeline), keep Unsloth as a benchmark to try
181
+ *after* a working baseline, not before. Sources:
182
+ https://unsloth.ai/docs/models/qwen3.5/fine-tune · https://github.com/unslothai/unsloth/issues/3358
183
+
184
+ **A ready Unsloth fallback is now in the repo** (in case of trouble on the new
185
+ instance): `scripts/setup_unsloth.sh`, `train_sft_unsloth.py`,
186
+ `train_kto_unsloth.py`, `configs/{sft,kto}_unsloth.yaml`, `unsloth_common.py`
187
+ (FastVisionModel loading). These are grounded in Unsloth's documented Qwen3.5
188
+ API but UNVERIFIED on hardware — use the TRL path first; switch only if it
189
+ misbehaves. The 4-bit-vs-48GB tension (Unsloth advises against 4-bit on
190
+ Qwen3.5, but 27B bf16 = ~56GB > 48GB) is documented in setup_unsloth.sh: on
191
+ 48GB you either run 4-bit against advice (validate quality) or drop to a
192
+ smaller Qwen3.5 variant (9B ≈ 22GB).
193
+
194
+ ## Turnkey sequence on the next instance
195
+
196
+ ```bash
197
+ git clone https://github.com/karvachiik-lgtm/threejstraining.git coder-training
198
+ cd coder-training
199
+ bash scripts/setup_env.sh
200
+ bash scripts/setup_fast_kernels.sh # fla 0.4.2 + fused MoE + verify fast path
201
+ # transfer archive/ + datasets/ per README (tar+gzip stream, not scp -r)
202
+ python data/curate_manifest.py --in archive/duels_index.jsonl \
203
+ --out archive/duels_index_curated.jsonl --per-prompt-cap 8
204
+ python data/build_datasets.py --manifest archive/duels_index_curated.jsonl \
205
+ --out-dir ./datasets # overwrites datasets/ with the ~10% curated set
206
+ # re-run the 32-row smoke test FIRST and compare s/example to the 49.7s baseline:
207
+ python train_sft.py --config configs/smoketest_sft.yaml
208
+ # then the real runs:
209
+ python train_sft.py --config configs/sft.yaml
210
+ python train_kto.py --config configs/kto.yaml
211
+ ```
212
+
213
+ ## Measured profiling on the A6000 (July 2026) — where the 33s/step goes
214
+
215
+ Ran controlled fwd/bwd benchmarks on the real 27B 4-bit model (one 4096-token
216
+ example, gradient checkpointing on):
217
+
218
+ - **Baseline: 32.8s/step** (pure fwd+bwd; real training ~49s/example incl. data).
219
+ - **It is NOT the LoRA.** Full LoRA (r64, all-linear, 319M trainable) vs a 64×
220
+ smaller LoRA (r8, attn-only, 5M): fwd+bwd 29.4s vs 27.5s — the giant adapter
221
+ costs only **2.0s (7%)**. Shrinking LoRA is not a throughput lever.
222
+ - **It's the base-model backward.** Backward is **77%** of the step (22.8s of
223
+ 29.4s); forward alone is ~7s. Backward being ~4× forward (vs the usual ~2×)
224
+ points at the naive Gated-DeltaNet kernel's backward + gradient-checkpoint
225
+ recompute as the hotspot — exactly the layers a fused kernel would replace.
226
+ - **Both fused paths are blocked by Triton on this instance.** `fla` (0.4.2 and
227
+ 0.5.2) hangs even in isolation on a tiny tensor (30s timeout); `torch.compile`
228
+ (inductor, also Triton) hangs the same way (compile workers at 0% CPU). Root
229
+ cause is the environment: **Triton 3.7.1 / CUDA 13.0 / A6000 deadlocks on
230
+ kernel generation**, not the model. On a stable stack (e.g. torch 2.5 /
231
+ CUDA 12.x / triton 3.1) fla should work and unlock the backward — this is the
232
+ real ~10× and the top priority. See `DEPLOY_A100_AGENT_RUNBOOK.md`'s CRITICAL
233
+ section.
234
+
235
+ ## RESOLVED (2026-07-31): triton 3.6.0 unlocks fla — 3.6× measured
236
+
237
+ The "Triton is broken" conclusion above was half-right: triton **3.7.1**
238
+ deadlocks, but **triton 3.6.0 works**. Found via vLLM (it ran the model's GDN
239
+ kernels fine on 3.6.0). After `pip install triton==3.6.0 flash-linear-attention==0.5.2`
240
+ in the training venv, the fixed-4096 fwd+bwd dropped **32.8s → 9.0s/step (3.6×)**;
241
+ the fla chunk kernel warms to 5.4ms. Not the full ~10× because causal-conv1d
242
+ (needs nvcc) still falls back. See `NEXT_INSTANCE_TRAINING.md` for the recipe.
TRAINING_GUIDE.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Coder checkpoint training guide
2
+
3
+ Companion to `../CODER_TRAINING_PLAN.md` (the data side — what's archived, why,
4
+ and how it was verified) and this repo's `README.md` (how to actually run
5
+ this on a rented instance). This doc is the algorithm choice: which
6
+ preference-optimization method, why, and with what hyperparameters —
7
+ grounded in the actual papers, not general reputation. Same spirit as
8
+ `../CONTRASTIVE_TRAINING_GUIDE.md`'s comparison-table format, applied to a
9
+ real LLM fine-tune instead of a custom Gaussian decoder, so TRL does the
10
+ heavy lifting instead of a hand-rolled loss.
11
+
12
+ ## Two-stage recipe
13
+
14
+ 1. **SFT** (`train_sft.py`) on winners-only generations — teaches output
15
+ format and Three.js conventions from scratch. Preference optimization
16
+ alone can't do this; it only sharpens preferences between things the
17
+ model already knows how to produce.
18
+ 2. **Preference optimization** (`train_kto.py` / `train_dpo.py` /
19
+ `train_simpo.py`) on top of the SFT adapter — teaches the model to
20
+ prefer what the real competition judge preferred, not just plausible
21
+ Three.js code.
22
+
23
+ ## Algorithm comparison
24
+
25
+ | Algorithm | Needs paired data? | Needs a reference model? | Best-fit here |
26
+ |-----------|---------------------|----------------------------|----------------|
27
+ | **KTO** (recommended) | No — independent (x, y, label) | Yes (PEFT-adapter-disable trick, no 2nd copy) | Matches our binary + draws + potential-imbalance data shape directly |
28
+ | DPO | Yes — strict (chosen, rejected) | Yes (same trick) | Fallback/comparison run; well-studied, more brittle to the pairing requirement |
29
+ | SimPO | Yes — strict (chosen, rejected) | **No** — reference-free | Cheapest per step; explicitly fixes a length-bias risk that's real for us (JS length varies a lot by object) |
30
+
31
+ ## 1. KTO — recommended first choice
32
+
33
+ **Loss** (Ethayarajh et al., 2402.01306): for each independent example
34
+ `(x, y, label)`, with `r_θ(x,y) = log(π_θ(y|x)/π_ref(y|x))` and a KL estimate
35
+ `z_0` from a reference microbatch (no gradient through `z_0`):
36
+
37
+ ```
38
+ v(x,y) = λ_D · σ(β(r_θ − z_0)) if y is desirable
39
+ = λ_U · σ(β(z_0 − r_θ)) if y is undesirable
40
+ L_KTO = E[λ_y − v(x,y)]
41
+ ```
42
+
43
+ **Why this is the best-grounded choice for our data, not just "the newest
44
+ option"**: the paper states its own decision rule directly — *"When human
45
+ feedback is in a binary format, and especially when there is an imbalance
46
+ between the desirable and undesirable examples, KTO is the natural
47
+ choice."* Our archived duel data is exactly binary-format feedback (winner/
48
+ loser per prompt) with a real draw fraction (~23% in the round checked —
49
+ see `../CODER_TRAINING_PLAN.md`) that has no valid chosen/rejected ordering
50
+ DPO and SimPO's Bradley-Terry loss structurally requires. KTO doesn't need
51
+ matched pairs at all — the paper shows it tolerating up to 90% dropout of
52
+ desirable examples and beating DPO with 72% less data in a one-y-per-x
53
+ setup. It also pairs naturally with an SFT-first recipe (their own
54
+ recommended pipeline).
55
+
56
+ **Hyperparameters** (`configs/kto.yaml`): `beta=0.1` ("close-to-optimal for
57
+ most settings" per paper), `lr=5e-6`, AdamW, effective batch ≈32. For
58
+ imbalance, the paper's rule is `desirable_weight·n_D / (undesirable_weight·
59
+ n_U) ∈ [1, 4/3]` — check `data/build_datasets.py`'s printed counts before
60
+ assuming the default 1.0/1.0 still holds if you filter the data afterward.
61
+
62
+ **Using the graded per-angle scores**: not native to KTO's binary loss, but
63
+ the paper explicitly flags `λ_y` as extensible — *"more complex schemes
64
+ could also be used for importance sampling."* An untested but paper-licensed
65
+ extension: scale `desirable_weight`/`undesirable_weight` per example by the
66
+ archived judge's per-angle penalty gap (`detail.s1.angles[].pen_a/pen_b` in
67
+ `../CODER_TRAINING_PLAN.md`'s schema) instead of a flat 1.0 — harsher
68
+ penalty for confidently-bad losers, gentler for near-misses. Not implemented
69
+ here; worth trying if the flat-weight run underperforms.
70
+
71
+ ## 2. DPO — fallback / comparison run
72
+
73
+ **Loss** (Rafailov et al., 2305.18290):
74
+ ```
75
+ L_DPO = −E[log σ(β·log(π_θ(y_w|x)/π_ref(y_w|x)) − β·log(π_θ(y_l|x)/π_ref(y_l|x)))]
76
+ ```
77
+ **Hyperparameters** (`configs/dpo.yaml`): `beta=0.1` (paper used 0.5 for a
78
+ summarization task specifically — not ours), `lr=1e-6`, linear warmup over
79
+ 150 steps, batch 64. The paper's own experiments used RMSprop; TRL defaults
80
+ to AdamW — if training is unstable, RMSprop is the paper-exact thing to try
81
+ first, not a random guess. **The sigmoid weighting is load-bearing** — the
82
+ paper's own ablation found removing it "can cause the language model to
83
+ degenerate." `loss_type: "sigmoid"` in the config is the standard/tested
84
+ form; TRL's DPOConfig also accepts `"ipo"` (adds its own regularization,
85
+ worth trying if sigmoid-DPO overfits) and other variants — check your
86
+ installed TRL version's docs before switching.
87
+
88
+ ## 3. SimPO — reference-free alternative
89
+
90
+ **Loss** (Meng, Xia, Chen, 2405.14734), via TRL's `CPOTrainer` with
91
+ `loss_type="simpo"`:
92
+ ```
93
+ L_SimPO = −E[log σ((β/|y_w|)·log π_θ(y_w|x) − (β/|y_l|)·log π_θ(y_l|x) − γ)]
94
+ ```
95
+ No reference model at all — reward is the length-*normalized* average
96
+ log-prob. **Why this matters for us specifically, not just in general**:
97
+ the paper's motivating finding is that DPO's un-normalized (summed)
98
+ log-prob reward is biased toward longer completions, and generated
99
+ Three.js module length genuinely varies a lot by object complexity in our
100
+ data — this isn't a hypothetical risk, it's the exact failure mode the
101
+ method exists to fix.
102
+
103
+ **Hyperparameters** (`configs/simpo.yaml`): using the paper's "Llama-3-Base"
104
+ setting (`beta=2.0`, `gamma=1.0`, `lr=6e-7`) as the closest analog to our
105
+ recipe — their "Instruct" settings assume on-policy-regenerated pairs, ours
106
+ are the competition's own archived (off-policy) generations. **Note the
107
+ learning rate is an order of magnitude below KTO/DPO's** — that's the
108
+ paper's finding, not a typo; SimPO needed a smaller lr than DPO in every
109
+ setting they tested. `gamma` is a literal target-margin term the paper
110
+ found needs tuning — "performance improves with an increasing target margin
111
+ but degrades when too large" — the single knob most worth sweeping if
112
+ results are weak. Untested extension, same spirit as KTO's `λ_y` idea:
113
+ scale `gamma` per-pair from the archived per-angle penalty gap instead of a
114
+ fixed scalar.
115
+
116
+ ## LoRA / QLoRA setup (all three methods)
117
+
118
+ `common.py` + every config's `lora:`/`qlora:` block, grounded in:
119
+ - **QLoRA** (Dettmers et al., 2305.14314): *"the most critical LoRA
120
+ hyperparameter is how many LoRA adapters are used in total and that LoRA
121
+ on all linear transformer block layers are required to match full
122
+ finetuning performance ... the projection dimension r does not affect
123
+ performance."* This is why `DEFAULT_LORA_TARGET_MODULES` covers every
124
+ linear in the backbone (attention + MLP), not just `q_proj`/`v_proj` —
125
+ and why rank isn't obsessed over: `r=64` here is QLoRA's own setting for
126
+ their largest models, not a swept-and-chosen value.
127
+ - **LoRA** (Hu et al., 2106.09685): independently confirms this — on GPT-3
128
+ 175B, adapting `{Wq, Wv}` at `r=4` beat adapting one matrix type alone at
129
+ `r=8`, and `r∈{1,2,4,8,64}` were "nearly indistinguishable" once ≥2 matrix
130
+ types were adapted. Spreading a fixed budget across more matrix types
131
+ beats concentrating it in fewer at higher rank.
132
+ - **33B/65B-bucket values, not 7B/13B**: our ~27.8B model is closer to
133
+ QLoRA's larger bucket — `lr=1e-4` (not `2e-4`), LoRA `dropout=0.05` (not
134
+ `0.1`), constant LR schedule (their setting for that bucket, used in
135
+ `configs/sft.yaml`).
136
+ - **QLoRA's other headline finding, worth remembering while building
137
+ `data/build_datasets.py`'s filters**: *"data quality is far more important
138
+ than dataset size"* — their 9,846-example curated run beat 450k-example
139
+ subsamples. If a full run underperforms, narrowing to
140
+ `--min-margin` (decisive, high-confidence duels only) before doubling raw
141
+ volume is the paper-grounded thing to try first.
142
+
143
+ ## What to watch in wandb
144
+
145
+ - `train/loss` — should decrease steadily for all three methods; SFT before
146
+ the other two even start (see two-stage recipe above).
147
+ - KTO/DPO/SimPO's implicit accuracy/margin metrics (TRL logs these
148
+ automatically, e.g. `rewards/accuracies`, `rewards/margins`) — target
149
+ meaningfully above 0.5 accuracy once the preference stage is running.
150
+ - `eval/win_rate_vs_archived_winner` — from `eval/self_judge_eval.py`
151
+ (Phase 3), logged as its own wandb run. This is the metric that actually
152
+ matters: does the checkpoint beat the REAL archived competition winners
153
+ on held-out prompts, judged by the real validator rubric — not a proxy.
archive/dpo_manifest.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
archive/sft_manifest.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
claude-1-faster-at-least-by-100x.txt ADDED
The diff for this file is too large to render. See raw diff
 
claude-after-sft-judge-fix-first-run-log1.txt ADDED
@@ -0,0 +1,1205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ╭─── Claude Code v2.1.212 ─────────────────────────────────────────────────────╮
2
+ │ │ Tips for getting │
3
+ │ Welcome back Manoj! │ started │
4
+ │ │ Run /init to create a … │
5
+ │ ▐▛███▜▌ │ ─────────────────────── │
6
+ │ ▝▜█████▛▘ │ What's new │
7
+ │ ▘▘ ▝▝ │ Bug fixes and reliabil… │
8
+ │ Opus 4.8 · Claude Pro · │ Added Claude Opus 5 (`… │
9
+ │ manojbhat.research@gmail.com's Organization │ Added `sandbox.network… │
10
+ │ ~/…/404-gen-subnet/404-agent/coder-training │ /release-notes for more │
11
+ ╰──────────────────────────────────────────────────────────────────────────────╯
12
+
13
+
14
+ ⏺ Everything's done. Here's the complete status.
15
+
16
+ ✅ Model uploaded — all 3 checkpoints, public, no README
17
+
18
+ One repo, three branches (all rank-32 PEFT adapters on Qwen/Qwen3.6-27B, ~960
19
+ MB each, public, adapter-only — no model card):
20
+
21
+ reneeice/threejs-coder-qwen3.6-27b-sft-lora
22
+ - main → final sampler (threejs-sft-v1-final = step319 export) — the best per
23
+ the eval
24
+ - step300 → second-last checkpoint
25
+ - step25 → first checkpoint
26
+
27
+ Load a specific one with revision="step25" / "step300". To confirm your
28
+ earlier question: yes — what I first pushed was the final sampler adapter (the
29
+ clean 921 MB inference LoRA, not optimizer state). The step25/step300
30
+ checkpoints were training states (2.7 GB w/ optimizer), so I exported each to
31
+ a clean sampler adapter before publishing.
32
+
33
+ Two hiccups worth noting: push-hf doesn't create the target branch (first
34
+ attempt 404'd on preupload/step300) — I pre-created the branches; and one
35
+ transient RemoteDisconnected cleared on retry.
36
+
37
+ ✅ DPO script review — mechanics correct, two fixes needed
38
+
39
+ The DPO logic is sound (fixed SFT reference, compute_dpo_loss,
40
+ budget/resume/wandb mirroring SFT). But before a real run:
41
+ 1. Eval contamination — load_rows() has no split filter, so it trains on all
42
+ 5,890 pairs including the 814 eval rows the exact-judge harness holds out.
43
+ Filter to split=='train' (5,076).
44
+ 2. --sft-checkpoint must be a load_state STATE path
45
+ (.../weights/threejs-sft-v1-step319), not the final sampler.
46
+ 3. Validate the multimodal reference-logprob path with --limit 2
47
+ --max-cost-usd 1 first (it's the one unproven piece; fails closed).
48
+
49
+ ✅ Phase-2 estimate (computed like SFT)
50
+
51
+ Measured from the real data: 10,770 tokens/pair avg, rate $4.103/1M, script
52
+ bills 2× (policy + reference):
53
+
54
+ - train-only full epoch (5,076 pairs): ~$449, ~14–18 h
55
+ - full file: ~$521
56
+ - budget-capped $50 probe: ~560 pairs, ~1.5–2 h
57
+
58
+ The docstring's "~$260" was ~2× optimistic — it didn't count the reference
59
+ forward. Bottom line: a full Tinker DPO epoch is ~$449 / most of a day (vs
60
+ SFT's $30/65 min). I'd either run a budget-capped partial DPO gated by the
61
+ exact-judge win-rate, or do the full epoch on a rented A100 (train_dpo.py +
62
+ fla stack), which is far cheaper per token.
63
+
64
+ Want me to apply the split=='train' fix to the DPO script and run the --limit
65
+ 2 --max-cost-usd 1 validation?
66
+
67
+ ✻ Brewed for 1m 6s
68
+
69
+ ❯ /compact
70
+ ⎿ Compacted (ctrl+o to see full summary)
71
+ Tip: You have access to Opus 1M with 5x more context
72
+ ⎿  Read ../../../../.claude/projects/-Users-xavier-bittensor-404-gen-subnet-40
73
+ 4-agent-coder-training/memory/exact-judge-eval-pipeline.md (39 lines)
74
+ ⎿  Read ../../../../.claude/projects/-Users-xavier-bittensor-404-gen-subnet-40
75
+ 4-agent-coder-training/memory/dpo-phase2-cost-and-review.md (39 lines)
76
+ ⎿  Read ../../../../.claude/jobs/6053750e/tmp/estimate_dpo_tokens.py (38
77
+ lines)
78
+ ⎿  Read ../../../../.claude/jobs/6053750e/tmp/convert_ckpts.py (16 lines)
79
+ ⎿  Referenced file tinker/exact_eval/run.py
80
+
81
+ ❯ HANDOFF.md THUNDER_JUDGE_IMAGE_RUNBOOK.md `compare_full.py CLI args;
82
+ default = logs/full_faithful_rerun; verified 117/128 (91.4%)` read this to
83
+ understand the issues we faced and we need to fix right now first for
84
+ local-eval parity using thundercompute instances with that of the validators
85
+ results. try reproducing this and use ~/dockercreds ~/dockerkey to upload the
86
+ image created again and with patch etc when we reproduce and get another
87
+ validation of parity
88
+
89
+ ⏺ I'll start by locating and reading the files you mentioned.
90
+
91
+ Listed 1 directory, ran 1 shell command (ctrl+o to expand)
92
+
93
+ ⏺ The files are in the 404-agent dir. Let me read all three.
94
+
95
+ Read 3 files (ctrl+o to expand)
96
+
97
+ ⏺ I've read all three docs. Now I understand the mission: reproduce the round-30
98
+ validator-faithful parity benchmark using the durable Docker image on a
99
+ Thunder A6000, re-validate parity (~112–118/128 expected), and re-push the
100
+ image with patches. Let me assess current state before acting.
101
+
102
+ Ran 1 shell command (ctrl+o to expand)
103
+ ⎿  Interrupted · What should Claude do instead?
104
+
105
+ ❯ no we did reproduce and get the results second time 117 right? Do you think
106
+ thats enough to validate with just replaceing our final sft trianed phase1
107
+ model and get results? we can use appropriate instance a100 even
108
+
109
+ ⏺ You've got the strategy right, and I was about to over-engineer it. Let me
110
+ separate the two things clearly, because they validate different components:
111
+
112
+ 1. Is 117/128 enough? Yes — don't re-run parity
113
+
114
+ The 115 → 117 across two independent boxes and two independent image builds,
115
+ both landing at the same left-win margin (ours 0.3516 vs on-chain 0.3281), is
116
+ a solid validation of the judge. Every one of the ~11–13 mismatches is
117
+ documented as temp-0 GPU-logit boundary noise (S1 angle penalty off by 1–2 pts
118
+ crossing the |diff|≥2.0 line; S2 checklist nondeterminism) — on-chain itself
119
+ would flip those stems on a re-run. A third parity pass would just re-draw
120
+ from the same ~112–118 distribution and teach us nothing new.
121
+
122
+ So: the judge is proven faithful. That's banked. And re-pushing the Docker
123
+ image is moot unless we change it — it's already durable on Hub at the
124
+ recorded digest. No need to re-upload an identical 24 GB.
125
+
126
+ 2. But "replacing our model and get results" isn't a dir swap
127
+
128
+ Here's the important mechanical point. The parity benchmark judged leader/
129
+ (left) vs generations/ (right) — and generations/ is pre-rendered PNGs +
130
+ embeddings.npz, not code. It's miner 5E2's output artifacts. To score our
131
+ phase-1 SFT model we have to actually produce those artifacts from our model
132
+ first:
133
+
134
+ 1. Sample our SFT model on the 128 round-30 prompts → Three.js code
135
+ 2. Render each with render-service-js (CPU) → 8 white + 4 gray + grid +
136
+ embeddings.npz into generations_ours/<stem>/
137
+ 3. Judge leader (left) vs generations_ours (right) with the validated Thunder
138
+ judge — same seed 3964015748, base64 local transport, --custom-model for any
139
+ missing npz
140
+
141
+ The output is exactly what you want: how often our model beats the round-30
142
+ leader head-to-head under the on-chain-faithful judge. Win >50% of 128 and we
143
+ have real evidence we'd place at/above the leader.
144
+
145
+ The good news: steps 2–3 are code we already have (exact_eval/produce.py
146
+ renders; the Thunder judge is up-able from Hub). The only new piece is step 1
147
+ wired to the round-30 prompt set.
148
+
149
+ 3. Instance choice
150
+
151
+ - Judge: the A6000 is already sufficient — that's literally the parity box. An
152
+ A100/H200 only buys marginally-closer bit-exact S1 logits (on-chain is
153
+ ~H200-class). For a relative "do we beat the leader" verdict, A6000 is fine.
154
+ Only go H200-class if you want the absolute score free of boundary noise.
155
+ - Generation: I'd use the Tinker managed sampler (no GPU) — reuse the proven
156
+ exact_eval sampling path against our published adapter. That keeps gen cheap
157
+ (per-token) and avoids standing up a second 27B GPU. An A100 could do both gen
158
+ + judge on one box, but sequentially, and it's more moving parts.
159
+
160
+ So my recommendation: Tinker sampler for gen + A6000 (Hub image) for judge,
161
+ output generations_ours/ → duel vs leader.
162
+
163
+ One decision drives what I build next:
164
+
165
+ ⏺ User answered Claude's questions:
166
+ ⎿  · How should we generate our SFT model's round-30 outputs (step 1)? →
167
+ Tinker sampler (Recommended)
168
+ · What's the comparison bar for scoring our model? → Vs round-30 leader
169
+ (Recommended)
170
+
171
+ ⏺ Good — Tinker sampler for gen, dueling vs the round-30 leader. Before I write
172
+ anything, I need to nail down the exact data flow so generations_ours/ matches
173
+ what the judge expects. Let me investigate the key pieces in parallel.
174
+
175
+ Ran 2 shell commands (ctrl+o to expand)
176
+
177
+ ⏺ The artifact schema is clear: each stem dir = white/ (8) + gray/ (4) +
178
+ grid.png + embeddings.npz, and judge-round --left-local-dir leader
179
+ --right-local-dir <ours> does the duel. Now the critical piece — how our model
180
+ turns a prompt image into JS. Let me read the sampling glue in
181
+ exact_eval/run.py and the renderer.
182
+
183
+ Read 1 file (ctrl+o to expand)
184
+
185
+ ⏺ The sampling glue (sample_js, image→JS multimodal) and renderer
186
+ (produce_generation) already exist and are proven. So the only new code is a
187
+ bridge: generate+render our SFT model's output for the 128 round-30 prompts →
188
+ generations_ours/, then judge leader (left) vs generations_ours (right) on the
189
+ validated Thunder box.
190
+
191
+ Let me verify the two unknowns before writing: (a) how judge-round handles
192
+ local dirs + missing embeddings (our renders won't have DINOv3 npz), and (b)
193
+ that the final SFT state checkpoint is still live on Tinker.
194
+
195
+ Read 1 file, ran 2 shell commands (ctrl+o to expand)
196
+ ⏺ The wiring is perfect — everything reuses proven code. judge-round
197
+ --prompt-file prompts_all.txt --left-local-dir leader --right-local-dir
198
+ generations_ours --custom-model will duel leader (left) vs our renders
199
+ (right), generating the missing DINOv3 embeddings for our side in-process
200
+ (Tooony133 ungated fork) — same as the validated parity run. And per HANDOFF a
201
+ full 128-duel run is ~45 min, not hours (self-hosted vLLM is fast).
202
+
203
+ So the only new piece is a bridge: generate (Tinker sampler, image→JS) +
204
+ render (render-service-js, CPU) our final SFT output for the 128 round-30
205
+ prompts → generations_ours/. Let me set up tasks and verify the two
206
+ prerequisites: the final SFT state checkpoint is live, and the render service
207
+ runs.
208
+
209
+ Ran 1 shell command (ctrl+o to expand)
210
+
211
+ ⏺ Render server path was a guess — let me find the actual validator repo +
212
+ render service location, and verify the final SFT checkpoint is live on
213
+ Tinker.
214
+
215
+ Ran 2 shell commands (ctrl+o to expand)
216
+
217
+ ⏺ Final SFT state is live — generation works. But I need to locate the render
218
+ service and judge module (my path guesses missed). Let me find them.
219
+
220
+ Ran 1 shell command (ctrl+o to expand)
221
+
222
+ ⏺ There's a nested 404-agent/404-gen-subnet/ (what exact_eval uses). Let me
223
+ confirm the render service is runnable there.
224
+
225
+ Ran 1 shell command (ctrl+o to expand)
226
+
227
+ ⏺ All prerequisites confirmed. The one thing I must replicate exactly is the SFT
228
+ prompt template (system/user text around the image) — otherwise our model is
229
+ sampled off-distribution. Let me read that.
230
+
231
+ Ran 2 shell commands (ctrl+o to expand)
232
+
233
+ ⏺ Everything's confirmed and the design is locked. The SFT prompt template is a
234
+ constant raw format (single distinct system + user text), so I can reuse
235
+ sample_js verbatim by constructing a row with the round-30 prompt image.
236
+ Here's the plan:
237
+
238
+ Pipeline (reuses proven code): for each of 128 round-30 prompts → download
239
+ prompt PNG → Tinker-sample final SFT (step319, image→JS, greedy) → render via
240
+ render-service-js (CPU) → generations_ours/<stem>/{white,gray,grid}. Then
241
+ judge leader (left) vs generations_ours (right) on the validated Thunder A6000
242
+ (--custom-model fills our DINOv3 embeddings), same seed 3964015748. Tally =
243
+ how often our model beats the round-30 leader.
244
+
245
+ Let me set up tracking and write the bridge.
246
+
247
+ ⏺ Now let me read produce.py to call the renderer correctly, then write the
248
+ bridge.
249
+
250
+ Read 1 file (ctrl+o to expand)
251
+
252
+ ⏺ Now I'll write the bridge script, reusing make_sampler/sample_js (from run.py)
253
+ and produce_generation. It'll be resumable (skip already-rendered stems) so
254
+ the full 128 run can recover.
255
+
256
+ ⏺ Write(tinker/exact_eval/generate_ours.py)
257
+ ⎿  Wrote 217 lines to tinker/exact_eval/generate_ours.py
258
+ 1 #!/usr/bin/env python3
259
+ s prompt set.
260
+ 4 Bridges the trained Tinker checkpoint to the validator-faithful
261
+ judge harness
262
+ ile we:
263
+ 7 1. download the reference PNG (cached under <out>/_prompts/<st
264
+ 8 2. sample our SFT model (image -> Three.js module) via the Tin
265
+ ker sampler,
266
+ on,
267
+ nto the on-disk
268
+ … +266 lines (ctrl+o to expand)
269
+
270
+ ⏺ Now the smoke test on 2 stems — this is the key risk gate (does our SFT
271
+ produce renderable Three.js from these prompts?).
272
+
273
+ Ran 1 shell command (ctrl+o to expand)
274
+
275
+ ⏺ The Bash tool's own 2-min limit killed it (not the work). Sampler export +
276
+ sampling takes longer — let me run it in the background with a log.
277
+
278
+ Ran 2 shell commands (ctrl+o to expand)
279
+ ⏺ Task #1 is done. Let me monitor the smoke run for completion or failure.
280
+
281
+ ⏺ Monitor(smoke gen: OK/DONE/fail on 2 stems)
282
+ ⎿  Monitor started · task boflf210y · timeout 900s
283
+
284
+ ⏺ The smoke run is in progress (sampler export + 2 samples + render). I'll wait
285
+ for the monitor. Meanwhile, let me line up the Thunder judge step so it's
286
+ ready to fire once generation is validated — checking current Thunder instance
287
+ state.
288
+
289
+ Ran 1 shell command (ctrl+o to expand)
290
+
291
+ ⏺ The API path guess was wrong. Let me read thunder_client.py to get the correct
292
+ endpoints and how start-judge-thunder works.
293
+
294
+ Read 1 file (ctrl+o to expand)
295
+
296
+ ⏺ Correct endpoint is instances/list. Let me check current instances — the
297
+ parity box j8o4kxb2 may still be alive and reusable.
298
+
299
+ Ran 1 shell command (ctrl+o to expand)
300
+
301
+ ⏺ No instances alive — I'll stand up a fresh A6000 from the Hub image (runbook
302
+ §0). Let me read start-judge-thunder to prepare the exact standup, while the
303
+ smoke gen finishes.
304
+
305
+ Read 1 file, ran 1 shell command (ctrl+o to expand)
306
+
307
+ ⏺ Stock start-judge-thunder deploys unpatched vLLM with compile OFF — not the
308
+ validated config. For faithful parity I'll create the box via the API directly
309
+ and SSH-deploy the Hub image (judgebase:patched, compile ON) per runbook §0.
310
+ I'll prepare that once generation validates.
311
+
312
+ Let me peek at the smoke log's current progress.
313
+
314
+ Ran 1 shell command (ctrl+o to expand)
315
+
316
+ ⏺ Progressing well — sampler is exporting, render service is up. The Tinker
317
+ sampler export takes a few minutes. The monitor will notify on the first
318
+ OK/DONE/failure. I'll wait for it rather than poll.
319
+
320
+ Read 1 file, ran 1 shell command (ctrl+o to expand)
321
+
322
+ ⏺ I have the exact validated serve config now (compile ON, no
323
+ --compilation-config, Thunder's --device nvidia.com/gpu=all flag). I'm ready
324
+ to script the box standup the moment generation validates.
325
+
326
+ Current status: the smoke gen is running — sampler exported, render service
327
+ up, now sampling + rendering the 2 test stems. The critical question it
328
+ answers is whether our SFT model produces valid renderable Three.js from the
329
+ round-30 prompt images. I'll wait for the monitor to report the first render
330
+ outcome before spending anything on a GPU box (no point idling a judge box
331
+ while generation runs, and no point at all if the smoke reveals a problem).
332
+
333
+ Read 1 file (ctrl+o to expand)
334
+
335
+ ⏺ Still exporting the sampler on Tinker (this is the slow part — a few minutes).
336
+ I'll let the monitor notify me when the first stem renders or fails. Standing
337
+ by.
338
+
339
+ ✻ Cooked for 11m 17s
340
+
341
+ ⏺ Monitor event: "smoke gen: OK/DONE/fail on 2 stems"
342
+
343
+ ⏺ Monitor "smoke gen: OK/DONE/fail on 2 stems" stream ended
344
+
345
+ ⏺ Smoke result: 1 OK, 1 render-fail. The good news — our SFT model produces
346
+ valid, renderable Three.js (stem 00aef17d rendered cleanly, 19KB module). The
347
+ render-fail on stem 2 could be a genuine bad-code loss (correct competitive
348
+ semantic) or a transient render issue worth recovering. Let me diagnose both.
349
+
350
+ Ran 1 shell command (ctrl+o to expand)
351
+
352
+ ⏺ OK stem has perfect schema (8 white, 4 gray, grid). The fail is "static
353
+ analysis failed" — the render service's real validator gate rejected the code.
354
+ That's a legitimate competitive loss if the code is genuinely bad, but a
355
+ fixable artifact if our model wraps output in markdown fences or adds prose.
356
+ Let me check the raw output format of both.
357
+
358
+ Ran 1 shell command (ctrl+o to expand)
359
+ ⏺ Both are clean JS — no fences, no prose, proper export default function
360
+ generate(THREE). So the static-analysis rejection is something specific in the
361
+ code body, not a formatting artifact. Before committing to the full 128-gen,
362
+ let me understand what the static analyzer rejects, so I know if it's a
363
+ one-off or systematic.
364
+
365
+ Ran 1 shell command (ctrl+o to expand)
366
+
367
+ ⏺ Both outputs are clean JS; the rejection is a specific THREE API/identifier
368
+ the allowlist forbids — a real (if recoverable) competitive loss, not a
369
+ formatting bug. With n=2, one failure tells us little. The decisive move is to
370
+ run the full 128 and measure the actual render-pass rate — that's the real
371
+ signal. It's resumable (skips the completed stem) and I'll watch the pass rate
372
+ live. Let me launch it and diagnose the single failure in parallel.
373
+
374
+ Ran 1 shell command (ctrl+o to expand)
375
+
376
+ ⏺ Full 128-gen launched. Now let me diagnose the single static-analysis failure
377
+ while it runs — I'll invoke the validator directly on the fail module to get
378
+ the exact rejection reason.
379
+
380
+ Ran 1 shell command (ctrl+o to expand)
381
+
382
+ ⏺ staticValidate(source) returns the failure reasons. Let me run it on the fail
383
+ module.
384
+
385
+ Ran 1 shell command (ctrl+o to expand)
386
+
387
+ ⏺ The failure is FORBIDDEN_IDENTIFIER: Math.random — our model emitted
388
+ randomness, which the validator hard-forbids (procedural gen must be
389
+ deterministic). That's a legitimate on-chain loss, not a fixable artifact — a
390
+ miner submitting this would lose the stem regardless of visual quality.
391
+ Importantly, the render-pass rate is itself a key competitive metric
392
+ (valid-submission rate), so the full run will quantify how often our model
393
+ self-disqualifies this way.
394
+
395
+ I don't want to spend on a judge box until I see the pass-rate trend is
396
+ healthy. Let me set an early checkpoint at ~30 stems, plus a completion/crash
397
+ watch.
398
+
399
+ Ran 1 shell command (ctrl+o to expand)
400
+
401
+ ⏺ Full generation is running (127 stems remaining after the smoke). I've set an
402
+ early checkpoint that'll report the pass-rate trend at ~30 stems — that's my
403
+ go/no-go gate before spending on a judge box.
404
+
405
+ Status so far:
406
+ - ✅ Bridge script works: our final SFT (step319) generates clean Three.js
407
+ from round-30 prompt images, renders to the exact judge layout (8 white + 4
408
+ gray + grid).
409
+ - ✅ Judge is already validated (117/128 parity, banked — no re-run needed).
410
+ - ⏳ Full 128-gen in progress (~90 min). One early finding: the render-pass
411
+ rate is itself a competitive signal — the one smoke failure was Math.random (a
412
+ validator-forbidden identifier = automatic on-chain loss). The full run
413
+ quantifies how often our model self-disqualifies this way.
414
+
415
+ Once I see a healthy pass-rate at the ~30-stem checkpoint, I'll stand up the
416
+ A6000 judge from the Hub image to overlap the remaining generation, then run
417
+ the 128-duel leader vs ours and tally. I'll report the checkpoint numbers when
418
+ they land.
419
+
420
+ ✻ Sautéed for 2m 27s
421
+
422
+ ⏺ Background command "Wait for ~30-stem checkpoint on full gen" completed (exit
423
+ code 0)
424
+
425
+ Read 1 file (ctrl+o to expand)
426
+
427
+ ⏺ Full gen crashed immediately — render service died with EADDRINUSE on port
428
+ 3000 (the render service's internal static server). The smoke run left a
429
+ straggler holding port 3000. Let me find and kill it, then relaunch.
430
+
431
+ Ran 1 shell command (ctrl+o to expand)
432
+
433
+ ⏺ Found it: node PID 87475 — the smoke run's render service leaked (its child
434
+ outlived the parent) and is holding port 3000 (the render service's hardcoded
435
+ internal static-server port). Two render services can't coexist. Let me kill
436
+ it and relaunch the full gen (resumable — it'll skip the completed stem).
437
+
438
+ Ran 1 shell command (ctrl+o to expand)
439
+
440
+ ⏺ Port 3000 free. Relaunching the full gen.
441
+
442
+ Ran 2 shell commands (ctrl+o to expand)
443
+
444
+ ⏺ I'll wait for the startup confirmation. Once the render service is up and
445
+ stems start flowing, I'll set the ~30-stem checkpoint again to read the
446
+ pass-rate trend before committing to a judge box.
447
+
448
+ ✻ Cooked for 44s
449
+
450
+ ⏺ Background command "Confirm relaunched gen gets past startup" completed (exit
451
+ code 0)
452
+
453
+ Read 1 file (ctrl+o to expand)
454
+
455
+ ⏺ Render service up, sampler exporting. Let me arm the ~30-stem checkpoint
456
+ (go/no-go for the judge box) plus catch any crash.
457
+ Ran 1 shell command (ctrl+o to expand)
458
+
459
+ ⏺ Generation running cleanly now. I'll wait for the ~30-stem checkpoint to read
460
+ the render-pass rate — that's my gate before spending on the judge box.
461
+ Standing by for that notification.
462
+
463
+ ✻ Cooked for 16s
464
+
465
+ ⏺ Background command "Wait for ~30-stem pass-rate checkpoint" completed (exit
466
+ code 0)
467
+
468
+ Read 1 file (ctrl+o to expand)
469
+
470
+ ⏺ ~30-stem checkpoint: 23 OK / 6 render-fail / 1 skip → ~79% valid-submission
471
+ rate. That's healthy enough to proceed — the ~21% failures are legitimate
472
+ on-chain auto-losses (forbidden identifiers like Math.random, or non-rendering
473
+ code), and they'll correctly count as losses in the duel. The benchmark is
474
+ valid.
475
+
476
+ Generation will run ~80 more min. Box standup (create + 24GB pull + compile)
477
+ is the long, error-prone pole, so I'll start it now to overlap and leave
478
+ buffer to debug. Let me first capture the current failure reasons
479
+ (informative), then create the A6000.
480
+
481
+ Ran 1 shell command (ctrl+o to expand)
482
+
483
+ ⏺ Those per-stem reasons are unreliable mid-run (some "missing grid.png" stems
484
+ are just in-flight, being rendered concurrently) — I'll do a clean failure
485
+ analysis after gen completes. The authoritative count is the 6 explicit
486
+ RENDER-FAILs. One was a syntax error ("Unexpected token"), another Math.random
487
+ — the expected legit-failure modes.
488
+
489
+ Now the priority: create the A6000 judge box. Let me create the instance via
490
+ the Thunder API.
491
+
492
+ Ran 1 shell command (ctrl+o to expand)
493
+
494
+ ⏺ Box is up: u9wrto9j at 216.81.200.241:31323, endpoint
495
+ https://u9wrto9j-8000.thundercompute.net. Let me verify SSH + docker + GPU,
496
+ then log in to Docker Hub and start the 24GB image pull.
497
+
498
+ Ran 2 shell commands (ctrl+o to expand)
499
+
500
+ ⏺ SSH/docker/GPU/disk all good (A6000 49GB, 150G free). Now log in to Docker Hub
501
+ (PAT via stdin) and kick off the 24GB pull detached (per runbook — SSH drop
502
+ would kill a foreground pull).
503
+
504
+ Ran 1 shell command (ctrl+o to expand)
505
+
506
+ ⏺ Login succeeded, 24GB pull running detached. Meanwhile generation continues on
507
+ the Mac. Let me arm a background watcher for the pull completion (~10-15 min)
508
+ — polling the remote pull log.
509
+
510
+ Ran 1 shell command (ctrl+o to expand)
511
+
512
+ ⏺ Two things now running in parallel, both watched:
513
+ - Generation (Mac): ~79% pass rate at 30 stems, ~80 min to finish all 128.
514
+ - Judge box (u9wrto9j, A6000): 24GB Hub image pulling (~10-15 min), then I'll
515
+ start vLLM with compile ON.
516
+
517
+ I'll get notified as each completes. Let me also arm the full-generation
518
+ completion watch so I know when generations_ours/ is ready.
519
+
520
+ Ran 1 shell command (ctrl+o to expand)
521
+
522
+ ⏺ Both watchers armed. Here's where things stand:
523
+
524
+ In flight (both monitored):
525
+
526
+ ┌──────────────────────┬──────────────────────┬───────────────────────────┐
527
+ │ Track │ State │ ETA │
528
+ ├──────────────────────┼──────────────────────┼──────────��────────────────┤
529
+ │ Generation (Mac) │ 128 stems, ~79% │ ~80 min │
530
+ │ │ valid so far │ │
531
+ ├──────────────────────┼──────────────────────┼───────────────────────────┤
532
+ │ Judge box u9wrto9j │ 24GB image pulling │ ~10-15 min, then vLLM │
533
+ │ (A6000) │ │ compile ~1 min │
534
+ └──────────────────────┴──────────────────────┴───────────────────────────┘
535
+
536
+ When the image pull finishes, I'll launch vLLM (compile ON, exact validated
537
+ serve args) and wait for /health. When generation finishes, I'll have a
538
+ complete generations_ours/ with a measured valid-submission rate. Once both
539
+ are ready, I run the 128-duel leader vs ours and tally our win rate. I'll
540
+ report as milestones land.
541
+
542
+ ✻ Worked for 2m 18s
543
+
544
+ ⏺ Background command "Wait for Docker image pull completion" was stopped
545
+
546
+ ⏺ Background command "Wait for full generation completion" was stopped
547
+
548
+ ⏺ Both watchers were stopped (not by me — likely a session reset). Let me check
549
+ the actual state of both directly and re-arm.
550
+
551
+ Ran 1 shell command (ctrl+o to expand)
552
+
553
+ ⏺ Gen healthy (38/128, 31 OK / 6 fail, still ~84%). Pull still in progress
554
+ (image not yet materialized). Let me check pull progress and re-arm both
555
+ watchers.
556
+
557
+ Ran 1 shell command (ctrl+o to expand)
558
+
559
+ ⏺ Pull is nearly complete — 26 of ~27 layers done, final (big model) layer
560
+ verifying/extracting. Let me re-arm both watchers.
561
+
562
+ Ran 2 shell commands (ctrl+o to expand)
563
+ ⏺ Both watchers re-armed. The image pull is essentially done (final layer
564
+ extracting); I'll launch vLLM the moment it materializes. Generation continues
565
+ healthily. Waiting on the pull-complete notification to start the judge
566
+ server.
567
+
568
+ ✻ Cogitated for 51s
569
+
570
+ ❯ /fork I think we are missing the point that the harness needs to be there like from the past winners /Users/xavier/bittensor/404-gen-subnet/404-agent/past-winner right? there is a new winner of round 30 which is same silent-daemon repo so should we also try replacing the model there and getting generations which would also mean thata we need to use the saMe hardware 4xh200 right which is too expensive?
571
+ ⎿ ⑂ forked into a background session · ⑂ dig deeper into some bugs and fix it before we get a new ins ⑂ make sure all compiles and then continue to push to this rep ⑂ read /Users/xavier/bittensor/affine/affine-cortex-new/TINKER ⑂ read this conversation /Users/xavier/bittensor/404-gen-subne ⑂ HANDOFF.md THUNDER_JUDGE_IMAGE_RUNBOOK.md `compare_full.py C ⑂ I think we are missing the point that the harness needs to b
572
+ it is already working, with everything from this conversation up to now · nothing here changes
573
+ it edits this checkout in place — the same files you have open here, so mind overlapping work
574
+ to check on it: ← opens the agent view, or claude attach b1f3c2a5 in another terminal · its result lands there, not in this conversation
575
+
576
+ ❯ is it done? check the status
577
+
578
+ ⏺ Let me check the running jobs and look at the past-winner harness you're
579
+ pointing at.
580
+
581
+ Ran 2 shell commands (ctrl+o to expand)
582
+
583
+ ⏺ Status: Gen at 62/128, 52 OK / 9 fail (~85% valid), running. Image fully
584
+ pulled (43.8 GB on box) — ready to serve. Now let me look at your real point —
585
+ the silent-daemon winner harness.
586
+
587
+ Ran 1 shell command (ctrl+o to expand)
588
+
589
+ ⏺ This is a genuinely important catch. The README reveals the real winning flow,
590
+ and it changes how to read our benchmark. Before I answer fully, two things
591
+ in parallel: the image is fully pulled so let me start the judge vLLM now
592
+ (stop wasting the idle box), and read silent-daemon's actual
593
+ ensemble/selection config.
594
+
595
+ Ran 2 shell commands (ctrl+o to expand)
596
+
597
+ ⏺ The judge start failed on a zsh quoting quirk (unquoted var isn't word-split
598
+ in zsh, so -i swallowed everything). Let me redo with literal flags.
599
+
600
+ Ran 1 shell command (ctrl+o to expand)
601
+
602
+ ⏺ The docker run -d returns fast normally — the SSH likely hung on connection.
603
+ Let me verify the container is actually up with a fresh quick check.
604
+
605
+ Ran 1 shell command (ctrl+o to expand)
606
+
607
+ ⏺ No container was created. Let me read the backgrounded start command's output
608
+ to see what happened.
609
+
610
+ Read 1 file (ctrl+o to expand)
611
+
612
+ ⏺ SSH hung with no output — the container was never created (likely the nested
613
+ quoting over SSH). Let me avoid quoting hell: write the run script to a file,
614
+ copy it to the box, and execute it.
615
+
616
+ Ran 1 shell command (ctrl+o to expand)
617
+
618
+ ⏺ The earlier "hung" run actually did create a container (there was a race). Let
619
+ me clean-slate it and start exactly one, with a verify.
620
+
621
+ Ran 1 shell command (ctrl+o to expand)
622
+
623
+ ⏺ Clean slate confirmed (no containers). Now start exactly one, via the script.
624
+
625
+ Ran 1 shell command (ctrl+o to expand)
626
+
627
+ ⏺ The container c4e947f6 persists (the empty ps -a was a race). Let me inspect
628
+ why it's there — get its logs and state before removing, since if vLLM is
629
+ crash-looping that's the real signal.
630
+
631
+ Ran 1 shell command (ctrl+o to expand)
632
+
633
+ ⏺ The container is flapping (exists/gone) — classic sign it's crash-looping
634
+ under --restart unless-stopped, exiting instantly (likely the vLLM command
635
+ never runs). Let me kill any stale local SSH, nuke everything on the box, and
636
+ start without --restart so a crash stays exited and I can read the error.
637
+
638
+ Ran 1 shell command (ctrl+o to expand)
639
+
640
+ ⏺ Background command "Wait for image to materialize on box" failed with exit
641
+ code 144
642
+ ⏺ Background command "Start judge vLLM with literal ssh flags" failed with exit
643
+ code 144
644
+
645
+ ⏺ The mystery is solved: PID 2783 was the original --restart unless-stopped
646
+ start command whose SSH stayed connected — it kept resurrecting the container.
647
+ My pkill cleared all stale local SSH (the failed exit-144 notifications
648
+ confirm). Now let me verify a clean state and start the judge fresh.
649
+
650
+ Ran 1 shell command (ctrl+o to expand)
651
+
652
+ ⏺ The pgrep matched its own command line. Let me directly query the box state
653
+ cleanly.
654
+
655
+ Ran 1 shell command (ctrl+o to expand)
656
+
657
+ ⏺ Box is clean (no containers). Now start the judge fresh via the no-restart
658
+ script.
659
+
660
+ Ran 1 shell command (ctrl+o to expand)
661
+
662
+ ⏺ Something on the box is still recreating containers (a new id 6f8a18fe,
663
+ despite a clean check moments before) — a stale remote process survived the
664
+ local SSH kill. Let me hunt it down on the box.
665
+
666
+ Ran 1 shell command (ctrl+o to expand)
667
+ ⎿  Interrupted · What should Claude do instead?
668
+
669
+ ❯ you can do tnr delete 0 and restart as well but make sure you read the docs
670
+ of previous work ```[Pasted text #1 +4 lines]```
671
+
672
+ ⏺ Understood — and I see my likely error. I deployed with --device
673
+ nvidia.com/gpu=all (from commit.py), but the runbook §0's proven command uses
674
+ --gpus all with a bash -c entrypoint. On a fresh box without CDI configured,
675
+ the CDI device flag makes the container fail instantly → crash-loop under
676
+ --restart unless-stopped. That's the flapping.
677
+
678
+ Rather than re-pull 24GB on a new instance, let me first confirm the crash
679
+ cause and salvage this box: disable the restart loop, read the actual crash
680
+ log, then redeploy with the runbook-exact command.
681
+
682
+ Ran 1 shell command (ctrl+o to expand)
683
+
684
+ ⏺ Box is clean now (the loop stopped once I killed the stale SSH). Let me deploy
685
+ the runbook-exact command — --gpus all, bash -c, no --restart — and
686
+ immediately check whether it stays up or exits.
687
+
688
+ Ran 1 shell command (ctrl+o to expand)
689
+
690
+ ⏺ That's the real answer: Thunder requires --device nvidia.com/gpu=all and
691
+ rejects --gpus all. So my original flag was right for Thunder — the runbook
692
+ §0's --gpus all predates this Thunder change. The crash-loop had a different
693
+ cause. Let me redeploy with the correct CDI flag, no restart, wait through the
694
+ compile window, and actually read the crash log this time.
695
+
696
+ Ran 1 shell command (ctrl+o to expand)
697
+
698
+ ⏺ No output (SSH likely timed out on the compile). Let me check the container
699
+ state and logs directly.
700
+
701
+ Ran 1 shell command (ctrl+o to expand)
702
+
703
+ ⏺ I've spent too many cycles fighting this box's flaky SSH and wedged docker
704
+ state. Let me take your offered clean path — tnr delete 0 and recreate fresh.
705
+ First, verify tnr and current state.
706
+
707
+ Ran 1 shell command (ctrl+o to expand)
708
+
709
+ ⏺ Confirmed: the box's docker daemon is wedged — docker ps -a shows empty yet
710
+ docker run conflicts on an existing container ce394dd2. That inconsistency is
711
+ an unrecoverable daemon state (fallout from the --restart flapping + fastvfs).
712
+ Your call is right — nuke it. Deleting instance 0 and recreating fresh.
713
+
714
+ Ran 1 shell command (ctrl+o to expand)
715
+
716
+ ⏺ tnr delete needs -y for non-interactive. Let me delete with confirmation
717
+ skipped.
718
+
719
+ Ran 1 shell command (ctrl+o to expand)
720
+
721
+ ⏺ Deleted. Now recreate a fresh A6000 and check on generation (which runs
722
+ independently on the Mac).
723
+
724
+ Ran 1 shell command (ctrl+o to expand)
725
+
726
+ ❯ why not use the 404-cli commands is that wrong to use? given that we have
727
+ finished the tinker sampling for the roun30 with out trained final model
728
+ right?
729
+ ⏺ You're right on both counts — let me correct course.
730
+
731
+ On using 404-cli: it's not wrong — it's the right path, and I over-engineered
732
+ by going around it. start-judge-thunder creates the instance, deploys the
733
+ judge over SSH, forwards the port, and health-checks it — all in one tested
734
+ command with retries. I went manual only to use the Hub judgebase:patched
735
+ image (model baked in + compile ON, matching the exact 117/128 parity config).
736
+ That detour is what dragged me into the SSH flakiness and the wedged docker
737
+ daemon. Not worth it.
738
+
739
+ The one tradeoff to know: start-judge-thunder deploys the stock
740
+ vllm/vllm-openai:v0.20.0 with --compilation-config {"mode":0} (compile OFF)
741
+ and downloads the GLM model fresh (~15-25 min). The parity run was compile ON.
742
+ But for our purpose — ranking our renders vs the leader's — compile on/off
743
+ doesn't change the judge's verdicts (same model weights; the only differences
744
+ the HANDOFF documented were sub-point S1 numeric jitter at boundaries). So
745
+ stock + compile-OFF is a perfectly valid, far more robust judge for this
746
+ comparison. Let me use it.
747
+
748
+ Let me confirm generation is actually finished before spending on the judge
749
+ box.
750
+
751
+ Ran 1 shell command (ctrl+o to expand)
752
+ ⎿  Interrupted · What should Claude do instead?
753
+
754
+ ❯ yes proceed and use the two docs as reference
755
+ '/Users/xavier/bittensor/404-gen-subnet/404-agent/THUNDER_JUDGE_IMAGE_RUNBOOK
756
+ .md''/Users/xavier/bittensor/404-gen-subnet/404-agent/HANDOFF.md' closely. so
757
+ we need to be able to use judgebase:patched so take the decision
758
+ accordingly as we will only use the 117 proven method
759
+
760
+ ⏺ Clear decision: judgebase:patched, the 117-proven method (compile ON, patched
761
+ image) — following the two docs closely. Generation is still running (65/128,
762
+ healthy) and will finish on its own in parallel.
763
+
764
+ I'll redo the box the right way this time, avoiding my earlier mistakes:
765
+ - --device nvidia.com/gpu=all (Thunder's required flag — the runbook's --gpus
766
+ all is stale; the box itself rejected it and commit.py confirms the CDI flag)
767
+ - NO --restart (that policy caused the flapping/resurrection that wedged the
768
+ daemon)
769
+ - deploy via an scp'd script (no SSH quoting issues), on a fresh clean-daemon
770
+ box
771
+
772
+ Let me create the fresh instance.
773
+
774
+ Ran 1 shell command (ctrl+o to expand)
775
+
776
+ ⏺ Fresh box: pi0k9k53 at 216.81.200.241:32390, endpoint
777
+ https://pi0k9k53-8000.thundercompute.net. Now Docker Hub login + start the
778
+ 24GB pull detached.
779
+
780
+ Ran 1 shell command (ctrl+o to expand)
781
+
782
+ ⏺ Login OK, 24GB pull running. Let me stage the deploy script + the patch file
783
+ on the box now (ready for when the pull finishes), and arm the pull-completion
784
+ watcher.
785
+
786
+ Ran 2 shell commands (ctrl+o to expand)
787
+
788
+ ⏺ Pull watcher armed. Let me re-arm the generation-completion watcher (killed in
789
+ the earlier session reset).
790
+
791
+ Ran 1 shell command (ctrl+o to expand)
792
+
793
+ ⏺ Both watchers armed on the fresh box. Current state:
794
+
795
+ ┌─────────────────────────┬──────────────────────────────────────┬────────┐
796
+ │ Track │ State │ ETA │
797
+ ├─────────────────────────┼──────────────────────────────────────┼────────┤
798
+ │ Generation (Mac) │ 65/128 done, 64 OK / 10 fail (~86% │ ~55 │
799
+ │ │ valid) │ min │
800
+ ├─────────────────────────┼──────────────────────────────────────┼────────┤
801
+ │ Judge box pi0k9k53 │ 24GB judgebase:patched pulling │ ~15 │
802
+ │ (A6000) │ │ min │
803
+ └─────────────────────────┴──────────────────────────────────────┴────────┘
804
+
805
+ When the pull finishes I'll deploy the 117-proven config (judgebase:patched,
806
+ compile ON, --device nvidia.com/gpu=all, no restart policy) via the staged
807
+ script and watch the vLLM logs for VLLM_COMPILE:3 + torch.compile took ~50s +
808
+ /health 200. patch_final.py is staged on the box in case the baked fastvfs
809
+ patch needs re-applying on compile. I'll report when the judge is live.
810
+
811
+ ✻ Baked for 2m 15s
812
+
813
+ ⏺ Background command "Wait for image pull on fresh box" completed (exit code 0)
814
+
815
+ Read 1 file (ctrl+o to expand)
816
+
817
+ ⏺ Image pulled (43.8 GB). Now deploy the 117-proven judge via the staged script
818
+ and check it stays up.
819
+
820
+ Ran 1 shell command (ctrl+o to expand)
821
+
822
+ ⏺ Let me check the container state directly (SSH output was empty again — likely
823
+ just dropped).
824
+
825
+ Ran 1 shell command (ctrl+o to expand)
826
+
827
+ ⏺ Let me capture the deploy output to a file on the box (decoupling from the
828
+ flaky SSH stdout), then read it.
829
+
830
+ Ran 1 shell command (ctrl+o to expand)
831
+
832
+ ⏺ The container 25a3e120 does exist — it's just invisible to docker ps -a (a
833
+ Thunder/fastvfs quirk) and unremovable by name. Crucially, it was created by
834
+ my first "no-output" deploy — it may already be the judge, compiling. Let me
835
+ inspect it by ID.
836
+
837
+ Ran 1 shell command (ctrl+o to expand)
838
+
839
+ ⏺ The container is a ghost — the name registry holds it but inspect/logs/ps -a
840
+ can't find it. That's a fastvfs metadata inconsistency, and both boxes showed
841
+ it. Possibly a container is actually running vLLM while the metadata queries
842
+ fail. Let me check what actually matters: is anything serving on port 8000?
843
+
844
+ Ran 1 shell command (ctrl+o to expand)
845
+
846
+ ⏺ No running container, nothing on 8000 — the ghost 25a3e120 is a dead
847
+ name-registry entry blocking docker run --name 404-judge, so vLLM never
848
+ launches. The clean fix is to restart the docker daemon (clears the corrupted
849
+ registry), then deploy fresh.
850
+
851
+ Ran 1 shell command (ctrl+o to expand)
852
+ ⏺ No systemd on Thunder (can't restart docker that way), but ps -a is now clean
853
+ and the ghost name cleared. Let me deploy with a fresh container name
854
+ (sidestepping any stuck 404-judge entry) and the runbook's bash -c form,
855
+ capturing the container ID to confirm it truly starts.
856
+
857
+ Ran 1 shell command (ctrl+o to expand)
858
+
859
+ ⏺ SSH stdout dropped again (recurring flakiness). The deploy ran and wrote
860
+ /tmp/deploy.log — let me read it in a separate call.
861
+
862
+ Ran 1 shell command (ctrl+o to expand)
863
+
864
+ ⏺ A simple cat returned nothing too — the box's SSH has gone unresponsive, which
865
+ often means vLLM is now compiling and saturating the box (a good sign). Let
866
+ me bypass SSH and poll the endpoint /health directly (through Thunder's
867
+ proxy).
868
+
869
+ Ran 1 shell command (ctrl+o to expand)
870
+
871
+ ⏺ Health is 404 — the Thunder proxy is up but nothing's serving on 8000, so vLLM
872
+ isn't running. And SSH keeps returning empty, which blocks diagnosis. Let me
873
+ test whether SSH works at all right now with a trivial command.
874
+
875
+ Ran 1 shell command (ctrl+o to expand)
876
+
877
+ ⏺ SSH works now and reveals a container 404-judge is "Up 3 minutes" (an earlier
878
+ "no-output" deploy actually succeeded), but box load is 0.00 and health is 404
879
+ — so vLLM inside either crashed or is stalled. Let me read its logs to see
880
+ the real state.
881
+
882
+ Ran 1 shell command (ctrl+o to expand)
883
+
884
+ ⏺ The judge was working the whole time. The "ghost" 25a3e120 = 404-judge is real
885
+ and actively loading the model — compile ON (VLLM_COMPILE:3, the 117 config),
886
+ safetensors 50% loaded. The fastvfs layer was just making inspect/logs
887
+ queries flake intermittently, and my rm -f couldn't remove a container that
888
+ was busy starting up. I was fighting a container that was coming up fine.
889
+
890
+ It needs ~4-5 more min (2 more shards on the slow OVERLAY fs + compile + graph
891
+ capture). Let me stop touching it and poll /health via HTTPS until 200.
892
+
893
+ Ran 1 shell command (ctrl+o to expand)
894
+
895
+ ⏺ Judge health poller armed. Both remaining tracks are now watched and I'll stop
896
+ touching the box so vLLM can finish:
897
+
898
+ ┌────────────────────────┬────────────────────────────────────────────────┐
899
+ │ Track │ State │
900
+ ├────────────────────────┼────────────────────────────────────────────────┤
901
+ │ Judge │ Model loading, compile ON (117 config) — ~4-5 │
902
+ │ pi0k9k53/404-judge │ min to /health 200 │
903
+ ├────────────────────────┼────────────────────────────────────────────────┤
904
+ │ Generation (Mac) │ ~65+/128, ~86% valid, finishing in parallel │
905
+ └────────────────────────┴────────────────────────────────────────────────┘
906
+
907
+ Key lesson from the thrash: the container was never actually broken —
908
+ Thunder's fastvfs makes docker inspect/logs/ps queries flake intermittently
909
+ (return "no such container" for a container that's really running), and rm -f
910
+ can't remove one that's mid-startup. So the "ghost/conflict" loop was me
911
+ fighting a judge that was coming up correctly all along. It's on the exact
912
+ 117-proven config now. I'll run the 128-duel leader vs generations_ours once
913
+ both are green.
914
+
915
+ ✻ Crunched for 8m 11s
916
+
917
+ ⏺ Background command "Poll judge health until 200" completed (exit code 0)
918
+
919
+ Read 1 file (ctrl+o to expand)
920
+
921
+ ⏺ Judge is live — /health 200, serving glm-4.6v-flash, compile ON (117 config).
922
+ Task 4 done. Let me check generation status.
923
+
924
+ Ran 1 shell command (ctrl+o to expand)
925
+
926
+ ⏺ Judge is healthy and idle-ready; generation is at 96/128 (~85% valid), ~30 min
927
+ left. The gen-completion watcher is armed. Let me verify the embeddings fork
928
+ and stage the exact judge-round command while I wait.
929
+
930
+ Ran 1 shell command (ctrl+o to expand)
931
+
932
+ ⏺ All prerequisites confirmed: embeddings fork
933
+ Tooony133/dinov3-vits16-pretrain-lvd1689m (via --custom-model), seed
934
+ 3964015748, judge healthy. 82 stems rendered so far.
935
+
936
+ I must wait for generation to fully complete before judging (any
937
+ not-yet-generated stem would be scored as a loss). The gen-completion watcher
938
+ is armed. Once it fires, I'll run:
939
+
940
+ judge-round --prompt-file prompts_all.txt --left-local-dir leader \
941
+ --right-local-dir generations_ours --seed 3964015748 \
942
+ --endpoint https://pi0k9k53-8000.thundercompute.net \
943
+ --output-dir logs/ours_vs_leader --concurrency 2 --custom-model
944
+
945
+ Holding for generation to finish (~30 min).
946
+
947
+ ✻ Crunched for 45s
948
+
949
+ ❯ check the progress now and if we not suign the instance can we delete it?
950
+ just make sure we edit the docs to include the fixes
951
+
952
+ ⏺ Let me check current progress on both tracks.
953
+
954
+ Ran 1 shell command (ctrl+o to expand)
955
+ ⏺ Gen is at 127/128 (last stem finishing now) — 107 OK / 19 fail (~85% valid).
956
+ Judge healthy (200).
957
+
958
+ On deleting the instance: not yet — we still need it for the 128-duel judge
959
+ run, which starts the moment gen finishes (any second). Deleting now would
960
+ throw away the whole setup. We delete right after the judge run completes.
961
+ It's idle for only a couple more minutes.
962
+
963
+ Let me edit the docs with the fixes I found while the last stem finishes.
964
+ First, re-reading the exact command lines to fix.
965
+
966
+ Ran 1 shell command (ctrl+o to expand)
967
+
968
+ ⏺ Let me fix the GPU flag in both docs and add a gotchas section documenting
969
+ today's fixes.
970
+
971
+ ⏺ Update(~/bittensor/404-gen-subnet/404-agent/HANDOFF.md)
972
+ ⎿  Added 1 line, removed 1 line
973
+ 62 sudo -n docker login -u manojbhat777 --password-stdin < ~/docke
974
+ rkey # or paste PAT
975
+ 63 sudo -n docker pull manojbhat777/judgebase:patched
976
+ 64 # Run with compile ON (no --compilation-config). Model already
977
+ in image → no re-download.
978
+ 65 -sudo -n docker run -d --gpus all --name 404-judge -p 8000:8000
979
+ -\
980
+ 65 +sudo -n docker run -d --device nvidia.com/gpu=all --name 404-ju
981
+ +dge -p 8000:8000 \
982
+ 66 manojbhat777/judgebase:patched \
983
+ 67 bash -c '/sbin/ldconfig && exec vllm serve zai-org/GLM-4.6V-F
984
+ lash \
985
+ 68 --revision 411bb4d77144a3f03accbf4b780f5acb8b7cde4e \
986
+
987
+ ⏺ Update(~/bittensor/404-gen-subnet/404-agent/THUNDER_JUDGE_IMAGE_RUNBOOK.md)
988
+ ⎿  Added 2 lines, removed 2 lines
989
+ 22 EOF
990
+ 23 sudo -n docker pull manojbhat777/judgebase:patched
991
+ 24 sudo -n docker rm -f 404-judge 2>/dev/null
992
+ 25 - sudo -n docker run -d --gpus all --name 404-judge -p 8000:800
993
+ -0 \
994
+ 25 + sudo -n docker run -d --device nvidia.com/gpu=all --name 404-
995
+ +judge -p 8000:8000 \
996
+ 26 manojbhat777/judgebase:patched \
997
+ 27 bash -c "/sbin/ldconfig && exec vllm serve zai-org/GLM-4.6V
998
+ -Flash \
999
+ 28 --revision 411bb4d77144a3f03accbf4b780f5acb8b7cde4e \
1000
+ ...
1001
+ 118
1002
+ 119 ```bash
1003
+ 120 sudo -n docker rm -f 404-judge
1004
+ 121 -sudo -n docker run -d --gpus all --name 404-judge -p 8000:8000
1005
+ - \
1006
+ 121 +sudo -n docker run -d --device nvidia.com/gpu=all --name 404-j
1007
+ +udge -p 8000:8000 \
1008
+ 122 judgebase:patched \
1009
+ 123 bash -c '/usr/bin/python3 /tmp/patch_final.py; /sbin/ldconfi
1010
+ g && exec vllm serve \
1011
+ 124 zai-org/GLM-4.6V-Flash \
1012
+
1013
+ ⏺ Now let me add a prominent fixes section to the runbook. Let me find the
1014
+ insertion point after the TL;DR.
1015
+
1016
+ Read 1 file (ctrl+o to expand)
1017
+
1018
+ ⏺ Update(~/bittensor/404-gen-subnet/404-agent/THUNDER_JUDGE_IMAGE_RUNBOOK.md)
1019
+ ⎿  Added 42 lines
1020
+ 52
1021
+ 53 ---
1022
+ 54
1023
+ 55 +## 0.5. MUST-READ fixes (verified 2026-08-02 on a fresh redeplo
1024
+ +y)
1025
+ 56 +
1026
+ 57 +A second, independent redeploy hit four traps not obvious from
1027
+ +the 2026-08-01 notes.
1028
+ 58 +All four cost real time; read before touching a box.
1029
+ 59 +
1030
+ 60 +1. **GPU flag: use `--device nvidia.com/gpu=all`, NOT `--gpus a
1031
+ +ll`.** Current Thunder
1032
+ 61 + docker *rejects* `--gpus all` outright: `Thunder Compute use
1033
+ +s a special version of
1034
+ 62 + docker. To add GPUs to a container, use --device nvidia.com/
1035
+ +gpu=all. Do not use
1036
+ 63 + --runtime=nvidia nor --gpus`. The 2026-08-01 `--gpus all` co
1037
+ +mmands above are stale and
1038
+ 64 + have been corrected in place. (`404-cli/commit.py` already u
1039
+ +ses the `--device` form.)
1040
+ 65 +
1041
+ 66 +2. **NEVER pass `--restart unless-stopped`.** If vLLM has any s
1042
+ +tartup hiccup the container
1043
+ 67 + exits and the daemon restarts it in a tight loop; combined w
1044
+ +ith the fastvfs metadata lag
1045
+ 68 + (below) this looks like a container that keeps "reappearing"
1046
+ + and cannot be removed, and
1047
+ 69 + it effectively wedges the name registry. Run with **no resta
1048
+ +rt policy** so a failed start
1049
+ 70 + stays exited and its logs are readable. (Re-run by hand if i
1050
+ +t dies.)
1051
+ 71 +
1052
+ 72 +3. **fastvfs makes docker metadata LIE — trust `/health`, not `
1053
+ +docker ps`.** On Thunder,
1054
+ 73 + `docker ps -a`, `docker inspect <id>`, and `docker logs <id>
1055
+ +` **intermittently return
1056
+ 74 + "No such container" for a container that is genuinely runnin
1057
+ +g**, and `docker rm -f
1058
+ 75 + <name>` cannot remove a container that is mid-startup (you t
1059
+ +hen get spurious
1060
+ 76 + `Conflict. The container name "/404-judge" is already in use
1061
+ +` on the next `run`). Do NOT
1062
+ 77 + interpret these as a broken container and start deleting/rec
1063
+ +reating — that is a rabbit
1064
+ 78 + hole. The container named `404-judge` created by the very fi
1065
+ +rst `docker run` is almost
1066
+ 79 + always the real, healthy one coming up. **Poll `https://<uui
1067
+ +d>-8000.thundercompute.net/health`
1068
+ 80 + (HTTPS via the Thunder proxy, independent of the flaky SSH+d
1069
+ +ocker path) until 200**;
1070
+ 81 + ignore transient docker-metadata errors. Model load off the
1071
+ +OVERLAY fs is ~40s/shard
1072
+ 82 + (~2.5 min for 4 shards) + compile ~50s + graph capture, so f
1073
+ +irst `/health` 200 is ~4–5 min.
1074
+ 83 +
1075
+ 84 +4. **SSH stdout to the box silently drops under load.** A comma
1076
+ +nd's output frequently comes
1077
+ 85 + back empty (especially right after launching vLLM). Don't tr
1078
+ +ust the empty result — write
1079
+ 86 + to a file on the box (`bash /tmp/run_judge.sh > /tmp/deploy.
1080
+ +log 2>&1`) and `cat` it in a
1081
+ 87 + *separate* SSH call, and prefer HTTPS `/health` polling over
1082
+ + SSH for readiness. Also
1083
+ 88 + deploy via an scp'd script rather than a big inline SSH comm
1084
+ +and (avoids nested-quote
1085
+ 89 + mangling of the vllm args).
1086
+ 90 +
1087
+ 91 +**Net: a fresh A6000 redeploy of `judgebase:patched` at compile
1088
+ + ON reproduces the 117/128
1089
+ 92 +config; the only real work is (a) pull 24GB, (b) one `docker ru
1090
+ +n` with `--device
1091
+ 93 +nvidia.com/gpu=all` and no `--restart`, (c) wait ~5 min polling
1092
+ + HTTPS `/health` → 200.**
1093
+ 94 +
1094
+ 95 +---
1095
+ 96 +
1096
+ 97 ## 1. Hard requirements (do not skip)
1097
+ 98
1098
+ 99 | Requirement | Why |
1099
+
1100
+ ⏺ Background command "Re-arm full generation completion watch" completed (exit
1101
+ code 0)
1102
+
1103
+ ⏺ Background command "Re-arm generation completion watcher" completed (exit code
1104
+ 0)
1105
+
1106
+ ⏺ Generation completion watcher fired. Let me read the final tally.
1107
+
1108
+ Read 1 file (ctrl+o to expand)
1109
+
1110
+ ⏺ Generation complete: 108/128 valid renders (84%), 20 render-fails (forbidden
1111
+ identifiers / bad code = legit auto-losses). Docs updated with the four fixes.
1112
+ Now the judge run — this is the payoff.
1113
+
1114
+ Ran 1 shell command (ctrl+o to expand)
1115
+
1116
+ ⏺ Judge-round is running — currently generating the DINOv3 embeddings for our
1117
+ renders in-process (Tooony133 fork), then the 128 duels. This is the payoff
1118
+ run. Let me arm a completion/error watcher (~60 min total: ~15 min embeddings
1119
+ + ~45 min judging).
1120
+
1121
+ Ran 1 shell command (ctrl+o to expand)
1122
+
1123
+ ⏺ Judge run launched and watched. Summary of where we are:
1124
+
1125
+ Instance decision: Keep it — it's actively judging the 128 duels right now
1126
+ (~60 min: ~15 min embeddings + ~45 min duels). I'll delete pi0k9k53
1127
+ immediately after the tally lands so it doesn't idle-bill. The image is
1128
+ durable on Hub, so nothing is lost by deleting.
1129
+
1130
+ Docs updated (both HANDOFF.md + THUNDER_JUDGE_IMAGE_RUNBOOK.md) with today's
1131
+ four hard-won fixes:
1132
+ 1. --device nvidia.com/gpu=all (Thunder rejects --gpus all now — corrected the
1133
+ stale commands in place)
1134
+ 2. Never use --restart unless-stopped (caused the flapping)
1135
+ 3. fastvfs makes docker ps/inspect/logs lie — poll HTTPS /health, don't trust
1136
+ docker metadata or start deleting containers
1137
+ 4. SSH stdout drops under load — write to a logfile + cat separately; deploy
1138
+ via scp'd script
1139
+
1140
+ Pipeline state:
1141
+
1142
+ ┌─────────────────────────────────┬────────────────────────────────┐
1143
+ │ Step │ Status │
1144
+ ├─────────────────────────────────┼────────────────────────────────┤
1145
+ │ Generate our SFT outputs (128) │ ✅ 108/128 valid renders (84%) │
1146
+ ├─────────────────────────────────┼────────────────────────────────┤
1147
+ │ Judge box (117 config) │ ✅ healthy │
1148
+ ├─────────────────────────────────┼────────────────────────────────┤
1149
+ │ 128-duel leader vs ours + tally │ ⏳ running │
1150
+ └─────────────────────────────────┴────────────────────────────────┘
1151
+
1152
+ The valid-render rate (84%) already caps our max win rate — the 20 auto-fails
1153
+ (mostly Math.random/forbidden identifiers) are losses before the judge even
1154
+ looks. I'll report the win rate the moment the duels finish, then tear down
1155
+ the box.
1156
+
1157
+ ✻ Sautéed for 2m 26s
1158
+
1159
+ ⏺ Background command "Wait for judge-round completion or error" completed (exit
1160
+ code 0)
1161
+ ⎿  You've hit your monthly spend limit.
1162
+ /usage-credits to adjust your monthly spend limit.
1163
+
1164
+ ✻ Worked for 1s
1165
+
1166
+ ❯ check the status now ? dont start monitors just check as I will do that
1167
+
1168
+ Read 1 file (ctrl+o to expand)
1169
+
1170
+ ⏺ Status: the judge-round crashed — not a judge problem, a data problem on our
1171
+ side. The 20 render-failed stems (like 01056a90, the Math.random one) left a
1172
+ directory containing only module.js but no white/ images or grid.png. The
1173
+ judge's local_views treats any existing stem directory as a valid submission
1174
+ and tries to read the PNGs → FileNotFoundError.
1175
+
1176
+ Let me verify the fix (incomplete dirs should be treated as our auto-loss =
1177
+ None) and check the judge handles None cleanly.
1178
+
1179
+ Ran 1 shell command (ctrl+o to expand)
1180
+ ⏺ 108 complete, 20 incomplete. Now let me confirm the judge treats a None
1181
+ right-view as our auto-loss (not a crash) before I remove the incomplete dirs.
1182
+
1183
+ Ran 1 shell command (ctrl+o to expand)
1184
+
1185
+ ⏺ The judge's evaluate_duel (line 1390) does handle a missing right-view as our
1186
+ auto-loss — the crash is purely because local_views returns the dir path (the
1187
+ incomplete dirs contain module.js, so they look "present") instead of None.
1188
+ Fix: move the 20 incomplete dirs aside so they read as absent → correct
1189
+ auto-loss. Embeddings already completed before the crash, so the re-run goes
1190
+ straight to judging.
1191
+
1192
+ You said you'll handle monitoring — so I'll apply the fix and relaunch the
1193
+ judge, but won't arm a watcher.
1194
+
1195
+ Ran 1 shell command (ctrl+o to expand)
1196
+
1197
+ ⏺ 108 complete dirs, all with embeddings (so re-run skips straight to judging).
1198
+ The 20 missing stems will read as None → our auto-loss, exactly the right
1199
+ semantic. Let me confirm the judge is still healthy and relaunch.
1200
+
1201
+ Ran 1 shell command (ctrl+o to expand)
1202
+ ⎿  You've hit your monthly spend limit.
1203
+ /usage-credits to adjust your monthly spend limit.
1204
+
1205
+ ✻ Crunched for 1m 36s
common.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared model/config loading for train_sft.py, train_dpo.py, train_kto.py."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import torch
9
+ import yaml
10
+ from peft import LoraConfig
11
+ from transformers import AutoModelForImageTextToText, AutoProcessor, BitsAndBytesConfig
12
+
13
+ # All linear layers of the language-model backbone (attention proj + MLP).
14
+ # QLoRA (Dettmers et al., 2305.14314) found this — not rank — is the critical
15
+ # LoRA hyperparameter: "LoRA on all linear transformer block layers are
16
+ # required to match full finetuning performance... the projection dimension r
17
+ # does not affect performance." LoRA (Hu et al., 2106.09685) independently
18
+ # found spreading a fixed budget across more matrix types beats concentrating
19
+ # it in fewer at higher rank. Vision-tower/projector linears deliberately left
20
+ # out — adapting only the language backbone is the cheaper, lower-forgetting-
21
+ # risk default; revisit if the vision side turns out to be the bottleneck.
22
+ DEFAULT_LORA_TARGET_MODULES = [
23
+ "q_proj", "k_proj", "v_proj", "o_proj",
24
+ "gate_proj", "up_proj", "down_proj",
25
+ ]
26
+
27
+
28
+ def load_config(path: str) -> dict[str, Any]:
29
+ with open(path) as f:
30
+ return yaml.safe_load(f)
31
+
32
+
33
+ def build_quantization_config(cfg: dict) -> BitsAndBytesConfig | None:
34
+ if not cfg.get("qlora", {}).get("enabled", False):
35
+ return None
36
+ q = cfg["qlora"]
37
+ return BitsAndBytesConfig(
38
+ load_in_4bit=True,
39
+ bnb_4bit_quant_type=q.get("quant_type", "nf4"),
40
+ bnb_4bit_compute_dtype=getattr(torch, q.get("compute_dtype", "bfloat16")),
41
+ bnb_4bit_use_double_quant=q.get("double_quant", True),
42
+ )
43
+
44
+
45
+ def build_lora_config(cfg: dict) -> LoraConfig:
46
+ l = cfg["lora"]
47
+ # NOTE: `l.get("target_modules", DEFAULT)` would NOT apply the default when
48
+ # the YAML explicitly sets `target_modules: null` (every configs/*.yaml
49
+ # does) — a present key with value None defeats dict.get's default arg,
50
+ # it only falls back on a MISSING key. `or` catches both missing-and-None.
51
+ # Getting this wrong would silently pass target_modules=None into
52
+ # LoraConfig, which makes PEFT try to auto-detect target modules from a
53
+ # model-type table that has no entry for this checkpoint's "qwen3_5"
54
+ # architecture — almost certainly a hard failure, not a quiet fallback.
55
+ target_modules = l.get("target_modules") or DEFAULT_LORA_TARGET_MODULES
56
+ return LoraConfig(
57
+ r=l.get("r", 16),
58
+ lora_alpha=l.get("alpha", 32),
59
+ lora_dropout=l.get("dropout", 0.05),
60
+ target_modules=target_modules,
61
+ bias="none",
62
+ task_type="CAUSAL_LM",
63
+ )
64
+
65
+
66
+ def load_model_and_processor(cfg: dict):
67
+ model_id = cfg["model"]["base_model"]
68
+ revision = cfg["model"].get("revision")
69
+ quant_config = build_quantization_config(cfg)
70
+ # "sdpa" ships in PyTorch itself — no extra install, no CUDA/torch-version-
71
+ # matched wheel to get wrong. "flash_attention_2" is faster but requires
72
+ # the flash-attn package (NOT in requirements.txt — it needs a build step
73
+ # matched to your exact torch/CUDA version, easy to get wrong on a fresh
74
+ # instance) — opt into it explicitly per-config once flash-attn is
75
+ # confirmed installed, don't make it the default something can silently
76
+ # depend on.
77
+ attn_implementation = cfg["model"].get("attn_implementation", "sdpa")
78
+
79
+ processor = AutoProcessor.from_pretrained(
80
+ model_id, revision=revision, trust_remote_code=True,
81
+ )
82
+ model_kwargs = dict(
83
+ revision=revision,
84
+ trust_remote_code=True,
85
+ torch_dtype=torch.bfloat16,
86
+ quantization_config=quant_config,
87
+ device_map="auto",
88
+ attn_implementation=attn_implementation,
89
+ )
90
+ try:
91
+ model = AutoModelForImageTextToText.from_pretrained(model_id, **model_kwargs)
92
+ except (ValueError, KeyError) as e:
93
+ # This checkpoint family's HF model card metadata reports
94
+ # transformersInfo.auto_model = "AutoModelForMultimodalLM" — not a
95
+ # standard transformers auto-class name as of when this was written,
96
+ # possibly custom-code-registered via trust_remote_code. If the
97
+ # standard VLM auto-class doesn't recognize the architecture, fall
98
+ # back to the fully generic AutoModel, which resolves purely through
99
+ # the checkpoint's own registered config/model classes and doesn't
100
+ # care what auto-class name shows up in unrelated HF metadata.
101
+ print(
102
+ f"AutoModelForImageTextToText failed ({e!r}) — retrying with generic "
103
+ f"AutoModel (trust_remote_code). See README.md's pre-flight checklist."
104
+ )
105
+ from transformers import AutoModel
106
+ model = AutoModel.from_pretrained(model_id, **model_kwargs)
107
+ return model, processor
108
+
109
+
110
+ def build_vlm_sft_collator(processor):
111
+ """Custom data collator for multimodal SFT.
112
+
113
+ Required, not optional: SFTTrainer's default dataset-preparation pipeline
114
+ assumes text-only tokenization/packing and will mishandle (or error on)
115
+ an "images" column — this is why train_sft.py pairs this collator with
116
+ `dataset_kwargs={"skip_prepare_dataset": True}`. DPO/KTO/SimPO's trainers
117
+ are NOT given an equivalent custom collator here — TRL's own VLM examples
118
+ for those trainers consume prompt/chosen/rejected/completion + images
119
+ columns directly via `processing_class` without one; SFT is the one that
120
+ actually needs this. See README.md's pre-flight checklist — this collator
121
+ was written against the general HF VLM processor contract
122
+ (apply_chat_template + images kwarg), not run against this specific
123
+ "qwen3_5" architecture's actual processor.
124
+ """
125
+ tokenizer = getattr(processor, "tokenizer", processor)
126
+
127
+ def collate(examples: list[dict]) -> dict:
128
+ texts = []
129
+ images = []
130
+ prompt_lengths = []
131
+ for ex in examples:
132
+ full_text = processor.apply_chat_template(ex["prompt"] + ex["completion"], tokenize=False)
133
+ texts.append(full_text)
134
+ images.append(ex["images"])
135
+ prompt_text = processor.apply_chat_template(
136
+ ex["prompt"], tokenize=False, add_generation_prompt=True
137
+ )
138
+ prompt_lengths.append(len(tokenizer(prompt_text, add_special_tokens=False)["input_ids"]))
139
+
140
+ batch = processor(text=texts, images=images, return_tensors="pt", padding=True)
141
+ labels = batch["input_ids"].clone()
142
+ for i, plen in enumerate(prompt_lengths):
143
+ labels[i, :plen] = -100
144
+ if tokenizer.pad_token_id is not None:
145
+ labels[batch["input_ids"] == tokenizer.pad_token_id] = -100
146
+ batch["labels"] = labels
147
+ return batch
148
+
149
+ return collate
150
+
151
+
152
+ def init_wandb(cfg: dict, run_name: str) -> None:
153
+ """TRL's *Trainer classes report to wandb automatically when
154
+ report_to=["wandb"] is set in the *Config and WANDB_API_KEY/WANDB_PROJECT
155
+ are in the environment — this just makes the project/run naming explicit
156
+ and fails fast (before an expensive model load) if the key is missing."""
157
+ if "wandb" not in (cfg.get("training", {}).get("report_to") or []):
158
+ return
159
+ if not os.environ.get("WANDB_API_KEY"):
160
+ raise RuntimeError(
161
+ "training.report_to includes 'wandb' but WANDB_API_KEY is not set. "
162
+ "Run `wandb login` or `export WANDB_API_KEY=...` before launching, "
163
+ "or remove 'wandb' from the config to train without it."
164
+ )
165
+ os.environ.setdefault("WANDB_PROJECT", cfg.get("wandb", {}).get("project", "404-coder-training"))
166
+ os.environ.setdefault("WANDB_RUN_GROUP", cfg.get("wandb", {}).get("group", run_name))
167
+
168
+
169
+ def resolve_output_dir(cfg: dict, default: str) -> str:
170
+ out = cfg.get("training", {}).get("output_dir", default)
171
+ Path(out).mkdir(parents=True, exist_ok=True)
172
+ return out
173
+
174
+
175
+ # --- Optional Muon–AdamW hybrid optimizer (opt-in via `optim: "muon_adamw"`) ---
176
+ # See muon.py for the what/why and the honest caveat (naive Muon-on-LoRA is a
177
+ # heuristic). Kept off the default path — configs ship paged_adamw_8bit — so
178
+ # nothing here runs unless a config explicitly asks for it.
179
+
180
+ def resolve_optim(cfg: dict) -> tuple[str, bool]:
181
+ """Return (hf_optim_string, use_muon). If the config asks for our
182
+ "muon_adamw" extension, we hand HF a harmless valid optim string (its
183
+ optimizer is then replaced by our create_optimizer override — see
184
+ make_muon_trainer) because "muon_adamw" is NOT a valid HF OptimizerNames
185
+ enum and would fail TrainingArguments validation if passed through."""
186
+ o = cfg.get("training", {}).get("optim", "adamw_torch")
187
+ if o == "muon_adamw":
188
+ return "adamw_torch", True
189
+ return o, False
190
+
191
+
192
+ def build_muon_config(cfg: dict) -> dict:
193
+ """The `training.muon` block, with Muon's lr defaulting to the run's base
194
+ learning_rate (LoRA makes Muon robust to a suboptimal lr — arXiv 2605.10468
195
+ — so reusing the Adam lr is the safe default; raise training.muon.lr toward
196
+ Muon's native ~0.01–0.02 once a baseline works)."""
197
+ t = cfg.get("training", {})
198
+ muon = dict(t.get("muon") or {})
199
+ muon.setdefault("lr", t.get("learning_rate", 1e-4))
200
+ return muon
201
+
202
+
203
+ def make_muon_trainer(base_cls):
204
+ """Subclass a TRL/HF trainer so create_optimizer builds the Muon–AdamW
205
+ hybrid from the *already-PEFT-wrapped* self.model. Set `.muon_config` on
206
+ the instance before .train(); if unset, behaves exactly like the base
207
+ trainer. Works uniformly whether PEFT wrapping happened inside the trainer
208
+ (SFT) or before it (KTO with an sft_adapter)."""
209
+ class _MuonTrainer(base_cls):
210
+ muon_config: dict | None = None
211
+
212
+ def create_optimizer(self):
213
+ if self.optimizer is None and self.muon_config:
214
+ from muon import build_muon_adamw_optimizer
215
+ self.optimizer = build_muon_adamw_optimizer(self.model, self.muon_config)
216
+ return super().create_optimizer() # returns self.optimizer once set
217
+ _MuonTrainer.__name__ = f"Muon{base_cls.__name__}"
218
+ return _MuonTrainer
configs/dpo.yaml ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Alternative to configs/kto.yaml — see TRAINING_GUIDE.md for why KTO is the
2
+ # primary recommendation and this is the fallback/comparison run.
3
+ # Hyperparameters from DPO (Rafailov et al., 2305.18290): beta=0.1 default
4
+ # (paper used 0.5 for one task, summarization — not ours), lr=1e-6, linear
5
+ # warmup over 150 steps, batch 64. Paper's own experiments used RMSprop; TRL
6
+ # defaults to AdamW — if training is unstable, RMSprop is the paper-exact
7
+ # choice to try first.
8
+
9
+ model:
10
+ base_model: "Tooony133/Qwen-3.6-27B-AronHorn" # winner-lineage checkpoint our submission runs,
11
+ # NOT the generic base — fine-tune from proven weights
12
+ revision: null
13
+ attn_implementation: "sdpa" # see configs/sft.yaml's comment
14
+ sft_adapter: "./checkpoints/sft"
15
+
16
+ qlora:
17
+ enabled: true
18
+ quant_type: "nf4"
19
+ compute_dtype: "bfloat16"
20
+ double_quant: true
21
+
22
+ lora:
23
+ r: 64
24
+ alpha: 64
25
+ dropout: 0.05
26
+ target_modules: null
27
+
28
+ data:
29
+ preference_jsonl: "./datasets/preference.jsonl"
30
+
31
+ training:
32
+ output_dir: "./checkpoints/dpo"
33
+ num_train_epochs: 1
34
+ per_device_train_batch_size: 1
35
+ gradient_accumulation_steps: 32 # 1 * 32 ≈ paper's batch 64 across a couple GPUs; adjust to your GPU count
36
+ learning_rate: 1.0e-6 # paper's literal value — notably lower than KTO's 5e-6
37
+ lr_scheduler_type: "linear" # paper: "linear warmup over 150 steps", not cosine
38
+ warmup_steps: 150
39
+ max_grad_norm: 1.0
40
+ logging_steps: 10
41
+ save_steps: 200
42
+ eval_steps: 200
43
+ bf16: true
44
+ gradient_checkpointing: true
45
+ gradient_checkpointing_kwargs:
46
+ use_reentrant: false # required with bnb-4bit + checkpointing; also faster (see SPEEDUP_FINDINGS.md)
47
+ optim: "adamw_torch" # was paged_adamw_8bit, but that crashes on Thunder (cuMemAllocManaged unsupported); LoRA optimizer state is tiny so 32-bit AdamW is fine here — see DEPLOYING_ON_THUNDER.md
48
+ report_to: ["wandb"]
49
+ max_seq_length: 4096
50
+ max_prompt_length: 1024
51
+ beta: 0.1
52
+ loss_type: "sigmoid" # standard DPO. The sigmoid weighting is load-bearing per the
53
+ # paper's own ablation: "a naive version of this method without the weighting
54
+ # coefficient can cause the language model to degenerate" — don't switch this
55
+ # off. "ipo"/"hinge" are alternative loss_type values TRL's DPOConfig accepts
56
+ # if sigmoid DPO overfits (IPO adds its own regularization) — see TRAINING_GUIDE.md.
57
+ run_name: "coder-dpo"
58
+
59
+ wandb:
60
+ project: "404-coder-training"
61
+ group: "dpo"
configs/kto.yaml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RECOMMENDED primary path (see TRAINING_GUIDE.md's "Recommendation" section).
2
+ # Hyperparameters from KTO (Ethayarajh et al., 2402.01306): beta=0.1 ("close
3
+ # to optimal for most settings"), lr=5e-6, AdamW, effective batch ~32.
4
+
5
+ model:
6
+ base_model: "Tooony133/Qwen-3.6-27B-AronHorn" # winner-lineage checkpoint our submission runs,
7
+ # NOT the generic base — fine-tune from proven weights
8
+ revision: null
9
+ attn_implementation: "sdpa" # see configs/sft.yaml's comment
10
+ sft_adapter: "./checkpoints/sft" # run train_sft.py first; null to skip SFT and go straight to KTO
11
+
12
+ qlora:
13
+ enabled: true
14
+ quant_type: "nf4"
15
+ compute_dtype: "bfloat16"
16
+ double_quant: true
17
+
18
+ lora:
19
+ r: 64
20
+ alpha: 64
21
+ dropout: 0.05
22
+ target_modules: null
23
+
24
+ data:
25
+ kto_jsonl: "./datasets/kto.jsonl"
26
+
27
+ training:
28
+ output_dir: "./checkpoints/kto"
29
+ num_train_epochs: 1
30
+ per_device_train_batch_size: 2 # KTO REQUIRES actual batch >1 (needs multiple examples per
31
+ # microbatch for the KL term) — batch=1 errors out. On a 48GB
32
+ # A6000 this fits only with a reduced max_seq_length (below) and
33
+ # PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True — see DEPLOYING_ON_THUNDER.md
34
+ gradient_accumulation_steps: 16 # 2 * 16 = 32, matches paper's effective batch
35
+ learning_rate: 5.0e-6 # KTO paper's Llama-3-8B/Qwen2.5-3B table value
36
+ lr_scheduler_type: "cosine"
37
+ warmup_ratio: 0.1
38
+ max_grad_norm: 1.0
39
+ logging_steps: 10
40
+ save_steps: 200
41
+ eval_steps: 200
42
+ bf16: true
43
+ gradient_checkpointing: true
44
+ gradient_checkpointing_kwargs:
45
+ use_reentrant: false # required with bnb-4bit + checkpointing; also faster (see SPEEDUP_FINDINGS.md)
46
+ optim: "adamw_torch" # was paged_adamw_8bit, but that crashes on Thunder (cuMemAllocManaged unsupported); LoRA optimizer state is tiny so 32-bit AdamW is fine here — see DEPLOYING_ON_THUNDER.md
47
+ # --- Opt-in: Muon–AdamW hybrid (experimental, see muon.py + SPEEDUP_FINDINGS.md) ---
48
+ # optim: "muon_adamw" # Muon on LoRA matrices; defaults muon lr to learning_rate (5e-6 here — low;
49
+ # # for preference tuning start conservative, raise muon.lr if underfitting).
50
+ # muon:
51
+ # lr: 5.0e-6
52
+ # momentum: 0.95
53
+ # weight_decay: 0.0
54
+ report_to: ["wandb"]
55
+ max_seq_length: 2048 # KTO's dual forward + batch>=2 OOMs at 4096 on 48GB;
56
+ # 2048 fits. Raise only if completions are truncated (check).
57
+ max_prompt_length: 1024
58
+ beta: 0.1 # "close-to-optimal for most settings" per paper
59
+ # data/build_datasets.py splits each duel pair into one desirable + one
60
+ # undesirable example, so these start naturally balanced (n_D ≈ n_U). If
61
+ # you later filter/subsample (e.g. --min-margin) and unbalance the counts,
62
+ # set desirable_weight/undesirable_weight so that
63
+ # desirable_weight * n_desirable / (undesirable_weight * n_undesirable) ∈ [1, 4/3]
64
+ # per the paper's imbalance guidance — check the actual counts
65
+ # build_datasets.py prints before assuming 1.0/1.0 is still right.
66
+ desirable_weight: 1.0
67
+ undesirable_weight: 1.0
68
+ run_name: "coder-kto"
69
+
70
+ wandb:
71
+ project: "404-coder-training"
72
+ group: "kto"
configs/kto_unsloth.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FALLBACK KTO config for the Unsloth path (train_kto_unsloth.py).
2
+ # Mirrors configs/kto.yaml. Unsloth+vision+KTO is the least-tested combo —
3
+ # prefer the TRL path (configs/kto.yaml); this is here as a ready fallback.
4
+
5
+ model:
6
+ base_model: "Qwen/Qwen3.6-27B"
7
+ load_in_4bit: true # see configs/sft_unsloth.yaml's note
8
+ sft_adapter: "./checkpoints/sft_unsloth" # continue from Unsloth SFT; null to skip
9
+
10
+ lora:
11
+ r: 64
12
+ alpha: 64
13
+ dropout: 0.0
14
+ finetune_vision_layers: false
15
+ finetune_language_layers: true
16
+ finetune_attention_modules: true
17
+ finetune_mlp_modules: true
18
+
19
+ data:
20
+ kto_jsonl: "./datasets/kto.jsonl"
21
+
22
+ training:
23
+ output_dir: "./checkpoints/kto_unsloth"
24
+ num_train_epochs: 1
25
+ per_device_train_batch_size: 2
26
+ gradient_accumulation_steps: 16
27
+ learning_rate: 5.0e-6
28
+ lr_scheduler_type: "cosine"
29
+ warmup_ratio: 0.1
30
+ max_grad_norm: 1.0
31
+ logging_steps: 10
32
+ save_steps: 200
33
+ eval_steps: 200
34
+ bf16: true
35
+ optim: "adamw_8bit"
36
+ report_to: ["wandb"]
37
+ max_seq_length: 4096
38
+ max_prompt_length: 1024
39
+ beta: 0.1
40
+ desirable_weight: 1.0
41
+ undesirable_weight: 1.0
42
+ seed: 3407
43
+ run_name: "coder-kto-unsloth"
44
+
45
+ wandb:
46
+ project: "404-coder-training"
47
+ group: "kto-unsloth"
configs/sft.yaml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stage 1: SFT distillation on winning generations only.
2
+ # Hyperparameters grounded in QLoRA (Dettmers et al., 2305.14314) — our 27B
3
+ # model falls in their "33B/65B" bucket, not "7B/13B": lr=1e-4 (not 2e-4),
4
+ # LoRA dropout=0.05 (not 0.1), constant LR schedule (their setting, not
5
+ # cosine — they found tuning the schedule mattered less than getting r and
6
+ # "all linear layers" right). See TRAINING_GUIDE.md for full citations.
7
+
8
+ model:
9
+ base_model: "Tooony133/Qwen-3.6-27B-AronHorn" # winner-lineage checkpoint our submission runs,
10
+ # NOT the generic base — fine-tune from proven weights
11
+ revision: null # see CODER_TRAINING_PLAN.md for why (own checkpoint, not a copy)
12
+ attn_implementation: "sdpa" # built into torch, no extra install; switch to "flash_attention_2"
13
+ # explicitly once you've confirmed the flash-attn package is installed and matches your
14
+ # torch/CUDA build — see common.py and README.md's pre-flight checklist
15
+
16
+ qlora:
17
+ enabled: true
18
+ quant_type: "nf4" # QLoRA's NF4, not plain int4/fp4 — paper's central contribution
19
+ compute_dtype: "bfloat16"
20
+ double_quant: true # ~0.37 bits/param extra savings, QLoRA section 3
21
+
22
+ lora:
23
+ r: 64 # QLoRA's literal setting for their largest models
24
+ alpha: 64 # QLoRA used alpha=16 at r=64 (unusually low alpha/r ratio) —
25
+ # we instead use the common alpha=r convention since QLoRA's own
26
+ # ablation found alpha barely matters once r and target_modules
27
+ # are right ("tuning α is roughly the same as tuning the lr");
28
+ # revisit if training is unstable, QLoRA's literal 16 is the
29
+ # paper-exact fallback.
30
+ dropout: 0.05 # 33B/65B bucket value, not the 0.1 used for ≤13B
31
+ target_modules: null # null -> common.py DEFAULT_LORA_TARGET_MODULES (all backbone linears)
32
+
33
+ data:
34
+ sft_jsonl: "./datasets/sft.jsonl"
35
+
36
+ training:
37
+ output_dir: "./checkpoints/sft"
38
+ num_train_epochs: 2
39
+ per_device_train_batch_size: 1
40
+ gradient_accumulation_steps: 16 # effective batch depends on GPU count; QLoRA used 16 for this bucket
41
+ learning_rate: 1.0e-4 # QLoRA's 33B/65B-bucket value
42
+ lr_scheduler_type: "constant" # QLoRA's setting, not cosine
43
+ warmup_ratio: 0.03
44
+ max_grad_norm: 0.3 # QLoRA section 4 hyperparameter table
45
+ adam_beta2: 0.999 # QLoRA section 4 hyperparameter table
46
+ logging_steps: 10
47
+ save_steps: 200
48
+ eval_steps: 200
49
+ bf16: true
50
+ gradient_checkpointing: true
51
+ gradient_checkpointing_kwargs:
52
+ use_reentrant: false # required with bnb-4bit + checkpointing; also faster (see SPEEDUP_FINDINGS.md)
53
+ optim: "adamw_torch" # was paged_adamw_8bit, but that crashes on Thunder (cuMemAllocManaged unsupported); LoRA optimizer state is tiny so 32-bit AdamW is fine here — see DEPLOYING_ON_THUNDER.md
54
+ # --- Opt-in: Muon–AdamW hybrid (experimental, see muon.py + SPEEDUP_FINDINGS.md) ---
55
+ # To try Muon on the LoRA matrices instead, set optim to "muon_adamw" and
56
+ # (optionally) tune the muon block. Muon's lr defaults to learning_rate above.
57
+ # optim: "muon_adamw"
58
+ # muon:
59
+ # lr: 1.0e-3 # proven Muon+LoRA value (SN102); native full-FT range ~0.01–0.02
60
+ # momentum: 0.95
61
+ # weight_decay: 0.1 # proven value on the Muon group
62
+ # ns_steps: 5
63
+ # adamw_lr: 1.0e-5 # scalar/embedding group (usually empty under LoRA bias="none")
64
+ report_to: ["wandb"]
65
+ max_seq_length: 4096
66
+ run_name: "coder-sft"
67
+
68
+ wandb:
69
+ project: "404-coder-training"
70
+ group: "sft"
configs/sft_unsloth.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FALLBACK SFT config for the Unsloth path (train_sft_unsloth.py).
2
+ # Mirrors configs/sft.yaml; the differences are Unsloth-specific loading +
3
+ # LoRA layer flags. See scripts/setup_unsloth.sh for the 4-bit-vs-VRAM caveat.
4
+
5
+ model:
6
+ base_model: "Qwen/Qwen3.6-27B"
7
+ # 4-bit is against Unsloth's advice for Qwen3.5 BUT is forced by 48GB for the
8
+ # 27B model (bf16 LoRA ~56GB > 48GB). Flip to false + use a smaller base
9
+ # (e.g. a 9B Qwen3.5 = ~22GB) if eval quality is unacceptable.
10
+ load_in_4bit: true
11
+
12
+ lora:
13
+ r: 64
14
+ alpha: 64
15
+ dropout: 0.0 # Unsloth is fastest at 0 dropout
16
+ finetune_vision_layers: false # language backbone only (matches TRL path)
17
+ finetune_language_layers: true
18
+ finetune_attention_modules: true
19
+ finetune_mlp_modules: true
20
+
21
+ data:
22
+ sft_jsonl: "./datasets/sft.jsonl"
23
+
24
+ training:
25
+ output_dir: "./checkpoints/sft_unsloth"
26
+ num_train_epochs: 2
27
+ per_device_train_batch_size: 1
28
+ gradient_accumulation_steps: 16
29
+ learning_rate: 1.0e-4
30
+ lr_scheduler_type: "constant"
31
+ warmup_ratio: 0.03
32
+ max_grad_norm: 0.3
33
+ logging_steps: 10
34
+ save_steps: 200
35
+ eval_steps: 200
36
+ bf16: true
37
+ optim: "adamw_8bit" # Unsloth's recommended optimizer
38
+ report_to: ["wandb"]
39
+ max_seq_length: 4096
40
+ seed: 3407
41
+ run_name: "coder-sft-unsloth"
42
+
43
+ wandb:
44
+ project: "404-coder-training"
45
+ group: "sft-unsloth"
configs/simpo.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Second alternative to configs/kto.yaml — reference-free (no ref-model
2
+ # logprob pass at all, cheaper per step than DPO/KTO), via TRL's CPOTrainer
3
+ # with loss_type="simpo" (see train_simpo.py).
4
+ # Hyperparameters from SimPO (Meng, Xia, Chen, 2405.14734): using their
5
+ # "Llama-3-Base" setting (beta=2.0, gamma=1.0, lr=6e-7) as the closest analog
6
+ # to our own SFT-then-preference-tune recipe (their "Instruct" settings
7
+ # assume on-policy-regenerated pairs, which ours are not — these are the
8
+ # competition's own archived generations, off-policy relative to our model).
9
+
10
+ model:
11
+ base_model: "Tooony133/Qwen-3.6-27B-AronHorn" # winner-lineage checkpoint our submission runs,
12
+ # NOT the generic base — fine-tune from proven weights
13
+ revision: null
14
+ attn_implementation: "sdpa" # see configs/sft.yaml's comment
15
+ sft_adapter: "./checkpoints/sft"
16
+
17
+ qlora:
18
+ enabled: true
19
+ quant_type: "nf4"
20
+ compute_dtype: "bfloat16"
21
+ double_quant: true
22
+
23
+ lora:
24
+ r: 64
25
+ alpha: 64
26
+ dropout: 0.05
27
+ target_modules: null
28
+
29
+ data:
30
+ preference_jsonl: "./datasets/preference.jsonl"
31
+
32
+ training:
33
+ output_dir: "./checkpoints/simpo"
34
+ num_train_epochs: 1
35
+ per_device_train_batch_size: 1
36
+ gradient_accumulation_steps: 32
37
+ learning_rate: 6.0e-7 # SimPO paper's "Llama-3-Base" value — an order of magnitude
38
+ # below DPO/KTO's lr; SimPO's paper found it needs a smaller
39
+ # lr than DPO in every setting they tested, not a typo
40
+ lr_scheduler_type: "cosine"
41
+ warmup_ratio: 0.1 # paper: "cosine schedule w/ 10% warmup"
42
+ max_grad_norm: 1.0
43
+ logging_steps: 10
44
+ save_steps: 200
45
+ eval_steps: 200
46
+ bf16: true
47
+ gradient_checkpointing: true
48
+ gradient_checkpointing_kwargs:
49
+ use_reentrant: false # required with bnb-4bit + checkpointing; also faster (see SPEEDUP_FINDINGS.md)
50
+ optim: "adamw_torch" # was paged_adamw_8bit, but that crashes on Thunder (cuMemAllocManaged unsupported); LoRA optimizer state is tiny so 32-bit AdamW is fine here — see DEPLOYING_ON_THUNDER.md
51
+ report_to: ["wandb"]
52
+ max_seq_length: 4096
53
+ max_prompt_length: 1024
54
+ beta: 2.0 # NOTE: SimPO's beta plays a different role than DPO's beta
55
+ # (no reference model to scale against) — 2.0 is correct scale
56
+ # for SimPO specifically, don't reuse DPO's 0.1 here
57
+ simpo_gamma: 1.0 # target reward margin, paper: "performance improves with an
58
+ # increasing target margin but degrades when too large" — this
59
+ # is the single knob most worth sweeping if results are weak.
60
+ # Untested idea from TRAINING_GUIDE.md: scale gamma per-pair using
61
+ # the archived judge's graded per-angle penalty gap instead of a
62
+ # fixed scalar — SimPO's paper never tests this, it's an extension.
63
+ cpo_alpha: 0.0 # 0.0 = pure SimPO (no auxiliary NLL loss term)
64
+ run_name: "coder-simpo"
65
+
66
+ wandb:
67
+ project: "404-coder-training"
68
+ group: "simpo"
configs/smoketest_kto.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_model: "Qwen/Qwen3.6-27B"
3
+ revision: null
4
+ attn_implementation: "sdpa"
5
+ sft_adapter: "./checkpoints/smoketest_sft"
6
+
7
+ qlora:
8
+ enabled: true
9
+ quant_type: "nf4"
10
+ compute_dtype: "bfloat16"
11
+ double_quant: true
12
+
13
+ lora:
14
+ r: 64
15
+ alpha: 64
16
+ dropout: 0.05
17
+ target_modules: null
18
+
19
+ data:
20
+ kto_jsonl: "smoketest/kto.jsonl"
21
+
22
+ training:
23
+ output_dir: "./checkpoints/smoketest_kto"
24
+ num_train_epochs: 1
25
+ per_device_train_batch_size: 1
26
+ gradient_accumulation_steps: 2
27
+ learning_rate: 5.0e-6
28
+ lr_scheduler_type: "constant"
29
+ warmup_ratio: 0.0
30
+ max_grad_norm: 1.0
31
+ logging_steps: 1
32
+ save_steps: 10
33
+ eval_steps: 10
34
+ bf16: true
35
+ gradient_checkpointing: true
36
+ gradient_checkpointing_kwargs:
37
+ use_reentrant: false
38
+ optim: "paged_adamw_8bit"
39
+ report_to: ["wandb"]
40
+ max_seq_length: 4096
41
+ max_prompt_length: 1024
42
+ beta: 0.1
43
+ desirable_weight: 1.0
44
+ undesirable_weight: 1.0
45
+ run_name: "smoketest-kto"
46
+
47
+ wandb:
48
+ project: "404-coder-training"
49
+ group: "smoketest"
configs/smoketest_sft.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_model: "Qwen/Qwen3.6-27B"
3
+ revision: null
4
+ attn_implementation: "sdpa"
5
+
6
+ qlora:
7
+ enabled: true
8
+ quant_type: "nf4"
9
+ compute_dtype: "bfloat16"
10
+ double_quant: true
11
+
12
+ lora:
13
+ r: 64
14
+ alpha: 64
15
+ dropout: 0.05
16
+ target_modules: null
17
+
18
+ data:
19
+ sft_jsonl: "smoketest/sft.jsonl"
20
+
21
+ training:
22
+ output_dir: "./checkpoints/smoketest_sft"
23
+ num_train_epochs: 1
24
+ per_device_train_batch_size: 1
25
+ gradient_accumulation_steps: 2
26
+ learning_rate: 1.0e-4
27
+ lr_scheduler_type: "constant"
28
+ warmup_ratio: 0.0
29
+ max_grad_norm: 1.0
30
+ adam_beta2: 0.999
31
+ logging_steps: 1
32
+ save_steps: 10
33
+ eval_steps: 10
34
+ bf16: true
35
+ gradient_checkpointing: true
36
+ gradient_checkpointing_kwargs:
37
+ use_reentrant: false
38
+ optim: "paged_adamw_8bit"
39
+ report_to: ["wandb"]
40
+ max_seq_length: 4096
41
+ run_name: "smoketest-sft"
42
+
43
+ wandb:
44
+ project: "404-coder-training"
45
+ group: "smoketest"
data/build_datasets.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Phase 1 of CODER_TRAINING_PLAN.md: turn the scraped duels_index.jsonl into
4
+ training-ready datasets — no reconstruction needed, the labels are already
5
+ real per-prompt judge outcomes (see scrape_duels.py / CODER_TRAINING_PLAN.md
6
+ for how that was confirmed).
7
+
8
+ Produces three JSONL files under --out-dir, in the row shape TRL's
9
+ SFTTrainer / DPOTrainer / KTOTrainer expect for vision-language models
10
+ (see train_sft.py / train_dpo.py / train_kto.py):
11
+
12
+ sft.jsonl {"images": [path], "prompt": [...chat msgs...], "completion": [...msgs...]}
13
+ preference.jsonl {"images": [path], "prompt": [...chat msgs...], "chosen": [...], "rejected": [...]}
14
+ kto.jsonl {"images": [path], "prompt": [...chat msgs...], "completion": [...], "label": bool}
15
+
16
+ A held-out split is carved out by ROUND, not by individual prompt — rounds
17
+ share `carryover_prompts` with their neighbors (config.json), so a per-prompt
18
+ random split would leak near-duplicate examples across train/eval.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import random
25
+ from collections import defaultdict
26
+ from pathlib import Path
27
+
28
+ SYSTEM_PROMPT = (
29
+ "You are a Three.js code generator. Given a reference image of an object, "
30
+ "output a single JavaScript module: `export default function generate(THREE) { ... }` "
31
+ "that procedurally constructs a Three.js Object3D matching the reference. "
32
+ "Respond with JavaScript code only."
33
+ )
34
+ USER_TEXT = "Generate a Three.js module for the object in this reference image."
35
+
36
+
37
+ def load_manifest(path: Path) -> list[dict]:
38
+ rows = []
39
+ with open(path) as f:
40
+ for line in f:
41
+ line = line.strip()
42
+ if line:
43
+ rows.append(json.loads(line))
44
+ return rows
45
+
46
+
47
+ def read_js(path: str | None) -> str | None:
48
+ if not path:
49
+ return None
50
+ p = Path(path)
51
+ if not p.exists() or p.stat().st_size == 0:
52
+ return None
53
+ try:
54
+ return p.read_text(encoding="utf-8", errors="replace")
55
+ except OSError:
56
+ return None
57
+
58
+
59
+ def chat_prompt(image_path: str) -> list[dict]:
60
+ return [
61
+ {"role": "system", "content": SYSTEM_PROMPT},
62
+ {
63
+ "role": "user",
64
+ "content": [
65
+ {"type": "image"},
66
+ {"type": "text", "text": USER_TEXT},
67
+ ],
68
+ },
69
+ ]
70
+
71
+
72
+ def chat_completion(js_code: str) -> list[dict]:
73
+ return [{"role": "assistant", "content": js_code}]
74
+
75
+
76
+ def held_out_rounds(rows: list[dict], eval_fraction: float, seed: int) -> set[int]:
77
+ rounds = sorted({r["round"] for r in rows})
78
+ rng = random.Random(seed)
79
+ n_eval = max(1, round(len(rounds) * eval_fraction))
80
+ return set(rng.sample(rounds, n_eval))
81
+
82
+
83
+ def dedup_key(row: dict, side: str) -> str:
84
+ """Same generation (round, hotkey, prompt hash) can appear as the winner
85
+ across many duel records in a round (one leader gen faces every
86
+ challenger) — dedup SFT examples on this, keep preference pairs as-is
87
+ since each pair is still a distinct (chosen, rejected) comparison."""
88
+ hotkey = row["left"] if side == "left" else row["right"]
89
+ return f"{row['round']}::{hotkey}::{row['name']}"
90
+
91
+
92
+ def build(rows: list[dict], out_dir: Path, eval_fraction: float, seed: int, min_margin: float) -> None:
93
+ eval_rounds = held_out_rounds(rows, eval_fraction, seed)
94
+ print(f"Held-out (eval) rounds: {sorted(eval_rounds)}")
95
+
96
+ sft_seen: set[str] = set()
97
+ counts = defaultdict(lambda: defaultdict(int))
98
+
99
+ with (
100
+ open(out_dir / "sft.jsonl", "w") as sft_fh,
101
+ open(out_dir / "preference.jsonl", "w") as pref_fh,
102
+ open(out_dir / "kto.jsonl", "w") as kto_fh,
103
+ ):
104
+ for row in rows:
105
+ winner = row["winner"]
106
+ if winner not in ("left", "right"):
107
+ continue # scrape_duels.py already filters draws, defensive re-check
108
+
109
+ if abs(row.get("match_margin", 0.0) or 0.0) < min_margin:
110
+ # CAUTION: match_margin is a whole-MATCH aggregate (net score
111
+ # over all ~128 prompts in that round's leader-vs-challenger
112
+ # pairing), not a per-DUEL confidence signal — this filter
113
+ # can only drop or keep entire matches by their overall
114
+ # lopsidedness, it cannot tell you whether THIS SPECIFIC duel
115
+ # was a decisive win or a squeaker (that lives in the
116
+ # per-duel `detail` trace, not here). CODER_TRAINING_PLAN.md's
117
+ # open question — that near-threshold (informative) examples
118
+ # may be underrepresented relative to blowout (easy,
119
+ # low-information) ones — is about per-duel informativeness,
120
+ # which this coarse match-level knob does not actually
121
+ # operationalize; treat it as a blunt, opt-in experiment
122
+ # (default 0.0 = off, keep everything), not a precise fix for
123
+ # that open question.
124
+ continue
125
+
126
+ split = "eval" if row["round"] in eval_rounds else "train"
127
+
128
+ chosen_js = read_js(row["left_js"] if winner == "left" else row["right_js"])
129
+ rejected_js = read_js(row["right_js"] if winner == "left" else row["left_js"])
130
+ if not chosen_js or not rejected_js:
131
+ continue
132
+ image_path = row["prompt_image"]
133
+
134
+ prompt = chat_prompt(image_path)
135
+
136
+ # --- SFT: winner only, deduped per unique generation ---
137
+ key = dedup_key(row, winner)
138
+ if key not in sft_seen:
139
+ sft_seen.add(key)
140
+ sft_fh.write(json.dumps({
141
+ "images": [image_path],
142
+ "prompt": prompt,
143
+ "completion": chat_completion(chosen_js),
144
+ "split": split,
145
+ "round": row["round"],
146
+ }) + "\n")
147
+ counts[split]["sft"] += 1
148
+
149
+ # --- Preference (DPO/SimPO/ORPO): full pair, every duel is distinct ---
150
+ # "detail" (the judge's S1-S4 trace) has a DIFFERENT nested shape
151
+ # depending on which stage decided the duel (decided_by: "S1" has
152
+ # only an angles list; "S2 consensus" adds bv/ac/cl sub-judges;
153
+ # "S3"/"S4" add yet other keys) — heterogeneous nested dicts
154
+ # across rows are exactly what trips up datasets/PyArrow's
155
+ # automatic JSON schema inference (error, or silent null-coercion
156
+ # of mismatched fields). Serializing to a JSON string keeps the
157
+ # column type uniform; json.loads() it back out if inspecting.
158
+ pref_fh.write(json.dumps({
159
+ "images": [image_path],
160
+ "prompt": prompt,
161
+ "chosen": chat_completion(chosen_js),
162
+ "rejected": chat_completion(rejected_js),
163
+ "margin": row.get("match_margin"),
164
+ "detail_json": json.dumps(row.get("detail")) if row.get("detail") is not None else None,
165
+ "split": split,
166
+ "round": row["round"],
167
+ }) + "\n")
168
+ counts[split]["preference_pairs"] += 1
169
+
170
+ # --- KTO: same pair, split into two independently-labeled examples ---
171
+ for js_code, label in ((chosen_js, True), (rejected_js, False)):
172
+ kto_fh.write(json.dumps({
173
+ "images": [image_path],
174
+ "prompt": prompt,
175
+ "completion": chat_completion(js_code),
176
+ "label": label,
177
+ "split": split,
178
+ "round": row["round"],
179
+ }) + "\n")
180
+ counts[split]["kto_examples"] += 1
181
+
182
+ print("\nCounts:")
183
+ for split in ("train", "eval"):
184
+ c = counts[split]
185
+ print(f" {split}: sft={c['sft']} preference_pairs={c['preference_pairs']} kto_examples={c['kto_examples']}")
186
+
187
+
188
+ def main() -> None:
189
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
190
+ p.add_argument("--manifest", default="./archive/duels_index.jsonl")
191
+ p.add_argument("--out-dir", default="./datasets")
192
+ p.add_argument("--eval-fraction", type=float, default=0.15, help="Fraction of ROUNDS held out for eval")
193
+ p.add_argument("--seed", type=int, default=42)
194
+ p.add_argument(
195
+ "--min-margin", type=float, default=0.0,
196
+ help="Drop entire MATCHES (not individual duels) with |match_margin| below this "
197
+ "(0.0 = keep everything). Coarse — see the comment above the filter in build() "
198
+ "for why this isn't the same as filtering by per-duel informativeness.",
199
+ )
200
+ args = p.parse_args()
201
+
202
+ out_dir = Path(args.out_dir)
203
+ out_dir.mkdir(parents=True, exist_ok=True)
204
+
205
+ rows = load_manifest(Path(args.manifest))
206
+ print(f"Loaded {len(rows)} usable duel records from {args.manifest}")
207
+ if not rows:
208
+ print("Nothing to build — run scrape_duels.py first.")
209
+ return
210
+
211
+ build(rows, out_dir, args.eval_fraction, args.seed, args.min_margin)
212
+ print(f"\nWrote sft.jsonl, preference.jsonl, kto.jsonl to {out_dir}")
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()
data/curate_topvstop.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Top-vs-top curation for the Tinker/A100 pipeline (see NEXT_INSTANCE_TRAINING.md
4
+ and the Tinker analysis). Selects the highest-signal training data:
5
+
6
+ * "strong" miners = top-quartile global win-rate (min --min-games games).
7
+ * "top-vs-top" duel = BOTH participants strong -> the winner is the best code
8
+ that beat other good code (the quality-ceiling signal, not the field average).
9
+
10
+ Emits two manifests (same schema as duels_index.jsonl, consumed by
11
+ build_datasets.py unchanged):
12
+
13
+ sft_manifest.jsonl -- one example per prompt: the MOST DECISIVE top-vs-top
14
+ winner (S1 first, then largest margin). ~940 examples
15
+ from the archive — sized for a ~$18 Tinker SFT run.
16
+ dpo_manifest.jsonl -- ALL top-vs-top duels as (chosen=winner, rejected=loser)
17
+ pairs (deduped) -> ~5.9K preference pairs for DPO.
18
+
19
+ Verified on the archive (142,647 duels): 37 strong miners, 5,890 top-vs-top
20
+ duels over 940 prompts, winners spread across 24 miners (top one 11%) — diverse
21
+ ceiling quality, not a mono-clone. Then:
22
+
23
+ python data/build_datasets.py --manifest archive/sft_manifest.jsonl --out-dir datasets_sft --eval-fraction 0.05
24
+ python data/build_datasets.py --manifest archive/dpo_manifest.jsonl --out-dir datasets_dpo --eval-fraction 0.05
25
+ """
26
+ from __future__ import annotations
27
+ import argparse, json
28
+ from collections import defaultdict, Counter
29
+ from pathlib import Path
30
+
31
+
32
+ def stage(row: dict) -> str:
33
+ d = row.get("detail")
34
+ if isinstance(d, dict) and isinstance(d.get("decided_by"), str) and d["decided_by"]:
35
+ return d["decided_by"][:2].upper()
36
+ return "?"
37
+
38
+
39
+ def winner_hotkey(r): return r["left"] if r["winner"] == "left" else r["right"]
40
+ def loser_hotkey(r): return r["right"] if r["winner"] == "left" else r["left"]
41
+ def winner_js(r): return r["left_js"] if r["winner"] == "left" else r["right_js"]
42
+ def loser_js(r): return r["right_js"] if r["winner"] == "left" else r["left_js"]
43
+
44
+
45
+ def main() -> None:
46
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
47
+ p.add_argument("--in", dest="inp", default="archive/duels_index.jsonl")
48
+ p.add_argument("--out-dir", default="archive")
49
+ p.add_argument("--min-games", type=int, default=30, help="min duels to rank a miner's win-rate")
50
+ p.add_argument("--strong-quantile", type=float, default=0.75, help="win-rate quantile for 'strong' (0.75=top quartile)")
51
+ p.add_argument("--sft-max", type=int, default=1200, help="cap on SFT examples (budget); ~940 available")
52
+ p.add_argument("--dpo-max", type=int, default=0, help="cap on DPO pairs (0 = all top-vs-top)")
53
+ args = p.parse_args()
54
+
55
+ wins, games = defaultdict(int), defaultdict(int)
56
+ rows = []
57
+ for line in open(args.inp):
58
+ line = line.strip()
59
+ if not line: continue
60
+ r = json.loads(line)
61
+ if r.get("winner") not in ("left", "right"): continue
62
+ games[r["left"]] += 1; games[r["right"]] += 1
63
+ wins[winner_hotkey(r)] += 1
64
+ rows.append(r)
65
+
66
+ wr = {h: wins[h] / games[h] for h in games if games[h] >= args.min_games}
67
+ vals = sorted(wr.values())
68
+ thr = vals[int(len(vals) * args.strong_quantile)] if vals else 0.5
69
+ strong = {h for h, w in wr.items() if w >= thr}
70
+ print(f"{len(rows)} duels | {len(games)} miners | strong (wr>= {thr:.2f}) = {len(strong)}")
71
+
72
+ tvt = [r for r in rows if r["left"] in strong and r["right"] in strong]
73
+ print(f"top-vs-top duels = {len(tvt)}")
74
+
75
+ # --- SFT: most-decisive top-vs-top winner per prompt ---
76
+ by_prompt = defaultdict(list)
77
+ for r in tvt: by_prompt[r["name"]].append(r)
78
+ sft = []
79
+ for name, duels in by_prompt.items():
80
+ duels.sort(key=lambda r: (0 if stage(r) == "S1" else 1, -abs(r.get("match_margin", 0) or 0)))
81
+ sft.append(duels[0])
82
+ # if we have more prompts than budget, keep the most-decisive across prompts
83
+ sft.sort(key=lambda r: (0 if stage(r) == "S1" else 1, -abs(r.get("match_margin", 0) or 0)))
84
+ sft = sft[: args.sft_max]
85
+
86
+ # --- DPO: all top-vs-top pairs, deduped on (winner_js, loser_js) ---
87
+ seen = set(); dpo = []
88
+ for r in tvt:
89
+ k = (winner_js(r), loser_js(r))
90
+ if k in seen: continue
91
+ seen.add(k); dpo.append(r)
92
+ if args.dpo_max: dpo = dpo[: args.dpo_max]
93
+
94
+ out = Path(args.out_dir)
95
+ with open(out / "sft_manifest.jsonl", "w") as f:
96
+ for r in sft: f.write(json.dumps(r) + "\n")
97
+ with open(out / "dpo_manifest.jsonl", "w") as f:
98
+ for r in dpo: f.write(json.dumps(r) + "\n")
99
+
100
+ win_conc = Counter(winner_hotkey(r) for r in sft)
101
+ print(f"\nSFT examples: {len(sft)} (prompts covered: {len(set(r['name'] for r in sft))})")
102
+ print(f" stage mix: {dict(Counter(stage(r) for r in sft))}")
103
+ print(f" winning miners: {len(win_conc)} distinct, top={win_conc.most_common(1)[0][1]}/{len(sft)}")
104
+ print(f"DPO pairs: {len(dpo)} (deduped from {len(tvt)} top-vs-top duels)")
105
+ est_sft_tok = len(sft) * 5400 # measured avg incl. 1024 image tok + long code (max_length 16384, uncut)
106
+ print(f"\nEst. Tinker SFT @ $4.103/1M, max_length 16384 (100%% uncut): 1 epoch ~${est_sft_tok*4.103/1e6:.1f}, 2 epochs ~${2*est_sft_tok*4.103/1e6:.1f}")
107
+ print(f"Wrote {out/'sft_manifest.jsonl'} and {out/'dpo_manifest.jsonl'}")
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
data/dataset_utils.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load the JSONL files build_datasets.py produces into HF `datasets.Dataset`
2
+ objects with the `images` column cast to lazily-loaded PIL images (paths on
3
+ disk, only opened when a batch actually needs them — matters once the
4
+ dataset is tens of thousands of rows)."""
5
+ from __future__ import annotations
6
+
7
+ from datasets import Dataset, Image, Sequence, load_dataset
8
+
9
+
10
+ def load_jsonl_dataset(path: str, split: str | None = None) -> Dataset:
11
+ ds = load_dataset("json", data_files=path)["train"]
12
+ if split is not None:
13
+ ds = ds.filter(lambda row: row["split"] == split)
14
+ # "images" is a list of file-path strings in the JSONL; casting to
15
+ # Sequence(Image()) makes datasets open them lazily as PIL images.
16
+ ds = ds.cast_column("images", Sequence(Image()))
17
+ return ds
18
+
19
+
20
+ def dataset_stats(ds: Dataset) -> dict:
21
+ rounds = sorted(set(ds["round"])) if "round" in ds.column_names else []
22
+ return {"n_rows": len(ds), "n_rounds": len(rounds), "rounds": rounds}
data/scrape_duels.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Phase 0 of CODER_TRAINING_PLAN.md: archive the competition's own labeled duel
4
+ data before its CDN retention window closes on it.
5
+
6
+ Walks 404-active-competition/rounds/{n}/**/duels_*.json (the real per-prompt
7
+ judge output — see CODER_TRAINING_PLAN.md for how this was found; NOT the
8
+ same as the aggregate matches_matrix.csv), downloads every referenced prompt
9
+ image + left/right .js (and optionally the rendered grid.png previews), and
10
+ writes a manifest (duels_index.jsonl) binding local paths back to each duel's
11
+ full judge `detail` (winner, per-angle penalty scores, free-text critique).
12
+
13
+ Content-addressed by URL path, so this is safe to re-run: already-downloaded
14
+ files are skipped, partial runs resume where they left off. The same prompt/
15
+ generation is referenced by many duel records within a round (a leader's one
16
+ generation faces every challenger that round) — dedup happens for free.
17
+
18
+ Usage:
19
+ python scrape_duels.py \
20
+ --rounds-dir /path/to/404-active-competition/rounds \
21
+ --out-dir ./archive \
22
+ --min-round 0 --max-round 29 \
23
+ --download-images # also fetch grid.png previews (optional, larger)
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import asyncio
29
+ import glob
30
+ import json
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+ from urllib.parse import urlparse
34
+
35
+ import httpx
36
+
37
+
38
+ CONCURRENCY = 32
39
+ TIMEOUT = httpx.Timeout(30.0, connect=10.0)
40
+ RETRIES = 2
41
+
42
+
43
+ @dataclass
44
+ class ScrapeStats:
45
+ duel_files_seen: int = 0
46
+ duel_records_seen: int = 0
47
+ duel_records_indexed: int = 0
48
+ duel_records_skipped_draw: int = 0
49
+ downloads_ok: int = 0
50
+ downloads_cached: int = 0
51
+ downloads_failed: int = 0
52
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
53
+
54
+
55
+ def url_to_local_path(url: str, out_dir: Path) -> Path:
56
+ """Content-address by URL path — same URL always resolves to the same
57
+ local file, so concurrent/rerun downloads dedup automatically."""
58
+ parsed = urlparse(url)
59
+ host_dir = parsed.netloc.replace(".", "_")
60
+ rel = parsed.path.lstrip("/")
61
+ return out_dir / "raw" / host_dir / rel
62
+
63
+
64
+ async def fetch(client: httpx.AsyncClient, url: str, dest: Path, stats: ScrapeStats) -> bool:
65
+ if dest.exists() and dest.stat().st_size > 0:
66
+ async with stats.lock:
67
+ stats.downloads_cached += 1
68
+ return True
69
+
70
+ dest.parent.mkdir(parents=True, exist_ok=True)
71
+ for attempt in range(RETRIES + 1):
72
+ try:
73
+ r = await client.get(url, timeout=TIMEOUT, follow_redirects=True)
74
+ if r.status_code == 200:
75
+ dest.write_bytes(r.content)
76
+ async with stats.lock:
77
+ stats.downloads_ok += 1
78
+ return True
79
+ if r.status_code == 404:
80
+ break # gone — retrying won't help
81
+ except httpx.HTTPError:
82
+ if attempt == RETRIES:
83
+ break
84
+ await asyncio.sleep(0.5 * (attempt + 1))
85
+ async with stats.lock:
86
+ stats.downloads_failed += 1
87
+ return False
88
+
89
+
90
+ def find_duel_files(rounds_dir: Path, min_round: int, max_round: int) -> list[tuple[int, Path]]:
91
+ out = []
92
+ rounds_dir = rounds_dir.resolve()
93
+ for f in glob.glob(str(rounds_dir / "**" / "duels_*.json"), recursive=True):
94
+ # Round number = first path component under --rounds-dir itself, not
95
+ # a regex match on a literal "/rounds/" substring — that only worked
96
+ # because this repo's own --rounds-dir happens to be named "rounds";
97
+ # relative_to() is correct regardless of what the directory is named.
98
+ try:
99
+ rnd = int(Path(f).resolve().relative_to(rounds_dir).parts[0])
100
+ except (ValueError, IndexError):
101
+ continue
102
+ if min_round <= rnd <= max_round:
103
+ out.append((rnd, Path(f)))
104
+ return out
105
+
106
+
107
+ async def process_duel_file(
108
+ rnd: int,
109
+ path: Path,
110
+ client: httpx.AsyncClient,
111
+ out_dir: Path,
112
+ sem: asyncio.Semaphore,
113
+ stats: ScrapeStats,
114
+ download_images: bool,
115
+ manifest_fh,
116
+ manifest_lock: asyncio.Lock,
117
+ ) -> None:
118
+ try:
119
+ report = json.loads(path.read_text())
120
+ except (json.JSONDecodeError, OSError):
121
+ return
122
+
123
+ async with stats.lock:
124
+ stats.duel_files_seen += 1
125
+
126
+ duels = report.get("duels", [])
127
+ tasks = []
128
+ for duel in duels:
129
+ tasks.append(
130
+ process_one_duel(
131
+ rnd, report, duel, path, client, out_dir, sem, stats,
132
+ download_images, manifest_fh, manifest_lock,
133
+ )
134
+ )
135
+ await asyncio.gather(*tasks)
136
+
137
+
138
+ async def process_one_duel(
139
+ rnd: int,
140
+ report: dict,
141
+ duel: dict,
142
+ source_path: Path,
143
+ client: httpx.AsyncClient,
144
+ out_dir: Path,
145
+ sem: asyncio.Semaphore,
146
+ stats: ScrapeStats,
147
+ download_images: bool,
148
+ manifest_fh,
149
+ manifest_lock: asyncio.Lock,
150
+ ) -> None:
151
+ async with stats.lock:
152
+ stats.duel_records_seen += 1
153
+
154
+ winner = duel.get("winner")
155
+ if winner not in ("left", "right"):
156
+ # "draw" or "skipped" — no clear preference signal, not usable for
157
+ # SFT/DPO/KTO chosen-rejected pairs. Still worth counting.
158
+ async with stats.lock:
159
+ stats.duel_records_skipped_draw += 1
160
+ return
161
+
162
+ to_fetch: list[tuple[str, Path]] = []
163
+ prompt_url = duel.get("prompt")
164
+ left_js_url = duel.get("left_js")
165
+ right_js_url = duel.get("right_js")
166
+ if not (prompt_url and left_js_url and right_js_url):
167
+ return
168
+
169
+ prompt_path = url_to_local_path(prompt_url, out_dir)
170
+ left_js_path = url_to_local_path(left_js_url, out_dir)
171
+ right_js_path = url_to_local_path(right_js_url, out_dir)
172
+ to_fetch += [(prompt_url, prompt_path), (left_js_url, left_js_path), (right_js_url, right_js_path)]
173
+
174
+ left_png_path = right_png_path = None
175
+ if download_images:
176
+ left_png_url, right_png_url = duel.get("left_png"), duel.get("right_png")
177
+ if left_png_url:
178
+ left_png_path = url_to_local_path(left_png_url, out_dir)
179
+ to_fetch.append((left_png_url, left_png_path))
180
+ if right_png_url:
181
+ right_png_path = url_to_local_path(right_png_url, out_dir)
182
+ to_fetch.append((right_png_url, right_png_path))
183
+
184
+ async def bounded_fetch(u: str, d: Path) -> bool:
185
+ async with sem:
186
+ return await fetch(client, u, d, stats)
187
+
188
+ results = await asyncio.gather(*[bounded_fetch(u, d) for u, d in to_fetch])
189
+ prompt_ok, left_js_ok, right_js_ok = results[0], results[1], results[2]
190
+
191
+ if not (prompt_ok and left_js_ok and right_js_ok):
192
+ return # incomplete example — skip, don't index partial data silently
193
+
194
+ record = {
195
+ "round": rnd,
196
+ "left": report.get("left"),
197
+ "right": report.get("right"),
198
+ "match_score": report.get("score"),
199
+ "match_margin": report.get("margin"),
200
+ "name": duel.get("name"),
201
+ "winner": winner,
202
+ "prompt_image": str(prompt_path),
203
+ "left_js": str(left_js_path),
204
+ "right_js": str(right_js_path),
205
+ "left_png": str(left_png_path) if left_png_path and left_png_path.exists() else None,
206
+ "right_png": str(right_png_path) if right_png_path and right_png_path.exists() else None,
207
+ "detail": duel.get("detail"),
208
+ "source_file": str(source_path),
209
+ }
210
+ async with manifest_lock:
211
+ manifest_fh.write(json.dumps(record) + "\n")
212
+
213
+ async with stats.lock:
214
+ stats.duel_records_indexed += 1
215
+
216
+
217
+ async def main_async(args: argparse.Namespace) -> None:
218
+ rounds_dir = Path(args.rounds_dir)
219
+ out_dir = Path(args.out_dir)
220
+ out_dir.mkdir(parents=True, exist_ok=True)
221
+
222
+ duel_files = find_duel_files(rounds_dir, args.min_round, args.max_round)
223
+ print(f"Found {len(duel_files)} duels_*.json files in rounds [{args.min_round}, {args.max_round}]")
224
+ if not duel_files:
225
+ print("Nothing to do — check --rounds-dir.")
226
+ return
227
+
228
+ stats = ScrapeStats()
229
+ sem = asyncio.Semaphore(args.concurrency)
230
+ manifest_path = out_dir / "duels_index.jsonl"
231
+ manifest_lock = asyncio.Lock()
232
+
233
+ async with httpx.AsyncClient(headers={"User-Agent": "coder-training-scraper/1.0"}) as client:
234
+ # "w", not "a": downloaded FILES are safely re-run-idempotent (fetch()
235
+ # skips anything already on disk), but the manifest itself is not —
236
+ # appending on every run would duplicate a row for every already-
237
+ # indexed duel each time this script is re-invoked (e.g. to pick up
238
+ # new rounds, or after an interrupted run gets restarted), silently
239
+ # inflating the dataset with repeated examples. Rebuilding the
240
+ # manifest fresh each run is cheap (local JSON re-scan + fast on-disk
241
+ # existence checks, no network cost for anything already cached) and
242
+ # is what actually makes the whole run idempotent, not just the
243
+ # downloads.
244
+ with open(manifest_path, "w") as manifest_fh:
245
+ file_tasks = [
246
+ process_duel_file(
247
+ rnd, path, client, out_dir, sem, stats,
248
+ args.download_images, manifest_fh, manifest_lock,
249
+ )
250
+ for rnd, path in duel_files
251
+ ]
252
+ # Chunk so we don't schedule everything at once for huge archives
253
+ chunk = 50
254
+ for i in range(0, len(file_tasks), chunk):
255
+ await asyncio.gather(*file_tasks[i: i + chunk])
256
+ print(
257
+ f" [{min(i + chunk, len(file_tasks))}/{len(file_tasks)} files] "
258
+ f"records seen={stats.duel_records_seen} indexed={stats.duel_records_indexed} "
259
+ f"draws_skipped={stats.duel_records_skipped_draw} "
260
+ f"downloads(ok={stats.downloads_ok} cached={stats.downloads_cached} failed={stats.downloads_failed})",
261
+ flush=True,
262
+ )
263
+
264
+ print("\nDone.")
265
+ print(f" duel files processed: {stats.duel_files_seen}")
266
+ print(f" duel records seen: {stats.duel_records_seen}")
267
+ print(f" duel records indexed (usable pairs): {stats.duel_records_indexed}")
268
+ print(f" draws/skipped (no preference signal): {stats.duel_records_skipped_draw}")
269
+ print(f" downloads: {stats.downloads_ok} new, {stats.downloads_cached} cached, {stats.downloads_failed} failed")
270
+ print(f" manifest: {manifest_path}")
271
+
272
+
273
+ def main() -> None:
274
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
275
+ p.add_argument("--rounds-dir", required=True, help="Path to 404-active-competition/rounds")
276
+ p.add_argument("--out-dir", default="./archive", help="Where to store downloaded files + manifest")
277
+ p.add_argument("--min-round", type=int, default=0)
278
+ p.add_argument("--max-round", type=int, default=999)
279
+ p.add_argument("--concurrency", type=int, default=CONCURRENCY)
280
+ p.add_argument(
281
+ "--download-images", action="store_true",
282
+ help="Also fetch left_png/right_png grid previews (not needed for SFT/DPO text training, "
283
+ "useful only if you plan to re-run our own judge for QA/extension later).",
284
+ )
285
+ args = p.parse_args()
286
+ asyncio.run(main_async(args))
287
+
288
+
289
+ if __name__ == "__main__":
290
+ main()
eval/judge_challenge.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vendored copy of the REAL validator judge — judge-service/judge_service/challenge.py
3
+ in the official 404-gen-subnet repo — not a reimplementation. Copied rather than
4
+ imported across repos so this eval script has no dependency on the
5
+ 404-gen-subnet checkout being present on the training instance (only
6
+ ../miner-submission needs to travel alongside coder-training/, for the
7
+ renderer — see self_judge_eval.py's docstring). Keep in sync by hand if the
8
+ upstream file changes; it's small and rarely touched.
9
+
10
+ This is the actual scoring function every leader in past-winner/ is
11
+ optimizing against — see past-winner/README.md's "Validator-side ground
12
+ truth" section for how that was established.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ from typing import Literal
18
+
19
+ from openai import AsyncOpenAI
20
+ from pydantic import BaseModel, Field
21
+
22
+ # Default matches the real validator's exact model string — correct if
23
+ # --judge-base-url points at whatever internal endpoint the subnet itself
24
+ # uses. If pointing at OpenRouter or another provider instead, that provider's
25
+ # catalogue slug for this model may use different casing/formatting (e.g.
26
+ # OpenRouter's other model slugs in this repo's configs are lowercase,
27
+ # "org/model-name" style) — verify the exact string against your provider's
28
+ # model list rather than assuming this default resolves there. It was
29
+ # previously hardcoded and unreachable from the CLI; self_judge_eval.py's
30
+ # --judge-model now actually threads through to ask_judge()/evaluate_duel().
31
+ MODEL = "zai-org/GLM-4.1V-9B-Thinking"
32
+ TEMPERATURE = 0.0
33
+ MAX_TOKENS = 1024
34
+ SYSTEM_PROMPT = """
35
+ You are a specialized 3D model evaluation system.
36
+ Analyze visual quality and prompt adherence with expert precision.
37
+ Always respond with valid JSON only."""
38
+ USER_PROMPT_IMAGE = """Does each 3D model match the image prompt?
39
+
40
+ Penalty 0-10:
41
+ 0 = Perfect match
42
+ 3 = Minor issues (slight shape differences, missing small details)
43
+ 5 = Moderate issues (wrong style, significant details missing)
44
+ 7 = Major issues (wrong category but related, e.g. chair vs stool)
45
+ 10 = Completely wrong object
46
+
47
+ Output: {"penalty_1": <0-10>, "penalty_2": <0-10>, "issues": "<brief>"}"""
48
+
49
+
50
+ class JudgeResponse(BaseModel):
51
+ penalty_1: int
52
+ penalty_2: int
53
+ issues: str
54
+
55
+
56
+ class DuelResult(BaseModel):
57
+ outcome: Literal[-1, 0, 1] = Field(..., description="-1 = left wins, 0 = draw, 1 = right wins")
58
+ issues: str
59
+
60
+
61
+ async def ask_judge(
62
+ client: AsyncOpenAI, prompt_url: str, left_url: str, right_url: str, seed: int, model: str = MODEL,
63
+ ) -> JudgeResponse:
64
+ messages = [
65
+ {"role": "system", "content": SYSTEM_PROMPT},
66
+ {
67
+ "role": "user",
68
+ "content": [
69
+ {"type": "text", "text": "Image prompt to generate 3D model:"},
70
+ {"type": "image_url", "image_url": {"url": prompt_url}},
71
+ {"type": "text", "text": "First 3D model (4 different views):"},
72
+ {"type": "image_url", "image_url": {"url": left_url}},
73
+ {"type": "text", "text": "Second 3D model (4 different views):"},
74
+ {"type": "image_url", "image_url": {"url": right_url}},
75
+ {"type": "text", "text": USER_PROMPT_IMAGE},
76
+ ],
77
+ },
78
+ ]
79
+ response_format = {
80
+ "type": "json_schema",
81
+ "json_schema": {"name": "judge-response", "schema": JudgeResponse.model_json_schema()},
82
+ }
83
+ completion = await client.chat.completions.create(
84
+ model=model, messages=messages, temperature=TEMPERATURE,
85
+ max_tokens=MAX_TOKENS, response_format=response_format, seed=seed,
86
+ )
87
+ return JudgeResponse.model_validate_json(completion.choices[0].message.content)
88
+
89
+
90
+ async def evaluate_duel(
91
+ client: AsyncOpenAI, prompt_url: str, left_url: str, right_url: str, seed: int, model: str = MODEL,
92
+ ) -> DuelResult:
93
+ """Position-balanced duel: two calls with left/right swapped, averaged."""
94
+ try:
95
+ result_1, result_2 = await asyncio.gather(
96
+ ask_judge(client, prompt_url, left_url, right_url, seed, model=model),
97
+ ask_judge(client, prompt_url, right_url, left_url, seed, model=model),
98
+ )
99
+ left_penalty = (result_1.penalty_1 + result_2.penalty_2) / 2
100
+ right_penalty = (result_1.penalty_2 + result_2.penalty_1) / 2
101
+
102
+ if abs(left_penalty - right_penalty) <= 1:
103
+ outcome: Literal[-1, 0, 1] = 0
104
+ elif left_penalty < right_penalty:
105
+ outcome = -1
106
+ else:
107
+ outcome = 1
108
+
109
+ return DuelResult(outcome=outcome, issues=result_1.issues)
110
+ except Exception as e:
111
+ return DuelResult(outcome=0, issues=f"Internal error: {e}")
eval/self_judge_eval.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Phase 3 of CODER_TRAINING_PLAN.md: after each checkpoint, generate on the
4
+ held-out (eval-split) prompts and judge against the REAL archived winner for
5
+ those exact prompts — not just our own baseline, actual ground truth from
6
+ the competition — using the same judge the live competition uses
7
+ (judge-service/challenge.py's evaluate_duel: small VLM, 0-10 penalty,
8
+ position-swapped double-call — see past-winner/README.md for why this is
9
+ the one that actually matters, not the more elaborate internal S1-S4
10
+ tournament in modules/judge/multi_stage.py).
11
+
12
+ VERIFY BEFORE TRUSTING THIS SCRIPT: the renderer integration (RendererModule
13
+ + PipelineTask, reused from ../miner-submission/pipeline_service) was written
14
+ by reading that module's source, not by running it — there's no GPU in the
15
+ environment this was written in to test against. Check task.rendered_png
16
+ actually gets populated by renderer.process(task) before trusting eval
17
+ numbers; see the try/except around render_js below for where this would surface.
18
+
19
+ Usage (run from coder-training/, not eval/ — see --preference-jsonl's help):
20
+ python eval/self_judge_eval.py \
21
+ --checkpoint-base-url http://localhost:8000/v1 --checkpoint-model <served-name> \
22
+ --judge-base-url https://openrouter.ai/api/v1 \
23
+ --judge-model zai-org/glm-4.1v-9b-thinking \
24
+ --judge-api-key-env OPENROUTER_API_KEY \
25
+ --n-prompts 64
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import asyncio
31
+ import base64
32
+ import json
33
+ import os
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ # Reuse the real renderer instead of reimplementing it — see
38
+ # miner-submission/README.md for why that repo is the reference. The judge
39
+ # (judge_challenge.py, next to this file) is vendored rather than imported
40
+ # across repos — see that file's docstring for why.
41
+ sys.path.insert(0, str(Path(__file__).resolve().parent)) # for judge_challenge.py
42
+
43
+ from openai import AsyncOpenAI # noqa: E402
44
+ from judge_challenge import evaluate_duel # noqa: E402
45
+
46
+ try:
47
+ import wandb
48
+ except ImportError:
49
+ wandb = None
50
+
51
+
52
+ def chat_text(message: dict) -> str:
53
+ """Extract plain text from a {"role": ..., "content": ...} message where
54
+ content may be a plain string or TRL/VLM-style [{"type": "text", ...}] list
55
+ (see data/build_datasets.py's chat_completion())."""
56
+ content = message["content"]
57
+ if isinstance(content, str):
58
+ return content
59
+ return "".join(part.get("text", "") for part in content if isinstance(part, dict))
60
+
61
+
62
+ def load_eval_rows(preference_jsonl: str, n_prompts: int | None) -> list[dict]:
63
+ rows = []
64
+ with open(preference_jsonl) as f:
65
+ for line in f:
66
+ row = json.loads(line)
67
+ if row.get("split") == "eval":
68
+ rows.append(row)
69
+ if n_prompts:
70
+ rows = rows[:n_prompts]
71
+ return rows
72
+
73
+
74
+ async def generate_js(client: AsyncOpenAI, model: str, image_path: str, max_tokens: int) -> str | None:
75
+ """Ask the checkpoint under test for a Three.js module given the reference image."""
76
+ with open(image_path, "rb") as f:
77
+ b64 = base64.b64encode(f.read()).decode()
78
+ resp = await client.chat.completions.create(
79
+ model=model,
80
+ max_tokens=max_tokens,
81
+ temperature=0.6,
82
+ messages=[
83
+ {
84
+ "role": "system",
85
+ "content": (
86
+ "You are a Three.js code generator. Given a reference image of an object, "
87
+ "output a single JavaScript module: "
88
+ "`export default function generate(THREE) { ... }` that procedurally "
89
+ "constructs a Three.js Object3D matching the reference. "
90
+ "Respond with JavaScript code only."
91
+ ),
92
+ },
93
+ {
94
+ "role": "user",
95
+ "content": [
96
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
97
+ {"type": "text", "text": "Generate a Three.js module for the object in this reference image."},
98
+ ],
99
+ },
100
+ ],
101
+ )
102
+ return resp.choices[0].message.content
103
+
104
+
105
+ async def render_js(renderer, stem: str, image_url: str, js_code: str) -> bytes | None:
106
+ from pipeline.task import PipelineTask # local import: only exists once sys.path is patched above
107
+
108
+ task = PipelineTask(stem=stem, image_url=image_url, js_code=js_code)
109
+ task = await renderer.process(task)
110
+ if task.render_errors:
111
+ print(f" [{stem}] render errors: {task.render_errors}")
112
+ return task.rendered_png
113
+
114
+
115
+ def png_to_data_url(png_bytes: bytes) -> str:
116
+ return "data:image/png;base64," + base64.b64encode(png_bytes).decode()
117
+
118
+
119
+ async def main_async(args: argparse.Namespace) -> None:
120
+ sys.path.insert(0, args.pipeline_service_dir)
121
+ from modules.renderer.module import RendererModule # local import, needs the path patch above
122
+ from config.settings import settings as pipeline_settings
123
+
124
+ rows = load_eval_rows(args.preference_jsonl, args.n_prompts)
125
+ print(f"Loaded {len(rows)} held-out eval rows")
126
+ if not rows:
127
+ print("No eval rows found — did data/build_datasets.py run? Is --preference-jsonl correct?")
128
+ return
129
+
130
+ checkpoint_client = AsyncOpenAI(
131
+ base_url=args.checkpoint_base_url,
132
+ api_key=os.environ.get(args.checkpoint_api_key_env, "local"),
133
+ )
134
+ if args.judge_api_key_env not in os.environ:
135
+ raise SystemExit(
136
+ f"${args.judge_api_key_env} is not set — export it before running, or pass "
137
+ f"--judge-api-key-env to point at a different variable."
138
+ )
139
+ judge_client = AsyncOpenAI(
140
+ base_url=args.judge_base_url,
141
+ api_key=os.environ[args.judge_api_key_env],
142
+ )
143
+
144
+ renderer = RendererModule(pipeline_settings.renderer)
145
+ await renderer.startup()
146
+
147
+ if wandb is not None and args.wandb:
148
+ wandb.init(project=args.wandb_project, group="eval", name=args.run_name, job_type="eval")
149
+
150
+ wins = losses = draws = errors = 0
151
+ try:
152
+ for i, row in enumerate(rows):
153
+ stem = row.get("name", f"eval_{i}")
154
+ image_path = row["images"][0]
155
+ archived_winner_js = chat_text(row["chosen"][0])
156
+
157
+ candidate_js = await generate_js(checkpoint_client, args.checkpoint_model, image_path, args.max_tokens)
158
+ if not candidate_js:
159
+ errors += 1
160
+ continue
161
+
162
+ candidate_png, archived_png = await asyncio.gather(
163
+ render_js(renderer, f"{stem}_candidate", image_path, candidate_js),
164
+ render_js(renderer, f"{stem}_archived", image_path, archived_winner_js),
165
+ )
166
+ if not candidate_png or not archived_png:
167
+ errors += 1
168
+ continue
169
+
170
+ with open(image_path, "rb") as f:
171
+ prompt_data_url = "data:image/png;base64," + base64.b64encode(f.read()).decode()
172
+
173
+ result = await evaluate_duel(
174
+ client=judge_client,
175
+ prompt_url=prompt_data_url,
176
+ left_url=png_to_data_url(archived_png), # archived ground-truth winner = left
177
+ right_url=png_to_data_url(candidate_png), # our checkpoint's new generation = right
178
+ seed=42,
179
+ model=args.judge_model,
180
+ )
181
+ if result.outcome > 0:
182
+ wins += 1
183
+ elif result.outcome < 0:
184
+ losses += 1
185
+ else:
186
+ draws += 1
187
+
188
+ n_done = wins + losses + draws
189
+ if n_done % 10 == 0:
190
+ print(f" [{n_done}/{len(rows)}] win={wins} loss={losses} draw={draws} err={errors}")
191
+
192
+ finally:
193
+ await renderer.shutdown()
194
+
195
+ n_judged = wins + losses + draws
196
+ win_rate = wins / n_judged if n_judged else 0.0
197
+ print(f"\nResult: {wins}W / {losses}L / {draws}D / {errors} errors — win_rate={win_rate:.1%}")
198
+ print("win_rate > 50% means this checkpoint beats the ARCHIVED REAL WINNERS on held-out prompts —")
199
+ print("that's the bar worth caring about, not just 'better than the base model'.")
200
+
201
+ if wandb is not None and args.wandb:
202
+ wandb.log({
203
+ "eval/win_rate_vs_archived_winner": win_rate,
204
+ "eval/wins": wins, "eval/losses": losses, "eval/draws": draws, "eval/errors": errors,
205
+ })
206
+ wandb.finish()
207
+
208
+
209
+ def main() -> None:
210
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
211
+ p.add_argument(
212
+ "--preference-jsonl", default="./datasets/preference.jsonl",
213
+ help="Relative to cwd. README.md documents running this script as "
214
+ "`python eval/self_judge_eval.py` from coder-training/ (not `cd eval/` first) — "
215
+ "this default, and the image paths stored inside the JSONL by "
216
+ "build_datasets.py, both assume that cwd.",
217
+ )
218
+ p.add_argument("--n-prompts", type=int, default=64, help="Cap eval set size — full held-out set can be large")
219
+ p.add_argument(
220
+ "--pipeline-service-dir",
221
+ default=str(Path(__file__).resolve().parents[2] / "miner-submission" / "pipeline_service"),
222
+ help="Path to a pipeline_service/ checkout, for its RendererModule. Default assumes "
223
+ "coder-training/ and miner-submission/ were scp'd as siblings under the same parent dir.",
224
+ )
225
+
226
+ p.add_argument("--checkpoint-base-url", required=True, help="OpenAI-compatible endpoint serving the checkpoint under test (e.g. a vLLM instance)")
227
+ p.add_argument("--checkpoint-model", required=True)
228
+ p.add_argument("--checkpoint-api-key-env", default="CHECKPOINT_API_KEY")
229
+ p.add_argument("--max-tokens", type=int, default=24576)
230
+
231
+ p.add_argument("--judge-base-url", default="https://openrouter.ai/api/v1")
232
+ p.add_argument("--judge-model", default="zai-org/glm-4.1v-9b-thinking")
233
+ p.add_argument("--judge-api-key-env", default="OPENROUTER_API_KEY")
234
+
235
+ p.add_argument("--wandb", action="store_true")
236
+ p.add_argument("--wandb-project", default="404-coder-training")
237
+ p.add_argument("--run-name", default="self-judge-eval")
238
+
239
+ args = p.parse_args()
240
+ asyncio.run(main_async(args))
241
+
242
+
243
+ if __name__ == "__main__":
244
+ main()
logs/pipeline.log ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2026-07-31 15:24:26 | INFO | modules.renderer.module:startup:51 | [RENDERER] starting 8 sidecar(s) | node=node runner=/Users/xavier/bittensor/404-gen-subnet/404-agent/miner-submission/pipeline_service/modules/renderer/render_service/render_runner.mjs base_port=8003 cwd=/Users/xavier/bittensor/404-gen-subnet/404-agent/miner-submission/pipeline_service/modules/renderer/render_service pool_size_per_sidecar=2
2
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #1/stdout] [render_runner] starting static server...
3
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #2/stdout] [render_runner] starting static server...
4
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #6/stdout] [render_runner] starting static server...
5
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #1/stdout] [render_runner] launching browser...
6
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #2/stdout] [render_runner] launching browser...
7
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #7/stdout] [render_runner] starting static server...
8
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #6/stdout] [render_runner] launching browser...
9
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #2/stdout] [render_runner] listening on 127.0.0.1:8005
10
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #1/stdout] [render_runner] listening on 127.0.0.1:8004
11
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #4/stdout] [render_runner] starting static server...
12
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #6/stdout] [render_runner] listening on 127.0.0.1:8009
13
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] starting static server...
14
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #7/stdout] [render_runner] launching browser...
15
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #4/stdout] [render_runner] launching browser...
16
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] launching browser...
17
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #7/stdout] [render_runner] listening on 127.0.0.1:8010
18
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #4/stdout] [render_runner] listening on 127.0.0.1:8007
19
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] listening on 127.0.0.1:8003
20
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #5/stdout] [render_runner] starting static server...
21
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #3/stdout] [render_runner] starting static server...
22
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #5/stdout] [render_runner] launching browser...
23
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #5/stdout] [render_runner] listening on 127.0.0.1:8008
24
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #3/stdout] [render_runner] launching browser...
25
+ 2026-07-31 15:24:26 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #3/stdout] [render_runner] listening on 127.0.0.1:8006
26
+ 2026-07-31 15:24:33 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #4/stdout] [render_runner] ready
27
+ 2026-07-31 15:24:34 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #5/stdout] [render_runner] ready
28
+ 2026-07-31 15:24:34 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #7/stdout] [render_runner] ready
29
+ 2026-07-31 15:24:34 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #2/stdout] [render_runner] ready
30
+ 2026-07-31 15:24:34 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] ready
31
+ 2026-07-31 15:24:34 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #6/stdout] [render_runner] ready
32
+ 2026-07-31 15:24:34 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #3/stdout] [render_runner] ready
33
+ 2026-07-31 15:24:34 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #5 ready on port 8008
34
+ 2026-07-31 15:24:34 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #0 ready on port 8003
35
+ 2026-07-31 15:24:34 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #4 ready on port 8007
36
+ 2026-07-31 15:24:34 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #7 ready on port 8010
37
+ 2026-07-31 15:24:34 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #3 ready on port 8006
38
+ 2026-07-31 15:24:34 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #2 ready on port 8005
39
+ 2026-07-31 15:24:34 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #6 ready on port 8009
40
+ 2026-07-31 15:25:58 | INFO | modules.renderer.module:startup:51 | [RENDERER] starting 1 sidecar(s) | node=node runner=/Users/xavier/bittensor/404-gen-subnet/404-agent/miner-submission/pipeline_service/modules/renderer/render_service/render_runner.mjs base_port=8003 cwd=/Users/xavier/bittensor/404-gen-subnet/404-agent/miner-submission/pipeline_service/modules/renderer/render_service pool_size_per_sidecar=1
41
+ 2026-07-31 15:25:58 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #0 ready on port 8003
42
+ 2026-07-31 15:25:58 | INFO | modules.renderer.module:startup:65 | [RENDERER] 1 sidecar(s) ready, total slots=1
43
+ 2026-07-31 15:25:58 | INFO | modules.renderer.module:process:278 | [RENDERER] 'smoke' start | sidecar=#0 | path=code | js_code=175 bytes
44
+ 2026-07-31 15:25:58 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] starting static server...
45
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr] [render_runner] fatal startup error: Error: listen EADDRINUSE: address already in use 127.0.0.1:3000
46
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr]  at Server.setupListenHandle [as _listen2] (node:net:1940:16)
47
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr]  at listenInCluster (node:net:1997:12)
48
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr]  at node:net:2206:7
49
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr]  at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
50
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr] code: 'EADDRINUSE',
51
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr] errno: -48,
52
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr] syscall: 'listen',
53
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr] address: '127.0.0.1',
54
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr] port: 3000
55
+ 2026-07-31 15:25:58 | WARNING | modules.renderer.module:_pipe_logger:422 | [renderer-sidecar #0/stderr] }
56
+ 2026-07-31 15:26:00 | INFO | modules.renderer.module:process:300 | [RENDERER] 'smoke' PASS sidecar=#0 | png=48889B render=1.8s
57
+ 2026-07-31 15:28:25 | INFO | modules.renderer.module:startup:51 | [RENDERER] starting 1 sidecar(s) | node=node runner=/Users/xavier/bittensor/404-gen-subnet/404-agent/miner-submission/pipeline_service/modules/renderer/render_service/render_runner.mjs base_port=8046 cwd=/Users/xavier/bittensor/404-gen-subnet/404-agent/miner-submission/pipeline_service/modules/renderer/render_service pool_size_per_sidecar=1
58
+ 2026-07-31 15:28:25 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] starting static server...
59
+ 2026-07-31 15:28:25 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] launching browser...
60
+ 2026-07-31 15:28:25 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] listening on 127.0.0.1:8046
61
+ 2026-07-31 15:28:27 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] ready
62
+ 2026-07-31 15:28:27 | INFO | modules.renderer.module:_spawn_sidecar:99 | [RENDERER] sidecar #0 ready on port 8046
63
+ 2026-07-31 15:28:27 | INFO | modules.renderer.module:startup:65 | [RENDERER] 1 sidecar(s) ready, total slots=1
64
+ 2026-07-31 15:28:36 | INFO | modules.renderer.module:shutdown:210 | [RENDERER] terminating sidecar #0
65
+ 2026-07-31 15:28:36 | DEBUG | modules.renderer.module:_pipe_logger:424 | [renderer-sidecar #0/stdout] [render_runner] SIGTERM received, shutting down...
muon.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Muon–AdamW hybrid optimizer for QLoRA fine-tuning (opt-in).
2
+
3
+ Muon (Jordan et al., https://kellerjordan.github.io/posts/muon/) optimizes 2D
4
+ hidden weight matrices by orthogonalizing the SGD-momentum update via a
5
+ Newton–Schulz iteration (equalizing the update's singular values); scalars,
6
+ 1D params, embeddings, and the LM head stay on AdamW. This module vendors the
7
+ canonical single-GPU hybrid — one optimizer with per-group routing — so it can
8
+ be handed to HF Trainer as a single `self.optimizer`.
9
+
10
+ WHY THIS IS OFFERED FOR *OUR* SETUP (and the honest caveat):
11
+ * "Can Muon Fine-tune Adam-Pretrained Models?" (ICML 2026, arXiv 2605.10468)
12
+ finds a genuine optimizer-mismatch penalty when you fine-tune an
13
+ Adam-pretrained model with Muon — BUT that **LoRA gives implicit
14
+ robustness** to that mismatch (the update is confined to a low-rank
15
+ subspace), making Muon+LoRA "stable and competitive even at suboptimal
16
+ learning rates." That's exactly our case (QLoRA on an Adam-pretrained
17
+ Qwen3.5), which is why this is worth trying.
18
+ * CAVEAT, stated plainly: applying Muon to the LoRA factors A and B as if
19
+ they were ordinary weight matrices is **parametrization-dependent** — it
20
+ is NOT identical to orthogonalizing the effective ΔW = B·A update.
21
+ "LoRA meets Riemannion" (ICLR 2026, arXiv 2507.12142) shows the
22
+ parametrization-invariant (Riemannian) version and that the naive form is
23
+ a heuristic. We implement the naive form here (what nearly every practical
24
+ Muon+LoRA impl uses, and what the ICML paper evaluates) — treat it as an
25
+ A/B experiment against paged_adamw_8bit, not a guaranteed win. Validate on
26
+ the smoke test + held-out eval before trusting it on a long run.
27
+
28
+ Prefer torch.optim.Muon when available (PyTorch >= 2.9 ships an official one),
29
+ but it is Muon-only; the hybrid routing (Muon for 2D, AdamW for the rest) is
30
+ what HF Trainer needs as a single optimizer, so we always use the vendored
31
+ SingleDeviceMuonWithAuxAdam here for a uniform, self-contained path.
32
+
33
+ Vendored faithfully from Keller Jordan's reference
34
+ (https://github.com/KellerJordan/Muon/blob/master/muon.py), single-device
35
+ variant (no torch.distributed collectives — correct for our single-GPU box).
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import torch
40
+
41
+
42
+ def zeropower_via_newtonschulz5(G: torch.Tensor, steps: int = 5) -> torch.Tensor:
43
+ """Quintic Newton–Schulz iteration for the orthogonal factor of G. Runs
44
+ stably in bfloat16 (Jordan's coefficients, tuned to push singular values
45
+ toward 1 without converging exactly, which empirically trains better)."""
46
+ assert G.ndim >= 2
47
+ a, b, c = (3.4445, -4.7750, 2.0315)
48
+ X = G.bfloat16()
49
+ if G.size(-2) > G.size(-1):
50
+ X = X.mT
51
+ X = X / (X.norm(dim=(-2, -1), keepdim=True) + 1e-7)
52
+ for _ in range(steps):
53
+ A = X @ X.mT
54
+ B = b * A + c * A @ A
55
+ X = a * X + B @ X
56
+ if G.size(-2) > G.size(-1):
57
+ X = X.mT
58
+ return X
59
+
60
+
61
+ def _muon_update(grad, momentum, beta=0.95, ns_steps=5, nesterov=True):
62
+ momentum.lerp_(grad, 1 - beta)
63
+ update = grad.lerp_(momentum, beta) if nesterov else momentum
64
+ if update.ndim == 4: # conv filters -> flatten to 2D
65
+ update = update.view(len(update), -1)
66
+ update = zeropower_via_newtonschulz5(update, steps=ns_steps)
67
+ # RMS-match the update magnitude across differently-shaped matrices.
68
+ update *= max(1.0, grad.size(-2) / grad.size(-1)) ** 0.5
69
+ return update
70
+
71
+
72
+ def _adam_update(grad, buf1, buf2, step, betas, eps):
73
+ # Canonical Adam: bias-correct BOTH moments, then add eps to the
74
+ # bias-corrected second-moment sqrt (matches PyTorch Adam and Keller
75
+ # Jordan's reference; do not fold eps onto the raw sqrt — that shifts the
76
+ # denominator by a step-dependent factor early in training).
77
+ buf1.lerp_(grad, 1 - betas[0])
78
+ buf2.lerp_(grad.square(), 1 - betas[1])
79
+ buf1c = buf1 / (1 - betas[0] ** step)
80
+ buf2c = buf2 / (1 - betas[1] ** step)
81
+ return buf1c / (buf2c.sqrt() + eps)
82
+
83
+
84
+ class SingleDeviceMuonWithAuxAdam(torch.optim.Optimizer):
85
+ """One optimizer, two update rules routed per param-group via `use_muon`.
86
+
87
+ Build it with explicit param groups, e.g.:
88
+ SingleDeviceMuonWithAuxAdam([
89
+ dict(params=muon_params, use_muon=True, lr=1e-4, momentum=0.95, weight_decay=0.0),
90
+ dict(params=adam_params, use_muon=False, lr=1e-4, betas=(0.9,0.95), eps=1e-8, weight_decay=0.0),
91
+ ])
92
+ """
93
+
94
+ def __init__(self, param_groups):
95
+ for g in param_groups:
96
+ if g.get("use_muon"):
97
+ g.setdefault("lr", 1e-4)
98
+ g.setdefault("momentum", 0.95)
99
+ g.setdefault("weight_decay", 0.0)
100
+ g.setdefault("ns_steps", 5)
101
+ else:
102
+ g.setdefault("lr", 1e-4)
103
+ g.setdefault("betas", (0.9, 0.95))
104
+ g.setdefault("eps", 1e-8)
105
+ g.setdefault("weight_decay", 0.0)
106
+ super().__init__(param_groups, {})
107
+
108
+ @torch.no_grad()
109
+ def step(self, closure=None):
110
+ loss = closure() if closure is not None else None
111
+ for group in self.param_groups:
112
+ if group["use_muon"]:
113
+ for p in group["params"]:
114
+ if p.grad is None:
115
+ continue
116
+ state = self.state[p]
117
+ if "momentum_buffer" not in state:
118
+ state["momentum_buffer"] = torch.zeros_like(p)
119
+ update = _muon_update(
120
+ p.grad, state["momentum_buffer"],
121
+ beta=group["momentum"], ns_steps=group["ns_steps"],
122
+ )
123
+ if group["weight_decay"]:
124
+ p.mul_(1 - group["lr"] * group["weight_decay"])
125
+ p.add_(update.reshape(p.shape).to(p.dtype), alpha=-group["lr"])
126
+ else:
127
+ for p in group["params"]:
128
+ if p.grad is None:
129
+ continue
130
+ state = self.state[p]
131
+ if "exp_avg" not in state:
132
+ state["exp_avg"] = torch.zeros_like(p)
133
+ state["exp_avg_sq"] = torch.zeros_like(p)
134
+ state["step"] = 0
135
+ state["step"] += 1
136
+ update = _adam_update(
137
+ p.grad, state["exp_avg"], state["exp_avg_sq"],
138
+ state["step"], group["betas"], group["eps"],
139
+ )
140
+ if group["weight_decay"]:
141
+ p.mul_(1 - group["lr"] * group["weight_decay"])
142
+ p.add_(update.to(p.dtype), alpha=-group["lr"])
143
+ return loss
144
+
145
+
146
+ # Names that should stay on AdamW even though they may be 2D.
147
+ _ADAM_NAME_HINTS = ("embed", "wte", "wpe", "lm_head", "embed_tokens", "shared")
148
+
149
+
150
+ def _is_adam_param(name: str, p: torch.Tensor) -> bool:
151
+ if p.ndim < 2:
152
+ return True # biases, norms, scalars, 1D
153
+ lname = name.lower()
154
+ return any(h in lname for h in _ADAM_NAME_HINTS)
155
+
156
+
157
+ def build_muon_adamw_optimizer(model, cfg: dict) -> SingleDeviceMuonWithAuxAdam:
158
+ """Split a model's *trainable* params into a Muon group (2D hidden
159
+ matrices — for QLoRA these are the lora_A/lora_B factors) and an AdamW
160
+ group (everything 1D / embedding-ish), then build the hybrid optimizer.
161
+
162
+ `cfg` is the config's `training.muon` block (all keys optional):
163
+ lr, momentum, weight_decay, ns_steps (Muon group)
164
+ adamw_lr, adamw_betas, adamw_eps, adamw_weight_decay (AdamW group)
165
+ Muon's lr defaults to the AdamW/base lr for LoRA safety (the ICML paper's
166
+ robustness result) — tune training.muon.lr up once a baseline works.
167
+ Proven reference values from a production Muon+LoRA miner (SN102, LoRA
168
+ r=128): momentum=0.95, Muon-group weight_decay=0.1, muon lr≈1e-3, and a
169
+ much lower lr (~1e-5) for the AdamW scalar group. Muon's native full-FT
170
+ range is ~0.01–0.02; LoRA tolerates a wide band.
171
+ """
172
+ muon_params, adam_params = [], []
173
+ for n, p in model.named_parameters():
174
+ if not p.requires_grad:
175
+ continue
176
+ (adam_params if _is_adam_param(n, p) else muon_params).append(p)
177
+
178
+ # Muon's Newton-Schulz momentum is unstable if the trainable parameter
179
+ # itself is bf16 — a proven production Muon+LoRA setup (SN102 miner) upcasts
180
+ # trainable params to fp32 before optimizing. PEFT already keeps LoRA
181
+ # adapters in fp32 under a bf16 base, so this normally holds for free; warn
182
+ # (don't mutate — the Trainer owns dtypes) if any Muon param is low-precision.
183
+ _lowp = [p for p in muon_params if p.dtype in (torch.bfloat16, torch.float16)]
184
+ if _lowp:
185
+ print(f"[muon] WARNING: {len(_lowp)} Muon param(s) are {_lowp[0].dtype} — "
186
+ "Newton-Schulz is more stable in fp32. If training is unstable, "
187
+ "ensure LoRA adapters are fp32 (PEFT's default).")
188
+
189
+ base_lr = cfg.get("lr", 1e-4)
190
+ groups = []
191
+ if muon_params:
192
+ groups.append(dict(
193
+ params=muon_params, use_muon=True,
194
+ lr=cfg.get("lr", base_lr),
195
+ momentum=cfg.get("momentum", 0.95),
196
+ weight_decay=cfg.get("weight_decay", 0.0),
197
+ ns_steps=cfg.get("ns_steps", 5),
198
+ ))
199
+ if adam_params:
200
+ groups.append(dict(
201
+ params=adam_params, use_muon=False,
202
+ lr=cfg.get("adamw_lr", base_lr),
203
+ betas=tuple(cfg.get("adamw_betas", (0.9, 0.95))),
204
+ eps=cfg.get("adamw_eps", 1e-8),
205
+ weight_decay=cfg.get("adamw_weight_decay", 0.0),
206
+ ))
207
+ if not groups:
208
+ raise ValueError("Muon optimizer: model has no trainable parameters.")
209
+ n_muon = sum(p.numel() for p in muon_params)
210
+ n_adam = sum(p.numel() for p in adam_params)
211
+ print(f"[muon] {len(muon_params)} matrices ({n_muon:,} params) on Muon | "
212
+ f"{len(adam_params)} tensors ({n_adam:,} params) on AdamW")
213
+ return SingleDeviceMuonWithAuxAdam(groups)
preference-optimization-sft-6000-a100-to-tinker.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core training stack
2
+ torch>=2.4.0
3
+ transformers>=4.46.0
4
+ accelerate>=1.0.0
5
+ trl>=0.12.0
6
+ peft>=0.13.0
7
+ bitsandbytes>=0.44.0 # 4-bit QLoRA
8
+ datasets>=3.0.0
9
+
10
+ # Multimodal I/O
11
+ pillow>=10.0.0
12
+ httpx>=0.27.0 # data/scrape_duels.py
13
+ torchvision # AutoProcessor's composite loading for this checkpoint family pulls
14
+ # in a Qwen3VLVideoProcessor sub-component (it's natively an omni-modal architecture, video
15
+ # processor included, even though we only feed it images) that hard-requires torchvision — found
16
+ # by actually running the pipeline (ImportError, not a guess), not by inspection beforehand.
17
+
18
+ # Experiment tracking
19
+ wandb>=0.18.0
20
+
21
+ # Config
22
+ pyyaml>=6.0
23
+
24
+ # NOTE: Tooony133/Qwen-3.6-27B-* checkpoints report model_type "qwen3_5"
25
+ # (architecture Qwen3_5ForConditionalGeneration) per the HF API. Verify this
26
+ # is supported by whatever `transformers` version you land on BEFORE
27
+ # launching a real run — pin a version known to include it, or install
28
+ # transformers from source/main if it's too new for the latest PyPI release.
29
+ # This is the single biggest "verify on first run" risk in this repo; see
30
+ # README.md's pre-flight checklist.
scrape_run.log ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Found 2576 duels_*.json files in rounds [0, 29]
2
+ [50/2576 files] records seen=6400 indexed=5242 draws_skipped=1155 downloads(ok=5558 cached=10168 failed=0)
3
+ [100/2576 files] records seen=12800 indexed=10151 draws_skipped=2606 downloads(ok=7774 cached=22679 failed=0)
4
+ [150/2576 files] records seen=19200 indexed=15018 draws_skipped=4043 downloads(ok=9127 cached=35927 failed=0)
5
+ [200/2576 files] records seen=25600 indexed=19971 draws_skipped=5438 downloads(ok=10252 cached=49661 failed=0)
6
+ [250/2576 files] records seen=32000 indexed=20066 draws_skipped=7057 downloads(ok=10381 cached=54408 failed=9182)
7
+ [300/2576 files] records seen=38400 indexed=20066 draws_skipped=8282 downloads(ok=10381 cached=59462 failed=19290)
8
+ [350/2576 files] records seen=44800 indexed=20066 draws_skipped=9389 downloads(ok=10381 cached=64672 failed=29710)
9
+ [400/2576 files] records seen=51200 indexed=20066 draws_skipped=10499 downloads(ok=10381 cached=69948 failed=40262)
10
+ [450/2576 files] records seen=57600 indexed=20066 draws_skipped=11339 downloads(ok=10381 cached=73683 failed=47732)
11
+ [500/2576 files] records seen=64000 indexed=20066 draws_skipped=11583 downloads(ok=10508 cached=74609 failed=49838)
12
+ [550/2576 files] records seen=70400 indexed=20066 draws_skipped=17290 downloads(ok=10508 cached=74918 failed=50456)
13
+ [600/2576 files] records seen=76800 indexed=20066 draws_skipped=21548 downloads(ok=10508 cached=75012 failed=50644)
14
+ [650/2576 files] records seen=83200 indexed=20066 draws_skipped=24355 downloads(ok=10508 cached=75986 failed=52592)
15
+ [700/2576 files] records seen=89600 indexed=20066 draws_skipped=29348 downloads(ok=10508 cached=75986 failed=52592)
16
+ [750/2576 files] records seen=96000 indexed=20066 draws_skipped=33330 downloads(ok=10508 cached=76484 failed=53588)
17
+ [800/2576 files] records seen=102400 indexed=20066 draws_skipped=37450 downloads(ok=10508 cached=76972 failed=54564)
18
+ [850/2576 files] records seen=108800 indexed=20066 draws_skipped=41054 downloads(ok=10508 cached=77454 failed=55528)
19
+ [900/2576 files] records seen=115200 indexed=20066 draws_skipped=42532 downloads(ok=10508 cached=78543 failed=57706)
20
+ [950/2576 files] records seen=121600 indexed=20066 draws_skipped=46202 downloads(ok=10508 cached=78842 failed=58304)
21
+ [1000/2576 files] records seen=128000 indexed=20066 draws_skipped=48928 downloads(ok=10508 cached=79700 failed=60020)
22
+ [1050/2576 files] records seen=134400 indexed=22990 draws_skipped=51958 downloads(ok=13101 cached=85879 failed=60020)
23
+ [1100/2576 files] records seen=140800 indexed=27789 draws_skipped=52736 downloads(ok=15590 cached=97787 failed=60020)
24
+ [1150/2576 files] records seen=147200 indexed=29383 draws_skipped=53621 downloads(ok=16534 cached=104976 failed=66722)
25
+ [1200/2576 files] records seen=153600 indexed=31262 draws_skipped=54636 downloads(ok=18883 cached=111584 failed=73362)
26
+ [1250/2576 files] records seen=160000 indexed=36764 draws_skipped=55526 downloads(ok=20400 cached=126573 failed=73362)
27
+ [1300/2576 files] records seen=166400 indexed=42072 draws_skipped=56475 downloads(ok=20920 cached=141977 failed=73362)
28
+ [1350/2576 files] records seen=172800 indexed=47501 draws_skipped=57343 downloads(ok=21517 cached=157667 failed=73362)
29
+ [1400/2576 files] records seen=179200 indexed=49813 draws_skipped=58559 downloads(ok=22773 cached=166215 failed=79098)
30
+ [1450/2576 files] records seen=185600 indexed=54894 draws_skipped=59878 downloads(ok=24378 cached=179853 failed=79098)
31
+ [1500/2576 files] records seen=192000 indexed=60281 draws_skipped=60884 downloads(ok=26718 cached=193674 failed=79098)
32
+ [1550/2576 files] records seen=198400 indexed=64058 draws_skipped=62059 downloads(ok=27787 cached=205188 failed=81602)
33
+ [1600/2576 files] records seen=204800 indexed=64058 draws_skipped=63133 downloads(ok=27856 cached=209727 failed=90818)
34
+ [1650/2576 files] records seen=211200 indexed=66167 draws_skipped=64193 downloads(ok=29398 cached=217477 failed=96748)
35
+ [1700/2576 files] records seen=217600 indexed=70506 draws_skipped=65101 downloads(ok=33152 cached=227057 failed=97382)
36
+ [1750/2576 files] records seen=224000 indexed=70506 draws_skipped=66124 downloads(ok=33155 cached=232226 failed=107726)
37
+ [1800/2576 files] records seen=230400 indexed=73390 draws_skipped=67413 downloads(ok=34841 cached=241201 failed=111744)
38
+ [1850/2576 files] records seen=236800 indexed=78657 draws_skipped=68546 downloads(ok=36116 cached=255727 failed=111744)
39
+ [1900/2576 files] records seen=243200 indexed=83474 draws_skipped=70112 downloads(ok=39571 cached=266723 failed=111744)
40
+ [1950/2576 files] records seen=249600 indexed=88217 draws_skipped=71769 downloads(ok=42248 cached=278275 failed=111744)
41
+ [2000/2576 files] records seen=256000 indexed=93034 draws_skipped=73352 downloads(ok=42904 cached=292070 failed=111744)
42
+ [2050/2576 files] records seen=262400 indexed=96183 draws_skipped=74668 downloads(ok=43230 cached=302952 failed=115266)
43
+ [2100/2576 files] records seen=268800 indexed=101083 draws_skipped=75474 downloads(ok=46334 cached=315018 failed=116206)
44
+ [2150/2576 files] records seen=275200 indexed=103526 draws_skipped=76429 downloads(ok=48500 cached=322822 failed=121488)
45
+ [2200/2576 files] records seen=281600 indexed=106702 draws_skipped=77325 downloads(ok=51139 cached=330714 failed=123494)
46
+ [2250/2576 files] records seen=288000 indexed=110776 draws_skipped=78290 downloads(ok=53441 cached=341983 failed=126192)
47
+ [2300/2576 files] records seen=294400 indexed=116308 draws_skipped=79039 downloads(ok=54832 cached=357188 failed=126192)
48
+ [2350/2576 files] records seen=300800 indexed=121991 draws_skipped=79746 downloads(ok=55592 cached=373477 failed=126192)
49
+ [2400/2576 files] records seen=307200 indexed=127488 draws_skipped=80523 downloads(ok=56067 cached=389493 failed=126192)
50
+ [2450/2576 files] records seen=313600 indexed=133107 draws_skipped=81294 downloads(ok=56873 cached=405544 failed=126192)
51
+ [2500/2576 files] records seen=320000 indexed=135544 draws_skipped=82285 downloads(ok=58930 cached=413540 failed=131676)
52
+ [2550/2576 files] records seen=326400 indexed=140101 draws_skipped=83817 downloads(ok=63579 cached=422562 failed=131676)
53
+ [2576/2576 files] records seen=329728 indexed=142647 draws_skipped=84599 downloads(ok=65650 cached=428129 failed=131676)
54
+
55
+ Done.
56
+ duel files processed: 2576
57
+ duel records seen: 329728
58
+ duel records indexed (usable pairs): 142647
59
+ draws/skipped (no preference signal): 84599
60
+ downloads: 65650 new, 428129 cached, 131676 failed
61
+ manifest: archive/duels_index.jsonl
scripts/run_pipeline.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Orchestrates the full pipeline end to end: [scrape -> build datasets ->]
3
+ # SFT -> preference-tune (KTO by default, see TRAINING_GUIDE.md) -> eval.
4
+ # Run scripts/setup_env.sh first. Each stage is also runnable standalone —
5
+ # see README.md — this is just the "run everything with sane defaults" path.
6
+ #
7
+ # Skips scrape+build entirely if datasets/ is already present (e.g. scp'd
8
+ # over per README.md's "Getting this onto an instance") — ROUNDS_DIR is only
9
+ # required when datasets/ is actually missing.
10
+ set -euo pipefail
11
+ cd "$(dirname "$0")/.."
12
+ source .venv/bin/activate
13
+
14
+ PREF_METHOD="${PREF_METHOD:-kto}" # kto (recommended) | dpo | simpo — see TRAINING_GUIDE.md
15
+
16
+ if [ -f "datasets/preference.jsonl" ] && [ -f "datasets/sft.jsonl" ] && [ -f "datasets/kto.jsonl" ]; then
17
+ echo "=== datasets/ already present — skipping Phase 0/1 (scrape + build) ==="
18
+ else
19
+ ROUNDS_DIR="${ROUNDS_DIR:?datasets/ not found and ROUNDS_DIR is unset — either scp datasets/ over (see README.md), or set ROUNDS_DIR to your 404-active-competition/rounds path so Phase 0/1 can build it}"
20
+
21
+ echo "=== Phase 0: scrape archived duel data (this is the time-sensitive step — see CODER_TRAINING_PLAN.md) ==="
22
+ python3 data/scrape_duels.py --rounds-dir "$ROUNDS_DIR" --out-dir ./archive --min-round 0 --max-round 999
23
+
24
+ echo "=== Phase 1: build SFT / preference / KTO datasets ==="
25
+ python3 data/build_datasets.py --manifest ./archive/duels_index.jsonl --out-dir ./datasets
26
+ fi
27
+
28
+ echo "=== Phase 2a: SFT (winners-only distillation) ==="
29
+ python3 train_sft.py --config configs/sft.yaml
30
+
31
+ echo "=== Phase 2b: preference optimization ($PREF_METHOD) ==="
32
+ python3 "train_${PREF_METHOD}.py" --config "configs/${PREF_METHOD}.yaml"
33
+
34
+ echo
35
+ echo "=== Done. Checkpoints in ./checkpoints/{sft,$PREF_METHOD}/ ==="
36
+ echo "Next: Phase 3 held-out eval — see eval/self_judge_eval.py and README.md."
37
+ echo "(Not run automatically here — it needs the new checkpoint served behind an"
38
+ echo " OpenAI-compatible endpoint first, e.g. vLLM, which this script doesn't start.)"
scripts/setup_blackwell.sh ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # Blackwell (RTX PRO 6000, 96GB, sm_120) setup for the threejs coder fine-tune.
4
+ # Adapts our A6000-proven stack to Blackwell. Reference stacks that informed
5
+ # this: affine/setup_blackwell.sh and affine/install_finetune_blackwell.sh
6
+ # (both use CUDA 12.8 / cu128 — nightly torch for sm_120).
7
+ #
8
+ # THE ONE THING THAT MATTERS: does fla's Gated-DeltaNet Triton kernel COMPILE
9
+ # on sm_120? Our fix on the A6000 was triton 3.6.0, but Blackwell is NEWER than
10
+ # triton 3.6.0 — its sm_120 codegen may be absent. This script installs, then
11
+ # RUNS THE 30s fla ISOLATION TEST AS A HARD GATE before you trust anything.
12
+ # Do not launch a real run until the gate prints FLA_OK.
13
+ #
14
+ # Run: bash scripts/setup_blackwell.sh
15
+ # ============================================================================
16
+ set -euo pipefail
17
+ cd "$(dirname "$0")/.."
18
+
19
+ echo "=== 0. GPU check (expect RTX PRO 6000 / sm_120 / ~96GB) ==="
20
+ nvidia-smi --query-gpu=name,memory.total,compute_cap --format=csv,noheader || nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
21
+
22
+ echo "=== 1. venv ==="
23
+ python3 -m venv .venv || python3.12 -m venv .venv
24
+ source .venv/bin/activate
25
+ pip install --upgrade pip wheel
26
+
27
+ # --- 2. PyTorch for Blackwell -----------------------------------------------
28
+ # Two candidate stacks, try in order. Our A6000 stack was torch 2.13.0+cu130;
29
+ # CUDA 13.0 >= 12.8 so it SHOULD cover sm_120 IF the wheel ships sm_120 kernels.
30
+ # If torch can't see the GPU (sm_120 not in the wheel), fall back to cu128
31
+ # nightly (what affine's script uses for Blackwell).
32
+ echo "=== 2. install torch (try cu130 stable, else cu128 nightly) ==="
33
+ pip install "torch==2.13.0" torchvision --index-url https://download.pytorch.org/whl/cu130 || \
34
+ pip install --pre torch torchvision --index-url https://download.pytorch.org/whl/nightly/cu128
35
+ python - <<'PY'
36
+ import torch
37
+ print("torch", torch.__version__, "| cuda", torch.version.cuda, "| avail", torch.cuda.is_available())
38
+ if torch.cuda.is_available():
39
+ p=torch.cuda.get_device_properties(0)
40
+ print("GPU", p.name, "| sm", f"{p.major}.{p.minor}", "| VRAM", round(p.total_memory/1e9), "GB")
41
+ # sanity: a real matmul must run (proves the wheel has sm_120 kernels)
42
+ a=torch.randn(1024,1024,device="cuda"); (a@a).sum().item(); print("cuda matmul OK")
43
+ else:
44
+ raise SystemExit("torch cannot see the Blackwell GPU — the wheel lacks sm_120. Re-run and let it fall through to cu128 nightly.")
45
+ PY
46
+
47
+ echo "=== 3. training deps (transformers 5.x REQUIRED for qwen3_5) ==="
48
+ # NOTE: affine's ref pins transformers<5.0, but OUR model_type qwen3_5 only
49
+ # exists in transformers 5.x — do NOT downgrade transformers here.
50
+ pip install "transformers>=5.0.0" "trl>=1.9.0" "peft>=0.13.0" "accelerate>=1.0.0" \
51
+ "bitsandbytes>=0.48.1" "datasets>=3.0.0" pillow httpx pyyaml wandb
52
+
53
+ echo "=== 4. fla + triton (the fast Gated-DeltaNet kernel) ==="
54
+ # Start with the A6000-proven pin. If the gate below fails on sm_120, the doc
55
+ # (NEXT_INSTANCE_TRAINING.md, Blackwell section) lists the escalation: try the
56
+ # triton that ships WITH this torch (uninstall the 3.6.0 pin), or fla from git.
57
+ pip install "triton==3.6.0" "flash-linear-attention==0.5.2" || \
58
+ pip install "flash-linear-attention==0.5.2" # keep torch's bundled triton if 3.6.0 refuses
59
+ python -c "import torch,triton,fla;print('torch',torch.__version__,'| triton',triton.__version__,'| fla',fla.__version__)"
60
+
61
+ echo "=== 5. HARD GATE: does the fla chunk kernel compile+run on sm_120? (30s) ==="
62
+ python - <<'PY'
63
+ import torch, time, signal, os
64
+ def to(s,f):
65
+ print("FLA_HANG: chunk kernel did not finish in 90s on sm_120 — triton likely lacks sm_120 codegen.", flush=True)
66
+ os._exit(2)
67
+ signal.signal(signal.SIGALRM, to); signal.alarm(90)
68
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule as chunk
69
+ B,T,H,D=1,4096,4,128; dev="cuda"; dt=torch.bfloat16
70
+ q=torch.randn(B,T,H,D,device=dev,dtype=dt,requires_grad=True)
71
+ k=torch.randn(B,T,H,D,device=dev,dtype=dt); v=torch.randn(B,T,H,D,device=dev,dtype=dt)
72
+ g=torch.rand(B,T,H,device=dev,dtype=torch.float32).log(); beta=torch.rand(B,T,H,device=dev,dtype=dt)
73
+ def step():
74
+ o,_=chunk(q,k,v,g,beta,use_qk_l2norm_in_kernel=True); o.sum().backward(); q.grad=None
75
+ t0=time.time(); step(); torch.cuda.synchronize(); print(f"cold fwd+bwd {time.time()-t0:.1f}s (compile)", flush=True)
76
+ t0=time.time()
77
+ for _ in range(5): step()
78
+ torch.cuda.synchronize(); signal.alarm(0)
79
+ ms=1000*(time.time()-t0)/5
80
+ print(f"warm fwd+bwd {ms:.1f}ms/layer-call", flush=True)
81
+ print("FLA_OK" if ms < 500 else "FLA_SLOW: ran but slow — investigate before a long run.", flush=True)
82
+ PY
83
+
84
+ echo ""
85
+ echo "=== Done. If you saw FLA_OK above, fla works on this Blackwell — proceed. ==="
86
+ echo "If FLA_HANG/FLA_SLOW: see NEXT_INSTANCE_TRAINING.md 'Blackwell' section for the"
87
+ echo "triton/torch escalation, or train on the torch fallback (Blackwell's silicon is"
88
+ echo "fast and 96GB removes the KTO memory limits either way)."
89
+ echo ""
90
+ echo "Blackwell config deltas (96GB): in configs/kto.yaml set max_seq_length: 4096"
91
+ echo "and per_device_train_batch_size: 4 (accum 8); SFT can use batch 2. No"
92
+ echo "expandable_segments juggling needed. Keep optim: adamw_torch."
scripts/setup_env.sh ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Run once on a fresh training instance, after:
3
+ # git clone https://github.com/karvachiik-lgtm/threejstraining.git coder-training
4
+ # scp -r you@local:.../coder-training/{archive,datasets} coder-training/ # data, not in git — see README.md
5
+ set -euo pipefail
6
+
7
+ cd "$(dirname "$0")/.."
8
+
9
+ # Fresh minimal cloud/Docker images often lack python3-venv (→ `ensurepip is
10
+ # not available`) and build tooling bitsandbytes/flash-attn wheels sometimes
11
+ # need — best-effort install, skipped quietly if apt-get isn't usable (no
12
+ # root, non-Debian image, etc.) rather than failing the whole script over it.
13
+ if command -v apt-get >/dev/null 2>&1 && [ "$(id -u)" = "0" ]; then
14
+ echo "=== Ensuring python3-venv/build-essential (apt) ==="
15
+ apt-get update -qq && apt-get install -y -qq python3-venv python3-pip build-essential >/dev/null \
16
+ || echo " (apt-get install failed or partially failed — continuing; venv creation below will surface any real problem)"
17
+ fi
18
+
19
+ python3 -m venv .venv
20
+ source .venv/bin/activate
21
+ pip install --upgrade pip
22
+ pip install -r requirements.txt
23
+
24
+ echo
25
+ echo "=== Pre-flight checks (see README.md's checklist for what to do if these fail) ==="
26
+ python3 - <<'PY'
27
+ import importlib
28
+ import sys
29
+
30
+ checks = ["torch", "transformers", "trl", "peft", "bitsandbytes", "datasets", "wandb"]
31
+ for mod in checks:
32
+ try:
33
+ m = importlib.import_module(mod)
34
+ print(f" OK {mod:<14} {getattr(m, '__version__', '?')}")
35
+ except ImportError as e:
36
+ print(f" FAIL {mod:<14} {e}")
37
+ sys.exit(1)
38
+
39
+ import torch
40
+ print(f" CUDA available: {torch.cuda.is_available()} device_count: {torch.cuda.device_count()}")
41
+ if not torch.cuda.is_available():
42
+ print(" WARN no CUDA GPU visible — QLoRA/bitsandbytes below needs one; check `nvidia-smi` on this instance.")
43
+
44
+ try:
45
+ from transformers import AutoConfig
46
+ # Cheap check: does this transformers version know about the qwen3_5
47
+ # architecture Tooony133/Qwen-3.6-27B-* and Qwen/Qwen3.6-27B report?
48
+ # See requirements.txt's note — this is the biggest unverified risk here.
49
+ AutoConfig.for_model("qwen3_5")
50
+ print(" OK transformers recognizes model_type=qwen3_5")
51
+ except Exception as e:
52
+ print(f" WARN transformers may not support model_type=qwen3_5 yet: {e}")
53
+ print(" You likely need `pip install git+https://github.com/huggingface/transformers.git`")
54
+ PY
55
+
56
+ echo
57
+ if [ -f "datasets/preference.jsonl" ] && [ -f "datasets/sft.jsonl" ] && [ -f "datasets/kto.jsonl" ]; then
58
+ echo "=== datasets/ already present (scp'd) — data pipeline (Phase 0/1) already done, skip it ==="
59
+ echo "Next: source .venv/bin/activate && python train_sft.py --config configs/sft.yaml"
60
+ else
61
+ echo "=== datasets/ not found — either scp it over, or build it fresh: ==="
62
+ echo " 1) scp -r you@local:.../coder-training/{archive,datasets} . (fastest — data's already built)"
63
+ echo " or"
64
+ echo " 2) python data/scrape_duels.py --rounds-dir <path-to-404-active-competition/rounds> --out-dir ./archive"
65
+ echo " python data/build_datasets.py --manifest ./archive/duels_index.jsonl --out-dir ./datasets"
66
+ fi
67
+ echo "See README.md for the full pipeline; TRAINING_GUIDE.md for the algorithm/hyperparameter choices."
scripts/setup_fast_kernels.sh ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Enable the flash-linear-attention (fla) fused Gated-DeltaNet kernel — the
3
+ # single biggest training-throughput lever. VERIFIED on a Thunder A6000:
4
+ # fixed-4096 fwd+bwd dropped 32.8s -> 9.0s/step (3.6x) with this exact recipe.
5
+ #
6
+ # THE KEY FINDING (see NEXT_INSTANCE_TRAINING.md): fla's kernel "hangs" on the
7
+ # default stack's Triton 3.7.1 (ships with torch 2.13+cu130) — it's not a real
8
+ # hang, triton 3.7.1 DEADLOCKS compiling the Gated-DeltaNet kernel. Pinning
9
+ # **triton 3.6.0** fixes it (torch 2.13 warns about its version pin but runs
10
+ # fine). This was proven by vLLM running the same model's GDN kernels fine on
11
+ # triton 3.6.0. torch.compile also hangs on 3.7.1 for the same reason.
12
+ set -euo pipefail
13
+ cd "$(dirname "$0")/.."
14
+ source .venv/bin/activate
15
+
16
+ echo "=== current versions ==="
17
+ python -c "import torch,triton;print('torch',torch.__version__,'triton',triton.__version__)"
18
+
19
+ echo "=== pin triton 3.6.0 (THE fix) + fla 0.5.2 ==="
20
+ # 0.5.2, not 0.4.x: works with triton 3.6.0 for TRAINING (the 0.5.0 '!!!!'
21
+ # corruption bug is inference/generation-only, doesn't affect loss training).
22
+ pip install "triton==3.6.0" "flash-linear-attention==0.5.2"
23
+ python -c "import torch,triton,fla;print('now: torch',torch.__version__,'triton',triton.__version__,'fla',fla.__version__)"
24
+
25
+ echo "=== verify fla kernel WARMS (do NOT judge on the first call — it compiles ~2s) ==="
26
+ python - <<'PY'
27
+ import torch, time
28
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule as chunk
29
+ B,T,H,D=1,4096,4,128
30
+ q=torch.randn(B,T,H,D,device="cuda",dtype=torch.bfloat16,requires_grad=True)
31
+ k=torch.randn(B,T,H,D,device="cuda",dtype=torch.bfloat16); v=torch.randn(B,T,H,D,device="cuda",dtype=torch.bfloat16)
32
+ g=torch.rand(B,T,H,device="cuda").log(); beta=torch.rand(B,T,H,device="cuda",dtype=torch.bfloat16)
33
+ def step():
34
+ o,_=chunk(q,k,v,g,beta,use_qk_l2norm_in_kernel=True); o.sum().backward(); q.grad=None
35
+ t0=time.time(); step(); torch.cuda.synchronize(); print(f"cold fwd+bwd (compile): {time.time()-t0:.1f}s")
36
+ t0=time.time()
37
+ for _ in range(5): step()
38
+ torch.cuda.synchronize()
39
+ ms=1000*(time.time()-t0)/5
40
+ print(f"WARM fwd+bwd: {ms:.1f}ms/call")
41
+ if ms > 500:
42
+ raise SystemExit("!! fla kernel is slow even warm — check triton version (need 3.6.0)")
43
+ print("OK — fla is active and fast. Re-run the smoke and compare s/step to the torch-fallback baseline.")
44
+ PY
45
+
46
+ echo
47
+ echo "=== OPTIONAL: causal-conv1d for the COMPLETE fast path (needs nvcc) ==="
48
+ # is_fast_path_available also needs causal-conv1d. Without it the conv falls
49
+ # back to torch (why we get 3.6x not ~10x). causal-conv1d is source-only and
50
+ # needs nvcc (absent by default on Thunder). To try: install a pip nvcc first
51
+ # pip install nvidia-cuda-nvcc-cu12 # then ensure it's on PATH
52
+ # pip install causal-conv1d --no-build-isolation
53
+ # Skip if it fails — fla alone is the bulk of the win.
54
+ echo "(skipped by default — see NEXT_INSTANCE_TRAINING.md if you want to attempt it)"
scripts/setup_unsloth.sh ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # FALLBACK training path — install Unsloth. Use this only if the primary
3
+ # TRL + flash-linear-attention path (scripts/setup_fast_kernels.sh) hits
4
+ # trouble on the new instance. Unsloth ships its own fused Gated-DeltaNet /
5
+ # MoE Triton kernels (so it doesn't depend on fla) and claims ~1.5-1.7x
6
+ # faster / 50-60% less VRAM vs FA2. See SPEEDUP_FINDINGS.md's "TRL vs Unsloth".
7
+ #
8
+ # READ THIS BEFORE USING — two real caveats specific to our model on 48GB:
9
+ # 1. Unsloth EXPLICITLY recommends AGAINST 4-bit QLoRA for Qwen3.5 ("not
10
+ # recommended to do QLoRA (4-bit) ... due to higher-than-normal
11
+ # quantization differences", and "MoE QLoRA 4-bit not recommended due to
12
+ # BitsandBytes limitations"). It steers you to bf16 LoRA.
13
+ # 2. But their own VRAM table puts 27B bf16 LoRA at ~56GB — OVER our 48GB.
14
+ # So on a single 48GB card you're forced to either (a) run 4-bit anyway,
15
+ # against their advice, and validate output quality hard on the eval set, or
16
+ # (b) drop to a smaller Qwen3.5 variant that fits bf16 (their table: 9B=22GB,
17
+ # 4B=10GB). The configs/*_unsloth.yaml default to 4-bit with that warning;
18
+ # flip load_in_4bit->false + pick a smaller base if quality is unacceptable.
19
+ #
20
+ # Run AFTER scripts/setup_env.sh, in the same venv.
21
+ set -euo pipefail
22
+ cd "$(dirname "$0")/.."
23
+ source .venv/bin/activate
24
+
25
+ echo "=== Installing Unsloth (this reinstalls torch/deps to Unsloth-matched versions) ==="
26
+ # Unsloth's documented install for the latest models. --force-reinstall because
27
+ # Unsloth pins specific torch/xformers/trl builds; on a fresh instance that's
28
+ # fine, but be aware it may move torch off the version fla was built against —
29
+ # which is exactly why this is a SEPARATE, opt-in path, not folded into
30
+ # setup_env.sh. Do NOT run this and setup_fast_kernels.sh into the same venv
31
+ # expecting both to stay consistent; pick one path per venv.
32
+ pip install --upgrade --force-reinstall --no-cache-dir unsloth unsloth_zoo
33
+
34
+ echo
35
+ echo "=== Verify Unsloth imports and sees the GPU ==="
36
+ python - <<'PY'
37
+ import torch
38
+ print("torch:", torch.__version__, "| cuda:", torch.cuda.is_available())
39
+ try:
40
+ from unsloth import FastVisionModel, FastModel # noqa: F401
41
+ print("Unsloth import OK (FastVisionModel / FastModel available).")
42
+ except Exception as e:
43
+ print(f"!! Unsloth import FAILED: {e!r}")
44
+ raise SystemExit(1)
45
+ print("\nOK. Next: python train_sft_unsloth.py --config configs/sft_unsloth.yaml")
46
+ print("(Re-run the smoke test first — same as the TRL path — to compare s/example.)")
47
+ PY
threejs-sft-v1.progress.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "threejs-sft-v1",
3
+ "state_path": "tinker://6775d09f-0fa4-5e88-a96a-d88ecaaea32b:train:0/weights/threejs-sft-v1-step319",
4
+ "step": 319,
5
+ "epoch": 1,
6
+ "data_index": 336,
7
+ "billed_tokens": 7301784,
8
+ "loss_tokens_total": 5899460.0,
9
+ "examples_seen": 1276,
10
+ "seed": 0,
11
+ "base_model": "Qwen/Qwen3.6-27B",
12
+ "rank": 32
13
+ }
tinker/README.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tinker path — fast, managed SFT on Qwen/Qwen3.6-27B
2
+
3
+ Two-stage, cross-platform pipeline. Verified live against `tinker` SDK 0.24.0
4
+ (env: conda `affine-chutes`; key in `package_finetune32B/api_key.md`).
5
+
6
+ ## Why this path
7
+ - **Managed & fast:** Tinker runs the fwd/bwd on their GPUs, driven from the Mac.
8
+ Measured **~1.2s/example** (batch 4, ~2,900 tok/s) — ~10× the fla-A6000, no
9
+ GPU/triton ops. Multimodal (image+code) **verified working**.
10
+ - **Base only:** Tinker fine-tunes `Qwen/Qwen3.6-27B` (the base), NOT custom
11
+ checkpoints like `Tooony133/...AronHorn`. So this builds *our own* ceiling
12
+ checkpoint from base — the original "not a copy" rationale.
13
+ - **Methods:** SFT (`cross_entropy`) ✓, **DPO** ✓ (no KTO on Tinker → DPO),
14
+ RL/GRPO (`importance_sampling`/`ppo`/`cispo`). Context: **64K** (not the limit).
15
+
16
+ ## The data: top-vs-top curation (the key idea)
17
+ Naive winner-distillation clones the field average. We instead keep the
18
+ **winner of duels between two *strong* miners** — the best code that beat other
19
+ good code (quality-ceiling signal). From 142,647 duels: 37 strong miners →
20
+ 5,890 top-vs-top duels over 940 prompts. Winners spread across 24 miners (top
21
+ 11%) — a *diverse* ceiling, not a mono-clone.
22
+ - `data/curate_topvstop.py` → `archive/{sft,dpo}_manifest.jsonl`
23
+ - SFT = most-decisive top-vs-top winner per prompt (**940 examples**, 892 S1).
24
+ - DPO = all top-vs-top pairs (**5,890**, chosen=winner/rejected=loser).
25
+
26
+ ## ⚠️ Cost is the real constraint (not time)
27
+ Tinker bills **$4.103 / 1M training tokens**. Our winners are long code
28
+ (median total ~5,300 tok, up to ~18K), so `max_length=16384` (keeps 100% of the
29
+ code uncut; 4096 would truncate 75% — do NOT lower it).
30
+ - **SFT: 1 epoch ≈ $22** (~880 examples fit a $20 cap; the hard `--max-cost-usd`
31
+ stops cleanly at budget). 2 epochs ≈ $44.
32
+ - **DPO: ~2× tokens/pair + a reference forward → a full epoch ≈ $260.** Too
33
+ expensive on Tinker → run only a small subset here, or do the full DPO on a
34
+ rented **A100** with the repo's `train_dpo.py` (fla-fixed stack) — see
35
+ `NEXT_INSTANCE_TRAINING.md`. `datasets_dpo/preference.jsonl` feeds either.
36
+
37
+ ## Run it
38
+ ```bash
39
+ # 0. env (from repo root)
40
+ source activate affine-chutes && export TINKER_TELEMETRY=0
41
+ export TINKER_API_KEY="$(sed -n 1p ../affine/package_finetune32B/api_key.md)" # adjust path
42
+
43
+ # 1. curate + build (one-time; data must be local under archive/)
44
+ python data/curate_topvstop.py
45
+ python data/build_datasets.py --manifest archive/sft_manifest.jsonl --out-dir datasets_sft --eval-fraction 0.05
46
+ python data/build_datasets.py --manifest archive/dpo_manifest.jsonl --out-dir datasets_dpo --eval-fraction 0.05
47
+
48
+ # 2. smoke test (~$0.25) — confirms multimodal SFT works end-to-end
49
+ python tinker/train_sft_tinker.py --limit 8 --max-cost-usd 1.0 --save-every 0
50
+
51
+ # 3. REAL SFT (1 epoch, hard-capped at $20 → ~880 examples, ~30 min)
52
+ python tinker/train_sft_tinker.py --epochs 1 --max-cost-usd 20 --save-every 50
53
+ # -> prints a tinker:// sampler checkpoint path on finish
54
+
55
+ # 4. export the SFT adapter for the A100 DPO stage (or to deploy)
56
+ # per TINKER_ACCESS.md: get_checkpoint_archive_url -> tar -> merge_models.py
57
+ # (vLLM LoRA-merge verified for Qwen3/3.5 dense)
58
+
59
+ # 5a. DPO on A100 (recommended): repo train_dpo.py + datasets_dpo/preference.jsonl (fla stack)
60
+ # 5b. DPO on Tinker (subset only, pricey): validate then run
61
+ python tinker/train_dpo_tinker.py --limit 2 --max-cost-usd 1 # multimodal ref-logprob check
62
+ python tinker/train_dpo_tinker.py --sft-checkpoint tinker://... --limit 200 --max-cost-usd 15
63
+ ```
64
+
65
+ ## Files
66
+ - `tinker_data.py` — multimodal Datum builder (image = 1024 tok for 1024×1024;
67
+ SFT loss on completion only; cookbook shift input=full[:-1]/target=full[1:]).
68
+ - `train_sft_tinker.py` — SFT (`cross_entropy`), budget-capped, checkpointing.
69
+ - `train_dpo_tinker.py` — DPO (compute_dpo_loss + reference logprobs +
70
+ forward_backward_custom); multimodal ref-logprob path flagged for validation.
71
+
72
+ ## Honest expectations
73
+ SFT on ~880–940 ceiling-quality diverse winners reaches toward the top miners'
74
+ quality (LIMA "less is more" regime) — matching + more consistency, not magic.
75
+ The DPO stage (A100) is what sharpens toward reliably *winning* duels. Base-only
76
+ + single-stage SFT is a fast ~$20/~30-min experiment; add DPO for the real edge.
77
+
78
+ ## Pause / resume (add funds mid-run)
79
+ Both trainers checkpoint FULL state (weights + optimizer) via Tinker `save_state`
80
+ every `--save-every` steps, recorded in a local `<output-name>.progress.json`.
81
+ Verified end-to-end: a run that hits the budget cap saves its exact position
82
+ (step, epoch, data index, cumulative tokens); resuming continues from there with
83
+ **no re-spend**.
84
+ ```bash
85
+ # run hits the $20 cap and stops, printing the resume command:
86
+ python tinker/train_sft_tinker.py --output-name run1 --max-cost-usd 20
87
+ # == BUDGET STOP ... Resume later with --resume run1.progress.json ==
88
+ # raise the limit (after adding funds) and resume — picks up mid-epoch:
89
+ python tinker/train_sft_tinker.py --resume run1.progress.json --max-cost-usd 40
90
+ ```
91
+ Also survives a network drop / ^C (checkpointed every --save-every steps). The
92
+ `--max-cost-usd` counter is CUMULATIVE across resumes.
93
+
94
+ ## Observability (wandb)
95
+ On by default (project `404-coder-tinker`); reads the W&B key from
96
+ `package_finetune32B/api_key.md` line 2 or `WANDB_API_KEY`. `--no-wandb` to
97
+ disable. Logged per step (with defined step-axis charts):
98
+ - **loss:** `nll` + `nll_ema` (SFT); `dpo_loss`/`ema`, `accuracy`, `margin`,
99
+ `chosen_reward`, `rejected_reward` (DPO).
100
+ - **budget:** `cost_usd`, `budget_used_pct`, `budget_remaining_usd`,
101
+ `projected_epoch_cost_usd`, `eta_to_budget_min`.
102
+ - **throughput:** `step_time_s`, `tokens_per_s`, `tokens_per_s_avg`.
103
+ - **data/progress:** `tokens`, `loss_tokens` (completion tokens trained),
104
+ `loss_token_frac`, `examples_seen`, `data_coverage_pct`, `seq_len_mean/max`.
105
+ - checkpoint steps flagged; final cost + sampler path in the run summary.
tinker/eval_tinker.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Evaluate one or more Tinker SFT checkpoints WITHOUT renting a GPU.
4
+
5
+ Samples each checkpoint on Tinker's GPUs, renders the generated Three.js
6
+ locally (headless Chromium / swiftshader, CPU), and duels each render against
7
+ the ARCHIVED REAL WINNER for that held-out prompt via a vision judge on
8
+ OpenRouter. Reports win-rate-vs-archived-winner per checkpoint plus a
9
+ first-vs-last delta, so you can see whether training actually improved renders
10
+ (not just lowered loss).
11
+
12
+ - --save-every checkpoints are `save_state` (resume) checkpoints; we
13
+ load_state() then save_weights_and_get_sampling_client() to sample them.
14
+ - Multiple --checkpoint LABEL=tinker://... are compared on the SAME prompts.
15
+ Archived-winner renders are rendered once and cached across checkpoints.
16
+
17
+ Judge model: the live validator uses GLM-4.1V-9B-Thinking, which OpenRouter has
18
+ retired. Default here is z-ai/glm-4.5v (nearest available) — a PROXY good for
19
+ relative comparison, not the exact validator verdict. Override with --judge-model.
20
+
21
+ Usage:
22
+ python tinker/eval_tinker.py \
23
+ --checkpoint first=tinker://.../weights/threejs-sft-v1-step25 \
24
+ --checkpoint last=tinker://.../weights/threejs-sft-v1-step319 \
25
+ --n-prompts 8
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import asyncio
31
+ import base64
32
+ import json
33
+ import os
34
+ import random
35
+ import sys
36
+ from pathlib import Path
37
+
38
+ HERE = Path(__file__).resolve().parent
39
+ sys.path.insert(0, str(HERE)) # tinker_data (avoid SDK name clash)
40
+ sys.path.insert(0, str(HERE.parent / "eval")) # self_judge_eval + judge_challenge
41
+
42
+ import tinker # noqa: E402
43
+ from tinker import types as tt # noqa: E402
44
+
45
+ from tinker_data import image_expected_tokens, _texts # noqa: E402
46
+ from judge_challenge import evaluate_duel # noqa: E402
47
+ from self_judge_eval import render_js, png_to_data_url, chat_text # noqa: E402
48
+
49
+ try:
50
+ import wandb
51
+ except ImportError:
52
+ wandb = None
53
+
54
+
55
+ def read_line(path: str, line: int) -> str | None:
56
+ try:
57
+ with open(os.path.expanduser(path)) as f:
58
+ lines = [ln.strip() for ln in f if ln.strip()]
59
+ return lines[line] if line < len(lines) else None
60
+ except OSError:
61
+ return None
62
+
63
+
64
+ def build_prompt_input(row, tok, root):
65
+ """Prompt-only ModelInput matching the training prefix EXACTLY (minus the
66
+ completion): [system + nl<image>nl] [ImageChunk] [nl+user+nl]."""
67
+ sys_txt, user_txt = _texts(row)
68
+ img_path = os.path.join(root, row["images"][0])
69
+ itoks = image_expected_tokens(img_path)
70
+ img_bytes = open(img_path, "rb").read()
71
+ pre = tok.encode(sys_txt + "\n<image>\n", add_special_tokens=False)
72
+ post = tok.encode("\n" + user_txt + "\n", add_special_tokens=False)
73
+ mi = tinker.ModelInput.empty()
74
+ for t in pre:
75
+ mi = mi.append_int(t)
76
+ mi = mi.append(tt.ImageChunk(data=img_bytes, format="png", expected_tokens=itoks, type="image"))
77
+ for t in post:
78
+ mi = mi.append_int(t)
79
+ return mi
80
+
81
+
82
+ def load_eval_rows(preference_jsonl, n_prompts):
83
+ rows = [json.loads(l) for l in open(preference_jsonl) if l.strip()]
84
+ rows = [r for r in rows if r.get("split") == "eval"]
85
+ return rows[:n_prompts] if n_prompts else rows
86
+
87
+
88
+ def make_sampling_client(svc, label, state_path, base_model, rank):
89
+ """load_state(step-N resume checkpoint) -> export a sampler on Tinker."""
90
+ tc = svc.create_lora_training_client(base_model=base_model, rank=rank)
91
+ print(f"[{label}] load_state: {state_path}", flush=True)
92
+ tc.load_state(state_path).result()
93
+ print(f"[{label}] exporting sampler (on Tinker)...", flush=True)
94
+ sc = tc.save_weights_and_get_sampling_client(name=f"eval-{label}-sampler")
95
+ tok = tc.get_tokenizer()
96
+ return sc, tok
97
+
98
+
99
+ def generate_js(sc, tok, row, root, max_tokens, temperature, seed):
100
+ mi = build_prompt_input(row, tok, root)
101
+ resp = sc.sample(
102
+ prompt=mi, num_samples=1,
103
+ sampling_params=tinker.SamplingParams(max_tokens=max_tokens, temperature=temperature, seed=seed),
104
+ ).result()
105
+ toks = resp.sequences[0].tokens
106
+ return tok.decode(toks, skip_special_tokens=True) if toks else None
107
+
108
+
109
+ async def main_async(args):
110
+ # ---- renderer setup (single sidecar; randomize ports to dodge stragglers) ----
111
+ sys.path.insert(0, args.pipeline_service_dir)
112
+ from modules.renderer.module import RendererModule
113
+ from config.settings import settings as ps
114
+ ps.renderer.sidecar_count = 1
115
+ ps.renderer.pool_size = 1
116
+ ps.renderer.startup_timeout_s = 180.0
117
+ base = random.randint(20, 200)
118
+ ps.renderer.sidecar_port = 8003 + base
119
+ ps.renderer.static_port_base = 3000 + base
120
+
121
+ rows = load_eval_rows(args.preference_jsonl, args.n_prompts)
122
+ print(f"Loaded {len(rows)} held-out eval rows | checkpoints: {[c[0] for c in args.checkpoints]}", flush=True)
123
+ if not rows:
124
+ print("No eval rows — check --preference-jsonl / split=='eval'."); return
125
+
126
+ # ---- judge client (OpenRouter) ----
127
+ key = os.environ.get(args.judge_api_key_env) or read_line(args.judge_api_key_file, 0)
128
+ if not key:
129
+ raise SystemExit(f"No judge key: set ${args.judge_api_key_env} or put it in {args.judge_api_key_file}")
130
+ from openai import AsyncOpenAI
131
+ judge = AsyncOpenAI(base_url=args.judge_base_url, api_key=key)
132
+
133
+ svc = tinker.ServiceClient()
134
+ renderer = RendererModule(ps.renderer)
135
+ await renderer.startup()
136
+
137
+ if wandb is not None and args.wandb:
138
+ wandb.init(project=args.wandb_project, group="eval", name=args.run_name, job_type="eval")
139
+
140
+ results = {} # label -> dict(wins,losses,draws,errors)
141
+ archived_png_cache = {} # prompt image_path -> png bytes (render once)
142
+
143
+ try:
144
+ for label, state_path in args.checkpoints:
145
+ print(f"\n===== checkpoint '{label}' =====", flush=True)
146
+ sc, tok = make_sampling_client(svc, label, state_path, args.base_model, args.rank)
147
+ wins = losses = draws = errors = empty = 0
148
+ for i, row in enumerate(rows):
149
+ stem = row.get("name", f"eval_{i}")
150
+ image_path = os.path.join(args.root, row["images"][0])
151
+ try:
152
+ cand_js = generate_js(sc, tok, row, args.root, args.max_tokens, args.temperature, args.seed)
153
+ if not cand_js:
154
+ print(f" [{label}][{stem}] empty gen"); errors += 1; continue
155
+ cand_png = await render_js(renderer, f"{label}_{stem}_cand", image_path, cand_js)
156
+ if image_path not in archived_png_cache:
157
+ arch_js = chat_text(row["chosen"][0])
158
+ archived_png_cache[image_path] = await render_js(renderer, f"{stem}_arch", image_path, arch_js)
159
+ arch_png = archived_png_cache[image_path]
160
+ if not cand_png or not arch_png:
161
+ print(f" [{label}][{stem}] empty render (cand={bool(cand_png)} arch={bool(arch_png)})")
162
+ empty += 1; errors += 1; continue
163
+ with open(image_path, "rb") as f:
164
+ prompt_url = "data:image/png;base64," + base64.b64encode(f.read()).decode()
165
+ res = await evaluate_duel(
166
+ client=judge, prompt_url=prompt_url,
167
+ left_url=png_to_data_url(arch_png), # archived winner
168
+ right_url=png_to_data_url(cand_png), # our checkpoint
169
+ seed=42, model=args.judge_model,
170
+ )
171
+ if res.outcome > 0: wins += 1
172
+ elif res.outcome < 0: losses += 1
173
+ else: draws += 1
174
+ if args.save_renders:
175
+ d = Path(args.save_renders); d.mkdir(parents=True, exist_ok=True)
176
+ (d / f"{label}_{stem}_cand.png").write_bytes(cand_png)
177
+ n = wins + losses + draws
178
+ print(f" [{label}][{n}/{len(rows)}] {stem}: outcome={res.outcome} "
179
+ f"(W{wins}/L{losses}/D{draws}) — {res.issues[:50]}", flush=True)
180
+ except Exception as e:
181
+ print(f" [{label}][{stem}] ERROR: {e}"); errors += 1
182
+ nj = wins + losses + draws
183
+ wr = wins / nj if nj else 0.0
184
+ results[label] = dict(wins=wins, losses=losses, draws=draws, errors=errors, empty=empty, win_rate=wr, n=nj)
185
+ print(f"[{label}] {wins}W/{losses}L/{draws}D/{errors}err ({empty} empty) — win_rate={wr:.1%}", flush=True)
186
+ finally:
187
+ await renderer.shutdown()
188
+
189
+ # ---- comparison ----
190
+ print("\n================ SUMMARY ================", flush=True)
191
+ for label, r in results.items():
192
+ print(f" {label:>8}: win_rate={r['win_rate']:.1%} ({r['wins']}W/{r['losses']}L/{r['draws']}D, "
193
+ f"{r['errors']} err, n={r['n']})", flush=True)
194
+ labels = [c[0] for c in args.checkpoints]
195
+ if len(labels) >= 2:
196
+ a, b = labels[0], labels[-1]
197
+ d = results[b]["win_rate"] - results[a]["win_rate"]
198
+ print(f"\n Δ ({b} - {a}) = {d:+.1%} win-rate vs archived winners "
199
+ f"→ training {'HELPED' if d > 0 else 'did NOT help' if d < 0 else 'unchanged'}", flush=True)
200
+ total_empty = sum(r["empty"] for r in results.values())
201
+ total_n = sum(r["n"] for r in results.values())
202
+ if total_n == 0 and total_empty:
203
+ print(" ALL renders empty — RENDERER problem, numbers meaningless.", flush=True)
204
+ print(" (judge = proxy; win_rate>50% = beats archived REAL winners on held-out prompts)", flush=True)
205
+
206
+ if wandb is not None and args.wandb:
207
+ wandb.log({f"eval/{lab}/win_rate": r["win_rate"] for lab, r in results.items()})
208
+ wandb.finish()
209
+
210
+
211
+ def parse_ckpt(s):
212
+ if "=" not in s:
213
+ raise argparse.ArgumentTypeError("use LABEL=tinker://... e.g. last=tinker://...step319")
214
+ lab, path = s.split("=", 1)
215
+ return (lab, path)
216
+
217
+
218
+ def main():
219
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
220
+ p.add_argument("--checkpoint", dest="checkpoints", action="append", type=parse_ckpt, required=True,
221
+ help="LABEL=tinker://... (repeatable; compared on the same prompts)")
222
+ p.add_argument("--base-model", default="Qwen/Qwen3.6-27B")
223
+ p.add_argument("--rank", type=int, default=32)
224
+ p.add_argument("--preference-jsonl", default="datasets_dpo/preference.jsonl")
225
+ p.add_argument("--root", default=".")
226
+ p.add_argument("--n-prompts", type=int, default=8)
227
+ p.add_argument("--max-tokens", type=int, default=16384)
228
+ p.add_argument("--temperature", type=float, default=0.6)
229
+ p.add_argument("--seed", type=int, default=0)
230
+ p.add_argument("--save-renders", default=None, help="dir to dump candidate PNGs for inspection")
231
+
232
+ p.add_argument("--pipeline-service-dir",
233
+ default=str(Path(__file__).resolve().parents[2] / "miner-submission" / "pipeline_service"))
234
+
235
+ p.add_argument("--judge-base-url", default="https://openrouter.ai/api/v1")
236
+ p.add_argument("--judge-model", default="z-ai/glm-4.5v",
237
+ help="Validator uses GLM-4.1V-9B-Thinking (retired on OpenRouter); this is a proxy.")
238
+ p.add_argument("--judge-api-key-env", default="OPENROUTER_API_KEY")
239
+ p.add_argument("--judge-api-key-file", default=os.path.expanduser("~/openrouterkey"))
240
+ p.add_argument("--api-key-file", default="/Users/xavier/bittensor/affine/package_finetune32B/api_key.md",
241
+ help="line 1 = Tinker key (for TINKER_API_KEY if unset).")
242
+
243
+ p.add_argument("--wandb", action="store_true")
244
+ p.add_argument("--wandb-project", default="404-coder-tinker")
245
+ p.add_argument("--run-name", default="eval-compare")
246
+ args = p.parse_args()
247
+
248
+ if "TINKER_API_KEY" not in os.environ:
249
+ k = read_line(args.api_key_file, 0)
250
+ if k:
251
+ os.environ["TINKER_API_KEY"] = k
252
+ asyncio.run(main_async(args))
253
+
254
+
255
+ if __name__ == "__main__":
256
+ main()
tinker/tinker_data.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shared dataloader for Tinker training of Qwen/Qwen3.6-27B on our threejs data.
3
+
4
+ Builds MULTIMODAL Datums (image + text) — verified working on Tinker:
5
+ a 1024x1024 image = 1024 image tokens (patch_size 16 x merge_size 2 -> factor
6
+ 32; tokens = (W/32)*(H/32)). Our reference PNGs are 1024x1024, so 1024 each.
7
+
8
+ Sequence layout per SFT example:
9
+ [system + "\n<image>\n"] [ImageChunk(1024)] ["\n"+user_text+"\n"] [assistant code + EOS]
10
+ SFT loss (cross_entropy) is put ONLY on the completion tokens (weight 1),
11
+ everything else weight 0. Uses the cookbook shift: input = full[:-1],
12
+ target = full[1:] (see tinker_cookbook.supervised.common.datum_from_tokens_weights).
13
+ """
14
+ from __future__ import annotations
15
+ import json, os, signal
16
+ from PIL import Image
17
+ import tinker
18
+ from tinker import types as tt
19
+
20
+ PATCH, MERGE = 16, 2
21
+ FACTOR = PATCH * MERGE # 32
22
+ TRAIN_RATE_PER_1M = 4.103 # $/1M tokens, Qwen3.6-27B train
23
+
24
+
25
+ def image_expected_tokens(path: str) -> int:
26
+ """Qwen3-VL image-token count. All our renders are 1024x1024 -> 1024.
27
+ General: round each side to a multiple of FACTOR, then (W/FACTOR)*(H/FACTOR).
28
+ (Assumes within [min,max]_pixels — true for our 1024x1024 set.)"""
29
+ with Image.open(path) as im:
30
+ w, h = im.size
31
+ gw = max(1, round(w / FACTOR))
32
+ gh = max(1, round(h / FACTOR))
33
+ return gw * gh
34
+
35
+
36
+ def _texts(row):
37
+ sys_txt = row["prompt"][0]["content"]
38
+ user_txt = ""
39
+ for c in row["prompt"][1]["content"]:
40
+ if isinstance(c, dict) and c.get("type") == "text":
41
+ user_txt = c["text"]
42
+ return sys_txt, user_txt
43
+
44
+
45
+ def _build_multimodal(tok, root, img_rel, pre_txt, post_txt, comp_txt, max_length):
46
+ """Return (model_input, target_tokens, weights, n_tokens) for one example.
47
+ Weight=1 only on the completion (comp_txt) tokens."""
48
+ img_path = os.path.join(root, img_rel)
49
+ itoks = image_expected_tokens(img_path)
50
+ img_bytes = open(img_path, "rb").read()
51
+ pre = tok.encode(pre_txt, add_special_tokens=False)
52
+ post = tok.encode(post_txt, add_special_tokens=False)
53
+ eos = getattr(tok, "eos_token_id", None)
54
+ comp = tok.encode(comp_txt, add_special_tokens=False) + ([eos] if eos is not None else [])
55
+
56
+ n_prefix = len(pre) + itoks + len(post)
57
+ total = n_prefix + len(comp)
58
+ # budget: if over max_length, truncate the COMPLETION from the end (keep image+prompt)
59
+ if total > max_length:
60
+ keep = max(1, max_length - n_prefix)
61
+ comp = comp[:keep]
62
+ total = n_prefix + len(comp)
63
+
64
+ flat_targets = [0] * n_prefix + comp
65
+ flat_weights = [0.0] * n_prefix + [1.0] * len(comp)
66
+ tgt = flat_targets[1:]
67
+ w = flat_weights[1:]
68
+
69
+ mi = tinker.ModelInput.empty()
70
+ for t in pre:
71
+ mi = mi.append_int(t)
72
+ mi = mi.append(tt.ImageChunk(data=img_bytes, format="png", expected_tokens=itoks, type="image"))
73
+ for t in (post + comp)[:-1]: # full[:-1]
74
+ mi = mi.append_int(t)
75
+ return mi, tgt, w, total
76
+
77
+
78
+ def build_sft_datum(row, tok, root, max_length=16384):
79
+ sys_txt, user_txt = _texts(row)
80
+ mi, tgt, w, ntok = _build_multimodal(
81
+ tok, root, row["images"][0],
82
+ pre_txt=sys_txt + "\n<image>\n", post_txt="\n" + user_txt + "\n",
83
+ comp_txt=row["completion"][0]["content"], max_length=max_length,
84
+ )
85
+ datum = tinker.Datum(
86
+ model_input=mi,
87
+ loss_fn_inputs={
88
+ "weights": tt.TensorData(data=[float(x) for x in w], dtype="float32", shape=[len(w)]),
89
+ "target_tokens": tt.TensorData(data=[int(x) for x in tgt], dtype="int64", shape=[len(tgt)]),
90
+ },
91
+ )
92
+ return datum, ntok
93
+
94
+
95
+ def build_dpo_sequences(row, tok, root, max_length=16384):
96
+ """For DPO: same prompt+image, two completions (chosen, rejected).
97
+ Returns two (model_input, comp_token_ids, comp_start_index, n_tokens) tuples —
98
+ the caller computes per-token logprobs of the completion under policy+ref."""
99
+ sys_txt, user_txt = _texts(row)
100
+ out = {}
101
+ for key, msgs in (("chosen", row["chosen"]), ("rejected", row["rejected"])):
102
+ mi, tgt, w, ntok = _build_multimodal(
103
+ tok, root, row["images"][0],
104
+ pre_txt=sys_txt + "\n<image>\n", post_txt="\n" + user_txt + "\n",
105
+ comp_txt=msgs[0]["content"], max_length=max_length,
106
+ )
107
+ out[key] = dict(model_input=mi, target_tokens=tgt, weights=w, n_tokens=ntok)
108
+ return out
109
+
110
+
111
+ def load_rows(path, limit=None):
112
+ rows = []
113
+ for line in open(path):
114
+ line = line.strip()
115
+ if line:
116
+ rows.append(json.loads(line))
117
+ if limit and len(rows) >= limit:
118
+ break
119
+ return rows
120
+
121
+
122
+ def install_stop_handler():
123
+ """Graceful kill: first SIGINT/SIGTERM sets a flag so the loop saves a
124
+ resume checkpoint after the current step, then exits (lossless). A second
125
+ Ctrl-C force-quits. Lets you watch cost on the dashboard and kill safely."""
126
+ state = {"stop": False}
127
+ def _h(signum, frame):
128
+ if state["stop"]:
129
+ print("\n[signal] second interrupt — force quit", flush=True); os._exit(130)
130
+ state["stop"] = True
131
+ print("\n[signal] caught — saving a resume checkpoint after the current step "
132
+ "(Ctrl-C again to force-quit)", flush=True)
133
+ signal.signal(signal.SIGINT, _h)
134
+ try: signal.signal(signal.SIGTERM, _h)
135
+ except Exception: pass
136
+ return state
tinker/train_dpo_tinker.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 2 (Tinker, OPTIONAL): DPO on top-vs-top preference pairs
4
+ (datasets_dpo/preference.jsonl). MULTIMODAL. Replicates tinker_cookbook DPO
5
+ (compute_dpo_loss + reference logprobs + forward_backward_custom), with the
6
+ same PAUSE/RESUME + wandb as the SFT script.
7
+
8
+ ⚠️ COST: ~2x SFT tokens/pair + a reference forward -> a full epoch over 5,890
9
+ pairs is ~$260. Run a SUBSET here (--limit) or do the full DPO on an A100
10
+ (repo train_dpo.py + datasets_dpo/preference.jsonl, fla stack). The hard
11
+ --max-cost-usd cap + resume let you add funds and continue.
12
+
13
+ ⚠️ VALIDATION: multimodal reference-logprob (compute_logprobs over an image
14
+ sequence) is uncharted — run `--limit 2 --max-cost-usd 1` first; it stops if it
15
+ errors.
16
+
17
+ Usage:
18
+ python tinker/train_dpo_tinker.py --limit 2 --max-cost-usd 1
19
+ python tinker/train_dpo_tinker.py --sft-checkpoint tinker://... --max-cost-usd 15
20
+ python tinker/train_dpo_tinker.py --resume threejs-dpo-XX.progress.json
21
+ """
22
+ from __future__ import annotations
23
+ import argparse, asyncio, json, os, random, sys, time
24
+ import torch, tinker
25
+ from tinker import types as tt
26
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # add tinker/ dir (avoid SDK name clash)
27
+ from tinker_data import build_dpo_sequences, load_rows, TRAIN_RATE_PER_1M, install_stop_handler
28
+ from tinker_cookbook.preference.train_dpo import compute_dpo_loss
29
+
30
+
31
+ def _datum(seq):
32
+ return tt.Datum(model_input=seq["model_input"], loss_fn_inputs={
33
+ "weights": tt.TensorData(data=[float(x) for x in seq["weights"]], dtype="float32", shape=[len(seq["weights"])]),
34
+ "target_tokens": tt.TensorData(data=[int(x) for x in seq["target_tokens"]], dtype="int64", shape=[len(seq["target_tokens"])]),
35
+ })
36
+
37
+
38
+ def maybe_wandb(args, name):
39
+ if args.no_wandb: return None
40
+ key = os.environ.get("WANDB_API_KEY")
41
+ if not key:
42
+ try: key = open(os.path.join(os.path.dirname(args.root), "affine/package_finetune32B/api_key.md")).read().splitlines()[1].strip()
43
+ except Exception: key = None
44
+ if key: os.environ["WANDB_API_KEY"] = key
45
+ try:
46
+ import wandb
47
+ wandb.init(project="404-coder-tinker", name=name, config=vars(args), resume="allow", id=name)
48
+ wandb.define_metric("step")
49
+ for k in ("dpo_loss","dpo_loss_ema","accuracy","margin","chosen_reward","rejected_reward",
50
+ "cost_usd","budget_used_pct","budget_remaining_usd","step_time_s","eta_to_budget_min","pairs_seen"):
51
+ wandb.define_metric(k, step_metric="step")
52
+ return wandb
53
+ except Exception as e:
54
+ print(f"(wandb disabled: {e})"); return None
55
+
56
+
57
+ def main() -> None:
58
+ ap = argparse.ArgumentParser()
59
+ ap.add_argument("--dpo-jsonl", default="datasets_dpo/preference.jsonl")
60
+ ap.add_argument("--root", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
61
+ ap.add_argument("--base-model", default="Qwen/Qwen3.6-27B")
62
+ ap.add_argument("--sft-checkpoint", default=None, help="tinker:// state from SFT (policy+reference start); else base")
63
+ ap.add_argument("--rank", type=int, default=32)
64
+ ap.add_argument("--lr", type=float, default=5e-6)
65
+ ap.add_argument("--beta", type=float, default=0.1)
66
+ ap.add_argument("--batch-size", type=int, default=2, help="pairs/step")
67
+ ap.add_argument("--epochs", type=int, default=1)
68
+ ap.add_argument("--max-length", type=int, default=16384)
69
+ ap.add_argument("--max-cost-usd", type=float, default=15.0)
70
+ ap.add_argument("--save-every", type=int, default=25)
71
+ ap.add_argument("--output-name", default=None)
72
+ ap.add_argument("--resume", default=None)
73
+ ap.add_argument("--limit", type=int, default=None)
74
+ ap.add_argument("--seed", type=int, default=0)
75
+ ap.add_argument("--no-wandb", action="store_true")
76
+ args = ap.parse_args()
77
+
78
+ resume = json.load(open(args.resume)) if (args.resume and os.path.exists(args.resume)) else {}
79
+ if resume:
80
+ print(f"RESUMING DPO {args.resume}: step {resume['step']}, spent ${resume['billed']*TRAIN_RATE_PER_1M/1e6:.2f}")
81
+ args.seed = resume.get("seed", args.seed)
82
+ name = resume.get("name") or args.output_name or f"threejs-dpo-{int(time.time())}"
83
+ progress_path = os.path.join(args.root, f"{name}.progress.json")
84
+ ref_source = resume.get("ref_source", args.sft_checkpoint) # reference is FIXED across DPO
85
+
86
+ jsonl = args.dpo_jsonl if os.path.isabs(args.dpo_jsonl) else os.path.join(args.root, args.dpo_jsonl)
87
+ rows = load_rows(jsonl, args.limit)
88
+ print(f"loaded {len(rows)} DPO pairs | beta {args.beta} lr {args.lr} max_length {args.max_length} | cap ${args.max_cost_usd:.2f}")
89
+
90
+ wb = maybe_wandb(args, name)
91
+ svc = tinker.ServiceClient()
92
+ tc = svc.create_lora_training_client(base_model=args.base_model, rank=args.rank)
93
+ # policy: resume-state if resuming, else the SFT checkpoint, else base
94
+ if resume.get("state_path"):
95
+ tc.load_state(resume["state_path"]).result(); print("policy <- resume", resume["state_path"])
96
+ elif ref_source:
97
+ tc.load_state(ref_source).result(); print("policy <- SFT", ref_source)
98
+ tok = tc.get_tokenizer()
99
+ # reference: FIXED = the SFT starting point (or base). Recreate from a fresh client at ref_source.
100
+ ref_tc = svc.create_lora_training_client(base_model=args.base_model, rank=args.rank)
101
+ if ref_source: ref_tc.load_state(ref_source).result()
102
+ ref = ref_tc.save_weights_and_get_sampling_client("dpo-reference")
103
+ adam = tinker.AdamParams(learning_rate=args.lr, beta1=0.9, beta2=0.95, eps=1e-8)
104
+
105
+ billed = resume.get("billed", 0); step = resume.get("step", 0); pairs_seen = resume.get("pairs_seen", 0)
106
+ start_epoch = resume.get("epoch", 0); start_index = resume.get("data_index", 0)
107
+ t_start = time.time(); stop = False; ema = None
108
+ stopper = install_stop_handler()
109
+
110
+ def save_progress(epoch, data_index):
111
+ sp = tc.save_state(f"{name}-step{step}", ttl_seconds=7*24*3600, overwrite=True).result()
112
+ state_path = getattr(sp, "path", str(sp))
113
+ json.dump({"name": name, "state_path": state_path, "ref_source": ref_source, "step": step,
114
+ "epoch": epoch, "data_index": data_index, "billed": billed, "pairs_seen": pairs_seen,
115
+ "seed": args.seed, "base_model": args.base_model, "rank": args.rank}, open(progress_path, "w"), indent=2)
116
+ print(f" checkpoint+progress: {state_path}", flush=True)
117
+ return state_path
118
+
119
+ for epoch in range(start_epoch, args.epochs):
120
+ idx = list(range(len(rows))); random.Random(args.seed + epoch).shuffle(idx)
121
+ b0 = start_index if epoch == start_epoch else 0
122
+ for b in range(b0, len(idx), args.batch_size):
123
+ if stopper["stop"]:
124
+ print(f"== INTERRUPTED at step {step}: saving resume point =="); save_progress(epoch, b); stop = True; break
125
+ pairs = [rows[i] for i in idx[b:b + args.batch_size]]
126
+ data = []; ntok = 0
127
+ for r in pairs:
128
+ seqs = build_dpo_sequences(r, tok, args.root, args.max_length)
129
+ data.append(_datum(seqs["chosen"])); ntok += seqs["chosen"]["n_tokens"]
130
+ data.append(_datum(seqs["rejected"])); ntok += seqs["rejected"]["n_tokens"]
131
+ if (billed + ntok * 2) * TRAIN_RATE_PER_1M / 1e6 > args.max_cost_usd:
132
+ print(f"\n== BUDGET STOP at ${billed*TRAIN_RATE_PER_1M/1e6:.2f}. Add funds & resume: "
133
+ f"--resume {os.path.basename(progress_path)} =="); save_progress(epoch, b); stop = True; break
134
+ try:
135
+ ref_lp = asyncio.run(asyncio.gather(*[ref.compute_logprobs_async(d.model_input) for d in data]))
136
+ except Exception as e:
137
+ print("❌ multimodal reference-logprob FAILED (validation point):", repr(e)[:300]); return
138
+ ref_seqs = [torch.tensor(lp[1:]) for lp in ref_lp]
139
+ chosen_ref = [ref_seqs[i] for i in range(0, len(data), 2)]
140
+ rejected_ref = [ref_seqs[i] for i in range(1, len(data), 2)]
141
+
142
+ def dpo_loss_fn(data_, logprobs_list):
143
+ c = [logprobs_list[i] for i in range(0, len(data_), 2)]
144
+ r = [logprobs_list[i] for i in range(1, len(data_), 2)]
145
+ cl, rl, crl, rrl = [], [], [], []
146
+ for i in range(len(c)):
147
+ cw = torch.tensor(data_[2*i].loss_fn_inputs["weights"].data).float()
148
+ rw = torch.tensor(data_[2*i+1].loss_fn_inputs["weights"].data).float()
149
+ cl.append(torch.dot(c[i].float(), cw)); crl.append(torch.dot(chosen_ref[i].float(), cw))
150
+ rl.append(torch.dot(r[i].float(), rw)); rrl.append(torch.dot(rejected_ref[i].float(), rw))
151
+ return compute_dpo_loss(cl, rl, crl, rrl, args.beta)
152
+
153
+ t0 = time.time()
154
+ out = tc.forward_backward_custom(data, dpo_loss_fn).result()
155
+ tc.optim_step(adam).result()
156
+ dt = time.time() - t0
157
+ billed += ntok * 2; step += 1; pairs_seen += len(pairs)
158
+ m = getattr(out, "metrics", {}) or {}
159
+ loss = m.get("dpo_loss", float("nan"))
160
+ if loss == loss: ema = loss if ema is None else 0.9*ema + 0.1*loss
161
+ cost = billed * TRAIN_RATE_PER_1M / 1e6
162
+ elapsed = time.time() - t_start; rate = cost / elapsed if elapsed > 0 else 0
163
+ eta = (args.max_cost_usd - cost) / rate / 60 if rate > 0 else 0
164
+ print(f"e{epoch} step {step}: loss={loss:.3f} acc={m.get('accuracy',0):.2f} "
165
+ f"margin={m.get('margin',0):.3f} {dt:.1f}s | ${cost:.2f}/{args.max_cost_usd:.0f}", flush=True)
166
+ if wb:
167
+ wb.log({"dpo_loss": loss, "dpo_loss_ema": ema, "accuracy": m.get("accuracy",0),
168
+ "margin": m.get("margin",0), "chosen_reward": m.get("chosen_reward",0),
169
+ "rejected_reward": m.get("rejected_reward",0), "cost_usd": cost,
170
+ "budget_used_pct": 100.0*cost/args.max_cost_usd, "budget_remaining_usd": args.max_cost_usd-cost,
171
+ "step_time_s": dt, "eta_to_budget_min": eta, "pairs_seen": pairs_seen}, step=step)
172
+ if args.save_every and step % args.save_every == 0:
173
+ save_progress(epoch, b + args.batch_size)
174
+ if stop: break
175
+
176
+ final = tc.save_weights_for_sampler(f"{name}-final").result()
177
+ if not stop:
178
+ save_progress(args.epochs, 0)
179
+ print(f"\n=== DPO DONE: {step} steps, ${billed*TRAIN_RATE_PER_1M/1e6:.2f}, {(time.time()-t_start)/60:.0f} min ===")
180
+ print("FINAL:", getattr(final, "path", str(final)), "| progress:", progress_path)
181
+ if wb:
182
+ wb.summary["final_cost_usd"] = billed*TRAIN_RATE_PER_1M/1e6; wb.finish()
183
+
184
+
185
+ if __name__ == "__main__":
186
+ main()
tinker/train_sft_tinker.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 1 (Tinker): SFT of Qwen/Qwen3.6-27B on the top-vs-top winner distillation
4
+ set (datasets_sft/sft.jsonl). MULTIMODAL (image + code), verified on Tinker.
5
+
6
+ Cost-capped ($4.103/1M tokens; 1 epoch of 940 long-code examples ~$22, so
7
+ --max-cost-usd defaults to 20 and stops cleanly). PAUSE/RESUME and wandb are
8
+ built in:
9
+
10
+ * RESUME: `save_state` (full weights+optimizer) every --save-every steps ->
11
+ a tinker:// path recorded in a local <output-name>.progress.json. If the run
12
+ stops (budget cap, network drop, ^C), re-run with `--resume <file>.progress.json`
13
+ to continue from the exact step/example (same shuffle seed) — no re-spend.
14
+ * WANDB: on by default when a W&B key is available (api_key.md line 2 or
15
+ WANDB_API_KEY); logs nll, cost, tokens, step time, tok/s, lr, checkpoints.
16
+ Disable with --no-wandb.
17
+
18
+ Usage:
19
+ python tinker/train_sft_tinker.py --limit 8 --max-cost-usd 1.0 # smoke
20
+ python tinker/train_sft_tinker.py --epochs 1 --max-cost-usd 20 # real run
21
+ python tinker/train_sft_tinker.py --resume threejs-sft-XX.progress.json # resume
22
+ """
23
+ from __future__ import annotations
24
+ import argparse, json, os, random, sys, time
25
+ import tinker
26
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # add tinker/ dir (avoid SDK name clash)
27
+ from tinker_data import build_sft_datum, load_rows, TRAIN_RATE_PER_1M, install_stop_handler
28
+ from tinker_cookbook.supervised.common import compute_mean_nll
29
+
30
+
31
+ def maybe_wandb(args, name):
32
+ if args.no_wandb:
33
+ return None
34
+ key = os.environ.get("WANDB_API_KEY")
35
+ if not key:
36
+ try: # api_key.md line 2 = W&B key (see TINKER_ACCESS.md)
37
+ key = open(os.path.join(os.path.dirname(args.root), "affine/package_finetune32B/api_key.md")).read().splitlines()[1].strip()
38
+ except Exception:
39
+ key = None
40
+ if key:
41
+ os.environ["WANDB_API_KEY"] = key
42
+ try:
43
+ import wandb
44
+ wandb.init(project="404-coder-tinker", name=name, config=vars(args), resume="allow", id=name)
45
+ return wandb
46
+ except Exception as e:
47
+ print(f"(wandb disabled: {e})")
48
+ return None
49
+
50
+
51
+ def main() -> None:
52
+ ap = argparse.ArgumentParser()
53
+ ap.add_argument("--sft-jsonl", default="datasets_sft/sft.jsonl")
54
+ ap.add_argument("--root", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
55
+ ap.add_argument("--base-model", default="Qwen/Qwen3.6-27B")
56
+ ap.add_argument("--rank", type=int, default=32)
57
+ ap.add_argument("--lr", type=float, default=1e-4)
58
+ ap.add_argument("--batch-size", type=int, default=4)
59
+ ap.add_argument("--epochs", type=int, default=1)
60
+ ap.add_argument("--max-length", type=int, default=16384)
61
+ ap.add_argument("--max-cost-usd", type=float, default=20.0)
62
+ ap.add_argument("--save-every", type=int, default=25, help="save_state (resumable) every N steps")
63
+ ap.add_argument("--output-name", default=None)
64
+ ap.add_argument("--resume", default=None, help="path to a <name>.progress.json to resume from")
65
+ ap.add_argument("--limit", type=int, default=None)
66
+ ap.add_argument("--seed", type=int, default=0)
67
+ ap.add_argument("--no-wandb", action="store_true")
68
+ args = ap.parse_args()
69
+
70
+ # ---- resume state ----
71
+ resume = {}
72
+ if args.resume and os.path.exists(args.resume):
73
+ resume = json.load(open(args.resume))
74
+ print(f"RESUMING from {args.resume}: step {resume['step']}, epoch {resume['epoch']}, "
75
+ f"data_index {resume['data_index']}, spent ${resume['billed_tokens']*TRAIN_RATE_PER_1M/1e6:.2f}")
76
+ args.seed = resume.get("seed", args.seed)
77
+ name = resume.get("name") or args.output_name or f"threejs-sft-{int(time.time())}"
78
+ progress_path = os.path.join(args.root, f"{name}.progress.json")
79
+
80
+ root = args.root
81
+ jsonl = args.sft_jsonl if os.path.isabs(args.sft_jsonl) else os.path.join(root, args.sft_jsonl)
82
+ rows = load_rows(jsonl, args.limit)
83
+ print(f"loaded {len(rows)} SFT examples | {args.base_model} rank {args.rank} | max_length {args.max_length} | cap ${args.max_cost_usd:.2f}")
84
+
85
+ wb = maybe_wandb(args, name)
86
+ svc = tinker.ServiceClient()
87
+ tc = svc.create_lora_training_client(base_model=args.base_model, rank=args.rank)
88
+ if resume.get("state_path"):
89
+ print("load_state:", resume["state_path"]); tc.load_state(resume["state_path"]).result()
90
+ tok = tc.get_tokenizer()
91
+ adam = tinker.AdamParams(learning_rate=args.lr, beta1=0.9, beta2=0.95, eps=1e-8)
92
+
93
+ billed_tokens = resume.get("billed_tokens", 0)
94
+ loss_tokens_total = resume.get("loss_tokens_total", 0)
95
+ examples_seen = resume.get("examples_seen", 0)
96
+ step = resume.get("step", 0)
97
+ start_epoch = resume.get("epoch", 0)
98
+ start_index = resume.get("data_index", 0)
99
+ t_start = time.time(); stop = False
100
+ ema_nll = None
101
+ stopper = install_stop_handler()
102
+ total_examples = len(rows) * args.epochs
103
+ if wb:
104
+ # nicer charts: everything vs step; plus a cost/budget x-axis
105
+ wb.define_metric("step")
106
+ for k in ("nll","nll_ema","cost_usd","budget_used_pct","budget_remaining_usd",
107
+ "projected_epoch_cost_usd","tokens","loss_tokens","loss_token_frac",
108
+ "step_time_s","tokens_per_s","tokens_per_s_avg","examples_seen",
109
+ "data_coverage_pct","eta_to_budget_min","lr","epoch","seq_len_mean","seq_len_max"):
110
+ wb.define_metric(k, step_metric="step")
111
+
112
+ def save_progress(epoch, data_index):
113
+ sp = tc.save_state(f"{name}-step{step}", ttl_seconds=7 * 24 * 3600, overwrite=True).result()
114
+ state_path = getattr(sp, "path", str(sp))
115
+ json.dump({"name": name, "state_path": state_path, "step": step, "epoch": epoch,
116
+ "data_index": data_index, "billed_tokens": billed_tokens,
117
+ "loss_tokens_total": loss_tokens_total, "examples_seen": examples_seen,
118
+ "seed": args.seed, "base_model": args.base_model, "rank": args.rank},
119
+ open(progress_path, "w"), indent=2)
120
+ print(f" checkpoint+progress saved: {state_path}", flush=True)
121
+ if wb: wb.log({"checkpoint_step": step}, step=step)
122
+ return state_path
123
+
124
+ for epoch in range(start_epoch, args.epochs):
125
+ idx = list(range(len(rows)))
126
+ random.Random(args.seed + epoch).shuffle(idx)
127
+ b0 = start_index if epoch == start_epoch else 0
128
+ for b in range(b0, len(idx), args.batch_size):
129
+ if stopper["stop"]:
130
+ print(f"== INTERRUPTED at step {step}: saving resume point =="); save_progress(epoch, b); stop = True; break
131
+ batch = [rows[i] for i in idx[b:b + args.batch_size]]
132
+ data = []; ntok = 0
133
+ for r in batch:
134
+ d, n = build_sft_datum(r, tok, root, args.max_length); data.append(d); ntok += n
135
+ if (billed_tokens + ntok) * TRAIN_RATE_PER_1M / 1e6 > args.max_cost_usd:
136
+ print(f"\n== BUDGET STOP at ${billed_tokens*TRAIN_RATE_PER_1M/1e6:.2f} (next would exceed ${args.max_cost_usd:.2f}). "
137
+ f"Resume later with --resume {os.path.basename(progress_path)} ==")
138
+ save_progress(epoch, b); stop = True; break
139
+ t0 = time.time()
140
+ fb = tc.forward_backward(data, "cross_entropy").result()
141
+ tc.optim_step(adam).result()
142
+ dt = time.time() - t0
143
+ billed_tokens += ntok; step += 1
144
+ examples_seen += len(batch)
145
+ lt = sum(sum(d.loss_fn_inputs["weights"].data) for d in data) # completion tokens trained
146
+ loss_tokens_total += lt
147
+ cost = billed_tokens * TRAIN_RATE_PER_1M / 1e6
148
+ elapsed = time.time() - t_start
149
+ try:
150
+ nll = compute_mean_nll([x["logprobs"] for x in fb.loss_fn_outputs],
151
+ [d.loss_fn_inputs["weights"] for d in data])
152
+ except Exception:
153
+ nll = float("nan")
154
+ if nll == nll: # not NaN
155
+ ema_nll = nll if ema_nll is None else 0.9 * ema_nll + 0.1 * nll
156
+ cov = 100.0 * examples_seen / max(1, total_examples)
157
+ proj_epoch_cost = cost / (cov / 100.0) if cov > 0 else 0.0 # extrapolated full-run cost
158
+ rate_usd_per_s = cost / elapsed if elapsed > 0 else 0.0
159
+ eta_budget = (args.max_cost_usd - cost) / rate_usd_per_s / 60 if rate_usd_per_s > 0 else 0.0
160
+ seq_lens = [d.model_input.length for d in data]
161
+ print(f"e{epoch} step {step}: nll={nll:.3f} {dt:.1f}s {ntok}tok "
162
+ f"({ntok/dt:.0f} tok/s) | seen {examples_seen}/{total_examples} "
163
+ f"({cov:.0f}%) | ${cost:.2f}/{args.max_cost_usd:.0f} (proj ${proj_epoch_cost:.0f})", flush=True)
164
+ if wb:
165
+ wb.log({"nll": nll, "nll_ema": ema_nll, "cost_usd": cost,
166
+ "budget_used_pct": 100.0 * cost / args.max_cost_usd,
167
+ "budget_remaining_usd": args.max_cost_usd - cost,
168
+ "projected_epoch_cost_usd": proj_epoch_cost,
169
+ "tokens": billed_tokens, "loss_tokens": loss_tokens_total,
170
+ "loss_token_frac": lt / max(1, ntok),
171
+ "step_time_s": dt, "tokens_per_s": ntok / dt,
172
+ "tokens_per_s_avg": billed_tokens / elapsed if elapsed > 0 else 0.0,
173
+ "examples_seen": examples_seen, "data_coverage_pct": cov,
174
+ "eta_to_budget_min": eta_budget, "lr": args.lr, "epoch": epoch,
175
+ "seq_len_mean": sum(seq_lens) / len(seq_lens), "seq_len_max": max(seq_lens)},
176
+ step=step)
177
+ if args.save_every and step % args.save_every == 0:
178
+ save_progress(epoch, b + args.batch_size)
179
+ if stop: break
180
+
181
+ # export current weights for sampler (inference/merge) either way
182
+ final = tc.save_weights_for_sampler(f"{name}-final").result()
183
+ fp = getattr(final, "path", str(final))
184
+ if not stop:
185
+ save_progress(args.epochs, 0) # completion marker; a --resume becomes a no-op
186
+ # (on budget stop, the resume point saved by the budget branch is kept intact)
187
+ dur = (time.time() - t_start) / 60
188
+ print(f"\n=== DONE: {step} steps, {billed_tokens:,} tokens, ${billed_tokens*TRAIN_RATE_PER_1M/1e6:.2f}, {dur:.0f} min ===")
189
+ print(f"FINAL sampler checkpoint (export/merge): {fp}")
190
+ print(f"Resumable state + progress in: {progress_path}")
191
+ if wb:
192
+ wb.summary["final_cost_usd"] = billed_tokens * TRAIN_RATE_PER_1M / 1e6
193
+ wb.summary["final_sampler_path"] = fp
194
+ wb.finish()
195
+
196
+
197
+ if __name__ == "__main__":
198
+ main()
train_dpo.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 2 of CODER_TRAINING_PLAN.md's Phase 2: preference optimization on
4
+ datasets/preference.jsonl — real per-prompt (chosen, rejected) pairs from
5
+ the competition's own judge, not a proxy loss.
6
+
7
+ Run this AFTER train_sft.py; DPO sharpens an existing policy's preferences
8
+ between things it already knows how to produce, it does not teach output
9
+ format from scratch. Starts from the SFT adapter by default
10
+ (model.base_model + model.sft_adapter in configs/dpo.yaml) rather than the
11
+ raw base checkpoint.
12
+
13
+ With a LoRA/PEFT model, TRL's DPOTrainer computes the reference-model
14
+ logprobs by disabling the adapter on the *same* model instead of loading a
15
+ second full copy — this is what makes DPO tractable on a 27B model without
16
+ 2x the VRAM. See README.md's pre-flight checklist: verify this matches your
17
+ installed TRL version's actual behavior before a real run (`ref_model=None`
18
+ + a peft_config is the documented way to get it, but TRL's API has moved
19
+ around across versions).
20
+
21
+ Usage:
22
+ python train_dpo.py --config configs/dpo.yaml
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+
28
+ from peft import PeftModel
29
+ from trl import DPOConfig, DPOTrainer
30
+
31
+ from common import (build_lora_config, build_muon_config, init_wandb, load_config,
32
+ load_model_and_processor, make_muon_trainer, resolve_optim, resolve_output_dir)
33
+ from data.dataset_utils import dataset_stats, load_jsonl_dataset
34
+
35
+
36
+ def main() -> None:
37
+ p = argparse.ArgumentParser()
38
+ p.add_argument("--config", default="configs/dpo.yaml")
39
+ args = p.parse_args()
40
+
41
+ cfg = load_config(args.config)
42
+ init_wandb(cfg, run_name="dpo")
43
+
44
+ print(f"Loading base model: {cfg['model']['base_model']}")
45
+ model, processor = load_model_and_processor(cfg)
46
+
47
+ sft_adapter = cfg["model"].get("sft_adapter")
48
+ if sft_adapter:
49
+ print(f"Loading SFT adapter from {sft_adapter}")
50
+ model = PeftModel.from_pretrained(model, sft_adapter, is_trainable=True)
51
+ lora_config = None if sft_adapter else build_lora_config(cfg)
52
+
53
+ print(f"Loading dataset: {cfg['data']['preference_jsonl']}")
54
+ train_ds = load_jsonl_dataset(cfg["data"]["preference_jsonl"], split="train")
55
+ eval_ds = load_jsonl_dataset(cfg["data"]["preference_jsonl"], split="eval")
56
+ print(f" train: {dataset_stats(train_ds)} | eval: {dataset_stats(eval_ds)}")
57
+
58
+ t = cfg["training"]
59
+ hf_optim, use_muon = resolve_optim(cfg)
60
+ dpo_config = DPOConfig(
61
+ output_dir=resolve_output_dir(cfg, "./checkpoints/dpo"),
62
+ beta=t.get("beta", 0.1),
63
+ loss_type=t.get("loss_type", "sigmoid"), # "sigmoid" = standard DPO; TRL also
64
+ # accepts "ipo", "hinge", and others depending on version — see README's
65
+ # pre-flight checklist before changing this.
66
+ # max_steps overrides num_train_epochs when > 0 (config key was
67
+ # previously ignored — it never reached the trainer). Used by the
68
+ # smoke configs; -1 = disabled (epoch-driven) for real runs.
69
+ max_steps=t.get("max_steps", -1),
70
+ num_train_epochs=t.get("num_train_epochs", 1),
71
+ per_device_train_batch_size=t.get("per_device_train_batch_size", 1),
72
+ per_device_eval_batch_size=t.get("per_device_eval_batch_size", 1),
73
+ gradient_accumulation_steps=t.get("gradient_accumulation_steps", 16),
74
+ learning_rate=t.get("learning_rate", 5e-6),
75
+ lr_scheduler_type=t.get("lr_scheduler_type", "cosine"),
76
+ # HF TrainingArguments uses warmup_steps over warmup_ratio whenever
77
+ # warmup_steps > 0 — configs/dpo.yaml sets warmup_steps=150 to match
78
+ # the DPO paper exactly; configs/kto.yaml/simpo.yaml use warmup_ratio instead.
79
+ warmup_ratio=t.get("warmup_ratio", 0.0),
80
+ warmup_steps=t.get("warmup_steps", 0),
81
+ max_grad_norm=t.get("max_grad_norm", 1.0),
82
+ logging_steps=t.get("logging_steps", 10),
83
+ save_steps=t.get("save_steps", 200),
84
+ eval_steps=t.get("eval_steps", 200),
85
+ eval_strategy="steps",
86
+ bf16=t.get("bf16", True),
87
+ gradient_checkpointing=t.get("gradient_checkpointing", True),
88
+ # 8-bit paged optimizer (QLoRA paper 2305.14314 uses paged optimizers to
89
+ # survive gradient-checkpointing memory spikes; 8-bit halves/quarters
90
+ # optimizer-state memory) — frees VRAM so batch_size can rise above 1,
91
+ # which drives throughput more than the optimizer's own compute cost.
92
+ optim=hf_optim,
93
+ # use_reentrant=False is the documented fix for the bnb-4bit + gradient-
94
+ # checkpointing "inputs don't require grad" RuntimeError, and is also
95
+ # generally faster; PyTorch's future default. See SPEEDUP_FINDINGS.md.
96
+ gradient_checkpointing_kwargs=t.get("gradient_checkpointing_kwargs") or {"use_reentrant": False},
97
+ report_to=t.get("report_to", ["wandb"]),
98
+ run_name=t.get("run_name", "coder-dpo"),
99
+ max_length=t.get("max_seq_length", 4096),
100
+ remove_unused_columns=False,
101
+ )
102
+
103
+ TrainerCls = make_muon_trainer(DPOTrainer) if use_muon else DPOTrainer
104
+ trainer = TrainerCls(
105
+ model=model,
106
+ ref_model=None, # None + peft adapter -> TRL derives the reference by
107
+ # disabling the adapter on this same model, not a second full copy.
108
+ args=dpo_config,
109
+ train_dataset=train_ds,
110
+ eval_dataset=eval_ds,
111
+ processing_class=processor,
112
+ peft_config=lora_config,
113
+ )
114
+ if use_muon:
115
+ trainer.muon_config = build_muon_config(cfg)
116
+
117
+ trainer.train()
118
+ trainer.save_model(dpo_config.output_dir)
119
+ processor.save_pretrained(dpo_config.output_dir)
120
+ print(f"DPO adapter saved to {dpo_config.output_dir}")
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
train_kto.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Alternative to train_dpo.py: Kahneman-Tversky Optimization on
4
+ datasets/kto.jsonl (each duel's chosen/rejected pair split into two
5
+ independently-labeled examples — see data/build_datasets.py).
6
+
7
+ KTO's real advantage over DPO here isn't the draws (DPO/SimPO already just
8
+ exclude those, same as KTO would) — it's that KTO doesn't require examples
9
+ to come in matched pairs at all, so it can use "desirable"/"undesirable"
10
+ labels from ANY source, not just head-to-head duels. Worth comparing against
11
+ train_dpo.py's paired result rather than assuming either is better outright
12
+ — see TRAINING_GUIDE.md for the paper-grounded reasoning.
13
+
14
+ Usage:
15
+ python train_kto.py --config configs/kto.yaml
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+
21
+ from peft import PeftModel
22
+ from trl import KTOConfig, KTOTrainer
23
+
24
+ from common import (build_lora_config, build_muon_config, init_wandb, load_config,
25
+ load_model_and_processor, make_muon_trainer, resolve_optim, resolve_output_dir)
26
+ from data.dataset_utils import dataset_stats, load_jsonl_dataset
27
+
28
+
29
+ def main() -> None:
30
+ p = argparse.ArgumentParser()
31
+ p.add_argument("--config", default="configs/kto.yaml")
32
+ args = p.parse_args()
33
+
34
+ cfg = load_config(args.config)
35
+ init_wandb(cfg, run_name="kto")
36
+
37
+ print(f"Loading base model: {cfg['model']['base_model']}")
38
+ model, processor = load_model_and_processor(cfg)
39
+
40
+ sft_adapter = cfg["model"].get("sft_adapter")
41
+ if sft_adapter:
42
+ print(f"Loading SFT adapter from {sft_adapter}")
43
+ model = PeftModel.from_pretrained(model, sft_adapter, is_trainable=True)
44
+ lora_config = None if sft_adapter else build_lora_config(cfg)
45
+
46
+ print(f"Loading dataset: {cfg['data']['kto_jsonl']}")
47
+ train_ds = load_jsonl_dataset(cfg["data"]["kto_jsonl"], split="train")
48
+ eval_ds = load_jsonl_dataset(cfg["data"]["kto_jsonl"], split="eval")
49
+ n_pos = sum(train_ds["label"])
50
+ print(f" train: {len(train_ds)} examples ({n_pos} desirable / {len(train_ds) - n_pos} undesirable) {dataset_stats(train_ds)}")
51
+ print(f" eval: {dataset_stats(eval_ds)}")
52
+
53
+ t = cfg["training"]
54
+ hf_optim, use_muon = resolve_optim(cfg)
55
+ kto_config = KTOConfig(
56
+ output_dir=resolve_output_dir(cfg, "./checkpoints/kto"),
57
+ beta=t.get("beta", 0.1),
58
+ desirable_weight=t.get("desirable_weight", 1.0),
59
+ undesirable_weight=t.get("undesirable_weight", 1.0),
60
+ # KTO is sensitive to class imbalance (Ethayarajh et al.) — since our
61
+ # data comes from split pairs, desirable/undesirable counts start
62
+ # equal, but any later filtering can unbalance them. If so, set these
63
+ # weights so desirable_weight * n_desirable ≈ undesirable_weight *
64
+ # n_undesirable — see TRAINING_GUIDE.md.
65
+ # max_steps overrides num_train_epochs when > 0 (config key was
66
+ # previously ignored — it never reached the trainer). Used by the
67
+ # smoke configs; -1 = disabled (epoch-driven) for real runs.
68
+ max_steps=t.get("max_steps", -1),
69
+ num_train_epochs=t.get("num_train_epochs", 1),
70
+ per_device_train_batch_size=t.get("per_device_train_batch_size", 1),
71
+ per_device_eval_batch_size=t.get("per_device_eval_batch_size", 1),
72
+ gradient_accumulation_steps=t.get("gradient_accumulation_steps", 16),
73
+ learning_rate=t.get("learning_rate", 5e-6),
74
+ lr_scheduler_type=t.get("lr_scheduler_type", "cosine"),
75
+ warmup_ratio=t.get("warmup_ratio", 0.1),
76
+ max_grad_norm=t.get("max_grad_norm", 1.0),
77
+ logging_steps=t.get("logging_steps", 10),
78
+ save_steps=t.get("save_steps", 200),
79
+ eval_steps=t.get("eval_steps", 200),
80
+ eval_strategy="steps",
81
+ bf16=t.get("bf16", True),
82
+ gradient_checkpointing=t.get("gradient_checkpointing", True),
83
+ # 8-bit paged optimizer (QLoRA paper 2305.14314 uses paged optimizers to
84
+ # survive gradient-checkpointing memory spikes; 8-bit halves/quarters
85
+ # optimizer-state memory) — frees VRAM so batch_size can rise above 1,
86
+ # which drives throughput more than the optimizer's own compute cost.
87
+ optim=hf_optim,
88
+ # use_reentrant=False is the documented fix for the bnb-4bit + gradient-
89
+ # checkpointing "inputs don't require grad" RuntimeError, and is also
90
+ # generally faster; PyTorch's future default. See SPEEDUP_FINDINGS.md.
91
+ gradient_checkpointing_kwargs=t.get("gradient_checkpointing_kwargs") or {"use_reentrant": False},
92
+ report_to=t.get("report_to", ["wandb"]),
93
+ run_name=t.get("run_name", "coder-kto"),
94
+ max_length=t.get("max_seq_length", 4096),
95
+ remove_unused_columns=False,
96
+ )
97
+
98
+ TrainerCls = make_muon_trainer(KTOTrainer) if use_muon else KTOTrainer
99
+ trainer = TrainerCls(
100
+ model=model,
101
+ ref_model=None, # same PEFT-adapter-disable trick as train_dpo.py
102
+ args=kto_config,
103
+ train_dataset=train_ds,
104
+ eval_dataset=eval_ds,
105
+ processing_class=processor,
106
+ peft_config=lora_config,
107
+ )
108
+ if use_muon:
109
+ trainer.muon_config = build_muon_config(cfg)
110
+
111
+ trainer.train()
112
+ trainer.save_model(kto_config.output_dir)
113
+ processor.save_pretrained(kto_config.output_dir)
114
+ print(f"KTO adapter saved to {kto_config.output_dir}")
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()
train_kto_unsloth.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ FALLBACK Stage-2 KTO via an Unsloth-loaded model (mirror of train_kto.py).
4
+ Uses TRL's KTOTrainer (Unsloth patches the model, not the trainer) so the
5
+ KTO logic is identical to the TRL path — only the model loading changes.
6
+
7
+ MOST-UNVERIFIED SCRIPT IN THE REPO: Unsloth + vision + KTO is barely
8
+ documented (Unsloth's vision examples are SFT/GRPO). Treat this as a starting
9
+ point, not a proven recipe. If KTOTrainer rejects the Unsloth model or the
10
+ vision inputs, prefer the TRL path (train_kto.py) — that's the recommended
11
+ route regardless; this exists only so a fallback is ready. See
12
+ scripts/setup_unsloth.sh + unsloth_common.py headers.
13
+
14
+ Continuing from the Unsloth SFT stage: point model.base_model at the saved
15
+ adapter dir from train_sft_unsloth.py (checkpoints/sft_unsloth), or set
16
+ model.sft_adapter to load it on top — see the note below.
17
+
18
+ Usage:
19
+ python train_kto_unsloth.py --config configs/kto_unsloth.yaml
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+
25
+ from trl import KTOConfig, KTOTrainer
26
+
27
+ from unsloth_common import init_wandb, load_config, load_unsloth_vision_model, resolve_output_dir
28
+ from data.dataset_utils import dataset_stats, load_jsonl_dataset
29
+
30
+
31
+ def main() -> None:
32
+ p = argparse.ArgumentParser()
33
+ p.add_argument("--config", default="configs/kto_unsloth.yaml")
34
+ args = p.parse_args()
35
+
36
+ cfg = load_config(args.config)
37
+ init_wandb(cfg, run_name="kto-unsloth")
38
+
39
+ from unsloth import FastVisionModel
40
+
41
+ print(f"Loading base model via Unsloth: {cfg['model']['base_model']}")
42
+ model, tokenizer = load_unsloth_vision_model(cfg)
43
+
44
+ # Optionally continue from a saved Unsloth SFT adapter. get_peft_model has
45
+ # already attached a fresh adapter in load_unsloth_vision_model; loading
46
+ # trained weights on top is done via load_adapter when a path is given.
47
+ sft_adapter = cfg["model"].get("sft_adapter")
48
+ if sft_adapter:
49
+ try:
50
+ model.load_adapter(sft_adapter, adapter_name="default")
51
+ print(f"Loaded SFT adapter weights from {sft_adapter}")
52
+ except Exception as e: # noqa: BLE001
53
+ print(f"WARNING: could not load SFT adapter from {sft_adapter} ({e!r}); "
54
+ "training KTO from the base (skip-SFT) instead.")
55
+
56
+ FastVisionModel.for_training(model)
57
+
58
+ print(f"Loading dataset: {cfg['data']['kto_jsonl']}")
59
+ train_ds = load_jsonl_dataset(cfg["data"]["kto_jsonl"], split="train")
60
+ eval_ds = load_jsonl_dataset(cfg["data"]["kto_jsonl"], split="eval")
61
+ n_pos = sum(train_ds["label"])
62
+ print(f" train: {len(train_ds)} ({n_pos} desirable / {len(train_ds) - n_pos} undesirable) "
63
+ f"{dataset_stats(train_ds)}")
64
+ print(f" eval: {dataset_stats(eval_ds)}")
65
+
66
+ t = cfg["training"]
67
+ kto_config = KTOConfig(
68
+ output_dir=resolve_output_dir(cfg, "./checkpoints/kto_unsloth"),
69
+ beta=t.get("beta", 0.1),
70
+ desirable_weight=t.get("desirable_weight", 1.0),
71
+ undesirable_weight=t.get("undesirable_weight", 1.0),
72
+ num_train_epochs=t.get("num_train_epochs", 1),
73
+ per_device_train_batch_size=t.get("per_device_train_batch_size", 1),
74
+ per_device_eval_batch_size=t.get("per_device_eval_batch_size", 1),
75
+ gradient_accumulation_steps=t.get("gradient_accumulation_steps", 16),
76
+ learning_rate=t.get("learning_rate", 5e-6),
77
+ lr_scheduler_type=t.get("lr_scheduler_type", "cosine"),
78
+ warmup_ratio=t.get("warmup_ratio", 0.1),
79
+ max_grad_norm=t.get("max_grad_norm", 1.0),
80
+ logging_steps=t.get("logging_steps", 10),
81
+ save_steps=t.get("save_steps", 200),
82
+ eval_steps=t.get("eval_steps", 200),
83
+ eval_strategy="steps",
84
+ bf16=t.get("bf16", True),
85
+ optim=t.get("optim", "adamw_8bit"),
86
+ report_to=t.get("report_to", ["wandb"]),
87
+ run_name=t.get("run_name", "coder-kto-unsloth"),
88
+ max_length=t.get("max_seq_length", 4096),
89
+ remove_unused_columns=False,
90
+ )
91
+
92
+ trainer = KTOTrainer(
93
+ model=model,
94
+ ref_model=None,
95
+ args=kto_config,
96
+ train_dataset=train_ds,
97
+ eval_dataset=eval_ds,
98
+ processing_class=tokenizer,
99
+ )
100
+
101
+ trainer.train()
102
+ trainer.save_model(kto_config.output_dir)
103
+ tokenizer.save_pretrained(kto_config.output_dir)
104
+ print(f"Unsloth KTO adapter saved to {kto_config.output_dir}")
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
train_sft.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 1 of CODER_TRAINING_PLAN.md's Phase 2: SFT distillation on the winning
4
+ generations in datasets/sft.jsonl (built by data/build_datasets.py).
5
+
6
+ Teaches the base checkpoint the coding conventions that already reliably
7
+ pass JSChecker's budgets *and* won real on-chain duels — a tighter prior
8
+ than generic Three.js code, and the necessary first stage before preference
9
+ optimization (train_dpo.py / train_kto.py) can do anything useful: DPO/KTO
10
+ sharpen an existing policy's preferences, they don't teach output format
11
+ from scratch.
12
+
13
+ Usage:
14
+ python train_sft.py --config configs/sft.yaml
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+
20
+ from trl import SFTConfig, SFTTrainer
21
+
22
+ from common import (build_lora_config, build_muon_config, build_vlm_sft_collator, init_wandb,
23
+ load_config, load_model_and_processor, make_muon_trainer, resolve_optim, resolve_output_dir)
24
+ from data.dataset_utils import dataset_stats, load_jsonl_dataset
25
+
26
+
27
+ def main() -> None:
28
+ p = argparse.ArgumentParser()
29
+ p.add_argument("--config", default="configs/sft.yaml")
30
+ args = p.parse_args()
31
+
32
+ cfg = load_config(args.config)
33
+ init_wandb(cfg, run_name="sft")
34
+
35
+ print(f"Loading base model: {cfg['model']['base_model']}")
36
+ model, processor = load_model_and_processor(cfg)
37
+ lora_config = build_lora_config(cfg)
38
+
39
+ print(f"Loading dataset: {cfg['data']['sft_jsonl']}")
40
+ train_ds = load_jsonl_dataset(cfg["data"]["sft_jsonl"], split="train")
41
+ eval_ds = load_jsonl_dataset(cfg["data"]["sft_jsonl"], split="eval")
42
+ print(f" train: {dataset_stats(train_ds)} | eval: {dataset_stats(eval_ds)}")
43
+
44
+ t = cfg["training"]
45
+ hf_optim, use_muon = resolve_optim(cfg)
46
+ sft_config = SFTConfig(
47
+ output_dir=resolve_output_dir(cfg, "./checkpoints/sft"),
48
+ # max_steps overrides num_train_epochs when > 0 (config key was
49
+ # previously ignored — it never reached the trainer). Used by the
50
+ # smoke configs; -1 = disabled (epoch-driven) for real runs.
51
+ max_steps=t.get("max_steps", -1),
52
+ num_train_epochs=t.get("num_train_epochs", 2),
53
+ per_device_train_batch_size=t.get("per_device_train_batch_size", 1),
54
+ per_device_eval_batch_size=t.get("per_device_eval_batch_size", 1),
55
+ gradient_accumulation_steps=t.get("gradient_accumulation_steps", 16),
56
+ learning_rate=t.get("learning_rate", 1e-4),
57
+ lr_scheduler_type=t.get("lr_scheduler_type", "cosine"),
58
+ warmup_ratio=t.get("warmup_ratio", 0.03),
59
+ max_grad_norm=t.get("max_grad_norm", 1.0),
60
+ adam_beta2=t.get("adam_beta2", 0.999),
61
+ logging_steps=t.get("logging_steps", 10),
62
+ save_steps=t.get("save_steps", 200),
63
+ eval_steps=t.get("eval_steps", 200),
64
+ eval_strategy="steps",
65
+ bf16=t.get("bf16", True),
66
+ gradient_checkpointing=t.get("gradient_checkpointing", True),
67
+ # 8-bit paged optimizer (QLoRA paper 2305.14314 uses paged optimizers to
68
+ # survive gradient-checkpointing memory spikes; 8-bit halves/quarters
69
+ # optimizer-state memory) — frees VRAM so batch_size can rise above 1,
70
+ # which drives throughput more than the optimizer's own compute cost.
71
+ optim=hf_optim,
72
+ # use_reentrant=False is the documented fix for the bnb-4bit + gradient-
73
+ # checkpointing "inputs don't require grad" RuntimeError, and is also
74
+ # generally faster; PyTorch's future default. See SPEEDUP_FINDINGS.md.
75
+ gradient_checkpointing_kwargs=t.get("gradient_checkpointing_kwargs") or {"use_reentrant": False},
76
+ report_to=t.get("report_to", ["wandb"]),
77
+ run_name=t.get("run_name", "coder-sft"),
78
+ max_length=t.get("max_seq_length", 4096),
79
+ # True, not False: SFTTrainer's default dataset preparation assumes
80
+ # text-only data and will mishandle the "images" column — the custom
81
+ # collator below (build_vlm_sft_collator) does tokenization +
82
+ # image-processing + prompt-masking itself instead. See common.py.
83
+ dataset_kwargs={"skip_prepare_dataset": True},
84
+ remove_unused_columns=False, # keep "images"/"prompt"/"completion" raw for the collator
85
+ )
86
+
87
+ TrainerCls = make_muon_trainer(SFTTrainer) if use_muon else SFTTrainer
88
+ trainer = TrainerCls(
89
+ model=model,
90
+ args=sft_config,
91
+ train_dataset=train_ds,
92
+ eval_dataset=eval_ds,
93
+ processing_class=processor,
94
+ peft_config=lora_config,
95
+ data_collator=build_vlm_sft_collator(processor),
96
+ )
97
+ if use_muon:
98
+ trainer.muon_config = build_muon_config(cfg)
99
+
100
+ trainer.train()
101
+ trainer.save_model(sft_config.output_dir)
102
+ processor.save_pretrained(sft_config.output_dir)
103
+ print(f"SFT adapter saved to {sft_config.output_dir}")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
train_sft_unsloth.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ FALLBACK Stage-1 SFT via Unsloth (mirror of train_sft.py). Use the TRL path
4
+ (train_sft.py) first; switch here only if the TRL + flash-linear-attention
5
+ path misbehaves on the new instance. See scripts/setup_unsloth.sh for caveats.
6
+
7
+ Same data (datasets/sft.jsonl), same held-out-by-round split, same wandb
8
+ project. The differences are all Unsloth-side: FastVisionModel loading, its
9
+ fused kernels, and UnslothVisionDataCollator instead of our custom collator.
10
+
11
+ UNVERIFIED ON HARDWARE — see unsloth_common.py's header.
12
+
13
+ Usage:
14
+ python train_sft_unsloth.py --config configs/sft_unsloth.yaml
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+
20
+ from PIL import Image as PILImage
21
+ from trl import SFTConfig, SFTTrainer
22
+
23
+ from unsloth_common import init_wandb, load_config, load_unsloth_vision_model, resolve_output_dir
24
+ from data.dataset_utils import dataset_stats, load_jsonl_dataset
25
+
26
+
27
+ def to_messages(row: dict) -> dict:
28
+ """Convert a build_datasets.py SFT row (prompt/completion chat lists +
29
+ image paths) into the single `messages` conversation Unsloth's vision
30
+ collator consumes, with the image inlined as a PIL object."""
31
+ img = PILImage.open(row["images"][0]) if isinstance(row["images"][0], str) else row["images"][0]
32
+ if hasattr(img, "convert"):
33
+ img = img.convert("RGB")
34
+ messages = []
35
+ for msg in row["prompt"]:
36
+ content = msg["content"]
37
+ if isinstance(content, list):
38
+ # replace the {"type":"image"} placeholder with the actual image
39
+ content = [{"type": "image", "image": img} if c.get("type") == "image" else c
40
+ for c in content]
41
+ messages.append({"role": msg["role"], "content": content})
42
+ for msg in row["completion"]:
43
+ c = msg["content"]
44
+ messages.append({"role": msg["role"],
45
+ "content": c if isinstance(c, list) else [{"type": "text", "text": c}]})
46
+ return {"messages": messages}
47
+
48
+
49
+ def main() -> None:
50
+ p = argparse.ArgumentParser()
51
+ p.add_argument("--config", default="configs/sft_unsloth.yaml")
52
+ args = p.parse_args()
53
+
54
+ cfg = load_config(args.config)
55
+ init_wandb(cfg, run_name="sft-unsloth")
56
+
57
+ from unsloth import FastVisionModel
58
+ from unsloth.trainer import UnslothVisionDataCollator
59
+
60
+ print(f"Loading base model via Unsloth: {cfg['model']['base_model']}")
61
+ model, tokenizer = load_unsloth_vision_model(cfg)
62
+ FastVisionModel.for_training(model)
63
+
64
+ print(f"Loading dataset: {cfg['data']['sft_jsonl']}")
65
+ train_ds = load_jsonl_dataset(cfg["data"]["sft_jsonl"], split="train")
66
+ eval_ds = load_jsonl_dataset(cfg["data"]["sft_jsonl"], split="eval")
67
+ print(f" train: {dataset_stats(train_ds)} | eval: {dataset_stats(eval_ds)}")
68
+ # Keep the lazy image column; map to Unsloth's messages shape (remove the
69
+ # old columns so only `messages` remains for the collator).
70
+ train_ds = train_ds.map(to_messages, remove_columns=train_ds.column_names)
71
+ eval_ds = eval_ds.map(to_messages, remove_columns=eval_ds.column_names)
72
+
73
+ t = cfg["training"]
74
+ sft_config = SFTConfig(
75
+ output_dir=resolve_output_dir(cfg, "./checkpoints/sft_unsloth"),
76
+ num_train_epochs=t.get("num_train_epochs", 2),
77
+ per_device_train_batch_size=t.get("per_device_train_batch_size", 1),
78
+ per_device_eval_batch_size=t.get("per_device_eval_batch_size", 1),
79
+ gradient_accumulation_steps=t.get("gradient_accumulation_steps", 16),
80
+ learning_rate=t.get("learning_rate", 1e-4),
81
+ lr_scheduler_type=t.get("lr_scheduler_type", "constant"),
82
+ warmup_ratio=t.get("warmup_ratio", 0.03),
83
+ max_grad_norm=t.get("max_grad_norm", 0.3),
84
+ logging_steps=t.get("logging_steps", 10),
85
+ save_steps=t.get("save_steps", 200),
86
+ eval_steps=t.get("eval_steps", 200),
87
+ eval_strategy="steps",
88
+ bf16=t.get("bf16", True),
89
+ optim=t.get("optim", "adamw_8bit"), # Unsloth's recommended default
90
+ report_to=t.get("report_to", ["wandb"]),
91
+ run_name=t.get("run_name", "coder-sft-unsloth"),
92
+ max_seq_length=t.get("max_seq_length", 4096),
93
+ # Vision: Unsloth's collator does prep on the fly, like the TRL path.
94
+ dataset_kwargs={"skip_prepare_dataset": True},
95
+ remove_unused_columns=False,
96
+ dataset_num_proc=1,
97
+ )
98
+
99
+ trainer = SFTTrainer(
100
+ model=model,
101
+ args=sft_config,
102
+ train_dataset=train_ds,
103
+ eval_dataset=eval_ds,
104
+ tokenizer=tokenizer,
105
+ data_collator=UnslothVisionDataCollator(model, tokenizer),
106
+ )
107
+
108
+ trainer.train()
109
+ trainer.save_model(sft_config.output_dir)
110
+ tokenizer.save_pretrained(sft_config.output_dir)
111
+ print(f"Unsloth SFT adapter saved to {sft_config.output_dir}")
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()
train_simpo.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Second alternative to train_dpo.py / train_kto.py — SimPO (Meng, Xia, Chen,
4
+ 2405.14734) via TRL's CPOTrainer with loss_type="simpo". Reference-free: no
5
+ frozen reference-model logprob pass at all (cheaper per step than DPO/KTO,
6
+ which both need one even with the PEFT-adapter-disable trick), reward is the
7
+ length-normalized average log-prob instead — the paper's whole point is that
8
+ un-normalized (summed) log-prob rewards, like DPO's, are biased toward
9
+ longer completions; JS code length varies a lot across objects, so this bias
10
+ is a real, not theoretical, risk for us specifically.
11
+
12
+ Usage:
13
+ python train_simpo.py --config configs/simpo.yaml
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+
19
+ from peft import PeftModel
20
+ from trl import CPOConfig, CPOTrainer
21
+
22
+ from common import (build_lora_config, build_muon_config, init_wandb, load_config,
23
+ load_model_and_processor, make_muon_trainer, resolve_optim, resolve_output_dir)
24
+ from data.dataset_utils import dataset_stats, load_jsonl_dataset
25
+
26
+
27
+ def main() -> None:
28
+ p = argparse.ArgumentParser()
29
+ p.add_argument("--config", default="configs/simpo.yaml")
30
+ args = p.parse_args()
31
+
32
+ cfg = load_config(args.config)
33
+ init_wandb(cfg, run_name="simpo")
34
+
35
+ print(f"Loading base model: {cfg['model']['base_model']}")
36
+ model, processor = load_model_and_processor(cfg)
37
+
38
+ sft_adapter = cfg["model"].get("sft_adapter")
39
+ if sft_adapter:
40
+ print(f"Loading SFT adapter from {sft_adapter}")
41
+ model = PeftModel.from_pretrained(model, sft_adapter, is_trainable=True)
42
+ lora_config = None if sft_adapter else build_lora_config(cfg)
43
+
44
+ print(f"Loading dataset: {cfg['data']['preference_jsonl']}")
45
+ train_ds = load_jsonl_dataset(cfg["data"]["preference_jsonl"], split="train")
46
+ eval_ds = load_jsonl_dataset(cfg["data"]["preference_jsonl"], split="eval")
47
+ print(f" train: {dataset_stats(train_ds)} | eval: {dataset_stats(eval_ds)}")
48
+
49
+ t = cfg["training"]
50
+ hf_optim, use_muon = resolve_optim(cfg)
51
+ simpo_config = CPOConfig(
52
+ output_dir=resolve_output_dir(cfg, "./checkpoints/simpo"),
53
+ loss_type="simpo",
54
+ beta=t.get("beta", 2.0), # NOT the same scale as DPO's beta — see configs/simpo.yaml
55
+ simpo_gamma=t.get("simpo_gamma", 1.0),
56
+ cpo_alpha=t.get("cpo_alpha", 0.0), # 0.0 = pure SimPO, no auxiliary NLL term
57
+ # max_steps overrides num_train_epochs when > 0 (config key was
58
+ # previously ignored — it never reached the trainer). Used by the
59
+ # smoke configs; -1 = disabled (epoch-driven) for real runs.
60
+ max_steps=t.get("max_steps", -1),
61
+ num_train_epochs=t.get("num_train_epochs", 1),
62
+ per_device_train_batch_size=t.get("per_device_train_batch_size", 1),
63
+ per_device_eval_batch_size=t.get("per_device_eval_batch_size", 1),
64
+ gradient_accumulation_steps=t.get("gradient_accumulation_steps", 32),
65
+ learning_rate=t.get("learning_rate", 6e-7), # an order of magnitude below DPO/KTO — see configs/simpo.yaml
66
+ lr_scheduler_type=t.get("lr_scheduler_type", "cosine"),
67
+ warmup_ratio=t.get("warmup_ratio", 0.1),
68
+ max_grad_norm=t.get("max_grad_norm", 1.0),
69
+ logging_steps=t.get("logging_steps", 10),
70
+ save_steps=t.get("save_steps", 200),
71
+ eval_steps=t.get("eval_steps", 200),
72
+ eval_strategy="steps",
73
+ bf16=t.get("bf16", True),
74
+ gradient_checkpointing=t.get("gradient_checkpointing", True),
75
+ # 8-bit paged optimizer (QLoRA paper 2305.14314 uses paged optimizers to
76
+ # survive gradient-checkpointing memory spikes; 8-bit halves/quarters
77
+ # optimizer-state memory) — frees VRAM so batch_size can rise above 1,
78
+ # which drives throughput more than the optimizer's own compute cost.
79
+ optim=hf_optim,
80
+ # use_reentrant=False is the documented fix for the bnb-4bit + gradient-
81
+ # checkpointing "inputs don't require grad" RuntimeError, and is also
82
+ # generally faster; PyTorch's future default. See SPEEDUP_FINDINGS.md.
83
+ gradient_checkpointing_kwargs=t.get("gradient_checkpointing_kwargs") or {"use_reentrant": False},
84
+ report_to=t.get("report_to", ["wandb"]),
85
+ run_name=t.get("run_name", "coder-simpo"),
86
+ max_length=t.get("max_seq_length", 4096),
87
+ remove_unused_columns=False,
88
+ )
89
+
90
+ TrainerCls = make_muon_trainer(CPOTrainer) if use_muon else CPOTrainer
91
+ trainer = TrainerCls(
92
+ model=model,
93
+ args=simpo_config,
94
+ train_dataset=train_ds,
95
+ eval_dataset=eval_ds,
96
+ processing_class=processor,
97
+ peft_config=lora_config,
98
+ )
99
+ if use_muon:
100
+ trainer.muon_config = build_muon_config(cfg)
101
+
102
+ trainer.train()
103
+ trainer.save_model(simpo_config.output_dir)
104
+ processor.save_pretrained(simpo_config.output_dir)
105
+ print(f"SimPO adapter saved to {simpo_config.output_dir}")
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
unsloth_common.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared Unsloth model loading for the FALLBACK training path.
2
+
3
+ Mirrors common.py (TRL path) but loads the model through Unsloth's
4
+ FastVisionModel. Reuses common.py's config/wandb/output helpers so the two
5
+ paths stay consistent. See scripts/setup_unsloth.sh for the caveats — most
6
+ importantly that 4-bit on Qwen3.5 is against Unsloth's own advice but is
7
+ forced by our 48GB budget for the 27B model.
8
+
9
+ UNVERIFIED ON HARDWARE: written against Unsloth's documented Qwen3.5 / Qwen3-VL
10
+ fine-tuning API (unsloth.ai/docs/models/qwen3.5/fine-tune and the Qwen3-VL
11
+ notebook). Unsloth's vision API moves fast — check FastVisionModel.get_peft_model's
12
+ current signature and UnslothVisionDataCollator against your installed version
13
+ before a long run, exactly like the TRL path's pre-flight checklist.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from common import load_config, init_wandb, resolve_output_dir # noqa: F401 (re-exported)
18
+
19
+
20
+ def load_unsloth_vision_model(cfg: dict):
21
+ """Load base model + processor via Unsloth FastVisionModel, then attach a
22
+ LoRA adapter. Returns (model, tokenizer) where `tokenizer` is Unsloth's
23
+ combined processor/tokenizer (it plays the role of common.py's processor)."""
24
+ from unsloth import FastVisionModel
25
+
26
+ m = cfg["model"]
27
+ lora = cfg.get("lora", {})
28
+ load_in_4bit = bool(m.get("load_in_4bit", True))
29
+ if load_in_4bit:
30
+ print("[unsloth] load_in_4bit=True — NOTE: Unsloth advises against 4-bit "
31
+ "for Qwen3.5; validate eval quality carefully (see setup_unsloth.sh).")
32
+
33
+ model, tokenizer = FastVisionModel.from_pretrained(
34
+ model_name=m["base_model"],
35
+ max_seq_length=cfg.get("training", {}).get("max_seq_length", 4096),
36
+ load_in_4bit=load_in_4bit,
37
+ # bf16 path (load_in_4bit=False) needs >48GB for 27B — see setup script.
38
+ dtype=None, # None -> Unsloth picks bf16/fp16 for the GPU
39
+ )
40
+
41
+ model = FastVisionModel.get_peft_model(
42
+ model,
43
+ # Adapt the language backbone only (matches the TRL path's
44
+ # DEFAULT_LORA_TARGET_MODULES, which deliberately excludes the vision
45
+ # tower — cheaper, lower forgetting risk; flip if the vision side turns
46
+ # out to be the bottleneck).
47
+ finetune_vision_layers=bool(lora.get("finetune_vision_layers", False)),
48
+ finetune_language_layers=bool(lora.get("finetune_language_layers", True)),
49
+ finetune_attention_modules=bool(lora.get("finetune_attention_modules", True)),
50
+ finetune_mlp_modules=bool(lora.get("finetune_mlp_modules", True)),
51
+ r=lora.get("r", 64),
52
+ lora_alpha=lora.get("alpha", 64),
53
+ lora_dropout=lora.get("dropout", 0.0), # Unsloth is fastest at dropout=0
54
+ bias="none",
55
+ random_state=cfg.get("training", {}).get("seed", 3407),
56
+ use_gradient_checkpointing="unsloth", # Unsloth's own long-context checkpointing
57
+ )
58
+ return model, tokenizer