| """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 |
|
|
|
|
| def _install_chalk(uv, py): |
| """pip-install our custom chalk kernels (freesolo-chalk: hand-written Triton/CUDA Qwen3.5/3.6 |
| kernels — fused MLP, RoPE, fused embedding, fused LoRA-delta, FP8 base) into ``py``. The kernels |
| are APPLIED to the verl actor model by _patch_verl_chalk() (a verl-file patch that calls |
| apply_chalk_kernel_to_qwen35 in _build_module) — a sitecustomize get_peft_model wrap was tried |
| first but never fired in verl's Ray trainer actor. Gated by AUTOSLM_VERL_CHALK (default on); |
| FLASH_CHALK_SPEC overrides the pip spec (e.g. a local wheel or git ref).""" |
| if os.environ.get("AUTOSLM_VERL_CHALK", "1").strip().lower() not in ("1", "true", "yes"): |
| return |
| spec = os.environ.get("FLASH_CHALK_SPEC", "").strip() or "freesolo-chalk" |
| _hb("verl_install", step="chalk", spec=spec) |
| |
| |
| |
| bsp = ["--break-system-packages"] if os.environ.get("AUTOSLM_VERL_USE_BAKED_STACK", "1").strip().lower() in ("1", "true", "yes") else [] |
| r = _run([uv, "pip", "install", "-p", py, *bsp, spec], check=False, capture=True) |
| ok = subprocess.run([py, "-c", "import chalk; print(chalk.__file__)"], text=True, capture_output=True) |
| print(f"[verl][chalk] install rc={r.returncode}; import chalk -> {'OK' if ok.returncode==0 else 'FAILED: '+ok.stderr[-150:]}", flush=True) |
|
|
|
|
| _REVERSE_SYS = "Reverse the text character-by-character. Put your answer in <reversed_text> tags." |
|
|
|
|
| def _reverse_text_rows(n_rows): |
| """Reverse-text TASK rows (same task as the Prime `reverse-text` verifiers env the tinker side |
| trains on): a random string to reverse, ground_truth = the reversed string. Self-contained.""" |
| import random |
|
|
| rng = random.Random(0) |
| letters = "abcdefghijklmnopqrstuvwxyz" |
| rows = [] |
| for i in range(n_rows): |
| words = ["".join(rng.choice(letters) for _ in range(rng.randint(3, 7))) |
| for _ in range(rng.randint(4, 9))] |
| text = " ".join(words) |
| rows.append({ |
| "data_source": "reverse_text", |
| "prompt": [{"role": "system", "content": _REVERSE_SYS}, |
| {"role": "user", "content": text}], |
| "ability": "reverse", |
| "reward_model": {"style": "rule", "ground_truth": text[::-1]}, |
| "extra_info": {"index": i, "split": "train"}, |
| }) |
| return rows |
|
|
|
|
| def _build_dataset(model_path: str, n_rows: int, prompt_tokens: int, env: str = ""): |
| """GRPO dataset. Default = synthetic throughput rows; env='reverse-text' = the reverse-text task |
| (matched to the tinker reverse-text env). Throughput (gen n*resp + train) dominates s/step.""" |
| os.makedirs(WORKDIR, exist_ok=True) |
| import pandas as pd |
|
|
| if env == "reverse-text": |
| df = pd.DataFrame(_reverse_text_rows(n_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} reverse-text rows -> {WORKDIR}/train.parquet", flush=True) |
| return |
|
|
| |
| |
| |
| 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(env: str = ""): |
| """verl custom_reward_function. Default = trivial length reward; env='reverse-text' = a real |
| reverse-text reward (extract <reversed_text>, score char-level reversal correctness).""" |
| if env == "reverse-text": |
| src = ( |
| "import re\n" |
| "def compute_score(data_source, solution_str, ground_truth, extra_info=None):\n" |
| " s = solution_str or ''\n" |
| " m = re.search(r'<reversed_text>(.*?)</reversed_text>', s, re.DOTALL)\n" |
| " ans = (m.group(1).strip() if m else s.strip())\n" |
| " gt = (ground_truth or '').strip()\n" |
| " if not gt:\n" |
| " return 0.0\n" |
| " correct = sum(1 for a, b in zip(ans, gt) if a == b)\n" |
| " ratio = correct / max(len(gt), len(ans), 1)\n" |
| " fmt = 0.1 if m else 0.0\n" |
| " return min(1.0, 0.9 * ratio + fmt)\n" |
| ) |
| else: |
| 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"] |
| |
| |
| |
| _strategy = os.environ.get("AUTOSLM_VERL_STRATEGY", "fsdp2").strip() or "fsdp2" |
| 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", |
| |
| f"actor_rollout_ref.actor.strategy={_strategy}", |
| f"actor_rollout_ref.ref.strategy={_strategy}", |
| |
| "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", |
| f"critic.strategy={_strategy}", |
| |
| |
| |
| |
| |
| "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}"] |
| |
| |
| |
| |
| _chalk_on = os.environ.get("AUTOSLM_VERL_CHALK", "1").strip().lower() in ("1", "true", "yes") |
| if os.environ.get("AUTOSLM_VERL_USE_LIGER", "1").strip().lower() in ("1", "true", "yes") and not _chalk_on: |
| |
| |
| |
| |
| ov.append("actor_rollout_ref.model.use_liger=True") |
| |
| |
| |
| if os.environ.get("AUTOSLM_VERL_OPTIM_8BIT", "").strip().lower() in ("1", "true", "yes"): |
| ov += [ |
| "actor_rollout_ref.actor.optim.optimizer_impl=bitsandbytes.optim", |
| "actor_rollout_ref.actor.optim.optimizer=AdamW8bit", |
| ] |
| if os.environ.get("AUTOSLM_VERL_QLORA", "").strip().lower() in ("1", "true", "yes"): |
| |
| |
| |
| |
| |
| |
| if os.environ.get("AUTOSLM_VERL_QLORA_BNB_ROLLOUT", "").strip().lower() in ("1", "true", "yes"): |
| ov += [ |
| "actor_rollout_ref.rollout.load_format=bitsandbytes", |
| "actor_rollout_ref.rollout.quantization=bitsandbytes", |
| ] |
| |
| |
| |
| |
| |
| _extra = os.environ.get("AUTOSLM_VERL_EXTRA_OVERRIDES", "").strip() |
| if _extra: |
| ov += _extra.split() |
| return [RUN_PY] + entry + ov |
|
|
|
|
| def _patch_vllm_qwen35_moe_sync(): |
| """Make vLLM's qwen3_5 FUSED-EXPERT runtime weight load tolerant during verl one_step_off sync. |
| |
| Qwen3.6-35B-A3B is MoE + `*ForConditionalGeneration` (the LM nests under |
| ``language_model.model.``). verl's one_step_off checkpoint engine streams the updated policy to |
| the rollout vLLM via ``load_weights``; for the fused experts vLLM's |
| ``Qwen3_5Model.load_fused_expert_weights`` does a bare ``params_dict[name]`` — and when the name |
| doesn't resolve in a given (TP/EP) rank's ``params_dict`` it raises ``KeyError |
| 'layers.0.mlp.experts.w13_weight'``, which kills the rollout EngineCore at the FIRST weight |
| transfer (step 0) and hangs/fails the run. The non-fused branch right below it already SKIPS a |
| name that isn't in ``params_dict`` (it's tolerant); the fused branch isn't. This patches the |
| installed qwen3_5.py to make the fused branch equally tolerant: try common prefix variants, and |
| if still absent SKIP (return False) instead of a fatal KeyError. Idempotent + anchor-guarded |
| (no-op on vllm version drift). Set AUTOSLM_VERL_MOE_DEBUG=1 to log the actual param keys.""" |
| try: |
| out = subprocess.run( |
| [RUN_PY, "-c", "import vllm.model_executor.models.qwen3_5 as m; print(m.__file__)"], |
| text=True, capture_output=True, timeout=120, |
| ) |
| path = (out.stdout.strip().splitlines() or [""])[-1].strip() |
| if not path or not os.path.exists(path): |
| print(f"[verl] MoE-sync patch: qwen3_5.py not found ({out.stderr[-200:]})", flush=True) |
| return |
| src = open(path).read() |
| if "AUTOSLM-MOE-PATCH" in src: |
| print("[verl] MoE-sync patch: already applied", flush=True) |
| return |
| anchor = " num_experts: int,\n ) -> bool:\n param = params_dict[name]\n" |
| if anchor not in src: |
| print("[verl] MoE-sync patch: anchor not found (vllm drift) — skipping", flush=True) |
| return |
| repl = ( |
| " num_experts: int,\n ) -> bool:\n" |
| " # AUTOSLM-MOE-PATCH: tolerate prefix mismatch / absent fused-expert param during\n" |
| " # verl one_step_off runtime weight sync (Qwen *ForConditionalGeneration nests the\n" |
| " # LM under language_model.model.; a TP/EP rank may not own a given fused param).\n" |
| " # Resolve prefix variants; if still absent SKIP like the non-fused branch instead\n" |
| " # of a fatal KeyError that kills the rollout EngineCore at the first weight sync.\n" |
| " if name not in params_dict:\n" |
| " # Candidate names: the fused-expert param often lives under .base_layer.\n" |
| " # (PEFT LoRA wraps the FusedMoE -> vLLM registers experts.base_layer.w13_weight),\n" |
| " # and Qwen *ForConditionalGeneration nests the LM under language_model.model.\n" |
| " _cands = [name]\n" |
| " for _suf in ('w13_weight', 'w2_weight'):\n" |
| " if 'experts.' + _suf in name:\n" |
| " _cands.append(name.replace('experts.' + _suf, 'experts.base_layer.' + _suf))\n" |
| " _alt = None\n" |
| " for _c in _cands:\n" |
| " for _p in ('', 'language_model.model.', 'language_model.', 'model.'):\n" |
| " if _p + _c in params_dict:\n" |
| " _alt = _p + _c; break\n" |
| " if _p and _c.startswith(_p) and _c[len(_p):] in params_dict:\n" |
| " _alt = _c[len(_p):]; break\n" |
| " if _alt is not None:\n" |
| " break\n" |
| " if _alt is None:\n" |
| " import os as _os\n" |
| " if _os.environ.get('AUTOSLM_VERL_MOE_DEBUG'):\n" |
| " _ek = [k for k in params_dict if 'expert' in k.lower()][:6]\n" |
| " _mk = [k for k in params_dict if '.mlp.' in k][:6]\n" |
| " print('[autoslm-moe-patch] skip ' + repr(name) + '; expert keys=' + repr(_ek) + '; mlp keys=' + repr(_mk), flush=True)\n" |
| " return False\n" |
| " name = _alt\n" |
| " param = params_dict[name]\n" |
| ) |
| open(path, "w").write(src.replace(anchor, repl, 1)) |
| |
| chk = subprocess.run([RUN_PY, "-c", f"import ast; ast.parse(open({path!r}).read())"], |
| text=True, capture_output=True, timeout=60) |
| if chk.returncode != 0: |
| open(path, "w").write(src) |
| print(f"[verl] MoE-sync patch: reverted (syntax) {chk.stderr[-200:]}", flush=True) |
| return |
| print(f"[verl] MoE-sync patch: applied to {path}", flush=True) |
| except Exception as e: |
| print(f"[verl] MoE-sync patch skipped: {e}", flush=True) |
|
|
|
|
| def _patch_verl_chalk(): |
| """Apply our chalk kernels (+ Liger) on the verl actor by patching verl's FSDP _build_module to |
| call ``apply_chalk_kernel_to_qwen35(module, liger="auto")`` right after the model loads (where |
| verl applies Liger). This is RELIABLE across Ray trainer actors — the earlier sitecustomize/ |
| get_peft_model wrap never fired in the actor (console showed no [chalk] lines, use_liger:False). |
| |
| chalk's kernels are CLASS-LEVEL installers (fused MLP/RoPE/embedding patch the transformers |
| Qwen3.5 classes; fused LoRA-delta patches the PEFT LoRA Linear class), so applying here — BEFORE |
| verl's later get_peft_model in _build_lora_module — still installs fused_lora_delta for the LoRA |
| layers built afterward. liger="auto" applies Liger too (RoPE forced off so chalk's RoPE installs); |
| fused_linear_cross_entropy=False matches verl's requirement. Gated by AUTOSLM_VERL_CHALK (default |
| on), idempotent, compile-checked + reverted on syntax error. No-op off-GPU / non-Qwen3.5.""" |
| if os.environ.get("AUTOSLM_VERL_CHALK", "1").strip().lower() not in ("1", "true", "yes"): |
| return |
| try: |
| out = subprocess.run( |
| [RUN_PY, "-c", "import verl.workers.engine.fsdp.transformer_impl as m; print(m.__file__)"], |
| text=True, capture_output=True, timeout=120, |
| ) |
| path = (out.stdout.strip().splitlines() or [""])[-1].strip() |
| if not path or not os.path.exists(path): |
| print(f"[verl] chalk patch: transformer_impl not found ({out.stderr[-200:]})", flush=True) |
| return |
| src = open(path).read() |
| if "AUTOSLM-CHALK" in src: |
| print("[verl] chalk patch: already applied", flush=True) |
| return |
| |
| anchor = " fused_kernel_options = self.model_config.fused_kernel_options\n" |
| if anchor not in src: |
| print("[verl] chalk patch: anchor not found (verl drift) — skipping", flush=True) |
| return |
| inject = ( |
| " try: # AUTOSLM-CHALK\n" |
| " import os as _os\n" |
| " if _os.environ.get('AUTOSLM_VERL_CHALK', '1').strip().lower() in ('1', 'true', 'yes'):\n" |
| " from chalk.transformers import apply_chalk_kernel_to_qwen35\n" |
| " _rep = apply_chalk_kernel_to_qwen35(module, liger='auto', fused_linear_cross_entropy=False)\n" |
| " print('[chalk] applied to verl actor: ' + repr(_rep), flush=True)\n" |
| " except Exception as _e:\n" |
| " print('[chalk] apply skipped: ' + repr(_e), flush=True)\n" |
| ) |
| open(path, "w").write(src.replace(anchor, inject + anchor, 1)) |
| chk = subprocess.run([RUN_PY, "-c", f"import ast; ast.parse(open({path!r}).read())"], |
| text=True, capture_output=True, timeout=60) |
| if chk.returncode != 0: |
| open(path, "w").write(src) |
| print(f"[verl] chalk patch: reverted (syntax) {chk.stderr[-200:]}", flush=True) |
| return |
| print(f"[verl] chalk patch: applied apply_chalk_kernel_to_qwen35 to {path}", flush=True) |
| except Exception as e: |
| print(f"[verl] chalk patch skipped: {e}", flush=True) |
|
|
|
|
| def _git_restore_verl(path: str): |
| """Restore a verl source file to pristine git state. RunPod REUSES workers, so a verl checkout can |
| carry a stale patch from a prior run; restoring first guarantees every run patches a clean base |
| (otherwise idempotency markers make stale edits stick and new fixes never apply).""" |
| try: |
| root = subprocess.run(["git", "-C", os.path.dirname(path), "rev-parse", "--show-toplevel"], |
| text=True, capture_output=True, timeout=30) |
| repo = (root.stdout.strip().splitlines() or [""])[-1].strip() |
| if repo and os.path.isdir(repo): |
| r = subprocess.run(["git", "-C", repo, "checkout", "--", path], capture_output=True, text=True, timeout=30) |
| print(f"[verl] git-restored {os.path.basename(path)} (rc={r.returncode})", flush=True) |
| except Exception as e: |
| print(f"[verl] git-restore skipped for {path}: {e}", flush=True) |
|
|
|
|
| def _patch_verl_qlora(): |
| """Load the frozen base in 4-bit NF4 (QLoRA) on the verl trainer — the COST lever: a 4-bit base |
| (~1/4 the VRAM) lets a big model train + serve on a SMALLER/cheaper GPU (e.g. 35B ~70GB bf16 -> |
| ~18GB). verl has no native 4-bit support, so patch its FSDP from_pretrained to pass a |
| BitsAndBytesConfig and skip verl's `module.to(torch_dtype)` (bitsandbytes forbids casting a 4-bit |
| model). REQUIRES strategy=fsdp (FSDP1/FlatParameter): fsdp2's fully_shard can't wrap Params4bit |
| ("only Tensors of floating point dtype can require gradients"). Gated by AUTOSLM_VERL_QLORA, |
| idempotent, compile-checked + reverted on syntax error.""" |
| try: |
| out = subprocess.run( |
| [RUN_PY, "-c", "import verl.workers.engine.fsdp.transformer_impl as m; print(m.__file__)"], |
| text=True, capture_output=True, timeout=120, |
| ) |
| path = (out.stdout.strip().splitlines() or [""])[-1].strip() |
| if not path or not os.path.exists(path): |
| print(f"[verl] QLoRA patch: transformer_impl not found ({out.stderr[-200:]})", flush=True) |
| return |
| |
| |
| |
| _git_restore_verl(path) |
| src = open(path).read() |
| |
| |
| |
| |
| if "AUTOSLM-QLORA-DEQUANT" in src: |
| print("[verl] QLoRA patch: already applied (incl. dequant)", flush=True) |
| return |
| anchor = ( |
| " config=self.model_config.hf_config,\n" |
| " trust_remote_code=self.model_config.trust_remote_code,\n" |
| " )\n" |
| ) |
| |
| |
| if anchor not in src: |
| print("[verl] QLoRA patch: from_pretrained anchor already consumed (or drift) — skipping that edit", flush=True) |
| else: |
| repl = ( |
| " config=self.model_config.hf_config,\n" |
| " quantization_config=__import__('transformers').BitsAndBytesConfig( # AUTOSLM-QLORA\n" |
| " load_in_4bit=True, bnb_4bit_quant_type='nf4',\n" |
| " bnb_4bit_compute_dtype=__import__('torch').bfloat16,\n" |
| " bnb_4bit_use_double_quant=True),\n" |
| " trust_remote_code=self.model_config.trust_remote_code,\n" |
| " )\n" |
| ) |
| src = src.replace(anchor, repl, 1) |
| cast_anchor = " # some parameters may not in torch_dtype\n module.to(torch_dtype)\n" |
| if cast_anchor in src: |
| src = src.replace( |
| cast_anchor, |
| " # some parameters may not in torch_dtype\n" |
| " if not (getattr(module, 'is_loaded_in_4bit', False) or getattr(module, 'is_quantized', False)): # AUTOSLM-QLORA\n" |
| " module.to(torch_dtype)\n", |
| 1, |
| ) |
| else: |
| print("[verl] QLoRA patch: .to(dtype) cast anchor not found (may still crash)", flush=True) |
| |
| |
| |
| |
| fsdp1_anchor = " module = FSDP(\n module,\n param_init_fn=init_fn,\n" |
| if fsdp1_anchor in src: |
| src = src.replace( |
| fsdp1_anchor, |
| " import torch as _t_ql # AUTOSLM-QLORA: exclude 4-bit base from FSDP flatten\n" |
| " _ql_ignored = [_m for _m in module.modules()\n" |
| " if any(getattr(_p, 'dtype', None) == _t_ql.uint8 for _p in _m.parameters(recurse=False))]\n" |
| " module = FSDP(\n" |
| " module,\n" |
| " ignored_modules=(_ql_ignored or None),\n" |
| " param_init_fn=init_fn,\n", |
| 1, |
| ) |
| else: |
| print("[verl] QLoRA patch: FSDP1 anchor not found — ignored_modules not applied", flush=True) |
| |
| |
| |
| |
| |
| |
| |
| gen_anchor = " per_tensor_param = (\n" |
| if gen_anchor in src and "AUTOSLM-QLORA-DEQUANT" not in src: |
| src = src.replace( |
| gen_anchor, |
| " import bitsandbytes as _bnb_ql, torch as _t_ql2 # AUTOSLM-QLORA-DEQUANT\n" |
| " _ql_qs = {}\n" |
| " for _qn, _qm in (getattr(self.module, '_fsdp_wrapped_module', self.module)).named_modules():\n" |
| " _qw = getattr(_qm, 'weight', None)\n" |
| " if _qw is not None and getattr(_qw, 'quant_state', None) is not None:\n" |
| " _ql_qs[_qn.replace('._fsdp_wrapped_module', '').replace('.base_layer', '')] = _qw\n" |
| " if _ql_qs: # drop bnb quant_state component keys (state_dict serializes them separately);\n" |
| " # the rollout receives the dequantized bf16 .weight, not this metadata.\n" |
| " params = {_pk: _pv for _pk, _pv in params.items()\n" |
| " if not any(_s in _pk for _s in ('.absmax', '.quant_map', '.quant_state', '.nested_', 'bitsandbytes__'))}\n" |
| " def _ql_deq(_name, _p):\n" |
| " if _ql_qs and getattr(_p, 'dtype', None) == _t_ql2.uint8:\n" |
| " _base = _name[:-7] if _name.endswith('.weight') else _name\n" |
| " _base2 = _base[:-len('.base_layer')] if _base.endswith('.base_layer') else _base\n" |
| " for _cand in (_base, _base2):\n" |
| " _tail = _cand.split('.')[-3:]\n" |
| " for _k, _w in _ql_qs.items():\n" |
| " if _k.endswith(_cand) or _cand.endswith(_k) or _k.split('.')[-3:] == _tail:\n" |
| " return _bnb_ql.functional.dequantize_4bit(_w.data, _w.quant_state).to(_t_ql2.bfloat16)\n" |
| " raise RuntimeError('AUTOSLM-QLORA: no quant_state match for 4-bit param ' + repr(_name) + '; sample modules=' + repr(list(_ql_qs)[:3]))\n" |
| " return _p\n" |
| " per_tensor_param = (\n", |
| 1, |
| ) |
| |
| src = src.replace( |
| " if isinstance(param, DTensor)\n" |
| " else param,\n", |
| " if isinstance(param, DTensor)\n" |
| " else _ql_deq(name, param),\n", |
| 1, |
| ) |
| print("[verl] QLoRA patch: module-level dequant map applied", flush=True) |
| else: |
| print("[verl] QLoRA patch: per_tensor generator anchor not found / already patched", flush=True) |
| open(path, "w").write(src) |
| chk = subprocess.run([RUN_PY, "-c", f"import ast; ast.parse(open({path!r}).read())"], |
| text=True, capture_output=True, timeout=60) |
| if chk.returncode != 0: |
| open(path, "w").write(src) |
| print(f"[verl] QLoRA patch: reverted (syntax) {chk.stderr[-200:]}", flush=True) |
| return |
| print(f"[verl] QLoRA patch: applied 4-bit NF4 base load + FSDP1 ignored_modules to {path}", flush=True) |
| |
| |
| rs = subprocess.run( |
| [RUN_PY, "-c", "import verl.workers.rollout.vllm_rollout.vllm_async_server as m; print(m.__file__)"], |
| text=True, capture_output=True, timeout=120, |
| ) |
| rpath = (rs.stdout.strip().splitlines() or [""])[-1].strip() |
| if rpath and os.path.exists(rpath): |
| rsrc = open(rpath).read() |
| qanchor = '_SUPPORTED_QUANTIZATION = ["fp8", "torchao", "ascend"]' |
| if "bitsandbytes" not in rsrc and qanchor in rsrc: |
| rsrc = rsrc.replace(qanchor, '_SUPPORTED_QUANTIZATION = ["fp8", "torchao", "ascend", "bitsandbytes"]', 1) |
| open(rpath, "w").write(rsrc) |
| print("[verl] QLoRA patch: allowed bitsandbytes rollout quantization", flush=True) |
| except Exception as e: |
| print(f"[verl] QLoRA patch skipped: {e}", flush=True) |
|
|
|
|
| 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() |
| |
| |
| |
| if inf > 0: |
| _patch_vllm_qwen35_moe_sync() |
| |
| |
| _patch_verl_chalk() |
| |
| |
| if os.environ.get("AUTOSLM_VERL_QLORA", "").strip().lower() in ("1", "true", "yes"): |
| _patch_verl_qlora() |
|
|
| _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) |
|
|
| bench_env = os.environ.get("AUTOSLM_VERL_ENV", "").strip().lower() |
| _build_dataset(model_path, n_rows=max(64, train_bs * 4), prompt_tokens=prompt_len, env=bench_env) |
| _write_reward(env=bench_env) |
|
|
| 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 |
|
|