* fix: kill full process trees on rl cleanup to prevent orphaned processes
Each subprocess is now started with `start_new_session=True` so it becomes
its own process group leader. `cleanup_processes` uses `os.killpg` to send
signals to the entire group, ensuring grandchildren (e.g. vLLM workers
spawned by `uv`) are also terminated. A SIGTERM handler is added so that
external termination (e.g. from test timeouts) triggers proper cleanup.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: handle NoSuchProcess race in children() during cleanup
Move parent.children() inside the try/except psutil.NoSuchProcess
block so a process exiting between Process() and children() doesn't
abort the cleanup loop.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove unbounded wait after SIGKILL in cleanup
process.wait() after SIGKILL can block indefinitely if a process is
in uninterruptible kernel state (D state). Just fire SIGKILL and move on.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: set process titles on all entrypoints for process tree visibility
Adds setproctitle dependency and labels every prime-rl process
(Launcher, Inference, Orchestrator, Trainer, SFT, EnvServer) so they
are identifiable in ps/htop/pstree. Bumps verifiers pin to include
the companion change (Verifiers::EnvServer, Verifiers::EnvWorkerN).
Updates the monitor-run skill with process tree documentation.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove intermediate uv wrappers from local launchers
The launcher already runs inside `uv run`, so child processes inherit
the venv. Invoke entrypoints (inference, orchestrator) and torchrun
directly, eliminating one unnecessary process per subprocess.
Also bumps verifiers pin to 73deb26 (set_proc_title in __init__).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add vLLM process discovery to monitor-run skill
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove noisy log from set_proc_title
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: bump verifiers pin to adf8138 (merged companion PR)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The test used random inputs without a fixed seed, causing gradient
differences to occasionally exceed the tolerance threshold.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add watchdog to packer to detect silent hangs
packer on rank 0 can silently hang on NFS I/O, leaving all other
ranks waiting forever for rank_N.bin files. adds a heartbeat +
watchdog thread that kills the process after 30min of no progress,
letting the StatefulSet restart recover automatically.
* scope watchdog to only be active during pack()
watchdog is now armed/disarmed around pack() in wait_for_batch()
so long training steps, checkpoints, or weight broadcasts don't
trigger false-positive restarts.
* wrap pack() in try/finally to always disarm watchdog
* chore: unify log directories across local and SLURM deployments
Remove Python file logging (log.file config) — deployment-level capture
(stdout redirect for local, tee for SLURM) is sufficient. This eliminates
duplicate log files and simplifies the logging architecture.
Key changes:
- Remove log.file config option and JsonFileSink from logger
- Rename .stdout -> .log for deployment-captured logs
- Unify SLURM logs from slurm/ into logs/ (same as local)
- Trainer shows rank 0 only, all rank logs in logs/trainer/torchrun/
- Multi-node SLURM: logs/trainer/node_N.log, logs/inference/node_N.log
- Symlink logs/trainer.log -> trainer/node_0.log (multi-node)
- Historical per-job logs under logs/slurm/job_{id}/
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: update env log paths in docs to match actual structure
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: simplify env and torchrun logging sections
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: include per-node and per-rank log paths in log messages
Show where to find node-level logs (for multi-node) and per-rank
torchrun logs in the startup log messages for RL, SFT, and inference.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: extract format_log_message to shared utility
Move format_log_message from rl.py to utils/pathing.py and reuse it
in SFT and inference entrypoints, eliminating duplicated formatting logic.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove historical per-job SLURM log copies
The job_* log copies in logs/slurm/ added complexity without much value.
SLURM's own job output log (job_%j.log) already serves as the historical
record.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: move tmux helper section to bottom of logging.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: consolidate tmux.sh and slurm_tmux.sh into one script
Log paths are now unified across local and SLURM, so both scripts
were tailing the same files. Merge into a single tmux.sh with a Logs
window (4 panes tailing trainer/orchestrator/envs/inference) and a
Monitor window (nvtop + htop).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: fix logger docs to match actual behavior
setup_logger doesn't raise when called twice (it reconfigures).
get_logger always works (auto-initializes a default if needed).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: remove incorrect env_worker_logs reference
The env_worker_logs config field is defined but never read — env worker
logs are written unconditionally.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove dead env_worker_logs config field
Defined but never read anywhere in the codebase.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add router logs to slurm monitoring section
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: mention per-node and per-rank trainer logs in performance section
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: generalize config path references to {output_dir}/configs/
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: template rendering bugs and improve log message labels
- Fix Jinja2 tags on same line as tee commands (broken bash output)
- Rename "Trainer:" to "Trainer (rank 0):" in log messages
- Rename "Nodes:" to "All nodes:" and "Per-rank:" to "All ranks:"
- Make per-rank log line a tail -F command following torchrun structure
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: include stderr in all-ranks log tail command
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: update stale log paths in examples, SFT tests, and pathing test
- Fix torchrun glob: **/*.log → */*/*/*.log (tail -F doesn't support **)
- Update 5 example READMEs from slurm/latest_* to logs/ paths
- Update SFT tests from logs/trainer/rank_0.log to logs/trainer.log
- Update pathing test fixture to match new log structure
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: clean up log message code and fix test bug
- Remove hardcoded "Showing rank 0 logs only" message from trainers
(already communicated via format_log_message)
- Derive env_log_dir inside format_log_message instead of requiring
callers to pass it
- Fix test_pathing double mkdir crash (FileExistsError)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: split LogConfig into TrainerLogConfig and OrchestratorLogConfig
- TrainerLogConfig adds ranks_filter (configures torchrun
--local-ranks-filter, defaults to [0]) and log_data
- OrchestratorLogConfig adds vf_level
- Base LogConfig retains level and json_logging
- ranks_filter is passed through to SLURM templates
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: keep LogConfig as-is, only extend with TrainerLogConfig
Revert OrchestratorLogConfig — keep vf_level and log_data on the base
LogConfig for safety. Only TrainerLogConfig extends with ranks_filter.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove "(rank 0)" from trainer log message
ranks_filter is now configurable so it may show more than rank 0.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: use total_infer_nodes for log hint and add CHANGELOG entries
- Fix num_infer_nodes using per-replica count instead of total, which
suppressed "All nodes" hint for multi-replica inference
- Add CHANGELOG entries for removed config fields and new ranks_filter
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: use `uv run sft` entrypoint in SFT integration tests
The SFT tests were calling torchrun directly, bypassing the SFT
entrypoint which handles stdout redirection to trainer.log. This caused
tests to read stale/wrong log files from the shared output directory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add --clean-output-dir to initial SFT integration tests
The SFT entrypoint validates that output_dir doesn't contain stale
checkpoints. Since output_dir is session-scoped and shared across test
modules, the SFT tests need --clean-output-dir on the initial run.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add --clean-output-dir to RL integration tests too
All integration tests sharing the session-scoped output_dir should
clean on initial run to avoid stale checkpoint validation errors.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add GitHub PR guidelines to AGENTS.md
No test plan section in PRs unless tests were actually run or
explicitly requested.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: separate Git and GitHub sections, use bullet list
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add draft PR guideline to AGENTS.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: format branch prefixes as bullet list
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add deterministic garbage collection to avoid stragglers
Disable Python's automatic GC and run manual collections at fixed
intervals so all distributed ranks collect simultaneously, preventing
one rank from stalling others at sync points.
Opt-in via config: `gc = { freq = 50 }` (both SFT and RL trainers).
Inspired by torchtitan's approach (https://arxiv.org/abs/2505.05713).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: enable deterministic GC by default (freq=50)
Matches torchtitan's default. Can be disabled with `gc = null` in config.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use f-string for loguru GC log message
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: address review feedback
- Rename `freq` to `interval` for consistency with codebase conventions
- Remove `@staticmethod` and `reason` param from `collect`, make it `_collect`
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* chore: replace toml-config skill with broader config skill
Replaces the narrow toml-config skill with a comprehensive config skill
covering TOML files, CLI overrides, config composition, inspection,
and all field type patterns (booleans, None, lists, dicts, unions, models).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add entrypoints skill, remove inference-server skill
Add entrypoints skill covering rl, sft, and inference commands.
Remove inference-server skill as its content is now covered by entrypoints.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: streamline installation skill
Consolidate install commands into one code block with basic/advanced sections.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: clean up AGENTS.md, add release skill
Move release notes instructions into a dedicated skill. Streamline
AGENTS.md: concise code guidelines, updated running code section,
removed CLI usage (now covered by config skill).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add monitor-rl-run skill
Covers finding output directories, log file locations (local vs SLURM),
node allocation, performance diagnostics (trainer wait, orchestrator wait,
env server event loop lag), and quick health checks.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename monitor-rl-run to monitor-run, add RL section
Restructure to support future SFT monitoring section alongside RL.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: restructure monitor-run into Check Logs and Check Performance sections
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: detail GPU allocation for single-node and multi-node RL runs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* update readme
* fix revamp-readme
* update readme
* add real world example
* add real world example
* add swe and deepdive
* add qwen example
* add intellect 3.1 example
* add minimax swe
* add all
* fix wording and typos across example READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix README links and wording, add memory usage doc reference
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* updare training
* fix glm5 PD disagg config: num_infer_nodes must equal prefill + decode
num_infer_nodes was 16 but prefill (4) + decode (4) = 8.
Set num_infer_nodes = 8 with num_infer_replicas = 2 for 16 total.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix model table: move INTELLECT-3 to glm4_moe, add Trinity as afmoe
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* updare training
* address PR review comments
- Restore accidentally deleted examples/hendrycks_sanity/ from main
- Restore installation section (uv sync, FA3, python/flash-attn checks, eval step)
- Fix model table description: trainer works with HF/Prime ModelForCausalLM, not "built on HF Transformers"
- Improve activation checkpointing description and explain freq parameter
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The gradient comparison between HF and PrimeRL NemotronH diverges in the
attention path (139.5 vs atol=10), causing CI failures. The logits forward
check still passes, and test_nemotron_h_backward independently verifies
all parameters receive non-zero gradients.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Track how many eval rollouts failed due to sandbox/infra errors.
Derived from the difference between total eval inputs and successful
outputs. Also logged in the all-fail early return path.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
PyTorch 2.9 defaults torch.load to weights_only=True, which blocks
deserialization of DTensor types like _StridedShard used in EP checkpoints.
This caused checkpoint resume to fail silently on 397B models with EP=8.
* selective ac
* ruff
* fix
* some changes
* some changes
* some more
* fix
* some more
* some more
* small
* simplify
* address comments
* clean
* fix
* address comment
* address comments
* add attn_proj and mlp targets, remove attention_sdpa
Replace attention_sdpa (checkpointing the attention kernel saves zero
memory with flash attention) with two new selective AC targets:
- attn_proj: checkpoints QKV projections, QK norms, RoPE, and output
projection — everything in attention except the kernel
- mlp: checkpoints the entire dense MLP forward (skipped for MoE layers)
Refactor FlashAttention and SDPAAttention to extract _attn_projections
and _output_proj methods as checkpoint boundaries.
* fix: add rms_norm re-export for nemotron_h compatibility
The selective AC refactoring moved RMSNorm/RMSNormConfig to norms.py,
but nemotron_h (added in main) imports from rms_norm.py. Add a
re-export shim to keep both paths working.
* fix: handle position_embeddings=None in SDPAAttention
NemotronH passes position_embeddings=None since it uses its own rotary
scheme. The FlashAttention path already guarded for this but
SDPAAttention._attn_projections and both forward() signatures were
missing the None handling.
* fix: handle LatentMoE in buffer reset and allow impl=auto for selective AC
- _reset_runtime_moe_buffers now checks (MoE, LatentMoE) like all other
MoE instance checks in the file
- selective_ac_only_with_custom_impl accepts ("custom", "auto") matching
the pattern used by ep_only_with_custom_impl and
router_replay_only_with_custom_impl
* Fix selective AC LatentMoE target detection
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
* Delete tests/unit/train/models/test_selective_checkpointing.py
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
* fixes for nemotron and GDN models
---------
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>
* feat: integrate verifiers multi-env-worker support
Pin verifiers to 8dffd10 (multi-env-worker branch) which introduces
env worker processes for parallel environment execution. Add per-env
`num_workers` config field (default "auto", scales as 1 worker per 256
concurrent rollouts). Update imports and API calls to match the new
verifiers serve module (workers → serve, log_file → log_dir).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* bump
* chore: unify env log dir and add env log tail commands
Move env server logs to output_dir/logs/envs/{env_name}/ for both
train and eval envs. Use resolved_name consistently instead of
env.name or env.id. Add env log tail commands to RL startup messages
(single_node and slurm) and add an Envs pane to the tmux script.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* bump vf
* docs: add changelog entry for orchestrator.env[].num_workers
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* formatting
* refactor: move env logs to main logs dir and improve log formatting
Move env logs from outputs/run_default/logs/envs/ to outputs/logs/envs/
so they live alongside trainer/orchestrator/inference logs. Also clean up
the log path display: truncate long env names, align columns, and reorder
tmux panes to put envs between orchestrator and inference.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: resolve eval env workers based on num_examples * rollouts_per_example
When num_examples=-1 (all samples), defaults max_concurrent to 1024
(4 workers) with a warning log explaining the fallback.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: separate train/eval env logs and nested log display
Move env logs into envs/train/ and envs/eval/ subdirs to avoid name
clashes when the same env is used for both. Display logs in a nested
hierarchy: Envs > Train/Eval > individual envs.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix standalone env server logdir
* bump vf
* remove env server config
* address comments
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
`get_sampling_args` was gating `return_token_ids=True` on `use_token_client`,
which meant the non-TITO client path never received token IDs from vLLM.
The verifiers `parse_tokens()` then crashed with `len(None)` because the
response attributes existed but were None.
Replace the `use_token_client` flag with `is_vllm` (derived from
`config.teacher_rollout_model is None`) so vLLM-specific extra_body
params (`return_token_ids`, `top_k`, `min_p`) are always sent when
hitting a vLLM server, and skipped only for SFT distillation against
external non-vLLM APIs.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: disaggregated prefill-decode inference with multi-replica support
Extracted PD disaggregation changes from PR #2010. Adds:
- Disaggregated deployment type with separate prefill/decode nodes
- vLLM kernel format weight transfer (avoids HF checkpoint round-trip)
- Pause/resume lifecycle for draining in-flight requests during weight updates
- Admin URL separation (bypass router for direct server access)
- Multi-replica inference support
- NIXL/UCX, DeepEP, and vllm-router install scripts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: remove vLLM kernel format weight transfer
This PR should focus on PD disaggregation only. The kernel format
transfer path (fused projections, stacked experts, FP8 quantization)
is a separate optimization that can be added back in a dedicated PR.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* style: fix ruff formatting
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address PR review comments
- Raise error if tp != 1 in disaggregated mode instead of silently overriding
- Revert auto_setup_model to main's version (FP8 model name logic not needed for PD)
- Revert nccl.py broadcast to main's inline style (method extraction was for kernel format)
- Add try/finally around weight update to ensure engines are always resumed
- Fix sample config: num_infer_nodes=3 + num_infer_replicas=2 to pass validation
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add disaggregated P/D support to inference SLURM template
Extends the existing inference.sbatch.j2 template with conditional
disaggregated mode support. When deployment type is "disaggregated",
the template splits nodes into prefill/decode groups with per-replica
vllm-router, NIXL KV transfer, and DeepEP expert parallelism.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add inference disag slurm
* add extra deps
* add extra deps
* fix eps
* fadd stuff
* fadd stuff
* fadd stuff
* fix smth
* move deep-gemm from dep group to disagg extra for --all-extras
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: configurable deep-gemm via use_deep_gemm config field
Rebuild deep-gemm from vLLM 0.17 recommended commit (477618c).
Add use_deep_gemm bool to InferenceConfig that sets VLLM_USE_DEEP_GEMM=1
in the sbatch template. Only works with per-tensor FP8 models (e.g. GLM-5-FP8).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* wip
* add config
* add deps
* fix studfs
* fix studfs
* use vllm router from matej
* feat: add X-Session-ID header for prefix cache affinity in PD inference
Monkey-patch verifiers' OpenAI clients to inject X-Session-ID (derived
from example_id) on every inference request. The vllm-router uses this
header for sticky routing so that all requests for the same example hit
the same decode node, enabling prefix cache reuse.
Also updates hendrycks_math config for disaggregated PD with EP.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Revert "feat: add X-Session-ID header for prefix cache affinity in PD inference"
This reverts commit 12deff893d0c5053273c25a537b6979be601eb6a.
* delete slurm
* feat: sticky routing, deep-gemm support, and P/D cleanup
- Add extra_headers_from_state to ClientConfig for per-request dynamic
headers (X-Session-ID from example_id for sticky routing)
- Auto-configure session headers in RL runs
- Pass use_deep_gemm to disagg RL template (VLLM_USE_DEEP_GEMM=1)
- Add --intra-node-data-parallel-size 1 to P/D router args
- Fix uv sync: remove stale --group fp8-inference (deep-gemm now in disagg extra)
- Update verifiers to f6ff5274 (extra_headers_from_state support)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: update verifiers to main (f5580acd)
Points to merged extra_headers_from_state support.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: update disagg rl config for Qwen3-30B-A3B (1P+1D)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add disaggregated inference guide and GLM-5 config (#2077)
* chore: add reasoning_parser to GLM-5 inference config (#2081)
Enables vLLM to split reasoning_content from content natively,
so verifiers saves it as a separate field in trajectories.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Enable none
* Feat: skip master weights gather
* updates deps
* remove configs
---------
Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* fix: use sys.exit(1) in clean_exit to terminate process on fatal error
raise alone doesn't terminate the process in async context - the event
loop swallows the exception and the process hangs indefinitely, leaving
runs stuck in RUNNING state with leaked pods.
* fix: remove unused exception variable for ruff
* Revert "Enable none in config (#2093)"
This reverts commit a25b3e7a18.
* Revert "Fix/none in list (#2094)"
This reverts commit 4f612601f6.
* fix conflict
mamba-ssm needs nvcc and CUDA torch to compile. uv was resolving
CPU-only torch for the build environment, causing bare_metal_version
to be undefined. Adding match-runtime = true ensures the CUDA torch
from pytorch-cu128 index is used during the build.
Add nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16 and
nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 with qwen3_coder parser.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: hybrid CP for Qwen3.5 MoE (DeltaNet + standard attention)
Integrate fla (flash-linear-attention) library for native context parallelism
on GatedDeltaNet layers. Standard attention layers use ring attention for CP,
while DeltaNet layers use fla's state-passing CP which communicates only the
compact recurrent state (O(d²) per layer) instead of all-gathering full
sequences (O(N×d)).
- Add flash-linear-attention dependency (Triton kernels + CP support)
- Wire up fla's build_cp_context/cp_context in GatedDeltaNet forward
- Add setup_hybrid_cp to configure DeltaNet modules for CP
- Add CP gather/scatter autograd primitives as fallback in cp.py
- Fix VLM num_hidden_layers access for debug.num_layers config
- Add test configs for Qwen3.5-35B-A3B CP testing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* style: fix ruff formatting
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove config files from tracking
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: validate VLM bfloat16 dtypes from loaded config
Move the VLM bfloat16 validation from ModelConfig (which only had
the model name) to get_model() where we have the actual loaded HF
config and can reliably detect VLMs via is_vlm_config().
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add NemotronH (Nemotron-3-Super-120B-A12B) model support
Implement hybrid Mamba-Transformer-MoE architecture with three distinct
layer types: Mamba-2 SSM (via HF NemotronHMamba2Mixer), LatentMoE with
non-gated experts and latent projections, and shared attention layers.
- Add NemotronHConfig with hybrid_override_pattern parsing
- Add NonGatedGroupedExperts, NemotronHRouter, LatentMoE to layers/moe.py
- Add bidirectional weight conversion (HF mixer.* <-> PrimeRL namespaces)
- Register model in AutoConfig and update FSDP/EP isinstance checks
- Add comprehensive tests (forward/backward, weight roundtrip, reverse conversion)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: NemotronH weight conversion, MoE forward pass, and HF model compat
Weight conversion (converting_nemotron_h.py):
- Handle backbone.* -> model.* prefix rename (HF uses "backbone", PrimeRL uses "model")
- Stack individual expert weights into fused 3D tensors (HF stores per-expert, PrimeRL uses fused)
- Unstack fused tensors back to individual experts for HF export
- Drop mtp.* (multi-token prediction) keys during conversion
- Support both backbone.* and model.* prefixes in layer type inference
MoE forward pass (moe.py):
- Apply routing scores AFTER expert computation (was before), matching vLLM and HF reference
- Apply routed_scaling_factor separately after expert output, before fc2_latent_proj
- Remove routed_scaling_factor from router scores (applied in LatentMoE instead)
Model loading (model.py):
- Support HF models with "embeddings" attr (not just "embed_tokens") in FSDP setup
- Support HF models with "norm_f" attr (not just "norm") in FSDP setup
- Guard all .mlp accesses with getattr for HF model compat (NemotronHBlock has no .mlp)
Modeling (modeling_nemotron_h.py):
- Handle backbone.* prefix in is_hf_state_dict detection
- Handle both model.* and backbone.* in layer type inference
- Per-layer HF conversion for weight broadcast (model.* -> backbone.*)
Configs:
- Add nemotron_4node/ and nemotron_debug/ run configs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove spurious RoPE from NemotronH attention layers
NemotronH gets position information from Mamba layers, not RoPE.
Both HF and vLLM implementations confirm NemotronH attention does not
apply rotary embeddings. The spurious RoPE was causing ~0.5 KL mismatch
between vLLM inference and PrimeRL training; after removal KL drops to
near zero.
- Make position_embeddings optional in FlashAttention/SDPAAttention
- Remove RotaryEmbedding from NemotronHModel
- Add KL mismatch test suite for NemotronH
- Mark test_nemotron_h_reverse as xfail (pre-existing HF fused tensor issue)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use mamba_ssm Triton SSD kernels for NemotronH to match vLLM precision
The HF torch_forward computes softplus in bf16 while vLLM uses fp32
Triton kernels, causing ~0.4 KL divergence in Mamba layers. This patch
monkey-patches NemotronHMamba2Mixer to use mamba_chunk_scan_combined
from mamba_ssm (Triton, fp32 softplus) with PyTorch nn.Conv1d fallback.
- Add mamba_ssm Triton SSD patch for NemotronHMamba2Mixer
- Add mamba-ssm as optional dependency in pyproject.toml
- Update installation skill with mamba-ssm instructions
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: update uv.lock for mamba-ssm and fix ruff formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: move mamba-ssm to dependency-groups to fix CI CPU tests
mamba-ssm requires nvcc to build from source. When it was in
[project.optional-dependencies], `uv sync --all-extras` tried to build
it in CI where nvcc isn't available. Moving it to [dependency-groups]
means it's only installed explicitly via `uv sync --group mamba-ssm`.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: detect attention layers in is_prime_state_dict for weight broadcast
The per-layer is_prime_state_dict check missed attention-only layers
(which have self_attn.* keys), causing the HF conversion to be skipped
during weight broadcast. vLLM then received PrimeRL keys (self_attn.*)
instead of HF keys (mixer.*), failing with a 500 error.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: update uv.lock and ruff formatting for NemotronH
- Reformat modeling_nemotron_h.py to pass ruff check
- Update uv.lock after mamba-ssm dependency group addition
- Add pre_run_command to nemotron config for mamba-ssm install
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: guard mamba_ssm import for CI environments without it
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: include mamba-ssm in Docker build for NemotronH support
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address review feedback for NemotronH
- Add non-layer weight handling to convert_layer_to_prime (backbone.* prefix)
- Make embed_module fallback consistent (safe getattr for both attrs)
- Remove unused routed_scaling_factor from NemotronHRouter
- Remove dead get_max_layer_num function from converting_nemotron_h
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Individual rollout group failures in generate() are now caught and
logged instead of propagating up and crashing the orchestrator.
Metrics are computed on the successful rollouts. If all rollouts
fail for an env, evaluate_env skips metrics with a warning.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add GPT-OSS support with LoRA + DP fix
Add monkey patches to fix two vLLM 0.17.0 bugs that prevent serving
GPT-OSS MoE models with LoRA enabled under data parallelism:
1. Harmony stop token propagation: vLLM's ChatCompletionRequest doesn't
merge harmony stop tokens (<|call|>, <|return|>) from
default_sampling_params into per-request SamplingParams. The model
ignores tool call boundaries. Fix: patch to_sampling_params() to
merge default stop token IDs.
2. FusedMoE LoRA + DP: LoRA injection on MoE layers replaces the quant
method with FusedMoEModularMethod, which inadvertently sets
supports_internal_mk=True. This makes the MoE runner skip DP
dispatch/combine, but the LoRA kernel uses NoDPEP and doesn't handle
DP. Additionally, LoRA decorators capture full-batch tensors but fire
per-chunk inside the kernel's chunk loop, causing shape mismatches at
DP>=3. Fix: set moe_kernel=None to restore dispatch/combine, and make
decorators chunk-aware by tracking offsets.
Also adds an example config for wiki-search with GPT-OSS-20B.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: apply MoE LoRA+DP monkey patch in worker subprocesses
The monkey_patch_fused_moe_lora_dp() in server.py only runs in the main
API server process. vLLM DP workers are spawned as separate subprocesses
that import FusedMoEWithLoRA fresh, so the patched _inject_lora_into_fused_moe
never reaches them. This causes corrupted MoE output at DP>1 with --enable-lora.
Apply the patch in the worker extension module (filesystem.py) which gets
imported inside every worker subprocess.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove redundant MoE LoRA+DP patch from server.py
This patch only ran in the main API server process, not the DP worker
subprocesses where FusedMoEWithLoRA is actually instantiated. The
effective call is in filesystem.py (worker extension).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: move MoE LoRA+DP patch to worker __init__.py
Move from filesystem.py to __init__.py so it applies regardless of which
worker extension is loaded (filesystem or nccl).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove GPT-OSS wiki-search config from PR
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: dev <dev@prime-rl.dev>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* SFT distillation with teacher endpoint
* streamline SFT distillation rollout/eval model split
* fix sft reconstruction and default loss scaling regressions
* simplify SFT distillation by removing eval inference split
* chore: apply ruff formatting
* docs: add changelog entries for RolloutModelConfig, SFTLossConfig, and CustomLossConfig
Co-authored-by: will brown <willccbb@users.noreply.github.com>
* refine external SFT rollout path and cleanup tests
* refactor shared SFT chat-template tokenization logic
* fix: remove dead store in _tokenize_step_from_messages
full_ids was tokenized via _render_messages then immediately overwritten
by build_incremental_token_mask, wasting a tokenization pass per step.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove unused _should_add_generation_prompt from trajectories
Duplicate of should_add_generation_prompt in utils/chat_template.py,
never called anywhere.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: pass top_k and min_p for both token and non-token client paths
Explicitly disable top-k and min-p filtering on all vLLM requests,
not just the token client path.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove redundant test_rl_config_external_rollout_mode_rejects_inference
Redundant with the Pydantic model validator definition.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: correct CHANGELOG field name to teacher_rollout_model
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: pass tool definitions through pretokenize pipeline
When external teacher rollouts have tool_defs, convert them to OAI
format and pass through to build_incremental_token_mask so that
tokenization includes tool definition tokens from the chat template.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: enable collapse_consecutive_tool_messages in pretokenization
Matches the SFT data pipeline behavior. Without this, parallel tool
call responses cause an assertion failure in incremental tokenization
when the chat template re-renders consecutive tool messages.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: handle dict tool_defs in _convert_tools_to_oai_format
Tool definitions arrive as plain dicts after ZMQ msgpack serialization
(verifiers' msgpack_encoder calls model_dump() on Tool pydantic objects).
Use duck-typed accessor to support both dict and object forms.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: VLM processor support in SFT distillation pretokenization
For VLM models, the tokenizer alone produces only 1 <|image_pad|> token
per image, but the model expects the count to match actual image patches.
Thread the processor through pretokenize → render_messages →
build_incremental_token_mask so that processor.apply_chat_template
(which expands image placeholders correctly) is used when available.
Also move pretokenize before build_vlm_image_cache in the orchestrator,
since the cache build strips image data from messages.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* perf: replace incremental token mask with direct completion masking
In the SFT distillation path, completion is always a single assistant
message (enforced by verifiers' parse_response_message), so the
completion mask is trivially all-True. Replace N incremental
tokenizer/processor calls from build_incremental_token_mask with a
single render_messages call. For VLM models this avoids redundant
image preprocessing on every incremental prefix.
Added assertion to guard the single-assistant-role assumption.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove duplicate SFT distillation configs
Keep examples/alphabet_sort/sft_distill_hard.toml as the canonical
example config.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: always request logprobs in sampling args
logprobs=True was only set when use_token_client=True, but non-token-
client paths (e.g. external APIs) also need logprobs for RL training.
return_token_ids remains gated behind use_token_client since it is
vLLM-specific.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove test_rl_config_external_rollout_mode_rejects_token_client
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: set checkpoint_ready in non-policy-update path
When enable_policy_updates is False (SFT distillation), generate_batch
skipped calling checkpoint_ready.set(). This worked by accident because
the event starts set and is only cleared inside maybe_update_policy
(which is never called in this path), but would deadlock if anything
else ever cleared the event.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Address PR review feedback
- Revert loss_scale regression: use loss_mask-based scaling unconditionally
- Move setup_external_rollout_model to orchestrator/utils.py
- Clarify log message to say "SFT distillation mode"
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: truncate prompt_ids to common prefix to prevent corrupted token sequences
When tokenizing trajectory steps from messages, the prompt-only and
full (prompt+completion) tokenizations can diverge at a boundary
(non-prefix split). Previously, the full prompt_ids was returned even
when split_idx < len(prompt_ids), producing corrupted sequences where
prompt_ids + completion_ids != full_ids. This broke interleaving
(extension property checks fail on mismatched prefixes) and fed
invalid token sequences to the trainer.
Fix: use full_ids[:split_idx] as prompt_ids so the concatenation
always equals full_ids exactly.
Verified across GLM-4, Qwen3, Qwen2.5, Qwen2.5-VL tokenizers and
tested end-to-end SFT distillation on alphabet-sort, wiki-search,
tic-tac-toe, and color-codeword (VLM) environments.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: restore non-prefix tokenization debug log after prompt_ids truncation
The previous commit truncating prompt_ids to full_ids[:split_idx] made
the debug log condition always false (split_idx < split_idx). Track the
original prompt length before overwrite so the log fires correctly.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: William Brown <williambrown97@gmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: will brown <willccbb@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Console reward was using results_df.reward.mean() (flat mean across all
rollouts) while wandb logged by_example.reward.mean().mean() (mean per
example, then across examples). These diverge when rollouts_per_example
varies across problems. Now both use the same aggregation.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Add router_url support for elastic inference pool
When configured, inference requests route through a vllm-router
while admin operations (weight updates, LoRA loading) still go
directly to discovered pods via elastic DNS discovery.
* Gate router traffic on ready servers
Only expose the router client when there are actually ready backends,
preventing requests from being sent to a router with no healthy pods
during weight updates or scale-down.
* fix: remove misleading orchestrator throughput metric
The orchestrator's perf/throughput (tokens/s) was computed as
num_tokens / generate_completions_time, but with in-flight rollouts
some tokens are generated during the previous training step. This makes
generate_completions_time shorter than the actual total inference time,
inflating the reported throughput. Per-rollout generation_ms metrics
remain available for accurate inference speed tracking.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove throughput from orchestrator benchmark table
Same misleading metric — remove it from print_benchmark as well.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add Group Relative Reward Rescaling as length penalty
* require online difficulty filtering
* add config validation
* fix mean
* refactor
* move `baseline`
* GR3 length penalty: Advantage config validator bug (#2039)
The validate_gr3_alpha validator in AdvantageConfig was incorrectly
accessing self.online_difficulty_filtering, which belongs to BufferConfig,
not AdvantageConfig. This caused an AttributeError whenever gr3_alpha was
set to a truthy value, making the GR3 feature unusable.
Fixed by moving the online_difficulty_filtering check to OrchestratorConfig
where both advantage and buffer configs are accessible.
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
* fix baseline
* fix dtype
* changelog
* rename to `length_shaping_alpha`
* deprecate `length_weighte_mean`
* add test
---------
Signed-off-by: rasdani <73563550+rasdani@users.noreply.github.com>
Co-authored-by: rasdani <3563550+rasdani@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Add a sample_ratio field (0.0–1.0) to LogExtrasConfig that controls
what fraction of rollouts are logged per step. When set, the effective
sample cap is computed from the actual rollout count at runtime:
int(len(rollouts) * sample_ratio).
1.0 = all rollouts (full data)
0.5 = half of rollouts
0.0 = disable sample logging
None (default) = current behavior (log all)
Usage: --prime-monitor.log-extras.sample-ratio 0.5
atexit handler ensures spawned env server processes are terminated when
the orchestrator crashes, preventing orphaned subprocesses that keep the
container alive and leave the run stuck in RUNNING.
* fix: handle DTensor weights in MultiLoRAGroupedExperts for EP compatibility
When Expert Parallelism is enabled, distribute_module() converts all
parameters to DTensors sharded across the EP mesh. The base GroupedExperts
path handles this via the @expert_parallel decorator, but
MultiLoRAGroupedExperts.forward() bypassed the decorator entirely,
passing DTensors directly to torch._grouped_mm alongside regular tensors.
Mirror the @expert_parallel decorator logic: convert DTensors to local
shards, apply generate_permute_indices for token reordering and alignment
padding, and unpermute the output.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: gather EP-sharded LoRA weights in state_dict and exclude base_layer from modules_to_save
Two fixes for EP + LoRA MoE weight broadcast:
1. state_dict_for_adapter: call full_tensor() on DTensor LoRA weights
before per-expert indexing. With EP, these weights are sharded across
ranks and direct indexing triggers a DTensor redistribute assertion.
2. save_lora_config: exclude "base_layer" params from modules_to_save
detection. After EP/FSDP wrapping, base layer params can have
requires_grad=True, causing them to be incorrectly added to
modules_to_save which vLLM rejects.
Tested end-to-end: Qwen3-30B-A3B EP=4, LoRA rank 16, 30 steps at
batch sizes 128 and 256 on H200.
* fix: re-freeze base params after EP replaces them with DTensors
ExpertParallel() replaces expert params with DTensors that default to
requires_grad=True, overriding the freeze applied by LoRA setup.
Re-run freeze_all_except_lora_and_specified after apply_ep to restore
correct grad state.
This also reverts the save_lora_config workaround (base_layer filter)
since the root cause is now fixed.
* fix: use new_zeros instead of new_empty for unpermuted output buffer
new_empty leaves uninitialized memory in positions not covered by
permuted_indices, which could leak garbage values into the output.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Previously, custom losses were normalized by batch_size (number of
sequences) while the default loss was normalized by the number of
unmasked tokens. This made the effective learning rate depend on
sequence length for custom losses. Now all loss types consistently
normalize by the number of unmasked tokens.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* make the loss equal weight per unmaked token
* minor fixes
* run ruff
* prevent nan-poisoning
* update
---------
Co-authored-by: hallerite <git@hallerite.com>
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a was hardcoded
for exactly 2 subloras, causing IndexError with Qwen3.5's 4-way
qkvz fusion when fully_sharded_loras=True.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Move max_retries from EvalEnvConfig to EnvConfig so it applies to both
training and eval environments. The scheduler now looks up max_retries
per task from the env config instead of hardcoding 0.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add Qwen 3.5 MoE model support with EP and CP integration
Adds a custom Qwen 3.5 MoE (GatedDeltaNet + MoE) implementation with:
- HF <-> PrimeRL weight conversion (fused/unfused expert formats)
- Expert Parallelism support (MoE layers auto-detected by apply_ep)
- Context Parallelism support (ring attention patching for flash attention layers)
- Router replay via routed_experts argument
- Unit tests for forward pass, weight roundtrip, router replay, and CP patching
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* remove vflm warning
* feat: add custom VLM support for Qwen 3.5 MoE
Extend Qwen3_5MoeForCausalLM to handle both text-only and VLM configs.
When the config has a vision_config, the model creates a composite body
(HF frozen vision encoder + custom PrimeRL text model). Weight conversion
auto-detects VLM keys and remaps accordingly.
- Unified model class (no separate VLM file) driven by config
- Config-based VLM detection fallback for local model paths
- VLM dispatch in get_model() via _CUSTOM_VLM_MAPPING
- mini_moe.py preset for qwen3_5_moe_vlm testing
- 6 new GPU tests covering forward/backward/weights/roundtrip/router/meta
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add debug SFT config for real Qwen3.5-35B-A3B VLM
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: support VLM layer key format in weight broadcast
VLM models use `model.language_model.layers.*` instead of
`model.layers.*`, which crashed get_max_layer_num and caused
filter_state_dict_by_layers to silently drop layer weights.
Also fixes off-by-one in filter_state_dict_by_layers that
skipped layer 0.
* use registry-based approach
* run ruff
* chore: remove debug SFT configs for Qwen3.5 MoE
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
* fix: use repr for rollout error log to show full error chain
The rollout error warning was using str formatting which only showed
the short error_chain_str. Using repr shows the full error_chain_repr
with the actual error message, making debugging much easier.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: print error_chain_repr instead of full error dict
Show only the error_chain_repr from the rollout error dict in the
warning log, which contains the actual useful error message rather
than the entire dict.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* simplify: index directly into error dict
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: make errored_rollouts and empty_rollouts metrics rates per step
Instead of logging raw counts, divide by total rollouts in the step
to get the fraction of errored/empty rollouts. This makes the metrics
comparable across steps with different numbers of rollouts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: re-schedule errored rollouts instead of filtering after group completion
Rollouts with a populated "error" field are now re-scheduled (like empty
trajectories) instead of being accepted into the group. Both conditions
are checked independently so a rollout that is both empty and errored
increments both counters. Adds scheduler/errored_rollouts metric.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: remove now-dead error/mean metrics from orchestrator
Errored rollouts are filtered in the scheduler before reaching the
batch, so error is always None in results_df. Remove the error column
and the error/all/mean and error/{env}/mean metrics. Error tracking
is now handled by scheduler/errored_rollouts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: per-env metrics for empty and errored rollouts
Track empty_rollouts and errored_rollouts counts per task. Report both
global (scheduler/empty_rollouts/all, scheduler/errored_rollouts/all)
and per-env (scheduler/empty_rollouts/{task}, scheduler/errored_rollouts/{task})
metrics.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: move empty/errored rollout metrics to their own section
Use empty_rollouts/ and errored_rollouts/ prefixes instead of nesting
under scheduler/.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: allow num_infer_nodes=0 with fake data in multi-node SLURM RL
Skip launching inference servers and orchestrator when num_infer_nodes=0,
running only the trainer with fake data. Useful for benchmarking multi-node
training without needing inference resources.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: skip weight broadcast when using fake data
No inference server exists in fake data mode, so broadcasting weights
would either hang (NCCL) or write unnecessary files (filesystem).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: per-env metrics logging with consistent naming convention
Adopt {metric}/{scope}/{stat} naming where scope is "all" (global) or
an env name. All metrics that were previously global-only now get
per-env breakdowns when multiple envs are present.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: always show per-env breakdown and drop reward std/median
Remove the nunique() > 1 gate so per-env metrics are always logged,
even with a single env. Remove std and median from reward stats.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: metrics/{env}/{metric} format, remove error type breakdown
- Change verifier/filter metrics to metrics/{env}/{metric} (no global, no stat suffix)
- Remove per-error-type logging (error/{error_type})
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove redundant batch/{env}/{env} keys
Env ratios only make sense at the global level (batch/all/{env}).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: separate solve/batch/off_policy metrics, flatten async_level
- Extract solve_none, solve_all, effective_batch_size as top-level
metrics with /all and /{env} breakdowns
- Move off_policy_level to off_policy_level/all/{stat}
- Make async_level a flat key
- batch/ now only contains env ratios and inflight/cancelled counts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: per-env off_policy_level tracking
Add task field to InflightRolloutInfo so off_policy_level can be
reported per env as off_policy_level/{env}/{stat}.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: rename batch/ inflight/cancelled to progress/, simplify batch/{env}
- batch/inflight_rollouts, batch/inflight_samples, batch/cancelled_rollouts
moved to progress/ prefix
- batch/all/{env} simplified to batch/{env}
- async_level moved to scheduler/async_level
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: inline grouped_stats, separate global and per-env sections
Remove grouped_stats helper in favor of explicit inlined metrics.
Global metrics come first, per-env metrics in a dedicated section after.
All metrics consistently group by example_id before aggregating.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: validate that env name is not "all" (reserved for global metrics)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update scheduler config
* fix: use example_id grouping for solve stats instead of index arithmetic
The previous index-based approach (index // rollouts_per_example)
assumed rollouts were contiguous by example, which is not guaranteed
when the scheduler interleaves groups from different envs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: update scheduler test for new task field on InflightRolloutInfo
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: add changelog entry for metrics logging overhaul
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: validate unique env names, use notna(), simplify metrics_df access
- Add unique env name validation on OrchestratorConfig and EvalConfig
- Use notna() instead of ~isna() for error rate
- Use index-based loc instead of copying metrics_df with task/example_id
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: extract compute_solve_rates, inline _off_policy_steps_by_task
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: inline solve_stats, use compute_solve_rates directly
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* also log per_env stop conditions
* minor
* style
* address bugbot
* min diff in changelog
* update changelog
* revert metrics_df
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Empty trajectories were filtered after sampling from the buffer, which
could yield incomplete groups and break the advantage computation's
assumption that each group has exactly `rollouts_per_example` rollouts.
Now empty trajectories are detected per-rollout as they complete. When
one is found, `rollouts_to_schedule` is incremented so the group
naturally re-fills via `_fill_inflight_requests`, and the group is only
yielded once it has the full count of non-empty rollouts.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: disk-backed image offloading for VLM orchestrator memory
Replace base64 image data in rollout trajectories with file paths
immediately after receiving from ZMQ. This eliminates the triangle
duplication problem where 15-turn rollouts store 120 copies of
screenshot base64 strings in memory.
Images are written to {output_dir}/assets/images/{sha256}.png and
deduped by content hash. The VLM image cache reads from disk instead
of decoding from base64 strings.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add VLM memory benchmark for disk offloading
Benchmark generates synthetic rollouts with triangle-duplicated
screenshots, simulates ZMQ msgpack roundtrip, and measures RSS
with and without disk-backed image offloading.
Results with 32 rollouts, 15 turns, 512x384 screenshots (~770KB each):
- Without offload: +2.9 GB (91 MB/rollout)
- With offload: +7.8 MB (0.24 MB/rollout)
- 99.7% memory reduction
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: ruff lint fixes in vlm_memory_bench
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: ruff format
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: remove benchmarks folder
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Revert "chore: remove benchmarks folder"
This reverts commit 79918131a8c06be55b5a7450a24f2ca82e9aa206.
* revert: restore benchmarks folder, only remove vlm_memory_bench.py
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: handle file:// URLs in _extract_images_from_messages
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: filter empty trajectory rollouts in scheduler
Empty trajectories consume batch slots without producing training signal.
Filter them after sampling so they don't count toward batch progress,
and track the count as a metric for observability.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* rename to empty_rollouts for consistency
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* remove empty batch retry logic from orchestrator
The scheduler already filters empty trajectories, so the orchestrator
should not silently retry on empty batches — better to fail fast.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Adds automated PR review using anthropics/claude-code-action@v1.
Reviews run on PR open/sync/reopen and responds to @claude mentions.
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* chore: move env packages to dedicated `envs` extras group
Move math-env and reverse-text from main dependencies into a new
`envs` optional-dependencies group alongside all other environment
packages used in configs (aime2024, aime2025, alphabet-sort, code-env,
color-codeword, logic-env, math-python, math500, science-env,
wiki-search). All sourced from the primeintellect index.
Install with: uv sync --extra envs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: remove primeintellect/ prefix from env IDs in configs
Envs are now installed directly via the envs extras group, so the
primeintellect/ prefix is no longer needed for runtime installation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: mark primeintellect index as explicit
Prevents uv from querying the primeintellect index for every package
during resolution, drastically speeding up uv sync/lock.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add configurable pre_run_command for SLURM jobs
Allow running a cleanup command on compute nodes before starting
the job (e.g. `sudo pkill -f vllm`). Configured via `slurm.pre_run_command`.
For multi-node jobs, the command runs on all nodes via srun.
Replaces the hardcoded `pkill -9 -f vllm` in the inference template
with the configurable option.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: tighten whitespace in template pre_run_command blocks
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: run pre_run_command on head node only, avoid shell quoting issues
Drop the srun bash -c wrapper from multi-node templates. The command
now runs directly on the head node (same as single-node), which avoids
single-quote injection when the user's command contains quotes.
Users who need all-nodes execution can wrap with srun themselves:
pre_run_command = "srun bash -c \"pkill -f vllm || true\""
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add CHANGELOG entry for slurm.pre_run_command
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add nodelist, exclude, account, and time SLURM options
Add commonly needed SLURM scheduling fields to SlurmConfig:
- nodelist: target specific nodes
- exclude: exclude specific nodes
- account: charge to a SLURM account
- time: set maximum wall time
Also extract common slurm fields into SlurmConfig.template_vars
to avoid duplicating them across every template.render() call.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: clean up Jinja2 whitespace for optional SBATCH directives
Use {%- if %} to strip leading newlines so no blank lines appear
when optional fields are unset.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: run pre_run_command after env setup in single-node templates
Single-node templates ran pre_run_command before cd, .env sourcing,
and venv activation. Move it after setup to match multi-node and
inference templates. Update docs to clarify execution context.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove orchestrator W&B resume ID warning
The warning about missing W&B run ID for orchestrator when resuming
training is not useful and creates noise.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove trainer W&B resume ID warning
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: replace warnings.warn with get_logger().warning in configs
Use prime-rl's logger instead of Python's warnings module for
config validation warnings.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: reduce orchestrator memory usage for VLM rollouts
The orchestrator's RSS grew unboundedly when processing VLM rollouts
with images (e.g. 1.2 GB → 25+ GB over 10 steps, spiking to 38 GB).
Three root causes:
1. Base64 image data in rollout prompts stayed alive through the entire
step pipeline (preprocessing, training batch, wandb logging). Now
stripped immediately after image extraction in _extract_images_from_examples.
2. Intermediate objects (PIL images, torch tensors, chunk results) in
_preprocess_images_batched were held simultaneously. Now freed eagerly
with del/clear() after each conversion step.
3. Python's GC and glibc malloc arenas retained freed memory across steps.
Now explicitly gc.collect() + malloc_trim(0) at end of each step.
Result: baseline 3-5 GB (stable), spikes 5-9 GB (bounded).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: extract strip_base64_images into a standalone function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: delete chunks before clearing images to actually free PIL objects
chunks holds shallow-copy references to the same PIL images, so
images.clear() alone doesn't free them during peak memory usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Update src/prime_rl/orchestrator/trajectories.py
Signed-off-by: hallerite <git@hallerite.com>
---------
Signed-off-by: hallerite <git@hallerite.com>
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
* Add arm64 support to Dockerfile and deps
- Swap builder base to multi-arch nvidia/cuda:12.8.1 image
- Add platform_machine markers to x86_64-only wheel deps
* Fix tzdata interactive prompt in arm64 build
* Fix tzdata interactive prompt in Docker build
* add arm64 flash-attn source build and expose max_num_seqs on inference CLI
* only target sm_100 for arm64 flash-attn build
* remove max_num_seqs, belongs in a separate PR
* also build flash-attn-3 from source for arm64, supports sm_100
* use pip for flash-attn-3, uv cant resolve torch match-runtime from git
* use pip for flash-attn-3: uv rejects match-runtime without static metadata
* link uv issue in dockerfile comment
* use venv pip for flash-attn-3, pip not on PATH in builder
* use uv run pip for flash-attn-3
* install pip into venv before using it for flash-attn-3
* fix arm64 flash-attn build: export env vars, add ninja
* fix: install python ninja package, export all env vars properly
* remove flash-attn-3 from arm64 build, fa4 (flash-attn-cute) is used instead
* Fix missing cutlass.utils.ampere_helpers on arm64 (#1948)
* Fix missing cutlass.utils.ampere_helpers on arm64
flash-attn.cute imports cutlass.utils.ampere_helpers but
nvidia-cutlass-dsl 4.4.1 doesn't ship that module. Copy it
from flashinfer's vendored cutlass which has the file.
* Expand Dockerfile comment explaining cutlass ampere_helpers workaround
* Reinstall flash-attn-cute after flash-attn on arm64 to fix namespace conflict (#1949)
* Pin flash-attn-cute to locked commit, upstream renamed package to flash-attn-4 (#1950)
* Upgrade flash-attn-cute for cutlass-dsl 4.4.1 backward pass fix (#1952)
* Upgrade flash-attn-cute to 7ed0898 for cutlass-dsl 4.4.1 compatibility
* Pin fix-flash-attn-cute.sh to same commit as pyproject.toml
* Pin flash-attn-cute to 2b5db43 for cutlass-dsl 4.4.1 compat and sm100 backward fix
* refactor: extract arm64 post-install logic into script
* skip arm64 script entirely on x86, trim comments
* update uv.lock
* revert pydantic-config to branch=main
* pin flash-attn==2.8.3 in arm64 post-install
* pin flash-attn-cute to e2743ab5, regenerate uv.lock
* align flash-attn-cute rev in scripts with pyproject.toml (e2743ab5)
* fix: modality-aware batch distribution to prevent FSDP deadlocks
When training multimodal models with FSDP, ranks must execute the same
operations at each step. If one rank processes a multimodal batch
(triggering the vision encoder all-gather) while another processes
text-only, training hangs. Fix by separating micro batches by modality,
padding each group independently, and distributing in strided order so
all ranks see the same modality at each step index.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* ruff format
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: disable timeout on admin httpx clients
Admin operations (weight updates, LoRA loading, NCCL broadcast) can block
for an unbounded amount of time — especially under load where vLLM servers
are slow to enter NCCL receive mode. The previous 1200s read timeout was
causing orchestrator crashes on heavy prod runs.
Also adds retry logic to _update_weights for 5xx responses, matching the
existing behaviour of load_lora_adapter.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* remove retry
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat: add Qwen3.5 support
Bump vLLM to >=0.16.1.dev (nightly) which includes Qwen3.5 model support.
This requires torch 2.10 (resolved from the existing >=2.9.0 pin), an
updated flash-attn wheel built against torch 2.10, and version overrides
for nvidia-cutlass-dsl and quack-kernels.
Bump transformers pin to 5c1c72b which includes a rope validation fix
for Qwen3.5 (https://github.com/huggingface/transformers/pull/44272).
Add a trainer monkey-patch for a transformers bug where Qwen3.5 passes
3D MRoPE position_ids to decoder layers instead of 2D text_position_ids,
which breaks flash attention and causes NaN gradients. The upstream fix
is pending: https://github.com/huggingface/transformers/pull/44399
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* apply patch for Qwen3.5 MoE model variants
* remove duplicated nvidia-cutlass-dsl override
* fix: patch Qwen3.5 MoE weight conversion mapping for broadcasting
* ruff
* change wheel
* fix vllm v0.16.1.dev (#1954)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* fix: use qwen3_coder tool parser for Qwen3.5 models
Qwen3.5 uses a different tool call format than Qwen3. Qwen3 uses
hermes-style JSON, but Qwen3.5 uses an XML-like format with
<function=name><parameter=arg> tags. Map all Qwen3.5 variants to
the qwen3_coder parser so tool calls are parsed correctly.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix for tool parser test
---------
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Johannes Hagemann <johannes@primeintellect.ai>
* chore: update pydantic-config for JSON dict CLI support
Update pydantic-config to latest main which adds support for passing
dict[str, Any] fields as JSON via CLI:
--inference.vllm-extra '{"custom_arg": "value"}'
Also switch source from pinned rev to branch = "main".
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: update pydantic-config lock to include JSON dict fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use space-separated list args for tyro CLI compatibility
tyro parses list[str] fields as space-separated values, not
comma-separated. Update the multi-node SLURM template and integration
test to match. Also fix snake_case --weight_broadcast.host to
kebab-case --weight-broadcast.host.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert unnecessary kebab-case change for weight_broadcast.host
Both snake_case and kebab-case are accepted by tyro, so keep the
original snake_case to minimize diff.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* bump vf (bb73f78, feature branch)
* fix: drop stale groups concurrently to avoid inflated cancellation count
The sequential drop_group loop allowed _fill_inflight_requests to add
new tasks to not-yet-dropped stale groups during yields, causing the
cancelled count to exceed max_inflight_rollouts. Using asyncio.gather
ensures all drops snapshot inflight_requests before any of them yield.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* bump vf (45fae8d, main)
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
In multi-turn TITO rollouts, prompt_token_ids are injected after
render_chat_request, bypassing vLLM's built-in context length
validation. When the prompt exceeds max_model_len, get_max_tokens
returns a negative value, causing a BadRequestError ("max_tokens must
be at least 1") that isn't recognized as an overlong prompt by the
verifiers client — aborting the rollout instead of truncating it.
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* first impl for dppo+kl
* fix ratio_type ref
* sum the loss
* set kl_tau=1e-3 by default
* fix
* change to ipo + remove type ignore
* update changelog
* fix
* update names
* add SLURM scheduling support for standalone inference entrypoint
Move inference entrypoint to src/prime_rl/entrypoints/inference.py following
the SFT/RL patterns. Add opt-in [slurm] and [deployment] config sections to
InferenceConfig for submitting inference as SLURM jobs. Supports single-node
and multi-node (independent vLLM replicas per node, no cross-node parallelism).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* use single inference template
* add dry run and remove launcher fields
* correctly resolve union/annotated types
* log msg
* export urls
* switch to 0.0.0.0
* fix vllm
* move
* update changelog
* pass seed
* align with sft/rl entrypoint
* use config dir helper
* update docs and skill for inference SLURM entrypoint
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add back writing config
* add comment
* Revert "add comment"
This reverts commit 1481510decd244174049e1392ca51c1b7b29b294.
* Revert "add back writing config"
This reverts commit a67e8dfe3e57f5906fee0cb6f8fd299c148ecca5.
* remove non-user facing changelog items
* fix ruff
* fix infer entrypoint
* bump pydantic_config
* multi node is 2 nodes by default
* use rev
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
The on-policy distillation docs referenced teacher_gpu_ids which was
removed from RLConfig and replaced by the [deployment] section with
num_teacher_gpus. Users following the docs would get a pydantic
extra_forbidden error.
Closes#1924
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* migrate config system from pydantic-settings to pydantic_config
Replace the custom pydantic-settings wrapper (BaseSettings, parse_argv,
toml_files inheritance) with the external pydantic_config library which
provides tyro-backed CLI parsing, @ syntax for TOML files, and deep merge
of configs + CLI overrides.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to fix-tyro branch and fix benchmark CLI args for tyro
- Switch dependency from refactor-tyro to fix-tyro branch (includes
validators moved upstream)
- Simplify config.py by removing validators now in pydantic_config
- Fix benchmark script to use tyro subcommand syntax for optional
nested configs (compile, ac, ac-offloading)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to include bare flag support for Optional configs
The benchmark script's --model.compile and --model.ac bare flags now
work without changes, thanks to upstream pydantic_config handling.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to main (includes AvoidSubcommands fix)
Fixes dict[str, Any] tyro parser errors and union subcommand issues.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to include sub-field override fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* 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>
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.
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>
* 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
* 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>
* 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
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>
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>
* 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>
* 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>
* 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>
* 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>
* 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>
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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
* 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>
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>
* 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>
* 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>
* 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>
* 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>
* 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
* 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>
* 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>
* 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>
* 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>
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>
* 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>
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>
* 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>
@logger.catch used loguru's default global logger, not the custom logger
created by setup_logger(). This meant fatal exceptions bypassed the JSON
formatter entirely. Move exception logging into clean_exit using get_logger(),
with a safe fallback to loguru's default if the logger isn't set up yet.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
- Avoid try/except blocks unless it's really necessary. It's fine that a program fails if something goes wrong as this helps us to catch non-obvious bugs and unforeseen side-effects earlier. You can add try catch on code that explicitly aims to be fault tolerant like adding retry mechanisms or explicit and intentional robustness.
- Do not add unnecessary comments. Especially do not try to explain code change that reflect your work process, do not refer to old code. "The code used to do that but now we are doing this" is not a pattern we want. Instead prefer to use targeted comments sparingly to explain ambiguous code.
## Zen of Python
remember the zen of python when writing code.
## Writing code
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Zen of Python**: remember the Zen of Python when writing code.
```
Beautiful is better than ugly.
Explicit is better than implicit.
@@ -34,14 +29,9 @@ Namespaces are one honking great idea -- let's do more of those!
## Running code
-All code should be runnable with `uv run` or `uv run <command>`.
-All dependencies should already be installed and pin in the lock file. If not, add it to pyproject.toml and run `uv sync --all-extras` to install it.
## CLI Usage
- Config files use `@` syntax: `uv run sft @ path/to/config.toml`
- For multi-GPU with torchrun: `uv run torchrun --nproc-per-node 2 src/prime_rl/trainer/sft/train.py @ path/to/config.toml`
- See the `toml-config` skill in `skills/` for full details on TOML structure, CLI overrides, and available commands.
-**Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
-**Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
## Skills
@@ -55,18 +45,10 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
## Git
Branch prefixes: `feature/`, `fix/`, `chore/`
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
## Releases
## GitHub
When preparing release notes:
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
1.**Style reference**: check the previous release (`gh release list --limit 1` then `gh release view <tag>`) to match the tone and formatting.
2.**Gather changes**: use `git log <last-tag>..origin/main --oneline --no-merges` to list all commits since the last release.
2.**Check for new commits**: always `git fetch origin main` and re-check right before publishing, since PRs may have been merged while drafting.
3.**Structure**: organize notes into numbered highlight sections (`# 1.`, `# 2.`, ...), then `# Breaking Changes`, `# Bug Fixes`, and `# Misc`.
4.**Highlights**: group related PRs under a single highlight. Use `##` subsections when a highlight contains multiple items (e.g. Performance & Parallelism). Keep the top highlights for the most impactful user-facing features.
5.**Config examples**: when referencing TOML config, verify the exact field names against the actual code or docs — don't guess.
6.**Links**: use clickable links for docs (`[docs/foo.md](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/docs/foo.md)`) and PR references (`[#1234](https://github.com/PrimeIntellect-ai/prime-rl/pull/1234)`).
7.**Contributors**: list all contributors ranked by number of commits, using their GitHub `@username`. Get usernames via the GitHub API, not git author names (which can be inconsistent).
8.**Draft first**: always create releases as `--draft` first, iterate on content, then publish.
- **`log.file` and `log.env_worker_logs` removed**: Removed `log.file` (from `LogConfig` and `SharedLogConfig`) and `log.env_worker_logs` (from `LogConfig`). Python file logging is replaced by deployment-level capture. Existing configs using these fields must delete them. Log paths unified: `.stdout` files renamed to `.log`, SLURM logs moved from `slurm/` to `logs/`. (2026-03-31)
- **`trainer.log.ranks_filter` (NEW)**: Added `ranks_filter: list[int]` to `TrainerLogConfig` (default: `[0]`). Controls which ranks appear in trainer console output via torchrun's `--local-ranks-filter`. (2026-03-31)
- **`wandb.log_extras.sample_ratio` / monitor sample logging defaults**: `wandb.log_extras.sample_ratio` is now actually applied to W&B sample-table logging via the shared monitor sampler (it was previously a no-op for WandB). Separately, the orchestrator no longer hard-caps sample logging to 8 rollouts before monitor-level sampling runs, so when monitor `sample_ratio` is `None`, monitors now receive and may log the full rollout batch for a step instead of at most 8 rollouts. This affects both W&B and Prime monitor sample logging behavior. (2026-03-27)
- **`[model.vlm].freeze_vision_encoder`**: Added to `VLMConfig`. Controls whether the vision encoder is frozen (default: `true`). When `false`, the vision encoder is trainable and FSDP-sharded per-block. Has no effect with LoRA. Moved from `[trainer.model].freeze_vision_encoder` into the VLM sub-config. (2026-03-25)
- **`loss_impl = "quack_fused"` (SFT)**: Added `quack_fused` option for the SFT `loss_impl` field. Uses quack-kernels for chunked linear + cross-entropy with CuTe DSL CUDA kernels, avoiding full logits materialization. Requires `quack-kernels` package. Does not support Gemma logit softcapping. Custom model impl (`model.impl = "custom"`) also gains quack RMSNorm acceleration on CUDA automatically. (2026-03-26)
- **`model.ac.targets`**: Removed the `mamba` selective activation checkpoint target and folded that behavior into the broader `linear_attn` target. Existing configs using `targets = ["mamba"]` will now fail validation at runtime with `ValueError`; switch them to `targets = ["linear_attn"]`. The `linear_attn` target description now covers supported token mixers outside the standard softmax-attention path, including NemotronH Mamba layers, Qwen3.5-MoE GatedDeltaNet layers, and AFMoE sliding-window attention layers. (2026-03-28)
- **`model.tp` (trainer `ModelConfig`)**: Removed from the trainer model config. Existing trainer configs must delete this field; it is no longer accepted. (2026-03-26)
- **`orchestrator.env[].num_workers`**: Added configurable env server worker count (`int | "auto"`, default: `"auto"`). When `"auto"`, scales based on concurrency (1 worker per 256 concurrent rollouts). Only used when the orchestrator spawns the env server (i.e. `address` is not set). (2026-03-25)
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
- **`model.ep_comm_backend`**: Added expert-parallel communication backend selection. Accepted values are `torch` (default, uses TorchTitan all-to-all collectives) and `deepep` (uses DeepEP custom kernels). This field only affects configurations with expert parallelism enabled via `model.ep > 1`. (2026-03-22)
- **`model.deepep_num_sms`**: Added DeepEP SM allocation control for intranode dispatch/combine kernels (default: `20`, minimum: `1`). This field is only used when `model.ep_comm_backend='deepep'`; it also determines the internode RDMA channel count (`num_channels = num_sms / 2`). (2026-03-22)
- **`model.deepep_token_chunk_size`**: Added optional token chunk size for DeepEP MoE pipelining (default: `None`, minimum: `1`). When set, DeepEP dispatch for chunk `i+1` overlaps expert compute for chunk `i`. This field is only used when `model.ep_comm_backend='deepep'`. (2026-03-22)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently `norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
- **`orchestrator.verification.enabled`**: Added top-level rollout verification switch. `orchestrator.buffer.skip_verification` has been removed; use `verification.enabled = false` instead. When disabled, rewards are always 0 and reward-dependent buffer features (`online_difficulty_filtering`, `easy_threshold`, `hard_threshold`) must be unset (2026-03-03)
- **`client.dp_rank_count`**: Added configuration for data-parallel inference routing. When > 1, each `client.base_url` is expanded into `dp_rank_count` logical clients and pinned via `X-data-parallel-rank` to keep multi-turn rollouts on a consistent DP rank (default: 1) (2026-03-03)
- **`model.lora`**: Moved from `model.experimental.lora` to `model.lora` (no longer experimental) (#1440, 2025-12-16)
- Auto-set `api_server_count=1` on inference when LoRA is enabled, because vLLM doesn't support hotloading for multiple API servers (#1422, 2025-12-17)
- **`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)
- **`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)
- **`[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)
- **`sft.val`**: Added optional periodic SFT validation with `val/loss` and `val/num_tokens` logging. Configure via `sft.val.data` (validation dataset) and `sft.val.interval` (every N steps, default 50). Runs the full validation dataset each pass. (2026-02-26)
- **`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)
- **Inference entrypoint**: Moved from `prime_rl.inference.server` to `prime_rl.entrypoints.inference`. No change to CLI usage (`uv run inference`) (2026-02-26)
- **`[slurm]` (inference)**: Added SLURM configuration to `InferenceConfig`. When present, `uv run inference` generates and submits an sbatch script instead of running locally. Each SLURM node runs an independent vLLM replica (no cross-node parallelism) (2026-02-26)
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
- **`orchestrator.teacher_rollout_model`**: Added optional external rollout model configuration. When set, rollouts are generated from this endpoint/model instead of the student inference server. Accepts a `TeacherRolloutModelConfig` with `client` and `model` sub-fields, or `None` (default: `None`) (2026-02-26)
- **`trainer.loss.type = "sft"`**: Added SFT loss variant. Set `trainer.loss.type = "sft"` to use masked negative log-likelihood loss instead of the default RL loss (2026-02-26)
- **`trainer.loss.type = "custom"`**: Added custom loss variant. Set `trainer.loss.type = "custom"` with `import_path` (e.g. `"my_module.my_loss"`) and optional `kwargs` to use an external loss function (2026-02-26)
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
- **`trainer.ckpt.skip_optimizer`**: Added flag to skip loading optimizer states when resuming training. When set, only the model weights are loaded from the checkpoint. (2026-03-24)
@@ -29,13 +29,37 @@ PRIME-RL: Async RL Training at Scale
## Overview
PRIME-RL is a framework for large-scale asynchronous reinforcement learning. It is designed to be easy-to-use and hackable, yet capable of scaling to 1000+ GPUs. Beyond that, here is why we think you might like it:
PRIME-RL is a framework for large-scale reinforcement learning. It is designed to be easytouse and hackable, yet capable of scaling to 1000+ GPUs. Here is what we think sets it apart:
1. Fully asynchronous RL for high-throughput agentic training at scale.
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
## Models support
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
1. Integrates natively with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments via the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars)
2. Supports end-to-end post-training, including SFT and RL training and evals
3. Multi-node deployment with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) training and [vLLM](https://github.com/vllm-project/vllm) inference backend
4. Designed for asynchronous agentic RL training at scale
5. Hackable, modular and extensible by nature
## Setup
@@ -160,12 +184,27 @@ uv run hf auth login
## Training Examples
We provide end-to-end training examples in the [`examples`](examples) directory to highlight features of the framework and guide you through the process of training your own models.
### Basic Training: 1 to 8 GPUs
Follow this guide to learn the basics of Prime-RL. You can train your own models on 1 to 8 GPUs. Ideal for getting started and exploring the capabilities of the framework. These guides cover most use cases -- single-turn, multi-turn, tool calling, etc. -- on toy environments and small models.
1. [**Reverse Text**](examples/reverse_text/README.md): Train `Qwen3-0.6B` to reverse a small chunk of text. Demonstrates tiny-scale single-turn SFT and RL training. Can be trained on a single consumer GPU in a few minutes, and is ideal for getting started.
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...*
### Advanced Training: 32 - 2048 GPUs:
Follow this guide to train large models on hard reasoning and agentic / swe environments.
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
1. [**Qwen 3 30B - A3B Math**](examples/qwen30b_math/README.md): Train `Qwen3-30B-A3B` to solve hard math problems.
2. [**Qwen 3 30B - A3B SWE**](examples/qwen30b_swe/README.md): Train `Qwen3-30B-A3B` to solve hard SWE problems.
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
## Docs
@@ -179,7 +218,9 @@ Check out the [docs](docs) directory for in-depth guides on how to use PRIME-RL.
- [**Checkpointing**](docs/checkpointing.md) - Saving and resuming training from checkpoints
- [**Benchmarking**](docs/benchmarking.md) - Performance benchmarking and throughput measurement
- [**Deployment**](docs/deployment.md) - Training deployment on single-GPU, multi-GPU, and multi-node clusters
We rely on vLLMs multi-node deployment primitives and load balancing for multi-node deployments. Currently, vLLM supports multi-node data parallel deployment ([docs](https://docs.vllm.ai/en/v0.10.0/serving/data_parallel_deployment.html)).
For SLURM-based inference deployment, see the [SLURM guide](slurm.md#inference-examples). Each node runs an independent vLLM replica — no manual coordination needed.
For manual multi-node deployment without SLURM, we rely on vLLM's multi-node data parallel deployment primitives ([docs](https://docs.vllm.ai/en/v0.10.0/serving/data_parallel_deployment.html)).
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
@@ -281,7 +283,7 @@ Of course, you can further scale up the number of nodes used by the trainer and
@@ -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
@@ -50,7 +50,7 @@ For more details on multi-node deployment options, see the [deployment](deployme
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
To start an SFT training, you need to prepare a dataset in [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) (we do not support any other format). Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
On a single GPU, start the training with the `sft` entrypoint
prime-rl uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging with a global logger pattern. Logs are written to both console and files under `{output_dir}/logs/`. For RL training, we recommend streaming file logs into tmux panes (as set up by `tmux.sh`).
## tmux helper (`scripts/tmux.sh`)
`scripts/tmux.sh` sets up a tmux session for RL runs with **three panes (one per subprocess)**:
prime-rl uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging with a global logger pattern. All logs are captured at the deployment level (stdout/stderr redirection for local, `tee` for SLURM) under `{output_dir}/logs/`. For RL training, we recommend streaming logs into tmux panes (as set up by `tmux.sh`).
## Logger Architecture
@@ -20,7 +12,7 @@ We use a **singleton pattern** with a module-level global logger instance (`_LOG
1.**`setup_logger(log_level, log_file)`** - Initializes the global logger exactly once:
- Creates an isolated loguru `Logger` instance (not the default `loguru.logger`) to prevent third-party code from hijacking our logs
- Adds a stdout handler with colorized output
- Optionally adds a file handler (deletes existing file first)
- Raises `RuntimeError` if called twice
1.**`get_logger()`** - Returns the global logger instance. Always works — if `setup_logger` hasn't been called yet, it initializes a default logger automatically. Safe to call from any module at any time.
2.**`get_logger()`** - Returns the global logger instance:
-Raises `RuntimeError` if `setup_logger` hasn't been called yet
-Safe to call from any module after initialization
2.**`setup_logger(log_level)`** - Configures (or reconfigures) the global logger:
-Creates an isolated loguru `Logger` instance (not the default `loguru.logger`) to prevent third-party code from hijacking our logs
-Adds a stdout handler with colorized output (or JSON output if `json_logging=True`)
- Can be called multiple times — cleans up the previous logger before creating a new one
3.**`reset_logger()`** - Resets the global logger to `None`:
- Used in subprocesses that inherit parent state (e.g., env workers)
- Used in tests between test cases
## RL Log File Structure
## Log File Structure
For RL training, logs are organized by component:
Logs are captured at the deployment level — the entrypoint redirects subprocess stdout/stderr to files (local) or `tee` captures them (SLURM). The structure is consistent across deployment types: `logs/trainer.log` and `logs/inference.log` always exist, regardless of whether the run is local or multi-node SLURM.
| Component | Log Path | Description |
|-----------|----------|-------------|
| **RL (parent)** | `logs/rl.log` | Main process that spawns subprocesses |
| **Inference** | `logs/inference.stdout` | vLLM inference server stdout/stderr |
Environment are run via `vf.EnvServer` in separate processes. By default, each environment logs to a file in its run directory under `{output_dir}/run_default/train/{env_name}.log` and `{output_dir}/run_default/eval/{env_name}.log`. The log verbosity can be controlled with `orchestrator.log.vf_level`.
You can also use torchrun's native log redirection:
Environment logs live under `logs/envs/train/{env_name}/` and `logs/envs/eval/{env_name}/`. Env log verbosity is controlled by `orchestrator.log.vf_level`.
```bash
uv run torchrun \
--local-ranks-filter 0\
--nproc-per-node 8\
--log-dir outputs/torchrun \
--redirects 3\
--tee 3\
...
```
Only rank 0 output is shown in `trainer.log`. Per-rank logs from all ranks are available under `logs/trainer/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`, written by torchrun's `--log-dir`.
This writes to `outputs/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`.
## tmux helper (`scripts/tmux.sh`)
`scripts/tmux.sh` sets up a tmux session for RL runs with **four panes**:
While most of our parallelism techniques in prime-rl are designed to scale training up (FSDP, EP, CP, ...), we also provide many tools to scale training down that allow training large MoE models on a limited amount of GPUs.
These techniques target the trainer part of prime-rl.
## TLDR: config to use for maximum memory usage reduction with correct throughput
```toml
[trainer.model]
impl="custom"
attn="flash_attention_2"
fused_lm_head_token_chunk_size=1024
ep=8
cp=2
optim_cpu_offload=true
[trainer.model.compile]
[trainer.model.ac]
freq=1
[trainer.model.ac_offloading]
max_inflight_activations=1
```
## Activation checkpointing
Activation checkpointing discards intermediate activations during the forward pass and recomputes them during the backward pass, trading compute for memory.
To enable it, use:
```toml
[trainer.model.ac]
freq=1
```
`freq` controls how often layers are checkpointed: every `freq` layers. Lower values yield lower memory usage (e.g. `freq = 1` checkpoints every layer).
## Activation offloading
Activation offloading offloads the activations to CPU to reduce the memory usage of the trainer. It can be used in combination with activation checkpointing.
To enable it, use:
```toml
[trainer.model.ac]
freq=1
[trainer.model.ac_offloading]
max_inflight_activations=5
```
## Chunk loss
Chunk loss splits the loss computation into smaller chunks to reduce the memory usage of the trainer.
To enable it, use:
```toml
[trainer.model]
fused_lm_head_token_chunk_size=auto
```
## Expert parallelism
While expert parallelism splits the weights of the experts across all GPUs like FSDP, using EP still reduces memory usage by reducing the communication size and therefore the FSDP buffer.
EP is only available for models with MoE layers using the custom model implementation.
```
[trainer.model]
impl = "custom"
ep = 8
```
## Context parallelism
Context parallelism splits the context into smaller chunks to reduce the memory usage of the activations. We don't advise using CP across multiple nodes (i.e., increasing CP beyond 8).
CP is only available for certain models and only with the custom model implementation.
```
[trainer.model]
impl = "custom"
cp = 2
```
We recommend CP 2 or CP 4 for most 128K sequence length training runs. Can be pushed to 8.
## torch compile
Enabling torch.compile can reduce the memory usage for certain model architectures, especially MoE with the custom model implementation.
```
[trainer.model.compile]
```
## CPU Optimizer offloading
Offloading the optimizer states to CPU can reduce the memory usage of the trainer significantly, especially at low GPU counts where the optimizer states take a lot of memory as they won't be sharded enough.
In RL, in contrast with pretraining, we end up with many gradient accumulation steps, so the cost of offloading the optimizer states is not as high as in pretraining, and indeed barely noticeable.
```
[trainer.optim]
optim_cpu_offload = true
```
## :warning: FSDP CPU offloading
FSDP CPU offloading offloads the parameters, gradients, and optimizer states to CPU to reduce the memory usage of the trainer.
This will make training significantly slower and is not recommended most of the time.
```
[trainer.model]
fsdp_cpu_offload = true
```
## :warning: Lora training
LoRA training significantly reduces the memory usage of the trainer at the cost of smaller gradient updates.
Enable VLM mode by adding a `[model.vlm]` section. Both fields are required — they tell prime-rl where the vision encoder and language model live on the model object:
```toml
[model]
name="Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr="model.visual"
language_model_attr="model.language_model"
```
For the registered models in the table above, use the attrs shown there. For custom VLMs, check your model's structure with `model.named_children()`.
Both fields are dotted attribute paths resolved on the loaded model. A bad path raises a `ValueError` immediately — there are no silent fallbacks.
The weight key prefix for NCCL broadcasting is derived automatically as `{language_model_attr}.layers.`.
To add permanent support for a new model family, add an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
## Current Limitations
- **No SFT support**: Supervised fine-tuning is not yet supported for VLM models. Only RL training is available.
- **Vision encoder is frozen by default**: The vision encoder is frozen during training by default. Set `freeze_vision_encoder = false` in `[model.vlm]` to make it trainable. When unfrozen, the vision encoder is FSDP-sharded per-block for proper gradient flow. Note: this has no effect when using LoRA.
- **Vision encoder is frozen**: The vision encoder is automatically frozen during training. Only the language model is trained.
- **No multimodal-safe truncation**: Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` are passed through unchanged. If a multimodal sample exceeds `seq_len`, image tokens can be dropped while image tensors still describe the full set of images. Ensure `seq_len` covers your longest VLM samples.
- **No multimodal-safe truncation**: Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` are passed through unchanged. If a multimodal sample exceeds `seq_len`, image tokens can be dropped while image tensors still describe the full set of images. Ensure `seq_len` covers your longest VLM samples or avoid overlong rollouts.
- **Optimization dtype must be bfloat16**: Set `optimization_dtype = "bfloat16"` and `reduce_dtype = "bfloat16"` in your trainer config.
- **The images that the VLM sees are not logged**
- **Higher KL mismatch with multi-image inputs**: VLM training exhibits higher KL mismatch compared to text-only, especially with multiple images.
- **Optimization dtype must be bfloat16**: VLM models must load in bfloat16 to match vLLM inference. If the trainer uses a different dtype, the vision encoder produces different `pixel_values`, causing a mismatch between inference and training. A workaround would be to propagate the `pixel_values` computed by vLLM to the trainer, but this is more involved. For now, set `optimization_dtype = "bfloat16"` and `reduce_dtype = "bfloat16"` in your trainer config.
- **Images are not logged**: The images the VLM sees during training are not logged to monitors.
- **Higher KL mismatch with multi-image inputs**: VLM training exhibits higher KL mismatch between inference and trainer logprobs compared to text-only models, especially with multiple images per sample. We are investigating the root cause. The existing importance ratio masking thresholds should handle reasonable mismatches.
## How Multi-Turn VLM RL Training Works
## How Multi-Turn VLM Training Works
VLM training uses the same `interleave_rollout` path as text-only models. Multi-turn trajectory steps are merged into a single training sample wherever the extension property holds (consecutive steps share a token prefix). When extension breaks (e.g., due to context compaction), a new sample is started automatically.
VLM training uses the same `interleave_rollout` path as text-only models. Multi-turn trajectory steps are merged into a single training sample wherever the extension property holds.
Images are handled via a `VLMImageCache` built once per batch:
1.**Extract**: Base64 images are decoded from trajectory step prompts into PIL images. Since prompts are cumulative, only new images per step are extracted.
2.**Preprocess**: All images are processed in a single batched call through the HuggingFace image processor, producing `pixel_values` (patches) and `image_grid_thw` (grid dimensions).
3.**Attach**: Each training sample receives the cumulative `pixel_values` up to its last merged step. When steps are merged, the sample's images are updated to include all images seen so far.
1.**Extract**: Base64 images are decoded from trajectory step prompts into PIL images.
2.**Preprocess**: Images are processed through the HuggingFace image processor, producing `pixel_values` and `image_grid_thw`.
3.**Attach**: Each training sample receives the cumulative `pixel_values` up to its last merged step.
This works correctly for all combinations: images in early turns with text-only follow-ups, images appearing mid-conversation, new images accumulating across turns, and interleaved agents with separate image streams.
Each multimodal sample becomes its own micro-batch during training (no packing with other samples) since image tensor sizes vary per sample.
Each multimodal sample becomes its own micro-batch during training (no packing) since image tensor sizes vary.
## vLLM Configuration
`VLLM_WORKER_MULTIPROC_METHOD=spawn` is required for VLM inference. This is set automatically in `src/prime_rl/inference/config.py`, so if you use `uv run rl @ ...` it works out of the box, but if you start the vLLM server yourself, make sure this environment variable is set.
`VLLM_WORKER_MULTIPROC_METHOD=spawn` is required for VLM inference. This is set automatically when using `uv run rl @ ...`, but if you start the vLLM server yourself, make sure this environment variable is set.
@@ -6,10 +6,11 @@ For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/
## Quick Start
Add `teacher_gpu_ids` and set `teacher_tau > 0`:
Add `num_teacher_gpus` to `[deployment]` and set `teacher_tau > 0`:
```toml
teacher_gpu_ids=[2,3]
[deployment]
num_teacher_gpus=2
[trainer.loss]
teacher_tau=0.5
@@ -18,7 +19,8 @@ teacher_tau = 0.5
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
```toml
teacher_gpu_ids=[2,3]
[deployment]
num_teacher_gpus=2
[teacher_inference.model]
name="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
@@ -47,26 +49,68 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
The `rl`, `sft`, and `inference` entrypoints all 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"` |
| `nodelist` | Comma-separated list of specific nodes to run on (`--nodelist`) | `None` |
| `exclude` | Comma-separated list of nodes to exclude (`--exclude`) | `None` |
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.
---
## Inference Examples
### Single-node SLURM
Run a vLLM server on a single allocated node:
```toml
output_dir="/shared/outputs/my-inference"
[model]
name="Qwen/Qwen3-8B"
[parallel]
tp=8
[slurm]
job_name="my-inference"
```
```bash
uv run inference @ inference_slurm.toml
```
### Multi-node SLURM
Each node runs an independent vLLM replica. TP and DP must fit within a single node — there is no cross-node parallelism.
```toml
output_dir="/shared/outputs/my-inference"
[model]
name="PrimeIntellect/INTELLECT-3-RL-600"
[parallel]
tp=4
dp=2
[deployment]
type="multi_node"
num_nodes=4
[slurm]
job_name="my-inference"
```
After submission, the SLURM template prints the inference URLs for all nodes (one per node).
### Dry run
Use `dry_run = true` to generate the sbatch script without submitting:
```bash
uv run inference @ config.toml --dry-run true
```
---
## 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
# All deployment types (trainer.log and inference.log are symlinks for multi-node)
tail -F {output_dir}/logs/trainer.log
tail -F {output_dir}/logs/orchestrator.log
tail -F {output_dir}/logs/inference.log
# Multi-node: per-node logs
tail -F {output_dir}/logs/trainer/node_*.log
tail -F {output_dir}/logs/inference/node_*.log
# Multi-node inference: per-replica router logs
tail -F {output_dir}/logs/inference/router_*.log
```
For convenience, a tmux launcher sets up a session with all log streams:
This example guides you through reproducing the [INTELLECT-3.1](https://huggingface.co/PrimeIntellect/INTELLECT-3.1) RL training on top of [GLM-4.5-Air-Base](https://huggingface.co/zai-org/GLM-4.5-Air-Base).
## Requirements
You need access to a Slurm cluster with at least 16 nodes to run this example. Each node must have a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
If you don't have access to that many nodes, you can downscale inference and training nodes to lower values and scale down the batch size accordingly.
For training, going below 4 nodes might cause OOM.
You also need to have prime-rl cloned on your cluster into the shared filesystem.
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
The [mini-swe-agent-plus](https://github.com/PrimeIntellect-ai/sandbox-mini-swe-agent-plus) environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview).
You will need to create a sandbox account and add the credentials to the `.env` file.
Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
This example guides you through deploying a highly efficient GLM-5 RL training with PD disaggregation and FP8 inference on agentic SWE tasks.
## Requirements
You need access to a Slurm cluster with at least 32 nodes to run this example. Each node must have a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need to have prime-rl cloned on your cluster into the shared filesystem.
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
The [mini-swe-agent-plus](https://github.com/PrimeIntellect-ai/sandbox-mini-swe-agent-plus) environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview).
You will need to create a sandbox account and add the credentials to the `.env` file.
Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
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 \
This example guides you through RL training [MiniMax-M2.5](https://huggingface.co/MiniMaxAI/MiniMax-M2.5) on agentic SWE tasks.
## Requirements
You need access to a Slurm cluster with at least 16 nodes to run this example. Each node must have a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need to have prime-rl cloned on your cluster into the shared filesystem.
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
The [mini-swe-agent-plus](https://github.com/PrimeIntellect-ai/sandbox-mini-swe-agent-plus) environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview).
You will need to create a sandbox account and add the credentials to the `.env` file.
Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on math tasks.
## Requirements
You need access to a Slurm cluster with at least 4 nodes to run this example. Each node must have a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need to have prime-rl cloned on your cluster into the shared filesystem.
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on agentic SWE tasks.
## Requirements
You need access to a Slurm cluster with at least 4 nodes to run this example. Each node must have a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need to have prime-rl cloned on your cluster into the shared filesystem.
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
The [mini-swe-agent-plus](https://github.com/PrimeIntellect-ai/sandbox-mini-swe-agent-plus) environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview).
You will need to create a sandbox account and add the credentials to the `.env` file.
Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
@@ -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.


*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.


*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
description:How the prime-rl config system works — TOML files, CLI, config composition, and special patterns. Use when creating configs, debugging config errors, or overriding values via CLI.
---
# Config
prime-rl uses `pydantic_config` (combines `tyro` and `pydantic`) for configuration.
## Use configs
Every entrypoint accepts TOML files via `@` syntax and CLI overrides to configure it.
```bash
# Configure RL training with a TOML file
uv run rl @ examples/reverse_text/rl.toml
# Override specific fields via CLI
uv run rl @ examples/reverse_text/rl.toml --max-steps 50
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
```
Nested configs can be loaded for specific sections:
```bash
uv run rl --model @ model.toml --data @ data.toml
```
Mixed composition works too:
```bash
uv run rl @ base.toml --trainer @ trainer_override.toml --trainer.lr 1e-3
```
Merging is deep — unset fields in the override are preserved from the base config.
## Inspect & validate configs
Use `--help` to see all available fields and their defaults. When combined with a config file, defaults reflect the TOML values:
```bash
uv run rl --help # shows class defaults
uv run rl @ examples/reverse_text/rl.toml --help # shows defaults from TOML
```
Use `--dry-run` to validate and dump the fully resolved config:
```bash
uv run rl @ examples/reverse_text/rl.toml --dry-run --output-dir /tmp/test
# Writes resolved TOML to /tmp/test/configs
```
## Naming
CLI uses kebab-case (`--model.max-model-len`), TOML uses snake_case (`max_model_len`). Both refer to the same field.
## General rules
- **Fail early**: incompatible option combinations (e.g. CP requires flash attention, NCCL broadcast requires async level 1) should raise in `model_validator` at config resolution time, not at runtime. When adding new constraints, add a validator to the config class.
- **Deprecation**: when renaming or removing config fields, emit a deprecation warning with a clear migration path (e.g. "field X is deprecated, use Y instead"). Do not silently drop fields — help users update their configs.
## Important patterns
### Boolean fields
```bash
uv run inference --model.enforce-eager # sets to true
uv run inference --model.no-enforce-eager # sets to false
```
In TOML, booleans must be explicit:
```toml
[model]
enforce_eager=true
```
### None fields
TOML has no null type. Use the string `"None"`:
```toml
max_model_len="None"
```
On the CLI, pass `None` as a plain string:
```bash
uv run inference --model.max-model-len None
```
### List fields
In TOML, use `[[double brackets]]` (array of tables) for lists of objects:
```toml
[[orchestrator.env]]
id="reverse-text"
[[orchestrator.env]]
id="math-env"
```
On the CLI, list items are indexed: `--env.0.id reverse-text --env.1.id math-env`.
### Dict fields
In TOML, use a section:
```toml
[vllm_extra]
key1="value1"
key2=123
```
On the CLI, pass as a JSON string:
```bash
uv run inference --vllm-extra '{"key1": "value1", "key2": 123}'
```
### Discriminated unions
Some config fields use discriminated unions (e.g. loss type, data type). Set the `type` field to select the variant:
```toml
[trainer.loss]
type="sft"
[data]
type="fake"
batch_size=2
```
On the CLI:
```bash
uv run sft --data.type fake --data.batch-size 4
```
If you wish to configure values of the default variant, you don't need to set the `type` field.
### Model fields
For `BaseModel | None` fields (like `[ckpt]`, `[wandb]`, `[compile]`), a bare flag enables them with defaults:
```bash
uv run rl @ config.toml --model.compile # enables compilation with defaults (fullgraph = false)
uv run rl @ config.toml --model.compile.fullgraph # enables compilation and sets nested field (fullgraph = true)
```
In TOML, an empty section header does the same:
```toml
[ckpt]# enables checkpointing with defaults
```
## Key files
-`src/prime_rl/utils/config.py` — re-exports `BaseConfig` and `cli` from pydantic_config
-`src/prime_rl/configs/` — all domain-specific config classes
-`configs/debug/` — minimal debug configs for testing
-`examples/` — full example configs for various tasks
description:All available prime-rl entrypoints — what they do, how to launch them, and which config class they use. Use when running commands, launching training, or starting servers.
---
# Entrypoints
All entrypoints are run via `uv run <command>` and accept TOML configs via `@ path/to/config.toml` with CLI overrides. See the `config` skill for config system details.
## `rl` — RL training
Orchestrates the complete RL loop: launches inference server, orchestrator, and trainer as subprocesses.
```bash
uv run rl @ examples/reverse_text/rl.toml
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml # with SLURM
uv run rl @ examples/reverse_text/rl.toml --dry-run # generate scripts without running
description:Start and test the prime-rl inference server. Use when asked to run inference, start vLLM, test a model, or launch the inference server.
---
# Inference Server
## Starting the server
Always use the `inference` entry point — never `vllm serve` or `python -m vllm.entrypoints.openai.api_server` directly. The entry point runs `setup_vllm_env()` which configures environment variables (LoRA, multiprocessing) before vLLM is imported.
```bash
# With a TOML config
uv run inference @ path/to/config.toml
# With CLI overrides
uv run inference --model.name Qwen/Qwen3-0.6B --model.max_model_len 2048 --model.enforce_eager
# Combined
uv run inference @ path/to/config.toml --server.port 8001 --gpu-memory-utilization 0.5
```
## Custom endpoints
The server extends vLLM with:
-`/v1/chat/completions/tokens` — accepts token IDs as prompt input (used by multi-turn RL rollouts)
-`/update_weights` — hot-reload model weights from the trainer
-`/load_lora_adapter` — load LoRA adapters at runtime
-`/init_broadcaster` — initialize weight broadcast for distributed training
## Testing the server
```bash
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json"\
-d '{
"model": "Qwen/Qwen3-0.6B",
"messages": [{"role": "user", "content": "Hi"}],
"max_tokens": 50
}'
```
## 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/inference/vllm/server.py` — FastAPI routes and vLLM monkey-patches
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.