* 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>
* refactor: buffer take dataset as input
* Fix: Seed validation dataset from val buffer config
Co-authored-by: sami <sami@primeintellect.ai>
* refactor: move env execution to sub process
* refactor: move env execution to sub process
* refactor: move env execution to sub process
* add lag monitoring to subprocess
* add multi env worker
* fix: route examples to correct environment workers (#1502)
* fix: route examples to correct environment workers
Examples were being sent to workers via round-robin, ignoring the
example's task field. This caused mini-swe-agent-plus examples to be
processed by deepdive workers (with deepdive's tools), and vice versa.
Now examples are routed to the worker pool for their specific
environment, with least-pending load balancing within that pool.
env_ratios is respected for environment selection.
* log env id to wandb samples table
---------
Co-authored-by: Johannes Hagemann <johannes@primeintellect.ai>
* remove commebnt
* remove unscerayu stff
* remove unused client
* remove unused client
* remove extra errro handling
* fix queue and update policy
* Refactor: Initialize checkpoint manager and determine step early
Co-authored-by: sami <sami@primeintellect.ai>
* Refactor: Remove redundant checkpoint step comments
Co-authored-by: sami <sami@primeintellect.ai>
* fix lora
* fix smth
* Update src/prime_rl/orchestrator/scheduler.py
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
---------
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: rasdani <73563550+rasdani@users.noreply.github.com>
Co-authored-by: Johannes Hagemann <johannes@primeintellect.ai>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* kitchsen sink
fix device for set offsets
fqn hook on multilora
refactor: base lora layer
dont export private stuff and use abs pathing;
standardize int32 cast for lora_num_tokens
encapsulate logic into multi lora module
save module instead of parameters
move registration into apply lora
* fix no more experimental
* move more things to base
* have overriden state dict function
* set correct device for multi node offset
* fix: other ranks need to init optimizer in run hooks
* refactor: move creation and deletion into their own functions
* introduce sync runs in run object
* follower ranks sync runs from master
* fix: import dist
* move run init to after PG setup
* drop deletion hooks and make creation hooks happen in sync_data instead of check for changes on master
* make state dict creation for lora on runs
* wrong indentation
* fix some comments
* only full tensor on the updating model
* fix: dont reset ready to update in delete run data
* fix test import
* untested multi-scheduler [skip ci]
* take out debug print in multi optim
* remove lora lienar
* defaults for lora num tokens
* make multi optimizer suport both paths [skip ci]
* rename multilora module
* move set offsets into base
* remove unused state dict func
* make named params call abstract in base class
* add back setup_optimizer
* have assert before pack
* return zero if nothing is ready to update
* correct cover max concurrent 1 case
* only step on ready to update idxs
* remove irrelevant comment
* set the default max concurrent to 1 for tests to pass
* fix batch tests
* fix: init process grtoup in runs test
* add wait for optimizer to be created in lora case
* have list to cover muon case
* multi run tests
* add multi run to tests
* route the padding tokens to the last lora
* typo in the ignore
* runs doc
* fix: chunk cu offsets in cp
* fix: sort used idx to maintain consistency across ranks
* only master checks for changes
* rename set offsets to set multilora offsets
* dont have multi components for single run [skip ci]
* fix: we still need to wait for run 0 creation because otherwise, its arrival will reset the parameters and this may happen after ckpt loading which would wipe the ckpt
* change dist init to fixture
* hide optim creation nuance in setup optimizer
* move the hook registration into scheduler.py
* missing optimizer arg
* rename to multilora components
* fix: trainer shouldnt accidentally revive runs that have been deleted mid update
* we shouldnt need this guard anymore
* sft shouldnt have the lora option as it doesnt have runs so it wont reset
* remove all the code specific stuff and just have a high level in the docs
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* feat: Add disk usage logging for checkpoints
Adds logging of disk space usage before saving checkpoints to help monitor disk space.
Co-authored-by: sami <sami@primeintellect.ai>
* Refactor: Log disk usage metrics to monitor
Co-authored-by: sami <sami@primeintellect.ai>
* Refactor: Extract checkpoint disk metrics logging
Co-authored-by: sami <sami@primeintellect.ai>
* Refactor: Rename _get_ckpt_disk_metrics to get_ckpt_disk_metrics
Co-authored-by: sami <sami@primeintellect.ai>
* Refactor: Centralize checkpoint disk metric collection
Co-authored-by: sami <sami@primeintellect.ai>
* Fix: Log disk metrics on all ranks
Co-authored-by: sami <sami@primeintellect.ai>
* Refactor: Log disk metrics separately in RL and SFT trainers
Co-authored-by: sami <sami@primeintellect.ai>
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
* Remove weight_broadcast.adapter_only config option
The adapter_only flag was automatically enabled when LoRA was configured,
making it a redundant configuration option. This change:
- Removes the adapter_only field from BaseWeightBroadcastConfig
- Derives adapter_only behavior from the presence of lora_config in
FileSystemWeightBroadcast
- Simplifies validate_lora_broadcast by removing adapter_only logic
- Removes adapter_only from rl_lora config TOML files
- Updates broadcast_weights method signatures to remove adapter_only param
* Refactor: Remove trainer.weight_broadcast.adapter_only
Co-authored-by: ongjackm <ongjackm@gmail.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
* error if train seq len too short and add arg for setting in rl.py
* change all configs to use root seq len
* update changelog
* just inline the util
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* Implement PrimeMonitor
* Fix ruff issues
* Adjust monitor set up to conform to new design
* Cleanup
* Use trajectories format
* Ensure proper use of .enabled in monitor
* Default to LogExtrasConfig() in both wand and prime monitors
* Minor bugbot fix
* Fix circular import in Heartbeat Config
* Ensure latest main change included
* Update src/prime_rl/orchestrator/config.py
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Signed-off-by: manveer <m13basra@gmail.com>
* Update src/prime_rl/utils/config.py
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Signed-off-by: manveer <m13basra@gmail.com>
* Fix bug in prime -> prime_monitor rename
* Switch to directly passing in api key rather than setting env var
* Address PR Comments
* Address bugbot comment
* Rename default api_key_var to PRIME_API_KEY
* Add retries to prime monitor requests
* remove unused var
* remove unused var
* Fix bugbot comment on thread cleanup
---------
Signed-off-by: manveer <m13basra@gmail.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Jannik Straube <info@jannik-straube.de>
* implement event loop lag class
* remove getter
* Revert "remove getter"
This reverts commit 8369d7c7ad8faabe00bdc4ac78f566c0efccbc9d.
* compute more informative metrics
* integrate with orch
* rename to med
* lower thresholds
* reset lag metrics across steps
* remove singleton pattern
* handle empty list case
* reset and cancel task
* dont use enum setter for logprobs mode
* fix: stale imports
* update to torch 2.9
* init_app_state doesnt take vllm config anymore somehow
* use runnable because of CUDAGraphWrapper
* vllm now uses default seed 0
* fix import
* moe venv
* use mjun flash attn for torch 2.9 and up vllm version
* Revert "moe venv"
This reverts commit 8934ceb3f92e3d38d8423f4f5418b8766d315548.
* remove some todos
* remove unused import
* Apply suggestions from code review
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* set very high max cpu loras to patch around areal lora hack
* make flash attn optional and put uv sync extras everywhere
* Integrate token-in route with vLLM v0.12.0 (#1444)
* Move LoRA out of experimental section (#1440)
* Add Bug Bot instructions for changelog enforcement (#1441)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
* duplicate chat completinos endpoint into /generate
* serve chat with token in functionality
* use field to avoid misleading warning
* nicer error msg
* lock feature branch
* make use tokens prompt configurable
* use setter and print info
* bump
* include inference
* do not print warning log (logs all the time)
* bump
* bump + bring back warning log
* bump vf
* bump vf
* use dp=6 in wordle example
* no deepcopy and no warning
* do not tokenize on the server
* add field names so that tokens is cached and no warning of unrecognized field is shown
* bump vf
* auto install
* bump vf
* bump vf + set vllm tokenize method
* skip applying chat template
* Revert "skip applying chat template"
This reverts commit 43c6a2b2a835fbf2def3ed93571ec3c3a2aa945c.
* Revert "do not tokenize on the server"
This reverts commit 918219176773ad45bd45e749e0e596d6d1a7e423.
* bring back log
* use route /v1/chat/completions/tokens
* fix log
* bump vf and make everything configurable
* bump and more informative log
* bump and make non-exact tokenization default
* use token prompts by default
* remove retokenization issue from docs
* rename class
* bump vf
* fix auto asc setup for lora
* bump vf
* bump vf
* bump vf
* bring back setter
* bump vf
* bump vf to latest prime-rl
* make custom routes v0.12.0 compatible
* monkey patch api server worker proc again to enable multi api server mode
---------
Co-authored-by: will brown <williambrown97@gmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: will brown <williambrown97@gmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
* duplicate chat completinos endpoint into /generate
* serve chat with token in functionality
* use field to avoid misleading warning
* nicer error msg
* lock feature branch
* make use tokens prompt configurable
* use setter and print info
* bump
* include inference
* do not print warning log (logs all the time)
* bump
* bump + bring back warning log
* bump vf
* bump vf
* use dp=6 in wordle example
* no deepcopy and no warning
* do not tokenize on the server
* add field names so that tokens is cached and no warning of unrecognized field is shown
* bump vf
* auto install
* bump vf
* bump vf + set vllm tokenize method
* skip applying chat template
* Revert "skip applying chat template"
This reverts commit 43c6a2b2a835fbf2def3ed93571ec3c3a2aa945c.
* Revert "do not tokenize on the server"
This reverts commit 918219176773ad45bd45e749e0e596d6d1a7e423.
* bring back log
* use route /v1/chat/completions/tokens
* fix log
* bump vf and make everything configurable
* bump and more informative log
* bump and make non-exact tokenization default
* use token prompts by default
* remove retokenization issue from docs
* rename class
* bump vf
* fix auto asc setup for lora
* bump vf
* bump vf
* bump vf
* bring back setter
* bump vf
* bump vf to latest prime-rl
* Explicitly catch env errors (#1416)
* add math python example
* use ac
* update rl instructinos
* use 8 gpus and no ac
* use offline filtering and val split because inference a bit too quick
* 12k seq len, 2k max tokens, 300 steps
* use hendrycks math with 512 tokens/turn
* zero completion on error
* log error rate
* update math python to use vf version
* fix arg
* fix completion mask type
* fix tests
* handle empty trajectories case
* add changelog
* bump vf
* log err rate and err distribution
* fix instance
* bump vf
* fix dropna only on err col
* also mask out first turn in interleaved mode
* handle skipped rollouts
* Revert "Explicitly catch env errors (#1416)"
This reverts commit c1aa49253d417b024645c33a69f99554322924c6.
* bump vf
* add asc comment
* add math python example
* use ac
* update rl instructinos
* use 8 gpus and no ac
* use offline filtering and val split because inference a bit too quick
* 12k seq len, 2k max tokens, 300 steps
* use hendrycks math with 512 tokens/turn
* zero completion on error
* log error rate
* update math python to use vf version
* fix arg
* fix completion mask type
* fix tests
* handle empty trajectories case
* add changelog
* bump vf
* log err rate and err distribution
* fix instance
* bump vf
* fix dropna only on err col
* also mask out first turn in interleaved mode
* handle skipped rollouts
* remove asc comment
* add output saving and retries
* resume with UUID
* checkpoint: Avg@2=0.7904, high
* add exacto config
* add running average
* test int3 on pinference
* fix
* retry with new `max_tokens`
* clean up config
* deprecate HF saving
* rollouts instead of groups
* revert synthesize
* minor fix
* address comments
* fix save path
* fix reasoning_content in orchestrator
* import from synthesize
* model validate resume config
* reintroduce saving to HF
* make retry configurable
* fix
* fix sampling args retry
* offer both, per rollout and group based
* resume path instead of uuid
* update config
* fix
* fix
* support stream save for groups
* default to per_rollout
* model validate resume path
* `per_rollout` defaults to false
---------
Co-authored-by: rasdani <3563550+rasdani@users.noreply.github.com>
* filesystem transport
* make orchestrator output batch
* fix circular import
* fix: advantage assignment
* changes to orchestrator for multi-dir
* rename some orchestrator stuff
* BC util imports
* multi dir train packing no broadcast
* configs and docs changes
* gitignore
* multi broadcast
* fix paths for tests
* remove duplicate progress
* fix test trajectories
* test runs
* allow setting max-loras
* use transport config
* fix: circular import
* test orchestrator log path
* rename to rollout_transport
* make prepare batch use lists instead of tensors
* extend is a little fastertan +=
* make trajectories use bool
* make packer to dataloader use msgpack
* guard write with tmp rename
* cursor be dumb sometimes
* rename TrainingExample to TrainingSample
* small fix
* use bool cast
* make notify private
* stdout is still in root logs folder
* set packer timeout
* fix run_default path
* fix last steps of broadcast
* fix: log self save sharded
* DEBUG CI
* more print
* test rl lora first
* separate lora test from non lora test
* turn off debug
* dont pass orch seqlen to trainer
* dont support none positions ids for now
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* monkey-patch run server so its used by multi api server as well
* add api server count arg to inference config
* auto setup asc >= dp
* monkey patch st child processes also get it
* remove debug print
* move lora layer to models
* strip and init meta
* add debug log
* skip lm head if tied weight embeddings
* use load using meta
* fix: exclude lora from pre load state dict hook
* make lora linear support any module
* add tests
* add tests for sequential
* remove rl lora config
* add logic to save dp_replicate_ranks
* fix: dont do relicate seeding when no dp replicate
* just raise NotImplemented for now
* fix: param freezing test
* broadcast seeding on dp replicate
* setup default wandb project and name
* use 8 gpus and limit context
* higher seq len and default config because err's on no logprob on dummy response
* run wiki search on 8 gpus again
* run for 200 steps
* us tp/ dp in wordle
* 3-5 turns in alphabet sort
* fix: round up max_lora_rank to valid vLLM values
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
When using LoRA ranks like 4 that aren't in this list, vLLM would reject them.
This adds a validator that automatically rounds up to the minimum valid value
that can serve adapters of the requested rank (e.g., rank 4 -> max_lora_rank 8).
A warning is emitted when rounding occurs.
* remove warning on max_lora_rank rounding
* add TODO for cleaner vLLM import on upgrade
The setup_admin_clients function was mutating the shared headers dict
from ClientConfig when adding the Authorization header. Since this dict
is part of the config object that gets serialized to wandb, the API key
was being logged.
Fix: Use .copy() to avoid mutating the original config dict.
* all claud opus 45 lol
* use pod specific inference urls
* fix: bad inferenc url [skip ci]
* fix: inference url in reverse text example
* Revert "all claud opus 45 lol" [skip ci]
This reverts commit 65064c2c9c9a50b604c2cf0c591e001c02aece33.
* monkey patch is da way
* add auto setup arguments required for lora
* more explicit default name and also broadcast by default
* ensure env var needed for dynamic lora is workign
* import whole module to get lora routes
* import vllm after validating config to set env var
* minor changes in alignment
* update alphabet sort
* allow configuring max lora rank
* update warning
* do not enable lora explicitly in wiki-search (not required)
* raise runtime error if lora + nccl
* rename to test_configs
* cleanup unit tests
* update sft integration test
* working sft tests
* fix eval ci
* synthesize integration tests
* rl integration test
* enable lora flag in inference config
* add lora integration tests
* Move utils and fixtures around
* use tmp output dir
* use shared wandb project
* bring back world reset
* update wandb names
* remove reverse text configs (moved to ci)
* fix rl examples
* remove vllm server fixture
* Minor changes
* add nightly ci
* Add nightly CI
* install prime in ci to enable auto install
* add pull pull request trigger
* make workflow visible when pr against main
* Add more experiments, auto-discovery, parallelize across runners
* build matrix correct
* fix configs
* use tp for 7b
* update configs
* add wordle
* remove tool install
* add logging on fail
* print logs on error and auto skip if failed
* use fixture to auto skip on error
* use team id and base url
* log stdout on install error
* use auto install in examples
* Retrigger CI
* use the same config for example and nightly reverse text
* do not use default interval in shared ckpt config
* match example
* add inference
* no lora in ci
* add hendrycks math
* update configs
* do not use commit hash as its recorded by wandb anyways
* use qwen 1.7b
* increase batch size
* add acereason
* add cron schedule
* name envs
* higher bs and no online filtering
* Split cpu tests into unit and integration and inject secrets
* Retrigger CI
* use util to check for error
* kill stray process (make containerized soon)
* try using docker setup
* Retrigger CI
* Retrigger CI
* set 24h timeout
* enable lora and no difficulty filtering in configs
* make lora work
* update wiki search configs
* update alphabet sort example
* disable ac
* use 4 train gpus hendrycks
* adjust configs from examples
* only eval aime24
* udpate acerason
* use 4 trainer, 4 inference for acereason
* bring back sep bc otherwise i dont see logs?!
* allow autosetup dp
* longer cleanup timeout period
* 200 steps alphabet sort
* clean exit on orchestrator
* revert changes to configs and examples unrelated to this pr
* no online filtering in wiki search example
* remove trigger to run nightly ci on pr against main [skip ci]
* fix running integration tests
* remove misplaced assert
* remove legacy test [skip ci]
* refactor models to dir and add conversion function
* move llama too
* fix qwen3 moe conversion tt -> hf
* use index 0 in the conversion
* add tests for qwen3 moe
* add tests for conversion
* fix position ids for HF
* fallback to for loop for non hopper
* fix: imports need cuda
* remove unused scripts
* fix default device and dtype at module level bad
* take out moe specific language
* fix tests
* fix missing cls
* use custom init buffers
* add back conversion test
* make max layer counting and looping simpler
* cover qwen with mlp case
* add tests for llama
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Previously, when the orchestrator resumed after hitting the max_async_level barrier, it scheduled only a single new group rollout. This caused the scheduler to enter a 'one-out, one-in' state, starving the inference server and collapsing throughput from ~20k to ~500 tokens/s.
This fix aggressively refills the inflight queue up to 'problems_per_batch' immediately after the barrier lifts, restoring full concurrency and throughput.
* Skeleton of syn data entrypoint
* Async gen and saving
* Properly merge reasoning content and save to results.jsonl
* Use output dir
* add configs
* Fix base url and use vf debug mode
* Always parse reasoning content
* less verbose vf logs
* Add skip first
* remove agent traces configs
* allow configuring reasoning content
* set default to oai
* add debug configs
* add comment
* use gpt41mini for evals by default as well
* autoinstall envs
* info and answer are optional
* rename configs
* minior
* explicit error msg
* install env on orch
* remove deprecated server type arg
* another one
* add section on synthetic data
* update eval docs and fix logprobs not defined against api models
* Fix up parsing length and finish reason
* shallow copy to avoid mutations
* fix skip first
* use exception
* add oai key
* Fix eval test
* add gsm8k configs
* fixes
* update hendrycks math configs
* fix hendrycks
* delete intellect math
* rename to use underscore
* update multi reverse text
* delete skywork acerason
* update acereason math
* remove skywork math configs
* use rl.toml for alphabet sort examle
* add rl toml to reverse text (but keep old way for k8s deployment)
* update wordle
* add local ranks filter
* use rl.toml for acereason
* translate deepscaler
* add new config test
* clear toml files if argv parsing fails
* small fixes in tests
* Deprecate logging distributions and disable logging extras on trainer
* also use in eval
* use either wandb monitor or wnadb with extras monitor
* fix config
* avoid blocking full orchestrator with sync waiting for stable file, add new async barrier
* make logging less verbose
* make level more understandable
* improve logging setup, only log waiting for trainer once, remove unecessary loggig in policy update. it essentially just waits for the checkpoint to arrive so its technically misleading
* update logs
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Return token IDs and prompt logprobs unconditionaly
* Remove parsing utils patches
* Bump vf
* Bump vf to be able to use logprob pydantic hotfix
* Change to rollouts per example
* First working run
* Make trajectory strategy configurable
* Fix branching rollouts converter
* Bring back computing advantages with our config
* Roll back compute advantages changse
* Fix unit test
* Truncate when preparing rl sample
* correct interleave rollout
* Never mask or zero truncated rollout
* Rework interleave trajectory and add tetsts
* Basic tests for client (need some more work)
* edit
* Update default sampling args
* revert changes on batch
* adjust everything to make it run
* Extract typing
* Bring back some logging
* add debug alphabet sort multi turn env
* show mismatches
* Remove assertions
* Do not put advantages in results df
* quick rl config
* set max seq len so that truncation computed
* Use smaller model bc 4b instruct is too good
* Export is truncated
* use deepseek distill
* add quick rl wiki search
* Bring back lora to fit on my little machnie
* Fix tests
* add utils and tests for serializing state
* add utils for serializing state and tests
* serialize state before saving buffer
* Less verbose warning
* add docs for strategy
* revert comment out
* bring back sample logging
* remove trajectory strategy from scheduler
* comment for jack
* correctly log rollouts
* log input ids as string
* Make client test gpu only
* Bump vf version to veresion on prime-rl branch
* use deepcopy
* allow logprob to be dict
* add missing prefix
* make evals work
* expose lora apis in client
* support lora in orchestrator
* fix: dumbest bug ever
* fix: dont unload because it will 404 inflight requests
* fix: dont crash without lora
* add full_weight prefix
* add dynamic lora tests
* run non lora and lora test separately
* use lora_name instead of load_lora
* have step in lora name so its less confusing when name ends with number
* fix: test should use lora name now
* do inplace update of lora adapter
* cleanup lora adapter after training
* TEMP: test scripts
* TEMP: script changes
* TEMP: parallel scripts
* TEMP: update meow.sh to use reverse text model
* dont unload weights in update
* fix ruff
* fix: save adapter separately moved
* support broadcasting
* Revert "TEMP: update meow.sh to use reverse text model"
This reverts commit 18326d48838fa2be4839190cd4cf84f45c294cae.
* Revert "TEMP: parallel scripts"
This reverts commit 1ca54b25f57d30679c8256abd4c01ae1949a3bec.
* Revert "TEMP: script changes"
This reverts commit 20fb5f33a979b873602ee058261531b6446d7b55.
* Revert "TEMP: test scripts"
This reverts commit 05631dec3398c782be8843ee23d8006916768bd8.
* drop unused merged weights
* remove unused counting
* remove unused stuff
* fix server in test
* fix ckpt saving for lora
* fix args in test
* print logs for easier debugging ci
* run lora one first to fail fast
* add logging to non lora test
* make output dir?
* Comment out LoRA adapter unloading logic
Comment out the unloading of the LoRA adapter in orchestrator.py.
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* make cursor bot happy
* dont unload for now
* restore original order
* add validation for adapter only
* change everything to adapter only
* have base broadcast config
* guard nccl broadcast from adapter_only
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* add basic helm chart based k8s support with reverse text example
* sleep once training completes instead of restarting
* cleanup k8s docs
* remove redundant logs
* nitpick on docs
* improve prime-rl example
* fix logic issue in examples
* additional readme perfectionism
* adjust get pods command
* removing nccl for now, will come back later with ib support for k8s
* apply valid k8s findings
* Change time.time() to time.perf_counter() where a time-span is being computed
* re-base from main, introduce perf_counter back in
* remove duplicate lines
* remove duplicate lines
* rename module to nccl
* Refawctorrr
* Ignore broadcast dir as well
* Cleaner
* Clean broadcast dir
* Only delete necessary dirs
* Turn off weight checkpointing by default
* Rename to broadcasts to avoid gitignoring
* Notify orchestrator at start of NCCL broadcast
* Ensure dir exists before writing file
* Put back sender-receiver interface zto be easy to test
* Change defaults
* Only save on master rank and optionally with LoRAs
* Only notify on master
* Also cleanup broadcast dir to avoid out of disk
* Lazily load cuda
* Fix attr not defined
* Deprecate weight ckpt manager
* Make trainer ckpt manager responsible of deleting ckpt directories
* Fix SFT trainer
* Use broadcast dir on resume
* Revert "Deprecate weight ckpt manager"
This reverts commit 3f5d0057e0527509fe135b383ff8858f3730b1b2.
* Revert "Fix SFT trainer"
This reverts commit 568013d4f9716be50b9cc14bb4c284c02e30430b.
* Use public attrs
* Keep broadcast dir with fs
* Organize imports
* Do write final steps to resume proper
* Remove unused func
* Also save model config
* Do not remove broadcast dir on resume
* Remove ugly backticks
* Make weight ckpt part of full ckpt
* Fix weight ckpt logic
* use sharded safetensors by default
* Make async save threadsafe
* Use async save by default
* Do not try joining current thread
* Wait for final thread in main loop
* Fix not saving intermediate dataloader
* Also cleanup from inside the weight ckpt manager
* Clean final ckpt as well
* Make ckpt cleaning thread save
* Only save weights on master rank
* Do not allow async saving of full ckpt (as before)
* Do not gather weights and adapters in thread
* Remove ability to async save again because it barely saves time
* minor
* Remove unused arg
* Do not validate runtime
* Fix wiki search toml
* Fix skywork acereasong config
* Add base config everywhere its possible
* Fix config
* Rename BaseConfig to StrictModel
* Remove debug stuff
* Bring back None string
* Revert "Rename BaseConfig to StrictModel"
This reverts commit 2f97620de8b83c5fcfac342040aade01034f120a.
* refactor buffers
* nicer
* Update buffer.py
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
* Mika/buffer refactor (#1280)
* Update orchestrator to use new buffer
* Export buffer metrics
* Deprecate has zero adv
* Update metrics export
* Fix pool count being wrong
* Simplify checkpoint logic
* Make sure we always log pool ratio across all pools
* Remove zero adv test
* Remove mean util function
* Fix ruff
* Use new buffer and autoinstall envs
* Use 128 val examples
* Deprecate old hendrycks configs
* Use correct names
* Less frequent val
---------
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Implement scheduler class with update loop and continuous batching
* Make runnable
* Update configs
* Change log and fix async barrier
* Bring back strict async level
* Make semaphore singleton
* Use the same timeouts on admin clients
* Fix tests
* Fix semaphore in evals
* Nicer start of loop log
* Fix
* Use None with conditionals to be able to set max_async_level=0
* Do not allow setting oversampling factor on online difficulty buffer
* Use example id from verifiers in buffer
* One more bump
* Fix buffer test
* Add hendrycks rl.toml
* fix
* Bump vf
* fix ckpt start (#1244)
* fix eval (#1254)
* use scheduler ckpt step everywhere and fix eval
* fix eval
* merge main (#1257)
* Remove continuous batching config (unused)
* Add paper links
* Use named tuple
* Remove debug logs from sampling from buffer
* Deprecate global std norm
---------
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
* Bump vf
* Do not wandb and difficulty pool buffer for debuggin
* More monkeypatches wooo
* Patch in correct order
* Move all patches to separate file to ensure proper isolation
* Format
* Revert configs
* Bump verifiers
* Add env mix config
* Update configs
* Update configs
* Skip evals
* Bump vf to use map_kwargs in env group format dataset
* Bump again
* bring back skywork
* add nccl worker vllm
* add nccl worker vllm
* add nccl broadcast dummy
* add nccl broadcast class
* add nccl broadcast class
* some fix
* some fix
* some fix
* finaly fix
* add proper weight update
* fix and add tests
* add timing nccl
* add async level error nccl
* add nccl broadcast param
* fix multi gpu trainer
* fix multi gpu
* fix tp inference
* fix rebase
* add dp support
* add dp support
* add dp support rl.py
* fix nccl update
* fix nccl update on all tp rank
* fix nccl update on all tp rank
* add still use stable file
* update worker
* debug log
* rename
* cahnge default port
* add which url failed (#1163)
* add mika uncommited line (#1162)
* add nccl timeout
* fix ckpt
* fix oom
* fix oom maybe
* add oom logsi
* add oom logs
* Revert "add oom logsi"
This reverts commit 7e8774f206b8720ad4afeebc36631ab4fa179d48.
* Revert "add oom logs"
This reverts commit 57dd0cc1b54730625d33f22d52f269b34916dfc8.
* fix tests
* refactor per state dict
* fix over stuff
* add moe support
* add cpu pin
* remove pin cpu
* remove pin cpu
* make more streamable
* fix smth
* fix smth
* cast before full tensor
* use + 1 in layers
* fix layer 10 issue
* fix comment
* fix async level
* IT SHOULD WOKR NOW AFTER SYNCING WITH MIKA
* Make NCCL beautiful (#1208)
* Minor cleanup on the infer server
* Align configs across all components and validate them
* Best effort warning that NCCL requires >=2 GPUs
* Remove confusing ckpt step log
* Always resume from latest ckpt
* Rename to env
* Move env specific configs into the right place
* Implement val spit and overlap train,val and eval
* Fix test
* Support multi-env training and evals
* Fix log
* Change orch config
* Multi env evals
* Move training semaphore out so that it is also used for evals
* Add multi-env train example configs
* Fix configs
* Minor
* Move seed
* Do not double validate a step
* Add multi env train/val/eval training example configs
* Make pbar description configurable
* Validate every interval
* Write batch before awaiting val and eval results
* Quicker evals
* Pin commit
* Do not limit concurrency by default
* Comment on future TODO
* Update configs
* skip ci for now
* Support multi-env training and evals
* Fix log
* Change orch config
* Multi env evals
* Move training semaphore out so that it is also used for evals
* Add multi-env train example configs
* Fix configs
* Refactor rollout type
* Use dataframe for metric computation and add task into rollout
* Log per env rewards
* Bump verifiers
* Fix tests
* Update configs
* Bring back old truncation logic
* Rename to val config
* Update wandb keys
* Update configs
* Minor config change
* Val step follows orch step
* Do not change example
* Only log val reward on interval steps
* Fix NCCL hanging on last steps
* Correct fix
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Rename to env
* Move env specific configs into the right place
* Implement val spit and overlap train,val and eval
* Fix test
* Support multi-env training and evals
* Fix log
* Change orch config
* Multi env evals
* Move training semaphore out so that it is also used for evals
* Add multi-env train example configs
* Fix configs
* Minor
* Move seed
* Do not double validate a step
* Add multi env train/val/eval training example configs
* Make pbar description configurable
* Validate every interval
* Write batch before awaiting val and eval results
* Quicker evals
* Pin commit
* Do not limit concurrency by default
* Comment on future TODO
* Update configs
* Support multi-env training and evals
* Fix log
* Change orch config
* Multi env evals
* Move training semaphore out so that it is also used for evals
* Add multi-env train example configs
* Fix configs
* Refactor rollout type
* Use dataframe for metric computation and add task into rollout
* Log per env rewards
* Bump verifiers
* Fix tests
* Update configs
* Bring back old truncation logic
* Rename to val config
* Update wandb keys
* Update configs
* Minor config change
* Val step follows orch step
* Do not change example
* Only log val reward on interval steps
* Support multi-env training and evals
* Fix log
* Change orch config
* Multi env evals
* Move training semaphore out so that it is also used for evals
* Add multi-env train example configs
* Fix configs
* Refactor rollout type
* Use dataframe for metric computation and add task into rollout
* Log per env rewards
* Bump verifiers
* Fix tests
* Update configs
* Bring back old truncation logic
* auto-infer infer dp if not set
* Remove stray wiki_search rl.toml to fix tests.
Tests expect only rl/train, orch, infer, or eval TOMLs under configs/examples. The single configs/wiki_search/rl.toml violated this convention and caused test_config to fail; removing it restores consistency.
* Add support for top-level rl.toml configs and fix DP inference detection.
- Teach tests to recognize rl.toml by adding RL to CONFIG_MAP and patterns.
- Restore configs/wiki_search/rl.toml sample.
- Improve RLConfig dp inference: detect explicit dp from TOML, not defaults.
- Skip GPU ID validation when no CUDA devices are available (CI/unit envs).
* fix auto dp
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
* Fix reverse text seq len
* Also fix in configs
* Also revert debug config to run faster
* Quicker reverse text sft
* more
* Match trainer path tests as well
* Fix multi-API server mode with import-time patching
Replace custom vLLM function implementations with import-time monkey
patching to support both single and multi-API server modes.
- Simplify server.py from 134 to 93 lines (31% reduction)
- Remove custom implementations (98 lines of duplicated vLLM code)
- Add _apply_patches() function with monkey patching logic
- Add platform check (Linux-only, fork semantics required)
- Add fork enforcement for multi-server mode
Tested on production hardware (2x NVIDIA H100):
- Single-API server mode (n=1): all endpoints working
- Multi-API server mode (n=2): all endpoints working
- Load distribution: 10/10 requests successful across workers
All 13 tests passed.
* Fix ruff import ordering
* Run ruff format
* Fix ruff import ordering in worker.py
* Fix ruff import ordering in server.py (add blank line before first-party imports)
* Do not allow partial loading to get explicit error
* Add weight utils for weight conversion
* Convert on the fly first attempt
* Make non master ranks for conversion
* Do not unsqueeze?
* No tqdm
* Do not warn on general mismatch
* Refactor save state dict format
* Fix dcp import
* Only sort if multiple shards
* Bump verifiers
* Adjust eval utils
* Fix default path
* Use different default path for online and offline evals
* Merge metadata
* Go back to manually inflating prompt list
* move client
* Move admin client
* Revert "Move admin client"
This reverts commit f31350cd3966eaebd8ba6a095a3c3fa5e53a1c3a.
* Implement round robin oai client + multi admin client
* Remove bench.py
* Assert the same api key var across all servers
* Move client config
* Working RL run with per-problem asynchrony
* Use verifiers problem IDs
* More concise
* Use multi-client in evals
* Still use base url
* Update verifiers
* Use own tqdm progress bar
* Progress bar over all rollouts
* Move utils to vf utils
* More defensive
* Fix tests
* kind of working
* dont allow sampling repeats
* add missing dist
* fix: index
* fix: create buffer once key is seen
* fix: eliminate weight update bottleneck with dedicated admin client
Problem:
During RL training with high concurrent rollouts, weight update operations
(update_weights, reload_weights) experienced 8-30 second delays before the
server received requests due to shared HTTP connection pool saturation.
Root Cause:
- Shared httpx client pool saturates with streaming inference requests
- HTTP/1.1 requires connections to be IDLE for reuse
- Thousands of active streaming connections = 0 IDLE connections
- Weight update requests queue waiting for available connections
Solution:
Create dedicated HTTP client for admin endpoints that bypasses the
saturated shared pool. Uses Connection: close header for one-shot
connections.
Implementation:
- Add _admin_client() helper function
- Update update_weights() to use dedicated client
- Update reload_weights() to use dedicated client
Impact:
- Weight updates: 8.58s → 55ms (155x faster under 4k concurrent streams)
- Zero queue delay under production load
- No impact on streaming workload
- Minimal code change (20 lines added)
* fix: add authentication and simplify admin client design
- Create setup_admin_client() mirroring setup_client() pattern
- Configure httpx.AsyncClient with base_url for simpler API
- Include Authorization header from client_config.api_key_var
- Simplify update_weights/reload_weights to only need admin_client
* use admin client in eval
* Revert orchestrator inflight stuff
* Use async wait for path everywhere
* Removed too much
* Revert buffer changes
* Use async client type directly
* go back to sync on rl trainer to properly cleanup
---------
Co-authored-by: Jackmin801 <ongjackm@gmail.com>
Co-authored-by: AmeenP <ameenp360@gmail.com>
Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
* Add more buckets in stack dataset
* More debug logs for model loading
* Increase timeout for setting up torch dist pg
* Dynamically compute more buckets
* Nicer log
* Rename logprobs and make recomputing only log the error and not replace the inference logprobs
* fix
* Replace importance ratio logging with the KL divergence between the trainer and inference logprobs
* Remove recomputing logprobs
* Fix logging and remove imports
* clean
* .
* Fix KL
* .
* clean
* clean
---------
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
* Make dataset strictly increasing again to use as proxy for total samples seen
* Fix tests and align step/index definition for fake data
* Fix multi-rank resume
* Only log if more than one subset/split
* Use iterable dataset in SFTDataset
* Fix import error
* Use less memory and clean up
* Fix tests
* Remove quotation marks agin
* Add info logs
* Back to default logs
* Resume explicitly
* Revert back to using regular dataset
* Fix skip (again lol)
* Make dataset strictly increasing again to use as proxy for total samples seen
* Fix tests and align step/index definition for fake data
* Fix multi-rank resume
* Only log if more than one subset/split
* Comment out index logging
* Support subsets
* Revert "Comment out index logging"
This reverts commit f2d842c5b35d42c100f60cc565b43b24f9452a68.
* Use interleave dataset for oversampling on the fly
* Pass probabilities
* Pass stopping strategy
* Make all exhausted the default
* Use dataset as iter and allow not processing for unit tests
* Add unit tests for epoch borders
* Break unit tests into two files
* Add detailed unit tests for SFT dataset
* Update fake dataset
* Fix all tests
* Fix calling setup dataloader
* Do not support max examples from configs
* Fix fallback if tools is None col
* Better fallback
* Rename loss mask
* Debug print yielded samples
* Fallback to fix test
* Remove redundant log
* First working version
* Use constants from transformers and adjust debug logs
* Minor
* Fix update weights call on resume
* Make it non breaking
* Rename symbols
* PEFT-compatible LoRA adapter saving
- adds a `save_adapter_separately` variable to the configuration
save_lora_config() produces a peft-compatible lora adapter config JSON, extracts + detects both the target lora modules (target_modules) & fully trainable modules (modules_to_save)
- weights.py has `_get_adapter_state_dict`, it only triggers when: `save_adapter_separately=True`, the process is master rank, and lora layers are found. this function transforms/serializes the keys to PEFT format. we specifically must add the .weight suffix to the A/B lora matrices, while the `base_model.model.*` prefix is added to everything that requires_grad (all trainable parameters) and is not None in `named_parameters()`
- adapters are saved to `{step}/lora_adapters/adapter_model.bin` and `adapter_config.json` via `_save_lora_adapters()`
- when setting up the weight ckpt manager, we raise ValueError if save adapter is set to True but LoRA is disabled
- both train.py scripts in SFT and RL paths pass the lora config to `setup_weight_ckpt_manager()`
* remove unused func, fix syntax
* PEFT-compatible LoRA adapter saving
- adds a `save_adapter_separately` variable to the configuration
save_lora_config() produces a peft-compatible lora adapter config JSON, extracts + detects both the target lora modules (target_modules) & fully trainable modules (modules_to_save)
- weights.py has `_get_adapter_state_dict`, it only triggers when: `save_adapter_separately=True`, the process is master rank, and lora layers are found. this function transforms/serializes the keys to PEFT format. we specifically must add the .weight suffix to the A/B lora matrices, while the `base_model.model.*` prefix is added to everything that requires_grad (all trainable parameters) and is not None in `named_parameters()`
- adapters are saved to `{step}/lora_adapters/adapter_model.bin` and `adapter_config.json` via `_save_lora_adapters()`
- when setting up the weight ckpt manager, we raise ValueError if save adapter is set to True but LoRA is disabled
- both train.py scripts in SFT and RL paths pass the lora config to `setup_weight_ckpt_manager()`
* remove unused func, fix syntax
* move validation to configs, minor cleanup
* export one big model safetensor
* support sharding safetensor for upload to hf hub
* convert moe to hf
* dont index 0 if we dont have degenerate dimension
* Empty commit
* Checkpoint local dataloader
* Checkpoint stack dataset state
* Fix tests
* Mark as GPU test again
* Fix key error
* Fix shuffling off by one
* Add model and optimizer hashes as debug logs
* add skip dataloader (#1041)
---------
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
* extract glm layers
* extract glm layers
* take out attention masks
* ruff stuff
* move rope in glm out
* cut more blubber
* remove some more unused args
* add qwen
* type hints
* refactor mlp
* fix some qwen kwargs and allow intermediate dim greater than hidden dim in attn
* rename custom models to models
* support none position ids
* add num layer
* add num layer
* add num layeri
* add num layer
* add paramters to allow random init
* add paramters to allow random init
* add paramters to allow random init
* make this a config
* fix name func
* fix name func
* add jacks comments
* Allow arbitrary seq len by letting final bucket be a non power 2
* Log dataset indexes
* 3 fixed bucket sizes
* Fix attribute missing
* Fix truncation condition
* Fix non-1 mbs which would make rl --bench command fail
* Begin docs rewrite
* Add image on framework arch
* Move configs into /examples and /experiments
* Add badges
* Write less paper-y
* Create log dir if it doesnt exist
* Fix typos
* Overhaul setup section
* Remove redundant info
* Move into /docs folder
* Ensure mbs=1 for fake RL data
* Fix custom client routes with base_url client config
* [WIP] Configs for wordle SFT and RL
* we're back
* Use double mbs on trainer
* Update wordle rl configs
* Update SFT config
* Update README
* Add async section
* Add benchmark
* Checkpoint into trainer subdir
* Add ckpt docs
* Add config
* Update troubleshooting
* Update environments
* Add evals
* Update los
* Add back MOE debug config
* Add MOE debug config to setup
* Add logs docs
* Move tests
* Add deployment section
* More contributing docs
* Do not use actual paths outside examples
* Move into entrypoint docs and rename some doc pages
* Latest
* Latest
* Finalize reverse text example
* Update wordle example
* Minor
* Remove old wordle configs
* Add link in wordle example
* Change config dir structure
* Fix test paths
* Fix config tests
* Fix reverse text dir name
* Fix broken links
* Fix integration test
* Disable weight ckpt config by default but autosetup if checkpointing
* Decouple full and weight ckpting
* Assert weight ckpt manager on rl trainer
* First ckpt weights, then full ckpt
* Add utility to print loss mask of a sample
* Implement loss mask by message type
* Remove debug prints
* Fix loss mask shifting
* Print example batch in debug mode
* Add unit tests
* Ruff
* Fix sft init
* More asserts
* Add test for multi turn tool call + support parallel tool call output
* Improve docs
* Skip overlong samples
* Skip only if no trainable tokens
* Better error msg
* Fix tests
* Switch MOE debug model
* Fallback to appending EOS token ID with warning print
* Allow local file logging
* Refactor logging utils
* Add file logging to RL entrypoint
* Rename tmux log streaming to avoid name clashes
* Fix tests
* Fix assigning singleton
* Deprecate utc
* Actually lets do color
* Log to file by default
* Fix tests
* Do not log from vllm server process
* Do not do file logging by default
* Revert "Do not do file logging by default"
This reverts commit d8395c904618f2c691872a362ae7c17a57ce3fbd.
* Clear log file
* Log all ranks to console by default and use torchrun to filter
* True by default
* Allow specifying device ids to run on single gpu
* Include `gpu_memory_utilization` in inference config
* Remove shared orch and inference config
* Change set -> list type
* Fix test
* fix: always fix rotary if they are in the buffers
* cover tt moe buffer case
* allow partial load again
* add option to log signature
* allow disabling meta loading
* dont compress signature
* support setting optimization dtype
* change default optim dtype to fp32
* torch_dtype -> dtype
* shard like tt fsdp
* add full graph compile
* add full graph compile
* Use None instead of enable for compile cnfig
* Add info logs for ac and compile
* (Revert later) Remove max_vio to run 30B-A3B
* Revert "(Revert later) Remove max_vio to run 30B-A3B"
This reverts commit 330048a362055b751a16de6c23eab4ac91d1f657.
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Include peak memory in step logs and benchmark table
* Fix step log
* Only use single digit precision
* Loss precision on SFT trainer
* Add peak memory to wandb history
* Report GiB, percentage of total and no std in table
* up vllm version and add tt deps
* remove monkeypatch for process logprobs
* no need for deps moe
* remove venv test
* we dont need the dual version in model loading anymore now that all is torch2.8
* dont use load dcp from hf
* add comment explaining bad load dcp line
* dcp loading from hf
* fix max vio PR
* fix: private import for torch 2.7
* dont support torch2.7 at all
* use snapshot download method which is much faster
---------
Co-authored-by: Ubuntu <ubuntu@denvrbm-2007.hou1.cloud.denvrdata.com>
* remove extra loss stuff
* remove extra loss stuff
* fix moe
* fix metrics
* fix model float
* Use custom reduction
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* remove float and continugous for faster and less memory usage
* Also use forward helper in sft trainer
* Cast to float on RL trainer
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Add gpqa
* Add livecodebench
* Bump datasets to v0.4.0 and update lock
* Add max_concurrent to eval
* Update livecodebench
* Add TAU-2 bench
* Use dataset to use verifiers info col parsing
* Add reasoning effort to eval sampling args
* Add SimpleQa
* Add HLE
* Bump vllm and openai
* Add BrowseComp
* Revert "Add BrowseComp"
This reverts commit 95ae3fbd06b65164f61e5425c88d872e609906ec.
* Fix for vLLM v0.10.1.1
* Update all eval envs
* Make env args a JSON string of list of dicts
* Revert "Make env args a JSON string of list of dicts"
This reverts commit 495c51e7e0695cd72731c78589ac67134a0ba71b.
* Implement push eval results to HF
* Allow only setting single value for all benchmarks
* Less verbose warnings + success log
* Fix type
* Align eval result dataset schema
* Also don't save info col
* Update LCB to v0.1.2.post0
* Normalize prompt and completion and split name for concat to work
* Update MOE deps
* Use run_evals util on orchestrator too
* Remove unused import
* Trigger CI
* Add back logprobs
* Resolve merge conflicts in moe deps
* Update refs and remove explicit index
* Bring back explicit index
* Update moe deps
* Update orchestrator.py
* extract properly(?), remove std, clean logs
* missed removal of one
* this didnt even respect the rubric weights i think
* standardize
* Use base url instead of host and port
* Pass api key as env var
* Catch route not found errors
* Remove unused helpers
* Add server type and prepare sampling args for oai or vllm server
* Do not compute completion len and truncated ratio for oai models
* Sav combined eval results
* Revert "Sav combined eval results"
This reverts commit f15bb1ada57a2cb81f644b3f6c9a0ff5158244e0.
* Minor fix
* Do not get logprobs by default in eval (not supported for some OAI models and we don't need it)
* Assert server type is vllm for RL training
* Change `api_key` to `api_key_var`
* Update README isntructions for changing port
* make it so that rl can be invoked from any directory if the user has installed the package, otherwise make it return an error if the user hasn't installed it AND the relative path src/prime_rl/trainer/rl/train.py does not exist
* untested but should be correct.
* Update rl.py
* Update rl.py
* Update rl.py
* remove max_model_len from inference config
* move infer.max_seq_len -> orch.sampling.max_tokens -- setting in infer is not robust for multi-turn and should be avoided in general
* support ep tp
* take parallel dims from torchtitan
* fix logger
* get back to what we previously supported [skip ci]
* duplicate data on non dp rank
* refactor parallel dims into training script
* take out debug prints
* implement pack functions
* guard stacking in cp
* add back sftdataconfig type annotation
* dummy context when no cp
* guard in rl because im lazy
* make simpler truncate loging in stackingdataset
* bucket timeout
* greedy combine and pad
* cover mesh dim 1 case
* why none instead of empty list?
* always have dp shard dim
* reverse ugly workaround
* Update src/prime_rl/trainer/sft/data.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* add support for Liger Kernel
* don't use Liger Kernel for loss
* Revert holdover changes to train.py from Liger Kernel loss compute
revert spacing
...
...
* move AutoModelForCausalLM to top of model.py
* remove Liger Kernel+GSPO validation check
* Simplify get_model with model_cls var
* Fix SFT dataloader checkpoint issue
- Add dataloader_state support to AppState
- Update CheckpointManager to handle dataloader state
- Fix SFT trainer to properly skip samples on resume
- Handle GPU count changes in checkpoint restoration
* Fix SFT dataloader checkpoint loading
- Add dataloader_state parameter to checkpoint loading
- Remove unnecessary hasattr check for _last_app_state
- Fix checkpoint loading to properly handle dataloader state
* Fix SFT dataloader checkpoint: simplify state_dict method and ensure dataloader state is always saved
* Fix SFT dataloader checkpoint: implement proper state management with public attributes
* Fix dataloader_state.update
* Fix: only save dataloader_state when not None
* Remove redundant shuffle_seed from data state
* Add SFT dataset tests
* Move tests
* Add num examples to data config for debugging
* Implement stateful dataset and dataloader + tests
* Change internal step definition to start at 0
* No clip debug log
* Print dataloader step in debug logs
* Update MOE deps
* Move loss test
* Remove backtick in log
* Correctly count total samples when packing
* Remove ckpt by default in sft
* Change valid batch<>world config and allow 2 ranks for SFT reverse text test
* Cleanup
* Correct condition
* Sami suggestion
* Add resume test for SFT dataset
* Fix bug in SFT dataset
* Rename RealDataConfig to SFTDataConfig
---------
Co-authored-by: baonudesifeizhai <baonudesifeizhai@gmail.com>
* fix: Change shared config key from --model-name to --model.name to align with module's configs
- Add ModelConfig class for shared model settings
- Replace model_name field with model.name structure in RLConfig
- Update auto_setup_model validator to use model.name
- Maintain backward compatibility with existing configs
- All tests pass (167 unit tests)
Fixes#840
* fix: Address review comments for model config consistency
- Change ModelConfig.name from str | None to str with default value
- Change RLConfig.model from ModelConfig to ModelConfig | None with None default
- Update auto_setup_model validator to check self.model is not None
- All tests pass (98 unit tests)
Addresses review comments from @mikasenghaas
* fix entrypoint in dockerfile
* set uv install to dir that is accessible to non-root users in builder stage
in the final stage of the dockerfile, the user is switched to "appuser",
which won't have access to the root dir. So if we want to use a non root
user at runtime, uv should be installed in a nonroot accessible
location.
* removing duplicate header in README
* Empty commit
* First working version
* Move unsharded state dicts into app state
* Use built-in async save
* Let the trainer ckpt manager handle deleting the step path
* Fix definition of last step to avoid double checkpoint writing
* Cleanup after final ckpt writing
* Put async save in rl.py config
* Initialize CPU and GPU default pg for async save to work
* Await async checkpoint writing on final checkpoint
* Move setup torch distributed into util function
* Deprecate async ckpt save
* Change token parsing ot operate on states
* Align flatten/nest logic with orchestrator + use tensor ops, report truncated ratio
* Remove double parentheses
* Eval with larger timeout
* Fuck it - crazy large eval timeout
* Fix ruff
* add requested type hint
* implement method to get active params
* add test to guard new flop counting behavior
* CI doesnt have torchtitan
* remove comment
* remove main in test
* guard gpu peak flop for tests
* fix: isolate meta device as default to just test perf counter context
* use proper prime environmentshub index instead of hardcoded urls
* add latest versions from hub
* fix typo on version - likely not the last typo here
* update lock
* fix uv lock
---------
Co-authored-by: Jannik Straube <info@jannik-straube.de>
* copy configs from 30b [skip ci]
* trust remote code everywhere
* add blobfile dependency used by moonlight tokenizer
* 16b configs
* EP working for moonlight but weights arent correct [skip ci]
* disable-recompute [skip ci]
* allow congiuring ep mode
* first mapping
* remap weights
* disable grouped mm
* revert changes to pyproject.toml
* revert changes to pyproject.toml [skip ci]
* trust remote code on tokenizer
* add torchtitan dep
* move configs
* change all Model type to nn.Module
* update moe impl
* up torch version to 2.8.0
* specify ep and fsdp mesh and separate path for qwen replacement [skip
ci]
* mesh here mesh there mesh mesh everywhere
* dont recompute logprobs
* use pre tt moe model
* remove conversion logic
* only do the ep parallelize when ep is enabled
* support grad norm for ep
* map weights before save
* use pi-flash-attn which has torch 2.8
* fix configs
* use ep instead of ep_mode
* keep a moe pyproject toml
* add torchtitan dep
* change model path
* best configs for 16b on 8xH200
* use flash for 30b
* disable ep because its not that stable
* fix: 16b configs
* add muon fsdp to moe pyproject
* uv lock
* lint
* remove ep code completely
* more robust conversion code
* index first tensor
* fix: stuff missed by merge;
* fix conversion for 16b
* add reverse text for 16b
* update moe pyproject toml
* fix: imports and ruff
* fix: refactor ac
* fix: rollouts_per_prompt -> rollouts_per_example
* fix: more key fixes in configs
* add post hook map
* fix configs
* patch right into the rl config check
* fix: remove duplicate
* deps/moe
* uv lock for moe venv
* fix: warning about device set
* fix: specify cuda device
* deleted environments in prime-rl
* install envs via environment hub
* update readme on how to install envs
* Redo lock file
* Update all packages and add eval envs
* Update all eval envs
* Fix outdated eval docs in README
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Save eval samples and metrics as JSON report
* Only report completion len in artifact but not to W&B
* Move save to base eval settings, slightly adjust signature
* Use step path here too
* Add eval subdir to gitignore and cleanup
* Add info print
* Setup but not use monitor
* More precision on printout
* Save by default if eval enabled
* use verifiers for evals (draft)
* type warning fix
* update config
* config updates
* use a_generate for evals
* update skywork configs
* refactor for maintaining eval.py pathway, misc config tweaks
* config cleanup
* move offlineevalconfig to eval section
* revert eval freq for hendrycks config
* remove assert
* remove typecheck
* Create new lockfile after rebase
* Warn if eval dataset not found
* Allow running with defaults sampling args (#726)
* Port old math500 eval logic to vf env
* Do not pass parser and debug prints
* Disable sampling args
* Update to use math verify (reproduces current main)
* Adjust to question answer interface
* Fixed MATH-500 env
* Allow default sampling configs in eval
* Remove alternative venv
* [TMP] Update verifiers to PR commit with updated think parser
* Update math rubric in hendrycks-math
* Port intellect math env to use math rubric
* Also keep solve rate field around
* Hotfix bug in hendrycks math dataset
* Write solve rate in info col
* Update verifiers pin
* Fix lock file
* Change name to config key to environment_ids
* Change config key in config files too
* Fix pydantic validation
* Fix environment IDs in offline eval script
* Rename to environment args
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Fix key errors in print benchmark
* Fix yield
* Improve fake data print
* Only print benchmark on master
* Remove wrong type (jax files if we compile)
* Also report MFU in benchmark table
* Do not log extras or ckpt on benchmark
* Less verbose benchmark warning
* Fixed length fake data
* Comment out non-compute and add timing logic
* Revert "Comment out non-compute and add timing logic"
This reverts commit f99f5537266342e9deb5f7df3d71d3d670527633.
* Add variable or fixed length data config
* Bring back partial ac
* Update bench docs
* Update configs to fix tests
* Simpler type
* Small fix
---------
Co-authored-by: Ubuntu <ubuntu@g386.voltagepark.net>
I think this is supposed to be `sft.toml` not `train.toml`
BEFORE (error):
```
[jrcummings@devvm4767.pnb0 ~/projects/prime-rl (main)]$ uv run sft @ configs/debug/train.toml
Traceback (most recent call last):
File "/home/jrcummings/projects/prime-rl/.venv/bin/sft", line 10, in <module>
sys.exit(main())
^^^^^^
File "/home/jrcummings/projects/prime-rl/src/prime_rl/trainer/sft/train.py", line 274, in main
train(parse_argv(SFTTrainerConfig))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/jrcummings/projects/prime-rl/src/prime_rl/utils/pydantic_config.py", line 269, in parse_argv
config = config_cls(_cli_parse_args=to_kebab_case(cli_args))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/jrcummings/projects/prime-rl/.venv/lib/python3.12/site-packages/pydantic_settings/main.py", line 188, in __init__
super().__init__(
File "/home/jrcummings/projects/prime-rl/.venv/lib/python3.12/site-packages/pydantic/main.py", line 253, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 2 validation errors for SFTTrainerConfig
data.fake
Input should be a valid boolean [type=bool_type, input_value={'batch_size': 16, 'micro...ize': 8, 'seq_len': 128}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.11/v/bool_type
async_level
Extra inputs are not permitted [type=extra_forbidden, input_value=5, input_type=int]
For further information visit https://errors.pydantic.dev/2.11/v/extra_forbidden
```
AFTER:
```
[jrcummings@devvm4767.pnb0 ~/projects/prime-rl (main)]$ uv run sft @ configs/debug/sft.toml
11:36:35 INFO Starting SFT trainer in World(world_size=1, rank=0, local_rank=0, local_world_size=1, num_nodes=1)
11:36:35 INFO Initializing monitor (file=disabled, socket=disabled, api=disabled, wandb=disabled, system_log_frequency=0)
11:36:36 INFO Initializing model and tokenizer (name='PrimeIntellect/Qwen3-0.6B' attn='flash_attention_2' compile=False ac=False reshard_after_forward=True)
You are attempting to use Flash Attention 2.0 without specifying a torch dtype. This might lead to unexpected behaviour
You are attempting to use Flash Attention 2.0 with a model not initialized on GPU. Make sure to move the model to GPU after initializing it on CPU with `model.to('cuda')`.
11:36:39 INFO Initializing optimizer (lr=0.0004 weight_decay=0.01 max_norm=1.0 type='adamw' betas1=0.9 betas2=0.999)
11:36:39 INFO Using `constant` scheduler (type='constant')
11:36:39 INFO Starting from step 0 (total_tokens=0, total_samples=0)
11:36:39 INFO Initializing dataset (name=PrimeIntellect/Reverse-Text-SFT, split=train)
11:36:39 INFO Initializing dataloader (micro_batch_size=8, batch_size=16, collate_mode=packing)
11:36:39 INFO Starting training loop (config.max_steps=5)
NCCL version 2.26.2+cuda12.2
11:36:43 WARNING Peak FLOPS undefined for `NVIDIA PG509-210`. Falling back to A100 (312 TFLOPS)
11:36:43 SUCCESS Step 0 | Time: 3.51s | Loss: 14.3244 | Accuracy: 0.0000 | Grad. Norm: 80.9217 | LR: 4.00e-04 | Throughput: 0 tokens/s | MFU: 0.0%
11:36:44 SUCCESS Step 1 | Time: 0.90s | Loss: 12.5202 | Accuracy: 0.0000 | Grad. Norm: 65.4769 | LR: 4.00e-04 | Throughput: 2264 tokens/s | MFU: 2.0%
11:36:44 SUCCESS Step 2 | Time: 0.74s | Loss: 12.7759 | Accuracy: 0.0000 | Grad. Norm: 27.9819 | LR: 4.00e-04 | Throughput: 2485 tokens/s | MFU: 2.1%
11:36:45 SUCCESS Step 3 | Time: 0.75s | Loss: 12.4309 | Accuracy: 0.0000 | Grad. Norm: 9.1706 | LR: 4.00e-04 | Throughput: 2561 tokens/s | MFU: 2.2%
11:36:46 SUCCESS Step 4 | Time: 0.81s | Loss: 12.1576 | Accuracy: 0.0000 | Grad. Norm: 4.5774 | LR: 4.00e-04 | Throughput: 2553 tokens/s | MFU: 2.2%
11:36:46 INFO Peak memory: 13.47 GB
11:36:46 SUCCESS SFT trainer finished!
```
Signed-off-by: Joe Cummings <jrcummings27@gmail.com>
* add muon
* update to pypi pakcage
* apply suggestion
* apply suggestion
* apply suggestion
* Use type alias for discriminator field
* Revert last commit lol
* Use setup function on SFT trainer
* Fix type import
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Make session wide outputs dir which is auto-cleaned
* Cleanup tmp outputs dir in CI directly
* Fix type and do less SFT steps in integration test
* Also use outputs dir for orch test
* Empty commit
* Move RL specific trainer into submodule
* Copy over train script
* Extract shared and RL-specific configs
* Functional SFT script
* POC training run on simple text data
* Update defaults
* Implement SFT dataset
* Use bool dtype everywhere
* Use function CE and views for flatten + expand
* Compute and log token accuracy
* Fix tests
* Remove uncessary line
* Make SFT epoch and rank aware
* Add weight ckpting to SFT
* Fix tests
* Some cleanup
* Add SFT config
* Add SFT CI test
* Also weight ckpt on final step
* Do not allow infinite training on SFT trainer
* Adjust configs and environment
* Use SFT checkpoint in RL integration test
* Add SFT section
* Rename to name
* Add collate mode to data config with dummy packing
* Move padding and truncation into collate func
* Implement packing as offline dataset
* Fix ruff
* Fix integration test + flatten dir structure
* Set env and timeout
* Fix loss mask not bool
* feadd packing smai way
* feadd packing smai way
* add debug
* add padding
* add workd handler
* Some small refactors
* Split setup dataset and dataloader
* Add dataloader to ckpt
* Export epoch information (ugly)
* Update src/prime_rl/trainer/config.py
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* Update src/prime_rl/orchestrator/config.py
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* Remove unused import
* Do not ckpt dataloader (yet)
* Adjust debug SFT configs
* Remove dataloader import
* Checkpoint into tmp directory to save disk
* Fix scoping problem
---------
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
* Add test for resuming run
* Don't double save final checkpoint
* Add underscore for fixture
* Use shared config keys
* Tryna be too smart
* Return the actual project
* Type hints
* Remove path configs
* Change path definition in ckpt and weight ckpt manager
* Add outputs_dir to trainer and orch config and pass to ckpt managers
* Remove exp_id, use output dir in batch loading/ writing, change validation
* Fix some more paths
* Update gitignore
* Interactive cleanup for safety
* Discriminate session name and outputs dir in tmux.sh and use outputs by default
* Update README
* Remove configurable wandb path
* Extract shared path definitions
* Rephrase multi-exp per node section
* Fix tests
* Remove wandb dir
* Also remove wandb dir
* Fix fake rollouts integration test
* Minor comment change
* Fix attribute not defined
* Unify the definition of shared configs in rl.py
* Do not allow to set UTC shared
* Revert "Do not allow to set UTC shared"
This reverts commit d14b06f214738d9867c6f9309c3127b9fdb1e802.
* Log config is RL config
* Add W&B section
* Fix typos and inconsistencies
* Add pydantic validation
* Fix missing infer server
* Fix type err
* Log distributions and samples in RL CI
* Fix wandb setup in CI:)
* Refactor config tests into single file
* Extract shared config validation and add unit test
* Fix wrong shared configs
* Fix import error
* Move orch integration test into correct folder
* Fix orchestrator test hanging
* Remove unncessary del
* Remove temp scaling
* Set default logprobs_mode and raise if set different
* Patch sampler to apply temperature before exporting processed logprobs
* Monkey-patch properly
* Bump vllm to v0.10.0
* Run vllm server and allow running in headless mode
* Custom vLLM v0.10.0 server
* Use built-in reload_weights and rename routes
* Fix eval
* Implement generic log distributions (WIP)
* Log dists from orchestrator
* Log distributions from trainer
* Make table logging info level
* Log final distributions on trainer and log tables after the other metrics on orch
* Empty commit
* POC for tensor metrics
* Also log (unmasked) tensor numel
* Dont write back logprob err into micro batch
* Remove train and infer from perf keys
* More detailed orch logs
* Fix recomputed logprob err log
* Also log sum of prompt/completion/seq len
* Debug lovely tensors on trainer
* Fix type
* Do not log train/orch in timing wandb keys
* Change clip loss too and fix unbound var
* Align jaxtypes, remove _masked_sum helper, don't reduce entropy
* Fix grad norm averaging
* All reduce total token loss scale
* Add assert, make micro metric comp padding safe, don't full tensor on grad norm
* Fix assert
* Log grad norm in console
* Bring back full tensor and sum all reduce loss
* Remove all reducing loss and ruff
* Revert to using local loss scale
* Temporarily bring back sum and numel
* More asserst and log logprob tensor itself
* Log debug tensors for first micro batch
* Rename to old_logprobs and log as well
* Refactor loss inputs/outputs and apply bool mask
* Remove debug logprob save
* Less strict assert
* Remove unused class
* Refacto tensor metrics
* Rename back to importance_ratio
* Correct recompute logprob shape
* More informative assert
* Don't log sum and std of seq lens
* Don't log sum and numel
* Allow for custom reduce ops
* Remove adv metrics
* Log sum and mean for is clipped
* Mean reduce seq len tensors before computing min/max/mean
* Do not log min/max rewards
* Mean reduce later to have correct token count
* Fix loss unit tests
* 2 proposal
* Rename to loss
* Remove sections and update jax return type
* Detach before updating
* Refactor tensor metrics to tensors
* Add comment
* Align micro step debug logs with main step logs
* Fix loss unit test
* Use batch,seq,vocab for jax dims
* Implement generic log distributions (WIP)
* Revert "Implement generic log distributions (WIP)"
This reverts commit 442c0409e77fcc35d66d4d67ec114865b4f8f32f.
---------
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
* remove div by temp
* Revert "remove div by temp"
This reverts commit f6f63cd5fcff8e6f30047ff1100357ef5545fa9a.
* add if statement temp
* add temperature scaling logprob
* fix temp
* Remove conditional
* Move temperature scaling to batch preparation
* Small refactor
* Remove min_p, top_p, top_k on trainer, isolate sampling arg to eval
* Set default values for top_p, top_k and min_p to avoid issues with default sampling args in vllm
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* reorganize config files
* update readme
* wrong nested structure
* remove main folder
* fix test config
* fix tests
* Start test inference server correctly
* Delete model eval configs and move debug eval
* Fix eval debug name and test config file paths
* Move skywork math 7b and 32b in config subdirs
---------
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* linear, cosine lr schedulers
* linear, cosine lr schedulers
* fix naming + misc things
* missed one
* fix wsd decay logic i think
* keep fallback
* refactor lr schedulers with pydantic validation + more
* save scheduler state dict in ckpt
* remove pointless conditionals
* Warn instead of info
* Default oversampling factor and only request missing problems
* Log performance from orchestrator loop
* Do not oversample by default
* Lock change (?)
* Save checkpoints in experiment dir
* Do not save ckpt on first step
* Write ckpt at final step
* Only adjust ckpt path if available
* Move data pool
* Rename data to batch
* Use discrimnated union for config and setup skeleton pools
* Copy over orchestrator file from main
* Implement default pool
* Add docstrings for base and default pool
* Implement online data filtering
* Assert batch size rollouts are passed to trainer
* Implement low-high priority pool
* Fix tests
* Use type alias
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
* Remove comments
* Rename to simple pool
* Use default list type
* Rename to buffer
* Improve class docstrings
* Add unit tests for simple buffer
* Add unit tests for priority pool and align epoch definition with simple buffer
* Add unit tests for online difficulty buffer
* Remove epoch definition from orchestrator loop
* Pre-shuffle dataset
* Switch to random sampling
* Rename to difficulty pool and dfine easy, normal and hard
* Fix unit tests
* Make difficulty pool decision rule configurable
* Compute advantage stats on accepted rollouts
* Minor change to log
* stupid lol
* Fix handling env outputs
* Use result rewards and do not zero truncate rollouts
* Revert "Use result rewards and do not zero truncate rollouts"
This reverts commit cb67d9da13b4c4b31cc26efc23126be9dab0efc2.
* Revert "Fix handling env outputs"
This reverts commit 4900ee0df4593e464a5ed87551cdc7ccbb9f045b.
---------
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
* Revert "Add zero logprob to all but first packed sample"
This reverts commit b2ca19e4bec9d858072c4412c872c42468b027b9.
* Add zero logit/logprob on trainer and orchestrator
* Move some code around to make it cleaner
* Fix import error
* Make clear when shifted logits are used
* Fix unit test
* Fix fake data loader dim mismatch
* Let garbage collection handle it?
* Fix dummy batch
* Do not clone on already detached values
* Create zero matrix on right device and with right dtype
* Delete logits after shifted
* Move back stuff from model.py to loss.py
* Correct order for easier diffs
* Use nightly test index
* Add section on supported architectures
* add b200 mfu
* fix b200 number
* Add additional comment
---------
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
* Restructure/word README
* Use host port client args
* Allow creating multiple experiment sessions
* Use experiment identified shared file system
* Fix eval setup
* Use rl experiment by default
* Fix ruff
* MInor adjustments to README
* Deprecate W&B group for run name
* Set -bench suffix in subconfigs
* Disable evals directly in orchestrator
* Deepcopy prefix
* Scale num micro batches by world size
* Only do 3 bench steps
* Do not set suffix wandb project
* Fix orchestrator benchmark
* Fix typo
* Implement trainer benchmark
* Implement bench model from rl.py
* Disable evals, sample logging and overwrite fake data
* Do not overwrite group
* Add docs
* updated parser, falling back to i-math parsing
* data filtering fix
* Check is not None
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* add tmunxinator
* use loguru instead of log
* Clean up tail process
* use loguru instead of log
* update readme
* fix .log
* Update README.md
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Update README.md
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Do not pass values that are defaults anyways
* Catch and reraise errs to display stderr
* Nicer error log
* Add back color
* Remove debug raise
* Log to one stdout file
* Alllow partial path updates
* Exclude toml files from serialization
* Working RL training entrypoint
* Use tmuxinator as skeleton
* Log samples on debug RL run
* Move install script
* Move orchestrator one dir level up
* Log samples only as part of CI
* Renmae training -> trainer and infer -> inference endpoint
* Adapt rl.py to new trainer def
* Make inference optional
* Rename trainer logs
* Add rl entrypoint
* Allow to restart experiments from within tmux sesion
* Remove sidecar
* Misc
* Implement local device auto-placement
* Make orchestrator info logs slightly more informative
* Do not log start cmd
* Even better orchestrator logs
* Improve trainer logs
* Install tmuxinator
* Clean and setup logging from rl
* More nice logs
* Only clean up log files
* Tie async level
* Fix parallel bug
* Add docs
* Remove log configs at start
* Use torchrun for trainer
* Fix tests and make rl test and integration test
* Bubble up subprocess exceptions
* Set eval config path
* Pipe outputs
* Fix RL CI run
* RL shows trainer streams trainer logs
* Fix tests
* Fxi integration test
* Implement toml subconfigs
* Update configs, README and test with TOML subconfig passing
* Log inference output to file to prevent server hanging
* Update README
* Do not echo for cleaner tmuxinator open
* Use space in between @ and toml
* Fix wrong config path
---------
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
* Fix type
* Implement weight ckpt manager
* Move weight ckpt cleanup into weight ckpt manager
* Make cleanup async
* Save ckpt at beginning of step
* Decouple step path definitions
* Move past step definition in function
* Extract non-ckpt util function
* Implement train ckpt manager
* Fix create ckpt path as dir
* Do not ckpt at step 0
* Change ckpt name
* Fix ckpt step path
* Save correct progress state at correct step
* Auto-setup max steps
* Do not clean by default
* Misc improvements to trainer ckpt
* Implement orchestrator ckpt
* Use same stop condition logic across trainer + orchestrator
* Use correct logprob model when resuming
* Use resume step instead of path
* Cleanup
* Resume with async
* Init optimizer before load from ckpt
* Ensure resume step at least 1
* Load the async logprob model from weights checkpoint
* Save pytorch model HF compatible
* Load all async logprob models
* Fix start ckpt_step
* Save all async logprob models correctly
* Fixes to async resume logic
* Enable resuming a W&B run
* Off by one
* Implement async save
* Disable ckpt by default
* Remove ckpt getter
* Fix type
* Fix keeping async weight ckpts for restart
* Remove description
* Only clean if not resume
* Docs
* Increase default seq len to avoid overlong prompt error
* Mirror log level
* Set more resilient http defaults
* Use public post/get requests instead of private _client
* Tokenize synchronously
* Use OAI async client correctly for custom routes
* Correctly cast the tokenize response
* Use envs to disable vllm logging on orchestrator
* add 7b simple math config (#525)
* add 7b
* add 7b
* fix timeojut
* add 7b
* remove alias for reshard after forward
add math config
add math confi
* use inheritance for 7b
* Implement timing and logging blocking time
* Fix unbound variable
* Fix unused variable (should i update my pyright configs)
* Coding is hard (my type checker would have caught that)
* Rename key
* Inherit wandb project name
* Fix test
* Use group name in RL debug
* change to server and add training prefix to train.py
* Adjust debug configs
* Update README
* Do not wandb log by default
* Run debug run for 30 steps
* Separate tests and config docs
* Minor spelling stuff
* Move dev stuff into contributing
* Move back contributing to readme
* Remove level stuff
* Remove contributing
* Remove pre commit from main install
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* educe vllm logs in tests
* Fix bug in run_benchmark
* Do not limit model len
* Kill trainer if orchestrator dies
* Increase e2e timeout
* Improve async client resilience
* Only raise if orchestrator died with exit code 1
* Fix ruff issues
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Fix types
* Implement W&B sample logging from monitor class
* Remove old util function
* Change config key and only copy project and group over
* Log samples by default if wandb enabled
* Do not duplicate configs to sidecar
* Reduce log verbosity
* Debug log if log to W&B tbale
* Adjust reverse text config
* Change defaults
* Log less for reverse text task
* show advantages
* show advantages
* Rename wandb keys, log mean and std for reward + adv
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Remove old configs
* Bring back CI markers
* Fix train integration tests
* Fix inference integration test
* Integration tests
* Implement integration and e2e with persistent inference server
* Fix config tests
* Delete old inference unit tsets
* Fix train unit tests
* Add ruff as dev dep
* Add pre-commit as dev dep
* Fix ruff errors (removed deepcoder utils)
* Install with all extras
* Directly install with all extras
* Add setuptools
* Add setuptools as regular dep
* Fix installation comand
* Move deps
* Change uv sync in dockerfile
* Add cleanup script
* Fix import error
* Free more mem
* Fix type
* Reduce mbs to lower mem footprint
* move clean to script
* add simple math inference config
* add simple math training config
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* Enable logging to file
* Don't log E2E test to W&B by default
* How to start in training + orchestrator sidecar and stream file logs
* Use logs/eval path by default
* refactor move padding to own files
* refactor move collate_mode to orchestator
* refactor allow padding and not padding sample process
* riase error of truncate
* add sequence packing
* Fix rebase issues
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* First draft train configs (not running)
* Rename orchestrator data configs
* Cleanup trainer
* Refactor activation checkpointing
* Simplify logprob recomputation
* Clean up metrics averager
* Rename world info to world for brevity
* Remove explicit batch loss
* Move grad norm to loss config and improve timing metrics
* Remove reward server
* Bring back perf counter
* Bring back fake data loader and debug train config
* Move util functions away from entrypoint script
* Remove legacy code
* Final cleanup in train configs
* Allow training sync with buffer size
* Remove old code
* Use alias for reshard
* Move compute logprobs func
* Move fsdp and ac into model file and simplify setup logic
* Remove unused code
* Remove seeding on trainer
* Renamed back to input_ids
* Remove buffer size and renamed to async_level
* No config inheritance;((
* add interface for data
* add data packing from orchestrator
* Fix default seq_len and micro_bs
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Any PR that modifies configuration structures or usage patterns must update `CHANGELOG.md`. This includes changes to config fields (added, removed, renamed, moved, or default value changes) in:
-`src/prime_rl/*/config.py`
-`src/prime_rl/rl.py`
-`src/prime_rl/utils/config.py`
If such changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
- 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)
PRIME-RL is a framework for large-scale asynchronous reinforcement learning. It is designed to be easy-to-use and hackable, yet capable of scaling to 1000+ GPUs. Beyond that, here is why we think you might like it:
1. Integrates natively with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments via the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars)
2. Supports end-to-end post-training, including SFT and RL training and evals
3. Multi-node deployment with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) training and [vLLM](https://github.com/vllm-project/vllm) inference backend
4. Designed for asynchronous agentic RL training at scale
5. Hackable, modular and extensible by nature
## Setup
> *We develop and test on NVIDIA RTX 3090/4090/5090, A100, H100, H200, and B200. If your setup fails, please create an [issue](https://github.com/PrimeIntellect-ai/prime-rl/issues).*
### Prerequisites
Currently, you **need at least one NVIDIA GPU to use PRIME-RL**. If you don't already have access to one, we recommend our [compute platform](https://app.primeintellect.ai) for everything from renting on-demand single GPUs for developing, debugging and small ablations, to [reserving 1000+ GPU clusters](https://app.primeintellect.ai/dashboard/quotes) for production-scale training.
3.Set up the environment (will default to Python 3.12)
3.Install dependencies from the lock file
```bash
uv sync && uv sync --extra fa
uv sync --all-extras
```
You can check that `flash_attn` is installed correctly by running `uv run python -c "import flash_attn"` and ensure no error is thrown.
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
4. Precommit install
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`
3. Check that you can run SFT trainer (*this requires 1 GPU*)
```bash
uv run sft @ configs/debug/sft/train.toml
```
4. Check that you can run the RL trainer (*this requires 1 GPU*)
```bash
uv run trainer @ configs/debug/rl/train.toml
```
5. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference @ configs/debug/infer.toml
```
*Keep the inference server running in the background for the next steps.*
5.1. Check that you can run the orchestrator against the inference server
```bash
uv run orchestrator @ configs/debug/orch.toml
```
5.2. Check that you can run evals against the inference server
```bash
uv run eval @ configs/debug/eval.toml
```
</details>
### Additional Setup
1. If you want to log your runs to [W&B](https://wandb.ai), log in
```bash
uv run wandb login
# Or set `export WANDB_API_KEY=...`
```
2. If you require gated/ private models or datasets from [HuggingFace](https://huggingface.co), log in
```bash
uv run hf auth login
# Or set `export HF_TOKEN=...`
```
## Training Examples
We provide end-to-end training examples in the [`examples`](examples) directory to highlight features of the framework and guide you through the process of training your own models.
1. [**Reverse Text**](examples/reverse_text/README.md): Train `Qwen3-0.6B` to reverse a small chunk of text. Demonstrates tiny-scale single-turn SFT and RL training. Can be trained on a single consumer GPU in a few minutes, and is ideal for getting started.
2. [**Wordle**](examples/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/alphabet_sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/wiki_search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/hendrycks_sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
*More to come...*
## Docs
Check out the [docs](docs) directory for in-depth guides on how to use PRIME-RL.
- [**Entrypoints**](docs/entrypoints.md) - Overview of the main components (orchestrator, trainer, inference) and how to run SFT, RL, and evals
- [**Configs**](docs/configs.md) - Configuration system using TOML files, CLI arguments, and environment variables
- [**Environments**](docs/environments.md) - Installing and using verifiers environments from the Environments Hub
- [**Async Training**](docs/async.md) - Understanding asynchronous off-policy training and step semantics
- [**Logging**](docs/logging.md) - Logging with loguru, torchrun, and Weights & Biases
- [**Checkpointing**](docs/checkpointing.md) - Saving and resuming training from checkpoints
- [**Benchmarking**](docs/benchmarking.md) - Performance benchmarking and throughput measurement
- [**Deployment**](docs/deployment.md) - Training deployment on single-GPU, multi-GPU, and multi-node clusters
- [**Troubleshooting**](docs/troubleshooting.md) - Common issues and their solutions
## Contributing
We warmly welcome community contributions! We use [issues](https://github.com/PrimeIntellect-ai/prime-rl/issues) to track bugs, feature requests, and share our internal roadmap. If you encounter bugs, have pain points during development, or have ideas for new features, please open an issue.
Contributions are welcome via PR. Please follow these guidelines:
1. Install the [pre-commit hooks](#pre-commit-hooks) to ensure your code is formatted correctly.
2. Please keep your PR in "Draft" until it is ready for review.
3. If your PR resolves an issue, please link the issue in the PR description
4. If you can, try running the [test suite](#tests) locally to ensure your changes are working as expected.
### Pre-Commit Hooks
Please install the [pre-commit](https://pre-commit.com) hooks to ensure your code is formatted correctly.
```bash
uv run pre-commit install
```
6. debug run
training
```bash
uv run torchrun --nproc_per_node=2 src/zeroband/train.py @ configs/training/debug.toml
```
inference
```bash
uv run python src/zeroband/infer.py @ configs/inference/debug.toml
```
## Simple Math Run
This debug run trains `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` on the `justus27/math-hendrycks-genesys-format` dataset using separate inference and training processes.
Depending on the number of available GPUs, we have to adjust the number of generated samples on the inference workers to match the batch size of the training process.
Training samples per step: `batch_size * step_per_rollout`
Inference samples per step: `batch_size * dp`
If you have 2 GPUs, run the following commands:
```bash
# Start inference worker
exportCUDA_VISIBLE_DEVICES=0
exportVLLM_WORKER_MULTIPROC_METHOD=spawn
uv run python src/zeroband/infer.py @ configs/inference/simple_math.toml --parallel.dp 1 --max-batch-size 512
```
```bash
# Start trainer
ulimit -n 65536
exportCUDA_VISIBLE_DEVICES=1
uv run torchrun src/zeroband/train.py @ configs/training/simple_math.toml
```
If you have 4 GPUs, run the following commands:
```bash
# Start inference workers
exportCUDA_VISIBLE_DEVICES=0,1
exportVLLM_WORKER_MULTIPROC_METHOD=spawn
uv run python src/zeroband/infer.py @ configs/inference/simple_math.toml --parallel.dp 2 --max-batch-size 256
```
```bash
# Start trainer
ulimit -n 65536
exportCUDA_VISIBLE_DEVICES=2
uv run torchrun src/zeroband/train.py @ configs/training/simple_math.toml
```
If you have 8 GPUs, run the following commands:
```bash
# Start inference workers
exportCUDA_VISIBLE_DEVICES=0,1,2,3,4,5
exportVLLM_WORKER_MULTIPROC_METHOD=spawn
uv run python src/zeroband/infer.py @ configs/inference/simple_math.toml
```
```bash
# Start trainer
ulimit -n 65536
exportCUDA_VISIBLE_DEVICES=6,7
uv run torchrun --nproc_per_node=2 src/zeroband/train.py @ configs/training/simple_math.toml --data.num_workers 2
```
## 2k seq length run
on two different terminal do:
```bash
exportCUDA_VISIBLE_DEVICES=0,1,2,3,4,5
exportVLLM_WORKER_MULTIPROC_METHOD=spawn
uv run python src/zeroband/infer.py @ configs/inference/deepscaler.toml
```
then start the trainer
```bash
ulimit -n 65536
exportCUDA_VISIBLE_DEVICES=6,7
uv run torchrun --nproc_per_node=2 src/zeroband/train.py @ configs/training/deepscaler.toml
```
if running on h100 node instead of H200 you should add ` --train.micro_bs 4`
## Distributed inference
Inference supports running in multi-node multi-GPU setups supporting DP, TP and PP, and sensible combinations of these.
Below are examples of how to run inference for different parallelization strategies.
Single Node (DP=1, TP=1, PP=1, *requires 1 GPU*)
```bash
CUDA_VISIBLE_DEVICES=0 uv run python src/zeroband/infer.py @ configs/inference/debug.toml
```
Only TP (TP=2, PP=1, DP=1, *requires 2 GPUs*)
```bash
CUDA_VISIBLE_DEVICES=0,1 uv run python src/zeroband/infer.py @ configs/inference/debug.toml --parallel.tp 2
```
Only DP (DP=2, TP=1, PP=1, *requires 2 GPUs*)
```bash
CUDA_VISIBLE_DEVICES=0,1 uv run python src/zeroband/infer.py @ configs/inference/debug.toml --parallel.dp 2
```
Only PP (DP=1, TP=1, PP=2, *requires 2 GPUs*)
```bash
# Node 1
CUDA_VISIBLE_DEVICES=0 uv run python src/zeroband/infer.py @ configs/inference/debug.toml \
--parallel.pp.rank 0\
--parallel.pp.world-size 2\
--seed 69
```
```bash
# Node 2
CUDA_VISIBLE_DEVICES=1 uv run python src/zeroband/infer.py @ configs/inference/debug.toml \
--parallel.pp.rank 1\
--parallel.pp.world-size 2\
--seed 69
```
*Note: Setting the seed here is important to ensure model shards work on the same data shards.*
DP+TP (DP=2, TP=2, PP=1, *requires 4 GPUs*)
```bash
CUDA_VISIBLE_DEVICES=0,1,2,3 uv run python src/zeroband/infer.py @ configs/inference/debug.toml --parallel.dp 2 --parallel.tp auto
```
PP+TP (DP=1, TP=2, PP=2, *requires 4 GPUs*)
```bash
# Node 1
CUDA_VISIBLE_DEVICES=0,1 uv run python src/zeroband/infer.py @ configs/inference/debug.toml \
--parallel.tp auto \
--parallel.pp.rank 0\
--parallel.pp.world-size 2\
--seed 69
```
```bash
# Node 2
CUDA_VISIBLE_DEVICES=2,3 uv run python src/zeroband/infer.py @ configs/inference/debug.toml \
--parallel.tp auto \
--parallel.pp.rank 1\
--parallel.pp.world-size 2\
--seed 69
```
*Note: To check the logs of `prime-iroh` (used for connecting PP nodes), you can add the `RUST_LOG=prime_iroh=info` environment variable.*
We don't support DP+PP and so that configuration will raise an exception.
## Tests
### Tests
Run the full test suite
@@ -233,71 +226,19 @@ To run CPU-only tests, use the inverse of the `gpu` marker:
uv run pytest -v -m "not gpu"
```
To run fast tests, use the inverse of the `slow` marker:
```bash
uv run pytest -v -m "not slow"
```
## Configs
We use `pydantic-settings` to configure `prime-rl`. To get an overview of the available configurations, run the following command:
```bash
uv run python src/zeroband/train.py --help
```
```bash
uv run python src/zeroband/infer.py --help
```
### Sources
We support the following sources for configuration, in this order of precedence:
1.**Command-line arguments**: You can pass (nested) arguments as `--key.subkey value` to the script. For example, to set the model name you can run `--model.name`
2.**Config files**: You can pass `.toml` config files (defined in the `configs` directory) using the `@` prefix. For example, to use the `debug.toml` config file, you can run `uv run python src/zeroband/infer.py @ configs/inference/debug.toml`. (*If you leave a space between the `@` and the config file, you will get shell path auto-completions.*)
3.**Environment variables**: You can set environment variables to override the config values. All environment variables must be prefixed with `PRIME_` and use the `__` delimiter to nest the keys. For example, to set the model name you can run `export PRIME_MODEL__NAME=Qwen/Qwen3-0.6B`.
4.**Defaults**: For almost all config arguments, we have a default value which will be used if no other source is provided.
In general we recommend setting configurations via config files to define reproducible experiments and use command-line arguments to override the config values to run variants of the same experiment. Environment variables are usually only used in production settings to communicate with the [Prime Protocol](https://github.com/PrimeIntellect-ai/protocol) worker. In most cases, you should not need to use environment variables.
The precendence order will be important if multiple sources try to configure the same argument. For example, in the following command, all sources will define a model name
```toml
# qwen8b.toml
[model]
name="Qwen/Qwen3-8B"
```
```toml
# qwen14b.toml
[model]
name="Qwen/Qwen-14B"
```
```bash
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run src/zeroband/infer.py @qwen8b.toml @qwen14b.toml --model.name Qwen/Qwen3-32B
```
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precendence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
## License
This project is licensed under the Apache 2.0 license, as found in the [License](LICENSE) file.
## Citation
If you find `prime-rl` useful, feel free to cite our work:
If you find our work useful, feel free to cite it using
title={INTELLECT-2: A Reasoning Model Trained Through Globally Decentralized Reinforcement Learning},
author={Prime Intellect Team and Sami Jaghouar and Justus Mattern and Jack Min Ong and Jannik Straube and Manveer Basra and Aaron Pazdera and Kushal Thaman and Matthew Di Ferrante and Felix Gabriel and Fares Obeid and Kemal Erdem and Michael Keiblinger and Johannes Hagemann},
"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.