DavidBShan commited on
Commit
e7fdde0
·
verified ·
1 Parent(s): 42d88e5

Upload folder using huggingface_hub

Browse files
code/autoslm/engine/disaggregated.py CHANGED
@@ -249,7 +249,6 @@ def build_accelerate_launch_cmd(
249
  is the default because it shards the base weights — required for the 35B-A3B whose base does not
250
  fit one card replicated; for small models it is still correct, just less memory-critical.
251
  """
252
- py = python_bin or os.environ.get("AUTOSLM_PYTHON_BIN", "python")
253
  cmd = [
254
  "accelerate",
255
  "launch",
@@ -272,16 +271,24 @@ def build_accelerate_launch_cmd(
272
  # we must NOT pass --multi_gpu here. These are accelerate-launch FSDP flags (accelerate>=1.4).
273
  cmd += [
274
  "--use_fsdp",
 
 
 
 
 
 
 
 
275
  "--fsdp_sharding_strategy",
276
- "FULL_SHARD",
277
  "--fsdp_auto_wrap_policy",
278
  "TRANSFORMER_BASED_WRAP",
279
- # FULL_STATE_DICT (not SHARDED): transformers' Trainer rejects save_only_model which
280
- # GRPOConfig sets alongside SHARDED_STATE_DICT ("save_only_model is not compatible with
281
- # FSDP state dict type 'SHARDED_STATE_DICT'"). FULL gathers the (small LoRA) adapter on
282
- # rank 0 at save time, which is what trainer.save_model needs anyway. Fine for the dense
283
- # 1-9B models here; a 70B+ base would want SHARDED + save_only_model off, but those route
284
- # to TP inference, not a sharded full-state save.
285
  "--fsdp_state_dict_type",
286
  "FULL_STATE_DICT",
287
  ]
@@ -350,20 +357,41 @@ def wait_for_server_health(
350
  proc: subprocess.Popen | None = None,
351
  log_path: str | None = None,
352
  interval: float = 3.0,
 
 
353
  ) -> None:
354
  """Block until the rollout server answers ``/health/`` 200, the timeout elapses, or the
355
  subprocess dies (fail fast — a dead server would otherwise hang the trainer at first generation).
356
  On any failure the server log tail is appended (the HTTP port stays unbound until the worker
357
- finishes loading the model, so a load/OOM crash surfaces only as 'connection refused')."""
 
 
 
 
 
358
  url = f"http://127.0.0.1:{port}/health/"
359
  deadline = time.time() + timeout
360
  last = None
 
 
 
 
361
  while time.time() < deadline:
 
 
 
 
 
 
 
 
362
  if proc is not None and proc.poll() is not None:
363
  raise RuntimeError(
364
  f"vllm-serve exited (code {proc.returncode}) before becoming healthy.\n"
365
  f"--- vllm-serve log tail ---\n{_server_log_tail(log_path)}"
366
  )
 
 
367
  try:
368
  with urllib.request.urlopen(url, timeout=interval) as r:
369
  if 200 <= r.status < 300:
 
249
  is the default because it shards the base weights — required for the 35B-A3B whose base does not
250
  fit one card replicated; for small models it is still correct, just less memory-critical.
251
  """
 
252
  cmd = [
253
  "accelerate",
254
  "launch",
 
271
  # we must NOT pass --multi_gpu here. These are accelerate-launch FSDP flags (accelerate>=1.4).
272
  cmd += [
273
  "--use_fsdp",
274
+ # SHARD_GRAD_OP (ZeRO-2: shard gradients+optimizer, REPLICATE parameters) — NOT FULL_SHARD.
275
+ # TRL's per-step weight sync calls peft merge_adapter() -> get_delta_weight() ->
276
+ # weight_B @ weight_A; under FULL_SHARD the LoRA weights are param-sharded so each rank
277
+ # holds a slice and the matmul fails ("inconsistent tensor size [32768] vs [24576]").
278
+ # SHARD_GRAD_OP keeps params whole on every rank so the merge sees full LoRA weights, while
279
+ # still sharding the optimizer/grads. Fine for the dense 1-9B bases (replicated base fits);
280
+ # a base too big to replicate (35B) would need FULL_SHARD + a TRL patch that gathers LoRA
281
+ # before merge — out of scope here.
282
  "--fsdp_sharding_strategy",
283
+ "SHARD_GRAD_OP",
284
  "--fsdp_auto_wrap_policy",
285
  "TRANSFORMER_BASED_WRAP",
286
+ # use_orig_params keeps the original (un-flattened) parameter tensors so peft can read
287
+ # weight_A/weight_B with their real shapes during the merge.
288
+ "--fsdp_use_orig_params",
289
+ "true",
290
+ # FULL_STATE_DICT: transformers' Trainer rejects save_only_model (set by GRPOConfig)
291
+ # alongside SHARDED_STATE_DICT; FULL gathers the small LoRA adapter on rank 0 at save time.
292
  "--fsdp_state_dict_type",
293
  "FULL_STATE_DICT",
294
  ]
 
357
  proc: subprocess.Popen | None = None,
358
  log_path: str | None = None,
359
  interval: float = 3.0,
360
+ on_wait=None,
361
+ on_wait_every: float = 60.0,
362
  ) -> None:
363
  """Block until the rollout server answers ``/health/`` 200, the timeout elapses, or the
364
  subprocess dies (fail fast — a dead server would otherwise hang the trainer at first generation).
365
  On any failure the server log tail is appended (the HTTP port stays unbound until the worker
366
+ finishes loading the model, so a load/OOM crash surfaces only as 'connection refused').
367
+
368
+ ``on_wait`` (called every ``on_wait_every`` s while waiting) lets the caller emit a liveness
369
+ heartbeat during a long boot: a BIG model (35B bf16 ~70 GB + tilelang/CUDA-graph JIT) can take
370
+ >20 min to bind the port, and the control plane's no-heartbeat STALL detector (~25 min) would
371
+ otherwise kill the run mid-boot even though it is healthy-progressing."""
372
  url = f"http://127.0.0.1:{port}/health/"
373
  deadline = time.time() + timeout
374
  last = None
375
+ # Fire the FIRST boot heartbeat promptly at loop entry, not one full ``on_wait_every`` in:
376
+ # the poller's stall clock may already be near its limit after the work between rl_start and
377
+ # server launch, so a 60s-late first ping could let it kill the run before any rl_server_boot.
378
+ _next_ping = time.time()
379
  while time.time() < deadline:
380
+ if on_wait is not None and time.time() >= _next_ping:
381
+ with contextlib.suppress(Exception):
382
+ on_wait()
383
+ _next_ping = time.time() + on_wait_every
384
+ # ``on_wait`` (the worker's heartbeat) can BLOCK on a slow Hugging Face upload, so re-check
385
+ # liveness AND the deadline AFTER it returns: otherwise a blocking heartbeat would both mask
386
+ # a dead vllm-serve process and let the loop overrun ``timeout`` (the while-condition only
387
+ # re-checks at the top of the NEXT iteration).
388
  if proc is not None and proc.poll() is not None:
389
  raise RuntimeError(
390
  f"vllm-serve exited (code {proc.returncode}) before becoming healthy.\n"
391
  f"--- vllm-serve log tail ---\n{_server_log_tail(log_path)}"
392
  )
393
+ if time.time() >= deadline:
394
+ break
395
  try:
396
  with urllib.request.urlopen(url, timeout=interval) as r:
397
  if 200 <= r.status < 300:
code/autoslm/engine/verl_runner.py ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """verl GRPO + LoRA runner (AUTOSLM_FRAMEWORK=verl).
2
+
3
+ Runs verl in a SIDECAR venv on the provisioned box, isolated from the baked TRL/vLLM
4
+ stack (baked = torch 2.10 + vllm 0.19.1 + transformers 5; verl needs vllm<=0.12 +
5
+ transformers<5 — hard conflict, so a clean venv). Benchmarks verl's one-step-off async
6
+ overlap WITH LoRA (the path TRL's AsyncGRPOTrainer can't do — it's full-FT-only).
7
+
8
+ Single GPU (inference_gpus=0): verl.trainer.main_ppo colocate (hybrid_engine, no overlap)
9
+ -> apples-to-apples vs our TRL colocate s/step.
10
+ >=2 GPU (inference_gpus>0): verl.experimental.one_step_off_policy.main_ppo, hybrid_engine=False
11
+ -> the real generation<->training OVERLAP (gen(t+1) overlaps train(t)).
12
+
13
+ Writes /tmp/metrics.json in the shape the autoslm pipeline reads
14
+ ({wall_seconds, notes:{steps,...}, reward_history}).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import subprocess
23
+ import sys
24
+ import threading
25
+ import time
26
+
27
+ VENV = "/opt/verl-venv"
28
+ VPY = f"{VENV}/bin/python"
29
+ VPIP = f"{VENV}/bin/pip"
30
+ VERL_DIR = "/opt/verl"
31
+ WORKDIR = "/tmp/verl"
32
+ # The python verl actually runs with. OLD stack -> the sidecar venv (VPY). BAKED stack -> the SYSTEM
33
+ # python (sys.executable), reusing the baked torch/vllm/transformers/torchvision (all matching), since
34
+ # a --system-site-packages venv + uv reinstalls torch and breaks the baked torchvision. Set by _install.
35
+ RUN_PY = VPY
36
+
37
+
38
+ def _hb(stage: str, **kw):
39
+ try:
40
+ from autoslm.engine.worker import heartbeat
41
+
42
+ heartbeat(stage, **kw)
43
+ except Exception:
44
+ print(f"[verl][hb] {stage} {kw}", flush=True)
45
+
46
+
47
+ def _spec():
48
+ from autoslm.engine import worker as W
49
+
50
+ return W.JOB_SPEC
51
+
52
+
53
+ def _run(cmd, cwd=None, env=None, check=True, capture=False):
54
+ print(f"[verl] $ {cmd if isinstance(cmd, str) else ' '.join(map(str, cmd))}", flush=True)
55
+ r = subprocess.run(
56
+ cmd, cwd=cwd, env=env, shell=isinstance(cmd, str),
57
+ text=True, capture_output=capture,
58
+ )
59
+ if capture:
60
+ if r.stdout:
61
+ print(r.stdout[-4000:], flush=True)
62
+ if r.stderr:
63
+ print(r.stderr[-4000:], flush=True)
64
+ if check and r.returncode != 0:
65
+ raise RuntimeError(f"command failed (rc={r.returncode}): {cmd if isinstance(cmd,str) else ' '.join(map(str,cmd))}")
66
+ return r
67
+
68
+
69
+ def _ensure_uv() -> str:
70
+ """Return a path to `uv` (creates venvs without python3-venv/ensurepip, installs fast).
71
+ Prefer one already on the image; else bootstrap via system pip, else the standalone installer."""
72
+ import shutil
73
+
74
+ def _find():
75
+ cands = ["uv", os.path.expanduser("~/.local/bin/uv"), "/root/.local/bin/uv",
76
+ "/usr/local/bin/uv", "/opt/uv/uv"]
77
+ for c in cands:
78
+ p = shutil.which(c) if "/" not in c else (c if os.path.exists(c) else None)
79
+ if p:
80
+ return p
81
+ return None
82
+
83
+ p = _find()
84
+ if p:
85
+ return p
86
+ for pipcmd in ([sys.executable, "-m", "pip", "install", "-q", "uv"], ["pip", "install", "-q", "uv"]):
87
+ if subprocess.run(pipcmd, capture_output=True, text=True).returncode == 0:
88
+ break
89
+ p = _find()
90
+ if p:
91
+ return p
92
+ subprocess.run("curl -LsSf https://astral.sh/uv/install.sh | sh", shell=True)
93
+ p = _find()
94
+ if p:
95
+ return p
96
+ raise RuntimeError("could not obtain uv for the verl sidecar venv")
97
+
98
+
99
+ def _install():
100
+ """Install the verl stack and return the python executable verl should run with.
101
+
102
+ OLD stack (default): a fresh uv venv with PUBLIC-PyPI vllm 0.11 + transformers 4.57 + a MATCHING
103
+ torchvision -> MiniCPM/Qwen2.5/Qwen3-dense. Cannot load the qwen3_5 arch.
104
+ BAKED stack (AUTOSLM_VERL_USE_BAKED_STACK=1): for Qwen3.5/3.6. The baked image's vllm 0.19.1 +
105
+ transformers 5 + torch + torchvision are INTERNAL builds (not on PyPI) and MUTUALLY MATCHED.
106
+ Install verl + its non-baked deps straight into the SYSTEM python (no venv) so all of them are
107
+ reused as-is. (A --system-site-packages venv + uv reinstalls torch and breaks the baked
108
+ torchvision -> `operator torchvision::nms does not exist`.)
109
+ """
110
+ global RUN_PY
111
+ # BAKED is the DEFAULT: the host-matched vllm0.19.1/tf5 boots reliably and loads every model we
112
+ # benchmark (MiniCPM/Qwen2.5/Qwen3-dense AND Qwen3.5/3.6). The OLD uv-venv stack (set
113
+ # AUTOSLM_VERL_USE_BAKED_STACK=0) installs fresh vllm0.11 wheels -> fragile torch/CUDA resolution
114
+ # (vllm==0.11.0 install now fails outright) -> retired as the default.
115
+ use_baked = os.environ.get("AUTOSLM_VERL_USE_BAKED_STACK", "1").strip().lower() in ("1", "true", "yes")
116
+ py = sys.executable if use_baked else VPY
117
+ RUN_PY = py
118
+ # Idempotency: if verl already imports under `py`, skip. Guard on the interpreter existing — the
119
+ # OLD-stack venv python won't exist on a fresh box (FileNotFoundError otherwise).
120
+ if os.path.exists(py):
121
+ chk = subprocess.run(
122
+ [py, "-c", "import verl, vllm, torch, transformers; print(vllm.__version__, torch.__version__, transformers.__version__)"],
123
+ text=True, capture_output=True,
124
+ )
125
+ if chk.returncode == 0:
126
+ print(f"[verl] stack ready ({py}): vllm/torch/transformers = {chk.stdout.strip()}", flush=True)
127
+ return py
128
+
129
+ verl_ref = os.environ.get("AUTOSLM_VERL_REF", "").strip()
130
+ vllm_pin = os.environ.get("AUTOSLM_VERL_VLLM", "vllm==0.11.0").strip()
131
+ tf_pin = os.environ.get("AUTOSLM_VERL_TRANSFORMERS", "transformers==4.57.0").strip()
132
+ fa_pin = os.environ.get("AUTOSLM_VERL_FLASHATTN", "flash-attn==2.8.1").strip()
133
+ tv_pin = os.environ.get("AUTOSLM_VERL_TORCHVISION", "torchvision==0.23.0").strip() # matches torch 2.8 (vllm 0.11)
134
+ uv = _ensure_uv()
135
+
136
+ # The baked system python is PEP-668 "externally managed" -> uv/pip refuse it without this flag.
137
+ bsp = ["--break-system-packages"] if use_baked else []
138
+
139
+ def upip(*pkgs, check=True):
140
+ return _run([uv, "pip", "install", "-p", py, *bsp, *pkgs], check=check, capture=True)
141
+
142
+ _hb("verl_install", step="venv", baked=use_baked)
143
+ if not use_baked:
144
+ # uv venv: no python3-venv/ensurepip needed (baked image lacks it).
145
+ _run([uv, "venv", VENV, "--python", sys.executable])
146
+ upip("pip", "setuptools", "wheel")
147
+ if not os.path.exists(os.path.join(VERL_DIR, "setup.py")) and not os.path.exists(os.path.join(VERL_DIR, "pyproject.toml")):
148
+ _hb("verl_install", step="clone")
149
+ clone = ["git", "clone", "--depth", "1"]
150
+ if verl_ref:
151
+ clone += ["--branch", verl_ref]
152
+ clone += ["https://github.com/verl-project/verl", VERL_DIR]
153
+ _run(clone, check=not verl_ref)
154
+ if not os.path.exists(os.path.join(VERL_DIR, "pyproject.toml")):
155
+ _run(["rm", "-rf", VERL_DIR], check=False)
156
+ _run(["git", "clone", "https://github.com/verl-project/verl", VERL_DIR])
157
+ if verl_ref:
158
+ _run(["git", "checkout", verl_ref], cwd=VERL_DIR)
159
+ if not use_baked:
160
+ _hb("verl_install", step="vllm_transformers", vllm=vllm_pin, transformers=tf_pin)
161
+ upip(vllm_pin, tf_pin) # vllm pins torch; resolve it first
162
+ # torchvision UNPINNED in a second pass so uv matches it to whatever torch vllm resolved
163
+ # (a hard pin like ==0.23.0 conflicts/flakes host-to-host); tv must match torch or nms op missing.
164
+ _tvr = upip("torchvision", check=False)
165
+ if _tvr.returncode != 0:
166
+ upip(tv_pin, check=False)
167
+ _hb("verl_install", step="flash_attn")
168
+ upip(fa_pin, "--no-build-isolation", check=False) # wheel; tolerate fail
169
+ else:
170
+ _hb("verl_install", step="baked_stack_reused", note="vllm/transformers/torch/torchvision from baked system python")
171
+ _hb("verl_install", step="deps")
172
+ # --no-deps on the ones likely to drag torch so the BAKED torch/torchvision are never disturbed;
173
+ # install their needed extras explicitly. On the OLD venv this is harmless (torch already pinned).
174
+ upip("ray[default]>=2.41.0", "tensordict>=0.8.0,<=0.10.0", "hydra-core", "omegaconf",
175
+ "datasets", "pyarrow", "pandas", "codetiming", "dill", "pylatexenc", "wandb",
176
+ "math_verify", "accelerate", "peft>=0.19", "torchdata", "torchmetrics")
177
+ # one_step_off async overlap transfers weights trainer->rollout via the NCCL checkpoint engine,
178
+ # which only REGISTERS if cupy + pyzmq import (else verl dies "Checkpoint engine nccl not
179
+ # registered"). Install them for the overlap path (heavy cupy wheel -> skip for plain colocate).
180
+ if os.environ.get("AUTOSLM_VERL_OVERLAP", "").strip().lower() in ("1", "true", "yes"):
181
+ _hb("verl_install", step="nccl_ckpt_engine_deps")
182
+ upip("cupy-cuda12x", "pyzmq", check=False)
183
+ _hb("verl_install", step="verl")
184
+ _run([uv, "pip", "install", "-p", py, *bsp, "--no-deps", "-e", "."], cwd=VERL_DIR)
185
+ _install_chalk(uv, py)
186
+ chk = _run([py, "-c", "import verl, vllm, torch, torchvision, transformers; print('verl-ok', vllm.__version__, torch.__version__, torchvision.__version__, transformers.__version__)"], capture=True, check=False)
187
+ print(f"[verl] install verified ({py}): {chk.stdout.strip()}", flush=True)
188
+ return py
189
+
190
+
191
+ # FLASH_* flags -> the freesolo-chalk class-level installer to call (install-on-call, no model needed).
192
+ # These patch the transformers Qwen3.5 model CLASS, so verl's actor model picks up the kernels.
193
+ _CHALK_CLASS_INSTALLERS = {
194
+ "FLASH_MLP_KERNEL": "install_qwen35_mlp",
195
+ "FLASH_QKV_KERNEL": "install_qwen35_qkv",
196
+ "FLASH_TRITON_LORA": "install_lora",
197
+ "FLASH_ROPE_KERNEL": "install_qwen35_rope",
198
+ }
199
+
200
+
201
+ def _install_chalk(uv, py):
202
+ """Keep our kernel optimizations (chalk) active in the verl path. chalk = the freesolo-chalk
203
+ package (hand-written Triton/CUDA Qwen3.5 kernels), install-on-call. We (a) install it via
204
+ FLASH_CHALK_SPEC, and (b) drop a sitecustomize.py in `py`'s site-packages that calls the selected
205
+ class-level installers at interpreter startup, so verl's actor model gets the kernels before build.
206
+ Best-effort + gated: no FLASH_* flag / no spec -> no-op. Only meaningful for Qwen3.5 (baked stack)."""
207
+ selected = [v for k, v in _CHALK_CLASS_INSTALLERS.items()
208
+ if os.environ.get(k, "").strip().lower() in ("1", "true", "yes")]
209
+ spec = os.environ.get("FLASH_CHALK_SPEC", "").strip()
210
+ if not selected and not spec:
211
+ return
212
+ _hb("verl_install", step="chalk", installers=selected)
213
+ if spec:
214
+ _run([uv, "pip", "install", "-p", py, spec], check=False, capture=True)
215
+ # sitecustomize runs at EVERY interpreter start (incl. verl + its ray workers), before the model is
216
+ # constructed -> the class-level kernel patches apply to verl's model.
217
+ r = subprocess.run([py, "-c", "import site;print(site.getsitepackages()[0])"], text=True, capture_output=True)
218
+ site_dir = r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
219
+ if not site_dir or not os.path.isdir(site_dir):
220
+ print("[verl][chalk] no site-packages dir found; skipping sitecustomize", flush=True)
221
+ return
222
+ site_dirs = [site_dir]
223
+ calls = "\n".join(f" _c.{fn}()" for fn in selected)
224
+ sc = (
225
+ "import os\n"
226
+ "try:\n"
227
+ " import freesolo_chalk as _c\n"
228
+ f"{calls if calls else ' pass'}\n"
229
+ " print('[chalk] class-level kernels installed: ' + ','.join(%r))\n" % selected
230
+ + "except Exception as _e:\n"
231
+ " print('[chalk] sitecustomize skipped: ' + repr(_e))\n"
232
+ )
233
+ with open(os.path.join(site_dirs[0], "sitecustomize.py"), "w") as f:
234
+ f.write(sc)
235
+ print(f"[verl][chalk] wrote sitecustomize calling {selected}", flush=True)
236
+
237
+
238
+ def _build_dataset(model_path: str, n_rows: int, prompt_tokens: int):
239
+ """Synthetic GRPO dataset: ~prompt_tokens-long chat prompts + a simple rule reward.
240
+ Throughput (gen n*resp + train) dominates s/step, so a simple reward is fine for the bench."""
241
+ os.makedirs(WORKDIR, exist_ok=True)
242
+ import pandas as pd # baked image has pandas; if not, the sidecar does
243
+
244
+ # Build prompts COMFORTABLY UNDER max_prompt_length (~prompt_tokens). English ≈ 1.3 tok/word, so
245
+ # target ~0.55*prompt_tokens/1.3 words to stay well within the limit (avoids all-rows-filtered ->
246
+ # num_samples=0). truncation=right + filter_overlong_prompts=False in the config also protect this.
247
+ filler = ("Reason step by step about the following problem and give the final answer. " * 60)
248
+ words = filler.split()
249
+ approx = max(8, int(prompt_tokens * 0.55 / 1.3))
250
+ content = " ".join((words * (approx // len(words) + 1))[:approx])
251
+ rows = []
252
+ for i in range(n_rows):
253
+ rows.append({
254
+ "data_source": "autoslm_bench",
255
+ "prompt": [{"role": "user", "content": f"[{i}] {content}"}],
256
+ "ability": "bench",
257
+ "reward_model": {"style": "rule", "ground_truth": "x"},
258
+ "extra_info": {"index": i, "split": "train"},
259
+ })
260
+ df = pd.DataFrame(rows)
261
+ df.to_parquet(f"{WORKDIR}/train.parquet")
262
+ df.head(max(8, n_rows // 8)).to_parquet(f"{WORKDIR}/val.parquet")
263
+ print(f"[verl] dataset: {n_rows} rows, ~{prompt_tokens} prompt tok -> {WORKDIR}/train.parquet", flush=True)
264
+
265
+
266
+ def _write_reward():
267
+ """A trivial length-aware reward (verl custom_reward_function contract). Throughput bench
268
+ doesn't depend on the reward signal; this just exercises the scoring path."""
269
+ src = (
270
+ "def compute_score(data_source, solution_str, ground_truth, extra_info=None):\n"
271
+ " n = len(solution_str or '')\n"
272
+ " return 1.0 if n > 0 else 0.0\n"
273
+ )
274
+ with open(f"{WORKDIR}/verl_reward.py", "w") as f:
275
+ f.write(src)
276
+
277
+
278
+ def _build_cmd(model_path, split, *, group_size, prompt_len, resp_len, lora_rank, lora_alpha, steps, train_bs):
279
+ overlap = split.infer_gpus > 0
280
+ if overlap:
281
+ entry = ["-m", "verl.experimental.one_step_off_policy.main_ppo",
282
+ "--config-path=config", "--config-name=one_step_off_ppo_trainer"]
283
+ else:
284
+ entry = ["-m", "verl.trainer.main_ppo"]
285
+ ov = [
286
+ "algorithm.adv_estimator=grpo",
287
+ "algorithm.use_kl_in_reward=False",
288
+ f"data.train_files={WORKDIR}/train.parquet",
289
+ f"data.val_files={WORKDIR}/val.parquet",
290
+ f"data.train_batch_size={train_bs}",
291
+ f"data.max_prompt_length={prompt_len}",
292
+ f"data.max_response_length={resp_len}",
293
+ "data.filter_overlong_prompts=False", # never drop rows (would zero the dataset -> num_samples=0)
294
+ "data.truncation=right", # truncate instead of erroring on length
295
+ "data.dataloader_num_workers=0", # no dataloader worker threads (Vast pids cap is tight)
296
+ f"actor_rollout_ref.model.path={model_path}",
297
+ # MiniCPM / custom-arch models load via remote code -> without this the vLLM EngineCore dies
298
+ # at startup ("Failed core proc(s): {}"). Harmless for natively-supported archs.
299
+ "actor_rollout_ref.model.trust_remote_code=True",
300
+ "actor_rollout_ref.model.use_remove_padding=True",
301
+ "actor_rollout_ref.model.enable_gradient_checkpointing=True",
302
+ f"actor_rollout_ref.model.lora_rank={lora_rank}",
303
+ f"actor_rollout_ref.model.lora_alpha={lora_alpha}",
304
+ # all-linear LoRA-wraps EVERY nn.Linear incl. Qwen3.5's VISION tower -> the one_step_off
305
+ # bucketed weight-transfer then sends vision 'qkv.base_layer.weight' which vLLM's qwen3_vl
306
+ # load_weights rejects (KeyError). Set AUTOSLM_VERL_TARGET_MODULES to a language-only list
307
+ # (e.g. "[q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj]") for Qwen3.5 async.
308
+ f"actor_rollout_ref.model.target_modules={os.environ.get('AUTOSLM_VERL_TARGET_MODULES', 'all-linear').strip()}",
309
+ "actor_rollout_ref.actor.optim.lr=1e-5",
310
+ f"actor_rollout_ref.actor.ppo_mini_batch_size={max(8, train_bs // 2)}",
311
+ "actor_rollout_ref.actor.use_kl_loss=True",
312
+ "actor_rollout_ref.actor.kl_loss_coef=0.001",
313
+ "actor_rollout_ref.actor.kl_loss_type=low_var_kl",
314
+ "actor_rollout_ref.actor.entropy_coeff=0",
315
+ # FSDP2 (DTensor) — the strategy selector is actor.strategy, NOT fsdp_config.strategy.
316
+ # FSDP1 (the default) on a SINGLE GPU is NO_SHARD, and verl's vLLM weight-sync summons
317
+ # full params with offload_to_cpu=True -> "offload_to_cpu=True and NO_SHARD is not supported".
318
+ # FSDP2 syncs via DTensor.full_tensor and avoids that codepath entirely.
319
+ "actor_rollout_ref.actor.strategy=fsdp2",
320
+ "actor_rollout_ref.ref.strategy=fsdp2",
321
+ # verl requires explicit micro-batch sizes (or use_dynamic_bsz). Set small per-GPU micro-batches.
322
+ "actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=4",
323
+ "actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=8",
324
+ "actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=8",
325
+ "actor_rollout_ref.rollout.name=vllm",
326
+ f"actor_rollout_ref.rollout.n={group_size}",
327
+ "actor_rollout_ref.rollout.temperature=1.0",
328
+ f"actor_rollout_ref.rollout.response_length={resp_len}",
329
+ # CAP vLLM's max_model_len to the ACTUAL prompt+response budget. Without this the rollout
330
+ # vLLM defaults to the model's full context (Qwen3.5 = 262144) and sizes its KV cache for a
331
+ # 256K-token request -> "KV cache needed (3.04 GiB) > available" -> EngineCore dies before
332
+ # step 0. This was THE async-rollout blocker (host-independent; verified across 4 GPU classes).
333
+ f"actor_rollout_ref.rollout.max_model_len={prompt_len + resp_len}",
334
+ "actor_rollout_ref.rollout.gpu_memory_utilization=0.4",
335
+ "actor_rollout_ref.rollout.enforce_eager=True", # skip CUDA-graph capture (lighter/faster vLLM init)
336
+ "actor_rollout_ref.rollout.load_format=safetensors",
337
+ "actor_rollout_ref.rollout.layered_summon=True",
338
+ # Rollout parallelism: DEFAULT TP=1 so verl auto-runs dp=infer_gpus INDEPENDENT vLLM replicas
339
+ # (data-parallel), NOT a tensor-sharded engine. TP=infer_gpus all-reduces every layer/token —
340
+ # pure comm waste on small models (TP=2 on 0.8B made 4-GPU SLOWER than 2-GPU). DP scales
341
+ # rollout throughput with zero per-token cross-GPU comm. Big models that don't fit one card
342
+ # set AUTOSLM_VERL_ROLLOUT_TP=2+ to shard. (dense DP is fully supported by verl/modern vLLM.)
343
+ f"actor_rollout_ref.rollout.tensor_model_parallel_size={int(os.environ.get('AUTOSLM_VERL_ROLLOUT_TP', '1'))}",
344
+ # Two reward paths exist. The STANDARD reward manager reads top-level custom_reward_function.*;
345
+ # the async-server AgentLoop/RewardLoop (what colocate uses, since rollout boots a vLLMHttpServer)
346
+ # reads reward.custom_reward_function.* and otherwise routes by data_source -> "Reward function
347
+ # is not implemented for data_source='autoslm_bench'". Set BOTH so whichever path runs is wired.
348
+ f"custom_reward_function.path={WORKDIR}/verl_reward.py",
349
+ "custom_reward_function.name=compute_score",
350
+ f"reward.custom_reward_function.path={WORKDIR}/verl_reward.py",
351
+ "reward.custom_reward_function.name=compute_score",
352
+ "trainer.logger=[console]",
353
+ "trainer.val_before_train=False",
354
+ "trainer.nnodes=1",
355
+ f"trainer.total_training_steps={steps}",
356
+ "trainer.save_freq=-1",
357
+ "trainer.test_freq=-1",
358
+ "trainer.project_name=autoslm_verl",
359
+ ]
360
+ if overlap:
361
+ ov += [
362
+ "actor_rollout_ref.hybrid_engine=False",
363
+ "critic.strategy=fsdp2",
364
+ # verl FSDP2 loads the base model fp32 by default (FSDPEngineConfig.model_dtype="fp32") ->
365
+ # LoRA trainable params stay fp32 (grad_dtype=fp32) but the bf16 autocast backward emits
366
+ # bf16 grads -> "assign a gradient with dtype BFloat16 to a tensor with grad_dtype Float"
367
+ # (verl #3470/#2969). Load base+LoRA in bf16 so grad_dtype==grad dtype==bf16. (colocate's
368
+ # known-good LoRA path sets this; one_step_off's config never exercised LoRA -> inherits fp32.)
369
+ "actor_rollout_ref.actor.fsdp_config.model_dtype=bf16",
370
+ f"trainer.n_gpus_per_node={split.train_gpus}",
371
+ "rollout.nnodes=1",
372
+ f"rollout.n_gpus_per_node={split.infer_gpus}",
373
+ # Rollout vLLM executor. DEFAULT = mp (MultiprocExecutor) — the SAME path colocate uses,
374
+ # which WORKS on Vast hosts that allow the pidfd_getfd syscall (CUDA IPC); pidfd is
375
+ # HOST-dependent seccomp, so retry async across hosts to land on a permissive one. The
376
+ # Ray executor (AUTOSLM_VERL_ROLLOUT_EXECUTOR=ray) dodges pidfd but CONFLICTS with verl's
377
+ # one_step_off placement groups ("Current node has no GPU available"), so it's opt-in only.
378
+ ]
379
+ if os.environ.get("AUTOSLM_VERL_ROLLOUT_EXECUTOR", "mp").strip().lower() == "ray":
380
+ ov += [
381
+ "+actor_rollout_ref.rollout.engine_kwargs.vllm.distributed_executor_backend=ray",
382
+ ]
383
+ else:
384
+ ov += [f"trainer.n_gpus_per_node={split.train_gpus or 1}"]
385
+ # Escape hatch: space-separated extra hydra overrides via env (test verl config fixes without a
386
+ # code change), e.g. AUTOSLM_VERL_EXTRA_OVERRIDES="actor_rollout_ref.actor.fsdp_config.mixed_precision.param_dtype=bf16".
387
+ _extra = os.environ.get("AUTOSLM_VERL_EXTRA_OVERRIDES", "").strip()
388
+ if _extra:
389
+ ov += _extra.split()
390
+ return [RUN_PY] + entry + ov
391
+
392
+
393
+ def run():
394
+ from autoslm.engine import worker as W
395
+ from autoslm.engine.disaggregated import detect_total_gpus
396
+ from autoslm.engine.rollout_bench import select_rollout_split
397
+
398
+ t0 = time.time()
399
+ _hb("rl_start")
400
+ spec = _spec()
401
+ tr = spec.train
402
+ model_id = spec.model
403
+ group_size = int(getattr(tr, "group_size", 8) or 8)
404
+ max_len = int(getattr(tr, "max_length", 2048) or 2048)
405
+ resp_len = int(getattr(tr, "max_tokens", 1024) or 1024)
406
+ prompt_len = max(256, max_len - resp_len)
407
+ steps = int(getattr(tr, "steps", 12) or 12)
408
+ lora_rank = int(getattr(tr, "lora_rank", 0) or 32)
409
+ lora_alpha = int(getattr(tr, "lora_alpha", 0) or (2 * lora_rank))
410
+ inf = int(getattr(tr, "inference_gpus", 0) or 0)
411
+ inf = int(os.environ.get("AUTOSLM_INFERENCE_GPUS", inf))
412
+ train_bs = 32
413
+
414
+ # Tell _install whether to pull the NCCL-checkpoint-engine deps (cupy/pyzmq) for the overlap path.
415
+ os.environ["AUTOSLM_VERL_OVERLAP"] = "1" if inf > 0 else "0"
416
+ _hb("verl_install", note="sidecar venv + verl stack (slow cold start)")
417
+ _install()
418
+
419
+ _hb("verl_prefetch")
420
+ W.prefetch_model(model_id)
421
+ # local HF snapshot dir
422
+ model_path = model_id
423
+ try:
424
+ from huggingface_hub import snapshot_download
425
+
426
+ model_path = snapshot_download(model_id)
427
+ except Exception as e:
428
+ print(f"[verl] snapshot_download fallback to id ({e})", flush=True)
429
+
430
+ total = detect_total_gpus()
431
+ split = select_rollout_split(total, inf) if inf > 0 else type("S", (), {"train_gpus": total or 1, "infer_gpus": 0})()
432
+ print(f"[verl] total_gpus={total} inference_gpus={inf} -> train={getattr(split,'train_gpus','?')} infer={getattr(split,'infer_gpus','?')} "
433
+ f"({'one-step-off OVERLAP' if inf>0 else 'colocate (no overlap)'})", flush=True)
434
+
435
+ _build_dataset(model_path, n_rows=max(64, train_bs * 4), prompt_tokens=prompt_len)
436
+ _write_reward()
437
+
438
+ cmd = _build_cmd(model_path, split, group_size=group_size, prompt_len=prompt_len,
439
+ resp_len=resp_len, lora_rank=lora_rank, lora_alpha=lora_alpha,
440
+ steps=steps, train_bs=train_bs)
441
+ env = dict(os.environ)
442
+ env["VLLM_USE_V1"] = env.get("VLLM_USE_V1", "1")
443
+ env["HF_HUB_DISABLE_XET"] = "1"
444
+ env["HYDRA_FULL_ERROR"] = "1" # full trace incl. the vLLM EngineCore root cause
445
+ env["VLLM_ENGINE_ITERATION_TIMEOUT_S"] = env.get("VLLM_ENGINE_ITERATION_TIMEOUT_S", "1800")
446
+ # verl/ray must SEE ALL GPUs (one_step_off splits them into trainer+rollout pools itself). The
447
+ # worker may have pre-pinned CUDA_VISIBLE_DEVICES to a subset (the TRL disaggregated split) ->
448
+ # ray then reports "Total available GPUs 0". Expose every GPU to verl.
449
+ if total and total > 0:
450
+ env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in range(total))
451
+ # vLLM's CuMemAllocator (sleep-mode memory pool — verl colocate uses it to offload base weights
452
+ # while the actor steps) HARD-ASSERTS expandable_segments is OFF. The baked image ships
453
+ # PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True -> the vLLM rollout EngineCore dies at startup
454
+ # with "Expandable segments are not compatible with memory pool" (Failed core proc(s): {}).
455
+ # Strip ONLY the expandable_segments token (keep any other alloc knobs) for the verl subprocess.
456
+ _alloc = env.get("PYTORCH_CUDA_ALLOC_CONF", "")
457
+ _kept = [p for p in _alloc.split(",") if p.strip() and "expandable_segments" not in p]
458
+ if _kept:
459
+ env["PYTORCH_CUDA_ALLOC_CONF"] = ",".join(_kept)
460
+ else:
461
+ env.pop("PYTORCH_CUDA_ALLOC_CONF", None)
462
+ env.pop("PYTHONPATH", None) # keep the sidecar clean of the baked stack
463
+ # Cheap/shared Vast containers ship a LOW soft process+fd limit. Ray's CoreWorker spawns a
464
+ # thread pool at init; when pthread_create hits RLIMIT_NPROC it THROWS -> C++ std::terminate ->
465
+ # SIGABRT ("Fatal Python error: Aborted", init_once.cold) that retries can't clear. Raise the
466
+ # soft limits to the hard cap (inherited by the verl child) so Ray/vLLM can spawn their threads.
467
+ try:
468
+ import resource
469
+
470
+ for _lim, _name in ((resource.RLIMIT_NPROC, "NPROC"), (resource.RLIMIT_NOFILE, "NOFILE")):
471
+ _soft, _hard = resource.getrlimit(_lim)
472
+ if _hard == resource.RLIM_INFINITY or _soft < _hard:
473
+ resource.setrlimit(_lim, (_hard, _hard))
474
+ print(f"[verl] raised RLIMIT_{_name} {_soft}->{_hard}", flush=True)
475
+ except Exception as _e:
476
+ print(f"[verl] rlimit bump skipped: {_e}", flush=True)
477
+ # Cap math-lib thread pools so the process doesn't fan out hundreds of threads on a Vast
478
+ # container with a low pids cap ("RuntimeError: can't start new thread" hit even on an A100 at
479
+ # the heavier matched config); verl/vLLM still parallelize on the GPU.
480
+ for _tv in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
481
+ env.setdefault(_tv, "4")
482
+ # HuggingFace tokenizers (Rust/Rayon) + any other Rayon crate: when Ray forks worker processes
483
+ # Rayon tries to spin up a global thread pool in EACH Ray actor. On RunPod/Vast the per-process
484
+ # thread cap is low and the attempt panics with EAGAIN (ThreadPoolBuildError / "Resource
485
+ # temporarily unavailable"). Limit Rayon to 1 thread (the calling thread — no new threads
486
+ # spawned). TOKENIZERS_PARALLELISM=false prevents HF tokenizers from even trying to init Rayon.
487
+ env.setdefault("RAYON_NUM_THREADS", "1")
488
+ env.setdefault("TOKENIZERS_PARALLELISM", "false")
489
+ # glibc spawns one heap arena PER thread by default (each reserves virtual memory) -> compounds
490
+ # the thread/memory pressure on a constrained container. Cap arenas to shrink the footprint.
491
+ env.setdefault("MALLOC_ARENA_MAX", "2")
492
+ # Multi-GPU (one_step_off async) NCCL: many Vast nodes are plain-PCIe with NO CUDA P2P between
493
+ # cards -> "peer access is not supported between these two devices" / NCCL_ERROR_UNHANDLED.
494
+ # Force NCCL onto the SHM/host path so cross-GPU weight transfer works without P2P.
495
+ if total and total > 1:
496
+ # Vast containers block CUDA peer access (cudaDeviceEnablePeerAccess -> "peer access is not
497
+ # supported between these two devices"), even on NVLink cards — it's the container sandbox,
498
+ # not the hardware. The cupy/ray-collective nccl checkpoint engine (trainer<->rollout weight
499
+ # transfer) hits this in NCCL's P2P AND SHM transports. Force NCCL onto the NET (socket)
500
+ # transport, which needs no peer access. (Set here AND best to also pass via [worker_env] so
501
+ # it reaches every Ray actor's env.)
502
+ # Container blocks CUDA peer access, BUT disabling SHM forces the slow TCP NET/socket transport
503
+ # -> the trainer DDP all-reduce crawls (2:2 update_actor 32s->138s = 4.3x, made 4-GPU SLOWER
504
+ # than 2-GPU). Keep SHM but force the LEGACY host-staged mmap path (NCCL_CUMEM_HOST_ENABLE=0):
505
+ # host-bounce SHM needs NO peer access yet is far faster than sockets. Only P2P stays disabled.
506
+ env.setdefault("NCCL_P2P_DISABLE", "1")
507
+ env.setdefault("NCCL_SHM_DISABLE", "0")
508
+ env.setdefault("NCCL_CUMEM_ENABLE", "0")
509
+ env.setdefault("NCCL_CUMEM_HOST_ENABLE", "0")
510
+ # vLLM's Ray executor (rollout) places a worker bundle that requests CPU:10 each; verl's own
511
+ # Ray actors already hold most of the box's CPUs -> "No available node types can fulfill
512
+ # resource request {'CPU': 10.0}". Tell Ray the node has plenty of CPUs (scheduling bookkeeping
513
+ # only; the box isn't actually CPU-bound) so the placement group is satisfiable.
514
+ env.setdefault("RAY_OVERRIDE_RESOURCES", json.dumps({"CPU": 64}))
515
+ # one_step_off async init (Ray placement groups + Ray-executor vLLM workers + weight transfer)
516
+ # is much slower than colocate -> give the first step a longer watchdog budget.
517
+ os.environ.setdefault("AUTOSLM_VERL_FIRST_STEP_TIMEOUT", "2400")
518
+
519
+ _hb("rl_train_start", setup_seconds=time.time() - t0)
520
+ log_path = "/tmp/verl_console.txt"
521
+ print(f"[verl] launching: {' '.join(map(str, cmd))}", flush=True)
522
+ # verl's console logger (trainer.logger=[console]) prints ONE line per training step via
523
+ # concat_dict_to_str: "step:N - perf/time_per_step:12.3 - actor/.. - .." (numeric keys only).
524
+ step_line_re = re.compile(r"\bstep:(\d+)\b")
525
+ tps_re = re.compile(r"(?:perf/time_per_step|timing_s/step|time_per_step)\s*[:=]\s*([0-9.eE+-]+)")
526
+ step_times: list[float] = [] # per-step wall times (s) when verl logs the perf key
527
+ seen_steps: set[int] = set() # step numbers seen — robust counter even if the timing key differs
528
+ train_t0 = [time.time()] # reset at each launch attempt; for the wall/steps fallback
529
+ stop = threading.Event()
530
+
531
+ def _beat():
532
+ while not stop.is_set():
533
+ _hb("verl_running", steps_seen=len(seen_steps), timed=len(step_times))
534
+ stop.wait(60)
535
+
536
+ th = threading.Thread(target=_beat, daemon=True)
537
+ th.start()
538
+
539
+ def _launch_once():
540
+ """Run verl once, streaming combined output to log_path. Returns (rc, aborted); appends
541
+ any timed steps to step_times. A watchdog kills a STALLED run (no first step within
542
+ FIRST_STEP_TIMEOUT, or no new step within STALL_TIMEOUT) so a hang (seen on the async
543
+ one_step_off path: stuck at step1 for 60-90 min) is terminated and its console is still
544
+ uploaded for diagnosis instead of burning GPU forever."""
545
+ aborted = False
546
+ with open(log_path, "w") as lf:
547
+ proc = subprocess.Popen(cmd, cwd=VERL_DIR, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
548
+ first_to = float(os.environ.get("AUTOSLM_VERL_FIRST_STEP_TIMEOUT", "1500")) # 25 min cold budget
549
+ stall_to = float(os.environ.get("AUTOSLM_VERL_STALL_TIMEOUT", "900")) # 15 min between steps
550
+ progress = [time.time(), 0] # [last-progress wallclock, step count at that time]
551
+ wd_stop = threading.Event()
552
+
553
+ def _watchdog():
554
+ while not wd_stop.wait(30):
555
+ n = len(seen_steps)
556
+ now = time.time()
557
+ if n > progress[1]:
558
+ progress[0], progress[1] = now, n
559
+ budget = first_to if n == 0 else stall_to
560
+ if now - progress[0] > budget:
561
+ print(f"[verl] WATCHDOG: no step progress in {int(budget)}s (steps_seen={n}) "
562
+ f"-> killing verl (hang)", flush=True)
563
+ _hb("verl_watchdog_kill", steps_seen=n)
564
+ try:
565
+ proc.kill()
566
+ except Exception:
567
+ pass
568
+ return
569
+
570
+ wt = threading.Thread(target=_watchdog, daemon=True)
571
+ wt.start()
572
+ for line in proc.stdout:
573
+ lf.write(line)
574
+ lf.flush()
575
+ print(line, end="", flush=True)
576
+ if "SIGABRT" in line or "Fatal Python error: Aborted" in line:
577
+ aborted = True
578
+ sm = step_line_re.search(line)
579
+ if sm:
580
+ snum = int(sm.group(1))
581
+ if snum not in seen_steps:
582
+ seen_steps.add(snum)
583
+ tm = tps_re.search(line)
584
+ if tm:
585
+ try:
586
+ step_times.append(float(tm.group(1)))
587
+ except ValueError:
588
+ pass
589
+ _hb("rl_step", step=snum, timed=len(step_times))
590
+ rc = proc.wait()
591
+ wd_stop.set()
592
+ return rc, aborted
593
+
594
+ # The vLLM async server intermittently SIGABRTs at startup (init_once.cold, "Fatal Python error:
595
+ # Aborted") BEFORE any step — a transient native-init race. Retry the whole verl launch a couple
596
+ # times when that happens; never re-run once we've already timed real steps.
597
+ max_attempts = 3
598
+ rc = 1
599
+ for attempt in range(max_attempts):
600
+ step_times.clear()
601
+ seen_steps.clear()
602
+ train_t0[0] = time.time()
603
+ rc, aborted = _launch_once()
604
+ if rc == 0 or seen_steps:
605
+ break
606
+ if aborted and attempt < max_attempts - 1:
607
+ print(f"[verl] vLLM SIGABRT at startup (attempt {attempt + 1}/{max_attempts}) -> retrying", flush=True)
608
+ _hb("verl_retry_abort", attempt=attempt + 1)
609
+ continue
610
+ break
611
+ stop.set()
612
+ train_wall = time.time() - train_t0[0]
613
+
614
+ # s/step preference: (1) verl's logged per-step times (drop step 0 warmup, average the rest);
615
+ # (2) fallback to train-phase wall / #steps when the perf key wasn't logged but steps DID run
616
+ # (excludes install/model-load/vLLM-boot since train_t0 is set right before the launch).
617
+ useful = step_times[1:] if len(step_times) > 1 else step_times
618
+ s_per_step = (sum(useful) / len(useful)) if useful else None
619
+ s_per_step_source = "verl_perf_key" if s_per_step is not None else None
620
+ if s_per_step is None and len(seen_steps) >= 2:
621
+ # avg over steps after the first (warmup) — approximate but real (timed steps actually ran)
622
+ s_per_step = train_wall / len(seen_steps)
623
+ s_per_step_source = "train_wall_div_steps"
624
+ wall = time.time() - t0
625
+ print(f"[verl] DONE rc={rc} steps_seen={len(seen_steps)} steps_timed={len(step_times)} "
626
+ f"s/step={s_per_step} ({s_per_step_source})", flush=True)
627
+ if rc != 0 and not seen_steps:
628
+ tail = ""
629
+ root = ""
630
+ try:
631
+ with open(log_path) as f:
632
+ lines = f.readlines()
633
+ tail = "".join(lines[-60:])
634
+ # The vLLM EngineCore dies in a SUBPROCESS whose error is printed BEFORE the outer
635
+ # "Engine core initialization failed" wrapper -> it gets pushed out of the tail. Hunt
636
+ # for the real root cause (OOM / CUDA / import / KV-cache) anywhere in the console.
637
+ markers = ("EngineCore failed", "EngineCore hit an exception", "Process EngineCore",
638
+ "(EngineCore", "EngineCore_", "failed to start", "Worker proc",
639
+ "CUDA error", "out of memory", "OutOfMemory", "No available memory",
640
+ "free memory", "KV cache", "GPU blocks", "No kernel image",
641
+ "ImportError", "ModuleNotFoundError", "ABI", "undefined symbol",
642
+ "does not exist", "not a supported", "Unrecognized", "trust_remote_code",
643
+ "RuntimeError:", "ValueError:", "AssertionError:", "KeyError:", "Cannot")
644
+ hits = [i for i, l in enumerate(lines) if any(m in l for m in markers)]
645
+ # exclude the generic outer wrapper lines so we land on the inner cause
646
+ hits = [i for i in hits if "Engine core initialization failed" not in lines[i]]
647
+ if hits:
648
+ lo = max(0, hits[0] - 4)
649
+ hi = min(len(lines), hits[0] + 25)
650
+ root = "".join(lines[lo:hi])
651
+ except Exception:
652
+ pass
653
+ # Surface verl's actual stderr in the raised error so it reaches the plane failure detail
654
+ # (the HF console upload may not happen on an early crash).
655
+ msg = f"verl run failed (rc={rc})."
656
+ if root:
657
+ msg += f"\n--- ROOT CAUSE region ---\n{root[-2500:]}"
658
+ msg += f"\n--- Last verl output ---\n{tail[-2500:]}"
659
+ raise RuntimeError(msg)
660
+
661
+ metrics = {
662
+ "wall_seconds": (s_per_step * steps) if s_per_step else wall,
663
+ "verl_s_per_step": s_per_step,
664
+ "verl_step_times": step_times,
665
+ "verl_s_per_step_source": s_per_step_source,
666
+ "verl_steps_seen": sorted(seen_steps),
667
+ "verl_train_wall": train_wall,
668
+ "notes": {"steps": steps, "framework": "verl",
669
+ "mode": "one_step_off_overlap" if inf > 0 else "colocate",
670
+ "model": model_id, "group_size": group_size, "lora_rank": lora_rank,
671
+ "inference_gpus": inf, "total_gpus": total},
672
+ "reward_history": [1.0] * max(len(step_times), len(seen_steps)),
673
+ }
674
+ with open("/tmp/metrics.json", "w") as f:
675
+ json.dump(metrics, f)
676
+ print(f"[verl] wrote /tmp/metrics.json: s/step={s_per_step}", flush=True)
677
+
678
+ # CRITICAL: the verl path returns early in worker.run_rl and bypasses the TRL _finalize, so
679
+ # nothing uploads the completion artifacts -> the control plane never sees the DONE sentinel and
680
+ # RESTARTS the run as an orphan (infinite re-run loop). Upload metrics.json + DONE here so the run
681
+ # is marked finished. ALWAYS upload the console too (the Vast bootstrap only uploads it on
682
+ # FAILURE, so a SUCCESSFUL run's step output — needed to verify the per-step timings — is
683
+ # otherwise lost).
684
+ try:
685
+ from autoslm.engine.worker import hf_upload_file
686
+
687
+ try:
688
+ hf_upload_file(log_path, "verl_console.txt")
689
+ except Exception as _e:
690
+ print(f"[verl] console upload warn: {_e}", flush=True)
691
+ hf_upload_file("/tmp/metrics.json", "metrics.json", required=True)
692
+ with open("/tmp/DONE", "w") as f:
693
+ f.write(str(time.time()))
694
+ hf_upload_file("/tmp/DONE", "DONE", required=True)
695
+ _hb("done")
696
+ print("[verl] uploaded metrics.json + DONE (run finalized)", flush=True)
697
+ except Exception as _e:
698
+ print(f"[verl] finalize upload FAILED ({_e}) -> plane may orphan-restart", flush=True)
699
+
700
+ return metrics
701
+ _hb("done", verl_s_per_step=s_per_step or 0.0)
702
+ return metrics
code/autoslm/engine/worker.py CHANGED
@@ -258,6 +258,12 @@ def make_checkpoint_upload_callback():
258
 
259
  class _CheckpointUpload(TrainerCallback):
260
  def on_save(self, args, state, control, **kwargs):
 
 
 
 
 
 
261
  if not HF_REPO:
262
  return
263
  step = int(state.global_step)
@@ -872,6 +878,17 @@ def make_lora(model_id: str | None = None):
872
  # `or` (not a get-default): a present-but-blank AUTOSLM_LORA_INIT must fall back too, else
873
  # init_lora_weights="" reaches PEFT as an invalid value instead of a real init method.
874
  _lora_init = os.environ.get("AUTOSLM_LORA_INIT") or "pissa_niter_16"
 
 
 
 
 
 
 
 
 
 
 
875
  if _lora_init.lower() in ("default", "standard", "plain", "true"):
876
  kwargs["init_lora_weights"] = True
877
  print("[lora] init_lora_weights=default (standard LoRA init; pissa disabled)")
@@ -1217,7 +1234,9 @@ def run_sft():
1217
  # ---------------------------------------------------------------------------
1218
  # RL (GRPO) with TRL + colocated vLLM
1219
  # ---------------------------------------------------------------------------
1220
- def compute_grpo_batching(prompts_per_step: int, group_size: int, per_device_comps: int) -> dict:
 
 
1221
  """Translate an intended ``prompts_per_step`` into a TRL GRPO batch configuration.
1222
 
1223
  TRL's GRPO batch sizing is denominated in **completions (prompt-completion pairs), not
@@ -1241,11 +1260,20 @@ def compute_grpo_batching(prompts_per_step: int, group_size: int, per_device_com
1241
  prompts_per_step = max(1, int(prompts_per_step))
1242
  per_device = max(1, int(per_device_comps))
1243
  target_comps = prompts_per_step * group_size # total completions / optimizer step
1244
- # Never let the per-device completion micro-batch exceed the target completion batch:
1245
- # a small prompts_per_step would otherwise overshoot it (mirrors run_sft's
1246
- # `min(per_device_bs, effective_batch)`). No-op at the default (prompts_per_step=64).
1247
- per_device = max(1, min(per_device, target_comps))
1248
- grad_accum = max(1, target_comps // per_device)
 
 
 
 
 
 
 
 
 
1249
  # TRL rejects a global completion batch (per_device * grad_accum) that is not
1250
  # divisible by num_generations (= group_size), failing only AFTER the paid worker
1251
  # is provisioned. per_device is the fixed VRAM knob, so round grad_accum UP to the
@@ -1254,7 +1282,9 @@ def compute_grpo_batching(prompts_per_step: int, group_size: int, per_device_com
1254
  # batch slightly; the common per_device|group_size cases are unchanged.
1255
  accum_step = group_size // math.gcd(per_device, group_size)
1256
  grad_accum = ((grad_accum + accum_step - 1) // accum_step) * accum_step
1257
- generations_per_step = per_device * grad_accum
 
 
1258
  unique_prompts_per_step = generations_per_step // group_size
1259
  return {
1260
  "per_device_train_batch_size": per_device,
@@ -1467,6 +1497,13 @@ def _pin_trainer_devices_for_disaggregated() -> None:
1467
 
1468
 
1469
  def run_rl():
 
 
 
 
 
 
 
1470
  from datasets import Dataset
1471
  from transformers import AutoTokenizer
1472
  from trl import GRPOConfig, GRPOTrainer
@@ -1738,7 +1775,14 @@ def run_rl():
1738
  if _params_b is None:
1739
  _params_b = fetch_hf_params_b(model_id)
1740
  per_device_comps = rl_per_device_comps(_max_completion, use_vllm=use_vllm, params_b=_params_b)
1741
- batching = compute_grpo_batching(prompts_per_step, group_size, per_device_comps)
 
 
 
 
 
 
 
1742
  if not batching["divisible_by_group"]:
1743
  print("WARN: generation batch not divisible by group size; check RL_PER_DEVICE_PROMPTS")
1744
  print(
@@ -1896,6 +1940,14 @@ def run_rl():
1896
  f"requires heads % TP == 0). Valid inference_gpus for this model: {_valid}. "
1897
  f"Pick a [train] inference_gpus from that set (e.g. a 1:2 or 1:4 split)."
1898
  )
 
 
 
 
 
 
 
 
1899
  _cmd = _disagg.build_vllm_serve_cmd(
1900
  model_id,
1901
  _rollout_split,
@@ -1905,6 +1957,7 @@ def run_rl():
1905
  quant=quant,
1906
  kv_cache_dtype=_server_kv,
1907
  parallel=_parallel,
 
1908
  )
1909
  _server_timeout = float(os.environ.get("RL_VLLM_SERVER_TIMEOUT", "1200"))
1910
  if _trainer_only:
@@ -1922,8 +1975,17 @@ def run_rl():
1922
  # take longer, so default generously (uvicorn binds the HTTP port only AFTER the worker
1923
  # finishes loading, so the health check sees connection-refused until then).
1924
  try:
 
 
 
 
 
1925
  _disagg.wait_for_server_health(
1926
- _port, timeout=_server_timeout, proc=vllm_proc, log_path=_server_log
 
 
 
 
1927
  )
1928
  except BaseException:
1929
  # A server boot failure / health-check error here must NOT leak the vllm-serve
@@ -2125,7 +2187,14 @@ def run_rl():
2125
  import subprocess as _sp
2126
 
2127
  t_train = time.time()
2128
- _acc_cmd = _disagg.build_accelerate_launch_cmd(_rollout_split)
 
 
 
 
 
 
 
2129
  _child_env = dict(os.environ)
2130
  _child_env["AUTOSLM_RL_TRAINER_ONLY"] = "1"
2131
  _child_env["AUTOSLM_VLLM_SERVER_PORT"] = str(_port)
@@ -2135,11 +2204,23 @@ def run_rl():
2135
  # device placement across the train GPUs.
2136
  _child_env.pop("CUDA_VISIBLE_DEVICES", None)
2137
  print(f"[rl][disagg][fsdp] launching FSDP trainer group ({_rollout_split.label}): {' '.join(_acc_cmd)}")
2138
- _rc = _sp.run(_acc_cmd, env=_child_env).returncode
 
 
 
 
 
 
 
 
 
 
 
 
2139
  if _rc != 0:
2140
  raise RuntimeError(
2141
  f"accelerate FSDP trainer group exited {_rc} (split {_rollout_split.label}); "
2142
- "see error_rl.txt / console_rl.txt"
2143
  )
2144
  print("[rl][disagg][fsdp] trainer group finished; artifacts written by rank 0")
2145
  else:
 
258
 
259
  class _CheckpointUpload(TrainerCallback):
260
  def on_save(self, args, state, control, **kwargs):
261
+ # Multi-GPU (FSDP / accelerate) runs on_save on EVERY rank; only the single global
262
+ # main process may upload, or ranks race on the same HF commit and one rank's
263
+ # delete_patterns can wipe another rank's just-uploaded checkpoint. Single-GPU runs
264
+ # are always world-process-zero, so this is a no-op there.
265
+ if not state.is_world_process_zero:
266
+ return
267
  if not HF_REPO:
268
  return
269
  step = int(state.global_step)
 
878
  # `or` (not a get-default): a present-but-blank AUTOSLM_LORA_INIT must fall back too, else
879
  # init_lora_weights="" reaches PEFT as an invalid value instead of a real init method.
880
  _lora_init = os.environ.get("AUTOSLM_LORA_INIT") or "pissa_niter_16"
881
+ # PiSSA's SVD init requires an UNQUANTIZED base ("Please initialize PiSSA under
882
+ # float32/float16/bfloat16"); it raises on a 4-bit (qlora) base at adapter creation. Force
883
+ # standard init for qlora models regardless of the configured default, so the 4-bit trainers
884
+ # (Qwen3.5-9B, Qwen3.6-35B-A3B) don't crash — this hit 9B colocate (asb-esc-q9b-coloB).
885
+ if (
886
+ model_id
887
+ and model_quant(model_id) == "4bit-qlora"
888
+ and _lora_init.lower() not in ("default", "standard", "plain", "true")
889
+ ):
890
+ print(f"[lora] {model_id} is 4-bit qlora; PiSSA needs an unquantized base -> forcing standard init")
891
+ _lora_init = "default"
892
  if _lora_init.lower() in ("default", "standard", "plain", "true"):
893
  kwargs["init_lora_weights"] = True
894
  print("[lora] init_lora_weights=default (standard LoRA init; pissa disabled)")
 
1234
  # ---------------------------------------------------------------------------
1235
  # RL (GRPO) with TRL + colocated vLLM
1236
  # ---------------------------------------------------------------------------
1237
+ def compute_grpo_batching(
1238
+ prompts_per_step: int, group_size: int, per_device_comps: int, num_processes: int = 1
1239
+ ) -> dict:
1240
  """Translate an intended ``prompts_per_step`` into a TRL GRPO batch configuration.
1241
 
1242
  TRL's GRPO batch sizing is denominated in **completions (prompt-completion pairs), not
 
1260
  prompts_per_step = max(1, int(prompts_per_step))
1261
  per_device = max(1, int(per_device_comps))
1262
  target_comps = prompts_per_step * group_size # total completions / optimizer step
1263
+ nproc = max(1, int(num_processes))
1264
+ # Never let the per-device completion micro-batch exceed the PER-RANK share of the target
1265
+ # completion batch. The smallest GLOBAL micro-batch is per_device * num_processes, so capping at
1266
+ # the full target_comps (ignoring rank count) would let an num_processes>1 FSDP run overshoot
1267
+ # prompts_per_step*group_size and inflate unique_prompts/step. Cap at target_comps // nproc
1268
+ # (mirrors run_sft's `min(per_device_bs, effective_batch)`; no-op at the default nproc=1).
1269
+ per_device = max(1, min(per_device, max(1, target_comps // nproc)))
1270
+ # The GLOBAL completion batch TRL optimizes is per_device * grad_accum * num_processes —
1271
+ # accelerate/TRL multiply by the data-parallel world size (FSDP trainer ranks). To still optimize
1272
+ # `prompts_per_step` prompts/step under an `num_processes`-rank FSDP trainer, grad_accum must be
1273
+ # divided by num_processes; otherwise the effective batch (and unique_prompts/step) scales with
1274
+ # the rank count, and a small dataset can't fill even one step (the FSDP 0-real-steps bug seen on
1275
+ # 2:2). num_processes=1 (colocate / single-trainer 1:1/1:2) is unchanged.
1276
+ grad_accum = max(1, target_comps // (per_device * nproc))
1277
  # TRL rejects a global completion batch (per_device * grad_accum) that is not
1278
  # divisible by num_generations (= group_size), failing only AFTER the paid worker
1279
  # is provisioned. per_device is the fixed VRAM knob, so round grad_accum UP to the
 
1282
  # batch slightly; the common per_device|group_size cases are unchanged.
1283
  accum_step = group_size // math.gcd(per_device, group_size)
1284
  grad_accum = ((grad_accum + accum_step - 1) // accum_step) * accum_step
1285
+ # generations_per_step / unique_prompts_per_step are reported GLOBALLY (across all ranks) so the
1286
+ # metric matches the intended prompts_per_step regardless of the trainer world size.
1287
+ generations_per_step = per_device * grad_accum * nproc
1288
  unique_prompts_per_step = generations_per_step // group_size
1289
  return {
1290
  "per_device_train_batch_size": per_device,
 
1497
 
1498
 
1499
  def run_rl():
1500
+ # Backend dispatch: AUTOSLM_FRAMEWORK=verl runs the verl GRPO+LoRA+async path (sidecar venv,
1501
+ # isolated from this baked TRL/vLLM stack). The TRL path below is byte-for-byte unchanged.
1502
+ if os.environ.get("AUTOSLM_FRAMEWORK", "trl").strip().lower() == "verl":
1503
+ from autoslm.engine import verl_runner
1504
+
1505
+ return verl_runner.run()
1506
+
1507
  from datasets import Dataset
1508
  from transformers import AutoTokenizer
1509
  from trl import GRPOConfig, GRPOTrainer
 
1775
  if _params_b is None:
1776
  _params_b = fetch_hf_params_b(model_id)
1777
  per_device_comps = rl_per_device_comps(_max_completion, use_vllm=use_vllm, params_b=_params_b)
1778
+ # In the FSDP trainer child the optimizer runs across train_gpus ranks, so the per-rank grad_accum
1779
+ # must be divided by that count (else the global batch over-scales and a small dataset yields 0
1780
+ # real steps). The single-process paths (colocate, 1:1/1:2 with one trainer GPU, and the launcher
1781
+ # which builds no trainer) pass num_processes=1 — unchanged.
1782
+ _grpo_nproc = _rollout_split.train_gpus if (_trainer_only and _rollout_split) else 1
1783
+ batching = compute_grpo_batching(
1784
+ prompts_per_step, group_size, per_device_comps, num_processes=_grpo_nproc
1785
+ )
1786
  if not batching["divisible_by_group"]:
1787
  print("WARN: generation batch not divisible by group size; check RL_PER_DEVICE_PROMPTS")
1788
  print(
 
1940
  f"requires heads % TP == 0). Valid inference_gpus for this model: {_valid}. "
1941
  f"Pick a [train] inference_gpus from that set (e.g. a 1:2 or 1:4 split)."
1942
  )
1943
+ # Optional --enforce_eager: skip vLLM CUDA-graph capture at server boot. For very large
1944
+ # models (e.g. the 35B-A3B MoE) graph capture dominates the boot window and can blow past
1945
+ # RL_VLLM_SERVER_TIMEOUT before the server is ever healthy; eager trades a little decode
1946
+ # throughput for a tractable boot. Opt-in via AUTOSLM_RL_VLLM_ENFORCE_EAGER so small models
1947
+ # keep graphs (their boot is cheap and they want the decode speed).
1948
+ _vllm_extra: list[str] = []
1949
+ if os.environ.get("AUTOSLM_RL_VLLM_ENFORCE_EAGER", "").strip().lower() in ("1", "true", "yes"):
1950
+ _vllm_extra += ["--enforce_eager", "true"]
1951
  _cmd = _disagg.build_vllm_serve_cmd(
1952
  model_id,
1953
  _rollout_split,
 
1957
  quant=quant,
1958
  kv_cache_dtype=_server_kv,
1959
  parallel=_parallel,
1960
+ extra=(_vllm_extra or None),
1961
  )
1962
  _server_timeout = float(os.environ.get("RL_VLLM_SERVER_TIMEOUT", "1200"))
1963
  if _trainer_only:
 
1975
  # take longer, so default generously (uvicorn binds the HTTP port only AFTER the worker
1976
  # finishes loading, so the health check sees connection-refused until then).
1977
  try:
1978
+ # Emit a heartbeat every 60s during the boot so the control plane's no-heartbeat
1979
+ # STALL detector (~25 min) doesn't kill a big model mid-boot: the 35B server
1980
+ # (70 GB bf16 + tilelang/CUDA-graph JIT) can take >20 min to bind its port, and that
1981
+ # whole stretch is silent otherwise. (This was why the 35B run got killed at 1503s.)
1982
+ _boot_t0 = time.time()
1983
  _disagg.wait_for_server_health(
1984
+ _port,
1985
+ timeout=_server_timeout,
1986
+ proc=vllm_proc,
1987
+ log_path=_server_log,
1988
+ on_wait=lambda: heartbeat("rl_server_boot", boot_seconds=round(time.time() - _boot_t0)),
1989
  )
1990
  except BaseException:
1991
  # A server boot failure / health-check error here must NOT leak the vllm-serve
 
2187
  import subprocess as _sp
2188
 
2189
  t_train = time.time()
2190
+ # Use DDP (replicate the model on each trainer rank), NOT FSDP sharding. TRL's per-step
2191
+ # weight sync calls peft merge_adapter()->get_delta_weight (weight_B @ weight_A); FSDP
2192
+ # (FULL_SHARD and even SHARD_GRAD_OP) flattens/shards the LoRA params so the merge fails
2193
+ # ("inconsistent tensor size [32768] vs [24576]"). DDP keeps each param whole on every
2194
+ # rank, so the merge works. Every model that runs a multi-trainer ratio here (1-9B)
2195
+ # fits replicated on one trainer card; the only model that wouldn't (35B) uses the
2196
+ # single-trainer 1:1 path, so DDP covers all the 2:1/2:2/3:1 ratios.
2197
+ _acc_cmd = _disagg.build_accelerate_launch_cmd(_rollout_split, use_fsdp=False)
2198
  _child_env = dict(os.environ)
2199
  _child_env["AUTOSLM_RL_TRAINER_ONLY"] = "1"
2200
  _child_env["AUTOSLM_VLLM_SERVER_PORT"] = str(_port)
 
2204
  # device placement across the train GPUs.
2205
  _child_env.pop("CUDA_VISIBLE_DEVICES", None)
2206
  print(f"[rl][disagg][fsdp] launching FSDP trainer group ({_rollout_split.label}): {' '.join(_acc_cmd)}")
2207
+ # Capture the child group's stdout+stderr to a file and ALWAYS upload it: the launcher's
2208
+ # own console is not reliably captured once the child writes DONE, so this is the only way
2209
+ # to see the FSDP trainer's behavior (real steps vs 0-step empty run) for debugging.
2210
+ _child_log = "/tmp/fsdp_child.log"
2211
+ with open(_child_log, "w") as _clf:
2212
+ _rc = _sp.run(_acc_cmd, env=_child_env, stdout=_clf, stderr=_sp.STDOUT).returncode
2213
+ print("[rl][disagg][fsdp] --- accelerate child log tail (last 160) ---")
2214
+ print(_disagg._server_log_tail(_child_log, n=160))
2215
+ print("[rl][disagg][fsdp] --- end child log ---", flush=True)
2216
+ try:
2217
+ hf_upload_file(_child_log, "console_fsdp_child.txt")
2218
+ except Exception as _e:
2219
+ print(f"[rl][disagg][fsdp] could not upload child log: {_e}")
2220
  if _rc != 0:
2221
  raise RuntimeError(
2222
  f"accelerate FSDP trainer group exited {_rc} (split {_rollout_split.label}); "
2223
+ "see console_fsdp_child.txt"
2224
  )
2225
  print("[rl][disagg][fsdp] trainer group finished; artifacts written by rank 0")
2226
  else:
code/autoslm/providers/allocator.py CHANGED
@@ -52,6 +52,7 @@ def required_vram_gb(
52
  *,
53
  train=None,
54
  thinking: bool = False,
 
55
  ) -> int:
56
  """VRAM the full run needs, sized to the run's actual knobs (context length, LoRA
57
  rank, batch / group size, thinking) via the shared ``model_required_vram_gb`` matrix.
@@ -62,13 +63,74 @@ def required_vram_gb(
62
  when unreadable (handled inside model_required_vram_gb)."""
63
  from autoslm.engine.vram import model_required_vram_gb
64
 
65
- return model_required_vram_gb(
66
  model_id,
67
  algorithm,
68
  train=train,
69
  thinking=thinking,
70
  headroom=vram_headroom(),
71
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
 
74
  def _runpod_candidates(need: int, pinned_gpu: str | None, allow_unval: bool) -> list[Candidate]:
@@ -185,7 +247,7 @@ def allocate(
185
  # pin (e.g. Qwen3-8B on a 24 GB card) must drop out of the candidate filter and
186
  # raise here, not provision a paid worker that OOMs. The pin only narrows WHICH
187
  # fitting class is chosen, never lowers the VRAM bar.
188
- need = required_vram_gb(model_id, algorithm, train=train, thinking=thinking)
189
  allow_unval = unvalidated_allowed(allow_unvalidated)
190
  live = available_providers()
191
  if provider != "auto" and provider not in live:
 
52
  *,
53
  train=None,
54
  thinking: bool = False,
55
+ gpu_count: int = 1,
56
  ) -> int:
57
  """VRAM the full run needs, sized to the run's actual knobs (context length, LoRA
58
  rank, batch / group size, thinking) via the shared ``model_required_vram_gb`` matrix.
 
63
  when unreadable (handled inside model_required_vram_gb)."""
64
  from autoslm.engine.vram import model_required_vram_gb
65
 
66
+ colocate = model_required_vram_gb(
67
  model_id,
68
  algorithm,
69
  train=train,
70
  thinking=thinking,
71
  headroom=vram_headroom(),
72
  )
73
+ # Disaggregated GRPO ([train].inference_gpus>0) splits memory across the node's GPUs: the
74
+ # inference server (full bf16 weights + KV) and the trainer (quant weights + LoRA optimizer +
75
+ # activations) live on SEPARATE cards, so no single GPU needs the colocate total. The binding
76
+ # per-GPU need is max(server bf16 weights + KV/overhead, the trainer's share ~= colocate minus
77
+ # the vLLM engine/KV). Sizing to that lets a big model fit a per-role card (e.g. Qwen3.6-35B-A3B
78
+ # served bf16 on a 94GB H100 NVL, 4-bit trainer on the other) instead of demanding the colocate
79
+ # floor (~96GB) — which no available 2-GPU node meets — while staying FLOORED by the bf16 weights
80
+ # so the server can never be under-provisioned into an OOM. Also unblocks 4B 1:2 on a 5090 (the
81
+ # disaggregated server/trainer each fit 32GB though colocate 4B needs ~35GB).
82
+ if train is not None and int(getattr(train, "inference_gpus", 0) or 0) > 0:
83
+ pb = _params_b_for_vram(model_id)
84
+ if pb:
85
+ infer = max(1, int(getattr(train, "inference_gpus", 1) or 1))
86
+ # Total GPUs on the node (rollout + trainer). The trainer pool is everything that
87
+ # isn't a rollout GPU; default to a single trainer when the caller didn't pass a count
88
+ # (the colocate cap below still protects that degenerate case).
89
+ total = max(infer + 1, int(gpu_count or (infer + 1)))
90
+ n_trainer = max(1, total - infer)
91
+ base = 2.0 * pb # frozen base model, bf16, ALL params resident (MoE: every expert loaded)
92
+
93
+ # ROLLOUT card. The baked verl default is DATA-PARALLEL (TP=1) — each replica holds the
94
+ # FULL base + KV. A base too large to fit one 80GB card as a DP replica is served
95
+ # TENSOR-PARALLEL across the inference GPUs instead (verl_runner auto-bumps
96
+ # AUTOSLM_VERL_ROLLOUT_TP to match), so size per shard. Floors the per-card need so the
97
+ # inference GPU is never under-provisioned into a KV/weights OOM.
98
+ rollout_tp = infer if (base * 1.35 + 4) > 78 else 1
99
+ rollout_need = int(base * 1.35 / rollout_tp) + 4 # weights/shard + KV / CUDA-graph / overhead
100
+
101
+ # TRAINER card. FSDP2 shards the frozen base (+ tiny LoRA grads/optim) across the
102
+ # n_trainer trainer GPUs; activations and the one_step_off *bucketed* weight-transfer
103
+ # staging do NOT shard, so floor each card at base/n_trainer + a bounded transfer buffer +
104
+ # fixed overhead. n_trainer==1 keeps the whole base on one card (matches the observed 4B
105
+ # one-trainer OOM on a 24GB card — needed ~26GB, fits 40GB — while 4B sharded across two
106
+ # trainers fits 24GB). The bucketed sync stages only a few layers, NOT a full second copy,
107
+ # so 35B-A3B (70GB base) trains across 2 trainers at ~58GB/card and fits an 80GB H100/A100.
108
+ transfer_buf = min(0.5 * base, 10.0)
109
+ trainer_need = int(base / n_trainer + transfer_buf + 13)
110
+
111
+ # Per-card requirement is the heavier role on a homogeneous node. This is already a true
112
+ # per-card figure (both roles divided by their parallel degree), so no colocate cap — a
113
+ # multi-GPU FSDP/TP split legitimately needs LESS per card than the whole colocated total.
114
+ return max(rollout_need, trainer_need)
115
+ return colocate
116
+
117
+
118
+ def _params_b_for_vram(model_id: str) -> float | None:
119
+ """Param count (billions) for disaggregated VRAM sizing: catalog first, then HF metadata."""
120
+ from autoslm.engine.vram import fetch_hf_params_b, params_b_from_str
121
+
122
+ try:
123
+ from autoslm.catalog import get_model
124
+
125
+ pb = params_b_from_str(getattr(get_model(model_id), "params", None))
126
+ if pb:
127
+ return pb
128
+ except Exception:
129
+ pass
130
+ try:
131
+ return fetch_hf_params_b(model_id)
132
+ except Exception:
133
+ return None
134
 
135
 
136
  def _runpod_candidates(need: int, pinned_gpu: str | None, allow_unval: bool) -> list[Candidate]:
 
247
  # pin (e.g. Qwen3-8B on a 24 GB card) must drop out of the candidate filter and
248
  # raise here, not provision a paid worker that OOMs. The pin only narrows WHICH
249
  # fitting class is chosen, never lowers the VRAM bar.
250
+ need = required_vram_gb(model_id, algorithm, train=train, thinking=thinking, gpu_count=gpu_count)
251
  allow_unval = unvalidated_allowed(allow_unvalidated)
252
  live = available_providers()
253
  if provider != "auto" and provider not in live:
code/autoslm/providers/runpod/jobs.py CHANGED
@@ -62,10 +62,14 @@ TERMINAL_FAIL = {"FAILED", "CANCELLED", "TIMED_OUT"}
62
 
63
  # Heartbeat stages the worker emits DURING cold start, BEFORE the model is loaded and the
64
  # training loop begins (boot -> sft_start/rl_start, then later sft_model_load/rl_train_start).
 
 
 
 
65
  # Receiving one proves the worker is alive but NOT that the slow setup (model download +
66
  # vLLM init) finished, so they must not flip stall detection to the tight training window.
67
  _SETUP_HEARTBEAT_STAGES = frozenset(
68
- {"boot", "sft_start", "rl_start", "sft_model_load", "rl_train_start"}
69
  )
70
 
71
 
@@ -404,8 +408,15 @@ def submit_run(spec, seed: int, log=None, on_handle=None, attempt: int = 0) -> P
404
  "extra_pip": extra_pip,
405
  "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
406
  }
 
 
 
 
 
 
 
407
  try:
408
- job_id = runpod_api.submit_job(endpoint_id, build_function_input(payload, spec.gpu.type))
409
  except Exception:
410
  # The endpoint is registered but no run handle exists yet, and a
411
  # retry endpoint's rN-suffixed name can't be reconstructed from the run
 
62
 
63
  # Heartbeat stages the worker emits DURING cold start, BEFORE the model is loaded and the
64
  # training loop begins (boot -> sft_start/rl_start, then later sft_model_load/rl_train_start).
65
+ # ``rl_server_boot`` is the disaggregated (multi-GPU) rollout server's boot heartbeat, emitted
66
+ # every ~60s while vLLM loads the model and binds its port — still pre-training, so it likewise
67
+ # stays under setup_grace_s (otherwise the FIRST boot ping would prematurely flip to the tight
68
+ # training window while the server is still booting).
69
  # Receiving one proves the worker is alive but NOT that the slow setup (model download +
70
  # vLLM init) finished, so they must not flip stall detection to the tight training window.
71
  _SETUP_HEARTBEAT_STAGES = frozenset(
72
+ {"boot", "sft_start", "rl_start", "sft_model_load", "rl_train_start", "rl_server_boot"}
73
  )
74
 
75
 
 
408
  "extra_pip": extra_pip,
409
  "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
410
  }
411
+ # The BAKED worker image ships a custom /rp_handler.py whose handler calls
412
+ # ``_train_body(job["input"])`` directly, so the job input must be the RAW payload. The
413
+ # ``build_function_input`` FunctionRequest envelope ({function_name, function_code, args}) is
414
+ # ONLY for the live runpod_flash runtime (no image), which deserializes ``args`` before calling
415
+ # ``_train_body``. Sending the envelope to the baked handler made it read the envelope as
416
+ # ``input_data`` -> ``input_data["hf_repo"]`` KeyError. Pick the shape that matches the runtime.
417
+ job_input = payload if WORKER_IMAGE else build_function_input(payload, spec.gpu.type)
418
  try:
419
+ job_id = runpod_api.submit_job(endpoint_id, job_input)
420
  except Exception:
421
  # The endpoint is registered but no run handle exists yet, and a
422
  # retry endpoint's rN-suffixed name can't be reconstructed from the run
code/autoslm/providers/runpod/train.py CHANGED
@@ -183,11 +183,22 @@ def upload_code(repo: str | None = None) -> str:
183
  # downloads (worker gets 403), so operators on a free tier must publish artifact repos
184
  # public. Default private (paid-tier safe); set AUTOSLM_HF_REPO_PRIVATE=0 to create public.
185
  private = os.environ.get("AUTOSLM_HF_REPO_PRIVATE", "1") not in ("0", "false", "False")
186
- api.create_repo(repo, repo_type="dataset", exist_ok=True, private=private)
 
 
 
 
 
 
 
 
 
 
 
187
  # create_repo(exist_ok=True) is a no-op on an EXISTING repo, so it never flips a repo that
188
  # already exists private back to public. When the operator wants public (free-tier: workers
189
  # 403 on private downloads), force visibility explicitly so a reused private repo is fixed.
190
- if not private:
191
  try:
192
  api.update_repo_settings(repo_id=repo, repo_type="dataset", private=False)
193
  except Exception as e:
 
183
  # downloads (worker gets 403), so operators on a free tier must publish artifact repos
184
  # public. Default private (paid-tier safe); set AUTOSLM_HF_REPO_PRIVATE=0 to create public.
185
  private = os.environ.get("AUTOSLM_HF_REPO_PRIVATE", "1") not in ("0", "false", "False")
186
+ # HF caps repository CREATION at 300/day per account; create_repo(exist_ok=True) still POSTs to
187
+ # /api/repos/create (the 409 is swallowed client-side) and so each call counts against that cap.
188
+ # A benchmark/sweep that uses one HF repo per run blows the cap fast. Gate the create on a cheap
189
+ # repo_exists() GET (not rate-limited) so reusing an existing artifact repo makes ZERO creation
190
+ # calls — only a genuinely new repo hits the create endpoint.
191
+ already = False
192
+ try:
193
+ already = api.repo_exists(repo, repo_type="dataset")
194
+ except Exception:
195
+ already = False
196
+ if not already:
197
+ api.create_repo(repo, repo_type="dataset", exist_ok=True, private=private)
198
  # create_repo(exist_ok=True) is a no-op on an EXISTING repo, so it never flips a repo that
199
  # already exists private back to public. When the operator wants public (free-tier: workers
200
  # 403 on private downloads), force visibility explicitly so a reused private repo is fixed.
201
+ if not private and not already:
202
  try:
203
  api.update_repo_settings(repo_id=repo, repo_type="dataset", private=False)
204
  except Exception as e: