Pratyush-01 commited on
Commit
6aaeee1
·
verified ·
1 Parent(s): 6a3d97c

training: add early-stop callback + lr=1e-5 for next run

Browse files
Files changed (1) hide show
  1. train/job_train.py +508 -0
train/job_train.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "unsloth",
5
+ # "trl==0.24.0",
6
+ # "transformers",
7
+ # "datasets",
8
+ # "peft",
9
+ # "accelerate",
10
+ # "bitsandbytes",
11
+ # "wandb",
12
+ # # setuptools/wheel/pip aren't ML deps but torch._inductor.cpp_builder
13
+ # # imports them at runtime when probing CPU SIMD ISA inside the very
14
+ # # first GRPO training step. Missing them => "ModuleNotFoundError:
15
+ # # No module named 'setuptools'" deep in compile_fx. Add them defensively
16
+ # # alongside the env-level torch.compile disable below.
17
+ # "setuptools",
18
+ # "wheel",
19
+ # "pip",
20
+ # "scipy>=1.10,<2.0",
21
+ # "sympy>=1.12,<2.0",
22
+ # "pydantic>=2.5,<3.0",
23
+ # "numpy>=1.24,<3.0",
24
+ # "openenv-core[core]>=0.2.2",
25
+ # "huggingface_hub>=0.24,<1.0",
26
+ # "matplotlib>=3.7,<4.0",
27
+ # ]
28
+ # ///
29
+ """PhysiX RLVR training driver for Hugging Face Jobs.
30
+
31
+ Deploy with:
32
+
33
+ hf jobs uv run job_train.py \
34
+ --image unsloth/unsloth:2026.3.8-pt2.9.0-vllm-0.16.0-cu12.8-studio-release \
35
+ --flavor l40sx1 \
36
+ --secrets HF_TOKEN \
37
+ --secrets WANDB_API_KEY \
38
+ -v hf://datasets/Pratyush-01/physix-live-src:/physix-live \
39
+ --timeout 3h
40
+
41
+ How dependencies work on HF Jobs (lesson from the 2026-04-26 failure):
42
+ The Unsloth studio-release image provides CUDA toolkit, system libs, and a
43
+ *wheel cache* — but every `hf jobs uv run` job creates a fresh, isolated
44
+ uv-managed venv that only contains packages declared in the inline block
45
+ above. There is NO carry-over from /opt/conda site-packages. The official
46
+ unsloth-jobs blog example follows this exact pattern (declare unsloth, trl,
47
+ datasets in the inline deps).
48
+
49
+ We pin trl==0.24.0 hard because Unsloth's patch_trl_openenv() does
50
+ inspect.getsource(...) on a TRL internal function, and that breaks with
51
+ "OSError: could not get source code" on newer TRL. All other ML deps are
52
+ left unpinned so Unsloth can pull a self-consistent set off its wheel
53
+ cache (matches torch 2.9.0 / vLLM 0.16.0 / CUDA 12.8 baked into the image).
54
+
55
+ The mounted dataset at /physix-live contains the source we want to train,
56
+ installed as an editable package below.
57
+ """
58
+
59
+ from __future__ import annotations
60
+
61
+ import os
62
+ import shutil
63
+ import subprocess
64
+ import sys
65
+ from pathlib import Path
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Environment hardening (lessons from the Spaces run)
70
+ # ---------------------------------------------------------------------------
71
+ # HF Jobs runs the container as a non-root UID with no /etc/passwd entry,
72
+ # so getpass.getuser() raises and torch._inductor blows up. Same as Spaces.
73
+ def _harden_env() -> None:
74
+ os.environ.setdefault("USER", "physix")
75
+ os.environ.setdefault("LOGNAME", "physix")
76
+ os.environ.setdefault("HOME", "/tmp/home")
77
+
78
+ # Route every cache/scratch dir under /tmp (writable everywhere).
79
+ os.environ.setdefault("HF_HOME", "/tmp/hf_cache")
80
+ os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", "/tmp/torchinductor_cache")
81
+ os.environ.setdefault("TRITON_CACHE_DIR", "/tmp/triton_cache")
82
+ os.environ.setdefault("XDG_CACHE_HOME", "/tmp/xdg-cache")
83
+ os.environ.setdefault("WANDB_DIR", "/tmp/wandb")
84
+ os.environ.setdefault("WANDB_CACHE_DIR", "/tmp/wandb-cache")
85
+ os.environ.setdefault("WANDB_DATA_DIR", "/tmp/wandb-data")
86
+ os.environ.setdefault("WANDB_ARTIFACT_DIR", "/tmp/wandb-artifacts")
87
+ os.environ.setdefault("WANDB_CONFIG_DIR", "/tmp/wandb-config")
88
+
89
+ # Disable wandb model artifact uploads (we push to HF Hub instead).
90
+ os.environ.setdefault("WANDB_DISABLE_ARTIFACTS", "true")
91
+ os.environ.setdefault("WANDB_LOG_MODEL", "false")
92
+ os.environ.setdefault("WANDB_PROJECT", "physix-live")
93
+
94
+ # Unsloth / torch tuning.
95
+ #
96
+ # We disable torch.compile / inductor at multiple layers:
97
+ # - UNSLOTH_COMPILE_DISABLE: skips Unsloth's own torch.compile wraps
98
+ # - TORCH_COMPILE_DISABLE: short-circuits torch.compile() calls
99
+ # - TORCHINDUCTOR_DISABLE: prevents inductor backend invocation
100
+ # - TORCHDYNAMO_DISABLE: stops dynamo from tracing in the first place
101
+ # All four needed because Unsloth GRPO's _unsloth_training_step still
102
+ # triggers an inductor CPU-SIMD probe (cpu_vec_isa.pick_vec_isa) on the
103
+ # first step, which crashes if setuptools or a host C++ toolchain isn't
104
+ # present in the uv venv. We don't want compile speedups on a 3B-LoRA
105
+ # run anyway — the eager path is plenty fast on L40S.
106
+ os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")
107
+ os.environ.setdefault("TORCH_COMPILE_DISABLE", "1")
108
+ os.environ.setdefault("TORCHINDUCTOR_DISABLE", "1")
109
+ os.environ.setdefault("TORCHDYNAMO_DISABLE", "1")
110
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
111
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
112
+ os.environ.setdefault("PYTHONUNBUFFERED", "1")
113
+
114
+ # Mirror HF_TOKEN into the standard names that huggingface_hub picks up.
115
+ if os.environ.get("HF_TOKEN"):
116
+ os.environ.setdefault("HUGGINGFACE_HUB_TOKEN", os.environ["HF_TOKEN"])
117
+
118
+ for d in (
119
+ os.environ["HOME"],
120
+ os.environ["HF_HOME"],
121
+ os.environ["TORCHINDUCTOR_CACHE_DIR"],
122
+ os.environ["TRITON_CACHE_DIR"],
123
+ os.environ["XDG_CACHE_HOME"],
124
+ os.environ["WANDB_DIR"],
125
+ os.environ["WANDB_CACHE_DIR"],
126
+ os.environ["WANDB_DATA_DIR"],
127
+ os.environ["WANDB_ARTIFACT_DIR"],
128
+ os.environ["WANDB_CONFIG_DIR"],
129
+ ):
130
+ Path(d).mkdir(parents=True, exist_ok=True)
131
+
132
+
133
+ def _banner(msg: str) -> None:
134
+ line = "=" * 72
135
+ print(f"\n{line}\n {msg}\n{line}", flush=True)
136
+
137
+
138
+ def _run(cmd: list[str], *, env: dict | None = None) -> None:
139
+ print(f"$ {' '.join(cmd)}", flush=True)
140
+ subprocess.run(cmd, check=True, env=env or os.environ.copy())
141
+
142
+
143
+ def _require(name: str) -> str:
144
+ val = os.environ.get(name)
145
+ if not val:
146
+ sys.exit(f"FATAL: required secret {name!r} is not set on the job")
147
+ return val
148
+
149
+
150
+ def _stage_physix_live() -> Path:
151
+ """The dataset is mounted read-only at /physix-live. pip install -e
152
+ needs a writable tree (it creates an .egg-info), so copy to /tmp/src
153
+ and install from there."""
154
+ src = Path("/physix-live")
155
+ if not src.exists():
156
+ sys.exit(
157
+ "FATAL: expected physix-live source mounted at /physix-live. "
158
+ "Pass `-v hf://datasets/<user>/physix-live-src:/physix-live` "
159
+ "when submitting the job."
160
+ )
161
+ dst = Path("/tmp/src/physix-live")
162
+ if dst.exists():
163
+ shutil.rmtree(dst)
164
+ dst.parent.mkdir(parents=True, exist_ok=True)
165
+ shutil.copytree(src, dst)
166
+ return dst
167
+
168
+
169
+ def _install_physix(repo: Path) -> None:
170
+ # The base image already pins torch / transformers / unsloth / trl etc.
171
+ # --no-deps prevents pip from upgrading any of them.
172
+ #
173
+ # The Unsloth uv-managed environment does NOT ship pip-the-module by
174
+ # default (`python -m pip` raises "No module named pip"). Try the `uv
175
+ # pip` shim first (uv is guaranteed to be on PATH under `hf jobs uv
176
+ # run`); if that fails for any reason, bootstrap pip via ensurepip and
177
+ # fall back. Either path uses --no-deps so the carefully pinned
178
+ # torch/transformers/unsloth/trl in the base image stay untouched.
179
+ install_args = ["--no-cache-dir", "-e", str(repo), "--no-deps"]
180
+ try:
181
+ _run(["uv", "pip", "install", "--python", sys.executable, *install_args])
182
+ return
183
+ except (subprocess.CalledProcessError, FileNotFoundError) as exc:
184
+ print(f"[install] uv pip path failed ({exc!r}); bootstrapping pip via ensurepip", flush=True)
185
+ _run([sys.executable, "-m", "ensurepip", "--upgrade"])
186
+ _run([sys.executable, "-m", "pip", "install", *install_args])
187
+
188
+
189
+ def _sanity_check_imports() -> None:
190
+ print("--- Sanity import check ---", flush=True)
191
+ code = (
192
+ "import torch, trl, transformers, datasets, wandb, unsloth, physix; "
193
+ "print(f'torch={torch.__version__} cuda={torch.cuda.is_available()} "
194
+ "device={torch.cuda.get_device_name(0) if torch.cuda.is_available() else None}'); "
195
+ "print(f'unsloth={unsloth.__version__} trl={trl.__version__} "
196
+ "transformers={transformers.__version__} datasets={datasets.__version__}'); "
197
+ "print(f'physix loaded from {physix.__file__}'); "
198
+ "assert trl.__version__ == '0.24.0', f'trl must be pinned to 0.24.0, got {trl.__version__}'"
199
+ )
200
+ _run([sys.executable, "-c", code])
201
+
202
+
203
+ def _gpu_check() -> None:
204
+ print("--- GPU check ---", flush=True)
205
+ try:
206
+ subprocess.run(["nvidia-smi"], check=True)
207
+ except FileNotFoundError:
208
+ sys.exit("FATAL: nvidia-smi missing — job hardware is not GPU")
209
+
210
+
211
+ # ---------------------------------------------------------------------------
212
+ # Per-model training profile.
213
+ #
214
+ # Each profile bundles the (base-model, lora-r, hub repo names, run names,
215
+ # lr, num_steps) tuple so we can switch between 1.5B and 7B with a single
216
+ # constant change. Sized for A100-80GB.
217
+ # ---------------------------------------------------------------------------
218
+ PROFILES: dict[str, dict] = {
219
+ "1.5b": {
220
+ "base_model": "Qwen/Qwen2.5-1.5B-Instruct",
221
+ "sft_lora_r": "32",
222
+ "grpo_lora_r": "32",
223
+ "sft_lr": "2e-5",
224
+ "grpo_lr": "5e-6",
225
+ "sft_epochs": "3",
226
+ "num_steps": "300",
227
+ "num_generations": "4",
228
+ "max_completion": "256",
229
+ "hub_final_repo": "Pratyush-01/physix-1.5b-rl",
230
+ "hub_ckpt_repo": "Pratyush-01/physix-1.5b-rl-ckpt",
231
+ "sft_run_name": "physix-sft-1.5b",
232
+ "grpo_run_name": "physix-grpo-1.5b",
233
+ },
234
+ "3b": {
235
+ "base_model": "Qwen/Qwen2.5-3B-Instruct",
236
+ "sft_lora_r": "32",
237
+ "grpo_lora_r": "32",
238
+ "sft_lr": "1.5e-5",
239
+ # LR history for 3B + LoRA-32 GRPO on damped_spring:
240
+ # 3e-6 (run c8wgysg4) → flat for 67+ steps, near-zero gradient
241
+ # 3e-5 (run xrlhnyty) → converged to reward_match≈0.999 by step ~250/500
242
+ # curve was too steep; model saturated early
243
+ # 1e-5 (this run) → ~1/3 of 3e-5; projects convergence at ~750 steps,
244
+ # so 500 steps lands at ~67% of the curve —
245
+ # a smooth, steadily rising reward trajectory.
246
+ # Early stopping fires automatically if std
247
+ # stays flat for 50 consecutive steps.
248
+ "grpo_lr": "1e-5",
249
+ "sft_epochs": "4",
250
+ # Budget cap: early stopping will fire well before step 500 if the
251
+ # policy converges (reward_std < 0.05 for 50 consecutive steps).
252
+ "num_steps": "500",
253
+ "num_generations": "4",
254
+ "max_completion": "384",
255
+ "hub_final_repo": "Pratyush-01/physix-3b-rl",
256
+ "hub_ckpt_repo": "Pratyush-01/physix-3b-rl-ckpt",
257
+ "sft_run_name": "physix-sft-3b-v4",
258
+ "grpo_run_name": "physix-grpo-3b-lr1e5",
259
+ },
260
+ "7b": {
261
+ "base_model": "Qwen/Qwen2.5-7B-Instruct",
262
+ # Smaller LoRA rank: 7B has ~4.6× more params than 1.5B so even
263
+ # at r=16 the trainable count (~40M) is comparable to 1.5B at r=32.
264
+ "sft_lora_r": "16",
265
+ "grpo_lora_r": "16",
266
+ # Lower LR for the bigger base.
267
+ "sft_lr": "1e-5",
268
+ "grpo_lr": "2e-6",
269
+ "sft_epochs": "3",
270
+ "num_steps": "200",
271
+ "num_generations": "4",
272
+ "max_completion": "256",
273
+ "hub_final_repo": "Pratyush-01/physix-7b-rl",
274
+ "hub_ckpt_repo": "Pratyush-01/physix-7b-rl-ckpt",
275
+ "sft_run_name": "physix-sft-7b",
276
+ "grpo_run_name": "physix-grpo-7b",
277
+ },
278
+ }
279
+
280
+ #: Active profile. ``3b`` chosen for the fast-iteration run — best
281
+ #: capacity/wall-clock tradeoff for the PhysiX 3-system POC.
282
+ ACTIVE_PROFILE: str = "3b"
283
+
284
+
285
+ def _profile() -> dict:
286
+ return PROFILES[ACTIVE_PROFILE]
287
+
288
+
289
+ def _run_sft() -> None:
290
+ p = _profile()
291
+ _banner(f"Step 1/2: SFT warm-start ({p['base_model']})")
292
+ _run([
293
+ sys.executable, "-m", "physix.training.sft",
294
+ "--model", p["base_model"],
295
+ "--output-dir", "/tmp/physix-sft",
296
+ "--epochs", p["sft_epochs"],
297
+ "--instances-per-system", "64",
298
+ "--lora-r", p["sft_lora_r"],
299
+ "--learning-rate", p["sft_lr"],
300
+ "--wandb-run-name", p["sft_run_name"],
301
+ # Push the merged SFT model to the same checkpoint repo GRPO uses,
302
+ # under <repo>/sft. Lets a future restart skip SFT and reuse it.
303
+ "--hub-checkpoint-repo-id", p["hub_ckpt_repo"],
304
+ "--seed", "0",
305
+ ])
306
+
307
+
308
+ def _try_resume_from_grpo_checkpoint() -> tuple[Path | None, str | None]:
309
+ """Look for a prior GRPO checkpoint in the Hub repo for this profile.
310
+
311
+ Returns ``(local_path, wandb_run_id)`` if a checkpoint was found and
312
+ successfully downloaded, else ``(None, None)``. The downloaded
313
+ directory is what gets passed to ``--resume-from-checkpoint``; the
314
+ run id (when present) is set as ``WANDB_RUN_ID`` so the GRPO chart
315
+ continues on the same timeline rather than starting fresh.
316
+ """
317
+ p = _profile()
318
+ repo_id = p["hub_ckpt_repo"]
319
+ try:
320
+ from physix.training.checkpoints import (
321
+ download_checkpoint,
322
+ find_latest_grpo_checkpoint,
323
+ )
324
+ except ImportError as exc:
325
+ print(f"[resume] checkpoints helper not importable yet: {exc}", flush=True)
326
+ return None, None
327
+
328
+ token = os.environ.get("HF_TOKEN")
329
+ handle = find_latest_grpo_checkpoint(repo_id, token=token)
330
+ if handle is None:
331
+ print(f"[resume] No prior GRPO checkpoint in {repo_id}; cold start.", flush=True)
332
+ return None, None
333
+
334
+ print(
335
+ f"[resume] Found prior GRPO checkpoint at {handle.hub_url} (step={handle.step}). "
336
+ f"Downloading to /tmp/physix-grpo-resume ...",
337
+ flush=True,
338
+ )
339
+ local = download_checkpoint(handle, "/tmp/physix-grpo-resume", token=token)
340
+
341
+ # Look up the W&B run id stashed at repo root by the on_train_begin
342
+ # callback. If present, we'll pass it through so wandb.init resumes
343
+ # the same run and the loss/reward charts stay continuous.
344
+ run_id: str | None = None
345
+ try:
346
+ from huggingface_hub import hf_hub_download
347
+
348
+ run_id_path = hf_hub_download(
349
+ repo_id=repo_id,
350
+ filename="wandb_run_id.txt",
351
+ repo_type="model",
352
+ token=token,
353
+ )
354
+ run_id = Path(run_id_path).read_text().strip() or None
355
+ if run_id:
356
+ print(f"[resume] W&B run id {run_id} — chart will continue on the same timeline.", flush=True)
357
+ except Exception as exc: # noqa: BLE001
358
+ print(f"[resume] No wandb_run_id.txt on repo (will start fresh W&B run): {exc}", flush=True)
359
+
360
+ return local, run_id
361
+
362
+
363
+ def _run_grpo(
364
+ *,
365
+ lora_adapter_repo: str | None = None,
366
+ resume_from_checkpoint: Path | None = None,
367
+ ) -> None:
368
+ """Run the GRPO step.
369
+
370
+ Three modes (mutually exclusive):
371
+ - Cold start (default): warm from /tmp/physix-sft/merged.
372
+ - From an existing Hub LoRA adapter: ``lora_adapter_repo`` set.
373
+ - Resume from a prior in-flight ckpt: ``resume_from_checkpoint`` set
374
+ (continues the SAME wandb run id when one is published on the repo).
375
+
376
+ Reward set (physix.training.reward_fns):
377
+ match, match_dense, correctness, simplicity, format
378
+
379
+ Anti-hack invariants (RCA from 5kuqns9x):
380
+ - ``progress`` removed (duplicated ``match`` in single-turn).
381
+ - ``simplicity`` gated on R² ≥ 0.10.
382
+ - ``format`` requires simulation success, not just parse success.
383
+ - Three correctness-shaped signals dominate the GRPO advantage.
384
+ """
385
+ p = _profile()
386
+ num_steps = int(p["num_steps"])
387
+ _banner(f"GRPO RLVR ({num_steps} steps on {p['base_model']})")
388
+ cmd = [
389
+ sys.executable, "-m", "physix.training.loop",
390
+ "--model", p["base_model"],
391
+ "--output-dir", "/tmp/physix-grpo",
392
+ "--num-steps", str(num_steps),
393
+ "--num-generations", p["num_generations"],
394
+ "--max-completion-length", p["max_completion"],
395
+ "--learning-rate", p["grpo_lr"],
396
+ "--instances-per-system", "64",
397
+ "--lora-r", p["grpo_lora_r"],
398
+ "--save-method", "merged_16bit",
399
+ "--push-to-hub",
400
+ "--hub-repo-id", p["hub_final_repo"],
401
+ "--hub-checkpoint-repo-id", p["hub_ckpt_repo"],
402
+ "--wandb-project", "physix-live",
403
+ "--wandb-run-name", p["grpo_run_name"],
404
+ "--early-stop-patience", "50",
405
+ "--seed", "0",
406
+ ]
407
+ if resume_from_checkpoint is not None:
408
+ cmd += ["--resume-from-checkpoint", str(resume_from_checkpoint)]
409
+ elif lora_adapter_repo:
410
+ cmd += ["--lora-adapter-repo", lora_adapter_repo]
411
+ else:
412
+ cmd += ["--sft-checkpoint", "/tmp/physix-sft/merged"]
413
+ _run(cmd)
414
+
415
+
416
+ # ---------------------------------------------------------------------------
417
+ # Resume configuration (baked in deliberately).
418
+ #
419
+ # We ship resume parameters as module-level constants instead of `-e` env
420
+ # flags because `hf jobs uv run -e KEY=VAL` was observed to silently drop
421
+ # env entries on submission (the job spec's `environment` dict ends up
422
+ # containing only the auto-injected LOCAL_FILES_ENCODED). The script
423
+ # encoding is reliable, so embedding the constants here is the
424
+ # fail-safe path.
425
+ #
426
+ # To do a fresh run instead, set RESUME_LORA_REPO to None.
427
+ #
428
+ # Note: we deliberately do NOT resume into the SAME W&B run id this time
429
+ # (RESUME_WANDB_RUN_ID = None). The previous run 5kuqns9x logged 4 reward
430
+ # components; this one logs 3 (no_progress). Continuing the same chart
431
+ # would mix two different reward setups on one timeline, which is
432
+ # misleading. Instead we start a fresh run and link back to the source
433
+ # run via wandb config + summary.
434
+ # ---------------------------------------------------------------------------
435
+ #: When set, skip SFT and warm-start GRPO from this Hub LoRA adapter.
436
+ #: Must be ``None`` when switching base models — a 1.5B adapter cannot
437
+ #: be loaded onto a 7B base. Only set this to resume the *same* model
438
+ #: family from a prior interrupted run.
439
+ RESUME_LORA_REPO: str | None = None
440
+ RESUME_FROM_WANDB_RUN: str | None = None # informational only (link)
441
+
442
+
443
+ def main() -> None:
444
+ _harden_env()
445
+ if RESUME_FROM_WANDB_RUN:
446
+ # Pin the source run as W&B config so the new run's Overview tab
447
+ # shows the lineage. We do NOT set WANDB_RUN_ID here.
448
+ os.environ["WANDB_RESUMED_FROM"] = RESUME_FROM_WANDB_RUN
449
+ print(
450
+ f"[resume] Warm-starting from W&B run {RESUME_FROM_WANDB_RUN} "
451
+ f"(https://wandb.ai/pratyush01/physix-live/runs/{RESUME_FROM_WANDB_RUN})",
452
+ flush=True,
453
+ )
454
+
455
+ resume_lora = RESUME_LORA_REPO
456
+ p = _profile()
457
+
458
+ if resume_lora:
459
+ _banner(
460
+ f"PhysiX RLVR RESUME job ({ACTIVE_PROFILE} on A100-large)\n"
461
+ f" adapter: {resume_lora}\n"
462
+ f" steps: {p['num_steps']}\n"
463
+ f" wandb: {os.environ.get('WANDB_RUN_ID', '<new>')}"
464
+ )
465
+ else:
466
+ _banner(
467
+ f"PhysiX RLVR training job ({ACTIVE_PROFILE} / {p['base_model']} on A100-large)"
468
+ )
469
+ _require("HF_TOKEN")
470
+ _require("WANDB_API_KEY")
471
+ _gpu_check()
472
+
473
+ repo = _stage_physix_live()
474
+ _install_physix(repo)
475
+ _sanity_check_imports()
476
+
477
+ if resume_lora:
478
+ # Forced LoRA resume (RESUME_LORA_REPO set above) — skip SFT and
479
+ # warm-start GRPO from a specific Hub adapter, fresh wandb run.
480
+ _run_grpo(lora_adapter_repo=resume_lora)
481
+ else:
482
+ # Auto-resume: if a prior GRPO checkpoint already exists in the
483
+ # checkpoint repo (e.g. previous job died at step 87), pick up
484
+ # where it left off and continue the SAME wandb run id so the
485
+ # loss/reward chart is one continuous line. If nothing's there,
486
+ # do the normal SFT -> GRPO cold start.
487
+ ckpt_local, prior_run_id = _try_resume_from_grpo_checkpoint()
488
+ if ckpt_local is not None:
489
+ if prior_run_id:
490
+ # wandb.init(resume="allow") inside loop.py picks this up.
491
+ os.environ["WANDB_RUN_ID"] = prior_run_id
492
+ os.environ["WANDB_RESUME"] = "allow"
493
+ _run_grpo(resume_from_checkpoint=ckpt_local)
494
+ else:
495
+ _run_sft()
496
+ _run_grpo()
497
+
498
+ _banner("DONE")
499
+ print(
500
+ f"Final model → https://huggingface.co/{p['hub_final_repo']}\n"
501
+ f"Checkpoints → https://huggingface.co/{p['hub_ckpt_repo']}\n"
502
+ f"W&B project → https://wandb.ai/pratyush01/physix-live\n",
503
+ flush=True,
504
+ )
505
+
506
+
507
+ if __name__ == "__main__":
508
+ main()