Compare commits

...
Author SHA1 Message Date
will brownandGitHub 944163ac68 track seqs per rollout (#1852)
Release / Push CUDA image to Docker (push) Canceled after 0s
* track seqs per rollout

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

* Add CHANGELOG entry for orchestrator.use_token_client config field

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

---------

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

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

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

* add sft example

* add SFT MoE SLURM example and slim down SFT docs

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

* add sft slur config to tests

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 18:31:36 -08:00
11 changed files with 284 additions and 12 deletions
+1
View File
@@ -61,4 +61,5 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`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)
+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
+1
View File
@@ -44,6 +44,7 @@ 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"
+7
View File
@@ -825,6 +825,13 @@ class OrchestratorConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
use_token_client: Annotated[
bool,
Field(
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
),
] = True
@model_validator(mode="after")
def validate_unique_filter_types(self):
types = [f.type for f in self.filters]
+16 -1
View File
@@ -103,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:
@@ -491,12 +497,14 @@ async def orchestrate(config: OrchestratorConfig):
train_examples: list[TrainingSample] = []
rollout_prefill_lens: list[int] = []
rollout_decode_lens: list[int] = []
rollout_samples_per_rollout: list[int] = []
num_prefill_tokens = 0
num_decode_tokens = 0
for rollout, advantage, samples in zip(train_rollouts, advantages, results):
rollout_prefill_tokens = 0
rollout_decode_tokens = 0
if samples is not None:
rollout_samples_per_rollout.append(len(samples))
for sample in samples:
sample.advantage = advantage
sample.reward = rollout["reward"]
@@ -505,6 +513,8 @@ async def orchestrate(config: OrchestratorConfig):
rollout_decode_tokens += sample_decode_tokens
rollout_prefill_tokens += sample_prefill_tokens
train_examples.append(sample)
else:
rollout_samples_per_rollout.append(0)
rollout_prefill_lens.append(rollout_prefill_tokens)
rollout_decode_lens.append(rollout_decode_tokens)
num_prefill_tokens += rollout_prefill_tokens
@@ -572,6 +582,7 @@ async def orchestrate(config: OrchestratorConfig):
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
"prefill_len": rollout_prefill_lens,
"decode_len": rollout_decode_lens,
"samples_per_rollout": rollout_samples_per_rollout,
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
@@ -634,6 +645,10 @@ async def orchestrate(config: OrchestratorConfig):
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
# Seqs per rollout metrics
"samples_per_rollout/mean": results_df.groupby("example_id").samples_per_rollout.mean().mean(),
"samples_per_rollout/max": results_df.groupby("example_id").samples_per_rollout.mean().max(),
"samples_per_rollout/min": results_df.groupby("example_id").samples_per_rollout.mean().min(),
# Turn metrics
"num_turns/mean": results_df.groupby("example_id").num_turns.mean().mean(),
"num_turns/max": results_df.groupby("example_id").num_turns.mean().max(),
+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
'
+7 -5
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,
+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 []
+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,
]