Compare commits

...
Author SHA1 Message Date
Matej SirovatkaandGitHub b92c2128dd Feat: add weigh transfer fix (#2099)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: add weigh transfer fix

* Fix style
2026-03-25 18:01:05 +01:00
rasdaniandGitHub c2b99e69ce refactor: use AutoModelForImageTextToText to configure VLMs (#2098)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-25 00:24:54 -07:00
ecd0809280 feat: disaggregated prefill-decode inference with multi-replica support (#2030)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-24 23:21:22 -07:00
JannikStandGitHub 381733e0cf fix: terminate process on fatal orchestrator error (#2092)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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
2026-03-25 03:54:52 +01:00
rasdaniandGitHub 27c35b1ce1 fix: hybrid CP for Qwen3.5 MoE (DeltaNet + attention) (#2097)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-25 03:29:33 +01:00
halleriteandGitHub b7afd84024 perf: run VLM image preprocessing in thread to unblock event loop (#2065)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-24 19:14:13 -07:00
Matej SirovatkaandGitHub e7adec38f0 Revert exclude none (#2095)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Revert "Enable none in config (#2093)"

This reverts commit a25b3e7a18.

* Revert "Fix/none in list (#2094)"

This reverts commit 4f612601f6.

* fix conflict
2026-03-25 02:12:49 +01:00
Matej SirovatkaandGitHub 4f612601f6 Fix/none in list (#2094)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Enable none

* Fix: convert none in a list correctly too

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-03-25 01:55:36 +01:00
Matej SirovatkaandGitHub a25b3e7a18 Enable none in config (#2093)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-25 01:37:29 +01:00
JannikStandGitHub 692dfc8a4b fix mamba-ssm build by using CUDA torch in build env (#2091)
Release / Push CUDA image to Docker (push) Canceled after 0s
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.
2026-03-24 17:33:11 -07:00
2ddb1c8199 feat: add NemotronH models to tool call parser map (#2089)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-24 16:52:36 -07:00
53a8b45660 feat: hybrid CP for Qwen3.5 MoE (DeltaNet + attention) (#2080)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-24 16:45:40 -07:00
c2dfc338c3 feat: add NemotronH (Nemotron-3-Super-120B-A12B) model support (#2046)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-24 16:44:08 -07:00
f414d9ae49 fix: handle eval rollout failures without crashing the orchestrator (#2086)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-24 23:05:58 +01:00
Matej SirovatkaandGitHub 60f01a0468 Feat: skip optimizer load (#2087)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-24 15:05:44 -07:00
halleriteandGitHub d803065204 feat: add explicit vlm config flag for VLM detection (#2063)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-23 22:40:44 -07:00
rasdaniandGitHub 19511dc2b0 fix: don't constrain VLM dtype for SFT (#2079)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: don't constrain VLM dtype for SFT

* changelog
2026-03-24 01:38:44 +01:00
rasdaniandGitHub 7ef29a7660 feat: accept messages column for SFT (#2074)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: accept `messages` column for SFT

* return list instead of tuple

* elif prompt
2026-03-23 22:47:13 +01:00
rasdaniandGitHub 7e853195ea fix: scheduler test fixture drift after enable_policy_updates (#2078)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-23 22:46:38 +01:00
9c25ce2ca1 feat: GPT-OSS support with LoRA + DP fixes (#2073)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-23 14:40:25 -07:00
3dd48be5bf feat: integrate FP8 weight transfer format (#2038)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: integrate GLM5 FP8 kernel-format weight transfer

* refactor: clean fp8 transfer flow and model-name split

* refactor: unify quantized transfer config and enforce strict kernel updates

* fix: restore pre-existing nccl receiver log levels

* refactor: unify preprocess flow and validate kernel transfer method

* refactor: simplify transfer validation and flatten nccl preprocess flow

* refactor: use module-level preprocess functions for nccl broadcast

* refactor: split nccl worker loaders and postprocessors

* chore: remove fp8 weight transfer config tests per PR review

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

---------

Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 18:46:59 -07:00
40da51a235 SFT distillation: bug fixes, VLM support, and pretokenization optimization (#2053)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-21 17:49:00 -07:00
rasdaniandGitHub bb4c23b122 breakdown difficulty pool metrics per env (#2070)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-21 23:55:10 +01:00
1bc1021a0f validate VLM dtype in configs (#2060)
Release / Push CUDA image to Docker (push) Canceled after 0s
* validate VLM dtype in configs

* ruff

* Add changelog entry for VLM bfloat16 validation requirement

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

* Remove VLM bfloat16 dtype test

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: rasdani <rasdani@users.noreply.github.com>
2026-03-21 23:01:05 +01:00
Philipp NormannandGitHub 4875c101c2 Add SFT LoRA support (#1849)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add SFT LoRA support

* Fix ruff formatting and add missing comment

* Use MultiRunManager for SFT LoRA adapter export

* Rename SFT LoRA run adapter export helper
2026-03-20 20:18:15 -07:00
Shayon MukherjeeandGitHub fc6fd48fae Fix: typo in comment for sample_ratio (#2058)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-20 22:34:25 +01:00
DominikandGitHub d5c7240676 Feature: Add platform integration. (#1896)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-20 02:34:11 +01:00
3dcff28e02 fix: use mean().mean() for console metrics to match wandb (#2056)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-19 18:20:49 -07:00
JannikStandGitHub 58f4b37d5b Add router_url support for elastic inference pool (#2049)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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.
2026-03-20 02:11:39 +01:00
47f6bb8307 fix: remove misleading orchestrator throughput metric (#2048)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-19 13:10:28 -07:00
1f6de8fff4 chore: bump verifiers to 1960e77 (#2051)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 11:53:03 -07:00
c1bbbf9231 add Group Relative Reward Rescaling as length penalty (#2029)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-19 02:00:36 +01:00
halleriteandGitHub f399e2664c add weights-only checkpointing (#2033)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-18 15:10:37 -07:00
Mika SenghaasandGitHub 0f236d322c shared wandb mode (#2044)
Release / Push CUDA image to Docker (push) Canceled after 0s
* poc of shared run mode

* deprecate wandb.id

* style

* use step metric to align x-axis

* remove flush + fix signatures

* init monitor earlier

* retry shared run creation

* add note

* update changelog
2026-03-18 13:47:11 -07:00
Shayon MukherjeeandGitHub f7192e15f3 Add sample_ratio to LogExtrasConfig for gradual rollout data control (#2023)
Release / Push CUDA image to Docker (push) Canceled after 0s
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
2026-03-18 13:49:55 -04:00
JannikStandGitHub bd110a10e9 fix: cleanup env subprocesses on orchestrator crash (#2028)
Release / Push CUDA image to Docker (push) Canceled after 0s
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.
2026-03-18 05:13:42 +01:00
d1c36af4b3 fix: handle DTensor weights in MultiLoRAGroupedExperts for EP (#2035)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-17 18:39:32 -07:00
rasdaniandGitHub eba667d9c0 bump verifiers (#2036)
Release / Push CUDA image to Docker (push) Canceled after 0s
* bump verifiers

bumps to verifiers `de2ed50`

https://github.com/PrimeIntellect-ai/verifiers/commit/de2ed50f015ed1af0990b218de1df0853d9b3973

Signed-off-by: rasdani <73563550+rasdani@users.noreply.github.com>

* update lock file

---------

Signed-off-by: rasdani <73563550+rasdani@users.noreply.github.com>
2026-03-17 16:22:18 -07:00
7e06730200 fix: use token-level loss normalization for all loss types (#2034)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-17 09:49:41 -07:00
6c55a9aab2 make the loss equal weight per unmaked token (#1961)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make the loss equal weight per unmaked token

* minor fixes

* run ruff

* prevent nan-poisoning

* update

---------

Co-authored-by: hallerite <git@hallerite.com>
2026-03-16 12:41:06 -07:00
33d266b41f fix: patch sharded LoRA slice_lora_a for Qwen3.5 MoE (#2027)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-13 13:41:49 -07:00
8fa0dde0be feat: make max_retries configurable per training env (#2025)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-13 01:57:33 -07:00
76946689cf add Qwen 3.5 MoE model support with EP and VLM weight broadcast (#2026)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-13 00:51:53 -07:00
67de232773 fix: avoid duplicate policy updates during scheduler cancellation (#2004)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Fix duplicate policy updates during cancellation

* fix: cancel inflight scheduler policy update on stop

---------

Co-authored-by: Sebastian <sebastian@primeintellect.ai>
2026-03-12 10:47:04 -07:00
cab621fc5d fix: improve rollout error logging and normalize error/empty metrics (#2020)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-12 01:22:37 -07:00
275914349a make httpx connect timout configurable (#2017)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make httpx connect timout configurable

* Set default connect_timeout to 30s and add CHANGELOG entry

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: rasdani <rasdani@users.noreply.github.com>
2026-03-12 00:29:07 +01:00
rasdaniandGitHub 9b2fb9afbe feat: save checkpoints and weights to separate path (#2018)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-11 15:50:27 -07:00
halleriteandGitHub be9f9f8d83 add monkeypatch for qwen3.5 lora (#2019)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-11 14:48:04 -07:00
51fcbae998 fix: re-schedule errored rollouts (#2016)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-11 12:42:39 -07:00
faresobeidandGitHub 74a13f0ee2 add zero grad tracking (#1966)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add zero grad tracking

* address comments
2026-03-11 10:48:00 -07:00
051c8bac23 feat: allow num_infer_nodes=0 with fake data in multi-node SLURM RL (#2012)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-11 10:43:37 -07:00
a7db21723e feat: per-env metrics logging (#1989)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-11 05:23:17 -07:00
00a4752a49 fix: re-schedule empty trajectories instead of filtering after group completion (#2014)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-10 18:34:19 -07:00
halleriteandGitHub fa95af173c Revert "chore: add Claude Code review GitHub Action (#2000)" (#2015)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit bcb504bd4f.
2026-03-10 17:41:22 -07:00
rasdaniandGitHub 51bd1ad5d4 disinguish is_truncated and log stop_conditions (#2009)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-10 17:55:03 +01:00
samsjaandGitHub 93cd1fa37f feature: switch fused lm head to sequence chunking (#1987)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feature: switch fused lm head to sequence chunking

* fix: deprecate old fused lm head chunk config

* fix: update benchmark token chunk flag

* fix: stream vocab shards inside sequence chunked lm head

* fix: retune benchmark token chunk to 1024

* fix: treat benchmark memory as an upper bound

* fix: remove fused lm head chunk alias

* fix: remove token chunk size validation
2026-03-09 21:42:19 -07:00
00778b5a22 feat: disk-backed image offloading for VLM memory (#2006)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-09 20:13:59 -07:00
Philipp NormannandGitHub 447cafedea Add SFT validation eval with val_data (#1850)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 19:54:05 -07:00
halleriteandGitHub aa432f2c1f fix: patch HF tokenizer 'Already borrowed' crash under concurrent load (#1999)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 18:11:53 -07:00
7994d6c1aa fix: filter empty trajectory rollouts in scheduler (#2003)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-09 17:30:47 -07:00
JannikStandGitHub 3639f0ab4f fix _tied_weights_keys for transformers v5 compat (#1998)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 16:07:05 -07:00
8eecadc943 fix: use pydantic-config dict coercion instead of local workaround (#1997)
Release / Push CUDA image to Docker (push) Canceled after 0s
Point pydantic-config to main which now includes proper string-to-type
coercion for dict fields in BaseConfig (samsja/pydantic_config#23).

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 14:54:46 -07:00
bcb504bd4f chore: add Claude Code review GitHub Action (#2000)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-09 13:07:17 -07:00
samsjaandGitHub 2041d93132 feat: fused linear cross-entropy loss for SFT (#1958)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 12:16:16 -07:00
46f26ce195 chore: move env packages to dedicated envs extras group (#1993)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-09 12:00:38 -07:00
e113981a4e feat: add pre_run_command and common SLURM scheduling options (#1988)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-09 11:39:09 -07:00
JannikStandGitHub deecddc4af fix crash when pad_token_id is a list in model config (#1991)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 17:08:57 +01:00
Shayon MukherjeeandGitHub 26fd0e34be fix: route env install output through structured logger (#1985)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-08 09:15:02 -07:00
rasdaniandGitHub 710c9b32e9 fix: Patch get_encode_kwargs to prevent HF tokenizer left-truncation (#1986)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-08 04:26:16 -07:00
4d91edc9e6 add dp-rank-routing (#1940)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add dp-rank-routing

* docs: add changelog entry for client.dp_rank_count

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

* fix elastic

* fix

* dp-rank-route

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-03-08 06:20:21 +00:00
2c5c69da8b chore: config warnings (#1984)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-07 18:28:14 -08:00
5f0dcc8a1b chore: upgrade vllm from 0.17.0rc0 to 0.17.0 stable (#1980)
Release / Push CUDA image to Docker (push) Canceled after 0s
Use the stable PyPI release instead of pre-built wheels from wheels.vllm.ai.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:27:51 -08:00
rasdaniandGitHub 8ea7bd4834 fix: wire verifiers max_seq_len correctly (#1983)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-08 00:19:09 +01:00
302ef6d084 fix: only pass --weight_broadcast.host to orchestrator when nccl broadcast is configured (#1979)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 15:07:42 -08:00
JannikStandGitHub 89a5343780 fix arm64 flash-attn-cute: revert to 2b5db43 for sm100 pipeline fix (#1982)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn-cute: use 2b5db43 rev with sm100 pipeline fix

* also update fix-flash-attn-cute.sh to 2b5db43
2026-03-07 23:23:26 +01:00
22f0ae7640 fix: reduce orchestrator memory usage for VLM rollouts (#1964)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-06 18:06:09 -08:00
JannikStandGitHub f0746566e9 fix arm64 flash-attn: run uv pip from /tmp to avoid pyproject.toml build vars (#1975)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-07 02:10:43 +01:00
JannikStandGitHub 99c02bba6c fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD (#1974)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD

* also set FLASH_ATTENTION_FORCE_BUILD to bypass cached wheel download
2026-03-07 00:12:09 +01:00
JannikStandGitHub ebb5a1cac2 add --no-cache to force flash-attn source build on arm64 (#1973)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:43:45 +01:00
JannikStandGitHub d19ce7919f force flash-attn source build on arm64 with --no-binary (#1972)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:02:18 +01:00
JannikStandGitHub e2175c11ae add aarch64 vllm wheel and restrict uv environments to linux x86_64/aarch64 (#1970)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 10:53:20 +01:00
JannikStandGitHub d4bfa08977 Add arm64 support to Dockerfile and deps (#1933)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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)
2026-03-06 09:56:16 +01:00
599cea81c1 fix vllm 17 nihglty (#1969)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix vllm 17 nihglty

* fix vllm 0.17 compat: conditionally pass log_error_stack

---------

Co-authored-by: Jannik Straube <info@jannik-straube.de>
2026-03-06 00:25:05 -08:00
c344a8a3c6 fix: modality-aware batch distribution to prevent FSDP deadlocks (#1959)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-06 03:04:33 +01:00
892c895b83 fix: disable timeout on admin httpx clients (#1955)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-05 10:57:46 -08:00
94984b9790 feat: add Qwen3.5 support (#1946)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-05 11:34:43 +01:00
Christian RandGitHub 15fc324d1b perf: parallelize VLM image preprocessing across threads (#1951)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-04 22:57:53 -08:00
868ba03d9b fix: use qwen3_coder tool parser for Qwen3.5 models (#1953)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-04 21:36:31 -08:00
halleriteandGitHub aa33d910a4 update deep-gemm (#1944)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-04 12:57:07 -08:00
ac7ac62115 chore: update pydantic-config for JSON dict CLI support (#1943)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-04 12:33:16 -08:00
JannikStandGitHub 99058e9e37 bump nvidia-cutlass-dsl to 4.4.1 for flash-attn-cute ampere_helpers (#1945)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-04 05:54:10 +01:00
halleriteandGitHub fe32efbee1 perf: deduplicate VLM image bytes in orchestrator cache (#1935)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-03 13:49:21 -08:00
6a97762b5c fix: use space-separated list args for tyro CLI compatibility (#1942)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-03 13:33:19 -08:00
8451067db7 fix env server task cancellation (#1939)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-03 12:03:21 -08:00
ea161dd743 fix: validate prompt length in TITO endpoint before computing max_tokens (#1938)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-03 11:07:29 -08:00
Christian RandGitHub 9104df43c6 Serialize VLM pixel_values as raw bytes for 8-10x faster preprocessing (#1923)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-03 09:51:29 -08:00
Mika SenghaasandGitHub 02bdca2e41 change default rl algo to ipo (#1930)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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
2026-03-03 02:55:39 -08:00
bf71516c91 individual rollouts (#1865)
Release / Push CUDA image to Docker (push) Canceled after 0s
* individual-rollouts

* fixes

* fix group based scoring envs

* ruff

* ruff pls

* Fix inflight sample metric semantics

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

* fixes

* Delete tests/unit/orchestrator/test_scheduler.py

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>

* fix: off-policy off-by-one - cancel when off_policy_steps >= max

Made-with: Cursor

* Fix off-policy increment race in scheduler

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

* adress comments

* ruff

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-03-03 02:54:37 -08:00
Ido HakimiandGitHub aacc466401 fix: remove trailing comma from vllm dependency in pyproject.toml (#1937)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-03 02:28:54 -08:00
68e443b833 inference entrypoint (#1898)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-02 15:25:59 -08:00
6f6fa002a5 fix: replace removed teacher_gpu_ids with deployment.num_teacher_gpus in docs (#1929)
Release / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-03-02 14:52:37 -08:00
Ido HakimiandGitHub 732cbde83c fix: handle external CUDA_VISIBLE_DEVICES (#1920)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-02 09:16:46 -08:00
09a6875f11 migrate config system to pydantic_config (#1915)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-03-02 08:37:24 -08:00
Christian RandGitHub f00925c006 fix: propagate use_cache=False to sub-configs for VLM models (#1922)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-01 16:56:52 -08:00
samsjaandGitHub 5a6ab4a968 add vllm 16 back (#1893)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-28 11:48:12 -08:00
DominikandGitHub 5ae5079478 validate mint.json pages exist before syncing docs (#1912)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-27 13:49:47 -08:00
753a728e8a disable fused lm head chunking by default (#1904)
Release / Push CUDA image to Docker (push) Canceled after 0s
* disable fused lm head chunking by default

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

* reduce benchmark_regression seq_len to 16384

65536 OOMs on A6000 without fused lm head chunking.

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

* pin fused lm head chunk size in benchmark regression test

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

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

* pin fused lm head chunk size in rl_multi_run CI config

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

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

---------

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

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

* fix

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

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

---------

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

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

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

* format ruff

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

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

* fix stale comment about eval subprocess

* add unit tests for eval scheduling range check

* extract eval scheduling logic into compute_eval_ckpt_step function

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

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

* Feat; base64

* Feat: more work

* Feat: works now

* Feat: router replay done

* Fix: paths

* Fix: reshape vs view

* Final

* Fix: cp

* fix: config

* Add tests for router replay and fix routed_experts KeyError

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

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

* nit

* Fix

* Feat: address comments

* add to minimax and glm moe dsa

* add to minimax and glm moe dsa

* Fix: boundaries

---------

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

* put hendrycks sanity into nightly config

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

* also use in sft entrypoint

* update changelog

* fix exclude launcher fields

* address bugbot

* do not exclude deployment

* fix sft

* exclude clean output dir to not double clean

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

* update policy loop + cleanup

* always create policy loop task

* diff

* fix race

* cancel all

* fix

* safe cancel rollouts

* fix off by one err in off policy lag

* fill up in loop

* fix mutation

* cleaner

* update comments

* actually safe cancel

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

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

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

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

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

* changelog

* fix cursor bugbot

* changelog

* remove tests

* keep oversampling_factor

* restore oversampling_factor in wiki and math configs

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

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

---------

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

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

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

* Fix get_mesh lazy init ordering

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

This reverts commit bf679db5f4069374a74d409c0064cd04d8091c6b.

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

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

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

---------

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

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

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

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

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

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

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

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

* move shared configs into rl configs

* move trainer configs into shared.py

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

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

* move some stuff

* update configs

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

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

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

* update changelog with config consolidation entry

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

* style

---------

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

* ruff

---------

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

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

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

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

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

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

---------

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

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

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

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

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

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

* add hendrycks sanity check exp (#1873)

* Flesh out hendrycks sanity example README

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

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

* update examples

* Add hendrycks sanity to training examples list in README

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

* update readme

---------

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

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

* Add output_dir safety check to prevent accidental overwrites

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

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

* Move output_dir validation to entrypoints (before SLURM submission)

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

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

* Remove old clean flag from RLConfig local path

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

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

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

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

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

* update err message

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

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

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

* only raise if checkpoints exists

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

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

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

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

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

* add env var to never clean output dir safeguard

---------

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

* add some more tests

---------

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

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

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

* Move output_dir validation to entrypoints (before SLURM submission)

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

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

* Remove old clean flag from RLConfig local path

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

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

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

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

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

* update err message

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

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

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

* only raise if checkpoints exists

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

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

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

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

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

* add env var to never clean output dir safeguard

---------

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

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

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

* update examples

* Add hendrycks sanity to training examples list in README

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

* update readme

---------

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

* also migrate sft slurm

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

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

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

* update

* add single node template

* allow setting env vars everywhere

* fixes

* fix

* rename to .sbatch

* update scripts

* update configs

* adopt deployment and slurm config for sft

* rename slurm.template -> slurm.template_path

* style

* make inference optional again and some misc bug fixes

* update examples

* fix configs

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

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

* fix config

* deprecate hf hub offline in sft slurm

* only HF_HUB_OFFLINE in multi_node

* tail with -F

* exclude deployment

* update changelog

* move templates

* update branch

* fix output dir

* do not allow None partition

* fix

* revert env_vars

* remove env_vars entries from changelog

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

* address bugbot

* extract sft entrypoint

* move entrypoints

* cleanup logic in sft local

* fix single node sft slurm

* fix

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

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

* add changelog line

---------

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

* tmp

---------

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

* some fixes

* docs: add inference EP config changelog entry

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

* revert docs

* oops

---------

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

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

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

* Fix tool_call_parser not resolved when model name is propagated

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

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

---------

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

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

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

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

* Progress we run against vllm

* Feat: works but slow

* works now i think

* Cleanup

* deps

* Minor changes

* fix minimoe

* To be verified

* Feat: glm5

* Fix: scaling

* Fix more scaling

* FP8 quant

* Scale

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

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

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

* final

* nit

* Fix GlmMoeDsaConfig pad_token_id forwarding

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

---------

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

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

* Add CHANGELOG entry for orchestrator.use_token_client config field

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

---------

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

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

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

* add sft example

* add SFT MoE SLURM example and slim down SFT docs

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

* add sft slur config to tests

---------

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

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

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

* refactor: simplify MODEL_TOOL_CALL_PARSER to dict, address PR review

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

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

* refactor: use exact model names in MODEL_TOOL_CALL_PARSER dict

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

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

* remove extra inference stuff

* feat: default enable_auto_tool_choice to True

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

* feat: auto-enable enable_auto_tool_choice when tool_call_parser is set

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

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

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

---------

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

* do not run env server as daemon

* update commit to main

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

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

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

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

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

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

* Remove freeze_moe_router unit tests

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 14:50:15 -08:00
245 changed files with 18227 additions and 5982 deletions
+33
View File
@@ -12,6 +12,39 @@ jobs:
trigger-docs-sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate mint.json pages exist
run: |
missing=()
pages=$(python3 -c "
import json, sys
data = json.load(open('docs/mint.json'))
pages = []
def collect(obj):
if isinstance(obj, list):
for item in obj: collect(item)
elif isinstance(obj, dict):
if 'pages' in obj: collect(obj['pages'])
if 'groups' in obj: collect(obj['groups'])
elif isinstance(obj, str):
pages.append(obj)
collect(data.get('navigation', []))
print('\n'.join(pages))
")
while IFS= read -r page; do
[ -z "$page" ] && continue
if [ ! -f "docs/${page}.md" ] && [ ! -f "docs/${page}.mdx" ]; then
missing+=("${page}")
fi
done <<< "$pages"
if [ ${#missing[@]} -gt 0 ]; then
echo "ERROR: The following pages listed in mint.json do not exist in docs/:"
printf ' - %s\n' "${missing[@]}"
exit 1
fi
echo "All mint.json pages verified."
- name: Trigger public-docs workflow
uses: peter-evans/repository-dispatch@v3
with:
+57 -1
View File
@@ -2,6 +2,18 @@
Documenting changes which affect configuration usage patterns (added/moved/removed/renamed fields, notable logic changes).
- **`[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.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)
- **`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)
- **`slurm.nodelist`**, **`slurm.exclude`**, **`slurm.account`**, **`slurm.time`**: Added common SLURM scheduling options (all 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)
- **`inference.model.rope_scaling`**: Added RoPE scaling configuration passthrough to vLLM (#1447 2025-12-17)
@@ -59,5 +71,49 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTConfig` (2026-02-23)
- **`[deployment]` (RL)**: Added deployment configuration. `type = "single_node"` auto-derives contiguous GPU assignments from `num_infer_gpus`, `num_train_gpus`, `num_teacher_gpus`. `type = "multi_node"` requires `[slurm]` and uses `num_train_nodes`, `num_infer_nodes` (2026-02-23)
- **`[deployment]` (SFT)**: Added deployment configuration. `type = "single_node"` with `num_gpus` (default: 1). `type = "multi_node"` with `num_nodes`, `nodes_per_fsdp_group`, `hf_hub_offline` (2026-02-23)
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
- **`[slurm]` (SFT)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run sft` generates and submits an sbatch script instead of running locally (2026-02-23)
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
- **`clean_output_dir`**: Added to `RLConfig` and `SFTConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
- **`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)
+19 -4
View File
@@ -1,7 +1,7 @@
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Build stage
FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel AS builder
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -12,12 +12,22 @@ RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
ENV CUDA_HOME=/usr/local/cuda
ENV PATH=$PATH:/usr/local/cuda/bin
# Install packages
# Install packages (including Python 3.12 and ninja for fast CUDA kernel compilation)
ARG DEBIAN_FRONTEND=noninteractive
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
build-essential \
curl \
sudo \
git \
ninja-build \
software-properties-common \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y --no-install-recommends python3.12 python3.12-dev python3.12-venv \
&& ln -sf /usr/bin/python3.12 /usr/bin/python3 \
&& ln -sf /usr/bin/python3.12 /usr/bin/python \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Download the latest installer
@@ -43,7 +53,12 @@ COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
RUN --mount=type=cache,target=/app/.cache/uv \
uv sync --all-extras --locked --no-dev
uv sync --all-extras --group mamba-ssm --locked --no-dev
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
FROM python:3.12-slim
+2 -1
View File
@@ -164,8 +164,9 @@ We provide end-to-end training examples in the [`examples`](examples) directory
2. [**Wordle**](examples/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/alphabet_sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/wiki_search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/hendrycks_sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
4. *More to come...*
*More to come...*
## Docs
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "a76eec30",
"timestamp": "2026-02-01T00:37:17.504432+00:00",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
},
"metrics": {
"mfu": {
"mean": 17.08174826544651,
"std": 0.00860887294908562,
"min": 17.07595532741123,
"max": 17.091640740120457
"mean": 16.41977165630161,
"std": 0.010586646038388221,
"min": 16.407648988464405,
"max": 16.42719598975201
},
"throughput": {
"mean": 2040.0423352992304,
"std": 1.0281421434405753,
"min": 2039.3504951752516,
"max": 2041.2237756777045
"mean": 1960.9836648020673,
"std": 1.2643440104327244,
"min": 1959.5358764831926,
"max": 1961.8703395331793
},
"step_time": {
"mean": 63.29752009687945,
"std": 0.1304965028229097,
"min": 63.170207182411104,
"max": 63.430982740130275
"mean": 65.87,
"std": 0.13,
"min": 65.74,
"max": 66.0
},
"peak_memory": {
"gib": 22.685546875,
"pct": 47.72
"gib": 31.806640625,
"pct": 67.03
}
}
}
@@ -13,36 +13,36 @@
"micro_batches": 2,
"ep": 1,
"cp": 1,
"docker_image": "primeintellect/prime-rl@sha256:d3e9636af265f5ba2e56cd2555534489f5ff64e04a3f645059ca7989508de419",
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "a76eec30",
"timestamp": "2026-01-31T01:13:40.536972+00:00",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
},
"metrics": {
"mfu": {
"mean": 16.165875888064594,
"std": 0.010063094728313886,
"min": 16.154265967508614,
"max": 16.172097002189034
"mean": 15.634260517326164,
"std": 0.009817863071768202,
"min": 15.622927380137481,
"max": 15.640172924064188
},
"throughput": {
"mean": 7722.645407567771,
"std": 4.80726889329249,
"min": 7717.099200218126,
"max": 7725.61731325081
"mean": 7468.685954343421,
"std": 4.690118598479809,
"min": 7463.271969943842,
"max": 7471.510386564679
},
"step_time": {
"mean": 66.21160964062437,
"std": 0.11667723461510121,
"min": 66.1170196281746,
"max": 66.34198968904093
"mean": 68.34095695288852,
"std": 0.16054587555887065,
"min": 68.16114284005016,
"max": 68.46991707291454
},
"peak_memory": {
"gib": 14.1328125,
"pct": 29.74
"gib": 23.25390625,
"pct": 49.05701678145735
}
}
}
+3 -3
View File
@@ -11,7 +11,7 @@ from typing import Annotated
from pydantic import Field
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
from prime_rl.utils.config import BaseConfig, cli
SHORTENED_ATTN_MAPPING = {
"flash_attention_2": "FA2",
@@ -23,7 +23,7 @@ SHORTENED_ATTN_MAPPING = {
DEVICE_NAME_STRIP_WORDS = ["NVIDIA", "RTX", "80GB", "40GB"]
class AggregateConfig(BaseSettings):
class AggregateConfig(BaseConfig):
"""Configuration for aggregating benchmark results."""
artifacts_dir: Annotated[Path, Field(description="Directory containing benchmark JSON artifacts")]
@@ -197,7 +197,7 @@ def generate_markdown(
def main():
config = parse_argv(AggregateConfig)
config = cli(AggregateConfig)
results = load_json_dir(config.artifacts_dir)
print(f"Loaded {len(results)} benchmark results", file=sys.stderr)
+12 -3
View File
@@ -19,7 +19,7 @@ from typing import Annotated, Literal
import torch
from pydantic import Field
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
from prime_rl.utils.config import BaseConfig, cli
MAX_LORAS = 4
@@ -46,7 +46,7 @@ def extract_oom_error_reason(output: str) -> str | None:
return None
class BenchmarkConfig(BaseSettings):
class BenchmarkConfig(BaseConfig):
"""Configuration for running a single benchmark."""
type: Annotated[
@@ -83,6 +83,11 @@ class BenchmarkConfig(BaseSettings):
cp: Annotated[int, Field(ge=1, description="Context parallelism size (1 = no CP)")] = 1
fused_lm_head_token_chunk_size: Annotated[
int | None,
Field(description="Fused LM head token chunk size (None uses trainer default)"),
] = None
docker_image: Annotated[str | None, Field(description="Docker image used for the benchmark")] = None
# Metadata set by the script
@@ -152,6 +157,10 @@ def build_command(config: BenchmarkConfig) -> list[str]:
if config.cp > 1:
cmd.extend(["--model.cp", str(config.cp)])
# Fused LM head chunk size
if config.fused_lm_head_token_chunk_size is not None:
cmd.extend(["--model.fused-lm-head-token-chunk-size", str(config.fused_lm_head_token_chunk_size)])
# Data configuration differs between RL and SFT
if config.type.startswith("rl"):
cmd.extend(["--data.fake.batch-size", str(config.micro_batches * config.num_gpus)])
@@ -239,7 +248,7 @@ def run_benchmark(config: BenchmarkConfig) -> None:
def main():
config = parse_argv(BenchmarkConfig)
config = cli(BenchmarkConfig)
run_benchmark(config)
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
+1 -1
View File
@@ -17,7 +17,7 @@ rollouts_per_example = 16
max_tokens = 512
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2 }
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 10
seq_len = 2048
@@ -20,7 +17,7 @@ rollouts_per_example = 8
max_tokens = 384
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
@@ -0,0 +1,29 @@
max_steps = 10
seq_len = 2048
[deployment]
type = "single_node"
num_infer_gpus = 1
num_train_gpus = 1
[ckpt]
[model]
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 1024
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 25
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 25
seq_len = 2048
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
@@ -5,6 +5,7 @@ max_async_level = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_token_chunk_size = 8192
[model.lora]
rank = 8
@@ -0,0 +1,30 @@
max_steps = 20
[ckpt]
resume_step = 10
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[model.lora]
rank = 8
target_modules = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
]
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
batch_size = 4
seq_len = 1024
[optim]
lr = 1.5e-5
@@ -0,0 +1,29 @@
max_steps = 10
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[model.lora]
rank = 8
target_modules = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
]
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
batch_size = 4
seq_len = 1024
[optim]
lr = 1.5e-5
+5 -4
View File
@@ -3,12 +3,13 @@
# - 300 instead of 500 steps
# - No checkpointing
# - No evals
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
@@ -21,7 +22,7 @@ temperature = 0.6
max_tokens = 8192
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
-46
View File
@@ -1,46 +0,0 @@
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 2048
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 1024
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "primeintellect/math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_fraction = 0.0
hard_fraction = 0.0
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.val]
interval = 5
num_examples = 128
[orchestrator.eval]
interval = 10
[orchestrator.eval.sampling]
max_tokens = 2048
[[orchestrator.eval.env]]
id = "primeintellect/math500"
name = "math500"
num_examples = 30
rollouts_per_example = 4
[trainer] # Default trainer config
[inference]
@@ -1,13 +1,18 @@
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 25
seq_len = 4096
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
@@ -16,7 +21,7 @@ rollouts_per_example = 16
max_tokens = 64
[[orchestrator.env]]
id = "primeintellect/color-codeword"
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[orchestrator.val]
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1500
seq_len = 24576
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+2 -2
View File
@@ -41,6 +41,6 @@ port = 8000
sync_interval = 5.0
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+4 -4
View File
@@ -1,9 +1,10 @@
trainer_gpu_ids = [0,1,2,3]
inference_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "env-mix-debug"
name = "env-mix"
@@ -47,6 +48,5 @@ api_server_count = 8
gpu_memory_utilization = 0.8
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
max_model_len = 8192
@@ -0,0 +1,19 @@
enable_expert_parallel = true
enable_eplb = false
use_deep_gemm = true
gpu_memory_utilization = 0.85
[model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
num_prefill_nodes = 4
num_decode_nodes = 2
gpus_per_node = 8
[slurm]
job_name = "glm5"
partition = "cluster"
+1 -4
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 100
seq_len = 2048
@@ -19,7 +16,7 @@ rollouts_per_example = 16
max_tokens = 2048
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
+2 -5
View File
@@ -1,6 +1,3 @@
trainer_gpu_ids = [0]
inference_gpu_ids = [1]
max_steps = 500
seq_len = 2048
@@ -19,7 +16,7 @@ rollouts_per_example = 16
max_tokens = 2048
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -38,7 +35,7 @@ interval = 10
max_tokens = 2048
[[orchestrator.eval.env]]
id = "primeintellect/math500"
id = "math500"
num_examples = 30
rollouts_per_example = 4
+2 -5
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 3000
seq_len = 8192
@@ -16,7 +13,7 @@ batch_size = 512
rollouts_per_example = 8
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
@@ -24,7 +21,7 @@ name = "hendrycks-math"
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
id = "aime2024"
name = "aime2024"
rollouts_per_example = 16
+3 -6
View File
@@ -1,6 +1,3 @@
trainer_gpu_ids = [0]
inference_gpu_ids = [1]
max_steps = 500
[wandb]
@@ -16,12 +13,12 @@ rollouts_per_example = 16
oversampling_factor = 1.5
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
@@ -37,7 +34,7 @@ num_examples = 128
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
id = "aime2024"
name = "aime2024"
num_examples = 30
rollouts_per_example = 4
-1
View File
@@ -25,6 +25,5 @@ args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox
api_server_count = 4
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
max_model_len = 4096
+5 -4
View File
@@ -1,12 +1,13 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 15
seq_len = 4096
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
@@ -16,7 +17,7 @@ rollouts_per_example = 16
max_tokens = 64
[[orchestrator.env]]
id = "primeintellect/color-codeword"
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[orchestrator.val]
@@ -0,0 +1,35 @@
max_steps = 3
seq_len = 2048
output_dir = "outputs/rl_color_codeword_test"
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[orchestrator]
batch_size = 16
rollouts_per_example = 2
[orchestrator.sampling]
max_tokens = 32
[[orchestrator.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.parallel]
dp = 1
+80
View File
@@ -0,0 +1,80 @@
output_dir = "/data/sami_debug/nemotron-debug"
clean_output_dir = true
max_steps = 5
seq_len = 2048
[slurm]
job_name = "nemotron-4node"
pre_run_command = "uv sync --all-extras --group mamba-ssm"
[deployment]
type = "multi_node"
num_train_nodes = 4
num_infer_nodes = 4
[log]
level = "debug"
[wandb]
project = "sami_debug_nemotron"
name = "nemotron-120b-math"
shared = true
[weight_broadcast]
type = "nccl"
[model]
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
[trainer]
dist_timeout_seconds = 1800
[trainer.model]
impl = "custom"
attn = "flash_attention_2"
optim_cpu_offload = true
ep = 8
fused_lm_head_token_chunk_size = 8192
[trainer.model.ac]
freq = 1
[trainer.model.ac_offloading]
max_inflight_activations = 5
[trainer.model.compile]
[orchestrator]
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.val]
interval = 5
num_examples = 128
[orchestrator.eval]
interval = 10
[orchestrator.eval.sampling]
max_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
[inference.parallel]
tp = 8
dp = 1
+79
View File
@@ -0,0 +1,79 @@
output_dir = "outputs/rl-nemotron-debug"
clean_output_dir = true
max_steps = 500
seq_len = 4096
[slurm]
job_name = "nemotron-sami-debug"
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 2
[log]
level = "debug"
[wandb]
project = "nemotron_sami_debug"
name = "nemotron-120b-math"
shared = true
[weight_broadcast]
type = "nccl"
[model]
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
[trainer.model]
impl = "custom"
attn = "flash_attention_2"
optim_cpu_offload = true
fused_lm_head_token_chunk_size = 8192
[trainer.model.debug]
random_init = true
num_layers = 8
[trainer.model.ac_offloading]
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[orchestrator]
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 4096
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.val]
interval = 5
num_examples = 128
[orchestrator.eval]
interval = 10
[orchestrator.eval.sampling]
max_tokens = 4096
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
[inference.parallel]
tp = 4
dp = 4
+1 -5
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 500
seq_len = 4096
@@ -40,8 +37,7 @@ max_tokens = 512
online_difficulty_filtering = true
[[orchestrator.env]]
id = "primeintellect/wiki-search"
id = "wiki-search"
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
+3 -1
View File
@@ -87,7 +87,9 @@ See the dedicated [SLURM guide](slurm.md).
## Inference
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.
+91
View File
@@ -0,0 +1,91 @@
# Disaggregated Prefill/Decode Inference
Run MoE models with separate prefill and decode node groups for higher throughput.
## Quick Start
See [`configs/glm5_disagg_inference/inference.toml`](../configs/glm5_disagg_inference/inference.toml) for an example config.
```bash
uv run inference @ configs/glm5_disagg_inference/inference.toml --output-dir /data/$USER/outputs
```
## Prefill/Decode Ratio
| Workload | Recommended ratio (P:D) | Why |
|---|---|---|
| Agentic (SWE, Lean) | **3:1** | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | **1:2** | Short prompts, long generations → decode-heavy |
Monitor live queue depths:
```bash
curl -s http://<prefill_node>:8100/metrics | grep num_requests_waiting
curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
```
If prefill has queued requests and decode has zero, add more prefill nodes (and vice versa).
For historical averages (cumulative over the entire run), query the histogram metrics:
```bash
# Average queue time per request (seconds)
curl -s http://<node>:<port>/metrics | awk '
/request_queue_time_seconds_sum\{/ { sum += $2 }
/request_queue_time_seconds_count\{/ { count += $2 }
END { if (count > 0) printf "avg queue: %.2fs (%d requests)\n", sum/count, count }
'
# Average prefill/decode compute time
curl -s http://<node>:<port>/metrics | awk '
/request_prefill_time_seconds_sum\{/ { ps += $2 }
/request_prefill_time_seconds_count\{/ { pc += $2 }
/request_decode_time_seconds_sum\{/ { ds += $2 }
/request_decode_time_seconds_count\{/ { dc += $2 }
END {
if (pc > 0) printf "avg prefill: %.2fs\n", ps/pc
if (dc > 0) printf "avg decode: %.2fs\n", ds/dc
}
'
```
Other useful metrics on the `/metrics` endpoint:
- `vllm:e2e_request_latency_seconds` — end-to-end latency
- `vllm:kv_cache_usage_perc` — KV cache memory pressure
- `vllm:nixl_xfer_time_seconds` — NIXL KV transfer duration
- `vllm:nixl_bytes_transferred` — bytes per KV transfer
## UCX 1.19
NVSHMEM requires UCX >= 1.19 for multi-GPU CUDA support. Most clusters ship UCX 1.17 (via HPC-X), which causes `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch.
**Check your version:**
```bash
/opt/hpcx/ucx/bin/ucx_info -v | head -1
# If < 1.19, you need to build from source
```
**Build UCX 1.19 (run once on a GPU node):**
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
```
This installs UCX 1.19 to `prime-rl/third_party/ucx/`. The sbatch template automatically adds it to `LD_LIBRARY_PATH`, overriding the system version.
## Troubleshooting
### `DeepEP error: timeout (dispatch CPU)`
NVSHMEM internode communication failing. Check:
1. UCX version >= 1.19? (`third_party/ucx/bin/ucx_info -v`)
2. NVSHMEM libs reachable at `/tmp/deepep_build/nvshmem/lib/`? If not:
```bash
ssh <node> 'mkdir -p /tmp/deepep_build/nvshmem && \
ln -sfn <venv>/lib/python3.12/site-packages/nvidia/nvshmem/lib \
/tmp/deepep_build/nvshmem/lib'
```
3. IBGDA driver enabled? `ssh <node> 'cat /proc/driver/nvidia/params | grep EnableStreamMemOPs'` should show `1`.
### Router healthy but requests hang
NIXL side channel not running on prefill. Check:
```bash
ssh <prefill_node> 'ss -tlnp sport ge :5600 sport le :5608 | grep -c LISTEN'
# Should show 8 (one per DP rank). If 0, check logs for UCX/NVSHMEM errors.
```
+1 -1
View File
@@ -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
+1
View File
@@ -7,6 +7,7 @@ This directory maintains the documentation for PRIME-RL. It is organized into th
- [**Environments**](environments.md) - Installing and using verifiers environments from the Environments Hub
- [**Async Training**](async.md) - Understanding asynchronous off-policy training and step semantics
- [**Logging**](logging.md) - Logging with loguru, torchrun, and Weights & Biases
- [**Platform Monitoring**](platform-monitoring.md) - Register runs on the Prime Intellect platform and stream training metrics
- [**MultiRunManager**](multi_run_manager.md) - Multi-run training with the MultiRunManager object for concurrent LoRA adapters
- [**Checkpointing**](checkpointing.md) - Saving and resuming training from checkpoints
- [**Benchmarking**](benchmarking.md) - Performance benchmarking and throughput measurement
+1 -1
View File
@@ -10,7 +10,7 @@
"environments",
"async",
"logging",
"runs",
"multi_run_manager",
"checkpointing",
"benchmarking",
"deployment",
+43 -16
View File
@@ -1,35 +1,62 @@
# Multimodal (VLM) Support
Prime-RL has experimental support for training vision-language models (VLMs) like Qwen3-VL.
Prime-RL supports training vision-language models (VLMs) like Qwen3-VL.
## VLM Configuration
### Supported Models
The built-in registry supports these model families out of the box:
| Model Family | model_type | Vision Encoder | Language Model |
|-------------|------------|---------------|----------------|
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
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**: 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 or avoid overlong rollouts.
- **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.
- **The images that the VLM sees are not logged**
- **Optimization dtype must be bfloat16**: Set `optimization_dtype = "bfloat16"` and `reduce_dtype = "bfloat16"` in your trainer config.
- **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.
- **Higher KL mismatch with multi-image inputs**: VLM training exhibits higher KL mismatch compared to text-only, especially with multiple images.
- **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.
- **Images are not logged**: The images the VLM sees during training are not logged to monitors.
## How Multi-Turn VLM Training Works
## How Multi-Turn VLM RL 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.
+52 -8
View File
@@ -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:
```toml
teacher_gpu_ids = [2, 3]
[deployment]
num_teacher_gpus = 2
[trainer.loss]
teacher_tau = 1.0
adv_tau = 0.0 # Disable reward-based learning
[orchestrator.buffer]
skip_verification = true # Skip expensive verification
[orchestrator.verification]
enabled = false # Skip expensive verification
```
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
```toml
[trainer.loss]
type = "sft"
[orchestrator]
use_token_client = false
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
skip_model_check = true
[orchestrator.teacher_rollout_model.model]
name = "teacher-model-name"
```
In this mode:
- Rollouts are generated from `orchestrator.teacher_rollout_model`
- The orchestrator uses text-level reconstruction with the student tokenizer
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
- Omit `[inference]` (no local inference server required)
### Image Input (VLM) Support
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
Notes:
- This path currently expects `data:image/...` payloads in message content
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
Reference configs:
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
- `examples/alphabet_sort/sft_distill_hard.toml`
## Parameters
| Parameter | Default | Description |
|-----------|---------|-------------|
| `teacher_gpu_ids` | `None` | GPUs for teacher server. Auto-starts server when set. |
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for teacher server. Auto-starts server when set. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.buffer.skip_verification` | `false` | Skip verification. Use with `adv_tau = 0`. |
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
## Monitoring
+48
View File
@@ -0,0 +1,48 @@
# Platform Monitoring
Use `orchestrator.prime_monitor` to register a run on the Prime Intellect platform and stream training metrics, samples, and distributions.
> **Internal-only for now:** external run registration is currently only enabled for internal / allowlisted teams.
## Prerequisites
You need a Prime API key with `rft:write` scope.
Use the CLI:
```bash
prime login
```
Or set an environment variable directly:
```bash
export PRIME_API_KEY=pit_...
```
## Minimal config
```toml
[orchestrator.prime_monitor]
run_name = "my-experiment"
```
You can also override from the CLI:
```bash
uv run rl @ config.toml --orchestrator.prime_monitor.run_name "my-experiment"
```
## Troubleshooting
### `API key not found`
Set the env var from `api_key_var` or run:
```bash
prime login
```
### `External training runs are not enabled for this team`
Your team is not allowlisted yet. This feature is currently internal-only.
+222 -79
View File
@@ -1,89 +1,124 @@
# SLURM
For SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
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
uv run rl_slurm @ examples/slurm/hendrycks_math.toml
# 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
```
This will:
The SLURM config is a thin overlay that inherits from a base config and adds `[slurm]` + `[deployment]` sections:
1. Write resolved sub-configs to `{output_dir}/configs/` (trainer.toml, orchestrator.toml, inference.toml)
2. Render the SLURM script to `{output_dir}/rl.sh`
3. Submit the job via `sbatch`
```toml
# examples/reverse_text/slurm_rl.toml
toml_files = ["rl.toml"]
To only generate the script without submitting, use `--dry-run`:
output_dir = "outputs/reverse-text-rl"
```bash
uv run rl_slurm @ examples/slurm/hendrycks_math.toml --dry-run
[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
The SLURM config extends the standard RL config with the following fields:
### `[slurm]` — Job submission (shared between RL and SFT)
| Field | Description |
|---|---|
| `job_name` | SLURM job name |
| `output_dir` | Directory for outputs, sub-configs, and logs |
| `project_dir` | Path to the project root on the cluster (defaults to cwd) |
| `num_train_nodes` | Number of nodes for training |
| `num_infer_nodes` | Number of nodes for inference |
| `gpus_per_node` | Number of GPUs per node (default: 8) |
| `nodes_per_fsdp_group` | Number of train nodes per FSDP island (optional, auto-sets `trainer.dp_replicate`) |
| `slurm_template` | Path to a custom Jinja2 template (optional) |
| `dry_run` | Only generate the script without submitting (default: false) |
| 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` |
| `account` | SLURM account to charge (`--account`) | `None` |
| `time` | Maximum wall time, e.g. `"24:00:00"` (`--time`) | `None` |
| `pre_run_command` | Shell command to run on head node after env setup, before starting the job (e.g. cleanup) | `None` |
All standard RL config fields (model, trainer, orchestrator, inference, wandb, ckpt, etc.) are available and will be resolved into the sub-configs.
### `[deployment]` — Node and GPU allocation
### Dense model (Hendrycks Math)
**RL** uses a discriminated union with `type = "single_node"` (default) or `type = "multi_node"`:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_train_gpus` | Training GPUs | — |
| `num_infer_gpus` | Inference GPUs | — |
| `num_train_nodes` | — | Training nodes |
| `num_infer_nodes` | — | Inference nodes |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
**SFT** follows the same pattern but only has training nodes:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_gpus` | Number of GPUs (default: 1) | — |
| `num_nodes` | — | Training nodes (default: 2) |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
**Inference** runs independent vLLM replicas per node:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_nodes` | — | Number of inference nodes (default: 1) |
The SLURM template is auto-selected based on `deployment.type`. You can override it with `slurm.template_path`.
### Constraints
- `output_dir` should be explicitly set when using SLURM (defaults to `"outputs"`)
- Multi-node deployment requires `[slurm]` to be set
---
## RL Examples
### Single-node SLURM
The simplest case: run on a single allocated node. No `[deployment]` needed — defaults to `single_node`.
```toml
job_name = "hendrycks-math"
output_dir = "/shared/outputs/my-rl-run"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[wandb]
project = "hendrycks-math"
name = "hendrycks-math"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[inference.parallel]
tp = 1
dp = 8
[slurm]
job_name = "my-rl-run"
```
### MoE model (Hendrycks Math)
For MoE models like `Qwen3-30B-A3B`, the config is designed to minimize memory usage on a single training node. It enables activation checkpointing with offloading, optimizer CPU offload, and NCCL weight broadcast:
### Multi-node SLURM (Hendrycks Math)
```toml
job_name = "hendrycks-math-moe"
num_train_nodes = 1
num_infer_nodes = 1
output_dir = "outputs/rl-math-moe"
max_steps = 500
seq_len = 2048
[slurm]
job_name = "hendrycks-math-rl-moe"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[weight_broadcast]
type = "nccl"
@@ -118,37 +153,145 @@ tp = 4
dp = 2
```
## Custom SLURM Templates
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
The default template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
---
```bash
uv run rl_slurm \
@ my_config.toml \
--slurm-template path/to/my_template.sh.j2
## SFT Examples
### Single-node SLURM
```toml
output_dir = "/shared/outputs/my-sft-run"
[slurm]
job_name = "my-sft-run"
```
The template receives the following variables: `job_name`, `project_dir`, `output_dir`, `config_dir`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `hf_hub_offline`. See `src/prime_rl/slurm/rl_slurm.sh.j2` for the default template as a starting point.
### 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, the logs are available at:
After submission, logs are available at:
```bash
tail -f {output_dir}/slurm/latest_train_node_rank_0.log
tail -f {output_dir}/slurm/latest_infer_node_rank_0.log
tail -f {output_dir}/slurm/latest_orchestrator.log
# Single-node
tail -F {output_dir}/logs/trainer/rank_0.log
# Multi-node RL
tail -F {output_dir}/slurm/latest_train_node_rank_0.log
tail -F {output_dir}/slurm/latest_infer_node_rank_0.log
tail -F {output_dir}/slurm/latest_orchestrator.log
# Inference (single or multi-node)
tail -F {output_dir}/slurm/latest_infer_node_rank_0.log
```
For convenience, a tmux launcher is provided that sets up a session with all three log streams:
For convenience, a tmux launcher sets up a session with all log streams:
```bash
bash scripts/slurm_tmux.sh my-rl-job /shared/outputs/my-rl-job
```
This creates a tmux session `slurm-my-rl-job` with two windows:
- **Window 0 (Terminal)**: a plain shell for running commands
- **Window 1 (Logs)**: three vertical panes tailing trainer, orchestrator, and inference logs
The trainer and inference panes use glob patterns (`latest_train_node_rank_*.log`, `latest_infer_node_rank_*.log`) to follow logs from all node ranks. Re-running the same command attaches to the existing session.
+2 -1
View File
@@ -90,7 +90,8 @@ The correct alphabetical order by last name should be: Akman, Cakir, Durgun. The
We train with LoRA (rank 32, alpha 64) for 100 steps.
![RL](rl/wandb.png)
![RL](rl.png)
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
```bash
# In the `Trainer` pane

Before

Width:  |  Height:  |  Size: 141 KiB

After

Width:  |  Height:  |  Size: 141 KiB

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

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 129 KiB

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

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

-14
View File
@@ -1,14 +0,0 @@
max_steps = 100
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
[optim]
lr = 2e-5
[ckpt] # Checkpoint at the end of training
+5
View File
@@ -0,0 +1,5 @@
# Usage: uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
output_dir = "outputs/reverse-text-rl"
[slurm]
job_name = "reverse-text-rl"
+5
View File
@@ -0,0 +1,5 @@
# Usage: uv run sft @ examples/reverse_text/sft.toml @ examples/reverse_text/slurm_sft.toml
output_dir = "outputs/reverse-text-sft"
[slurm]
job_name = "reverse-text-sft"
-41
View File
@@ -1,41 +0,0 @@
job_name = "hendrycks-math"
output_dir = "outputs/hendrycks-math"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[log]
level = "debug"
[wandb]
project = "hendrycks-math-debug"
name = "hendrycks-math"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[trainer]
[inference.parallel]
tp = 1
dp = 8
+4 -4
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
@@ -48,5 +49,4 @@ id = "primeintellect/wiki-search"
[ckpt] # Checkpoint at the end of training
[inference.model]
enable_auto_tool_choice = true
tool_call_parser = "hermes"
+5
View File
@@ -0,0 +1,5 @@
# Usage: uv run rl @ examples/wiki_search/rl.toml @ examples/wiki_search/slurm_rl.toml
output_dir = "outputs/wiki-search"
[slurm]
job_name = "wiki-search"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
project = "wordle"
name = "wordle"
+5
View File
@@ -0,0 +1,5 @@
# Usage: uv run rl @ examples/wordle/rl.toml @ examples/wordle/slurm_rl.toml
output_dir = "outputs/wordle-rl"
[slurm]
job_name = "wordle-rl"
+5
View File
@@ -0,0 +1,5 @@
# Usage: uv run sft @ examples/wordle/sft.toml @ examples/wordle/slurm_sft.toml
output_dir = "outputs/wordle-sft"
[slurm]
job_name = "wordle-sft"
+63 -17
View File
@@ -12,20 +12,19 @@ dependencies = [
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"pydantic>=1.10.13",
"pydantic-settings>=2.10.1",
"pydantic-config",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"numpy>=2.2.6",
"torch>=2.9.0",
"torchdata>=0.11.0",
"transformers",
"vllm",
"vllm>=0.17.0",
"wandb>=0.24.2",
"ring-flash-attn>=0.1.8",
"prime>=0.5.37",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"math-env",
"tenacity>=8.2.0",
"openai>=1.106.1",
"rich>=14.0.0",
@@ -33,33 +32,57 @@ dependencies = [
"torchtitan",
"verifiers",
"dion",
"reverse-text",
"tilelang>=0.1.8",
"flash-linear-attention",
]
[project.scripts]
rl = "prime_rl.rl:main"
rl_slurm = "prime_rl.slurm.rl:main"
rl = "prime_rl.entrypoints.rl:main"
sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.trainer.rl.train:main"
orchestrator = "prime_rl.orchestrator.orchestrator:main"
inference = "prime_rl.inference.server:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
sft = "prime_rl.trainer.sft.train:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
[project.optional-dependencies]
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-3 = [
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl",
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-cute = [
"flash-attn-cute",
]
envs = [
"reverse-text",
"alphabet-sort",
"wiki-search",
"math-python",
"math-env",
"code-env",
"science-env",
"logic-env",
"color-codeword",
"math500",
"aime2024",
"aime2025",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
"deep-gemm ; platform_machine == 'x86_64'",
"nixl",
"nixl-cu12 ; platform_machine == 'x86_64'",
"vllm-router",
]
[dependency-groups]
mamba-ssm = [
"mamba-ssm>=2.3.0",
]
dev = [
"ipykernel>=6.29.5",
"ipywidgets>=8.1.7",
@@ -72,28 +95,49 @@ dev = [
[tool.uv]
preview = true
no-build-isolation-package = ["flash-attn"]
prerelease = "allow"
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
"sys_platform == 'linux' and platform_machine == 'aarch64'",
]
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"transformers>=5.1.0.dev0",
"quack-kernels>=0.2.7",
]
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
math-env = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "013d4da" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "f5580acd" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
vllm = { url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" }
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "main" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "5c1c72b" }
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "e2743ab5" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
vllm-router = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.3/vllm_router-0.1.11-cp38-abi3-linux_x86_64.whl" }
reverse-text = { index = "primeintellect" }
alphabet-sort = { index = "primeintellect" }
wiki-search = { index = "primeintellect" }
math-python = { index = "primeintellect" }
math-env = { index = "primeintellect" }
code-env = { index = "primeintellect" }
science-env = { index = "primeintellect" }
logic-env = { index = "primeintellect" }
color-codeword = { index = "primeintellect" }
math500 = { index = "primeintellect" }
aime2024 = { index = "primeintellect" }
aime2025 = { index = "primeintellect" }
deep-ep = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.2/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.2/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
nixl-cu12 = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
@@ -101,12 +145,14 @@ flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
[[tool.uv.index]]
name = "primeintellect"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/test/cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true
[tool.ruff.lint]
select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
# arm64 post-install fixups for Docker builds.
set -e
echo "=== building flash-attn from source (sm_100 / GB200) ==="
# Run from /tmp so uv doesn't read pyproject.toml's [tool.uv.extra-build-variables]
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and prevents CUDA kernel compilation.
export TORCH_CUDA_ARCH_LIST="10.0"
export MAX_JOBS=4
export FLASH_ATTENTION_FORCE_BUILD=TRUE
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
(cd /tmp && uv pip install --python /app/.venv/bin/python \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache)
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --reinstall --no-deps \
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
SITE_PACKAGES=".venv/lib/python3.12/site-packages"
cp "$SITE_PACKAGES/flashinfer/data/cutlass/python/CuTeDSL/cutlass/utils/ampere_helpers.py" \
"$SITE_PACKAGES/nvidia_cutlass_dsl/python_packages/cutlass/utils/ampere_helpers.py"
+1 -1
View File
@@ -11,7 +11,7 @@
set -e
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=flash_attn/cute"
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
# Verify installation
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
# Build and install DeepGEMM from source for FP8 MoE inference.
#
# Uses the commit recommended by vLLM for compatibility with vLLM 0.17+.
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
#
# Usage:
# bash scripts/install_deep_gemm.sh
#
# Options:
# --ref REF DeepGEMM commit hash (default: 477618c)
# --wheel-dir DIR Output wheel to DIR instead of installing
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
DEEPGEMM_GIT_REF="477618cd51baffca09c4b0b87e97c03fe827ef03"
WHEEL_DIR=""
while [[ $# -gt 0 ]]; do
case $1 in
--ref) DEEPGEMM_GIT_REF="$2"; shift 2 ;;
--wheel-dir) WHEEL_DIR="$2"; shift 2 ;;
*) echo "Unknown argument: $1" >&2; exit 1 ;;
esac
done
# Skip if already installed at the right version
INSTALLED_VER=$(python -c "import deep_gemm; print(deep_gemm.__version__)" 2>/dev/null || echo "")
SHORT_REF="${DEEPGEMM_GIT_REF:0:7}"
if [[ "$INSTALLED_VER" == *"$SHORT_REF"* ]]; then
echo "DeepGEMM ${INSTALLED_VER} already installed, skipping."
exit 0
fi
# Auto-detect CUDA version
CUDA_VERSION=$(nvcc --version 2>/dev/null | grep -oP 'release \K[\d.]+' || echo "")
if [ -z "$CUDA_VERSION" ]; then
echo "ERROR: nvcc not found. CUDA toolkit required." >&2
exit 1
fi
CUDA_MAJOR="${CUDA_VERSION%%.*}"
CUDA_MINOR="${CUDA_VERSION#*.}"
CUDA_MINOR="${CUDA_MINOR%%.*}"
if [ "$CUDA_MAJOR" -lt 12 ] || { [ "$CUDA_MAJOR" -eq 12 ] && [ "$CUDA_MINOR" -lt 8 ]; }; then
echo "Skipping DeepGEMM (requires CUDA 12.8+, got ${CUDA_VERSION})"
exit 0
fi
echo "================================================================"
echo " Building DeepGEMM (${SHORT_REF})"
echo " CUDA: ${CUDA_VERSION}"
echo "================================================================"
TMPDIR=$(mktemp -d)
cleanup() { rm -rf "$TMPDIR"; }
trap cleanup EXIT
git clone --recurse-submodules "$DEEPGEMM_GIT_REPO" "$TMPDIR/DeepGEMM" 2>&1
cd "$TMPDIR/DeepGEMM"
git checkout "$DEEPGEMM_GIT_REF"
git submodule update --init --recursive
cd "$REPO_ROOT"
if [ -n "$WHEEL_DIR" ]; then
mkdir -p "$WHEEL_DIR"
uv build --no-build-isolation --wheel --out-dir "$WHEEL_DIR" "$TMPDIR/DeepGEMM"
echo ""
echo "Wheel built:"
ls -lh "$WHEEL_DIR"/deep_gemm*.whl
else
uv pip install --no-build-isolation --reinstall "$TMPDIR/DeepGEMM"
echo ""
echo "Installed: $(python -c 'import deep_gemm; print(deep_gemm.__version__)')"
fi
echo "================================================================"
echo " DeepGEMM build complete"
echo "================================================================"
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env bash
# Install DeepEP kernels for expert-parallel disaggregated inference.
#
# Builds NVSHMEM + DeepEP from source and installs into the project venv.
# Required for disaggregated prefill/decode deployments with expert parallelism.
#
# Auto-detects the CUDA toolkit version that matches the installed PyTorch
# and looks for it at /usr/local/cuda-X.Y. Fails if not found.
#
# Prerequisites:
# - Matching CUDA toolkit installed (e.g. `sudo apt install cuda-toolkit-12-8`)
# - For multi-node: IBGDA driver configured (see --configure-drivers)
#
# Usage:
# bash scripts/install_ep_kernels.sh
#
# Options:
# --workspace DIR Build directory (default: ./ep_kernels_workspace)
# --deepep-ref REF DeepEP commit hash (default: 73b6ea4)
# --nvshmem-ver VER NVSHMEM version (default: 3.3.24)
# --configure-drivers Also configure IBGDA drivers (requires sudo, needs reboot)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPEP_COMMIT_HASH="73b6ea4"
NVSHMEM_VER="3.3.24"
WORKSPACE="$REPO_ROOT/ep_kernels_workspace"
CONFIGURE_DRIVERS=0
while [[ $# -gt 0 ]]; do
case $1 in
--workspace) WORKSPACE="$2"; shift 2 ;;
--deepep-ref) DEEPEP_COMMIT_HASH="$2"; shift 2 ;;
--nvshmem-ver) NVSHMEM_VER="$2"; shift 2 ;;
--configure-drivers) CONFIGURE_DRIVERS=1; shift ;;
*) echo "Unknown argument: $1" >&2; exit 1 ;;
esac
done
# Skip if DeepEP is already installed
if python -c "import deep_ep" 2>/dev/null; then
echo "DeepEP already installed, skipping."
exit 0
fi
# ── Auto-detect CUDA toolkit matching torch ───────────────────────────────────
TORCH_CUDA_VER=$(python -c "import torch; print(torch.version.cuda)")
CUDA_MAJOR_MINOR=$(echo "$TORCH_CUDA_VER" | grep -oP '^\d+\.\d+')
CUDA_MAJOR=$(echo "$CUDA_MAJOR_MINOR" | cut -d. -f1)
CUDA_HOME="/usr/local/cuda-${CUDA_MAJOR_MINOR}"
if [ ! -x "$CUDA_HOME/bin/nvcc" ]; then
echo "ERROR: Could not find CUDA toolkit matching torch (cuda ${TORCH_CUDA_VER}) at ${CUDA_HOME}" >&2
echo "Install it with: sudo apt install cuda-toolkit-${CUDA_MAJOR_MINOR//./-}" >&2
exit 1
fi
export CUDA_HOME
# Verify versions actually match
NVCC_VER=$("$CUDA_HOME/bin/nvcc" --version | grep -oP 'release \K[\d.]+')
echo "Torch CUDA: ${TORCH_CUDA_VER}, nvcc: ${NVCC_VER} (${CUDA_HOME})"
# ── Auto-detect GPU architecture ──────────────────────────────────────────────
GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader,nounits -i 0 2>/dev/null)
case "$GPU_NAME" in
*H100*|*H200*|*H800*) TORCH_CUDA_ARCH_LIST="9.0" ;;
*B100*|*B200*|*GB200*) TORCH_CUDA_ARCH_LIST="10.0" ;;
*)
echo "Could not auto-detect GPU arch from '$GPU_NAME'. Set TORCH_CUDA_ARCH_LIST manually." >&2
echo " Hopper (H100/H200): TORCH_CUDA_ARCH_LIST=9.0" >&2
echo " Blackwell (B200): TORCH_CUDA_ARCH_LIST=10.0" >&2
exit 1
;;
esac
export TORCH_CUDA_ARCH_LIST
echo "================================================================"
echo " Installing DeepEP kernels"
echo " CUDA: ${CUDA_HOME} (${NVCC_VER})"
echo " GPU: ${GPU_NAME} (arch ${TORCH_CUDA_ARCH_LIST})"
echo " DeepEP: ${DEEPEP_COMMIT_HASH}"
echo " NVSHMEM: ${NVSHMEM_VER}"
echo " Workspace: ${WORKSPACE}"
echo "================================================================"
mkdir -p "$WORKSPACE"
# ── Step 1: Install build deps ────────────────────────────────────────────────
echo ""
echo "--- Installing build dependencies ---"
cd "$REPO_ROOT"
uv pip install cmake ninja
# ── Step 2: Download and extract NVSHMEM ──────────────────────────────────────
echo ""
echo "--- Setting up NVSHMEM ${NVSHMEM_VER} ---"
ARCH=$(uname -m)
case "${ARCH,,}" in
x86_64|amd64) NVSHMEM_SUBDIR="linux-x86_64" ;;
aarch64|arm64) NVSHMEM_SUBDIR="linux-sbsa" ;;
*) echo "Unsupported architecture: ${ARCH}" >&2; exit 1 ;;
esac
NVSHMEM_DIR="$WORKSPACE/nvshmem"
if [ ! -d "$NVSHMEM_DIR/lib" ]; then
NVSHMEM_FILE="libnvshmem-${NVSHMEM_SUBDIR}-${NVSHMEM_VER}_cuda${CUDA_MAJOR}-archive.tar.xz"
NVSHMEM_URL="https://developer.download.nvidia.com/compute/nvshmem/redist/libnvshmem/${NVSHMEM_SUBDIR}/${NVSHMEM_FILE}"
echo "Downloading ${NVSHMEM_URL}"
curl -fSL "${NVSHMEM_URL}" -o "$WORKSPACE/${NVSHMEM_FILE}"
tar -xf "$WORKSPACE/${NVSHMEM_FILE}" -C "$WORKSPACE"
mv "$WORKSPACE/${NVSHMEM_FILE%.tar.xz}" "$NVSHMEM_DIR"
rm -f "$WORKSPACE/${NVSHMEM_FILE}"
rm -rf "$NVSHMEM_DIR/lib/bin" "$NVSHMEM_DIR/lib/share"
echo "NVSHMEM extracted to ${NVSHMEM_DIR}"
else
echo "NVSHMEM already present at ${NVSHMEM_DIR}, skipping download"
fi
export CMAKE_PREFIX_PATH="${NVSHMEM_DIR}/lib/cmake:${CMAKE_PREFIX_PATH:-}"
export NVSHMEM_DIR
# ── Step 3: Build and install DeepEP ──────────────────────────────────────────
echo ""
echo "--- Building DeepEP (${DEEPEP_COMMIT_HASH}) ---"
DEEPEP_DIR="$WORKSPACE/DeepEP"
if [ ! -d "$DEEPEP_DIR/.git" ]; then
git clone https://github.com/deepseek-ai/DeepEP "$DEEPEP_DIR"
fi
cd "$DEEPEP_DIR"
git fetch origin
git checkout "$DEEPEP_COMMIT_HASH"
WHEEL_DIR="$REPO_ROOT/deps"
mkdir -p "$WHEEL_DIR"
python setup.py bdist_wheel --dist-dir "$WHEEL_DIR"
WHEEL=$(ls "$WHEEL_DIR"/deep_ep*.whl | head -1)
echo ""
echo "--- DeepEP wheel built at: $WHEEL ---"
# ── Step 4 (optional): Configure IBGDA drivers ───────────────────────────────
if [ "$CONFIGURE_DRIVERS" -eq 1 ]; then
echo ""
echo "--- Configuring IBGDA drivers (requires sudo) ---"
echo 'options nvidia NVreg_EnableStreamMemOPs=1 NVreg_RegistryDwords="PeerMappingOverride=1;"' | sudo tee -a /etc/modprobe.d/nvidia.conf
if command -v update-initramfs &> /dev/null; then
sudo update-initramfs -u
elif command -v dracut &> /dev/null; then
sudo dracut --force
else
echo "No supported initramfs update tool found." >&2
exit 1
fi
echo ""
echo "IBGDA configured. Please REBOOT the system to apply changes."
fi
echo ""
echo "================================================================"
echo " DeepEP installation complete"
echo " NVSHMEM: ${NVSHMEM_DIR}"
echo " To verify: uv run python -c 'import deep_ep; print(deep_ep.__file__)'"
echo "================================================================"
+71
View File
@@ -0,0 +1,71 @@
#!/bin/bash
set -euo pipefail
# Build UCX 1.19.x with CUDA + IB support, then build NIXL against it.
# Installs the unrepaired wheel (no auditwheel) so NIXL uses the UCX libs
# directly from third_party/ucx/ at runtime via LD_LIBRARY_PATH.
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
VENV_BIN="$PROJECT_DIR/.venv/bin"
PYTHON="$VENV_BIN/python"
WORKSPACE="$PROJECT_DIR/nixl_workspace"
mkdir -p "$WORKSPACE"
UCX_SRC="$WORKSPACE/ucx_source"
UCX_INSTALL="$PROJECT_DIR/third_party/ucx"
NIXL_SRC="$WORKSPACE/nixl_source"
NIXL_VERSION="${NIXL_VERSION:-0.10.1}"
CUDA_PATH="${CUDA_HOME:-/usr/local/cuda}"
NPROC=$(nproc)
export PATH="$VENV_BIN:$PATH"
echo "=== Building UCX 1.19.x with CUDA + IB ==="
if [ ! -d "$UCX_SRC" ]; then
git clone https://github.com/openucx/ucx.git "$UCX_SRC"
fi
cd "$UCX_SRC"
git checkout v1.19.x
if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
./autogen.sh
./configure \
--prefix="$UCX_INSTALL" \
--enable-shared \
--disable-static \
--disable-doxygen-doc \
--enable-optimizations \
--enable-cma \
--enable-devel-headers \
--enable-mt \
--with-verbs \
--with-cuda="$CUDA_PATH" \
--with-ze=no
make -j"$NPROC"
make install
echo "=== UCX installed to $UCX_INSTALL ==="
else
echo "=== UCX already built, skipping ==="
fi
echo "=== Building NIXL $NIXL_VERSION ==="
if [ ! -d "$NIXL_SRC" ]; then
git clone https://github.com/ai-dynamo/nixl.git "$NIXL_SRC"
else
cd "$NIXL_SRC" && git fetch --tags
fi
cd "$NIXL_SRC"
git checkout "$NIXL_VERSION"
export PKG_CONFIG_PATH="$UCX_INSTALL/lib/pkgconfig"
export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}"
# Build and install directly (no auditwheel) so NIXL links to our UCX at runtime
WHEEL_DIR="$PROJECT_DIR/deps"
mkdir -p "$WHEEL_DIR"
uv pip install pip 2>/dev/null
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
WHEEL=$(ls "$WHEEL_DIR"/nixl*.whl | head -1)
echo "=== NIXL wheel built at: $WHEEL ==="
+30
View File
@@ -0,0 +1,30 @@
#!/bin/bash
# Builds the patched vllm-router wheel (Rust via setuptools-rust) from our fork.
# Requires: Rust toolchain (cargo), Python 3.8+, and uv or pip.
# Override output dir: VLLM_ROUTER_WHEEL_DIR=/path/to/dir
set -euo pipefail
REPO_URL="https://github.com/S1ro1/router.git"
BRANCH="fix/preserve-extra-fields-disagg"
BUILD_DIR="/tmp/vllm-router-build"
SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
OUTPUT_DIR="${VLLM_ROUTER_WHEEL_DIR:-$SCRIPT_DIR/deps}"
echo "Cloning $REPO_URL (branch: $BRANCH)..."
rm -rf "$BUILD_DIR"
git clone --depth 1 --branch "$BRANCH" "$REPO_URL" "$BUILD_DIR"
echo "Building wheel -> $OUTPUT_DIR ..."
mkdir -p "$OUTPUT_DIR"
if command -v uv >/dev/null 2>&1; then
uv build --wheel --out-dir "$OUTPUT_DIR" "$BUILD_DIR"
else
(cd "$BUILD_DIR" && python3 -m pip wheel . --no-deps -w "$OUTPUT_DIR")
fi
echo "Cleaning up..."
rm -rf "$BUILD_DIR"
wheel=$(ls -1t "$OUTPUT_DIR"/*.whl 2>/dev/null | head -1)
echo "Done. Wheel: $wheel"
echo "Install: uv pip install $wheel"
+93 -18
View File
@@ -17,17 +17,60 @@ from pathlib import Path
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
)
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeVLM
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.utils import default_dtype
setup_logger("info")
def _qwen3_5_moe_vlm_config():
"""Build a tiny composite VLM config for Qwen3.5 MoE."""
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
tc.hidden_size = 256
tc.num_hidden_layers = 2
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
tc.num_experts_per_tok = 2
tc.max_position_embeddings = 512
tc.linear_key_head_dim = 32
tc.linear_value_head_dim = 32
tc.linear_num_key_heads = 4
tc.linear_num_value_heads = 8
tc.layer_types = ["full_attention", "linear_attention"]
tc.use_cache = False
vc = config.vision_config
vc.depth = 2
vc.hidden_size = 128
vc.intermediate_size = 256
vc.num_heads = 4
vc.out_hidden_size = tc.hidden_size
config.image_token_id = 250
config.video_token_id = 251
config.vision_start_token_id = 252
config.vision_end_token_id = 253
return config
ARCH_PRESETS = {
"glm4_moe": {
"config_class": Glm4MoeConfig,
@@ -87,6 +130,14 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
"qwen3_5_moe_vlm": {
"config_fn": _qwen3_5_moe_vlm_config,
"hf_model_class": HFQwen3_5MoeVLM,
"prime_model_class": PrimeRLQwen3_5MoeVLM,
"tokenizer_source": "Qwen/Qwen3.5-35B-A3B",
"is_vlm": True,
},
# glm_moe_dsa: HF implementation is incorrect, not supported here
}
@@ -114,12 +165,20 @@ def _create_hf_model_from_config(preset, config):
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
def _build_config(preset):
"""Build model config from preset (handles both config_class and config_fn styles)."""
if "config_fn" in preset:
return preset["config_fn"]()
return preset["config_class"](**preset["config_kwargs"])
def create(arch: str, output_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
config = preset["config_class"](**preset["config_kwargs"])
config = _build_config(preset)
text_config = getattr(config, "text_config", config)
print(f"Creating mini {arch} model...")
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
print(f" hidden_size={text_config.hidden_size}, layers={text_config.num_hidden_layers}")
with torch.device("cpu"):
model = _create_hf_model(preset, config)
@@ -138,14 +197,20 @@ def create(arch: str, output_dir: Path) -> None:
def verify(arch: str, model_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
is_vlm = preset.get("is_vlm", False)
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
trust_remote_code = preset["hf_model_class"] is None
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
config._attn_implementation = "sdpa"
if hasattr(config, "text_config"):
config.text_config._attn_implementation = "sdpa"
text_config = getattr(config, "text_config", config)
vocab_size = text_config.vocab_size
hf_model = _load_hf_model(preset, model_dir, config).to(device="cuda", dtype=torch.float32)
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = _load_hf_model(preset, model_dir, config)
prime_model = preset["prime_model_class"]._from_config(config)
with torch.no_grad():
@@ -155,29 +220,39 @@ def verify(arch: str, model_dir: Path) -> None:
inject_prime_lm_head(prime_model, chunk_size=None)
# Use tokens in safe range (avoid special VLM token IDs)
max_token = min(vocab_size, 200) if is_vlm else vocab_size
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, config.vocab_size, (1, 64))
input_ids = torch.randint(0, max_token, (1, 64))
position_ids = torch.arange(1, 65).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids)
hf_output = hf_model(input_ids=input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids)
logits_diff = prime_output["logits"] - hf_output.logits
max_diff = logits_diff.abs().max().item()
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
if is_vlm:
# HF GatedDeltaNet has a dtype bug in float32 mode; just verify non-NaN output
assert not torch.isnan(prime_output["logits"]).any(), "PrimeRL VLM output contains NaN"
assert prime_output["logits"].shape == hf_output.logits.shape
print(" VLM forward pass verified (shape match, no NaN)")
else:
logits_diff = prime_output["logits"] - hf_output.logits
max_diff = logits_diff.abs().max().item()
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
# Roundtrip weight conversion: HF -> PrimeRL -> HF
# Normalize both through the same roundtrip to handle expert format differences
prime_cls = preset["prime_model_class"]
with torch.no_grad():
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
with torch.device("cuda"), default_dtype(torch.float32):
hf_roundtrip = _create_hf_model_from_config(preset, config)
hf_roundtrip.load_state_dict(roundtrip_state_dict)
roundtrip_sd = prime_cls.convert_to_hf(dict(prime_model.state_dict()))
orig_sd = dict(hf_model.state_dict())
prime_cls.convert_to_prime(orig_sd)
prime_cls.convert_to_hf(orig_sd)
hf_roundtrip_output = hf_roundtrip(input_ids, position_ids)
roundtrip_diff = hf_roundtrip_output.logits - hf_output.logits
max_roundtrip_diff = roundtrip_diff.abs().max().item()
print(f" HF -> PrimeRL -> HF roundtrip max logits diff: {max_roundtrip_diff:.6f}")
assert max_roundtrip_diff < 0.1, f"Roundtrip logits mismatch: max diff {max_roundtrip_diff}"
for key in orig_sd:
assert key in roundtrip_sd, f"Missing key after roundtrip: {key}"
assert torch.equal(orig_sd[key], roundtrip_sd[key]), f"Roundtrip mismatch at {key}"
print(" HF -> PrimeRL -> HF weight roundtrip verified")
print(" Verification passed.")
+62 -2
View File
@@ -20,6 +20,64 @@ uv run inference --model.name Qwen/Qwen3-0.6B --model.max_model_len 2048 --model
uv run inference @ path/to/config.toml --server.port 8001 --gpu-memory-utilization 0.5
```
## SLURM scheduling
The inference entrypoint supports optional SLURM scheduling, following the same patterns as SFT and RL.
### Single-node SLURM
```toml
# inference_slurm.toml
output_dir = "/shared/outputs/my-inference"
[model]
name = "Qwen/Qwen3-8B"
[parallel]
tp = 8
[slurm]
job_name = "my-inference"
partition = "cluster"
```
```bash
uv run inference @ inference_slurm.toml
```
### Multi-node SLURM (independent vLLM replicas)
Each node runs an independent vLLM instance. No cross-node parallelism — TP and DP must fit within a single node's GPUs.
```toml
# inference_multinode.toml
output_dir = "/shared/outputs/my-inference"
[model]
name = "PrimeIntellect/INTELLECT-3-RL-600"
[parallel]
tp = 8
dp = 1
[deployment]
type = "multi_node"
num_nodes = 4
gpus_per_node = 8
[slurm]
job_name = "my-inference"
partition = "cluster"
```
### Dry run
Add `dry_run = true` to generate the sbatch script without submitting:
```bash
uv run inference @ config.toml --dry-run true
```
## Custom endpoints
The server extends vLLM with:
@@ -43,7 +101,9 @@ curl http://localhost:8000/v1/chat/completions \
## Key files
- `src/prime_rl/inference/server.py` — entry point, env var setup
- `src/prime_rl/inference/config.py` — `InferenceConfig` and all sub-configs
- `src/prime_rl/entrypoints/inference.py` — entrypoint with local/SLURM routing
- `src/prime_rl/inference/server.py` — vLLM env setup
- `src/prime_rl/configs/inference.py` — `InferenceConfig` and all sub-configs
- `src/prime_rl/inference/vllm/server.py` — FastAPI routes and vLLM monkey-patches
- `src/prime_rl/templates/inference.sbatch.j2` — SLURM template (handles both single and multi-node)
- `configs/debug/infer.toml` — minimal debug config
+59
View File
@@ -0,0 +1,59 @@
---
name: installation
description: How to install prime-rl and its optional dependencies. Use when setting up the project, installing extras like deep-gemm for FP8 models, or troubleshooting dependency issues.
---
# Installation
## Basic install
```bash
uv sync
```
This installs all core dependencies defined in `pyproject.toml`.
## All extras at once
The recommended way to install for most users:
```bash
uv sync --all-extras
```
This installs all optional extras (flash-attn, flash-attn-cute, etc.) in one go.
## Mamba-SSM (NemotronH models)
For NemotronH (hybrid Mamba-Transformer-MoE) models, install `mamba-ssm` for Triton-based SSD kernels that match vLLM's precision:
```bash
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
```
Requires `nvcc` (CUDA toolkit). Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch implementation which computes softplus in bf16, causing ~0.4 KL divergence vs vLLM.
Note: do NOT install `causal-conv1d` unless your GPU architecture matches the compiled CUDA kernels. The code automatically falls back to PyTorch nn.Conv1d when it's absent.
## FP8 inference with deep-gemm
For certain models like GLM-5-FP8, you need `deep-gemm`. Install it via the `fp8-inference` dependency group:
```bash
uv sync --group fp8-inference
```
This installs the pre-built `deep-gemm` wheel. No CUDA build step is needed.
## Dev dependencies
```bash
uv sync --group dev
```
Installs pytest, ruff, pre-commit, and other development tools.
## Key files
- `pyproject.toml` — all dependencies, extras, and dependency groups
- `uv.lock` — pinned lockfile (update with `uv sync --all-extras`)
+99 -20
View File
@@ -5,7 +5,7 @@ description: How to write and use TOML configs in prime-rl. Use when creating co
# TOML Config
All prime-rl commands use pydantic-settings with TOML configs and CLI overrides.
All prime-rl commands use `pydantic_config` (tyro-backed) with TOML configs and CLI overrides.
## Running with configs
@@ -19,11 +19,17 @@ uv run rl @ configs/debug/rl/train.toml
uv run inference @ config.toml --model.name Qwen/Qwen3-0.6B --server.port 8001
# Boolean flags: no value needed
uv run inference --model.enforce_eager # sets to true
uv run inference --no-model.enforce_eager # sets to false
uv run inference --model.enforce-eager # sets to true
uv run inference --no-model.enforce-eager # sets to false
# CLI-only (no TOML file)
uv run inference --model.name Qwen/Qwen3-0.6B --model.max_model_len 2048
uv run inference --model.name Qwen/Qwen3-0.6B --model.max-model-len 2048
# Compose multiple config files (later files override earlier ones)
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
# Nested config files: load a config for a specific section
uv run rl --model @ model.toml --data @ data.toml
```
## TOML structure
@@ -46,19 +52,6 @@ port = 8000
Putting a top-level field after a section header nests it inside that section, which causes validation errors.
## Config inheritance
Configs can inherit from other TOML files:
```toml
toml_files = ["base.toml"]
[model]
name = "Qwen/Qwen3-0.6B" # overrides base
```
Paths in `toml_files` are relative to the file containing the field.
## Setting None
Use the string `"None"` in TOML to set a field to None:
@@ -67,20 +60,106 @@ Use the string `"None"` in TOML to set a field to None:
max_model_len = "None"
```
## SLURM mode
Both `rl` and `sft` commands support SLURM execution via an optional `[slurm]` section. When present, the run is submitted as a SLURM job instead of running locally.
SLURM configs are composed with the base config via CLI:
```bash
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
```
### RL SLURM
```toml
output_dir = "/shared/experiments/my-run"
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
gpus_per_node = 8
# nodes_per_fsdp_group = 1
[slurm]
job_name = "my-rl-job"
# dry_run = true # generate script without submitting
# template_path = "path/to/custom.sh.j2"
# project_dir = "/path/to/project"
```
When `[slurm]` is set for RL:
- `output_dir` must be explicitly set (the default `outputs` is rejected)
- Teacher inference is not supported in multi-node deployment
### SFT SLURM
```toml
output_dir = "/shared/experiments/my-sft-run"
[deployment]
type = "multi_node"
num_nodes = 2
gpus_per_node = 8
# nodes_per_fsdp_group = 1
[slurm]
job_name = "my-sft-job"
# dry_run = true
# template_path = "path/to/custom.sh.j2"
# project_dir = "/path/to/project"
```
SFT deployment follows the same pattern as RL:
- `[deployment]` configures node/GPU allocation (`single_node` default or `multi_node`)
- `[slurm]` configures SLURM submission (job name, partition, template)
- `output_dir` must be explicitly set when using SLURM
- Multi-node deployment requires `[slurm]` to be set
## SFT Distillation (Hard Distillation) With Teacher Rollouts
Use this when the teacher is an external OpenAI-compatible endpoint and you want to train from teacher completions directly (no teacher token logprobs required).
```toml
[trainer.loss]
type = "sft"
[orchestrator]
use_token_client = false
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
skip_model_check = true
[orchestrator.teacher_rollout_model.model]
name = "teacher-model-name"
```
Notes:
- `orchestrator.teacher_rollout_model` switches rollout generation to the external teacher endpoint.
- `use_token_client = false` is required when `orchestrator.teacher_rollout_model` is set.
- `trainer.loss.type = "sft"` makes the RL trainer optimize masked NLL like SFT.
- In this mode, omit `[inference]`.
- Image input is supported when using a VLM student model and OpenAI-style image messages (`data:image/...`).
## Available commands
All accept `@ config.toml` and CLI overrides:
| Command | Config class | Description |
|---------|-------------|-------------|
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer |
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer (local or SLURM) |
| `uv run inference` | `InferenceConfig` | vLLM inference server |
| `uv run trainer` | trainer config | RL trainer |
| `uv run orchestrator` | orchestrator config | Rollout orchestrator |
| `uv run env-server` | env server config | Environment server |
| `uv run sft` | SFT config | Supervised fine-tuning |
| `uv run sft` | SFT config | Supervised fine-tuning (local or SLURM) |
## Key files
- `src/prime_rl/utils/pydantic_config.py` — `parse_argv`, `BaseSettings`, `@` syntax parsing
- `src/prime_rl/utils/config.py` — `BaseConfig`, `cli`, `get_all_fields`
- `src/prime_rl/entrypoints/rl.py` — unified RL entrypoint (local + SLURM)
- `src/prime_rl/configs/rl.py` — `RLConfig`, `SlurmConfig, DeploymentConfig`
- `src/prime_rl/entrypoints/sft.py` — unified SFT entrypoint (local + SLURM)
- `src/prime_rl/configs/sft.py` — `SFTConfig`
- `configs/` — all config files, organized by task
View File
@@ -3,12 +3,12 @@ from typing import Annotated
from pydantic import Field
from prime_rl.orchestrator.config import EnvConfig
from prime_rl.utils.config import LogConfig
from prime_rl.utils.pydantic_config import BaseSettings
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseSettings):
class EnvServerConfig(BaseConfig):
"""Configures an environment server."""
env: EnvConfig = EnvConfig()
@@ -1,9 +1,11 @@
from argparse import Namespace
from typing import Annotated, Any, Literal
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
from prime_rl.utils.utils import rgetattr, rsetattr
# TODO: Set thinking/ solution budget
@@ -38,16 +40,9 @@ class ParallelConfig(BaseConfig):
return f"tp={self.tp} dp={self.dp}"
class ModelConfig(BaseConfig):
class ModelConfig(BaseModelConfig):
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html)."""
name: Annotated[
str,
Field(
description="Name or path of the HF model to use.",
),
] = "Qwen/Qwen3-0.6B"
dtype: Annotated[
Literal["auto", "float16", "bfloat16", "float32"],
Field(
@@ -76,19 +71,13 @@ class ModelConfig(BaseConfig):
),
] = False
enable_auto_tool_choice: Annotated[
bool,
Field(
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`",
),
] = False
tool_call_parser: Annotated[
str,
str | None,
Field(
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`",
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
'Set to "auto" to infer from the model name.',
),
] = "hermes"
] = None
reasoning_parser: Annotated[
str | None,
@@ -105,7 +94,7 @@ class ModelConfig(BaseConfig):
] = None
class WeightBroadcastConfig(BaseSettings):
class WeightBroadcastConfig(BaseConfig):
"""Configures weight broadcast settings."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
@@ -117,15 +106,77 @@ class WeightBroadcastConfig(BaseSettings):
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_all2allv",
"naive",
"pplx",
]
class InferenceConfig(BaseSettings):
class BaseInferenceDeploymentConfig(BaseModel):
"""Base deployment config for inference."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
"""Configures a single-node inference deployment."""
type: Literal["single_node"] = "single_node"
class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
"""Configures a multi-node inference deployment. Each node runs an independent vLLM replica."""
type: Literal["multi_node"] = "multi_node"
num_nodes: Annotated[int, Field(ge=1, description="Number of inference nodes.")] = 2
router_port: Annotated[int, Field(description="Port for the vllm-router.")] = 8000
backend_port: Annotated[int, Field(description="Port for vLLM backend instances.")] = 8100
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
"""Configures a disaggregated prefill/decode inference deployment.
Each inference replica is split into separate prefill and decode node groups.
Requires NIXL for KV transfer and a vllm-router for request routing.
"""
type: Literal["disaggregated"] = "disaggregated"
num_prefill_nodes: Annotated[int, Field(ge=1, description="Number of prefill nodes per replica.")] = 1
num_decode_nodes: Annotated[int, Field(ge=1, description="Number of decode nodes per replica.")] = 1
router_port: Annotated[int, Field(description="Port for the vllm-router on each replica.")] = 8000
prefill_port: Annotated[int, Field(description="Port for prefill vLLM instances.")] = 8100
decode_port: Annotated[int, Field(description="Port for decode vLLM instances.")] = 8200
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
InferenceDeploymentConfig: TypeAlias = Annotated[
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
Field(discriminator="type"),
]
class InferenceConfig(BaseConfig):
"""Configures inference."""
# The server configuration
server: ServerConfig = ServerConfig()
# The model configuration
model: ModelConfig = ModelConfig()
model: ModelConfig = Field(default_factory=ModelConfig)
# The parallel configuration
parallel: ParallelConfig = ParallelConfig()
@@ -178,11 +229,28 @@ class InferenceConfig(BaseSettings):
api_server_count: Annotated[
int,
Field(
ge=1,
description="The number of API servers to use. Passed to vLLM as `--api-server-count`",
ge=0,
description="The number of API servers to use. Passed to vLLM as `--api-server-count`. Set to 0 for headless mode.",
),
] = 1
data_parallel_size_local: Annotated[
int | None,
Field(
ge=1,
description="Number of data parallel replicas to run on this node. Passed to vLLM as `--data-parallel-size-local`.",
),
] = None
data_parallel_rpc_port: Annotated[
int,
Field(
ge=1,
le=65535,
description="RPC port for data parallel communication. Passed to vLLM as `--data-parallel-rpc-port`.",
),
] = 13345
seed: Annotated[
int,
Field(
@@ -190,13 +258,109 @@ class InferenceConfig(BaseSettings):
),
] = 0
enable_expert_parallel: Annotated[
bool,
Field(
description="Enable expert parallelism for MoE models. Passed to vLLM as `--enable-expert-parallel`.",
),
] = False
all2all_backend: Annotated[
All2AllBackend,
Field(
description="All-to-all backend for expert parallel communication. Passed to vLLM as `--all2all-backend`.",
),
] = "allgather_reducescatter"
enable_eplb: Annotated[
bool,
Field(
description="Enable expert parallel load balancer (EPLB). Passed to vLLM as `--enable-eplb`.",
),
] = False
use_deep_gemm: Annotated[
bool,
Field(
description="Force DeepGEMM FP8 kernels via VLLM_USE_DEEP_GEMM=1. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8).",
),
] = False
weight_broadcast: Annotated[WeightBroadcastConfig, Field(description="The weight broadcast config.")] = (
WeightBroadcastConfig()
)
enable_return_routed_experts: Annotated[
bool,
Field(
description="Whether to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts`",
),
] = False
vllm_extra: Annotated[
dict[str, Any],
Field(
description="Extra arguments to pass to vLLM. These are applied as attributes on the vLLM namespace after config translation.",
),
] = {}
# Launcher-only fields
deployment: Annotated[
InferenceDeploymentConfig,
Field(
description="Deployment configuration for inference.",
),
] = SingleNodeInferenceDeploymentConfig()
slurm: Annotated[
SlurmConfig | None,
Field(
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
),
] = None
output_dir: Annotated[Path, Field(description="Directory for SLURM logs and generated scripts.")] = Path("outputs")
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
@model_validator(mode="after")
def round_up_max_lora_rank(self):
"""Round up max_lora_rank to the nearest valid vLLM value.
def validate_multi_node_requires_slurm(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
def auto_setup_disaggregated(self):
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
if self.deployment.type == "disaggregated":
if "enable_expert_parallel" not in self.model_fields_set:
self.enable_expert_parallel = True
if "enable_eplb" not in self.model_fields_set:
self.enable_eplb = False
gpus_per_node = self.deployment.gpus_per_node
tp = self.parallel.tp
dp_per_node = gpus_per_node // tp
if self.data_parallel_size_local is None:
self.data_parallel_size_local = dp_per_node
if self.parallel.dp == 1:
self.parallel.dp = dp_per_node
if self.api_server_count == 1:
self.api_server_count = dp_per_node
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
@@ -219,8 +383,14 @@ class InferenceConfig(BaseSettings):
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.api_server_count < self.parallel.dp:
self.api_server_count = self.parallel.dp
if self.vllm_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
@@ -237,12 +407,13 @@ class InferenceConfig(BaseSettings):
"model.max_model_len": "max_model_len",
"model.enforce_eager": "enforce_eager",
"model.trust_remote_code": "trust_remote_code",
"model.enable_auto_tool_choice": "enable_auto_tool_choice",
"model.tool_call_parser": "tool_call_parser",
"model.reasoning_parser": "reasoning_parser",
"model.rope_scaling": "rope_scaling",
"parallel.tp": "tensor_parallel_size",
"parallel.dp": "data_parallel_size",
"data_parallel_size_local": "data_parallel_size_local",
"data_parallel_rpc_port": "data_parallel_rpc_port",
"enable_lora": "enable_lora",
"enable_prefix_caching": "enable_prefix_caching",
"max_loras": "max_loras",
@@ -250,11 +421,16 @@ class InferenceConfig(BaseSettings):
"max_lora_rank": "max_lora_rank",
"gpu_memory_utilization": "gpu_memory_utilization",
"api_server_count": "api_server_count",
"enable_return_routed_experts": "enable_return_routed_experts",
"enable_expert_parallel": "enable_expert_parallel",
"all2all_backend": "all2all_backend",
"enable_eplb": "enable_eplb",
"seed": "seed",
}
for key in get_all_fields(self):
value = rgetattr(self, key.replace("-", "_"))
rsetattr(namespace, to_vllm.get(key, key), value)
for config_key, vllm_key in to_vllm.items():
value = rgetattr(self, config_key.replace("-", "_"))
rsetattr(namespace, vllm_key, value)
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
@@ -1,20 +1,19 @@
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import AliasChoices, BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
from prime_rl.utils.config import (
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
TransportConfig,
WandbWithExtrasConfig,
)
from prime_rl.utils.config import (
ModelConfig as BaseModelConfig,
)
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
from prime_rl.utils.config import BaseConfig
class OptimizerConfig(BaseConfig):
@@ -288,6 +287,25 @@ class EnvConfig(BaseConfig):
),
),
] = {}
max_retries: Annotated[
int,
Field(
ge=0,
description="Maximum number of times the environment will retry a failed rollout.",
),
] = 0
@property
def resolved_name(self) -> str:
return self.name or self.id.split("@")[0]
@model_validator(mode="after")
def validate_env_name(self):
if self.resolved_name == "all":
raise ValueError(
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
)
return self
class EvalEnvConfig(EnvConfig):
@@ -313,17 +331,6 @@ class EvalEnvConfig(EnvConfig):
),
] = 0
# TODO: should live on the EnvConfig and also apply to training envs but
# this is hard right now because we use the vf.EnvGroup which treats all
# envs as one. for now training envs hardcode no retries, but we should
# probably treat them like environment groups long-term
max_retries: Annotated[
int,
Field(
description="Maximum number of times the environment will try to retry running a rollout.",
),
] = 0
class ValConfig(BaseConfig):
"""Configures the validation of the model."""
@@ -383,6 +390,14 @@ class EvalConfig(BaseConfig):
),
] = False
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(f"Duplicate eval environment names: {set(duplicates)}. Each env must have a unique name.")
return self
class CheckpointConfig(BaseConfig):
"""Configures checkpointing the orchestrator."""
@@ -503,17 +518,6 @@ class BufferConfig(BaseConfig):
),
] = ["task", "prompt"]
skip_verification: Annotated[
bool,
Field(
description=(
"Whether to skip verification of rollouts using the environment's rubric. "
"If True, rewards are always set to 0, online_difficulty_filtering is disabled, "
"and easy/hard thresholds are not used."
),
),
] = False
@model_validator(mode="after")
def validate_thresholds(self):
if self.easy_threshold is not None and self.hard_threshold is not None:
@@ -526,33 +530,31 @@ class BufferConfig(BaseConfig):
assert all(ratio > 0 for ratio in self.env_ratios), "All env_ratios must be positive."
return self
@model_validator(mode="after")
def validate_skip_verification(self):
"""Validate that skip_verification is not used with reward-dependent features."""
if self.skip_verification:
if self.online_difficulty_filtering:
raise ValueError(
"skip_verification cannot be True when online_difficulty_filtering is True. "
"These features depend on rewards which are disabled when skip_verification=True."
)
if self.easy_threshold is not None:
raise ValueError(
"skip_verification cannot be True when easy_threshold is set. "
"Easy threshold depends on rewards which are disabled when skip_verification=True."
)
if self.hard_threshold is not None:
raise ValueError(
"skip_verification cannot be True when hard_threshold is set. "
"Hard threshold depends on rewards which are disabled when skip_verification=True."
)
return self
class VerificationConfig(BaseConfig):
"""Configures rollout verification and rubric scoring."""
enabled: Annotated[
bool,
Field(
description=(
"Whether to verify training rollouts using the environment rubric. "
"If False, rewards are always set to 0."
),
),
] = True
class AdvantageConfig(BaseConfig):
class DefaultAdvantageConfig(BaseModel):
"""Config for the default advantage."""
model_config = ConfigDict(extra="forbid")
type: Literal["default"] = "default"
length_weighted_mean: bool = False
length_shaping_alpha: Annotated[
float | None,
Field(description="Penalty coefficient for Group Relative Reward Rescaling (GR³). Recommended value: 0.33"),
] = None
class CustomAdvantageConfig(BaseModel):
@@ -567,15 +569,9 @@ class CustomAdvantageConfig(BaseModel):
]
def _advantage_config_discriminator(v: Any) -> str:
if isinstance(v, dict):
return v.get("type", "default")
return getattr(v, "type", "default")
AdvantageConfigType: TypeAlias = Annotated[
Annotated[AdvantageConfig, Tag("default")] | Annotated[CustomAdvantageConfig, Tag("custom")],
Discriminator(_advantage_config_discriminator),
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
@@ -629,7 +625,7 @@ class RepetitionFilterConfig(BaseModel):
] = 0.99
FilterConfigType: TypeAlias = Annotated[
FilterConfig: TypeAlias = Annotated[
GibberishFilterConfig | RepetitionFilterConfig,
Field(discriminator="type"),
]
@@ -649,9 +645,23 @@ class NCCLWeightBroadcastConfig(BaseModel):
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
quantize_in_weight_transfer: Annotated[
bool,
Field(description="Use kernel-format FP8 quantized NCCL transfer for weight updates."),
] = False
inference_world_size: Annotated[
int,
Field(
ge=1,
description="Total number of inference GPUs across all servers. Used by init_nccl_broadcast to compute per-server rank offsets.",
),
] = 1
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class TeacherModelConfig(BaseConfig):
@@ -668,7 +678,21 @@ class TeacherModelConfig(BaseConfig):
] = ModelConfig()
class OrchestratorConfig(BaseSettings):
class TeacherRolloutModelConfig(BaseConfig):
"""Configures an external teacher model used to generate rollout text."""
client: Annotated[
ClientConfig,
Field(description="The OAI client configuration for rollout generation."),
] = ClientConfig()
model: Annotated[
ModelConfig,
Field(description="The model configuration for rollout generation."),
] = ModelConfig()
class OrchestratorConfig(BaseConfig):
"""Configures the orchestrator for RL training."""
# The OAI client configuration
@@ -690,6 +714,17 @@ class OrchestratorConfig(BaseSettings):
),
] = None
# External teacher rollout model configuration (optional)
teacher_rollout_model: Annotated[
TeacherRolloutModelConfig | None,
Field(
description=(
"Optional external teacher model used for rollout generation. "
"When set, rollouts are generated from this endpoint/model instead of the student inference server."
),
),
] = None
# The sampling configuration
sampling: SamplingConfig = SamplingConfig()
@@ -702,11 +737,14 @@ class OrchestratorConfig(BaseSettings):
# Data buffer configuration
buffer: BufferConfig = BufferConfig()
# Rollout verification configuration
verification: VerificationConfig = VerificationConfig()
# The advantage configuration
advantage: AdvantageConfigType | None = AdvantageConfig()
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
# Rollout filters (monitor by default, enforce optionally)
filters: list[FilterConfigType] = [GibberishFilterConfig(), RepetitionFilterConfig()]
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig()]
# The logging configuration
log: LogConfig = LogConfig()
@@ -723,11 +761,9 @@ class OrchestratorConfig(BaseSettings):
# The validation configuration
val: ValConfig | None = None
weight_broadcast: Annotated[WeightBroadcastConfigType, Field(discriminator="type")] = (
FileSystemWeightBroadcastConfig()
)
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
rollout_transport: Annotated[TransportConfigType, Field(discriminator="type")] = FileSystemTransportConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
output_dir: Annotated[
Path,
@@ -751,15 +787,44 @@ class OrchestratorConfig(BaseSettings):
),
] = None
batch_size: Annotated[int, Field(ge=1, description="Number of samples to train on per step.")] = 128
oversampling_factor: Annotated[
float,
batch_size: Annotated[
int | None,
Field(
ge=1,
description="Factor by which to oversample the batch. Will lead to more in-flight group rollout requests at the same time.",
description="Number of samples to train on per step (rollout-based batching). Set this OR token_batch_size.",
),
] = 1.0
] = None
token_batch_size: Annotated[
int | None,
Field(
ge=1,
description="Number of tokens to train on per step (token-based batching). Set this OR batch_size.",
),
] = None
oversampling_factor: Annotated[
float | None,
Field(
ge=1,
description=(
"Rollout-mode batching only. Multiplier used to derive max_inflight_rollouts from batch_size "
"when max_inflight_rollouts is unset."
),
),
] = None
max_inflight_rollouts: Annotated[
int | None,
Field(
ge=1,
description=(
"Maximum number of rollouts to keep in-flight. Required for token-based batching. "
"If batch_size is set and this is unset, defaults to batch_size * oversampling_factor "
"(or batch_size when oversampling_factor is unset)."
),
),
] = None
rollouts_per_example: Annotated[
int,
@@ -825,6 +890,13 @@ class OrchestratorConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
use_token_client: Annotated[
bool,
Field(
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
),
] = True
@model_validator(mode="after")
def validate_unique_filter_types(self):
types = [f.type for f in self.filters]
@@ -846,9 +918,43 @@ class OrchestratorConfig(BaseSettings):
return self
@model_validator(mode="after")
def validate_batch_size(self):
if self.batch_size % self.rollouts_per_example != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
def resolve_batching(self):
has_rollout_batch = self.batch_size is not None
has_token_batch = self.token_batch_size is not None
if has_rollout_batch and has_token_batch:
raise ValueError("Set exactly one of batch_size or token_batch_size")
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_rollouts is None:
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.rollouts_per_example != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
expected_max_inflight_rollouts = int(self.batch_size * self.oversampling_factor)
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
if self.max_inflight_rollouts is None:
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
self.max_inflight_rollouts = int(self.batch_size * oversampling_factor)
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(f"Duplicate environment names: {set(duplicates)}. Each env must have a unique name.")
return self
@model_validator(mode="after")
@@ -857,6 +963,35 @@ class OrchestratorConfig(BaseSettings):
assert len(self.buffer.env_ratios) == len(self.env), "env_ratios length must match number of environments"
return self
@model_validator(mode="after")
def validate_verification_config(self):
if self.verification.enabled:
return self
if self.buffer.online_difficulty_filtering:
raise ValueError(
"verification.enabled cannot be False when buffer.online_difficulty_filtering is True. "
"These features depend on rewards which are disabled when verification.enabled=False."
)
if self.buffer.easy_threshold is not None:
raise ValueError(
"verification.enabled cannot be False when buffer.easy_threshold is set. "
"Easy threshold depends on rewards which are disabled when verification.enabled=False."
)
if self.buffer.hard_threshold is not None:
raise ValueError(
"verification.enabled cannot be False when buffer.hard_threshold is set. "
"Hard threshold depends on rewards which are disabled when verification.enabled=False."
)
return self
@model_validator(mode="after")
def validate_length_shaping_requires_online_difficulty_filtering(self):
if isinstance(self.advantage, DefaultAdvantageConfig) and self.advantage.length_shaping_alpha is not None:
if not self.buffer.online_difficulty_filtering:
raise ValueError("Group Relative Reward (GR³) scaling requires online difficulty filtering")
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
@@ -875,8 +1010,8 @@ class OrchestratorConfig(BaseSettings):
@model_validator(mode="after")
def resolve_extra_env_kwargs(self):
train_extra_env_kwargs = dict(
seq_len=self.seq_len,
score_rollouts=not self.buffer.skip_verification,
max_seq_len=self.seq_len,
score_rollouts=self.verification.enabled,
)
for env in self.env:
# extra_env_kwargs is not meant to be used by the user, we shamelessly override here
+882
View File
@@ -0,0 +1,882 @@
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.orchestrator import (
CheckpointConfig as OrchestratorCheckpointConfig,
)
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.shared import (
SlurmConfig,
VLMConfig,
WandbConfig,
WandbWithExtrasConfig,
)
from prime_rl.configs.trainer import (
BenchConfig,
FakeDataLoaderConfig,
TrainerConfig,
)
from prime_rl.configs.trainer import (
CheckpointConfig as TrainerCheckpointConfig,
)
from prime_rl.configs.trainer import (
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_async_level,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_output_dir,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
class SharedLogConfig(BaseConfig):
"""Configures shared logging."""
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
file: Annotated[bool | None, Field(description="Whether to log to a file.")] = True
json_logging: Annotated[
bool,
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
] = False
class SharedWandbConfig(BaseConfig):
"""Configures shared W&B configs."""
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
shared: Annotated[
bool,
Field(
description="Use shared W&B mode to log trainer and orchestrator metrics to a single run. "
"Requires wandb SDK >= 0.19.9. Incompatible with offline mode.",
),
] = True
@model_validator(mode="after")
def validate_shared_not_offline(self):
if self.shared and self.offline:
raise ValueError("W&B shared mode requires server connectivity and is incompatible with offline mode")
return self
class SharedCheckpointConfig(BaseConfig):
"""Configures shared checkpoint configs."""
output_dir: Annotated[
Path | None,
Field(
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir.",
),
] = None
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
resume_step: Annotated[
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
] = None
keep_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
class SharedModelConfig(BaseConfig):
"""Configures shared model settings."""
name: Annotated[
str,
Field(description="The name of the model to use."),
] = "Qwen/Qwen3-0.6B"
vlm: Annotated[
"VLMConfig | None",
Field(description="VLM configuration. Set to enable vision-language model support."),
] = None
class SharedWeightBroadcastConfig(BaseConfig):
"""Configures shared weight broadcast settings."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
"filesystem"
)
port: Annotated[int, Field(description="The port to use for NCCL weight broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
quantize_in_weight_transfer: Annotated[
bool,
Field(
description=(
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
"When disabled, uses default HF checkpoint-format transfer."
),
),
] = False
class BaseDeploymentConfig(BaseModel):
"""Configures a base deployment."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a single node deployment."""
type: Literal["single_node"] = "single_node"
num_train_gpus: Annotated[int, Field(description="Number of training GPUs")] = 1
num_infer_gpus: Annotated[int, Field(description="Number of inference GPUs")] = 1
num_teacher_gpus: Annotated[int | None, Field(description="Number of teacher inference GPUs")] = None
@model_validator(mode="after")
def validate_gpu_count(self):
total = self.num_train_gpus + self.num_infer_gpus + (self.num_teacher_gpus or 0)
if total > self.gpus_per_node:
raise ValueError(
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer"
f" + {self.num_teacher_gpus or 0} teacher) exceeds gpus_per_node ({self.gpus_per_node})."
)
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi node deployment."""
type: Literal["multi_node"] = "multi_node"
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
num_infer_nodes: Annotated[
int,
Field(
ge=0,
description="Number of inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data).",
),
]
num_infer_replicas: Annotated[
int,
Field(
ge=1,
description="Number of independent inference replicas. Total inference nodes = num_infer_nodes * num_infer_replicas.",
),
] = 1
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="Number of training nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group."
),
] = None
@property
def total_infer_nodes(self) -> int:
return self.num_infer_nodes * self.num_infer_replicas
@model_validator(mode="after")
def teacher_inference_not_supported(self):
if self.num_teacher_nodes is not None:
raise ValueError("Teacher inference is not yet supported in multi node deployment.")
return self
DeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
]
class RLConfig(BaseConfig):
"""Configures an RL training run."""
trainer: TrainerConfig
orchestrator: OrchestratorConfig
inference: Annotated[
InferenceConfig | None,
Field(
description="The inference config. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."
),
] = None
teacher_inference: Annotated[
InferenceConfig | None,
Field(
description="Teacher inference config. If None, will use the same config as inference or a default config. Only used when teacher GPUs or nodes are set."
),
] = None
output_dir: Annotated[
Path,
Field(
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
),
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
### Shared configurations
log: Annotated[
SharedLogConfig,
Field(
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
),
] = SharedLogConfig()
ckpt: Annotated[
SharedCheckpointConfig | None,
Field(
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
),
] = None
wandb: Annotated[
SharedWandbConfig | None,
Field(
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
),
] = None
model: Annotated[
SharedModelConfig | None,
Field(
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
),
] = None
max_steps: Annotated[
int | None,
Field(
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
),
] = None
max_model_len: Annotated[
int | None,
Field(
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
),
] = None
seq_len: Annotated[
int | None,
Field(
description="Shared sequence length. Propagates to trainer.model.seq_len and orchestrator.seq_len, "
"but only for those not explicitly set in the config. "
"Explicitly set per-component values always take precedence."
),
] = None
max_async_level: Annotated[
int | None,
Field(
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
),
] = None
weight_broadcast: Annotated[
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
] = None
bench: Annotated[
bool,
Field(
description="Whether to run in benchmark mode. Automatically sets the trainer and orchestrator to benchmark mode and, if present, suffixes the W&B project with `-bench`.",
),
] = False
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
slurm: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
if self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if self.deployment.num_infer_nodes > 0 and not self.inference:
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
if self.deployment.num_infer_nodes == 0 and self.inference:
raise ValueError(
"Cannot configure inference with num_infer_nodes = 0. "
"Either set num_infer_nodes > 0 or remove the inference config."
)
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
raise ValueError(
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
"since no orchestrator or inference server will be running."
)
return self
# TODO: fix this
@model_validator(mode="after")
def validate_no_teacher_in_multinode(self):
if self.deployment.type == "multi_node" and self.teacher_inference is not None:
raise ValueError(
"Teacher inference is not supported in multi-node deployment. "
"The SLURM template only handles inference and training nodes."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.deployment.type == "single_node":
if self.trainer.weight_broadcast.type == "nccl":
if self.deployment.num_train_gpus + self.deployment.num_infer_gpus < 2:
raise ValueError(
"NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group."
)
return self
@model_validator(mode="after")
def validate_quantize_in_weight_transfer(self):
if self.weight_broadcast is None or not self.weight_broadcast.quantize_in_weight_transfer:
return self
if self.weight_broadcast.type != "nccl":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires weight_broadcast.type = 'nccl'.")
if self.inference is None:
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
if self.trainer.model.impl != "custom":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
return self
@model_validator(mode="after")
def validate_teacher_model(self):
if (
self.trainer.loss.type == "default" and self.trainer.loss.teacher_tau > 0
) and not self.orchestrator.teacher_model:
raise ValueError(
"teacher_model must be configured when teacher_tau > 0. "
"Either set teacher_tau = 0, set deployment.num_teacher_gpus, or configure teacher_model manually."
)
return self
@model_validator(mode="after")
def validate_external_rollout_mode(self):
if self.orchestrator.teacher_rollout_model is None:
return self
if self.trainer.loss.type != "sft":
raise ValueError('orchestrator.teacher_rollout_model is only supported when trainer.loss.type = "sft".')
if self.inference is not None:
raise ValueError(
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
"External rollout mode does not use the local inference server."
)
if self.orchestrator.use_token_client:
raise ValueError(
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
)
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
def auto_setup_output_dir(self):
"""Auto-setup shared output directory for trainer and orchestrator."""
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_logs(self):
"""Auto-setup shared log config for trainer and orchestrator."""
if self.log is not None:
if self.log.level is not None:
self.trainer.log.level = self.log.level
self.orchestrator.log.level = self.log.level
if self.log.file is not None:
self.trainer.log.file = self.log.file
self.orchestrator.log.file = self.log.file
self.trainer.log.json_logging = self.log.json_logging
self.orchestrator.log.json_logging = self.log.json_logging
return self
@model_validator(mode="after")
def auto_setup_ckpt(self):
"""Auto-setup shared checkpoint config for trainer and orchestrator."""
if self.ckpt is not None:
# Create checkpoint configs if not specified
if self.trainer.ckpt is None:
self.trainer.ckpt = TrainerCheckpointConfig()
if self.orchestrator.ckpt is None:
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
# If specified, override checkpoint output directory
if self.ckpt.output_dir is not None:
self.trainer.ckpt.output_dir = self.ckpt.output_dir
# If specified, use the same ckpt interval
if self.ckpt.interval is not None:
self.trainer.ckpt.interval = self.ckpt.interval
self.orchestrator.ckpt.interval = self.ckpt.interval
# If resuming training, ensure orchestrator resume from the same step
if self.ckpt.resume_step is not None:
self.trainer.ckpt.resume_step = self.ckpt.resume_step
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
# If specified, propagate keep policy
if self.ckpt.keep_last is not None:
self.trainer.ckpt.keep_last = self.ckpt.keep_last
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
if self.ckpt.keep_interval is not None:
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
validate_shared_ckpt_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_wandb(self):
"""Auto-setup shared W&B config for trainer and orchestrator."""
if self.wandb is not None:
if not self.trainer.wandb:
self.trainer.wandb = WandbConfig()
if not self.orchestrator.wandb:
self.orchestrator.wandb = WandbWithExtrasConfig()
if self.wandb.project:
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
if self.wandb.shared:
if self.wandb.name:
self.trainer.wandb.name = self.wandb.name
self.orchestrator.wandb.name = self.wandb.name
else:
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
validate_shared_wandb_config(self.trainer, self.orchestrator)
if self.orchestrator.prime_monitor is not None and self.orchestrator.prime_monitor.run_name is None:
if self.wandb and self.wandb.name:
self.orchestrator.prime_monitor.run_name = self.wandb.name
return self
@model_validator(mode="after")
def auto_setup_model(self):
"""Auto-setup shared model config for trainer, orchestrator, and inference."""
if self.model is not None:
self.trainer.model.name = self.model.name
if self.inference is not None:
inference_model_explicitly_set = "name" in self.inference.model.model_fields_set
if not inference_model_explicitly_set:
self.inference.model.name = self.model.name
self.orchestrator.model.name = self.inference.model.name
else:
self.orchestrator.model.name = self.model.name
if self.model.vlm is not None:
self.trainer.model.vlm = self.model.vlm
self.orchestrator.model.vlm = self.model.vlm
if self.inference is not None:
self.inference.model.vlm = self.model.vlm
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_max_steps(self):
"""Auto-setup shared max steps for trainer and orchestrator."""
if self.max_steps is not None:
self.trainer.max_steps = self.max_steps
self.orchestrator.max_steps = self.max_steps
validate_shared_max_steps(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_async_level(self):
"""Auto-setup shared async level for trainer and orchestrator."""
if self.max_async_level is not None:
self.trainer.max_async_level = self.max_async_level
self.orchestrator.max_async_level = self.max_async_level
validate_shared_max_async_level(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_seq_len(self):
"""Auto-setup shared seq_len for trainer and orchestrator.
Only propagates to components that weren't explicitly set in the config.
Uses model_fields_set to detect explicit assignment.
"""
if self.seq_len is not None:
if "seq_len" not in self.trainer.model.model_fields_set:
self.trainer.model.seq_len = self.seq_len
if "seq_len" not in self.orchestrator.model_fields_set:
self.orchestrator.seq_len = self.seq_len
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
return self
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
self.trainer.bench = BenchConfig()
self.orchestrator.bench = True
self.trainer.data.fake = FakeDataLoaderConfig(
batch_size=self.orchestrator.batch_size or 32,
)
trainer_bench_enabled = self.trainer.bench is not None
if trainer_bench_enabled != self.orchestrator.bench:
raise ValueError(
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode "
f"({self.orchestrator.bench}) must match. Use the top-level bench = true to set both."
)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
get_logger().warning(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank."
)
return self
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
return self
@model_validator(mode="after")
def auto_setup_router_replay(self):
if self.trainer.enable_router_replay:
if self.inference is not None:
if self.inference.enable_return_routed_experts is False:
get_logger().warning(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True."
)
self.inference.enable_return_routed_experts = True
else:
get_logger().warning(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server."
)
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "single_node": # single-node
# set num_train_workers to the number of data replicas
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
if self.deployment.num_train_gpus > 1:
self.orchestrator.num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
# fill up inference capacity with dp ranks
if self.inference is not None:
num_infer_gpus = self.deployment.num_infer_gpus
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
assert num_infer_gpus % self.inference.parallel.tp == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.trainer.model.dp_replicate = (
self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
)
if (
self.inference is not None
and self.inference.enable_expert_parallel
and self.inference.deployment.type != "disaggregated"
):
inference_tp = self.inference.parallel.tp
if self.deployment.gpus_per_node % inference_tp != 0:
raise ValueError(
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
"when inference.enable_expert_parallel is enabled in multi-node deployment."
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
)
if self.inference.data_parallel_size_local is None:
self.inference.data_parallel_size_local = inferred_dp_local
elif self.inference.data_parallel_size_local != inferred_dp_local:
raise ValueError(
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
)
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
self.inference.api_server_count = inferred_dp_local
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
total_infer_gpus = self.deployment.gpus_per_node * self.deployment.total_infer_nodes
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
assert self.orchestrator.weight_broadcast.type == "nccl"
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
return self
@model_validator(mode="after")
def auto_setup_disaggregated_inference(self):
"""Auto-setup for disaggregated P/D inference within a multi-node deployment."""
if self.inference is None or self.inference.deployment.type != "disaggregated":
return self
if self.deployment.type != "multi_node":
return self
infer_deploy = self.inference.deployment
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
if self.deployment.num_infer_nodes != expected_infer_nodes:
raise ValueError(
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
)
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
assert self.orchestrator.weight_broadcast.type == "nccl"
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
return self
@model_validator(mode="after")
def auto_setup_dp_rank_count(self):
"""Auto-set orchestrator client dp_rank_count from inference DP size.
Uses data_parallel_size_local (per-node DP) when set, since each base URL
points to a single node whose API server only knows about its local ranks.
Falls back to the global parallel.dp for single-node setups.
"""
if self.inference is not None and "dp_rank_count" not in self.orchestrator.client.model_fields_set:
self.orchestrator.client.dp_rank_count = (
self.inference.data_parallel_size_local or self.inference.parallel.dp
)
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
if self.deployment.type != "single_node":
return self
if self.deployment.num_teacher_gpus is None or self.deployment.num_teacher_gpus == 0:
return self
import copy
from prime_rl.configs.orchestrator import TeacherModelConfig
if self.teacher_inference is None:
if self.inference is None:
self.teacher_inference = InferenceConfig()
else:
self.teacher_inference = copy.deepcopy(self.inference)
self.teacher_inference.server.port = (self.inference.server.port if self.inference else 8000) + 1
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
raise ValueError(
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
f"inference.server.port ({self.inference.server.port}). "
"Either use different ports or let teacher_inference be auto-configured."
)
tp = self.teacher_inference.parallel.tp
num_teacher_gpus = self.deployment.num_teacher_gpus
if num_teacher_gpus != self.teacher_inference.parallel.dp * tp:
assert num_teacher_gpus % tp == 0, "Number of teacher GPUs must be divisible by tensor parallel size"
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
if self.orchestrator.teacher_model is None:
self.orchestrator.teacher_model = TeacherModelConfig()
host = self.teacher_inference.server.host or "localhost"
port = self.teacher_inference.server.port
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
return self
### Warnings
@@ -1,20 +1,25 @@
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, Field, model_validator
from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.trainer.config import (
from prime_rl.configs.shared import (
HeartbeatConfig,
LogConfig,
SlurmConfig,
WandbConfig,
)
from prime_rl.configs.trainer import (
AdamWConfig,
BenchConfig,
CheckpointConfig,
ConstantSchedulerConfig,
ModelConfig,
OptimizerConfigType,
SchedulerConfigType,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
)
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
from prime_rl.utils.config import BaseConfig
class BaseDataConfig(BaseModel):
@@ -101,10 +106,58 @@ class SFTDataConfig(BaseDataConfig):
return self
DataConfigType: TypeAlias = FakeDataConfig | SFTDataConfig
class SFTValConfig(BaseConfig):
interval: Annotated[int, Field(ge=1, description="Run validation every N training steps.")] = 50
eval_on_start: Annotated[bool, Field(description="Run validation before the first training step.")] = False
data: SFTDataConfig
class SFTTrainerConfig(BaseSettings):
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
class BaseDeploymentConfig(BaseModel):
"""Base deployment config for SFT."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a single-node SFT deployment."""
type: Literal["single_node"] = "single_node"
num_gpus: Annotated[int, Field(description="Number of GPUs.")] = 1
@model_validator(mode="after")
def validate_gpu_count(self):
if self.num_gpus > self.gpus_per_node:
raise ValueError(f"num_gpus ({self.num_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi-node SFT deployment."""
type: Literal["multi_node"] = "multi_node"
num_nodes: Annotated[int, Field(description="Number of training nodes.")] = 2
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group."
),
] = None
SFTDeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
]
class SFTConfig(BaseConfig):
"""Configures the SFT trainer"""
# The model configuration
@@ -114,13 +167,16 @@ class SFTTrainerConfig(BaseSettings):
tokenizer: TokenizerConfig = TokenizerConfig()
# The data configuration
data: Annotated[DataConfigType, Field(discriminator="type")] = SFTDataConfig()
data: DataConfig = SFTDataConfig()
# Optional validation configuration
val: SFTValConfig | None = None
# The optimizer configuration
optim: Annotated[OptimizerConfigType, Field(discriminator="type")] = AdamWConfig()
optim: OptimizerConfig = AdamWConfig()
# The learning rate scheduler configuration
scheduler: Annotated[SchedulerConfigType, Field(discriminator="type")] = ConstantSchedulerConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
@@ -138,6 +194,13 @@ class SFTTrainerConfig(BaseSettings):
),
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
max_steps: Annotated[
int | None,
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
@@ -162,44 +225,82 @@ class SFTTrainerConfig(BaseSettings):
] = 600
loss_impl: Annotated[
Literal["liger", "torch"], Field(description="Implementation of the cross entropy loss function to use.")
Literal["liger", "torch", "liger_fused"],
Field(
description="Implementation of the cross entropy loss function to use. "
"'liger_fused' fuses the lm_head projection with the CE loss to avoid materializing full logits."
),
] = "torch"
heartbeat: Annotated[
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
slurm: Annotated[
SlurmConfig | None,
Field(
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
),
] = None
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
### Pre-validation normalization
@model_validator(mode="before")
@classmethod
def normalize_deployment(cls, data):
if not isinstance(data, dict):
return data
deployment = data.get("deployment")
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
for key in ("num_gpus",):
deployment.pop(key, None)
return data
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if self.ckpt: # Do not checkpoint
self.ckpt = None
def validate_deployment(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
def validate_pack_function(self):
if self.model.cp > 1 and self.data.pack_function != "cat":
raise ValueError("Packing function must be 'cat' when CP is enabled")
if self.model.cp > 1:
if self.data.pack_function != "cat":
raise ValueError("Packing function must be 'cat' when CP is enabled")
if self.val is not None and self.val.data.pack_function != "cat":
raise ValueError("Validation packing function must be 'cat' when CP is enabled")
return self
@model_validator(mode="after")
def validate_cp_seq_len(self):
if self.model.cp > 1 and self.data.seq_len % self.model.cp != 0:
raise ValueError("Sequence length must be divisible by CP degree")
if self.model.cp > 1:
if self.data.seq_len % self.model.cp != 0:
raise ValueError("Sequence length must be divisible by CP degree")
if self.val is not None and self.val.data.seq_len % self.model.cp != 0:
raise ValueError("Validation sequence length must be divisible by CP degree")
return self
@model_validator(mode="after")
def validate_cp_micro_batch_size(self):
if self.model.cp > 1 and self.data.micro_batch_size != 1:
raise ValueError("Micro batch size must be 1 when CP is enabled")
if self.model.cp > 1:
if self.data.micro_batch_size != 1:
raise ValueError("Micro batch size must be 1 when CP is enabled")
if self.val is not None and self.val.data.micro_batch_size != 1:
raise ValueError("Validation micro batch size must be 1 when CP is enabled")
return self
@model_validator(mode="after")
def validate_seq_len(self):
if self.data.pack_function == "stack":
if self.data.seq_len % 256 != 0:
raise ValueError("The sequence length must be divisible by 256 when using pack function stack")
if self.data.pack_function == "stack" and self.data.seq_len % 256 != 0:
raise ValueError("The sequence length must be divisible by 256 when using pack function stack")
if self.val is not None and self.val.data.pack_function == "stack" and self.val.data.seq_len % 256 != 0:
raise ValueError("The validation sequence length must be divisible by 256 when using pack function stack")
return self
@model_validator(mode="after")
@@ -230,22 +331,15 @@ class SFTTrainerConfig(BaseSettings):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def validate_and_disable_chunked_loss(self):
if isinstance(self.model.fused_lm_head_chunk_size, int):
if isinstance(self.model.fused_lm_head_token_chunk_size, int):
raise ValueError(
"Chunked loss is not supported for SFT training yet, please set `model.fused_lm_head_chunk_size` to 'disabled'"
"Chunked loss is not supported for SFT training yet, please set "
"`model.fused_lm_head_token_chunk_size` to 'disabled'"
)
self.model.fused_lm_head_chunk_size = "disabled"
self.model.fused_lm_head_token_chunk_size = "disabled"
return self
@model_validator(mode="after")
@@ -254,3 +348,45 @@ class SFTTrainerConfig(BaseSettings):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "multi_node":
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_nodes ({self.deployment.num_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.model.dp_replicate = self.deployment.num_nodes // self.deployment.nodes_per_fsdp_group
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
return self
+461
View File
@@ -0,0 +1,461 @@
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, Field, model_validator
from prime_rl.utils.config import BaseConfig
class SlurmConfig(BaseConfig):
"""Configures SLURM scheduling."""
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
project_dir: Annotated[
Path,
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
] = Path(".")
template_path: Annotated[
Path | None,
Field(
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
),
] = None
partition: Annotated[
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
] = "cluster"
nodelist: Annotated[
str | None,
Field(description="Comma-separated list of specific nodes to run on. Passed as #SBATCH --nodelist."),
] = None
exclude: Annotated[
str | None,
Field(description="Comma-separated list of nodes to exclude. Passed as #SBATCH --exclude."),
] = None
account: Annotated[
str | None,
Field(description="SLURM account to charge. Passed as #SBATCH --account."),
] = None
time: Annotated[
str | None,
Field(description="Maximum wall time (e.g. '24:00:00', '7-00:00:00'). Passed as #SBATCH --time."),
] = None
pre_run_command: Annotated[
str | None,
Field(
description="Shell command to run on the head node before starting the job. "
"Runs after cd into project dir, .env sourcing, and venv activation. "
"Useful for cleanup routines like 'sudo pkill -f vllm'. "
"To run on all nodes, wrap with srun: 'srun bash -c \"pkill -f vllm || true\"'.",
),
] = None
@property
def template_vars(self) -> dict:
"""Common template variables for all SLURM templates."""
return {
"job_name": self.job_name,
"project_dir": self.project_dir,
"partition": self.partition,
"nodelist": self.nodelist,
"exclude": self.exclude,
"account": self.account,
"time": self.time,
"pre_run_command": self.pre_run_command,
}
@model_validator(mode="after")
def resolve_project_dir(self):
self.project_dir = self.project_dir.resolve()
return self
ServerType = Literal["vllm", "openai"]
class VLMConfig(BaseConfig):
"""Configures vision-language model support.
Presence of this config enables VLM mode. You must specify where the
vision encoder and language model live on the model object.
Usage:
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
"""
vision_encoder_attr: Annotated[
str,
Field(description="Dotted attribute path to the vision encoder module (e.g. 'model.visual')."),
]
language_model_attr: Annotated[
str,
Field(description="Dotted attribute path to the language model module (e.g. 'model.language_model')."),
]
class BaseModelConfig(BaseConfig):
"""Configures the model."""
name: Annotated[str, Field(description="Name or path of the HF model to use.")] = "Qwen/Qwen3-0.6B"
trust_remote_code: Annotated[
bool,
Field(
description="Whether to trust remote code for tokenizer initialization.",
),
] = False
vlm: Annotated[
"VLMConfig | None",
Field(
description="VLM configuration. Set this to enable vision-language model support.",
),
] = None
class ElasticConfig(BaseConfig):
"""Configures elastic inference pool with DNS-based service discovery.
Works with any DNS hostname that resolves to multiple IP addresses.
"""
hostname: Annotated[
str,
Field(
description="DNS hostname that resolves to inference server IPs.",
),
]
port: Annotated[
int,
Field(
description="Port that inference servers listen on.",
),
] = 8000
sync_interval: Annotated[
float,
Field(
description="Interval in seconds between server discovery checks.",
),
] = 5.0
class ClientConfig(BaseConfig):
"""Configures the OAI client.
Supports two modes:
- Static mode (default): Uses fixed base_url list
- Elastic mode: Uses DNS-based service discovery via hostname
If elastic config is provided, base_url is ignored and servers are discovered dynamically.
"""
timeout: Annotated[
int,
Field(
description="Timeout in seconds. By default, it is set to 1200 seconds.",
),
] = 1200
connect_timeout: Annotated[
float,
Field(
description="TCP connect timeout in seconds for inference API requests.",
),
] = 30.0
base_url: Annotated[
list[str],
Field(
description="Base URLs to use for the OpenAI API. By default, it is set to a single server on localhost at port 8000 which matches the default local vLLM server configuration. If you specify more than one URL, the client will round-robin (chat) completion requests across all servers. Ignored if elastic config is provided.",
),
] = ["http://localhost:8000/v1"]
api_key_var: Annotated[
str,
Field(
description="Name of environment variable containing the API key to use for the inference API. Will parse using `os.getenv(client_config.api_key_var)`. Can be set to an arbitrary string if the inference server is not protected by an API key. If multiple URLs are specified, the same API key will be used for all servers.",
),
] = "VLLM_API_KEY"
headers: Annotated[
dict[str, str],
Field(
description="Headers to use for the OpenAI API. By default, it is set to an empty dictionary.",
),
] = {}
extra_headers_from_state: Annotated[
dict[str, str],
Field(
description="Maps HTTP header names to state field names. For each inference request, "
"the header value is dynamically read from the rollout state dict. "
'e.g. {"X-Session-ID": "example_id"} enables sticky routing at the inference router.',
),
] = {}
skip_model_check: Annotated[
bool,
Field(
description="Whether 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.",
),
] = False
dp_rank_count: Annotated[
int,
Field(
ge=1,
description=(
"Number of data-parallel ranks behind each base URL. When > 1, "
"each URL is expanded into dp_rank_count logical clients, each "
"pinned to a specific DP rank via the X-data-parallel-rank header. "
"This ensures all requests within a multi-turn rollout hit the same "
"DP engine, maximizing KV cache reuse. Auto-set from "
"inference.data_parallel_size_local (or inference.parallel.dp) "
"when using the RL entrypoint."
),
),
] = 1
admin_base_url: Annotated[
list[str] | None,
Field(
description="Separate base URLs for admin operations (weight updates, health checks). "
"When set, admin clients use these URLs instead of base_url, allowing weight "
"updates to bypass routers and hit each server directly. Used in disaggregated "
"P/D deployments where the inference router should not handle admin traffic.",
),
] = None
elastic: Annotated[
ElasticConfig | None,
Field(
description="Elastic inference pool configuration for DNS-based service discovery. If provided, base_url is ignored and inference servers are discovered dynamically via DNS.",
),
] = None
router_url: Annotated[
str | None,
Field(
description="URL of a vllm-router for load-aware inference routing. When set with elastic mode, inference requests go through the router while admin operations (weight updates, LoRA loading) still go directly to discovered pods.",
),
] = None
@property
def is_elastic(self) -> bool:
"""Check if elastic mode is enabled."""
return self.elastic is not None
class LogConfig(BaseConfig):
"""Configures the logger."""
level: Annotated[
str,
Field(description="Logging level for the process. Will determine the logging verbosity and format."),
] = "info"
vf_level: Annotated[
str,
Field(description="Logging level for the verifiers package. Will determine the logging verbosity and format."),
] = "info"
file: Annotated[
bool,
Field(
description="Whether to log to a file. If True, will log to a file in the output directory.",
),
] = True
env_worker_logs: Annotated[
bool,
Field(
description="Whether env workers log to files. If True, workers write to logs/env_workers/{env_name}.log.",
),
] = False
log_data: Annotated[
bool,
Field(
description="Whether to log the first data sample to the logger.",
),
] = False
json_logging: Annotated[
bool,
Field(
description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.).",
),
] = False
class LogExtrasConfig(BaseConfig):
"""Configures extra logging for monitoring platforms."""
samples: Annotated[
bool,
Field(
description="Whether to log prompt/response samples.",
),
] = True
distributions: Annotated[
bool,
Field(
description="Whether to log distributions (like rewards, advantages, etc.).",
),
] = True
interval: Annotated[
int,
Field(
ge=1,
description="Step interval at which to log extras.",
),
] = 10
sample_ratio: Annotated[
float | None,
Field(
ge=0.0,
le=1.0,
description="Fraction of rollouts to log per step (0.0–1.0). "
"When set, the effective sample cap is len(rollouts) * sample_ratio. "
"1.0 = all rollouts, 0.5 = half, 0.0 = none. "
"None (default)",
),
] = None
class WandbConfig(BaseConfig):
"""Configures logging to Weights and Biases."""
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
name: Annotated[
str | None,
Field(
description="The W&B name to to use for logging.",
),
] = None
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
class WandbWithExtrasConfig(WandbConfig):
"""Configures logging to Weights and Biases with extras."""
log_extras: Annotated[
LogExtrasConfig | None,
Field(
description="Configuration for logging extras. If None, no extras are logged.",
),
] = LogExtrasConfig()
class PrimeMonitorConfig(BaseConfig):
"""Configures logging to Prime Intellect API."""
base_url: Annotated[
str,
Field(
description="The base URL for Prime Intellect monitoring API.",
),
] = "https://api.primeintellect.ai/api/v1/rft"
api_key_var: Annotated[
str,
Field(
description="Name of environment variable containing the API key for Prime Intellect API. Will parse using `os.getenv(config.api_key_var)`.",
),
] = "PRIME_API_KEY"
log_extras: Annotated[
LogExtrasConfig | None,
Field(
description="Configuration for logging extras. If None, no extras are logged.",
),
] = LogExtrasConfig()
run_name: Annotated[
str | None,
Field(
description="Name for the run shown on the platform. Defaults to the W&B run name if set, otherwise auto-generated by the platform.",
),
] = None
team_id: Annotated[
str | None,
Field(
description="Team ID to associate the run with.",
),
] = None
frontend_url: Annotated[
str | None,
Field(
description="Frontend base URL used for the dashboard link shown after registration. Defaults to the Prime CLI frontend URL when unset.",
),
] = None
class HeartbeatConfig(BaseConfig):
"""Configures the heartbeat for BetterStack."""
url: Annotated[str, Field(description="The URL to send the heartbeat to.")]
class MetricsServerConfig(BaseConfig):
"""Configures the Prometheus metrics server for trainer observability."""
port: Annotated[
int,
Field(
ge=1,
le=65535,
description="Port to expose metrics and health endpoints. Defaults to 8000.",
),
] = 8000
host: Annotated[
str,
Field(
description="Host to bind the server to. Defaults to 0.0.0.0.",
),
] = "0.0.0.0"
class BaseTransportConfig(BaseModel):
"""Base configuration for transport."""
pass
class FileSystemTransportConfig(BaseTransportConfig):
"""Configures filesystem-based transport for training examples."""
type: Literal["filesystem"] = "filesystem"
class ZMQTransportConfig(BaseTransportConfig):
"""Configures ZMQ-based transport for training examples."""
type: Literal["zmq"] = "zmq"
host: Annotated[str, Field(description="The host address for ZMQ transport.")] = "localhost"
port: Annotated[int, Field(description="The base port for ZMQ transport.")] = 5555
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
@@ -1,9 +1,20 @@
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BaseModel, Field, model_validator
from prime_rl.utils.pydantic_config import BaseConfig
from prime_rl.configs.shared import (
BaseModelConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
MetricsServerConfig,
TransportConfig,
WandbConfig,
)
from prime_rl.utils.config import BaseConfig
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
@@ -13,11 +24,6 @@ AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_atte
# to attempt installing a kernel from hub.
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
MOE_MODEL_MAPS = {
"Qwen/Qwen3-30B-A3B": "Jackmin108/Qwen3-30B-A3B-Fast",
"moonshotai/Moonlight-16B-A3B-Instruct": "Jackmin108/Moonlight-16B-A3B-Instruct-Fast",
}
class ActivationCheckpointConfig(BaseConfig):
"""Configures activation checkpointing."""
@@ -63,22 +69,6 @@ class BenchConfig(BaseConfig):
] = None
class DebugModelConfig(BaseConfig):
"""Debugging feature around model and distributed training."""
num_layers: Annotated[
int | None,
Field(description="The number of layers in the model."),
] = None
random_init: Annotated[
bool,
Field(
description="Whether to random initialize the model.",
),
] = False
class LoRAConfig(BaseConfig):
"""Configuration for LoRA (Low-Rank Adaptation)."""
@@ -131,15 +121,24 @@ class LoRAConfig(BaseConfig):
] = []
class ModelConfig(BaseConfig):
"""Configures the model for training."""
class DebugModelConfig(BaseConfig):
"""Debugging feature around model and distributed training."""
name: Annotated[
str,
num_layers: Annotated[
int | None,
Field(description="The number of layers in the model."),
] = None
random_init: Annotated[
bool,
Field(
description="Name or path of the HF model to use.",
description="Whether to random initialize the model.",
),
] = "Qwen/Qwen3-0.6B"
] = False
class ModelConfig(BaseModelConfig):
"""Configures the model for training."""
seq_len: Annotated[int, Field(description="The sequence length to use for the model.")] = 2048
@@ -189,13 +188,6 @@ class ModelConfig(BaseConfig):
bool, Field(description="Whether to reshard the model after each forward pass.")
] = True
trust_remote_code: Annotated[
bool,
Field(
description="Whether to trust remote code for model and tokenizer initialization.",
),
] = False
dp_replicate: Annotated[
int,
Field(
@@ -255,6 +247,13 @@ class ModelConfig(BaseConfig):
),
] = True
freeze_moe_router: Annotated[
bool,
Field(
description="Whether to freeze the MoE router parameters during training.",
),
] = False
lora: Annotated[
LoRAConfig | None,
Field(
@@ -269,19 +268,19 @@ class ModelConfig(BaseConfig):
),
] = DebugModelConfig()
fused_lm_head_chunk_size: Annotated[
fused_lm_head_token_chunk_size: Annotated[
int | Literal["auto", "disabled"],
Field(
description=(
"The chunk size to use for the fused LM head. "
"The flattened token chunk size to use for the fused LM head. "
"Three behaviors: "
"(1) int >= 512: explicitly set chunk size for fused LM head; "
"(2) 'auto': auto-enable (RL training auto-sets to 2048); "
"(1) int >= 1: explicitly set the number of tokens per LM-head chunk; "
"(2) 'auto': auto-enable (RL training auto-sets to 8192); "
"(3) 'disabled': explicitly disable fused LM head (use vanilla). "
"Explicitly setting an integer value for this feature isn't supported for SFT training."
),
),
] = "auto"
] = "disabled"
@model_validator(mode="before")
@classmethod
@@ -291,13 +290,6 @@ class ModelConfig(BaseConfig):
data["attn"] = _ATTN_ALIASES[data["attn"]]
return data
@model_validator(mode="after")
def _map_model_name_for_moe(self):
"""Map model name if it exists in MOE_MODEL_MAPS."""
if self.name in MOE_MODEL_MAPS:
self.name = MOE_MODEL_MAPS[self.name]
return self
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
@@ -330,16 +322,6 @@ class ModelConfig(BaseConfig):
raise ValueError("Cannot enable both fsdp_cpu_offload and optim_cpu_offload. Use one or the other.")
return self
@model_validator(mode="after")
def fused_lm_head_chunk_size_is_valid(self):
if isinstance(self.fused_lm_head_chunk_size, int):
low = 512
if self.fused_lm_head_chunk_size < low:
raise ValueError(
f"Fused LM head chunk size must be at least {low}, got {self.fused_lm_head_chunk_size}"
)
return self
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
if self.attn == "fa4" and self.impl != "custom":
@@ -408,7 +390,9 @@ class CosineSchedulerConfig(BaseModel):
min_lr: Annotated[float, Field(ge=0, description="Minimum learning rate to converge to.")] = 0.0
SchedulerConfigType: TypeAlias = ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig
SchedulerConfig: TypeAlias = Annotated[
ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type")
]
class BaseOptimizerConfig(BaseModel):
@@ -442,7 +426,7 @@ class MuonConfig(BaseOptimizerConfig):
] = 0.95
OptimizerConfigType: TypeAlias = SGDConfig | AdamWConfig | MuonConfig
OptimizerConfig: TypeAlias = Annotated[SGDConfig | AdamWConfig | MuonConfig, Field(discriminator="type")]
class WeightCheckpointConfig(BaseConfig):
@@ -473,6 +457,13 @@ class WeightCheckpointConfig(BaseConfig):
class CheckpointConfig(BaseConfig):
"""Configures checkpointing the full model, optimizer and training state for resuming training."""
output_dir: Annotated[
Path | None,
Field(
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir. Useful for writing large checkpoints to a separate storage volume.",
),
] = None
interval: Annotated[
int | None,
Field(
@@ -483,6 +474,20 @@ class CheckpointConfig(BaseConfig):
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
skip_gather_master_weights: Annotated[
bool,
Field(
description="When true, skip gathering and saving HF-compatible weight checkpoints. Useful for large models where the gather is expensive and only DCP checkpoints are needed.",
),
] = False
weights_only: Annotated[
bool,
Field(
description="When true, only save weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training.",
),
] = False
resume_step: Annotated[
int | None,
Field(
@@ -527,3 +532,291 @@ class CheckpointConfig(BaseConfig):
description="Whether to skip loading the dataloader from checkpoint.",
),
] = False
skip_optimizer: Annotated[
bool,
Field(
description="Whether to skip loading the optimizer state from checkpoint.",
),
] = False
class DefaultLossConfig(BaseModel):
"""Config for the default loss."""
type: Literal["default"] = "default"
ipo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for masking tokens.")] = 0.2
ipo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for masking tokens.")] = 0.2
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 1e-3
class SFTLossConfig(BaseModel):
"""Config for SFT-style masked negative log-likelihood loss."""
type: Literal["sft"] = "sft"
class CustomLossConfig(BaseModel):
"""Config for a custom external loss function."""
type: Literal["custom"] = "custom"
import_path: Annotated[str, Field(description="Import path to the loss function (e.g., 'my_module.my_loss')")]
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | SFTLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
"""Configures a fake data loader sampling random micro batches for debugging."""
batch_size: Annotated[int, Field(ge=1)] = 2
generate_samples: Annotated[
bool, Field(description="Whether to generate separate samples and pack them into a single micro batch.")
] = False
class DataLoaderConfig(BaseConfig):
"""Configures the data loader used for training."""
fake: Annotated[FakeDataLoaderConfig | None, Field(description="Whether to use a fake data loader.")] = None
class BaseWeightBroadcastConfig(BaseModel):
"""Configures the base weight broadcast."""
pass
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
"""Configures the weight broadcast."""
type: Literal["filesystem"] = "filesystem"
save_sharded: Annotated[bool, Field(description="Whether to save the weight checkpoint in sharded format.")] = True
save_format: Annotated[
Literal["safetensors", "torch"], Field(description="The format to save the weight checkpoint in.")
] = "safetensors"
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
"""Configures the NCCL broadcast."""
type: Literal["nccl"] = "nccl"
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
# TODO: Should not be configurable, but auto-inferred
inference_world_size: Annotated[int, Field(description="The number of GPUs used for inference.")] = 1
quantize_in_weight_transfer: Annotated[
bool,
Field(
description=(
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
"When disabled, uses default HF checkpoint-format transfer."
),
),
] = False
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class TrainerConfig(BaseConfig):
"""Configures the RL trainer"""
# The model configuration
model: ModelConfig = ModelConfig()
# The tokenizer configuration
tokenizer: TokenizerConfig = TokenizerConfig()
# The data configuration
data: DataLoaderConfig = DataLoaderConfig()
# The loss configuration
loss: LossConfig = DefaultLossConfig()
# The optimizer configuration
optim: OptimizerConfig = AdamWConfig()
# The learning rate scheduler configuration
scheduler: SchedulerConfig = ConstantSchedulerConfig()
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
# The logging configuration
log: LogConfig = LogConfig()
# The wandb configuration
wandb: WandbConfig | None = None
output_dir: Annotated[
Path,
Field(
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
),
] = Path("outputs")
max_steps: Annotated[
int | None,
Field(
description="Maximum number of steps to run training for. If None, will run indefinitely.",
),
] = None
max_async_level: Annotated[
int,
Field(
ge=0,
description="Maximum number of steps that inference can be ahead of training. Determines how 'off-policy' the inference engines can be. Higher values yield better throughput through async execution, but may yield lower performance. If 0, will be fully synchronous.",
),
] = 1
enable_router_replay: Annotated[
bool,
Field(
description="Whether to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models.",
),
] = False
memory_profiler_path: Annotated[Path | None, Field(description="Path to write memory profile to.")] = None
bench: Annotated[
BenchConfig | None,
Field(
description="Whether to run in benchmark mode. It will automatically set the maximum number of steps to run to 4 and use fake data.",
),
] = None
trace_path: Annotated[Path | None, Field(description="Path to write pytorch profiler trace to.")] = None
dist_timeout_seconds: Annotated[
int,
Field(
description="Timeout in seconds for torch distributed ops. Defaults to 600 seconds.",
),
] = 600
heartbeat: Annotated[
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
metrics_server: Annotated[
MetricsServerConfig | None,
Field(description="Prometheus metrics server config. If set, exposes /metrics endpoint for scraping."),
] = None
max_concurrent_runs: Annotated[
int,
Field(
ge=1,
description="The maximum number of concurrent runs to allow. If 1, then only one run will be allowed at a time.",
),
] = 1
@model_validator(mode="after")
def vlms_require_bfloat16(self):
if self.model.vlm is not None and (
self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16"
):
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if not self.data.fake:
self.data.fake = FakeDataLoaderConfig()
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def dont_do_massive_traces(self):
if self.trace_path:
if self.max_steps is None:
raise ValueError("Must specify max_steps when tracing")
if self.max_steps >= 10:
raise ValueError(
"Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
lora_enabled = self.model and self.model.lora
if not lora_enabled:
raise ValueError(
"save_adapter_separately=True requires LoRA to be enabled. "
"Set model.lora or disable save_adapter_separately."
)
return self
@model_validator(mode="after")
def validate_weight_broadcast_type(self):
if self.weight_broadcast.type == "nccl" and self.max_async_level != 1:
raise ValueError("NCCL weight broadcast only works with async level 1")
return self
@model_validator(mode="after")
def validate_opt_and_fsdp_offload(self):
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_optim_cpu_offload_single_run(self):
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
return self
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
# TODO: Support this
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_fused_lm_head_token_chunk_size(self):
if self.model.fused_lm_head_token_chunk_size == "auto":
self.model.fused_lm_head_token_chunk_size = 8192
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@model_validator(mode="after")
def router_replay_only_with_custom_impl(self):
if self.enable_router_replay and self.model.impl not in ("custom", "auto"):
raise ValueError("Router replay is only supported with the custom implementation or auto mode")
return self
+142
View File
@@ -0,0 +1,142 @@
import subprocess
import sys
from pathlib import Path
import tomli_w
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import get_config_dir
INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
"""Write resolved config to disk."""
output_dir.mkdir(parents=True, exist_ok=True)
config_path = output_dir / INFERENCE_TOML
with open(config_path, "wb") as f:
tomli_w.dump(config.model_dump(exclude=exclude, exclude_none=True, mode="json"), f)
return config_path
def write_slurm_script(config: InferenceConfig, config_path: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
is_disaggregated = config.deployment.type == "disaggregated"
template_vars = dict(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
gpus_per_node=config.deployment.gpus_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
disaggregated=is_disaggregated,
)
is_multi_node = config.deployment.type == "multi_node"
if is_disaggregated:
template_vars.update(
num_prefill_nodes=config.deployment.num_prefill_nodes,
num_decode_nodes=config.deployment.num_decode_nodes,
prefill_port=config.deployment.prefill_port,
decode_port=config.deployment.decode_port,
router_port=config.deployment.router_port,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
)
elif is_multi_node:
template_vars.update(
router_port=config.deployment.router_port,
backend_port=config.deployment.backend_port,
)
script = template.render(**template_vars)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def inference_slurm(config: InferenceConfig):
"""Run inference via SLURM."""
assert config.slurm is not None
logger = setup_logger("info")
config_dir = get_config_dir(config.output_dir)
exclude = (
{"deployment", "slurm", "dry_run"}
if config.deployment.type in ("multi_node", "disaggregated")
else {"slurm", "dry_run"}
)
config_path = write_config(config, config_dir, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / INFERENCE_SBATCH
write_slurm_script(config, config_path, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
log_message = (
f"Logs:\n"
f" Job: tail -F {config.output_dir}/job_*.log\n"
f" Inference: tail -F {config.output_dir}/slurm/latest_infer_node_rank_*.log\n"
)
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def inference_local(config: InferenceConfig):
"""Run inference locally."""
from prime_rl.inference.server import setup_vllm_env
logger = setup_logger("info")
if config.dry_run:
logger.success("Dry run complete. To start inference locally, remove --dry-run from your command.")
return
host = config.server.host or "0.0.0.0"
port = config.server.port
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
setup_vllm_env(config)
from prime_rl.inference.vllm.server import server # pyright: ignore
server(config, vllm_extra=config.vllm_extra)
def inference(config: InferenceConfig):
if config.slurm is not None:
inference_slurm(config)
else:
inference_local(config)
def main():
inference(cli(InferenceConfig))
if __name__ == "__main__":
main()
+523
View File
@@ -0,0 +1,523 @@
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.rl import RLConfig
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.utils import (
get_free_port,
get_log_dir,
)
RL_TOML = "rl.toml"
RL_SBATCH = "rl.sbatch"
TRAINER_TOML = "trainer.toml"
ORCHESTRATOR_TOML = "orchestrator.toml"
INFERENCE_TOML = "inference.toml"
TEACHER_INFERENCE_TOML = "teacher_inference.toml"
def get_physical_gpu_ids() -> list[int]:
"""Return physical GPU IDs visible to the launcher."""
raw_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
if raw_visible is None:
pynvml.nvmlInit()
return list(range(pynvml.nvmlDeviceGetCount()))
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
output_dir.mkdir(parents=True, exist_ok=True)
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
with open(output_dir / RL_TOML, "wb") as f:
tomli_w.dump(config_dict, f)
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / TRAINER_TOML, "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
with open(output_dir / ORCHESTRATOR_TOML, "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude=exclude_inference, exclude_none=True, mode="json"), f)
teacher_inference = getattr(config, "teacher_inference", None)
if teacher_inference is not None:
with open(output_dir / TEACHER_INFERENCE_TOML, "wb") as f:
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
def check_gpus_available(gpu_ids: list[int]) -> None:
"""Raise error if there are existing processes on the specified GPUs."""
pynvml.nvmlInit()
occupied = []
for gpu_id in gpu_ids:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
if processes:
pids = [p.pid for p in processes]
occupied.append((gpu_id, pids))
if occupied:
msg = "Existing processes found on GPUs:\n"
for gpu_id, pids in occupied:
msg += f" GPU {gpu_id}: PIDs {pids}\n"
msg += "Kill these processes or use different GPUs."
raise RuntimeError(msg)
def rl_local(config: RLConfig):
assert config.deployment.type == "single_node"
logger = setup_logger(
config.log.level or "info",
log_file=config.output_dir / "logs" / "rl.log" if config.log.file else None,
json_logging=config.log.json_logging,
)
config_dir = config.output_dir / "configs"
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
if config.dry_run:
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
gpu_offset += num_infer_gpus
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
gpu_offset += config.deployment.num_train_gpus
num_teacher_gpus = config.deployment.num_teacher_gpus or 0
teacher_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_teacher_gpus)) if num_teacher_gpus > 0 else []
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus + num_teacher_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
teacher_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in teacher_local_gpu_ids]
start_command = sys.argv
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Build shared W&B env vars for subprocesses
wandb_shared_env: dict[str, str] = {}
if config.wandb and config.wandb.shared:
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
wandb_shared_env["WANDB_SHARED_RUN_ID"] = uuid.uuid4().hex
# Check for existing processes on GPUs
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
check_gpus_available(all_gpu_ids)
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Prepare paths to communicate with the trainer
log_dir = get_log_dir(config.output_dir)
log_dir.mkdir(parents=True, exist_ok=True)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
try:
# Optionally, start inference process
if config.inference:
inference_cmd = ["uv", "run", "inference", "@", (config_dir / INFERENCE_TOML).as_posix()]
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.stdout", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
if config.orchestrator.teacher_rollout_model is None:
logger.warning(
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
)
else:
logger.info(
"No inference config specified, using orchestrator.teacher_rollout_model for rollout generation."
)
# Optionally, start teacher inference process
if config.teacher_inference:
if not teacher_gpu_ids:
raise ValueError(
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
)
teacher_inference_cmd = ["uv", "run", "inference", "@", (config_dir / TEACHER_INFERENCE_TOML).as_posix()]
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, teacher_gpu_ids))}")
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
with open(log_dir / "teacher_inference.stdout", "w") as log_file:
teacher_inference_process = Popen(
teacher_inference_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, teacher_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(teacher_inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["teacher_inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
elif (
config.trainer.loss.type == "default" and config.trainer.loss.teacher_tau > 0
) or config.orchestrator.teacher_model:
logger.warning(
"No teacher_inference config specified, skipping starting teacher inference server. "
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
)
# Start orchestrator process
orchestrator_cmd = [
"uv",
"run",
"orchestrator",
"@",
(config_dir / ORCHESTRATOR_TOML).as_posix(),
]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.stdout", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / TRAINER_TOML).as_posix(),
]
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", log_dir / "trainer.stdout"])
processes.append(tail_process)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# Small delay to avoid busy waiting
time.sleep(1)
# Check if any critical process failed
if orchestrator_process.returncode != 0:
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
logger.success("RL training finished!")
# Cleanup threads and processes
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
config_path=config_dir / RL_TOML,
output_dir=config.output_dir,
gpus_per_node=config.deployment.gpus_per_node,
)
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
infer_deploy = config.inference.deployment
script = template.render(
**config.slurm.template_vars,
is_disaggregated=True,
config_dir=config_dir,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
nodes_per_infer_replica=infer_deploy.num_nodes,
num_infer_replicas=config.deployment.num_infer_replicas,
num_prefill_nodes=infer_deploy.num_prefill_nodes,
num_decode_nodes=infer_deploy.num_decode_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router_port=infer_deploy.router_port,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
use_deep_gemm=config.inference.use_deep_gemm,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
wandb_shared=config.wandb is not None and config.wandb.shared,
)
else:
script = template.render(
**config.slurm.template_vars,
is_disaggregated=False,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.num_infer_nodes,
num_infer_replicas=config.deployment.num_infer_replicas,
num_teacher_nodes=config.deployment.num_teacher_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router_port=getattr(config.inference.deployment, "router_port", 8000) if config.inference else 8000,
backend_port=getattr(config.inference.deployment, "backend_port", 8100) if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
wandb_shared=config.wandb is not None and config.wandb.shared,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def rl_slurm(config: RLConfig):
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = config.output_dir / "configs"
if config.deployment.type == "single_node":
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
logger.info(f"Wrote config to {config_dir / RL_TOML}")
log_dir = get_log_dir(config.output_dir)
log_message = (
f"Logs:\n"
f" Trainer: tail -F {log_dir}/trainer.stdout\n"
f" Orchestrator: tail -F {log_dir}/orchestrator.stdout\n"
f" Inference: tail -F {log_dir}/inference.stdout"
)
else:
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
slurm_log_dir = config.output_dir / "slurm"
log_lines = [f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log"]
if config.deployment.num_infer_nodes > 0:
log_lines.append(f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log")
log_lines.append(f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log")
log_message = "Logs:\n" + "\n".join(log_lines)
script_path = config.output_dir / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def rl(config: RLConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
validate_output_dir(config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir)
config.output_dir.mkdir(parents=True, exist_ok=True)
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
rl_slurm(config)
else:
rl_local(config)
def main():
rl(cli(RLConfig))
if __name__ == "__main__":
main()
+210
View File
@@ -0,0 +1,210 @@
import os
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import tomli_w
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import get_config_dir, get_log_dir, validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.utils import get_free_port
SFT_TOML = "sft.toml"
SFT_SBATCH = "sft.sbatch"
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
config_path.parent.mkdir(parents=True, exist_ok=True)
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
with open(config_path, "wb") as f:
tomli_w.dump(config_dict, f)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
gpus_per_node=config.deployment.gpus_per_node,
)
else:
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
num_nodes=config.deployment.num_nodes,
gpus_per_node=config.deployment.gpus_per_node,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_path = config_dir / SFT_TOML
exclude = (
{"deployment", "slurm", "dry_run", "clean_output_dir"}
if config.deployment.type == "multi_node"
else {"slurm", "dry_run", "clean_output_dir"}
)
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
if config.deployment.type == "single_node":
log_message = f"Logs:\n Trainer: tail -F {get_log_dir(config.output_dir)}/trainer/rank_0.log"
else:
log_message = f"Logs:\n Trainer: tail -F {config.output_dir}/slurm/latest_train_node_rank_*.log"
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def sft_local(config: SFTConfig):
"""Run SFT training locally with process monitoring and cleanup."""
assert config.deployment.type == "single_node"
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_path = config_dir / SFT_TOML
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
if config.dry_run:
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
log_dir = config.output_dir / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
(config_dir / SFT_TOML).as_posix(),
]
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
logger.debug(f"Trainer command: {' '.join(trainer_cmd)}")
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
try:
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
stop_event = Event()
monitor_thread = Thread(
target=monitor_process,
args=(trainer_process, stop_event, error_queue, "trainer"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", str(log_dir / "trainer.stdout")])
processes.append(tail_process)
stop_event.wait()
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
logger.success("SFT training finished!")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def sft(config: SFTConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
sft_slurm(config)
else:
sft_local(config)
def main():
sft(cli(SFTConfig))
if __name__ == "__main__":
main()
+467
View File
@@ -9,6 +9,60 @@ def transformers_v5_compat():
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
Qwen3VLMoeTextConfig.tie_word_embeddings = False
_patch_qwen35_lora()
monkey_patch_dp_engine_core_pause_resume_deadlock()
def _patch_qwen35_lora():
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
Qwen3.5's GDN layers use create_qkvz_proj with 4 output_sizes (q, k, v, z)
but packed_modules_mapping only lists 2 entries, causing an IndexError
during LoRA initialization.
Also generalizes MergedColumnParallelLinearWithLoRA.can_replace_layer
to accept any number of packed modules (not just 2), and generalizes
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a to handle N
subloras instead of the hardcoded 2 (needed for fully_sharded_loras=True).
Upstream: https://github.com/vllm-project/vllm/issues/36372
"""
from vllm.lora.layers.column_parallel_linear import (
MergedColumnParallelLinearWithLoRA,
MergedColumnParallelLinearWithShardedLoRA,
)
from vllm.model_executor.models.qwen3_5 import (
Qwen3_5ForCausalLMBase,
Qwen3_5ForConditionalGeneration,
)
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
@classmethod
@_not_fully_sharded_can_replace
def can_replace_layer(cls, source_layer, lora_config, packed_modules_list, model_config=None):
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
return type(source_layer) is MergedColumnParallelLinear and len(packed_modules_list) == len(
source_layer.output_sizes
)
MergedColumnParallelLinearWithLoRA.can_replace_layer = can_replace_layer
def slice_lora_a(self, lora_a):
output_shard_size = self.lora_a_stacked[0].shape[2]
output_start_idx = self.tp_rank * output_shard_size
return [
a[output_start_idx : output_start_idx + output_shard_size, :] if a is not None else None for a in lora_a
]
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a = slice_lora_a
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
@@ -201,8 +255,130 @@ def monkey_patch_tokenize_params_validation():
)
return text
def _patched_get_encode_kwargs(self):
"""Use max_total_tokens (max_model_len) instead of max_input_tokens for HF tokenizer truncation.
The original uses max_input_tokens (= max_model_len - max_tokens) + 1, which causes HuggingFace's
tokenizer.encode() to left-truncate prompts before _token_len_check even runs.
"""
max_length = self.truncate_prompt_tokens
if max_length is not None and max_length < 0:
max_length = self.max_total_tokens
elif max_length is None and self.max_total_tokens is not None:
max_length = self.max_total_tokens + 1
return dict(
truncation=max_length is not None,
max_length=max_length,
add_special_tokens=self.add_special_tokens,
)
TokenizeParams._token_len_check = _patched_token_len_check
TokenizeParams._text_len_check = _patched_text_len_check
TokenizeParams.get_encode_kwargs = _patched_get_encode_kwargs
def monkey_patch_hermes_tool_parser_thread_safety():
"""Patch Hermes2ProToolParser to cache tokenizer encode/decode results.
The original __init__ calls tokenizer.encode() and tokenizer.decode() on
every instantiation. Under concurrent load, the shared HuggingFace tokenizer's
Rust backend panics with ``RuntimeError: Already borrowed`` because multiple
threads mutably borrow the same internal state simultaneously.
Fix: run the first __init__ (which calls encode/decode) under a lock, cache
the results, and reuse them for all subsequent instantiations without ever
touching the tokenizer again.
"""
import threading
import regex as re
from vllm.tool_parsers.abstract_tool_parser import ToolParser
from vllm.tool_parsers.hermes_tool_parser import Hermes2ProToolParser
_original_init = Hermes2ProToolParser.__init__
_cache: dict[int, dict] = {}
_lock = threading.Lock()
def _patched_init(self, tokenizer):
from vllm.tokenizers.mistral import MistralTokenizer
# Resolve the actual tokenizer that __init__ will use for encode/decode
actual_tokenizer = tokenizer.tokenizer if isinstance(tokenizer, MistralTokenizer) else tokenizer
key = id(actual_tokenizer)
if key in _cache:
# Fast path: skip encode/decode entirely, set up instance from cache
ToolParser.__init__(self, tokenizer)
if isinstance(tokenizer, MistralTokenizer):
self.model_tokenizer = tokenizer.tokenizer
self.current_tool_name_sent = False
self.prev_tool_call_arr = []
self.current_tool_id = -1
self.streamed_args_for_tool = []
self.tool_call_start_token = "<tool_call>"
self.tool_call_end_token = "</tool_call>"
self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>|<tool_call>(.*)", re.DOTALL)
self.scratch_pad_regex = re.compile(r"<scratch_pad>(.*?)</scratch_pad>", re.DOTALL)
cached = _cache[key]
self.tool_call_start_token_ids = cached["start_ids"]
self.tool_call_end_token_ids = cached["end_ids"]
self.tool_call_start_token_array = cached["start_array"]
self.tool_call_end_token_array = cached["end_array"]
self.buffered_delta_text = ""
return
# Slow path: first instantiation for this tokenizer, run under lock
with _lock:
if key in _cache:
# Another thread populated it while we waited
_patched_init(self, tokenizer)
return
_original_init(self, tokenizer)
_cache[key] = {
"start_ids": self.tool_call_start_token_ids,
"end_ids": self.tool_call_end_token_ids,
"start_array": self.tool_call_start_token_array,
"end_array": self.tool_call_end_token_array,
}
Hermes2ProToolParser.__init__ = _patched_init
def monkey_patch_tokenizer_thread_safety():
"""Patch HuggingFace tokenizer to make _encode_plus thread-safe.
Under concurrent request load, vLLM's API server calls _encode_plus from
multiple async handlers simultaneously. _encode_plus mutates the Rust
tokenizer's internal state via set_truncation_and_padding (enable_truncation/
enable_padding) and encode_special_tokens. The Rust backend uses RefCell-style
borrow tracking (PyO3), and concurrent mutable borrows cause it to panic
with ``RuntimeError: Already borrowed``.
Fix: wrap the entire _encode_plus method in a per-tokenizer threading lock
so that state mutation and the subsequent encode call are atomic.
"""
import threading
from transformers import PreTrainedTokenizerFast
_original_encode_plus = PreTrainedTokenizerFast._encode_plus
_locks: dict[int, threading.Lock] = {}
_meta_lock = threading.Lock()
def _get_lock(tokenizer_id: int) -> threading.Lock:
if tokenizer_id not in _locks:
with _meta_lock:
if tokenizer_id not in _locks:
_locks[tokenizer_id] = threading.Lock()
return _locks[tokenizer_id]
def _patched_encode_plus(self, *args, **kwargs):
lock = _get_lock(id(self._tokenizer))
with lock:
return _original_encode_plus(self, *args, **kwargs)
PreTrainedTokenizerFast._encode_plus = _patched_encode_plus
def monkey_patch_minimax_m2_for_lora():
@@ -278,3 +454,294 @@ def monkey_patch_minimax_m2_for_lora():
".up_proj.": ".w3.",
},
)
def monkey_patch_harmony_stop_token_propagation():
"""Fix: vLLM 0.17.0 doesn't merge harmony stop tokens into per-request SamplingParams.
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
ignores them, using only self.stop_token_ids (which defaults to []).
Upstream: https://github.com/vllm-project/vllm/issues/22519
"""
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
# Merge harmony stop tokens from default_sampling_params
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
if default_stop_ids:
existing = set(params.stop_token_ids or [])
merged = list(existing | set(default_stop_ids))
params.stop_token_ids = merged
return params
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
def monkey_patch_fused_moe_lora_dp():
"""Fix: LoRA + MoE + DP>1 produces corrupted output in vLLM 0.17.0.
Two bugs:
1. LoRA injection sets supports_internal_mk=True (via moe_kernel not None),
causing the MoE runner to skip DP dispatch/combine. But the LoRA kernel
uses NoDPEP and doesn't handle DP internally.
2. LoRA decorators capture full-batch tensors but fire per-chunk inside the
kernel's chunk loop. At DP>=3, dispatched batch > CHUNK_SIZE causes
shape mismatches.
Fix: Replace _inject_lora_into_fused_moe with a version that:
(a) sets moe_kernel=None so the runner correctly dispatches
(b) makes decorators chunk-aware by tracking chunk offsets
Upstream: https://github.com/vllm-project/vllm/issues/23244
"""
import types
from vllm import envs
from vllm.distributed.utils import divide
from vllm.lora.layers.fused_moe import FusedMoEWithLoRA
from vllm.model_executor.layers.fused_moe.config import _get_config_dtype_str
from vllm.model_executor.layers.fused_moe.fused_marlin_moe import MarlinExperts
from vllm.model_executor.layers.fused_moe.fused_moe import TritonExperts
from vllm.model_executor.layers.fused_moe.fused_moe_modular_method import FusedMoEModularMethod
from vllm.model_executor.layers.fused_moe.gpt_oss_triton_kernels_moe import UnfusedOAITritonExperts
from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel
from vllm.model_executor.layers.fused_moe.prepare_finalize import MoEPrepareAndFinalizeNoDPEPModular
def _fixed_inject(self):
moe_state_dict = {}
top_k = self.base_layer.top_k
self.base_layer.ensure_moe_quant_config_init()
quant_config = self.base_layer.quant_method.moe_quant_config
if getattr(self.base_layer.quant_method, "supports_internal_mk", False):
m_fused_moe_fn = self.base_layer.quant_method.moe_kernel
m_fused_moe_fn.shared_experts = None
else:
prepare_finalize = MoEPrepareAndFinalizeNoDPEPModular()
m_fused_moe_fn = FusedMoEKernel(
prepare_finalize,
self.base_layer.quant_method.select_gemm_impl(prepare_finalize, self.base_layer),
)
if quant_config.use_mxfp4_w4a16:
assert isinstance(m_fused_moe_fn.impl.fused_experts, (MarlinExperts, UnfusedOAITritonExperts))
else:
assert isinstance(m_fused_moe_fn.impl.fused_experts, TritonExperts)
# --- Decorators (chunk-aware) ---
def fwd_decorator(layer, func):
def wrapper(*args, **kwargs):
moe_state_dict["hidden_states"] = kwargs["hidden_states"]
moe_state_dict["topk_ids"] = kwargs["topk_ids"]
moe_state_dict["topk_weights"] = kwargs["topk_weights"]
moe_state_dict["expert_map"] = kwargs["expert_map"]
moe_state_dict["apply_router_weight_on_input"] = kwargs["apply_router_weight_on_input"]
moe_state_dict["_chunk_offset"] = 0
return func(*args, **kwargs)
return wrapper
def act_decorator(layer, func):
def wrapper(*args, **kwargs):
_, output, input = args
chunk_M = input.view(-1, top_k, input.shape[-1]).shape[0]
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
curr_topk_ids = moe_state_dict["topk_ids"][chunk_offset : chunk_offset + chunk_M]
expert_map = moe_state_dict["expert_map"]
config_dtype = _get_config_dtype_str(
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
)
num_tokens = hidden_states.size(0)
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
max_lora_rank = self.w13_lora_a_stacked[0].shape[-2]
shrink_config, expand_config = self._get_lora_moe_configs(
op_prefix="w13",
num_loras=self.max_loras,
rank=max_lora_rank,
num_slices=self._w13_slices,
M=M,
layer=layer,
top_k=top_k,
config_dtype=config_dtype,
)
SPARSITY_FACTOR = 8
naive_block_assignment = (
expert_map is None
and num_tokens * top_k * SPARSITY_FACTOR <= self.base_layer.local_num_experts * self.max_loras
)
token_lora_mapping, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora = (
self.punica_wrapper.moe_lora_align_block_size(
curr_topk_ids,
num_tokens,
shrink_config["BLOCK_SIZE_M"],
self.base_layer.local_num_experts,
self.max_loras,
self.adapter_enabled,
expert_map,
naive_block_assignment=naive_block_assignment,
)
)
moe_state_dict["sorted_token_ids_lora"] = sorted_token_ids_lora
moe_state_dict["expert_ids_lora"] = expert_ids_lora
moe_state_dict["num_tokens_post_padded_lora"] = num_tokens_post_padded_lora
moe_state_dict["token_lora_mapping"] = token_lora_mapping
if sorted_token_ids_lora is not None:
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
self.punica_wrapper.add_lora_fused_moe(
input.view(-1, top_k, input.shape[-1]),
hidden_states,
self.w13_lora_a_stacked,
self.w13_lora_b_stacked,
topk_weights,
sorted_token_ids_lora,
expert_ids_lora,
num_tokens_post_padded_lora,
max_lora_rank,
top_k,
shrink_config,
expand_config,
self.adapter_enabled,
fully_sharded=self.fully_sharded,
token_lora_mapping=token_lora_mapping,
)
result = func(*args, **kwargs)
moe_state_dict["intermediate_cache2"] = output
moe_state_dict["_chunk_M"] = chunk_M
return result
return wrapper
def moe_sum_decorator(layer, func):
def wrapper(*args, **kwargs):
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
chunk_M = moe_state_dict.get("_chunk_M", moe_state_dict["hidden_states"].size(0))
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
config_dtype = _get_config_dtype_str(
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
)
num_tokens = hidden_states.size(0)
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
max_lora_rank = self.w2_lora_a_stacked[0].shape[-2]
shrink_config, expand_config = self._get_lora_moe_configs(
op_prefix="w2",
num_loras=self.max_loras,
rank=max_lora_rank,
num_slices=1,
M=M,
layer=layer,
top_k=top_k,
config_dtype=config_dtype,
)
sorted_token_ids_lora = moe_state_dict["sorted_token_ids_lora"]
expert_ids_lora = moe_state_dict["expert_ids_lora"]
num_tokens_post_padded_lora = moe_state_dict["num_tokens_post_padded_lora"]
token_lora_mapping = moe_state_dict.get("token_lora_mapping")
if sorted_token_ids_lora is not None:
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
intermediate_cache2 = moe_state_dict["intermediate_cache2"]
intermediate_cache3 = args[0]
shard_size_w2 = divide(self.base_layer.hidden_size, self.tp_size)
self.punica_wrapper.add_lora_fused_moe(
intermediate_cache3,
intermediate_cache2,
self.w2_lora_a_stacked,
self.w2_lora_b_stacked,
topk_weights,
sorted_token_ids_lora,
expert_ids_lora,
num_tokens_post_padded_lora,
max_lora_rank,
top_k,
shrink_config,
expand_config,
self.adapter_enabled,
True,
fully_sharded=self.fully_sharded,
offset=shard_size_w2 * self.tp_rank if self.fully_sharded else 0,
token_lora_mapping=token_lora_mapping,
)
result = func(*args, **kwargs)
moe_state_dict["_chunk_offset"] = chunk_offset + chunk_M
return result
return wrapper
# --- Install decorators and replace quant method ---
fused_experts = m_fused_moe_fn.impl.fused_experts
m_fused_moe_fn.apply = fwd_decorator(self.base_layer, m_fused_moe_fn.apply)
fused_experts.activation = act_decorator(self.base_layer, fused_experts.activation)
fused_experts.moe_sum = moe_sum_decorator(self.base_layer, fused_experts.moe_sum)
new_method = FusedMoEModularMethod(self.base_layer.quant_method, m_fused_moe_fn)
# Bug 1 fix: NoDPEP kernel makes supports_internal_mk=True, causing the
# runner to skip DP dispatch/combine. Set moe_kernel=None and patch apply().
if isinstance(m_fused_moe_fn.prepare_finalize, MoEPrepareAndFinalizeNoDPEPModular):
saved_kernel = new_method.moe_kernel
saved_disable_expert_map = new_method.disable_expert_map
new_method.moe_kernel = None
def _apply_with_saved_kernel(self, layer, x, topk_weights, topk_ids, shared_experts_input):
return saved_kernel.apply(
hidden_states=x,
w1=layer.w13_weight,
w2=layer.w2_weight,
topk_weights=topk_weights,
topk_ids=topk_ids,
activation=layer.activation,
global_num_experts=layer.global_num_experts,
apply_router_weight_on_input=layer.apply_router_weight_on_input,
expert_map=None if saved_disable_expert_map else layer.expert_map,
shared_experts_input=shared_experts_input,
)
new_method.apply = types.MethodType(_apply_with_saved_kernel, new_method)
self.base_layer._replace_quant_method(new_method)
FusedMoEWithLoRA._inject_lora_into_fused_moe = _fixed_inject
def monkey_patch_dp_engine_core_pause_resume_deadlock():
"""Fix deadlock with pause/resume and collective_rpc in DP engine core.
When a request arrives for an already-completed wave while the scheduler is
paused, the unpatched code sends a start_wave notification that triggers
collective_rpc on other DP engines. But the paused engine can't participate
in the collective, causing a deadlock.
Fix: only send the start_wave notification when the scheduler is unpaused,
and explicitly set engines_running=True before notifying.
Upstream: https://github.com/vllm-project/vllm/pull/37024
"""
from vllm.v1.core.sched.interface import PauseState
from vllm.v1.engine import EngineCoreOutputs
from vllm.v1.engine.core import DPEngineCoreProc, EngineCore
from vllm.v1.request import Request
_base_add_request = EngineCore.add_request
def _patched_add_request(self, request: Request, request_wave: int = 0):
_base_add_request(self, request, request_wave)
if self.has_coordinator and request_wave != self.current_wave:
if request_wave > self.current_wave:
self.current_wave = request_wave
elif not self.engines_running and self.scheduler.pause_state == PauseState.UNPAUSED:
self.engines_running = True
self.output_queue.put_nowait((-1, EngineCoreOutputs(start_wave=self.current_wave)))
DPEngineCoreProc.add_request = _patched_add_request
+4 -4
View File
@@ -1,7 +1,7 @@
import os
from prime_rl.inference.config import InferenceConfig
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
def setup_vllm_env(config: InferenceConfig):
@@ -15,13 +15,13 @@ def setup_vllm_env(config: InferenceConfig):
def main():
config = parse_argv(InferenceConfig, allow_extras=True)
config = cli(InferenceConfig)
setup_vllm_env(config)
# We import here to be able to set environment variables before importing vLLM
from prime_rl.inference.vllm.server import server # pyright: ignore
server(config, vllm_args=config.get_unknown_args())
server(config, vllm_extra=config.vllm_extra)
if __name__ == "__main__":
+176 -29
View File
@@ -1,5 +1,6 @@
from argparse import Namespace
from http import HTTPStatus
from typing import Any
import uvloop
from fastapi import APIRouter, Depends, HTTPException, Request
@@ -21,23 +22,144 @@ from vllm.entrypoints.utils import load_aware_call, with_cancellation
from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
from prime_rl.inference.config import InferenceConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.logger import get_logger
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
# GLM-4.5
"zai-org/GLM-4.5": "glm45",
"zai-org/GLM-4.5-FP8": "glm45",
"zai-org/GLM-4.5-Base": "glm45",
"zai-org/GLM-4.5-Air": "glm45",
"zai-org/GLM-4.5-Air-FP8": "glm45",
"zai-org/GLM-4.5-Air-Base": "glm45",
"zai-org/GLM-4.5V": "glm45",
"zai-org/GLM-4.5V-FP8": "glm45",
# GLM-4.7
"zai-org/GLM-4.7": "glm47",
"zai-org/GLM-4.7-FP8": "glm47",
"zai-org/GLM-4.7-Flash": "glm47",
# GLM-5
"zai-org/GLM-5": "glm47",
"zai-org/GLM-5-FP8": "glm47",
# MiniMax M2
"MiniMaxAI/MiniMax-M2": "minimax_m2",
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
# INTELLECT-3
"PrimeIntellect/INTELLECT-3": "hermes",
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
"PrimeIntellect/INTELLECT-3.1": "hermes",
# Qwen3 dense
"Qwen/Qwen3-0.6B": "hermes",
"Qwen/Qwen3-0.6B-Base": "hermes",
"Qwen/Qwen3-0.6B-FP8": "hermes",
"Qwen/Qwen3-1.7B": "hermes",
"Qwen/Qwen3-1.7B-Base": "hermes",
"Qwen/Qwen3-1.7B-FP8": "hermes",
"Qwen/Qwen3-4B": "hermes",
"Qwen/Qwen3-4B-Base": "hermes",
"Qwen/Qwen3-4B-FP8": "hermes",
"Qwen/Qwen3-8B": "hermes",
"Qwen/Qwen3-8B-Base": "hermes",
"Qwen/Qwen3-8B-FP8": "hermes",
"Qwen/Qwen3-14B": "hermes",
"Qwen/Qwen3-14B-Base": "hermes",
"Qwen/Qwen3-14B-FP8": "hermes",
"Qwen/Qwen3-32B": "hermes",
"Qwen/Qwen3-32B-FP8": "hermes",
# Qwen3 MoE
"Qwen/Qwen3-30B-A3B": "hermes",
"Qwen/Qwen3-30B-A3B-Base": "hermes",
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
"Qwen/Qwen3-235B-A22B": "hermes",
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
# Qwen3 2507
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
# Qwen3-Next
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
# Qwen3-Coder
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
# Qwen3-Coder-Next
"Qwen/Qwen3-Coder-Next": "hermes",
"Qwen/Qwen3-Coder-Next-Base": "hermes",
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
# Qwen3.5 dense (uses qwen3_coder tool format, not hermes)
"Qwen/Qwen3.5-0.8B": "qwen3_coder",
"Qwen/Qwen3.5-0.8B-Base": "qwen3_coder",
"Qwen/Qwen3.5-2B": "qwen3_coder",
"Qwen/Qwen3.5-2B-Base": "qwen3_coder",
"Qwen/Qwen3.5-4B": "qwen3_coder",
"Qwen/Qwen3.5-4B-Base": "qwen3_coder",
"Qwen/Qwen3.5-9B": "qwen3_coder",
"Qwen/Qwen3.5-9B-Base": "qwen3_coder",
"Qwen/Qwen3.5-27B": "qwen3_coder",
"Qwen/Qwen3.5-27B-FP8": "qwen3_coder",
# Qwen3.5 MoE (uses qwen3_coder tool format, not hermes)
"Qwen/Qwen3.5-35B-A3B": "qwen3_coder",
"Qwen/Qwen3.5-35B-A3B-Base": "qwen3_coder",
"Qwen/Qwen3.5-35B-A3B-FP8": "qwen3_coder",
"Qwen/Qwen3.5-122B-A10B": "qwen3_coder",
"Qwen/Qwen3.5-122B-A10B-FP8": "qwen3_coder",
"Qwen/Qwen3.5-397B-A17B": "qwen3_coder",
"Qwen/Qwen3.5-397B-A17B-FP8": "qwen3_coder",
# NemotronH
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "qwen3_coder",
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "qwen3_coder",
}
def resolve_tool_call_parser(model_name: str, tool_call_parser: str | None) -> str | None:
"""Resolve tool_call_parser from model name if set to "auto"."""
if tool_call_parser == "auto":
return MODEL_TOOL_CALL_PARSER.get(model_name)
return tool_call_parser
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_harmony_stop_token_propagation,
monkey_patch_hermes_tool_parser_thread_safety,
monkey_patch_load_lora_adapter,
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode,
monkey_patch_tokenize_params_validation,
monkey_patch_tokenizer_thread_safety,
)
from prime_rl.inference.vllm.serving_chat_with_tokens import (
ChatCompletionRequestWithTokens,
OpenAIServingChatWithTokens,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models (vLLM 0.17.0 bug)
monkey_patch_harmony_stop_token_propagation()
# NOTE: Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode()
# NOTE: Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
monkey_patch_load_lora_adapter()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
monkey_patch_tokenize_params_validation()
# NOTE: Monkeypatch Hermes tool parser to fix "Already borrowed" RuntimeError under concurrent load
monkey_patch_hermes_tool_parser_thread_safety()
# NOTE: Monkeypatch HF tokenizer to fix "Already borrowed" RuntimeError during concurrent chat template processing
# Can be removed once https://github.com/vllm-project/vllm/pull/36557 is merged and we upgrade vllm
monkey_patch_tokenizer_thread_safety()
logger = init_logger("vllm.entrypoints.openai.api_server")
@@ -67,11 +189,22 @@ def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
return request.app.state.openai_serving_chat_with_tokens
@router.post("/pause")
async def pause(request: Request):
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
return {"status": "paused"}
@router.post("/resume")
async def resume(request: Request):
await engine_client(request).resume_generation()
return {"status": "resumed"}
@router.post("/update_weights")
async def update_weights(request: Request):
data = await request.json()
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
# Reset prefix cache to invalidate KV states computed with old weights
await engine_client(request).reset_prefix_cache()
return {"status": "ok"}
@@ -98,12 +231,13 @@ async def init_broadcaster(request: Request):
host = data.get("host")
port = data.get("port")
timeout = data.get("timeout")
# Support both legacy and new field names
server_rank = data.get("server_rank")
num_inference_server = data.get("num_inference_server")
rank_offset = data.get("rank_offset")
inference_world_size = data.get("inference_world_size")
gpus_per_server = data.get("gpus_per_server")
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
await engine_client(request).collective_rpc(
"init_broadcaster",
args=(host, port, server_rank, num_inference_server, timeout),
args=(host, port, rank_offset, inference_world_size, gpus_per_server, timeout, quantize_in_weight_transfer),
)
return {"status": "ok"}
@@ -162,28 +296,31 @@ async def custom_init_app_state(
resolved_chat_template = load_chat_template(args.chat_template)
state.openai_serving_chat_with_tokens = (
OpenAIServingChatWithTokens(
engine_client,
state.openai_serving_models,
args.response_role,
request_logger=request_logger,
chat_template=resolved_chat_template,
chat_template_content_format=args.chat_template_content_format,
trust_request_chat_template=args.trust_request_chat_template,
return_tokens_as_token_ids=args.return_tokens_as_token_ids,
enable_auto_tools=args.enable_auto_tool_choice,
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
tool_parser=args.tool_call_parser,
reasoning_parser=args.structured_outputs_config.reasoning_parser,
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
enable_force_include_usage=args.enable_force_include_usage,
enable_log_outputs=args.enable_log_outputs,
log_error_stack=args.log_error_stack,
)
if "generate" in supported_tasks
else None
chat_kwargs = dict(
request_logger=request_logger,
chat_template=resolved_chat_template,
chat_template_content_format=args.chat_template_content_format,
trust_request_chat_template=args.trust_request_chat_template,
return_tokens_as_token_ids=args.return_tokens_as_token_ids,
enable_auto_tools=args.enable_auto_tool_choice,
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
tool_parser=args.tool_call_parser,
reasoning_parser=args.structured_outputs_config.reasoning_parser,
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
enable_force_include_usage=args.enable_force_include_usage,
enable_log_outputs=args.enable_log_outputs,
)
if hasattr(args, "log_error_stack"):
chat_kwargs["log_error_stack"] = args.log_error_stack
serving_chat = OpenAIServingChatWithTokens(
engine_client,
state.openai_serving_models,
args.response_role,
**chat_kwargs,
)
state.openai_serving_chat = serving_chat if "generate" in supported_tasks else None
state.openai_serving_chat_with_tokens = serving_chat if "generate" in supported_tasks else None
def custom_run_api_server_worker_proc(listen_address, sock, args, client_config=None, **uvicorn_kwargs) -> None:
@@ -223,16 +360,26 @@ vllm.entrypoints.cli.serve.run_api_server_worker_proc = custom_run_api_server_wo
# Adapted from vllm/entrypoints/cli/serve.py
# Only difference we do some config translation (i.e. pass populated namespace
# to `parse_args`) and additional arg validation
def server(config: InferenceConfig, vllm_args: list[str]):
def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
from vllm.entrypoints.openai.api_server import run_server
namespace = config.to_vllm()
if vllm_extra:
for key, value in vllm_extra.items():
setattr(namespace, key, value)
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
parser = make_arg_parser(parser)
args = parser.parse_args(args=vllm_args, namespace=config.to_vllm())
args = parser.parse_args(args=[], namespace=namespace)
assert args is not None
validate_parsed_serve_args(args)
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
args.enable_auto_tool_choice = args.tool_call_parser is not None
if args.tool_call_parser is not None:
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
# Set the worker extension class based on the broadcast backend
args.worker_extension_cls = WORKER_EXTENSION_CLS[config.weight_broadcast.type]
@@ -1,6 +1,8 @@
from collections.abc import AsyncGenerator
import base64
from collections.abc import AsyncGenerator, AsyncIterator
from typing import ClassVar, Optional, Union
import numpy as np
from fastapi import Request
from pydantic import Field
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest, ChatCompletionResponse
@@ -8,57 +10,37 @@ from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
from vllm.entrypoints.openai.engine.serving import GenerationError
from vllm.entrypoints.utils import get_max_tokens
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.outputs import RequestOutput
from vllm.reasoning import ReasoningParser
from vllm.sampling_params import BeamSearchParams, SamplingParams
from vllm.v1.sample.logits_processor import validate_logits_processors_parameters
logger = init_logger(__name__)
def _collapse_image_placeholders(
original_tokens: list[int],
override_tokens: list[int],
) -> list[int]:
"""
Collapse pre-expanded image placeholder tokens in override_tokens.
class _RoutedExpertsCapture:
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
self._generator = generator
self.routed_experts: dict[int, dict] = {}
In multi-turn VLM conversations, tokens from previous turns already have
expanded image placeholders (e.g., 64 consecutive <|image_pad|> tokens).
If left as-is, _process_inputs re-expands each token individually, causing
compounding token inflation across turns.
def _encode_routed_experts(self, arr: np.ndarray) -> dict:
return {
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
"shape": list(arr.shape),
}
Detects placeholder token IDs by comparing with the original engine tokens
(which have single placeholders from _preprocess_chat), then collapses
consecutive runs back to single tokens so _process_inputs can expand
them correctly.
"""
if not override_tokens or original_tokens == override_tokens:
return override_tokens
async def __aiter__(self):
async for request_output in self._generator:
for output in request_output.outputs:
if output.routed_experts is not None:
self.routed_experts[output.index] = self._encode_routed_experts(output.routed_experts)
yield request_output
def get_block_tokens(tokens: list[int], min_run: int) -> set[int]:
"""Return token IDs that appear in consecutive runs >= min_run."""
result = set()
run_start = 0
for i in range(1, len(tokens) + 1):
if i == len(tokens) or tokens[i] != tokens[run_start]:
if i - run_start >= min_run:
result.add(tokens[run_start])
run_start = i
return result
# Placeholder tokens appear in blocks of 2+ in override but only as singles in original
placeholder_ids = get_block_tokens(override_tokens, 2) - get_block_tokens(original_tokens, 2)
if not placeholder_ids:
return override_tokens
result = []
for token in override_tokens:
if token in placeholder_ids and result and result[-1] == token:
continue
result.append(token)
return result
def post_process(self, response: ChatCompletionResponse):
for choice in response.choices:
if choice.index in self.routed_experts:
choice.routed_experts = self.routed_experts[choice.index]
class ChatCompletionRequestWithTokens(ChatCompletionRequest):
@@ -67,7 +49,46 @@ class ChatCompletionRequestWithTokens(ChatCompletionRequest):
class OpenAIServingChatWithTokens(OpenAIServingChat):
"""OpenAI-compatible generate API that allows token-in."""
"""OpenAI-compatible generate API that allows token-in and routed experts capture."""
async def chat_completion_full_generator(
self,
request: ChatCompletionRequest,
result_generator: AsyncIterator[RequestOutput],
request_id: str,
model_name: str,
conversation,
tokenizer,
request_metadata: RequestResponseMetadata,
reasoning_parser: ReasoningParser | None = None,
) -> ErrorResponse | ChatCompletionResponse:
# We need to override the full_generator to be able to capture the routed experts
# By default, VLLM does not save the routed experts into ChatCompletionResponse.choices, so we need to capture them manually
# How this works:
# 1. We create a custom generator that encapsulates the original result_generator in self._generator
# 2. We override it's __aiter__ method to also capture the routed experts as an extra field in ChatCompletionResponse.choices
# 3. We override the full_generator method to use the custom generator instead of the original one if expert routing is enabled
if self.model_config.enable_return_routed_experts:
capture = _RoutedExpertsCapture(result_generator)
result_generator = capture
else:
capture = None
response = await super().chat_completion_full_generator(
request,
result_generator,
request_id,
model_name,
conversation,
tokenizer,
request_metadata,
reasoning_parser,
)
if capture and isinstance(response, ChatCompletionResponse):
capture.post_process(response)
return response
async def create_chat_completion_with_tokens(
self,
@@ -75,8 +96,11 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
raw_request: Optional[Request] = None,
) -> Union[AsyncGenerator[str, None], ChatCompletionResponse, ErrorResponse]:
"""
Copy of OpenAIServingChat.create_chat_completion, adapted to use prompt
ids directly via ChatCompletionRequestWithTokens.
Chat Completion API similar to OpenAI's API.
See https://platform.openai.com/docs/api-reference/chat/create
for the API specification. This API mimics the OpenAI
Chat Completion API.
"""
# Streaming response
tokenizer = self.renderer.tokenizer
@@ -102,16 +126,10 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
conversation, engine_prompts = result
# For VLM models: collapse pre-expanded image placeholders before _process_inputs.
# In multi-turn token prompts, previous turns' image placeholders are already expanded
# (e.g., 64 consecutive <|image_pad|>). Without collapsing, _process_inputs re-expands
# each token, inflating counts (64 → 127 → 253 → ...) across turns.
if engine_prompts[0].get("multi_modal_data"):
override_tokens = _collapse_image_placeholders(engine_prompts[0]["prompt_token_ids"], request.tokens) # type: ignore
else:
override_tokens = request.tokens
engine_prompts[0]["prompt_token_ids"] = override_tokens # type: ignore
# We override prompt tokens directly.
# VLM conversations use MITO (message-based) instead of TITO, so
# multi_modal_data is not expected here.
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
@@ -131,20 +149,33 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
data_parallel_rank = self._get_data_parallel_rank(raw_request)
# Schedule the request and get the result generator.
max_model_len = self.model_config.max_model_len
generators: list[AsyncGenerator[RequestOutput, None]] = []
try:
for i, engine_prompt in enumerate(engine_prompts):
prompt_text = self._extract_prompt_text(engine_prompt)
prompt_token_ids = self._extract_prompt_components(engine_prompt).token_ids
# If we are creating sub requests for multiple prompts, ensure that they
# have unique request ids.
sub_request_id = request_id if len(engine_prompts) == 1 else f"{request_id}_{i}"
prompt_len = self._extract_prompt_len(engine_prompt)
if prompt_len >= max_model_len:
raise VLLMValidationError(
f"This model's maximum context length is "
f"{max_model_len} tokens. However, your request has "
f"{prompt_len} input tokens. Please reduce the length of "
"the input messages.",
parameter="input_tokens",
value=prompt_len,
)
max_tokens = get_max_tokens(
self.max_model_len,
max_model_len,
request.max_completion_tokens if request.max_completion_tokens is not None else request.max_tokens,
self._extract_prompt_len(engine_prompt),
self.default_sampling_params,
self.override_max_tokens,
)
sampling_params: SamplingParams | BeamSearchParams
@@ -153,13 +184,8 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
else:
sampling_params = request.to_sampling_params(
max_tokens,
self.model_config.logits_processor_pattern,
self.default_sampling_params,
)
validate_logits_processors_parameters(
self.logits_processors,
sampling_params,
)
self._log_inputs(
sub_request_id,
@@ -179,35 +205,19 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
trace_headers=trace_headers,
)
else:
tok_params = request.build_tok_params(self.model_config)
tokenization_kwargs = tok_params.get_encode_kwargs()
reasoning_ended = (
reasoning_parser.is_reasoning_end(prompt_token_ids or []) if reasoning_parser else None
)
engine_request = self.input_processor.process_inputs(
sub_request_id,
generator = self.engine_client.generate(
engine_prompt,
sampling_params,
lora_request=lora_request,
tokenization_kwargs=tokenization_kwargs,
trace_headers=trace_headers,
priority=request.priority,
data_parallel_rank=data_parallel_rank,
)
reasoning_ended = None
if reasoning_parser:
reasoning_ended = reasoning_parser.is_reasoning_end(
engine_request.prompt_token_ids or [] # type: ignore[attr-defined]
)
engine_request.reasoning_ended = reasoning_ended
generator = self.engine_client.generate(
engine_request,
sampling_params,
sub_request_id,
lora_request=lora_request,
trace_headers=trace_headers,
priority=request.priority,
prompt_text=prompt_text,
tokenization_kwargs=tokenization_kwargs,
data_parallel_rank=data_parallel_rank,
reasoning_ended=reasoning_ended,
)
generators.append(generator)
@@ -1,6 +1,13 @@
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager, monkey_patch_minimax_m2_for_lora
from prime_rl.inference.patches import (
monkey_patch_fused_moe_lora_dp,
monkey_patch_LRUCacheWorkerLoRAManager,
monkey_patch_minimax_m2_for_lora,
)
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
monkey_patch_LRUCacheWorkerLoRAManager()
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
monkey_patch_minimax_m2_for_lora()
# NOTE: Fix LoRA + MoE + DP>1 corrupted output (vLLM 0.17.0 bug)
# Applied here so it runs inside every worker subprocess, not just the main API server process.
monkey_patch_fused_moe_lora_dp()

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