* feat: disaggregated prefill-decode inference with multi-replica support
Extracted PD disaggregation changes from PR #2010. Adds:
- Disaggregated deployment type with separate prefill/decode nodes
- vLLM kernel format weight transfer (avoids HF checkpoint round-trip)
- Pause/resume lifecycle for draining in-flight requests during weight updates
- Admin URL separation (bypass router for direct server access)
- Multi-replica inference support
- NIXL/UCX, DeepEP, and vllm-router install scripts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: remove vLLM kernel format weight transfer
This PR should focus on PD disaggregation only. The kernel format
transfer path (fused projections, stacked experts, FP8 quantization)
is a separate optimization that can be added back in a dedicated PR.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* style: fix ruff formatting
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address PR review comments
- Raise error if tp != 1 in disaggregated mode instead of silently overriding
- Revert auto_setup_model to main's version (FP8 model name logic not needed for PD)
- Revert nccl.py broadcast to main's inline style (method extraction was for kernel format)
- Add try/finally around weight update to ensure engines are always resumed
- Fix sample config: num_infer_nodes=3 + num_infer_replicas=2 to pass validation
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add disaggregated P/D support to inference SLURM template
Extends the existing inference.sbatch.j2 template with conditional
disaggregated mode support. When deployment type is "disaggregated",
the template splits nodes into prefill/decode groups with per-replica
vllm-router, NIXL KV transfer, and DeepEP expert parallelism.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add inference disag slurm
* add extra deps
* add extra deps
* fix eps
* fadd stuff
* fadd stuff
* fadd stuff
* fix smth
* move deep-gemm from dep group to disagg extra for --all-extras
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: configurable deep-gemm via use_deep_gemm config field
Rebuild deep-gemm from vLLM 0.17 recommended commit (477618c).
Add use_deep_gemm bool to InferenceConfig that sets VLLM_USE_DEEP_GEMM=1
in the sbatch template. Only works with per-tensor FP8 models (e.g. GLM-5-FP8).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* wip
* add config
* add deps
* fix studfs
* fix studfs
* use vllm router from matej
* feat: add X-Session-ID header for prefix cache affinity in PD inference
Monkey-patch verifiers' OpenAI clients to inject X-Session-ID (derived
from example_id) on every inference request. The vllm-router uses this
header for sticky routing so that all requests for the same example hit
the same decode node, enabling prefix cache reuse.
Also updates hendrycks_math config for disaggregated PD with EP.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Revert "feat: add X-Session-ID header for prefix cache affinity in PD inference"
This reverts commit 12deff893d0c5053273c25a537b6979be601eb6a.
* delete slurm
* feat: sticky routing, deep-gemm support, and P/D cleanup
- Add extra_headers_from_state to ClientConfig for per-request dynamic
headers (X-Session-ID from example_id for sticky routing)
- Auto-configure session headers in RL runs
- Pass use_deep_gemm to disagg RL template (VLLM_USE_DEEP_GEMM=1)
- Add --intra-node-data-parallel-size 1 to P/D router args
- Fix uv sync: remove stale --group fp8-inference (deep-gemm now in disagg extra)
- Update verifiers to f6ff5274 (extra_headers_from_state support)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: update verifiers to main (f5580acd)
Points to merged extra_headers_from_state support.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: update disagg rl config for Qwen3-30B-A3B (1P+1D)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add disaggregated inference guide and GLM-5 config (#2077)
* chore: add reasoning_parser to GLM-5 inference config (#2081)
Enables vLLM to split reasoning_content from content natively,
so verifiers saves it as a separate field in trajectories.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Enable none
* Feat: skip master weights gather
* updates deps
* remove configs
---------
Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* fix: use sys.exit(1) in clean_exit to terminate process on fatal error
raise alone doesn't terminate the process in async context - the event
loop swallows the exception and the process hangs indefinitely, leaving
runs stuck in RUNNING state with leaked pods.
* fix: remove unused exception variable for ruff
* Revert "Enable none in config (#2093)"
This reverts commit a25b3e7a18.
* Revert "Fix/none in list (#2094)"
This reverts commit 4f612601f6.
* fix conflict
mamba-ssm needs nvcc and CUDA torch to compile. uv was resolving
CPU-only torch for the build environment, causing bare_metal_version
to be undefined. Adding match-runtime = true ensures the CUDA torch
from pytorch-cu128 index is used during the build.
Add nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16 and
nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 with qwen3_coder parser.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: hybrid CP for Qwen3.5 MoE (DeltaNet + standard attention)
Integrate fla (flash-linear-attention) library for native context parallelism
on GatedDeltaNet layers. Standard attention layers use ring attention for CP,
while DeltaNet layers use fla's state-passing CP which communicates only the
compact recurrent state (O(d²) per layer) instead of all-gathering full
sequences (O(N×d)).
- Add flash-linear-attention dependency (Triton kernels + CP support)
- Wire up fla's build_cp_context/cp_context in GatedDeltaNet forward
- Add setup_hybrid_cp to configure DeltaNet modules for CP
- Add CP gather/scatter autograd primitives as fallback in cp.py
- Fix VLM num_hidden_layers access for debug.num_layers config
- Add test configs for Qwen3.5-35B-A3B CP testing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* style: fix ruff formatting
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove config files from tracking
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: validate VLM bfloat16 dtypes from loaded config
Move the VLM bfloat16 validation from ModelConfig (which only had
the model name) to get_model() where we have the actual loaded HF
config and can reliably detect VLMs via is_vlm_config().
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add NemotronH (Nemotron-3-Super-120B-A12B) model support
Implement hybrid Mamba-Transformer-MoE architecture with three distinct
layer types: Mamba-2 SSM (via HF NemotronHMamba2Mixer), LatentMoE with
non-gated experts and latent projections, and shared attention layers.
- Add NemotronHConfig with hybrid_override_pattern parsing
- Add NonGatedGroupedExperts, NemotronHRouter, LatentMoE to layers/moe.py
- Add bidirectional weight conversion (HF mixer.* <-> PrimeRL namespaces)
- Register model in AutoConfig and update FSDP/EP isinstance checks
- Add comprehensive tests (forward/backward, weight roundtrip, reverse conversion)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: NemotronH weight conversion, MoE forward pass, and HF model compat
Weight conversion (converting_nemotron_h.py):
- Handle backbone.* -> model.* prefix rename (HF uses "backbone", PrimeRL uses "model")
- Stack individual expert weights into fused 3D tensors (HF stores per-expert, PrimeRL uses fused)
- Unstack fused tensors back to individual experts for HF export
- Drop mtp.* (multi-token prediction) keys during conversion
- Support both backbone.* and model.* prefixes in layer type inference
MoE forward pass (moe.py):
- Apply routing scores AFTER expert computation (was before), matching vLLM and HF reference
- Apply routed_scaling_factor separately after expert output, before fc2_latent_proj
- Remove routed_scaling_factor from router scores (applied in LatentMoE instead)
Model loading (model.py):
- Support HF models with "embeddings" attr (not just "embed_tokens") in FSDP setup
- Support HF models with "norm_f" attr (not just "norm") in FSDP setup
- Guard all .mlp accesses with getattr for HF model compat (NemotronHBlock has no .mlp)
Modeling (modeling_nemotron_h.py):
- Handle backbone.* prefix in is_hf_state_dict detection
- Handle both model.* and backbone.* in layer type inference
- Per-layer HF conversion for weight broadcast (model.* -> backbone.*)
Configs:
- Add nemotron_4node/ and nemotron_debug/ run configs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove spurious RoPE from NemotronH attention layers
NemotronH gets position information from Mamba layers, not RoPE.
Both HF and vLLM implementations confirm NemotronH attention does not
apply rotary embeddings. The spurious RoPE was causing ~0.5 KL mismatch
between vLLM inference and PrimeRL training; after removal KL drops to
near zero.
- Make position_embeddings optional in FlashAttention/SDPAAttention
- Remove RotaryEmbedding from NemotronHModel
- Add KL mismatch test suite for NemotronH
- Mark test_nemotron_h_reverse as xfail (pre-existing HF fused tensor issue)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use mamba_ssm Triton SSD kernels for NemotronH to match vLLM precision
The HF torch_forward computes softplus in bf16 while vLLM uses fp32
Triton kernels, causing ~0.4 KL divergence in Mamba layers. This patch
monkey-patches NemotronHMamba2Mixer to use mamba_chunk_scan_combined
from mamba_ssm (Triton, fp32 softplus) with PyTorch nn.Conv1d fallback.
- Add mamba_ssm Triton SSD patch for NemotronHMamba2Mixer
- Add mamba-ssm as optional dependency in pyproject.toml
- Update installation skill with mamba-ssm instructions
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: update uv.lock for mamba-ssm and fix ruff formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: move mamba-ssm to dependency-groups to fix CI CPU tests
mamba-ssm requires nvcc to build from source. When it was in
[project.optional-dependencies], `uv sync --all-extras` tried to build
it in CI where nvcc isn't available. Moving it to [dependency-groups]
means it's only installed explicitly via `uv sync --group mamba-ssm`.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: detect attention layers in is_prime_state_dict for weight broadcast
The per-layer is_prime_state_dict check missed attention-only layers
(which have self_attn.* keys), causing the HF conversion to be skipped
during weight broadcast. vLLM then received PrimeRL keys (self_attn.*)
instead of HF keys (mixer.*), failing with a 500 error.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: update uv.lock and ruff formatting for NemotronH
- Reformat modeling_nemotron_h.py to pass ruff check
- Update uv.lock after mamba-ssm dependency group addition
- Add pre_run_command to nemotron config for mamba-ssm install
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: guard mamba_ssm import for CI environments without it
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: include mamba-ssm in Docker build for NemotronH support
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address review feedback for NemotronH
- Add non-layer weight handling to convert_layer_to_prime (backbone.* prefix)
- Make embed_module fallback consistent (safe getattr for both attrs)
- Remove unused routed_scaling_factor from NemotronHRouter
- Remove dead get_max_layer_num function from converting_nemotron_h
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Individual rollout group failures in generate() are now caught and
logged instead of propagating up and crashing the orchestrator.
Metrics are computed on the successful rollouts. If all rollouts
fail for an env, evaluate_env skips metrics with a warning.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add GPT-OSS support with LoRA + DP fix
Add monkey patches to fix two vLLM 0.17.0 bugs that prevent serving
GPT-OSS MoE models with LoRA enabled under data parallelism:
1. Harmony stop token propagation: vLLM's ChatCompletionRequest doesn't
merge harmony stop tokens (<|call|>, <|return|>) from
default_sampling_params into per-request SamplingParams. The model
ignores tool call boundaries. Fix: patch to_sampling_params() to
merge default stop token IDs.
2. FusedMoE LoRA + DP: LoRA injection on MoE layers replaces the quant
method with FusedMoEModularMethod, which inadvertently sets
supports_internal_mk=True. This makes the MoE runner skip DP
dispatch/combine, but the LoRA kernel uses NoDPEP and doesn't handle
DP. Additionally, LoRA decorators capture full-batch tensors but fire
per-chunk inside the kernel's chunk loop, causing shape mismatches at
DP>=3. Fix: set moe_kernel=None to restore dispatch/combine, and make
decorators chunk-aware by tracking offsets.
Also adds an example config for wiki-search with GPT-OSS-20B.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: apply MoE LoRA+DP monkey patch in worker subprocesses
The monkey_patch_fused_moe_lora_dp() in server.py only runs in the main
API server process. vLLM DP workers are spawned as separate subprocesses
that import FusedMoEWithLoRA fresh, so the patched _inject_lora_into_fused_moe
never reaches them. This causes corrupted MoE output at DP>1 with --enable-lora.
Apply the patch in the worker extension module (filesystem.py) which gets
imported inside every worker subprocess.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove redundant MoE LoRA+DP patch from server.py
This patch only ran in the main API server process, not the DP worker
subprocesses where FusedMoEWithLoRA is actually instantiated. The
effective call is in filesystem.py (worker extension).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: move MoE LoRA+DP patch to worker __init__.py
Move from filesystem.py to __init__.py so it applies regardless of which
worker extension is loaded (filesystem or nccl).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove GPT-OSS wiki-search config from PR
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: dev <dev@prime-rl.dev>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* SFT distillation with teacher endpoint
* streamline SFT distillation rollout/eval model split
* fix sft reconstruction and default loss scaling regressions
* simplify SFT distillation by removing eval inference split
* chore: apply ruff formatting
* docs: add changelog entries for RolloutModelConfig, SFTLossConfig, and CustomLossConfig
Co-authored-by: will brown <willccbb@users.noreply.github.com>
* refine external SFT rollout path and cleanup tests
* refactor shared SFT chat-template tokenization logic
* fix: remove dead store in _tokenize_step_from_messages
full_ids was tokenized via _render_messages then immediately overwritten
by build_incremental_token_mask, wasting a tokenization pass per step.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove unused _should_add_generation_prompt from trajectories
Duplicate of should_add_generation_prompt in utils/chat_template.py,
never called anywhere.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: pass top_k and min_p for both token and non-token client paths
Explicitly disable top-k and min-p filtering on all vLLM requests,
not just the token client path.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove redundant test_rl_config_external_rollout_mode_rejects_inference
Redundant with the Pydantic model validator definition.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: correct CHANGELOG field name to teacher_rollout_model
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: pass tool definitions through pretokenize pipeline
When external teacher rollouts have tool_defs, convert them to OAI
format and pass through to build_incremental_token_mask so that
tokenization includes tool definition tokens from the chat template.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: enable collapse_consecutive_tool_messages in pretokenization
Matches the SFT data pipeline behavior. Without this, parallel tool
call responses cause an assertion failure in incremental tokenization
when the chat template re-renders consecutive tool messages.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: handle dict tool_defs in _convert_tools_to_oai_format
Tool definitions arrive as plain dicts after ZMQ msgpack serialization
(verifiers' msgpack_encoder calls model_dump() on Tool pydantic objects).
Use duck-typed accessor to support both dict and object forms.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: VLM processor support in SFT distillation pretokenization
For VLM models, the tokenizer alone produces only 1 <|image_pad|> token
per image, but the model expects the count to match actual image patches.
Thread the processor through pretokenize → render_messages →
build_incremental_token_mask so that processor.apply_chat_template
(which expands image placeholders correctly) is used when available.
Also move pretokenize before build_vlm_image_cache in the orchestrator,
since the cache build strips image data from messages.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* perf: replace incremental token mask with direct completion masking
In the SFT distillation path, completion is always a single assistant
message (enforced by verifiers' parse_response_message), so the
completion mask is trivially all-True. Replace N incremental
tokenizer/processor calls from build_incremental_token_mask with a
single render_messages call. For VLM models this avoids redundant
image preprocessing on every incremental prefix.
Added assertion to guard the single-assistant-role assumption.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove duplicate SFT distillation configs
Keep examples/alphabet_sort/sft_distill_hard.toml as the canonical
example config.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: always request logprobs in sampling args
logprobs=True was only set when use_token_client=True, but non-token-
client paths (e.g. external APIs) also need logprobs for RL training.
return_token_ids remains gated behind use_token_client since it is
vLLM-specific.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove test_rl_config_external_rollout_mode_rejects_token_client
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: set checkpoint_ready in non-policy-update path
When enable_policy_updates is False (SFT distillation), generate_batch
skipped calling checkpoint_ready.set(). This worked by accident because
the event starts set and is only cleared inside maybe_update_policy
(which is never called in this path), but would deadlock if anything
else ever cleared the event.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Address PR review feedback
- Revert loss_scale regression: use loss_mask-based scaling unconditionally
- Move setup_external_rollout_model to orchestrator/utils.py
- Clarify log message to say "SFT distillation mode"
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: truncate prompt_ids to common prefix to prevent corrupted token sequences
When tokenizing trajectory steps from messages, the prompt-only and
full (prompt+completion) tokenizations can diverge at a boundary
(non-prefix split). Previously, the full prompt_ids was returned even
when split_idx < len(prompt_ids), producing corrupted sequences where
prompt_ids + completion_ids != full_ids. This broke interleaving
(extension property checks fail on mismatched prefixes) and fed
invalid token sequences to the trainer.
Fix: use full_ids[:split_idx] as prompt_ids so the concatenation
always equals full_ids exactly.
Verified across GLM-4, Qwen3, Qwen2.5, Qwen2.5-VL tokenizers and
tested end-to-end SFT distillation on alphabet-sort, wiki-search,
tic-tac-toe, and color-codeword (VLM) environments.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: restore non-prefix tokenization debug log after prompt_ids truncation
The previous commit truncating prompt_ids to full_ids[:split_idx] made
the debug log condition always false (split_idx < split_idx). Track the
original prompt length before overwrite so the log fires correctly.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: William Brown <williambrown97@gmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: will brown <willccbb@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Console reward was using results_df.reward.mean() (flat mean across all
rollouts) while wandb logged by_example.reward.mean().mean() (mean per
example, then across examples). These diverge when rollouts_per_example
varies across problems. Now both use the same aggregation.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Add router_url support for elastic inference pool
When configured, inference requests route through a vllm-router
while admin operations (weight updates, LoRA loading) still go
directly to discovered pods via elastic DNS discovery.
* Gate router traffic on ready servers
Only expose the router client when there are actually ready backends,
preventing requests from being sent to a router with no healthy pods
during weight updates or scale-down.
* fix: remove misleading orchestrator throughput metric
The orchestrator's perf/throughput (tokens/s) was computed as
num_tokens / generate_completions_time, but with in-flight rollouts
some tokens are generated during the previous training step. This makes
generate_completions_time shorter than the actual total inference time,
inflating the reported throughput. Per-rollout generation_ms metrics
remain available for accurate inference speed tracking.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove throughput from orchestrator benchmark table
Same misleading metric — remove it from print_benchmark as well.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add Group Relative Reward Rescaling as length penalty
* require online difficulty filtering
* add config validation
* fix mean
* refactor
* move `baseline`
* GR3 length penalty: Advantage config validator bug (#2039)
The validate_gr3_alpha validator in AdvantageConfig was incorrectly
accessing self.online_difficulty_filtering, which belongs to BufferConfig,
not AdvantageConfig. This caused an AttributeError whenever gr3_alpha was
set to a truthy value, making the GR3 feature unusable.
Fixed by moving the online_difficulty_filtering check to OrchestratorConfig
where both advantage and buffer configs are accessible.
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
* fix baseline
* fix dtype
* changelog
* rename to `length_shaping_alpha`
* deprecate `length_weighte_mean`
* add test
---------
Signed-off-by: rasdani <73563550+rasdani@users.noreply.github.com>
Co-authored-by: rasdani <3563550+rasdani@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Add a sample_ratio field (0.0–1.0) to LogExtrasConfig that controls
what fraction of rollouts are logged per step. When set, the effective
sample cap is computed from the actual rollout count at runtime:
int(len(rollouts) * sample_ratio).
1.0 = all rollouts (full data)
0.5 = half of rollouts
0.0 = disable sample logging
None (default) = current behavior (log all)
Usage: --prime-monitor.log-extras.sample-ratio 0.5
atexit handler ensures spawned env server processes are terminated when
the orchestrator crashes, preventing orphaned subprocesses that keep the
container alive and leave the run stuck in RUNNING.
* fix: handle DTensor weights in MultiLoRAGroupedExperts for EP compatibility
When Expert Parallelism is enabled, distribute_module() converts all
parameters to DTensors sharded across the EP mesh. The base GroupedExperts
path handles this via the @expert_parallel decorator, but
MultiLoRAGroupedExperts.forward() bypassed the decorator entirely,
passing DTensors directly to torch._grouped_mm alongside regular tensors.
Mirror the @expert_parallel decorator logic: convert DTensors to local
shards, apply generate_permute_indices for token reordering and alignment
padding, and unpermute the output.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: gather EP-sharded LoRA weights in state_dict and exclude base_layer from modules_to_save
Two fixes for EP + LoRA MoE weight broadcast:
1. state_dict_for_adapter: call full_tensor() on DTensor LoRA weights
before per-expert indexing. With EP, these weights are sharded across
ranks and direct indexing triggers a DTensor redistribute assertion.
2. save_lora_config: exclude "base_layer" params from modules_to_save
detection. After EP/FSDP wrapping, base layer params can have
requires_grad=True, causing them to be incorrectly added to
modules_to_save which vLLM rejects.
Tested end-to-end: Qwen3-30B-A3B EP=4, LoRA rank 16, 30 steps at
batch sizes 128 and 256 on H200.
* fix: re-freeze base params after EP replaces them with DTensors
ExpertParallel() replaces expert params with DTensors that default to
requires_grad=True, overriding the freeze applied by LoRA setup.
Re-run freeze_all_except_lora_and_specified after apply_ep to restore
correct grad state.
This also reverts the save_lora_config workaround (base_layer filter)
since the root cause is now fixed.
* fix: use new_zeros instead of new_empty for unpermuted output buffer
new_empty leaves uninitialized memory in positions not covered by
permuted_indices, which could leak garbage values into the output.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Previously, custom losses were normalized by batch_size (number of
sequences) while the default loss was normalized by the number of
unmasked tokens. This made the effective learning rate depend on
sequence length for custom losses. Now all loss types consistently
normalize by the number of unmasked tokens.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* make the loss equal weight per unmaked token
* minor fixes
* run ruff
* prevent nan-poisoning
* update
---------
Co-authored-by: hallerite <git@hallerite.com>
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a was hardcoded
for exactly 2 subloras, causing IndexError with Qwen3.5's 4-way
qkvz fusion when fully_sharded_loras=True.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Move max_retries from EvalEnvConfig to EnvConfig so it applies to both
training and eval environments. The scheduler now looks up max_retries
per task from the env config instead of hardcoding 0.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add Qwen 3.5 MoE model support with EP and CP integration
Adds a custom Qwen 3.5 MoE (GatedDeltaNet + MoE) implementation with:
- HF <-> PrimeRL weight conversion (fused/unfused expert formats)
- Expert Parallelism support (MoE layers auto-detected by apply_ep)
- Context Parallelism support (ring attention patching for flash attention layers)
- Router replay via routed_experts argument
- Unit tests for forward pass, weight roundtrip, router replay, and CP patching
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* remove vflm warning
* feat: add custom VLM support for Qwen 3.5 MoE
Extend Qwen3_5MoeForCausalLM to handle both text-only and VLM configs.
When the config has a vision_config, the model creates a composite body
(HF frozen vision encoder + custom PrimeRL text model). Weight conversion
auto-detects VLM keys and remaps accordingly.
- Unified model class (no separate VLM file) driven by config
- Config-based VLM detection fallback for local model paths
- VLM dispatch in get_model() via _CUSTOM_VLM_MAPPING
- mini_moe.py preset for qwen3_5_moe_vlm testing
- 6 new GPU tests covering forward/backward/weights/roundtrip/router/meta
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add debug SFT config for real Qwen3.5-35B-A3B VLM
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: support VLM layer key format in weight broadcast
VLM models use `model.language_model.layers.*` instead of
`model.layers.*`, which crashed get_max_layer_num and caused
filter_state_dict_by_layers to silently drop layer weights.
Also fixes off-by-one in filter_state_dict_by_layers that
skipped layer 0.
* use registry-based approach
* run ruff
* chore: remove debug SFT configs for Qwen3.5 MoE
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
* fix: use repr for rollout error log to show full error chain
The rollout error warning was using str formatting which only showed
the short error_chain_str. Using repr shows the full error_chain_repr
with the actual error message, making debugging much easier.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: print error_chain_repr instead of full error dict
Show only the error_chain_repr from the rollout error dict in the
warning log, which contains the actual useful error message rather
than the entire dict.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* simplify: index directly into error dict
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: make errored_rollouts and empty_rollouts metrics rates per step
Instead of logging raw counts, divide by total rollouts in the step
to get the fraction of errored/empty rollouts. This makes the metrics
comparable across steps with different numbers of rollouts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: re-schedule errored rollouts instead of filtering after group completion
Rollouts with a populated "error" field are now re-scheduled (like empty
trajectories) instead of being accepted into the group. Both conditions
are checked independently so a rollout that is both empty and errored
increments both counters. Adds scheduler/errored_rollouts metric.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: remove now-dead error/mean metrics from orchestrator
Errored rollouts are filtered in the scheduler before reaching the
batch, so error is always None in results_df. Remove the error column
and the error/all/mean and error/{env}/mean metrics. Error tracking
is now handled by scheduler/errored_rollouts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: per-env metrics for empty and errored rollouts
Track empty_rollouts and errored_rollouts counts per task. Report both
global (scheduler/empty_rollouts/all, scheduler/errored_rollouts/all)
and per-env (scheduler/empty_rollouts/{task}, scheduler/errored_rollouts/{task})
metrics.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: move empty/errored rollout metrics to their own section
Use empty_rollouts/ and errored_rollouts/ prefixes instead of nesting
under scheduler/.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: allow num_infer_nodes=0 with fake data in multi-node SLURM RL
Skip launching inference servers and orchestrator when num_infer_nodes=0,
running only the trainer with fake data. Useful for benchmarking multi-node
training without needing inference resources.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: skip weight broadcast when using fake data
No inference server exists in fake data mode, so broadcasting weights
would either hang (NCCL) or write unnecessary files (filesystem).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: per-env metrics logging with consistent naming convention
Adopt {metric}/{scope}/{stat} naming where scope is "all" (global) or
an env name. All metrics that were previously global-only now get
per-env breakdowns when multiple envs are present.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: always show per-env breakdown and drop reward std/median
Remove the nunique() > 1 gate so per-env metrics are always logged,
even with a single env. Remove std and median from reward stats.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: metrics/{env}/{metric} format, remove error type breakdown
- Change verifier/filter metrics to metrics/{env}/{metric} (no global, no stat suffix)
- Remove per-error-type logging (error/{error_type})
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove redundant batch/{env}/{env} keys
Env ratios only make sense at the global level (batch/all/{env}).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: separate solve/batch/off_policy metrics, flatten async_level
- Extract solve_none, solve_all, effective_batch_size as top-level
metrics with /all and /{env} breakdowns
- Move off_policy_level to off_policy_level/all/{stat}
- Make async_level a flat key
- batch/ now only contains env ratios and inflight/cancelled counts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: per-env off_policy_level tracking
Add task field to InflightRolloutInfo so off_policy_level can be
reported per env as off_policy_level/{env}/{stat}.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: rename batch/ inflight/cancelled to progress/, simplify batch/{env}
- batch/inflight_rollouts, batch/inflight_samples, batch/cancelled_rollouts
moved to progress/ prefix
- batch/all/{env} simplified to batch/{env}
- async_level moved to scheduler/async_level
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: inline grouped_stats, separate global and per-env sections
Remove grouped_stats helper in favor of explicit inlined metrics.
Global metrics come first, per-env metrics in a dedicated section after.
All metrics consistently group by example_id before aggregating.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: validate that env name is not "all" (reserved for global metrics)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update scheduler config
* fix: use example_id grouping for solve stats instead of index arithmetic
The previous index-based approach (index // rollouts_per_example)
assumed rollouts were contiguous by example, which is not guaranteed
when the scheduler interleaves groups from different envs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: update scheduler test for new task field on InflightRolloutInfo
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: add changelog entry for metrics logging overhaul
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: validate unique env names, use notna(), simplify metrics_df access
- Add unique env name validation on OrchestratorConfig and EvalConfig
- Use notna() instead of ~isna() for error rate
- Use index-based loc instead of copying metrics_df with task/example_id
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: extract compute_solve_rates, inline _off_policy_steps_by_task
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: inline solve_stats, use compute_solve_rates directly
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* also log per_env stop conditions
* minor
* style
* address bugbot
* min diff in changelog
* update changelog
* revert metrics_df
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Empty trajectories were filtered after sampling from the buffer, which
could yield incomplete groups and break the advantage computation's
assumption that each group has exactly `rollouts_per_example` rollouts.
Now empty trajectories are detected per-rollout as they complete. When
one is found, `rollouts_to_schedule` is incremented so the group
naturally re-fills via `_fill_inflight_requests`, and the group is only
yielded once it has the full count of non-empty rollouts.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: disk-backed image offloading for VLM orchestrator memory
Replace base64 image data in rollout trajectories with file paths
immediately after receiving from ZMQ. This eliminates the triangle
duplication problem where 15-turn rollouts store 120 copies of
screenshot base64 strings in memory.
Images are written to {output_dir}/assets/images/{sha256}.png and
deduped by content hash. The VLM image cache reads from disk instead
of decoding from base64 strings.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add VLM memory benchmark for disk offloading
Benchmark generates synthetic rollouts with triangle-duplicated
screenshots, simulates ZMQ msgpack roundtrip, and measures RSS
with and without disk-backed image offloading.
Results with 32 rollouts, 15 turns, 512x384 screenshots (~770KB each):
- Without offload: +2.9 GB (91 MB/rollout)
- With offload: +7.8 MB (0.24 MB/rollout)
- 99.7% memory reduction
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: ruff lint fixes in vlm_memory_bench
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: ruff format
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: remove benchmarks folder
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Revert "chore: remove benchmarks folder"
This reverts commit 79918131a8c06be55b5a7450a24f2ca82e9aa206.
* revert: restore benchmarks folder, only remove vlm_memory_bench.py
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: handle file:// URLs in _extract_images_from_messages
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: filter empty trajectory rollouts in scheduler
Empty trajectories consume batch slots without producing training signal.
Filter them after sampling so they don't count toward batch progress,
and track the count as a metric for observability.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* rename to empty_rollouts for consistency
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* remove empty batch retry logic from orchestrator
The scheduler already filters empty trajectories, so the orchestrator
should not silently retry on empty batches — better to fail fast.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Adds automated PR review using anthropics/claude-code-action@v1.
Reviews run on PR open/sync/reopen and responds to @claude mentions.
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* chore: move env packages to dedicated `envs` extras group
Move math-env and reverse-text from main dependencies into a new
`envs` optional-dependencies group alongside all other environment
packages used in configs (aime2024, aime2025, alphabet-sort, code-env,
color-codeword, logic-env, math-python, math500, science-env,
wiki-search). All sourced from the primeintellect index.
Install with: uv sync --extra envs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: remove primeintellect/ prefix from env IDs in configs
Envs are now installed directly via the envs extras group, so the
primeintellect/ prefix is no longer needed for runtime installation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: mark primeintellect index as explicit
Prevents uv from querying the primeintellect index for every package
during resolution, drastically speeding up uv sync/lock.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add configurable pre_run_command for SLURM jobs
Allow running a cleanup command on compute nodes before starting
the job (e.g. `sudo pkill -f vllm`). Configured via `slurm.pre_run_command`.
For multi-node jobs, the command runs on all nodes via srun.
Replaces the hardcoded `pkill -9 -f vllm` in the inference template
with the configurable option.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: tighten whitespace in template pre_run_command blocks
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: run pre_run_command on head node only, avoid shell quoting issues
Drop the srun bash -c wrapper from multi-node templates. The command
now runs directly on the head node (same as single-node), which avoids
single-quote injection when the user's command contains quotes.
Users who need all-nodes execution can wrap with srun themselves:
pre_run_command = "srun bash -c \"pkill -f vllm || true\""
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: add CHANGELOG entry for slurm.pre_run_command
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add nodelist, exclude, account, and time SLURM options
Add commonly needed SLURM scheduling fields to SlurmConfig:
- nodelist: target specific nodes
- exclude: exclude specific nodes
- account: charge to a SLURM account
- time: set maximum wall time
Also extract common slurm fields into SlurmConfig.template_vars
to avoid duplicating them across every template.render() call.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: clean up Jinja2 whitespace for optional SBATCH directives
Use {%- if %} to strip leading newlines so no blank lines appear
when optional fields are unset.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: run pre_run_command after env setup in single-node templates
Single-node templates ran pre_run_command before cd, .env sourcing,
and venv activation. Move it after setup to match multi-node and
inference templates. Update docs to clarify execution context.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove orchestrator W&B resume ID warning
The warning about missing W&B run ID for orchestrator when resuming
training is not useful and creates noise.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove trainer W&B resume ID warning
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: replace warnings.warn with get_logger().warning in configs
Use prime-rl's logger instead of Python's warnings module for
config validation warnings.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: reduce orchestrator memory usage for VLM rollouts
The orchestrator's RSS grew unboundedly when processing VLM rollouts
with images (e.g. 1.2 GB → 25+ GB over 10 steps, spiking to 38 GB).
Three root causes:
1. Base64 image data in rollout prompts stayed alive through the entire
step pipeline (preprocessing, training batch, wandb logging). Now
stripped immediately after image extraction in _extract_images_from_examples.
2. Intermediate objects (PIL images, torch tensors, chunk results) in
_preprocess_images_batched were held simultaneously. Now freed eagerly
with del/clear() after each conversion step.
3. Python's GC and glibc malloc arenas retained freed memory across steps.
Now explicitly gc.collect() + malloc_trim(0) at end of each step.
Result: baseline 3-5 GB (stable), spikes 5-9 GB (bounded).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: extract strip_base64_images into a standalone function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: delete chunks before clearing images to actually free PIL objects
chunks holds shallow-copy references to the same PIL images, so
images.clear() alone doesn't free them during peak memory usage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Update src/prime_rl/orchestrator/trajectories.py
Signed-off-by: hallerite <git@hallerite.com>
---------
Signed-off-by: hallerite <git@hallerite.com>
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
* Add arm64 support to Dockerfile and deps
- Swap builder base to multi-arch nvidia/cuda:12.8.1 image
- Add platform_machine markers to x86_64-only wheel deps
* Fix tzdata interactive prompt in arm64 build
* Fix tzdata interactive prompt in Docker build
* add arm64 flash-attn source build and expose max_num_seqs on inference CLI
* only target sm_100 for arm64 flash-attn build
* remove max_num_seqs, belongs in a separate PR
* also build flash-attn-3 from source for arm64, supports sm_100
* use pip for flash-attn-3, uv cant resolve torch match-runtime from git
* use pip for flash-attn-3: uv rejects match-runtime without static metadata
* link uv issue in dockerfile comment
* use venv pip for flash-attn-3, pip not on PATH in builder
* use uv run pip for flash-attn-3
* install pip into venv before using it for flash-attn-3
* fix arm64 flash-attn build: export env vars, add ninja
* fix: install python ninja package, export all env vars properly
* remove flash-attn-3 from arm64 build, fa4 (flash-attn-cute) is used instead
* Fix missing cutlass.utils.ampere_helpers on arm64 (#1948)
* Fix missing cutlass.utils.ampere_helpers on arm64
flash-attn.cute imports cutlass.utils.ampere_helpers but
nvidia-cutlass-dsl 4.4.1 doesn't ship that module. Copy it
from flashinfer's vendored cutlass which has the file.
* Expand Dockerfile comment explaining cutlass ampere_helpers workaround
* Reinstall flash-attn-cute after flash-attn on arm64 to fix namespace conflict (#1949)
* Pin flash-attn-cute to locked commit, upstream renamed package to flash-attn-4 (#1950)
* Upgrade flash-attn-cute for cutlass-dsl 4.4.1 backward pass fix (#1952)
* Upgrade flash-attn-cute to 7ed0898 for cutlass-dsl 4.4.1 compatibility
* Pin fix-flash-attn-cute.sh to same commit as pyproject.toml
* Pin flash-attn-cute to 2b5db43 for cutlass-dsl 4.4.1 compat and sm100 backward fix
* refactor: extract arm64 post-install logic into script
* skip arm64 script entirely on x86, trim comments
* update uv.lock
* revert pydantic-config to branch=main
* pin flash-attn==2.8.3 in arm64 post-install
* pin flash-attn-cute to e2743ab5, regenerate uv.lock
* align flash-attn-cute rev in scripts with pyproject.toml (e2743ab5)
* fix: modality-aware batch distribution to prevent FSDP deadlocks
When training multimodal models with FSDP, ranks must execute the same
operations at each step. If one rank processes a multimodal batch
(triggering the vision encoder all-gather) while another processes
text-only, training hangs. Fix by separating micro batches by modality,
padding each group independently, and distributing in strided order so
all ranks see the same modality at each step index.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* ruff format
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: disable timeout on admin httpx clients
Admin operations (weight updates, LoRA loading, NCCL broadcast) can block
for an unbounded amount of time — especially under load where vLLM servers
are slow to enter NCCL receive mode. The previous 1200s read timeout was
causing orchestrator crashes on heavy prod runs.
Also adds retry logic to _update_weights for 5xx responses, matching the
existing behaviour of load_lora_adapter.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* remove retry
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat: add Qwen3.5 support
Bump vLLM to >=0.16.1.dev (nightly) which includes Qwen3.5 model support.
This requires torch 2.10 (resolved from the existing >=2.9.0 pin), an
updated flash-attn wheel built against torch 2.10, and version overrides
for nvidia-cutlass-dsl and quack-kernels.
Bump transformers pin to 5c1c72b which includes a rope validation fix
for Qwen3.5 (https://github.com/huggingface/transformers/pull/44272).
Add a trainer monkey-patch for a transformers bug where Qwen3.5 passes
3D MRoPE position_ids to decoder layers instead of 2D text_position_ids,
which breaks flash attention and causes NaN gradients. The upstream fix
is pending: https://github.com/huggingface/transformers/pull/44399
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* apply patch for Qwen3.5 MoE model variants
* remove duplicated nvidia-cutlass-dsl override
* fix: patch Qwen3.5 MoE weight conversion mapping for broadcasting
* ruff
* change wheel
* fix vllm v0.16.1.dev (#1954)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* fix: use qwen3_coder tool parser for Qwen3.5 models
Qwen3.5 uses a different tool call format than Qwen3. Qwen3 uses
hermes-style JSON, but Qwen3.5 uses an XML-like format with
<function=name><parameter=arg> tags. Map all Qwen3.5 variants to
the qwen3_coder parser so tool calls are parsed correctly.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix for tool parser test
---------
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Johannes Hagemann <johannes@primeintellect.ai>
* chore: update pydantic-config for JSON dict CLI support
Update pydantic-config to latest main which adds support for passing
dict[str, Any] fields as JSON via CLI:
--inference.vllm-extra '{"custom_arg": "value"}'
Also switch source from pinned rev to branch = "main".
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore: update pydantic-config lock to include JSON dict fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use space-separated list args for tyro CLI compatibility
tyro parses list[str] fields as space-separated values, not
comma-separated. Update the multi-node SLURM template and integration
test to match. Also fix snake_case --weight_broadcast.host to
kebab-case --weight-broadcast.host.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* revert unnecessary kebab-case change for weight_broadcast.host
Both snake_case and kebab-case are accepted by tyro, so keep the
original snake_case to minimize diff.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* bump vf (bb73f78, feature branch)
* fix: drop stale groups concurrently to avoid inflated cancellation count
The sequential drop_group loop allowed _fill_inflight_requests to add
new tasks to not-yet-dropped stale groups during yields, causing the
cancelled count to exceed max_inflight_rollouts. Using asyncio.gather
ensures all drops snapshot inflight_requests before any of them yield.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* bump vf (45fae8d, main)
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
In multi-turn TITO rollouts, prompt_token_ids are injected after
render_chat_request, bypassing vLLM's built-in context length
validation. When the prompt exceeds max_model_len, get_max_tokens
returns a negative value, causing a BadRequestError ("max_tokens must
be at least 1") that isn't recognized as an overlong prompt by the
verifiers client — aborting the rollout instead of truncating it.
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* first impl for dppo+kl
* fix ratio_type ref
* sum the loss
* set kl_tau=1e-3 by default
* fix
* change to ipo + remove type ignore
* update changelog
* fix
* update names
* add SLURM scheduling support for standalone inference entrypoint
Move inference entrypoint to src/prime_rl/entrypoints/inference.py following
the SFT/RL patterns. Add opt-in [slurm] and [deployment] config sections to
InferenceConfig for submitting inference as SLURM jobs. Supports single-node
and multi-node (independent vLLM replicas per node, no cross-node parallelism).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* use single inference template
* add dry run and remove launcher fields
* correctly resolve union/annotated types
* log msg
* export urls
* switch to 0.0.0.0
* fix vllm
* move
* update changelog
* pass seed
* align with sft/rl entrypoint
* use config dir helper
* update docs and skill for inference SLURM entrypoint
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add back writing config
* add comment
* Revert "add comment"
This reverts commit 1481510decd244174049e1392ca51c1b7b29b294.
* Revert "add back writing config"
This reverts commit a67e8dfe3e57f5906fee0cb6f8fd299c148ecca5.
* remove non-user facing changelog items
* fix ruff
* fix infer entrypoint
* bump pydantic_config
* multi node is 2 nodes by default
* use rev
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
The on-policy distillation docs referenced teacher_gpu_ids which was
removed from RLConfig and replaced by the [deployment] section with
num_teacher_gpus. Users following the docs would get a pydantic
extra_forbidden error.
Closes#1924
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* migrate config system from pydantic-settings to pydantic_config
Replace the custom pydantic-settings wrapper (BaseSettings, parse_argv,
toml_files inheritance) with the external pydantic_config library which
provides tyro-backed CLI parsing, @ syntax for TOML files, and deep merge
of configs + CLI overrides.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to fix-tyro branch and fix benchmark CLI args for tyro
- Switch dependency from refactor-tyro to fix-tyro branch (includes
validators moved upstream)
- Simplify config.py by removing validators now in pydantic_config
- Fix benchmark script to use tyro subcommand syntax for optional
nested configs (compile, ac, ac-offloading)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to include bare flag support for Optional configs
The benchmark script's --model.compile and --model.ac bare flags now
work without changes, thanks to upstream pydantic_config handling.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to main (includes AvoidSubcommands fix)
Fixes dict[str, Any] tyro parser errors and union subcommand issues.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update pydantic-config to include sub-field override fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* disable fused lm head chunking by default
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* reduce benchmark_regression seq_len to 16384
65536 OOMs on A6000 without fused lm head chunking.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* pin fused lm head chunk size in benchmark regression test
The benchmark baselines were generated with chunking enabled, so
the regression test must explicitly enable it regardless of the
default.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* pin fused lm head chunk size in rl_multi_run CI config
This test uses seq_len=65536 which needs chunking to avoid OOM on
A6000 GPUs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
disown detaches the orchestrator from the shell job table, preventing
it from receiving SIGHUP on shell exit. This causes the orchestrator
and its env server subprocesses to survive as orphans after job
cancellation, leading to port conflicts on subsequent runs.
The default Path(".") was passed as-is to sbatch templates, producing
`export PROJECT_DIR=.` which breaks on compute nodes where the cwd
differs from the submission directory. Now resolved at config
construction time.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: handle skipped eval intervals when ckpt_step jumps + fix eval step reporting
When strict_async_level=False, ckpt_step can jump over eval interval
boundaries (e.g. 24->26 skipping 25), permanently missing scheduled evals.
Replace exact modulo check with range check that detects crossed intervals.
Also fix eval metrics being logged at progress.step instead of ckpt_step,
which caused eval results to appear at the wrong step in the metrics API.
* format ruff
* revert step=ckpt_step back to step=progress.step for eval logging
W&B requires monotonically increasing steps. Using ckpt_step (which lags
behind progress.step) causes W&B to silently drop eval metrics since
training already logged at a higher step. The ckpt_step is already
embedded in the metrics as progress/ckpt_step for platform-side lookup.
* fix stale comment about eval subprocess
* add unit tests for eval scheduling range check
* extract eval scheduling logic into compute_eval_ckpt_step function
Move range check logic from inline in orchestrator.py to a proper
function in eval_utils.py so tests import the real implementation.
* use plain functions instead of class in tests
* Enable top_k indices from inference
* Feat; base64
* Feat: more work
* Feat: works now
* Feat: router replay done
* Fix: paths
* Fix: reshape vs view
* Final
* Fix: cp
* fix: config
* Add tests for router replay and fix routed_experts KeyError
- Add unit tests for `_align_routed_experts` (none, empty, no deficit,
deficit padding, excess length)
- Add tests for `interleave_rollout` with routed experts (single-step
alignment, multi-step extension, None passthrough)
- Add tests for `prepare_sample` with routed experts (passthrough,
truncation, None)
- Add GPU test for Qwen3 MoE router replay (forward + backward with
forced expert indices)
- Fix `tokens["routed_experts"]` -> `tokens.get("routed_experts")` in
trajectories.py to avoid KeyError when field is absent
- Fix `_attn_only` tests for afmoe/glm4_moe/qwen3_moe broken by
`routed_experts` kwarg passed to nn.Identity
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* nit
* Fix
* Feat: address comments
* add to minimax and glm moe dsa
* add to minimax and glm moe dsa
* Fix: boundaries
---------
Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
* unify dump_config and dry_run across local and slurm entrypoint
* also use in sft entrypoint
* update changelog
* fix exclude launcher fields
* address bugbot
* do not exclude deployment
* fix sft
* exclude clean output dir to not double clean
* fix rl
Update benchmark baselines to reflect the memory increase from commit
83c21ddac which changed the default fused_lm_head_chunk_size from 2048
to 8192 for improved numerical stability.
Memory changes:
- 1-GPU: 22.69 GiB → 31.81 GiB
- 4-GPU: 14.13 GiB → 23.25 GiB
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
The auto-detection ran at config time via a model_validator, but the model
name may not be final yet (e.g. RLConfig propagates it later), requiring a
hacky reset+re-resolve in auto_setup_model(). Moving the lookup to
server() ensures we always resolve against the final model name.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* add option for token-batch-size
* changelog
* fix cursor bugbot
* changelog
* remove tests
* keep oversampling_factor
* restore oversampling_factor in wiki and math configs
Keep these RL config files aligned with main and retain the oversampling_factor naming convention instead of max_inflight_rollouts.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
* Fix DeviceMesh flattened dim deprecation warning (PT 2.10+)
Store _flatten() return values in a _submeshes dict and access them
via get_mesh() instead of going through world_mesh.__getitem__, which
triggers "Slicing a flattened dim from root mesh will be deprecated
in PT 2.11" warnings and will break in PT 2.11.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Fix get_mesh lazy init ordering
Ensure world_mesh (and _submeshes) are initialized before checking
the submeshes dict, so synthetic names like "hsdp" don't fall through
to the root mesh lookup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: pass explicit step to wandb.log in orchestrator
Without an explicit step, wandb auto-increments its internal counter,
causing subsequent calls with explicit step values to trigger
"step N is less than current step N+1" warnings.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use explicit None check for step=0 in eval_utils
`step or ckpt_step` treats step=0 as falsy, silently substituting
ckpt_step. Use `step if step is not None else ckpt_step` instead.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* simplify: step is always an int, drop Optional and fallback
Both call sites always pass step=progress.step (int), so remove the
None type and the ckpt_step fallback that was broken for step=0.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: commit immediately on wandb.log to avoid delayed dashboard data
With explicit step=, wandb accumulates without committing until it sees
a new step. Adding commit=True flushes data to the dashboard immediately.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Revert "fix: commit immediately on wandb.log to avoid delayed dashboard data"
This reverts commit bf679db5f4069374a74d409c0064cd04d8091c6b.
* fix: add monitor.flush() for immediate wandb commits
commit=True can't be used on individual wandb.log calls when multiple
calls share the same step (it advances the counter, breaking subsequent
calls). Instead, accumulate with the default commit=False, then flush
once at the end of the step.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* consolidate config modules into prime_rl.configs subpackage
Move all scattered config.py files (utils, trainer, rl, sft, orchestrator,
env_server, inference, transport, rl_config) into a single prime_rl.configs
subpackage for better discoverability and organization. Update all imports
across 59 files and refresh skill docs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* merge shared, transport, and utility configs into configs/shared.py
Move SharedLog/Wandb/Checkpoint/Model/WeightBroadcast configs, deployment
configs, transport configs, and common utility configs (ModelConfig,
ClientConfig, LogConfig, WandbConfig, etc.) into a single configs/shared.py.
Remove configs/transport.py and configs/utils.py.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* rename SFTTrainerConfig -> SFTConfig, sft_trainer.py -> sft.py
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* move shared configs into rl configs
* move trainer configs into shared.py
Merge configs/trainer.py into configs/shared.py since these configs
(model, optimizer, scheduler, checkpoint, LoRA, SLURM, etc.) are shared
across both SFT and RL trainers. Rename ModelConfig -> TrainerModelConfig
to avoid collision with the common ModelConfig.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* move some stuff
* update configs
* clean up config naming: move trainer configs, drop component prefixes
- Rename rl_trainer.py -> trainer.py, RLTrainerConfig -> TrainerConfig
- Move shared trainer building blocks (ModelConfig, optimizers, schedulers,
checkpointing, LoRA, etc.) from shared.py into trainer.py
- Rename TrainerModelConfig -> ModelConfig, common ModelConfig -> BaseModelConfig
- Rename TrainerCheckpointConfig -> CheckpointConfig
- Drop Orchestrator/Inference prefixes from config classes
(OrchestratorModelConfig -> ModelConfig, InferenceModelConfig -> ModelConfig, etc.)
since the module name provides context; use aliases in rl.py for disambiguation
- Fix OrchestratorModelConfig inheriting from training ModelConfig instead of BaseModelConfig
- Fix broadcast module imports that had mismatched class names
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update changelog with config consolidation entry
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* Drop Type suffix from config union TypeAliases
Rename all *ConfigType aliases to drop the redundant suffix:
- OptimizerConfigType → OptimizerConfig
- SchedulerConfigType → SchedulerConfig
- DeploymentConfigType → DeploymentConfig
- SFTDeploymentConfigType → SFTDeploymentConfig
- DataConfigType → DataConfig
- TransportConfigType → TransportConfig
- FilterConfigType → FilterConfig
- WeightBroadcastConfigType → WeightBroadcastConfig
- LossConfigType → LossConfig (class renamed to DefaultLossConfig)
- AdvantageConfigType → AdvantageConfig (class renamed to DefaultAdvantageConfig)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Move Field(discriminator) into TypeAliases, simplify field sites
Embed Field(discriminator="type") in each union TypeAlias so field
declarations can use the alias directly without wrapping in
Annotated[..., Field(discriminator="type")].
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
LossConfigType and AdvantageConfigType used callable discriminators with
Tag annotations to provide a default fallback when the "type" key was
missing. This is unnecessary since _default_discriminator_types on
BaseSettings already injects the type tag from defaults. Switch to the
simpler Field(discriminator="type") pattern used by all other unions.
LossConfig and AdvantageConfig are changed from BaseConfig to BaseModel
because BaseConfig's field_validator("*", mode="before") conflicts with
pydantic's string-based discriminator. Neither model has Optional fields
that benefit from the empty_str_to_none validator.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: per-component seq_len overrides shared seq_len
Remove `nested_model_default_partial_update=True` from BaseSettings so that
`model_fields_set` correctly tracks which nested fields were explicitly set
in the config. This lets `auto_setup_seq_len` propagate the shared `seq_len`
only to components that didn't receive an explicit value.
- Bump pydantic-settings >=2.12.0
- Replace the `normalize_deployment` workaround with a generic
`_default_discriminator_types` before-validator that injects the `type`
tag from a field's default instance when missing
- Guard `auto_setup_seq_len` with `model_fields_set` checks
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add hendrycks sanity check exp (#1873)
* Flesh out hendrycks sanity example README
Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update examples
* Add hendrycks sanity to training examples list in README
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update readme
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* add output_dir safety check to prevent accidental overwrites (#1872)
* Add output_dir safety check to prevent accidental overwrites
Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Move output_dir validation to entrypoints (before SLURM submission)
Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Remove old clean flag from RLConfig local path
The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Move clean_output_dir to RLConfig and use shared ckpt for resume check
clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update err message
* Fix stray paren in error message, ensure dirs exist after clean, add changelog
- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* only raise if checkpoints exists
* Make RLConfig.output_dir non-optional and fix docs to match actual behavior
output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add changelog entry for output_dir type change and SLURM validation removal
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add env var to never clean output dir safeguard
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* add some more tests
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* Add output_dir safety check to prevent accidental overwrites
Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Move output_dir validation to entrypoints (before SLURM submission)
Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Remove old clean flag from RLConfig local path
The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Move clean_output_dir to RLConfig and use shared ckpt for resume check
clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update err message
* Fix stray paren in error message, ensure dirs exist after clean, add changelog
- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* only raise if checkpoints exists
* Make RLConfig.output_dir non-optional and fix docs to match actual behavior
output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add changelog entry for output_dir type change and SLURM validation removal
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add env var to never clean output dir safeguard
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* Flesh out hendrycks sanity example README
Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update examples
* Add hendrycks sanity to training examples list in README
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update readme
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* Move tool_call_parser log from validator to server startup
Validators shouldn't have logging side effects - they run during
config construction which causes spurious log messages on import.
Also use default_factory for ModelConfig to avoid eager instantiation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Fix tool_call_parser not resolved when model name is propagated
auto_setup_model() changes inference.model.name after the ModelConfig
validator has already run, leaving tool_call_parser stale from the
default model. Re-resolve after propagating the name, but only when
the current parser was auto-detected (preserves explicit overrides).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add GLM-5 (glm_moe_dsa) custom model with MLA attention
Implement GLM-5 as a custom model following the 4-file convention:
- configuration, modeling, converting, and __init__
- MLA (Multi-head Latent Attention) with LoRA-compressed Q/KV
- Interleaved RoPE support via apply_rotary_pos_emb_interleave()
- Dense attention only (sparse Lightning Indexer is future work)
- Reuses existing MoE, MLP, RMSNorm, and RotaryEmbedding layers
- Weight conversion roundtrip (HF <-> PrimeRL) for MoE experts
- Indexer weights declared but unused for state dict compatibility
- mini_moe.py preset for test model creation
- Unit tests (attn-only, mlp-only, full model + roundtrip)
* feat: add sparse MLA attention with tilelang kernels for GLM-5
Add Dynamic Sparse Attention (DSA) to the glm_moe_dsa model using
vendored tilelang kernels for training fwd+bwd. Includes a bf16
PyTorch indexer (varlen-aware via cu_seqlens) and the absorption
trick to operate in compressed KV latent space (d_qk=576, d_v=512).
* Progress we run against vllm
* Feat: works but slow
* works now i think
* Cleanup
* deps
* Minor changes
* fix minimoe
* To be verified
* Feat: glm5
* Fix: scaling
* Fix more scaling
* FP8 quant
* Scale
* Cleanup: remove banner comments, verbose docstrings, dead code, and broken tests
- Remove license banner, section separators, and shape annotation comments
- Remove unused _weight_scale variable and commented-out code in fp8_indexer
- Trim verbose vendor attribution comments
- Consolidate duplicate warnings in GlmMoeDsaForCausalLM
- Remove broken test file (tests passed wrong kwargs to attention forward)
- Remove sloppy init comment in models/__init__.py
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* final
* nit
* Fix GlmMoeDsaConfig pad_token_id forwarding
Co-authored-by: Matej Sirovatka <S1ro1@users.noreply.github.com>
---------
Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Matej Sirovatka <S1ro1@users.noreply.github.com>
* make tito client opt-in
* Add CHANGELOG entry for orchestrator.use_token_client config field
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* add SFT SLURM entrypoint (`sft_slurm`)
Adds a `sft_slurm` CLI that mirrors `rl_slurm` but for SFT training.
The config extends `SFTTrainerConfig` directly (no `[trainer]` nesting)
with slurm-specific fields (num_nodes, gpus_per_node, etc.). Includes a
simplified Jinja2 SLURM template with no inference/orchestrator nodes.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add sft example
* add SFT MoE SLURM example and slim down SFT docs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add sft slur config to tests
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat(inference): auto-detect tool_call_parser from model name
Previously tool_call_parser defaulted to "hermes" regardless of model,
causing silent failures when the wrong parser was used. Now the parser
is automatically inferred from the model name via a hardcoded mapping.
Users can still override explicitly.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: simplify MODEL_TOOL_CALL_PARSER to dict, address PR review
- Use get_logger instead of std logging
- Replace ordered list-of-tuples with a simple dict (no aliases/ordering concerns)
- Don't raise on unknown model, leave tool_call_parser as None
- Scope supported models to GLM, MiniMax, INTELLECT-3, Qwen3
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: use exact model names in MODEL_TOOL_CALL_PARSER dict
Replace substring pattern matching with exact 1:1 model name lookup.
All supported models are listed explicitly by their HuggingFace ID.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* remove extra inference stuff
* feat: default enable_auto_tool_choice to True
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: auto-enable enable_auto_tool_choice when tool_call_parser is set
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: remove hermes default, leave tool_call_parser as None for unknown models
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
vLLM's Hermes2ProToolParser.__init__ calls tokenizer.encode() and
tokenizer.decode() on every instantiation. Under concurrent request
load, multiple threads call these methods simultaneously on the same
shared HuggingFace tokenizer instance. The tokenizer's Rust backend
(via PyO3) uses RefCell-style borrow tracking, and concurrent mutable
borrows cause it to panic with `RuntimeError: Already borrowed`.
This was causing ~1% of /v1/chat/completions requests to fail with
500 Internal Server Error when tool calling (hermes parser) is enabled.
Fix: monkey-patch the parser __init__ to run the first tokenizer
encode/decode under a threading lock, cache the results, and reuse
them for all subsequent instantiations without touching the tokenizer.
Co-authored-by: root <root@industrious-conscious-koala.datacrunch.io>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Add option to freeze MoE router during training
Adds `freeze_moe_router` config option to prevent routing collapse and
keep load balancing stable during RL and SFT fine-tuning. Supports both
custom MoE (router) and HuggingFace (gate) implementations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Remove freeze_moe_router unit tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: add STABLE marker files to orchestrator checkpoints
Previously, orchestrator checkpoints did not create STABLE marker files,
causing the trainer's resume logic to fail when resuming with resume_step=-1.
The trainer would not find any STABLE files and incorrectly default to step 0,
even when orchestrator checkpoints existed at later steps.
This fix adds mark_stable() method to the orchestrator CheckpointManager
and calls it after successfully saving checkpoints, matching the behavior
of the trainer checkpoint manager.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* refactor: use mark_stable method in WeightCheckpointManager for consistency
Previously, WeightCheckpointManager directly touched the STABLE file
instead of using a dedicated method. This adds a mark_stable() method
to match the pattern used in CheckpointManager and OrchestratorCheckpointManager.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* make public methods
* indent
* consistency
* do not write stable from orch + search for any run ckpt dirs
* require stable for multi-tenant
---------
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix MiniMax M2 LoRA compatibility in vLLM inference
vLLM's MiniMax M2 model has two issues preventing MoE LoRA from working:
1. The MoE gate (router) uses float32 params and casts inputs to float32,
but vLLM's LoRA Triton kernel only supports float16/bfloat16. Fixed by
recreating the gate in model dtype and removing the float32 cast.
2. PrimeRL saves adapter keys as mlp.experts.{j}.gate_proj/down_proj/up_proj
but vLLM expects block_sparse_moe.experts.{j}.w1/w2/w3. Fixed by adding
hf_to_vllm_mapper on the model to remap adapter keys on load.
Also adds debug configs for MiniMax M2 and Qwen3 MoE LoRA RL training.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* remove debug LoRA config files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* improve comments explaining MiniMax M2 LoRA patches
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* dont reload weights by default
* Remove reload_weights_on_start config and dead code path
The reload_weights mechanism was a no-op in practice: vLLM servers
start with base weights already loaded, and LoRA runs already
skipped the reload. Remove the config field, server endpoint,
client function, and orchestrator branching.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Remove helo/orchestrator.toml from branch
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add changelog entry for reload_weights_on_start removal
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* add exp
* bump vf
* setup timeouts and logging interception
* bump and use built-in wait for server health
* no prefix
* bump and show info logs
* add name and intercept without prefix
* slower health checks
* bump to lower health timeout
* back to 8k seq len
* bump
* update log interception and new config
* get free port pair
* bump to have prime-rl env server logs
* mini
* bump
* do not intercept on env server
* bump vf
* copy lock
* update lock
* remove configs
* fix vlm in transformers 5
* improve
* fix bug
* rename
* fix: auto-install transformers v5 compat hook for vLLM workers
* refactor: use vLLM plugin system instead of .pth hook for transformers v5 compat (#1810)
Replace the runtime site-packages mutation (.pth file + generated module)
with a vllm.general_plugins entry-point. vLLM loads general plugins in
every process it spawns (workers, engine core, API servers), so the patch
survives multiprocessing spawn without writing to site-packages.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* minor fixes
* add nightly for multimodal
* improve exact config
---------
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(slurm): move NCCL and runtime configs from template to config
- Add port/timeout fields to SharedWeightBroadcastConfig
- Propagate port/timeout in auto_setup_weight_broadcast
- Add auto_setup_slurm_nccl validator that sets:
- orchestrator.num_train_workers from SLURM topology
- trainer.weight_broadcast.host to 0.0.0.0
- trainer.weight_broadcast.inference_world_size from SLURM topology
- Add validate_inference_config to catch missing inference config early
- Remove hardcoded env vars and CLI args from SLURM template
Only --weight_broadcast.host $MASTER_ADDR and --client.base-url remain
as CLI args (runtime values from SLURM).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* feat(slurm): add rl_slurm entrypoint and update docs
- Add rl_slurm script entrypoint to pyproject.toml
- Update docs to use `uv run rl_slurm` instead of `uv run python -m prime_rl.slurm.rl`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* refactor config
* Add SLURM entrypoint with Jinja2 template and tmux launcher
Adds a new `rl_slurm` entrypoint that resolves the full RL config,
dumps sub-configs as TOML, renders a SLURM batch script from a Jinja2
template, and submits it via sbatch (with --dry-run option). Includes
a tmux launcher for monitoring trainer/orchestrator/inference logs and
documentation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix ruff formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(slurm): sync orchestrator output dir with cleanup
Co-authored-by: samsja <samsja@users.noreply.github.com>
* test(configs): include slurm config parser in config loading test
Co-authored-by: samsja <samsja@users.noreply.github.com>
* add auto dir
* fix(slurm): move auto_setup_output_dir to BaseRLConfig so SLURM entrypoint propagates output_dir
RLSLURMConfig extends BaseRLConfig, not RLConfig, so the validator that
propagates output_dir to trainer and orchestrator was never running.
This caused the Jinja template cleanup to target wrong paths and the
trainer to pick up stale rollouts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add args
* feat(slurm): make config more flexible and self-contained
- Replace base_dir/env_file/venv with single project_dir
- Add gpus_per_node (default 8) to remove hardcoded GPU counts
- Add nodes_per_fsdp_group to auto-compute dp_replicate
- Use -m module syntax for torchrun instead of file path
- Derive .env and .venv paths from project_dir
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix many stuff
* add math
* addexamples
* add moe example
* docs(slurm): update to Hendrycks Math examples with MoE config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: add required output_dir to slurm example configs
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: samsja <samsja@users.noreply.github.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
* fix: use per-expert format in MoE weight conversion for vLLM compatibility
convert_tt_layer_to_hf was producing transformers v5 fused format
(experts.gate_up_proj, experts.down_proj) but vLLM expects per-expert
format (experts.{j}.gate_proj.weight, etc). This caused KeyError during
weight updates in the inference server. Also adds MoE RL integration
tests for both hf and custom impl.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use underscores in MoE TOML config keys
Hyphens only work as CLI args, TOML config needs underscores.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* test: remove HF round-trip tests for MoE models
The MoE weight conversion now outputs per-expert format for vLLM
compatibility, which is incompatible with HF transformers 5.0+ fused
format. Remove the round-trip tests that loaded converted weights
back into HF models since vLLM is the target format.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Implement full pipeline for MiniMax M2.1 (230B MoE, 10B activated/token):
modeling code, HF<->PrimeRL weight conversion, registration, and mini-model
verification.
Key additions:
- Per-layer QK norm support in shared attention (qk_norm_type="per_layer")
- MiniMax M2.1 model module with config, conversion, and modeling
- Mini model preset for testing at small scale
- Refactored mini_moe.py to support remote-code HF models
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* configure default logger instead of raise
* fix: cleanup old logger resources when calling setup_logger
Calling setup_logger multiple times now properly cleans up the old
logger instance by calling logger.remove() before creating a new one.
This prevents resource leaks:
- Background threads from enqueue=True handlers are stopped
- JsonFileSink file handles are properly released
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: add cleanup to reset_logger to prevent resource leaks
Calling reset_logger now properly cleans up the logger instance by
calling logger.remove() before setting _LOGGER to None. This ensures
that any active handlers (file sinks, enqueued handlers, background
threads) are properly released, matching the cleanup pattern in
setup_logger.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
The downgrade from 2.8.3 to 2.6.3 happened during the vllm/transformers
bump (commit 8f2e6bbc) when PyTorch was upgraded from 2.9 to 2.10.
Flash-attn 2.6.3 does not support Blackwell GPUs (compute capability 12.0),
causing "FlashAttention only supports Ampere GPUs or newer" errors.
This upgrades back to 2.8.3 which may have better compatibility with newer
GPU architectures. The 2.8.3 wheel for torch 2.10 + cu128 is available in
the same v0.7.16 release.
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix(deps): bump verifiers to e629347 (ZMQ env server deadlock fix)
The ZMQ env server used asyncio.wait_for around recv_multipart which
has a race condition in CPython's Task cancellation that silently
discards consumed messages. The verifiers fix replaces it with a
zmq.asyncio.Poller.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* use spawn method
* bump to commit on main
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
@logger.catch used loguru's default global logger, not the custom logger
created by setup_logger(). This meant fatal exceptions bypassed the JSON
formatter entirely. Move exception logging into clean_exit using get_logger(),
with a safe fallback to loguru's default if the logger isn't set up yet.
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* add glm flash
* update vllm to nighjlty
* fix moe
* fix glm
* fix ruff
* fix: resolve unit test failures
- Add return_dict=False to apply_chat_template calls in SFT data processing
(transformers now returns BatchEncoding by default instead of list[int])
- Handle missing pad_token_id in MoE model config for test_perf_counter
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: update models for transformers 5.0.0 compatibility
- Remove deprecated rope_config_validation calls from configs
- Add pad_token_id attribute to MoE configs
- Add compute_default_rope_parameters to RotaryEmbedding classes
- Add attribute_map for num_local_experts in Glm4MoeConfig
- Override get_correct_experts_implementation in PreTrainedModelPrimeRL
- Update state dict conversion to handle new fused gate_up_proj format
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: address Cursor bot review comments
- Fix temperature parameter type in Glm4MoeLiteForCausalLM (High):
Changed from Optional[float] = 1.0 to Optional[torch.Tensor] = None
to match other models and avoid crash with FusedOutputLinear
- Fix SDPA/flex_attn support flags (Medium):
Set _supports_sdpa and _supports_flex_attn to False since the model
only implements flash attention
- Update GLM4MoeLite conversion for transformers 5.0 fused format (High):
Added support for new gate_up_proj fused format in convert_hf_layer_to_tt
and convert_tt_layer_to_hf to match glm4_moe and qwen3_moe
- Fix return_dict keyword argument order in sft/data.py (Low):
Use dict merge pattern to avoid duplicate keyword argument crash
when chat_template_kwargs contains return_dict
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: update is_hf_state_dict to detect transformers 5.0 fused format
The is_hf_state_dict methods now check for both:
- Old per-expert format: mlp.experts.1.up_proj
- New fused format (transformers 5.0+): mlp.experts.gate_up_proj
Updated in: glm4_moe, glm4_moe_lite, qwen3_moe
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix smth
* fix glm
* remove glm flash
* fix: format serving_chat_with_tokens.py
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: update vllm 0.15 API compatibility
- Remove get_prompt_components import, use _extract_prompt_text instead
- Rename update_weights to update_weights_from_path to avoid conflict with vllm's built-in method
* feat: add revert_weight_conversion for transformers models
For non-PrimeRL transformers models (e.g., Glm4MoeLiteForCausalLM),
the internal fused format (experts.gate_up_proj) needs to be reverted
to the original HF hub format (experts.{j}.gate_proj.weight) for vLLM
compatibility.
Uses transformers' built-in revert_weight_conversion which:
- Unfuses MoE expert weights for models with conversion mappings
- No-ops for dense models (returns state_dict unchanged)
Applied to:
- ckpt.py: checkpoint saving
- nccl.py: NCCL weight broadcast
- filesystem.py: filesystem weight broadcast
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: CI vLLM CUDA bug and update baselines for transformers 5.0
- Add VLLM_WORKER_MULTIPROC_METHOD=spawn to fix CUDA driver init bug
- Update benchmark baselines for transformers 5.0 memory usage:
- 1-GPU: 19.5 GiB -> 22.7 GiB
- 4-GPU: 12.4 GiB -> 14.1 GiB
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* docs: add clarifying comments for vLLM 0.15 API changes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Revert "docs: add clarifying comments for vLLM 0.15 API changes"
This reverts commit 84c62da44dba60dc5c712a21bdf903908b83de0b.
* bump t5 and vllm
* bump fa
* chore: sync uv.lock after rebase
* feat: update transformers to support GLM-5
Update transformers to main branch (commit 609e3d5) which includes
GlmMoeDsa (GLM-5) support. Add override-dependency to work around
vllm's transformers<5 constraint.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: restore weight tying after to_empty() for HF models
The to_empty() call breaks weight tying by allocating separate tensors
for lm_head.weight and embed_tokens.weight. This adds tie_weights() calls
after to_empty() to restore proper weight sharing.
Also reverts benchmark baselines to original values since the fix
eliminates the memory regression.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* chore: update baselines for transformers 5.0 memory usage
Transformers 5.0 uses ~16% more peak memory. The tie_weights() fix
doesn't help because FSDP already preserves weight tying through
to_empty(). Accept the new memory baseline.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* chore: upgrade to vLLM 0.16.0 official release
Use the official vLLM 0.16.0 release wheel from GitHub releases
instead of the nightly index. Key features:
- PyTorch 2.10 support
- Transformers v5 compatibility
- GLM-5 model support
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: add attribute_map for MoE configs transformers 5.0 compatibility
Add attribute_map = {"num_local_experts": "num_experts"} to Qwen3MoeConfig
and AfmoeConfig to match the pattern used in Glm4MoeConfig for
transformers 5.0 compatibility.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Add `--dump-config` flag to rl command
Adds a `dump_config: Path | None` parameter to `RLConfig`. When set,
resolved subconfigs are written to the given directory and the process
exits without starting any services.
Also refactors config serialization into a shared `write_subconfigs`
function used by both the dump path and the normal run path.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add dump_config entry to CHANGELOG
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add warning messages to --dump-config mode
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Use bisect.insort to maintain sorted order when adding new checkpoint steps.
Previously, appending to the list could break sort order when saving a checkpoint
with a step number lower than existing ones, causing AssertionError in maybe_clean().
* Fix checkpoint cleanup crashing trainer on OSError
When external processes (e.g. checkpoint uploader) hold open file handles
on checkpoint directories, shutil.rmtree can fail with "Directory not
empty". Skip the deletion and log a warning instead of crashing — the
next maybe_clean call will retry.
* Retain failed-to-delete steps in ckpt_steps for retry
Steps where rmtree fails were being removed from ckpt_steps, making
them orphaned and never retried. Track which deletions succeed and
only remove those from the list.
* Restore debug logging before checkpoint deletion
* Revert ckpt_steps tracking, just skip failed deletions
The steps_deleted tracking caused state divergence across ranks since
only master populates it. Keep the original ckpt_steps pruning logic
and accept potential disk leak over complexity.
* Fix IndexError in load_state_dict sort for non-standard safetensor filenames
The sort assumed filenames follow the `model-NNNNN-of-NNNNN.safetensors`
convention, crashing on files like `model.safetensors`. The sort is
unnecessary since the function merges all shards into a flat dict where
key order doesn't matter.
* Only load full snapshot on master rank for format conversion
Previously all ranks loaded the full model weights into CPU memory just
to check key names for format detection. Now all ranks read only the
safetensor key names (no tensor data), and only master loads the full
state dict when conversion is actually needed.
* add skills dir & first skill for vllm
* remove unimplemented stuff
* make symlink relative
* make separate config skill
* update AGENTS.md & skills
* make more explicit
* start env servers for env group
* bump
* working reverse-text
* correctly set log levels
* use client configs everywhere + make val work
* cycle through clients via inference pool
* update model name
* deprecate env worker
* implement evals
* deprecate evals+synthesize
* deprecate serialization
* use all clients for evals
* simplify config
* fix types and use inference pool for opd
* bring back logging intercept
* setup env client/server in prime-rl
* externalize running env server
* style
* bring back rate limiter on scheduler
* revert vf branch
* back to custom branch
* do not double asyncio
* bring back eval
* fix cpu tests
* bump vf
* add math group config
* remove stop server call
* add logs
* remove last mentions of vf.State
* deprecate some configs
* more
* remove eval + cpu integration tests
* remove evals + synthesize configs
* bump vf
* fix branch with vlm cache
* do not reference rollout status
* use correct model name
* stop teacher infer pool if setup
* update changelog
* deprecate server discovery (unused)
* fix env id stripping
* use updated model name for evals
* strip env version on env server
* remove server discovery tests
* bump vf
* do not fail if env server not yet up
* add elastic sanity check
* update docs
* use extra env kwargs consistently across orch and env server
* update math group config
* update cfg
* use dynamic model name in final evals
* add extra_env_kwargs to changelog
* resolve vf merge conflicts
* assert lora name not None
* fix unit tests
* fix types
* add hendrycks math sanity check
* bump vf
* do not double repeat eval inputs
* do not duplicate eval inputs
* lower avg@
* Initialize logger in env-server before install_env (#1743)
install_env() calls get_logger() which requires the logger to be set up first.
This was missing in env-server but present in orchestrator.
* disable vf logging on orch
* Fix elastic autoscaling: use base model for health checks (#1745)
The health check was using `model_name` which gets updated to the LoRA
adapter name after training starts. New inference servers only have the
base model, so they would fail health checks and never get added to the
pool.
Store the original model name as `base_model_name` and use it for health
checks, allowing new servers to be discovered and have the LoRA adapter
loaded on them.
---------
Co-authored-by: JannikSt <JannikSt@users.noreply.github.com>
Co-authored-by: William Brown <williambrown97@gmail.com>
* validate client port matches inference server
* error on existing GPU processes before training
* respect resume_step config in trainer
* format rl.py
* fix defenseslop
* move port validation from config to runtime
* docs: add release notes guidelines to AGENTS.md
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: add style reference step to release guidelines
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* update loss interface
* refactor: rename grpo_loss to prime_rl_loss and consolidate loss interface
- Rename grpo_loss to prime_rl_loss (uses LossConfig directly)
- Move LossInputs, LossOutputs, LossFn from loss_interface.py into loss.py
- Remove loss_interface.py
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* feat: add bring-your-own-loss support for custom loss functions
- Add CustomLossConfig with path and kwargs fields
- Add LossConfigType union (LossConfig | CustomLossConfig)
- Update setup_loss_fn to handle custom loss imports
- Add _import_object helper for dynamic imports
- Add test for custom loss configuration
- Add docs/bring-your-own-loss.md documentation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* feat: add bring-your-own advantage function support
- Add AdvantageInputs/AdvantageOutputs dataclasses
- Add CustomAdvantageConfig with path and kwargs
- Add setup_advantage_fn for custom advantage imports
- Refactor compute_advantages to use the new interface
- Add tests for custom advantage configuration
- Rename docs to bring-your-own-algorithms.md with both loss and advantage sections
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* refactor: rename path to byo_function in custom configs
More descriptive name that ties into the "bring your own" concept.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* refactor: address PR review feedback
- Extract import_object to shared utils (deduplicate from loss.py and advantage.py)
- Add pydantic discriminator types for LossConfigType and AdvantageConfigType
- Rename byo_function to import_path (standard Python terminology)
- Rename grpo_advantage to default_advantage
- Fix train.py AttributeError when using CustomLossConfig
- Fix docs: per-example terminology, loss/advantage descriptions, config examples
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: update prime_rl_loss description
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: handle custom loss metrics in training loop and restore extra=forbid on AdvantageConfig
- Guard mismatch_kl access in micro-step and step logging (custom loss may not emit it)
- Change AdvantageConfig base from BaseModel to BaseConfig to restore extra="forbid" validation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: rename prime_rl_loss to default_loss_fn
Consistent with default_advantage naming.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: simplify loss setup logging
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: rename default_advantage to default_advantage_fn
Consistent with default_loss_fn naming.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Platform sends versioned env IDs (e.g. d42me/meow@0.1.5) for installation.
The version must be stripped before passing to vf.load_environment() since
importlib.import_module() cannot handle @ in module names.
Add peak BF16 FLOPS specifications for AMD Instinct accelerators:
- MI300X: 1307.4 TFLOPS
- MI325X: 1307.4 TFLOPS (same compute dies as MI300X, more HBM3e)
This enables accurate MFU reporting when training on AMD GPUs instead of
falling back to A100 baseline which produces misleading >100% MFU values.
Co-authored-by: Daniel Zautner <daniel.zautner@silo.ai>
* [feature] add optimizer state CPU offload
Add CPUOffloadOptimizer that keeps optimizer states (exp_avg, exp_avg_sq)
on CPU, moving them to GPU only during optimizer.step(). Unlike FSDP's
CPUOffload, this keeps weights on GPU to avoid H2D all-gather overhead.
- Add optim_cpu_offload config option to ModelConfig
- Integrate into SFT trainer
- Works with DTensor/FSDP2 by operating on _local_tensor
Trade-off: saves ~2GB GPU memory for 0.6B model but ~10x slower due to
per-tensor transfer overhead. Best for memory-constrained scenarios.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Refactor: move CPU offload logic into setup_optimizer and setup_scheduler
- setup_optimizer now handles wrapping with CPUOffloadOptimizer internally
- setup_scheduler now handles extracting base optimizer from CPUOffloadOptimizer
- Simplified SFT train.py to just pass cpu_offload flag
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Shorten docstring
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add validation to prevent both cpu offload options enabled
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Move DTensor import to top of file
Co-authored-by: sami <sami@primeintellect.ai>
* docs: add changelog for optim_cpu_offload
Co-authored-by: sami <sami@primeintellect.ai>
* Fix CPU offload pinning race
Co-authored-by: sami <sami@primeintellect.ai>
* fix: avoid mutating DTensor state
Co-authored-by: sami <sami@primeintellect.ai>
* Fix checkpointing with CPUOffloadOptimizer
The checkpoint system uses PyTorch's get_state_dict/set_state_dict which
expect actual Optimizer objects. CPUOffloadOptimizer is a wrapper, so we
need to extract the base optimizer for checkpointing and re-initialize
the wrapper state after loading.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add docstring clarifying _move_states behavior
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix devise
* fix: pass optim_cpu_offload to RL optimizer setup
- Add cpu_offload parameter to setup_optimizer call in RL training
- Add validation to prevent optim_cpu_offload with max_concurrent_runs > 1
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
* bump vf
* use ckpt consistently
* fix imports
* make env worker run
* fix utils used in eval and synthesize endpoint
* restore old semaphore behavior
* remove unnessary semaphore setup
* set max_concurrent_groups
* fix to make concurrency global
* fix key error
* access oai_tools safely
* use vf retries
* use new types
* consistent tool handling
* misc
* Add JSON structured logging option for log aggregation
* Add CHANGELOG entry and fix default value pattern
* Pass JSON logging config to env workers
* Wire JSON logging to all entrypoints (eval, synthesize, sft)
* Pass JSON logging to eval subprocesses
* Rename json to json_logging to avoid Pydantic shadowing warning
* Use flat JSON format for log aggregation instead of loguru serialize
* Fix exception handling in JSON logger sinks
* Remove [verifiers] prefix from intercepted logs
* Fix outdated docstring for intercept_verifiers_logging
* Refactor JSON logging: dedupe, non-blocking sinks, fix CHANGELOG
* Remove unused close method from _JsonFileSink
* Include worker tag in JSON log output
* Create parent directories for JSON file sink
* Restore [verifiers] prefix for intercepted logs
* Rename json parameter to json_logging in setup_logger for consistency
* Replace tqdm with ProgressTracker for JSON logging compatibility
When JSON logging is enabled, progress bars are replaced with periodic
log messages (every 10%) to avoid garbled output. When disabled, tqdm
works as before.
* Fix file handle leak and emit structured progress events
- Add atexit cleanup for _JsonFileSink file handle
- Progress events now emit structured JSON with type/current/total/percent fields
- Remove unused is_json_logging function
- Add proper type hints for postfix dict
* Add step context to progress events and fix 0% jump
- Add optional step parameter to ProgressTracker
- Include step in JSON output and tqdm desc
- Don't emit 0% on init (only on actual progress)
* Keep tqdm output unchanged, only add step to JSON mode
* Remove enqueue=True from non-JSON handlers to fix tqdm
enqueue=True causes loguru to use background thread which
interferes with tqdm's terminal output. Only needed for JSON mode.
* Remove unreachable else branch in _emit_progress
* Fix typo in get_logger docstring
* Add lock to prevent interleaved JSON output
Both _json_sink (loguru background thread) and _emit_progress write
to stdout - without synchronization they can corrupt JSON lines.
* Route progress through loguru for single output path
Instead of writing directly to stdout (which needed a lock),
progress events now go through loguru with _progress marker.
_build_log_entry detects and formats them specially.
* Add level field to progress events for consistency
* weee test
* add it to gha
* 4gpu test
* add row for 4 x a6000 to benchamrks
* change the baseline a bit
* im not sure if we actually regressed :(
* up tolerance because massed compute suk
* [fix] add Gemma3 support: final_logit_softcapping and meta device buffer handling
* [fix] handle softcap=0 as disabled
* [fix] use comment not docstring
* zombie guard on checkpoint
* make the cleanup code safer
* make resume from latest stable so we dont try to resume from orchestrator only ckts
* simpler logic
* the old checkpoint step discovery is needed by single packer
* we need to relook for stable step in load_run otherwise packer might ahveincremented the step and we are introuble
* dont set step after ckpt load because we might reset packer progress
Add `check_exists` parameter to `get_weight_dir()` to handle NCCL weight
broadcast mode where weights are transmitted via NCCL rather than stored
on disk.
* Add missing [ckpt] section to reverse_text rl.toml
The README.md documents that `outputs/weights/step_20` will be created
after RL training, but the rl.toml was missing the [ckpt] section.
Without this section, no weight checkpoints are saved because
`setup_ckpt_managers()` returns (None, None) when ckpt_config is None.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add missing [ckpt] section to other example configs
Also adds [ckpt] section to:
- examples/wiki_search/rl.toml
- examples/reverse_text/sft/train.toml
- examples/reverse_text/rl/train.toml
These training configs were missing checkpoint configuration,
which would result in no weights being saved after training.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* bump ruff version & move to ruff-check
* add ruff format to CI
* run ruff format
* fix ruff
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
* fix cpu offloading
* fix offlaod for moe
Fix buffer init in random init path
Co-authored-by: sami <sami@primeintellect.ai>
Fix buffer device move when meta load unavailable
Co-authored-by: sami <sami@primeintellect.ai>
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
* use discovery in eval
* make eval use lora name unless none of the servers have it
* address comments to encapsulate and not be too defensive
* type hinting
* pass model name directly instead of doing model config
* better logging
* we dont need complicated discovery because only ckpt 0 is base in lora
* wait indefinitely similar to the env workers
* move the wait into discovery
* Add elastic inference pool with DNS-based service discovery
- Add ElasticInferencePool for tracking pod readiness and adapter sync
- Main process discovers pods via K8s headless service DNS
- Only exposes pods with correct LoRA adapter as "ready" to workers
- Workers receive ready URLs via callback to prevent model-not-found errors
- Fully backwards compatible with static base_url configuration
* Fix tests: use asyncio.run() pattern instead of pytest-asyncio
* Fix: pass ready URLs to workers in elastic mode
* Generalize elastic inference pool to support any DNS-based discovery
- Rename headless_service to hostname (works with any DNS with multiple A records)
- Rename pod terminology to server throughout (not K8s-specific)
- Update docstrings to mention Kubernetes as one option among many
* Add changelog entry for elastic inference pool
* Fix min_pods -> min_servers parameter name
* Validate elastic inference requires LoRA training
* Add health and base model check before marking server as discovered
* Remove servers that fail health checks during sync
* Change elastic pool logs from info to debug
* fix: queue rollout requests when no inference servers available
- Clear clients when URLs become empty (instead of keeping stale clients)
- Queue incoming requests while waiting for servers to become ready
- Process queued requests once servers are available again
- Add NoServersAvailableError safety check in process_request
* fix: avoid false adapter match on default step=0
Only match by step when step > 0 to prevent false matches when
both loaded and desired adapters have default step=0 but different paths.
* test: fix elastic tests for health check changes
- Mock _check_server_health in _add_server and sync tests
- Add test for step=0 not causing false adapter matches
- Add test for health check failure in _add_server
- Add tests for _check_server_health method
* feat: support elastic inference for non-LoRA training
Elastic pool now works for base model inference too. Servers are
ready once they pass health check and have the base model loaded.
* fix: address cursor bot concerns
- Compare URLs as sets to avoid spurious callbacks from order changes
- Close old inference clients before creating new ones to prevent connection leaks
* refactor: use Literal type for server status
* docs: simplify elastic pool descriptions
* test: convert to pytest function style
* fix: address copilot review feedback
- Move time import to module level
- Use empty list instead of fallback to base_url in elastic mode
- Add comments to except:pass blocks
* docs: clarify sync_interval unit is seconds
* refactor: rename sync_interval to sync_interval_s for clarity
* rename update_weights to sync_adapter in elastic pool
* rename sync_adapter back to update_weights, remove test_elastic.py
* refactor: workers do own DNS discovery, remove callback pattern
- Workers discover servers via DNS and check /v1/models directly
- Majority vote: use all healthy servers if no adapter, only adapter servers otherwise
- Remove callback/URL push machinery from scheduler and elastic pool
- Simplify elastic.py to only handle admin operations (adapter sync)
* fix: pass model_name per-request for LoRA compatibility
* Simplify orchestrator: remove worker_client_config branching
* Restore comments in extract_result
* Encapsulate elastic mode behind InferencePool abstraction
* Move discovery functions to elastic.py to reduce duplication
* Restore comments in env_worker.py
* Fix type annotations - remove unnecessary string quotes
* Fix code review issues: rename sync_weights to public, add debug logging
* Add unit tests for elastic inference pool
* refactor: consolidate elastic config handling in WorkerServerDiscovery
- Remove redundant elastic params from env_worker (hostname, port, sync_interval)
- Extract elastic config from ClientConfig inside workers
- Add WorkerServerDiscovery class to encapsulate worker-side discovery
- Simplify worker loop logic, remove duplicate get_clients calls
- Convert tests to function-based format
🤖 Generated with [Claude Code](https://claude.com/claude-code)
* refactor: move client discovery logic to WorkerServerDiscovery class
* restore inline comment
* remove redundant update_model_name - model name is fixed at init
* restore update_model_name method
* move update_model_name to original location
* fix test: patch setup_clients function instead of non-existent method
* fix: dedupe servers, guard elastic requires LoRA, don't close clients mid-request
* fix: workers start with base model name, switch to LoRA after loading
* add logging for model switch and tests for update_model_name
* fix test: mock queue put to avoid multiprocessing timing issues
* make inference_pool required parameter in Scheduler
* cache inference clients in ElasticInferencePool to avoid recreating on each access
* update worker discovery model name when request model changes (LoRA switch)
* fix: multi-adapter detection, refactor InferencePool to Protocol
- fix _get_loaded_adapter to filter by adapter name when multiple adapters loaded
- unify LoadedAdapter and DesiredAdapterState into AdapterState
- refactor InferencePool to Protocol with StaticInferencePool and ElasticInferencePool implementations
- remove unused admin_clients param from Scheduler
- fix discover_ready_servers to only return servers with requested model (no fallback)
- add tests for multi-adapter case
* refactor: clean up elastic discovery with shared utility functions
- Add ServerDiscovery class for env workers (DNS discovery + client management)
- ElasticInferencePool uses same discovery functions
- Shared logic via utility functions: discover_server_ips, discover_ready_servers
- Remove mode flags and unnecessary abstractions
* remove early elastic+lora validation from orchestrator (handled in ElasticInferencePool.update_weights)
* add debug logging for adapter mismatch + parallelize sync_weights
* add more debug logging for adapter matching
* close inference clients on ElasticInferencePool shutdown
* add run eviction logic
* add some tests
* add run eviction to docs
* update rename in index
* make packer evict runs it doesnt like
* add check for teacher logprobs
* dont error on idx not found in case we double evict
* remove stale test
* this log is quite spammy
* rename config folder to control
* Disable final checkpoint saving when max_concurrent_runs > 1
When max_concurrent_runs > 1, checkpoints are managed by the
MultiCheckpointManager at the whims of the orchestrator, making
the final checkpoint save in the trainer redundant and meaningless.
* Update src/prime_rl/trainer/rl/train.py
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* Update src/prime_rl/trainer/rl/train.py
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
* Add AGENTS.md and CLAUDE.md for AI coding agents
- AGENTS.md as source of truth for all AI agents
- CLAUDE.md imports AGENTS.md for Claude Code compatibility
* Update AGENTS.md
---------
Signed-off-by: JannikSt <JannikSt@users.noreply.github.com>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* better runs docs
* some renamin
* missed tests
* missed comments
* meraid docs render in gh according to CC [skip ci]
* better diagram [skip ci]
* Update docs/runs.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* docs update
* rename to MultiRunManager
* guard the discovery apis rom being used by non master ranks
* variable renaming
* sync runs to synchronize state
* dont register master only hooks on non master
* encapsulate lora hook registration into run manager setup
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Add exponential backoff retry for empty training batches
When inference becomes temporarily unavailable, all rollouts may fail
resulting in an empty batch. Instead of crashing, retry the step with
exponential backoff (30s, 60s, 120s, 240s, 300s cap) up to 5 times.
* Cancel validation task before retry to avoid accumulation
* Fix off-by-one: use >= for retry count check
* Fix trainer crash when all rollouts in a batch fail
When all rollouts fail (e.g., conversations exceed context limit), the tensor is empty and compute_stats() crashes on .min()/.max() calls. Skip stats computation for empty tensors.
* Emit NaN for empty tensor stats instead of skipping
* Auto-restart env workers on unexpected death
- Add restart() method to EnvWorker
- Modify collect_responses() to auto-restart with warning log
- Scheduler catches WorkerDiedError and continues instead of crashing
- Add unit tests for restart functionality
* Fix: join dead process to prevent zombies
* Add max restart limit (5) to prevent infinite restart loops
* Make max_worker_restarts configurable via orchestrator config
* Rename to max_env_worker_restarts for clarity
* Support -1 for unlimited restarts
* Fix AI review feedback on worker restart behavior
- Reset restart count after 10 successful responses (prevents
isolated failures over time from accumulating)
- Store fatal error on worker so orchestrator can detect and crash
when max restarts exceeded
- Fix misleading log message that claimed auto-restart unconditionally
- Add _check_for_fatal_worker_errors() to crash orchestrator properly
* Remove elastic utility file
* Remove k8s references from config and scheduler
* Make restart method private
* Fix test mock to use _restart
* support index in register post creation callback
register scheduler at index 0
plumbing
first draft
fixes
* just copy for now
* fix issue where only master tracks saved ckpt steps
* only master should do the broadcast copy
* add deletion hooks
* delete stale managers on deletion
* support the -1 convention
* make orchestrator broadcast support reading from ckpy dir
* only delete manager if it exists
* fix: add creation hook so we check existing ckpts before orchestrator
creates them
* missing arg [skip ci]
* dcp is not my friend
* add ckpt config to test
* more efficient trainer
* include some stop resume in the tests
* fix tests
* add some useful debug logs
* fix: type in orch check
* fix: dont load progress in create run hook
* broadcast progress so all ranks know when to ckpt
* better debug log for ckpting
* fix: we must wait for trainer checkpoint before we can delete run
* ci uses single gpu trainer
* Revert "ci uses single gpu trainer"
This reverts commit 7b0382b947aa0cb2af64645c17d849708adef467.
* refactor wait and kill for tests
* tests passing but kinda messy
* remove old log
* cleanup test
* cosmetic changes to multi run test
* fix: missed orch proc setting
* put start print in a better location
* exclude the resumes from reward go up check
* use stable file to mark trainer is done with checkpointing
* the barrier needs t be outside the try catch
* add timeout to wait for file
* mark stable after last barrier
* error in wait for log if timeout
* fix fixture signature
* append to tracked steps after barrier
* fix bad while else
* fix: move barrier and mark stable into the loop
* the orchestrator finish wait was apparently necessary for beta orch to exit correctly
* better error message for not finding weight dir
* cleaner manager creation in multi ckpt
* try catch the weight copy
* fix: manager access in clean
* move wait file print to less spammy place
* no max steps in trainer toml should make it infinite
* add comment about wide try except
* support exporting json in bench mode
* script to run one benchmark
* auto set batch size
* aggregation script
* draft nightly
* add benchmarks folder to image
* support passing docker image
* use image and from micro batches
* some reordering and passing more args
* try this
* use runner name in step name
* bash the entrypoint and working dir
* rename artifact
* dont support sft lora for now
* remove concurrency gorup
* print last 100 lines in success so we can see the table in the ci run output
* add comment
* make containers use host HF home to speedup multiple tests on the same runner
* set max loras
* use hosts root cache
* add runner to artifact name
* make baselines dir
* dont use this random dudes step wth claude
* do /data
* don do labels
* try to just use a named volume
* try directly having root level dir
* try clearing lock and changing permissions
* just start container as root
* god i cant rmb the name of my own args
* better device name surfacing
* pin a digest because tag might drift
* should probably make it easier to test changes to agg result but yolo i trust the ai overlords
* get the image digest on a self hosted runner so we have image cache
* go out of our way to surface OOM
* allow setting diff display threshold
* baseline should be set after running not before
* put docker image in the markdown
* displaying per microbatch step time probably makes more sense
* set better name for benchmark json files
* dont use batch size in config key
* move constants to the top
* rename and cleanup
* wishlist matrix
* missing commas lol
* fix typo
* use the 1xa6000 as the digest runner
* rename workflow
* set longer timeout for 235b
* try shell arithmetic
* we need to multiply the num tokens by dp size
* add time taken
* better sorting key
* change hardware col order
* just print every line in the success case, we arent poor
* lines
* wishlist benchmarks
* prune some more errors
* remove some dead ones
* rl bench validator
* add timeou to run single benchmark
* only copy the scripts
* sort matrix a bit better
* more pruning and tuning
* Update benchmark results 2026-01-16 (#13)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
* Apply suggestions from code review
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* make regression flag more unique
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
* Add health endpoint for worker nodes in multi-node training
- Add HealthServer base class with /health endpoint only
- MetricsServer now extends HealthServer
- Worker nodes start HealthServer, master gets full MetricsServer
- Add tests for HealthServer
* Fix port conflict: only start server on local_rank 0 per node
* Fix ruff formatting
* Format test file
* Fix ruff lint errors
* remove transient error testfile
* generated packer tests
* simplify packer tests
* packer doc
* support buffers and smaller orchestrator granularity
* fix duplicates in filesystem reader
* make small batch granularity toggleable to not break single run behavior
* add comment about temperature
* fix reset staleness
* fix: cc is way too defensive and didnt understand what we meant with needing full batches in small_batch_granularity=False case
* missing samples increment
* guard infinite loop in select samples
* remove the tests because the previous logic didnt make sense so theyre probably super stale and confusing
* fix: check every run in full batch case
* do popleft
* add create run data hook
* just prealloc state cuz life is easier
* set small granularity packing on the multi run test
* remove debug prints
* have very descriptive name for pack flag
* the doc isnt particularly helpful
* cover overfull case
* split out single run packer
* remove packer arg
* missing step arg
* pop out the oversized batch
* take out tokens collected if skip
* transport config
* move packing reset hook to deletion
* refactor(eval): move checkpoint step validation to runtime
Keep the same stable-checkpoint step validation logic, but run it at eval startup instead of during config parsing.
Co-authored-by: sami <sami@primeintellect.ai>
* chore(eval): remove runtime step validation comment
Co-authored-by: sami <sami@primeintellect.ai>
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
* fix: keep eval running on checkpoint failures
Adds `continue_on_ckpt_error` so a single bad checkpoint won't abort multi-checkpoint evals. In watcher mode, existing stable checkpoints are skipped (per docs) and failed new checkpoints remain pending for retry.
Co-authored-by: sami <sami@primeintellect.ai>
* chore: sort imports in eval checkpoint test
Co-authored-by: sami <sami@primeintellect.ai>
* chore: satisfy ruff import ordering in eval test
Co-authored-by: sami <sami@primeintellect.ai>
* chore: apply ruff import ordering fix
Co-authored-by: sami <sami@primeintellect.ai>
* fix: avoid global sys.modules stubs in eval test
Use anyio marker and local monkeypatching so this test doesn't break collection for other unit tests.
Co-authored-by: sami <sami@primeintellect.ai>
* refactor: always continue on checkpoint eval failures
Remove the config/test and make checkpoint eval best-effort by default: per-checkpoint exceptions are logged and evaluation continues. Watcher mode keeps failed checkpoints pending for retry.
Co-authored-by: sami <sami@primeintellect.ai>
* fix: keep watcher evaluating existing checkpoints
Restore prior watcher behavior: evaluate all stable checkpoints first, then watch for new ones. Checkpoint failures are logged and skipped without aborting the whole eval process.
Co-authored-by: sami <sami@primeintellect.ai>
* refactor: inline checkpoint try/except in eval
Co-authored-by: sami <sami@primeintellect.ai>
* Revert "refactor: inline checkpoint try/except in eval"
This reverts commit 4b6483786bd39889676c2226693229ae59a4e63a.
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
* wip add watcher
* docs: add changelog entry for eval.watcher
Document the new eval.watcher config flag per config-change review rules.
Co-authored-by: sami <sami@primeintellect.ai>
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
* add env worker logging
* reset logger before env logger
* redirect verifiers logger to file
* Add CHANGELOG entry for orchestrator.env.log configuration
Documents the new EnvLogConfig class and log field added to EnvConfig,
which provides logging configuration for environment workers.
* Fix worker crash when logging disabled
When logging is disabled (default), reset_logger() sets _LOGGER to None
but setup_logger() was not called. This caused EventLoopLagMonitor to
crash with RuntimeError when calling get_logger().
Fix: Always set up a logger in worker processes. When logging is disabled,
use CRITICAL level which produces no output (critical logging is disabled
in setup_logger).
* fix
* Add formatter to verifiers logger FileHandler
The FileHandler added for the verifiers logger was missing a Formatter,
causing log messages to be written as raw text without timestamps, log
levels, or logger names. This makes the verifiers logs difficult to
correlate or debug effectively.
Added a Formatter with timestamp (HH:MM:SS) and log level formatting,
matching the format used by the prime-rl logger for consistency.
* Add missing reset_logger() in else branch
On Linux with fork start method, worker subprocesses inherit _LOGGER
from parent. Both branches need reset_logger() before setup_logger()
to avoid RuntimeError("Logger already set").
* Revert "Fix worker crash when logging disabled"
This reverts commit f37ab4be3ce4fe85e15391ecdc3164bfe5b59ee5.
* refactor
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Ensures consistency with the config default changed in #1567. The
MultiLoRALinear and MultiLoRAGroupedExperts classes had stale defaults
that should match the orchestrator and trainer configs.
Co-authored-by: Claude <noreply@anthropic.com>
* fix: detect dead worker process in collect_responses
Previously if a worker subprocess crashed, collect_responses() would loop forever waiting for responses. Now it checks process.is_alive() and raises RuntimeError with exit code.
* fix: remove unused import
* fix: rewrite tests as sync to avoid pytest-asyncio dependency
* Add _stopping flag to skip dead worker error during shutdown
* Reset _stopping flag in start() to fix restart detection
* Remove unused tests for EnvWorker subprocess management
Co-authored-by: jannik <jannik@primeintellect.ai>
* Fix race condition and pending futures on worker death
* Prevent scheduler from routing to dead workers
* Drain response queue before checking dead worker
* Add WorkerDiedError to propagate through scheduler for K8s restart
* Fix exit code race condition in rl.py main loop
* Check subprocess return codes directly after loop
* feat: set default fused_lm_head_chunk_size to 2048 for RL training
Auto-configures model.fused_lm_head_chunk_size to 2048 for RL training
when not explicitly set. SFT training continues to use None (no chunking)
as it doesn't support chunked loss yet.
* docs: update fused_lm_head_chunk_size description and changelog
Update the field description to mention RL training auto-sets to 2048.
Add changelog entry for the default behavior change.
* Fix: RL training auto-sets fused_lm_head_chunk_size except for liger_kernel
Co-authored-by: ongjackm <ongjackm@gmail.com>
* Refactor check_number_in_range to improve step searching
Co-authored-by: ongjackm <ongjackm@gmail.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
* Add optional Prometheus metrics server for trainer observability
- Exposes /metrics endpoint with training metrics (step, loss, throughput, grad_norm, etc.)
- Disabled by default, enable via `metrics_server.port` config
- Uses isolated CollectorRegistry per instance
- prometheus_client is optional dependency (uv sync --extra metrics)
* Update lockfile for prometheus_client optional dep
* Add changelog entry for metrics_server
* Convert tests to function style
* Clean up Prometheus metrics naming and add mismatch_kl
- Remove rft_ prefix from all metrics (trainer_* instead of rft_trainer_*)
- Add trainer_mismatch_kl metric for tracking KL divergence
* Add per-run/LoRA metrics to Prometheus server
Aggregate metrics:
- trainer_runs_discovered: run folders found
- trainer_runs_active: runs with assigned slots
- trainer_runs_ready: runs ready for gradient updates
- trainer_runs_max: maximum run capacity
Per-run metrics (with labels):
- trainer_run_step{run="run_001"}: training step
- trainer_run_tokens{run="run_001"}: total tokens processed
- trainer_run_learning_rate{run="run_001"}: current LR
- trainer_run_ready{run="run_001"}: ready status (1/0)
* Add /health endpoint for K8s liveness probes
- Add HealthCheckConfig with max_step_age_seconds and startup_grace_seconds
- Add /health endpoint to MetricsServer for trainer liveness checks
- Fix socket leak in stop() by calling server_close() and joining thread
* Use heartbeat instead of step-age for health checks
- Rename max_step_age_seconds to timeout_seconds
- Add heartbeat() method called every loop iteration
- Detects hung main thread even when waiting for runs
* Add optional on_wait callback to sync_wait_for_path
* Revert unused on_wait callback
* Simplify /health to always return 200
* orchestrator config is ok and component integrations look satisfactory
* rename lora_name to lora.name in orchestrator
* fix in rl.py
* multilora independent scaling factors
* train.py changes
* changes to runs
* update tomls for lora.name
* set the default lora rank to trainers
* set lora scaling dtype to bf16
* missed lora_name -> lora.name
* allow run to reset the lora globals
* damn these configs got hands
* i feel like i might have made my life hard for no reason. ah well, im lazy to think of somethin better rn
* set higher default lr on orch side
* fix configs for non-master ranks
With agents now drafting PRs and auto-generating descriptions, the
template with placeholder text is no longer needed.
Co-authored-by: Claude <noreply@anthropic.com>
* [feat] Enable loss chunking for non-custom HuggingFace models
Add support for chunked loss computation (via FusedOutputLinear) for any
HuggingFace CausalLM model, not just custom PrimeRL implementations.
Changes:
- Add wrap_lm_head_for_hf_model() function in model.py that:
- Wraps the lm_head with FusedOutputLinear or VanillaOutputLinear
- Overrides the model's forward method to accept labels and temperature
- Returns PrimeLmOutput with logprobs/entropy for chunked mode
- Update setup_model() to call wrap_lm_head_for_hf_model for non-PrimeRL models
- Remove config validator restriction that limited fused_lm_head_chunk_size
to custom/auto implementations
- Add tests for HF model wrapping with both vanilla and fused modes
* change PrimeLmOutput to TypedDict so that it is pytree node by default
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
* change all references to output for dict
* guard against unconventional model being used
* dont be so defensive in tests with model output
* guard against lm heads with bias
* move lm head injection logic into lm_head.py and unify injection path for custom and hf impl
* update inject in tests
* fix forward signature for custom impls
* cover input embeds case
---------
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
* plumbing to get it to be loaded
* first draft without tenant splitting
* correct fqns
* cleanup multilora moe impl
* fix: param counting
* fix excessive vram usage due to views
* fix perf lora adapter param counting
* make packer only pack global mbs rows with similar run_idx
* add comment because this packing is kinda weird
* fix: set offset correctly for multiloramoe
* idk if th vibe coding has more typos or me
* support lora dropout
* add experts to default lora targets
* remove outdated tests
* feat: Add LoRA dropout to MultiLoRAGroupedExperts
Co-authored-by: ongjackm <ongjackm@gmail.com>
* cursor nits
* forgot the changelog lol
* Update CHANGELOG with recent changes and fixes
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Johannes Hagemann <johannes@primeintellect.ai>
* fix: enable grouped_mm on blackwell
* fix: disable grouped_mm in unit tests for MoE models other than AFMoE
* use_grouped_mm should default to True
---------
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* basic slow afmoe setup
* add flex attention
* avoid compilation error on flex-attn
* super rough fix for swa and sequence packing
* massively simplify impl
* remove a bunch of dead/unused code and clean up
* un-correct unrelated bug for later fix
* remove debug config file accidentally left in
* remove redundant extra imports
* simplify attention impl
* revert comment
* remove flex_attn for now
* fix ruff lints
* do not put attn in separate file
* satisfy ruff
* Add retry logic to load_lora_adapter for NFS delays
Uses tenacity with exponential backoff (1-30s) for up to 10 attempts.
Retries on 404 (adapter not found) and 500 (server error) which can
occur due to NFS propagation delays between trainer broadcast and
inference server load.
* Add unit tests for load_lora_adapter retry logic
* Fix tests: use asyncio.run instead of pytest.mark.asyncio
* Refactor tests to pytest function style (no classes)
* Fix: Adjust reward check thresholds and step in lora integration test
Co-authored-by: ongjackm <ongjackm@gmail.com>
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: ongjackm <ongjackm@gmail.com>
* feat: Add NCCL broadcast support for weight updates
This commit introduces NCCL broadcast as a new method for updating weights. It includes modifications to the orchestrator, scheduler, and NCCL broadcast implementation to handle the synchronization required for NCCL communication. The `update_weights` utility function is updated to create a `NCCL_READY` marker file when NCCL broadcast is enabled, signaling to the trainer that inference workers are ready to receive weights.
Co-authored-by: sami <sami@primeintellect.ai>
* Refactor: Remove unused is_nccl_broadcast flag
Co-authored-by: sami <sami@primeintellect.ai>
* Remove NCCL ready marker cleanup from broadcast
Co-authored-by: sami <sami@primeintellect.ai>
* feat: Add timeout to sync_wait_for_path and wait_for_path
Co-authored-by: sami <sami@primeintellect.ai>
* Checkpoint before follow-up message
Co-authored-by: sami <sami@primeintellect.ai>
* remove to
* remove upus ty
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
2025-12-31 09:46:27 +01:00
406 changed files with 38734 additions and 9465 deletions
- Avoid try/except blocks unless it's really necessary. It's fine that a program fails if something goes wrong as this helps us to catch non-obvious bugs and unforeseen side-effects earlier. You can add try catch on code that explicitly aims to be fault tolerant like adding retry mechanisms or explicit and intentional robustness.
- Do not add unnecessary comments. Especially do not try to explain code change that reflect your work process, do not refer to old code. "The code used to do that but now we are doing this" is not a pattern we want. Instead prefer to use targeted comments sparingly to explain ambiguous code.
## Zen of Python
remember the zen of python when writing code.
```
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
```
## Running code
- All code should be runnable with `uv run` or `uv run <command>`.
- All dependencies should already be installed and pin in the lock file. If not, add it to pyproject.toml and run `uv sync --all-extras` to install it.
## CLI Usage
- Config files use `@` syntax: `uv run sft @ path/to/config.toml`
- For multi-GPU with torchrun: `uv run torchrun --nproc-per-node 2 src/prime_rl/trainer/sft/train.py @ path/to/config.toml`
- See the `toml-config` skill in `skills/` for full details on TOML structure, CLI overrides, and available commands.
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
## Testing
Write tests as plain functions with pytest fixtures. Don't use class-based tests.
## Git
Branch prefixes: `feature/`, `fix/`, `chore/`
## Releases
When preparing release notes:
1.**Style reference**: check the previous release (`gh release list --limit 1` then `gh release view <tag>`) to match the tone and formatting.
2.**Gather changes**: use `git log <last-tag>..origin/main --oneline --no-merges` to list all commits since the last release.
2.**Check for new commits**: always `git fetch origin main` and re-check right before publishing, since PRs may have been merged while drafting.
3.**Structure**: organize notes into numbered highlight sections (`# 1.`, `# 2.`, ...), then `# Breaking Changes`, `# Bug Fixes`, and `# Misc`.
4.**Highlights**: group related PRs under a single highlight. Use `##` subsections when a highlight contains multiple items (e.g. Performance & Parallelism). Keep the top highlights for the most impactful user-facing features.
5.**Config examples**: when referencing TOML config, verify the exact field names against the actual code or docs — don't guess.
6.**Links**: use clickable links for docs (`[docs/foo.md](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/docs/foo.md)`) and PR references (`[#1234](https://github.com/PrimeIntellect-ai/prime-rl/pull/1234)`).
7.**Contributors**: list all contributors ranked by number of commits, using their GitHub `@username`. Get usernames via the GitHub API, not git author names (which can be inconsistent).
8.**Draft first**: always create releases as `--draft` first, iterate on content, then publish.
- **`[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)
- **`orchestrator.verification.enabled`**: Added top-level rollout verification switch. `orchestrator.buffer.skip_verification` has been removed; use `verification.enabled = false` instead. When disabled, rewards are always 0 and reward-dependent buffer features (`online_difficulty_filtering`, `easy_threshold`, `hard_threshold`) must be unset (2026-03-03)
- **`client.dp_rank_count`**: Added configuration for data-parallel inference routing. When > 1, each `client.base_url` is expanded into `dp_rank_count` logical clients and pinned via `X-data-parallel-rank` to keep multi-turn rollouts on a consistent DP rank (default: 1) (2026-03-03)
- **`model.lora`**: Moved from `model.experimental.lora` to `model.lora` (no longer experimental) (#1440, 2025-12-16)
- Auto-set `api_server_count=1` on inference when LoRA is enabled, because vLLM doesn't support hotloading for multiple API servers (#1422, 2025-12-17)
- **`orchestrator.buffer.env_ratios`**: Added environment ratio configuration for buffer sampling (#1450, 2025-12-18)
- **`orchestrator.buffer.skip_verification`**: Added configuration to skip verification of rollouts using the environment's rubric. If True, rewards are always set to 0. Cannot be used with `online_difficulty_filtering=True` or when `easy_threshold`/`hard_threshold` are set (default: False)
- **`orchestrator.buffer.easy_fraction`** and **`orchestrator.buffer.hard_fraction`**: Easy and hard fraction now defines the fraction of easy and hard problems to convert to normal when resuming, whereas previously it was the ratio of easy/ hard samples to sample per step (#1450, 2025-12-18)
- **`orchestrator.teacher_model`**: Added teacher model configuration for computing teacher logprobs (e.g. for distillation). Supports `TeacherModelConfig` (custom model) or `None` (disabled). Renamed from `reference_model` (2025-12-20)
- **`seq_len`**: Added root-level `seq_len` config that sets both `trainer.model.seq_len` and `orchestrator.seq_len`. Added validation that `trainer.model.seq_len >= orchestrator.seq_len` (2025-12-18)
- **`trainer.loss.sequence_mask_ratio_low`** and **`trainer.loss.sequence_mask_ratio_high`**: Renamed to `trainer.loss.sequence_mask_low` and `trainer.loss.sequence_mask_high` (2025-12-19)
- **`trainer.loss.token_mask_high`** and **`trainer.loss.token_mask_low`**: Added token-level importance ratio masking thresholds (2025-12-19)
- **`trainer.loss.sequence_clip_high`**: Added sequence-level importance ratio clipping threshold (2025-12-19)
- **`trainer.loss.geo_mask_high`** and **`trainer.loss.geo_mask_low`**: Added geometric importance ratio masking thresholds (2025-12-19)
- **`trainer.loss.adv_tau`**: Added tau parameter for advantages (default: 1.0)
- **`trainer.loss.teacher_tau`**: Added tau parameter for teacher logprobs (default: 0.0). Renamed from `ref_tau`
- **`teacher_gpu_ids`**: Added GPU IDs for teacher inference server. When set, automatically starts a teacher inference server and configures `orchestrator.teacher_model`
- **`teacher_inference`**: Added optional teacher inference config. Defaults to copying from `inference` config with port 8001
- **`{orchestrator,trainer}.transport.zmq`**: Added ZMQ transport for training batches and micro batches (#1446, 2025-12-22)
- **`model.impl`**: Changed default from `hf` to `auto`. With `auto`, the implementation automatically selects `custom` if supported for the model, otherwise falls back to `hf` (#1488, 2025-12-27)
- **`orchestrator.eval.skip_eval_on_resume`**: Added flag (default `True`) to skip the first potentially redundant online eval immediately after resuming from a checkpoint (#1491, 2025-12-27)
- **`trainer.weight_broadcast.adapter_only`**: Removed. Adapter-only behavior is now automatically derived from the presence of LoRA configuration (2025-12-27)
- **`ckpt.keep`**: Renamed to `ckpt.keep_last`. Added `ckpt.keep_interval` to keep checkpoints at every N steps permanently (2025-12-31)
- **`MultiLoRAMoE`**: QwenMoE now supports training expert loras and this is enabled by default in the `target_modules`. (2026-01-01)
- **`model.fused_lm_head_chunk_size`**: Added chunk size configuration for fused LM head to enable memory-efficient chunked logprob computation. When set, splits vocabulary into chunks to avoid materializing full [N, V] logit tensor (default: None) (#1525, 2026-01-03)
- **`model.fused_lm_head_chunk_size`**: RL training now auto-sets this to 2048 if not specified (except when `impl='liger_kernel'`). SFT training continues to use None (2026-01-05)
- **`trainer.metrics_server`**: Added optional Prometheus metrics server for trainer observability. Exposes `/metrics` endpoint with step, loss, throughput, grad_norm, etc. Disabled by default (default: None) (#1547, 2026-01-06)
- **`model.lora.alpha`**: Changed default from 16.0 to 32.0 (2026-01-10)
- **`orchestrator.env.log`**: Added logging configuration for environment workers. If set, enables logging with `level` (str, default: "warn") and `vf_level` (str, default: "warn") fields. If None (default), logging is disabled (#1561, 2026-01-13)
- **`eval.watcher`**: Added flag (default `False`) to watch `weights_dir` for newly-created stable checkpoints and evaluate them as they appear (2026-01-14)
- **`orchestrator.log.env_worker_logs`**: Added flag (default `False`) to write env worker logs to `logs/env_workers/{env_name}.log` (2026-01-15)
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
- **`client.skip_model_check`**: Added configuration to skip checking if the model is available in the inference pool. Useful for external APIs or API keys that don't support the /models endpoint (default: False) (#1543, 2026-01-06)
- **`orchestrator.sampling.temp_scheduler`**: Added optional temperature schedule configuration with linear and cosine schedules. Set either `sampling.temperature` (constant) or `sampling.temp_scheduler` (schedule), not both. Default remains 1.0 if neither is set. (2026-01-27)
- **`orchestrator.trajectory_strategy`**: Deprecated. Interleaving now automatically handles extension breaks by starting a new sample when the prefix doesn't match, achieving best-of-both behavior. The setting is ignored and interleaved mode is always used. (2026-01-30)
- **`model.impl`**: Removed `liger_kernel` model implementation from supported options. The Liger kernel dependency remains for SFT loss. (2026-01-30)
- **`log.json_logging`**: Added JSON structured logging option for log aggregation systems (Loki, Grafana, etc.). Outputs flat newline-delimited JSON with `timestamp`, `level`, `message`, `module`, `function`, `line` fields. Available on root `log`, `trainer.log`, and `orchestrator.log` (default: False) (2026-01-28)
- **`model.optim_cpu_offload`**: Added flag to offload optimizer states to CPU without moving parameters (default: False) (2026-01-31)
- **`orchestrator.tasks_per_minute`**: Added optional rate limiting for sandbox tasks per environment worker. Uses token bucket algorithm. If None (default), no rate limiting is applied (2026-02-02)
- **`model.cp`**: When `cp>1` with `attn="flash_attention_3"`, require `model.impl="custom"` (FA3 ring-attention kernel only in custom path) (2026-02-06)
- **`model.attn`**: Added `fa4` as an attention implementation option. Flash attention 4 is only supported with the custom implementation (#1726, 2026-02-06)
- **`inference.model.enable_prefix_caching`**: Added flag to enable prefix caching in vLLM. Passed to vLLM as `--enable-prefix-caching` (default: None) (2026-02-08)
- **`orchestrator.env.address`**: Added address field on `EnvConfig`. If set, connect to an environment server at this address; if None, spawn a server in a subprocess (2026-02-06)
- **`orchestrator.env.extra_env_kwargs`**: Added on `EnvConfig`. Extra kwargs passed to the env (e.g. seq_len, interleaved_rollouts, score_rollouts). Auto-populated by the orchestrator for training envs; generally not recommended for user override. Main use case is to match these kwargs when running an env in an isolated environment server (default: {}) (2026-02-06)
- **`OrchestratorConfig`**: Removed `workers_per_env`, `max_env_worker_restarts`, and `mask_env_responses` (2026-02-06)
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTConfig` (2026-02-23)
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
- **`[slurm]` (SFT)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run sft` generates and submits an sbatch script instead of running locally (2026-02-23)
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
- **`clean_output_dir`**: Added to `RLConfig` and `SFTConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
- **`sft.val`**: Added optional periodic SFT validation with `val/loss` and `val/num_tokens` logging. Configure via `sft.val.data` (validation dataset) and `sft.val.interval` (every N steps, default 50). Runs the full validation dataset each pass. (2026-02-26)
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
- **`slurm.dry_run`**: Removed from `SlurmConfig`. Replaced by top-level `dry_run` (see below) (2026-02-26)
- **`dry_run`**: Added to `RLConfig` and `SFTConfig` (default: `False`). When set, validates the config, writes resolved subconfigs to `output_dir/configs/`, and exits without starting any processes. Works the same for both local and SLURM runs (2026-02-26)
- **Config output location**: Resolved subconfigs are now always written to `output_dir/configs/` instead of `.pydantic_config/<uuid>/`. This applies to both local and SLURM entrypoints, and for both single-node and multi-node deployments (2026-02-26)
- **SFT config filename**: The resolved SFT trainer config is now written as `sft.toml` instead of `trainer.toml` (2026-02-26)
- **Inference entrypoint**: Moved from `prime_rl.inference.server` to `prime_rl.entrypoints.inference`. No change to CLI usage (`uv run inference`) (2026-02-26)
- **`[slurm]` (inference)**: Added SLURM configuration to `InferenceConfig`. When present, `uv run inference` generates and submits an sbatch script instead of running locally. Each SLURM node runs an independent vLLM replica (no cross-node parallelism) (2026-02-26)
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
- **`orchestrator.teacher_rollout_model`**: Added optional external rollout model configuration. When set, rollouts are generated from this endpoint/model instead of the student inference server. Accepts a `TeacherRolloutModelConfig` with `client` and `model` sub-fields, or `None` (default: `None`) (2026-02-26)
- **`trainer.loss.type = "sft"`**: Added SFT loss variant. Set `trainer.loss.type = "sft"` to use masked negative log-likelihood loss instead of the default RL loss (2026-02-26)
- **`trainer.loss.type = "custom"`**: Added custom loss variant. Set `trainer.loss.type = "custom"` with `import_path` (e.g. `"my_module.my_loss"`) and optional `kwargs` to use an external loss function (2026-02-26)
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
- **`trainer.ckpt.skip_optimizer`**: Added flag to skip loading optimizer states when resuming training. When set, only the model weights are loaded from the checkpoint. (2026-03-24)
@@ -34,7 +34,7 @@ PRIME-RL is a framework for large-scale asynchronous reinforcement learning. It
1. Integrates natively with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments via the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars)
2. Supports end-to-end post-training, including SFT and RL training and evals
3. Multi-node deployment with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) training and [vLLM](https://github.com/vllm-project/vllm) inference backend
4. Designed for asynchronous training in decentralized settings
4. Designed for asynchronous agentic RL training at scale
5. Hackable, modular and extensible by nature
## Setup
@@ -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.
"error_reason":"[rank0]: torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 37.09 GiB. GPU 0 has a total capacity of 79.18 GiB of which 34.48 GiB is free. Including non-PyTorch memory, this process has 44.69 GiB memory in use. Of the allocated memory 43.38 GiB is allocated by PyTorch, and 103.94 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)",
"error_reason":"[rank4]: torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 8.00 GiB. GPU 4 has a total capacity of 178.36 GiB of which 7.20 GiB is free. Including non-PyTorch memory, this process has 171.05 GiB memory in use. Of the allocated memory 168.36 GiB is allocated by PyTorch, and 418.92 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)",
> :warning: indicates regression > 5% from baseline
> diffs shown when abs(change) >= 1.0% (except regressions, which always show diffs)
> :clock10: The Step Time shown is the time taken per micro batch. This differs from what gets displayed in the bench table which is the total step time.
## INTELLECT-3
| Type | SeqLen | AC | Attn | EP | CP | Hardware | MFU | TPS | Step Time | Peak Mem |
f"> :warning: indicates regression > {threshold*100:.0f}% from baseline",
f"> diffs shown when abs(change) >= {diff_display_threshold*100:.1f}% (except regressions, which always show diffs)",
"",
"> :clock10: The Step Time shown is the time taken per micro batch. This differs from what gets displayed in the bench table which is the total step time."
"",
]
formodel,model_resultsinsorted(by_model.items()):
lines.append(f"## {model.split('/')[-1]}")
lines.append("")
lines.append("| Type | SeqLen | AC | Attn | EP | CP | Hardware | MFU | TPS | Step Time | Peak Mem |")
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.