Compare commits

...
Author SHA1 Message Date
Christian RandGitHub f00925c006 fix: propagate use_cache=False to sub-configs for VLM models (#1922)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-01 16:56:52 -08:00
samsjaandGitHub 5a6ab4a968 add vllm 16 back (#1893)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-28 11:48:12 -08:00
DominikandGitHub 5ae5079478 validate mint.json pages exist before syncing docs (#1912)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-27 13:49:47 -08:00
753a728e8a disable fused lm head chunking by default (#1904)
Release / Push CUDA image to Docker (push) Canceled after 0s
* disable fused lm head chunking by default

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* reduce benchmark_regression seq_len to 16384

65536 OOMs on A6000 without fused lm head chunking.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* pin fused lm head chunk size in benchmark regression test

The benchmark baselines were generated with chunking enabled, so
the regression test must explicitly enable it regardless of the
default.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* pin fused lm head chunk size in rl_multi_run CI config

This test uses seq_len=65536 which needs chunking to avoid OOM on
A6000 GPUs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 22:09:32 -08:00
JannikStandGitHub df50bd2eb1 remove disown from orchestrator in multi-node sbatch template (#1907)
Release / Push CUDA image to Docker (push) Canceled after 0s
disown detaches the orchestrator from the shell job table, preventing
it from receiving SIGHUP on shell exit. This causes the orchestrator
and its env server subprocesses to survive as orphans after job
cancellation, leading to port conflicts on subsequent runs.
2026-02-26 20:29:43 -08:00
982a7756ec fix: resolve slurm project_dir to absolute path (#1908)
Release / Push CUDA image to Docker (push) Canceled after 0s
The default Path(".") was passed as-is to sbatch templates, producing
`export PROJECT_DIR=.` which breaks on compute nodes where the cwd
differs from the submission directory. Now resolved at config
construction time.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 19:06:39 -08:00
35671879fb support multi-node ep (#1894)
Release / Push CUDA image to Docker (push) Canceled after 0s
* support multi-node ep

* fix

* docs(changelog): add inference data parallel config entries

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-02-27 02:43:43 +00:00
JannikStandGitHub 1ea7a8d3b5 fix: handle skipped eval intervals when ckpt_step jumps (#1903)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: handle skipped eval intervals when ckpt_step jumps + fix eval step reporting

When strict_async_level=False, ckpt_step can jump over eval interval
boundaries (e.g. 24->26 skipping 25), permanently missing scheduled evals.
Replace exact modulo check with range check that detects crossed intervals.

Also fix eval metrics being logged at progress.step instead of ckpt_step,
which caused eval results to appear at the wrong step in the metrics API.

* format ruff

* revert step=ckpt_step back to step=progress.step for eval logging

W&B requires monotonically increasing steps. Using ckpt_step (which lags
behind progress.step) causes W&B to silently drop eval metrics since
training already logged at a higher step. The ckpt_step is already
embedded in the metrics as progress/ckpt_step for platform-side lookup.

* fix stale comment about eval subprocess

* add unit tests for eval scheduling range check

* extract eval scheduling logic into compute_eval_ckpt_step function

Move range check logic from inline in orchestrator.py to a proper
function in eval_utils.py so tests import the real implementation.

* use plain functions instead of class in tests
2026-02-27 01:45:14 +01:00
halleriteandGitHub f655f71c33 simplify vlm path (#1877)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-27 01:06:26 +01:00
bc77fa0692 Feat: router replay (#1807)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Enable top_k indices from inference

* Feat; base64

* Feat: more work

* Feat: works now

* Feat: router replay done

* Fix: paths

* Fix: reshape vs view

* Final

* Fix: cp

* fix: config

* Add tests for router replay and fix routed_experts KeyError

- Add unit tests for `_align_routed_experts` (none, empty, no deficit,
  deficit padding, excess length)
- Add tests for `interleave_rollout` with routed experts (single-step
  alignment, multi-step extension, None passthrough)
- Add tests for `prepare_sample` with routed experts (passthrough,
  truncation, None)
- Add GPU test for Qwen3 MoE router replay (forward + backward with
  forced expert indices)
- Fix `tokens["routed_experts"]` -> `tokens.get("routed_experts")` in
  trajectories.py to avoid KeyError when field is absent
- Fix `_attn_only` tests for afmoe/glm4_moe/qwen3_moe broken by
  `routed_experts` kwarg passed to nn.Identity

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

* nit

* Fix

* Feat: address comments

* add to minimax and glm moe dsa

* add to minimax and glm moe dsa

* Fix: boundaries

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-02-26 13:31:16 -08:00
Mika SenghaasandGitHub 7104dbdb5d hendrycks sanity ci (#1900)
Release / Push CUDA image to Docker (push) Canceled after 0s
* do not oversample hendrycks sanity (trainer bottlenecks)

* put hendrycks sanity into nightly config

* remove duplicate utils
2026-02-26 11:14:06 -08:00
Mika SenghaasandGitHub 3d9aa90a24 unify --dry-run flag across rl and sft entrypoint (#1897)
Release / Push CUDA image to Docker (push) Canceled after 0s
* unify dump_config and dry_run across local and slurm entrypoint

* also use in sft entrypoint

* update changelog

* fix exclude launcher fields

* address bugbot

* do not exclude deployment

* fix sft

* exclude clean output dir to not double clean

* fix rl
2026-02-26 11:11:23 -08:00
Mika SenghaasandGitHub 2da1e4ac5a stricly enforce async level + fix off policy off by one (#1901)
Release / Push CUDA image to Docker (push) Canceled after 0s
* stricly enforce async level

* update policy loop + cleanup

* always create policy loop task

* diff

* fix race

* cancel all

* fix

* safe cancel rollouts

* fix off by one err in off policy lag

* fill up in loop

* fix mutation

* cleaner

* update comments

* actually safe cancel

* address bugbot
2026-02-26 11:10:14 -08:00
halleriteandGitHub 7d8da4cbcc add deep_gemm as dependency for GLM5 (#1884)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-26 19:18:57 +01:00
Mika SenghaasandGitHub 7036a15119 update env var prefix (#1899)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-26 08:19:28 -08:00
leopold-tzafonandGitHub aef4a600f9 fix: vlm cache (#1887)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-26 15:00:40 +01:00
a3a307e70c fix: update benchmark baselines for fused_lm_head_chunk_size change (#1895)
Release / Push CUDA image to Docker (push) Canceled after 0s
Update benchmark baselines to reflect the memory increase from commit
83c21ddac which changed the default fused_lm_head_chunk_size from 2048
to 8192 for improved numerical stability.

Memory changes:
- 1-GPU: 22.69 GiB → 31.81 GiB
- 4-GPU: 14.13 GiB → 23.25 GiB

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 02:24:46 -08:00
Matej SirovatkaandGitHub 83c21ddac5 Feat: set default to 8192 (#1892)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-26 02:28:13 +01:00
5f2dc0fe42 chore: fix ruff formatting in orchestrator config (#1891)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 13:58:03 -08:00
5b15e54e88 chore: move tool_call_parser resolution from config validation to server startup (#1882)
Release / Push CUDA image to Docker (push) Canceled after 0s
The auto-detection ran at config time via a model_validator, but the model
name may not be final yet (e.g. RLConfig propagates it later), requiring a
hacky reset+re-resolve in auto_setup_model(). Moving the lookup to
server() ensures we always resolve against the final model name.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 09:14:31 -08:00
samsjaandGitHub 4825d76e75 fix vllm v16 (#1883)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-25 02:39:14 -08:00
668579aaf0 add option for token-batch-size (#1855)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add option for token-batch-size

* changelog

* fix cursor bugbot

* changelog

* remove tests

* keep oversampling_factor

* restore oversampling_factor in wiki and math configs

Keep these RL config files aligned with main and retain the oversampling_factor naming convention instead of max_inflight_rollouts.

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

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 05:42:42 +00:00
ce55c150e7 fix device mesh flattened dim deprecation warning (#1874)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Fix DeviceMesh flattened dim deprecation warning (PT 2.10+)

Store _flatten() return values in a _submeshes dict and access them
via get_mesh() instead of going through world_mesh.__getitem__, which
triggers "Slicing a flattened dim from root mesh will be deprecated
in PT 2.11" warnings and will break in PT 2.11.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix get_mesh lazy init ordering

Ensure world_mesh (and _submeshes) are initialized before checking
the submeshes dict, so synthetic names like "hsdp" don't fall through
to the root mesh lookup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 19:42:18 -08:00
75355f497b fix: wandb logging order (#1880)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: pass explicit step to wandb.log in orchestrator

Without an explicit step, wandb auto-increments its internal counter,
causing subsequent calls with explicit step values to trigger
"step N is less than current step N+1" warnings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use explicit None check for step=0 in eval_utils

`step or ckpt_step` treats step=0 as falsy, silently substituting
ckpt_step. Use `step if step is not None else ckpt_step` instead.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* simplify: step is always an int, drop Optional and fallback

Both call sites always pass step=progress.step (int), so remove the
None type and the ckpt_step fallback that was broken for step=0.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: commit immediately on wandb.log to avoid delayed dashboard data

With explicit step=, wandb accumulates without committing until it sees
a new step. Adding commit=True flushes data to the dashboard immediately.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Revert "fix: commit immediately on wandb.log to avoid delayed dashboard data"

This reverts commit bf679db5f4069374a74d409c0064cd04d8091c6b.

* fix: add monitor.flush() for immediate wandb commits

commit=True can't be used on individual wandb.log calls when multiple
calls share the same step (it advances the counter, breaking subsequent
calls). Instead, accumulate with the default commit=False, then flush
once at the end of the step.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 15:45:51 -08:00
Mika SenghaasandGitHub 1c559feb25 fix using prime-rl logger (#1881)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-24 13:31:49 -08:00
cae5532f5d chore: consolidate config modules into prime_rl.configs (#1871)
Release / Push CUDA image to Docker (push) Canceled after 0s
* consolidate config modules into prime_rl.configs subpackage

Move all scattered config.py files (utils, trainer, rl, sft, orchestrator,
env_server, inference, transport, rl_config) into a single prime_rl.configs
subpackage for better discoverability and organization. Update all imports
across 59 files and refresh skill docs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* merge shared, transport, and utility configs into configs/shared.py

Move SharedLog/Wandb/Checkpoint/Model/WeightBroadcast configs, deployment
configs, transport configs, and common utility configs (ModelConfig,
ClientConfig, LogConfig, WandbConfig, etc.) into a single configs/shared.py.
Remove configs/transport.py and configs/utils.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* rename SFTTrainerConfig -> SFTConfig, sft_trainer.py -> sft.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* move shared configs into rl configs

* move trainer configs into shared.py

Merge configs/trainer.py into configs/shared.py since these configs
(model, optimizer, scheduler, checkpoint, LoRA, SLURM, etc.) are shared
across both SFT and RL trainers. Rename ModelConfig -> TrainerModelConfig
to avoid collision with the common ModelConfig.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* move some stuff

* update configs

* clean up config naming: move trainer configs, drop component prefixes

- Rename rl_trainer.py -> trainer.py, RLTrainerConfig -> TrainerConfig
- Move shared trainer building blocks (ModelConfig, optimizers, schedulers,
  checkpointing, LoRA, etc.) from shared.py into trainer.py
- Rename TrainerModelConfig -> ModelConfig, common ModelConfig -> BaseModelConfig
- Rename TrainerCheckpointConfig -> CheckpointConfig
- Drop Orchestrator/Inference prefixes from config classes
  (OrchestratorModelConfig -> ModelConfig, InferenceModelConfig -> ModelConfig, etc.)
  since the module name provides context; use aliases in rl.py for disambiguation
- Fix OrchestratorModelConfig inheriting from training ModelConfig instead of BaseModelConfig
- Fix broadcast module imports that had mismatched class names

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update changelog with config consolidation entry

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 12:28:36 -08:00
8136f13c55 log reward statistics (#1866)
Release / Push CUDA image to Docker (push) Canceled after 0s
* log reward statistics

* ruff

---------

Co-authored-by: hallerite <git@hallerite.com>
2026-02-24 11:36:03 -08:00
cc59d7bedf cleaner naming for discriminated unions in config (#1879)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Drop Type suffix from config union TypeAliases

Rename all *ConfigType aliases to drop the redundant suffix:
- OptimizerConfigType → OptimizerConfig
- SchedulerConfigType → SchedulerConfig
- DeploymentConfigType → DeploymentConfig
- SFTDeploymentConfigType → SFTDeploymentConfig
- DataConfigType → DataConfig
- TransportConfigType → TransportConfig
- FilterConfigType → FilterConfig
- WeightBroadcastConfigType → WeightBroadcastConfig
- LossConfigType → LossConfig (class renamed to DefaultLossConfig)
- AdvantageConfigType → AdvantageConfig (class renamed to DefaultAdvantageConfig)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move Field(discriminator) into TypeAliases, simplify field sites

Embed Field(discriminator="type") in each union TypeAlias so field
declarations can use the alias directly without wrapping in
Annotated[..., Field(discriminator="type")].

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 11:28:16 -08:00
cfed378624 replace callable discriminator with field values (#1878)
Release / Push CUDA image to Docker (push) Canceled after 0s
LossConfigType and AdvantageConfigType used callable discriminators with
Tag annotations to provide a default fallback when the "type" key was
missing. This is unnecessary since _default_discriminator_types on
BaseSettings already injects the type tag from defaults. Switch to the
simpler Field(discriminator="type") pattern used by all other unions.

LossConfig and AdvantageConfig are changed from BaseConfig to BaseModel
because BaseConfig's field_validator("*", mode="before") conflicts with
pydantic's string-based discriminator. Neither model has Optional fields
that benefit from the empty_str_to_none validator.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 11:15:16 -08:00
f9b7856eec fix: per-component seq_len overrides shared seq_len (#1875)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: per-component seq_len overrides shared seq_len

Remove `nested_model_default_partial_update=True` from BaseSettings so that
`model_fields_set` correctly tracks which nested fields were explicitly set
in the config. This lets `auto_setup_seq_len` propagate the shared `seq_len`
only to components that didn't receive an explicit value.

- Bump pydantic-settings >=2.12.0
- Replace the `normalize_deployment` workaround with a generic
  `_default_discriminator_types` before-validator that injects the `type`
  tag from a field's default instance when missing
- Guard `auto_setup_seq_len` with `model_fields_set` checks

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add hendrycks sanity check exp (#1873)

* Flesh out hendrycks sanity example README

Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update examples

* Add hendrycks sanity to training examples list in README

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update readme

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* add output_dir safety check to prevent accidental overwrites (#1872)

* Add output_dir safety check to prevent accidental overwrites

Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move output_dir validation to entrypoints (before SLURM submission)

Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove old clean flag from RLConfig local path

The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move clean_output_dir to RLConfig and use shared ckpt for resume check

clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update err message

* Fix stray paren in error message, ensure dirs exist after clean, add changelog

- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
  exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* only raise if checkpoints exists

* Make RLConfig.output_dir non-optional and fix docs to match actual behavior

output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add changelog entry for output_dir type change and SLURM validation removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add env var to never clean output dir safeguard

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* add some more tests

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 10:29:23 -08:00
82652c7393 add output_dir safety check to prevent accidental overwrites (#1872)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add output_dir safety check to prevent accidental overwrites

Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move output_dir validation to entrypoints (before SLURM submission)

Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove old clean flag from RLConfig local path

The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move clean_output_dir to RLConfig and use shared ckpt for resume check

clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update err message

* Fix stray paren in error message, ensure dirs exist after clean, add changelog

- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
  exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* only raise if checkpoints exists

* Make RLConfig.output_dir non-optional and fix docs to match actual behavior

output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add changelog entry for output_dir type change and SLURM validation removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add env var to never clean output dir safeguard

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 09:52:11 -08:00
4b0ecdb223 add hendrycks sanity check exp (#1873)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Flesh out hendrycks sanity example README

Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update examples

* Add hendrycks sanity to training examples list in README

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update readme

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 09:13:47 -08:00
1826b18927 unify rl and sft slurm entrypoints to enable single-node slurm deployments (#1859)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fuse rl-slurm and rl

* also migrate sft slurm

* Move SLURM templates to templates/ and rename to multi_node_*

- rl_slurm.sh.j2 → templates/multi_node_rl.sh.j2
- sft_slurm.sh.j2 → templates/multi_node_sft.sh.j2
- Remove src/prime_rl/slurm/ directory entirely
- Update template path references in rl.py and sft/train.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update

* add single node template

* allow setting env vars everywhere

* fixes

* fix

* rename to .sbatch

* update scripts

* update configs

* adopt deployment and slurm config for sft

* rename slurm.template -> slurm.template_path

* style

* make inference optional again and some misc bug fixes

* update examples

* fix configs

* rewrite slurm docs for unified entrypoints and fix slurm_sft.toml

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix config

* deprecate hf hub offline in sft slurm

* only HF_HUB_OFFLINE in multi_node

* tail with -F

* exclude deployment

* update changelog

* move templates

* update branch

* fix output dir

* do not allow None partition

* fix

* revert env_vars

* remove env_vars entries from changelog

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* address bugbot

* extract sft entrypoint

* move entrypoints

* cleanup logic in sft local

* fix single node sft slurm

* fix

* fix: resolve SLURM template path relative to package for editable installs

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

* add changelog line

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-24 03:11:21 -08:00
db5092914d afmoe ring attention support. (#1848)
Release / Push CUDA image to Docker (push) Canceled after 0s
* initial test for ring attn

* tmp

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-02-23 23:23:54 -08:00
faresobeidandGitHub 5bd9809399 fix effective_batch_size metric (#1862)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-24 04:04:26 +00:00
448f8c09ad ep inference support (#1860)
Release / Push CUDA image to Docker (push) Canceled after 0s
* ep inference support

* some fixes

* docs: add inference EP config changelog entry

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

* revert docs

* oops

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-02-24 01:59:57 +00:00
4076a0e457 Fix tool_call_parser not resolved when model name is propagated (#1854)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Move tool_call_parser log from validator to server startup

Validators shouldn't have logging side effects - they run during
config construction which causes spurious log messages on import.
Also use default_factory for ModelConfig to avoid eager instantiation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix tool_call_parser not resolved when model name is propagated

auto_setup_model() changes inference.model.name after the ModelConfig
validator has already run, leaving tool_call_parser stale from the
default model. Re-resolve after propagating the name, but only when
the current parser was auto-detected (preserves explicit overrides).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 14:12:48 -08:00
Mika SenghaasandGitHub ad8d775fc3 bump vf 3f555af (#1858)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-23 09:04:33 -08:00
c2027a79d0 Feat: GLM5 (#1827)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add GLM-5 (glm_moe_dsa) custom model with MLA attention

Implement GLM-5 as a custom model following the 4-file convention:
- configuration, modeling, converting, and __init__
- MLA (Multi-head Latent Attention) with LoRA-compressed Q/KV
- Interleaved RoPE support via apply_rotary_pos_emb_interleave()
- Dense attention only (sparse Lightning Indexer is future work)
- Reuses existing MoE, MLP, RMSNorm, and RotaryEmbedding layers
- Weight conversion roundtrip (HF <-> PrimeRL) for MoE experts
- Indexer weights declared but unused for state dict compatibility
- mini_moe.py preset for test model creation
- Unit tests (attn-only, mlp-only, full model + roundtrip)

* feat: add sparse MLA attention with tilelang kernels for GLM-5

Add Dynamic Sparse Attention (DSA) to the glm_moe_dsa model using
vendored tilelang kernels for training fwd+bwd. Includes a bf16
PyTorch indexer (varlen-aware via cu_seqlens) and the absorption
trick to operate in compressed KV latent space (d_qk=576, d_v=512).

* Progress we run against vllm

* Feat: works but slow

* works now i think

* Cleanup

* deps

* Minor changes

* fix minimoe

* To be verified

* Feat: glm5

* Fix: scaling

* Fix more scaling

* FP8 quant

* Scale

* Cleanup: remove banner comments, verbose docstrings, dead code, and broken tests

- Remove license banner, section separators, and shape annotation comments
- Remove unused _weight_scale variable and commented-out code in fp8_indexer
- Trim verbose vendor attribution comments
- Consolidate duplicate warnings in GlmMoeDsaForCausalLM
- Remove broken test file (tests passed wrong kwargs to attention forward)
- Remove sloppy init comment in models/__init__.py

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

* final

* nit

* Fix GlmMoeDsaConfig pad_token_id forwarding

Co-authored-by: Matej Sirovatka <S1ro1@users.noreply.github.com>

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Matej Sirovatka <S1ro1@users.noreply.github.com>
2026-02-22 19:14:56 -08:00
will brownandGitHub 944163ac68 track seqs per rollout (#1852)
Release / Push CUDA image to Docker (push) Canceled after 0s
* track seqs per rollout

* rename
2026-02-22 17:37:49 -08:00
samsjaandGitHub 1e7561668d make tito default (#1851)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-22 15:54:02 -08:00
fd78f21f79 make tito client opt-in (#1847)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make tito client opt-in

* Add CHANGELOG entry for orchestrator.use_token_client config field

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 01:15:30 -08:00
7eade4f7e1 Add SFT SLURM entrypoint (#1832)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add SFT SLURM entrypoint (`sft_slurm`)

Adds a `sft_slurm` CLI that mirrors `rl_slurm` but for SFT training.
The config extends `SFTTrainerConfig` directly (no `[trainer]` nesting)
with slurm-specific fields (num_nodes, gpus_per_node, etc.). Includes a
simplified Jinja2 SLURM template with no inference/orchestrator nodes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add sft example

* add SFT MoE SLURM example and slim down SFT docs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add sft slur config to tests

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 18:31:36 -08:00
bf0f903b86 Feature/auto detect tool call parser (#1844)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(inference): auto-detect tool_call_parser from model name

Previously tool_call_parser defaulted to "hermes" regardless of model,
causing silent failures when the wrong parser was used. Now the parser
is automatically inferred from the model name via a hardcoded mapping.
Users can still override explicitly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: simplify MODEL_TOOL_CALL_PARSER to dict, address PR review

- Use get_logger instead of std logging
- Replace ordered list-of-tuples with a simple dict (no aliases/ordering concerns)
- Don't raise on unknown model, leave tool_call_parser as None
- Scope supported models to GLM, MiniMax, INTELLECT-3, Qwen3

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: use exact model names in MODEL_TOOL_CALL_PARSER dict

Replace substring pattern matching with exact 1:1 model name lookup.
All supported models are listed explicitly by their HuggingFace ID.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* remove extra inference stuff

* feat: default enable_auto_tool_choice to True

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: auto-enable enable_auto_tool_choice when tool_call_parser is set

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: remove hermes default, leave tool_call_parser as None for unknown models

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 17:57:15 -08:00
Mika SenghaasandGitHub 8ffa00c648 remove model map (#1842)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-20 15:58:47 -08:00
samsjaandGitHub bc740de6dc bump vf (#1843)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-20 14:39:05 -08:00
Mika SenghaasandGitHub c8fdcbb39c robustify env crash detection (#1841)
Release / Push CUDA image to Docker (push) Canceled after 0s
* bump vf

* do not run env server as daemon

* update commit to main

* kill env server process
2026-02-20 11:24:02 -08:00
f87be6ba76 fix Hermes tool parser "Already borrowed" crash under concurrent load (#1837)
Release / Push CUDA image to Docker (push) Canceled after 0s
vLLM's Hermes2ProToolParser.__init__ calls tokenizer.encode() and
tokenizer.decode() on every instantiation. Under concurrent request
load, multiple threads call these methods simultaneously on the same
shared HuggingFace tokenizer instance. The tokenizer's Rust backend
(via PyO3) uses RefCell-style borrow tracking, and concurrent mutable
borrows cause it to panic with `RuntimeError: Already borrowed`.

This was causing ~1% of /v1/chat/completions requests to fail with
500 Internal Server Error when tool calling (hermes parser) is enabled.

Fix: monkey-patch the parser __init__ to run the first tokenizer
encode/decode under a threading lock, cache the results, and reuse
them for all subsequent instantiations without touching the tokenizer.

Co-authored-by: root <root@industrious-conscious-koala.datacrunch.io>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-02-19 18:47:18 -08:00
192035e52c Add option to freeze MoE router during training (#1836)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add option to freeze MoE router during training

Adds `freeze_moe_router` config option to prevent routing collapse and
keep load balancing stable during RL and SFT fine-tuning. Supports both
custom MoE (router) and HuggingFace (gate) implementations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove freeze_moe_router unit tests

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 14:50:15 -08:00
halleriteandGitHub 30a14c1702 add mismatch_kl-entropy ratio (#1835)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-19 14:16:02 -08:00
halleriteandGitHub a646ad6050 use lower-variance estimator for pass@k (#1834)
Release / Push CUDA image to Docker (push) Canceled after 0s
* use unbiased estimator

* compute k's on the fly

* fix claude retardation
2026-02-19 14:15:28 -08:00
10135d4814 fix resume from latest step for single-run (#1805)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: add STABLE marker files to orchestrator checkpoints

Previously, orchestrator checkpoints did not create STABLE marker files,
causing the trainer's resume logic to fail when resuming with resume_step=-1.
The trainer would not find any STABLE files and incorrectly default to step 0,
even when orchestrator checkpoints existed at later steps.

This fix adds mark_stable() method to the orchestrator CheckpointManager
and calls it after successfully saving checkpoints, matching the behavior
of the trainer checkpoint manager.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* refactor: use mark_stable method in WeightCheckpointManager for consistency

Previously, WeightCheckpointManager directly touched the STABLE file
instead of using a dedicated method. This adds a mark_stable() method
to match the pattern used in CheckpointManager and OrchestratorCheckpointManager.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* make public methods

* indent

* consistency

* do not write stable from orch + search for any run ckpt dirs

* require stable for multi-tenant

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-19 13:57:35 -08:00
Mika SenghaasandGitHub 29cc7b24ef increase health check interval (#1833)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-19 04:29:43 -08:00
deb1aa92bc fix MiniMax M2 LoRA compatibility in vLLM inference (#1831)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix MiniMax M2 LoRA compatibility in vLLM inference

vLLM's MiniMax M2 model has two issues preventing MoE LoRA from working:

1. The MoE gate (router) uses float32 params and casts inputs to float32,
   but vLLM's LoRA Triton kernel only supports float16/bfloat16. Fixed by
   recreating the gate in model dtype and removing the float32 cast.

2. PrimeRL saves adapter keys as mlp.experts.{j}.gate_proj/down_proj/up_proj
   but vLLM expects block_sparse_moe.experts.{j}.w1/w2/w3. Fixed by adding
   hf_to_vllm_mapper on the model to remap adapter keys on load.

Also adds debug configs for MiniMax M2 and Qwen3 MoE LoRA RL training.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* remove debug LoRA config files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* improve comments explaining MiniMax M2 LoRA patches

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 21:18:33 -08:00
5c3008b3a5 Remove reload_weights_on_start dead code (#1829)
Release / Push CUDA image to Docker (push) Canceled after 0s
* dont reload weights by default

* Remove reload_weights_on_start config and dead code path

The reload_weights mechanism was a no-op in practice: vLLM servers
start with base weights already loaded, and LoRA runs already
skipped the reload. Remove the config field, server endpoint,
client function, and orchestrator branching.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove helo/orchestrator.toml from branch

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add changelog entry for reload_weights_on_start removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 17:35:18 -08:00
samsjaandGitHub 54b3e4cd24 remove hash from logs (#1830)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-18 17:20:58 -08:00
JannikStandGitHub bc55a1c85a pass json_logging to env servers (#1823)
Release / Push CUDA image to Docker (push) Canceled after 0s
* pass json_logging to env servers

- pass json_logging to ZMQEnvServer in standalone env-server entrypoint
- add json_logging param to spawn_env_server()
- pass config.log.json_logging in orchestrator spawn calls

* bump verifiers to 013d4da (json_logging support)

* remove duplicate
2026-02-18 16:18:23 +01:00
Mika SenghaasandGitHub 6f9c1362a1 env server recovery (#1816)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add exp

* bump vf

* setup timeouts and logging interception

* bump and use built-in wait for server health

* no prefix

* bump and show info logs

* add name and intercept without prefix

* slower health checks

* bump to lower health timeout

* back to 8k seq len

* bump

* update log interception and new config

* get free port pair

* bump to have prime-rl env server logs

* mini

* bump

* do not intercept on env server

* bump vf

* copy lock

* update lock

* remove configs
2026-02-18 07:08:51 -08:00
46d210bf6e add multimodal test to nightly CI (#1815)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix vlm in transformers 5

* improve

* fix bug

* rename

* fix: auto-install transformers v5 compat hook for vLLM workers

* refactor: use vLLM plugin system instead of .pth hook for transformers v5 compat (#1810)

Replace the runtime site-packages mutation (.pth file + generated module)
with a vllm.general_plugins entry-point. vLLM loads general plugins in
every process it spawns (workers, engine core, API servers), so the patch
survives multiprocessing spawn without writing to site-packages.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* minor fixes

* add nightly for multimodal

* improve exact config

---------

Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:58:05 -08:00
halleriteandGitHub 1e365924ac fix VLMs after transformers bump (#1806)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-17 23:19:56 +01:00
halleriteandGitHub decced2093 add gibberish & repetition filtering (#1746)
Release / Push CUDA image to Docker (push) Canceled after 0s
---------

Signed-off-by: hallerite <git@hallerite.com>
2026-02-17 22:46:10 +01:00
a77725e5c0 refactor(slurm): move NCCL and runtime configs from template to config (#1818)
Release / Push CUDA image to Docker (push) Canceled after 0s
* refactor(slurm): move NCCL and runtime configs from template to config

- Add port/timeout fields to SharedWeightBroadcastConfig
- Propagate port/timeout in auto_setup_weight_broadcast
- Add auto_setup_slurm_nccl validator that sets:
  - orchestrator.num_train_workers from SLURM topology
  - trainer.weight_broadcast.host to 0.0.0.0
  - trainer.weight_broadcast.inference_world_size from SLURM topology
- Add validate_inference_config to catch missing inference config early
- Remove hardcoded env vars and CLI args from SLURM template

Only --weight_broadcast.host $MASTER_ADDR and --client.base-url remain
as CLI args (runtime values from SLURM).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(slurm): add rl_slurm entrypoint and update docs

- Add rl_slurm script entrypoint to pyproject.toml
- Update docs to use `uv run rl_slurm` instead of `uv run python -m prime_rl.slurm.rl`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 13:42:59 -08:00
3102ca47cb Add SLURM entrypoint with Jinja2 template (#1774)
Release / Push CUDA image to Docker (push) Canceled after 0s
* refactor config

* Add SLURM entrypoint with Jinja2 template and tmux launcher

Adds a new `rl_slurm` entrypoint that resolves the full RL config,
dumps sub-configs as TOML, renders a SLURM batch script from a Jinja2
template, and submits it via sbatch (with --dry-run option). Includes
a tmux launcher for monitoring trainer/orchestrator/inference logs and
documentation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix ruff formatting

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(slurm): sync orchestrator output dir with cleanup

Co-authored-by: samsja <samsja@users.noreply.github.com>

* test(configs): include slurm config parser in config loading test

Co-authored-by: samsja <samsja@users.noreply.github.com>

* add auto dir

* fix(slurm): move auto_setup_output_dir to BaseRLConfig so SLURM entrypoint propagates output_dir

RLSLURMConfig extends BaseRLConfig, not RLConfig, so the validator that
propagates output_dir to trainer and orchestrator was never running.
This caused the Jinja template cleanup to target wrong paths and the
trainer to pick up stale rollouts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add args

* feat(slurm): make config more flexible and self-contained

- Replace base_dir/env_file/venv with single project_dir
- Add gpus_per_node (default 8) to remove hardcoded GPU counts
- Add nodes_per_fsdp_group to auto-compute dp_replicate
- Use -m module syntax for torchrun instead of file path
- Derive .env and .venv paths from project_dir

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix many stuff

* add math

* addexamples

* add moe example

* docs(slurm): update to Hendrycks Math examples with MoE config

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add required output_dir to slurm example configs

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: samsja <samsja@users.noreply.github.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-02-17 13:10:27 -08:00
7c40b334e6 fix: MoE weight conversion for vLLM compatibility (#1812)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: use per-expert format in MoE weight conversion for vLLM compatibility

convert_tt_layer_to_hf was producing transformers v5 fused format
(experts.gate_up_proj, experts.down_proj) but vLLM expects per-expert
format (experts.{j}.gate_proj.weight, etc). This caused KeyError during
weight updates in the inference server. Also adds MoE RL integration
tests for both hf and custom impl.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use underscores in MoE TOML config keys

Hyphens only work as CLI args, TOML config needs underscores.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* test: remove HF round-trip tests for MoE models

The MoE weight conversion now outputs per-expert format for vLLM
compatibility, which is incompatible with HF transformers 5.0+ fused
format. Remove the round-trip tests that loaded converted weights
back into HF models since vLLM is the target format.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-02-17 12:28:55 -08:00
aaeb711501 Add MiniMax M2.1 MoE model support (#1773)
Release / Push CUDA image to Docker (push) Canceled after 0s
Implement full pipeline for MiniMax M2.1 (230B MoE, 10B activated/token):
modeling code, HF<->PrimeRL weight conversion, registration, and mini-model
verification.

Key additions:
- Per-layer QK norm support in shared attention (qk_norm_type="per_layer")
- MiniMax M2.1 model module with config, conversion, and modeling
- Mini model preset for testing at small scale
- Refactored mini_moe.py to support remote-code HF models

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 11:07:04 -08:00
minh hoangandGitHub 6c8faec459 helm:specify deployment component in container name (#1793)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-17 16:24:02 +01:00
Mika SenghaasandGitHub 95a53f39e7 implement optional cancellation of inflight rollouts before eval (#1802)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-16 12:30:12 -08:00
halleriteandGitHub 0756df77c1 fix missing param (#1808)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-16 10:20:14 -08:00
66b1f4b6b7 configure default logger instead of raise (#1804)
Release / Push CUDA image to Docker (push) Canceled after 0s
* configure default logger instead of raise

* fix: cleanup old logger resources when calling setup_logger

Calling setup_logger multiple times now properly cleans up the old
logger instance by calling logger.remove() before creating a new one.
This prevents resource leaks:
- Background threads from enqueue=True handlers are stopped
- JsonFileSink file handles are properly released

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: add cleanup to reset_logger to prevent resource leaks

Calling reset_logger now properly cleans up the logger instance by
calling logger.remove() before setting _LOGGER to None. This ensures
that any active handlers (file sinks, enqueued handlers, background
threads) are properly released, matching the cleanup pattern in
setup_logger.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 09:52:47 -08:00
bb5e48292d fix: upgrade flash-attn from 2.6.3 to 2.8.3 (#1803)
Release / Push CUDA image to Docker (push) Canceled after 0s
The downgrade from 2.8.3 to 2.6.3 happened during the vllm/transformers
bump (commit 8f2e6bbc) when PyTorch was upgraded from 2.9 to 2.10.

Flash-attn 2.6.3 does not support Blackwell GPUs (compute capability 12.0),
causing "FlashAttention only supports Ampere GPUs or newer" errors.

This upgrades back to 2.8.3 which may have better compatibility with newer
GPU architectures. The 2.8.3 wheel for torch 2.10 + cu128 is available in
the same v0.7.16 release.

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 07:53:46 -08:00
187b7a438c fix env server deadlock (#1801)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix(deps): bump verifiers to e629347 (ZMQ env server deadlock fix)

The ZMQ env server used asyncio.wait_for around recv_multipart which
has a race condition in CPython's Task cancellation that silently
discards consumed messages. The verifiers fix replaces it with a
zmq.asyncio.Poller.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* use spawn method

* bump to commit on main

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 05:06:00 -08:00
faresobeidandGitHub 1b725b84b8 track prefill vs decode tokens (#1797)
Release / Push CUDA image to Docker (push) Canceled after 0s
* track prefill vs decode tokens

* fix ruff
2026-02-16 00:47:04 +00:00
c28eaf874b Alphabetical sort CI tests (#1784)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Align alphabet-sort nightly test with reverse-text checks

Co-authored-by: samsja <samsja@users.noreply.github.com>

* Add alphabet-sort integration CI test and config

Co-authored-by: samsja <samsja@users.noreply.github.com>

* Isolate alphabet-sort integration logs per run

Co-authored-by: samsja <samsja@users.noreply.github.com>

* Reduce alphabet-sort CI runtime and raise timeout

Co-authored-by: samsja <samsja@users.noreply.github.com>

* Seed resume output with alphabet-sort checkpoints

Co-authored-by: samsja <samsja@users.noreply.github.com>

* Copy resume weights for alphabet-sort integration

Co-authored-by: samsja <samsja@users.noreply.github.com>

* Simplify alphabet-sort integration test to single run

Co-authored-by: samsja <samsja@users.noreply.github.com>

* Remove unused alphabet-sort resume CI config

Co-authored-by: samsja <samsja@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: samsja <samsja@users.noreply.github.com>
2026-02-15 15:33:58 -08:00
195 changed files with 8535 additions and 2758 deletions
+6 -1
View File
@@ -65,10 +65,13 @@ jobs:
include:
- test: base
runner: vm
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py"
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
- test: rl_lora
runner: vm
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
- test: rl_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
@@ -102,6 +105,8 @@ jobs:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
+33
View File
@@ -12,6 +12,39 @@ jobs:
trigger-docs-sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate mint.json pages exist
run: |
missing=()
pages=$(python3 -c "
import json, sys
data = json.load(open('docs/mint.json'))
pages = []
def collect(obj):
if isinstance(obj, list):
for item in obj: collect(item)
elif isinstance(obj, dict):
if 'pages' in obj: collect(obj['pages'])
if 'groups' in obj: collect(obj['groups'])
elif isinstance(obj, str):
pages.append(obj)
collect(data.get('navigation', []))
print('\n'.join(pages))
")
while IFS= read -r page; do
[ -z "$page" ] && continue
if [ ! -f "docs/${page}.md" ] && [ ! -f "docs/${page}.mdx" ]; then
missing+=("${page}")
fi
done <<< "$pages"
if [ ${#missing[@]} -gt 0 ]; then
echo "ERROR: The following pages listed in mint.json do not exist in docs/:"
printf ' - %s\n' "${missing[@]}"
exit 1
fi
echo "All mint.json pages verified."
- name: Trigger public-docs workflow
uses: peter-evans/repository-dispatch@v3
with:
+4
View File
@@ -5,6 +5,10 @@ configs/endpoints.py
# Artifacts
**/slurm
!src/prime_rl/slurm
!examples/slurm
!scripts/slurm_tmux.sh
!docs/slurm.md
**/torchrun
**/weights
**/checkpoints
+35 -3
View File
@@ -37,7 +37,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
- **`orchestrator.reload_weights_on_start`**: Added flag to control resetting inference weights to the base model when starting from scratch (default: True) (2026-01-21)
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
- **`client.skip_model_check`**: Added configuration to skip checking if the model is available in the inference pool. Useful for external APIs or API keys that don't support the /models endpoint (default: False) (#1543, 2026-01-06)
@@ -56,6 +56,38 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTConfig` (2026-02-23)
- **`[deployment]` (RL)**: Added deployment configuration. `type = "single_node"` auto-derives contiguous GPU assignments from `num_infer_gpus`, `num_train_gpus`, `num_teacher_gpus`. `type = "multi_node"` requires `[slurm]` and uses `num_train_nodes`, `num_infer_nodes` (2026-02-23)
- **`[deployment]` (SFT)**: Added deployment configuration. `type = "single_node"` with `num_gpus` (default: 1). `type = "multi_node"` with `num_nodes`, `nodes_per_fsdp_group`, `hf_hub_offline` (2026-02-23)
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
- **`[slurm]` (SFT)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run sft` generates and submits an sbatch script instead of running locally (2026-02-23)
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
- **`clean_output_dir`**: Added to `RLConfig` and `SFTConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
- **`slurm.dry_run`**: Removed from `SlurmConfig`. Replaced by top-level `dry_run` (see below) (2026-02-26)
- **`dry_run`**: Added to `RLConfig` and `SFTConfig` (default: `False`). When set, validates the config, writes resolved subconfigs to `output_dir/configs/`, and exits without starting any processes. Works the same for both local and SLURM runs (2026-02-26)
- **Config output location**: Resolved subconfigs are now always written to `output_dir/configs/` instead of `.pydantic_config/<uuid>/`. This applies to both local and SLURM entrypoints, and for both single-node and multi-node deployments (2026-02-26)
- **SFT config filename**: The resolved SFT trainer config is now written as `sft.toml` instead of `trainer.toml` (2026-02-26)
+2 -1
View File
@@ -164,8 +164,9 @@ We provide end-to-end training examples in the [`examples`](examples) directory
2. [**Wordle**](examples/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/alphabet_sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/wiki_search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/hendrycks_sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
4. *More to come...*
*More to come...*
## Docs
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "a76eec30",
"timestamp": "2026-02-01T00:37:17.504432+00:00",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
},
"metrics": {
"mfu": {
"mean": 17.08174826544651,
"std": 0.00860887294908562,
"min": 17.07595532741123,
"max": 17.091640740120457
"mean": 16.41977165630161,
"std": 0.010586646038388221,
"min": 16.407648988464405,
"max": 16.42719598975201
},
"throughput": {
"mean": 2040.0423352992304,
"std": 1.0281421434405753,
"min": 2039.3504951752516,
"max": 2041.2237756777045
"mean": 1960.9836648020673,
"std": 1.2643440104327244,
"min": 1959.5358764831926,
"max": 1961.8703395331793
},
"step_time": {
"mean": 63.29752009687945,
"std": 0.1304965028229097,
"min": 63.170207182411104,
"max": 63.430982740130275
"mean": 65.87,
"std": 0.13,
"min": 65.74,
"max": 66.0
},
"peak_memory": {
"gib": 22.685546875,
"pct": 47.72
"gib": 31.806640625,
"pct": 67.03
}
}
}
@@ -13,36 +13,36 @@
"micro_batches": 2,
"ep": 1,
"cp": 1,
"docker_image": "primeintellect/prime-rl@sha256:d3e9636af265f5ba2e56cd2555534489f5ff64e04a3f645059ca7989508de419",
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "a76eec30",
"timestamp": "2026-01-31T01:13:40.536972+00:00",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
},
"metrics": {
"mfu": {
"mean": 16.165875888064594,
"std": 0.010063094728313886,
"min": 16.154265967508614,
"max": 16.172097002189034
"mean": 15.634260517326164,
"std": 0.009817863071768202,
"min": 15.622927380137481,
"max": 15.640172924064188
},
"throughput": {
"mean": 7722.645407567771,
"std": 4.80726889329249,
"min": 7717.099200218126,
"max": 7725.61731325081
"mean": 7468.685954343421,
"std": 4.690118598479809,
"min": 7463.271969943842,
"max": 7471.510386564679
},
"step_time": {
"mean": 66.21160964062437,
"std": 0.11667723461510121,
"min": 66.1170196281746,
"max": 66.34198968904093
"mean": 68.34095695288852,
"std": 0.16054587555887065,
"min": 68.16114284005016,
"max": 68.46991707291454
},
"peak_memory": {
"gib": 14.1328125,
"pct": 29.74
"gib": 23.25390625,
"pct": 49.05701678145735
}
}
}
@@ -83,6 +83,11 @@ class BenchmarkConfig(BaseSettings):
cp: Annotated[int, Field(ge=1, description="Context parallelism size (1 = no CP)")] = 1
fused_lm_head_chunk_size: Annotated[
int | None,
Field(description="Fused LM head chunk size (None uses trainer default)"),
] = None
docker_image: Annotated[str | None, Field(description="Docker image used for the benchmark")] = None
# Metadata set by the script
@@ -152,6 +157,10 @@ def build_command(config: BenchmarkConfig) -> list[str]:
if config.cp > 1:
cmd.extend(["--model.cp", str(config.cp)])
# Fused LM head chunk size
if config.fused_lm_head_chunk_size is not None:
cmd.extend(["--model.fused-lm-head-chunk-size", str(config.fused_lm_head_chunk_size)])
# Data configuration differs between RL and SFT
if config.type.startswith("rl"):
cmd.extend(["--data.fake.batch-size", str(config.micro_batches * config.num_gpus)])
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
@@ -0,0 +1,24 @@
max_steps = 10
seq_len = 2048
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 384
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 25
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 25
seq_len = 2048
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
+26
View File
@@ -0,0 +1,26 @@
max_steps = 20
seq_len = 2048
[ckpt]
[model]
name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[[orchestrator.env]]
id = "reverse-text"
[inference]
gpu_memory_utilization = 0.7
[inference.model]
max_model_len = 2048
@@ -5,6 +5,7 @@ max_async_level = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_chunk_size = 8192
[model.lora]
rank = 8
+4 -3
View File
@@ -3,12 +3,13 @@
# - 300 instead of 500 steps
# - No checkpointing
# - No evals
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
-46
View File
@@ -1,46 +0,0 @@
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 2048
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 1024
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "primeintellect/math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_fraction = 0.0
hard_fraction = 0.0
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.val]
interval = 5
num_examples = 128
[orchestrator.eval]
interval = 10
[orchestrator.eval.sampling]
max_tokens = 2048
[[orchestrator.eval.env]]
id = "primeintellect/math500"
name = "math500"
num_examples = 30
rollouts_per_example = 4
[trainer] # Default trainer config
[inference]
@@ -0,0 +1,36 @@
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
max_steps = 25
seq_len = 4096
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 64
[[orchestrator.env]]
id = "primeintellect/color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[orchestrator.val]
interval = 5
num_examples = 100
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1500
seq_len = 24576
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+1 -1
View File
@@ -43,4 +43,4 @@ sync_interval = 5.0
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+4 -4
View File
@@ -1,9 +1,10 @@
trainer_gpu_ids = [0,1,2,3]
inference_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "env-mix-debug"
name = "env-mix"
@@ -47,6 +48,5 @@ api_server_count = 8
gpu_memory_utilization = 0.8
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
max_model_len = 8192
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 100
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
trainer_gpu_ids = [0]
inference_gpu_ids = [1]
max_steps = 500
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 3000
seq_len = 8192
-3
View File
@@ -1,6 +1,3 @@
trainer_gpu_ids = [0]
inference_gpu_ids = [1]
max_steps = 500
[wandb]
-1
View File
@@ -25,6 +25,5 @@ args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox
api_server_count = 4
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
max_model_len = 4096
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 15
seq_len = 4096
-4
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 500
seq_len = 4096
@@ -43,5 +40,4 @@ online_difficulty_filtering = true
id = "primeintellect/wiki-search"
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
+2 -2
View File
@@ -83,7 +83,7 @@ uv run torchrun \
### SLURM
TBD.
See the dedicated [SLURM guide](slurm.md).
## Inference
@@ -281,7 +281,7 @@ Of course, you can further scale up the number of nodes used by the trainer and
### SLURM
TBD.
See the dedicated [SLURM guide](slurm.md).
## Kubernetes
+1 -1
View File
@@ -16,7 +16,7 @@ The trainer is responsible for producing an updated policy model given rollouts
### Inference
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with two custom endpoints to enable updating the server with the latest policy: `update_weights` is used to reload model weights from a HF-compatible checkpoint on disk, and `reload_weights` is used to reset the weights to the base model in between experiments. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with a custom `update_weights` endpoint to reload model weights from a HF-compatible checkpoint on disk. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
### RL
+1 -1
View File
@@ -10,7 +10,7 @@
"environments",
"async",
"logging",
"runs",
"multi_run_manager",
"checkpointing",
"benchmarking",
"deployment",
+226
View File
@@ -0,0 +1,226 @@
# SLURM
Both `rl` and `sft` have built-in SLURM support. Adding a `[slurm]` section to your config switches from local execution to SLURM job submission — no separate entrypoint needed.
## Quick Start
```bash
# Local run
uv run rl @ examples/reverse_text/rl.toml
# SLURM run (same entrypoint, just add [slurm] to the config)
uv run rl @ examples/reverse_text/slurm_rl.toml
```
The SLURM config is a thin overlay that inherits from a base config and adds `[slurm]` + `[deployment]` sections:
```toml
# examples/reverse_text/slurm_rl.toml
toml_files = ["rl.toml"]
output_dir = "outputs/reverse-text-rl"
[slurm]
job_name = "reverse-text-rl"
```
## How it works
When `[slurm]` is present, the entrypoint:
1. Resolves the full config
2. Renders a SLURM batch script from a Jinja2 template
3. Writes the script and resolved config to `{output_dir}/`
4. Submits via `sbatch` (or prints the script with `--slurm.dry-run`)
For **single-node** jobs, the entire config is dumped to a TOML file and the template simply runs `uv run rl @` or `uv run sft @` on the allocated node.
For **multi-node** jobs, sub-configs are written separately and `srun` dispatches processes across nodes.
## Configuration
### `[slurm]` — Job submission (shared between RL and SFT)
| Field | Description | Default |
|---|---|---|
| `job_name` | SLURM job name | `"prime-rl"` |
| `project_dir` | Path to the project root on the cluster | `"."` |
| `template_path` | Path to a custom Jinja2 template | auto-selected |
| `partition` | SLURM partition | `"cluster"` |
| `dry_run` | Generate script without submitting | `false` |
### `[deployment]` — Node and GPU allocation
**RL** uses a discriminated union with `type = "single_node"` (default) or `type = "multi_node"`:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_train_gpus` | Training GPUs | — |
| `num_infer_gpus` | Inference GPUs | — |
| `num_train_nodes` | — | Training nodes |
| `num_infer_nodes` | — | Inference nodes |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
**SFT** follows the same pattern but only has training nodes:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_gpus` | Number of GPUs (default: 1) | — |
| `num_nodes` | — | Training nodes (default: 2) |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
The SLURM template is auto-selected based on `deployment.type`. You can override it with `slurm.template_path`.
### Constraints
- `output_dir` should be explicitly set when using SLURM (defaults to `"outputs"`)
- Multi-node deployment requires `[slurm]` to be set
---
## RL Examples
### Single-node SLURM
The simplest case: run on a single allocated node. No `[deployment]` needed — defaults to `single_node`.
```toml
output_dir = "/shared/outputs/my-rl-run"
[slurm]
job_name = "my-rl-run"
```
### Multi-node SLURM (Hendrycks Math)
```toml
output_dir = "outputs/rl-math-moe"
max_steps = 500
seq_len = 2048
[slurm]
job_name = "hendrycks-math-rl-moe"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[weight_broadcast]
type = "nccl"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[trainer.model.ac_offloading]
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[inference.parallel]
tp = 4
dp = 2
```
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
---
## SFT Examples
### Single-node SLURM
```toml
output_dir = "/shared/outputs/my-sft-run"
[slurm]
job_name = "my-sft-run"
```
### Multi-node SLURM (MoE SFT)
```toml
output_dir = "outputs/sft-moe-math"
max_steps = 500
[slurm]
job_name = "sft-moe-math"
[deployment]
type = "multi_node"
num_nodes = 2
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[model.ac_offloading]
max_inflight_activations = 5
[model.ac]
freq = 1
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
subsets = ["default"]
splits = ["math"]
batch_size = 128
seq_len = 8192
```
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
---
## Custom SLURM Templates
The default templates handle standard setups with InfiniBand detection, environment setup, and `srun`-based process dispatch. For advanced use cases (custom partitions, account settings, module loads, etc.), provide your own Jinja2 template:
```bash
uv run rl @ my_config.toml --slurm.template-path path/to/my_template.sbatch.j2
```
See [`src/prime_rl/templates/`](../src/prime_rl/templates/) for the default templates as a starting point.
## Monitoring
After submission, logs are available at:
```bash
# Single-node
tail -F {output_dir}/logs/trainer/rank_0.log
# Multi-node RL
tail -F {output_dir}/slurm/latest_train_node_rank_0.log
tail -F {output_dir}/slurm/latest_infer_node_rank_0.log
tail -F {output_dir}/slurm/latest_orchestrator.log
```
For convenience, a tmux launcher sets up a session with all log streams:
```bash
bash scripts/slurm_tmux.sh my-rl-job /shared/outputs/my-rl-job
```
+2 -1
View File
@@ -90,7 +90,8 @@ The correct alphabetical order by last name should be: Akman, Cakir, Durgun. The
We train with LoRA (rank 32, alpha 64) for 100 steps.
![RL](rl/wandb.png)
![RL](rl.png)
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
```bash
# In the `Trainer` pane

Before

Width:  |  Height:  |  Size: 141 KiB

After

Width:  |  Height:  |  Size: 141 KiB

+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/alphabet-sort"
[slurm]
job_name = "alphabet-sort"
+25
View File
@@ -0,0 +1,25 @@
# Hendrycks Sanity
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
> This example runs on 8 GPUs (4 for inference, 4 for training).
## Training
Schedule training locally on a node with 8 GPUs
```bash
uv run rl @ examples/hendrycks_sanity/rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
Or schedule the same training via SLURM
```bash
uv run rl @ examples/hendrycks_sanity/slurm_rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
+37
View File
@@ -0,0 +1,37 @@
max_steps = 5000
seq_len = 8192
[wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
rollouts_per_example = 8
[[orchestrator.env]]
id = "math-env" # included in lock file
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
name = "aime2024"
rollouts_per_example = 32
[trainer.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
seq_len = 16384
[inference.model]
max_model_len = 8192
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/hendrycks-sanity"
[slurm]
job_name = "hendrycks-sanity"
+55
View File
@@ -0,0 +1,55 @@
output_dir = "outputs/rl-math-moe"
max_steps = 500
seq_len = 2048
[slurm]
job_name = "hendrycks-math-rl-moe"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[log]
level = "debug"
[wandb]
project = "hendrycks-math-debug"
name = "hendrycks-math"
[weight_broadcast]
type = "nccl"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[trainer.model.ac_offloading]
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[inference.parallel]
tp = 4
dp = 2
+35
View File
@@ -0,0 +1,35 @@
output_dir = "outputs/sft-moe-math"
max_steps = 500
[slurm]
job_name = "sft-moe-math"
[deployment]
type = "multi_node"
num_nodes = 2
[wandb]
project = "sft-moe-intellect"
name = "sft-moe-math"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[model.compile]
[model.ac_offloading]
max_inflight_activations = 5
[model.ac]
freq = 1
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
subsets = ["default"]
splits = ["math"]
batch_size = 128
seq_len = 8192
+2 -2
View File
@@ -36,7 +36,7 @@ This is of course just a quick vibe check and no full-fledged evaluation, but we
We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/PrimeIntellect/Qwen3-0.6B)), which is a clone of `Qwen/Qwen3-0.6B` ([HF](https://huggingface.co/Qwen/Qwen3-0.6B)) with a chat template suitable for multi-turn RL, on `willcb/R1-reverse-wikipedia-paragraphs-v1-1000` ([HF](https://huggingface.co/datasets/willcb/R1-reverse-wikipedia-paragraphs-v1-1000)) which contains 1K examples of reversals of small paragraphs.
![SFT](sft/wandb.png)
![SFT](sft.png)
*Check out the logs of the SFT run on [W&B](https://wandb.ai/primeintellect/examples?nw=s3p14m48jod).*
To train on a single GPU, run
@@ -72,7 +72,7 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT
For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of 128 and sequence length 128. Because of the small context, training should be extremely quick.
![RL](rl/wandb.png)
![RL](rl.png)
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
```bash

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 129 KiB

-2
View File
@@ -1,2 +0,0 @@
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
-15
View File
@@ -1,15 +0,0 @@
batch_size = 128
rollouts_per_example = 16
seq_len = 2048
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[sampling]
max_tokens = 128
[[env]]
id = "reverse-text"
[ckpt]
-9
View File
@@ -1,9 +0,0 @@
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-6
[ckpt]

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

-14
View File
@@ -1,14 +0,0 @@
max_steps = 100
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
[optim]
lr = 2e-5
[ckpt] # Checkpoint at the end of training
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/reverse-text-rl"
[slurm]
job_name = "reverse-text-rl"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["sft.toml"]
output_dir = "outputs/reverse-text-sft"
[slurm]
job_name = "reverse-text-sft"
+4 -4
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
@@ -48,5 +49,4 @@ id = "primeintellect/wiki-search"
[ckpt] # Checkpoint at the end of training
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/wiki-search"
[slurm]
job_name = "wiki-search"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
project = "wordle"
name = "wordle"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/wordle-rl"
[slurm]
job_name = "wordle-rl"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["sft.toml"]
output_dir = "outputs/wordle-sft"
[slurm]
job_name = "wordle-sft"
+3 -3
View File
@@ -27,7 +27,7 @@ spec:
{{- toYaml . | nindent 8 }}
{{- end }}
containers:
- name: prime-rl
- name: prime-rl-orchestrator
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.orchestrator.autoStart }}
@@ -133,7 +133,7 @@ spec:
runtimeClassName: {{ .Values.inference.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl
- name: prime-rl-inference
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.inference.autoStart }}
@@ -262,7 +262,7 @@ spec:
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl
- name: prime-rl-trainer
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.trainer.autoStart }}
+16 -9
View File
@@ -12,19 +12,20 @@ dependencies = [
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"pydantic>=1.10.13",
"pydantic-settings>=2.10.1",
"pydantic-settings>=2.12.0",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"numpy>=2.2.6",
"torch>=2.9.0",
"torchdata>=0.11.0",
"transformers",
"vllm",
"vllm>=0.16.0,",
"wandb>=0.24.2",
"ring-flash-attn>=0.1.8",
"prime>=0.5.37",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"math-env",
"tenacity>=8.2.0",
"openai>=1.106.1",
"rich>=14.0.0",
@@ -33,28 +34,35 @@ dependencies = [
"verifiers",
"dion",
"reverse-text",
"tilelang>=0.1.8",
]
[project.scripts]
rl = "prime_rl.rl:main"
rl = "prime_rl.entrypoints.rl:main"
sft = "prime_rl.entrypoints.sft:main"
trainer = "prime_rl.trainer.rl.train:main"
orchestrator = "prime_rl.orchestrator.orchestrator:main"
inference = "prime_rl.inference.server:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
sft = "prime_rl.trainer.sft.train:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
[project.optional-dependencies]
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.6.8/flash_attn-2.8.3+cu128torch2.9-cp312-cp312-linux_x86_64.whl",
]
flash-attn-3 = [
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl",
]
flash-attn-cute = [
"flash-attn-cute",
]
[dependency-groups]
fp8-inference = [
"deep-gemm @ https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl",
]
dev = [
"ipykernel>=6.29.5",
"ipywidgets>=8.1.7",
@@ -67,7 +75,6 @@ dev = [
[tool.uv]
preview = true
no-build-isolation-package = ["flash-attn"]
prerelease = "allow"
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
@@ -77,11 +84,11 @@ override-dependencies = [
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "786d300" }
math-env = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "b35d0c7" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
vllm = { url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" }
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "main" }
reverse-text = { index = "primeintellect" }
+64 -11
View File
@@ -15,12 +15,14 @@ import argparse
from pathlib import Path
import torch
from transformers import AutoConfig, AutoTokenizer
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.utils import default_dtype
@@ -57,21 +59,71 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
"tokenizer_source": "THUDM/GLM-4-9B-0414",
},
"minimax_m2": {
"config_class": MiniMaxM2Config,
"config_kwargs": dict(
vocab_size=200064,
hidden_size=512,
intermediate_size=256,
num_hidden_layers=12,
num_attention_heads=8,
num_key_value_heads=4,
head_dim=64,
hidden_act="silu",
max_position_embeddings=4096,
rms_norm_eps=1e-6,
rope_theta=5000000,
rotary_dim=32,
num_local_experts=8,
num_experts_per_tok=4,
scoring_func="sigmoid",
use_routing_bias=True,
use_qk_norm=True,
qk_norm_type="per_layer",
use_grouped_mm=False,
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
),
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
# glm_moe_dsa: HF implementation is incorrect, not supported here
}
def _create_hf_model(preset, config):
"""Create an HF model from a preset and config."""
hf_cls = preset["hf_model_class"]
if hf_cls is not None:
return hf_cls(config)
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
def _load_hf_model(preset, model_dir, config):
"""Load an HF model from a preset and directory."""
hf_cls = preset["hf_model_class"]
if hf_cls is not None:
return hf_cls.from_pretrained(str(model_dir), config=config)
return AutoModelForCausalLM.from_pretrained(str(model_dir), config=config, trust_remote_code=True)
def _create_hf_model_from_config(preset, config):
"""Create an empty HF model from config (for roundtrip verification)."""
hf_cls = preset["hf_model_class"]
if hf_cls is not None:
return hf_cls._from_config(config)
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
def create(arch: str, output_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
config = preset["config_class"](**preset["config_kwargs"])
print(f"Creating mini {arch} model...")
print(
f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}, "
f"experts={config.n_routed_experts}, moe_intermediate_size={config.moe_intermediate_size}"
)
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
with torch.device("cpu"):
model = preset["hf_model_class"](config)
model = _create_hf_model(preset, config)
param_count = sum(p.numel() for p in model.parameters())
print(f" Parameters: {param_count / 1e6:.1f}M")
@@ -89,11 +141,12 @@ def verify(arch: str, model_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
config = AutoConfig.from_pretrained(str(model_dir))
trust_remote_code = preset["hf_model_class"] is None
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
config._attn_implementation = "sdpa"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = preset["hf_model_class"].from_pretrained(str(model_dir), config=config)
hf_model = _load_hf_model(preset, model_dir, config)
prime_model = preset["prime_model_class"]._from_config(config)
with torch.no_grad():
@@ -107,7 +160,7 @@ def verify(arch: str, model_dir: Path) -> None:
input_ids = torch.randint(0, config.vocab_size, (1, 64))
position_ids = torch.arange(1, 65).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids)
hf_output = hf_model(input_ids=input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids)
logits_diff = prime_output["logits"] - hf_output.logits
@@ -118,10 +171,10 @@ def verify(arch: str, model_dir: Path) -> None:
with torch.no_grad():
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
with torch.device("cuda"), default_dtype(torch.float32):
hf_roundtrip = preset["hf_model_class"]._from_config(config)
hf_roundtrip = _create_hf_model_from_config(preset, config)
hf_roundtrip.load_state_dict(roundtrip_state_dict)
hf_roundtrip_output = hf_roundtrip(input_ids, position_ids)
hf_roundtrip_output = hf_roundtrip(input_ids=input_ids, position_ids=position_ids)
roundtrip_diff = hf_roundtrip_output.logits - hf_output.logits
max_roundtrip_diff = roundtrip_diff.abs().max().item()
print(f" HF -> PrimeRL -> HF roundtrip max logits diff: {max_roundtrip_diff:.6f}")
+50
View File
@@ -0,0 +1,50 @@
#!/bin/bash
JOB_NAME="$1"
OUTPUT_DIR="$2"
if [[ -z "$JOB_NAME" || -z "$OUTPUT_DIR" ]]; then
echo "Usage: $0 JOB_NAME OUTPUT_DIR" >&2
exit 1
fi
SLURM_LOG_DIR="${OUTPUT_DIR}/slurm"
SESSION_NAME="slurm-${JOB_NAME}"
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
echo "Attaching to existing tmux session: $SESSION_NAME"
exec tmux attach-session -t "$SESSION_NAME"
fi
echo "Creating tmux session: $SESSION_NAME"
# Window 0: Terminal
tmux new-session -d -s "$SESSION_NAME" -n "Terminal"
# Window 1: Logs - 3 vertical panes
tmux new-window -t "$SESSION_NAME" -n "Logs"
tmux split-window -v -t "$SESSION_NAME:Logs.0"
tmux split-window -v -t "$SESSION_NAME:Logs.1"
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Inference"
tmux send-keys -t "$SESSION_NAME:Logs.0" \
"tail -F ${SLURM_LOG_DIR}/latest_train_node_rank_*.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.1" \
"tail -F ${SLURM_LOG_DIR}/latest_orchestrator.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.2" \
"tail -F ${SLURM_LOG_DIR}/latest_infer_node_rank_*.log 2>/dev/null" C-m
# Pane title styling
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
tmux set-option -t "$SESSION_NAME" -g pane-border-format " #{pane_title} "
# Focus Terminal window and attach
tmux select-window -t "$SESSION_NAME:Terminal"
exec tmux attach-session -t "$SESSION_NAME"
+1 -1
View File
@@ -44,6 +44,6 @@ curl http://localhost:8000/v1/chat/completions \
## Key files
- `src/prime_rl/inference/server.py` — entry point, env var setup
- `src/prime_rl/inference/config.py` — `InferenceConfig` and all sub-configs
- `src/prime_rl/configs/inference.py` — `InferenceConfig` and all sub-configs
- `src/prime_rl/inference/vllm/server.py` — FastAPI routes and vLLM monkey-patches
- `configs/debug/infer.toml` — minimal debug config
+47
View File
@@ -0,0 +1,47 @@
---
name: installation
description: How to install prime-rl and its optional dependencies. Use when setting up the project, installing extras like deep-gemm for FP8 models, or troubleshooting dependency issues.
---
# Installation
## Basic install
```bash
uv sync
```
This installs all core dependencies defined in `pyproject.toml`.
## All extras at once
The recommended way to install for most users:
```bash
uv sync --all-extras
```
This installs all optional extras (flash-attn, flash-attn-cute, etc.) in one go.
## FP8 inference with deep-gemm
For certain models like GLM-5-FP8, you need `deep-gemm`. Install it via the `fp8-inference` dependency group:
```bash
uv sync --group fp8-inference
```
This installs the pre-built `deep-gemm` wheel. No CUDA build step is needed.
## Dev dependencies
```bash
uv sync --group dev
```
Installs pytest, ruff, pre-commit, and other development tools.
## Key files
- `pyproject.toml` — all dependencies, extras, and dependency groups
- `uv.lock` — pinned lockfile (update with `uv sync --all-extras`)
+57 -2
View File
@@ -67,20 +67,75 @@ Use the string `"None"` in TOML to set a field to None:
max_model_len = "None"
```
## SLURM mode
Both `rl` and `sft` commands support SLURM execution via an optional `[slurm]` section. When present, the run is submitted as a SLURM job instead of running locally.
### RL SLURM
```toml
output_dir = "/shared/experiments/my-run"
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
gpus_per_node = 8
# nodes_per_fsdp_group = 1
[slurm]
job_name = "my-rl-job"
# dry_run = true # generate script without submitting
# template_path = "path/to/custom.sh.j2"
# project_dir = "/path/to/project"
```
When `[slurm]` is set for RL:
- `output_dir` must be explicitly set (the default `outputs` is rejected)
- Teacher inference is not supported in multi-node deployment
### SFT SLURM
```toml
output_dir = "/shared/experiments/my-sft-run"
[deployment]
type = "multi_node"
num_nodes = 2
gpus_per_node = 8
# nodes_per_fsdp_group = 1
[slurm]
job_name = "my-sft-job"
# dry_run = true
# template_path = "path/to/custom.sh.j2"
# project_dir = "/path/to/project"
```
SFT deployment follows the same pattern as RL:
- `[deployment]` configures node/GPU allocation (`single_node` default or `multi_node`)
- `[slurm]` configures SLURM submission (job name, partition, template)
- `output_dir` must be explicitly set when using SLURM
- Multi-node deployment requires `[slurm]` to be set
## Available commands
All accept `@ config.toml` and CLI overrides:
| Command | Config class | Description |
|---------|-------------|-------------|
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer |
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer (local or SLURM) |
| `uv run inference` | `InferenceConfig` | vLLM inference server |
| `uv run trainer` | trainer config | RL trainer |
| `uv run orchestrator` | orchestrator config | Rollout orchestrator |
| `uv run env-server` | env server config | Environment server |
| `uv run sft` | SFT config | Supervised fine-tuning |
| `uv run sft` | SFT config | Supervised fine-tuning (local or SLURM) |
## Key files
- `src/prime_rl/utils/pydantic_config.py` — `parse_argv`, `BaseSettings`, `@` syntax parsing
- `src/prime_rl/rl.py` — unified RL entrypoint (local + SLURM)
- `src/prime_rl/configs/rl.py` — `RLConfig`, `SlurmConfig, DeploymentConfig`, `write_subconfigs`
- `src/prime_rl/trainer/sft/train.py` — unified SFT entrypoint (local + SLURM)
- `src/prime_rl/configs/sft.py` — `SFTConfig`, `SFTSlurmConfig`
- `configs/` — all config files, organized by task
View File
@@ -3,8 +3,8 @@ from typing import Annotated
from pydantic import Field
from prime_rl.orchestrator.config import EnvConfig
from prime_rl.utils.config import LogConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.pydantic_config import BaseSettings
@@ -3,6 +3,7 @@ from typing import Annotated, Any, Literal
from pydantic import Field, model_validator
from prime_rl.configs.shared import BaseModelConfig
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
from prime_rl.utils.utils import rgetattr, rsetattr
@@ -38,16 +39,9 @@ class ParallelConfig(BaseConfig):
return f"tp={self.tp} dp={self.dp}"
class ModelConfig(BaseConfig):
class ModelConfig(BaseModelConfig):
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html)."""
name: Annotated[
str,
Field(
description="Name or path of the HF model to use.",
),
] = "Qwen/Qwen3-0.6B"
dtype: Annotated[
Literal["auto", "float16", "bfloat16", "float32"],
Field(
@@ -76,19 +70,13 @@ class ModelConfig(BaseConfig):
),
] = False
enable_auto_tool_choice: Annotated[
bool,
Field(
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`",
),
] = False
tool_call_parser: Annotated[
str,
str | None,
Field(
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`",
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
'Set to "auto" to infer from the model name.',
),
] = "hermes"
] = None
reasoning_parser: Annotated[
str | None,
@@ -117,6 +105,16 @@ class WeightBroadcastConfig(BaseSettings):
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_all2allv",
"naive",
"pplx",
]
class InferenceConfig(BaseSettings):
"""Configures inference."""
@@ -125,7 +123,7 @@ class InferenceConfig(BaseSettings):
server: ServerConfig = ServerConfig()
# The model configuration
model: ModelConfig = ModelConfig()
model: ModelConfig = Field(default_factory=ModelConfig)
# The parallel configuration
parallel: ParallelConfig = ParallelConfig()
@@ -183,6 +181,23 @@ class InferenceConfig(BaseSettings):
),
] = 1
data_parallel_size_local: Annotated[
int | None,
Field(
ge=1,
description="Number of data parallel replicas to run on this node. Passed to vLLM as `--data-parallel-size-local`.",
),
] = None
data_parallel_rpc_port: Annotated[
int,
Field(
ge=1,
le=65535,
description="RPC port for data parallel communication. Passed to vLLM as `--data-parallel-rpc-port`.",
),
] = 13345
seed: Annotated[
int,
Field(
@@ -190,10 +205,38 @@ class InferenceConfig(BaseSettings):
),
] = 0
enable_expert_parallel: Annotated[
bool,
Field(
description="Enable expert parallelism for MoE models. Passed to vLLM as `--enable-expert-parallel`.",
),
] = False
all2all_backend: Annotated[
All2AllBackend,
Field(
description="All-to-all backend for expert parallel communication. Passed to vLLM as `--all2all-backend`.",
),
] = "allgather_reducescatter"
enable_eplb: Annotated[
bool,
Field(
description="Enable expert parallel load balancer (EPLB). Passed to vLLM as `--enable-eplb`.",
),
] = False
weight_broadcast: Annotated[WeightBroadcastConfig, Field(description="The weight broadcast config.")] = (
WeightBroadcastConfig()
)
enable_return_routed_experts: Annotated[
bool,
Field(
description="Whether to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts`",
),
] = False
@model_validator(mode="after")
def round_up_max_lora_rank(self):
"""Round up max_lora_rank to the nearest valid vLLM value.
@@ -219,8 +262,10 @@ class InferenceConfig(BaseSettings):
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.api_server_count < self.parallel.dp:
self.api_server_count = self.parallel.dp
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
@@ -237,12 +282,13 @@ class InferenceConfig(BaseSettings):
"model.max_model_len": "max_model_len",
"model.enforce_eager": "enforce_eager",
"model.trust_remote_code": "trust_remote_code",
"model.enable_auto_tool_choice": "enable_auto_tool_choice",
"model.tool_call_parser": "tool_call_parser",
"model.reasoning_parser": "reasoning_parser",
"model.rope_scaling": "rope_scaling",
"parallel.tp": "tensor_parallel_size",
"parallel.dp": "data_parallel_size",
"data_parallel_size_local": "data_parallel_size_local",
"data_parallel_rpc_port": "data_parallel_rpc_port",
"enable_lora": "enable_lora",
"enable_prefix_caching": "enable_prefix_caching",
"max_loras": "max_loras",
@@ -250,6 +296,10 @@ class InferenceConfig(BaseSettings):
"max_lora_rank": "max_lora_rank",
"gpu_memory_utilization": "gpu_memory_utilization",
"api_server_count": "api_server_count",
"enable_return_routed_experts": "enable_return_routed_experts",
"enable_expert_parallel": "enable_expert_parallel",
"all2all_backend": "all2all_backend",
"enable_eplb": "enable_eplb",
}
for key in get_all_fields(self):
@@ -1,19 +1,18 @@
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import AliasChoices, BaseModel, Discriminator, Field, Tag, model_validator
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
from prime_rl.utils.config import (
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
TransportConfig,
WandbWithExtrasConfig,
)
from prime_rl.utils.config import (
ModelConfig as BaseModelConfig,
)
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
@@ -376,6 +375,13 @@ class EvalConfig(BaseConfig):
),
] = True
cancel_inflight_rollouts_on_eval: Annotated[
bool,
Field(
description="Whether to cancel in-flight training rollouts before starting online evals. This is useful to avoid congestion (e.g. do not have training + eval rollouts happening at the same time) but leads to slower training steps as rollouts get cancelled and the pipeline has to fill up after each eval",
),
] = False
class CheckpointConfig(BaseConfig):
"""Configures checkpointing the orchestrator."""
@@ -541,9 +547,11 @@ class BufferConfig(BaseConfig):
return self
class AdvantageConfig(BaseConfig):
class DefaultAdvantageConfig(BaseModel):
"""Config for the default advantage."""
model_config = ConfigDict(extra="forbid")
type: Literal["default"] = "default"
length_weighted_mean: bool = False
@@ -560,15 +568,65 @@ class CustomAdvantageConfig(BaseModel):
]
def _advantage_config_discriminator(v: Any) -> str:
if isinstance(v, dict):
return v.get("type", "default")
return getattr(v, "type", "default")
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
AdvantageConfigType: TypeAlias = Annotated[
Annotated[AdvantageConfig, Tag("default")] | Annotated[CustomAdvantageConfig, Tag("custom")],
Discriminator(_advantage_config_discriminator),
class GibberishFilterConfig(BaseModel):
"""Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387)."""
model_config = ConfigDict(extra="forbid")
type: Literal["gibberish"] = "gibberish"
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
),
] = False
token_id_threshold: Annotated[
int,
Field(description="Token IDs above this are candidates for gibberish. BPE tokens are sorted by merge order."),
] = 100_000
logprob_offset: Annotated[
float,
Field(description="Offset from uniform distribution logprob. Threshold = -log(vocab_size) - logprob_offset."),
] = 2.0
class RepetitionFilterConfig(BaseModel):
"""Flags rollouts where the model gets stuck in a repetition loop, emitting high-confidence tokens
for an extended stretch. A rollout is flagged when `window` consecutive tokens are each sampled
with probability above `prob_threshold`. (Section 3.2, https://arxiv.org/abs/2506.13585)"""
model_config = ConfigDict(extra="forbid")
type: Literal["repetition"] = "repetition"
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
),
] = False
window: Annotated[
int,
Field(ge=1, description="Number of consecutive high-probability steps before flagging."),
] = 3_000
prob_threshold: Annotated[
float,
Field(
gt=0,
le=1,
description="Tokens sampled with probability above this are considered repetitive. Consecutive such tokens count toward the window.",
),
] = 0.99
FilterConfig: TypeAlias = Annotated[
GibberishFilterConfig | RepetitionFilterConfig,
Field(discriminator="type"),
]
@@ -588,7 +646,9 @@ class NCCLWeightBroadcastConfig(BaseModel):
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class TeacherModelConfig(BaseConfig):
@@ -640,7 +700,10 @@ class OrchestratorConfig(BaseSettings):
buffer: BufferConfig = BufferConfig()
# The advantage configuration
advantage: AdvantageConfigType | None = AdvantageConfig()
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
# Rollout filters (monitor by default, enforce optionally)
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig()]
# The logging configuration
log: LogConfig = LogConfig()
@@ -654,20 +717,12 @@ class OrchestratorConfig(BaseSettings):
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
# Whether to reset inference weights to base model when starting from scratch
reload_weights_on_start: Annotated[
bool,
Field(description="Whether to reset inference weights to the base model when starting from scratch."),
] = True
# The validation configuration
val: ValConfig | None = None
weight_broadcast: Annotated[WeightBroadcastConfigType, Field(discriminator="type")] = (
FileSystemWeightBroadcastConfig()
)
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
rollout_transport: Annotated[TransportConfigType, Field(discriminator="type")] = FileSystemTransportConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
output_dir: Annotated[
Path,
@@ -691,15 +746,44 @@ class OrchestratorConfig(BaseSettings):
),
] = None
batch_size: Annotated[int, Field(ge=1, description="Number of samples to train on per step.")] = 128
oversampling_factor: Annotated[
float,
batch_size: Annotated[
int | None,
Field(
ge=1,
description="Factor by which to oversample the batch. Will lead to more in-flight group rollout requests at the same time.",
description="Number of samples to train on per step (rollout-based batching). Set this OR token_batch_size.",
),
] = 1.0
] = None
token_batch_size: Annotated[
int | None,
Field(
ge=1,
description="Number of tokens to train on per step (token-based batching). Set this OR batch_size.",
),
] = None
oversampling_factor: Annotated[
float | None,
Field(
ge=1,
description=(
"Rollout-mode batching only. Multiplier used to derive max_inflight_rollouts from batch_size "
"when max_inflight_rollouts is unset."
),
),
] = None
max_inflight_rollouts: Annotated[
int | None,
Field(
ge=1,
description=(
"Maximum number of rollouts to keep in-flight. Required for token-based batching. "
"If batch_size is set and this is unset, defaults to batch_size * oversampling_factor "
"(or batch_size when oversampling_factor is unset)."
),
),
] = None
rollouts_per_example: Annotated[
int,
@@ -765,6 +849,20 @@ class OrchestratorConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
use_token_client: Annotated[
bool,
Field(
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
),
] = True
@model_validator(mode="after")
def validate_unique_filter_types(self):
types = [f.type for f in self.filters]
if len(types) != len(set(types)):
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
return self
@model_validator(mode="after")
def validate_max_concurrent(self):
if self.max_concurrent is not None and self.max_concurrent < self.rollouts_per_example:
@@ -779,9 +877,35 @@ class OrchestratorConfig(BaseSettings):
return self
@model_validator(mode="after")
def validate_batch_size(self):
if self.batch_size % self.rollouts_per_example != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
def resolve_batching(self):
has_rollout_batch = self.batch_size is not None
has_token_batch = self.token_batch_size is not None
if has_rollout_batch and has_token_batch:
raise ValueError("Set exactly one of batch_size or token_batch_size")
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_rollouts is None:
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.rollouts_per_example != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
expected_max_inflight_rollouts = int(self.batch_size * self.oversampling_factor)
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
if self.max_inflight_rollouts is None:
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
self.max_inflight_rollouts = int(self.batch_size * oversampling_factor)
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
return self
@model_validator(mode="after")
+720
View File
@@ -0,0 +1,720 @@
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.orchestrator import (
CheckpointConfig as OrchestratorCheckpointConfig,
)
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.shared import (
SlurmConfig,
WandbConfig,
WandbWithExtrasConfig,
)
from prime_rl.configs.trainer import (
BenchConfig,
FakeDataLoaderConfig,
TrainerConfig,
)
from prime_rl.configs.trainer import (
CheckpointConfig as TrainerCheckpointConfig,
)
from prime_rl.configs.trainer import (
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.utils.pydantic_config import BaseSettings
from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_async_level,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_output_dir,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
class SharedLogConfig(BaseSettings):
"""Configures shared logging."""
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
file: Annotated[bool | None, Field(description="Whether to log to a file.")] = True
json_logging: Annotated[
bool,
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
] = False
class SharedWandbConfig(BaseSettings):
"""Configures shared W&B configs."""
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
class SharedCheckpointConfig(BaseSettings):
"""Configures shared checkpoint configs."""
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
resume_step: Annotated[
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
] = None
keep_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
class SharedModelConfig(BaseSettings):
"""Configures shared model settings."""
name: Annotated[
str,
Field(description="The name of the model to use."),
] = "Qwen/Qwen3-0.6B"
class SharedWeightBroadcastConfig(BaseSettings):
"""Configures shared weight broadcast settings."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
"filesystem"
)
port: Annotated[int, Field(description="The port to use for NCCL weight broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
class BaseDeploymentConfig(BaseModel):
"""Configures a base deployment."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a single node deployment."""
type: Literal["single_node"] = "single_node"
num_train_gpus: Annotated[int, Field(description="Number of training GPUs")] = 1
num_infer_gpus: Annotated[int, Field(description="Number of inference GPUs")] = 1
num_teacher_gpus: Annotated[int | None, Field(description="Number of teacher inference GPUs")] = None
@model_validator(mode="after")
def validate_gpu_count(self):
total = self.num_train_gpus + self.num_infer_gpus + (self.num_teacher_gpus or 0)
if total > self.gpus_per_node:
raise ValueError(
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer"
f" + {self.num_teacher_gpus or 0} teacher) exceeds gpus_per_node ({self.gpus_per_node})."
)
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi node deployment."""
type: Literal["multi_node"] = "multi_node"
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
num_infer_nodes: Annotated[int, Field(description="Number of inference nodes.")]
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="Number of training nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group."
),
] = None
@model_validator(mode="after")
def teacher_inference_not_supported(self):
if self.num_teacher_nodes is not None:
raise ValueError("Teacher inference is not yet supported in multi node deployment.")
return self
DeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
]
class RLConfig(BaseSettings):
"""Configures an RL training run."""
trainer: TrainerConfig
orchestrator: OrchestratorConfig
inference: Annotated[
InferenceConfig | None,
Field(
description="The inference config. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."
),
] = None
teacher_inference: Annotated[
InferenceConfig | None,
Field(
description="Teacher inference config. If None, will use the same config as inference or a default config. Only used when teacher GPUs or nodes are set."
),
] = None
output_dir: Annotated[
Path,
Field(
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
),
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
### Shared configurations
log: Annotated[
SharedLogConfig,
Field(
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
),
] = SharedLogConfig()
ckpt: Annotated[
SharedCheckpointConfig | None,
Field(
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
),
] = None
wandb: Annotated[
SharedWandbConfig | None,
Field(
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
),
] = None
model: Annotated[
SharedModelConfig | None,
Field(
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
),
] = None
max_steps: Annotated[
int | None,
Field(
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
),
] = None
max_model_len: Annotated[
int | None,
Field(
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
),
] = None
seq_len: Annotated[
int | None,
Field(
description="Shared sequence length. Propagates to trainer.model.seq_len and orchestrator.seq_len, "
"but only for those not explicitly set in the config. "
"Explicitly set per-component values always take precedence."
),
] = None
max_async_level: Annotated[
int | None,
Field(
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
),
] = None
weight_broadcast: Annotated[
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
] = None
bench: Annotated[
bool,
Field(
description="Whether to run in benchmark mode. Automatically sets the trainer and orchestrator to benchmark mode and, if present, suffixes the W&B project with `-bench`.",
),
] = False
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
slurm: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
if self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if not self.inference:
raise ValueError("Must configure inference when using multi-node deployment.")
return self
# TODO: fix this
@model_validator(mode="after")
def validate_no_teacher_in_multinode(self):
if self.deployment.type == "multi_node" and self.teacher_inference is not None:
raise ValueError(
"Teacher inference is not supported in multi-node deployment. "
"The SLURM template only handles inference and training nodes."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.deployment.type == "single_node":
if self.trainer.weight_broadcast.type == "nccl":
if self.deployment.num_train_gpus + self.deployment.num_infer_gpus < 2:
raise ValueError(
"NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group."
)
return self
@model_validator(mode="after")
def validate_teacher_model(self):
if (
self.trainer.loss.type == "default" and self.trainer.loss.teacher_tau > 0
) and not self.orchestrator.teacher_model:
raise ValueError(
"teacher_model must be configured when teacher_tau > 0. "
"Either set teacher_tau = 0, set deployment.num_teacher_gpus, or configure teacher_model manually."
)
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
def auto_setup_output_dir(self):
"""Auto-setup shared output directory for trainer and orchestrator."""
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_logs(self):
"""Auto-setup shared log config for trainer and orchestrator."""
if self.log is not None:
if self.log.level is not None:
self.trainer.log.level = self.log.level
self.orchestrator.log.level = self.log.level
if self.log.file is not None:
self.trainer.log.file = self.log.file
self.orchestrator.log.file = self.log.file
self.trainer.log.json_logging = self.log.json_logging
self.orchestrator.log.json_logging = self.log.json_logging
return self
@model_validator(mode="after")
def auto_setup_ckpt(self):
"""Auto-setup shared checkpoint config for trainer and orchestrator."""
if self.ckpt is not None:
# Create checkpoint configs if not specified
if self.trainer.ckpt is None:
self.trainer.ckpt = TrainerCheckpointConfig()
if self.orchestrator.ckpt is None:
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
# If specified, use the same ckpt interval
if self.ckpt.interval is not None:
self.trainer.ckpt.interval = self.ckpt.interval
self.orchestrator.ckpt.interval = self.ckpt.interval
# If resuming training, ensure orchestrator resume from the same step
if self.ckpt.resume_step is not None:
self.trainer.ckpt.resume_step = self.ckpt.resume_step
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
# If specified, propagate keep policy
if self.ckpt.keep_last is not None:
self.trainer.ckpt.keep_last = self.ckpt.keep_last
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
if self.ckpt.keep_interval is not None:
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
validate_shared_ckpt_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_wandb(self):
"""Auto-setup shared W&B config for trainer and orchestrator."""
if self.wandb is not None:
if not self.trainer.wandb:
self.trainer.wandb = WandbConfig()
if not self.orchestrator.wandb:
self.orchestrator.wandb = WandbWithExtrasConfig()
if self.wandb.project:
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
validate_shared_wandb_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_model(self):
"""Auto-setup shared model config for trainer, orchestrator, and inference."""
if self.model is not None:
self.trainer.model.name = self.model.name
self.orchestrator.model.name = self.model.name
if self.inference is not None:
self.inference.model.name = self.model.name
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_max_steps(self):
"""Auto-setup shared max steps for trainer and orchestrator."""
if self.max_steps is not None:
self.trainer.max_steps = self.max_steps
self.orchestrator.max_steps = self.max_steps
validate_shared_max_steps(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_async_level(self):
"""Auto-setup shared async level for trainer and orchestrator."""
if self.max_async_level is not None:
self.trainer.max_async_level = self.max_async_level
self.orchestrator.max_async_level = self.max_async_level
validate_shared_max_async_level(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_seq_len(self):
"""Auto-setup shared seq_len for trainer and orchestrator.
Only propagates to components that weren't explicitly set in the config.
Uses model_fields_set to detect explicit assignment.
"""
if self.seq_len is not None:
if "seq_len" not in self.trainer.model.model_fields_set:
self.trainer.model.seq_len = self.seq_len
if "seq_len" not in self.orchestrator.model_fields_set:
self.orchestrator.seq_len = self.seq_len
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
return self
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
self.trainer.bench = BenchConfig()
self.orchestrator.bench = True
self.trainer.data.fake = FakeDataLoaderConfig(
batch_size=self.orchestrator.batch_size or 32,
)
trainer_bench_enabled = self.trainer.bench is not None
if trainer_bench_enabled != self.orchestrator.bench:
raise ValueError(
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode "
f"({self.orchestrator.bench}) must match. Use the top-level bench = true to set both."
)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank."
)
return self
@model_validator(mode="after")
def auto_setup_router_replay(self):
if self.trainer.enable_router_replay:
if self.inference is not None:
if self.inference.enable_return_routed_experts is False:
warnings.warn(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True."
)
self.inference.enable_return_routed_experts = True
else:
warnings.warn(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server."
)
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "single_node": # single-node
# set num_train_workers to the number of data replicas
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
if self.deployment.num_train_gpus > 1:
self.orchestrator.num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
# fill up inference capacity with dp ranks
if self.inference is not None:
num_infer_gpus = self.deployment.num_infer_gpus
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
assert num_infer_gpus % self.inference.parallel.tp == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.trainer.model.dp_replicate = (
self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
)
if self.inference is not None and self.inference.enable_expert_parallel:
inference_tp = self.inference.parallel.tp
if self.deployment.gpus_per_node % inference_tp != 0:
raise ValueError(
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
"when inference.enable_expert_parallel is enabled in multi-node deployment."
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
)
if self.inference.data_parallel_size_local is None:
self.inference.data_parallel_size_local = inferred_dp_local
elif self.inference.data_parallel_size_local != inferred_dp_local:
raise ValueError(
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
)
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
self.inference.api_server_count = inferred_dp_local
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
self.trainer.weight_broadcast.inference_world_size = (
self.deployment.gpus_per_node * self.deployment.num_infer_nodes
)
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
if self.deployment.type != "single_node":
return self
if self.deployment.num_teacher_gpus is None or self.deployment.num_teacher_gpus == 0:
return self
import copy
from prime_rl.configs.orchestrator import TeacherModelConfig
if self.teacher_inference is None:
if self.inference is None:
self.teacher_inference = InferenceConfig()
else:
self.teacher_inference = copy.deepcopy(self.inference)
self.teacher_inference.server.port = (self.inference.server.port if self.inference else 8000) + 1
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
raise ValueError(
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
f"inference.server.port ({self.inference.server.port}). "
"Either use different ports or let teacher_inference be auto-configured."
)
tp = self.teacher_inference.parallel.tp
num_teacher_gpus = self.deployment.num_teacher_gpus
if num_teacher_gpus != self.teacher_inference.parallel.dp * tp:
assert num_teacher_gpus % tp == 0, "Number of teacher GPUs must be divisible by tensor parallel size"
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
if self.orchestrator.teacher_model is None:
self.orchestrator.teacher_model = TeacherModelConfig()
host = self.teacher_inference.server.host or "localhost"
port = self.teacher_inference.server.port
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
return self
### Warnings
@model_validator(mode="after")
def warn_wandb_resume_id_missing(self):
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
if self.trainer.wandb and not self.trainer.wandb.id:
warnings.warn(
"W&B run ID is not set for trainer even though resuming training. The current run will be created as a new run."
)
if self.orchestrator.ckpt is not None and self.orchestrator.ckpt.resume_step is not None:
if self.orchestrator.wandb and not self.orchestrator.wandb.id:
warnings.warn(
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
)
return self
@@ -1,19 +1,24 @@
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, Field, model_validator
from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.trainer.config import (
from prime_rl.configs.shared import (
HeartbeatConfig,
LogConfig,
SlurmConfig,
WandbConfig,
)
from prime_rl.configs.trainer import (
AdamWConfig,
BenchConfig,
CheckpointConfig,
ConstantSchedulerConfig,
ModelConfig,
OptimizerConfigType,
SchedulerConfigType,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
)
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
@@ -101,10 +106,52 @@ class SFTDataConfig(BaseDataConfig):
return self
DataConfigType: TypeAlias = FakeDataConfig | SFTDataConfig
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
class SFTTrainerConfig(BaseSettings):
class BaseDeploymentConfig(BaseModel):
"""Base deployment config for SFT."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a single-node SFT deployment."""
type: Literal["single_node"] = "single_node"
num_gpus: Annotated[int, Field(description="Number of GPUs.")] = 1
@model_validator(mode="after")
def validate_gpu_count(self):
if self.num_gpus > self.gpus_per_node:
raise ValueError(f"num_gpus ({self.num_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi-node SFT deployment."""
type: Literal["multi_node"] = "multi_node"
num_nodes: Annotated[int, Field(description="Number of training nodes.")] = 2
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group."
),
] = None
SFTDeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
]
class SFTConfig(BaseSettings):
"""Configures the SFT trainer"""
# The model configuration
@@ -114,13 +161,13 @@ class SFTTrainerConfig(BaseSettings):
tokenizer: TokenizerConfig = TokenizerConfig()
# The data configuration
data: Annotated[DataConfigType, Field(discriminator="type")] = SFTDataConfig()
data: DataConfig = SFTDataConfig()
# The optimizer configuration
optim: Annotated[OptimizerConfigType, Field(discriminator="type")] = AdamWConfig()
optim: OptimizerConfig = AdamWConfig()
# The learning rate scheduler configuration
scheduler: Annotated[SchedulerConfigType, Field(discriminator="type")] = ConstantSchedulerConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
@@ -138,6 +185,13 @@ class SFTTrainerConfig(BaseSettings):
),
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
max_steps: Annotated[
int | None,
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
@@ -169,12 +223,36 @@ class SFTTrainerConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
slurm: Annotated[
SlurmConfig | None,
Field(
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
),
] = None
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
### Pre-validation normalization
@model_validator(mode="before")
@classmethod
def normalize_deployment(cls, data):
if not isinstance(data, dict):
return data
deployment = data.get("deployment")
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
for key in ("num_gpus",):
deployment.pop(key, None)
return data
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if self.ckpt: # Do not checkpoint
self.ckpt = None
def validate_deployment(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
@@ -230,14 +308,6 @@ class SFTTrainerConfig(BaseSettings):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def validate_and_disable_chunked_loss(self):
if isinstance(self.model.fused_lm_head_chunk_size, int):
@@ -254,3 +324,45 @@ class SFTTrainerConfig(BaseSettings):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "multi_node":
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_nodes ({self.deployment.num_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.model.dp_replicate = self.deployment.num_nodes // self.deployment.nodes_per_fsdp_group
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
return self
@@ -1,11 +1,42 @@
from typing import Annotated, Literal
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import Field
from pydantic import BaseModel, Field, model_validator
from prime_rl.utils.pydantic_config import BaseConfig
class ModelConfig(BaseConfig):
class SlurmConfig(BaseConfig):
"""Configures SLURM scheduling."""
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
project_dir: Annotated[
Path,
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
] = Path(".")
template_path: Annotated[
Path | None,
Field(
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
),
] = None
partition: Annotated[
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
] = "cluster"
@model_validator(mode="after")
def resolve_project_dir(self):
self.project_dir = self.project_dir.resolve()
return self
ServerType = Literal["vllm", "openai"]
class BaseModelConfig(BaseConfig):
"""Configures the model."""
name: Annotated[str, Field(description="Name or path of the HF model to use.")] = "Qwen/Qwen3-0.6B"
@@ -18,9 +49,6 @@ class ModelConfig(BaseConfig):
] = False
ServerType = Literal["vllm", "openai"]
class ElasticConfig(BaseConfig):
"""Configures elastic inference pool with DNS-based service discovery.
@@ -118,7 +146,7 @@ class LogConfig(BaseConfig):
vf_level: Annotated[
str,
Field(description="Logging level for the verifiers package. Will determine the logging verbosity and format."),
] = "warn"
] = "info"
file: Annotated[
bool,
@@ -259,3 +287,27 @@ class MetricsServerConfig(BaseConfig):
description="Host to bind the server to. Defaults to 0.0.0.0.",
),
] = "0.0.0.0"
class BaseTransportConfig(BaseModel):
"""Base configuration for transport."""
pass
class FileSystemTransportConfig(BaseTransportConfig):
"""Configures filesystem-based transport for training examples."""
type: Literal["filesystem"] = "filesystem"
class ZMQTransportConfig(BaseTransportConfig):
"""Configures ZMQ-based transport for training examples."""
type: Literal["zmq"] = "zmq"
host: Annotated[str, Field(description="The host address for ZMQ transport.")] = "localhost"
port: Annotated[int, Field(description="The base port for ZMQ transport.")] = 5555
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
@@ -1,9 +1,21 @@
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BaseModel, Field, model_validator
from prime_rl.utils.pydantic_config import BaseConfig
from prime_rl.configs.shared import (
BaseModelConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
MetricsServerConfig,
TransportConfig,
WandbConfig,
)
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
@@ -13,11 +25,6 @@ AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_atte
# to attempt installing a kernel from hub.
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
MOE_MODEL_MAPS = {
"Qwen/Qwen3-30B-A3B": "Jackmin108/Qwen3-30B-A3B-Fast",
"moonshotai/Moonlight-16B-A3B-Instruct": "Jackmin108/Moonlight-16B-A3B-Instruct-Fast",
}
class ActivationCheckpointConfig(BaseConfig):
"""Configures activation checkpointing."""
@@ -63,22 +70,6 @@ class BenchConfig(BaseConfig):
] = None
class DebugModelConfig(BaseConfig):
"""Debugging feature around model and distributed training."""
num_layers: Annotated[
int | None,
Field(description="The number of layers in the model."),
] = None
random_init: Annotated[
bool,
Field(
description="Whether to random initialize the model.",
),
] = False
class LoRAConfig(BaseConfig):
"""Configuration for LoRA (Low-Rank Adaptation)."""
@@ -131,15 +122,24 @@ class LoRAConfig(BaseConfig):
] = []
class ModelConfig(BaseConfig):
"""Configures the model for training."""
class DebugModelConfig(BaseConfig):
"""Debugging feature around model and distributed training."""
name: Annotated[
str,
num_layers: Annotated[
int | None,
Field(description="The number of layers in the model."),
] = None
random_init: Annotated[
bool,
Field(
description="Name or path of the HF model to use.",
description="Whether to random initialize the model.",
),
] = "Qwen/Qwen3-0.6B"
] = False
class ModelConfig(BaseModelConfig):
"""Configures the model for training."""
seq_len: Annotated[int, Field(description="The sequence length to use for the model.")] = 2048
@@ -189,13 +189,6 @@ class ModelConfig(BaseConfig):
bool, Field(description="Whether to reshard the model after each forward pass.")
] = True
trust_remote_code: Annotated[
bool,
Field(
description="Whether to trust remote code for model and tokenizer initialization.",
),
] = False
dp_replicate: Annotated[
int,
Field(
@@ -255,6 +248,13 @@ class ModelConfig(BaseConfig):
),
] = True
freeze_moe_router: Annotated[
bool,
Field(
description="Whether to freeze the MoE router parameters during training.",
),
] = False
lora: Annotated[
LoRAConfig | None,
Field(
@@ -276,12 +276,12 @@ class ModelConfig(BaseConfig):
"The chunk size to use for the fused LM head. "
"Three behaviors: "
"(1) int >= 512: explicitly set chunk size for fused LM head; "
"(2) 'auto': auto-enable (RL training auto-sets to 2048); "
"(2) 'auto': auto-enable (RL training auto-sets to 8192); "
"(3) 'disabled': explicitly disable fused LM head (use vanilla). "
"Explicitly setting an integer value for this feature isn't supported for SFT training."
),
),
] = "auto"
] = "disabled"
@model_validator(mode="before")
@classmethod
@@ -291,13 +291,6 @@ class ModelConfig(BaseConfig):
data["attn"] = _ATTN_ALIASES[data["attn"]]
return data
@model_validator(mode="after")
def _map_model_name_for_moe(self):
"""Map model name if it exists in MOE_MODEL_MAPS."""
if self.name in MOE_MODEL_MAPS:
self.name = MOE_MODEL_MAPS[self.name]
return self
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
@@ -334,10 +327,16 @@ class ModelConfig(BaseConfig):
def fused_lm_head_chunk_size_is_valid(self):
if isinstance(self.fused_lm_head_chunk_size, int):
low = 512
warn_threshold = 8192
if self.fused_lm_head_chunk_size < low:
raise ValueError(
f"Fused LM head chunk size must be at least {low}, got {self.fused_lm_head_chunk_size}"
)
if self.fused_lm_head_chunk_size < warn_threshold:
warnings.warn(
f"Fused LM head chunk size is set to {self.fused_lm_head_chunk_size}, which is less than the recommended threshold of {warn_threshold}. This may cause some runs to diverge due to numerical instability in floating point arithmetic."
)
return self
@model_validator(mode="after")
@@ -408,7 +407,9 @@ class CosineSchedulerConfig(BaseModel):
min_lr: Annotated[float, Field(ge=0, description="Minimum learning rate to converge to.")] = 0.0
SchedulerConfigType: TypeAlias = ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig
SchedulerConfig: TypeAlias = Annotated[
ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type")
]
class BaseOptimizerConfig(BaseModel):
@@ -442,7 +443,7 @@ class MuonConfig(BaseOptimizerConfig):
] = 0.95
OptimizerConfigType: TypeAlias = SGDConfig | AdamWConfig | MuonConfig
OptimizerConfig: TypeAlias = Annotated[SGDConfig | AdamWConfig | MuonConfig, Field(discriminator="type")]
class WeightCheckpointConfig(BaseConfig):
@@ -527,3 +528,304 @@ class CheckpointConfig(BaseConfig):
description="Whether to skip loading the dataloader from checkpoint.",
),
] = False
# -- RL trainer-specific configs --
class DefaultLossConfig(BaseModel):
"""Config for the default loss."""
type: Literal["default"] = "default"
ratio_type: Annotated[Literal["token", "sequence"], Field(description="Type of importance ratio to use.")] = "token"
token_mask_high: Annotated[
float, Field(ge=0, description="The high threshold for token importance ratio to mask.")
] = 8.0
token_mask_low: Annotated[
float, Field(ge=0, description="The low threshold for token importance ratio to mask.")
] = 0.125
sequence_clip_high: Annotated[
float, Field(ge=0, description="The high threshold for sequence importance ratio to clip.")
] = 10.0
geo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for geo importance ratio to mask.")] = (
10.0
)
geo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for geo importance ratio to mask.")] = 0.1
sequence_mask_low: Annotated[
float,
Field(
ge=0,
description="If set, masks entire sequences when any generated token has an importance ratio below this value.",
),
] = 0.0
sequence_mask_high: Annotated[
float,
Field(
ge=0,
description="If set, masks entire sequences when any generated token has an importance ratio above this value.",
),
] = 100.0
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 0.0
@model_validator(mode="after")
def validate_mask_bounds(self):
if self.token_mask_low >= self.token_mask_high:
raise ValueError(
f"token_mask_low ({self.token_mask_low}) must be less than token_mask_high ({self.token_mask_high})"
)
if self.geo_mask_low >= self.geo_mask_high:
raise ValueError(
f"geo_mask_low ({self.geo_mask_low}) must be less than geo_mask_high ({self.geo_mask_high})"
)
if self.sequence_mask_low >= self.sequence_mask_high:
raise ValueError(
f"sequence_mask_low ({self.sequence_mask_low}) must be less than sequence_mask_high ({self.sequence_mask_high})"
)
return self
class CustomLossConfig(BaseModel):
"""Config for a custom external loss function."""
type: Literal["custom"] = "custom"
import_path: Annotated[str, Field(description="Import path to the loss function (e.g., 'my_module.my_loss')")]
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
"""Configures a fake data loader sampling random micro batches for debugging."""
batch_size: Annotated[int, Field(ge=1)] = 2
generate_samples: Annotated[
bool, Field(description="Whether to generate separate samples and pack them into a single micro batch.")
] = False
class DataLoaderConfig(BaseConfig):
"""Configures the data loader used for training."""
fake: Annotated[FakeDataLoaderConfig | None, Field(description="Whether to use a fake data loader.")] = None
class BaseWeightBroadcastConfig(BaseModel):
"""Configures the base weight broadcast."""
pass
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
"""Configures the weight broadcast."""
type: Literal["filesystem"] = "filesystem"
save_sharded: Annotated[bool, Field(description="Whether to save the weight checkpoint in sharded format.")] = True
save_format: Annotated[
Literal["safetensors", "torch"], Field(description="The format to save the weight checkpoint in.")
] = "safetensors"
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
"""Configures the NCCL broadcast."""
type: Literal["nccl"] = "nccl"
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
# TODO: Should not be configurable, but auto-inferred
inference_world_size: Annotated[int, Field(description="The number of GPUs used for inference.")] = 1
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class TrainerConfig(BaseSettings):
"""Configures the RL trainer"""
# The model configuration
model: ModelConfig = ModelConfig()
# The tokenizer configuration
tokenizer: TokenizerConfig = TokenizerConfig()
# The data configuration
data: DataLoaderConfig = DataLoaderConfig()
# The loss configuration
loss: LossConfig = DefaultLossConfig()
# The optimizer configuration
optim: OptimizerConfig = AdamWConfig()
# The learning rate scheduler configuration
scheduler: SchedulerConfig = ConstantSchedulerConfig()
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
# The logging configuration
log: LogConfig = LogConfig()
# The wandb configuration
wandb: WandbConfig | None = None
output_dir: Annotated[
Path,
Field(
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
),
] = Path("outputs")
max_steps: Annotated[
int | None,
Field(
description="Maximum number of steps to run training for. If None, will run indefinitely.",
),
] = None
max_async_level: Annotated[
int,
Field(
ge=0,
description="Maximum number of steps that inference can be ahead of training. Determines how 'off-policy' the inference engines can be. Higher values yield better throughput through async execution, but may yield lower performance. If 0, will be fully synchronous.",
),
] = 1
enable_router_replay: Annotated[
bool,
Field(
description="Whether to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models.",
),
] = False
memory_profiler_path: Annotated[Path | None, Field(description="Path to write memory profile to.")] = None
bench: Annotated[
BenchConfig | None,
Field(
description="Whether to run in benchmark mode. It will automatically set the maximum number of steps to run to 4 and use fake data.",
),
] = None
trace_path: Annotated[Path | None, Field(description="Path to write pytorch profiler trace to.")] = None
dist_timeout_seconds: Annotated[
int,
Field(
description="Timeout in seconds for torch distributed ops. Defaults to 600 seconds.",
),
] = 600
heartbeat: Annotated[
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
metrics_server: Annotated[
MetricsServerConfig | None,
Field(description="Prometheus metrics server config. If set, exposes /metrics endpoint for scraping."),
] = None
max_concurrent_runs: Annotated[
int,
Field(
ge=1,
description="The maximum number of concurrent runs to allow. If 1, then only one run will be allowed at a time.",
),
] = 1
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if not self.data.fake:
self.data.fake = FakeDataLoaderConfig()
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def dont_do_massive_traces(self):
if self.trace_path:
if self.max_steps is None:
raise ValueError("Must specify max_steps when tracing")
if self.max_steps >= 10:
raise ValueError(
"Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
lora_enabled = self.model and self.model.lora
if not lora_enabled:
raise ValueError(
"save_adapter_separately=True requires LoRA to be enabled. "
"Set model.lora or disable save_adapter_separately."
)
return self
@model_validator(mode="after")
def validate_weight_broadcast_type(self):
if self.weight_broadcast.type == "nccl" and self.max_async_level != 1:
raise ValueError("NCCL weight broadcast only works with async level 1")
return self
@model_validator(mode="after")
def validate_opt_and_fsdp_offload(self):
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_optim_cpu_offload_single_run(self):
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
return self
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
# TODO: Support this
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_fused_lm_head_chunk_size(self):
if self.model.fused_lm_head_chunk_size == "auto":
self.model.fused_lm_head_chunk_size = 8192
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@model_validator(mode="after")
def router_replay_only_with_custom_impl(self):
if self.enable_router_replay and self.model.impl not in ("custom", "auto"):
raise ValueError("Router replay is only supported with the custom implementation or auto mode")
return self
+455
View File
@@ -0,0 +1,455 @@
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.rl import RLConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import (
get_free_port,
get_log_dir,
)
RL_TOML = "rl.toml"
RL_SBATCH = "rl.sbatch"
TRAINER_TOML = "trainer.toml"
ORCHESTRATOR_TOML = "orchestrator.toml"
INFERENCE_TOML = "inference.toml"
TEACHER_INFERENCE_TOML = "teacher_inference.toml"
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
output_dir.mkdir(parents=True, exist_ok=True)
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
with open(output_dir / RL_TOML, "wb") as f:
tomli_w.dump(config_dict, f)
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / TRAINER_TOML, "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
with open(output_dir / ORCHESTRATOR_TOML, "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
if config.inference is not None:
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
teacher_inference = getattr(config, "teacher_inference", None)
if teacher_inference is not None:
with open(output_dir / TEACHER_INFERENCE_TOML, "wb") as f:
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
def check_gpus_available(gpu_ids: list[int]) -> None:
"""Raise error if there are existing processes on the specified GPUs."""
pynvml.nvmlInit()
occupied = []
for gpu_id in gpu_ids:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
if processes:
pids = [p.pid for p in processes]
occupied.append((gpu_id, pids))
if occupied:
msg = "Existing processes found on GPUs:\n"
for gpu_id, pids in occupied:
msg += f" GPU {gpu_id}: PIDs {pids}\n"
msg += "Kill these processes or use different GPUs."
raise RuntimeError(msg)
def rl_local(config: RLConfig):
assert config.deployment.type == "single_node"
logger = setup_logger(
config.log.level or "info",
log_file=config.output_dir / "logs" / "rl.log" if config.log.file else None,
json_logging=config.log.json_logging,
)
config_dir = config.output_dir / "configs"
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
if config.dry_run:
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
# Derive GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
infer_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
gpu_offset += num_infer_gpus
trainer_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
gpu_offset += config.deployment.num_train_gpus
num_teacher_gpus = config.deployment.num_teacher_gpus or 0
teacher_gpu_ids = list(range(gpu_offset, gpu_offset + num_teacher_gpus)) if num_teacher_gpus > 0 else []
start_command = sys.argv
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Check for existing processes on GPUs
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
check_gpus_available(all_gpu_ids)
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Prepare paths to communicate with the trainer
log_dir = get_log_dir(config.output_dir)
log_dir.mkdir(parents=True, exist_ok=True)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
try:
# Optionally, start inference process
if config.inference:
inference_cmd = ["uv", "run", "inference", "@", (config_dir / INFERENCE_TOML).as_posix()]
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.stdout", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
)
# Optionally, start teacher inference process
if config.teacher_inference:
if not teacher_gpu_ids:
raise ValueError(
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
)
teacher_inference_cmd = ["uv", "run", "inference", "@", (config_dir / TEACHER_INFERENCE_TOML).as_posix()]
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, teacher_gpu_ids))}")
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
with open(log_dir / "teacher_inference.stdout", "w") as log_file:
teacher_inference_process = Popen(
teacher_inference_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, teacher_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(teacher_inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["teacher_inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
elif (
config.trainer.loss.type == "default" and config.trainer.loss.teacher_tau > 0
) or config.orchestrator.teacher_model:
logger.warning(
"No teacher_inference config specified, skipping starting teacher inference server. "
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
)
# Start orchestrator process
orchestrator_cmd = [
"uv",
"run",
"orchestrator",
"@",
(config_dir / ORCHESTRATOR_TOML).as_posix(),
]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.stdout", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / TRAINER_TOML).as_posix(),
]
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", log_dir / "trainer.stdout"])
processes.append(tail_process)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# Small delay to avoid busy waiting
time.sleep(1)
# Check if any critical process failed
if orchestrator_process.returncode != 0:
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
logger.success("RL training finished!")
# Cleanup threads and processes
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
if config.deployment.type == "single_node":
script = template.render(
config_path=config_dir / RL_TOML,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
partition=config.slurm.partition,
output_dir=config.output_dir,
gpus_per_node=config.deployment.gpus_per_node,
)
else:
assert config.inference is not None
script = template.render(
config_dir=config_dir, # TODO: should prob have each subconfig path separately
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
partition=config.slurm.partition,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.num_infer_nodes,
num_teacher_nodes=config.deployment.num_teacher_nodes,
gpus_per_node=config.deployment.gpus_per_node,
inference_tp=config.inference.parallel.tp,
inference_enable_expert_parallel=config.inference.enable_expert_parallel,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def rl_slurm(config: RLConfig):
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = config.output_dir / "configs"
if config.deployment.type == "single_node":
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
logger.info(f"Wrote config to {config_dir / RL_TOML}")
log_dir = get_log_dir(config.output_dir)
log_message = (
f"Logs:\n"
f" Trainer: tail -F {log_dir}/trainer.stdout\n"
f" Orchestrator: tail -F {log_dir}/orchestrator.stdout\n"
f" Inference: tail -F {log_dir}/inference.stdout"
)
else:
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
slurm_log_dir = config.output_dir / "slurm"
log_message = (
f"Logs:\n"
f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log\n"
f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log\n"
f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log"
)
script_path = config.output_dir / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def rl(config: RLConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
rl_slurm(config)
else:
rl_local(config)
def main():
rl(parse_argv(RLConfig))
if __name__ == "__main__":
main()
+214
View File
@@ -0,0 +1,214 @@
import os
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import tomli_w
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import get_config_dir, get_log_dir, validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import get_free_port
SFT_TOML = "sft.toml"
SFT_SBATCH = "sft.sbatch"
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
config_path.parent.mkdir(parents=True, exist_ok=True)
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
with open(config_path, "wb") as f:
tomli_w.dump(config_dict, f)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
if config.deployment.type == "single_node":
script = template.render(
config_path=config_path,
output_dir=config.output_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
gpus_per_node=config.deployment.gpus_per_node,
partition=config.slurm.partition,
)
else:
script = template.render(
config_path=config_path,
output_dir=config.output_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
num_nodes=config.deployment.num_nodes,
gpus_per_node=config.deployment.gpus_per_node,
partition=config.slurm.partition,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_path = config_dir / SFT_TOML
exclude = (
{"deployment", "slurm", "dry_run", "clean_output_dir"}
if config.deployment.type == "multi_node"
else {"slurm", "dry_run", "clean_output_dir"}
)
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
if config.deployment.type == "single_node":
log_message = f"Logs:\n Trainer: tail -F {get_log_dir(config.output_dir)}/trainer/rank_0.log"
else:
log_message = f"Logs:\n Trainer: tail -F {config.output_dir}/slurm/latest_train_node_rank_*.log"
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def sft_local(config: SFTConfig):
"""Run SFT training locally with process monitoring and cleanup."""
assert config.deployment.type == "single_node"
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_path = config_dir / SFT_TOML
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
if config.dry_run:
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
log_dir = config.output_dir / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
(config_dir / SFT_TOML).as_posix(),
]
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
logger.debug(f"Trainer command: {' '.join(trainer_cmd)}")
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
try:
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
stop_event = Event()
monitor_thread = Thread(
target=monitor_process,
args=(trainer_process, stop_event, error_queue, "trainer"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", str(log_dir / "trainer.stdout")])
processes.append(tail_process)
stop_event.wait()
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
logger.success("SFT training finished!")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def sft(config: SFTConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
sft_slurm(config)
else:
sft_local(config)
def main():
sft(parse_argv(SFTConfig))
if __name__ == "__main__":
main()
+154
View File
@@ -1,3 +1,15 @@
def transformers_v5_compat():
"""vLLM general plugin: patch transformers v5 config attrs that vLLM 0.16 still expects.
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
in every vLLM process, including spawned workers.
"""
from transformers import Qwen3VLMoeTextConfig
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
Qwen3VLMoeTextConfig.tie_word_embeddings = False
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
from vllm.v1.metrics import loggers as vllm_metrics_loggers
@@ -191,3 +203,145 @@ def monkey_patch_tokenize_params_validation():
TokenizeParams._token_len_check = _patched_token_len_check
TokenizeParams._text_len_check = _patched_text_len_check
def monkey_patch_hermes_tool_parser_thread_safety():
"""Patch Hermes2ProToolParser to cache tokenizer encode/decode results.
The original __init__ calls tokenizer.encode() and tokenizer.decode() on
every instantiation. Under concurrent load, the shared HuggingFace tokenizer's
Rust backend panics with ``RuntimeError: Already borrowed`` because multiple
threads mutably borrow the same internal state simultaneously.
Fix: run the first __init__ (which calls encode/decode) under a lock, cache
the results, and reuse them for all subsequent instantiations without ever
touching the tokenizer again.
"""
import threading
import regex as re
from vllm.tool_parsers.abstract_tool_parser import ToolParser
from vllm.tool_parsers.hermes_tool_parser import Hermes2ProToolParser
_original_init = Hermes2ProToolParser.__init__
_cache: dict[int, dict] = {}
_lock = threading.Lock()
def _patched_init(self, tokenizer):
from vllm.tokenizers.mistral import MistralTokenizer
# Resolve the actual tokenizer that __init__ will use for encode/decode
actual_tokenizer = tokenizer.tokenizer if isinstance(tokenizer, MistralTokenizer) else tokenizer
key = id(actual_tokenizer)
if key in _cache:
# Fast path: skip encode/decode entirely, set up instance from cache
ToolParser.__init__(self, tokenizer)
if isinstance(tokenizer, MistralTokenizer):
self.model_tokenizer = tokenizer.tokenizer
self.current_tool_name_sent = False
self.prev_tool_call_arr = []
self.current_tool_id = -1
self.streamed_args_for_tool = []
self.tool_call_start_token = "<tool_call>"
self.tool_call_end_token = "</tool_call>"
self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>|<tool_call>(.*)", re.DOTALL)
self.scratch_pad_regex = re.compile(r"<scratch_pad>(.*?)</scratch_pad>", re.DOTALL)
cached = _cache[key]
self.tool_call_start_token_ids = cached["start_ids"]
self.tool_call_end_token_ids = cached["end_ids"]
self.tool_call_start_token_array = cached["start_array"]
self.tool_call_end_token_array = cached["end_array"]
self.buffered_delta_text = ""
return
# Slow path: first instantiation for this tokenizer, run under lock
with _lock:
if key in _cache:
# Another thread populated it while we waited
_patched_init(self, tokenizer)
return
_original_init(self, tokenizer)
_cache[key] = {
"start_ids": self.tool_call_start_token_ids,
"end_ids": self.tool_call_end_token_ids,
"start_array": self.tool_call_start_token_array,
"end_array": self.tool_call_end_token_array,
}
Hermes2ProToolParser.__init__ = _patched_init
def monkey_patch_minimax_m2_for_lora():
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
These patches are only needed when using LoRA with MiniMax M2 but are safe
to apply unconditionally (verified with non-LoRA runs). We apply them at
import time because the worker __init__ runs before the vLLM config is
available, so we can't check if LoRA is enabled.
Problem 1 — Gate dtype mismatch:
vLLM's MiniMaxM2MoE creates the gate (router) with params_dtype=float32
and casts inputs to float32. When LoRA is enabled, vLLM wraps ALL
ReplicatedLinear layers (including the gate) with LoRA support. Even
though our adapter has no gate LoRA weights, the LoRA Triton kernel
still runs for all wrapped layers when any adapter is active — and it
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
problem because its gate uses the model dtype.
Fix: recreate the gate in model dtype and remove the float32 cast.
FusedMoE already has router_logits_dtype=float32, so routing precision
is preserved inside the expert dispatch.
Problem 2 — Adapter key naming mismatch:
PrimeRL saves adapter keys using its internal naming convention
(mlp.experts.{j}.gate_proj/down_proj/up_proj), which matches Qwen3 MoE
but not MiniMax M2. vLLM's MiniMax M2 model expects HF-style keys
(block_sparse_moe.experts.{j}.w1/w2/w3). For full model weights this
is handled by vLLM's load_weights(), but LoRA adapters are loaded
through a separate path (LoRAModel.from_local_checkpoint) that doesn't
have model-specific key translation.
Fix: set hf_to_vllm_mapper on the model class so vLLM remaps adapter
keys during LoRA loading. This attribute is only read by _load_adapter
in the LoRA worker manager — it has no effect without LoRA.
"""
from vllm.model_executor.models.minimax_m2 import MiniMaxM2ForCausalLM, MiniMaxM2MoE
from vllm.model_executor.models.utils import WeightsMapper
# --- Gate dtype fix (only matters with LoRA, safe without) ---
_original_init = MiniMaxM2MoE.__init__
def _patched_init(self, config, quant_config=None, prefix=""):
_original_init(self, config, quant_config, prefix)
from vllm.model_executor.layers.linear import ReplicatedLinear
self.gate = ReplicatedLinear(
config.hidden_size,
config.num_local_experts,
bias=False,
quant_config=None,
prefix=f"{prefix}.gate",
)
def _patched_forward(self, hidden_states):
from vllm.distributed import tensor_model_parallel_all_reduce
num_tokens, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
router_logits, _ = self.gate(hidden_states)
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
if self.tp_size > 1:
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
return final_hidden_states.view(num_tokens, hidden_dim)
MiniMaxM2MoE.__init__ = _patched_init
MiniMaxM2MoE.forward = _patched_forward
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
orig_to_new_substr={
".mlp.experts.": ".block_sparse_moe.experts.",
".gate_proj.": ".w1.",
".down_proj.": ".w2.",
".up_proj.": ".w3.",
},
)
+1 -1
View File
@@ -1,6 +1,6 @@
import os
from prime_rl.inference.config import InferenceConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.pydantic_config import parse_argv
+117 -30
View File
@@ -21,8 +21,98 @@ from vllm.entrypoints.utils import load_aware_call, with_cancellation
from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
from prime_rl.inference.config import InferenceConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.logger import get_logger
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
# GLM-4.5
"zai-org/GLM-4.5": "glm45",
"zai-org/GLM-4.5-FP8": "glm45",
"zai-org/GLM-4.5-Base": "glm45",
"zai-org/GLM-4.5-Air": "glm45",
"zai-org/GLM-4.5-Air-FP8": "glm45",
"zai-org/GLM-4.5-Air-Base": "glm45",
"zai-org/GLM-4.5V": "glm45",
"zai-org/GLM-4.5V-FP8": "glm45",
# GLM-4.7
"zai-org/GLM-4.7": "glm47",
"zai-org/GLM-4.7-FP8": "glm47",
"zai-org/GLM-4.7-Flash": "glm47",
# MiniMax M2
"MiniMaxAI/MiniMax-M2": "minimax_m2",
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
# INTELLECT-3
"PrimeIntellect/INTELLECT-3": "hermes",
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
"PrimeIntellect/INTELLECT-3.1": "hermes",
# Qwen3 dense
"Qwen/Qwen3-0.6B": "hermes",
"Qwen/Qwen3-0.6B-Base": "hermes",
"Qwen/Qwen3-0.6B-FP8": "hermes",
"Qwen/Qwen3-1.7B": "hermes",
"Qwen/Qwen3-1.7B-Base": "hermes",
"Qwen/Qwen3-1.7B-FP8": "hermes",
"Qwen/Qwen3-4B": "hermes",
"Qwen/Qwen3-4B-Base": "hermes",
"Qwen/Qwen3-4B-FP8": "hermes",
"Qwen/Qwen3-8B": "hermes",
"Qwen/Qwen3-8B-Base": "hermes",
"Qwen/Qwen3-8B-FP8": "hermes",
"Qwen/Qwen3-14B": "hermes",
"Qwen/Qwen3-14B-Base": "hermes",
"Qwen/Qwen3-14B-FP8": "hermes",
"Qwen/Qwen3-32B": "hermes",
"Qwen/Qwen3-32B-FP8": "hermes",
# Qwen3 MoE
"Qwen/Qwen3-30B-A3B": "hermes",
"Qwen/Qwen3-30B-A3B-Base": "hermes",
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
"Qwen/Qwen3-235B-A22B": "hermes",
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
# Qwen3 2507
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
# Qwen3-Next
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
# Qwen3-Coder
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
# Qwen3-Coder-Next
"Qwen/Qwen3-Coder-Next": "hermes",
"Qwen/Qwen3-Coder-Next-Base": "hermes",
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
# Qwen3.5
"Qwen/Qwen3.5-397B-A17B": "hermes",
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
}
def resolve_tool_call_parser(model_name: str, tool_call_parser: str | None) -> str | None:
"""Resolve tool_call_parser from model name if set to "auto"."""
if tool_call_parser == "auto":
return MODEL_TOOL_CALL_PARSER.get(model_name)
return tool_call_parser
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_hermes_tool_parser_thread_safety,
monkey_patch_load_lora_adapter,
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode,
monkey_patch_tokenize_params_validation,
@@ -38,6 +128,8 @@ monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode()
monkey_patch_load_lora_adapter()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
monkey_patch_tokenize_params_validation()
# NOTE: Monkeypatch Hermes tool parser to fix "Already borrowed" RuntimeError under concurrent load
monkey_patch_hermes_tool_parser_thread_safety()
logger = init_logger("vllm.entrypoints.openai.api_server")
@@ -76,14 +168,6 @@ async def update_weights(request: Request):
return {"status": "ok"}
@router.post("/reload_weights")
async def reload_weights(request: Request):
await engine_client(request).collective_rpc("reload_weights")
# Reset prefix cache to invalidate KV states computed with old weights
await engine_client(request).reset_prefix_cache()
return {"status": "ok"}
@router.post("/load_lora_adapter")
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
"""Load a LoRA adapter and reset the prefix cache.
@@ -170,28 +254,26 @@ async def custom_init_app_state(
resolved_chat_template = load_chat_template(args.chat_template)
state.openai_serving_chat_with_tokens = (
OpenAIServingChatWithTokens(
engine_client,
state.openai_serving_models,
args.response_role,
request_logger=request_logger,
chat_template=resolved_chat_template,
chat_template_content_format=args.chat_template_content_format,
trust_request_chat_template=args.trust_request_chat_template,
return_tokens_as_token_ids=args.return_tokens_as_token_ids,
enable_auto_tools=args.enable_auto_tool_choice,
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
tool_parser=args.tool_call_parser,
reasoning_parser=args.structured_outputs_config.reasoning_parser,
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
enable_force_include_usage=args.enable_force_include_usage,
enable_log_outputs=args.enable_log_outputs,
log_error_stack=args.log_error_stack,
)
if "generate" in supported_tasks
else None
serving_chat = OpenAIServingChatWithTokens(
engine_client,
state.openai_serving_models,
args.response_role,
request_logger=request_logger,
chat_template=resolved_chat_template,
chat_template_content_format=args.chat_template_content_format,
trust_request_chat_template=args.trust_request_chat_template,
return_tokens_as_token_ids=args.return_tokens_as_token_ids,
enable_auto_tools=args.enable_auto_tool_choice,
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
tool_parser=args.tool_call_parser,
reasoning_parser=args.structured_outputs_config.reasoning_parser,
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
enable_force_include_usage=args.enable_force_include_usage,
enable_log_outputs=args.enable_log_outputs,
log_error_stack=args.log_error_stack,
)
state.openai_serving_chat = serving_chat if "generate" in supported_tasks else None
state.openai_serving_chat_with_tokens = serving_chat if "generate" in supported_tasks else None
def custom_run_api_server_worker_proc(listen_address, sock, args, client_config=None, **uvicorn_kwargs) -> None:
@@ -241,6 +323,11 @@ def server(config: InferenceConfig, vllm_args: list[str]):
assert args is not None
validate_parsed_serve_args(args)
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
args.enable_auto_tool_choice = args.tool_call_parser is not None
if args.tool_call_parser is not None:
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
# Set the worker extension class based on the broadcast backend
args.worker_extension_cls = WORKER_EXTENSION_CLS[config.weight_broadcast.type]
@@ -1,6 +1,8 @@
from collections.abc import AsyncGenerator
import base64
from collections.abc import AsyncGenerator, AsyncIterator
from typing import ClassVar, Optional, Union
import numpy as np
from fastapi import Request
from pydantic import Field
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest, ChatCompletionResponse
@@ -17,48 +19,28 @@ from vllm.v1.sample.logits_processor import validate_logits_processors_parameter
logger = init_logger(__name__)
def _collapse_image_placeholders(
original_tokens: list[int],
override_tokens: list[int],
) -> list[int]:
"""
Collapse pre-expanded image placeholder tokens in override_tokens.
class _RoutedExpertsCapture:
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
self._generator = generator
self.routed_experts: dict[int, dict] = {}
In multi-turn VLM conversations, tokens from previous turns already have
expanded image placeholders (e.g., 64 consecutive <|image_pad|> tokens).
If left as-is, _process_inputs re-expands each token individually, causing
compounding token inflation across turns.
def _encode_routed_experts(self, arr: np.ndarray) -> dict:
return {
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
"shape": list(arr.shape),
}
Detects placeholder token IDs by comparing with the original engine tokens
(which have single placeholders from _preprocess_chat), then collapses
consecutive runs back to single tokens so _process_inputs can expand
them correctly.
"""
if not override_tokens or original_tokens == override_tokens:
return override_tokens
async def __aiter__(self):
async for request_output in self._generator:
for output in request_output.outputs:
if output.routed_experts is not None:
self.routed_experts[output.index] = self._encode_routed_experts(output.routed_experts)
yield request_output
def get_block_tokens(tokens: list[int], min_run: int) -> set[int]:
"""Return token IDs that appear in consecutive runs >= min_run."""
result = set()
run_start = 0
for i in range(1, len(tokens) + 1):
if i == len(tokens) or tokens[i] != tokens[run_start]:
if i - run_start >= min_run:
result.add(tokens[run_start])
run_start = i
return result
# Placeholder tokens appear in blocks of 2+ in override but only as singles in original
placeholder_ids = get_block_tokens(override_tokens, 2) - get_block_tokens(original_tokens, 2)
if not placeholder_ids:
return override_tokens
result = []
for token in override_tokens:
if token in placeholder_ids and result and result[-1] == token:
continue
result.append(token)
return result
def post_process(self, response: ChatCompletionResponse):
for choice in response.choices:
if choice.index in self.routed_experts:
choice.routed_experts = self.routed_experts[choice.index]
class ChatCompletionRequestWithTokens(ChatCompletionRequest):
@@ -67,7 +49,46 @@ class ChatCompletionRequestWithTokens(ChatCompletionRequest):
class OpenAIServingChatWithTokens(OpenAIServingChat):
"""OpenAI-compatible generate API that allows token-in."""
"""OpenAI-compatible generate API that allows token-in and routed experts capture."""
async def chat_completion_full_generator(
self,
request: ChatCompletionRequest,
result_generator: AsyncIterator[RequestOutput],
request_id: str,
model_name: str,
conversation,
tokenizer,
request_metadata: RequestResponseMetadata,
reasoning_parser: ReasoningParser | None = None,
) -> ErrorResponse | ChatCompletionResponse:
# We need to override the full_generator to be able to capture the routed experts
# By default, VLLM does not save the routed experts into ChatCompletionResponse.choices, so we need to capture them manually
# How this works:
# 1. We create a custom generator that encapsulates the original result_generator in self._generator
# 2. We override it's __aiter__ method to also capture the routed experts as an extra field in ChatCompletionResponse.choices
# 3. We override the full_generator method to use the custom generator instead of the original one if expert routing is enabled
if self.model_config.enable_return_routed_experts:
capture = _RoutedExpertsCapture(result_generator)
result_generator = capture
else:
capture = None
response = await super().chat_completion_full_generator(
request,
result_generator,
request_id,
model_name,
conversation,
tokenizer,
request_metadata,
reasoning_parser,
)
if capture and isinstance(response, ChatCompletionResponse):
capture.post_process(response)
return response
async def create_chat_completion_with_tokens(
self,
@@ -102,16 +123,9 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
conversation, engine_prompts = result
# For VLM models: collapse pre-expanded image placeholders before _process_inputs.
# In multi-turn token prompts, previous turns' image placeholders are already expanded
# (e.g., 64 consecutive <|image_pad|>). Without collapsing, _process_inputs re-expands
# each token, inflating counts (64 → 127 → 253 → ...) across turns.
if engine_prompts[0].get("multi_modal_data"):
override_tokens = _collapse_image_placeholders(engine_prompts[0]["prompt_token_ids"], request.tokens) # type: ignore
else:
override_tokens = request.tokens
engine_prompts[0]["prompt_token_ids"] = override_tokens # type: ignore
# VLM conversations use MITO (message-based) instead of TITO, so
# multi_modal_data is not expected here. Override prompt tokens directly.
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
@@ -1,4 +1,6 @@
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager, monkey_patch_minimax_m2_for_lora
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
monkey_patch_LRUCacheWorkerLoRAManager()
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
monkey_patch_minimax_m2_for_lora()
+4 -4
View File
@@ -5,7 +5,7 @@ import torch
from jaxtyping import Float, Int
from torch import Tensor
from prime_rl.orchestrator.config import AdvantageConfigType, CustomAdvantageConfig
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
from prime_rl.utils.utils import import_object
@@ -45,7 +45,7 @@ def default_advantage_fn(inputs: AdvantageInputs, length_weighted_mean: bool = F
return AdvantageOutputs(advantages=inputs.rewards - baseline)
def setup_advantage_fn(config: AdvantageConfigType) -> AdvantageFn:
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
"""Setup advantage function from config."""
if isinstance(config, CustomAdvantageConfig):
custom_fn = import_object(config.import_path)
@@ -66,7 +66,7 @@ def compute_advantages(
rewards: list[float],
completion_lengths: list[int],
samples_per_problem: int,
advantage_config: AdvantageConfigType | None,
advantage_config: AdvantageConfig | None,
) -> list[float]:
"""
Computes advantages from a flattened list of rewards, grouped by problem.
@@ -75,7 +75,7 @@ def compute_advantages(
rewards: Flattened list of rewards where first `samples_per_problem` rewards are for the first problem
completion_lengths: List of completion lengths for each reward
samples_per_problem: Number of samples (and thus, rewards) per problem
advantage_config: Configuration for advantage computation (AdvantageConfig or CustomAdvantageConfig)
advantage_config: Configuration for advantage computation (DefaultAdvantageConfig or CustomAdvantageConfig)
"""
if not advantage_config:
return rewards
+1 -1
View File
@@ -10,7 +10,7 @@ import verifiers as vf
from datasets import Dataset
from verifiers.utils.save_utils import make_serializable
from prime_rl.orchestrator.config import BufferConfig
from prime_rl.configs.orchestrator import BufferConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import format_num, mean, mean_normalize
+5 -5
View File
@@ -4,8 +4,8 @@ from pathlib import Path
import torch
from prime_rl.configs.orchestrator import CheckpointConfig
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.config import CheckpointConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import get_ckpt_dir, get_step_path
@@ -29,7 +29,7 @@ class CheckpointManager:
def get_ckpt_path(self, step: int) -> Path:
return get_step_path(self.ckpt_dir, step) / "orchestrator"
def _save_to_path(
def save_to_path(
self,
ckpt_path: Path,
progress: Progress,
@@ -47,7 +47,7 @@ class CheckpointManager:
self.logger.debug(f"Orchestrator checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
def _load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
def load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
"""Loads a checkpoint from a given path in-place."""
self.logger.debug(f"Loading checkpoint from {ckpt_path}")
start_time = time.perf_counter()
@@ -76,7 +76,7 @@ class CheckpointManager:
ckpt_path = self.get_ckpt_path(step)
if not ckpt_path.exists():
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
self._load_from_path(ckpt_path, progress, buffer)
self.load_from_path(ckpt_path, progress, buffer)
def save(
self,
@@ -87,7 +87,7 @@ class CheckpointManager:
"""Saves the full checkpoint state for a specified step."""
ckpt_path = self.get_ckpt_path(step)
ckpt_path.mkdir(parents=True, exist_ok=True)
self._save_to_path(ckpt_path, progress, buffer)
self.save_to_path(ckpt_path, progress, buffer)
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager | None:
@@ -1,6 +1,8 @@
import asyncio
from verifiers.workers import ZMQEnvServer
from prime_rl.orchestrator.env_server.config import EnvServerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import get_log_dir
from prime_rl.utils.pydantic_config import parse_argv
@@ -19,15 +21,18 @@ def run_server(config: EnvServerConfig):
env_name = config.env.name or config.env.id
log_file = (get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix()
ZMQEnvServer.run_server(
server = ZMQEnvServer(
env_id=strip_env_version(config.env.id),
env_args=config.env.args,
extra_env_kwargs=config.env.extra_env_kwargs,
log_level=config.log.level,
log_file_level=config.log.vf_level,
log_file=log_file,
json_logging=config.log.json_logging,
**{"address": config.env.address} if config.env.address is not None else {},
)
asyncio.run(server.run())
def main():
+42 -17
View File
@@ -6,13 +6,39 @@ import numpy as np
import pandas as pd
import verifiers as vf
from prime_rl.orchestrator.config import EvalSamplingConfig
from prime_rl.configs.orchestrator import EvalSamplingConfig
from prime_rl.orchestrator.vf_utils import evaluate, get_completion_len
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor import get_monitor
from prime_rl.utils.utils import capitalize
def compute_eval_ckpt_step(
ckpt_step: int,
prev_ckpt_step: int,
last_eval_step: int,
interval: int,
eval_base_model: bool = True,
) -> int | None:
"""Determine which checkpoint step (if any) should trigger an eval.
Handles the case where ckpt_step jumps over interval boundaries by finding
the highest interval-aligned step in (prev_ckpt_step, ckpt_step].
Returns the interval step to eval at, or None if no eval should run.
"""
if ckpt_step <= prev_ckpt_step:
return None
highest_interval_step = (ckpt_step // interval) * interval
if highest_interval_step > prev_ckpt_step and highest_interval_step > last_eval_step:
if highest_interval_step == 0:
if ckpt_step == 0 and eval_base_model:
return 0
else:
return highest_interval_step
return None
def get_eval_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any]:
"""Get sampling args for evaluation."""
# Initialize sampling args
@@ -45,22 +71,21 @@ def get_eval_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any
return sampling_args
def compute_pass_at_k(rewards: list[int]) -> dict[str, float]:
total_attempts = len(rewards)
k = total_attempts // 2
def _pass_at_k(n: int, c: int, k: int) -> float:
"""Unbiased estimator of pass@k (Chen et al., 2021).
if k == 0:
return {"pass@1": float(any(reward == 1.0 for reward in rewards))}
Computes 1 - C(n-c, k) / C(n, k) in a numerically stable way.
"""
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
num_trials = 100
pass_rates = []
for _ in range(num_trials):
sampled_rewards = np.random.choice(rewards, size=k, replace=False)
pass_rate = float(any(reward == 1.0 for reward in sampled_rewards))
pass_rates.append(pass_rate)
return {f"pass@{k}": float(np.mean(pass_rates))}
def compute_pass_at_k(rewards: list[float]) -> dict[str, float]:
n = len(rewards)
c = sum(r == 1.0 for r in rewards)
ks = [2**i for i in range(n.bit_length())]
return {f"pass@{k}": _pass_at_k(n, c, k) for k in ks}
async def evaluate_env(
@@ -72,7 +97,7 @@ async def evaluate_env(
rollouts_per_example: int,
max_retries: int,
ckpt_step: int,
step: int | None,
step: int,
get_client: Callable[[], Awaitable[vf.ClientConfig]],
):
logger = get_logger()
@@ -143,6 +168,6 @@ async def evaluate_env(
assert pass_at_k is not None
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
eval_metrics = {**{f"eval/{env_name}/{k}": v for k, v in eval_metrics.items()}}
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step or ckpt_step})
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step})
monitor = get_monitor()
monitor.log(eval_metrics, step=None)
monitor.log(eval_metrics, step=step)
+181
View File
@@ -0,0 +1,181 @@
"""Orchestrator-side rollout filters for detecting degenerate generations.
Filters run after rollouts complete, inspecting token IDs and logprobs to
detect gibberish or repetition. Detection metrics are always tracked.
When enforce=True, detected rollouts get their completion mask cleared so
they don't contribute to training. Reward is kept as-is for baseline
calculation.
"""
import math
from dataclasses import dataclass
from typing import Protocol
import verifiers as vf
from prime_rl.configs.orchestrator import FilterConfig
from prime_rl.utils.logger import get_logger
@dataclass
class FilterResult:
detected: bool
detection_index: int | None = None
class RolloutFilter(Protocol):
name: str
enforce: bool
def check(self, rollout: vf.RolloutOutput) -> FilterResult: ...
@dataclass
class GibberishFilter:
"""Flags rollouts containing rare tokens generated at high entropy.
A token is flagged when both:
- id(token) > token_id_threshold (rare BPE token)
- logprob(token) < -log(vocab_size) - logprob_offset (high entropy)
References:
Section 5.2, https://arxiv.org/abs/2510.02387
"""
name: str
token_id_threshold: int
logprob_threshold: float
enforce: bool = False
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
global_idx = 0
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
for token_id, logprob in zip(tokens["completion_ids"], tokens["completion_logprobs"]):
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
return FilterResult(detected=True, detection_index=global_idx)
global_idx += 1
return FilterResult(detected=False)
@dataclass
class RepetitionFilter:
"""Flags rollouts with pathological repetition loops.
Counts consecutive tokens where logprob > log(prob_threshold), indicating
the model is generating with very high confidence. When the streak reaches
the window size, the rollout is flagged.
References:
Section 3.2, https://arxiv.org/abs/2506.13585
"""
name: str
window: int
logprob_threshold: float
enforce: bool = False
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
consecutive = 0
global_idx = 0
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
for logprob in tokens["completion_logprobs"]:
if logprob > self.logprob_threshold:
consecutive += 1
else:
consecutive = 0
if consecutive >= self.window:
return FilterResult(detected=True, detection_index=global_idx)
global_idx += 1
return FilterResult(detected=False)
def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
"""Create a RolloutFilter from a filter config."""
if config.type == "gibberish":
return GibberishFilter(
name="gibberish",
token_id_threshold=config.token_id_threshold,
logprob_threshold=-math.log(vocab_size) - config.logprob_offset,
enforce=config.enforce,
)
elif config.type == "repetition":
return RepetitionFilter(
name="repetition",
window=config.window,
logprob_threshold=math.log(config.prob_threshold),
enforce=config.enforce,
)
raise ValueError(f"Unknown filter type: {config.type}")
def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutFilter]:
"""Create RolloutFilters from a list of filter configs."""
return [setup_filter(config, vocab_size) for config in configs]
def apply_filters(
filters: list[RolloutFilter],
rollouts: list[vf.RolloutOutput],
) -> dict[str, float]:
"""Apply filters to rollouts. Detection metrics are always tracked.
When a filter has enforce=True, detected rollouts get their completion
mask cleared and stop_condition set. Reward is kept as-is for baseline
calculation.
First matching filter wins per rollout (no double-counting).
Returns aggregate metrics dict for logging.
"""
if not filters:
return {}
counts: dict[str, int] = {f.name: 0 for f in filters}
total_detected = 0
total_enforced = 0
for rollout in rollouts:
if rollout.get("metrics") is None:
rollout["metrics"] = {}
for filt in filters:
rollout["metrics"].setdefault(f"filter/{filt.name}", 0.0)
for filt in filters:
result = filt.check(rollout)
if result.detected:
counts[filt.name] += 1
total_detected += 1
rollout["metrics"][f"filter/{filt.name}"] = 1.0
if filt.enforce:
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is not None:
tokens["completion_mask"] = [0] * len(tokens["completion_mask"])
rollout["stop_condition"] = filt.name
total_enforced += 1
break
n = len(rollouts)
metrics: dict[str, float] = {}
for f in filters:
metrics[f"filter/{f.name}_count"] = float(counts[f.name])
metrics[f"filter/{f.name}_rate"] = counts[f.name] / n if n > 0 else 0.0
metrics["filter/total_detected_rate"] = total_detected / n if n > 0 else 0.0
metrics["filter/total_enforced_rate"] = total_enforced / n if n > 0 else 0.0
if total_detected > 0:
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
get_logger().info(
f"Detected {total_detected}/{n} rollouts "
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
)
return metrics
+149 -92
View File
@@ -1,4 +1,5 @@
import asyncio
import multiprocessing as mp
import random
import time
from concurrent.futures import ThreadPoolExecutor
@@ -6,7 +7,7 @@ from concurrent.futures import ThreadPoolExecutor
import tomli_w
from prime_rl.orchestrator.advantage import compute_advantages
from prime_rl.orchestrator.eval_utils import get_eval_sampling_args
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step, get_eval_sampling_args
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
from prime_rl.orchestrator.trajectories import build_vlm_image_cache, interleave_rollout
@@ -26,10 +27,11 @@ import pandas as pd
import verifiers as vf
from transformers import AutoProcessor, AutoTokenizer
from prime_rl.configs.orchestrator import BufferConfig, OrchestratorConfig
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
from prime_rl.orchestrator.config import BufferConfig, OrchestratorConfig
from prime_rl.orchestrator.eval_utils import evaluate_env
from prime_rl.orchestrator.filters import apply_filters, setup_filters
from prime_rl.orchestrator.scheduler import Scheduler
from prime_rl.orchestrator.utils import (
compute_teacher_logprobs,
@@ -41,15 +43,14 @@ from prime_rl.orchestrator.utils import (
from prime_rl.orchestrator.vf_utils import (
generate,
get_completion_len,
get_prompt_len,
get_seq_len,
intercept_vf_logging,
setup_env_client,
spawn_env_server,
wait_for_env_servers,
)
from prime_rl.utils.client import (
init_nccl_broadcast,
reload_weights,
setup_inference_pool,
)
from prime_rl.utils.heartbeat import Heartbeat
@@ -59,7 +60,6 @@ from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.temp_scheduling import compute_temperature
from prime_rl.utils.utils import (
clean_exit,
count_chinese_chars,
get_env_ids_to_install,
install_env,
resolve_latest_ckpt_step,
@@ -77,7 +77,7 @@ async def orchestrate(config: OrchestratorConfig):
log_file=config.output_dir / "logs" / "orchestrator.log" if config.log.file else None,
json_logging=config.log.json_logging,
)
vf.setup_logging(level="CRITICAL")
intercept_vf_logging(logger="verifiers.workers", level=config.log.vf_level) # show logs from env clients
logger.info("Starting orchestrator")
event_loop_lag_monitor = EventLoopLagMonitor()
@@ -103,7 +103,13 @@ async def orchestrate(config: OrchestratorConfig):
install_env(env_id)
# Setup inference pool (handles both static and elastic modes)
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name)
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
if config.use_token_client:
logger.warning(
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
"history and the chat template has the extension property."
)
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name, client_type=client_type)
# Setup teacher inference pool if configured
if config.teacher_model:
@@ -131,6 +137,11 @@ async def orchestrate(config: OrchestratorConfig):
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
)
# Build rollout filters
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
if rollout_filters:
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
# Setup monitor
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
monitor = setup_monitor(
@@ -152,28 +163,34 @@ async def orchestrate(config: OrchestratorConfig):
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
)
env_ids = [strip_env_version(env.id) for env in config.env]
train_env_names = [env.name or env_id for env_id, env in zip(env_ids, config.env)]
train_env_group = vf.EnvGroup(
envs=[vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.env)],
env_names=[env.name or env_id for env_id, env in zip(env_ids, config.env)],
env_names=train_env_names,
map_kwargs=dict(writer_batch_size=1), # set defensively to not error on map operations on large datasets
)
train_env_addresses = []
for env_id, env, env_name in zip(env_ids, config.env, train_env_group.env_names):
env_processes: list[mp.Process] = []
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
if env.address is None:
address = spawn_env_server(
address, process = spawn_env_server(
env_id=env_id,
env_args=env.args,
extra_env_kwargs=env.extra_env_kwargs,
log_level="CRITICAL",
log_file=(get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix(),
log_file_level=config.log.vf_level,
json_logging=config.log.json_logging,
)
env_processes.append(process)
else:
address = env.address
logger.info(f"Connecting train environment {env_name} to server at {address}")
train_env_addresses.append(address)
train_env_clients = [setup_env_client(address) for address in train_env_addresses]
train_env_clients = [
setup_env_client(address=address, name=name) for name, address in zip(train_env_names, train_env_addresses)
]
logger.info("Waiting for train environment servers to be ready")
await wait_for_env_servers(train_env_clients)
@@ -193,20 +210,24 @@ async def orchestrate(config: OrchestratorConfig):
for env_id, env, eval_env_name in zip(env_ids, config.eval.env, eval_env_names):
if env.address is None:
address = spawn_env_server(
address, process = spawn_env_server(
env_id=env_id,
env_args=env.args,
extra_env_kwargs=env.extra_env_kwargs,
log_level="CRITICAL",
log_file=(get_log_dir(config.output_dir) / "eval" / f"{eval_env_name}.log").as_posix(),
log_file_level=config.log.vf_level,
json_logging=config.log.json_logging,
)
env_processes.append(process)
else:
address = env.address
logger.info(f"Connecting eval environment {eval_env_name} to server at {address}")
eval_env_addresses.append(address)
eval_env_clients = [setup_env_client(address) for address in eval_env_addresses]
eval_env_clients = [
setup_env_client(address=address, name=name) for name, address in zip(eval_env_names, eval_env_addresses)
]
logger.info("Waiting for eval environment servers to be ready")
await wait_for_env_servers(eval_env_clients)
@@ -247,7 +268,7 @@ async def orchestrate(config: OrchestratorConfig):
env=train_env_group,
buffer=buffer,
inference_pool=inference_pool,
oversampling_factor=config.oversampling_factor,
max_inflight_rollouts=config.max_inflight_rollouts,
max_async_level=config.max_async_level,
max_off_policy_steps=config.max_off_policy_steps,
strict_async_level=config.strict_async_level,
@@ -288,6 +309,8 @@ async def orchestrate(config: OrchestratorConfig):
# Track last online eval checkpoint step for this process
last_eval_step = -1
# Track previous ckpt_step to detect when ckpt_step jumps over eval interval boundaries
prev_ckpt_step = -1
# Reset weights to base model if starting from scratch
progress = Progress()
@@ -297,8 +320,12 @@ async def orchestrate(config: OrchestratorConfig):
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
scheduler.ckpt_step = progress.step # Always resume from the latest checkpoint
if config.eval and config.eval.skip_eval_on_resume:
prev_ckpt_step = scheduler.ckpt_step
last_eval_step = scheduler.ckpt_step
logger.info(f"Skipping online eval on resume (ckpt_step={scheduler.ckpt_step})")
else:
# Allow eval at resumed step by setting prev_ckpt_step one behind
prev_ckpt_step = scheduler.ckpt_step - 1
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
check_exists = config.weight_broadcast.type != "nccl"
@@ -309,14 +336,7 @@ async def orchestrate(config: OrchestratorConfig):
lora_name = config.model.lora.name if config.model.lora else None
await inference_pool.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
else:
if config.reload_weights_on_start:
if config.model.lora is None:
logger.info("Training from scratch. Resetting weights to base model")
await reload_weights(inference_pool.admin_clients)
else:
logger.info("Training from scratch. Skipping base weight reload because LoRA is enabled")
else:
logger.info("Training from scratch. Skipping base weight reload")
logger.info("Training from scratch")
# Iterate over dataset in batches
max_steps = config.max_steps or int(1e9)
@@ -324,9 +344,6 @@ async def orchestrate(config: OrchestratorConfig):
is_first_step = True
await set_semaphore(config.max_concurrent or -1)
# Start update policy loop
update_policy_task = asyncio.create_task(scheduler.update_policy_loop())
# Track consecutive empty batches for retry logic
empty_batch_retries = 0
max_empty_batch_retries = 5
@@ -341,13 +358,7 @@ async def orchestrate(config: OrchestratorConfig):
reason = evicted_path.read_text().strip()
raise RuntimeError(f"Run evicted by trainer: {reason}")
# Check if update_policy_task has failed and propagate the exception
if update_policy_task.done():
# End all other tasks
for task in asyncio.all_tasks():
task.cancel()
update_policy_task.result() # Raises if the task failed
# Capture ckpt_step once for consistency (it's updated by update_policy_loop concurrently)
# Capture ckpt_step once for consistency (it's updated inside the scheduler)
ckpt_step = scheduler.ckpt_step
# Save checkpoint (if we are at an interval step and not at the first or last step)
@@ -371,21 +382,35 @@ async def orchestrate(config: OrchestratorConfig):
logger.info(f"Starting orchestrator step {progress.step}")
step_start_time = time.perf_counter()
# Run evals BEFORE training (blocking, in subprocess to isolate event loop)
# This ensures weights don't change during eval and eval doesn't cause event loop lag
if (
config.eval
and ckpt_step % config.eval.interval == 0
and ckpt_step > last_eval_step
and ((ckpt_step == 0 and config.eval.eval_base_model) or ckpt_step > 0)
):
last_eval_step = ckpt_step
logger.info(f"Running evals for checkpoint step {ckpt_step}")
# Run evals BEFORE training (blocking). Weight updates are paused via
# scheduler.checkpoint_ready during eval to ensure consistent weights.
# Use range check to handle ckpt_step jumping over interval boundaries.
eval_ckpt_step = None
if config.eval:
eval_ckpt_step = compute_eval_ckpt_step(
ckpt_step=ckpt_step,
prev_ckpt_step=prev_ckpt_step,
last_eval_step=last_eval_step,
interval=config.eval.interval,
eval_base_model=config.eval.eval_base_model,
)
# Pause weight updates during eval and cancel inflight rollouts
# this avoid doing eval across different checkpoints and avoid congestion
if eval_ckpt_step is not None:
last_eval_step = ckpt_step
if eval_ckpt_step != ckpt_step:
logger.info(f"Running evals for interval step {eval_ckpt_step} (current ckpt_step={ckpt_step})")
else:
logger.info(f"Running evals for checkpoint step {ckpt_step}")
# Pause weight updates and re-scheduling of training rollouts during eval
# to avoid evaluating across different checkpoints and avoid congestion
scheduler.checkpoint_ready.clear()
scheduler.cancel_all_inflight_rollouts()
# For heavy eval workloads, it might be necessary additionally cancel in-flight training rollouts
if config.eval.cancel_inflight_rollouts_on_eval:
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
await scheduler.cancel_inflight_rollouts()
results = await asyncio.gather(
*[
evaluate_env(
@@ -407,6 +432,9 @@ async def orchestrate(config: OrchestratorConfig):
# Resume weight updates
scheduler.checkpoint_ready.set()
# Update prev_ckpt_step for next iteration
prev_ckpt_step = ckpt_step
# Schedule generating the training batch
temperature = compute_temperature(progress.step, config.sampling, config.max_steps)
sampling_args = get_sampling_args(config.sampling, temperature=temperature)
@@ -436,8 +464,13 @@ async def orchestrate(config: OrchestratorConfig):
generate_completions_time = scheduler.last_batch_generation_time
train_rollouts = train_task.result()
# Apply rollout filters (zeros reward/mask for degenerate generations)
filter_metrics = apply_filters(rollout_filters, train_rollouts)
# Compute advantages
example_ids = [r["example_id"] for r in train_rollouts]
num_rollouts = len(train_rollouts)
num_unique_examples = len(set(example_ids))
rewards = [r["reward"] for r in train_rollouts]
completion_lens = [get_completion_len(r) for r in train_rollouts]
advantages = compute_advantages(
@@ -449,7 +482,6 @@ async def orchestrate(config: OrchestratorConfig):
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
num_unique_examples = len(set(example_ids))
# VLM: build image cache for efficient batched preprocessing
if is_vlm:
@@ -473,12 +505,30 @@ async def orchestrate(config: OrchestratorConfig):
# Collect results and assign advantages
train_examples: list[TrainingSample] = []
rollout_prefill_lens: list[int] = []
rollout_decode_lens: list[int] = []
rollout_samples_per_rollout: list[int] = []
num_prefill_tokens = 0
num_decode_tokens = 0
for rollout, advantage, samples in zip(train_rollouts, advantages, results):
rollout_prefill_tokens = 0
rollout_decode_tokens = 0
if samples is not None:
rollout_samples_per_rollout.append(len(samples))
for sample in samples:
sample.advantage = advantage
sample.reward = rollout["reward"]
train_examples.extend(samples)
sample_decode_tokens = sum(sample.completion_mask)
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
rollout_decode_tokens += sample_decode_tokens
rollout_prefill_tokens += sample_prefill_tokens
train_examples.append(sample)
else:
rollout_samples_per_rollout.append(0)
rollout_prefill_lens.append(rollout_prefill_tokens)
rollout_decode_lens.append(rollout_decode_tokens)
num_prefill_tokens += rollout_prefill_tokens
num_decode_tokens += rollout_decode_tokens
parallel_preprocess_time = time.perf_counter() - parallel_preprocess_start
logger.debug(
@@ -539,9 +589,10 @@ async def orchestrate(config: OrchestratorConfig):
"reward": [rollout["reward"] for rollout in train_rollouts],
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
"error": [rollout["error"] for rollout in train_rollouts],
"completion_len": [get_completion_len(rollout) for rollout in train_rollouts],
"prompt_len": [get_prompt_len(rollout) for rollout in train_rollouts],
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
"prefill_len": rollout_prefill_lens,
"decode_len": rollout_decode_lens,
"samples_per_rollout": rollout_samples_per_rollout,
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
@@ -551,21 +602,6 @@ async def orchestrate(config: OrchestratorConfig):
# Gather individual reward function metrics
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
# Count Chinese characters in completions
chinese_stats = []
for rollout in train_rollouts:
trajectory = rollout["trajectory"]
if not trajectory:
continue
last_step = trajectory[-1]
tokens = last_step["tokens"]
completion_text = tokenizer.decode(tokens["completion_ids"])
chinese_count, total_count = count_chinese_chars(completion_text)
chinese_stats.append(
{"chinese_chars": chinese_count, "total_chars": total_count, "has_chinese": chinese_count > 0}
)
chinese_df = pd.DataFrame(chinese_stats)
val_results_df = (
pd.DataFrame(
{
@@ -581,25 +617,25 @@ async def orchestrate(config: OrchestratorConfig):
# Update progress metrics and throughput
num_tokens = int(results_df.seq_len.sum())
progress.total_tokens += num_tokens
progress.total_samples += config.batch_size
progress.total_problems += config.batch_size // config.rollouts_per_example
progress.total_samples += num_rollouts
progress.total_problems += num_unique_examples
throughput = num_tokens / generate_completions_time
# Compute solve all and none tensors
solve_all = (
results_df.groupby("example_id")
.apply(lambda x: x.reward.sum() == config.rollouts_per_example, include_groups=False)
.mean()
)
solve_none = results_df.groupby("example_id").apply(lambda x: x.reward.sum() == 0, include_groups=False).mean()
problem_indices = results_df.index // config.rollouts_per_example
reward_sum_per_problem = results_df.groupby(problem_indices).reward.sum()
solve_all = (reward_sum_per_problem == config.rollouts_per_example).mean()
solve_none = (reward_sum_per_problem == 0).mean()
effective_batch_size = 1 - solve_none - solve_all
step_time = time.perf_counter() - step_start_time
to_log = {
# Progress metrics
"progress/tokens": num_tokens,
"progress/samples": config.batch_size,
"progress/problems": config.batch_size // config.rollouts_per_example,
"progress/prefill_tokens": num_prefill_tokens,
"progress/decode_tokens": num_decode_tokens,
"progress/samples": num_rollouts,
"progress/problems": num_unique_examples,
"progress/total_tokens": progress.total_tokens,
"progress/total_samples": progress.total_samples,
"progress/total_problems": progress.total_problems,
@@ -608,15 +644,19 @@ async def orchestrate(config: OrchestratorConfig):
"seq_len/mean": results_df.groupby("example_id").seq_len.mean().mean(),
"seq_len/max": results_df.groupby("example_id").seq_len.mean().max(),
"seq_len/min": results_df.groupby("example_id").seq_len.mean().min(),
"prompt_len/mean": results_df.groupby("example_id").prompt_len.mean().mean(),
"prompt_len/max": results_df.groupby("example_id").prompt_len.mean().max(),
"prompt_len/min": results_df.groupby("example_id").prompt_len.mean().min(),
"completion_len/mean": results_df.groupby("example_id").completion_len.mean().mean(),
"completion_len/max": results_df.groupby("example_id").completion_len.mean().max(),
"completion_len/min": results_df.groupby("example_id").completion_len.mean().min(),
"prefill_len/mean": results_df.groupby("example_id").prefill_len.mean().mean(),
"prefill_len/max": results_df.groupby("example_id").prefill_len.mean().max(),
"prefill_len/min": results_df.groupby("example_id").prefill_len.mean().min(),
"decode_len/mean": results_df.groupby("example_id").decode_len.mean().mean(),
"decode_len/max": results_df.groupby("example_id").decode_len.mean().max(),
"decode_len/min": results_df.groupby("example_id").decode_len.mean().min(),
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
# Seqs per rollout metrics
"samples_per_rollout/mean": results_df.groupby("example_id").samples_per_rollout.mean().mean(),
"samples_per_rollout/max": results_df.groupby("example_id").samples_per_rollout.mean().max(),
"samples_per_rollout/min": results_df.groupby("example_id").samples_per_rollout.mean().min(),
# Turn metrics
"num_turns/mean": results_df.groupby("example_id").num_turns.mean().mean(),
"num_turns/max": results_df.groupby("example_id").num_turns.mean().max(),
@@ -632,6 +672,10 @@ async def orchestrate(config: OrchestratorConfig):
"perf/throughput": throughput,
# Train reward
"reward/mean": results_df.reward.mean(),
"reward/std": results_df.reward.std(),
"reward/min": results_df.reward.min(),
"reward/max": results_df.reward.max(),
"reward/median": results_df.reward.median(),
"sampling/temperature": temperature,
# Batch metrics
"batch/solve_none": solve_none,
@@ -648,14 +692,6 @@ async def orchestrate(config: OrchestratorConfig):
},
# Env metrics
**{f"metrics/{metric}": metrics_df[metric].mean() for metric in metrics_df.columns},
# Chinese character metrics (cast to native Python types for JSON serialization)
"chinese/char_count": int(chinese_df.chinese_chars.sum()),
"chinese/char_ratio": (
float(chinese_df.chinese_chars.sum() / chinese_df.total_chars.sum())
if chinese_df.total_chars.sum() > 0
else 0.0
),
"chinese/rollout_ratio": float(chinese_df.has_chinese.mean()),
# Time metrics
"time/step": step_time,
"time/generate_completions": generate_completions_time,
@@ -668,6 +704,8 @@ async def orchestrate(config: OrchestratorConfig):
**buffer.get_metrics(),
# Event loop lag metrics
**event_loop_lag_monitor.get_metrics(),
# Rollout filter metrics
**filter_metrics,
# W&B axis
"step": progress.step,
}
@@ -682,7 +720,15 @@ async def orchestrate(config: OrchestratorConfig):
# Optionally, add val metrics
if val_results_df is not None:
to_log.update({"val_reward/mean": val_results_df.reward.mean()})
to_log.update(
{
"val_reward/mean": val_results_df.reward.mean(),
"val_reward/std": val_results_df.reward.std(),
"val_reward/min": val_results_df.reward.min(),
"val_reward/max": val_results_df.reward.max(),
"val_reward/median": val_results_df.reward.median(),
}
)
if val_results_df.task.nunique() > 1:
per_env_reward = val_results_df.groupby("task").reward.mean().to_dict()
@@ -692,7 +738,7 @@ async def orchestrate(config: OrchestratorConfig):
to_log.update({f"val_batch/{env}": ratio for env, ratio in per_env_ratio.items()})
# Log metrics to monitor(s)
monitor.log(to_log)
monitor.log(to_log, step=progress.step)
# Log samples to monitor(s) if enabled
subset_train_rollouts = random.sample(train_rollouts, min(8, len(train_rollouts)))
@@ -707,6 +753,9 @@ async def orchestrate(config: OrchestratorConfig):
step=progress.step,
)
# Flush all accumulated metrics for this step
monitor.flush(step=progress.step)
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {results_df.reward.mean():.4f} |{f' Val. Reward: {val_results_df.reward.mean():.4f} |' if val_results_df is not None else ''} Throughput: {throughput:.1f} tokens/s | Seq. Length: {results_df.groupby('example_id').seq_len.mean().mean():.1f} tokens/sample | Async Level: {scheduler.async_level} | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
logger.success(step_message)
@@ -732,6 +781,7 @@ async def orchestrate(config: OrchestratorConfig):
sampling_args=eval_sampling_args,
num_examples=eval_env_config.num_examples or config.eval.num_examples,
rollouts_per_example=eval_env_config.rollouts_per_example or config.eval.rollouts_per_example,
max_retries=eval_env_config.max_retries,
ckpt_step=ckpt_step,
step=progress.step,
)
@@ -755,8 +805,7 @@ async def orchestrate(config: OrchestratorConfig):
rollout_executor.shutdown(wait=False)
# Stop scheduler
scheduler.cancel_all_inflight_rollouts()
update_policy_task.cancel()
await scheduler.stop()
# Stop inference pool
await inference_pool.stop()
@@ -767,6 +816,14 @@ async def orchestrate(config: OrchestratorConfig):
# Cancel event loop lag monitor task
event_loop_lag_monitor_task.cancel()
# Shutdown env processes
for process in env_processes:
process.terminate()
process.join(timeout=5)
if process.is_alive():
process.kill()
process.join(timeout=5)
logger.success("Orchestrator finished.")
# Optionally, print benchmark table
+75 -48
View File
@@ -9,10 +9,11 @@ from typing import NamedTuple
import verifiers as vf
from aiolimiter import AsyncLimiter
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.config import OrchestratorConfig
from prime_rl.orchestrator.utils import get_sampling_args
from prime_rl.orchestrator.vf_utils import run_group
from prime_rl.orchestrator.vf_utils import get_seq_len, run_group
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import ProgressTracker, get_logger
from prime_rl.utils.temp_scheduling import compute_temperature
@@ -48,7 +49,7 @@ class Scheduler:
inference_pool: InferencePool,
buffer: Buffer,
config: OrchestratorConfig,
oversampling_factor: float,
max_inflight_rollouts: int,
max_async_level: int,
max_off_policy_steps: int,
strict_async_level: bool,
@@ -65,9 +66,11 @@ class Scheduler:
self.buffer = buffer
self.config = config
self.batch_size = config.batch_size
self.token_batch_size = config.token_batch_size
self.rollouts_per_example = config.rollouts_per_example
self.seq_len = config.seq_len
self.problems_per_batch = int(oversampling_factor * self.batch_size // self.rollouts_per_example)
self.max_inflight_rollouts = max_inflight_rollouts
self.max_inflight_group_rollouts = max(1, self.max_inflight_rollouts // self.rollouts_per_example)
self.max_async_level = max_async_level
self.max_off_policy_steps = max_off_policy_steps
self.strict_async_level = strict_async_level
@@ -91,19 +94,37 @@ class Scheduler:
self.cancelled_rollouts_count = 0
self.last_batch_generation_time = 0.0
@property
def uses_token_batching(self) -> bool:
return self.token_batch_size is not None
@property
def batch_target(self) -> int:
if self.uses_token_batching:
assert self.token_batch_size is not None
return self.token_batch_size
assert self.batch_size is not None
return self.batch_size
def get_batch_progress_increment(self, rollouts: list[vf.RolloutOutput]) -> int:
if self.uses_token_batching:
return sum(get_seq_len(rollout) for rollout in rollouts)
return len(rollouts)
def finalize_batch_rollouts(self, rollouts: list[vf.RolloutOutput]) -> list[vf.RolloutOutput]:
if self.batch_size is None:
return rollouts
return rollouts[: self.batch_size]
def set_sampling_args(self, sampling_args: dict) -> None:
"""Update sampling args for future rollout requests."""
self.sampling_args = sampling_args
def cancel_all_inflight_rollouts(self):
"""Cancel all in-flight rollout requests.
Used when weights are updated to discard stale rollouts generated with old weights.
"""
async def cancel_inflight_rollouts(self):
"""Cancel all in-flight rollout requests."""
count = len(self.inflight_group_rollouts)
for future in list(self.inflight_group_rollouts.keys()):
if not future.done():
future.cancel()
await safe_cancel(future)
self.inflight_group_rollouts.clear()
self.cancelled_rollouts_count += count
@@ -138,10 +159,10 @@ class Scheduler:
async def update_policy_loop(self):
"""Continuously checks for new policy checkpoints."""
while True:
await self.update_policy()
await self.maybe_update_policy()
await asyncio.sleep(1)
async def update_policy(self):
async def maybe_update_policy(self):
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
latest_ckpt_step = get_latest_ckpt_step(get_broadcast_dir(self.config.output_dir)) or 0
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
@@ -180,33 +201,22 @@ class Scheduler:
self.checkpoint_ready.set()
# Handle off-policy tracking - cancel old requests
tasks_to_remove = []
tasks_to_update = []
for task, info in self.inflight_group_rollouts.items():
if info.off_policy_steps > self.max_off_policy_steps:
if not task.done():
task.cancel()
tasks_to_remove.append((task, info.client_config))
# Cancel stale rollouts and bump off-policy step for the rest
cancelled = []
updated = {}
for task, info in list(self.inflight_group_rollouts.items()):
new_off_policy_steps = info.off_policy_steps + 1
if new_off_policy_steps > self.max_off_policy_steps:
cancelled.append(task)
else:
tasks_to_update.append((task, info.off_policy_steps + 1, info.client_config))
updated[task] = InflightRolloutInfo(new_off_policy_steps, info.client_config)
self.inflight_group_rollouts = updated
await safe_cancel_all(cancelled)
self.cancelled_rollouts_count += len(cancelled)
# Remove cancelled
for task, _ in tasks_to_remove:
self.inflight_group_rollouts.pop(task, None)
self.cancelled_rollouts_count += len(tasks_to_remove)
# Update off-policy steps for remaining
for task, off_policy_steps, client_config in tasks_to_update:
if task in self.inflight_group_rollouts:
self.inflight_group_rollouts[task] = InflightRolloutInfo(
off_policy_steps=off_policy_steps, client_config=client_config
)
if len(tasks_to_remove) > 0:
if len(cancelled) > 0:
self.logger.warning(
f"Cancelled {len(tasks_to_remove)} old rollout requests (will refill naturally). Consider increasing max_off_policy_steps to avoid this."
f"Cancelled {len(cancelled)} group rollout requests because they would be generated by >{self.max_off_policy_steps} policy versions. These requests will refill naturally. To avoid cancellation, consider increasing max_off_policy_steps."
)
self.ckpt_step = next_ckpt_step
@@ -214,19 +224,29 @@ class Scheduler:
async def generate_batch(self, step: int) -> list[vf.RolloutOutput]:
"""Continuously generates a batch of rollouts."""
self.step = step
# Cancel the previous update policy task to avoid concurrent updates
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
# Manually check the async barrier before starting the step, the re-create the update policy loop
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
await self.maybe_update_policy()
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
batch_start_time = time.perf_counter()
# Schedule initial tasks
self.logger.debug("Starting to generate batch rollouts")
while len(self.inflight_group_rollouts) < self.problems_per_batch:
await self.schedule_group_rollout()
batch_rollouts: list[vf.RolloutOutput] = []
batch_progress = 0
pbar = ProgressTracker(
total=self.config.batch_size, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
total=self.batch_target, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
)
while len(batch_rollouts) < self.config.batch_size:
while batch_progress < self.batch_target:
# Fill up
while len(self.inflight_group_rollouts) < self.max_inflight_group_rollouts:
await self.schedule_group_rollout()
# Wait for at least one future to complete
finished_tasks, _ = await asyncio.wait(
self.inflight_group_rollouts.keys(),
@@ -236,8 +256,7 @@ class Scheduler:
await self.checkpoint_ready.wait()
for finished_task in finished_tasks:
if len(batch_rollouts) >= self.config.batch_size:
batch_rollouts = batch_rollouts[: self.config.batch_size]
if batch_progress >= self.batch_target:
break
# Safely pop the future from tracking
@@ -252,19 +271,27 @@ class Scheduler:
accepted_rollouts = self.buffer.sample_rollouts(n=self.config.rollouts_per_example)
batch_rollouts.extend(accepted_rollouts)
pbar.update(len(accepted_rollouts))
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
batch_progress += progress_increment
pbar.update(progress_increment)
except asyncio.CancelledError:
pass # Request was cancelled, will be rescheduled
except Exception as e:
self.logger.warning(f"Rollout failed: {e}")
await self.schedule_group_rollout()
batch_rollouts = self.finalize_batch_rollouts(batch_rollouts)
pbar.close()
self.last_batch_generation_time = time.perf_counter() - batch_start_time
return batch_rollouts
async def stop(self) -> None:
await self.cancel_inflight_rollouts()
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
self.update_policy_task = None
@property
def max_off_policy_level(self) -> int:
if not self.inflight_group_rollouts:
+85 -52
View File
@@ -12,6 +12,27 @@ from prime_rl.utils.logger import get_logger
# primitives are immutable. pixel_values/image_grid_thw are not mutated after creation.
def _align_routed_experts(
routed_experts: list[list[list[int]]] | None,
expected_len: int,
) -> list[list[list[int]]] | None:
"""Align routed_experts length with the expected token count.
VLLM's capturer uses `num_tokens - 1` slot mappings because the final
generated token was never fed as input to a forward pass and has no
routing decision. Append zero-filled entries for the missing positions.
"""
if routed_experts is None or not routed_experts:
return routed_experts
deficit = expected_len - len(routed_experts)
if deficit <= 0:
return routed_experts
num_layers = len(routed_experts[0])
topk = len(routed_experts[0][0])
zero_entry = [[0] * topk for _ in range(num_layers)]
return routed_experts + [zero_entry for _ in range(deficit)]
def interleave_rollout(
output: vf.RolloutOutput,
vlm_cache: "VLMImageCache | None" = None,
@@ -67,6 +88,12 @@ def interleave_rollout(
completion_mask = [bool(i) for i in tokens["completion_mask"]]
completion_ids = list(tokens["completion_ids"])
pixel_values, image_grid_thw = get_images(step_idx)
routed_experts = _align_routed_experts(
tokens.get("routed_experts"),
len(tokens["prompt_ids"]) + len(tokens["completion_ids"]),
)
return TrainingSample(
prompt_ids=list(tokens["prompt_ids"]),
prompt_mask=[bool(i) for i in tokens["prompt_mask"]],
@@ -78,6 +105,7 @@ def interleave_rollout(
advantage=None,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
routed_experts=routed_experts,
)
def extend_sample(sample: TrainingSample, step: vf.TrajectoryStep, prefix_len: int, step_idx: int) -> None:
@@ -107,6 +135,18 @@ def interleave_rollout(
sample.pixel_values = pixel_values
sample.image_grid_thw = image_grid_thw
if tokens.get("routed_experts") is not None and sample.routed_experts is not None:
step_routed = tokens["routed_experts"]
# The previous step's last routing entry was zero-padded by _align_routed_experts
# (vLLM only captures num_tokens-1 routings per request). This step actually
# processed that boundary token as part of its prompt, so replace the zero-fill
# with the real routing decision before appending new entries.
if prefix_len > 0 and prefix_len <= len(step_routed):
sample.routed_experts[prefix_len - 1] = step_routed[prefix_len - 1]
sample.routed_experts.extend(step_routed[prefix_len:])
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
sample.routed_experts = _align_routed_experts(sample.routed_experts, expected_len)
# Track multiple active (prefix, sample) pairs to handle interleaved agents
# Each entry is [prefix_tokens, sample] where prefix_tokens is the accumulated token sequence
active_samples: list[list] = []
@@ -149,8 +189,8 @@ def interleave_rollout(
# =============================================================================
def _extract_images_from_messages(messages: list) -> list[Image.Image]:
"""Extract images from OpenAI-style chat messages."""
def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str]]:
"""Extract (image, b64_key) pairs from OpenAI-style chat messages."""
images = []
if not messages or not isinstance(messages, list):
return images
@@ -165,79 +205,78 @@ def _extract_images_from_messages(messages: list) -> list[Image.Image]:
b64_data = url.split(",", 1)[1]
img_bytes = base64.b64decode(b64_data)
img = Image.open(BytesIO(img_bytes))
images.append(img)
images.append((img, b64_data))
return images
def _extract_images_from_examples(
examples: list[tuple[int, vf.RolloutOutput]],
) -> tuple[list[Image.Image], dict[int, list[int]]]:
) -> tuple[list[Image.Image], dict[int, list[list[int]]]]:
"""
Extract images from all trajectory steps of each example.
Parses OpenAI-style message content looking for image_url items with base64 data URLs
(e.g., "data:image/png;base64,..."). Each trajectory step's prompt is cumulative (contains
full conversation history), so we extract only the NEW images introduced in each step.
Parses OpenAI-style message content looking for image_url items with base64 data URLs.
Images are deduplicated across the batch by their base64 content. Each step records
the indices of its images into the deduplicated all_images list.
Args:
examples: List of (cache_key, output) tuples where output contains a "trajectory"
list with steps that have "prompt" messages in OpenAI chat format.
Returns:
Tuple of (all_images, images_per_step_per_example)
- all_images: flat list of decoded PIL images, ordered by example then by step
- images_per_step_per_example: dict mapping cache_key to list of cumulative image
counts per step (e.g., [1, 2, 2] means 1 image after step 0, 2 after step 1, 2 after step 2)
Tuple of (all_images, step_image_indices_per_example)
- all_images: deduplicated flat list of decoded PIL images
- step_image_indices_per_example: dict mapping cache_key to per-step lists of
indices into all_images (e.g., [[0], [0, 1], [1]] for the decreasing-images case)
"""
all_images = []
images_per_step_per_example = {}
all_images: list[Image.Image] = []
image_registry: dict[str, int] = {} # b64_key -> index in all_images
step_image_indices_per_example: dict[int, list[list[int]]] = {}
for eid, output in examples:
trajectory = output.get("trajectory", [])
if not trajectory:
images_per_step_per_example[eid] = []
step_image_indices_per_example[eid] = []
continue
example_images = []
cumulative_counts = []
step_image_indices = []
for step in trajectory:
prompt = step.get("prompt")
# Extract all images from this step's prompt (which is cumulative)
step_images = _extract_images_from_messages(prompt)
# Only take images beyond what we already have (new images in this step)
new_images = step_images[len(example_images) :]
example_images.extend(new_images)
cumulative_counts.append(len(example_images))
step_image_pairs = _extract_images_from_messages(prompt)
indices = []
for img, key in step_image_pairs:
if key not in image_registry:
image_registry[key] = len(all_images)
all_images.append(img)
indices.append(image_registry[key])
step_image_indices.append(indices)
images_per_step_per_example[eid] = cumulative_counts
all_images.extend(example_images)
step_image_indices_per_example[eid] = step_image_indices
return all_images, images_per_step_per_example
return all_images, step_image_indices_per_example
def _preprocess_images_batched(
images: list[Image.Image],
images_per_step_per_example: dict[int, list[int]],
step_image_indices_per_example: dict[int, list[list[int]]],
processor,
) -> dict[int, list[tuple[list | None, list | None]]]:
"""
Preprocess all images in a single batched call, then distribute results per step.
Args:
images: Flat list of all PIL images
images_per_step_per_example: Dict mapping cache_key to list of cumulative image
counts per step
images: Deduplicated flat list of all PIL images
step_image_indices_per_example: Dict mapping cache_key to per-step lists of
indices into images
processor: HuggingFace processor with image_processor attribute
Returns:
Dict mapping cache_key to list of (pixel_values, image_grid_thw) per step.
Each step's entry contains cumulative images up to that step.
"""
if not images or processor is None:
return {
eid: [(None, None)] * len(counts) if counts else [(None, None)]
for eid, counts in images_per_step_per_example.items()
eid: [(None, None)] * max(len(step_indices), 1)
for eid, step_indices in step_image_indices_per_example.items()
}
image_sizes = [(img.width, img.height) for img in images]
@@ -251,33 +290,27 @@ def _preprocess_images_batched(
f"pixel_values={all_pixel_values.shape}, grid_thw={all_grid_thw.tolist()}"
)
result = {}
img_idx = 0
patch_idx = 0
# Pre-compute patch start offset for each image
patch_starts = [0]
for g in all_grid_thw:
patch_starts.append(patch_starts[-1] + int(g[0] * g[1] * g[2]))
for eid, cumulative_counts in images_per_step_per_example.items():
if not cumulative_counts or cumulative_counts[-1] == 0:
result[eid] = [(None, None)] * max(len(cumulative_counts), 1)
result = {}
for eid, step_indices_list in step_image_indices_per_example.items():
if not step_indices_list:
result[eid] = [(None, None)]
continue
total_images = cumulative_counts[-1]
example_grids = all_grid_thw[img_idx : img_idx + total_images]
num_patches = sum(int(g[0] * g[1] * g[2]) for g in example_grids)
example_pixels = all_pixel_values[patch_idx : patch_idx + num_patches]
# Build per-step cumulative entries
per_step = []
for cum_count in cumulative_counts:
if cum_count == 0:
for indices in step_indices_list:
if not indices:
per_step.append((None, None))
else:
step_grids = example_grids[:cum_count]
step_patches = sum(int(g[0] * g[1] * g[2]) for g in step_grids)
per_step.append((example_pixels[:step_patches].tolist(), step_grids.tolist()))
grids = all_grid_thw[indices]
patches = sum([all_pixel_values[patch_starts[i] : patch_starts[i + 1]].tolist() for i in indices], [])
per_step.append((patches, grids.tolist()))
result[eid] = per_step
img_idx += total_images
patch_idx += num_patches
return result
+1 -1
View File
@@ -13,7 +13,7 @@ from rich.table import Table
from verifiers.utils.async_utils import maybe_semaphore
from verifiers.utils.client_utils import setup_openai_client
from prime_rl.orchestrator.config import SamplingConfig
from prime_rl.configs.orchestrator import SamplingConfig
from prime_rl.transport import TrainingSample
from prime_rl.utils.utils import (
format_num,
+36 -41
View File
@@ -1,16 +1,16 @@
import asyncio
import logging
import multiprocessing as mp
from collections.abc import Awaitable, Callable
from itertools import cycle
from multiprocessing import Process
from typing import Any
import verifiers as vf
from verifiers.envs.environment import EnvClient
from verifiers.utils.worker_utils import get_free_port
from verifiers.utils.worker_utils import get_free_port_pair
from verifiers.workers import ZMQEnvClient, ZMQEnvServer
from prime_rl.utils.logger import InterceptHandler, ProgressTracker, get_logger
from prime_rl.utils.logger import InterceptHandler, ProgressTracker
DEFAULT_RETRIES = 0
REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
@@ -22,18 +22,22 @@ def spawn_env_server(
env_args: dict[str, Any],
extra_env_kwargs: dict[str, Any],
address: str | None = None,
# logging configs
log_level: str | None = None,
log_file: str | None = None,
log_file_level: str | None = None,
daemon: bool = True,
) -> str:
json_logging: bool = False,
) -> tuple[str, mp.Process]:
"""
Starts a ZMQEnvServer process in a subprocess.
Mirrors vf.Environment.start_server().
"""
address = address or f"tcp://127.0.0.1:{get_free_port()}"
Process(
address = address or f"tcp://127.0.0.1:{get_free_port_pair()}"
# Use spawn to avoid inheriting file descriptors (e.g. sockets) from
# the parent process, which has caused hangs when multiple env server
# subprocesses share the same fds.
process = mp.get_context("spawn").Process(
target=ZMQEnvServer.run_server,
args=(
env_id,
@@ -43,43 +47,34 @@ def spawn_env_server(
log_file,
log_file_level,
),
kwargs=dict(address=address),
daemon=daemon,
).start()
kwargs=dict(address=address, json_logging=json_logging),
daemon=False, # cannot run daemon because env server uses subprocesses
)
process.start()
return address
return address, process
def setup_env_client(address: str) -> EnvClient:
def setup_env_client(
address: str,
name: str | None = None,
# health check configs
health_check_interval: float = 5.0, # 5s (we detect an env server as unhealth after 3 * 5s = 15s of unsuccessful health checks)
startup_timeout: float = 600.0, # 10m
recovery_timeout: float = 600.0, # 10m
) -> EnvClient:
"""Sets up a ZMQEnvClient for a given address."""
return ZMQEnvClient(address=address)
return ZMQEnvClient(
address=address,
name=name,
health_check_interval=health_check_interval,
startup_timeout=startup_timeout,
recovery_timeout=recovery_timeout,
)
async def wait_for_env_servers(
env_clients: list[EnvClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
) -> None:
logger = get_logger()
async def wait_for_env_server(env_client: EnvClient) -> None:
wait_time = 0
logger.debug(f"Starting pinging environment server at {env_client.address}")
while wait_time < timeout:
try:
await env_client.health(timeout=1) # quick timeout
logger.debug(f"Environment server at {env_client.address} is ready after {wait_time} seconds")
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.warning(
f"Environment server at {env_client.address} was not reached after {wait_time} seconds (Error: {e})"
)
await asyncio.sleep(interval)
wait_time += interval
msg = f"Environment server at {env_client.address} is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
logger.error(msg)
raise TimeoutError(msg)
await asyncio.gather(*[wait_for_env_server(env_client) for env_client in env_clients])
async def wait_for_env_servers(env_clients: list[EnvClient]) -> None:
await asyncio.gather(*[env_client.wait_for_server_startup() for env_client in env_clients])
async def run_group(
@@ -246,9 +241,9 @@ def get_completion_len(output: vf.RolloutOutput) -> int:
return get_seq_len(output) - get_prompt_len(output)
def intercept_vf_logging(level: str = "DEBUG", prefix: str = "verifiers"):
"""Intercepts verifiers logging and routes through prime-rl logger with [verifiers] prefix."""
vf_logger = logging.getLogger("verifiers")
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
vf_logger = logging.getLogger(logger)
vf_logger.handlers.clear()
vf_logger.addHandler(InterceptHandler(prefix=prefix))
vf_logger.setLevel(level.upper())
-930
View File
@@ -1,930 +0,0 @@
import json
import os
import shutil
import subprocess
import sys
import time
import uuid
import warnings
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from typing import Annotated, Literal
import pynvml
import tomli_w
from pydantic import Field, model_validator
from prime_rl.inference.config import InferenceConfig
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpointConfig
from prime_rl.orchestrator.config import FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig
from prime_rl.orchestrator.config import NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig
from prime_rl.orchestrator.config import OrchestratorConfig
from prime_rl.trainer.config import CheckpointConfig as TrainerCheckpointConfig
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig
from prime_rl.trainer.rl.config import RLTrainerConfig as TrainerConfig
from prime_rl.utils.config import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
from prime_rl.utils.utils import (
get_broadcast_dir,
get_free_port,
get_log_dir,
get_rollout_dir,
)
from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_async_level,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_output_dir,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
class SharedLogConfig(BaseSettings):
"""Configures shared logging."""
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
file: Annotated[bool | None, Field(description="Whether to log to a file.")] = True
json_logging: Annotated[
bool,
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
] = False
class SharedWandbConfig(BaseSettings):
"""Configures shared W&B configs."""
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
class SharedCheckpointConfig(BaseSettings):
"""Configures shared checkpoint configs."""
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
resume_step: Annotated[
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
] = None
keep_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
class SharedModelConfig(BaseSettings):
"""Configures shared model settings."""
name: Annotated[
str,
Field(description="The name of the model to use."),
] = "Qwen/Qwen3-0.6B"
class SharedWeightBroadcastConfig(BaseSettings):
"""Configures shared weight broadcast settings."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
"filesystem"
)
class RLConfig(BaseSettings):
"""Configures an RL training run."""
### Submodule configurations
trainer: TrainerConfig
orchestrator: OrchestratorConfig
inference: Annotated[
InferenceConfig | None,
Field(
description="The inference config. If None, will not start an inference process. Only viable, if an inference server was started manually."
),
] = None
### Top-level configurations
log: Annotated[
SharedLogConfig,
Field(
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
),
] = SharedLogConfig()
clean: Annotated[
bool,
Field(
description="Whether to clean the rollouts, checkpoint, checkpoint weights and logs directories at the beginning of the run. If True, will forceably, and irreversibly, delete all directories.",
),
] = True
inference_gpu_ids: Annotated[list[int], Field(description="The GPU IDs to use for inference.")] = [0]
trainer_gpu_ids: Annotated[list[int], Field(description="The GPU IDs to use for trainer.")] = [1]
teacher_gpu_ids: Annotated[
list[int] | None,
Field(
description="The GPU IDs to use for teacher inference. If None, teacher inference server will not be started."
),
] = None
teacher_inference: Annotated[
InferenceConfig | None,
Field(
description="The teacher inference config. If None, will use the same config as inference (if available) or a default config. Only used when teacher_gpu_ids is set."
),
] = None
### Shared configurations
output_dir: Annotated[
Path,
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
] = Path("outputs") # NOTE: Must match `OUTPUT_DIR` in `tmux.sh` to see logs
ckpt: Annotated[
SharedCheckpointConfig | None,
Field(
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
),
] = None
wandb: Annotated[
SharedWandbConfig | None,
Field(
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
),
] = None
model: Annotated[
SharedModelConfig | None,
Field(
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
),
] = None
max_steps: Annotated[
int | None,
Field(
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
),
] = None
max_model_len: Annotated[
int | None,
Field(
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
),
] = None
seq_len: Annotated[
int | None,
Field(
description="The sequence length to use. If set, will configure both trainer.model.seq_len and orchestrator.seq_len to this value. If None, each can be set independently."
),
] = None
max_async_level: Annotated[
int | None,
Field(
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
),
] = None
bench: Annotated[
bool,
Field(
description="Whether to run in benchmark mode. It will automatically set the trainer and orchestrator to benchmark mode and, if present, configure the W&B project by suffixing the project with `-bench`.",
),
] = False
weight_broadcast: Annotated[
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
] = None
dump_config: Annotated[
Path | None,
Field(
description="If set, dump resolved subconfigs (trainer, orchestrator, inference) to this directory and exit without starting any processes."
),
] = None
@model_validator(mode="after")
def auto_setup_dp(self):
if self.inference and len(self.inference_gpu_ids) != self.inference.parallel.dp * self.inference.parallel.tp:
assert len(self.inference_gpu_ids) % self.inference.parallel.tp == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = len(self.inference_gpu_ids) // self.inference.parallel.tp
return self
@model_validator(mode="after")
def auto_setup_num_train_workers(self):
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
if len(self.trainer_gpu_ids) > 1:
self.orchestrator.num_train_workers = len(self.trainer_gpu_ids) // non_data_parallel_size
return self
@model_validator(mode="after")
def auto_setup_logs(self):
# Copy log level
if self.log is not None:
if self.log.level is not None:
self.trainer.log.level = self.log.level
self.orchestrator.log.level = self.log.level
if self.log.file is not None:
self.trainer.log.file = self.log.file
self.orchestrator.log.file = self.log.file
self.trainer.log.json_logging = self.log.json_logging
self.orchestrator.log.json_logging = self.log.json_logging
return self
### Setup and validate shared configs
@model_validator(mode="after")
def auto_setup_ckpt(self):
# If specified, automatically setup checkpoint configs for trainer and orchestrator
if self.ckpt is not None:
# Create checkpoint configs if not specified
if self.trainer.ckpt is None:
self.trainer.ckpt = TrainerCheckpointConfig()
if self.orchestrator.ckpt is None:
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
# If specified, use the same ckpt interval
if self.ckpt.interval is not None:
self.trainer.ckpt.interval = self.ckpt.interval
self.orchestrator.ckpt.interval = self.ckpt.interval
# If resuming training, ensure orchestrator resume from the same step
if self.ckpt.resume_step is not None:
self.trainer.ckpt.resume_step = self.ckpt.resume_step
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
# If specified, propagate keep policy
if self.ckpt.keep_last is not None:
self.trainer.ckpt.keep_last = self.ckpt.keep_last
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
if self.ckpt.keep_interval is not None:
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
validate_shared_ckpt_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_wandb(self):
# If specified, automatically use shared W&B project for orchestrator and trainer
if self.wandb is not None:
if not self.trainer.wandb:
self.trainer.wandb = WandbConfig()
if not self.orchestrator.wandb:
self.orchestrator.wandb = WandbWithExtrasConfig()
if self.wandb.project:
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
validate_shared_wandb_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
# Set trainer and orchestrator to benchmark mode
self.trainer.bench = True
self.orchestrator.bench = True
# Configure the trainer fake data to match the orchestrator config
self.trainer.data.fake = FakeDataLoaderConfig(
batch_size=self.orchestrator.batch_size,
)
trainer_bench_enabled = self.trainer.bench is not None
if trainer_bench_enabled != self.orchestrator.bench:
raise ValueError(
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode ({self.orchestrator.bench}) are not the same. Please specify the same benchmark mode for both."
)
return self
@model_validator(mode="after")
def auto_setup_model(self):
# Use the same model for trainer, orchestrator and inference
if self.model is not None:
self.trainer.model.name = self.model.name
self.orchestrator.model.name = self.model.name
if self.inference is not None:
self.inference.model.name = self.model.name
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_max_steps(self):
# If specified, use the same max steps for trainer and orchestrator
if self.max_steps is not None:
self.trainer.max_steps = self.max_steps
self.orchestrator.max_steps = self.max_steps
validate_shared_max_steps(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_async_level(self):
# If specified, use the same async level for trainer and orchestrator
if self.max_async_level is not None:
self.trainer.max_async_level = self.max_async_level
self.orchestrator.max_async_level = self.max_async_level
validate_shared_max_async_level(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_output_dir(self):
# If specified, use the same outputs directory for trainer and orchestrator
if self.output_dir is not None:
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_seq_len(self):
# If specified, use the same seq_len for trainer and orchestrator
if self.seq_len is not None:
self.trainer.model.seq_len = self.seq_len
self.orchestrator.seq_len = self.seq_len
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
return self
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type, inference_world_size=inference_world_size
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
# Ensure orchestrator has LoRA config
if self.orchestrator.model.lora is None:
from prime_rl.orchestrator.config import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
# Validate orchestrator LoRA rank/alpha don't conflict with trainer
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
# Propagate rank/alpha from trainer when not explicitly set
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
# Auto-generate name if not provided
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, make sure to set `--enable_lora` and `--max-lora-rank`."
)
return self
@model_validator(mode="after")
def warn_wandb_resume_id_missing(self):
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
if self.trainer.wandb and not self.trainer.wandb.id:
warnings.warn(
"W&B run ID is not set for trainer even though resuming training. The current run will be created as a new run."
)
if self.orchestrator.ckpt is not None and self.orchestrator.ckpt.resume_step is not None:
if self.orchestrator.wandb and not self.orchestrator.wandb.id:
warnings.warn(
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.trainer.weight_broadcast.type == "nccl":
num_gpus = len(set(self.trainer_gpu_ids + self.inference_gpu_ids))
if num_gpus < 2:
raise ValueError("NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group.")
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
if self.teacher_gpu_ids is None or len(self.teacher_gpu_ids) == 0:
return self
import copy
from prime_rl.orchestrator.config import TeacherModelConfig
# Create or complete teacher_inference config
if self.teacher_inference is None:
self.teacher_inference = copy.deepcopy(self.inference) if self.inference else InferenceConfig()
# Avoid port conflict with main inference by using next port
if self.inference is not None:
self.teacher_inference.server.port = self.inference.server.port + 1
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
raise ValueError(
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
f"inference.server.port ({self.inference.server.port}). "
"Either use different ports or let teacher_inference be auto-configured."
)
# Auto-configure DP based on GPU count
tp = self.teacher_inference.parallel.tp
if len(self.teacher_gpu_ids) != self.teacher_inference.parallel.dp * tp:
assert len(self.teacher_gpu_ids) % tp == 0, (
"Number of teacher GPUs must be divisible by tensor parallel size"
)
assert len(self.teacher_gpu_ids) > 0, "teacher_gpu_ids cannot be empty"
self.teacher_inference.parallel.dp = len(self.teacher_gpu_ids) // tp
# Auto-configure orchestrator's teacher_model client
if self.orchestrator.teacher_model is None:
self.orchestrator.teacher_model = TeacherModelConfig()
host = self.teacher_inference.server.host or "localhost"
port = self.teacher_inference.server.port
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
return self
@model_validator(mode="after")
def validate_teacher_model(self):
if self.trainer.loss.teacher_tau > 0 and not self.orchestrator.teacher_model:
raise ValueError(
"teacher_model must be configured when teacher_tau > 0. "
"Either set teacher_tau = 0, set teacher_gpu_ids, or configure teacher_model manually."
)
return self
def cleanup_threads(threads: list[Thread]):
for thread in threads:
thread.join(timeout=5)
def cleanup_processes(processes: list[Popen]):
for process in processes:
if process.poll() is None: # Process is still running
process.terminate()
try:
process.wait(timeout=60) # 60 seconds to terminate gracefully
except subprocess.TimeoutExpired:
process.kill()
def monitor_process(process: Popen, stop_event: Event, error_queue: list, process_name: str):
"""Monitor a subprocess and signal errors via shared queue"""
try:
# Wait for process to complete
process.wait()
if process.returncode != 0:
err_msg = f"{process_name.capitalize()} failed with exit code {process.returncode}"
if process.stderr:
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
error_queue.append(RuntimeError(err_msg))
stop_event.set()
except Exception as e:
error_queue.append(RuntimeError(f"Error monitoring {process_name}: {e}"))
stop_event.set()
def check_gpus_available(gpu_ids: list[int]) -> None:
"""Raise error if there are existing processes on the specified GPUs."""
pynvml.nvmlInit()
occupied = []
for gpu_id in gpu_ids:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
if processes:
pids = [p.pid for p in processes]
occupied.append((gpu_id, pids))
if occupied:
msg = "Existing processes found on GPUs:\n"
for gpu_id, pids in occupied:
msg += f" GPU {gpu_id}: PIDs {pids}\n"
msg += "Kill these processes or use different GPUs."
raise RuntimeError(msg)
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / "trainer.toml", "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
with open(output_dir / "orchestrator.toml", "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
if config.inference is not None:
with open(output_dir / "inference.toml", "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
if config.teacher_inference is not None:
with open(output_dir / "teacher_inference.toml", "wb") as f:
tomli_w.dump(config.teacher_inference.model_dump(exclude_none=True, mode="json"), f)
def rl(config: RLConfig):
# Setup logger
logger = setup_logger(
config.log.level or "info",
log_file=config.output_dir / "logs" / "rl.log" if config.log.file else None,
json_logging=config.log.json_logging,
)
# If dump_config is set, write resolved subconfigs and exit early
if config.dump_config is not None:
logger.warning(
"--dump-config is set. No RL training will be started. Only writing resolved subconfigs to disk."
)
write_subconfigs(config, config.dump_config)
logger.info(f"Dumping resolved subconfigs to {config.dump_config}")
logger.info(f" Wrote trainer config to {config.dump_config / 'trainer.toml'}")
logger.info(f" Wrote orchestrator config to {config.dump_config / 'orchestrator.toml'}")
if config.inference is not None:
logger.info(f" Wrote inference config to {config.dump_config / 'inference.toml'}")
if config.teacher_inference is not None:
logger.info(f" Wrote teacher inference config to {config.dump_config / 'teacher_inference.toml'}")
logger.success(f"Config dump complete. Files written to {config.dump_config}")
logger.warning("To start an RL run, remove --dump-config from your command.")
return
start_command = sys.argv
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Check for existing processes on GPUs
all_gpu_ids = list(set(config.inference_gpu_ids + config.trainer_gpu_ids + (config.teacher_gpu_ids or [])))
check_gpus_available(all_gpu_ids)
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Prepare paths to communicate with the trainer
log_dir = get_log_dir(config.output_dir)
orch_log_dir = get_log_dir(config.orchestrator.output_dir)
rollout_dir = get_rollout_dir(config.orchestrator.output_dir)
broadcast_dir = get_broadcast_dir(config.orchestrator.output_dir)
# Clean up directories if specified
if config.clean:
logger.info("Cleaning checkpoint, logs, weights, broadcast and rollout directories")
# Cleaning logs (so that streaming logs to terminal works)
logger.info(f"Cleaning log dir ({log_dir})")
shutil.rmtree(log_dir, ignore_errors=True)
log_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Cleaning orchestrator log dir ({orch_log_dir})")
shutil.rmtree(orch_log_dir, ignore_errors=True)
orch_log_dir.mkdir(parents=True, exist_ok=True)
# Cleaning broadcast dir (so that orchestrator does not pre-maturely update weights)
if not (
config.ckpt
and config.ckpt.resume_step
and config.trainer.weight_broadcast
and config.trainer.weight_broadcast.type == "filesystem"
):
logger.info(f"Cleaning broadcast directory ({broadcast_dir})")
shutil.rmtree(broadcast_dir, ignore_errors=True)
# Cleaning rollouts (so that trainer does not train on old rollouts)
logger.info(f"Cleaning rollout dir ({rollout_dir})")
shutil.rmtree(rollout_dir, ignore_errors=True)
# Write all resolved subconfigs to disk
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
write_subconfigs(config, config_dir)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
try:
# Optionally, start inference process
if config.inference:
inference_cmd = ["uv", "run", "inference", "@", (config_dir / "inference.toml").as_posix()]
logger.info(f"Starting inference process on GPU(s) {' '.join(map(str, config.inference_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.stdout", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(map(str, config.inference_gpu_ids))},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No inference config specified, skipping starting inference server. Is your inference server running?"
)
# Optionally, start teacher inference process
if config.teacher_inference:
if config.teacher_gpu_ids is None or len(config.teacher_gpu_ids) == 0:
raise ValueError(
"teacher_inference is configured but teacher_gpu_ids is not set or is empty. "
"Either set teacher_gpu_ids to start a teacher inference server, "
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
)
teacher_inference_cmd = ["uv", "run", "inference", "@", (config_dir / "teacher_inference.toml").as_posix()]
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, config.teacher_gpu_ids))}")
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
with open(log_dir / "teacher_inference.stdout", "w") as log_file:
teacher_inference_process = Popen(
teacher_inference_cmd,
env={**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(map(str, config.teacher_gpu_ids))},
stdout=log_file,
stderr=log_file,
)
processes.append(teacher_inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["teacher_inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
elif config.trainer.loss.teacher_tau > 0 or config.orchestrator.teacher_model:
logger.warning(
"No teacher_inference config specified, skipping starting teacher inference server. "
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
)
# Start orchestrator process
orchestrator_cmd = [
"uv",
"run",
"orchestrator",
"@",
(config_dir / "orchestrator.toml").as_posix(),
]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.stdout", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(config.trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / "trainer.toml").as_posix(),
]
logger.info(f"Starting trainer process on GPU(s) {' '.join(map(str, config.trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, config.trainer_gpu_ids)),
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", log_dir / "trainer.stdout"])
processes.append(tail_process)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# Small delay to avoid busy waiting
time.sleep(1)
# Check if any critical process failed
if orchestrator_process.returncode != 0:
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
logger.success("RL training finished!")
# Cleanup threads and processes
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def main():
rl(parse_argv(RLConfig))
if __name__ == "__main__":
main()
@@ -0,0 +1,159 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Configs
export NUM_TRAIN_NODES={{ num_train_nodes }}
export NUM_INFER_NODES={{ num_infer_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
# Enable distributed EP mode only when expert parallelism spans multiple inference nodes.
export USE_DISTRIBUTED_EP=0
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$NUM_INFER_NODES" -gt 1 ]; then
USE_DISTRIBUTED_EP=1
fi
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
mkdir -p $OUTPUT_DIR/slurm
# Clear previous rollouts and broadcast flags from ALL runs (not just the current one)
# to prevent the trainer from training on stale data from old run_* directories.
# WARN: This is potentially dangerous and could lead to data loss
rm -rf $OUTPUT_DIR/run_*/rollouts
rm -rf $OUTPUT_DIR/run_*/broadcasts
rm -rf $OUTPUT_DIR/rollouts
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
# Networking
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES} )
export INFER_HEAD_HOST="${INFER_HOSTS[0]}"
export HOSTNAMES_STR="${HOSTNAMES[*]}"
INFER_URLS=""
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
INFER_URLS="http://${INFER_HEAD_HOST}:8000/v1"
else
for host in "${INFER_HOSTS[@]}"; do
if [ -z "$INFER_URLS" ]; then
INFER_URLS="http://$host:8000/v1"
else
INFER_URLS="$INFER_URLS,http://$host:8000/v1"
fi
done
fi
export INFER_URLS
echo "HOSTNAMES=${HOSTNAMES[*]}"
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
echo "INFER_URLS=${INFER_URLS}"
echo "USE_DISTRIBUTED_EP=${USE_DISTRIBUTED_EP}"
export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
# Run RL
srun bash -c '
# Source environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
# Do not sync to avoid conflicts with lockfile
# 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,)
export NCCL_IB_HCA=$IB_HCA
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
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
INFER_DP_START_RANK=$((INFER_NODE_RANK * INFERENCE_DP_LOCAL))
if [ "$INFER_NODE_RANK" -eq 0 ]; then
uv run inference \
@ $CONFIG_DIR/inference.toml \
--data-parallel-address $INFER_HEAD_HOST \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
--data-parallel-start-rank $INFER_DP_START_RANK \
--data-parallel-address $INFER_HEAD_HOST \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--headless \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
fi
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
fi
else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
uv run orchestrator \
@ $CONFIG_DIR/orchestrator.toml \
--weight_broadcast.host $MASTER_ADDR \
--client.base-url $INFER_URLS \
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log &
fi
export HF_HUB_OFFLINE=1
# This is required for compilation to work correctly
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
uv run torchrun \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$OUTPUT_DIR/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter=$(seq -s, 0 $((GPUS_PER_NODE - 1))) \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.toml \
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
fi
'
@@ -0,0 +1,79 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes={{ num_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_PATH={{ config_path }}
export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/slurm
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
echo "HOSTNAMES=${HOSTNAMES[@]}"
export MASTER_ADDR="${HOSTNAMES[0]}"
export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
# Install environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Install environment as local package
cd $PROJECT_DIR && uv sync --all-extras
# Run SFT
srun bash -c '
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# 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,)
export NCCL_IB_HCA=$IB_HCA
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"
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
uv run torchrun \
--nnodes=$NUM_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$OUTPUT_DIR/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter=$(seq -s, 0 $((GPUS_PER_NODE - 1))) \
-m prime_rl.trainer.sft.train \
@ $CONFIG_PATH \
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
'
@@ -0,0 +1,20 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
#SBATCH --partition={{ partition }}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
export PROJECT_DIR={{ project_dir }}
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv run rl @ {{ config_path }}
@@ -0,0 +1,20 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
#SBATCH --partition={{ partition }}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
export PROJECT_DIR={{ project_dir }}
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv run sft @ {{ config_path }}
+14
View File
@@ -22,6 +22,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
# Teacher logprobs already cover the full sequence (prompt + completion),
# computed via prefill in the orchestrator when a teacher model is configured
teacher_logprobs = training_example.teacher_logprobs
routed_experts = training_example.routed_experts
if len(input_ids) > seq_len:
input_ids = input_ids[:seq_len]
@@ -32,6 +33,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
temperatures = temperatures[:seq_len]
if teacher_logprobs is not None:
teacher_logprobs = teacher_logprobs[:seq_len]
if routed_experts is not None:
routed_experts = routed_experts[:seq_len]
assert (
len(input_ids)
@@ -45,6 +48,12 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
)
if teacher_logprobs is not None:
assert len(teacher_logprobs) == len(input_ids), f"teacher_logprobs: {len(teacher_logprobs)}"
if routed_experts is not None:
assert len(routed_experts) == len(input_ids), (
f"routed_experts: {len(routed_experts)}, input_ids: {len(input_ids)}"
)
return MicroBatch(
input_ids=input_ids,
advantages=advantages,
@@ -53,6 +62,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
inference_logprobs=inference_logprobs,
teacher_logprobs=teacher_logprobs,
temperatures=temperatures,
routed_experts=routed_experts,
# Multimodal fields (Qwen3-VL) - passed through without modification
pixel_values=training_example.pixel_values,
image_grid_thw=training_example.image_grid_thw,
@@ -105,6 +115,10 @@ def packed_samples_into_micro_bs(
if bin_content.teacher_logprobs is None:
bin_content.teacher_logprobs = []
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
if sample.routed_experts is not None:
if bin_content.routed_experts is None:
bin_content.routed_experts = []
bin_content.routed_experts.extend(sample.routed_experts)
bin_content.position_ids.extend(sample.position_ids)
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
break
+43 -45
View File
@@ -18,7 +18,7 @@ from torch.optim.optimizer import Optimizer
from torchdata.stateful_dataloader import StatefulDataLoader
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.config import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
from prime_rl.trainer.lora import has_lora_layers, save_lora_config
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.optim import CPUOffloadOptimizer
@@ -30,7 +30,6 @@ from prime_rl.trainer.weights import (
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.tensor_hashing import get_module_signature, get_optimizer_signature
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
@@ -214,9 +213,6 @@ class CheckpointManager:
if not ckpt_path.exists():
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
self.load_from_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
self.logger.debug(
f"Signatures after loading training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
)
def save(
self,
@@ -230,9 +226,6 @@ class CheckpointManager:
"""Save the full checkpoint state for a specified step."""
ckpt_path = self.get_ckpt_path(step)
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
self.logger.debug(
f"Signatures before saving training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
)
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
bisect.insort(self.ckpt_steps, step)
@@ -305,6 +298,12 @@ class WeightCheckpointManager:
"""Get the path to write the weight checkpoint for a given step."""
return get_step_path(self.weights_dir, step)
def mark_stable(self, step: int) -> None:
"""Write STABLE file to indicate weight checkpoint is complete."""
if self.world.is_master:
step_path = self.get_step_path(step)
(step_path / "STABLE").touch()
def save_to_path(
self,
path: Path,
@@ -314,44 +313,45 @@ class WeightCheckpointManager:
tokenizer: PreTrainedTokenizer,
):
"""Save HF-compatible weight checkpoint to a given path."""
path.mkdir(parents=True, exist_ok=True)
start_time = time.perf_counter()
if self.world.is_master:
path.mkdir(parents=True, exist_ok=True)
start_time = time.perf_counter()
self.logger.debug(f"Saving weight checkpoint to {path}")
# Suppress torch.distributed warnings during checkpoint saving
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
self.logger.debug(f"Saving weight checkpoint to {path}")
# Suppress torch.distributed warnings during checkpoint saving
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
# Save weights
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
# Save weights
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
# Save model config, generation arguments and tokenizer
model.config.save_pretrained(path)
if model.generation_config:
# training sets use_cache=False which can conflict with
# cache_implementation — save with use_cache=True without
# mutating the model's config
from copy import deepcopy
# Save model config, generation arguments and tokenizer
model.config.save_pretrained(path)
if model.generation_config:
# training sets use_cache=False which can conflict with
# cache_implementation — save with use_cache=True without
# mutating the model's config
from copy import deepcopy
gen_config = deepcopy(model.generation_config)
gen_config.use_cache = True
gen_config.save_pretrained(path)
tokenizer.save_pretrained(path)
gen_config = deepcopy(model.generation_config)
gen_config.use_cache = True
gen_config.save_pretrained(path)
tokenizer.save_pretrained(path)
if self.config.save_adapter_separately and lora_state_dict is not None:
adapter_path = path / "lora_adapters"
adapter_path.mkdir(parents=True, exist_ok=True)
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
if self.lora_config:
save_lora_config(
model,
adapter_path,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
)
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
if self.config.save_adapter_separately and lora_state_dict is not None:
adapter_path = path / "lora_adapters"
adapter_path.mkdir(parents=True, exist_ok=True)
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
if self.lora_config:
save_lora_config(
model,
adapter_path,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
)
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
def save(
self,
@@ -400,10 +400,8 @@ class WeightCheckpointManager:
self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds")
# Save weight checkpoint on master rank
if self.world.is_master:
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
# Write STABLE file to indicate checkpoint is complete (for eval to safely read)
(step_path / "STABLE").touch()
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
self.mark_stable(step)
bisect.insort(self.ckpt_steps, step)
def maybe_clean(self) -> None:
+1 -1
View File
@@ -4,7 +4,7 @@ from typing import Dict, List
import torch
import torch.nn as nn
from prime_rl.trainer.config import LoRAConfig
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.trainer.models.layers.lora import MultiLoRALinear, MultiLoRAModule
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts
from prime_rl.trainer.models.layers.moe import GroupedExperts
+58 -14
View File
@@ -17,11 +17,11 @@ from torch.distributed.device_mesh import DeviceMesh
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
from torch.distributed.tensor.parallel import parallelize_module
from torchtitan.distributed.expert_parallel import ExpertParallel
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, PretrainedConfig
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
from prime_rl.trainer.config import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
from prime_rl.configs.trainer import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
from prime_rl.trainer.lora import apply_lora_to_model, strip_lora_from_state_dict
from prime_rl.trainer.models import (
AutoModelForCausalLMPrimeRL,
@@ -40,7 +40,6 @@ from prime_rl.trainer.weights import (
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.tensor_hashing import get_module_signature
from prime_rl.utils.vlm import is_vlm_model
# Add filter to the standard logging module for transformers.modeling_utils to supress the
@@ -86,6 +85,34 @@ def freeze_vision_encoder(model: nn.Module) -> None:
logger.info(f"Froze {num_frozen} parameters in vision encoder")
def freeze_moe_router(model: nn.Module) -> None:
"""Freeze MoE router parameters to maintain stable routing during training."""
logger = get_logger()
language_model = get_language_model(model)
num_frozen = 0
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if mlp is None:
continue
# Custom implementation: MoE class with router attribute
if isinstance(mlp, MoE):
for param in mlp.router.parameters():
param.requires_grad = False
num_frozen += 1
# HuggingFace implementation: gate attribute (nn.Linear)
elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Linear):
for param in mlp.gate.parameters():
param.requires_grad = False
num_frozen += 1
if num_frozen == 0:
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
logger.info(f"Froze {num_frozen} MoE router parameters")
def is_tt_moe_model(model: nn.Module) -> bool:
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
@@ -145,11 +172,26 @@ def get_model(
),
)
model_config.use_cache = False
for subconfig_key in getattr(model_config, "sub_configs", {}):
subconfig = getattr(model_config, subconfig_key, None)
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.use_grouped_mm = config.moe_use_grouped_mm
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it)
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
if not hasattr(model_config, "pad_token_id") or model_config.pad_token_id is None:
model_config.pad_token_id = model_config.eos_token_id
gen_config = GenerationConfig.from_model_config(model_config)
# Use `is not None` instead of truthiness: token ID 0 is valid.
pad_token_id = next(
(
v
for v in [gen_config.pad_token_id, gen_config.eos_token_id, getattr(model_config, "eos_token_id", None)]
if v is not None
),
None,
)
model_config.pad_token_id = pad_token_id
# NOTE: For VLM models, we do NOT propagate dtype to sub_configs.
# The model should load in its default dtype (bf16) to match vLLM inference.
@@ -180,11 +222,10 @@ def get_model(
)
with device:
# For VLM models, use AutoModelForVision2Seq or import specific model class
if is_vlm:
from transformers import AutoModelForVision2Seq
from transformers import AutoModelForImageTextToText
model_cls = AutoModelForVision2Seq
model_cls = AutoModelForImageTextToText
else:
match impl_to_use:
case "hf":
@@ -237,10 +278,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
"reshard_after_forward": config.reshard_after_forward,
}
if config.dp_replicate > 1:
hsdp_mesh = parallel_dims.world_mesh["dp_replicate", "dp_shard_cp"]
else:
hsdp_mesh = parallel_dims.world_mesh["dp_shard_cp"]
hsdp_mesh = parallel_dims.get_mesh("hsdp")
dp_mod_ep_mesh: DeviceMesh | None = None
if parallel_dims.ep_enabled:
@@ -543,7 +581,7 @@ def apply_ep(model: nn.Module, parallel_dims: ParallelDims):
if isinstance(transformer_block.mlp, MoE):
parallelize_module(
transformer_block.mlp.experts,
device_mesh=parallel_dims.world_mesh["ep"],
device_mesh=parallel_dims.get_mesh("ep"),
parallelize_plan=ExpertParallel(),
)
@@ -632,6 +670,9 @@ def setup_model(
if config.lora is not None:
apply_lora_to_model(model, config.lora)
if config.freeze_moe_router:
freeze_moe_router(model)
if parallel_dims.ep_enabled:
apply_ep(model, parallel_dims)
@@ -669,7 +710,6 @@ def setup_model(
else:
load_dcp_from_hf(model, config, parallel_dims)
logger.debug(f"Model signature: {get_module_signature(model, compress=True)}")
return model
@@ -680,6 +720,7 @@ def forward(
position_ids: Int[Tensor, "batch seq"],
labels: Int[Tensor, "batch seq"] | None = None,
temperature: Tensor | None = None,
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
# Multimodal fields (Qwen3-VL)
pixel_values: Float[Tensor, "num_patches patch_dim"] | None = None,
image_grid_thw: Int[Tensor, "num_images 3"] | None = None,
@@ -700,6 +741,9 @@ def forward(
else:
kwargs["position_ids"] = position_ids
if routed_experts is not None:
kwargs["routed_experts"] = routed_experts
out = model(**kwargs)
# PrimeLmOutput is a TypedDict (dict at runtime), HF outputs are dataclass-like objects

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