Compare commits

...
Author SHA1 Message Date
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
51 changed files with 2361 additions and 2019 deletions
+2
View File
@@ -2,6 +2,8 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`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.
+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"
+2 -2
View File
@@ -38,10 +38,10 @@ type = "zero_advantage"
enforce = false
# Qwen3 finetune with the standard PI template patch; always re-emits prior
# <think> blocks, matched by the qwen3 renderer's preserve_all_thinking.
# <think> blocks, matched by renderer thinking_retention.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
thinking_retention = "all"
[trainer.optim]
lr = 1e-6
+124
View File
@@ -0,0 +1,124 @@
# v1 RL ablation: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, bash_edit 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.
#
# 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.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1" }
harness = { id = "bash_edit", runtime = { type = "prime", labels = ["glm45air-swe"] } }
[orchestrator.prime_monitor]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash_edit 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 = "bash_edit", 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
+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
+2 -2
View File
@@ -35,8 +35,8 @@ num_prefill_nodes = 8
num_prefill_replicas = 4
num_decode_nodes = 8
num_decode_replicas = 1
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"}
[deployment.router]
type = "llm-d"
+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"
-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
+3 -3
View File
@@ -282,14 +282,14 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
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).
Two built-in **length penalties** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling: `tokens` penalizes long completions by weighted token cost, `turns` penalizes long multi-turn rollouts by turn count.
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.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "tokens"
type = "linear"
```
@@ -312,7 +312,7 @@ class MyAlgorithm(Algorithm):
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). Shared math like `efficiency_shaping` lives in `prime_rl.orchestrator.algo.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.
+35 -1
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
@@ -165,6 +166,39 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
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.
+4 -2
View File
@@ -253,10 +253,12 @@ For configuring various knobs with environment variables, we enable you to confi
[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.
+2 -1
View File
@@ -151,7 +151,6 @@ The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every
```toml
[trainer.model]
fused_lm_head_token_chunk_size = 1024 # default
# fused_lm_head_token_chunk_size = "auto" # picks 8192 for RL
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
@@ -180,6 +179,8 @@ The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fu
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):
-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 -13
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,17 +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"]
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
```
-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"
@@ -91,24 +91,22 @@ class SamplingConfig(BaseConfig):
# ---------------------------------------------------------------------------
class TokensLengthPenaltyConfig(BaseConfig):
type: Literal["tokens"] = "tokens"
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."""
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on model completion tokens. Finite and non-negative."""
type: Literal["linear"] = "linear"
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
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."""
class TurnsLengthPenaltyConfig(BaseConfig):
type: Literal["turns"] = "turns"
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
LengthPenaltyConfig: TypeAlias = LinearLengthPenaltyConfig
class EchoRoleConfig(BaseConfig):
@@ -199,7 +197,7 @@ class GRPOAlgoConfig(BaseAlgoConfig):
action_loss_type: ClassVar[ActionLossType] = "rl"
length_penalty: LengthPenaltyConfig | None = None
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
"""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):
@@ -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
@@ -300,10 +300,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] = {}
@@ -352,6 +352,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``."""
@@ -13,6 +13,7 @@ from prime_rl.configs.algorithm import (
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
EnvVars,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
@@ -500,6 +501,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
@@ -16,6 +16,7 @@ from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.shared import (
EnvVars,
SlurmConfig,
VLMConfig,
)
@@ -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."""
@@ -6,6 +6,7 @@ from pydantic import Field, model_validator
from renderers import RendererConfig
from prime_rl.configs.shared import (
EnvVars,
HeartbeatConfig,
SlurmConfig,
TrainerLogConfig,
@@ -173,6 +174,9 @@ class SFTExperimentalConfig(BaseConfig):
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
@@ -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"
@@ -6,6 +6,7 @@ from pydantic import Field, model_validator
from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
@@ -188,8 +189,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"] = 1024
"""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. SFT training silently disables this (not supported yet)."""
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
@@ -568,6 +569,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,13 +661,6 @@ 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.ep != "auto" and self.model.impl not in ("custom", "auto"):
+107 -64
View File
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers>=0.1.15.dev400",
"verifiers>=0.1.15.dev405",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -66,47 +66,69 @@ flash-attn-cute = [
"flash-attn-4",
]
envs = [
"alphabet-sort",
"general-agent",
"logic-env",
"math-env",
"math-python",
"reverse-text",
"rlm-swe",
"rlm-search",
"uuid-ctf-v1",
"wiki-search",
"wordle",
"reverse-text-v1",
"gsm8k-v1",
"math-env-v1",
"aime24-v1",
"aime25-v1",
"aime26-v1",
"alphabet-sort",
"alphabet-sort-v1",
"scaleswe-v1",
"apex-shortlist-v1",
"browsecomp-v1",
"code-golf-v1",
"color-codeword-v1",
"deepdive-v1",
"gpqa-v1",
"livecodebench-v1",
"r2e-gym-v1",
"terminal-bench-2-v1",
"code-golf-v1",
"deepwiki-v1",
"glossary-v1",
"swelego-v1",
"wiki-search-v1",
"wikispeedia-v1",
"wordle-v1",
"forth-lang-v1",
"general-agent",
"general-agent-v1",
"swebench-verified-v1",
"tau2-bench-v1",
"math500-v1",
"mmlu-pro-v1",
"ifeval-v1",
"simpleqa-verified-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",
"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",
"rlm-search",
"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",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -166,7 +188,6 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers>=0.1.15.dev400",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -218,47 +239,69 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", 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 }
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 }
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", 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/research-environments/environments/math_env_v1", 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 }
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_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 }
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", 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 }
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
glossary-v1 = { path = "deps/verifiers/environments/glossary_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 }
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/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 }
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
scaleswe-v1 = { path = "deps/research-environments/environments/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/swebench_pro_v1", editable = true }
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
swelego-v1 = { path = "deps/research-environments/environments/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/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 }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
+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`.
+10 -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"
@@ -81,8 +83,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 +153,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
+48 -10
View File
@@ -26,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"
@@ -163,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,
@@ -214,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)
@@ -260,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,
@@ -356,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,
@@ -387,8 +419,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,
@@ -420,6 +455,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)
+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,
+3 -4
View File
@@ -14,10 +14,9 @@ turns the signal half into runtime objects (the sampling half is the env's
and register it below.
- ``base`` — the :class:`Algorithm` base class, whose non-virtual
``finalize_rollout`` / ``finalize_group`` methods the pipeline drives.
- ``advantage`` — shared advantage math (``efficiency_shaping``). 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
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).
@@ -1,41 +0,0 @@
from __future__ import annotations
from jaxtyping import Float
from torch import Tensor
def efficiency_shaping(
rewards: Float[Tensor, "group_size"],
costs: Float[Tensor, "group_size"],
) -> Float[Tensor, "group_size"]:
"""Correctness-gated efficiency shaping with bounded advantages.
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
(e.g., completion length in tokens or number of turns).
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
"""
max_reward = rewards.max()
correct_mask = rewards >= max_reward
num_correct = correct_mask.sum()
# No shaping when max reward is 0 — no correct rollouts to differentiate
if max_reward <= 0:
return rewards - rewards.mean()
# Mean cost of correct rollouts
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
if mean_correct_cost <= 0:
return rewards - rewards.mean()
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
shaped_rewards = rewards * (1 + bonus * correct_mask)
return shaped_rewards - shaped_rewards.mean()
+15 -17
View File
@@ -4,10 +4,8 @@ from typing import TYPE_CHECKING
import torch
from prime_rl.configs.algorithm import GRPOAlgoConfig, TokensLengthPenaltyConfig
from prime_rl.orchestrator.algo.advantage import efficiency_shaping
from prime_rl.configs.algorithm import GRPOAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.utils import get_tool_response_len
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
@@ -25,21 +23,21 @@ class GRPOAlgorithm(Algorithm):
async def score_group(self, group: list[Rollout]) -> None:
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
lp = self.length_penalty
if lp is None:
length_penalty = self.length_penalty
if length_penalty is None:
advantages = rewards - rewards.mean()
elif isinstance(lp, TokensLengthPenaltyConfig):
costs = torch.tensor(
[
lp.completion_weight * rollout.completion_len
+ lp.tool_response_weight * get_tool_response_len(rollout)
for rollout in group
],
dtype=rewards.dtype,
else:
output = torch.tensor([rollout.num_output_tokens for rollout in group], dtype=rewards.dtype)
total = torch.tensor([rollout.num_total_tokens for rollout in group], dtype=rewards.dtype)
turns = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
input = total - output
penalty_frac = (
length_penalty.num_output_tokens_weight * (output / output.max().clamp(min=1))
+ length_penalty.num_input_tokens_weight * (input / input.max().clamp(min=1))
+ length_penalty.num_turns_weight * (turns / turns.max().clamp(min=1))
)
advantages = efficiency_shaping(rewards, costs)
else: # TurnsLengthPenaltyConfig
costs = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
advantages = efficiency_shaping(rewards, costs)
penalty = rewards.mean() * penalty_frac
shaped_rewards = rewards - penalty
advantages = shaped_rewards - shaped_rewards.mean()
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
+1 -1
View File
@@ -131,7 +131,7 @@ class EvalSink:
if valid:
rewards = [r.reward for r in valid]
lens = [sum(b.output_len for b in r.branches) for r in valid]
lens = [sum(b.num_output_tokens for b in r.branches) for r in valid]
metrics.group_size = self.group_size_for(env_name)
metrics.reward_mean = float(sum(rewards) / len(rewards))
metrics.completion_len_mean = float(sum(lens) / len(lens))
+2 -2
View File
@@ -31,7 +31,7 @@ class MetricsBuilder:
existing dashboards / alerts keep working."""
num_rollouts = len(rollouts)
num_unique_examples = len({r.group_id for r in rollouts})
num_tokens = sum(r.total_tokens for r in rollouts)
num_tokens = sum(r.num_total_tokens for r in rollouts)
results_df = pd.DataFrame(
{
@@ -42,7 +42,7 @@ class MetricsBuilder:
"is_truncated": [r.is_truncated for r in rollouts],
"is_filtered": [r.is_filtered for r in rollouts],
"stop_condition": [r.stop_condition for r in rollouts],
"seq_len": [r.total_tokens for r in rollouts],
"seq_len": [r.num_total_tokens for r in rollouts],
"prefill_len": metrics.rollout_prefill_lens,
"decode_len": metrics.rollout_decode_lens,
"samples_per_rollout": metrics.samples_per_rollout,
+1 -1
View File
@@ -559,7 +559,7 @@ class Orchestrator:
num_rollouts = len(batch.rollouts)
num_unique_examples = len({r.group_id for r in batch.rollouts})
num_tokens = sum(r.total_tokens for r in batch.rollouts)
num_tokens = sum(r.num_total_tokens for r in batch.rollouts)
self.progress.total_tokens += num_tokens
self.progress.total_samples += num_rollouts
self.progress.total_problems += num_unique_examples
+3 -3
View File
@@ -63,7 +63,7 @@ class TrainSink:
self.pending_batch: list[Rollout] = []
# Running token total of ``pending_batch`` (token-batched runs), kept in
# sync on append/pop so the readiness check never re-walks the uncached
# ``Trace.total_tokens`` graph property per arrival.
# ``Trace.num_total_tokens`` graph property per arrival.
self.pending_tokens: int = 0
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
@@ -216,7 +216,7 @@ class TrainSink:
r.is_filtered = False
self.pending_batch.append(r)
if self.token_batch_size is not None:
self.pending_tokens += r.total_tokens
self.pending_tokens += r.num_total_tokens
# Per-group summary. One line per finalized group; per-filter
# detection breakdown lives at debug level in ``apply_filters``
@@ -243,7 +243,7 @@ class TrainSink:
cut = 0
running = 0
for i, r in enumerate(self.pending_batch):
running += r.total_tokens
running += r.num_total_tokens
cut = i + 1
if running >= self.token_batch_size:
break
+6 -21
View File
@@ -57,13 +57,6 @@ mkdir -p $OUTPUT_DIR/logs/inference
rm -f $OUTPUT_DIR/logs/inference/*.log
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
export VLLM_CACHE_ROOT=/tmp/.vllm_cache_$(whoami)
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
@@ -176,6 +169,10 @@ srun --kill-on-bad-exit=1 bash -c '
INFER_NODE_RANK=$SLURM_PROCID
LOCAL_IP=$(hostname -I | awk "{print \$1}")
# Inference env vars: launcher defaults + [inference.env_vars]
{%- for key, value in inference_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
@@ -195,20 +192,11 @@ srun --kill-on-bad-exit=1 bash -c '
# Reconstruct hostnames array
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
export VLLM_WORKER_MULTIPROC_METHOD=spawn
{%- if use_deep_gemm %}
export VLLM_USE_DEEP_GEMM=1
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
export VLLM_ENGINE_READY_TIMEOUT_S=4200
export UCX_TLS=all
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
@@ -251,7 +239,7 @@ srun --kill-on-bad-exit=1 bash -c '
PORT=$PREFILL_PORT
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + SUB_REPLICA * NODES_PER_PREFILL_REPLICA))]}"
{% for key, value in prefill_env_overrides.items() %}
{% for key, value in prefill_env_vars.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
@@ -266,7 +254,7 @@ srun --kill-on-bad-exit=1 bash -c '
PORT=$DECODE_PORT
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + NUM_PREFILL_NODES + SUB_REPLICA * NODES_PER_DECODE_REPLICA))]}"
{% for key, value in decode_env_overrides.items() %}
{% for key, value in decode_env_vars.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
@@ -316,7 +304,6 @@ srun --kill-on-bad-exit=1 bash -c '
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
@@ -341,8 +328,6 @@ srun --kill-on-bad-exit=1 bash -c '
done
{%- else %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Required for graph compilation to work
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False
uv run inference \
@ $CONFIG_PATH \
+19 -24
View File
@@ -64,14 +64,8 @@ rm -f $OUTPUT_DIR/logs/inference/*.log
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_RUN_ID=$(python3 -c "import uuid; print(uuid.uuid4().hex)")
export WANDB_SHARED_RUN_ID=${WANDB_SHARED_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
# Networking
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
@@ -208,7 +202,6 @@ srun --kill-on-bad-exit=1 bash -c '
# Higher ulimit
ulimit -n 65536
export GIT_LFS_SKIP_SMUDGE=1
# Infiniband setup
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
@@ -217,9 +210,11 @@ srun --kill-on-bad-exit=1 bash -c '
{% if num_infer_nodes > 0 -%}
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
INFER_NODE_RANK=$SLURM_PROCID
export VLLM_WORKER_MULTIPROC_METHOD=spawn
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
{%- for key, value in inference_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
LOCAL_IP=$(hostname -I | awk "{print \$1}")
{%- if kv_offload %}
@@ -242,18 +237,12 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% if is_disaggregated -%}
# PD disaggregated: NIXL KV transfer + role-based inference
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if use_deep_gemm %}
export VLLM_USE_DEEP_GEMM=1
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
export VLLM_ENGINE_READY_TIMEOUT_S=4200
export UCX_TLS=all
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
@@ -288,7 +277,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
PORT=$PREFILL_PORT
START_RANK=$((ROLE_RANK * INFERENCE_DP_LOCAL))
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + SUB_REPLICA * NODES_PER_PREFILL_REPLICA))]}"
{% for key, value in prefill_env_overrides.items() %}
{% for key, value in prefill_env_vars.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
@@ -302,7 +291,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
PORT=$DECODE_PORT
START_RANK=$((ROLE_RANK * INFERENCE_DP_LOCAL))
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + NUM_PREFILL_NODES + SUB_REPLICA * NODES_PER_DECODE_REPLICA))]}"
{% for key, value in decode_env_overrides.items() %}
{% for key, value in decode_env_vars.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
@@ -385,10 +374,10 @@ else
TRAIN_NODE_RANK=$SLURM_PROCID
{%- endif %}
export HF_HUB_OFFLINE=1
# This is required for compilation to work correctly
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
# Trainer env vars: launcher defaults + [env_vars] + [trainer.env_vars]
{%- for key, value in trainer_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
@@ -415,8 +404,14 @@ else
{% if orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --model.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --model.client.admin-base-url $ADMIN_URLS"
{%- if orchestrator_env_vars %}
# Orchestrator env vars from [env_vars] + [orchestrator.env_vars]
{%- for key, value in orchestrator_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
{%- endif %}
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
@@ -36,12 +36,6 @@ export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/logs/trainer
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
echo "HOSTNAMES=${HOSTNAMES[@]}"
@@ -101,7 +95,6 @@ srun --kill-on-bad-exit=1 bash -c '
# Higher ulimit
ulimit -n 65536
export GIT_LFS_SKIP_SMUDGE=1
# Infiniband setup
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
@@ -109,10 +102,10 @@ srun --kill-on-bad-exit=1 bash -c '
TRAIN_NODE_RANK=$SLURM_PROCID
export HF_HUB_OFFLINE=1
# This is required for compilation to work correctly
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
# Trainer env vars: launcher defaults + [env_vars]
{%- for key, value in trainer_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
echo $HOSTNAMES | tee $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
uv run torchrun \
+4 -4
View File
@@ -349,8 +349,8 @@ class PrimeMonitor(Monitor):
"messages": [m.model_dump(mode="json") for m in branch.messages],
"reward": rollout.reward,
"advantage": rollout.scalar_advantage(),
"num_input_tokens": branch.prompt_len,
"num_output_tokens": branch.completion_len,
"num_input_tokens": branch.num_input_tokens,
"num_output_tokens": branch.num_output_tokens,
}
for branch in branches
]
@@ -373,8 +373,8 @@ class PrimeMonitor(Monitor):
"advantage": rollout.scalar_advantage(),
"metrics": json.dumps(rollout.metrics),
"timing": rollout.timing.model_dump_json(),
"num_input_tokens": branches[-1].prompt_len,
"num_output_tokens": branches[-1].completion_len,
"num_input_tokens": branches[-1].num_input_tokens,
"num_output_tokens": branches[-1].num_output_tokens,
"created_at": now,
}
)
+5 -5
View File
@@ -44,16 +44,16 @@ def format_log_message(
log_lines.append(f"{i2}{'All nodes:':<{col - 1}}tail -F {log_dir}/inference/node_*.log")
if train_env_names:
env_log_dir = log_dir / "envs"
log_lines.append(f"{i1}{'Envs:':<{col}}tail -F {env_log_dir}/*/*/*.log")
log_lines.append(f"{i2}{'Train:':<{col - 1}}tail -F {env_log_dir}/train/*/*.log")
log_lines.append(f"{i1}{'Envs:':<{col}}tail -F {env_log_dir}/*/*.log")
log_lines.append(f"{i2}{'Train:':<{col - 1}}tail -F {env_log_dir}/train/*.log")
for name in train_env_names:
short = name if len(name) <= max_name else name[: max_name - 3] + "..."
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/train/{name}/*.log")
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/train/{name}.log")
if eval_env_names:
log_lines.append(f"{i2}{'Eval:':<{col - 1}}tail -F {env_log_dir}/eval/*/*.log")
log_lines.append(f"{i2}{'Eval:':<{col - 1}}tail -F {env_log_dir}/eval/*.log")
for name in eval_env_names:
short = name if len(name) <= max_name else name[: max_name - 3] + "..."
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/eval/{name}/*.log")
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/eval/{name}.log")
return "Logs:\n" + "\n".join(log_lines)
+20
View File
@@ -13,6 +13,26 @@ from prime_rl.utils.logger import get_logger
PRIME_RL_PROC_PREFIX = "PRIME-RL"
# Applied to every launched component (trainer, orchestrator, inference).
DEFAULT_COMMON_ENV_VARS: dict[str, str] = {
"CUDA_DEVICE_ORDER": "PCI_BUS_ID",
"PYTHONUNBUFFERED": "1",
"OMP_NUM_THREADS": "1",
"GIT_LFS_SKIP_SMUDGE": "1",
}
DEFAULT_TRAINER_ENV_VARS: dict[str, str] = {
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
}
DEFAULT_INFERENCE_ENV_VARS: dict[str, str] = {
"VLLM_WORKER_MULTIPROC_METHOD": "spawn",
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:False",
"VLLM_ENGINE_READY_TIMEOUT_S": "4200",
"UCX_TLS": "all",
}
def set_proc_title(name: str) -> None:
"""Set the process title for visibility in tools like ``ps`` and ``htop``.
+38 -125
View File
@@ -1,28 +1,18 @@
import asyncio
import math
import pytest
import torch
import verifiers.v1 as vf
from prime_rl.configs.algorithm import (
GRPOAlgoConfig,
LinearLengthPenaltyConfig,
MaxRLAlgoConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
)
from prime_rl.orchestrator.algo.advantage import efficiency_shaping
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import Rollout
# Token-cost penalty over completion tokens only (the harness tool-response
# metric is absent on these rollouts, so the tool weight contributes nothing).
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
# Token-cost penalty over tool-response tokens only.
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
def _build_rollout(
reward: float,
@@ -131,13 +121,6 @@ def _make_group(rewards, completion_lengths=None, num_turns=None) -> list[Rollou
return rollouts
def _shape(rewards: list[float], costs: list[float]) -> list[float]:
"""Run ``efficiency_shaping`` directly on reward/cost vectors."""
return efficiency_shaping(
torch.tensor(rewards, dtype=torch.float32), torch.tensor(costs, dtype=torch.float32)
).tolist()
def _scalar(rollout: Rollout) -> float:
"""The per-rollout advantage scalar an algorithm assigned — broadcast over
the rollout's trainable (mask-True) tokens, so any trainable position holds it."""
@@ -185,123 +168,53 @@ def test_max_rl_mean_normalized():
# --------------------------------------------------------------------------
# efficiency_shaping: the bounded correctness-gated reward transform (pure).
# GRPO linear length penalty: pass_rate-scaled penalty before the baseline.
# --------------------------------------------------------------------------
def test_efficiency_mixed_group():
"""Mixed group: shaping preserves zero-mean, shorter correct gets higher advantage."""
# mean_correct_cost = (10+30+20)/3 = 20
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
# shaped = R * (1 + bonus * correct) = [1.5, 1, 0, 1]; baseline = 0.875
advs = _shape([1.0, 1.0, 0.0, 1.0], [10, 30, 20, 20])
assert advs == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_all_correct_group():
"""All-correct group: zero-mean, shorter gets higher advantage."""
# mean_cost = 70/3; bonus = clamp(1 - [10,20,40]/(70/3), 0, 1) = [4/7, 1/7, 0]
advs = _shape([1.0, 1.0, 1.0], [10, 20, 40])
shaped = [11.0 / 7, 8.0 / 7, 1.0]
mean_shaped = sum(shaped) / len(shaped)
assert advs == pytest.approx([s - mean_shaped for s in shaped], abs=1e-6)
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
assert advs[0] > advs[1] > advs[2]
def test_efficiency_all_zero_rewards():
"""When all rewards are 0 there is no correct rollout — no shaping (plain GRPO)."""
assert _shape([0.0, 0.0, 0.0], [10, 20, 15]) == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
def test_efficiency_single_correct():
"""A single correct rollout sits at its own mean cost (bonus 0) — plain GRPO."""
assert _shape([1.0, 0.0, 0.0, 0.0], [100, 50, 200, 150]) == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
def test_efficiency_shorter_correct_higher_advantage():
"""Among correct rollouts, shorter always gets higher advantage."""
advs = _shape([1.0, 1.0, 1.0, 0.0, 0.0], [50, 100, 200, 80, 120])
assert advs[0] > advs[1] > advs[2]
assert all(a > 0 for a in advs[:3])
assert all(a < 0 for a in advs[3:])
def test_efficiency_zero_mean_preserved():
assert sum(_shape([1.0, 1.0, 0.0, 1.0], [10, 30, 20, 20])) == pytest.approx(0.0, abs=1e-6)
assert sum(_shape([1.0, 1.0, 1.0], [10, 20, 40])) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_amplification_bounded():
"""Even with extreme length outliers, amplification is capped at 2x (advantage < 1)."""
assert _shape([1.0, 1.0, 0.0], [1, 10000, 5000])[0] < 1.0 + 1e-3
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
"""All-zero costs would divide by zero — fall back to plain GRPO, no NaNs."""
advs = _shape([1.0, 1.0, 0.0], [0.0, 0.0, 0.0])
assert not any(math.isnan(a) for a in advs)
assert advs == pytest.approx([1.0 / 3, 1.0 / 3, -2.0 / 3], abs=1e-6)
# --------------------------------------------------------------------------
# GRPO length-penalty cost dispatch (rollout fields -> per-rollout cost).
# --------------------------------------------------------------------------
def test_grpo_tokens_with_tool_response_weight():
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
def group():
return [
_build_rollout(1.0, sampled_lengths=[10], metrics={"rlm_total_tool_response_tokens": 200}),
_build_rollout(1.0, sampled_lengths=[10], metrics={"rlm_total_tool_response_tokens": 0}),
_build_rollout(1.0, sampled_lengths=[10], metrics={"rlm_total_tool_response_tokens": 100}),
]
# completion tokens identical (10 each) → completion-only shaping is a no-op
assert _grpo(group(), length_penalty=_TOKENS_COMPLETION) == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
# tool-response only: costs are [200, 0, 100], so only the below-mean rollout (idx 1) amplifies
advs = _grpo(group(), length_penalty=_TOKENS_TOOL_ONLY)
assert advs[1] > advs[0]
assert advs[1] > advs[2]
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_grpo_fractional_weight_with_int_rewards():
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
lengths = [7, 11, 13]
rewards_int = [1, 1, 0]
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
int_group = [_build_rollout(r, sampled_lengths=[length]) for r, length in zip(rewards_int, lengths)]
float_group = [_build_rollout(float(r), sampled_lengths=[length]) for r, length in zip(rewards_int, lengths)]
assert _grpo(int_group, length_penalty=fractional) == pytest.approx(
_grpo(float_group, length_penalty=fractional), abs=1e-6
def test_linear_equal_lengths_reduce_to_plain_grpo():
"""Equal completion length and turns → every rollout takes the same penalty
fraction, so subtracting it leaves the centered advantages unchanged."""
penalized = _grpo(
_make_group(rewards=[1.0, 0.0, 1.0], completion_lengths=[10, 10, 10], num_turns=[2, 2, 2]),
length_penalty=LinearLengthPenaltyConfig(),
)
plain = _grpo(_make_group(rewards=[1.0, 0.0, 1.0], completion_lengths=[10, 10, 10], num_turns=[2, 2, 2]))
assert penalized == pytest.approx(plain, abs=1e-6)
def test_grpo_tokens_default_weights_match_completion_when_no_metric():
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
def group():
return _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
assert _grpo(group(), length_penalty=TokensLengthPenaltyConfig()) == pytest.approx(
_grpo(group(), length_penalty=_TOKENS_COMPLETION), abs=1e-6
)
def test_linear_completion_term_penalizes_longer():
"""With only the completion term, longer completions get a larger penalty and a
lower advantage; advantages stay zero-mean."""
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.25, num_input_tokens_weight=0.0, num_turns_weight=0.0)
advs = _grpo(_make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 30]), length_penalty=cfg)
assert advs[0] > advs[1] > advs[2]
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_grpo_turns_penalty():
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
# token counts identical, turns differ: mean_correct_turns = (1+3+2)/3 = 2
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
def test_linear_context_term_penalizes_more_context():
"""The context term penalizes non-completion (prompt / tool-response) tokens: at
equal completion length, more context tokens yields a lower advantage."""
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.0, num_input_tokens_weight=0.25, num_turns_weight=0.0)
group = [
_build_rollout(1.0, sampled_lengths=[10], obs_lengths=[]),
_build_rollout(1.0, sampled_lengths=[10], obs_lengths=[100]),
]
asyncio.run(GRPOAlgorithm(GRPOAlgoConfig(length_penalty=cfg), policy_pool=None).score_group(group))
advs = [_scalar(rollout) for rollout in group]
assert advs[0] > advs[1]
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_linear_turns_term_penalizes_more_turns():
"""The turns term penalizes higher turn counts at equal token lengths."""
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.0, num_input_tokens_weight=0.0, num_turns_weight=0.25)
advs = _grpo(
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[100, 100, 100, 100], num_turns=[1, 3, 2, 2]),
length_penalty=TurnsLengthPenaltyConfig(),
_make_group(rewards=[1.0, 1.0], completion_lengths=[100, 100], num_turns=[1, 4]),
length_penalty=cfg,
)
assert advs == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
assert advs[0] > advs[1]
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
# --------------------------------------------------------------------------
Generated
+1807 -1412
View File
File diff suppressed because it is too large Load Diff