Compare commits

...
Author SHA1 Message Date
fd78f21f79 make tito client opt-in (#1847)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make tito client opt-in

* Add CHANGELOG entry for orchestrator.use_token_client config field

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

---------

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

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

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

* add sft example

* add SFT MoE SLURM example and slim down SFT docs

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

* add sft slur config to tests

---------

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

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

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

* refactor: simplify MODEL_TOOL_CALL_PARSER to dict, address PR review

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

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

* refactor: use exact model names in MODEL_TOOL_CALL_PARSER dict

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

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

* remove extra inference stuff

* feat: default enable_auto_tool_choice to True

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

* feat: auto-enable enable_auto_tool_choice when tool_call_parser is set

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

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

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

---------

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

* do not run env server as daemon

* update commit to main

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

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

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

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

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

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

* Remove freeze_moe_router unit tests

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 14:50:15 -08:00
halleriteandGitHub 30a14c1702 add mismatch_kl-entropy ratio (#1835)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-19 14:16:02 -08:00
halleriteandGitHub a646ad6050 use lower-variance estimator for pass@k (#1834)
Release / Push CUDA image to Docker (push) Canceled after 0s
* use unbiased estimator

* compute k's on the fly

* fix claude retardation
2026-02-19 14:15:28 -08:00
10135d4814 fix resume from latest step for single-run (#1805)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-02-19 13:57:35 -08:00
Mika SenghaasandGitHub 29cc7b24ef increase health check interval (#1833)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-19 04:29:43 -08:00
deb1aa92bc fix MiniMax M2 LoRA compatibility in vLLM inference (#1831)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-02-18 21:18:33 -08:00
5c3008b3a5 Remove reload_weights_on_start dead code (#1829)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-02-18 17:35:18 -08:00
samsjaandGitHub 54b3e4cd24 remove hash from logs (#1830)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-18 17:20:58 -08:00
JannikStandGitHub bc55a1c85a pass json_logging to env servers (#1823)
Release / Push CUDA image to Docker (push) Canceled after 0s
* pass json_logging to env servers

- pass json_logging to ZMQEnvServer in standalone env-server entrypoint
- add json_logging param to spawn_env_server()
- pass config.log.json_logging in orchestrator spawn calls

* bump verifiers to 013d4da (json_logging support)

* remove duplicate
2026-02-18 16:18:23 +01:00
Mika SenghaasandGitHub 6f9c1362a1 env server recovery (#1816)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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
2026-02-18 07:08:51 -08:00
46d210bf6e add multimodal test to nightly CI (#1815)
Release / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-02-17 15:58:05 -08:00
halleriteandGitHub 1e365924ac fix VLMs after transformers bump (#1806)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-17 23:19:56 +01:00
halleriteandGitHub decced2093 add gibberish & repetition filtering (#1746)
Release / Push CUDA image to Docker (push) Canceled after 0s
---------

Signed-off-by: hallerite <git@hallerite.com>
2026-02-17 22:46:10 +01:00
39 changed files with 1543 additions and 254 deletions
+4 -1
View File
@@ -37,7 +37,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
- **`orchestrator.reload_weights_on_start`**: Added flag to control resetting inference weights to the base model when starting from scratch (default: True) (2026-01-21)
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
- **`client.skip_model_check`**: Added configuration to skip checking if the model is available in the inference pool. Useful for external APIs or API keys that don't support the /models endpoint (default: False) (#1543, 2026-01-06)
@@ -58,5 +58,8 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`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)
@@ -0,0 +1,35 @@
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 25
seq_len = 4096
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 64
[[orchestrator.env]]
id = "primeintellect/color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[orchestrator.val]
interval = 5
num_examples = 100
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
+1 -1
View File
@@ -16,7 +16,7 @@ The trainer is responsible for producing an updated policy model given rollouts
### Inference
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with two custom endpoints to enable updating the server with the latest policy: `update_weights` is used to reload model weights from a HF-compatible checkpoint on disk, and `reload_weights` is used to reset the weights to the base model in between experiments. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with a custom `update_weights` endpoint to reload model weights from a HF-compatible checkpoint on disk. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
### RL
+18 -4
View File
@@ -1,6 +1,8 @@
# SLURM
For SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
## RL
For RL on SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
```bash
uv run rl_slurm @ examples/slurm/hendrycks_math.toml
@@ -118,9 +120,9 @@ tp = 4
dp = 2
```
## Custom SLURM Templates
### Custom SLURM Templates
The default template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
The default RL template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
```bash
uv run rl_slurm \
@@ -130,7 +132,7 @@ uv run rl_slurm \
The template receives the following variables: `job_name`, `project_dir`, `output_dir`, `config_dir`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `hf_hub_offline`. See `src/prime_rl/slurm/rl_slurm.sh.j2` for the default template as a starting point.
## Monitoring
### Monitoring
After submission, the logs are available at:
@@ -152,3 +154,15 @@ This creates a tmux session `slurm-my-rl-job` with two windows:
- **Window 1 (Logs)**: three vertical panes tailing trainer, orchestrator, and inference logs
The trainer and inference panes use glob patterns (`latest_train_node_rank_*.log`, `latest_infer_node_rank_*.log`) to follow logs from all node ranks. Re-running the same command attaches to the existing session.
---
## SFT
For SFT on SLURM, use the `sft_slurm` entrypoint. It works the same way as `rl_slurm` but only needs a trainer config — no inference or orchestrator nodes.
```bash
uv run sft_slurm @ examples/slurm/sft_moe.toml
```
See [`examples/slurm/sft_moe.toml`](../examples/slurm/sft_moe.toml) for a MoE example with activation checkpointing, CPU offload, and compilation. Use `--dry-run` to generate the script without submitting.
+32
View File
@@ -0,0 +1,32 @@
job_name = "sft-moe-math"
output_dir = "/shared/outputs/sft-moe-math"
num_nodes = 1
gpus_per_node = 8
max_steps = 500
[wandb]
project = "sft-moe-intellect"
name = "sft-moe-math"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[model.compile]
[model.ac_offloading]
max_inflight_activations = 5
[model.ac]
freq = 1
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
subsets = ["default"]
splits = ["math"]
batch_size = 128
seq_len = 8192
+5 -1
View File
@@ -44,6 +44,10 @@ orchestrator = "prime_rl.orchestrator.orchestrator:main"
inference = "prime_rl.inference.server:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
sft = "prime_rl.trainer.sft.train:main"
sft_slurm = "prime_rl.slurm.sft:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
[project.optional-dependencies]
flash-attn = [
@@ -80,7 +84,7 @@ override-dependencies = [
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
math-env = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "ad77074" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "9052ecf" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
+100 -4
View File
@@ -3,9 +3,90 @@ from typing import Annotated, Any, Literal
from pydantic import Field, model_validator
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
from prime_rl.utils.utils import rgetattr, rsetattr
logger = get_logger()
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
# GLM-4.5
"zai-org/GLM-4.5": "glm45",
"zai-org/GLM-4.5-FP8": "glm45",
"zai-org/GLM-4.5-Base": "glm45",
"zai-org/GLM-4.5-Air": "glm45",
"zai-org/GLM-4.5-Air-FP8": "glm45",
"zai-org/GLM-4.5-Air-Base": "glm45",
"zai-org/GLM-4.5V": "glm45",
"zai-org/GLM-4.5V-FP8": "glm45",
# GLM-4.7
"zai-org/GLM-4.7": "glm47",
"zai-org/GLM-4.7-FP8": "glm47",
"zai-org/GLM-4.7-Flash": "glm47",
# MiniMax M2
"MiniMaxAI/MiniMax-M2": "minimax_m2",
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
# INTELLECT-3
"PrimeIntellect/INTELLECT-3": "hermes",
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
"PrimeIntellect/INTELLECT-3.1": "hermes",
# Qwen3 dense
"Qwen/Qwen3-0.6B": "hermes",
"Qwen/Qwen3-0.6B-Base": "hermes",
"Qwen/Qwen3-0.6B-FP8": "hermes",
"Qwen/Qwen3-1.7B": "hermes",
"Qwen/Qwen3-1.7B-Base": "hermes",
"Qwen/Qwen3-1.7B-FP8": "hermes",
"Qwen/Qwen3-4B": "hermes",
"Qwen/Qwen3-4B-Base": "hermes",
"Qwen/Qwen3-4B-FP8": "hermes",
"Qwen/Qwen3-8B": "hermes",
"Qwen/Qwen3-8B-Base": "hermes",
"Qwen/Qwen3-8B-FP8": "hermes",
"Qwen/Qwen3-14B": "hermes",
"Qwen/Qwen3-14B-Base": "hermes",
"Qwen/Qwen3-14B-FP8": "hermes",
"Qwen/Qwen3-32B": "hermes",
"Qwen/Qwen3-32B-FP8": "hermes",
# Qwen3 MoE
"Qwen/Qwen3-30B-A3B": "hermes",
"Qwen/Qwen3-30B-A3B-Base": "hermes",
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
"Qwen/Qwen3-235B-A22B": "hermes",
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
# Qwen3 2507
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
# Qwen3-Next
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
# Qwen3-Coder
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
# Qwen3-Coder-Next
"Qwen/Qwen3-Coder-Next": "hermes",
"Qwen/Qwen3-Coder-Next-Base": "hermes",
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
# Qwen3.5
"Qwen/Qwen3.5-397B-A17B": "hermes",
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
}
# TODO: Set thinking/ solution budget
@@ -79,16 +160,18 @@ class ModelConfig(BaseConfig):
enable_auto_tool_choice: Annotated[
bool,
Field(
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`",
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`. "
"Automatically set to True when tool_call_parser is configured.",
),
] = False
tool_call_parser: Annotated[
str,
str | None,
Field(
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`",
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
"If not set, automatically inferred from the model name.",
),
] = "hermes"
] = None
reasoning_parser: Annotated[
str | None,
@@ -104,6 +187,19 @@ class ModelConfig(BaseConfig):
),
] = None
@model_validator(mode="after")
def resolve_tool_call_parser(self):
if self.tool_call_parser is None:
parser = MODEL_TOOL_CALL_PARSER.get(self.name)
if parser is not None:
logger.info(f"Auto-detected tool_call_parser='{parser}' for model '{self.name}'")
self.tool_call_parser = parser
if self.tool_call_parser is not None:
self.enable_auto_tool_choice = True
return self
class WeightBroadcastConfig(BaseSettings):
"""Configures weight broadcast settings."""
+154
View File
@@ -1,3 +1,15 @@
def transformers_v5_compat():
"""vLLM general plugin: patch transformers v5 config attrs that vLLM 0.16 still expects.
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
in every vLLM process, including spawned workers.
"""
from transformers import Qwen3VLMoeTextConfig
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
Qwen3VLMoeTextConfig.tie_word_embeddings = False
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
from vllm.v1.metrics import loggers as vllm_metrics_loggers
@@ -191,3 +203,145 @@ def monkey_patch_tokenize_params_validation():
TokenizeParams._token_len_check = _patched_token_len_check
TokenizeParams._text_len_check = _patched_text_len_check
def monkey_patch_hermes_tool_parser_thread_safety():
"""Patch Hermes2ProToolParser to cache tokenizer encode/decode results.
The original __init__ calls tokenizer.encode() and tokenizer.decode() on
every instantiation. Under concurrent load, the shared HuggingFace tokenizer's
Rust backend panics with ``RuntimeError: Already borrowed`` because multiple
threads mutably borrow the same internal state simultaneously.
Fix: run the first __init__ (which calls encode/decode) under a lock, cache
the results, and reuse them for all subsequent instantiations without ever
touching the tokenizer again.
"""
import threading
import regex as re
from vllm.tool_parsers.abstract_tool_parser import ToolParser
from vllm.tool_parsers.hermes_tool_parser import Hermes2ProToolParser
_original_init = Hermes2ProToolParser.__init__
_cache: dict[int, dict] = {}
_lock = threading.Lock()
def _patched_init(self, tokenizer):
from vllm.tokenizers.mistral import MistralTokenizer
# Resolve the actual tokenizer that __init__ will use for encode/decode
actual_tokenizer = tokenizer.tokenizer if isinstance(tokenizer, MistralTokenizer) else tokenizer
key = id(actual_tokenizer)
if key in _cache:
# Fast path: skip encode/decode entirely, set up instance from cache
ToolParser.__init__(self, tokenizer)
if isinstance(tokenizer, MistralTokenizer):
self.model_tokenizer = tokenizer.tokenizer
self.current_tool_name_sent = False
self.prev_tool_call_arr = []
self.current_tool_id = -1
self.streamed_args_for_tool = []
self.tool_call_start_token = "<tool_call>"
self.tool_call_end_token = "</tool_call>"
self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>|<tool_call>(.*)", re.DOTALL)
self.scratch_pad_regex = re.compile(r"<scratch_pad>(.*?)</scratch_pad>", re.DOTALL)
cached = _cache[key]
self.tool_call_start_token_ids = cached["start_ids"]
self.tool_call_end_token_ids = cached["end_ids"]
self.tool_call_start_token_array = cached["start_array"]
self.tool_call_end_token_array = cached["end_array"]
self.buffered_delta_text = ""
return
# Slow path: first instantiation for this tokenizer, run under lock
with _lock:
if key in _cache:
# Another thread populated it while we waited
_patched_init(self, tokenizer)
return
_original_init(self, tokenizer)
_cache[key] = {
"start_ids": self.tool_call_start_token_ids,
"end_ids": self.tool_call_end_token_ids,
"start_array": self.tool_call_start_token_array,
"end_array": self.tool_call_end_token_array,
}
Hermes2ProToolParser.__init__ = _patched_init
def monkey_patch_minimax_m2_for_lora():
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
These patches are only needed when using LoRA with MiniMax M2 but are safe
to apply unconditionally (verified with non-LoRA runs). We apply them at
import time because the worker __init__ runs before the vLLM config is
available, so we can't check if LoRA is enabled.
Problem 1 — Gate dtype mismatch:
vLLM's MiniMaxM2MoE creates the gate (router) with params_dtype=float32
and casts inputs to float32. When LoRA is enabled, vLLM wraps ALL
ReplicatedLinear layers (including the gate) with LoRA support. Even
though our adapter has no gate LoRA weights, the LoRA Triton kernel
still runs for all wrapped layers when any adapter is active — and it
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
problem because its gate uses the model dtype.
Fix: recreate the gate in model dtype and remove the float32 cast.
FusedMoE already has router_logits_dtype=float32, so routing precision
is preserved inside the expert dispatch.
Problem 2 — Adapter key naming mismatch:
PrimeRL saves adapter keys using its internal naming convention
(mlp.experts.{j}.gate_proj/down_proj/up_proj), which matches Qwen3 MoE
but not MiniMax M2. vLLM's MiniMax M2 model expects HF-style keys
(block_sparse_moe.experts.{j}.w1/w2/w3). For full model weights this
is handled by vLLM's load_weights(), but LoRA adapters are loaded
through a separate path (LoRAModel.from_local_checkpoint) that doesn't
have model-specific key translation.
Fix: set hf_to_vllm_mapper on the model class so vLLM remaps adapter
keys during LoRA loading. This attribute is only read by _load_adapter
in the LoRA worker manager — it has no effect without LoRA.
"""
from vllm.model_executor.models.minimax_m2 import MiniMaxM2ForCausalLM, MiniMaxM2MoE
from vllm.model_executor.models.utils import WeightsMapper
# --- Gate dtype fix (only matters with LoRA, safe without) ---
_original_init = MiniMaxM2MoE.__init__
def _patched_init(self, config, quant_config=None, prefix=""):
_original_init(self, config, quant_config, prefix)
from vllm.model_executor.layers.linear import ReplicatedLinear
self.gate = ReplicatedLinear(
config.hidden_size,
config.num_local_experts,
bias=False,
quant_config=None,
prefix=f"{prefix}.gate",
)
def _patched_forward(self, hidden_states):
from vllm.distributed import tensor_model_parallel_all_reduce
num_tokens, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
router_logits, _ = self.gate(hidden_states)
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
if self.tp_size > 1:
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
return final_hidden_states.view(num_tokens, hidden_dim)
MiniMaxM2MoE.__init__ = _patched_init
MiniMaxM2MoE.forward = _patched_forward
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
orig_to_new_substr={
".mlp.experts.": ".block_sparse_moe.experts.",
".gate_proj.": ".w1.",
".down_proj.": ".w2.",
".up_proj.": ".w3.",
},
)
+3 -8
View File
@@ -23,6 +23,7 @@ from vllm.utils.argparse_utils import FlexibleArgumentParser
from prime_rl.inference.config import InferenceConfig
from prime_rl.inference.patches import (
monkey_patch_hermes_tool_parser_thread_safety,
monkey_patch_load_lora_adapter,
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode,
monkey_patch_tokenize_params_validation,
@@ -38,6 +39,8 @@ monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode()
monkey_patch_load_lora_adapter()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
monkey_patch_tokenize_params_validation()
# NOTE: Monkeypatch Hermes tool parser to fix "Already borrowed" RuntimeError under concurrent load
monkey_patch_hermes_tool_parser_thread_safety()
logger = init_logger("vllm.entrypoints.openai.api_server")
@@ -76,14 +79,6 @@ async def update_weights(request: Request):
return {"status": "ok"}
@router.post("/reload_weights")
async def reload_weights(request: Request):
await engine_client(request).collective_rpc("reload_weights")
# Reset prefix cache to invalidate KV states computed with old weights
await engine_client(request).reset_prefix_cache()
return {"status": "ok"}
@router.post("/load_lora_adapter")
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
"""Load a LoRA adapter and reset the prefix cache.
@@ -1,4 +1,6 @@
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager, monkey_patch_minimax_m2_for_lora
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
monkey_patch_LRUCacheWorkerLoRAManager()
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
monkey_patch_minimax_m2_for_lora()
+4 -4
View File
@@ -29,7 +29,7 @@ class CheckpointManager:
def get_ckpt_path(self, step: int) -> Path:
return get_step_path(self.ckpt_dir, step) / "orchestrator"
def _save_to_path(
def save_to_path(
self,
ckpt_path: Path,
progress: Progress,
@@ -47,7 +47,7 @@ class CheckpointManager:
self.logger.debug(f"Orchestrator checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
def _load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
def load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
"""Loads a checkpoint from a given path in-place."""
self.logger.debug(f"Loading checkpoint from {ckpt_path}")
start_time = time.perf_counter()
@@ -76,7 +76,7 @@ class CheckpointManager:
ckpt_path = self.get_ckpt_path(step)
if not ckpt_path.exists():
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
self._load_from_path(ckpt_path, progress, buffer)
self.load_from_path(ckpt_path, progress, buffer)
def save(
self,
@@ -87,7 +87,7 @@ class CheckpointManager:
"""Saves the full checkpoint state for a specified step."""
ckpt_path = self.get_ckpt_path(step)
ckpt_path.mkdir(parents=True, exist_ok=True)
self._save_to_path(ckpt_path, progress, buffer)
self.save_to_path(ckpt_path, progress, buffer)
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager | None:
+74 -7
View File
@@ -1,7 +1,7 @@
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import AliasChoices, BaseModel, Discriminator, Field, Tag, model_validator
from pydantic import AliasChoices, BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
from prime_rl.utils.config import (
@@ -579,6 +579,62 @@ AdvantageConfigType: TypeAlias = Annotated[
]
class GibberishFilterConfig(BaseModel):
"""Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387)."""
model_config = ConfigDict(extra="forbid")
type: Literal["gibberish"] = "gibberish"
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
),
] = False
token_id_threshold: Annotated[
int,
Field(description="Token IDs above this are candidates for gibberish. BPE tokens are sorted by merge order."),
] = 100_000
logprob_offset: Annotated[
float,
Field(description="Offset from uniform distribution logprob. Threshold = -log(vocab_size) - logprob_offset."),
] = 2.0
class RepetitionFilterConfig(BaseModel):
"""Flags rollouts where the model gets stuck in a repetition loop, emitting high-confidence tokens
for an extended stretch. A rollout is flagged when `window` consecutive tokens are each sampled
with probability above `prob_threshold`. (Section 3.2, https://arxiv.org/abs/2506.13585)"""
model_config = ConfigDict(extra="forbid")
type: Literal["repetition"] = "repetition"
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
),
] = False
window: Annotated[
int,
Field(ge=1, description="Number of consecutive high-probability steps before flagging."),
] = 3_000
prob_threshold: Annotated[
float,
Field(
gt=0,
le=1,
description="Tokens sampled with probability above this are considered repetitive. Consecutive such tokens count toward the window.",
),
] = 0.99
FilterConfigType: TypeAlias = Annotated[
GibberishFilterConfig | RepetitionFilterConfig,
Field(discriminator="type"),
]
class FileSystemWeightBroadcastConfig(BaseModel):
"""Configures the filesystem weight broadcast."""
@@ -649,6 +705,9 @@ class OrchestratorConfig(BaseSettings):
# The advantage configuration
advantage: AdvantageConfigType | None = AdvantageConfig()
# Rollout filters (monitor by default, enforce optionally)
filters: list[FilterConfigType] = [GibberishFilterConfig(), RepetitionFilterConfig()]
# The logging configuration
log: LogConfig = LogConfig()
@@ -661,12 +720,6 @@ class OrchestratorConfig(BaseSettings):
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
# Whether to reset inference weights to base model when starting from scratch
reload_weights_on_start: Annotated[
bool,
Field(description="Whether to reset inference weights to the base model when starting from scratch."),
] = True
# The validation configuration
val: ValConfig | None = None
@@ -772,6 +825,20 @@ class OrchestratorConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
use_token_client: Annotated[
bool,
Field(
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
),
] = False
@model_validator(mode="after")
def validate_unique_filter_types(self):
types = [f.type for f in self.filters]
if len(types) != len(set(types)):
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
return self
@model_validator(mode="after")
def validate_max_concurrent(self):
if self.max_concurrent is not None and self.max_concurrent < self.rollouts_per_example:
@@ -1,3 +1,5 @@
import asyncio
from verifiers.workers import ZMQEnvServer
from prime_rl.orchestrator.env_server.config import EnvServerConfig
@@ -19,15 +21,18 @@ def run_server(config: EnvServerConfig):
env_name = config.env.name or config.env.id
log_file = (get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix()
ZMQEnvServer.run_server(
server = ZMQEnvServer(
env_id=strip_env_version(config.env.id),
env_args=config.env.args,
extra_env_kwargs=config.env.extra_env_kwargs,
log_level=config.log.level,
log_file_level=config.log.vf_level,
log_file=log_file,
json_logging=config.log.json_logging,
**{"address": config.env.address} if config.env.address is not None else {},
)
asyncio.run(server.run())
def main():
+12 -13
View File
@@ -45,22 +45,21 @@ def get_eval_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any
return sampling_args
def compute_pass_at_k(rewards: list[int]) -> dict[str, float]:
total_attempts = len(rewards)
k = total_attempts // 2
def _pass_at_k(n: int, c: int, k: int) -> float:
"""Unbiased estimator of pass@k (Chen et al., 2021).
if k == 0:
return {"pass@1": float(any(reward == 1.0 for reward in rewards))}
Computes 1 - C(n-c, k) / C(n, k) in a numerically stable way.
"""
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
num_trials = 100
pass_rates = []
for _ in range(num_trials):
sampled_rewards = np.random.choice(rewards, size=k, replace=False)
pass_rate = float(any(reward == 1.0 for reward in sampled_rewards))
pass_rates.append(pass_rate)
return {f"pass@{k}": float(np.mean(pass_rates))}
def compute_pass_at_k(rewards: list[float]) -> dict[str, float]:
n = len(rewards)
c = sum(r == 1.0 for r in rewards)
ks = [2**i for i in range(n.bit_length())]
return {f"pass@{k}": _pass_at_k(n, c, k) for k in ks}
async def evaluate_env(
+181
View File
@@ -0,0 +1,181 @@
"""Orchestrator-side rollout filters for detecting degenerate generations.
Filters run after rollouts complete, inspecting token IDs and logprobs to
detect gibberish or repetition. Detection metrics are always tracked.
When enforce=True, detected rollouts get their completion mask cleared so
they don't contribute to training. Reward is kept as-is for baseline
calculation.
"""
import math
from dataclasses import dataclass
from typing import Protocol
import verifiers as vf
from loguru import logger
from prime_rl.orchestrator.config import FilterConfigType
@dataclass
class FilterResult:
detected: bool
detection_index: int | None = None
class RolloutFilter(Protocol):
name: str
enforce: bool
def check(self, rollout: vf.RolloutOutput) -> FilterResult: ...
@dataclass
class GibberishFilter:
"""Flags rollouts containing rare tokens generated at high entropy.
A token is flagged when both:
- id(token) > token_id_threshold (rare BPE token)
- logprob(token) < -log(vocab_size) - logprob_offset (high entropy)
References:
Section 5.2, https://arxiv.org/abs/2510.02387
"""
name: str
token_id_threshold: int
logprob_threshold: float
enforce: bool = False
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
global_idx = 0
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
for token_id, logprob in zip(tokens["completion_ids"], tokens["completion_logprobs"]):
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
return FilterResult(detected=True, detection_index=global_idx)
global_idx += 1
return FilterResult(detected=False)
@dataclass
class RepetitionFilter:
"""Flags rollouts with pathological repetition loops.
Counts consecutive tokens where logprob > log(prob_threshold), indicating
the model is generating with very high confidence. When the streak reaches
the window size, the rollout is flagged.
References:
Section 3.2, https://arxiv.org/abs/2506.13585
"""
name: str
window: int
logprob_threshold: float
enforce: bool = False
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
consecutive = 0
global_idx = 0
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
for logprob in tokens["completion_logprobs"]:
if logprob > self.logprob_threshold:
consecutive += 1
else:
consecutive = 0
if consecutive >= self.window:
return FilterResult(detected=True, detection_index=global_idx)
global_idx += 1
return FilterResult(detected=False)
def setup_filter(config: FilterConfigType, vocab_size: int) -> RolloutFilter:
"""Create a RolloutFilter from a filter config."""
if config.type == "gibberish":
return GibberishFilter(
name="gibberish",
token_id_threshold=config.token_id_threshold,
logprob_threshold=-math.log(vocab_size) - config.logprob_offset,
enforce=config.enforce,
)
elif config.type == "repetition":
return RepetitionFilter(
name="repetition",
window=config.window,
logprob_threshold=math.log(config.prob_threshold),
enforce=config.enforce,
)
raise ValueError(f"Unknown filter type: {config.type}")
def setup_filters(configs: list[FilterConfigType], vocab_size: int) -> list[RolloutFilter]:
"""Create RolloutFilters from a list of filter configs."""
return [setup_filter(config, vocab_size) for config in configs]
def apply_filters(
filters: list[RolloutFilter],
rollouts: list[vf.RolloutOutput],
) -> dict[str, float]:
"""Apply filters to rollouts. Detection metrics are always tracked.
When a filter has enforce=True, detected rollouts get their completion
mask cleared and stop_condition set. Reward is kept as-is for baseline
calculation.
First matching filter wins per rollout (no double-counting).
Returns aggregate metrics dict for logging.
"""
if not filters:
return {}
counts: dict[str, int] = {f.name: 0 for f in filters}
total_detected = 0
total_enforced = 0
for rollout in rollouts:
if rollout.get("metrics") is None:
rollout["metrics"] = {}
for filt in filters:
rollout["metrics"].setdefault(f"filter/{filt.name}", 0.0)
for filt in filters:
result = filt.check(rollout)
if result.detected:
counts[filt.name] += 1
total_detected += 1
rollout["metrics"][f"filter/{filt.name}"] = 1.0
if filt.enforce:
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is not None:
tokens["completion_mask"] = [0] * len(tokens["completion_mask"])
rollout["stop_condition"] = filt.name
total_enforced += 1
break
n = len(rollouts)
metrics: dict[str, float] = {}
for f in filters:
metrics[f"filter/{f.name}_count"] = float(counts[f.name])
metrics[f"filter/{f.name}_rate"] = counts[f.name] / n if n > 0 else 0.0
metrics["filter/total_detected_rate"] = total_detected / n if n > 0 else 0.0
metrics["filter/total_enforced_rate"] = total_enforced / n if n > 0 else 0.0
if total_detected > 0:
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
logger.info(
f"Detected {total_detected}/{n} rollouts "
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
)
return metrics
+46 -41
View File
@@ -1,4 +1,5 @@
import asyncio
import multiprocessing as mp
import random
import time
from concurrent.futures import ThreadPoolExecutor
@@ -30,6 +31,7 @@ from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
from prime_rl.orchestrator.config import BufferConfig, OrchestratorConfig
from prime_rl.orchestrator.eval_utils import evaluate_env
from prime_rl.orchestrator.filters import apply_filters, setup_filters
from prime_rl.orchestrator.scheduler import Scheduler
from prime_rl.orchestrator.utils import (
compute_teacher_logprobs,
@@ -42,13 +44,13 @@ from prime_rl.orchestrator.vf_utils import (
generate,
get_completion_len,
get_seq_len,
intercept_vf_logging,
setup_env_client,
spawn_env_server,
wait_for_env_servers,
)
from prime_rl.utils.client import (
init_nccl_broadcast,
reload_weights,
setup_inference_pool,
)
from prime_rl.utils.heartbeat import Heartbeat
@@ -58,7 +60,6 @@ from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.temp_scheduling import compute_temperature
from prime_rl.utils.utils import (
clean_exit,
count_chinese_chars,
get_env_ids_to_install,
install_env,
resolve_latest_ckpt_step,
@@ -76,7 +77,7 @@ async def orchestrate(config: OrchestratorConfig):
log_file=config.output_dir / "logs" / "orchestrator.log" if config.log.file else None,
json_logging=config.log.json_logging,
)
vf.setup_logging(level="CRITICAL")
intercept_vf_logging(logger="verifiers.workers", level=config.log.vf_level) # show logs from env clients
logger.info("Starting orchestrator")
event_loop_lag_monitor = EventLoopLagMonitor()
@@ -102,7 +103,13 @@ async def orchestrate(config: OrchestratorConfig):
install_env(env_id)
# Setup inference pool (handles both static and elastic modes)
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name)
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
if config.use_token_client:
logger.warning(
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
"history and the chat template has the extension property."
)
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name, client_type=client_type)
# Setup teacher inference pool if configured
if config.teacher_model:
@@ -130,6 +137,11 @@ async def orchestrate(config: OrchestratorConfig):
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
)
# Build rollout filters
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
if rollout_filters:
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
# Setup monitor
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
monitor = setup_monitor(
@@ -151,28 +163,34 @@ async def orchestrate(config: OrchestratorConfig):
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
)
env_ids = [strip_env_version(env.id) for env in config.env]
train_env_names = [env.name or env_id for env_id, env in zip(env_ids, config.env)]
train_env_group = vf.EnvGroup(
envs=[vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.env)],
env_names=[env.name or env_id for env_id, env in zip(env_ids, config.env)],
env_names=train_env_names,
map_kwargs=dict(writer_batch_size=1), # set defensively to not error on map operations on large datasets
)
train_env_addresses = []
for env_id, env, env_name in zip(env_ids, config.env, train_env_group.env_names):
env_processes: list[mp.Process] = []
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
if env.address is None:
address = spawn_env_server(
address, process = spawn_env_server(
env_id=env_id,
env_args=env.args,
extra_env_kwargs=env.extra_env_kwargs,
log_level="CRITICAL",
log_file=(get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix(),
log_file_level=config.log.vf_level,
json_logging=config.log.json_logging,
)
env_processes.append(process)
else:
address = env.address
logger.info(f"Connecting train environment {env_name} to server at {address}")
train_env_addresses.append(address)
train_env_clients = [setup_env_client(address) for address in train_env_addresses]
train_env_clients = [
setup_env_client(address=address, name=name) for name, address in zip(train_env_names, train_env_addresses)
]
logger.info("Waiting for train environment servers to be ready")
await wait_for_env_servers(train_env_clients)
@@ -192,20 +210,24 @@ async def orchestrate(config: OrchestratorConfig):
for env_id, env, eval_env_name in zip(env_ids, config.eval.env, eval_env_names):
if env.address is None:
address = spawn_env_server(
address, process = spawn_env_server(
env_id=env_id,
env_args=env.args,
extra_env_kwargs=env.extra_env_kwargs,
log_level="CRITICAL",
log_file=(get_log_dir(config.output_dir) / "eval" / f"{eval_env_name}.log").as_posix(),
log_file_level=config.log.vf_level,
json_logging=config.log.json_logging,
)
env_processes.append(process)
else:
address = env.address
logger.info(f"Connecting eval environment {eval_env_name} to server at {address}")
eval_env_addresses.append(address)
eval_env_clients = [setup_env_client(address) for address in eval_env_addresses]
eval_env_clients = [
setup_env_client(address=address, name=name) for name, address in zip(eval_env_names, eval_env_addresses)
]
logger.info("Waiting for eval environment servers to be ready")
await wait_for_env_servers(eval_env_clients)
@@ -308,14 +330,7 @@ async def orchestrate(config: OrchestratorConfig):
lora_name = config.model.lora.name if config.model.lora else None
await inference_pool.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
else:
if config.reload_weights_on_start:
if config.model.lora is None:
logger.info("Training from scratch. Resetting weights to base model")
await reload_weights(inference_pool.admin_clients)
else:
logger.info("Training from scratch. Skipping base weight reload because LoRA is enabled")
else:
logger.info("Training from scratch. Skipping base weight reload")
logger.info("Training from scratch")
# Iterate over dataset in batches
max_steps = config.max_steps or int(1e9)
@@ -440,6 +455,9 @@ async def orchestrate(config: OrchestratorConfig):
generate_completions_time = scheduler.last_batch_generation_time
train_rollouts = train_task.result()
# Apply rollout filters (zeros reward/mask for degenerate generations)
filter_metrics = apply_filters(rollout_filters, train_rollouts)
# Compute advantages
example_ids = [r["example_id"] for r in train_rollouts]
rewards = [r["reward"] for r in train_rollouts]
@@ -569,21 +587,6 @@ async def orchestrate(config: OrchestratorConfig):
# Gather individual reward function metrics
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
# Count Chinese characters in completions
chinese_stats = []
for rollout in train_rollouts:
trajectory = rollout["trajectory"]
if not trajectory:
continue
last_step = trajectory[-1]
tokens = last_step["tokens"]
completion_text = tokenizer.decode(tokens["completion_ids"])
chinese_count, total_count = count_chinese_chars(completion_text)
chinese_stats.append(
{"chinese_chars": chinese_count, "total_chars": total_count, "has_chinese": chinese_count > 0}
)
chinese_df = pd.DataFrame(chinese_stats)
val_results_df = (
pd.DataFrame(
{
@@ -668,14 +671,6 @@ async def orchestrate(config: OrchestratorConfig):
},
# Env metrics
**{f"metrics/{metric}": metrics_df[metric].mean() for metric in metrics_df.columns},
# Chinese character metrics (cast to native Python types for JSON serialization)
"chinese/char_count": int(chinese_df.chinese_chars.sum()),
"chinese/char_ratio": (
float(chinese_df.chinese_chars.sum() / chinese_df.total_chars.sum())
if chinese_df.total_chars.sum() > 0
else 0.0
),
"chinese/rollout_ratio": float(chinese_df.has_chinese.mean()),
# Time metrics
"time/step": step_time,
"time/generate_completions": generate_completions_time,
@@ -688,6 +683,8 @@ async def orchestrate(config: OrchestratorConfig):
**buffer.get_metrics(),
# Event loop lag metrics
**event_loop_lag_monitor.get_metrics(),
# Rollout filter metrics
**filter_metrics,
# W&B axis
"step": progress.step,
}
@@ -788,6 +785,14 @@ async def orchestrate(config: OrchestratorConfig):
# Cancel event loop lag monitor task
event_loop_lag_monitor_task.cancel()
# Shutdown env processes
for process in env_processes:
process.terminate()
process.join(timeout=5)
if process.is_alive():
process.kill()
process.join(timeout=5)
logger.success("Orchestrator finished.")
# Optionally, print benchmark table
+32 -40
View File
@@ -7,10 +7,10 @@ from typing import Any
import verifiers as vf
from verifiers.envs.environment import EnvClient
from verifiers.utils.worker_utils import get_free_port
from verifiers.utils.worker_utils import get_free_port_pair
from verifiers.workers import ZMQEnvClient, ZMQEnvServer
from prime_rl.utils.logger import InterceptHandler, ProgressTracker, get_logger
from prime_rl.utils.logger import InterceptHandler, ProgressTracker
DEFAULT_RETRIES = 0
REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
@@ -22,21 +22,22 @@ def spawn_env_server(
env_args: dict[str, Any],
extra_env_kwargs: dict[str, Any],
address: str | None = None,
# logging configs
log_level: str | None = None,
log_file: str | None = None,
log_file_level: str | None = None,
daemon: bool = True,
) -> str:
json_logging: bool = False,
) -> tuple[str, mp.Process]:
"""
Starts a ZMQEnvServer process in a subprocess.
Mirrors vf.Environment.start_server().
"""
address = address or f"tcp://127.0.0.1:{get_free_port()}"
address = address or f"tcp://127.0.0.1:{get_free_port_pair()}"
# Use spawn to avoid inheriting file descriptors (e.g. sockets) from
# the parent process, which has caused hangs when multiple env server
# subprocesses share the same fds.
mp.get_context("spawn").Process(
process = mp.get_context("spawn").Process(
target=ZMQEnvServer.run_server,
args=(
env_id,
@@ -46,43 +47,34 @@ def spawn_env_server(
log_file,
log_file_level,
),
kwargs=dict(address=address),
daemon=daemon,
).start()
kwargs=dict(address=address, json_logging=json_logging),
daemon=False, # cannot run daemon because env server uses subprocesses
)
process.start()
return address
return address, process
def setup_env_client(address: str) -> EnvClient:
def setup_env_client(
address: str,
name: str | None = None,
# health check configs
health_check_interval: float = 5.0, # 5s (we detect an env server as unhealth after 3 * 5s = 15s of unsuccessful health checks)
startup_timeout: float = 600.0, # 10m
recovery_timeout: float = 600.0, # 10m
) -> EnvClient:
"""Sets up a ZMQEnvClient for a given address."""
return ZMQEnvClient(address=address)
return ZMQEnvClient(
address=address,
name=name,
health_check_interval=health_check_interval,
startup_timeout=startup_timeout,
recovery_timeout=recovery_timeout,
)
async def wait_for_env_servers(
env_clients: list[EnvClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
) -> None:
logger = get_logger()
async def wait_for_env_server(env_client: EnvClient) -> None:
wait_time = 0
logger.debug(f"Starting pinging environment server at {env_client.address}")
while wait_time < timeout:
try:
await env_client.health(timeout=1) # quick timeout
logger.debug(f"Environment server at {env_client.address} is ready after {wait_time} seconds")
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.warning(
f"Environment server at {env_client.address} was not reached after {wait_time} seconds (Error: {e})"
)
await asyncio.sleep(interval)
wait_time += interval
msg = f"Environment server at {env_client.address} is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
logger.error(msg)
raise TimeoutError(msg)
await asyncio.gather(*[wait_for_env_server(env_client) for env_client in env_clients])
async def wait_for_env_servers(env_clients: list[EnvClient]) -> None:
await asyncio.gather(*[env_client.wait_for_server_startup() for env_client in env_clients])
async def run_group(
@@ -249,9 +241,9 @@ def get_completion_len(output: vf.RolloutOutput) -> int:
return get_seq_len(output) - get_prompt_len(output)
def intercept_vf_logging(level: str = "DEBUG", prefix: str = "verifiers"):
"""Intercepts verifiers logging and routes through prime-rl logger with [verifiers] prefix."""
vf_logger = logging.getLogger("verifiers")
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
vf_logger = logging.getLogger(logger)
vf_logger.handlers.clear()
vf_logger.addHandler(InterceptHandler(prefix=prefix))
vf_logger.setLevel(level.upper())
-3
View File
@@ -91,9 +91,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
uv run inference \
@ $CONFIG_DIR/inference.toml \
--enable-auto-tool-choice \
--enable-log-requests \
--no-disable-log-requests \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${INFER_NODE_RANK}_infer_node_rank_${INFER_NODE_RANK}.log
else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
+113
View File
@@ -0,0 +1,113 @@
import subprocess
import sys
from pathlib import Path
import tomli_w
from jinja2 import Environment, FileSystemLoader
from pydantic import Field, model_validator
from prime_rl.trainer.sft.config import SFTTrainerConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pydantic_config import parse_argv
TEMPLATE_DIR = Path(__file__).parent
TEMPLATE_NAME = "sft_slurm.sh.j2"
class SFTSLURMConfig(SFTTrainerConfig):
job_name: str
num_nodes: int = Field(default=1, description="Number of training nodes.")
gpus_per_node: int = Field(default=8, description="Number of GPUs per node.")
nodes_per_fsdp_group: int | None = Field(
default=None,
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group.",
)
project_dir: Path = Field(
default_factory=lambda: Path.cwd(),
description="Path to the project root. Used to source .env, activate .venv, and run uv sync.",
)
hf_hub_offline: bool = Field(
default=False, description="Set HF_HUB_OFFLINE=1 on training nodes to prevent downloading models at runtime."
)
slurm_template: Path | None = Field(
default=None, description="The path to the SLURM template file. If none, will use the default template."
)
dry_run: bool = Field(default=False, description="Only generate the SLURM script and configs without submitting.")
@model_validator(mode="after")
def auto_setup_dp_replicate(self):
if self.nodes_per_fsdp_group is not None:
if self.num_nodes % self.nodes_per_fsdp_group != 0:
raise ValueError(
f"num_nodes ({self.num_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
)
self.model.dp_replicate = self.num_nodes // self.nodes_per_fsdp_group
return self
def write_trainer_config(config: SFTSLURMConfig, output_dir: Path) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
slurm_only_fields = set(SFTSLURMConfig.model_fields) - set(SFTTrainerConfig.model_fields)
trainer_data = config.model_dump(exclude_none=True, mode="json", exclude=slurm_only_fields)
with open(output_dir / "trainer.toml", "wb") as f:
tomli_w.dump(trainer_data, f)
def render_slurm_script(config: SFTSLURMConfig, config_dir: Path) -> str:
if config.slurm_template is not None:
template_dir = config.slurm_template.parent
template_name = config.slurm_template.name
else:
template_dir = TEMPLATE_DIR
template_name = TEMPLATE_NAME
env = Environment(loader=FileSystemLoader(template_dir), keep_trailing_newline=True)
template = env.get_template(template_name)
return template.render(
job_name=config.job_name,
output_dir=config.output_dir,
config_dir=config_dir,
num_nodes=config.num_nodes,
project_dir=config.project_dir,
gpus_per_node=config.gpus_per_node,
hf_hub_offline=config.hf_hub_offline,
)
def sft_slurm(config: SFTSLURMConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = config.output_dir / "configs"
write_trainer_config(config, config_dir)
logger.info(f"Wrote trainer config to {config_dir}")
script = render_slurm_script(config, config_dir)
script_path = config.output_dir / "sft.sh"
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
logger.info(f"Wrote SLURM script to {script_path}")
log_message = f"Logs:\n Trainer: tail -f {config.output_dir}/slurm/latest_train_node_rank_0.log"
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def main():
sft_slurm(parse_argv(SFTSLURMConfig))
if __name__ == "__main__":
main()
+79
View File
@@ -0,0 +1,79 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes={{ num_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition=cluster
#SBATCH --exclusive # Get the ENTIRE node exclusively
#SBATCH --output=/shared/logs/job_%j.log
#SBATCH --error=/shared/logs/job_%j.log
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/slurm
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
echo "HOSTNAMES=${HOSTNAMES[@]}"
export MASTER_ADDR="${HOSTNAMES[0]}"
export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
# Install environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Install environment as local package
cd $PROJECT_DIR && uv sync --all-extras
# Run SFT
srun bash -c '
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Higher ulimit
ulimit -n 65536
export GIT_LFS_SKIP_SMUDGE=1
# Infiniband setup
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
export NCCL_IB_HCA=$IB_HCA
TRAIN_NODE_RANK=$SLURM_PROCID
export HF_HUB_OFFLINE={{ 1 if hf_hub_offline else 0 }}
# This is required for compilation to work correctly
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
uv run torchrun \
--nnodes=$NUM_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$OUTPUT_DIR/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter=$(seq -s, 0 $((GPUS_PER_NODE - 1))) \
-m prime_rl.trainer.sft.train \
@ $CONFIG_DIR/trainer.toml \
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
'
+42 -44
View File
@@ -30,7 +30,6 @@ from prime_rl.trainer.weights import (
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.tensor_hashing import get_module_signature, get_optimizer_signature
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
@@ -214,9 +213,6 @@ class CheckpointManager:
if not ckpt_path.exists():
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
self.load_from_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
self.logger.debug(
f"Signatures after loading training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
)
def save(
self,
@@ -230,9 +226,6 @@ class CheckpointManager:
"""Save the full checkpoint state for a specified step."""
ckpt_path = self.get_ckpt_path(step)
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
self.logger.debug(
f"Signatures before saving training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
)
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
bisect.insort(self.ckpt_steps, step)
@@ -305,6 +298,12 @@ class WeightCheckpointManager:
"""Get the path to write the weight checkpoint for a given step."""
return get_step_path(self.weights_dir, step)
def mark_stable(self, step: int) -> None:
"""Write STABLE file to indicate weight checkpoint is complete."""
if self.world.is_master:
step_path = self.get_step_path(step)
(step_path / "STABLE").touch()
def save_to_path(
self,
path: Path,
@@ -314,44 +313,45 @@ class WeightCheckpointManager:
tokenizer: PreTrainedTokenizer,
):
"""Save HF-compatible weight checkpoint to a given path."""
path.mkdir(parents=True, exist_ok=True)
start_time = time.perf_counter()
if self.world.is_master:
path.mkdir(parents=True, exist_ok=True)
start_time = time.perf_counter()
self.logger.debug(f"Saving weight checkpoint to {path}")
# Suppress torch.distributed warnings during checkpoint saving
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
self.logger.debug(f"Saving weight checkpoint to {path}")
# Suppress torch.distributed warnings during checkpoint saving
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
# Save weights
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
# Save weights
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
# Save model config, generation arguments and tokenizer
model.config.save_pretrained(path)
if model.generation_config:
# training sets use_cache=False which can conflict with
# cache_implementation — save with use_cache=True without
# mutating the model's config
from copy import deepcopy
# Save model config, generation arguments and tokenizer
model.config.save_pretrained(path)
if model.generation_config:
# training sets use_cache=False which can conflict with
# cache_implementation — save with use_cache=True without
# mutating the model's config
from copy import deepcopy
gen_config = deepcopy(model.generation_config)
gen_config.use_cache = True
gen_config.save_pretrained(path)
tokenizer.save_pretrained(path)
gen_config = deepcopy(model.generation_config)
gen_config.use_cache = True
gen_config.save_pretrained(path)
tokenizer.save_pretrained(path)
if self.config.save_adapter_separately and lora_state_dict is not None:
adapter_path = path / "lora_adapters"
adapter_path.mkdir(parents=True, exist_ok=True)
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
if self.lora_config:
save_lora_config(
model,
adapter_path,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
)
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
if self.config.save_adapter_separately and lora_state_dict is not None:
adapter_path = path / "lora_adapters"
adapter_path.mkdir(parents=True, exist_ok=True)
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
if self.lora_config:
save_lora_config(
model,
adapter_path,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
)
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
def save(
self,
@@ -400,10 +400,8 @@ class WeightCheckpointManager:
self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds")
# Save weight checkpoint on master rank
if self.world.is_master:
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
# Write STABLE file to indicate checkpoint is complete (for eval to safely read)
(step_path / "STABLE").touch()
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
self.mark_stable(step)
bisect.insort(self.ckpt_steps, step)
def maybe_clean(self) -> None:
+7 -12
View File
@@ -13,11 +13,6 @@ AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_atte
# to attempt installing a kernel from hub.
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
MOE_MODEL_MAPS = {
"Qwen/Qwen3-30B-A3B": "Jackmin108/Qwen3-30B-A3B-Fast",
"moonshotai/Moonlight-16B-A3B-Instruct": "Jackmin108/Moonlight-16B-A3B-Instruct-Fast",
}
class ActivationCheckpointConfig(BaseConfig):
"""Configures activation checkpointing."""
@@ -255,6 +250,13 @@ class ModelConfig(BaseConfig):
),
] = True
freeze_moe_router: Annotated[
bool,
Field(
description="Whether to freeze the MoE router parameters during training.",
),
] = False
lora: Annotated[
LoRAConfig | None,
Field(
@@ -291,13 +293,6 @@ class ModelConfig(BaseConfig):
data["attn"] = _ATTN_ALIASES[data["attn"]]
return data
@model_validator(mode="after")
def _map_model_name_for_moe(self):
"""Map model name if it exists in MOE_MODEL_MAPS."""
if self.name in MOE_MODEL_MAPS:
self.name = MOE_MODEL_MAPS[self.name]
return self
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
+47 -8
View File
@@ -17,7 +17,7 @@ from torch.distributed.device_mesh import DeviceMesh
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
from torch.distributed.tensor.parallel import parallelize_module
from torchtitan.distributed.expert_parallel import ExpertParallel
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, PretrainedConfig
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
@@ -40,7 +40,6 @@ from prime_rl.trainer.weights import (
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.tensor_hashing import get_module_signature
from prime_rl.utils.vlm import is_vlm_model
# Add filter to the standard logging module for transformers.modeling_utils to supress the
@@ -86,6 +85,34 @@ def freeze_vision_encoder(model: nn.Module) -> None:
logger.info(f"Froze {num_frozen} parameters in vision encoder")
def freeze_moe_router(model: nn.Module) -> None:
"""Freeze MoE router parameters to maintain stable routing during training."""
logger = get_logger()
language_model = get_language_model(model)
num_frozen = 0
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if mlp is None:
continue
# Custom implementation: MoE class with router attribute
if isinstance(mlp, MoE):
for param in mlp.router.parameters():
param.requires_grad = False
num_frozen += 1
# HuggingFace implementation: gate attribute (nn.Linear)
elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Linear):
for param in mlp.gate.parameters():
param.requires_grad = False
num_frozen += 1
if num_frozen == 0:
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
logger.info(f"Froze {num_frozen} MoE router parameters")
def is_tt_moe_model(model: nn.Module) -> bool:
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
@@ -147,9 +174,20 @@ def get_model(
model_config.use_cache = False
model_config.use_grouped_mm = config.moe_use_grouped_mm
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it)
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
if not hasattr(model_config, "pad_token_id") or model_config.pad_token_id is None:
model_config.pad_token_id = model_config.eos_token_id
gen_config = GenerationConfig.from_model_config(model_config)
# Use `is not None` instead of truthiness: token ID 0 is valid.
pad_token_id = next(
(
v
for v in [gen_config.pad_token_id, gen_config.eos_token_id, getattr(model_config, "eos_token_id", None)]
if v is not None
),
None,
)
model_config.pad_token_id = pad_token_id
# NOTE: For VLM models, we do NOT propagate dtype to sub_configs.
# The model should load in its default dtype (bf16) to match vLLM inference.
@@ -180,11 +218,10 @@ def get_model(
)
with device:
# For VLM models, use AutoModelForVision2Seq or import specific model class
if is_vlm:
from transformers import AutoModelForVision2Seq
from transformers import AutoModelForImageTextToText
model_cls = AutoModelForVision2Seq
model_cls = AutoModelForImageTextToText
else:
match impl_to_use:
case "hf":
@@ -632,6 +669,9 @@ def setup_model(
if config.lora is not None:
apply_lora_to_model(model, config.lora)
if config.freeze_moe_router:
freeze_moe_router(model)
if parallel_dims.ep_enabled:
apply_ep(model, parallel_dims)
@@ -669,7 +709,6 @@ def setup_model(
else:
load_dcp_from_hf(model, config, parallel_dims)
logger.debug(f"Model signature: {get_module_signature(model, compress=True)}")
return model
+6
View File
@@ -505,6 +505,12 @@ def train(config: RLTrainerConfig):
}
monitor.log(optim_metrics, step=progress.step)
# Compute derived metrics
entropy_mean = tensor_stats.get("entropy/mean", 0.0)
mismatch_kl_mean = tensor_stats.get("mismatch_kl/mean")
if mismatch_kl_mean is not None and entropy_mean > 0:
tensor_stats["kl_ent_ratio/mean"] = mismatch_kl_mean / entropy_mean
# Log tensor stats
tensor_stats["step"] = progress.step
monitor.log(tensor_stats, step=progress.step)
+6 -3
View File
@@ -11,7 +11,7 @@ import torch.distributed.distributed_c10d as c10d
from prime_rl.trainer.config import LoRAConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_stable_ckpt_steps
from prime_rl.utils.pathing import get_all_ckpt_steps, get_stable_ckpt_steps
if TYPE_CHECKING:
from prime_rl.orchestrator.config import OrchestratorConfig
@@ -264,8 +264,11 @@ class MultiRunManager:
if config.ckpt is None or config.ckpt.resume_step is None:
self.progress[new_id].step = 0
elif config.ckpt.resume_step == -1:
stable_steps = get_stable_ckpt_steps(self.get_run_dir(new_id) / "checkpoints")
self.progress[new_id].step = max(stable_steps) if stable_steps else 0
ckpt_dir = self.get_run_dir(new_id) / "checkpoints"
# In multi-run, the trainer writes STABLE after saving LoRA weights to the run's checkpoint dir.
# In single-run, only the orchestrator writes checkpoints here (trainer has its own dir), so no STABLE exists.
steps = get_stable_ckpt_steps(ckpt_dir) if self.max_runs > 1 else get_all_ckpt_steps(ckpt_dir)
self.progress[new_id].step = max(steps) if steps else 0
else:
self.progress[new_id].step = config.ckpt.resume_step
+7 -23
View File
@@ -96,31 +96,33 @@ class StaticInferencePool:
pass
async def setup_inference_pool(client_config: ClientConfig, model_name: str) -> InferencePool:
async def setup_inference_pool(
client_config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
) -> InferencePool:
"""Create an inference pool from config (static or elastic)."""
logger = get_logger()
if client_config.is_elastic:
from prime_rl.utils.elastic import ElasticInferencePool
return await ElasticInferencePool.from_config(client_config, model_name=model_name)
return await ElasticInferencePool.from_config(client_config, model_name=model_name, client_type=client_type)
logger.info(
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
)
return StaticInferencePool(
clients=setup_clients(client_config),
clients=setup_clients(client_config, client_type=client_type),
admin_clients=setup_admin_clients(client_config),
skip_model_check=client_config.skip_model_check,
)
def setup_clients(client_config: ClientConfig) -> list[vf.ClientConfig]:
def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_completions") -> list[vf.ClientConfig]:
def setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
return vf.ClientConfig(
client_idx=client_idx,
client_type="openai_chat_completions_token",
client_type=client_type,
api_base_url=base_url,
api_key_var=client_config.api_key_var,
timeout=client_config.timeout,
@@ -249,24 +251,6 @@ async def update_weights(
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
async def reload_weights(admin_clients: list[AsyncClient]) -> None:
"""Make a HTTP post request to the vLLM server to reload weights (reset to base model)."""
logger = get_logger()
async def _reload_weights(admin_client: AsyncClient) -> None:
logger.debug("Sending request to reload weights (reset to base model)")
try:
response = await admin_client.post("/reload_weights", json={})
response.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
logger.warning("The route /reload_weights does not exist. Skipping weight reload.")
return
raise
await asyncio.gather(*[_reload_weights(admin_client) for admin_client in admin_clients])
def _is_retryable_lora_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for LoRA loading."""
if isinstance(exception, httpx.HTTPStatusError):
+1 -1
View File
@@ -118,7 +118,7 @@ class LogConfig(BaseConfig):
vf_level: Annotated[
str,
Field(description="Logging level for the verifiers package. Will determine the logging verbosity and format."),
] = "warn"
] = "info"
file: Annotated[
bool,
+8 -2
View File
@@ -107,6 +107,7 @@ class ElasticInferencePool:
model_name: str,
port: int = 8000,
sync_interval: float = 5.0,
client_type: str = "openai_chat_completions",
):
self.logger = get_logger()
self.hostname = hostname
@@ -115,6 +116,7 @@ class ElasticInferencePool:
self.base_model_name = model_name # Keep original for health checks
self.port = port
self.sync_interval = sync_interval
self.client_type = client_type
self._servers: dict[str, ServerState] = {}
self._admin_clients: dict[str, AsyncClient] = {}
@@ -129,7 +131,9 @@ class ElasticInferencePool:
self._started = False
@classmethod
async def from_config(cls, config: ClientConfig, model_name: str) -> ElasticInferencePool:
async def from_config(
cls, config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
) -> ElasticInferencePool:
if config.elastic is None:
raise ValueError("Elastic inference pool requires elastic config")
pool = cls(
@@ -138,6 +142,7 @@ class ElasticInferencePool:
model_name=model_name,
port=config.elastic.port,
sync_interval=config.elastic.sync_interval,
client_type=client_type,
)
await pool.start()
return pool
@@ -168,7 +173,8 @@ class ElasticInferencePool:
base_url=urls,
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
)
),
client_type=self.client_type,
)
if urls
else []
+5 -2
View File
@@ -82,7 +82,7 @@ class JsonFileSink:
class InterceptHandler(logging.Handler):
"""Intercept standard logging library and routes to our prime-rl logger with specified prefix."""
def __init__(self, prefix: str):
def __init__(self, prefix: str | None):
super().__init__()
self.prefix = prefix
@@ -98,7 +98,10 @@ class InterceptHandler(logging.Handler):
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(level, f"[{self.prefix}] {record.getMessage()}")
message = record.getMessage()
if self.prefix is not None:
message = f"[{self.prefix}] {message}"
logger.opt(depth=depth, exception=record.exc_info).log(level, message)
def setup_logger(
+3
View File
@@ -114,6 +114,7 @@ class MetricsServer(HealthServer):
self._mismatch_kl = Gauge(
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
)
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
# Aggregate run metrics
self._runs_discovered = Gauge(
"trainer_runs_discovered", "Number of run folders discovered", registry=self._registry
@@ -206,6 +207,8 @@ class MetricsServer(HealthServer):
self._mfu.set(mfu)
self._entropy.set(entropy)
self._mismatch_kl.set(mismatch_kl)
if entropy > 0:
self._kl_ent_ratio.set(mismatch_kl / entropy)
self._last_step_ts.set(time.time())
def update_runs(
-25
View File
@@ -319,28 +319,3 @@ def get_env_ids_to_install(env_configs: list[EnvConfig] | list[EvalEnvConfig]) -
if "/" in env_config.id:
env_ids_to_install.add(env_config.id)
return env_ids_to_install
def is_chinese_char(char: str) -> bool:
"""Check if a character is Chinese (CJK Unified Ideographs and extensions)."""
code_point = ord(char)
return (
0x4E00 <= code_point <= 0x9FFF # CJK Unified Ideographs
or 0x3400 <= code_point <= 0x4DBF # CJK Extension A
or 0x20000 <= code_point <= 0x2A6DF # CJK Extension B
or 0x2A700 <= code_point <= 0x2B73F # CJK Extension C
or 0x2B740 <= code_point <= 0x2B81F # CJK Extension D
or 0x2B820 <= code_point <= 0x2CEAF # CJK Extension E
or 0xF900 <= code_point <= 0xFAFF # CJK Compatibility Ideographs
or 0x2F800 <= code_point <= 0x2FA1F # CJK Compatibility Ideographs Supplement
)
def count_chinese_chars(text: str) -> tuple[int, int]:
"""Count Chinese characters in text.
Returns:
Tuple of (chinese_char_count, total_char_count)
"""
chinese_count = sum(1 for char in text if is_chinese_char(char))
return chinese_count, len(text)
@@ -0,0 +1,67 @@
from functools import partial
from pathlib import Path
from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_avg_reward_in_range, check_no_error, check_number_goes_up_or_down, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
REWARD_MIN_THRESHOLD = 0.85
REWARD_AVG_LAST_N_STEPS = 7
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for RL CI integration tests."""
return f"multimodal-color-codeword-{branch_name}"
@pytest.fixture(scope="module")
def rl_process(
run_process: Callable[..., ProcessResult],
output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/nightly/multimodal_color_codeword.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd)
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
@pytest.fixture(scope="module")
def test_no_error(rl_process: ProcessResult, output_dir: Path):
"""Tests that the RL process does not fail."""
check_no_error(rl_process, output_dir)
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the reward goes up in the RL process"""
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_goes_up(orchestrator_stdout)
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the average reward over the last steps exceeds the threshold"""
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_avg_reward_in_range(
orchestrator_stdout, last_n_steps=REWARD_AVG_LAST_N_STEPS, min_threshold=REWARD_MIN_THRESHOLD
)
+347
View File
@@ -0,0 +1,347 @@
import math
from prime_rl.orchestrator.config import GibberishFilterConfig, RepetitionFilterConfig
from prime_rl.orchestrator.filters import (
GibberishFilter,
RepetitionFilter,
apply_filters,
setup_filter,
setup_filters,
)
def _make_rollout(completion_ids, completion_logprobs, reward=1.0, multi_step=False):
"""Create a minimal rollout dict matching the verifiers RolloutOutput structure."""
if multi_step:
mid = len(completion_ids) // 2
trajectory = [
{
"tokens": {
"completion_ids": completion_ids[:mid],
"completion_logprobs": completion_logprobs[:mid],
"completion_mask": [1] * mid,
}
},
{
"tokens": {
"completion_ids": completion_ids[mid:],
"completion_logprobs": completion_logprobs[mid:],
"completion_mask": [1] * (len(completion_ids) - mid),
}
},
]
else:
trajectory = [
{
"tokens": {
"completion_ids": completion_ids,
"completion_logprobs": completion_logprobs,
"completion_mask": [1] * len(completion_ids),
}
}
]
return {
"trajectory": trajectory,
"reward": reward,
"stop_condition": None,
"metrics": {},
}
def _make_gibberish_filter(vocab_size=128_000, token_id_threshold=100_000, logprob_offset=2.0, enforce=False):
logprob_threshold = -math.log(vocab_size) - logprob_offset
return GibberishFilter(
name="gibberish", token_id_threshold=token_id_threshold, logprob_threshold=logprob_threshold, enforce=enforce
)
def _make_repetition_filter(window=5, prob_threshold=0.99, enforce=False):
return RepetitionFilter(
name="repetition", window=window, logprob_threshold=math.log(prob_threshold), enforce=enforce
)
# --- GibberishFilter tests ---
def test_gibberish_detects_rare_low_prob_token():
gibberish_filter = _make_gibberish_filter()
result = gibberish_filter.check(
_make_rollout(
completion_ids=[50, 120_000, 80],
completion_logprobs=[-1.0, gibberish_filter.logprob_threshold - 1.0, -0.5],
)
)
assert result.detected is True
assert result.detection_index == 1
def test_gibberish_ignores_normal_tokens():
gibberish_filter = _make_gibberish_filter()
result = gibberish_filter.check(
_make_rollout(
completion_ids=[10, 200, 5000],
completion_logprobs=[-1.0, -2.0, -3.0],
)
)
assert result.detected is False
assert result.detection_index is None
def test_gibberish_ignores_high_prob_rare_token():
gibberish_filter = _make_gibberish_filter()
result = gibberish_filter.check(
_make_rollout(
completion_ids=[120_000],
completion_logprobs=[-0.5],
)
)
assert result.detected is False
def test_gibberish_works_across_trajectory_steps():
gibberish_filter = _make_gibberish_filter()
result = gibberish_filter.check(
_make_rollout(
completion_ids=[50, 60, 120_000, 80],
completion_logprobs=[-1.0, -0.5, gibberish_filter.logprob_threshold - 1.0, -0.5],
multi_step=True,
)
)
assert result.detected is True
assert result.detection_index == 2
# --- RepetitionFilter tests ---
def test_repetition_triggers_after_window():
repetition_filter = _make_repetition_filter(window=5)
result = repetition_filter.check(
_make_rollout(
completion_ids=list(range(5)),
completion_logprobs=[-0.001] * 5,
)
)
assert result.detected is True
assert result.detection_index == 4
def test_repetition_no_trigger_below_window():
repetition_filter = _make_repetition_filter(window=5)
result = repetition_filter.check(
_make_rollout(
completion_ids=list(range(4)),
completion_logprobs=[-0.001] * 4,
)
)
assert result.detected is False
def test_repetition_resets_on_low_prob():
repetition_filter = _make_repetition_filter(window=5)
logprobs = [-0.001] * 3 + [-2.0] + [-0.001] * 3
result = repetition_filter.check(
_make_rollout(
completion_ids=list(range(7)),
completion_logprobs=logprobs,
)
)
assert result.detected is False
def test_repetition_varied_probs_no_trigger():
repetition_filter = _make_repetition_filter(window=3)
result = repetition_filter.check(
_make_rollout(
completion_ids=list(range(6)),
completion_logprobs=[-0.001, -3.0, -0.001, -3.0, -0.001, -3.0],
)
)
assert result.detected is False
# --- setup_filter / setup_filters tests ---
def test_setup_filter_gibberish():
config = GibberishFilterConfig(token_id_threshold=100_000, logprob_offset=2.0)
gibberish_filter = setup_filter(config, vocab_size=128_000)
assert isinstance(gibberish_filter, GibberishFilter)
assert gibberish_filter.name == "gibberish"
assert gibberish_filter.token_id_threshold == 100_000
assert abs(gibberish_filter.logprob_threshold - (-math.log(128_000) - 2.0)) < 1e-10
assert gibberish_filter.enforce is False
def test_setup_filter_gibberish_enforce():
config = GibberishFilterConfig(enforce=True)
gibberish_filter = setup_filter(config, vocab_size=128_000)
assert gibberish_filter.enforce is True
def test_setup_filter_repetition():
config = RepetitionFilterConfig(window=3_000, prob_threshold=0.99)
repetition_filter = setup_filter(config, vocab_size=128_000)
assert isinstance(repetition_filter, RepetitionFilter)
assert repetition_filter.name == "repetition"
assert repetition_filter.window == 3_000
assert abs(repetition_filter.logprob_threshold - math.log(0.99)) < 1e-10
assert repetition_filter.enforce is False
def test_setup_filter_repetition_enforce():
config = RepetitionFilterConfig(enforce=True)
repetition_filter = setup_filter(config, vocab_size=128_000)
assert repetition_filter.enforce is True
def test_setup_filters_multiple():
configs = [
GibberishFilterConfig(),
RepetitionFilterConfig(),
]
filters = setup_filters(configs, vocab_size=128_000)
assert len(filters) == 2
assert filters[0].name == "gibberish"
assert filters[1].name == "repetition"
# --- apply_filters tests (enforce=True) ---
def test_apply_filters_enforced_zeros_mask():
gibberish_filter = _make_gibberish_filter(enforce=True)
rollout = _make_rollout(
completion_ids=[120_000],
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
reward=1.0,
)
metrics = apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert all(m == 0 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] == "gibberish"
assert rollout["metrics"]["filter/gibberish"] == 1.0
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/gibberish_rate"] == 1.0
assert metrics["filter/total_detected_rate"] == 1.0
assert metrics["filter/total_enforced_rate"] == 1.0
def test_apply_filters_preserves_clean_rollouts():
gibberish_filter = _make_gibberish_filter(enforce=True)
rollout = _make_rollout(
completion_ids=[50, 60, 70],
completion_logprobs=[-1.0, -2.0, -1.5],
reward=1.0,
)
metrics = apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] is None
assert metrics["filter/gibberish_count"] == 0.0
assert metrics["filter/total_detected_rate"] == 0.0
assert metrics["filter/total_enforced_rate"] == 0.0
def test_apply_filters_first_filter_wins():
gibberish_filter = _make_gibberish_filter(enforce=True)
repetition_filter = _make_repetition_filter(window=2, enforce=True)
rollout = _make_rollout(
completion_ids=[120_000, 1, 2],
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0, -0.001, -0.001],
reward=1.0,
)
metrics = apply_filters([gibberish_filter, repetition_filter], [rollout])
assert rollout["stop_condition"] == "gibberish"
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/repetition_count"] == 0.0
assert metrics["filter/total_detected_rate"] == 1.0
assert metrics["filter/total_enforced_rate"] == 1.0
def test_apply_filters_empty_list():
rollout = _make_rollout(
completion_ids=[1, 2, 3],
completion_logprobs=[-1.0, -1.0, -1.0],
)
metrics = apply_filters([], [rollout])
assert metrics == {}
assert rollout["reward"] == 1.0
def test_apply_filters_mixed_batch():
gibberish_filter = _make_gibberish_filter(enforce=True)
clean = _make_rollout(completion_ids=[50], completion_logprobs=[-1.0], reward=1.0)
dirty = _make_rollout(
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
)
metrics = apply_filters([gibberish_filter], [clean, dirty])
assert clean["reward"] == 1.0
assert dirty["reward"] == 1.0
assert all(m == 0 for m in dirty["trajectory"][0]["tokens"]["completion_mask"])
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/gibberish_rate"] == 0.5
assert metrics["filter/total_detected_rate"] == 0.5
assert metrics["filter/total_enforced_rate"] == 0.5
# --- apply_filters tests (monitor-only, enforce=False) ---
def test_apply_filters_monitor_only_tracks_detection():
gibberish_filter = _make_gibberish_filter(enforce=False)
rollout = _make_rollout(
completion_ids=[120_000],
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
reward=1.0,
)
metrics = apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] is None
assert rollout["metrics"]["filter/gibberish"] == 1.0
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/gibberish_rate"] == 1.0
assert metrics["filter/total_detected_rate"] == 1.0
assert metrics["filter/total_enforced_rate"] == 0.0
def test_apply_filters_monitor_only_mixed_batch():
gibberish_filter = _make_gibberish_filter(enforce=False)
clean = _make_rollout(completion_ids=[50], completion_logprobs=[-1.0], reward=1.0)
dirty = _make_rollout(
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
)
metrics = apply_filters([gibberish_filter], [clean, dirty])
assert clean["reward"] == 1.0
assert dirty["reward"] == 1.0
assert metrics["filter/gibberish_rate"] == 0.5
assert metrics["filter/total_detected_rate"] == 0.5
assert metrics["filter/total_enforced_rate"] == 0.0
+2
View File
@@ -8,6 +8,7 @@ from prime_rl.inference.config import InferenceConfig
from prime_rl.orchestrator.config import OrchestratorConfig
from prime_rl.rl import RLConfig
from prime_rl.slurm.rl import RLSLURMConfig
from prime_rl.slurm.sft import SFTSLURMConfig
from prime_rl.trainer.rl.config import RLTrainerConfig
from prime_rl.trainer.sft.config import SFTTrainerConfig
from prime_rl.utils.pydantic_config import parse_argv
@@ -20,6 +21,7 @@ CONFIG_CLASSES = [
OrchestratorConfig,
InferenceConfig,
RLSLURMConfig,
SFTSLURMConfig,
]
+41
View File
@@ -0,0 +1,41 @@
import pytest
from prime_rl.inference.config import ModelConfig
@pytest.mark.parametrize(
"model_name,expected_parser",
[
# GLM-4.5
("zai-org/GLM-4.5", "glm45"),
("zai-org/GLM-4.5-Air", "glm45"),
("zai-org/GLM-4.5V", "glm45"),
# GLM-4.7
("zai-org/GLM-4.7", "glm47"),
("zai-org/GLM-4.7-Flash", "glm47"),
# MiniMax
("MiniMaxAI/MiniMax-M2", "minimax_m2"),
("MiniMaxAI/MiniMax-M2.1", "minimax_m2"),
("MiniMaxAI/MiniMax-M2.5", "minimax_m2"),
# INTELLECT
("PrimeIntellect/INTELLECT-3", "hermes"),
("PrimeIntellect/INTELLECT-3-FP8", "hermes"),
("PrimeIntellect/INTELLECT-3.1", "hermes"),
# Qwen3
("Qwen/Qwen3-0.6B", "hermes"),
("Qwen/Qwen3-32B", "hermes"),
("Qwen/Qwen3-235B-A22B", "hermes"),
("Qwen/Qwen3-4B-Instruct-2507", "hermes"),
("Qwen/Qwen3-Coder-480B-A35B-Instruct", "hermes"),
("Qwen/Qwen3-Next-80B-A3B-Instruct", "hermes"),
("Qwen/Qwen3.5-397B-A17B", "hermes"),
],
)
def test_auto_detect_tool_call_parser(model_name: str, expected_parser: str):
config = ModelConfig(name=model_name)
assert config.tool_call_parser == expected_parser
def test_explicit_parser_overrides_auto_detect():
config = ModelConfig(name="Qwen/Qwen3-4B-Instruct-2507", tool_call_parser="qwen3_xml")
assert config.tool_call_parser == "qwen3_xml"
+11 -2
View File
@@ -1,6 +1,6 @@
import pytest
import torch
from transformers import AutoConfig, AutoModelForCausalLM
from transformers import AutoConfig, AutoModelForCausalLM, GenerationConfig
from prime_rl.trainer.perf import PerfCounter
@@ -14,7 +14,16 @@ def test_perf_counter(model_name: str, active_params: int, flops_per_token: int)
with torch.device("meta"):
config = AutoConfig.from_pretrained(model_name)
if getattr(config, "pad_token_id", None) is None:
config.pad_token_id = config.eos_token_id
gen_config = GenerationConfig.from_model_config(config)
# Use `is not None` instead of truthiness: token ID 0 is valid.
config.pad_token_id = next(
(
v
for v in [gen_config.pad_token_id, gen_config.eos_token_id, getattr(config, "eos_token_id", None)]
if v is not None
),
None,
)
model = AutoModelForCausalLM.from_config(config)
perf_counter = PerfCounter(model, seq_len=1024, window_size=10)
+6 -1
View File
@@ -92,6 +92,7 @@ def test_server_update_metrics():
assert "trainer_loss" in content
assert "trainer_last_step_timestamp_seconds" in content
assert "trainer_mismatch_kl" in content
assert "trainer_kl_ent_ratio" in content
server.stop()
@@ -102,6 +103,8 @@ def test_server_metrics_values_are_correct():
server.start()
time.sleep(0.1)
entropy = 1.5
mismatch_kl = 0.045
server.update(
step=100,
loss=0.123,
@@ -109,7 +112,8 @@ def test_server_metrics_values_are_correct():
grad_norm=2.5,
peak_memory_gib=16.0,
learning_rate=3e-5,
mismatch_kl=0.045,
entropy=entropy,
mismatch_kl=mismatch_kl,
)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
@@ -118,6 +122,7 @@ def test_server_metrics_values_are_correct():
assert "trainer_step 100.0" in content
assert "trainer_loss 0.123" in content
assert "trainer_mismatch_kl 0.045" in content
assert f"trainer_kl_ent_ratio {mismatch_kl / entropy}" in content
server.stop()
+33
View File
@@ -116,6 +116,39 @@ def check_reward_in_range(
)
def check_avg_reward_in_range(
lines: list[str],
last_n_steps: int,
min_threshold: float | None = None,
max_threshold: float | None = None,
):
"""Helper to assert that the average reward over the last N steps is within a threshold"""
pattern = r"Reward:\s*(\d+\.\d{4})"
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
assert len(step_lines) >= last_n_steps, (
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
)
recent_lines = step_lines[-last_n_steps:]
rewards = []
for line in recent_lines:
match = re.search(pattern, line)
assert match is not None, f"Could not find Reward in line: {line}"
rewards.append(float(match.group(1)))
avg_reward = sum(rewards) / len(rewards)
if min_threshold is not None:
assert avg_reward >= min_threshold, (
f"Average reward over last {last_n_steps} steps did not reach minimum threshold. "
f"Found avg_reward={avg_reward:.4f} < {min_threshold} (rewards={rewards})"
)
if max_threshold is not None:
assert avg_reward <= max_threshold, (
f"Average reward over last {last_n_steps} steps exceeded maximum threshold. "
f"Found avg_reward={avg_reward:.4f} > {max_threshold} (rewards={rewards})"
)
def check_mismatch_kl_in_range(
lines: list[str],
step: int = -1,
Generated
+2 -2
View File
@@ -2373,7 +2373,7 @@ requires-dist = [
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ad77074" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=9052ecf" },
{ name = "vllm", url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" },
{ name = "wandb", specifier = ">=0.24.2" },
]
@@ -3702,7 +3702,7 @@ wheels = [
[[package]]
name = "verifiers"
version = "0.1.11.dev0"
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ad77074#ad77074e6e8585242425aabd598fc102584a0777" }
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=9052ecf#9052ecf0c794cd539b5555ae620c3d8935b347cd" }
dependencies = [
{ name = "anthropic" },
{ name = "datasets" },