| """verl GRPO + LoRA runner (AUTOSLM_FRAMEWORK=verl). |
| |
| Runs verl in a SIDECAR venv on the provisioned box, isolated from the baked TRL/vLLM |
| stack (baked = torch 2.10 + vllm 0.19.1 + transformers 5; verl needs vllm<=0.12 + |
| transformers<5 — hard conflict, so a clean venv). Benchmarks verl's one-step-off async |
| overlap WITH LoRA (the path TRL's AsyncGRPOTrainer can't do — it's full-FT-only). |
| |
| Single GPU (inference_gpus=0): verl.trainer.main_ppo colocate (hybrid_engine, no overlap) |
| -> apples-to-apples vs our TRL colocate s/step. |
| >=2 GPU (inference_gpus>0): verl.experimental.one_step_off_policy.main_ppo, hybrid_engine=False |
| -> the real generation<->training OVERLAP (gen(t+1) overlaps train(t)). |
| |
| Writes /tmp/metrics.json in the shape the autoslm pipeline reads |
| ({wall_seconds, notes:{steps,...}, reward_history}). |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| import os |
| import re |
| import subprocess |
| import sys |
| import threading |
| import time |
|
|
| VENV = "/opt/verl-venv" |
| VPY = f"{VENV}/bin/python" |
| VPIP = f"{VENV}/bin/pip" |
| VERL_DIR = "/opt/verl" |
| WORKDIR = "/tmp/verl" |
| |
| |
| |
| RUN_PY = VPY |
|
|
|
|
| def _hb(stage: str, **kw): |
| try: |
| from autoslm.engine.worker import heartbeat |
|
|
| heartbeat(stage, **kw) |
| except Exception: |
| print(f"[verl][hb] {stage} {kw}", flush=True) |
|
|
|
|
| def _spec(): |
| from autoslm.engine import worker as W |
|
|
| return W.JOB_SPEC |
|
|
|
|
| def _run(cmd, cwd=None, env=None, check=True, capture=False): |
| print(f"[verl] $ {cmd if isinstance(cmd, str) else ' '.join(map(str, cmd))}", flush=True) |
| r = subprocess.run( |
| cmd, cwd=cwd, env=env, shell=isinstance(cmd, str), |
| text=True, capture_output=capture, |
| ) |
| if capture: |
| if r.stdout: |
| print(r.stdout[-4000:], flush=True) |
| if r.stderr: |
| print(r.stderr[-4000:], flush=True) |
| if check and r.returncode != 0: |
| raise RuntimeError(f"command failed (rc={r.returncode}): {cmd if isinstance(cmd,str) else ' '.join(map(str,cmd))}") |
| return r |
|
|
|
|
| def _ensure_uv() -> str: |
| """Return a path to `uv` (creates venvs without python3-venv/ensurepip, installs fast). |
| Prefer one already on the image; else bootstrap via system pip, else the standalone installer.""" |
| import shutil |
|
|
| def _find(): |
| cands = ["uv", os.path.expanduser("~/.local/bin/uv"), "/root/.local/bin/uv", |
| "/usr/local/bin/uv", "/opt/uv/uv"] |
| for c in cands: |
| p = shutil.which(c) if "/" not in c else (c if os.path.exists(c) else None) |
| if p: |
| return p |
| return None |
|
|
| p = _find() |
| if p: |
| return p |
| for pipcmd in ([sys.executable, "-m", "pip", "install", "-q", "uv"], ["pip", "install", "-q", "uv"]): |
| if subprocess.run(pipcmd, capture_output=True, text=True).returncode == 0: |
| break |
| p = _find() |
| if p: |
| return p |
| subprocess.run("curl -LsSf https://astral.sh/uv/install.sh | sh", shell=True) |
| p = _find() |
| if p: |
| return p |
| raise RuntimeError("could not obtain uv for the verl sidecar venv") |
|
|
|
|
| def _install(): |
| """Install the verl stack and return the python executable verl should run with. |
| |
| OLD stack (default): a fresh uv venv with PUBLIC-PyPI vllm 0.11 + transformers 4.57 + a MATCHING |
| torchvision -> MiniCPM/Qwen2.5/Qwen3-dense. Cannot load the qwen3_5 arch. |
| BAKED stack (AUTOSLM_VERL_USE_BAKED_STACK=1): for Qwen3.5/3.6. The baked image's vllm 0.19.1 + |
| transformers 5 + torch + torchvision are INTERNAL builds (not on PyPI) and MUTUALLY MATCHED. |
| Install verl + its non-baked deps straight into the SYSTEM python (no venv) so all of them are |
| reused as-is. (A --system-site-packages venv + uv reinstalls torch and breaks the baked |
| torchvision -> `operator torchvision::nms does not exist`.) |
| """ |
| global RUN_PY |
| |
| |
| |
| |
| use_baked = os.environ.get("AUTOSLM_VERL_USE_BAKED_STACK", "1").strip().lower() in ("1", "true", "yes") |
| py = sys.executable if use_baked else VPY |
| RUN_PY = py |
| |
| |
| if os.path.exists(py): |
| chk = subprocess.run( |
| [py, "-c", "import verl, vllm, torch, transformers; print(vllm.__version__, torch.__version__, transformers.__version__)"], |
| text=True, capture_output=True, |
| ) |
| if chk.returncode == 0: |
| print(f"[verl] stack ready ({py}): vllm/torch/transformers = {chk.stdout.strip()}", flush=True) |
| return py |
|
|
| verl_ref = os.environ.get("AUTOSLM_VERL_REF", "").strip() |
| vllm_pin = os.environ.get("AUTOSLM_VERL_VLLM", "vllm==0.11.0").strip() |
| tf_pin = os.environ.get("AUTOSLM_VERL_TRANSFORMERS", "transformers==4.57.0").strip() |
| fa_pin = os.environ.get("AUTOSLM_VERL_FLASHATTN", "flash-attn==2.8.1").strip() |
| tv_pin = os.environ.get("AUTOSLM_VERL_TORCHVISION", "torchvision==0.23.0").strip() |
| uv = _ensure_uv() |
|
|
| |
| bsp = ["--break-system-packages"] if use_baked else [] |
|
|
| def upip(*pkgs, check=True): |
| return _run([uv, "pip", "install", "-p", py, *bsp, *pkgs], check=check, capture=True) |
|
|
| _hb("verl_install", step="venv", baked=use_baked) |
| if not use_baked: |
| |
| _run([uv, "venv", VENV, "--python", sys.executable]) |
| upip("pip", "setuptools", "wheel") |
| if not os.path.exists(os.path.join(VERL_DIR, "setup.py")) and not os.path.exists(os.path.join(VERL_DIR, "pyproject.toml")): |
| _hb("verl_install", step="clone") |
| clone = ["git", "clone", "--depth", "1"] |
| if verl_ref: |
| clone += ["--branch", verl_ref] |
| clone += ["https://github.com/verl-project/verl", VERL_DIR] |
| _run(clone, check=not verl_ref) |
| if not os.path.exists(os.path.join(VERL_DIR, "pyproject.toml")): |
| _run(["rm", "-rf", VERL_DIR], check=False) |
| _run(["git", "clone", "https://github.com/verl-project/verl", VERL_DIR]) |
| if verl_ref: |
| _run(["git", "checkout", verl_ref], cwd=VERL_DIR) |
| if not use_baked: |
| _hb("verl_install", step="vllm_transformers", vllm=vllm_pin, transformers=tf_pin) |
| upip(vllm_pin, tf_pin) |
| |
| |
| _tvr = upip("torchvision", check=False) |
| if _tvr.returncode != 0: |
| upip(tv_pin, check=False) |
| _hb("verl_install", step="flash_attn") |
| upip(fa_pin, "--no-build-isolation", check=False) |
| else: |
| _hb("verl_install", step="baked_stack_reused", note="vllm/transformers/torch/torchvision from baked system python") |
| _hb("verl_install", step="deps") |
| |
| |
| upip("ray[default]>=2.41.0", "tensordict>=0.8.0,<=0.10.0", "hydra-core", "omegaconf", |
| "datasets", "pyarrow", "pandas", "codetiming", "dill", "pylatexenc", "wandb", |
| "math_verify", "accelerate", "peft>=0.19", "torchdata", "torchmetrics") |
| |
| |
| |
| if os.environ.get("AUTOSLM_VERL_OVERLAP", "").strip().lower() in ("1", "true", "yes"): |
| _hb("verl_install", step="nccl_ckpt_engine_deps") |
| upip("cupy-cuda12x", "pyzmq", check=False) |
| _hb("verl_install", step="verl") |
| _run([uv, "pip", "install", "-p", py, *bsp, "--no-deps", "-e", "."], cwd=VERL_DIR) |
| _install_chalk(uv, py) |
| 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) |
| print(f"[verl] install verified ({py}): {chk.stdout.strip()}", flush=True) |
| return py |
|
|
|
|
| |
| |
| _CHALK_CLASS_INSTALLERS = { |
| "FLASH_MLP_KERNEL": "install_qwen35_mlp", |
| "FLASH_QKV_KERNEL": "install_qwen35_qkv", |
| "FLASH_TRITON_LORA": "install_lora", |
| "FLASH_ROPE_KERNEL": "install_qwen35_rope", |
| } |
|
|
|
|
| def _install_chalk(uv, py): |
| """Keep our kernel optimizations (chalk) active in the verl path. chalk = the freesolo-chalk |
| package (hand-written Triton/CUDA Qwen3.5 kernels), install-on-call. We (a) install it via |
| FLASH_CHALK_SPEC, and (b) drop a sitecustomize.py in `py`'s site-packages that calls the selected |
| class-level installers at interpreter startup, so verl's actor model gets the kernels before build. |
| Best-effort + gated: no FLASH_* flag / no spec -> no-op. Only meaningful for Qwen3.5 (baked stack).""" |
| selected = [v for k, v in _CHALK_CLASS_INSTALLERS.items() |
| if os.environ.get(k, "").strip().lower() in ("1", "true", "yes")] |
| spec = os.environ.get("FLASH_CHALK_SPEC", "").strip() |
| if not selected and not spec: |
| return |
| _hb("verl_install", step="chalk", installers=selected) |
| if spec: |
| _run([uv, "pip", "install", "-p", py, spec], check=False, capture=True) |
| |
| |
| r = subprocess.run([py, "-c", "import site;print(site.getsitepackages()[0])"], text=True, capture_output=True) |
| site_dir = r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None |
| if not site_dir or not os.path.isdir(site_dir): |
| print("[verl][chalk] no site-packages dir found; skipping sitecustomize", flush=True) |
| return |
| site_dirs = [site_dir] |
| calls = "\n".join(f" _c.{fn}()" for fn in selected) |
| sc = ( |
| "import os\n" |
| "try:\n" |
| " import freesolo_chalk as _c\n" |
| f"{calls if calls else ' pass'}\n" |
| " print('[chalk] class-level kernels installed: ' + ','.join(%r))\n" % selected |
| + "except Exception as _e:\n" |
| " print('[chalk] sitecustomize skipped: ' + repr(_e))\n" |
| ) |
| with open(os.path.join(site_dirs[0], "sitecustomize.py"), "w") as f: |
| f.write(sc) |
| print(f"[verl][chalk] wrote sitecustomize calling {selected}", flush=True) |
|
|
|
|
| def _build_dataset(model_path: str, n_rows: int, prompt_tokens: int): |
| """Synthetic GRPO dataset: ~prompt_tokens-long chat prompts + a simple rule reward. |
| Throughput (gen n*resp + train) dominates s/step, so a simple reward is fine for the bench.""" |
| os.makedirs(WORKDIR, exist_ok=True) |
| import pandas as pd |
|
|
| |
| |
| |
| filler = ("Reason step by step about the following problem and give the final answer. " * 60) |
| words = filler.split() |
| approx = max(8, int(prompt_tokens * 0.55 / 1.3)) |
| content = " ".join((words * (approx // len(words) + 1))[:approx]) |
| rows = [] |
| for i in range(n_rows): |
| rows.append({ |
| "data_source": "autoslm_bench", |
| "prompt": [{"role": "user", "content": f"[{i}] {content}"}], |
| "ability": "bench", |
| "reward_model": {"style": "rule", "ground_truth": "x"}, |
| "extra_info": {"index": i, "split": "train"}, |
| }) |
| df = pd.DataFrame(rows) |
| df.to_parquet(f"{WORKDIR}/train.parquet") |
| df.head(max(8, n_rows // 8)).to_parquet(f"{WORKDIR}/val.parquet") |
| print(f"[verl] dataset: {n_rows} rows, ~{prompt_tokens} prompt tok -> {WORKDIR}/train.parquet", flush=True) |
|
|
|
|
| def _write_reward(): |
| """A trivial length-aware reward (verl custom_reward_function contract). Throughput bench |
| doesn't depend on the reward signal; this just exercises the scoring path.""" |
| src = ( |
| "def compute_score(data_source, solution_str, ground_truth, extra_info=None):\n" |
| " n = len(solution_str or '')\n" |
| " return 1.0 if n > 0 else 0.0\n" |
| ) |
| with open(f"{WORKDIR}/verl_reward.py", "w") as f: |
| f.write(src) |
|
|
|
|
| def _build_cmd(model_path, split, *, group_size, prompt_len, resp_len, lora_rank, lora_alpha, steps, train_bs): |
| overlap = split.infer_gpus > 0 |
| if overlap: |
| entry = ["-m", "verl.experimental.one_step_off_policy.main_ppo", |
| "--config-path=config", "--config-name=one_step_off_ppo_trainer"] |
| else: |
| entry = ["-m", "verl.trainer.main_ppo"] |
| ov = [ |
| "algorithm.adv_estimator=grpo", |
| "algorithm.use_kl_in_reward=False", |
| f"data.train_files={WORKDIR}/train.parquet", |
| f"data.val_files={WORKDIR}/val.parquet", |
| f"data.train_batch_size={train_bs}", |
| f"data.max_prompt_length={prompt_len}", |
| f"data.max_response_length={resp_len}", |
| "data.filter_overlong_prompts=False", |
| "data.truncation=right", |
| "data.dataloader_num_workers=0", |
| f"actor_rollout_ref.model.path={model_path}", |
| |
| |
| "actor_rollout_ref.model.trust_remote_code=True", |
| "actor_rollout_ref.model.use_remove_padding=True", |
| "actor_rollout_ref.model.enable_gradient_checkpointing=True", |
| f"actor_rollout_ref.model.lora_rank={lora_rank}", |
| f"actor_rollout_ref.model.lora_alpha={lora_alpha}", |
| |
| |
| |
| |
| f"actor_rollout_ref.model.target_modules={os.environ.get('AUTOSLM_VERL_TARGET_MODULES', 'all-linear').strip()}", |
| "actor_rollout_ref.actor.optim.lr=1e-5", |
| f"actor_rollout_ref.actor.ppo_mini_batch_size={max(8, train_bs // 2)}", |
| "actor_rollout_ref.actor.use_kl_loss=True", |
| "actor_rollout_ref.actor.kl_loss_coef=0.001", |
| "actor_rollout_ref.actor.kl_loss_type=low_var_kl", |
| "actor_rollout_ref.actor.entropy_coeff=0", |
| |
| |
| |
| |
| "actor_rollout_ref.actor.strategy=fsdp2", |
| "actor_rollout_ref.ref.strategy=fsdp2", |
| |
| "actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=4", |
| "actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=8", |
| "actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=8", |
| "actor_rollout_ref.rollout.name=vllm", |
| f"actor_rollout_ref.rollout.n={group_size}", |
| "actor_rollout_ref.rollout.temperature=1.0", |
| f"actor_rollout_ref.rollout.response_length={resp_len}", |
| |
| |
| |
| |
| f"actor_rollout_ref.rollout.max_model_len={prompt_len + resp_len}", |
| "actor_rollout_ref.rollout.gpu_memory_utilization=0.4", |
| "actor_rollout_ref.rollout.enforce_eager=True", |
| "actor_rollout_ref.rollout.load_format=safetensors", |
| "actor_rollout_ref.rollout.layered_summon=True", |
| |
| |
| |
| |
| |
| f"actor_rollout_ref.rollout.tensor_model_parallel_size={int(os.environ.get('AUTOSLM_VERL_ROLLOUT_TP', '1'))}", |
| |
| |
| |
| |
| f"custom_reward_function.path={WORKDIR}/verl_reward.py", |
| "custom_reward_function.name=compute_score", |
| f"reward.custom_reward_function.path={WORKDIR}/verl_reward.py", |
| "reward.custom_reward_function.name=compute_score", |
| "trainer.logger=[console]", |
| "trainer.val_before_train=False", |
| "trainer.nnodes=1", |
| f"trainer.total_training_steps={steps}", |
| "trainer.save_freq=-1", |
| "trainer.test_freq=-1", |
| "trainer.project_name=autoslm_verl", |
| ] |
| if overlap: |
| ov += [ |
| "actor_rollout_ref.hybrid_engine=False", |
| "critic.strategy=fsdp2", |
| |
| |
| |
| |
| |
| "actor_rollout_ref.actor.fsdp_config.model_dtype=bf16", |
| f"trainer.n_gpus_per_node={split.train_gpus}", |
| "rollout.nnodes=1", |
| f"rollout.n_gpus_per_node={split.infer_gpus}", |
| |
| |
| |
| |
| |
| ] |
| if os.environ.get("AUTOSLM_VERL_ROLLOUT_EXECUTOR", "mp").strip().lower() == "ray": |
| ov += [ |
| "+actor_rollout_ref.rollout.engine_kwargs.vllm.distributed_executor_backend=ray", |
| ] |
| else: |
| ov += [f"trainer.n_gpus_per_node={split.train_gpus or 1}"] |
| |
| |
| _extra = os.environ.get("AUTOSLM_VERL_EXTRA_OVERRIDES", "").strip() |
| if _extra: |
| ov += _extra.split() |
| return [RUN_PY] + entry + ov |
|
|
|
|
| def run(): |
| from autoslm.engine import worker as W |
| from autoslm.engine.disaggregated import detect_total_gpus |
| from autoslm.engine.rollout_bench import select_rollout_split |
|
|
| t0 = time.time() |
| _hb("rl_start") |
| spec = _spec() |
| tr = spec.train |
| model_id = spec.model |
| group_size = int(getattr(tr, "group_size", 8) or 8) |
| max_len = int(getattr(tr, "max_length", 2048) or 2048) |
| resp_len = int(getattr(tr, "max_tokens", 1024) or 1024) |
| prompt_len = max(256, max_len - resp_len) |
| steps = int(getattr(tr, "steps", 12) or 12) |
| lora_rank = int(getattr(tr, "lora_rank", 0) or 32) |
| lora_alpha = int(getattr(tr, "lora_alpha", 0) or (2 * lora_rank)) |
| inf = int(getattr(tr, "inference_gpus", 0) or 0) |
| inf = int(os.environ.get("AUTOSLM_INFERENCE_GPUS", inf)) |
| train_bs = 32 |
|
|
| |
| os.environ["AUTOSLM_VERL_OVERLAP"] = "1" if inf > 0 else "0" |
| _hb("verl_install", note="sidecar venv + verl stack (slow cold start)") |
| _install() |
|
|
| _hb("verl_prefetch") |
| W.prefetch_model(model_id) |
| |
| model_path = model_id |
| try: |
| from huggingface_hub import snapshot_download |
|
|
| model_path = snapshot_download(model_id) |
| except Exception as e: |
| print(f"[verl] snapshot_download fallback to id ({e})", flush=True) |
|
|
| total = detect_total_gpus() |
| split = select_rollout_split(total, inf) if inf > 0 else type("S", (), {"train_gpus": total or 1, "infer_gpus": 0})() |
| print(f"[verl] total_gpus={total} inference_gpus={inf} -> train={getattr(split,'train_gpus','?')} infer={getattr(split,'infer_gpus','?')} " |
| f"({'one-step-off OVERLAP' if inf>0 else 'colocate (no overlap)'})", flush=True) |
|
|
| _build_dataset(model_path, n_rows=max(64, train_bs * 4), prompt_tokens=prompt_len) |
| _write_reward() |
|
|
| cmd = _build_cmd(model_path, split, group_size=group_size, prompt_len=prompt_len, |
| resp_len=resp_len, lora_rank=lora_rank, lora_alpha=lora_alpha, |
| steps=steps, train_bs=train_bs) |
| env = dict(os.environ) |
| env["VLLM_USE_V1"] = env.get("VLLM_USE_V1", "1") |
| env["HF_HUB_DISABLE_XET"] = "1" |
| env["HYDRA_FULL_ERROR"] = "1" |
| env["VLLM_ENGINE_ITERATION_TIMEOUT_S"] = env.get("VLLM_ENGINE_ITERATION_TIMEOUT_S", "1800") |
| |
| |
| |
| if total and total > 0: |
| env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in range(total)) |
| |
| |
| |
| |
| |
| _alloc = env.get("PYTORCH_CUDA_ALLOC_CONF", "") |
| _kept = [p for p in _alloc.split(",") if p.strip() and "expandable_segments" not in p] |
| if _kept: |
| env["PYTORCH_CUDA_ALLOC_CONF"] = ",".join(_kept) |
| else: |
| env.pop("PYTORCH_CUDA_ALLOC_CONF", None) |
| env.pop("PYTHONPATH", None) |
| |
| |
| |
| |
| try: |
| import resource |
|
|
| for _lim, _name in ((resource.RLIMIT_NPROC, "NPROC"), (resource.RLIMIT_NOFILE, "NOFILE")): |
| _soft, _hard = resource.getrlimit(_lim) |
| if _hard == resource.RLIM_INFINITY or _soft < _hard: |
| resource.setrlimit(_lim, (_hard, _hard)) |
| print(f"[verl] raised RLIMIT_{_name} {_soft}->{_hard}", flush=True) |
| except Exception as _e: |
| print(f"[verl] rlimit bump skipped: {_e}", flush=True) |
| |
| |
| |
| for _tv in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"): |
| env.setdefault(_tv, "4") |
| |
| |
| |
| |
| |
| env.setdefault("RAYON_NUM_THREADS", "1") |
| env.setdefault("TOKENIZERS_PARALLELISM", "false") |
| |
| |
| env.setdefault("MALLOC_ARENA_MAX", "2") |
| |
| |
| |
| if total and total > 1: |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| env.setdefault("NCCL_P2P_DISABLE", "1") |
| env.setdefault("NCCL_SHM_DISABLE", "0") |
| env.setdefault("NCCL_CUMEM_ENABLE", "0") |
| env.setdefault("NCCL_CUMEM_HOST_ENABLE", "0") |
| |
| |
| |
| |
| env.setdefault("RAY_OVERRIDE_RESOURCES", json.dumps({"CPU": 64})) |
| |
| |
| os.environ.setdefault("AUTOSLM_VERL_FIRST_STEP_TIMEOUT", "2400") |
|
|
| _hb("rl_train_start", setup_seconds=time.time() - t0) |
| log_path = "/tmp/verl_console.txt" |
| print(f"[verl] launching: {' '.join(map(str, cmd))}", flush=True) |
| |
| |
| step_line_re = re.compile(r"\bstep:(\d+)\b") |
| tps_re = re.compile(r"(?:perf/time_per_step|timing_s/step|time_per_step)\s*[:=]\s*([0-9.eE+-]+)") |
| step_times: list[float] = [] |
| seen_steps: set[int] = set() |
| train_t0 = [time.time()] |
| stop = threading.Event() |
|
|
| def _beat(): |
| while not stop.is_set(): |
| _hb("verl_running", steps_seen=len(seen_steps), timed=len(step_times)) |
| stop.wait(60) |
|
|
| th = threading.Thread(target=_beat, daemon=True) |
| th.start() |
|
|
| def _launch_once(): |
| """Run verl once, streaming combined output to log_path. Returns (rc, aborted); appends |
| any timed steps to step_times. A watchdog kills a STALLED run (no first step within |
| FIRST_STEP_TIMEOUT, or no new step within STALL_TIMEOUT) so a hang (seen on the async |
| one_step_off path: stuck at step1 for 60-90 min) is terminated and its console is still |
| uploaded for diagnosis instead of burning GPU forever.""" |
| aborted = False |
| with open(log_path, "w") as lf: |
| proc = subprocess.Popen(cmd, cwd=VERL_DIR, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) |
| first_to = float(os.environ.get("AUTOSLM_VERL_FIRST_STEP_TIMEOUT", "1500")) |
| stall_to = float(os.environ.get("AUTOSLM_VERL_STALL_TIMEOUT", "900")) |
| progress = [time.time(), 0] |
| wd_stop = threading.Event() |
|
|
| def _watchdog(): |
| while not wd_stop.wait(30): |
| n = len(seen_steps) |
| now = time.time() |
| if n > progress[1]: |
| progress[0], progress[1] = now, n |
| budget = first_to if n == 0 else stall_to |
| if now - progress[0] > budget: |
| print(f"[verl] WATCHDOG: no step progress in {int(budget)}s (steps_seen={n}) " |
| f"-> killing verl (hang)", flush=True) |
| _hb("verl_watchdog_kill", steps_seen=n) |
| try: |
| proc.kill() |
| except Exception: |
| pass |
| return |
|
|
| wt = threading.Thread(target=_watchdog, daemon=True) |
| wt.start() |
| for line in proc.stdout: |
| lf.write(line) |
| lf.flush() |
| print(line, end="", flush=True) |
| if "SIGABRT" in line or "Fatal Python error: Aborted" in line: |
| aborted = True |
| sm = step_line_re.search(line) |
| if sm: |
| snum = int(sm.group(1)) |
| if snum not in seen_steps: |
| seen_steps.add(snum) |
| tm = tps_re.search(line) |
| if tm: |
| try: |
| step_times.append(float(tm.group(1))) |
| except ValueError: |
| pass |
| _hb("rl_step", step=snum, timed=len(step_times)) |
| rc = proc.wait() |
| wd_stop.set() |
| return rc, aborted |
|
|
| |
| |
| |
| max_attempts = 3 |
| rc = 1 |
| for attempt in range(max_attempts): |
| step_times.clear() |
| seen_steps.clear() |
| train_t0[0] = time.time() |
| rc, aborted = _launch_once() |
| if rc == 0 or seen_steps: |
| break |
| if aborted and attempt < max_attempts - 1: |
| print(f"[verl] vLLM SIGABRT at startup (attempt {attempt + 1}/{max_attempts}) -> retrying", flush=True) |
| _hb("verl_retry_abort", attempt=attempt + 1) |
| continue |
| break |
| stop.set() |
| train_wall = time.time() - train_t0[0] |
|
|
| |
| |
| |
| useful = step_times[1:] if len(step_times) > 1 else step_times |
| s_per_step = (sum(useful) / len(useful)) if useful else None |
| s_per_step_source = "verl_perf_key" if s_per_step is not None else None |
| if s_per_step is None and len(seen_steps) >= 2: |
| |
| s_per_step = train_wall / len(seen_steps) |
| s_per_step_source = "train_wall_div_steps" |
| wall = time.time() - t0 |
| print(f"[verl] DONE rc={rc} steps_seen={len(seen_steps)} steps_timed={len(step_times)} " |
| f"s/step={s_per_step} ({s_per_step_source})", flush=True) |
| if rc != 0 and not seen_steps: |
| tail = "" |
| root = "" |
| try: |
| with open(log_path) as f: |
| lines = f.readlines() |
| tail = "".join(lines[-60:]) |
| |
| |
| |
| markers = ("EngineCore failed", "EngineCore hit an exception", "Process EngineCore", |
| "(EngineCore", "EngineCore_", "failed to start", "Worker proc", |
| "CUDA error", "out of memory", "OutOfMemory", "No available memory", |
| "free memory", "KV cache", "GPU blocks", "No kernel image", |
| "ImportError", "ModuleNotFoundError", "ABI", "undefined symbol", |
| "does not exist", "not a supported", "Unrecognized", "trust_remote_code", |
| "RuntimeError:", "ValueError:", "AssertionError:", "KeyError:", "Cannot") |
| hits = [i for i, l in enumerate(lines) if any(m in l for m in markers)] |
| |
| hits = [i for i in hits if "Engine core initialization failed" not in lines[i]] |
| if hits: |
| lo = max(0, hits[0] - 4) |
| hi = min(len(lines), hits[0] + 25) |
| root = "".join(lines[lo:hi]) |
| except Exception: |
| pass |
| |
| |
| msg = f"verl run failed (rc={rc})." |
| if root: |
| msg += f"\n--- ROOT CAUSE region ---\n{root[-2500:]}" |
| msg += f"\n--- Last verl output ---\n{tail[-2500:]}" |
| raise RuntimeError(msg) |
|
|
| metrics = { |
| "wall_seconds": (s_per_step * steps) if s_per_step else wall, |
| "verl_s_per_step": s_per_step, |
| "verl_step_times": step_times, |
| "verl_s_per_step_source": s_per_step_source, |
| "verl_steps_seen": sorted(seen_steps), |
| "verl_train_wall": train_wall, |
| "notes": {"steps": steps, "framework": "verl", |
| "mode": "one_step_off_overlap" if inf > 0 else "colocate", |
| "model": model_id, "group_size": group_size, "lora_rank": lora_rank, |
| "inference_gpus": inf, "total_gpus": total}, |
| "reward_history": [1.0] * max(len(step_times), len(seen_steps)), |
| } |
| with open("/tmp/metrics.json", "w") as f: |
| json.dump(metrics, f) |
| print(f"[verl] wrote /tmp/metrics.json: s/step={s_per_step}", flush=True) |
|
|
| |
| |
| |
| |
| |
| |
| try: |
| from autoslm.engine.worker import hf_upload_file |
|
|
| try: |
| hf_upload_file(log_path, "verl_console.txt") |
| except Exception as _e: |
| print(f"[verl] console upload warn: {_e}", flush=True) |
| hf_upload_file("/tmp/metrics.json", "metrics.json", required=True) |
| with open("/tmp/DONE", "w") as f: |
| f.write(str(time.time())) |
| hf_upload_file("/tmp/DONE", "DONE", required=True) |
| _hb("done") |
| print("[verl] uploaded metrics.json + DONE (run finalized)", flush=True) |
| except Exception as _e: |
| print(f"[verl] finalize upload FAILED ({_e}) -> plane may orphan-restart", flush=True) |
|
|
| return metrics |
| _hb("done", verl_s_per_step=s_per_step or 0.0) |
| return metrics |
|
|