* 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.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)
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.
4.*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 +225,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.