Compare commits

...
Author SHA1 Message Date
6bfbd64aef chore(deps): bump verifiers + research-environments to latest main (#2976)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bump both submodules to their current upstream main:
- verifiers:              50883f16 -> a497ee52
- research-environments:  404f0fa8 -> 3e3b5ac3

Reconcile pyproject/uv.lock with upstream changes:
- research-environments moved the SWE tasksets under environments/swe/,
  so repath r2e-gym-v1, scaleswe-v1, swebench-pro-v1, swebench-verified-v1
  and swelego-v1 to environments/swe/<name>.
- research-environments removed the v0 general_agent and rlm_search envs
  (#646), so drop general-agent and rlm-search from the `envs` extra and
  [tool.uv.sources]. general-agent-v1 is unaffected.

verifiers is consumed only via the verifiers.v1 namespace; the removed
verifiers.rl / verifiers-rl code and the RolloutContext->ModelContext
rename do not touch prime-rl. Verified `uv sync --extra envs` resolves,
all 64 env dists install, the moved SWE envs import, and prime-rl's
verifiers.v1 imports (incl. EnvConfig(vf.EnvServerConfig)) still work.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 14:39:52 -07:00
Sebastian MüllerandGitHub b453f40d8c fix(orchestrator): train shared sampled nodes exactly once across branches (#2975)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): train shared sampled nodes exactly once across branches

trace_to_samples built one sample per branch using branch.sampled_mask
directly, so a sampled node lying on N branches (a mid-trajectory fork)
was mask-True in N samples and received N x the gradient weight. Grant
each sampled node its mask only in the first branch containing it; later
branches carry its tokens as context (mask False). No behavior change
for traces whose branches share only input nodes.

* fix(orchestrator): keep echo branch/sample zip aligned under fork dedup

Extract the dedup'd branch selection into iter_trainable_branches and use
it in both trace_to_samples and EchoAlgorithm._weight_observations. When
a later branch's only sampled tokens are on an already-trained shared
node, it yields no sample; echo's old any(branch.sampled_mask) filter
would still count it, shifting the zip with rollout.samples on forked
traces.
2026-07-08 19:11:54 +02:00
samsjaandGitHub 1b028ca1d1 bump depsj (#2967)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-07 09:10:48 -07:00
samsjaandGitHub e96bbae2dd feat: derive inference node counts (#2959)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-06 10:03:29 -07:00
samsjaandGitHub df2acf4874 bump vf (#2956)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-03 20:31:12 -07:00
samsjaandGitHub 5ff9abd8b5 bump re (#2955)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-03 20:23:40 -07:00
5448f5a722 feat: opt-in fp32 MoE routing (trainer gates + inference router logits) (#2952)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(trainer): fp32 MoE router gates via model.moe_router_dtype

Add model.moe_router_dtype = "float32" to run MoE router gates in fp32,
matching checkpoints trained with fp32 routing (e.g. GLM-5.x via Megatron's
--moe-router-dtype fp32):

- router gate weights are cast to fp32 and exempted from the FSDP bf16
  parameter cast via a nested fully_shard unit with an fp32 mp policy
  (gradients also reduce in fp32)
- TokenChoiceTopKRouter upcasts the gate GEMM input to fp32, so routing
  logits are fp32 end-to-end in forward and backward (NemotronHRouter
  already computes in fp32; it only needed the weight exemption)
- router FSDP units join the manual EP prefetch schedule

Default "bfloat16" preserves current behavior exactly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(inference): fp32 MoE router logits for DeepSeek-family models

Add inference.enable_fp32_router_logits (default off): sets
out_dtype=float32 on vLLM's DeepseekV2MoE gate via a monkey patch, so the
bf16xbf16 gate GEMM writes its fp32 accumulator out unrounded instead of
truncating router logits to bf16 before expert scoring (GateLinear's
cuBLAS tier on SM90+). Covers GLM-5.x (glm_moe_dsa), which was trained
with fp32 routing; pairs with trainer.model.moe_router_dtype="float32".

Unlike upstream's full fp32 gate (vllm-project/vllm#47410, not in the
pinned release), the gate weight stays bf16, so the LoRA Triton kernel
dtype assert and the bf16 weight-broadcast path are unaffected. Follows
the fp32_lm_head pattern: flag flows through additional_config and the
patch self-gates at model construction. No-op when something else (e.g.
the ROCm AITER branch) already set an out_dtype.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: default fp32 MoE routing on (trainer + inference)

Flip model.moe_router_dtype to "float32" and
inference.enable_fp32_router_logits to true by default. Routing logits
are no longer rounded to bf16 anywhere: custom-impl MoE trainers run
fp32 gate weights/GEMM, and DeepSeek-family vLLM models emit fp32
router logits. apply_fp32_moe_router is now a silent no-op for non-MoE
and HF-impl models (previously raised), since the default makes absent
custom MoE routers the common case.

Set moe_router_dtype = "bfloat16" / enable_fp32_router_logits = false
to restore the previous numerics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: fares <fares@primeintellect.ai>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 20:16:24 -07:00
minh hoangandGitHub 8a977ecc9c chore: bump renderers for Laguna-XS-2.1 support (#2950)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Pulls in renderers#97 (laguna-xs-2.1 renderer variant: XS-2.1's template
drops the baked-in default system message) and renderers#94 (multimodal
payload through build_training_sample). No renderers dependency changes,
so uv.lock is untouched.
2026-07-03 12:48:17 -07:00
1ab29c0587 fix(deps): refresh flash-linear-attention lock to unbreak GDN training on Hopper (#2939)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
At the locked rev (bd67d11, June 22) fla's tilelang chunk_bwd_dqkwg fails to
JIT for sm_90a (tvm InternalError: Get different layout for b_dq), and the
Triton fallback is guard-blocked on Hopper (wrong dg/db/dk, fla#640) — so any
GDN model (Qwen3.5-MoE, Qwen3-Next) crashes at the first backward on H100/H200.
Upstream fixed the kernel in fla#975 (June 29). fla is an unpinned git dep, so
this is a lock-only refresh: bd67d11 -> a954753.

Co-authored-by: fares <fares@primeintellect.ai>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 12:34:13 -07:00
5e6b641574 fix(deps): bump torchtitan to 23e4dfc to fix EP grad-clip crash with empty ep_grads (#2911)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bumps torchtitan one commit forward (a1fdd7e -> 23e4dfc) to pull in
pytorch/torchtitan#1541, which guards _clip_grad_norm_with_ep against
calling .full_tensor() on a plain Tensor when ep_grads is empty.

This crash surfaces when EP is enabled but no trainable parameter is
EP-sharded — e.g. LoRA targeting only non-expert modules, or PP+EP
setups where some PP ranks own no MoE layers — causing
get_total_norm([]) to return tensor(0.) (a non-DTensor) and the
subsequent .full_tensor() to raise AttributeError at step 0.

The diff between the two torchtitan commits is exactly this one fix
(torchtitan/distributed/utils.py, +6/-1); all other prime-rl imports
from torchtitan (ExpertParallel, expert_parallel, TOKEN_GROUP_ALIGN_SIZE_M,
generate_permute_indices) are unchanged.

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-03 12:28:37 -07:00
16f5c7222b feat: make step numbers 1-indexed (policy versions stay 0-indexed) (#2896)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: 1-index step counters (policy versions stay 0-indexed)

The first trainer/orchestrator step is now step 1 (was step 0). Policy
versions remain 0-indexed, with v0 the base model. Training step x consumes
batch x and produces policy version x; orchestrator step x samples that batch
from policy v(x-1).

Checkpoints/broadcasts now follow a completed-step convention: the trainer
writes the broadcast + checkpoint at the END of each step's iteration (model
= the version just produced), the loop breaks on step == max_steps, and a
checkpoint step_S means "step S finished". Resuming from step_S continues at
step S+1 (orchestrator, trainer, and per-run progress all advance one step on
load). broadcasts/step_S holds policy vS, so the watcher derives the policy
version directly from the directory label; the broadcast label is
mm.progress[idx].step - 1 because pack() has already advanced progress.

This is a pure relabeling: the number of steps, LR schedule, data, and
off-policy/async-barrier behavior are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: drop CHANGELOG entry for 1-indexed steps (not a config-field change)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: align multi-run checkpoint step label with 1-indexed convention

MultiCheckpointManager.save derived its step from mm.progress[idx].step, but
pack() has already advanced that to the next step by the end-of-loop save
point — the same off-by-one the broadcast paths needed. It mislabeled the ckpt
dir step_{S+1} (vs the orchestrator's step_S), looked for the nonexistent
broadcasts/step_{S+1} when copying weights into the ckpt, and gated _should_save
on the wrong interval boundary. Subtract 1 to use the step just finished.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: fix misleading checkpoint comment in RL trainer loop

The "skip it here / written after the loop" note applied only to the single-run
branch; move it onto that branch and clarify the multi-run branch has no
after-loop final save.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: trim redundant async-pipeline sentence in algorithms.md

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: keep orchestrator resume step coordinated under ckpt.skip_progress

The resume increment ran on whatever progress.step held after load, but with
ckpt.skip_progress the orchestrator's CheckpointManager doesn't restore the
counter, so `+= 1` bumped the default (→ 2) while policy.version came from
resume_step — desyncing rollouts/checkpoints/dispatch-gate from the trainer and
mm.progress (both at resume_step + 1). Derive the step from resume_step so
skip_progress only resets the totals and the step stays coordinated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 10:06:58 -07:00
5c0a6dbdba chore(ci): drop uv extras that aren't required from CPU unit tests to fix disk exhaustion (#2940)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(ci): drop --all-extras from CPU unit tests to fix disk exhaustion

The CPU unit-test job ran `uv sync --all-extras --locked`, pulling the
entire dependency universe (envs, flash-attn-3, disagg, quack, gpt-oss,
modelexpress) just to run `pytest tests/unit -m "not gpu"`. That ~2-3GB
of GPU kernels and env deps (spacy, rdkit, chromadb, opencv, onnxruntime,
...) overflows the runner's root disk — the last run died extracting
triton with "No space left on device (os error 28)".

No `tests/unit` test imports any of those extras: they only use base deps
(torch, transformers, vllm, verifiers.v1) plus dev (pytest). The one test
touching flash_attn skips gracefully when it's absent. Install base + dev
only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* clean up comment

* fix(ci): install flash-attn extra for CPU unit tests

Dropping --all-extras entirely broke test collection: `ring_flash_attn`
(a base dep) hard-imports `flash_attn` at module load, and `flash_attn`
is provided only by the flash-attn extra. 12 model/train tests failed to
collect with `ModuleNotFoundError: No module named 'flash_attn'`.

Add back just the flash-attn extra (a prebuilt wheel on x86_64, no build).
The disk fix holds — we still skip envs/flash-attn-3/disagg/quack/etc.,
the ~2-3GB no unit test imports.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(ci): add envs extra for CPU unit tests config loading

test_load_configs loads every config TOML; configs referencing a v1
taskset make verifiers.v1.loaders import the taskset package by name at
runtime (scaleswe_v1, math500_v1, aime24_v1, ...), which ships via the
envs extra. Static import analysis missed this, so the prior commit's
base+flash-attn install failed 15 config-loading tests.

The run proved the disk fix and the extras audit: 454 tests passed with
only flash-attn installed, and the sole failures were envs tasksets. So
install flash-attn + envs and skip the GPU-only extras (flash-attn-3,
disagg, quack, gpt-oss, modelexpress, flash-attn-cute) no unit test uses.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* clean up comment

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 23:25:39 -07:00
dbe95b799a feat: optional per-node uv sync for multi-node RL (#2926)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: optional per-node uv sync for multi-node RL

Add a SlurmConfig.per_node_venv_sync flag (default False). When enabled,
the multi-node RL sbatch runs uv sync on every node via srun (one task per
node, blocking) instead of only the batch node.

This is needed when the venv is node-local (e.g. UV_PROJECT_ENVIRONMENT on
/tmp): a single batch-node sync would leave the other nodes without a venv.
The srun task re-sources .env so uv sees the node-local UV_PROJECT_ENVIRONMENT
/ UV_CACHE_DIR even if SLURM env propagation is disabled. With set -e, a failed
sync on any node aborts the job. Default keeps the original head-only behavior
for shared (NFS) venvs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: rename per_node_venv_sync to shared_fs, fix .env sourcing, extend to all multi-node templates

- Rename SlurmConfig.per_node_venv_sync (default False) to SlurmConfig.shared_fs
  (default True) with inverted logic, as suggested in PR review
- Fix .env sourcing in srun command to not fail when .env is absent
  (|| true guard), matching the rest of the script
- Fix comment: re-sourcing .env is needed because unexported vars don't cross
  srun even with normal SLURM env propagation, not because propagation is disabled
- Extend shared_fs to multi_node_sft.sbatch.j2 and inference.sbatch.j2
  since the flag lives in shared.py config

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 18:30:46 -07:00
07e6bec87a feat: log time/wait_for_policy for dispatch gate stalls (#2938)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: log time/wait_for_policy for dispatch gate stalls

The dispatch gate (`dispatch_allowed`) pauses the orchestrator when it
would run more than TARGET_LAG batches ahead of the trainer's policy
version, but that pause was invisible in metrics — the only signal was
two info log lines. When the trainer is the bottleneck this stall is
exactly what we want to quantify.

Accumulate the wall-clock the gate spends closed across pause/resume
cycles and log it as `time/wait_for_policy` alongside the other
orchestrator `time/*` metrics, resetting each shipped batch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: drop redundant comment on wait_for_policy state

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: add time/wait_for_policy to the W&B overview performance section

Show the orchestrator's dispatch-gate wait next to time/wait_for_batch
in the curated overview view.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 12:49:21 -07:00
9fede0ac78 feat: auto-create curated W&B overview view per project (#2933)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: auto-create curated W&B "overview" saved view per project

Creates an idempotent "overview" saved view (train / eval / stability /
performance sections) on the first run into a W&B project, so a new project
gets a usable overview without hand-picking panels from the thousands of
logged metrics.

- New src/prime_rl/utils/monitor/workspace.py builds the view via wandb-workspaces
- WandbMonitor creates it after wandb.init (run's primary process, online only,
  best-effort so a failure never breaks training; skips if it already exists)
- Per-env train/<env> and eval/<env> sections built from the orchestrator's
  resolved env names; single train env collapses to train/<env>, multiple add
  train/agg on top
- inference/* panels use the wall-clock x-axis (they are logged against
  _timestamp); every other panel uses `step`
- Config: WandbConfig.create_overview (default True; --wandb.no-create-overview)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: add time/wait_for_batch to overview performance section

* feat: always create overview when wandb enabled (drop create_overview config)

* chore: rename overview env-name params to train_env_names/eval_env_names

* chore: make overview metric/layout constants public

* feat: version overview on env-set change; make helpers public, inline x_for

* refactor: fold overview view code into monitor/wandb.py

* docs: note deliberate metric volume + auto-created W&B overview view

* feat: unify train/eval overview metrics (reward vs avg@), all subset only

* chore: drop perf throughput/throughput_per_gpu/peak_memory from overview

* fix: isolate per-view load in overview reuse loop so one bad view doesn't abort

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 12:39:30 -07:00
d16981b533 fix: advance progress.step before gating so dispatch lead is correct (#2937)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
`update_dispatch_gate` computed `lead = (progress.step + 1) - policy.version`
at both call sites, but `progress.step` meant different things at each: at
ship time it was still the just-shipped step (so +1 = the batch being
collected, correct), but at `on_new_version` a prior ship had already advanced
it to the collecting batch, so the +1 double-counted and overstated the lead by
one. That kept the dispatcher paused one policy version too long and could
self-sustain into a stall (a paused dispatcher can't ship the batch the trainer
needs to produce the next version).

Advance `progress.step` immediately after shipping so it always names the batch
being collected, then gate on a single `progress.step - policy.version`. The
lead is now correct at both sites and never overstated, so the gate can't
falsely stall.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 12:36:10 -07:00
b2b4f3f711 feat: bump vLLM 0.23.0 -> 0.24.0 (#2921)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: bump vLLM 0.23.0 -> 0.24.0

Base runtime bump. Changes:
- pyproject.toml: `vllm>=0.24.0` + the x86_64/aarch64 wheel URLs to v0.24.0
  (cu129 cp38-abi3); uv.lock regenerated (vllm 0.24.0 pulls humming-kernels
  0.1.6, prometheus-fastapi-instrumentator 8.0.2, starlette 1.3.1; drops gguf).
- weight_transfer.py: 0.24 turned `FusedMoE` into a factory returning a
  `MoERunner` and split its state -- the expert map now lives on
  `MoERunner.routed_experts` (RoutedExperts) and EPLB state on
  `MoERunner.router`. `isinstance(module, FusedMoE)` would raise TypeError.
  Rewrote `build_expert_map`/`_build_expert_source_indices` to match
  `MoERunner` and read both submodules. Keying by the MoERunner name still
  prefix-matches the nested `routed_experts.*` params in load_weights_kernel.
  (Only reached on the quantize_in_weight_transfer=True path.)
- patches.py: verified all 7 monkeypatches still apply on 0.24; only a docstring
  version ref updated (is_3d_moe_weight still defaults True in 0.24).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(inference): rebase monkey_patch_no_moe_lora onto vLLM 0.24 __post_init__

0.24 made FusedMoEConfig.intermediate_size the ctor field and
intermediate_size_per_partition a -1 sentinel that __post_init__ must compute.
The patch replaced __post_init__ with a verbatim-0.23 copy that never set it,
leaving intermediate_size_per_partition=-1 (silent corruption of every
downstream consumer) and dropping the % tp_size assert + aiter/mori/platform
guards. Mirror 0.24's body verbatim, then flip is_lora_enabled off.

Found in a second-pass audit of all 16 active monkeypatches (registered across
patches.py, orchestrator.py, server.py, worker/__init__.py); the rest KEEP.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(inference): drop 2 LoRA reload monkeypatches for vLLM 0.24 native load_inplace

0.24's native OpenAIServingModels.load_lora_adapter reuses the existing
lora_int_id on a same-name reload and repoints the path, and its worker
LRUCacheWorkerLoRAManager.add_adapter force-reloads when lora_request.load_inplace
is True -- exactly what monkey_patch_load_lora_adapter and
monkey_patch_LRUCacheWorkerLoRAManager reimplemented by copying upstream bodies.

Replace both with the native path plus a small mechanism in prime-rl's
/load_lora_adapter endpoint:
- set load_inplace=True on the incoming request so 0.24 doesn't reject the
  same-name reload and the worker re-reads the new weights during add_lora;
- reset the *stored* LoRARequest's load_inplace back to False afterward, because
  it is a sticky field that _maybe_get_adapters hands to every generation request
  -- left True it would force a per-scheduler-step disk reload (the perf trap the
  old _apply_adapters(force_load=False) override avoided).

The orchestrator awaits this endpoint before dispatching rollouts for the new
policy version, so the reset lands before any generation resolves the adapter.

Also refresh stale "vLLM 0.23.0" version refs in comments to 0.24.0 where the
described behavior was re-verified against the 0.24 source (minimax gate dtype,
V2-runner routing rationale, NemotronH layerwise-reload shim -- the latter's
counting path is byte-identical in 0.24, so the shim stays needed).

Requires a live LoRA weight-sync run to validate before merge: confirm the
adapter picks up fresh weights each step AND that there is no per-step reload
regression.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* style: ruff format (unwrap lines within 120-col limit)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(inference): simplify monkey_patch_no_moe_lora to wrap upstream __post_init__

The previous version copied vLLM 0.24's FusedMoEConfig.__post_init__ body
verbatim (intermediate_size_per_partition compute, ROCm/aiter/mori guards,
platform checks) just to append `is_lora_enabled = False` -- carrying a
drift-prone "keep in sync with upstream" burden plus _aiter_ops/current_platform
imports.

`is_lora_enabled` is never read inside __post_init__ (only later during kernel
selection in modular_kernel.py / oracle/unquantized.py), so flipping it after
the original runs is equivalent. Wrap the original instead: it computes
intermediate_size_per_partition and runs every guard itself, so nothing can
drift and the -1 sentinel can never leak.

Verified against the 0.24 wheel: with tp_size=2, intermediate_size_per_partition
= 128 and is_lora_enabled = False.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(inference): reset load_inplace unconditionally in /load_lora_adapter

Previously the sticky-flag reset ran only on success, so an ErrorResponse
returned before resetting. Not triggerable on vLLM 0.24 (native load_lora_adapter
stores the adapter only after add_lora succeeds, and builds a fresh request rather
than mutating the stored one), but the correctness relied on that vLLM-internal
invariant. Reset whatever is stored for the name regardless of outcome so a
lingering load_inplace=True can never force a per-scheduler-step disk reload,
independent of vLLM internals.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(inference): remap flat MoE kernel wire names to vLLM 0.24 routed_experts params

vLLM 0.24 nests FusedMoE expert weights under MoERunner.routed_experts
(...experts.routed_experts.w13_weight), while the trainer's
convert_layer_to_vllm_kernel still emits the pre-0.24 flat names
(...experts.w13_weight). load_weights_kernel's 'name not in params' gate
fired before the expert-map prefix match, so the first fp8 kernel weight
update raised 'Kernel weight transfer skipped N weights not found in
model'. Wrap the incoming stream with upstream's remap_moe_expert_weights,
the compat shim vLLM ships for exactly this transition (covers w13/w2
weights and their _scale_inv variants; leaves gate/shared_experts names
untouched).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(inference): drop NemotronH mixer.D reload shim, fixed upstream in 0.24

vllm-project/vllm#44814 did land in the pinned 0.24.0 release - in
reload/meta.py, which caps copied_numel at param.numel() to fix the
composed_weight_loader double-count that finalized layers early and
dropped Mamba mixer.D. The earlier audit diffed mamba_mixer2.py and
reload/layerwise.py (byte-identical) and missed it. The capture/restore
shim is now dead weight on every non-quantized weight update; remove it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(inference): LoRA/MoE patch hygiene for vLLM 0.24

- Drop monkey_patch_skip_lora_module_warnings: the per-module regex
  warning loop it skipped was removed upstream before 0.23, so it was a
  pure drift-carrier - its _load_adapter copy silently dropped 0.24's
  moe_ep_spec= passthrough (EP read-time expert filtering) and the
  lora.is_3d_lora_weight stamp (needed for enable_mixed_moe_lora_format).
  Stock _load_adapter now runs in workers.
- Re-derive _patch_lora_key_prefix's from_local_checkpoint copy from the
  0.24 original so the stock caller's moe_ep_spec= kwarg is accepted;
  keeps only the real payload (accept bare-suffix OR qualified expert
  module names) and picks up the EP remote-expert pruning + tensorizer
  hardening. Docstring rewritten: vllm#38522 was closed unmerged and the
  base_model.model. prefix case is handled upstream.
- Drop the MiniMax M2 forward patch: the MoERunner already all-reduces
  internally (_maybe_reduce_final_output), so the patched forward's extra
  tensor_model_parallel_all_reduce doubled the MoE output at TP>1.
  Upstream's forward needs no changes; the gate rebuild + hf_to_vllm
  mapper stay.
- Remove the dead transformers-v5 tie_word_embeddings shim (class attr
  exists on the pinned transformers, guard never fired) and refresh stale
  comments: DP coordinator upstream timeout is 120s not 30s; 0.24 routes
  MoE archs (DeepseekV2/Qwen2Moe/GraniteMoe) to the V2 runner by default
  too, making the forced V1 more load-bearing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(inference): rename transformers_v5_compat to apply_shared_vllm_patches

The function is the vllm.general_plugins entry point dispatching the six
patches that must run in every vLLM process; the transformers-v5 shim it
was named for was removed. Entry-point target updated in pyproject.toml
(vLLM swallows plugin load failures, so a stale target would silently
skip all patches - uv run re-syncs metadata automatically).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(inference): restore 0.23 parser semantics + guard new 0.24 request validation

vLLM 0.24 behavior changes outside this branch's original diff surface:

- qwen3_coder (parser engine) now full-strips every tool parameter value where
  0.23 trimmed exactly one leading/trailing newline, corrupting
  whitespace-significant args (str_replace old_str/new_str, indented file
  content). Restore single-newline trim via monkey_patch_qwen3_coder_param_newline_trim
  (also covers nemotron_v3, which reuses qwen3_config).
- minimax_m2's engine swallows the literal </think> in CONTENT state and strips
  content on tool turns, breaking minimax_m2_append_think round-tripping. Drop
  the (CONTENT, THINK_END) transition and disable the strip.
- VLLM_ENFORCE_STRICT_TOOL_CALLING default flipped to True in 0.24: structural-tag
  constrained decoding for required/named/strict tools would sample a distribution
  the trainer never sees. Default it off in setup_vllm_env.
- 0.24 rejects temperature > 2.0 at request validation; mirror the bound in
  TrainSamplingConfig/EvalSamplingConfig so misconfigured sweeps fail at config
  load, not per-rollout with HTTP 400s.
- Fix stale 30s -> 120s DP-coordinator timeout comment.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(inference): cover plugin entry-point load, MoE kernel remap, MoE mismatch KL

CI could not see three load-bearing paths of the 0.24 bump:

- vLLM swallows vllm.general_plugins load failures, so a stale/misnamed entry
  point (renamed on this branch) silently drops every shared patch; load it
  exactly like vLLM does and assert the padded-input scrub applied.
- The MoERunner weight-sync rewrite (flat trainer names -> nested
  routed_experts params via remap_moe_expert_weights, expert-map prefix
  slicing) is only reachable via NCCL broadcast, which no CI config uses;
  exercise load_weights_kernel directly on a fake module tree.
- reverse_text_moe asserted exit code only; add a trainer/inference mismatch-KL
  bound so silent MoE weight corruption fails the job.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: address review — drop test additions and comment flourishes

Per review: remove the plugin entry-point test, the weight-transfer kernel
unit tests, and the reverse_text_moe mismatch-KL addition; trim the vLLM-0.24
references from the temperature docstrings (the le=2.0 bound stays).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: fares <fares@primeintellect.ai>
2026-07-02 20:25:56 +01:00
50aeb3c7d6 chore(deps): bump research-environments + wire s1-deepresearch-v1/arxivmath-v1 (#2934)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): add s1-deepresearch-v1 + arxivmath-v1 environments to pyproject.toml + uv.lock

Bumps the research-environments pin to pick up the two new
bring-your-own-search v1 tasksets:

- s1-deepresearch-v1: ScienceOne-AI/S1-DeepResearch-15k closed-ended
  deep-research QA (6000 verifiable tasks, en/zh filter), binary semantic
  LLM judge.
- arxivmath-v1: MathArena/arxivmath-training research-level math
  (2605 tasks), in-runtime math-verify scoring of the boxed answer.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(deps): bump research-environments for trace.last_reply scoring fix

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(deps): bump research-environments to merge with upstream main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(deps): relock for research-environments verifiers pin bumps

The submodule merge brought main's env pyproject updates (verifiers pins
unified to >=0.1.15.dev411), which uv.lock records as requires-dist metadata.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(deps): bump research-environments to merged main (s1-deepresearch/arxivmath #630)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: fares <fares@primeintellect.ai>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 20:24:16 +01:00
4beb553525 feat: default per-env ratio to 1, drop natural-distribution mode (#2935)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Env sampling weight (`ratio`) now defaults to 1 (equal weight per env)
and no longer accepts unset/None. The None-for-all-envs mode that
sampled proportional to each env's dataset size is removed, along with
the all-or-none constraint — any subset of envs may set `ratio`, the
rest default to 1.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 09:50:56 -07:00
halleriteandGitHub 51dc60a895 chore: dead-code sweep across trainer, orchestrator, utils, and configs (#2932)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 09:49:14 +02:00
halleriteandGitHub a8f090b444 chore: delete dead get_adapter_state_dict from trainer/weights.py (#2929)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:51:09 +02:00
halleriteandGitHub cdea189e3d chore(configs): remove dead max_retries knob from Env/Train/EvalConfig (#2930)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:50:54 +02:00
halleriteandGitHub d5f218f708 chore(configs): remove empty *ExperimentalConfig placeholders (#2931)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:14:56 +02:00
halleriteandGitHub a03c70f55b chore: delete dead utils/tensor_hashing.py (#2928)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 02:21:33 +02:00
e48a53853e fix: weight-sync hardening + dead-code / get_max_layer_num cleanup (#2922)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: correct weight-broadcast validation + prefix-cache docs

- validate_shared_weight_broadcast: the chained comparison
  `trainer.type != orchestrator.type != inference.type` only compared
  adjacent pairs, so a mismatched inference weight_broadcast type
  (e.g. trainer/orchestrator=nccl, inference=filesystem) passed validation
  silently. Check trainer vs orchestrator, then inference vs both.
- update_weights / load_lora_adapter docstrings claimed the server resets
  the prefix cache on weight update; it doesn't — the orchestrator salts
  the prefix cache per weight version (cache_salt, see orchestrator/envs.py).
  Fix the docs and drop the dead reset_prefix_cache_after_update state flag
  (set but never read).
- heartbeat: docstring said "2s timeout"; the request uses timeout=1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: remove dead code in trainer/utils

Grep-verified as unused across src/:
- qwen3_moe: load_balancing_loss_func (aux-loss-free routing is used instead)
- rl/loss.py: shift_logits
- perf.py: _count_trainable_params
- kernels/fp8_utils.py: align()
- kernels/fp8_indexer.py: dead `_weight_scale = weight_scale` assignment
  (kernel intentionally ignores weight_scale, per its NOTE)
- layers/moe.py: leftover commented-out forward variant
- utils/utils.py: capitalize, to_row_format, mean_normalize
- broadcast/nccl.py: import NCCL_READY_MARKER from utils.client instead of
  redefining the same constant

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor: consolidate get_max_layer_num into trainer/weights

Seven converting_*.py modules each defined their own get_max_layer_num —
six as a fragile `int(key.split(".")[2])` one-liner and afmoe as a regex
variant that returned the max index (its callers compensated with
`range(max_layer + 1)`). Replace all seven with the canonical, robust
implementation in trainer/weights.py (handles an arbitrary layer_prefix,
guards non-digit segments, already used by the NCCL broadcaster).

- afmoe: the canonical returns a count (max+1), so its two callers switch
  from `range(max_layer + 1)` to `range(num_layers)` — behavior-identical.
- No import cycle: weights.py imports neither trainer.models nor the
  converting modules.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor: centralize flash-attn varlen import guard

afmoe and qwen3_5_moe each re-declared the identical three-way
try/except import guard for flash_attn_varlen_func / _3_ / _4_ that
already exists in trainer/models/layers/attn.py. Import the (None-able)
module-level names from attn.py instead; each model's `_funcs` dispatch
table is unchanged.

Note: their attention classes are genuinely model-specific (gated output,
local/global split, MRoPE, GatedDeltaNet), so they legitimately do NOT
subclass the shared FlashAttention — only the optional-dependency import
guard was duplicated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: break circular import from get_max_layer_num consolidation

The consolidation made the converting_*.py modules import trainer/weights.py,
but weights.py imports trainer/lora.py, which (via trainer/models/__init__)
imports the model modules and their converting_*.py — closing a cycle:

  lora -> models/__init__ -> afmoe/modeling -> converting_afmoe
    -> weights -> lora (partially initialized) -> ImportError

Move get_max_layer_num into a dependency-free leaf module
trainer/conversion_utils.py (imports only torch) and point the seven
converting modules + the NCCL broadcaster at it. weights.py no longer
defines it (it never used it internally). Keeps the single-source dedup
without the cycle.

Caught by the reverse_text integration tests (trainer crashed at import).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-07-01 19:12:57 +01:00
f3c85a947a exp: update swe ablation (#2925)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* exp: add glm45air scaleswe length-penalty ablation config

Length-penalty variant of configs/debug/v1/glm45air_scaleswe.toml: enables the
GRPO linear length penalty with output-token, input-token, and turns coefficients
all set to 0.1, using the current [orchestrator.algo.length_penalty] schema on main.
Distinct -lp SLURM job name, wandb run name, and prime sandbox labels.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp: move scaleswe length-penalty config to configs/glm45air/swe.toml

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp: move glm45air scaleswe config to configs/glm45air/swe.toml, use rlm harness

Promote configs/debug/v1/glm45air_scaleswe.toml to configs/glm45air/swe.toml as a
move + update: switch the train and eval harness from default to rlm, enable the
GRPO linear length penalty (all coefs 0.1), and drop the -lp suffix from the SLURM
job name and prime sandbox labels (labels can't reference $SLURM_JOB_NAME — that
field is passed verbatim to the sandbox API — so the literal must match the job name
that the pre-launch cleanup deletes by).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp: drop -lp from wandb run name

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:53:58 -07:00
f19ba721a9 chore(configs): bump dist_timeout_seconds default to 3600 (#2924)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The 600s default torch/NCCL distributed timeout was too tight for
large multi-node runs — startup collectives (step-0 evals, slow first
SWE batches) tripped the watchdog and SIGABRT'd the trainer. Bump the
default to 3600s for both RL and SFT trainer configs.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:23:35 -07:00
fd5db5df6a chore(deps): add longpdfs-v1 environment to pyproject.toml + uv.lock (#2920)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The longpdfs-v1 environment was added to research-environments main
(commit f1bdab50f, PR #542) but was missing from this PR's pyproject.toml.

- Add longpdfs-v1 to envs optional dependencies and [tool.uv.sources]
- Add longpdfs-v1 package entry to uv.lock

Co-authored-by: Sami Jaghouar <sami@primeintellect.ai>
2026-07-01 10:16:22 -07:00
halleriteandGitHub 7b7c7efdfa chore(configs): migrate v1 harness ids for the verifiers null/default rename (#2919)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-01 06:38:52 +02:00
2e2accb121 fix(deps): enable verifiers[harbor] extra so swebench-verified eval loads (#2917)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The `swebench-verified-v1` (and other Harbor) tasksets require the Harbor
CLI, shipped via the `harbor` extra of the `verifiers` package. The root
project depended on plain `verifiers`, and `uv sync --all-extras` only
enables the root project's own extras (not a dependency's), so `harbor`
was never installed — the eval env-pool worker crashed in `load_tasks()`
with `RuntimeError: Harbor tasksets require the Harbor CLI`.

Switch the root dep to `verifiers[harbor]` so `harbor==0.14.0` is pulled
in (and lands on SLURM compute nodes via the sbatch `uv sync --all-extras`).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 12:34:51 -07:00
436873190d fix: schedule tail eval rollouts before draining at max_steps (#2913)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(dispatcher): wait for partly-scheduled eval groups before reporting idle

is_idle only checked the eval_source queue, but an eval example leaves the queue when its group
opens (next_fresh_group) while its group_size rollouts dispatch one at a time across fill_inflight
passes. In the window where the queue is empty, an eval group still has rollouts_to_schedule > 0,
and inflight/out_q are momentarily empty, is_idle wrongly reported drained — main_loop exits, the
tail eval rollouts are never scheduled, the eval batch never completes, and the eval point is
dropped. This hits hardest at max_steps, where the final eval triggers just as the train side is
cancelled.

Factor the eval-has-work predicate (queue OR any pending eval group) into a shared
RolloutDispatcher.eval_has_work property used by both is_idle and fill_inflight so they can't drift.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test: drop dispatcher unit test — verify the tail-eval fix via e2e instead

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 11:06:17 -07:00
f0c339a234 [ENG-4306] fix(docker): repair CUDA image build broken by uv 0.11.25 centralized project envs (#2906)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(docker): pin uv project env to /app/.venv

uv's centralized/cached project environments (a preview feature as of uv
0.11.25, and a likely future default) make `uv sync` build the env in the
uv cache and leave `.venv` as a symlink into it. The runtime stage ships the
env via `COPY --from=builder /app /app`, which can't follow that symlink (the
cache store lives outside /app), so the venv goes missing and the build fails
at the `bin/python` relink.

Setting UV_PROJECT_ENVIRONMENT=/app/.venv forces uv to materialize a real
in-project venv directory regardless of that behavior, so the cross-stage copy
keeps working even if/when the feature graduates from preview to the default.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(uv): drop vestigial `preview = true`

This flag was added in #1772 solely to silence a `uv run` warning on an
older uv (~Feb 2026). That warning no longer fires on uv >= 0.11.9 (verified
with and without preview on `uv run` and `uv lock`), so the opt-in is dead
weight.

It is not harmless dead weight: `preview = true` enables uv's *entire*
experimental feature surface, including features added in future releases.
uv 0.11.25 shipped the `centralized-project-envs` preview feature, which the
global opt-in silently activated — relocating the project env into the uv
cache and leaving `.venv` as a symlink into it. The Docker image build COPYs
only `/app`, so that symlink dangled in the runtime stage and the venv went
missing (`rm /app/.venv/bin/python` failed). Dropping the flag removes the
root enabler of that class of breakage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* use system python intepreter and remove the re-linking steps

* clean up comments

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 10:32:15 -07:00
9f425fffcb feat(metrics): unify train/eval rollout metrics over the all/effective matrix (#2907)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(metrics): unify train/eval rollout metrics over the all/effective matrix

Closes #2903.

Replace the two divergent rollout-metric paths — the pandas-heavy MetricsBuilder
(train) and the hand-rolled EvalBatchMetrics.to_wandb_dict (eval) — with one shared,
pandas-free, unit-tested function `compute_rollout_metrics`, logged over the matrix:

    {train,eval} / {agg,<env>} / {all,effective} / <metric> / <stat>

- `all` = every rollout that came back (errored + filtered included); `effective` =
  its non-errored, non-filtered subset (~ what actually trained). The gap between them
  is the filtering/error cost, now directly comparable per metric.
- Train retains the full arrival window (TrainSink.arrivals_window → TrainBatch.all_rollouts)
  so an `all` set exists; eval already kept its full cohort.
- All metrics apply to both train and eval except pass@k / pass^k (eval-only; pass^k is
  new) and the filter-pipeline rates (train-only — eval has no filters).
- Drop pandas from this path; aggregation is plain Python (flat means/max/min/rates,
  group-by only for solve rates).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): rename token metrics to num_*_tokens, drop no_response, top-level is_filtered

- seq_len / prompt_len / completion_len -> num_total_tokens / num_input_tokens /
  num_output_tokens, matching the renamed vf.Trace properties
- remove the no_response metric
- log is_filtered as a top-level rollout metric (was filters/is_filtered); per-filter
  detection rates stay under filters/<name>

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(metrics): add full timing phases, reward components, is_completed

- timing: add setup + finalize spans; timing/total now sums all four phases
  (setup + generation + finalize + scoring) instead of just generation + scoring
- rewards/<name>: per-reward-component breakdown (mirrors metrics/<name>)
- is_completed/mean: a finished-on-its-own-terms rate alongside is_truncated

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): rename effective_batch_size -> solved_some

Names the mixed-reward-group rate consistently with its solve_none / solve_all siblings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): solve_none/solve_all -> solved_none/solved_all

Consistent solved_none / solved_some / solved_all trio.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(metrics): log eval reward as avg@<k> instead of reward/mean

Eval reports the mean reward under the conventional avg@<group_size> key (a single value via
the new reward_label arg); train keeps the reward mean/max/min distribution. Same value,
eval-friendly name.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): split into compute_train_metrics / compute_eval_metrics over a shared core

Replace the single flag-driven compute_rollout_metrics with two functions sharing
_common_metrics: train adds the reward distribution + filter-pipeline rates; eval adds the
avg@<k> score + pass@k/pass^k. Drops the include_filters / include_pass_at_k / reward_label
flags and the train/eval branching from the call sites.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): rename error_rate -> has_error/mean

Consistent with the other per-rollout boolean rates (is_truncated/mean, is_completed/mean).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): move rollout_metrics.py back into metrics.py

Reclaim the conventional module name vacated by the old MetricsBuilder. Rename the source +
test (rollout_metrics.py -> metrics.py, test_rollout_metrics.py -> test_metrics.py) and fix
the stale compute_rollout_metrics doc references left from the train/eval split.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(metrics): rename progress/{samples,problems} -> progress/{rollouts,tasks}

Also the cumulative keys: progress/total_samples -> progress/total_rollouts,
progress/total_problems -> progress/total_tasks. Metric-key renames only; the internal
Progress counter fields are unchanged (they're pickled in the orchestrator checkpoint).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(types): TrainBatch.rollouts = all rollouts + .effective view (symmetric with EvalBatch)

TrainBatch.rollouts now holds the full arrival window (errored + filtered included), matching
EvalBatch.rollouts. Both expose an `effective` property — the non-errored, non-filtered subset
as a view (references, not copies), so each expensive trace is retained once. Drops the separate
TrainBatch.all_rollouts field.

Consumers repointed: metrics over rollouts (all) + effective; sample/distribution logging and the
success-line quality metrics over effective; disk/progress/efficiency over rollouts (all).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): inline the dist spec list; make helpers public (dist_stats, rate, common_metrics)

Drop the _DIST_SPECS (name, getter) table — the five distributional metrics are emitted inline
in common_metrics. Rename the module helpers to clearer public names: _dist -> dist_stats,
_rate -> rate, _common_metrics -> common_metrics.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): drop redundant TrainBatchMetrics fields derivable from batch.rollouts

With TrainBatch.rollouts holding the full arrival window, several aggregates are redundant:
- arrivals_by_env / errors_by_env — per-env arrival/error counts = grouping batch.rollouts
  (and errored ones) by env; derive them in log_train_batch instead.
- samples_shipped — equalled len(batch.samples) and had no consumers.

The sink no longer tracks the per-env counters. Kept n_trainable (shipped non-filtered count,
feeds the empty-batch guard) and num_prefill/decode_tokens (cohort totals including filtered
rollouts, so not a sum over samples).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): rollout-container API (TrainRollouts/EvalRollouts with .metrics, .effective)

Replace the functional compute_train/eval_metrics with list-like rollout containers:
- TrainRollouts / EvalRollouts own the rollouts (append/__len__/__iter__), expose .effective
  (clean subset, same container type — a view), .by_env (train), and .metrics.
- TrainMetrics / EvalMetrics (over RolloutMetrics) expose each distributional/rate metric as a
  Stat (rollouts.metrics.num_input_tokens.mean()) and build the full {prefix}/{subset}/... dict
  via .to_wandb(); special metrics (solve rates, stop_condition, pass@k, custom/<name>) are methods.
- TrainBatch.rollouts / EvalBatch.rollouts are now these containers; TrainBatchMetrics is dropped
  (n_trainable + prefill/decode token totals are fields on TrainBatch).

solve_rates uses each group's actual size as the full-solve threshold (config-free metrics).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): derive trainable count + token totals, slim TrainBatch to {rollouts, samples}

- Add Rollout.is_trainable (a nonzero advantage on some token ⇒ carries gradient) and a
  train-only is_trainable/mean metric; the trainable count is now derived from the rollouts,
  not carried as TrainBatch.n_trainable.
- Drop TrainBatch.{n_trainable, num_prefill_tokens, num_decode_tokens}: prefill/decode totals
  derive from batch.samples (the shipped payload — excludes filtered rollouts, so the usage
  reporter no longer over-counts), and the empty-batch guard keys on `not batch.samples` (the
  precise "nothing shipped to the trainer" stall signal) instead of a zero count.
- Rename TrainSink.arrivals_window → pending_rollouts (matches pending_batch / pending_groups).
- Compute num_tokens / rollout / unique-example counts once in finalize_train_batch (were
  computed twice).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): nest timing as a sub-metric (metrics.timing.setup.mean())

Collapse the five flat timing_* Stat properties into a TimingMetrics sub-object reached via
metrics.timing, so per-phase durations read as metrics.timing.setup.mean() / .total.mean().
wandb keys (timing/<phase>/<stat>, timing/total/<stat>) are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(metrics): solved_all counts only reward==1.0 groups

Restore the binary "fully solved" semantics: a group is solved_all when every rollout scored
exactly 1.0 (was: every rollout had a nonzero reward, which over-reported solved_all for
continuous / partial-credit rewards). Config-free (no env group_size lookup); unspecified for
non-binary reward ranges.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): derive prefill/decode tokens from effective rollouts, not samples

progress/prefill_tokens, progress/decode_tokens, and the training usage report now sum the
effective rollouts' Trace.num_input_tokens / num_output_tokens (the shipped subset — its
branches are exactly what `samples` concatenates) instead of summing masks over batch.samples.
No metric is computed over `samples` anymore. progress/tokens stays over the full window.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(orchestrator): build the eval success line from the metrics API

Replace the hand-rolled reward/turns/truncation/error/branches sums in finalize_eval_batch with
effective.metrics / rollouts.metrics Stat accessors. Stat.mean() returns 0.0 for an empty set,
so this also drops the per-field empty guards (and fixes a latent ZeroDivisionError on the
branches mean for an empty cohort).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor: move compute_pass_metrics into orchestrator/utils.py, drop eval_utils.py

compute_pass_metrics was the only thing in eval_utils.py; fold it into the existing
orchestrator/utils.py and delete the one-function module.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(orchestrator): name token totals input/output (vf v1 convention)

Rename the per-step token breakdown from prefill/decode to input/output to match the vf v1
Trace token naming used across the metric matrix: progress/input_tokens, progress/output_tokens,
and the usage report sum r.num_input_tokens / r.num_output_tokens over the effective subset
(the same props the matrix reports), rather than deriving a prefill/decode split.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): add p10/p90 stats, derive eval group size, inline timing phases

- Stat gains p10/p90 (linear-interpolated percentiles); to_dict now emits mean/max/min/p10/p90.
- EvalMetrics derives the avg@<k> group size from the rollouts (largest group) instead of
  carrying a passed int, so EvalRollouts no longer needs a group_size argument — everything is
  derived from the rollout list.
- Drop the TimingMetrics._phase helper; inline the per-phase Stat into each phase property.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): generic StatGroup for timing/metrics/rewards; drop quoted forward refs

- Extract a StatGroup base (named Stats → {prefix}/<name>/<stat> via to_dict, group[name] access);
  TimingMetrics (fixed phases) and a new CustomMetrics (dynamic per-rollout dict keys) both subclass
  it. metrics.metrics / metrics.rewards are now nested StatGroups (like metrics.timing), replacing
  the shared custom(attr) helper.
- Drop the string-quoted forward refs (list["Rollout"], Iterator["Rollout"], "TrainRollouts", …) —
  the module already has `from __future__ import annotations`, so the annotations resolve unquoted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(orchestrator): build the train success line from the rollout container

Drop the hand-rolled arrivals_by_env / errors_by_env dicts and per-env quality sums in
log_train_batch; derive everything from batch.rollouts (.metrics for the aggregate error rate,
.effective.metrics for quality, .by_env() for the per-env lines). Same output, no manual aggregation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(metrics): trim tests; drop dead EvalRollouts.append + batch_share manual dict

- Tests: fold the fluent-access test into the to_wandb test, merge the two boolean-rate tests and
  the two train-only-metric tests, add a train_wandb() helper, drop the unused has_response field
  from the rollout fake. Same coverage, 222→184 lines.
- Remove EvalRollouts.append (eval wraps a finished list, never appends — unlike TrainRollouts).
- finalize_train_batch: build the per-env batch/<env> shares from rollouts.by_env() instead of a
  hand-rolled env-count dict (same as the log_train_batch cleanup).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(metrics): error-type breakdown by count; fix eval avg@k key split; small cleanups

- Add an error/<type> breakdown (counts of errored rollouts by Trace error type, e.g. Cancelled /
  ProviderError), emitted on the `all` subset alongside has_error/mean (mirrors stop_condition's
  per-key breakdown, but by count to match the old cancelled_count/errored_count).
- Fix eval avg@<k>: derive the group size once from the full epoch in EvalRollouts and carry it onto
  .effective, so `all` and `effective` share one stable avg@<k> key (was derived per-subset, so an
  eval error could split it into avg@4 vs avg@3).
- Drop the dead is_filtered clause from EvalRollouts.effective (eval never filters); bind effective
  once in log_train_batch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(train_sink): preserve the rollout window across empty (no-ship) batches

process_batch reset pending_rollouts unconditionally, but the orchestrator drops an empty batch
(no samples) without logging it — so that window's metrics/record were lost and any overflow left
in pending_batch shipped a later step unattributed. Reset the window only when the batch ships, so
a no-ship batch's arrivals (and overflow) carry into the next shipped batch's window.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 22:15:11 -07:00
16efd8afda feat(algo): linear length penalty (completion + context + turns) for GRPO (#2901)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(algo): linear length penalty (completion + context + turns) for GRPO

Port the length-penalty-context-turns branch onto current main's algorithm
abstraction as a new `linear` LengthPenaltyConfig variant. It subtracts a single
pass_rate-scaled penalty from each reward before the GRPO baseline: coef *
completion tokens + context_coef * non-completion (context) tokens over the
group's longest sequence, plus turns_coef * turns over the group's most turns —
each normalized by the group's own max, optionally gated to correct rollouts.

context_coef and turns_coef default to 0.1 (completion coef 0.25).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(algo): make linear the only length penalty (remove tokens/turns)

Per review, the linear penalty replaces the existing efficiency-shaping
length penalties rather than coexisting with them:
- Remove TokensLengthPenaltyConfig / TurnsLengthPenaltyConfig; LengthPenaltyConfig
  is now just LinearLengthPenaltyConfig.
- Simplify GRPOAlgorithm.score_group to None vs linear.
- Remove the now-orphaned efficiency_shaping (delete algo/advantage.py) and its
  references in algo/__init__ and docs.
- Rewrite test_advantage.py: drop the efficiency_shaping / tokens / turns cases,
  add linear-penalty tests (completion / context / turns terms, gating, and the
  equal-length reduce-to-plain-GRPO invariant).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(algo): drop gate_by_correctness; compute turns term unconditionally

- Remove the gate_by_correctness option from the linear length penalty.
- Always add the turns term (it contributes 0 when turns_coef=0); drops the
  asymmetric guard so all three terms are handled uniformly.
- Remove the gating unit test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(algo): rename linear length-penalty fields + per-term-max normalization

- Rename GRPOAlgoConfig.length_penalty -> length_pen; lp -> length_pen in grpo.
- Rename coef/context_coef/turns_coef -> completion_pen/input_pen/turns_pen.
- Normalize each term by its own group max: completion / max completion,
  input (= total - completion) / max input, turns / max turns (previously the
  completion and input terms shared the max-total denominator).
- Drop the explanatory comments in score_group; fix stale field/doc text.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(algo): rename input_tokens -> input for naming consistency

Matches the other bare locals (completion, total, turns).

* docs(changelog): note length_pen rename + tokens/turns removal

* chore: adopt consolidated num_ trace token properties + rename length penalty config (#2905)

* fix(template): orchestrator URLs use canonical model.client path (#2899)

The multinode RL sbatch template launched the orchestrator with
--student.client.{base-url,admin-base-url}, but OrchestratorConfig has no
`student` field — the canonical path is `model.client` (base_url /
admin_base_url on ClientConfig). The orchestrator-config rename left the
template stale, so every multi-node RL launch fails config parsing with
"Unrecognized arguments: <inference URLs>".

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: correct env log glob to logs/envs/<split>/<env>.log (#2898)

* fix: correct env log glob to logs/envs/<split>/<env>.log

Since the nano-as-v1 migration each env writes a single
logs/envs/{train,eval}/<env>.log file (two levels), but the launch
banner still printed three-level globs (logs/envs/*/*/*.log), which
match nothing. Fix the banner generator and the captured example
outputs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: drop captured launch-banner output from example READMEs

The "Output of the command" blocks duplicated the live launch banner
(now fixed in pathing.py) and drift out of sync. Remove them; the run
command stays.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: configurable env vars (#2863)

* feat(env): consolidate component env vars

Add shared env var defaults and per-component env_vars plumbing across RL, SFT, and inference launch paths.

Update launcher filtering, SLURM templates, examples, and docs to match the consolidated env config surface.

* feat: add rl-wide env vars (#2897)

---------

Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>

* Update configs for renderer thinking retention (#2900)

* chore: migrate to consolidated Trace/Branch num_ token properties

Bump deps/verifiers to the property consolidation (verifiers #1894) and
rename every prime-rl access of the renamed Trace/Branch properties:

  completion_len / output_len -> num_output_tokens
  prompt_len                  -> num_input_tokens
  rollout total_tokens        -> num_total_tokens

progress.total_tokens, Usage.total_tokens and RunStats.total_tokens are
unrelated and left unchanged; num_turns is unchanged upstream.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: rename length penalty config to num_*_tokens_weight + num_turns_weight

Align the linear length-penalty config (from #2901) with the consolidated
num_-prefixed trace property names:

  [orchestrator.algo.length_pen]  -> [orchestrator.algo.length_penalty]
  completion_pen                  -> num_output_tokens_weight
  input_pen                       -> num_input_tokens_weight
  turns_pen                       -> num_turns_weight

Updates grpo.score_group, the config class, docs, CHANGELOG, and tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: bump verifiers + research-environments to main (#2904)

* chore: bump verifiers + research-environments to main

- verifiers: aa95826d → 97be43bf
- research-environments: 99ebd2e13 → bae0ffe5a
- lock new v1 envs: lean-v1 (6 per-dataset Lean tasksets), prolog-v1
- bump verifiers floor 0.1.15.dev400 → dev404

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: lock remaining research-environments v1 envs

Lock the 21 previously-unlocked RE v1 env packages into the `envs` extra
+ tool.uv.sources, and alphabetize both the `envs` list and the env source
entries.

tau3-bench-v1 is intentionally excluded: it requires tau2 @ git 58e5e1a,
which conflicts with the tau2 @ 337326e pinned by the already-locked
tau2-bench-v1 (uv cannot resolve two URLs for one package).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: drop rlm-swe to remove the verifiers override

rlm-swe pins verifiers>=0.1.15.dev17,<0.1.15.dev156 — a stale upper bound
that conflicts with the editable verifiers submodule (dev404) and with the
other envs / prime-rl-configs. It was the sole reason verifiers needed a
global override-dependencies entry (without it, resolution is unsatisfiable).

Dropping rlm-swe lets us remove that override: verifiers now resolves to the
editable submodule through tool.uv.sources alone. Also prunes rlm-swe's heavy
transitive deps (modal, swebench, swe-rex, pygithub, …) from the lock.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: migrate rlm_swe config dependents to r2e-gym-v1

Dropping the rlm-swe env orphaned its in-repo config dependents:
- examples/glm5_llmd/rl.toml: migrate the v0 `rlm_swe` env block to the v1
  `r2e-gym-v1` taskset on the rlm harness (prime runtime), mirroring
  configs/debug/v1/r2e_gym.toml
- configs/rlm_swe/qwen35_4b.toml: remove (superseded by configs/debug/v1/r2e_gym.toml)
- skills/training/start-run: point the find_spec example at r2e_gym_v1
- configs/debug/v1/r2e_gym.toml: drop the stale reference to the removed v0 config

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: re-pin deps/verifiers to merged verifiers main (#1894)

The Trace/Branch num_ consolidation landed on verifiers main; point the
submodule at the merge commit instead of the temporary cherry-pick pin.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: require verifiers >=0.1.15.dev405 (Trace/Branch num_ consolidation)

The submodule is pinned at the consolidation commit (0.1.15.dev405); raise
the floor so the renamed Trace/Branch token properties are guaranteed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
Co-authored-by: eligotts <78387377+eligotts@users.noreply.github.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
Co-authored-by: eligotts <78387377+eligotts@users.noreply.github.com>
2026-06-29 14:41:49 -07:00
7d5f2d74a6 exp: scaleswe ablation (#2862)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(v1): GLM-4.5-Air scaleswe SWE ablation config (router replay)

v1 RL config: GLM-4.5-Air (zai-org/GLM-4.5-Air, 100B MoE) on scaleswe-v1 (train)
+ swebench-verified (eval), bash harness on prime sandboxes. Router replay on
(trainer.enable_router_replay + inference.enable_return_routed_experts).

2 train + 2 infer nodes. Trainer: cp=8 ulysses, muon, + GLM-5.1 prod-run memory
improvements (LM-head chunking, AC + activation offload, optimizer CPU offload,
skip-gather/skip-optimizer ckpt). Inference: 2x tp=8 replicas, NO expert
parallelism (inference EP + router-replay capture deadlocked the engine via
cross-node EP all-to-all). Renderer/parsers auto-resolve from the official slug.

Relies on fixes already in main: the glm4_moe routed_experts .contiguous() slice
(torch.compile stride assert) and the verifiers always-install-uv bootstrap.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(slurm): VLLM_CACHE_ROOT=/tmp in multi_node_rl template

vLLM's compile cache defaulted to NFS (~/.cache/vllm), which hung inference
startup on slow shared FS. Point it at node-local /tmp (matching inference.sbatch.j2).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(swe-abl): online fp8 inference + 384 rollout concurrency for glm45air

Inference runs vLLM online fp8 quant (vllm_extra={quantization="fp8"}) over the
bf16 policy for faster generation; trainer/inference/orchestrator all use the
bf16 zai-org/GLM-4.5-Air. The per-channel GLM-4.5-Air-FP8 checkpoint is
incompatible with prime-rl's block-wise fp8 path (use_deep_gemm /
quantize_in_weight_transfer), so we use online quant instead. max_inflight_rollouts=384.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(swe-abl): glm45air-scaleswe -lp variant (default length penalty)

Sibling of glm45air_scaleswe.toml with orchestrator.advantage.length_penalty
enabled at defaults (coef=0.25, gate_by_correctness=false). Distinct slurm
job_name + sandbox labels (glm45air-swe-lp) so it runs alongside the no-penalty
run without sharing prime sandboxes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(swe-abl): bump weight_broadcast timeout to 3600s for cold NFS loads

Cold-cache nodes read the 206GB bf16 model from NFS at ~50s/shard (~46min
total). The weight-broadcast store rendezvous default (1200s/20min) times out
before inference finishes loading (DistStoreError: 1/17 clients joined), killing
the trainer. 3600s covers the cold-load worst case with margin. Applied to both
the base and -lp ablation configs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): kv-offload + fp8, drop router replay, bash_edit

- Drop router replay (trainer.enable_router_replay + inference.enable_return_routed_experts):
  mutually exclusive with inference.kv_cache_offload (rl.py validator — external KV cache hits
  don't carry routed-expert decisions).
- Enable native KV-cache offloading with a 128GB CPU tier (extends the prefix cache).
- FP8 trainer (DeepGEMM blockwise linear/MoE) — impl=custom is already set.
- Use the bash_edit harness (bash + local edit tool) for train + eval, replacing pure bash.
- Bump max_inflight_rollouts 384 -> 512.
- Keep LM-head token chunking + activation checkpointing explicit at the values that become
  trainer defaults in #2867 (not merged yet, so removing them would disable the features).
- Drop the -lp length-penalty variant.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): kv-offload + fp8, drop router replay, bash_edit

- Drop router replay (trainer.enable_router_replay + inference.enable_return_routed_experts):
  mutually exclusive with inference.kv_cache_offload (rl.py validator — external KV cache hits
  don't carry routed-expert decisions).
- Enable native KV-cache offloading with a 128GB CPU tier (extends the prefix cache).
- FP8 trainer (DeepGEMM blockwise linear/MoE) — impl=custom is already set.
- Use the bash_edit harness (bash + local edit tool) for train + eval, replacing pure bash.
- Bump max_inflight_rollouts 384 -> 512.
- Keep LM-head token chunking + activation checkpointing explicit at the values that become
  trainer defaults in #2867 (not merged yet, so removing them would disable the features).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): drop inference fp8 quant to lower mismatch

Run bf16 inference (remove vllm_extra quantization=fp8). fp8 inference added
~10x mismatch KL (~0.002 vs ~0.0002); bf16 inference lowers it. Trainer fp8 +
native KV-cache offload (and the now-disabled router replay) unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): bump context to 131072

seq_len + inference.model.max_model_len 65536 -> 131072.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): revert to 65k ctx, drop kv offload, 384 inflight

- seq_len + inference.model.max_model_len 131072 -> 65536
- Remove inference.kv_cache_offload (native CPU tier)
- max_inflight_rollouts 512 -> 384

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): eval at step 0 (explicit skip_first_step=false)

Make the startup eval explicit so SWE-Bench Verified runs at step 0 before
any train rollouts (already the default; pinned for clarity).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): drop fp8 trainer

Remove trainer.model.fp8 (back to bf16 training).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): bring back router replay

Re-enable trainer.enable_router_replay + inference.enable_return_routed_experts.
Compatible again now that kv-cache offload and fp8 (both mutually exclusive with
router replay) have been dropped; replaying inference's routed-expert decisions in
the trainer cuts the train/inference mismatch by ~an order of magnitude.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): scale inference to 4 nodes / 4 replicas

num_infer_replicas 2 -> 4 (num_infer_nodes is per-replica, so total inference
nodes = num_infer_nodes * num_infer_replicas = 4). Total job = 2 train + 4 infer.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): bump max_inflight_rollouts 384 -> 512

Increase orchestrator rollout concurrency to better saturate the 4 inference replicas.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(slurm): node-local FlashInfer JIT cache to avoid weka lock deadlock

FLASHINFER_WORKSPACE_BASE defaulted to $HOME/.cache/flashinfer on shared weka.
With concurrent GLM-4.5-Air/MoE runs every TP worker contends on the same
fused_moe_*.lock there and deadlocks in uninterruptible (D-state) filesystem
I/O during the CUTLASS fused-MoE JIT build, so inference never serves. Pin it
to node-local /tmp like the Triton/vLLM caches.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* glm45air-scaleswe: bump max_steps 400 -> 1000

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): set node-local cache dirs via config env_vars

Move the cache-dir env vars out of the SLURM templates and into the config
so the PR only adds the TOML (the merged env-var feature, #2863, makes this
possible):
- [env_vars] TRITON_CACHE_DIR (trainer + inference)
- [inference.env_vars] VLLM_CACHE_ROOT, FLASHINFER_WORKSPACE_BASE

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* exp(glm45air-scaleswe): migrate renderer preserve_all_thinking -> thinking_retention

Main #2900 replaced the renderer `preserve_all_thinking` bool with
`thinking_retention`; the merge left the config on the removed field, so it
failed the config-load unit test ("No config class could be parsed"). Switch
to `thinking_retention = "all"` (the documented equivalent).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Mika Senghaas <mika@primeintellect.ai>
2026-06-29 14:34:51 -07:00
2a0007f51d chore: bump verifiers + research-environments to main (#2904)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump verifiers + research-environments to main

- verifiers: aa95826d → 97be43bf
- research-environments: 99ebd2e13 → bae0ffe5a
- lock new v1 envs: lean-v1 (6 per-dataset Lean tasksets), prolog-v1
- bump verifiers floor 0.1.15.dev400 → dev404

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: lock remaining research-environments v1 envs

Lock the 21 previously-unlocked RE v1 env packages into the `envs` extra
+ tool.uv.sources, and alphabetize both the `envs` list and the env source
entries.

tau3-bench-v1 is intentionally excluded: it requires tau2 @ git 58e5e1a,
which conflicts with the tau2 @ 337326e pinned by the already-locked
tau2-bench-v1 (uv cannot resolve two URLs for one package).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: drop rlm-swe to remove the verifiers override

rlm-swe pins verifiers>=0.1.15.dev17,<0.1.15.dev156 — a stale upper bound
that conflicts with the editable verifiers submodule (dev404) and with the
other envs / prime-rl-configs. It was the sole reason verifiers needed a
global override-dependencies entry (without it, resolution is unsatisfiable).

Dropping rlm-swe lets us remove that override: verifiers now resolves to the
editable submodule through tool.uv.sources alone. Also prunes rlm-swe's heavy
transitive deps (modal, swebench, swe-rex, pygithub, …) from the lock.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: migrate rlm_swe config dependents to r2e-gym-v1

Dropping the rlm-swe env orphaned its in-repo config dependents:
- examples/glm5_llmd/rl.toml: migrate the v0 `rlm_swe` env block to the v1
  `r2e-gym-v1` taskset on the rlm harness (prime runtime), mirroring
  configs/debug/v1/r2e_gym.toml
- configs/rlm_swe/qwen35_4b.toml: remove (superseded by configs/debug/v1/r2e_gym.toml)
- skills/training/start-run: point the find_spec example at r2e_gym_v1
- configs/debug/v1/r2e_gym.toml: drop the stale reference to the removed v0 config

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 13:56:02 -07:00
eligottsandGitHub 4e7bc94fcd Update configs for renderer thinking retention (#2900)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-29 11:51:46 -07:00
d70075381c feat: configurable env vars (#2863)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(env): consolidate component env vars

Add shared env var defaults and per-component env_vars plumbing across RL, SFT, and inference launch paths.

Update launcher filtering, SLURM templates, examples, and docs to match the consolidated env config surface.

* feat: add rl-wide env vars (#2897)

---------

Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-06-28 15:34:11 -07:00
064ee23a8c fix: correct env log glob to logs/envs/<split>/<env>.log (#2898)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: correct env log glob to logs/envs/<split>/<env>.log

Since the nano-as-v1 migration each env writes a single
logs/envs/{train,eval}/<env>.log file (two levels), but the launch
banner still printed three-level globs (logs/envs/*/*/*.log), which
match nothing. Fix the banner generator and the captured example
outputs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: drop captured launch-banner output from example READMEs

The "Output of the command" blocks duplicated the live launch banner
(now fixed in pathing.py) and drift out of sync. Remove them; the run
command stays.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 15:29:46 -07:00
7c8755d9d5 fix(template): orchestrator URLs use canonical model.client path (#2899)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The multinode RL sbatch template launched the orchestrator with
--student.client.{base-url,admin-base-url}, but OrchestratorConfig has no
`student` field — the canonical path is `model.client` (base_url /
admin_base_url on ClientConfig). The orchestrator-config rename left the
template stale, so every multi-node RL launch fails config parsing with
"Unrecognized arguments: <inference URLs>".

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 15:24:29 -07:00
samsjaandGitHub bf3d381cfe refactor: remove "auto" option from fused_lm_head_token_chunk_size (#2890)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The "auto" value for fused_lm_head_token_chunk_size previously resolved
to 8192 for RL training via a config validator. This was redundant since
users can simply set the integer explicitly. Remove the "auto" option,
its validator (auto_setup_fused_lm_head_token_chunk_size), and update
docs/CHANGELOG accordingly.

The type changes from int | Literal["auto", "disabled"] to
int | Literal["disabled"]. Users who relied on "auto" should set
fused_lm_head_token_chunk_size = 8192 explicitly.
2026-06-27 14:31:46 -07:00
halleriteandGitHub 0be5ac452a feat: algorithm abstraction — named algorithm classes + inline frozen-model references (grpo, opd, sft_distill, self_distill, echo) (#2746)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-27 21:15:02 +02:00
c5afcaa2e2 feat: default ep to auto for MoE models (#2868)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: default ep to "auto" for MoE models

ep now defaults to "auto" which resolves at trainer startup to the
largest valid EP degree up to 8. The resolution loads AutoConfig to
read num_experts, then picks the biggest divisor of num_experts that
also divides the FSDP island size (world_size // dp_replicate), is a
multiple of cp, and is <= 8. For non-MoE models, auto resolves to 1.

Changes:
- ModelConfig.ep type: int -> int | Literal["auto"], default "auto"
- Added resolve_ep() in parallel_dims.py, called before
  get_parallel_dims() in both rl/train.py and sft/train.py
- Fixed validators (validate_ep_comm_backend, ep_only_with_custom_impl)
  to handle the "auto" string without comparing to int
- get_parallel_dims() now asserts ep is resolved to int
- Updated docs/scaling.md and CHANGELOG.md

* fix: ruff format parallel_dims.py

* feat: enable memory-saving defaults (ac, ac_offloading, compile, optim_cpu_offload, chunk loss)

- model.ac: None -> ActivationCheckpointConfig() (full mode)
- model.ac_offloading: None -> ActivationOffloadingConfig()
- model.compile: None -> CompileConfig() (fullgraph=false)
- model.optim_cpu_offload: False -> True
- model.fused_lm_head_token_chunk_size: disabled -> 1024
- SFT silently disables fused_lm_head_token_chunk_size
- Multi-run CI config sets optim_cpu_offload=false
- Debug configs disable compile

* refactor: replace ep="auto" string with auto_ep boolean

- Replace ep: int | Literal["auto"] = "auto" with auto_ep: bool = True + ep: int = 1
- Update validators to check auto_ep instead of string comparisons
- Revert SFT changes to main (ep_only_with_custom_impl, sft/train.py)
- Keep SFT validate_and_disable_chunked_loss fix (silently disable)
- Remove isinstance assertion in get_parallel_dims (ep is always int now)
- Update docs and changelog

* fix: address review comments

- Rename resolve_ep to resolve_auto_ep (samsja)
- Add impl guard in resolve_auto_ep: skip EP for hf impl (bugbot)
- Add runtime check: raise if deepep resolves to ep=1 (bugbot)
- Revert configs/debug/moe/sft/train.toml to keep compile enabled (mika)

* fix: update benchmark baselines for memory-saving defaults

The new memory-saving defaults (ac, ac_offloading, compile, optim_cpu_offload,
fused_lm_head_token_chunk_size) reduce throughput. Update both 1-GPU and 4-GPU
baselines to the actual metrics from the CI run.

* refactor: replace auto_ep boolean with ep: int | Literal["auto"]

- Remove the auto_ep boolean field from ModelConfig
- Change ep type from int to int | Literal["auto"], default "auto"
- Rename resolve_auto_ep back to resolve_ep, check config.ep != "auto"
- Update validators to handle ep being a string (isinstance check)
- Add assertion in get_parallel_dims that ep is resolved to int
- Update docs/scaling.md and CHANGELOG.md

* fix(sft): handle ep="auto" in ep_only_with_custom_impl validator

The SFT validator used  which raises TypeError when ep is
"auto" (a str). Match the RL trainer's approach using != comparisons
to handle both int and str types.

* fix(sft): call resolve_ep before get_parallel_dims in SFT trainer

* Simplify resolve_ep: min(fsdp_island_size, 8) for MoE, 1 otherwise

Remove the magic auto-resolution that searched for the largest EP degree
satisfying num_experts divisibility, FSDP island divisibility, and cp
multiple constraints. Now just checks if the model is MoE and resolves
to min(fsdp_island_size, 8).

* docs(inference): document required NIXL/UCX from-source build for P/D disaggregation

---------

Co-authored-by: samsja <samsja@users.noreply.github.com>
2026-06-26 16:17:13 -07:00
3cbeb5d0f1 feat: vLLM 0.23 bump + GLM-5.2 16-node P/D inference config (mooncake + llm-d) (#2883)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump vLLM to 0.23.0 and prune/adapt monkeypatches

Bump vllm 0.22.0 -> 0.23.0 (pyproject + regenerated uv.lock).

Remove two now-redundant monkeypatches (verified against 0.23.0 source,
adversarially double-checked):
- monkey_patch_deep_gemm_silu_mul_quant_int64: upstream kernel already uses
  int64 pointer arithmetic, so the patch was a behavioral no-op.
- _patch_qwen35_lora (vllm#36372): the Qwen3.5 GDN LoRA IndexError is fixed
  natively in vLLM; the patch is redundant and would corrupt the native path.

Adapt two patches the bump moved/changed:
- serving_tokens: get_max_tokens moved out of the deleted vllm.entrypoints.utils
  to vllm.entrypoints.serve.utils.api_utils (import-time breakage otherwise).
- monkey_patch_minimax_m2_for_lora: the MoE gate is now GateLinear (was
  ReplicatedLinear); rebuild as GateLinear(out_dtype=float32) with a bf16 weight
  so the LoRA Triton kernel's bf16/fp16 assertion passes while router logits
  stay fp32.

Default VLLM_USE_V2_MODEL_RUNNER=0: vLLM 0.23.0 routes dense Llama/Mistral/Qwen3
to the V2 GPU model runner, which has no _preprocess hook for the padded-input
scrub and does not zero the padded decode tail itself, reproducing NaN logits.
Forcing V1 keeps the scrub effective for every model and is also required for
routed-experts capture. setdefault keeps it overridable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(inference): cite vllm#44814 as the NemotronH mixer.D reload fix

The _restore_reload_corrupted_params workaround's removal trigger was vague
("once the upstream bug is fixed"). The upstream fix is vllm-project/vllm#44814
(merged 2026-06-10), which is NOT in the pinned 0.23.0 release, so the workaround
is still required. Record the root cause (mixer.A's composed_weight_loader
double-count drops the trailing mixer.D) and the exact removal condition.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(configs): add GLM-5.2 16-node P/D mooncake + llm-d inference config

Standalone `inference` deployment for GLM-5.2-FP8 on 16 nodes: disaggregated
8 prefill (4 replicas) + 8 decode, mooncake distributed CPU KV store, llm-d
router (EPP+Envoy), vLLM 0.23. Requires source-built NIXL/UCX 1.19.x
(scripts/install_nixl_from_source.sh) — the wheel UCX segfaults on P/D KV
transfer. Validated: 1000-req/500-concurrent burst, 0 faults / 0 RPC_FAIL.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(inference): keep Qwen3.5-MoE on 2D per-expert LoRA format

Dropping _patch_qwen35_lora wholesale also removed the
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False override.
vLLM 0.23.0 defaults that flag to True, so the LoRA loader expects 3D
stacked-expert adapters, but our trainer emits the 2D per-expert layout
(MultiLoRAGroupedExperts.state_dict_for_adapter) which vLLM only reads
when is_3d_moe_weight is False (or enable_mixed_moe_lora_format=True).
Without the override Qwen3.5-MoE LoRA adapters fail to load.

Re-add it as a minimal standalone patch. The rest of the old shim
(in_proj_qkvz packed-mapping + N-slice can_replace_layer/slice_lora_a for
vllm#36372) stays removed -- 0.23.0 handles it natively via expand_packed_lora.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(dockerfile): bake NIXL-from-source into base image

The PyPI nixl wheel ships its own UCX that segfaults on prefill->decode KV
transfer (#2883). Rebuild NIXL against the UCX 1.19 we already compile in
the builder stage so the disagg P/D path works without per-host rebuilds.

Adds ~5 min to the amd64 build. arm64 unchanged for now — NIXL upstream
should support it but hasn't been validated here.

* gate NIXL build behind INCLUDE_NIXL_FROM_SOURCE arg

Default off — base build stays identical. The hosted-rl workflow that builds
the disagg P/D variant passes --build-arg INCLUDE_NIXL_FROM_SOURCE=1 (and
should tag-suffix the result, e.g. prime-rl:<ver>-nixl-amd64, to keep image
streams disambiguated).

* fix(dockerfile): seed pip into venv before building NIXL wheel

uv-created venvs don't include pip by default. Mirror install_nixl_from_source.sh
which seeds it via 'uv pip install pip' before invoking 'python -m pip wheel'.
Also swap the final install to 'uv pip install' so we don't depend on the
.venv/bin/pip shim either.

* feat(dockerfile): opt-in disagg extras build (INCLUDE_DISAGG_EXTRAS)

Adds --build-arg INCLUDE_DISAGG_EXTRAS=0 (default) gating --extra disagg
in the uv sync step. The disagg extra installs deep-ep, deep-gemm and
quack — heavy source builds only the disaggregated-MoE inference path
needs (e.g. GLM-5.2 16-node P/D with deepep_high_throughput).

Default off so training-only / single-node inference builds are unaffected.
Enable via --build-arg INCLUDE_DISAGG_EXTRAS=1; pairs with --build-arg
INCLUDE_NIXL_FROM_SOURCE=1 (#2885) for full disagg P/D images.

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Jannik Straube <info@jannik-straube.de>
2026-06-26 15:48:47 -07:00
f8660256f0 Qwen3.5 MRoPE VLM model (#2819)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix qwen3.5 mrope vlm model

* fix(qwen3.5): handle adjacent VLM image groups

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: eligotts <eligotts@users.noreply.github.com>
Co-authored-by: hubert-marek <hubert@uni.minerva.edu>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Hubert <163992334+hubert-marek@users.noreply.github.com>
2026-06-26 15:47:42 -07:00
minh hoangandGitHub a66f8bed1b [ENG-4094] docker: include cuda toolkit with runtime image (#2826)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* docker: copy cuda toolkit from builder into runtime image

* use slim bookworm for glibc 2.36

* use nvidia cuda base image at runtime to avoid glibc mismatches; include cuda 13 runtime

* bug bot fixes

* fix groupadd collision

* include python3.12-dev in runtime image

* use cuda 13 runtime libs source

* trim cuda12 toolkit to just the nvcc JIT essentials
2026-06-26 14:09:55 -07:00
d1f366b1bc chore: bump verifiers + research-environments to main (#2887)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump verifiers + research-environments to main

Bump deps/verifiers (62dc38a5 -> aa95826d, 0.1.15.dev396 -> dev400; adds the
reusable vf.Judge) and deps/research-environments (0687a15c -> 99ebd2e1) to
their latest main, and follow the env ports / removals they shipped.

research-environments removed six v0 envs prime-rl pinned (ported to v1):
- code-env -> i3-code-v1
- ifeval -> ifeval-v1
- math500 -> math500-v1
- mmlu-pro -> mmlu-pro-v1
- science-env -> i3-science-v1
- simpleqa-verified -> simpleqa-verified-v1

Also drop v0 envs that nothing references anymore: hle, rlm-swe, rlm-search,
tau2-bench (tau2-bench-v1 stays).

Configs:
- Migrate the math500 eval env onto math500-v1 (hendrycks_math, nemotron_4node,
  nemotron_debug).
- Remove the stale env_mix and math_group configs.

Bump the verifiers floor dev396 -> dev400 and relock.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: keep rlm-swe + rlm-search env deps

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 11:29:56 -07:00
halleriteandGitHub eb89285418 fix(orchestrator): eval completion_len is always 0 on the token-less relay (#2880)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 22:47:59 +02:00
halleriteandGitHub 9e1c011ce1 chore(utils): remove dead processor= path from chat_template (#2881)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 21:19:26 +02:00
halleriteandGitHub d507aeafc0 chore(configs): remove dead BaseModelConfig.is_vlm property (#2876)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:12:28 +02:00
halleriteandGitHub 3dd3b30e75 chore(client): remove dead InferencePool.get_metrics() (#2875)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:12:15 +02:00
halleriteandGitHub 3a5f617969 chore(utils): delete unused duplicate utils/messages.py (#2874)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:11:59 +02:00
halleriteandGitHub c268702f55 chore(filters): remove unconsumed FilterResult.detection_index (#2877)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:11:05 +02:00
halleriteandGitHub 62702bafa7 docs(inference): correct stale serving_tokens.py docstrings for vLLM 0.22 (#2878)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:10:26 +02:00
35b452b01c chore: bump verifiers + research-environments to main (#2873)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bump deps/verifiers (b055799f -> 20abcd91) and deps/research-environments
(dbc58e14 -> 0687a15c) to their latest main, and follow the env
deprecations/ports they shipped.

research-environments removed several v0 envs and ported others to v1:
- drop dead v0 env deps (removed upstream): color-codeword,
  mini-swe-agent-plus, opencode-{cp,deepdive,math,science,swe}
- migrate ported envs v0 -> v1: deepdive, gpqa, livecodebench
- migrate the two multimodal color-codeword configs onto the
  color-codeword-v1 taskset (default harness, subprocess runtime)

Also bump the verifiers floor 0.1.15.dev388 -> dev394 to match the new pin
and relock.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:36:03 -07:00
halleriteandGitHub 2e29c66fd7 fix(orchestrator): align gibberish/repetition filters to v1 branch streams (#2872)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 06:02:41 +02:00
halleriteandGitHub d3765e289d chore(deps): bump verifiers to 0.1.15.dev388 (#2870)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-24 22:52:46 +02:00
minh hoangandGitHub 9bf203c678 Fix Docker editable package version resolution (#2866)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-24 11:52:10 -07:00
46bcf628f6 chore: remove outdated math configs (#2865)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove outdated config dirs

Prune four stale, unused config directories. None are referenced by
docs, skills, CI, or scripts, and each is a one-off experiment or
feature demo whose last substantive edit predates the recent config
sweeps:

- wordle: legacy v0-bridge demo, last real edit 2025-08-30
- deepscaler: old multi-stage experiment (README points at a
  configs/deepscaler/eval.toml that no longer exists)
- glm5_disagg_inference: one-off disaggregated-inference demo
- elastic: alphabet-sort elastic/DNS-discovery demo

All four still parse against the current schema; removal is about
disuse, not breakage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: remove outdated acereason_math configs

Prune the stale acereason_math experiment configs (stage1/stage2, last
real edit 2025-12-23). They reference the aime24-v1 eval taskset that is
no longer available, so they fail to load against the current schema.

The live nightly run (configs/ci/nightly/acereason_math.toml) is
unaffected; drop its now-dangling comment reference to the deleted dir.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: keep wordle, elastic and glm5_disagg_inference configs

Narrow this PR to only the deepscaler and acereason_math configs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: remove acereason_math from nightly suite

Drop the nightly acereason-math config and its test. The nightly
workflow auto-discovers tests/nightly/test_*.py, so removing the test
file drops it from the matrix.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:45:19 -07:00
a3151e3711 chore: repoint v1 tasksets to research-environments (#2864)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): repoint scaleswe/swebench-verified/terminal-bench-2 v1 tasksets to research-environments

The three container-backed v1 SWE tasksets moved out of verifiers into
research-environments. Repoint their [tool.uv.sources] paths and bump both
submodules to match.

- deps/verifiers: drop the three envs
- deps/research-environments: add the three envs + advance to current main
- uv lock

Taskset ids are unchanged, so run configs that reference them by id need no changes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): bump verifiers + research-environments submodules to current heads

Picks up vf#1851 (swebench-verified ensures uv on PATH before scoring), now ported
into the research-environments copy of swebench_verified_v1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): repoint 6 more v1 tasksets to research-environments

Following their move out of verifiers, repoint math-env-v1, aime24-v1, r2e-gym-v1,
swelego-v1, wikispeedia-v1, and general-agent-v1 from deps/verifiers to
deps/research-environments, and bump both submodules to the updated heads. The
moved envs now pin verifiers>=0.1.15.dev381 (satisfied by the editable verifiers).

- uv lock

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): bump research-environments (drop moved eval configs + scaleswe fix)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): swap v0 aime for v1 tasksets + reference tau2-bench-v1

Following the aime/wikispeedia v0->v1 replacement in research-environments:
- drop aime2024, aime2025 (v0); reference aime24-v1, aime25-v1, aime26-v1
- add tau2-bench-v1
- bump deps/research-environments + uv lock

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): repin verifiers + research-environments to merged main

verifiers#1853 (remove the moved v1 tasksets) and research-environments#527 (add them)
have merged; repin both submodules to the merged main commits. uv.lock unchanged
(already consistent — `uv lock --check` passes).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(configs): point aime eval envs at the v1 tasksets

The v0 aime2024/aime2025 packages were dropped from the `envs` extra + sources, so
`uv sync --extra envs` no longer registers them and eval sections using the legacy
ids fail at runtime. Switch those eval entries to the v1 tasksets (aime24-v1 /
aime25-v1; default `subprocess` harness), keeping the display names for metric
continuity.

- configs/acereason_math/{stage1,stage2}.toml
- configs/debug/hendrycks_sanity/rl.toml
- configs/math_group/rl.toml

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:33:26 -07:00
c33020a3d4 chore: bump activation-offload memory warn threshold to 90% (#2861)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The CPU RAM usage warning in the activation offloader fired at 60%
virtual memory used, which is noisy on healthy runs. Bump the threshold
to 90% so it only warns when memory is genuinely close to exhaustion.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 18:10:19 -07:00
193 changed files with 9064 additions and 6185 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --extra flash-attn --extra envs --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
+6
View File
@@ -2,6 +2,12 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **fp32 MoE routing enabled by default**: `trainer.model.moe_router_dtype` (new field) defaults to `"float32"` — custom-impl MoE router gates keep fp32 weights through forward/backward (exempt from the FSDP bf16 cast) and compute the gate GEMM and routing logits in fp32. `inference.enable_fp32_router_logits` (new field) defaults to `true` — DeepSeek-family models served by vLLM (incl. GLM-5.x) emit fp32 router logits via `out_dtype=float32` on the gate. Both change MoE numerics for existing runs (routing logits are no longer rounded to bf16; near-tie expert selections can differ). Set `moe_router_dtype = "bfloat16"` / `enable_fp32_router_logits = false` to restore the previous behavior. Non-MoE and HF-impl models are unaffected. (2026-07-04)
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
+95 -8
View File
@@ -32,6 +32,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
libnl-route-3-dev \
libibverbs-dev \
librdmacm-dev \
python3.12 \
python3.12-venv \
python3.12-dev \
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
ARG UCX_VERSION=1.19.1
@@ -60,8 +64,13 @@ ADD https://astral.sh/uv/install.sh /uv-installer.sh
# Set install dir to location accessible to non-root users
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
ENV PATH="/usr/local/bin:$PATH"
ENV UV_PYTHON_INSTALL_DIR="/usr/local/share/uv/python"
# Build .venv against the system CPython, so the venv's recorded interpreter
# matches the runtime interpreter and no bin/python relink is needed at runtime.
ENV UV_PYTHON_PREFERENCE=only-system
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# Explicity set venv dir inside /app so to ensure it gets copied over during
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies (The gradual copies help with caching)
WORKDIR /app
@@ -77,20 +86,85 @@ COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
# Opt-in extras for disaggregated P/D inference (deep-ep, deep-gemm, quack).
# Default off — they're heavy source builds only the disagg-MoE path needs.
# Enable via `--build-arg INCLUDE_DISAGG_EXTRAS=1`.
ARG INCLUDE_DISAGG_EXTRAS=0
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/app/.cache/uv \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress --group mamba-ssm --locked --no-dev
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& \
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
&& \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
# the disaggregated P/D path — default off so training-only / single-node
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
ARG INCLUDE_NIXL_FROM_SOURCE=0
ARG NIXL_VERSION=0.10.1
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
VIRTUAL_ENV=/app/.venv uv pip install pip \
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
&& cd /tmp/nixl \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
fi
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
FROM python:3.12-slim
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
# COPY ships only the trimmed result (~1.5 GB) instead of the full ~6.6 GB. Drops the math
# runtime libs (cublas/cusparse/cufft/cusolver/curand/npp/nvjpeg) and big static .a
# archives since nvcc JIT (TileLang/FlashInfer build their own kernels) and torch
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
FROM builder AS cuda-trim
RUN find /usr/local/cuda-12.8/targets/*/lib \
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# CUDA 13 runtime libs source
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
# Runtime image
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
--no-install-recommends \
--force-yes \
python3.12 \
python3.12-venv \
python3.12-dev \
build-essential \
wget \
clang \
@@ -111,13 +185,30 @@ RUN apt-get update && apt-get install -y \
libibverbs1 \
ibverbs-providers \
librdmacm1 \
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
ENV CUDA_HOME=/usr/local/cuda
ENV PATH="/usr/local/cuda/bin:${PATH}"
# CUDA 13 runtime libs for deep-gemm
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
&& ldconfig \
&& ldconfig -p | grep -q libcudart.so.13 \
&& ldconfig -p | grep -q libnvrtc.so.13
ARG USER_ID=1000
ARG GROUP_ID=1000
RUN groupadd --gid $GROUP_ID appuser && \
RUN userdel -r ubuntu 2>/dev/null || true; \
groupdel ubuntu 2>/dev/null || true; \
groupadd --gid $GROUP_ID appuser && \
useradd --uid $USER_ID --gid appuser --create-home --shell /bin/bash appuser && \
usermod -aG sudo appuser && \
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
@@ -137,10 +228,6 @@ COPY --from=builder /opt/ucx /opt/ucx
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
RUN rm /app/.venv/bin/python && ln -s /usr/local/bin/python /app/.venv/bin/python
RUN rm /app/.venv/bin/python3 && ln -s /usr/local/bin/python /app/.venv/bin/python3
RUN rm /app/.venv/bin/python3.12 && ln -s /usr/local/bin/python /app/.venv/bin/python3.12
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
ENV UCX_HOME=/opt/ucx
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "0b37bc923",
"timestamp": "2026-05-19T01:28:25+00:00",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:50:40+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
},
"metrics": {
"mfu": {
"mean": 22.77046832707997,
"std": 0.03172890658906481,
"min": 22.750797215697055,
"max": 22.80707156937409
"mean": 20.802552047875178,
"std": 0.16199364988631793,
"min": 20.664358307416567,
"max": 20.98082222151257
},
"throughput": {
"mean": 2719.4358949662887,
"std": 3.7893259921987053,
"min": 2717.086609671837,
"max": 2723.8073540657224
"mean": 2484.411208996455,
"std": 19.346608946709658,
"min": 2467.9069802355616,
"max": 2505.7016937694384
},
"step_time": {
"mean": 48.285218452724315,
"std": 0.06726350421944344,
"min": 48.207625919021666,
"max": 48.327002701349556
"mean": 52.79691480938345,
"std": 0.4071756223542672,
"min": 52.35017399210483,
"max": 53.14720633160323
},
"peak_memory": {
"gib": 24.248046875,
"pct": 51.15428047554115
"gib": 11.728515625,
"pct": 24.742767157118376
}
}
}
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "0b37bc923",
"timestamp": "2026-05-19T01:32:27+00:00",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:55:54+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
},
"metrics": {
"mfu": {
"mean": 21.824271379711288,
"std": 0.07444985226850119,
"min": 21.739369034306105,
"max": 21.878404774433935
"mean": 17.217465998339005,
"std": 0.02905058130694137,
"min": 17.19503698271855,
"max": 17.250282374540514
},
"throughput": {
"mean": 10425.733211800512,
"std": 35.565645418564436,
"min": 10385.174276894972,
"max": 10451.593425935866
"mean": 8225.003435798719,
"std": 13.877833769765575,
"min": 8214.288808538377,
"max": 8240.68023789224
},
"step_time": {
"mean": 50.39627862814814,
"std": 0.1756523472528039,
"min": 50.26670710090548,
"max": 50.59620195720345
"mean": 63.90305413212627,
"std": 0.11015530079183487,
"min": 63.77801387012005,
"max": 63.985770548693836
},
"peak_memory": {
"gib": 17.490234375,
"pct": 36.897831788841806
"gib": 6.298828125,
"pct": 13.288163877053583
}
}
}
-53
View File
@@ -1,53 +0,0 @@
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[ckpt]
interval = 100
[wandb]
project = "acereason-math"
name = "stage1"
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "math500"
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-54
View File
@@ -1,54 +0,0 @@
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[ckpt]
interval = 100
resume_step = 500
[wandb]
project = "acereason-math"
name = "stage2"
[orchestrator]
batch_size = 2048
group_size = 16
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 16384
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "math500"
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+2 -2
View File
@@ -24,7 +24,7 @@ args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_tur
[inference]
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
# <think> blocks. Match that with renderer thinking_retention.
[orchestrator.renderer]
name = "auto"
preserve_all_thinking = true
thinking_retention = "all"
@@ -6,6 +6,7 @@ enable_token_export = true
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_token_chunk_size = 8192
optim_cpu_offload = false
[model.lora]
rank = 8
@@ -1,10 +1,10 @@
# Smoke test for the RL-entrypoint OPD (on-policy distillation) training mode.
# The student inference deployment is launched by the rl entrypoint on GPU 0;
# the teacher inference server is started externally by the test fixture (see
# Smoke test for the RL-entrypoint opd algorithm (on-policy distillation).
# The policy inference deployment is launched by the rl entrypoint on GPU 0;
# the frozen reference server is started externally by the test fixture (see
# tests/integration/test_reverse_text_rl_opd.py) on the same GPU. Trainer
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
max_steps = 15
seq_len = 2048
[model]
@@ -15,10 +15,16 @@ project = "reverse-text-ci"
name = "ci-rl-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
[orchestrator.renderer]
name = "qwen3"
@@ -38,12 +44,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
@@ -1,10 +1,10 @@
# Smoke test for the RL-entrypoint SFT (on-policy hard distillation) training
# mode. The student inference deployment is launched by the rl entrypoint on
# GPU 0; the teacher inference server is started externally by the test
# fixture (see tests/integration/test_reverse_text_rl_sft.py) on the same GPU.
# Trainer takes GPU 1. Training config mirrors `reverse_text/start.toml`.
# Smoke test for the RL-entrypoint sft algorithm (hard distillation).
# The policy inference deployment is launched by the rl entrypoint on GPU 0;
# the frozen sampling server is started externally by the test fixture (see
# tests/integration/test_reverse_text_rl_sft.py) on the same GPU. Trainer
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
max_steps = 15
seq_len = 2048
[model]
@@ -15,13 +15,25 @@ project = "reverse-text-ci"
name = "ci-rl-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 16
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `default` (wraps the student tokenizer's
# apply_chat_template) so the CE target is faithful to the student's actual
# chat template. The stock `qwen3` renderer reimplements the Qwen format and
# injects an empty `<think></think>` block, which this model's custom template
# does not emit — corrupting the distillation target.
[orchestrator.renderer]
name = "qwen3"
name = "default"
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -39,12 +51,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
-36
View File
@@ -1,36 +0,0 @@
# Run on 8xH200
# Similar to configs/acereason_math/stage1.toml, but
# - 300 instead of 500 steps
# - No checkpointing
# - No evals
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
@@ -21,8 +21,9 @@ group_size = 16
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
+62
View File
@@ -0,0 +1,62 @@
# Algorithm — Debug Configs
Minimal end-to-end configs for the algorithms against bundled verifiers envs, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the policy.
| Config | Algorithm | Frozen model | Notes |
|---|---|---|---|
| `grpo.toml` | `grpo` | none | |
| `max_rl.toml` | `max_rl` | none | GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft_distill.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_distill_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `self_distill.toml` | `opsd` | none (self-distills against the live policy) | SDFT; demo from reverse-text's `answer` field |
| `echo.toml` | `echo` | none | multi-turn `alphabet-sort`; CE on observation tokens |
| `mixed_grpo_opd.toml` | `grpo` + `opd` (per env) | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | two envs, one run; heterogeneous batches (with/without `ref_logprobs`) |
The policy inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local frozen model (used by `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`) is **not** auto-launched — start it manually on GPU 1.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd`, `[orchestrator.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
## Start the local frozen model
Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
```bash
# GRPO (no frozen model)
uv run rl @ configs/debug/algorithms/grpo.toml --output-dir outputs/grpo
# MaxRL (no frozen model)
uv run rl @ configs/debug/algorithms/max_rl.toml --output-dir outputs/max_rl
# OPD (needs the frozen model on port 8001)
uv run rl @ configs/debug/algorithms/opd.toml --output-dir outputs/opd
uv run rl @ configs/debug/algorithms/opd_lora.toml --output-dir outputs/opd_lora
# SFT distillation (needs the frozen model on port 8001)
uv run rl @ configs/debug/algorithms/sft_distill.toml --output-dir outputs/sft_distill
uv run rl @ configs/debug/algorithms/sft_distill_lora.toml --output-dir outputs/sft_distill_lora
# Self-distillation against the live policy (no frozen model)
uv run rl @ configs/debug/algorithms/self_distill.toml --output-dir outputs/self_distill
# ECHO (no frozen model; multi-turn env)
uv run rl @ configs/debug/algorithms/echo.toml --output-dir outputs/echo
# Mixed per-env algorithms: GRPO + OPD in one run (needs the frozen model on port 8001)
uv run rl @ configs/debug/algorithms/mixed_grpo_opd.toml --output-dir outputs/mixed_grpo_opd
```
See [docs/algorithms.md](../../../docs/algorithms.md) for what each algorithm does and how to author your own.
+50
View File
@@ -0,0 +1,50 @@
# ECHO on the multi-turn alphabet-sort env (bundled with verifiers): GRPO on
# action tokens + weighted CE on the env's observation tokens.
# uv run rl @ configs/debug/algorithms/echo.toml
max_steps = 20
seq_len = 4096
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-echo"
[orchestrator]
batch_size = 32
group_size = 4
# alphabet-sort's feedback arrives as user messages, so train the user role
# instead of echo's tool default.
[orchestrator.algo]
type = "echo"
[orchestrator.algo.roles.user]
alpha = 0.1
[[orchestrator.train.env]]
id = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
[orchestrator.train.sampling]
max_completion_tokens = 512
# ECHO learns from observation tokens even when the GRPO advantage collapses
# to zero — keep zero-advantage rollouts in the batch.
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
enforce = false
# Qwen3 finetune with the standard PI template patch; always re-emits prior
# <think> blocks, matched by renderer thinking_retention.
[orchestrator.renderer]
name = "qwen3"
thinking_retention = "all"
[trainer.optim]
lr = 1e-6
[inference]
gpu_memory_utilization = 0.5
@@ -5,14 +5,16 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
project = "algorithms-debug"
name = "debug-rl"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "grpo"
[orchestrator.renderer]
name = "qwen3"
+43
View File
@@ -0,0 +1,43 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-max-rl"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "max_rl"
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -1,9 +1,12 @@
# Start the teacher inference server first (on a separate GPU):
# Mixed per-env algorithms in one run: a GRPO env and an OPD env, both on
# reverse-text. Exercises heterogeneous train batches — OPD samples ship
# ref_logprobs, GRPO samples don't, and both pack into the same micro batches.
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd.toml
# uv run rl @ configs/debug/algorithms/mixed_grpo_opd.toml
max_steps = 20
seq_len = 2048
@@ -12,14 +15,16 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd"
project = "algorithms-debug"
name = "debug-mixed-grpo-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "grpo"
[orchestrator.renderer]
name = "qwen3"
@@ -28,9 +33,21 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-grpo"
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-opd"
[orchestrator.train.env.algo]
type = "opd"
[orchestrator.train.env.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
[orchestrator.eval]
interval = 1
interval = 5
num_examples = 128
[orchestrator.eval.sampling]
@@ -39,16 +56,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -1,9 +1,9 @@
# Start the teacher inference server first (on a separate GPU):
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft.toml
# uv run rl @ configs/debug/algorithms/opd.toml
max_steps = 20
seq_len = 2048
@@ -12,13 +12,19 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft"
project = "algorithms-debug"
name = "debug-opd"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
group_size = 16
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -40,12 +46,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
@@ -1,9 +1,9 @@
# Start the teacher inference server first (on a separate GPU):
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd_lora.toml
# uv run rl @ configs/debug/algorithms/opd_lora.toml
max_steps = 20
seq_len = 2048
@@ -12,14 +12,21 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
project = "algorithms-debug"
name = "debug-opd-lora"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
name = "qwen3"
@@ -39,12 +46,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
@@ -0,0 +1,49 @@
# Self-distillation (SDFT, https://arxiv.org/abs/2601.19897) against the live
# policy itself: the reference for each completion is the current model
# conditioned on the expert demonstration — no extra deployment needed.
# reverse-text carries the demonstration in its top-level `answer` field.
# uv run rl @ configs/debug/algorithms/self_distill.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-self-distill"
[orchestrator]
batch_size = 32
group_size = 1
# reverse-text's demo lives in the "answer" column.
[orchestrator.algo]
type = "opsd"
demo_key = "answer"
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.5
+60
View File
@@ -0,0 +1,60 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/algorithms/sft_distill.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-sft"
[orchestrator]
batch_size = 128
group_size = 4
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `default` (wraps the student tokenizer's
# apply_chat_template) so the CE target is faithful to the student's actual
# chat template. The stock `qwen3` renderer injects an empty `<think></think>`
# block this model's custom template never emits, corrupting the target.
[orchestrator.renderer]
name = "default"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -1,9 +1,9 @@
# Start the teacher inference server first (on a separate GPU):
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft_lora.toml
# uv run rl @ configs/debug/algorithms/sft_distill_lora.toml
max_steps = 20
seq_len = 2048
@@ -12,17 +12,28 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
project = "algorithms-debug"
name = "debug-sft-lora"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `default` (wraps the student tokenizer's
# apply_chat_template) so the CE target is faithful to the student's actual
# chat template. The stock `qwen3` renderer injects an empty `<think></think>`
# block this model's custom template never emits, corrupting the target.
[orchestrator.renderer]
name = "qwen3"
name = "default"
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -40,12 +51,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
+1 -1
View File
@@ -22,8 +22,8 @@ name = "hendrycks-math"
interval = 50
[[orchestrator.eval.env]]
id = "aime2024"
name = "aime2024"
taskset = { id = "aime24-v1" }
group_size = 16
[trainer.model.ac]
@@ -9,7 +9,6 @@ project = "reverse-text-debug"
name = "debug-multi-env"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
+3 -2
View File
@@ -40,8 +40,9 @@ enforce = false
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
harness = { id = "null", runtime = { type = "subprocess" } }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
+1
View File
@@ -5,3 +5,4 @@ batch_size = 2
[model]
seq_len = 1024
compile = "None"
+2 -1
View File
@@ -1,7 +1,8 @@
max_steps = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "PrimeIntellect/Qwen3-0.6B"
compile = "None"
[data]
type = "fake"
-42
View File
@@ -1,42 +0,0 @@
# Training Mode — Debug Configs
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
| Config | Mode | Teacher | Notes |
|---|---|---|---|
| `rl.toml` | `rl` | none | |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml`) is **not** auto-launched — start it manually on GPU 1.
## Start the local teacher
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
```bash
# RL (no teacher)
uv run rl @ configs/debug/training_modes/rl.toml
# OPD (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/opd.toml
uv run rl @ configs/debug/training_modes/opd_lora.toml
# SFT hard distill (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/sft.toml
uv run rl @ configs/debug/training_modes/sft_lora.toml
```
See [docs/training.md](../../docs/training.md#training-modes-rl--opd--sft-via-orchestrator) for what each mode does.
+1 -1
View File
@@ -37,6 +37,6 @@ max_completion_tokens = 768
[[orchestrator.train.env]]
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference] # Default inference config
+1 -2
View File
@@ -32,7 +32,6 @@ freq = 1
[trainer.model.compile]
[orchestrator]
training_mode = "rl"
batch_size = 256
rollouts_per_example = 8
max_off_policy_steps = 32
@@ -43,7 +42,7 @@ name = "qwen3"
[[orchestrator.train.env]]
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
taskset = { id = "general-agent-v1", tools = { colocated = true } }
harness = { id = "default", runtime = { type = "modal" } }
harness = { id = "null", runtime = { type = "modal" } }
[inference]
gpu_memory_utilization = 0.85
+2 -3
View File
@@ -15,7 +15,6 @@ name = "gsm8k-v1"
name = "Qwen/Qwen3-0.6B"
[orchestrator]
training_mode = "rl"
batch_size = 512
group_size = 16
@@ -24,7 +23,7 @@ max_completion_tokens = 2048
[[orchestrator.train.env]]
taskset = { id = "gsm8k-v1", split = "train" }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 20
@@ -35,7 +34,7 @@ max_completion_tokens = 2048
[[orchestrator.eval.env]]
taskset = { id = "gsm8k-v1", split = "test" }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer] # Default trainer config
+2 -2
View File
@@ -30,7 +30,7 @@ max_inflight_rollouts = 256
[[orchestrator.train.env]]
name = "hendrycks-math"
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
harness = { id = "default", runtime = { type = "modal" } }
harness = { id = "null", runtime = { type = "modal" } }
timeout = { scoring = 300 }
[orchestrator.eval]
@@ -39,7 +39,7 @@ interval = 50
[[orchestrator.eval.env]]
name = "aime2024"
taskset = { id = "aime24-v1" }
harness = { id = "default", runtime = { type = "modal" } }
harness = { id = "null", runtime = { type = "modal" } }
timeout = { scoring = 300 }
group_size = 32
+1 -3
View File
@@ -1,6 +1,4 @@
# v1 port of configs/rlm_swe/qwen35_4b.toml — identical except the env blocks, which load
# the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime instead of the
# v0 `rlm_swe` composable env. Same model / trainer / inference / orchestrator knobs.
# Qwen3.5-4B SWE RL on the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime.
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
max_steps = 400
+1 -2
View File
@@ -14,7 +14,6 @@ name = "v1"
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
@@ -28,7 +27,7 @@ max_completion_tokens = 128
taskset = { id = "reverse-text-v1" }
# reverse-text is a pure-text single-turn env: disable the bash tool (the model answers
# directly) and use the subprocess runtime (no docker).
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
# No eval block, mirroring examples/reverse_text/rl.toml — this is a train-only
# smoke. Add an [orchestrator.eval] block (with an interval) to exercise eval.
-167
View File
@@ -1,167 +0,0 @@
# DeepScaler
This is a reproduction of the [DeepScaleR](https://pretty-radio-b75.notion.site/DeepScaleR-Surpassing-O1-Preview-with-a-1-5B-Model-by-Scaling-RL-19681902c1468005bed8ca303013a4e2) experiments. They use RL to train from `Deepseek-R1-Distill-Qwen-1.5B` to 43.1% on AIME2024, surpassing OpenAI’s o1-preview with just 1.5B parameters.
## Setup
Install the environment using the `prime` CLI.
```bash
prime env install primeintellect/deepscaler
```
Verify that the environment is installed correctly.
```bash
uv run python -c "import deepscaler"
```
## Training
A key insight from the paper is that they train in **stages of increasing context length**. In stages 1, 2 and 3, they train with context lengths of 8192, 16384 and 24576 tokens, respectively. We match their training setup here.
### Stage 1
```bash
bash scripts/tmux.sh -s stage1 -o outputs/stage1
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage1.toml \
--output-dir outputs/stage1
```
### Stage 2
```bash
bash scripts/tmux.sh -s stage2 -o outputs/stage2
```
```bash
mkdir -p outputs/stage2/checkpoints
ln -s outputs/stage1/checkpoints/step_500 outputs/stage2/checkpoints/step_500
mkdir -p outputs/stage2/weights
ln -s outputs/stage1/weights/step_500 outputs/stage2/weights/step_500
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage2.toml \
--output-dir outputs/stage2
```
### Stage 3
```bash
bash scripts/tmux.sh -s stage3 -o outputs/stage3
```
```bash
mkdir -p outputs/stage3/checkpoints
ln -s outputs/stage2/checkpoints/step_1000 outputs/stage3/checkpoints/step_1000
mkdir -p outputs/stage3/weights
ln -s outputs/stage2/weights/step_1000 outputs/stage3/weights/step_1000
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage3.toml \
--output-dir outputs/stage3
```
## Evals
They evaluate on a series of math benchmarks, including Math500, AIME24, AMC23, Minerva Math and Olympiad Math. We will focus on `math500` and `aime2024` for the reproduction, as these are already implemented as evaluation environments on the Environment Hub and also the most prominent benchmarks. We uploaded the weight checkpoints to HF as `DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX` and evaluate the base model and each checkpoint.
![Evals](eval.png)
| Model | AIME 2024 | MATH 500 |
|-------|-----------|----------|
| DeepSeek-R1-Distill-Qwen-1.5B | 27.3% (16389±10200) | 81.4% (5450±7327) |
| DeepScaleR-100 | 30.8% (14510±9591) | 83.4% (4694±6311) |
| DeepScaleR-200 | 28.3% (11929±8630) | 83.2% (3610±4774) |
| DeepScaleR-300 | 30.6% (9898±7050) | 84.2% (3270±4027) |
| DeepScaleR-400 | 30.6% (9726±7077) | 83.6% (3283±4024) |
| DeepScaleR-500 | 33.1% (9686±6563) | 84.0% (3081±3438) |
| DeepScaleR-600 | 32.7% (9726±6222) | 86.6% (3205±3167) |
| DeepScaleR-700 | 32.5% (10162±5887) | 87.8% (3569±3953) |
| DeepScaleR-800 | 33.8% (10666±6032) | 85.4% (3835±3727) |
| DeepScaleR-900 | 28.3% (13375±6546) | 80.8% (5480±5887) |
| O1-Preview | 40.0% (N/A) | 81.4% (N/A) |
Start the inference server
```bash
bash scripts/tmux.sh
```
```bash
# Run this in the `Inference` pane
uv run inference --model.name ... --max-model-len 32768
```
*Note: The model checkpoints are uploaded to `mikasenghaas/DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX`.*
```bash
uv run eval @ configs/deepscaler/eval.toml --model.name ...
```
<details>
<summary>Raw results</summary>
<pre><code>
Base Model
Evaluated math500 in 1547.25s (Avg@1=0.8140, Pass@1: 0.8140, Completion Length: 5450.29 (±7327.93, ∈[266.00, 32734.00]), Truncated: 3.8%)
Evaluated aime2024 in 1546.06s (Avg@16=0.2729, Pass@8: 0.6130, Completion Length: 16389.57 (±10200.73, ∈[1643.00, 32699.00]), Truncated: 15.2%)
Step 100 (Stage 1)
Evaluated math500 in 1280.38s (Avg@1=0.8340, Pass@1: 0.8340, Completion Length: 4694.13 (±6311.37, ∈[225.00, 32729.00]), Truncated: 2.2%)
Evaluated aime2024 in 1279.09s (Avg@16=0.3083, Pass@8: 0.6363, Completion Length: 14510.24 (±9591.44, ∈[1606.00, 32696.00]), Truncated: 10.4%)
Step 200 (Stage 1)
Evaluated math500 in 942.63s (Avg@1=0.8320, Pass@1: 0.8320, Completion Length: 3610.20 (±4774.83, ∈[404.00, 32649.00]), Truncated: 0.8%)
Evaluated aime2024 in 942.34s (Avg@16=0.2833, Pass@8: 0.6043, Completion Length: 11929.71 (±8630.59, ∈[1770.00, 32701.00]), Truncated: 6.7%)
Step 300 (Stage 1)
Evaluated math500 in 737.77s (Avg@1=0.8420, Pass@1: 0.8420, Completion Length: 3270.25 (±4027.97, ∈[415.00, 32732.00]), Truncated: 0.4%)
Evaluated aime2024 in 736.54s (Avg@16=0.3063, Pass@8: 0.6350, Completion Length: 9898.05 (±7050.03, ∈[1606.00, 32696.00]), Truncated: 3.5%)
Step 400 (Stage 1)
Evaluated math500 in 727.78s (Avg@1=0.8360, Pass@1: 0.8360, Completion Length: 3283.45 (±4024.46, ∈[282.00, 32721.00]), Truncated: 0.4%)
Evaluated aime2024 in 726.83s (Avg@16=0.3063, Pass@8: 0.6567, Completion Length: 9726.12 (±7077.99, ∈[1266.00, 32686.00]), Truncated: 3.3%)
Step 500 (Stage 1)
Evaluated math500 in 660.66s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 2961.01 (±3426.75, ∈[543.00, 32695.00]), Truncated: 0.6%)
Evaluated aime2024 in 658.95s (Avg@16=0.3000, Pass@8: 0.6460, Completion Length: 9121.69 (±6423.23, ∈[1323.00, 32687.00]), Truncated: 3.1%)
Step 500 (Stage 2)
Evaluated math500 in 370.32s (Avg@1=0.8400, Pass@1: 0.8400, Completion Length: 3081.88 (±3438.49, ∈[614.00, 32709.00]), Truncated: 0.4%)
Evaluated aime2024 in 368.68s (Avg@16=0.3312, Pass@8: 0.6287, Completion Length: 9686.62 (±6563.93, ∈[1140.00, 32686.00]), Truncated: 2.5%)
Step 600 (Stage 2)
Evaluated math500 in 334.98s (Avg@1=0.8660, Pass@1: 0.8660, Completion Length: 3205.39 (±3167.25, ∈[554.00, 22164.00]), Truncated: 0.0%)
Evaluated aime2024 in 354.83s (Avg@16=0.3271, Pass@8: 0.6353, Completion Length: 9726.84 (±6222.77, ∈[1162.00, 32683.00]), Truncated: 1.9%)
Step 700 (Stage 2)
Evaluated math500 in 377.43s (Avg@1=0.8780, Pass@1: 0.8780, Completion Length: 3569.39 (±3953.57, ∈[618.00, 32611.00]), Truncated: 0.4%)
Evaluated aime2024 in 375.57s (Avg@16=0.3250, Pass@8: 0.6550, Completion Length: 10162.39 (±5887.47, ∈[1428.00, 32672.00]), Truncated: 1.5%)
Step 800 (Stage 2)
Evaluated math500 in 400.01s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 3835.00 (±3727.86, ∈[563.00, 23701.00]), Truncated: 0.0%)
Evaluated aime2024 in 398.19s (Avg@16=0.3375, Pass@8: 0.6860, Completion Length: 10666.42 (±6032.30, ∈[1898.00, 32686.00]), Truncated: 1.0%)
Step 850 (Stage 2)
Evaluated math500 in 445.40s (Avg@1=0.8640, Pass@1: 0.8640, Completion Length: 4216.45 (±4022.84, ∈[611.00, 23277.00]), Truncated: 0.0%)
Evaluated aime2024 in 446.29s (Avg@16=0.3250, Pass@8: 0.6350, Completion Length: 11313.77 (±5997.51, ∈[1695.00, 32686.00]), Truncated: 1.9%)
Step 900 (Stage 2)
Evaluated math500 in 564.56s (Avg@1=0.8080, Pass@1: 0.8080, Completion Length: 5480.47 (±5887.06, ∈[662.00, 32729.00]), Truncated: 1.8%)
SUCCESS Evaluated aime2024 in 562.67s (Avg@16=0.2833, Pass@8: 0.6003, Completion Length: 13375.38 (±6546.80, ∈[1706.00, 32687.00]), Truncated: 4.0%)
Step 950 (Stage 3)
Evaluated math500 in 755.59s (Avg@1=0.7200, Pass@1: 0.7200, Completion Length: 8146.41 (±7986.20, ∈[748.00, 32736.00]), Truncated: 4.6%)
Evaluated aime2024 in 751.49s (Avg@16=0.1833, Pass@8: 0.4207, Completion Length: 16031.10 (±6904.70, ∈[2366.00, 32699.00]), Truncated: 4.8%)
</code>
</pre>
</details>
<br/>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

-39
View File
@@ -1,39 +0,0 @@
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage1"
[ckpt]
interval = 100
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage2"
[ckpt]
interval = 100
resume_step = 500
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 16384
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 1500
seq_len = 24576
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage3"
[ckpt]
interval = 100
resume_step = 1000
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 24576
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+1 -1
View File
@@ -8,7 +8,7 @@ To test the elastic inference pool without having the `rl` entrypoint start the
uv run rl @ examples/alphabet_sort/rl_elastic.toml
```
The config uses `[orchestrator.client.elastic]` with `hostname = "localhost"` and `port = 8000`. The orchestrator will wait for at least one ready server before starting rollouts.
The config uses `[orchestrator.model.client.elastic]` with `hostname = "localhost"` and `port = 8000`. The orchestrator will wait for at least one ready server before starting rollouts.
2. **Start the inference server manually** (in a separate terminal or on another machine):
+1 -1
View File
@@ -35,7 +35,7 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[orchestrator.client.elastic]
[orchestrator.model.client.elastic]
hostname = "localhost"
port = 8000
sync_interval = 5.0
-18
View File
@@ -1,18 +0,0 @@
# math-python
## Setup
Install the environment as local packages
```bash
uv pip install -e ~/research-environments/environments/math_env
uv pip install -e ~/research-environments/environments/code_env
uv pip install -e ~/research-environments/environments/science_env
uv pip install -e ~/research-environments/environments/logic_env
```
## RL
```bash
uv run --no-sync rl @ configs/env_mix/env_mix.toml --log.level debug
```
-52
View File
@@ -1,52 +0,0 @@
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "env-mix-debug"
name = "env-mix"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
id = "math-env"
name = "math"
args = { min_avg_reward = 0.1, rubric_max_workers = 128 }
[[orchestrator.train.env]]
id = "code-env"
name = "code"
args = { min_avg_reward = 0.1 }
[[orchestrator.train.env]]
id = "science-env"
name = "science"
args = { min_avg_reward = 0.1, pool_size = 128, rubric_max_workers = 128 }
[[orchestrator.train.env]]
id = "logic-env"
name = "logic"
args = { min_avg_reward = 0.1 }
[[orchestrator.train.env]]
id = "math-env"
name = "math-python"
args = { min_avg_reward = 0.1, sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy", python_tool = true, rubric_max_workers = 128 }
[trainer]
[inference]
api_server_count = 8
gpu_memory_utilization = 0.8
[inference.model]
tool_call_parser = "hermes"
max_model_len = 8192
+137
View File
@@ -0,0 +1,137 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the output-token, input-token, and turns coefficients all
# set to 0.1. Each term is pass_rate-scaled and normalized by the group's own max before the GRPO
# baseline subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
# CPU offload, and skip-gather / skip-optimizer checkpointing. Derived from
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
max_steps = 1000
seq_len = 65536
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/triton-cache-$USER-$SLURM_JOB_ID"
[slurm]
job_name = "glm45air-swe"
project_dir = "."
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
project = "swe-ablations"
name = "glm45air-scaleswe"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
type = "muon"
# --- Orchestrator ---
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.algo]
type = "grpo"
# Linear length penalty at coef 0.1 on all three terms (output tokens, input tokens, turns).
[orchestrator.algo.length_penalty]
num_output_tokens_weight = 0.1
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1" }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
[orchestrator.prime_monitor]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
skip_first_step = false
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
timeout = { rollout = 3600 }
# --- Inference ---
[inference]
gpu_memory_utilization = 0.85
enable_prefix_caching = true
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
[inference.model]
max_model_len = 65536
[inference.parallel]
tp = 8
+50
View File
@@ -0,0 +1,50 @@
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.24.
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
#
# Launch: uv run inference @ configs/glm5.2_16node_llmd/inference.toml
output_dir = "/shared/outputs/glm5.2-16node-llmd"
enable_expert_parallel = true
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[model]
name = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
[vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[kv_cache_offload]
type = "mooncake"
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000
[deployment]
type = "disaggregated"
prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[deployment.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 }
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 }
non_cached_tokens = 128
[slurm]
job_name = "glm5.2-16node-llmd"
partition = "all"
+2 -2
View File
@@ -10,8 +10,8 @@ reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
num_prefill_nodes = 4
num_decode_nodes = 2
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 2
gpus_per_node = 8
[slurm]
+2 -2
View File
@@ -25,7 +25,7 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
[inference] # Default inference config
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
# <think> blocks. Match that with renderer thinking_retention.
[orchestrator.renderer]
name = "auto"
preserve_all_thinking = true
thinking_retention = "all"
+2 -1
View File
@@ -27,7 +27,8 @@ interval = 10
max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
name = "math500"
taskset = { id = "math500-v1" }
num_examples = 30
group_size = 4
-41
View File
@@ -1,41 +0,0 @@
max_steps = 500
[wandb]
project = "math-group-debug"
name = "math-group"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 256
group_size = 8
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
ratio = 0.5
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
ratio = 0.5
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "aime2024"
name = "aime2024"
num_examples = 30
group_size = 4
[trainer.model]
seq_len = 4096
[inference.model]
max_model_len = 2048
+2 -1
View File
@@ -62,7 +62,8 @@ interval = 10
max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
name = "math500"
taskset = { id = "math500-v1" }
num_examples = 30
group_size = 4
+2 -1
View File
@@ -61,7 +61,8 @@ interval = 10
max_completion_tokens = 4096
[[orchestrator.eval.env]]
id = "math500"
name = "math500"
taskset = { id = "math500-v1" }
num_examples = 30
group_size = 4
-97
View File
@@ -1,97 +0,0 @@
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
max_steps = 400
seq_len = 65536
[slurm]
job_name = "rlm-swe-qwen35-4b"
project_dir = "."
pre_run_command = "prime sandbox delete --label rlm-swe-qwen35-4b -y --plain || true"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 2
[wandb]
project = "rlm-swe-debug"
name = "qwen35-4b"
[weight_broadcast]
type = "nccl"
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "Qwen/Qwen3.5-4B"
# --- Trainer ---
[trainer]
[trainer.model]
cp = 4
cp_style = "ulysses"
[trainer.model.ac]
freq = 1
[trainer.model.compile]
# --- Orchestrator ---
[orchestrator]
batch_size = 256
group_size = 8
max_inflight_rollouts = 512
max_off_policy_steps = 16
# Thinking enabled for the Qwen3.5 renderer.
[orchestrator.renderer]
name = "qwen3.5"
enable_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
[[orchestrator.train.env]]
id = "rlm_swe"
name = "rlm-swe-r2e"
[orchestrator.train.env.args]
labels = ["rlm-swe-qwen35-4b"]
[orchestrator.prime_monitor]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
id = "rlm_swe"
name = "rlm-swe-swebench-verified-quick"
timeout = { rollout = 3600 }
[orchestrator.eval.env.args]
task_type = "swebench"
dataset_name = "PrimeIntellect/SWE-Bench-Verified-Quick"
labels = ["rlm-swe-qwen35-4b"]
# --- Inference ---
[inference]
gpu_memory_utilization = 0.85
enable_prefix_caching = true
[inference.model]
max_model_len = 65536
[inference.parallel]
dp = 8
# Qwen3.5-4B is a VL model; skip the vision tower for text-only SWE.
# `language_model_only` is a vLLM MultiModalConfig arg (no prime-rl field) → pass via vllm_extra.
[inference.vllm_extra]
language_model_only = true
+2 -2
View File
@@ -35,7 +35,7 @@ max_completion_tokens = 1024
# Qwen3 finetune with the standard PI template patch (byte-identical to
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
# Match that with the qwen3 renderer's preserve_all_thinking.
# Match that with renderer thinking_retention.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
thinking_retention = "all"
+1 -1
+1 -1
+4 -2
View File
@@ -139,9 +139,11 @@ curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
If prefill queues and decode is idle, add prefill nodes (and vice versa).
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. If your cluster doesn't ship with UCX >=1.19, you can build it from source with the following command:
**Required setup for disaggregated P/D (NIXL/UCX).** The pip-wheel NIXL's bundled UCX segfaults on the prefill→decode KV transfer (`signal 11: invalid permissions for mapped object` in `libucs.so`) — reproduced on vLLM 0.22 and 0.23, with/without mooncake, with/without llm-d. Building NIXL against UCX 1.19.x from source is therefore **required** (not optional) for disaggregated P/D.
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version.
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
+201 -102
View File
@@ -1,25 +1,151 @@
# Algorithms
This page covers the math and the configurable algorithmic components: how off-policy training works, the default loss and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
## Table of Contents
- [The Algorithm Abstraction](#the-algorithm-abstraction)
- [Model References](#model-references)
- [The Algorithms](#the-algorithms)
- [Customizing Components](#customizing-components)
- [Per-Env Algorithms](#per-env-algorithms)
- [The Algorithm Classes](#the-algorithm-classes)
- [Async / Off-Policy Training](#async--off-policy-training)
- [Loss](#loss)
- [Default Loss](#default-loss)
- [Loss Components](#loss-components)
- [Default RL Loss](#default-rl-loss)
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Custom Advantage](#custom-advantage)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
- [Difficulty Pools](#difficulty-pools)
- [Online Difficulty Filtering](#online-difficulty-filtering)
- [Multi-Turn Trajectories](#multi-turn-trajectories)
- [Extension Property](#extension-property)
- [Best-Effort Interleaving](#best-effort-interleaving)
- [Renderers](#renderers)
- [Discontinuous Trajectories](#discontinuous-trajectories)
## The Algorithm Abstraction
A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
### Model References
`prime-rl` hosts exactly one model: the trainable policy (`[orchestrator.model]`). Every other model an algorithm uses is an external OpenAI-compatible endpoint, declared *inline on the component that uses it*. A model reference is either the string `"policy"` (the live policy) or a frozen hosted model (`name` + `base_url`):
```toml
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = ["http://localhost:8001/v1"]
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
So for `opd` set `[orchestrator.algo.teacher]`; for `sft` set `[orchestrator.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
Liveness is a property of the reference, not of any role: rollouts sampled from `"policy"` get version-salted prefix caches, carry sampling logprobs for importance ratios, and age off-policy as weights update; rollouts and scores from frozen models get a stable prefix cache and never go stale. Frozen models are externally hosted (`base_url` is required) — `prime-rl` never launches or updates them, and each env's algorithm builds its own client pool to the endpoints it declares.
### The Algorithms
The `algo.type` names the algorithm, and each type's class defaults are its vetted setting — picking a type with no other keys IS the algorithm:
```toml
[orchestrator.algo]
type = "grpo" # the default
```
| `type` | Sampling | Loss | What it is |
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
| `echo` | policy | `rl` on actions + weighted `ce` on observations | ECHO: standard GRPO plus a cross-entropy loss on env-provided tokens already present in the rollout, selected by message role (needs the renderer's role attribution). Defaults to tool-response bodies at `alpha = 0.1` (ECHO's λ); set `roles` to train other roles, each at its own weight. |
### Customizing Components
Every key beyond `type` is visibly your own assembly — there is no preset layer to diverge from. The vetted setting is the class defaults; what you set is what runs:
```toml
# echo on tool AND user feedback tokens, each at its own weight.
# Setting any role replaces the whole table.
[orchestrator.algo]
type = "echo"
[orchestrator.algo.roles.tool]
alpha = 0.25
[orchestrator.algo.roles.user]
alpha = 0.05
```
A new algorithm is a named class in code, not a config that points at an import path — see [Authoring an Algorithm](#authoring-an-algorithm).
Echo also takes an optional user-supplied token filter that narrows the role selection per rollout — e.g. dropping warning lines from tool output, or tokens the sampler found unlikely:
```toml
[orchestrator.algo.filter]
import_path = "my_module.drop_warnings"
kwargs = { patterns = ["WARNING"] }
```
```python
# my_module.py — sees the raw rollout (message text, sampling logprobs);
# returns one keep-mask per trainable branch, spanning that branch's
# token_ids. False = never echo-trained.
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
### Per-Env Algorithms
Both components resolve per environment. Each env inherits `[orchestrator.algo]` unless it sets its own, so a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
```toml
[orchestrator.algo]
type = "grpo"
[[orchestrator.train.env]]
id = "math-env" # inherits grpo
[[orchestrator.train.env]]
id = "terminal-env"
algo = { type = "echo" } # this env runs its own algorithm
```
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
- `score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
## Async / Off-Policy Training
`prime-rl` is asynchronous by default. The trainer and inference always run one step overlapped: while the trainer is producing $\pi_n$ from rollouts at step $n$, inference is already generating the rollouts for step $n+1$ using $\pi_{n-1}$. With matched trainer and inference step times this produces fully-overlapped pipeline parallelism — neither side ever idles.
@@ -31,11 +157,25 @@ At step $n = 1, 2, 3, \dots$:
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
Step indices are 1-indexed; policy versions are 0-indexed, with $\pi_0$ the base model. At step 1 inference samples from $\pi_0$.
## Loss
### Default Loss
### Loss Components
The training loss is a **sum of three components**, each with its own per-token weight stream and its own normalization:
$$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### Default RL Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
@@ -66,20 +206,14 @@ The knobs (under `[trainer.loss]` with `type = "default"`):
| Knob | Default | What it does |
|---|---|---|
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 for pure distillation (no RL signal). |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
The trainer dispatches automatically based on the batch's training mode (set by the orchestrator via `orchestrator.training_mode`):
- `rl` mode → DPPO + KL with the advantage signal.
- `opd` mode → KL distillation against the teacher's per-token logprobs. The teacher must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
- `sft` mode → standard token-level NLL on teacher-generated rollouts.
Set `[trainer.loss] type = "default"` and configure via the knobs above. SFT and OPD modes ignore the policy-gradient–specific fields.
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
### Custom Loss
The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates.
`[trainer.loss] type = "custom"` replaces the `rl` component. The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates. `inputs.loss_mask` selects exactly the rl member tokens (for a plain GRPO run, all trainable tokens).
```python
# my_module.py
@@ -116,9 +250,10 @@ The dataclasses:
class LossInputs:
trainer_logprobs: Float[Tensor, "seq"] # current policy
inference_logprobs: Float[Tensor, "seq"] # rollout-time policy
teacher_logprobs: Float[Tensor, "seq"] | None # only set in OPD mode
ref_logprobs: Float[Tensor, "seq"] | None # set by reference-scoring algorithms
advantages: Float[Tensor, "seq"]
loss_mask: Bool[Tensor, "seq"]
loss_mask: Bool[Tensor, "seq"] # this component's member tokens
loss_weights: Float[Tensor, "seq"] | None # the component's weight stream (None = 1.0)
@dataclass
class LossOutputs:
@@ -130,68 +265,71 @@ Anything you put in `metrics` is averaged across sequences and logged with the o
## Advantage
The per-token training signal is set by `algo.type` and the [algorithm](#the-algorithm-abstraction)'s parameters — every signal is a per-token advantage stream, varying in evaluation site (orchestrator vs. trainer). The `algo.type` values:
| Type | Component | Effect |
|---|---|---|
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`model`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
### Default Advantage
The default advantage is per-group reward minus per-group baseline (DR-GRPO without std normalization). For each prompt's group of `group_size` rollouts, every token in rollout $i$ receives advantage $s_i - \bar{s}$ where $\bar{s}$ is the group mean.
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
This is intentionally simple — it does the right thing for most envs. Write a named algorithm class when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …) — see [Authoring an Algorithm](#authoring-an-algorithm).
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
```toml
[orchestrator.advantage.length_penalty]
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
```
[orchestrator.algo]
type = "grpo"
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
```toml
[orchestrator.advantage]
length_weighted_baseline = true
[orchestrator.algo.length_penalty]
type = "linear"
```
### Custom Advantage
### Authoring an Algorithm
Advantages are computed **per group**. You write a function that takes one group of rollouts and returns one advantage scalar per rollout. The orchestrator handles groups of varying size automatically — partial-group training kicks in when some rollouts in a group errored.
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
```python
# my_module.py
import statistics
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
# src/prime_rl/orchestrator/algo/my_algo.py
import torch
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
rewards = [r["reward"] for r in inputs.rollouts]
mean = statistics.fmean(rewards)
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
from prime_rl.orchestrator.algo.base import Algorithm
class MyAlgorithm(Algorithm):
async def score_group(self, group):
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
advantages = ... # one value per rollout
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
```
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
### Reference Scoring
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
```toml
[orchestrator.advantage]
type = "custom"
import_path = "my_module.normalized_advantage"
kwargs = { eps = 1e-8 }
[orchestrator.algo]
type = "opsd"
demo_key = "demonstration"
```
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
### Per-Env Advantage
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
```toml
[orchestrator.advantage]
type = "default" # the default every env inherits unless it overrides
[[orchestrator.train.env]]
id = "math-env" # inherits the default above
[[orchestrator.train.env]]
id = "agent-env"
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
```
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
## Filters
@@ -203,58 +341,19 @@ Filters drop rollouts between scoring and training. Built-ins (composable):
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
The default `[orchestrator]` config already includes all three filters with their defaults. To override, set `filters` explicitly — the list replaces the defaults wholesale:
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters` enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
```toml
[[orchestrator.filters]]
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
[[orchestrator.filters]]
[[orchestrator.post_batch_filters]]
type = "repetition"
threshold = 0.4
```
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Difficulty Pools
Difficulty pools gradually retire problems the model has solved or never solves. After each rollout, the average reward across a problem's group is compared to two thresholds:
- `buffer.easy_threshold` — at or above this, the problem moves into the `easy` pool and is no longer sampled.
- `buffer.hard_threshold` — at or below this, the problem moves into the `hard` pool and is no longer sampled.
- Otherwise the problem stays in `normal` and remains in the sampling rotation.
Pool assignments persist across checkpoints (`easy_examples.jsonl` / `hard_examples.jsonl` under each step's orchestrator checkpoint). When you resume — or want to broaden the curriculum mid-run — `buffer.easy_fraction` / `buffer.hard_fraction` randomly lift that fraction of pooled problems back into `normal` so they re-enter sampling.
```toml
[orchestrator.buffer]
easy_threshold = 0.95
hard_threshold = 0.05
easy_fraction = 0.0 # default; bump on resume to bring some easy problems back
hard_fraction = 0.0 # default; bump on resume to bring some hard problems back
```
Watch `pool/{env}/{easy,normal,hard}` (current pool ratios) and `evicted_examples/{env}/{easy,hard}` (per-step eviction rate).
## Online Difficulty Filtering
Online difficulty filtering (ODF) drops collapsed-advantage groups on the way *into* the buffer. Set `buffer.online_difficulty_filtering = true` (default `false`) to enable:
- Average reward across the group is **0.0** (every rollout failed) → drop the group, count under `filtered_rollouts/{env}/hard`.
- Average reward **1.0** (every rollout succeeded) → drop, count under `filtered_rollouts/{env}/easy`.
- Otherwise → into the buffer.
These are exactly the groups whose within-group advantage collapses to zero — DR-GRPO produces no gradient signal for them, so the trainer would burn step time on tokens it can't learn from.
```toml
[orchestrator.buffer]
online_difficulty_filtering = true
```
**Tradeoff: trainer stability vs. inference speed.** With ODF on, every rollout that reaches the trainer carries non-zero advantage — each trainer step's effective batch is predictable and the gradient signal is denser. The cost is paid on the inference side: rollouts get produced and then thrown away, so the orchestrator has to oversample to keep the trainer fed. If the orchestrator is your bottleneck (`time/wait_for_batch` high on the trainer), ODF can starve the loop. Bump `orchestrator.oversampling_factor` so inference produces enough groups per step to absorb the drops.
ODF is orthogonal to the [pools](#difficulty-pools): ODF reacts to the *current* group's reward distribution, the pools track the *running* per-problem average. Many configs use both — ODF for per-step density, pools for long-horizon curriculum cleanup.
## Multi-Turn Trajectories
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
+39 -2
View File
@@ -17,7 +17,8 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
- [Optional Sub-Configs](#optional-sub-configs)
- [None](#none)
- [Discriminated Unions](#discriminated-unions)
- [Environments (`[[orchestrator.train.env]]`)](#environments-orchestratortrainenv)
- [Environments](#environments-orchestratortrainenv)
- [Environment Variables](#environment-variables)
- [Examples](#examples)
## Sources and Precedence
@@ -150,10 +151,11 @@ Training environments are an array of tables — set one per env, optionally wit
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
ratio = 3 # 75% of batches
[[orchestrator.train.env]]
id = "reverse-text"
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
ratio = 1 # default — 25% of batches
[[orchestrator.eval.env]]
id = "math-env"
@@ -161,10 +163,45 @@ name = "gsm8k-eval"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
### Environment Variables
OS environment variables exported into launched component process(es). In `rl` configs, top-level `[env_vars]` applies to trainer, inference, and orchestrator:
```toml
[env_vars]
HF_HUB_OFFLINE = "1"
TOKENIZERS_PARALLELISM = "false"
```
Component-specific tables layer on top:
```toml
[trainer.env_vars]
NCCL_DEBUG = "INFO"
PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:False"
[inference.env_vars]
VLLM_USE_DEEP_GEMM = "1"
[orchestrator.env_vars]
PI_USAGE_BASE_URL = "https://..."
```
The `rl` launcher applies these the same way in both single-node and multi-node (SLURM) runs. Precedence, low to high:
1. The launcher's own defaults — **your `env_vars` override these**.
2. Your top-level `[env_vars]`.
3. Your `[component.env_vars]`.
4. Orchestration-critical vars the launcher always sets last — `CUDA_VISIBLE_DEVICES` (GPU partitioning) and `WANDB_SHARED_*` (the single shared W&B run) — **these cannot be overridden** from `env_vars`.
For standalone `sft` and `inference` configs, `[env_vars]` applies to that entrypoint's process(es). For disaggregated P/D inference, the role-specific [`deployment.{prefill,decode}_env_vars`](inference.md) layer on top of any shared inference env vars.
## Examples
The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) are the canonical, kept-up-to-date references — the rest of the repo's TOMLs (under `configs/`) are CI- and debug-internal and may drift. Each example directory has its own README with the full launch story.
+17 -15
View File
@@ -128,41 +128,39 @@ This configuration will run 2 vLLM processes, each with `data_parallel_size_loca
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and choosing how many nodes each prefill and decode replica spans.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
prefill_nodes_per_replica = 2
decode_nodes_per_replica = 2
```
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode stages. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of role replicas you want to run.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
prefill_nodes_per_replica = 2
num_prefill_replicas = 2
decode_nodes_per_replica = 2
num_decode_replicas = 1
```
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
Now each prefill replica spans 2 nodes and each decode replica spans 2 nodes. With 2 prefill replicas and 1 decode replica, one inference island spans 6 nodes.
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
For RL runs, the top-level deployment can multiply that whole inference island by setting `deployment.num_infer_replicas`. `deployment.num_infer_nodes` is inferred from the nested inference deployment when you omit it.
```toml
[deployment] # this is a top-level RL deployment, not inference.deployment!!
type = "multi_node"
num_train_nodes = 4
num_infer_nodes = 6 # this is per-replica
num_infer_replicas = 3
```
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
## Router
@@ -189,12 +187,12 @@ Both backends support the 2 most important things:
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.student.client.extra_headers_from_state` to the header the `router` expects to be set.
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.student.client.extra_headers_from_state]
[orchestrator.model.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
@@ -245,16 +243,20 @@ For optimal P/D disaggregation deployment, we automatically set the decode `all2
For KV cache transfer, we utilize the NIXL connector. This is the default and only currently supported connector. We aim to support more advanced options, such as D->P transfer, or Mooncake Connector in the future.
> **Required:** The pip-wheel NIXL's bundled UCX segfaults on the prefill→decode KV transfer. You must build NIXL against UCX 1.19.x from source — see [Disaggregated Prefill/Decode Inference](advanced.md#disaggregated-prefilldecode-inference) in the Advanced docs for the full setup.
For configuring various knobs with environment variables, we enable you to configure prefill and decode environment variables separately. This is useful if you want to configure different environment variables for the prefill and decode stages.
```toml
[inference.deployment]
type = "disaggregated"
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
```
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
+20 -31
View File
@@ -41,7 +41,7 @@ uv run rl @ rl.toml \
--inference.parallel.dp 6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next, teacher last. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
@@ -54,7 +54,7 @@ CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
bash scripts/tmux.sh -s exp2 -o outputs/exp2
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.client.base-url http://localhost:8001/v1 \
--orchestrator.model.client.base-url http://localhost:8001/v1 \
--output-dir outputs/exp2
```
@@ -92,10 +92,12 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
```toml
[trainer.model]
impl = "custom"
ep = 8 # EP degree; must divide num_experts
ep = 8 # explicit EP degree; must divide num_experts
ep_comm_backend = "torch" # or "deepep"
```
@@ -121,7 +123,7 @@ cp_style = "ulysses" # "ring"
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
Enable selective AC (custom impl only) for the best memory/throughput tradeoff:
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
```toml
[trainer.model.ac]
@@ -129,55 +131,40 @@ mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput:
```toml
[trainer.model.ac_offloading]
max_inflight_activations = 5
```
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
### Optimizer Offloading
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = true`) — a near-free memory win at low GPU counts:
```toml
[trainer.optim]
# any optimizer type
type = "adamw"
[trainer.model]
optim_cpu_offload = true
optim_cpu_offload = true # already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training). Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
### LM Head Chunking
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization:
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
```toml
[trainer.model]
fused_lm_head_token_chunk_size = "auto" # picks 8192 for RL
# or explicit:
# fused_lm_head_token_chunk_size = 1024 # smaller = lower memory, more launches
# fused_lm_head_token_chunk_size = "disabled" # default; vanilla LM head
fused_lm_head_token_chunk_size = 1024 # default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
`auto` is a safe starting point for RL. Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. Only available with `model.impl = "custom"`, and currently RL-only — the SFT trainer rejects integer values.
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
## Memory-Tight Recipe
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput:
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput. AC, AC offloading, compile, fused LM head chunking, optimizer offload, and EP auto-resolution are on by default — only CP needs to be set explicitly (and EP overridden if auto-resolution is not desired):
```toml
[trainer.model]
impl = "custom"
fused_lm_head_token_chunk_size = 1024
ep = 8
cp = 2
optim_cpu_offload = true
[trainer.model.compile]
[trainer.model.ac]
freq = 1
@@ -186,12 +173,14 @@ freq = 1
max_inflight_activations = 1
```
Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
## SLURM
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
### Activation
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
@@ -219,7 +208,7 @@ uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
num_infer_nodes = 1 # optional when inference.deployment defines the node topology
gpus_per_node = 8 # default
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
```
@@ -237,7 +226,7 @@ gpus_per_node = 8
Full multi-node configs ship in [`examples/multinode/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/multinode):
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE student.
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE policy.
- [`sft.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/sft.toml) — two-node SFT against the same model.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
+21 -14
View File
@@ -1,6 +1,6 @@
# Training
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer, the SFT trainer, and the related on-policy distillation mode. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
@@ -10,7 +10,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
- [RL Trainer](#rl-trainer)
- [Launch](#launch)
- [Useful Knobs](#useful-knobs)
- [Training Modes (RL / OPD / SFT)](#training-modes-rl--opd--sft)
- [Algorithms](#algorithms)
- [Important Metrics](#important-metrics)
- [SFT Trainer](#sft-trainer)
- [Dataset Format](#dataset-format)
@@ -59,7 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `orchestrator.training_mode` | `rl` (default), `opd`, or `sft`. See [Training modes](#training-modes-rl--opd--sft). |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -81,24 +81,29 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Training Modes (RL / OPD / SFT)
### Algorithms
The RL entrypoint supports three training modes, switched via `orchestrator.training_mode`:
The RL entrypoint supports several training algorithms, switched via `[orchestrator.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
| Mode | Student | Teacher | Use case |
|---|---|---|---|
| `rl` | Required | Forbidden | Standard RL |
| `opd` | Required | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): student generates rollouts, trainer minimizes KL to teacher logprobs |
| `sft` | Required | Required, any OpenAI-compatible endpoint | Hard-distill: teacher generates rollouts, student trains on them |
| `algo.type` | Frozen model | Use case |
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
| `echo` | None | GRPO plus cross-entropy on env-observation tokens |
The `rl` entrypoint only manages student-policy inference. For OPD and (local-vLLM) SFT, start the teacher inference server manually and point `[orchestrator.teacher.client]` at it:
A new algorithm is a named class in code, not a config — see [Algorithms § Authoring an Algorithm](algorithms.md#authoring-an-algorithm).
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name <teacher> --server.port 8001
--model.name <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no teacher, no orchestrator. Use `orchestrator.training_mode = "sft"` only when you want a teacher to generate the supervision on the fly.
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
### Important Metrics
@@ -221,7 +226,7 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
```bash
# First run: steps 0–10
# First run: steps 1–10
uv run rl @ rl.toml --max-steps 10 --ckpt
# Resume: continue to step 20
@@ -302,6 +307,8 @@ uv run rl @ rl.toml --wandb \
--no-trainer.wandb.log-extras.distributions
```
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### Platform Monitoring
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
-18
View File
@@ -58,21 +58,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
```bash
uv run rl @ examples/Intellect-3.1/rl.toml --output-dir /shared/outputs/intellect-3.1
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/intellect-3.1/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/intellect-3.1/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/intellect-3.1/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/intellect-3.1/logs/trainer.log
Orchestrator: tail -F /shared/outputs/intellect-3.1/logs/orchestrator.log
Inference: tail -F /shared/outputs/intellect-3.1/logs/inference.log
Envs: tail -F /shared/outputs/intellect-3.1/logs/envs/*/*/*.log
Train: tail -F /shared/outputs/intellect-3.1/logs/envs/train/*/*.log
swe: tail -F /shared/outputs/intellect-3.1/logs/envs/train/swe/*.log
```
-14
View File
@@ -71,17 +71,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
```bash
uv run rl @ examples/glm5_llmd/rl.toml --output-dir /shared/outputs/glm5-llmd
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-llmd/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-llmd/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-llmd/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/glm5-llmd/logs/trainer.log
Orchestrator: tail -F /shared/outputs/glm5-llmd/logs/orchestrator.log
Inference: tail -F /shared/outputs/glm5-llmd/logs/inference.log
Envs: tail -F /shared/outputs/glm5-llmd/logs/envs/*/*/*.log
```
+5 -16
View File
@@ -31,8 +31,8 @@ num_decode_nodes = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
@@ -88,7 +88,7 @@ name = "zai-org/GLM-5.1-FP8"
[orchestrator.renderer]
name = "glm-5.1"
preserve_all_thinking = true
clear_thinking = false
[orchestrator.train.sampling]
temperature = 1.0
@@ -96,20 +96,9 @@ extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.env]]
id = "rlm_swe"
name = "r2e"
num_workers = 16
[orchestrator.train.env.args]
max_turns = 300
timeout_seconds = 21600
summarize_at_tokens = [35000, 80000]
poll_interval = 5
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
labels = ["glm5-llmd"]
[orchestrator.advantage]
type = "default"
taskset = { id = "r2e-gym-v1" }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
[inference]
enable_expert_parallel = true
-18
View File
@@ -54,21 +54,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
```bash
uv run rl @ examples/glm5_pd_disag/rl.toml --output-dir /shared/outputs/glm5-pd-disag
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-pd-disag/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-pd-disag/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-pd-disag/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/glm5-pd-disag/logs/trainer.log
Orchestrator: tail -F /shared/outputs/glm5-pd-disag/logs/orchestrator.log
Inference: tail -F /shared/outputs/glm5-pd-disag/logs/inference.log
Envs: tail -F /shared/outputs/glm5-pd-disag/logs/envs/*/*/*.log
Train: tail -F /shared/outputs/glm5-pd-disag/logs/envs/train/*/*.log
swe: tail -F /shared/outputs/glm5-pd-disag/logs/envs/train/swe/*.log
```
+1 -1
View File
@@ -66,7 +66,7 @@ group_size = 16
oversampling_factor = 3
max_off_policy_steps = 16
[orchestrator.student.model]
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
-18
View File
@@ -54,21 +54,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
```bash
uv run rl @ examples/minimax_m2.5_swe/rl.toml --output-dir /shared/outputs/minimax-swe
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/minimax-swe/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/minimax-swe/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/minimax-swe/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/minimax-swe/logs/trainer.log
Orchestrator: tail -F /shared/outputs/minimax-swe/logs/orchestrator.log
Inference: tail -F /shared/outputs/minimax-swe/logs/inference.log
Envs: tail -F /shared/outputs/minimax-swe/logs/envs/*/*/*.log
Train: tail -F /shared/outputs/minimax-swe/logs/envs/train/*/*.log
swe: tail -F /shared/outputs/minimax-swe/logs/envs/train/swe/*.log
```
-18
View File
@@ -46,21 +46,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
```bash
uv run rl @ examples/qwen30b_math/rl.toml --output-dir /shared/outputs/qwen30b-math
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/qwen30b-math/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/qwen30b-math/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/qwen30b-math/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/qwen30b-math/logs/trainer.log
Orchestrator: tail -F /shared/outputs/qwen30b-math/logs/orchestrator.log
Inference: tail -F /shared/outputs/qwen30b-math/logs/inference.log
Envs: tail -F /shared/outputs/qwen30b-math/logs/envs/*/*/*.log
Train: tail -F /shared/outputs/qwen30b-math/logs/envs/train/*/*.log
math: tail -F /shared/outputs/qwen30b-math/logs/envs/train/math/*.log
```
-18
View File
@@ -54,21 +54,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
```bash
uv run rl @ examples/qwen30b_swe/rl.toml --output-dir /shared/outputs/qwen30b-swe
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/qwen30b-swe/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/qwen30b-swe/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/qwen30b-swe/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/qwen30b-swe/logs/trainer.log
Orchestrator: tail -F /shared/outputs/qwen30b-swe/logs/orchestrator.log
Inference: tail -F /shared/outputs/qwen30b-swe/logs/inference.log
Envs: tail -F /shared/outputs/qwen30b-swe/logs/envs/*/*/*.log
Train: tail -F /shared/outputs/qwen30b-swe/logs/envs/train/*/*.log
swe: tail -F /shared/outputs/qwen30b-swe/logs/envs/train/swe/*.log
```
+2 -2
View File
@@ -32,7 +32,7 @@ dp = 6
# Qwen3 finetune with the standard PI template patch (byte-identical to
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
# Match that with the qwen3 renderer's preserve_all_thinking.
# Match that with renderer thinking_retention.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
thinking_retention = "all"
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.8.dev28",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.1.15.dev357",
"verifiers>=0.1.15.dev390",
]
[build-system]
@@ -0,0 +1,324 @@
"""Algorithm abstraction: sampling and the per-token training signal.
An algorithm is a named, self-contained config — a discriminated union keyed
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
The bundle *is* the algorithm: each variant carries
its sampling component and its credit-assignment / loss-routing parameters,
and its class defaults are the vetted setting — ``type = "opd"`` with a
teacher IS on-policy distillation; any key you set is visibly your own
assembly. There is no separate ``advantage`` sub-component and no preset layer.
Each algorithm fixes two things:
1. **Sampling** — which model generates train rollouts. ``sampling.source`` is
a model reference: ``"policy"`` (the live policy) or an inline frozen hosted
model.
2. **The per-token training signal** — credit assignment and loss routing,
fused: one mapping from a finalized rollout to per-token ``(loss component,
weight)``. Group-relative algorithms compute scalars on the orchestrator and
ship numbers; reference-KL algorithms ship reference prefill logprobs and the
trainer evaluates the per-token signal against the live policy. The algorithm
determines which loss component consumes the action tokens (``rl`` / ``ce`` /
``ref_kl``, via the ``action_loss_type`` class declaration) and what happens
to env-provided observation tokens (masked out by default; ``echo`` trains on
them with weighted CE).
prime-rl only ever hosts the trainable policy. Every other model an algorithm
uses is an external OpenAI-compatible endpoint, declared inline on the
algorithm that uses it (a :class:`FrozenModelConfig`). Model roles like
"teacher" are algorithm-local vocabulary over these references; the pipeline
branches on liveness alone. The trainer is algorithm-blind: the loss is a sum
of three components (rl, ce, ref_kl), each normalized by its own global token
count; per-token component weights ship on the wire and the trainer just
executes them.
"""
from typing import Annotated, Any, ClassVar, Literal, TypeAlias
from pydantic import Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.config import BaseConfig
class FrozenModelConfig(ClientConfig):
"""An externally hosted model behind an OpenAI-compatible endpoint: the
client config plus the served model's ``name``.
prime-rl never launches or updates these — only the trainable policy is
ever hosted by prime-rl itself. Frozen models are reachable-but-unmanaged:
``base_url`` is required, their weights never change, and rollouts or
scores from them never go stale (stable prefix cache, no off-policy
aging)."""
name: str
"""Served model name, sent as the ``model`` field of every request."""
@model_validator(mode="after")
def require_explicit_endpoint(self):
if "base_url" not in self.model_fields_set and not self.is_elastic:
raise ValueError(
"a frozen model reference needs base_url — frozen models are externally "
"hosted; prime-rl only ever hosts the trainable policy."
)
return self
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
"""``"policy"`` (the live policy — weight-updated: prefix caches salted per
version, sampling logprobs carried, rollouts age off-policy) or an inline
externally-hosted frozen model."""
ActionLossType: TypeAlias = Literal["rl", "ce", "ref_kl"]
# ---------------------------------------------------------------------------
# Sampling
# ---------------------------------------------------------------------------
class SamplingConfig(BaseConfig):
source: ModelReference = "policy"
"""Model reference for train rollout generation: ``"policy"`` (the live
policy — prefix caches salted per version, sampling logprobs requested,
rollouts age off-policy) or an inline frozen hosted model (stable prefix
cache, no sampling logprobs, rollouts never go stale)."""
# ---------------------------------------------------------------------------
# Shared sub-configs (length penalty, echo roles)
# ---------------------------------------------------------------------------
class LinearLengthPenaltyConfig(BaseConfig):
"""Linear ``pass_rate``-scaled penalty subtracted from each reward before the GRPO baseline — the sum of three terms (completion tokens, input tokens, turns), each normalized by the group's own max for that quantity and disabled by setting its coefficient to 0."""
type: Literal["linear"] = "linear"
num_output_tokens_weight: float = Field(0.25, ge=0, allow_inf_nan=False)
"""Scale on the output-token term. Each reward is reduced by ``num_output_tokens_weight * pass_rate * (rollout num_output_tokens / group's max num_output_tokens)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative; 0 disables the term."""
num_input_tokens_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
"""Scale on the input-token term — tokens the model conditioned on but did not generate (``num_total_tokens - num_output_tokens``: prompts, tool responses), as a fraction of the group's max input tokens. 0 disables the term."""
num_turns_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
"""Scale on the turns term (``pass_rate * (rollout num_turns / group's max num_turns)``). 0 disables the term."""
LengthPenaltyConfig: TypeAlias = LinearLengthPenaltyConfig
class EchoRoleConfig(BaseConfig):
"""Echo CE supervision for one message role."""
alpha: float = Field(0.1, gt=0)
"""Per-token ce weight for this role's env-provided tokens (ECHO's lambda)."""
class EchoRolesConfig(BaseConfig):
"""Which env-provided message roles train, each at its own weight.
Setting any role replaces the whole table — unset roles stay disabled."""
system: EchoRoleConfig | None = None
user: EchoRoleConfig | None = None
assistant: EchoRoleConfig | None = None
tool: EchoRoleConfig | None = None
@model_validator(mode="after")
def require_a_role(self):
if self.system is None and self.user is None and self.assistant is None and self.tool is None:
raise ValueError("echo needs at least one role enabled (system, user, assistant, or tool)")
return self
class EchoFilterConfig(BaseConfig):
"""User-supplied per-token filter narrowing the role-selected echo tokens.
The callable is imported at startup and invoked once per rollout as
``filter_fn(rollout, **kwargs) -> list[list[bool]]`` — one keep-mask per
trainable branch, each spanning that branch's ``token_ids``. Tokens with
``False`` never receive echo weight; the
filter can only narrow the role selection, not widen it. The raw rollout
exposes message text and sampling logprobs, so content filters (e.g.
dropping tool-output warnings) and sampling-probability filters need no
extra framework surface."""
import_path: str
"""Import path to the filter callable (e.g. ``my_module.drop_warnings``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the filter."""
# ---------------------------------------------------------------------------
# The algorithms (a discriminated union keyed on ``type``)
# ---------------------------------------------------------------------------
class BaseAlgoConfig(BaseConfig):
"""Base for every algorithm: the shared sampling component and the
cross-cutting source/loss compatibility check. Each subclass sets ``type``
(the discriminator), declares its loss routing (``action_loss_type``), and
adds its own parameters — including any reference model it needs, named
where that model is actually used (opd scores against a frozen ``teacher``;
sft samples from its ``sampling.source``; opsd self-distills against the
live policy and names no model).
The bundle IS the algorithm — there is no separate ``advantage``
sub-component. ``algo.type`` names it, and the class defaults are the
vetted setting."""
action_loss_type: ClassVar[ActionLossType] = "rl"
sampling: SamplingConfig = SamplingConfig()
"""Sampling component: which model generates train rollouts."""
@model_validator(mode="after")
def validate_sampling_source(self):
"""The on-policy loss types (rl, ref_kl) need the live policy's own
sampling logprobs, so they must sample from ``"policy"``; only sft (ce)
may sample from a frozen model."""
if self.action_loss_type in ("rl", "ref_kl") and self.sampling.source != "policy":
raise ValueError(
f"algorithm '{self.type}' trains with the "
f"{self.action_loss_type} loss type but sampling.source is a frozen model — "
"the importance ratio and trust region need the live policy's own sampling logprobs. "
"Use the 'sft' algorithm to distill frozen-model tokens."
)
return self
class GRPOAlgoConfig(BaseAlgoConfig):
type: Literal["grpo"] = "grpo"
"""GRPO: scalar advantage = reward minus the per-group mean baseline,
consumed by the ``rl`` loss component on the rollout's action tokens."""
action_loss_type: ClassVar[ActionLossType] = "rl"
length_penalty: LengthPenaltyConfig | None = None
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
class EchoAlgoConfig(GRPOAlgoConfig):
type: Literal["echo"] = "echo" # type: ignore[assignment]
"""ECHO: group-relative advantage on action tokens (GRPO), plus weighted
CE on env-provided tokens of later turns (tool output, user feedback),
selected by message role via the renderer's per-token ``is_content``
attribution (renderers that don't attribute content fall back to weighting
the whole non-sampled span). Selected tokens feed the ``ce`` loss component
at their role's ``alpha`` and stay outside the rl mask and its denominator."""
roles: EchoRolesConfig = EchoRolesConfig(tool=EchoRoleConfig())
"""The role table. The default — tool-response bodies at ``alpha = 0.1``
— is the vetted ECHO setting."""
filter: EchoFilterConfig | None = None
"""Optional user-supplied filter narrowing the role-selected tokens."""
class MaxRLAlgoConfig(BaseAlgoConfig):
type: Literal["max_rl"] = "max_rl"
"""MaxRL (arXiv:2602.02710): scalar advantage = (reward − group mean) /
group mean, consumed by the ``rl`` loss component. Normalizing by the
mean instead of GRPO's standard deviation makes the policy gradient
unbiased for the order-``group_size`` truncation of the maximum-likelihood
objective: low-pass-rate examples get ~1/p weight, and ``group_size`` is
the truncation order interpolating REINFORCE (1) → exact maximum
likelihood (∞). Designed for non-negative (canonically binary) rewards;
a group with mean reward 0 carries zero advantages everywhere (the
zero-advantage filter drops it, matching the paper's K=0 convention)."""
action_loss_type: ClassVar[ActionLossType] = "rl"
class OPDAlgoConfig(BaseAlgoConfig):
type: Literal["opd"] = "opd"
"""On-policy distillation: the per-token signal is the reverse KL to
a reference model, evaluated in the trainer from reference prefill
logprobs scored over each sample's own context (``ref_logprobs`` on the
wire, ``ref_kl`` loss component). No scalar advantage is assigned —
rollouts keep ``advantages=None`` (advantage-based filters never fire) and
samples ship no advantage stream. ``group_size`` only fans out sampling."""
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
teacher: FrozenModelConfig
"""The teacher — an inline frozen hosted model (``name`` + ``base_url``)
whose reverse KL the policy distills toward. Required, and necessarily a
frozen endpoint: scoring the policy under itself yields zero KL signal, so
``"policy"`` is not even representable here (use ``opsd`` for
demo-conditioned self-teaching)."""
class OPSDAlgoConfig(BaseAlgoConfig):
type: Literal["opsd"] = "opsd"
"""On-policy self-distillation (SDFT, https://arxiv.org/abs/2601.19897):
the per-token signal is the reverse KL against the live policy conditioned
on an expert demonstration. The teacher *is* the policy — self-distillation
names no separate model — scoring each sample with the demonstration
prepended as a leading system message. The sample is scored verbatim (no
re-rendering), so it's robust to tool/multimodal prompts and works for any
number of turns. No scalar advantage is assigned — rollouts keep
``advantages=None`` (advantage-based filters never fire) and samples ship no
advantage stream."""
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
demo_key: str = "demonstration"
"""Key holding the expert demonstration text — looked up in the example's
``info`` dict first, then as a top-level rollout field (e.g. ``answer``)."""
template: str = "Here is an example of an expert response:\n<demonstration>\n{demonstration}\n</demonstration>"
"""Content of the leading system message carrying the demonstration.
Receives ``{demonstration}``; the original question stays in the (verbatim)
user turn, so it isn't templated here."""
renderer: RendererConfig = AutoRendererConfig()
"""Renderer family for the hint block. The tokenizer is always the live
policy's (self-distillation has no separate model — not configurable).
Defaults to ``"auto"`` (resolved from the policy tokenizer); set explicitly
to match a non-auto policy renderer."""
class SFTAlgoConfig(BaseAlgoConfig):
type: Literal["sft"] = "sft"
"""SFT distillation: cross-entropy on the sampled tokens. The ``ce`` loss
ignores advantages and SFT assigns none — it trains on every sampled token.
Reward-based filtering, if wanted, is an explicit filter, not smuggled
through an unused advantage stream."""
action_loss_type: ClassVar[ActionLossType] = "ce"
@model_validator(mode="after")
def require_frozen_source(self):
"""sft's teacher is the model it samples from — ``sampling.source`` must
be a frozen hosted model, not the policy (CE on the policy's own tokens
is not a distillation target)."""
if self.sampling.source == "policy":
raise ValueError(
f"algorithm '{self.type}' needs a teacher to sample rollouts from — "
"CE on the policy's own tokens is not a distillation target. Set "
"sampling.source to an inline hosted model (name + base_url)."
)
return self
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused). The ``type`` selects the algorithm, and
its class defaults are the vetted setting.
- ``grpo`` — policy group sampling, group-relative advantage, RL loss (the default).
- ``max_rl`` — GRPO with mean-normalized advantages (maximum-likelihood RL).
- ``opd`` — on-policy distillation: policy samples, per-token reverse KL against a reference model. Needs ``teacher``.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
A new credit-assignment scheme is a new named algorithm in code (subclass
``Algorithm``, register it), not a config that points at an import path.
"""
@@ -5,7 +5,7 @@ from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, LogConfig, SlurmConfig
from prime_rl.configs.shared import BaseModelConfig, EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
@@ -274,25 +274,22 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
# Disaggregated prefill/decode inference. Each replica is split into separate
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
# for request routing. Multi-replica: set ``num_prefill_replicas`` /
# ``num_decode_replicas`` to run multiple independent vLLM instances within the
# prefill / decode node groups. E.g. ``num_prefill_nodes=4, num_prefill_replicas=2``
# creates two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
# prefill and decode node groups. Requires NIXL for KV transfer and a router for
# request routing.
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["disaggregated"] = "disaggregated"
num_prefill_nodes: int = Field(1, ge=1)
"""Total prefill nodes."""
prefill_nodes_per_replica: int = Field(1, ge=1)
"""Nodes in each prefill vLLM instance."""
num_decode_nodes: int = Field(1, ge=1)
"""Total decode nodes."""
decode_nodes_per_replica: int = Field(1, ge=1)
"""Nodes in each decode vLLM instance."""
num_prefill_replicas: int = Field(1, ge=1)
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
"""Independent prefill vLLM instances."""
num_decode_replicas: int = Field(1, ge=1)
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
"""Independent decode vLLM instances."""
prefill_port: int = 8100
"""Port for prefill vLLM instances."""
@@ -300,10 +297,10 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
decode_port: int = 8200
"""Port for decode vLLM instances."""
prefill_env_overrides: dict[str, str] = {}
prefill_env_vars: EnvVars = {}
"""Extra environment variables exported only on prefill nodes."""
decode_env_overrides: dict[str, str] = {}
decode_env_vars: EnvVars = {}
"""Extra environment variables exported only on decode nodes."""
prefill_vllm_overrides: dict[str, Any] = {}
@@ -312,23 +309,43 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
decode_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
@property
def num_prefill_nodes(self) -> int:
return self.prefill_nodes_per_replica * self.num_prefill_replicas
@property
def num_decode_nodes(self) -> int:
return self.decode_nodes_per_replica * self.num_decode_replicas
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@model_validator(mode="after")
def validate_replicas_divide_nodes(self):
if self.num_prefill_nodes % self.num_prefill_replicas != 0:
raise ValueError(
f"num_prefill_replicas ({self.num_prefill_replicas}) must evenly divide "
f"num_prefill_nodes ({self.num_prefill_nodes})"
)
if self.num_decode_nodes % self.num_decode_replicas != 0:
raise ValueError(
f"num_decode_replicas ({self.num_decode_replicas}) must evenly divide "
f"num_decode_nodes ({self.num_decode_nodes})"
)
return self
@model_validator(mode="before")
@classmethod
def normalize_node_counts(cls, data: Any) -> Any:
if not isinstance(data, dict):
return data
data = dict(data)
def normalize_total_nodes(total_key: str, per_replica_key: str, replicas_key: str) -> None:
has_total = total_key in data
has_per_replica = per_replica_key in data
if has_total and has_per_replica:
raise ValueError(f"Set only {per_replica_key}; {total_key} is derived from it.")
if not has_total:
return
total_nodes = int(data.pop(total_key))
replicas = int(data.get(replicas_key, 1))
if total_nodes % replicas != 0:
raise ValueError(f"{total_key} ({total_nodes}) must be divisible by {replicas_key} ({replicas}).")
data[per_replica_key] = total_nodes // replicas
normalize_total_nodes("num_prefill_nodes", "prefill_nodes_per_replica", "num_prefill_replicas")
normalize_total_nodes("num_decode_nodes", "decode_nodes_per_replica", "num_decode_replicas")
return data
InferenceDeploymentConfig: TypeAlias = Annotated[
@@ -337,10 +354,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
]
class InferenceExperimentalConfig(BaseConfig):
pass
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
@@ -352,6 +365,9 @@ class InferenceConfig(BaseConfig):
log: LogConfig = LogConfig()
"""Logging configuration."""
env_vars: EnvVars = {}
"""Extra environment variables for the inference server process(es). Merged on top of the launcher defaults."""
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
@@ -417,6 +433,9 @@ class InferenceConfig(BaseConfig):
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
vllm_extra: dict[str, Any] = {}
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
@@ -433,8 +452,6 @@ class InferenceConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
@model_validator(mode="after")
def validate_multi_node_requires_slurm(self):
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
@@ -611,6 +628,10 @@ class InferenceConfig(BaseConfig):
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_lm_head"] = True
rsetattr(namespace, "additional_config", existing)
if self.enable_fp32_router_logits:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_router_logits"] = True
rsetattr(namespace, "additional_config", existing)
# Remove chat_template if not set (vLLM doesn't accept None)
if namespace.chat_template is None:
@@ -6,9 +6,14 @@ import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
AlgoConfig,
GRPOAlgoConfig,
)
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
EnvVars,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
@@ -40,9 +45,12 @@ class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
client: ClientConfig = ClientConfig()
"""Client of the live deployment (``[orchestrator.model.client]``)."""
class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0)
temperature: float = Field(1.0, ge=0, le=2.0)
"""Sampling temperature."""
max_completion_tokens: int | None = Field(
@@ -84,7 +92,7 @@ class TrainSamplingConfig(BaseConfig):
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0)
temperature: float | None = Field(None, ge=0, le=2.0)
"""Sampling temperature. None defers to the inference server default."""
top_p: float | None = None
@@ -149,11 +157,8 @@ class EnvConfig(vf.EnvServerConfig):
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
ratio: float | None = Field(None, gt=0)
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
max_retries: int = Field(3, ge=0)
"""Times the env server retries a failed rollout before returning an error."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
@model_validator(mode="before")
@classmethod
@@ -185,9 +190,9 @@ class EnvConfig(vf.EnvServerConfig):
def validate_env(self):
if not self.taskset.id and not self.id:
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
if self.resolved_name == "all":
if self.resolved_name == "agg":
raise ValueError(
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
)
return self
@@ -205,40 +210,6 @@ class EnvConfig(vf.EnvServerConfig):
return self
class LinearLengthPenaltyConfig(BaseConfig):
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
gate_by_correctness: bool = False
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LinearLengthPenaltyConfig | None = None
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
length_weighted_baseline: bool = False
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
class CustomAdvantageConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
class TrainEnvConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
@@ -247,10 +218,10 @@ class TrainEnvConfig(EnvConfig):
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
advantage: AdvantageConfig | None = None
"""Advantage strategy for this env's GRPO groups. Inherits from the top-level
``orchestrator.advantage`` when unset; set a different ``default``/``custom``
config to give this env its own advantage computation."""
algo: AlgoConfig | None = None
"""Training algorithm for this env. Inherits from the top-level
``orchestrator.algo`` when unset; set ``type`` (and its params) to give
this env its own algorithm."""
class EvalEnvConfig(EnvConfig):
@@ -274,13 +245,10 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
worker ``pool`` is configured per env, defaulting to elastic)."""
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
@@ -288,8 +256,6 @@ class TrainConfig(BaseConfig):
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = TrainSamplingConfig(**merged)
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@model_validator(mode="after")
@@ -302,15 +268,6 @@ class TrainConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_env_ratios(self):
ratios = [env.ratio for env in self.env]
if all(r is None for r in ratios):
return self
if any(r is None for r in ratios):
raise ValueError("Either all envs must have a ratio or none of them. Got a mix of set and unset ratios.")
return self
class EvalConfig(BaseConfig):
env: list[EvalEnvConfig] = Field(default_factory=list)
@@ -325,9 +282,6 @@ class EvalConfig(BaseConfig):
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Default rollouts per example. Can be overridden per env."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
@@ -337,7 +291,7 @@ class EvalConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
@@ -352,8 +306,6 @@ class EvalConfig(BaseConfig):
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@model_validator(mode="after")
@@ -469,25 +421,18 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class OrchestratorExperimentalConfig(BaseConfig):
pass
class RolloutModelConfig(BaseConfig):
model: ModelConfig = ModelConfig()
client: ClientConfig = ClientConfig()
class OrchestratorConfig(BaseConfig):
training_mode: Literal["rl", "opd", "sft"] = "rl"
"""Training mode. ``rl``: student generates rollouts, no teacher. ``opd``: student generates rollouts, teacher computes logprobs (teacher_tau > 0). ``sft``: teacher generates rollouts, student inference pool used for evals and weight sync."""
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused — its ``type`` names the algorithm).
Defaults to ``grpo``. Override per env via ``[[orchestrator.train.env]]``'s
``algo``."""
student: RolloutModelConfig = Field(RolloutModelConfig(), validation_alias=AliasChoices("student", "model"))
"""Student rollout participant (model + client) — the model being trained."""
teacher: RolloutModelConfig | None = Field(None, validation_alias=AliasChoices("teacher", "teacher_model"))
"""Teacher rollout participant (model + client). Role depends on ``training_mode``: ``opd`` — teacher computes logprobs; ``sft`` — teacher generates rollouts."""
model: ModelConfig = ModelConfig()
"""The model being trained: its model fields plus the client of the live
vLLM deployment (``[orchestrator.model] name = ...`` with
``[orchestrator.model.client]``). Algorithm components reference it as
``"policy"``."""
train: TrainConfig = TrainConfig()
@@ -510,8 +455,6 @@ class OrchestratorConfig(BaseConfig):
eval: EvalConfig | None = None
"""Evaluation configuration."""
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
pre_batch_filters: list[FilterConfig] = [
GibberishFilterConfig(enforce=False),
RepetitionFilterConfig(enforce=False),
@@ -532,6 +475,9 @@ class OrchestratorConfig(BaseConfig):
log: LogConfig = LogConfig()
env_vars: EnvVars = {}
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
wandb: WandbWithExtrasConfig | None = None
prime_monitor: PrimeMonitorConfig | None = None
@@ -540,7 +486,7 @@ class OrchestratorConfig(BaseConfig):
"""Collect inference-server metrics (requires wandb)."""
inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None
"""Role for each student admin client when collecting P/D inference metrics."""
"""Role for each policy admin client when collecting P/D inference metrics."""
ckpt: CheckpointConfig | None = None
"""Checkpoint configuration."""
@@ -591,69 +537,6 @@ class OrchestratorConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
@model_validator(mode="before")
@classmethod
def fold_student_shortcuts(cls, data: Any) -> Any:
"""Accept top-level ``[orchestrator.model]`` / ``[orchestrator.client]``
as shorthand for the student sub-config. Useful for ergonomic rl configs
where ``[orchestrator.student.*]`` is overkill, and required for
pre-refactor configs that used the flat layout to keep parsing:
- [orchestrator.client.*] -> [orchestrator.student.client.*]
- [orchestrator.model.<k>] -> [orchestrator.student.model.<k>]
(where <k> is any ModelConfig field)
Teacher must always be configured under [orchestrator.teacher.*]
(no equivalent shortcut), because rl mode forbids a teacher and we
don't want the same shortcut to silently route to two different roles.
"""
if not isinstance(data, dict):
return data
def deep_merge(dst: dict, src: dict) -> None:
"""In-place recursive merge of ``src`` into ``dst``. ``src`` wins at the leaf."""
for k, v in src.items():
if isinstance(v, dict) and isinstance(dst.get(k), dict):
deep_merge(dst[k], v)
else:
dst[k] = v
# 1. Re-nest top-level [orchestrator.client] under student.client.
legacy_client = data.pop("client", None)
if isinstance(legacy_client, dict):
student = data.setdefault("student", {})
if isinstance(student, dict):
deep_merge(student.setdefault("client", {}), legacy_client)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["client"] = legacy_client
# 2. Consolidate the legacy `model` alias into `student` so the
# flat-layout fix-up below sees a single target. Deep-merge with the
# legacy keys winning so a CLI `--model.<k>` overrides TOML `student.model.<k>`.
legacy_model = data.pop("model", None)
if legacy_model is not None:
existing = data.get("student")
if existing is None:
data["student"] = legacy_model
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
deep_merge(existing, legacy_model)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["model"] = legacy_model
# 3. Re-nest flat ModelConfig keys under student.model.
model_only_keys = set(ModelConfig.model_fields)
student = data.get("student")
if isinstance(student, dict):
flat = {k: student.pop(k) for k in list(student) if k in model_only_keys}
if flat:
student.setdefault("model", {}).update(flat)
return data
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
@@ -684,15 +567,15 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.student.model.name
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.student.model.trust_remote_code
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
self.model.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
return self
@model_validator(mode="after")
@@ -716,13 +599,33 @@ class OrchestratorConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_training_mode(self):
"""Enforce training mode invariants that involve only orchestrator fields."""
has_teacher = self.teacher is not None
if self.training_mode == "rl" and has_teacher:
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
if self.training_mode in ("opd", "sft") and not has_teacher:
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
Declared before any validator that reads ``algo``."""
for env_cfg in self.train.env:
if env_cfg.algo is None:
env_cfg.algo = self.algo.model_copy(deep=True)
return self
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.env)
@model_validator(mode="after")
def validate_pool_size(self):
"""``pool_size`` sizes the renderer-client pool for policy-sourced
sampling. Reject it when that path never runs — no train env samples
from the policy — so callers don't silently pass it and wonder why
it's ignored."""
if self.pool_size is None:
return self
if not self.any_policy_sourced:
raise ValueError(
f"orchestrator.pool_size={self.pool_size!r} is set but no train env samples "
"from the policy — the renderer-client sampling pool never runs (the renderer "
"is still used for client-side tokenization). Remove pool_size."
)
return self
@model_validator(mode="after")
@@ -742,7 +645,7 @@ class OrchestratorConfig(BaseConfig):
return self
from renderers.base import MODEL_RENDERER_MAP
model_id = self.tokenizer.name or self.student.model.name
model_id = self.tokenizer.name or self.model.name
if model_id in MODEL_RENDERER_MAP:
return self
raise ValueError(
@@ -799,11 +702,6 @@ class OrchestratorConfig(BaseConfig):
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
for env_cfg in self.train.env:
if "advantage" not in env_cfg.model_fields_set:
env_cfg.advantage = self.advantage
return self
@model_validator(mode="after")
@@ -822,13 +720,15 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults on each train env from top-level fields."""
if self.training_mode == "sft":
return self
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
for env in self.train.env:
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
assert env.algo is not None
if env.algo.sampling.source == "policy":
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
if env.is_legacy:
# v0 env: cap per-turn response tokens to the training budget (the legacy
# bridge applies extra_env_kwargs via env.set_kwargs).
@@ -16,6 +16,7 @@ from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.shared import (
EnvVars,
SlurmConfig,
VLMConfig,
)
@@ -45,10 +46,6 @@ from prime_rl.utils.validation import (
)
class RLExperimentalConfig(BaseConfig):
pass
class SharedLogConfig(BaseConfig):
level: str | None = None
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
@@ -158,8 +155,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
num_train_nodes: int
"""Training nodes."""
num_infer_nodes: int = Field(ge=0)
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
num_infer_nodes: int | None = Field(None, ge=0)
"""Inference nodes per replica. If unset, inferred from ``inference.deployment``. Set to 0 to skip inference and orchestrator (requires fake data)."""
num_infer_replicas: int = Field(1, ge=1)
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
@@ -170,9 +167,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
orchestrator_on_inference: bool = False
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
@property
def infer_nodes_per_replica(self) -> int:
return self.num_infer_nodes or 0
@property
def total_infer_nodes(self) -> int:
return self.num_infer_nodes * self.num_infer_replicas
return self.infer_nodes_per_replica * self.num_infer_replicas
DeploymentConfig: TypeAlias = Annotated[
@@ -188,6 +189,9 @@ class RLConfig(BaseConfig):
inference: InferenceConfig | None = None
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
env_vars: EnvVars = {}
"""Extra environment variables for every launched RL component. Component-specific env_vars override these."""
output_dir: Path = Path("outputs")
"""Output directory. Should be unique per experiment."""
@@ -230,23 +234,49 @@ class RLConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: RLExperimentalConfig = RLExperimentalConfig()
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def auto_setup_infer_nodes(self):
if self.deployment.type != "multi_node":
return self
if self.inference is None:
inferred_nodes = 0
elif self.inference.deployment.type == "multi_node":
inferred_nodes = self.inference.deployment.num_nodes
elif self.inference.deployment.type == "disaggregated":
inferred_nodes = self.inference.deployment.num_nodes
else:
inferred_nodes = 1
if self.deployment.num_infer_nodes is None:
self.deployment.num_infer_nodes = inferred_nodes
elif (
self.inference is not None
and self.inference.deployment.type == "multi_node"
and self.deployment.num_infer_nodes != inferred_nodes
):
raise ValueError(
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
f"inference.deployment.num_nodes ({inferred_nodes}) for multi-node inference."
)
return self
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
if self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if self.deployment.num_infer_nodes > 0 and not self.inference:
num_infer_nodes = self.deployment.infer_nodes_per_replica
if num_infer_nodes > 0 and not self.inference:
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
if self.deployment.num_infer_nodes == 0 and self.inference:
if num_infer_nodes == 0 and self.inference:
raise ValueError(
"Cannot configure inference with num_infer_nodes = 0. "
"Either set num_infer_nodes > 0 or remove the inference config."
)
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
raise ValueError(
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
"since no orchestrator or inference server will be running."
@@ -373,40 +403,40 @@ class RLConfig(BaseConfig):
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.student.model.lora is None:
if self.orchestrator.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.student.model.lora = LoRAConfig()
self.orchestrator.model.lora = LoRAConfig()
if (
self.orchestrator.student.model.lora.rank is not None
and self.orchestrator.student.model.lora.rank != self.trainer.model.lora.rank
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.student.model.lora.rank ({self.orchestrator.student.model.lora.rank}) conflicts with "
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.student.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.student.model.lora.alpha is not None
and self.orchestrator.student.model.lora.alpha != self.trainer.model.lora.alpha
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.student.model.lora.alpha ({self.orchestrator.student.model.lora.alpha}) conflicts with "
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.student.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.student.model.lora.rank is None:
self.orchestrator.student.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.student.model.lora.alpha is None:
self.orchestrator.student.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.student.model.lora.name is None:
self.orchestrator.student.model.lora.name = (
f"r{self.orchestrator.student.model.lora.rank}-a{self.orchestrator.student.model.lora.alpha}"
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
@@ -533,7 +563,7 @@ class RLConfig(BaseConfig):
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
@@ -595,12 +625,11 @@ class RLConfig(BaseConfig):
return self
infer_deploy = self.inference.deployment
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
if self.deployment.num_infer_nodes != expected_infer_nodes:
expected_infer_nodes = infer_deploy.num_nodes
if self.deployment.infer_nodes_per_replica != expected_infer_nodes:
raise ValueError(
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal the derived "
f"disaggregated inference nodes per replica ({expected_infer_nodes})."
)
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
@@ -623,23 +652,26 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_inference_client(self):
"""Auto-configure orchestrator student client from the inference server config.
"""Auto-configure the orchestrator policy client from the inference server config.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there.
must not inject a DP-rank header there. When no train env samples from
the policy (e.g. sft_distill), also set base_url — policy-sourced
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
"""
if self.inference is None:
return self
client = self.orchestrator.student.client
client = self.orchestrator.model.client
if "dp_rank_count" not in client.model_fields_set:
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
@@ -6,6 +6,7 @@ from pydantic import Field, model_validator
from renderers import RendererConfig
from prime_rl.configs.shared import (
EnvVars,
HeartbeatConfig,
SlurmConfig,
TrainerLogConfig,
@@ -166,13 +167,12 @@ SFTDeploymentConfig: TypeAlias = Annotated[
]
class SFTExperimentalConfig(BaseConfig):
pass
class SFTConfig(BaseConfig):
model: ModelConfig = ModelConfig()
env_vars: EnvVars = {}
"""Extra environment variables for the SFT trainer process(es). Merged on top of the launcher defaults."""
tokenizer: TokenizerConfig = TokenizerConfig()
renderer: RendererConfig | None = None
@@ -222,7 +222,7 @@ class SFTConfig(BaseConfig):
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 600
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
@@ -239,8 +239,6 @@ class SFTConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
### Pre-validation normalization
@model_validator(mode="before")
@@ -347,18 +345,12 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def validate_and_disable_chunked_loss(self):
if isinstance(self.model.fused_lm_head_token_chunk_size, int):
raise ValueError(
"Chunked loss is not supported for SFT training yet, please set "
"`model.fused_lm_head_token_chunk_size` to 'disabled'"
)
self.model.fused_lm_head_token_chunk_size = "disabled"
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@@ -2,10 +2,30 @@ import os
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic import AfterValidator, Field, model_validator
from prime_rl.utils.config import BaseConfig
# Launcher-managed env vars that a component's `env_vars` must not set: GPU partitioning
# and the single shared W&B run. The launcher always sets these last, so allowing them in
# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead.
PROTECTED_ENV_VARS = frozenset(
{"CUDA_VISIBLE_DEVICES", "WANDB_SHARED_MODE", "WANDB_SHARED_RUN_ID", "WANDB_SHARED_LABEL"}
)
def reject_protected_env_vars(env_vars: dict[str, str]) -> dict[str, str]:
clobbered = sorted(PROTECTED_ENV_VARS & env_vars.keys())
if clobbered:
raise ValueError(
f"env_vars cannot set launcher-managed vars {clobbered} — set by the launcher, not overridable"
)
return env_vars
EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_env_vars)]
"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`."""
class SlurmConfig(BaseConfig):
job_name: str = "prime-rl"
@@ -38,6 +58,9 @@ class SlurmConfig(BaseConfig):
cleanup_grace_period: int = Field(3600, ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
shared_fs: bool = True
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
@property
def template_vars(self) -> dict:
"""Common template variables for all SLURM templates."""
@@ -51,6 +74,7 @@ class SlurmConfig(BaseConfig):
"time": self.time,
"pre_run_command": self.pre_run_command,
"cleanup_grace_period": self.cleanup_grace_period,
"shared_fs": self.shared_fs,
}
@model_validator(mode="after")
@@ -83,10 +107,6 @@ class BaseModelConfig(BaseConfig):
vlm: "VLMConfig | None" = None
"""VLM configuration. Setting this enables vision-language model support."""
@property
def is_vlm(self) -> bool:
return self.vlm is not None
class ElasticConfig(BaseConfig):
hostname: str
@@ -6,6 +6,7 @@ from pydantic import Field, model_validator
from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
@@ -122,19 +123,19 @@ class ModelConfig(BaseModelConfig):
attn: AttnImplementation = "flash_attention_2"
"""Attention implementation. With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
compile: CompileConfig | None = None
compile: CompileConfig | None = CompileConfig()
"""Compile the model with ``torch.compile``."""
ac: ActivationCheckpointConfig | None = None
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
ac_offloading: ActivationOffloadingConfig | None = None
ac_offloading: ActivationOffloadingConfig | None = ActivationOffloadingConfig()
"""Activation offloading configuration. If None, activation offloading is disabled."""
fsdp_cpu_offload: bool = False
"""Enable FSDP CPU offloading for parameters, gradients, and optimizer states. Uses pinned memory for efficient CPU↔GPU transfers."""
optim_cpu_offload: bool = False
optim_cpu_offload: bool = True
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
reshard_after_forward: bool = True
@@ -143,8 +144,8 @@ class ModelConfig(BaseModelConfig):
dp_replicate: int = 1
"""Data parallel dim where model weights are replicated."""
ep: int = 1
"""Expert parallelism degree for MoE layers. 1 disables EP."""
ep: int | Literal["auto"] = "auto"
"""Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves to ``min(fsdp_island_size, 8)`` for MoE models (where ``fsdp_island_size = world_size // dp_replicate``), and to 1 for non-MoE models. Set an explicit integer to override."""
ep_comm_backend: EPCommBackend = "torch"
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
@@ -170,6 +171,9 @@ class ModelConfig(BaseModelConfig):
reduce_dtype: Literal["bfloat16", "float32"] = "float32"
"""dtype for gradient/parameter reductions."""
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
@@ -188,8 +192,8 @@ class ModelConfig(BaseModelConfig):
debug: DebugModelConfig = DebugModelConfig()
"""Debugging knobs for the model and distributed training."""
fused_lm_head_token_chunk_size: int | Literal["auto", "disabled"] = "disabled"
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``auto`` auto-enables (RL training picks 8192); ``disabled`` uses the vanilla LM head. Integer values aren't supported for SFT training."""
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
@model_validator(mode="before")
@classmethod
@@ -258,7 +262,7 @@ class ModelConfig(BaseModelConfig):
if self.ep_comm_backend == "torch":
return self
if self.ep <= 1:
if isinstance(self.ep, int) and self.ep <= 1:
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
return self
@@ -510,7 +514,7 @@ class TrainerConfig(BaseConfig):
data: DataLoaderConfig = DataLoaderConfig()
loss: LossConfig = DefaultLossConfig()
"""Loss config for rl-mode batches. opd and sft batches dispatch to their own loss fns unconditionally and do not read this."""
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
optim: OptimizerConfig = AdamWConfig()
@@ -553,7 +557,7 @@ class TrainerConfig(BaseConfig):
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 600
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
heartbeat: HeartbeatConfig | None = None
@@ -568,6 +572,9 @@ class TrainerConfig(BaseConfig):
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
env_vars: EnvVars = {}
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
@@ -657,16 +664,9 @@ class TrainerConfig(BaseConfig):
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_fused_lm_head_token_chunk_size(self):
if self.model.fused_lm_head_token_chunk_size == "auto":
self.model.fused_lm_head_token_chunk_size = 8192
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@@ -1,7 +1,6 @@
from pathlib import Path
from typing import Any
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
@@ -38,19 +37,3 @@ def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
return setattr(obj, attr_path, value)
parent_path, attr = attr_path.rsplit(".", 1)
setattr(rgetattr(obj, parent_path), attr, value)
def get_all_fields(model: BaseModel | type) -> list[str]:
if isinstance(model, BaseModel):
model_cls = model.__class__
else:
model_cls = model
fields = []
for name, field in model_cls.model_fields.items():
field_type = field.annotation
fields.append(name)
if field_type is not None and hasattr(field_type, "model_fields"):
sub_fields = get_all_fields(field_type)
fields.extend(f"{name}.{sub}" for sub in sub_fields)
return fields
@@ -22,9 +22,6 @@ def propagate_shared_fields(data: Any) -> Any:
The original footgun the mutex was designed to catch — a sub-config
value silently winning over a later CLI shared override — is still
caught because that scenario produces *different* values.
- **Aliased sub-paths**: ``orchestrator.model.*`` is checked against its
``orchestrator.student.model.*`` alias (and vice versa), so the
conflict fires regardless of which spelling the user wrote.
"""
if not isinstance(data, dict):
return data
@@ -51,36 +48,34 @@ def propagate_shared_fields(data: Any) -> Any:
conflicts: list[tuple[str, str]] = []
def propagate(shared_path: str, *targets: str, aliases: tuple[str, ...] = ()) -> None:
"""Verbatim shared → targets. Records *disagreeing* overlap (incl. alias
spellings) into ``conflicts`` and fills each target if the shared value
is set. Matching values are silently accepted so the materialized
config round-trips through re-load.
def propagate(shared_path: str, *targets: str) -> None:
"""Verbatim shared → targets. Records *disagreeing* overlap into
``conflicts`` and fills each target if the shared value is set. Matching
values are silently accepted so the materialized config round-trips
through re-load.
"""
value = get(shared_path)
if value is None:
return
for sub in (*targets, *aliases):
sub_value = get(sub)
for target in targets:
sub_value = get(target)
if sub_value is not None and sub_value != value:
conflicts.append((shared_path, sub))
conflicts.append((shared_path, target))
for target in targets:
fill(target, value)
# [model] → trainer / orchestrator (student, via AliasChoices) / inference.
# [model] → trainer / orchestrator / inference.
propagate(
"model.name",
"trainer.model.name",
"inference.model.name",
"orchestrator.model.name",
aliases=("orchestrator.student.model.name",),
)
propagate(
"model.vlm",
"trainer.model.vlm",
"inference.model.vlm",
"orchestrator.model.vlm",
aliases=("orchestrator.student.model.vlm",),
)
# [log]
@@ -224,18 +219,18 @@ def validate_shared_model_name(
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.model.name != orchestrator.student.model.name:
if inference.model.name != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. "
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.student.model.name:
if trainer.model.name != orchestrator.model.name:
raise ValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. Please specify the same model name for both."
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
)
@@ -322,14 +317,11 @@ def validate_shared_weight_broadcast(
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
if (
inference
and trainer.weight_broadcast.type != orchestrator.weight_broadcast.type != inference.weight_broadcast.type
):
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
elif trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
raise ValueError(
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
)
+120 -91
View File
@@ -19,9 +19,10 @@ dependencies = [
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.22.0",
"vllm>=0.24.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"ring-flash-attn>=0.1.8",
"prime>=0.6.4",
"pyzmq>=27.1.0",
@@ -33,7 +34,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers>=0.1.15.dev357",
"verifiers[harbor]>=0.1.15.dev411",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -54,7 +55,7 @@ orchestrator = "prime_rl.entrypoints.orchestrator:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
flash-attn = [
@@ -66,55 +67,70 @@ flash-attn-cute = [
"flash-attn-4",
]
envs = [
"aime2024",
"aime2025",
"alphabet-sort",
"code-env",
"color-codeword",
"deepdive",
"general-agent",
"gpqa",
"hle",
"ifeval",
"livecodebench",
"logic-env",
"math-env",
"math-python",
"math500",
"mini-swe-agent-plus",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
"opencode-math",
"opencode-science",
"opencode-swe",
"reverse-text",
"rlm-swe",
"rlm-search",
"rlm-uuid-ctf",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
"wordle",
"reverse-text-v1",
"gsm8k-v1",
"math-env-v1",
"aime24-v1",
"aime25-v1",
"aime26-v1",
"alphabet-sort",
"alphabet-sort-v1",
"scaleswe-v1",
"color-codeword-v1",
"r2e-gym-v1",
"terminal-bench-2-v1",
"apex-shortlist-v1",
"arxivmath-v1",
"browsecomp-v1",
"code-golf-v1",
"color-codeword-v1",
"deepdive-v1",
"deepwiki-v1",
"forth-lang-v1",
"general-agent-v1",
"glossary-v1",
"gpqa-v1",
"graphwalks-v1",
"gsm8k-v1",
"i3-code-v1",
"i3-science-v1",
"ifbench-v1",
"ifeval-v1",
"lean-v1",
"livecodebench-v1",
"logic-env",
"longcot-mini-v1",
"longcot-v1",
"longpdfs-v1",
"math-env",
"math-env-v1",
"math-python",
"math500-v1",
"mmlu-pro-v1",
"mrcr-v2-v1",
"oolong-pairs-v1",
"oolong-real-v1",
"oolong-synth-v1",
"openseeker-v1",
"openthoughts-tblite-v1",
"papersearchqa-v1",
"patterned-needle-in-haystack-v1",
"prolog-v1",
"r2e-gym-v1",
"redsearcher-v1",
"reverse-text",
"reverse-text-v1",
"s1-deepresearch-v1",
"scaleswe-v1",
"simpleqa-v1",
"simpleqa-verified-v1",
"swebench-pro-v1",
"swebench-verified-v1",
"swelego-v1",
"tau2-bench-v1",
"terminal-bench-2-v1",
"unscramble-v1",
"uuid-ctf-v1",
"verbatim-copy-v1",
"wideseek-v1",
"wiki-search",
"wiki-search-v1",
"wikispeedia-v1",
"wordle",
"wordle-v1",
"general-agent-v1",
"swebench-verified-v1",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -160,7 +176,6 @@ dev = [
# *without* the cooldown — bypassing this security policy.
required-version = ">=0.11.1"
exclude-newer = "7 days"
preview = true
no-build-isolation-package = ["flash-attn"]
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
@@ -174,7 +189,6 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers>=0.1.15.dev357",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -222,69 +236,84 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
# example live under deps/verifiers/environments.
# example live under deps/{verifiers,research-environments}/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
aime2024 = { path = "deps/research-environments/environments/aime2024", editable = true }
aime2025 = { path = "deps/research-environments/environments/aime2025", editable = true }
aime24-v1 = { path = "deps/research-environments/environments/aime24_v1", editable = true }
aime25-v1 = { path = "deps/research-environments/environments/aime25_v1", editable = true }
aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editable = true }
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
hle = { path = "deps/research-environments/environments/hle", editable = true }
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500 = { path = "deps/research-environments/environments/math500", editable = true }
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
opencode-math = { path = "deps/research-environments/environments/opencode_math", editable = true }
opencode-science = { path = "deps/research-environments/environments/opencode_science", editable = true }
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", editable = true }
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
math-env-v1 = { path = "deps/verifiers/environments/math_env_v1", editable = true }
aime24-v1 = { path = "deps/verifiers/environments/aime24_v1", editable = true }
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
scaleswe-v1 = { path = "deps/verifiers/environments/scaleswe_v1", editable = true }
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
r2e-gym-v1 = { path = "deps/verifiers/environments/r2e_gym_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/verifiers/environments/terminal_bench_2_v1", editable = true }
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_v1", editable = true }
arxivmath-v1 = { path = "deps/research-environments/environments/arxivmath_v1", editable = true }
browsecomp-v1 = { path = "deps/research-environments/environments/browsecomp_v1", editable = true }
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
swelego-v1 = { path = "deps/verifiers/environments/swelego_v1", editable = true }
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
graphwalks-v1 = { path = "deps/research-environments/environments/graphwalks_v1", editable = true }
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
i3-code-v1 = { path = "deps/research-environments/environments/i3_code_v1", editable = true }
i3-science-v1 = { path = "deps/research-environments/environments/i3_science_v1", editable = true }
ifbench-v1 = { path = "deps/research-environments/environments/ifbench_v1", editable = true }
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
lean-v1 = { path = "deps/research-environments/environments/lean_v1", editable = true }
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
longcot-mini-v1 = { path = "deps/research-environments/environments/longcot_mini_v1", editable = true }
longcot-v1 = { path = "deps/research-environments/environments/longcot_v1", editable = true }
longpdfs-v1 = { path = "deps/research-environments/environments/longpdfs_v1", editable = true }
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500-v1 = { path = "deps/research-environments/environments/math500_v1", editable = true }
mmlu-pro-v1 = { path = "deps/research-environments/environments/mmlu_pro_v1", editable = true }
mrcr-v2-v1 = { path = "deps/research-environments/environments/mrcr_v2_v1", editable = true }
oolong-pairs-v1 = { path = "deps/research-environments/environments/oolong_pairs_v1", editable = true }
oolong-real-v1 = { path = "deps/research-environments/environments/oolong_real_v1", editable = true }
oolong-synth-v1 = { path = "deps/research-environments/environments/oolong_synth_v1", editable = true }
openseeker-v1 = { path = "deps/research-environments/environments/openseeker_v1", editable = true }
openthoughts-tblite-v1 = { path = "deps/research-environments/environments/openthoughts_tblite_v1", editable = true }
papersearchqa-v1 = { path = "deps/research-environments/environments/papersearchqa_v1", editable = true }
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/patterned_needle_in_haystack_v1", editable = true }
prolog-v1 = { path = "deps/research-environments/environments/prolog_v1", editable = true }
r2e-gym-v1 = { path = "deps/research-environments/environments/swe/r2e_gym_v1", editable = true }
redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v1", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
s1-deepresearch-v1 = { path = "deps/research-environments/environments/s1_deepresearch_v1", editable = true }
scaleswe-v1 = { path = "deps/research-environments/environments/swe/scaleswe_v1", editable = true }
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
swebench-pro-v1 = { path = "deps/research-environments/environments/swe/swebench_pro_v1", editable = true }
swebench-verified-v1 = { path = "deps/research-environments/environments/swe/swebench_verified_v1", editable = true }
swelego-v1 = { path = "deps/research-environments/environments/swe/swelego_v1", editable = true }
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
unscramble-v1 = { path = "deps/research-environments/environments/unscramble_v1", editable = true }
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
verbatim-copy-v1 = { path = "deps/research-environments/environments/verbatim_copy_v1", editable = true }
wideseek-v1 = { path = "deps/research-environments/environments/wideseek_v1", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
wikispeedia-v1 = { path = "deps/verifiers/environments/wikispeedia_v1", editable = true }
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
general-agent-v1 = { path = "deps/verifiers/environments/general_agent_v1", editable = true }
swebench-verified-v1 = { path = "deps/verifiers/environments/swebench_verified_v1", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
set -euo pipefail
mode="env"
if [ "${1:-}" = "--shell" ] || [ "${1:-}" = "--github-output" ]; then
mode="${1#--}"
shift
fi
root="${1:-.}"
root="$(cd "$root" && pwd)"
dependency_floor_version() {
local package="$1"
find "$root" \
\( -path "$root/.git" -o -path "$root/.venv" \) -prune -o \
-type f -name pyproject.toml -print |
while IFS= read -r pyproject; do
sed -nE "s/.*[\"']${package}(\\[[^]]+\\])?>=([^\"',; ]+).*/\\2/p" "$pyproject"
done |
sort -V |
tail -n 1
}
next_patch_dev_version() {
local tag="$1"
local distance="$2"
local version="${tag#v}"
local major minor patch
if [ "$distance" = "0" ]; then
printf '%s\n' "$version"
return 0
fi
if [[ "$version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
major="${BASH_REMATCH[1]}"
minor="${BASH_REMATCH[2]}"
patch="${BASH_REMATCH[3]}"
printf '%s.%s.%s.dev%s\n' "$major" "$minor" "$((patch + 1))" "$distance"
return 0
fi
return 1
}
describe_distance() {
sed -E 's/.*-([0-9]+)-g[0-9a-f]+$/\1/' <<< "$1"
}
describe_tag() {
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
}
verifiers_git_version() {
local dir="$root/deps/verifiers"
local desc tag distance
[ -d "$dir" ] || return 1
desc="$(git -C "$dir" describe --tags --long --match 'v[0-9]*.[0-9]*.[0-9]*' --exclude '*dev*' 2>/dev/null)" || return 1
tag="$(describe_tag "$desc")"
distance="$(describe_distance "$desc")"
next_patch_dev_version "$tag" "$distance"
}
renderers_git_version() {
local dir="$root/deps/renderers"
local desc tag distance version
[ -d "$dir" ] || return 1
desc="$(git -C "$dir" describe --tags --long --match 'renderers-v*' 2>/dev/null)" || return 1
tag="$(describe_tag "$desc")"
distance="$(describe_distance "$desc")"
version="${tag#renderers-v}"
if [ "$distance" = "0" ]; then
printf '%s\n' "$version"
return 0
fi
next_patch_dev_version "v$version" "$distance"
}
resolve_version() {
local package="$1"
local env_name="$2"
local git_func="$3"
local version
version="${!env_name:-}"
if [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
if version="$("$git_func")" && [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
version="$(dependency_floor_version "$package")"
if [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
printf 'Could not infer a pretend version for %s under %s\n' "$package" "$root" >&2
return 1
}
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
case "$mode" in
shell)
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
;;
github-output)
printf 'verifiers=%s\n' "$verifiers_version"
printf 'renderers=%s\n' "$renderers_version"
;;
env)
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
;;
*)
printf 'Unknown output mode: %s\n' "$mode" >&2
exit 2
;;
esac
+1 -1
View File
@@ -53,7 +53,7 @@ if [ -n "$PRIME_RL_REF" ]; then
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's extras (Dockerfile.cuda:82) — explicit instead
# Mirror the image's uv sync extras — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
+5 -3
View File
@@ -47,9 +47,11 @@ id = "reverse-text"
CLI: `--env.0.id reverse-text --env.1.id math-env`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**Discriminated unions** — set the `type` field to pick the variant (`[trainer.loss] type = "sft"`). Omit `type` to keep the default variant.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-env override: `[orchestrator.train.env.algo] type = "opd"` (the env assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
@@ -62,7 +64,7 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
enable_token_export = true
+2
View File
@@ -34,6 +34,8 @@ Default cadence: **1 hour** (researcher can override). At each check-in:
**Notes**: anything unusual (errors, restarts, hangs). Omit if nothing notable.
```
In W&B, each project auto-gets an **"overview" saved view** (train / eval / stability / performance sections) on its first run — use it for a quick check instead of the auto-generated default workspace.
### Restarting a run
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
+1 -1
View File
@@ -36,7 +36,7 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
- SLURM: single- and multi-node
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('rlm_swe'))"`).
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
If a local env exists under `deps/research-environments/environments/` but does not
import, add it to the root `pyproject.toml` env extra, workspace members, and
`[tool.uv.sources]`, then run `uv sync --all-extras`.
+12 -3
View File
@@ -1,4 +1,5 @@
import json
import os
import subprocess
import sys
from pathlib import Path
@@ -10,7 +11,7 @@ from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
@@ -66,6 +67,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
kv_offload_device_name=offload.device_name if is_mooncake else "",
inference_env_vars={**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars},
)
is_multi_node = config.deployment.type == "multi_node"
@@ -74,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
template_vars.update(
num_prefill_nodes=config.deployment.num_prefill_nodes,
num_decode_nodes=config.deployment.num_decode_nodes,
prefill_nodes_per_replica=config.deployment.prefill_nodes_per_replica,
decode_nodes_per_replica=config.deployment.decode_nodes_per_replica,
num_prefill_replicas=config.deployment.num_prefill_replicas,
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
@@ -81,8 +85,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
router=config.deployment.router,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_overrides=config.deployment.prefill_env_overrides,
decode_env_overrides=config.deployment.decode_env_overrides,
prefill_env_vars=config.deployment.prefill_env_vars,
decode_env_vars=config.deployment.decode_env_vars,
prefill_vllm_extra_json=vllm_overrides_fragment(config.deployment.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides),
)
@@ -151,6 +155,11 @@ def inference_local(config: InferenceConfig):
port = config.server.port
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
# Apply the inference env (defaults + [inference.env_vars]) in-process so a standalone
# `uv run inference` gets the same environment the rl/SLURM launchers inject into the
# server subprocess. config.env_vars wins over the defaults; existing os.environ loses.
os.environ.update({**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars})
setup_vllm_env(config)
from prime_rl.inference.vllm.server import server # pyright: ignore
+73 -25
View File
@@ -12,6 +12,7 @@ from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
@@ -25,7 +26,15 @@ from prime_rl.utils.pathing import (
resolve_latest_ckpt_step,
validate_output_dir,
)
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
monitor_process,
set_proc_title,
)
RL_TOML = "rl.toml"
RL_SBATCH = "rl.sbatch"
@@ -118,16 +127,16 @@ def rl_local(config: RLConfig):
}
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.student.client.base_url[0]
base_url = config.orchestrator.model.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.student.client.base_url port ({client_port}) does not match "
f"orchestrator.model.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
@@ -162,6 +171,10 @@ def rl_local(config: RLConfig):
inference_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
@@ -181,19 +194,26 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No [inference] block configured - the student inference server will not be started here. "
"All training modes (rl/opd/sft) require a student inference pool for evals + weight sync; "
"make sure one is running at orchestrator.student.client.base_url "
f"({', '.join(config.orchestrator.student.client.base_url)}), otherwise the orchestrator "
"No [inference] block configured - the policy inference server will not be started here. "
"Every algorithm requires a policy inference pool for evals + weight sync; "
"make sure one is running at orchestrator.model.client.base_url "
f"({', '.join(config.orchestrator.model.client.base_url)}), otherwise the orchestrator "
"will hang waiting for it."
)
if config.orchestrator.teacher:
frozen_endpoints: list[str] = []
for env in config.orchestrator.train.env:
algo = env.algo
assert algo is not None, "TrainEnvConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
if frozen_endpoints:
endpoints = ", ".join(dict.fromkeys(frozen_endpoints))
logger.info(
"orchestrator.teacher is configured - the rl entrypoint does not start teacher inference "
"servers. Make sure your teacher endpoint at "
f"{', '.join(config.orchestrator.teacher.client.base_url)} is running before the "
"orchestrator starts, otherwise rollouts will hang."
"Frozen model references are configured - the rl entrypoint does not start them. "
f"Make sure these endpoints are serving before the orchestrator starts: {endpoints}; "
"otherwise rollouts will hang."
)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
@@ -206,11 +226,14 @@ def rl_local(config: RLConfig):
stderr=log_file,
env={
**os.environ,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.orchestrator.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
},
)
processes.append(orchestrator_process)
@@ -252,14 +275,16 @@ def rl_local(config: RLConfig):
trainer_cmd,
env={
**os.environ,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
"PYTHONUNBUFFERED": "1",
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.trainer.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
@@ -348,6 +373,21 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
kv_offload_device_name=offload.device_name if is_mooncake else "",
)
# Per-component env vars: launcher defaults (shared + multi-node-specific) with the
# user's config merged on top. Runtime wiring stays in the template.
trainer_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
**config.env_vars,
**config.trainer.env_vars,
}
orchestrator_env_vars = {**DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars}
inference_env_vars = (
{**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars, **config.inference.env_vars}
if config.inference
else {}
)
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
@@ -370,6 +410,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_infer_replicas=config.deployment.num_infer_replicas,
num_prefill_nodes=infer_deploy.num_prefill_nodes,
num_decode_nodes=infer_deploy.num_decode_nodes,
prefill_nodes_per_replica=infer_deploy.prefill_nodes_per_replica,
decode_nodes_per_replica=infer_deploy.decode_nodes_per_replica,
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
@@ -379,8 +421,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
inference_tp=config.inference.parallel.tp,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
use_deep_gemm=config.inference.use_deep_gemm,
prefill_env_overrides=infer_deploy.prefill_env_overrides,
decode_env_overrides=infer_deploy.decode_env_overrides,
prefill_env_vars=infer_deploy.prefill_env_vars,
decode_env_vars=infer_deploy.decode_env_vars,
trainer_env_vars=trainer_env_vars,
orchestrator_env_vars=orchestrator_env_vars,
inference_env_vars=inference_env_vars,
prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides),
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
@@ -398,11 +443,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.num_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
infer_nodes_per_replica=config.deployment.num_infer_nodes,
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
@@ -412,6 +457,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
trainer_env_vars=trainer_env_vars,
orchestrator_env_vars=orchestrator_env_vars,
inference_env_vars=inference_env_vars,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -450,7 +498,7 @@ def rl_slurm(config: RLConfig):
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
has_infer = config.deployment.num_infer_nodes > 0
has_infer = config.deployment.infer_nodes_per_replica > 0
log_message = format_log_message(
log_dir=log_dir,
trainer=True,
+18 -3
View File
@@ -12,7 +12,14 @@ from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
monitor_process,
set_proc_title,
)
SFT_TOML = "sft.toml"
SFT_SBATCH = "sft.sbatch"
@@ -36,6 +43,12 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
trainer_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
**config.env_vars,
}
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
@@ -48,6 +61,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
trainer_env_vars=trainer_env_vars,
num_nodes=config.deployment.num_nodes,
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
@@ -143,8 +157,9 @@ def sft_local(config: SFTConfig):
trainer_cmd,
env={
**os.environ,
"PYTHONUNBUFFERED": "1",
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
**config.env_vars,
},
stdout=log_file,
stderr=log_file,
+198 -420
View File
@@ -1,24 +1,21 @@
import torch
from vllm.triton_utils import tl, triton
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
def transformers_v5_compat():
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
def apply_shared_vllm_patches():
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
in every vLLM process, including spawned workers.
in every vLLM process, including spawned workers. Note vLLM swallows plugin
load failures (``load_plugins_by_group`` logs and continues), so a broken
entry-point target silently skips ALL of these patches.
"""
from transformers import Qwen3VLMoeTextConfig
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
Qwen3VLMoeTextConfig.tie_word_embeddings = False
_patch_qwen35_lora()
_patch_lora_key_prefix()
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_qwen3_coder_param_newline_trim()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
@@ -102,6 +99,91 @@ def monkey_patch_nano_v3_reasoning_parser():
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
def monkey_patch_qwen3_coder_param_newline_trim():
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
exactly one leading and one trailing newline. A full strip corrupts
whitespace-significant string parameters (str_replace-style
``old_str``/``new_str``, file content with an indented first line, values
with intentional trailing newlines), silently changing tool execution and
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
"""
import json
from vllm.parser import qwen3
def _trim_one_newline(value: str) -> str:
if value.startswith("\n"):
value = value[1:]
if value.endswith("\n"):
value = value[:-1]
return value
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
params: dict[str, object] = {}
for match in qwen3._PARAM_RE.finditer(raw_args):
name = match.group(1)
value = match.group(2)
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
if partial:
remaining = qwen3._PARAM_RE.sub("", raw_args)
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
if m:
name = m.group(1)
value = m.group(2)
if name:
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
return json.dumps(params, ensure_ascii=False)
qwen3._qwen3_arg_converter = _patched_arg_converter
# qwen3_config captures the converter when first built; drop any cached configs.
qwen3.qwen3_config.cache_clear()
def monkey_patch_minimax_m2_think_end_passthrough():
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
prime-rl serves MiniMax-M2 with ``reasoning=minimax_m2_append_think``, which
returns content as ``<think>`` + the full completion so think tags round-trip
through multi-turn re-serialization. vLLM 0.24's minimax_m2 parser engine
added a ``(CONTENT, THINK_END) -> no-events`` transition that silently
swallows the ``</think>`` (0.23's regex tool parser passed it through
untouched), and it also ``.strip()``s content whenever tool calls are
present. Drop the transition — the engine emits unmatched terminals as plain
state content — and disable the content strip.
"""
import dataclasses
import functools
from vllm.parser import minimax_m2
from vllm.parser.engine.parser_engine_config import ParserState
original_config = minimax_m2.minimax_m2_config
@functools.cache
def _patched_config():
config = original_config()
transitions = dict(config.transitions)
del transitions[(ParserState.CONTENT, "THINK_END")]
return dataclasses.replace(
config,
transitions=transitions,
strip_content_whitespace_with_tools=False,
)
minimax_m2.minimax_m2_config = _patched_config
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm import envs
from vllm.config.vllm import VllmConfig
@@ -184,212 +266,47 @@ def monkey_patch_strip_routed_experts_from_chat():
)
@triton.jit
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
y_ptr,
y_q_ptr,
y_s_ptr,
M: tl.int64,
N: tl.int64,
y_s_col_stride: tl.int64,
eps,
clamp_limit,
fp8_min: tl.constexpr,
fp8_max: tl.constexpr,
use_ue8m0: tl.constexpr,
HAS_CLAMP: tl.constexpr,
GROUP_SIZE: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
N_2 = N // 2
def _patch_qwen35_moe_lora_format():
"""Force Qwen3.5-MoE onto vLLM's 2D per-expert LoRA format.
m_offset = (pid_m * BLOCK_M).to(tl.int64)
n_offset = (pid_n * BLOCK_N).to(tl.int64)
if m_offset >= M:
return
vLLM 0.24.0 still defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
which makes the LoRA loader expect 3D stacked-expert adapters
(``base_layer.lora_{A,B}.weight`` / ``lora_{A,B}.weight``, experts folded into the
rank dim; see ``_stack_moe_lora_weights``). Our trainer instead emits the 2D
per-expert layout (``{expert_id}.gate_proj.lora_A.weight`` ...) from
``MultiLoRAGroupedExperts.state_dict_for_adapter`` -- vLLM only consults that layout
when ``is_3d_moe_weight`` is False (or ``enable_mixed_moe_lora_format=True``).
Without this override the adapters fail to load with key/shape mismatches.
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
base_y_ptr = y_ptr + m_offset * N + n_offset
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
act_in = tl.load(act_in_ptrs)
mul_in = tl.load(act_in_ptrs + N_2)
if HAS_CLAMP:
act_in = tl.minimum(act_in.to(tl.float32), clamp_limit).to(y_ptr.dtype.element_ty)
mul_in = tl.clamp(mul_in.to(tl.float32), -clamp_limit, clamp_limit).to(y_ptr.dtype.element_ty)
act_in = act_in.to(tl.float32)
one_f32 = tl.cast(1, tl.float32)
silu_out = (act_in / (one_f32 + tl.exp(-act_in))).to(y_ptr.dtype.element_ty)
y = (silu_out * mul_in).to(tl.float32)
absmax = tl.maximum(tl.max(tl.abs(y), axis=1), eps)
scale_raw = absmax * (1.0 / fp8_max)
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
y_s = tl.reshape(y_s, (BLOCK_M, 1))
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
base_y_q_ptr = y_q_ptr + m_offset * N_2 + n_offset
y_q_ptrs = base_y_q_ptr + offs_m[:, None] * N_2 + offs_n[None, :]
tl.store(y_q_ptrs, y_q)
group_id = n_offset // GROUP_SIZE
base_y_s_ptr = y_s_ptr + group_id * y_s_col_stride + m_offset
y_s_ptrs = base_y_s_ptr + offs_m
y_s = tl.reshape(y_s, (BLOCK_M,))
tl.store(y_s_ptrs, y_s)
def _silu_mul_per_token_group_quant_fp8_colmajor_int64(
input: torch.Tensor,
output: torch.Tensor | None = None,
use_ue8m0: bool | None = None,
eps: float = 1e-10,
clamp_limit: float | None = None,
):
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
group_size = 128
assert input.ndim == 2
if output is not None:
assert output.ndim == 2
assert input.size(0) % group_size == 0
assert input.size(1) % (group_size * 2) == 0
if use_ue8m0 is None:
use_ue8m0 = is_deep_gemm_e8m0_used()
M, N = input.size()
N_2 = N // 2
fp8_dtype = current_platform.fp8_dtype()
if output is None:
output = torch.empty((M, N_2), dtype=fp8_dtype, device=input.device)
output_scales = torch.empty(((N_2 // group_size), M), dtype=torch.float32, device=input.device).transpose(0, 1)
block_m = 8
block_n = group_size
assert M % block_m == 0
assert N_2 % block_n == 0
finfo = torch.finfo(fp8_dtype)
fp8_min = -224.0 if current_platform.is_fp8_fnuz() else finfo.min
fp8_max = 224.0 if current_platform.is_fp8_fnuz() else finfo.max
has_clamp = clamp_limit is not None
grid = (M // block_m, N_2 // block_n)
_silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel[grid](
input,
output,
output_scales,
M,
N,
output_scales.stride(-1),
eps,
clamp_limit if has_clamp else 0.0,
fp8_min,
fp8_max,
use_ue8m0,
has_clamp,
group_size,
block_m,
block_n,
)
return output, output_scales
def monkey_patch_deep_gemm_silu_mul_quant_int64():
import sys
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.utils import fp8_utils
logger = init_logger(__name__)
fp8_utils.silu_mul_per_token_group_quant_fp8_colmajor = _silu_mul_per_token_group_quant_fp8_colmajor_int64
deep_gemm_moe_module = sys.modules.get("vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe")
if deep_gemm_moe_module is not None:
deep_gemm_moe_module.silu_mul_per_token_group_quant_fp8_colmajor = (
_silu_mul_per_token_group_quant_fp8_colmajor_int64
)
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
def _patch_qwen35_lora():
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
Qwen3.5's GDN layers use create_qkvz_proj with 4 output_sizes (q, k, v, z)
but packed_modules_mapping only lists 2 entries, causing an IndexError
during LoRA initialization.
Also generalizes MergedColumnParallelLinearWithLoRA.can_replace_layer
to accept any number of packed modules (not just 2), and generalizes
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a to handle N
subloras instead of the hardcoded 2 (needed for fully_sharded_loras=True).
Upstream: https://github.com/vllm-project/vllm/issues/36372
The rest of the old Qwen3.5 LoRA shim (the in_proj_qkvz packed-mapping fix and the
N-slice ``can_replace_layer`` / ``slice_lora_a`` generalizations for vllm#36372) is
handled natively by 0.23.0 and was dropped. Remove this too once we either adopt the
3D stacked save format (like gpt-oss) or start the engine with
``enable_mixed_moe_lora_format=True``.
"""
from vllm.lora.layers.column_parallel_linear import (
MergedColumnParallelLinearWithLoRA,
MergedColumnParallelLinearWithShardedLoRA,
)
from vllm.model_executor.models.qwen3_5 import (
Qwen3_5ForCausalLMBase,
Qwen3_5ForConditionalGeneration,
Qwen3_5MoeForConditionalGeneration,
)
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
from vllm.model_executor.models.qwen3_5 import Qwen3_5MoeForConditionalGeneration
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
@classmethod
@_not_fully_sharded_can_replace
def can_replace_layer(cls, source_layer, lora_config, packed_modules_list, model_config=None):
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
return type(source_layer) is MergedColumnParallelLinear and len(packed_modules_list) == len(
source_layer.output_sizes
)
MergedColumnParallelLinearWithLoRA.can_replace_layer = can_replace_layer
def slice_lora_a(self, lora_a):
output_shard_size = self.lora_a_stacked[0].shape[2]
output_start_idx = self.tp_rank * output_shard_size
return [
a[output_start_idx : output_start_idx + output_shard_size, :] if a is not None else None for a in lora_a
]
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a = slice_lora_a
def _patch_lora_key_prefix():
"""Patch vLLM's LoRA loading to handle keys without base_model.model. prefix.
"""Accept both bare-suffix and fully-qualified expert module names in LoRA adapters.
This is a copy of the upstream patch: https://github.com/vllm-project/vllm/pull/38522
We can remove this patch once that PR makes it into a release.
Copy of vLLM 0.24.0's ``LoRAModel.from_local_checkpoint`` with one change: the
``.experts`` branch of ``check_unexpected_modules`` accepts either the bare suffix
(``down_proj``) or the qualified per-expert name (``experts.N.down_proj``), where
upstream only accepts the qualified form. Our trainer's 2D per-expert adapters
(Qwen3.5-MoE) carry names whose qualified form is not in the expected set while
the bare suffix is; Qwen3-30B-A3B adapters go the other way. Upstream fix
vllm-project/vllm#38522 was closed unmerged, so this stays.
"""
from vllm.lora.lora_model import (
LoRAModel,
MoEEPLoadSpec,
PEFTHelper,
TensorizerConfig,
WeightsMapper,
_is_remote_expert_key,
get_lora_id,
is_base_embedding_weights,
os,
@@ -410,6 +327,7 @@ def _patch_lora_key_prefix():
weights_mapper: WeightsMapper | None = None,
tensorizer_config_dict: dict | None = None,
skip_prefixes: list[str] | None = None,
moe_ep_spec: MoEEPLoadSpec | None = None,
) -> "LoRAModel":
"""Create a LoRAModel from a local checkpoint.
@@ -425,6 +343,11 @@ def _patch_lora_key_prefix():
skip_prefixes: List of module name prefixes to skip during loading.
Models can define this to skip modules not used in inference
(e.g., MTP layers). Format: ["mtp."]
moe_ep_spec: When 2D FusedMoE LoRA modules are present with
expert parallelism enabled, the (ep_rank, local, global)
slicing metadata shared across all MoE layers. Non-local
expert weights are skipped at read time instead of being
loaded and discarded later.
Returns:
Loaded LoRA Model.
@@ -449,22 +372,13 @@ def _patch_lora_key_prefix():
continue
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
# Case for expert lora weights.
# For standard MoE models the name ends in "...experts",
# so expert_idx+1 yields "experts" which is in
# expected_lora_modules.
# For Qwen 3.5 MoE (and similar models) the expert index
# is embedded: "...experts.N.down_proj". Taking everything
# after ".experts" gives "experts.N.down_proj" which is
# never in the expected set even though "down_proj" is.
# Qwen3-30B-A3B goes the other way: the expected set
# contains the fully-qualified per-expert name
# ("experts.N.down_proj") but not the bare suffix.
# Accept either form.
## START PATCHED CODE (upstream only accepts the qualified form)
if ".experts" in module_name:
expert_suffix = module_name.split(".")[-1]
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
unexpected_modules.append(module_name)
## END PATCHED CODE
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
unexpected_modules.append(module_name)
@@ -481,11 +395,15 @@ def _patch_lora_key_prefix():
from tensorizer import TensorDeserializer
tensorizer_config = TensorizerConfig(**tensorizer_config_dict)
lora_tensor_path = os.path.join(tensorizer_config.tensorizer_dir, "adapter_model.tensors")
tensorizer_dir = tensorizer_config.tensorizer_dir
if tensorizer_dir is None:
raise ValueError("tensorizer_dir must be set in tensorizer config.")
lora_tensor_path = os.path.join(tensorizer_dir, "adapter_model.tensors")
tensorizer_args = tensorizer_config._construct_tensorizer_args()
tensors = TensorDeserializer(
lora_tensor_path,
dtype=tensorizer_config.dtype,
device=device,
**tensorizer_args.deserialization_kwargs,
)
check_unexpected_modules(tensors)
@@ -502,11 +420,18 @@ def _patch_lora_key_prefix():
# Load tensors if there are only expected modules.
check_unexpected_modules(f)
for module in f.keys(): # noqa
if moe_ep_spec is not None and _is_remote_expert_key(module, moe_ep_spec):
continue
tensors[module] = f.get_tensor(module)
elif os.path.isfile(lora_bin_file_path) or os.path.isfile(lora_pt_file_path):
lora_file_path = lora_bin_file_path if os.path.isfile(lora_bin_file_path) else lora_pt_file_path
tensors = torch.load(lora_file_path, map_location=device, weights_only=True)
check_unexpected_modules(tensors)
if moe_ep_spec is not None:
# `.bin`/`.pt` adapters can't be lazy-loaded, but pruning
# the dict here still frees the non-local expert tensors
# before the dtype cast / pin_memory work that follows.
tensors = {k: v for k, v in tensors.items() if not _is_remote_expert_key(k, moe_ep_spec)}
else:
raise ValueError(f"{lora_dir} doesn't contain tensors")
@@ -524,177 +449,6 @@ def _patch_lora_key_prefix():
LoRAModel.from_local_checkpoint = classmethod(_patched_from_local_checkpoint)
# Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
def monkey_patch_load_lora_adapter():
from http import HTTPStatus
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
from vllm.entrypoints.openai.models.serving import (
OpenAIServingModels,
create_error_response,
)
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
logger = init_logger(__name__)
async def _patched_load_lora_adapter(
self: OpenAIServingModels, request: LoadLoRAAdapterRequest, base_model_name: str | None = None
) -> ErrorResponse | str:
lora_name = request.lora_name
# Ensure atomicity based on the lora name
async with self.lora_resolver_lock[lora_name]:
lora_path = request.lora_path
## START PATCHED CODE
if lora_name in self.lora_requests:
lora_request = self.lora_requests[lora_name]
lora_request.lora_path = lora_path
else:
unique_id = self.lora_id_counter.inc(1)
lora_request = LoRARequest(lora_name=lora_name, lora_int_id=unique_id, lora_path=lora_path)
## END PATCHED CODE
if base_model_name is not None and self.is_base_model(base_model_name):
lora_request.base_model_name = base_model_name
# Validate that the adapter can be loaded into the engine
# This will also preload it for incoming requests
try:
await self.engine_client.add_lora(lora_request)
except Exception as e:
error_type = "BadRequestError"
status_code = HTTPStatus.BAD_REQUEST
if "No adapter found" in str(e):
error_type = "NotFoundError"
status_code = HTTPStatus.NOT_FOUND
return create_error_response(message=str(e), err_type=error_type, status_code=status_code)
self.lora_requests[lora_name] = lora_request
logger.info("Loaded new LoRA adapter: name '%s', path '%s'", lora_name, lora_path)
return f"Success: LoRA adapter '{lora_name}' added successfully."
OpenAIServingModels.load_lora_adapter = _patched_load_lora_adapter
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
def monkey_patch_LRUCacheWorkerLoRAManager():
from vllm.lora.worker_manager import LoRARequest, LRUCacheLoRAModelManager, LRUCacheWorkerLoRAManager
# The dunder is intended. It's a private method that we're patching.
def _patched__apply_adapters(self: LRUCacheWorkerLoRAManager, lora_requests: set[LoRARequest]) -> None:
loras_map = {lora_request.lora_int_id: lora_request for lora_request in lora_requests if lora_request}
if len(loras_map) > self._adapter_manager.lora_slots:
raise RuntimeError(
f"Number of requested LoRAs ({len(loras_map)}) is greater "
"than the number of GPU LoRA slots "
f"({self._adapter_manager.lora_slots})."
)
for lora in loras_map.values():
## START PATCHED CODE
self.add_adapter(lora, force_load=False)
## END PATCHED CODE
def _patched_add_adapter(
self: LRUCacheWorkerLoRAManager, lora_request: LoRARequest, force_load: bool = True
) -> bool:
# Note that this method is not thread-safe. It may be invoked multiple
# times for the same adapter when using multiple API servers.
# This is ok because it's currently only called from
# the single-threaded core engine loop.
## START PATCHED CODE
if lora_request.lora_int_id not in self.list_adapters() or force_load:
## END PATCHED CODE
# Load the new adapter first to ensure it is actually valid, before
# evicting any existing adapters.
# This may cause the # of loaded lora adapters to very temporarily
# exceed `--max-cpu-loras`.
lora = self._load_adapter(lora_request)
## START PATCHED CODE
self._adapter_manager.remove_adapter(lora.id)
## END PATCHED CODE
# Loading succeeded, now check if we will exceed cache capacity and
# evict if the oldest adapter if so
if len(self._adapter_manager) + 1 > self._adapter_manager.capacity:
assert isinstance(self._adapter_manager, LRUCacheLoRAModelManager)
self._adapter_manager.remove_oldest_adapter()
# Then add the new adapter to the cache
loaded = self._adapter_manager.add_adapter(lora)
else:
# If the lora is already loaded, just touch it to
# update its position in the caches
loaded = self._adapter_manager.get_adapter(lora_request.lora_int_id) is not None
self._adapter_manager.activate_adapter(lora_request.lora_int_id)
return loaded
LRUCacheWorkerLoRAManager._apply_adapters = _patched__apply_adapters
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
# recompiling regex patterns inside is_supported_lora_module — purely to emit
# logger.warning_once about modules that will be ignored. Adapter validity is
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
def monkey_patch_skip_lora_module_warnings():
from vllm.exceptions import LoRAAdapterNotFoundError
from vllm.lora.lora_model import LoRAModel
from vllm.lora.peft_helper import PEFTHelper
from vllm.lora.request import LoRARequest
from vllm.lora.utils import get_adapter_absolute_path
from vllm.lora.worker_manager import WorkerLoRAManager
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
try:
supported_lora_modules = self._adapter_manager.supported_lora_modules
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
expected_lora_lst: list[str] = []
for module in supported_lora_modules:
if module in packed_modules_mapping:
expected_lora_lst.extend(packed_modules_mapping[module])
else:
expected_lora_lst.append(module)
if module == "experts":
expected_lora_lst.append(module)
expected_lora_modules = set(expected_lora_lst)
lora_path = get_adapter_absolute_path(lora_request.lora_path)
peft_helper = PEFTHelper.from_local_dir(
lora_path,
self.max_position_embeddings,
lora_request.tensorizer_config_dict,
)
peft_helper.validate_legal(self.lora_config)
model = self._adapter_manager.model
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
lora = self._lora_model_cls.from_local_checkpoint(
lora_path,
expected_lora_modules,
peft_helper=peft_helper,
lora_model_id=lora_request.lora_int_id,
device="cpu",
dtype=self.lora_config.lora_dtype,
model_vocab_size=self.vocab_size,
tensorizer_config_dict=lora_request.tensorizer_config_dict,
weights_mapper=hf_to_vllm_mapper,
skip_prefixes=lora_skip_prefixes,
)
except FileNotFoundError as e:
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
return lora
WorkerLoRAManager._load_adapter = _patched_load_adapter
# Monkeypatch TokenizeParams to fix overly conservative validation
def monkey_patch_tokenize_params_validation():
"""
@@ -781,9 +535,10 @@ def monkey_patch_minimax_m2_for_lora():
still runs for all wrapped layers when any adapter is active — and it
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
problem because its gate uses the model dtype.
Fix: recreate the gate in model dtype and remove the float32 cast.
FusedMoE already has router_logits_dtype=float32, so routing precision
is preserved inside the expert dispatch.
Fix: rebuild the gate as GateLinear with a bf16 weight (out_dtype=float32
keeps fp32 router logits). vLLM 0.24.0's own forward already drops the
float32 input cast. FusedMoE also has router_logits_dtype=float32, so
routing precision is preserved inside the expert dispatch.
Problem 2 — Adapter key naming mismatch:
PrimeRL saves adapter keys using its internal naming convention
@@ -805,29 +560,21 @@ def monkey_patch_minimax_m2_for_lora():
def _patched_init(self, config, quant_config=None, prefix=""):
_original_init(self, config, quant_config, prefix)
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
self.gate = ReplicatedLinear(
# vLLM 0.24.0 builds the gate as GateLinear with a float32 weight; rebuild it
# with a bf16 weight (model dtype) so the LoRA Triton kernel's float16/bfloat16
# assertion passes, keeping out_dtype=float32 so router logits stay fp32 (the
# GateLinear bf16xbf16->fp32 path).
self.gate = GateLinear(
config.hidden_size,
config.num_local_experts,
bias=False,
quant_config=None,
out_dtype=torch.float32,
prefix=f"{prefix}.gate",
)
def _patched_forward(self, hidden_states):
from vllm.distributed import tensor_model_parallel_all_reduce
num_tokens, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
router_logits, _ = self.gate(hidden_states)
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
if self.tp_size > 1:
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
return final_hidden_states.view(num_tokens, hidden_dim)
MiniMaxM2MoE.__init__ = _patched_init
MiniMaxM2MoE.forward = _patched_forward
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
@@ -872,23 +619,15 @@ def monkey_patch_no_moe_lora():
Otherwise, the oracle will always try to pick TritonExperts.
For blackwells, we want TRTLLMFlashInfer.
"""
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig, logger
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
original_post_init = FusedMoEConfig.__post_init__
def _patched__post_init__(self: FusedMoEConfig):
if self.dp_size > 1:
logger.debug_once("Using FusedMoEConfig::max_num_tokens=%d", self.max_num_tokens)
assert self.max_num_tokens > 0
if self.router_logits_dtype is None:
self.router_logits_dtype = self.in_dtype
if self.hidden_dim_unpadded is None:
self.hidden_dim_unpadded = self.hidden_dim
if self.intermediate_size_per_partition_unpadded is None:
self.intermediate_size_per_partition_unpadded = self.intermediate_size_per_partition
# Disable LoRA for MoE layers
original_post_init(self)
# Disable LoRA for MoE layers. `is_lora_enabled` is only read later during
# kernel selection (modular_kernel / unquantized oracle), never inside
# `__post_init__`, so flipping it after the original runs is sufficient.
self.is_lora_enabled = False
FusedMoEConfig.__post_init__ = _patched__post_init__
@@ -956,12 +695,51 @@ def monkey_patch_fp32_lm_head():
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_fp32_router_logits():
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
branch, whose kernel wants matching dtypes).
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
logger = init_logger(__name__)
_original_init = DeepseekV2MoE.__init__
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
additional_config = get_current_vllm_config().additional_config or {}
if not additional_config.get("fp32_router_logits", False):
return
if self.gate.out_dtype is None:
self.gate.set_out_dtype(torch.float32)
DeepseekV2MoE.__init__ = _patched_init
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
The coordinator child process is spawned on the DP-rank-0 API server while
every engine-core rank on the node is importing and loading weights, so its
own spawn-time re-import can take well over 30s under that CPU/IO
own spawn-time re-import can exceed the hard-coded timeout under that CPU/IO
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
"""
+16 -15
View File
@@ -2,7 +2,6 @@ import logging.config
import os
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
def setup_vllm_env(config: InferenceConfig):
@@ -11,6 +10,22 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
# Nemotron-Nano SWE, PR #2506; upstream fix vllm#42779 is still unmerged). V1 keeps
# the scrub effective for every model and is also required for routed-experts capture
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
# grammar-constrains generation (xgrammar structural tags) for tool_choice
# "required"/named and strict tools — a sampling distribution the trainer never
# sees. Keep it off so rollout logprobs stay faithful for importance ratios.
os.environ.setdefault("VLLM_ENFORCE_STRICT_TOOL_CALLING", "0")
deep_gemm_enabled = "1" if config.use_deep_gemm else "0"
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
@@ -32,17 +47,3 @@ def setup_vllm_env(config: InferenceConfig):
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
logging.config.dictConfig(build_dict_config(config.log.level))
def main():
config = cli(InferenceConfig)
setup_vllm_env(config)
# We import here to be able to set environment variables before importing vLLM
from prime_rl.inference.vllm.server import server # pyright: ignore
server(config, vllm_extra=config.vllm_extra)
if __name__ == "__main__":
main()
+22 -7
View File
@@ -22,7 +22,6 @@ logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_dp_coordinator_startup_timeout,
monkey_patch_harmony_stop_token_propagation,
monkey_patch_load_lora_adapter,
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
@@ -32,9 +31,6 @@ from prime_rl.inference.patches import (
# NOTE: Fix harmony stop token propagation for GPT-OSS models
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
monkey_patch_harmony_stop_token_propagation()
# NOTE: Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
# May be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
monkey_patch_load_lora_adapter()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
@@ -50,7 +46,7 @@ monkey_patch_vllm_padded_input_scrub()
# routed_experts from chat responses since the server-wide enable flag has no
# per-request toggle.
monkey_patch_strip_routed_experts_from_chat()
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
# NOTE: vLLM hard-codes a 120s DP coordinator startup timeout, which the rank-0
# API server blows through when all engine-core ranks on the node are loading
# weights concurrently (multi-node disaggregated deployments).
monkey_patch_dp_coordinator_startup_timeout()
@@ -97,9 +93,29 @@ async def update_weights(request: Request):
@router.post("/load_lora_adapter")
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
"""Wrapper around vLLM's /v1/load_lora_adapter."""
"""Wrapper around vLLM's /v1/load_lora_adapter.
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
changes per policy version; the name is constant, see orchestrator.lora_name).
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``,
so we force it here — that makes the worker re-read the new weights during
``add_lora``, reusing the existing ``lora_int_id``.
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
every generation request; left ``True`` it would force a disk reload on each
scheduler step. The orchestrator awaits this endpoint before dispatching
rollouts for the new version, so the reset always lands before generation.
The reset runs regardless of success/error: vLLM only stores the adapter on
success today, but resetting whatever is stored keeps us correct even if a
future version were to leave a ``load_inplace=True`` request behind on error.
"""
handler = models(raw_request)
lora_request.load_inplace = True
response = await handler.load_lora_adapter(lora_request)
stored = handler.lora_requests.get(lora_request.lora_name)
if stored is not None:
stored.load_inplace = False
if isinstance(response, ErrorResponse):
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
return {"status": "ok"}
@@ -150,7 +166,6 @@ async def custom_init_app_state(
"""
await init_app_state(engine_client, state, args, supported_tasks)
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
state.liveness_timeout_seconds = args.liveness_timeout_seconds
# Swap in our ServingTokens subclass for /inference/v1/generate so the
+18 -22
View File
@@ -1,28 +1,24 @@
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
vLLM 0.20 ships a generic tokens-in / tokens-out handler at
vLLM 0.22 ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs and
priority. Three prime-RL features are not in the upstream protocol though, so
we subclass it to add them back:
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
defaulting. We subclass it for the bits still missing from the upstream handler:
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
header and forwarded to ``engine_client.generate``. The DP-replicated
inference servers prime-RL runs need this to target a specific replica.
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
now does this too; we keep the equivalent path for the DP-replicated
inference servers prime-RL runs.
2. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
source fork.
3. Server-side ``max_tokens`` defaulting — ``ServingTokens`` hands the
client-supplied ``SamplingParams`` to the engine verbatim, and
``SamplingParams.max_tokens`` defaults to ``16`` (a dataclass-level
default that predates the OpenAI-compat layer). Every other vLLM
endpoint masks this server-side via
``vllm.entrypoints.utils.get_max_tokens`` (see e.g.
``OpenAIServingChat`` at ``serving.py:284``); the disagg endpoint
skips that path. Mirror it here so callers that omit ``max_tokens``
don't silently truncate at 16. Drop once vLLM patches upstream.
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
``get_max_tokens``); we keep an equivalent guard so callers that omit
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
@@ -47,7 +43,7 @@ from vllm.entrypoints.serve.disagg.protocol import (
GenerateResponseChoice,
)
from vllm.entrypoints.serve.disagg.serving import ServingTokens
from vllm.entrypoints.utils import get_max_tokens
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
@@ -156,7 +152,7 @@ class PrimeRlServingTokens(ServingTokens):
@cached_property
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
"""Server-side ``max_tokens`` defaulting inputs, mirroring ``OpenAIServingChat``.
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
Computed lazily because ``custom_init_app_state`` swaps in this
subclass via ``object.__new__`` + ``__dict__.update`` (so our
@@ -180,7 +176,7 @@ class PrimeRlServingTokens(ServingTokens):
request: GenerateRequest,
raw_request: Request | None = None,
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.20). Diffs:
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.22). Diffs:
# (a) inject ``data_parallel_rank`` from the inbound header into
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
@@ -253,10 +249,10 @@ class PrimeRlServingTokens(ServingTokens):
extra["kv_transfer_params"] = request.kv_transfer_params
sampling_params.extra_args = extra
# Server-side ``max_tokens`` defaulting — see module docstring.
# Mirrors ``OpenAIServingChat`` (vllm/entrypoints/openai/chat_completion/
# serving.py:284) so callers that omit ``max_tokens`` don't get capped
# at vLLM's 16-token ``SamplingParams`` default.
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
# ``ServingTokens`` now does this too; kept here so callers that omit
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
# default.
if not await _client_set_max_tokens(raw_request):
diff_sp, override = self._max_tokens_defaults
sampling_params.max_tokens = get_max_tokens(
@@ -3,19 +3,13 @@ import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_LRUCacheWorkerLoRAManager,
monkey_patch_fp32_router_logits,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
monkey_patch_skip_lora_module_warnings,
)
logger = logging.getLogger(__name__)
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
monkey_patch_LRUCacheWorkerLoRAManager()
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
monkey_patch_skip_lora_module_warnings()
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
monkey_patch_minimax_m2_for_lora()
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
@@ -27,3 +21,6 @@ else:
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
monkey_patch_fp32_router_logits()
+1 -43
View File
@@ -24,37 +24,6 @@ else:
logger = init_logger("vllm.inference.vllm.worker_nccl")
# NemotronH mixer.D is dropped by vLLM 0.22's layerwise online-reload path (left uninitialized).
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
"""Work around a vLLM 0.22 layerwise-reload bug for NemotronH.
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
(NaN/inf) and the logits go NaN after a weight update. The received broadcast value is correct,
so restore D from it via the param's own ``weight_loader``. Remove once the upstream bug is fixed.
"""
def _layer_key(name: str) -> str:
index = name.find("layers.")
return name[index:] if index >= 0 else name
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
for name, param in model.named_parameters():
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
continue
tensor = received_by_key.get(_layer_key(name))
if tensor is None:
continue
tensor = tensor.to(device=param.device)
weight_loader = getattr(param, "weight_loader", None)
if weight_loader is not None:
weight_loader(param, tensor)
elif tensor.shape == param.shape:
param.data.copy_(tensor.to(param.dtype))
def receive_integer(communicator: PyNcclCommunicator) -> int:
"""Receive an integer from the trainer master rank using NCCL communicator."""
@@ -179,20 +148,9 @@ class NCCLWeightUpdateWorker(Worker):
update_mla_absorbed_weights(model)
return
# vLLM 0.22's layerwise reload drops NemotronH mixer.D's weight load (see
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
received_reload_fix: dict[str, torch.Tensor] = {}
def _capture_reload_fix(weights):
for name, tensor in weights:
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
yield name, tensor
load_weights_checkpoint_layerwise(
model,
_capture_reload_fix(state_iter),
state_iter,
self.model_runner.model_config,
self.vllm_config,
)
_restore_reload_corrupted_params(model, received_reload_fix)
@@ -5,6 +5,7 @@ from torch.nn import Module
from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
@@ -47,20 +48,20 @@ def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_p
return physical_to_logical
def _build_expert_source_indices(module) -> torch.Tensor | None:
if module._expert_map is None:
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
if routed_experts._expert_map is None:
return None
physical_indices = torch.where(module._expert_map >= 0)[0]
local_indices = module._expert_map[physical_indices]
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
local_indices = routed_experts._expert_map[physical_indices]
physical_indices = physical_indices[local_indices.argsort()]
eplb_layer_state = getattr(module, "eplb_state", None)
eplb_layer_state = getattr(router, "eplb_state", None)
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
if logical_to_physical_map is None:
return physical_indices
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, module.global_num_experts)
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
if (logical_indices < 0).any():
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
@@ -70,14 +71,23 @@ def _build_expert_source_indices(module) -> torch.Tensor | None:
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
"""Map FusedMoE module names to source expert indices local to this worker."""
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
"""Map MoE module names to source expert indices local to this worker.
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
split the state that used to live on the ``FusedMoE`` module: the expert map
(``_expert_map`` / ``global_num_experts``) now lives on
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
remaps incoming flat names via ``remap_moe_expert_weights``.
"""
from vllm.model_executor.layers.fused_moe import MoERunner
source_indices_by_module: dict[str, torch.Tensor] = {}
for module_name, module in model.named_modules():
if not isinstance(module, FusedMoE):
if not isinstance(module, MoERunner):
continue
source_indices = _build_expert_source_indices(module)
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
if source_indices is None:
continue
source_indices_by_module[module_name] = source_indices
@@ -94,7 +104,10 @@ def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Te
skipped: list[str] = []
shape_mismatches: list[str] = []
for name, tensor in state_iter:
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
for name, tensor in remap_moe_expert_weights(state_iter, params):
if name not in params:
skipped.append(name)
continue
-115
View File
@@ -1,115 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable
import torch
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.types import Rollout
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
LinearLengthPenaltyConfig,
)
from prime_rl.utils.utils import import_object
@dataclass
class AdvantageInputs:
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
rollouts: list[vf.Trace]
@dataclass
class AdvantageOutputs:
"""Outputs from advantage computation of a single group."""
advantages: list[float]
AdvantageFn = Callable[..., AdvantageOutputs]
"""Type for an advantage function.
Expected signature:
def my_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
...
The function receives a single group and returns a list of advantages with one
entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
"""
def default_advantage_fn(
inputs: AdvantageInputs,
length_penalty: LinearLengthPenaltyConfig | None = None,
max_seq_len: int | None = None,
length_weighted_baseline: bool = False,
) -> AdvantageOutputs:
"""Default GRPO advantage for a single group: reward minus per-group baseline.
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
mean reward as the baseline instead of the plain mean.
"""
rewards = torch.tensor([r.reward for r in inputs.rollouts], dtype=torch.float32)
lengths = torch.tensor([r.completion_len for r in inputs.rollouts], dtype=rewards.dtype)
if length_penalty is not None:
if max_seq_len is None:
raise ValueError("max_seq_len is required when length_penalty is enabled")
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
if length_penalty.gate_by_correctness:
penalty = penalty * rewards
rewards = rewards - penalty
if length_weighted_baseline:
baseline = (lengths * rewards).sum() / lengths.sum()
else:
baseline = rewards.mean()
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
"""Setup advantage function from config."""
if isinstance(config, CustomAdvantageConfig):
custom_fn = import_object(config.import_path)
kwargs = config.kwargs
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return custom_fn(inputs, **kwargs)
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(
inputs,
length_penalty=config.length_penalty,
max_seq_len=max_seq_len,
length_weighted_baseline=config.length_weighted_baseline,
)
return advantage_fn
def assign_advantages(
rollouts: list[Rollout],
advantage_fn: AdvantageFn | None,
) -> None:
"""Compute and assign advantages for one finished group of rollouts
(``TrainSink.process_group`` hands in a single group's surviving rollouts).
``advantage_fn=None`` is the trivial case (advantage = reward); a custom
``advantage_fn`` receives the ``vf.Trace``\\ s via ``AdvantageInputs.rollouts``.
"""
if advantage_fn is None:
for rollout in rollouts:
rollout.advantage = rollout.reward
return
result = advantage_fn(AdvantageInputs(rollouts=[r for r in rollouts]))
for rollout, advantage in zip(rollouts, result.advantages):
rollout.advantage = advantage
@@ -0,0 +1,81 @@
"""Orchestrator-side algorithm runtime.
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``opd``,
``opsd``, ``sft``) — each named class owns its scoring hooks
(``score_rollout`` / ``score_group``) and declares what it needs (loss
component, a "teacher", ...). One instance per env, built by
:func:`build_algorithm`. A new credit-assignment scheme is a new named class:
subclass :class:`Algorithm`, assign advantages in the hook whose timing fits,
and register it below.
- ``base`` — the :class:`Algorithm` base class, whose non-virtual
``finalize_rollout`` / ``finalize_group`` methods the pipeline drives.
Advantages are per-token everywhere they are stored or shipped — there is no
scalar advantage in the pipeline. An algorithm assigns credit in its scoring
hook via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
rollout's completion tokens (uniform credit, the common case), or an explicit
full-length-N per-token list aligned to the concatenated sample token_ids
(0.0 off-mask).
- ``routing`` — wire-field stamping: per-token component weight streams
(rl / ce / ref_kl) and the per-token advantage stream.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_pool
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
from prime_rl.orchestrator.algo.opd import OPDAlgorithm
from prime_rl.orchestrator.algo.opsd import OPSDAlgorithm
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
from prime_rl.orchestrator.types import Rollout
if TYPE_CHECKING:
from prime_rl.configs.algorithm import AlgoConfig
from prime_rl.utils.client import InferencePool
# Runtime dispatch is keyed on ``algo.type`` — it names the algorithm, and
# each config class's defaults are its vetted parameterization.
ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
"grpo": GRPOAlgorithm,
"echo": EchoAlgorithm,
"max_rl": MaxRLAlgorithm,
"opd": OPDAlgorithm,
"opsd": OPSDAlgorithm,
"sft": SFTDistillAlgorithm,
}
def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling Sampler interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
return cls(config, policy_pool)
__all__ = [
"Algorithm",
"EchoAlgorithm",
"GRPOAlgorithm",
"MaxRLAlgorithm",
"OPDAlgorithm",
"OPSDAlgorithm",
"Rollout",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_pool",
"stamp_advantages",
"stamp_loss_routing",
]

Some files were not shown because too many files have changed in this diff Show More