Codeseys commited on
Commit
7090729
·
1 Parent(s): c98928e

examples: add sdpo_real_trace_train_smoke — close the forward+backward+step link

Browse files

The framework proved the SDPO data path (validate_real_trace_alignment:
832/832 mask alignment on real ~/.claude traces) and the loss math
(test_gradient_flow: SDPO routes finite grads on TinyLM) in isolation,
but never connected them: an actual compose_loss forward + backward +
optimizer.step() on a real HF model fed by the real-trace collator.

This is the never-implemented composer_replication.examples.
sdpo_with_real_traces_production module that Modal stage_4_sdpo_smoke
referenced. It is now real and PASSES on Qwen2.5-0.5B-Instruct over 6
real error-bearing sessions:

step 0: total=2.36307 lm_ce=2.33588 sdpo_jsd=0.02718 finite=True
step 1: total=2.32758 lm_ce=2.30190 sdpo_jsd=0.02568 finite=True
SDPO channel fired (>0): True | param moved: True (max|Δ|=6.22e-05)

Gates: (1) no crash, (2) finite loss, (3) SDPO channel fires >0 (shape-gate
passes, teacher forward contributes real signal — not the silent no-op the
empty-placeholder stage_4 would give), (4) a real param moves after step().

Operational notes captured in README: target = small instruct model (NOT
nanochat — no tool-error sites by construction); B=1 fp32 keeps the
151936-vocab logit peak ~14GB (B>=2 fp32 OOMs ~27GB); bf16-on-CPU is a
>10x slowdown (emulated GEMM); don't over-truncate seq (SDPO sites sit
deep in long traces); strip_thinking defaults False for SDPO.

examples/sdpo_real_trace_train_smoke/README.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SDPO real-trace training smoke
2
+
3
+ The missing **forward + backward + optimizer step** link for SDPO.
4
+
5
+ ## Why this exists
6
+
7
+ The framework proved two halves of the SDPO loop *in isolation*:
8
+
9
+ | Half | Where | What it proves |
10
+ |---|---|---|
11
+ | Data path | `examples/validate_real_trace_alignment/` | ingestion → adapter → collator emits a batch whose `sdpo_loss_mask` lands on content tokens at ~100% alignment on **real** `~/.claude` traces |
12
+ | Loss math | `composer_replication/tests/test_gradient_flow.py` | `compose_loss` routes finite non-zero gradients through the SDPO channel — but only on a millisecond `TinyLM` stand-in (no HF model) |
13
+
14
+ Nobody had **connected** them: an actual `compose_loss` forward + backward +
15
+ `optimizer.step()` on a real HuggingFace model fed by the real-trace collator.
16
+ That is the one unproven edge — and it is exactly the never-implemented
17
+ `composer_replication.examples.sdpo_with_real_traces_production` module that the
18
+ Modal `stage_4_sdpo_smoke` referenced. This script **is** that module, made real.
19
+
20
+ ## What it asserts (the gates)
21
+
22
+ 1. The collated real-trace batch drives `compose_loss` without crashing.
23
+ 2. `total` loss is finite (not NaN/Inf) across all steps.
24
+ 3. The SDPO channel **fires**: `sdpo_jsd > 0` on ≥1 step — proves the shape-gate
25
+ at `loss.py:163` passed and the hint-conditioned teacher forward contributed
26
+ real signal (not the silent no-op the empty-placeholder stage_4 would give).
27
+ 4. A real parameter **moved** after `optimizer.step()` (training happened).
28
+
29
+ ## Run
30
+
31
+ ```bash
32
+ # Canonical PASS config (B=1 fp32 — fast native CPU GEMM, ~14GB peak):
33
+ python examples/sdpo_real_trace_train_smoke/run.py \
34
+ --max-sessions 6 --max-steps 2 --max-examples 1 --dtype fp32
35
+ ```
36
+
37
+ Verified PASS (Qwen2.5-0.5B-Instruct, CPU, 6 real `~/.claude` error sessions):
38
+
39
+ ```
40
+ collated batch: input_ids (1, 1339), sdpo_loss_mask in-loss positions = 6
41
+ step 0: total=2.36307 lm_ce=2.33588 sdpo_jsd=0.02718 finite=True
42
+ step 1: total=2.32758 lm_ce=2.30190 sdpo_jsd=0.02568 finite=True
43
+ all losses finite: True
44
+ SDPO channel fired (>0): True
45
+ param 'model.embed_tokens.weight' moved: True (max|Δ|=6.22e-05)
46
+ RESULT: PASS ✅
47
+ ```
48
+
49
+ ## Operational notes (hard-won)
50
+
51
+ - **Target model = small instruct (Qwen2.5-0.5B-Instruct), NOT nanochat.** Agent-trace
52
+ SDPO needs traces with tool-error → recovery structure. A trained nanochat is a
53
+ plain chat model with no tool-use → 0% SDPO error sites by construction. The
54
+ correct SDPO target is a small instruct model with a chat template.
55
+ - **Memory: the killer is vocab × seq × dtype.** Qwen2.5 vocab is 151,936, so fp32
56
+ logits are ~1.17 GB per `(example, 2048-tok)` forward; SDPO does **two** forwards
57
+ (student + hint-conditioned teacher). The fp32 forward+backward transiently hits
58
+ ~27 GB and trips the host/cgroup OOM killer at B≥2. **B=1 fp32 keeps the peak
59
+ ~14 GB** and uses fast native CPU GEMM.
60
+ - **Do NOT use bf16 on CPU for this.** bf16 clears the memory wall but CPUs without
61
+ AVX512-BF16 fall back to emulated GEMM — a >10× slowdown (a single step ran >13 min
62
+ vs ~30-60 s in fp32). The `--dtype bf16` flag exists but fp32 + B=1 is the fast path.
63
+ - **Sequence length carries the signal — do not over-truncate.** The error-recovery
64
+ turns sit *deep* in long agent sessions. `--max-seq-len 1024` truncated all SDPO
65
+ sites away → all-zero mask → SKIP. Keep ≥1536; the script SKIP-guards (exit 2)
66
+ rather than silently training on zero signal.
67
+ - **`--strip-thinking` defaults False** (correct for SDPO): on real Claude Code traces
68
+ the recovery turn is frequently pure `[THINKING]`; stripping empties ~67% of error
69
+ sites and the SDPO channel sees no signal.
70
+ - **Run it detached from the gateway cgroup** if iterating live:
71
+ `systemd-run --user --scope -p MemoryMax=28G -- ...`. A gateway restart SIGTERMs
72
+ every child in its cgroup (exit 143); a transient scope survives.
73
+
74
+ ## Exit codes
75
+
76
+ - `0` PASS (all gates)
77
+ - `1` FAIL (a gate failed — non-finite loss, SDPO never fired, or no param moved)
78
+ - `2` SKIP (no error-bearing sessions, no chat-template model, or mask all-zero)
examples/sdpo_real_trace_train_smoke/run.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SDPO real-trace TRAINING smoke — the missing forward+backward+step link.
2
+
3
+ Why this exists
4
+ ---------------
5
+ The framework already proves two halves of the SDPO loop in isolation:
6
+
7
+ * ``examples/validate_real_trace_alignment/run.py`` proves the REAL-trace
8
+ DATA path: ingestion -> adapter -> collator emits a batch whose
9
+ ``sdpo_loss_mask`` lands on content tokens at ~100% alignment.
10
+ * ``composer_replication/tests/test_gradient_flow.py`` proves
11
+ ``compose_loss`` routes finite non-zero gradients through the SDPO
12
+ channel — but only on a millisecond ``TinyLM`` stand-in (no HF model).
13
+
14
+ Nobody has connected them: an actual forward + backward + optimizer step
15
+ of ``compose_loss`` on a REAL HuggingFace model fed by the REAL-trace
16
+ collator. That is the one unproven edge, and it is exactly the (never
17
+ implemented) ``sdpo_with_real_traces_production`` module that the Modal
18
+ ``stage_4_sdpo_smoke`` referenced. This script IS that module, made real.
19
+
20
+ What it asserts (the smoke gates)
21
+ ---------------------------------
22
+ 1. The collated real-trace batch drives ``compose_loss`` without crashing.
23
+ 2. ``total`` loss is finite (not NaN/Inf) across all steps.
24
+ 3. The SDPO channel actually FIRES: ``sdpo_jsd`` is strictly > 0 on at
25
+ least one step (proves the shape-gate at loss.py:163 passed and the
26
+ hint-conditioned teacher forward contributed real signal — not the
27
+ silent no-op that the empty-placeholder stage_4 would have produced).
28
+ 4. A real parameter MOVED after ``optimizer.step()`` (training happened).
29
+
30
+ Runs on CPU against Qwen/Qwen2.5-0.5B-Instruct — the correct target for
31
+ agent-trace SDPO (a small instruct model with a chat template), NOT the
32
+ trained nanochat (which has no tool-use / error-recovery structure and
33
+ therefore yields 0% SDPO error sites by construction). ~$0 cost.
34
+
35
+ Usage
36
+ -----
37
+ python examples/sdpo_real_trace_train_smoke/run.py \
38
+ [--projects-dir ~/.claude/projects] \
39
+ [--max-sessions 6] [--model Qwen/Qwen2.5-0.5B-Instruct] \
40
+ [--max-steps 5] [--lr 1e-5]
41
+
42
+ Exit 0 = PASS (all gates), 1 = FAIL (a gate failed), 2 = SKIP (no
43
+ error-bearing sessions / no chat-template model available).
44
+ """
45
+ from __future__ import annotations
46
+
47
+ import argparse
48
+ import os
49
+ import sys
50
+ import traceback
51
+ from pathlib import Path
52
+
53
+
54
+ def _discover_error_sessions(projects_dir: Path, limit: int) -> list[Path]:
55
+ """Find session JSONLs containing >=1 is_error:true tool_result, skipping
56
+ subagent (`agent-*`) files. Smallest first (faster, still representative)."""
57
+ hits: list[tuple[int, Path]] = []
58
+ for p in projects_dir.rglob("*.jsonl"):
59
+ if p.name.startswith("agent-"):
60
+ continue
61
+ try:
62
+ text = p.read_text(encoding="utf-8", errors="ignore")
63
+ except OSError:
64
+ continue
65
+ if '"is_error":true' in text or '"is_error": true' in text:
66
+ hits.append((p.stat().st_size, p))
67
+ hits.sort(key=lambda t: t[0])
68
+ return [p for _, p in hits[:limit]]
69
+
70
+
71
+ def main() -> int:
72
+ ap = argparse.ArgumentParser()
73
+ ap.add_argument("--projects-dir", default=str(Path.home() / ".claude" / "projects"))
74
+ ap.add_argument("--max-sessions", type=int, default=6)
75
+ ap.add_argument("--model", default="Qwen/Qwen2.5-0.5B-Instruct")
76
+ ap.add_argument("--max-steps", type=int, default=5)
77
+ ap.add_argument("--lr", type=float, default=1e-5)
78
+ ap.add_argument("--alpha-sdpo", type=float, default=1.0,
79
+ help="SDPO channel weight. Default 1.0 (not the lib default "
80
+ "0.1) so the smoke exercises the SDPO path strongly.")
81
+ ap.add_argument("--max-seq-len", type=int, default=2048,
82
+ help="Cap collated seq len to keep the CPU forward cheap.")
83
+ ap.add_argument("--max-examples", type=int, default=4,
84
+ help="Cap examples per collated batch. Qwen2.5 vocab is "
85
+ "151936, so fp32 logits are ~1.2GB per (example, "
86
+ "2048-tok) forward; SDPO does 2 forwards. Lower this "
87
+ "if the CPU run gets OOM-killed (exit 137).")
88
+ ap.add_argument("--dtype", choices=["bf16", "fp32"], default="bf16",
89
+ help="Model+activation dtype. Default bf16 halves the giant "
90
+ "(B, T, 151936) logit tensors — the fp32 forward+backward "
91
+ "transiently hits ~27GB and trips the gateway cgroup OOM "
92
+ "killer (exit 137). bf16 keeps the smoke under the limit.")
93
+ ap.add_argument(
94
+ "--strip-thinking",
95
+ action="store_true",
96
+ help="Strip [THINKING] blocks. DEFAULT FALSE for SDPO: on real Claude "
97
+ "Code traces the recovery turn is frequently pure thinking, so "
98
+ "stripping empties ~67%% of error sites and the SDPO channel sees "
99
+ "no signal. Keep thinking for hint-distillation.",
100
+ )
101
+ args = ap.parse_args()
102
+
103
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
104
+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
105
+
106
+ import torch
107
+ from transformers import AutoModelForCausalLM, AutoTokenizer
108
+
109
+ from composer_replication import compose_loss
110
+ from composer_replication.ingestion import ClaudeCodeIngester
111
+ from composer_replication.ingestion.trace_examples import (
112
+ claude_states_to_trace_examples,
113
+ )
114
+ from composer_replication.trainer.data_collator import (
115
+ CollatorConfig,
116
+ ComposerDataCollator,
117
+ )
118
+
119
+ projects_dir = Path(args.projects_dir).expanduser()
120
+ if not projects_dir.exists():
121
+ print(f"projects dir not found: {projects_dir}")
122
+ return 2
123
+
124
+ sessions = _discover_error_sessions(projects_dir, args.max_sessions)
125
+ if not sessions:
126
+ print(f"no error-bearing sessions under {projects_dir}")
127
+ return 2
128
+
129
+ try:
130
+ tok = AutoTokenizer.from_pretrained(args.model)
131
+ except Exception as e: # noqa: BLE001
132
+ print(f"could not load tokenizer {args.model}: {e!r}")
133
+ return 2
134
+ if not getattr(tok, "chat_template", None):
135
+ print(f"{args.model} has no chat template; pick an -Instruct model")
136
+ return 2
137
+
138
+ # ------------------------------------------------------------------
139
+ # Build error-bearing trace examples from the real sessions.
140
+ # ------------------------------------------------------------------
141
+ def hint_gen(kind, _meta):
142
+ return f"Recover from the {kind}: re-check the path/args before retrying."
143
+
144
+ pad_id = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
145
+ cfg = CollatorConfig(
146
+ hint_generator=hint_gen,
147
+ enable_replay_dpo=False,
148
+ max_seq_len=args.max_seq_len,
149
+ pad_token_id=pad_id,
150
+ )
151
+ collator = ComposerDataCollator(tokenizer=tok, config=cfg)
152
+
153
+ err_examples: list[dict] = []
154
+ for path in sessions:
155
+ try:
156
+ ing = ClaudeCodeIngester(skip_sidechain=True, strip_thinking=args.strip_thinking)
157
+ states = list(ing.ingest(path))
158
+ examples = claude_states_to_trace_examples(states)
159
+ for ex in examples:
160
+ if any(t.get("tool_error") for t in ex["turns"]):
161
+ err_examples.append(ex)
162
+ except Exception as e: # noqa: BLE001
163
+ print(f" skip {path.name[:18]}: {e!r}")
164
+ if not err_examples:
165
+ print("no error-turn examples extracted — nothing to train on")
166
+ return 2
167
+ print(f"extracted {len(err_examples)} error-bearing examples from "
168
+ f"{len(sessions)} sessions")
169
+
170
+ # Build ONE collated batch (cap to 4 examples to keep the CPU step cheap).
171
+ batch = collator(err_examples[:args.max_examples])
172
+ if "sdpo_loss_mask" not in batch or "ctx_teacher_input_ids" not in batch:
173
+ print("collated batch has no SDPO channel (no usable error sites) — "
174
+ "cannot run the SDPO training smoke")
175
+ return 2
176
+ in_loss = int((batch["sdpo_loss_mask"] == 1).sum().item())
177
+ if in_loss == 0:
178
+ print("sdpo_loss_mask is all-zero (empty-recovery sites) — re-run "
179
+ "WITHOUT --strip-thinking to recover SDPO signal")
180
+ return 2
181
+ print(f"collated batch: input_ids {tuple(batch['input_ids'].shape)}, "
182
+ f"sdpo_loss_mask in-loss positions = {in_loss}")
183
+
184
+ # ------------------------------------------------------------------
185
+ # Real HF model + optimizer. CPU, fp32, tiny LR.
186
+ # ------------------------------------------------------------------
187
+ print(f"loading {args.model} (CPU, {args.dtype}) ...")
188
+ model_dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float32
189
+ try:
190
+ model = AutoModelForCausalLM.from_pretrained(args.model, dtype=model_dtype)
191
+ except Exception as e: # noqa: BLE001
192
+ print(f"could not load model {args.model}: {e!r}")
193
+ return 2
194
+ model.train()
195
+ opt = torch.optim.SGD(model.parameters(), lr=args.lr)
196
+
197
+ # Snapshot a trainable parameter to prove it moves after .step().
198
+ watch_name, watch_param = next(
199
+ (n, p) for n, p in model.named_parameters() if p.requires_grad
200
+ )
201
+ before = watch_param.detach().clone()
202
+
203
+ # Move batch tensors to model device.
204
+ dev = next(model.parameters()).device
205
+ inputs = {k: (v.to(dev) if hasattr(v, "to") else v) for k, v in batch.items()}
206
+
207
+ sdpo_fired = False
208
+ finite_all = True
209
+ print("=" * 64)
210
+ print(f"SDPO REAL-TRACE TRAINING SMOKE (alpha_sdpo={args.alpha_sdpo}, "
211
+ f"steps={args.max_steps}, lr={args.lr})")
212
+ print("=" * 64)
213
+ try:
214
+ for step in range(args.max_steps):
215
+ opt.zero_grad(set_to_none=True)
216
+ comps = compose_loss(
217
+ model,
218
+ inputs,
219
+ alpha_sdpo=args.alpha_sdpo,
220
+ beta_replay=0.0, # DPO channel off — no ref logprobs in smoke
221
+ )
222
+ d = comps.detached()
223
+ finite = all(
224
+ (x == x) and (x not in (float("inf"), float("-inf")))
225
+ for x in d.values()
226
+ )
227
+ finite_all = finite_all and finite
228
+ if d["sdpo_jsd"] > 0.0:
229
+ sdpo_fired = True
230
+ comps.total.backward()
231
+ opt.step()
232
+ print(f" step {step}: total={d['total']:.5f} lm_ce={d['lm_ce']:.5f} "
233
+ f"sdpo_jsd={d['sdpo_jsd']:.5f} finite={finite}")
234
+ except Exception as e: # noqa: BLE001
235
+ print(f" CRASH during training: {e!r}")
236
+ traceback.print_exc()
237
+ return 1
238
+
239
+ moved = not torch.equal(before, watch_param.detach())
240
+ delta = float((watch_param.detach() - before).abs().max())
241
+
242
+ print("-" * 64)
243
+ print(f" all losses finite: {finite_all}")
244
+ print(f" SDPO channel fired (>0): {sdpo_fired}")
245
+ print(f" param '{watch_name[:40]}' moved: {moved} (max|Δ|={delta:.2e})")
246
+ ok = finite_all and sdpo_fired and moved
247
+ print(f" RESULT: {'PASS ✅' if ok else 'FAIL ❌'}")
248
+ if not ok:
249
+ if not finite_all:
250
+ print(" ✗ a loss was non-finite")
251
+ if not sdpo_fired:
252
+ print(" ✗ SDPO channel never fired (>0) — shape-gate skipped it "
253
+ "or mask was empty; the distillation signal did not flow")
254
+ if not moved:
255
+ print(" ✗ watched parameter did not move — no real training step")
256
+ return 0 if ok else 1
257
+
258
+
259
+ if __name__ == "__main__":
260
+ sys.exit(main())