Compare commits

...
Author SHA1 Message Date
3102ca47cb Add SLURM entrypoint with Jinja2 template (#1774)
Release / Push CUDA image to Docker (push) Canceled after 0s
* refactor config

* Add SLURM entrypoint with Jinja2 template and tmux launcher

Adds a new `rl_slurm` entrypoint that resolves the full RL config,
dumps sub-configs as TOML, renders a SLURM batch script from a Jinja2
template, and submits it via sbatch (with --dry-run option). Includes
a tmux launcher for monitoring trainer/orchestrator/inference logs and
documentation.

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

* fix ruff formatting

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

* fix(slurm): sync orchestrator output dir with cleanup

Co-authored-by: samsja <samsja@users.noreply.github.com>

* test(configs): include slurm config parser in config loading test

Co-authored-by: samsja <samsja@users.noreply.github.com>

* add auto dir

* fix(slurm): move auto_setup_output_dir to BaseRLConfig so SLURM entrypoint propagates output_dir

RLSLURMConfig extends BaseRLConfig, not RLConfig, so the validator that
propagates output_dir to trainer and orchestrator was never running.
This caused the Jinja template cleanup to target wrong paths and the
trainer to pick up stale rollouts.

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

* add args

* feat(slurm): make config more flexible and self-contained

- Replace base_dir/env_file/venv with single project_dir
- Add gpus_per_node (default 8) to remove hardcoded GPU counts
- Add nodes_per_fsdp_group to auto-compute dp_replicate
- Use -m module syntax for torchrun instead of file path
- Derive .env and .venv paths from project_dir

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

* fix many stuff

* add math

* addexamples

* add moe example

* docs(slurm): update to Hendrycks Math examples with MoE config

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

* fix: add required output_dir to slurm example configs

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: samsja <samsja@users.noreply.github.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-02-17 13:10:27 -08:00
7c40b334e6 fix: MoE weight conversion for vLLM compatibility (#1812)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: use per-expert format in MoE weight conversion for vLLM compatibility

convert_tt_layer_to_hf was producing transformers v5 fused format
(experts.gate_up_proj, experts.down_proj) but vLLM expects per-expert
format (experts.{j}.gate_proj.weight, etc). This caused KeyError during
weight updates in the inference server. Also adds MoE RL integration
tests for both hf and custom impl.

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

* fix: use underscores in MoE TOML config keys

Hyphens only work as CLI args, TOML config needs underscores.

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

* test: remove HF round-trip tests for MoE models

The MoE weight conversion now outputs per-expert format for vLLM
compatibility, which is incompatible with HF transformers 5.0+ fused
format. Remove the round-trip tests that loaded converted weights
back into HF models since vLLM is the target format.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-02-17 12:28:55 -08:00
aaeb711501 Add MiniMax M2.1 MoE model support (#1773)
Release / Push CUDA image to Docker (push) Canceled after 0s
Implement full pipeline for MiniMax M2.1 (230B MoE, 10B activated/token):
modeling code, HF<->PrimeRL weight conversion, registration, and mini-model
verification.

Key additions:
- Per-layer QK norm support in shared attention (qk_norm_type="per_layer")
- MiniMax M2.1 model module with config, conversion, and modeling
- Mini model preset for testing at small scale
- Refactored mini_moe.py to support remote-code HF models

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 11:07:04 -08:00
minh hoangandGitHub 6c8faec459 helm:specify deployment component in container name (#1793)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-17 16:24:02 +01:00
Mika SenghaasandGitHub 95a53f39e7 implement optional cancellation of inflight rollouts before eval (#1802)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-16 12:30:12 -08:00
halleriteandGitHub 0756df77c1 fix missing param (#1808)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-16 10:20:14 -08:00
66b1f4b6b7 configure default logger instead of raise (#1804)
Release / Push CUDA image to Docker (push) Canceled after 0s
* configure default logger instead of raise

* fix: cleanup old logger resources when calling setup_logger

Calling setup_logger multiple times now properly cleans up the old
logger instance by calling logger.remove() before creating a new one.
This prevents resource leaks:
- Background threads from enqueue=True handlers are stopped
- JsonFileSink file handles are properly released

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: add cleanup to reset_logger to prevent resource leaks

Calling reset_logger now properly cleans up the logger instance by
calling logger.remove() before setting _LOGGER to None. This ensures
that any active handlers (file sinks, enqueued handlers, background
threads) are properly released, matching the cleanup pattern in
setup_logger.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 09:52:47 -08:00
32 changed files with 1807 additions and 381 deletions
+4
View File
@@ -5,6 +5,10 @@ configs/endpoints.py
# Artifacts
**/slurm
!src/prime_rl/slurm
!examples/slurm
!scripts/slurm_tmux.sh
!docs/slurm.md
**/torchrun
**/weights
**/checkpoints
+2 -1
View File
@@ -56,6 +56,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12
- **`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.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)
+29
View File
@@ -0,0 +1,29 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
[ckpt]
[model]
name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[[orchestrator.env]]
id = "reverse-text"
[inference]
gpu_memory_utilization = 0.7
[inference.model]
max_model_len = 2048
+2 -2
View File
@@ -83,7 +83,7 @@ uv run torchrun \
### SLURM
TBD.
See the dedicated [SLURM guide](slurm.md).
## Inference
@@ -281,7 +281,7 @@ Of course, you can further scale up the number of nodes used by the trainer and
### SLURM
TBD.
See the dedicated [SLURM guide](slurm.md).
## Kubernetes
+154
View File
@@ -0,0 +1,154 @@
# 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`.
```bash
uv run python -m prime_rl.slurm.rl @ examples/slurm/hendrycks_math.toml
```
This will:
1. Write resolved sub-configs to `{output_dir}/configs/` (trainer.toml, orchestrator.toml, inference.toml)
2. Render the SLURM script to `{output_dir}/rl.sh`
3. Submit the job via `sbatch`
To only generate the script without submitting, use `--dry-run`:
```bash
uv run python -m prime_rl.slurm.rl @ examples/slurm/hendrycks_math.toml --dry-run
```
## Configuration
The SLURM config extends the standard RL config with the following fields:
| Field | Description |
|---|---|
| `job_name` | SLURM job name |
| `output_dir` | Directory for outputs, sub-configs, and logs |
| `project_dir` | Path to the project root on the cluster (defaults to cwd) |
| `num_train_nodes` | Number of nodes for training |
| `num_infer_nodes` | Number of nodes for inference |
| `gpus_per_node` | Number of GPUs per node (default: 8) |
| `nodes_per_fsdp_group` | Number of train nodes per FSDP island (optional, auto-sets `trainer.dp_replicate`) |
| `slurm_template` | Path to a custom Jinja2 template (optional) |
| `dry_run` | Only generate the script without submitting (default: false) |
All standard RL config fields (model, trainer, orchestrator, inference, wandb, ckpt, etc.) are available and will be resolved into the sub-configs.
### Dense model (Hendrycks Math)
```toml
job_name = "hendrycks-math"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[wandb]
project = "hendrycks-math"
name = "hendrycks-math"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[inference.parallel]
tp = 1
dp = 8
```
### MoE model (Hendrycks Math)
For MoE models like `Qwen3-30B-A3B`, the config is designed to minimize memory usage on a single training node. It enables activation checkpointing with offloading, optimizer CPU offload, and NCCL weight broadcast:
```toml
job_name = "hendrycks-math-moe"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[weight_broadcast]
type = "nccl"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[trainer.model.ac_offloading]
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[inference.parallel]
tp = 4
dp = 2
```
## 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:
```bash
uv run python -m prime_rl.slurm.rl \
@ my_config.toml \
--slurm-template path/to/my_template.sh.j2
```
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
After submission, the logs are available at:
```bash
tail -f {output_dir}/slurm/latest_train_node_rank_0.log
tail -f {output_dir}/slurm/latest_infer_node_rank_0.log
tail -f {output_dir}/slurm/latest_orchestrator.log
```
For convenience, a tmux launcher is provided that sets up a session with all three log streams:
```bash
bash scripts/slurm_tmux.sh my-rl-job /shared/outputs/my-rl-job
```
This creates a tmux session `slurm-my-rl-job` with two windows:
- **Window 0 (Terminal)**: a plain shell for running commands
- **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.
+41
View File
@@ -0,0 +1,41 @@
job_name = "hendrycks-math"
output_dir = "outputs/hendrycks-math"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[log]
level = "debug"
[wandb]
project = "hendrycks-math-debug"
name = "hendrycks-math"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[trainer]
[inference.parallel]
tp = 1
dp = 8
+53
View File
@@ -0,0 +1,53 @@
job_name = "hendrycks-math-moe"
output_dir = "outputs/hendrycks-math-moe"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[log]
level = "debug"
[wandb]
project = "hendrycks-math-debug"
name = "hendrycks-math"
[weight_broadcast]
type = "nccl"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[trainer.model.ac_offloading]
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[inference.parallel]
tp = 4
dp = 2
+3 -3
View File
@@ -27,7 +27,7 @@ spec:
{{- toYaml . | nindent 8 }}
{{- end }}
containers:
- name: prime-rl
- name: prime-rl-orchestrator
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.orchestrator.autoStart }}
@@ -133,7 +133,7 @@ spec:
runtimeClassName: {{ .Values.inference.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl
- name: prime-rl-inference
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.inference.autoStart }}
@@ -262,7 +262,7 @@ spec:
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl
- name: prime-rl-trainer
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.trainer.autoStart }}
+2
View File
@@ -25,6 +25,7 @@ dependencies = [
"prime>=0.5.37",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"math-env",
"tenacity>=8.2.0",
"openai>=1.106.1",
"rich>=14.0.0",
@@ -77,6 +78,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" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
+61 -9
View File
@@ -15,12 +15,14 @@ import argparse
from pathlib import Path
import torch
from transformers import AutoConfig, AutoTokenizer
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.utils import default_dtype
@@ -57,21 +59,70 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
"tokenizer_source": "THUDM/GLM-4-9B-0414",
},
"minimax_m2": {
"config_class": MiniMaxM2Config,
"config_kwargs": dict(
vocab_size=200064,
hidden_size=512,
intermediate_size=256,
num_hidden_layers=12,
num_attention_heads=8,
num_key_value_heads=4,
head_dim=64,
hidden_act="silu",
max_position_embeddings=4096,
rms_norm_eps=1e-6,
rope_theta=5000000,
rotary_dim=32,
num_local_experts=8,
num_experts_per_tok=4,
scoring_func="sigmoid",
use_routing_bias=True,
use_qk_norm=True,
qk_norm_type="per_layer",
use_grouped_mm=False,
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
),
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
}
def _create_hf_model(preset, config):
"""Create an HF model from a preset and config."""
hf_cls = preset["hf_model_class"]
if hf_cls is not None:
return hf_cls(config)
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
def _load_hf_model(preset, model_dir, config):
"""Load an HF model from a preset and directory."""
hf_cls = preset["hf_model_class"]
if hf_cls is not None:
return hf_cls.from_pretrained(str(model_dir), config=config)
return AutoModelForCausalLM.from_pretrained(str(model_dir), config=config, trust_remote_code=True)
def _create_hf_model_from_config(preset, config):
"""Create an empty HF model from config (for roundtrip verification)."""
hf_cls = preset["hf_model_class"]
if hf_cls is not None:
return hf_cls._from_config(config)
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
def create(arch: str, output_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
config = preset["config_class"](**preset["config_kwargs"])
print(f"Creating mini {arch} model...")
print(
f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}, "
f"experts={config.n_routed_experts}, moe_intermediate_size={config.moe_intermediate_size}"
)
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
with torch.device("cpu"):
model = preset["hf_model_class"](config)
model = _create_hf_model(preset, config)
param_count = sum(p.numel() for p in model.parameters())
print(f" Parameters: {param_count / 1e6:.1f}M")
@@ -89,11 +140,12 @@ def verify(arch: str, model_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
config = AutoConfig.from_pretrained(str(model_dir))
trust_remote_code = preset["hf_model_class"] is None
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
config._attn_implementation = "sdpa"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = preset["hf_model_class"].from_pretrained(str(model_dir), config=config)
hf_model = _load_hf_model(preset, model_dir, config)
prime_model = preset["prime_model_class"]._from_config(config)
with torch.no_grad():
@@ -118,7 +170,7 @@ def verify(arch: str, model_dir: Path) -> None:
with torch.no_grad():
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
with torch.device("cuda"), default_dtype(torch.float32):
hf_roundtrip = preset["hf_model_class"]._from_config(config)
hf_roundtrip = _create_hf_model_from_config(preset, config)
hf_roundtrip.load_state_dict(roundtrip_state_dict)
hf_roundtrip_output = hf_roundtrip(input_ids, position_ids)
+50
View File
@@ -0,0 +1,50 @@
#!/bin/bash
JOB_NAME="$1"
OUTPUT_DIR="$2"
if [[ -z "$JOB_NAME" || -z "$OUTPUT_DIR" ]]; then
echo "Usage: $0 JOB_NAME OUTPUT_DIR" >&2
exit 1
fi
SLURM_LOG_DIR="${OUTPUT_DIR}/slurm"
SESSION_NAME="slurm-${JOB_NAME}"
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
echo "Attaching to existing tmux session: $SESSION_NAME"
exec tmux attach-session -t "$SESSION_NAME"
fi
echo "Creating tmux session: $SESSION_NAME"
# Window 0: Terminal
tmux new-session -d -s "$SESSION_NAME" -n "Terminal"
# Window 1: Logs - 3 vertical panes
tmux new-window -t "$SESSION_NAME" -n "Logs"
tmux split-window -v -t "$SESSION_NAME:Logs.0"
tmux split-window -v -t "$SESSION_NAME:Logs.1"
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Inference"
tmux send-keys -t "$SESSION_NAME:Logs.0" \
"tail -F ${SLURM_LOG_DIR}/latest_train_node_rank_*.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.1" \
"tail -F ${SLURM_LOG_DIR}/latest_orchestrator.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.2" \
"tail -F ${SLURM_LOG_DIR}/latest_infer_node_rank_*.log 2>/dev/null" C-m
# Pane title styling
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
tmux set-option -t "$SESSION_NAME" -g pane-border-format " #{pane_title} "
# Focus Terminal window and attach
tmux select-window -t "$SESSION_NAME:Terminal"
exec tmux attach-session -t "$SESSION_NAME"
+7
View File
@@ -376,6 +376,13 @@ class EvalConfig(BaseConfig):
),
] = True
cancel_inflight_rollouts_on_eval: Annotated[
bool,
Field(
description="Whether to cancel in-flight training rollouts before starting online evals. This is useful to avoid congestion (e.g. do not have training + eval rollouts happening at the same time) but leads to slower training steps as rollouts get cancelled and the pipeline has to fill up after each eval",
),
] = False
class CheckpointConfig(BaseConfig):
"""Configures checkpointing the orchestrator."""
+10 -4
View File
@@ -381,10 +381,15 @@ async def orchestrate(config: OrchestratorConfig):
last_eval_step = ckpt_step
logger.info(f"Running evals for checkpoint step {ckpt_step}")
# Pause weight updates during eval and cancel inflight rollouts
# this avoid doing eval across different checkpoints and avoid congestion
# Pause weight updates and re-scheduling of training rollouts during eval
# to avoid evaluating across different checkpoints and avoid congestion
scheduler.checkpoint_ready.clear()
scheduler.cancel_all_inflight_rollouts()
# For heavy eval workloads, it might be necessary additionally cancel in-flight training rollouts
if config.eval.cancel_inflight_rollouts_on_eval:
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
scheduler.cancel_inflight_rollouts()
results = await asyncio.gather(
*[
evaluate_env(
@@ -747,6 +752,7 @@ async def orchestrate(config: OrchestratorConfig):
sampling_args=eval_sampling_args,
num_examples=eval_env_config.num_examples or config.eval.num_examples,
rollouts_per_example=eval_env_config.rollouts_per_example or config.eval.rollouts_per_example,
max_retries=eval_env_config.max_retries,
ckpt_step=ckpt_step,
step=progress.step,
)
@@ -770,7 +776,7 @@ async def orchestrate(config: OrchestratorConfig):
rollout_executor.shutdown(wait=False)
# Stop scheduler
scheduler.cancel_all_inflight_rollouts()
scheduler.cancel_inflight_rollouts()
update_policy_task.cancel()
# Stop inference pool
+2 -5
View File
@@ -95,11 +95,8 @@ class Scheduler:
"""Update sampling args for future rollout requests."""
self.sampling_args = sampling_args
def cancel_all_inflight_rollouts(self):
"""Cancel all in-flight rollout requests.
Used when weights are updated to discard stale rollouts generated with old weights.
"""
def cancel_inflight_rollouts(self):
"""Cancel all in-flight rollout requests."""
count = len(self.inflight_group_rollouts)
for future in list(self.inflight_group_rollouts.keys()):
if not future.done():
+2 -266
View File
@@ -16,17 +16,8 @@ import tomli_w
from pydantic import Field, model_validator
from prime_rl.inference.config import InferenceConfig
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpointConfig
from prime_rl.orchestrator.config import FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig
from prime_rl.orchestrator.config import NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig
from prime_rl.orchestrator.config import OrchestratorConfig
from prime_rl.trainer.config import CheckpointConfig as TrainerCheckpointConfig
from prime_rl.rl_config import BaseRLConfig
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig
from prime_rl.trainer.rl.config import RLTrainerConfig as TrainerConfig
from prime_rl.utils.config import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
from prime_rl.utils.utils import (
@@ -35,15 +26,6 @@ from prime_rl.utils.utils import (
get_log_dir,
get_rollout_dir,
)
from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_async_level,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_output_dir,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
class SharedLogConfig(BaseSettings):
@@ -112,29 +94,9 @@ class SharedWeightBroadcastConfig(BaseSettings):
)
class RLConfig(BaseSettings):
class RLConfig(BaseRLConfig):
"""Configures an RL training run."""
### Submodule configurations
trainer: TrainerConfig
orchestrator: OrchestratorConfig
inference: Annotated[
InferenceConfig | None,
Field(
description="The inference config. If None, will not start an inference process. Only viable, if an inference server was started manually."
),
] = None
### Top-level configurations
log: Annotated[
SharedLogConfig,
Field(
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
),
] = SharedLogConfig()
clean: Annotated[
bool,
Field(
@@ -165,55 +127,6 @@ class RLConfig(BaseSettings):
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
] = Path("outputs") # NOTE: Must match `OUTPUT_DIR` in `tmux.sh` to see logs
ckpt: Annotated[
SharedCheckpointConfig | None,
Field(
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
),
] = None
wandb: Annotated[
SharedWandbConfig | None,
Field(
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
),
] = None
model: Annotated[
SharedModelConfig | None,
Field(
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
),
] = None
max_steps: Annotated[
int | None,
Field(
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
),
] = None
max_model_len: Annotated[
int | None,
Field(
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
),
] = None
seq_len: Annotated[
int | None,
Field(
description="The sequence length to use. If set, will configure both trainer.model.seq_len and orchestrator.seq_len to this value. If None, each can be set independently."
),
] = None
max_async_level: Annotated[
int | None,
Field(
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
),
] = None
bench: Annotated[
bool,
Field(
@@ -221,10 +134,6 @@ class RLConfig(BaseSettings):
),
] = False
weight_broadcast: Annotated[
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
] = None
dump_config: Annotated[
Path | None,
Field(
@@ -250,83 +159,6 @@ class RLConfig(BaseSettings):
return self
@model_validator(mode="after")
def auto_setup_logs(self):
# Copy log level
if self.log is not None:
if self.log.level is not None:
self.trainer.log.level = self.log.level
self.orchestrator.log.level = self.log.level
if self.log.file is not None:
self.trainer.log.file = self.log.file
self.orchestrator.log.file = self.log.file
self.trainer.log.json_logging = self.log.json_logging
self.orchestrator.log.json_logging = self.log.json_logging
return self
### Setup and validate shared configs
@model_validator(mode="after")
def auto_setup_ckpt(self):
# If specified, automatically setup checkpoint configs for trainer and orchestrator
if self.ckpt is not None:
# Create checkpoint configs if not specified
if self.trainer.ckpt is None:
self.trainer.ckpt = TrainerCheckpointConfig()
if self.orchestrator.ckpt is None:
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
# If specified, use the same ckpt interval
if self.ckpt.interval is not None:
self.trainer.ckpt.interval = self.ckpt.interval
self.orchestrator.ckpt.interval = self.ckpt.interval
# If resuming training, ensure orchestrator resume from the same step
if self.ckpt.resume_step is not None:
self.trainer.ckpt.resume_step = self.ckpt.resume_step
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
# If specified, propagate keep policy
if self.ckpt.keep_last is not None:
self.trainer.ckpt.keep_last = self.ckpt.keep_last
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
if self.ckpt.keep_interval is not None:
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
validate_shared_ckpt_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_wandb(self):
# If specified, automatically use shared W&B project for orchestrator and trainer
if self.wandb is not None:
if not self.trainer.wandb:
self.trainer.wandb = WandbConfig()
if not self.orchestrator.wandb:
self.orchestrator.wandb = WandbWithExtrasConfig()
if self.wandb.project:
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
validate_shared_wandb_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
@@ -347,88 +179,6 @@ class RLConfig(BaseSettings):
return self
@model_validator(mode="after")
def auto_setup_model(self):
# Use the same model for trainer, orchestrator and inference
if self.model is not None:
self.trainer.model.name = self.model.name
self.orchestrator.model.name = self.model.name
if self.inference is not None:
self.inference.model.name = self.model.name
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_max_steps(self):
# If specified, use the same max steps for trainer and orchestrator
if self.max_steps is not None:
self.trainer.max_steps = self.max_steps
self.orchestrator.max_steps = self.max_steps
validate_shared_max_steps(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_async_level(self):
# If specified, use the same async level for trainer and orchestrator
if self.max_async_level is not None:
self.trainer.max_async_level = self.max_async_level
self.orchestrator.max_async_level = self.max_async_level
validate_shared_max_async_level(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_output_dir(self):
# If specified, use the same outputs directory for trainer and orchestrator
if self.output_dir is not None:
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_seq_len(self):
# If specified, use the same seq_len for trainer and orchestrator
if self.seq_len is not None:
self.trainer.model.seq_len = self.seq_len
self.orchestrator.seq_len = self.seq_len
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
return self
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type, inference_world_size=inference_world_size
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
@@ -485,20 +235,6 @@ class RLConfig(BaseSettings):
return self
@model_validator(mode="after")
def warn_wandb_resume_id_missing(self):
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
if self.trainer.wandb and not self.trainer.wandb.id:
warnings.warn(
"W&B run ID is not set for trainer even though resuming training. The current run will be created as a new run."
)
if self.orchestrator.ckpt is not None and self.orchestrator.ckpt.resume_step is not None:
if self.orchestrator.wandb and not self.orchestrator.wandb.id:
warnings.warn(
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.trainer.weight_broadcast.type == "nccl":
+346
View File
@@ -0,0 +1,346 @@
import warnings
from pathlib import Path
from typing import Annotated, Literal
from pydantic import Field, model_validator
from prime_rl.inference.config import InferenceConfig
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpointConfig
from prime_rl.orchestrator.config import FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig
from prime_rl.orchestrator.config import NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig
from prime_rl.orchestrator.config import OrchestratorConfig
from prime_rl.trainer.config import CheckpointConfig as TrainerCheckpointConfig
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig
from prime_rl.trainer.rl.config import RLTrainerConfig as TrainerConfig
from prime_rl.utils.config import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.pydantic_config import BaseSettings
from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_async_level,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_output_dir,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
class SharedLogConfig(BaseSettings):
"""Configures shared logging."""
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
file: Annotated[bool | None, Field(description="Whether to log to a file.")] = True
json_logging: Annotated[
bool,
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
] = False
class SharedWandbConfig(BaseSettings):
"""Configures shared W&B configs."""
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
class SharedCheckpointConfig(BaseSettings):
"""Configures shared checkpoint configs."""
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
resume_step: Annotated[
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
] = None
keep_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
class SharedModelConfig(BaseSettings):
"""Configures shared model settings."""
name: Annotated[
str,
Field(description="The name of the model to use."),
] = "Qwen/Qwen3-0.6B"
class SharedWeightBroadcastConfig(BaseSettings):
"""Configures shared weight broadcast settings."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
"filesystem"
)
class BaseRLConfig(BaseSettings):
"""Configures an RL training run."""
### Submodule configurations
trainer: TrainerConfig
orchestrator: OrchestratorConfig
output_dir: Annotated[
Path | None,
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
] = None
inference: Annotated[
InferenceConfig | None,
Field(
description="The inference config. If None, will not start an inference process. Only viable, if an inference server was started manually."
),
] = None
### Top-level configurations
log: Annotated[
SharedLogConfig,
Field(
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
),
] = SharedLogConfig()
ckpt: Annotated[
SharedCheckpointConfig | None,
Field(
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
),
] = None
wandb: Annotated[
SharedWandbConfig | None,
Field(
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
),
] = None
model: Annotated[
SharedModelConfig | None,
Field(
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
),
] = None
max_steps: Annotated[
int | None,
Field(
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
),
] = None
max_model_len: Annotated[
int | None,
Field(
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
),
] = None
seq_len: Annotated[
int | None,
Field(
description="The sequence length to use. If set, will configure both trainer.model.seq_len and orchestrator.seq_len to this value. If None, each can be set independently."
),
] = None
max_async_level: Annotated[
int | None,
Field(
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
),
] = None
weight_broadcast: Annotated[
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
] = None
### Setup and validate shared configs
@model_validator(mode="after")
def auto_setup_logs(self):
if self.log is not None:
if self.log.level is not None:
self.trainer.log.level = self.log.level
self.orchestrator.log.level = self.log.level
if self.log.file is not None:
self.trainer.log.file = self.log.file
self.orchestrator.log.file = self.log.file
self.trainer.log.json_logging = self.log.json_logging
self.orchestrator.log.json_logging = self.log.json_logging
return self
@model_validator(mode="after")
def auto_setup_ckpt(self):
# If specified, automatically setup checkpoint configs for trainer and orchestrator
if self.ckpt is not None:
# Create checkpoint configs if not specified
if self.trainer.ckpt is None:
self.trainer.ckpt = TrainerCheckpointConfig()
if self.orchestrator.ckpt is None:
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
# If specified, use the same ckpt interval
if self.ckpt.interval is not None:
self.trainer.ckpt.interval = self.ckpt.interval
self.orchestrator.ckpt.interval = self.ckpt.interval
# If resuming training, ensure orchestrator resume from the same step
if self.ckpt.resume_step is not None:
self.trainer.ckpt.resume_step = self.ckpt.resume_step
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
# If specified, propagate keep policy
if self.ckpt.keep_last is not None:
self.trainer.ckpt.keep_last = self.ckpt.keep_last
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
if self.ckpt.keep_interval is not None:
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
validate_shared_ckpt_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_wandb(self):
# If specified, automatically use shared W&B project for orchestrator and trainer
if self.wandb is not None:
if not self.trainer.wandb:
self.trainer.wandb = WandbConfig()
if not self.orchestrator.wandb:
self.orchestrator.wandb = WandbWithExtrasConfig()
if self.wandb.project:
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
validate_shared_wandb_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_model(self):
# Use the same model for trainer, orchestrator and inference
if self.model is not None:
self.trainer.model.name = self.model.name
self.orchestrator.model.name = self.model.name
if self.inference is not None:
self.inference.model.name = self.model.name
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_max_steps(self):
# If specified, use the same max steps for trainer and orchestrator
if self.max_steps is not None:
self.trainer.max_steps = self.max_steps
self.orchestrator.max_steps = self.max_steps
validate_shared_max_steps(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_async_level(self):
# If specified, use the same async level for trainer and orchestrator
if self.max_async_level is not None:
self.trainer.max_async_level = self.max_async_level
self.orchestrator.max_async_level = self.max_async_level
validate_shared_max_async_level(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_seq_len(self):
# If specified, use the same seq_len for trainer and orchestrator
if self.seq_len is not None:
self.trainer.model.seq_len = self.seq_len
self.orchestrator.seq_len = self.seq_len
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
return self
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type, inference_world_size=inference_world_size
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def warn_wandb_resume_id_missing(self):
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
if self.trainer.wandb and not self.trainer.wandb.id:
warnings.warn(
"W&B run ID is not set for trainer even though resuming training. The current run will be created as a new run."
)
if self.orchestrator.ckpt is not None and self.orchestrator.ckpt.resume_step is not None:
if self.orchestrator.wandb and not self.orchestrator.wandb.id:
warnings.warn(
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
)
return self
@model_validator(mode="after")
def auto_setup_output_dir(self):
if self.output_dir is not None:
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
+131
View File
@@ -0,0 +1,131 @@
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.rl_config import BaseRLConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pydantic_config import parse_argv
TEMPLATE_DIR = Path(__file__).parent
TEMPLATE_NAME = "rl_slurm.sh.j2"
class RLSLURMConfig(BaseRLConfig):
output_dir: Path
job_name: str
num_train_nodes: int
num_infer_nodes: int
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 train nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_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_train_nodes % self.nodes_per_fsdp_group != 0:
raise ValueError(
f"num_train_nodes ({self.num_train_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
)
self.trainer.dp_replicate = self.num_train_nodes // self.nodes_per_fsdp_group
return self
def write_subconfigs(config: RLSLURMConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / "trainer.toml", "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
with open(output_dir / "orchestrator.toml", "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
if config.inference is not None:
with open(output_dir / "inference.toml", "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
def render_slurm_script(config: RLSLURMConfig, config_dir: Path) -> str:
"""Render the SLURM script template with config values."""
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,
orchestrator_output_dir=config.orchestrator.output_dir,
config_dir=config_dir,
num_train_nodes=config.num_train_nodes,
num_infer_nodes=config.num_infer_nodes,
project_dir=config.project_dir,
gpus_per_node=config.gpus_per_node,
hf_hub_offline=config.hf_hub_offline,
)
def rl_slurm(config: RLSLURMConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = config.output_dir / "configs"
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
script = render_slurm_script(config, config_dir)
script_path = config.output_dir / "rl.sh"
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
logger.info(f"Wrote SLURM script to {script_path}")
slurm_log_dir = config.output_dir / "slurm"
log_message = (
f"Logs:\n"
f" Trainer: tail -f {slurm_log_dir}/latest_train_node_rank_0.log\n"
f" Inference: tail -f {slurm_log_dir}/latest_infer_node_rank_0.log\n"
f" Orchestrator: tail -f {slurm_log_dir}/latest_orchestrator.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():
rl_slurm(parse_argv(RLSLURMConfig))
if __name__ == "__main__":
main()
+142
View File
@@ -0,0 +1,142 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes={{ num_train_nodes + num_infer_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_TRAIN_NODES={{ num_train_nodes }}
export NUM_INFER_NODES={{ num_infer_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
mkdir -p $OUTPUT_DIR/slurm
# Clear previous rollouts and broadcast flags from ALL runs (not just the current one)
# to prevent the trainer from training on stale data from old run_* directories.
# WARN: This is potentially dangerous and could lead to data loss
rm -rf $OUTPUT_DIR/run_*/rollouts
rm -rf $OUTPUT_DIR/run_*/broadcasts
rm -rf $OUTPUT_DIR/rollouts
# 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 ) )
export INFER_HOSTS=${HOSTNAMES[@]:0:$NUM_INFER_NODES}
export TRAIN_HOSTS=${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES}
export BROADCAST_PORT=${BROADCAST_PORT:-29501}
export BROADCAST_TIMEOUT=${BROADCAST_TIMEOUT:-12000}
export NCCL_COMM_TIMEOUT=${NCCL_BROADCAST_TIMEOUT:-12000}
INFER_URLS=""
for host in ${INFER_HOSTS[@]}; do
if [ -z "$INFER_URLS" ]; then
INFER_URLS="http://$host:8000/v1"
else
INFER_URLS="$INFER_URLS,http://$host:8000/v1"
fi
done
export INFER_URLS
echo "HOSTNAMES=${HOSTNAMES[@]}"
echo "TRAIN_HOSTS=${TRAIN_HOSTS[@]}"
echo "INFER_HOSTS=${INFER_HOSTS[@]}"
echo "INFER_URLS=${INFER_URLS}"
export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
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 RL
srun bash -c '
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Disable sync to avoid conflicts with lockfile
# 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
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# This is required for vLLM graph compile to work
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
INFER_NODE_RANK=$SLURM_PROCID
export VLLM_WORKER_MULTIPROC_METHOD=spawn
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))
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
uv run orchestrator \
@ $CONFIG_DIR/orchestrator.toml \
--weight_broadcast.host $MASTER_ADDR \
--weight_broadcast.port $BROADCAST_PORT \
--weight_broadcast.timeout $BROADCAST_TIMEOUT \
--client.base-url $INFER_URLS \
--client.timeout 3600 \
--num-train-workers $((NUM_TRAIN_NODES * GPUS_PER_NODE)) \
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log & disown
fi
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_TRAIN_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.rl.train \
@ $CONFIG_DIR/trainer.toml \
--weight_broadcast.host 0.0.0.0 \
--weight_broadcast.port $BROADCAST_PORT \
--weight_broadcast.inference_world_size $((GPUS_PER_NODE * NUM_INFER_NODES)) \
--weight_broadcast.timeout $BROADCAST_TIMEOUT \
--dist_timeout_seconds $NCCL_COMM_TIMEOUT \
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
fi
'
+3
View File
@@ -13,17 +13,20 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
from prime_rl.trainer.models.llama import LlamaForCausalLM
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
# Make custom config discoverable by AutoConfig
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
@@ -132,19 +132,16 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
# Routed experts - convert to new fused format (transformers 5.0+)
w1 = state_dict[f"model.layers.{i}.mlp.experts.w1"] # (num_experts, moe_dim, dim)
w2 = state_dict[f"model.layers.{i}.mlp.experts.w2"] # (num_experts, dim, moe_dim)
w3 = state_dict[f"model.layers.{i}.mlp.experts.w3"] # (num_experts, moe_dim, dim)
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
# Fuse w1 (gate) and w3 (up) into gate_up_proj
gate_up_proj = torch.cat([w1, w3], dim=1) # (num_experts, 2*moe_dim, dim)
state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"] = gate_up_proj
state_dict[f"model.layers.{i}.mlp.experts.down_proj"] = w2
del state_dict[f"model.layers.{i}.mlp.experts.w1"]
del state_dict[f"model.layers.{i}.mlp.experts.w2"]
del state_dict[f"model.layers.{i}.mlp.experts.w3"]
num_experts = w1.shape[0]
for j in range(num_experts):
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
+60 -16
View File
@@ -1,5 +1,6 @@
import functools
from dataclasses import dataclass
from typing import Literal
import torch
import torch.nn.functional as F
@@ -36,6 +37,7 @@ class AttentionConfig:
attention_bias: bool
use_qk_norm: bool
rms_norm_eps: float
qk_norm_type: Literal["per_head", "per_layer"] = "per_head"
# TODO: Does torch compile support config._attn_implementation forking?
@@ -70,9 +72,18 @@ class FlashAttention(nn.Module):
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
if self.use_qk_norm:
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
if self.qk_norm_type == "per_layer":
self.q_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
)
self.k_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
)
else:
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self._flash_attn_version = flash_attn_version
self.func = self._funcs[flash_attn_version]
@@ -90,11 +101,19 @@ class FlashAttention(nn.Module):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape)
key_states = self.k_proj(hidden_states).view(hidden_shape)
value_states = self.v_proj(hidden_states).view(hidden_shape)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
if self.use_qk_norm: # main diff from Llama
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.view(hidden_shape)
key_states = key_states.view(hidden_shape)
value_states = value_states.view(hidden_shape)
if self.use_qk_norm and self.qk_norm_type == "per_head":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
@@ -156,9 +175,18 @@ class SDPAAttention(nn.Module):
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
if self.use_qk_norm:
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
if self.qk_norm_type == "per_layer":
self.q_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
)
self.k_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
)
else:
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
def forward(
self,
@@ -170,11 +198,19 @@ class SDPAAttention(nn.Module):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states: torch.Tensor = self.q_proj(hidden_states).view(hidden_shape)
key_states: torch.Tensor = self.k_proj(hidden_states).view(hidden_shape)
value_states: torch.Tensor = self.v_proj(hidden_states).view(hidden_shape)
query_states: torch.Tensor = self.q_proj(hidden_states)
key_states: torch.Tensor = self.k_proj(hidden_states)
value_states: torch.Tensor = self.v_proj(hidden_states)
if self.use_qk_norm: # main diff from Llama
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.view(hidden_shape)
key_states = key_states.view(hidden_shape)
value_states = value_states.view(hidden_shape)
if self.use_qk_norm and self.qk_norm_type == "per_head":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
@@ -229,11 +265,19 @@ def substitute_prime_rl_flash_attn(
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape)
key_states = self.k_proj(hidden_states).view(hidden_shape)
value_states = self.v_proj(hidden_states).view(hidden_shape)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
if self.use_qk_norm: # main diff from Llama
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.view(hidden_shape)
key_states = key_states.view(hidden_shape)
value_states = value_states.view(hidden_shape)
if self.use_qk_norm and self.qk_norm_type == "per_head":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
@@ -0,0 +1,13 @@
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2.modeling_minimax_m2 import (
MiniMaxM2ForCausalLM,
MiniMaxM2Model,
MiniMaxM2PreTrainedModel,
)
__all__ = [
"MiniMaxM2Config",
"MiniMaxM2ForCausalLM",
"MiniMaxM2Model",
"MiniMaxM2PreTrainedModel",
]
@@ -0,0 +1,151 @@
from transformers.configuration_utils import PretrainedConfig
from transformers.modeling_rope_utils import rope_config_validation
class MiniMaxM2Config(PretrainedConfig):
r"""
Configuration class for MiniMax M2.1 MoE model.
Args:
vocab_size (`int`, *optional*, defaults to 200064):
Vocabulary size of the model.
hidden_size (`int`, *optional*, defaults to 6144):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 24576):
Dimension of the MoE expert FFN.
num_hidden_layers (`int`, *optional*, defaults to 92):
Number of hidden layers in the Transformer.
num_attention_heads (`int`, *optional*, defaults to 48):
Number of attention heads.
num_key_value_heads (`int`, *optional*, defaults to 8):
Number of key-value heads for GQA.
head_dim (`int`, *optional*, defaults to 128):
Dimension of each attention head.
hidden_act (`str`, *optional*, defaults to `"silu"`):
Activation function for the MLP.
max_position_embeddings (`int`, *optional*, defaults to 131072):
Maximum sequence length.
rms_norm_eps (`float`, *optional*, defaults to 1e-6):
Epsilon for RMS normalization.
rope_theta (`float`, *optional*, defaults to 5000000):
Base period for RoPE.
rotary_dim (`int`, *optional*, defaults to 64):
Dimension of the rotary embeddings. Converted to `partial_rotary_factor` for HF rope init.
num_local_experts (`int`, *optional*, defaults to 256):
Number of routed experts per layer.
num_experts_per_tok (`int`, *optional*, defaults to 8):
Number of experts selected per token.
scoring_func (`str`, *optional*, defaults to `"sigmoid"`):
Scoring function for the router.
use_routing_bias (`bool`, *optional*, defaults to `True`):
Whether to use e_score_correction_bias for load balancing.
use_qk_norm (`bool`, *optional*, defaults to `True`):
Whether to use QK normalization.
qk_norm_type (`str`, *optional*, defaults to `"per_layer"`):
Type of QK normalization. "per_layer" means each head has its own scale.
attention_bias (`bool`, *optional*, defaults to `False`):
Whether to use bias in attention projections.
use_grouped_mm (`bool`, *optional*, defaults to `True`):
Whether to use grouped matmul for experts.
"""
model_type = "minimax_m2"
keys_to_ignore_at_inference = ["past_key_values"]
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size=200064,
hidden_size=6144,
intermediate_size=24576,
num_hidden_layers=92,
num_attention_heads=48,
num_key_value_heads=8,
head_dim=128,
hidden_act="silu",
max_position_embeddings=131072,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
tie_word_embeddings=False,
rope_theta=5000000,
rope_scaling=None,
rotary_dim=64,
pad_token_id=None,
bos_token_id=1,
eos_token_id=2,
num_local_experts=256,
num_experts_per_tok=8,
scoring_func="sigmoid",
use_routing_bias=True,
use_qk_norm=True,
qk_norm_type="per_layer",
attention_bias=False,
sliding_window=None,
attention_dropout=0.0,
output_router_logits=False,
router_aux_loss_coef=0.001,
router_jitter_noise=0.0,
use_grouped_mm=True,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.head_dim = head_dim
self.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.attention_bias = attention_bias
self.sliding_window = sliding_window
self.attention_dropout = attention_dropout
# Compute partial_rotary_factor from rotary_dim for HF rope init compatibility
self.rotary_dim = rotary_dim
self.partial_rotary_factor = rotary_dim / head_dim
if self.rope_scaling is not None and "type" in self.rope_scaling:
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
rope_config_validation(self)
# MoE arguments
self.num_local_experts = num_local_experts
self.num_experts_per_tok = num_experts_per_tok
self.scoring_func = scoring_func
self.use_routing_bias = use_routing_bias
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
self.router_jitter_noise = router_jitter_noise
# Attention
self.use_qk_norm = use_qk_norm
self.qk_norm_type = qk_norm_type
# Training
self.use_grouped_mm = use_grouped_mm
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@@ -0,0 +1,101 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
"""Convert a layer from HF to PrimeRL format in-place.
HF MiniMax M2.1 uses `block_sparse_moe` as the MoE block name, with
expert weights stored as `experts.{j}.w1.weight` (nn.Linear format).
"""
i = layer_idx
prefix = f"model.layers.{i}"
# Check if this layer has MoE experts
num_experts = len([k for k in state_dict.keys() if f"{prefix}.block_sparse_moe.experts" in k]) // 3
if num_experts == 0:
return
# Router: block_sparse_moe.gate.weight -> mlp.router.gate.weight
state_dict[f"{prefix}.mlp.router.gate.weight"] = state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
del state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
# e_score_correction_bias: direct tensor under block_sparse_moe -> mlp.expert_bias
bias_key = f"{prefix}.block_sparse_moe.e_score_correction_bias"
if bias_key in state_dict:
state_dict[f"{prefix}.mlp.expert_bias"] = state_dict[bias_key]
del state_dict[bias_key]
# Expert weights: stack individual experts into grouped tensors
# HF uses w1.weight, w2.weight, w3.weight (nn.Linear with .weight suffix)
dim, moe_dim = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.weight"].shape
dtype = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.weight"].dtype
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
for j in range(num_experts):
w1[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"])
w2[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"])
w3[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"])
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"]
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"]
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"]
state_dict[f"{prefix}.mlp.experts.w1"] = w1
state_dict[f"{prefix}.mlp.experts.w2"] = w2
state_dict[f"{prefix}.mlp.experts.w3"] = w3
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int):
"""Convert a layer from PrimeRL to HF format in-place."""
i = layer_idx
prefix = f"model.layers.{i}"
if f"{prefix}.mlp.router.gate.weight" not in state_dict:
return
# Router: mlp.router.gate.weight -> block_sparse_moe.gate.weight
state_dict[f"{prefix}.block_sparse_moe.gate.weight"] = state_dict[f"{prefix}.mlp.router.gate.weight"]
del state_dict[f"{prefix}.mlp.router.gate.weight"]
# expert_bias -> block_sparse_moe.e_score_correction_bias
if f"{prefix}.mlp.expert_bias" in state_dict:
state_dict[f"{prefix}.block_sparse_moe.e_score_correction_bias"] = state_dict[f"{prefix}.mlp.expert_bias"]
del state_dict[f"{prefix}.mlp.expert_bias"]
# tokens_per_expert is a runtime buffer, remove if present
if f"{prefix}.mlp.tokens_per_expert" in state_dict:
del state_dict[f"{prefix}.mlp.tokens_per_expert"]
# Expert weights: unstack grouped tensors into individual experts
num_experts, moe_dim, dim = state_dict[f"{prefix}.mlp.experts.w1"].shape
for j in range(num_experts):
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"] = state_dict[f"{prefix}.mlp.experts.w1"][j]
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"] = state_dict[f"{prefix}.mlp.experts.w2"][j]
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"] = state_dict[f"{prefix}.mlp.experts.w3"][j]
del state_dict[f"{prefix}.mlp.experts.w1"]
del state_dict[f"{prefix}.mlp.experts.w2"]
del state_dict[f"{prefix}.mlp.experts.w3"]
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
"""Convert MoE weights from HF to PrimeRL format in-place."""
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_hf_layer_to_tt(state_dict, i)
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
"""Convert MoE weights from PrimeRL to HF format in-place."""
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_tt_layer_to_hf(state_dict, i)
@@ -0,0 +1,276 @@
from typing import Optional, Union
import torch
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
convert_hf_layer_to_tt,
convert_hf_to_tt_moe,
convert_tt_layer_to_hf,
convert_tt_to_hf_moe,
)
logger = logging.get_logger(__name__)
class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: MiniMaxM2Config, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
attn_config = AttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
is_causal=True,
attention_bias=config.attention_bias,
use_qk_norm=config.use_qk_norm,
rms_norm_eps=config.rms_norm_eps,
qk_norm_type=config.qk_norm_type,
)
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
moe_args = MoEArgs(
num_experts=config.num_local_experts,
num_shared_experts=0,
score_func=config.scoring_func,
route_norm=True,
route_scale=1.0,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=1e-3 if config.use_routing_bias else None,
)
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
config: MiniMaxM2Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["MiniMaxM2DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": MiniMaxM2DecoderLayer,
}
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("block_sparse_moe.experts.1.w1" in name for name in state_dict.keys())
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict.keys())
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
convert_tt_to_hf_moe(state_dict)
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
convert_hf_to_tt_moe(state_dict)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_tt_layer_to_hf(state_dict, layer_idx)
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_hf_layer_to_tt(state_dict, layer_idx)
return state_dict
@auto_docstring
class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
def __init__(self, config: MiniMaxM2Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[MiniMaxM2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
else:
rope_type = "default"
rotary_config = RotaryEmbeddingConfig(
max_position_embeddings=config.max_position_embeddings,
rope_type=rope_type,
model_config=config,
)
self.rotary_emb = RotaryEmbedding(rotary_config)
self.gradient_checkpointing = False
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
flat_position_ids = position_ids.view(-1)
seqlens = torch.cat(
[
flat_position_ids[0:1],
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
flat_position_ids[-1:] + 1,
]
)
max_seqlen = seqlens.max().item()
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
max_seqlen = None
cu_seqlens = None
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
@auto_docstring
class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = MiniMaxM2Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Union[torch.Tensor, None] = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss.
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Per-token temperatures for logprobs/entropy computation.
"""
assert use_cache is None, "use_cache is not supported for custom minimax_m2 for now"
assert past_key_values is None, "past_key_values is not supported for custom minimax_m2 for now"
if position_ids is None:
if inputs_embeds is not None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
else:
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
outputs: BaseModelOutputWithPast = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
buffer_names = [name for name, _ in self.named_buffers()]
if "model.rotary_emb.inv_freq" in buffer_names:
rotary_emb = self.model.rotary_emb
inv_freq, rotary_emb.attention_scaling = rotary_emb.rope_init_fn(
rotary_emb.config, rotary_emb.inv_freq.device
)
rotary_emb.inv_freq.copy_(inv_freq)
__all__ = [
"MiniMaxM2ForCausalLM",
"MiniMaxM2Model",
"MiniMaxM2PreTrainedModel",
]
@@ -74,19 +74,16 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
# Routed experts - convert to new fused format (transformers 5.0+)
w1 = state_dict[f"model.layers.{i}.mlp.experts.w1"] # (num_experts, moe_dim, dim)
w2 = state_dict[f"model.layers.{i}.mlp.experts.w2"] # (num_experts, dim, moe_dim)
w3 = state_dict[f"model.layers.{i}.mlp.experts.w3"] # (num_experts, moe_dim, dim)
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
# Fuse w1 (gate) and w3 (up) into gate_up_proj
gate_up_proj = torch.cat([w1, w3], dim=1) # (num_experts, 2*moe_dim, dim)
state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"] = gate_up_proj
state_dict[f"model.layers.{i}.mlp.experts.down_proj"] = w2
del state_dict[f"model.layers.{i}.mlp.experts.w1"]
del state_dict[f"model.layers.{i}.mlp.experts.w2"]
del state_dict[f"model.layers.{i}.mlp.experts.w3"]
num_experts = w1.shape[0]
for j in range(num_experts):
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
+16 -20
View File
@@ -14,7 +14,7 @@ NO_BOLD = "\033[22m"
RESET = "\033[0m"
def _build_log_entry(record) -> dict:
def build_log_entry(record) -> dict:
"""Build a flat JSON log entry from a loguru record."""
extra = record["extra"]
@@ -54,14 +54,14 @@ def _build_log_entry(record) -> dict:
return log_entry
def _json_sink(message) -> None:
def json_sink(message) -> None:
"""Sink that outputs flat JSON to stdout for log aggregation (Loki, Grafana, etc.)."""
log_entry = _build_log_entry(message.record)
log_entry = build_log_entry(message.record)
sys.stdout.write(json_module.dumps(log_entry) + "\n")
sys.stdout.flush()
class _JsonFileSink:
class JsonFileSink:
"""File sink that keeps the handle open and writes flat JSON lines."""
def __init__(self, log_file: Path):
@@ -74,7 +74,7 @@ class _JsonFileSink:
self._file.close()
def write(self, message) -> None:
log_entry = _build_log_entry(message.record)
log_entry = build_log_entry(message.record)
self._file.write(json_module.dumps(log_entry) + "\n")
self._file.flush()
@@ -102,17 +102,19 @@ class InterceptHandler(logging.Handler):
def setup_logger(
log_level: str,
log_level: str = "info",
log_file: Path | None = None,
append: bool = False,
tag: str | None = None,
json_logging: bool = False,
):
global _LOGGER, _JSON_LOGGING
if _LOGGER is not None:
raise RuntimeError("Logger already set. Please call `setup_logger` only once.")
_JSON_LOGGING = json_logging
# Clean up old logger instance to prevent resource leaks
if _LOGGER is not None:
_LOGGER.remove()
# Format message with optional tag prefix
tag_prefix = f"[{tag}] " if tag else ""
message = "".join(
@@ -154,7 +156,7 @@ def setup_logger(
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
if json_logging:
logger.add(_json_sink, level=log_level.upper(), enqueue=True)
logger.add(json_sink, level=log_level.upper(), enqueue=True)
else:
logger.add(sys.stdout, format=format, level=log_level.upper(), colorize=True)
@@ -163,7 +165,7 @@ def setup_logger(
if not append and log_file.exists():
log_file.unlink()
if json_logging:
file_sink = _JsonFileSink(log_file)
file_sink = JsonFileSink(log_file)
logger.add(file_sink.write, level=log_level.upper(), enqueue=True)
else:
logger.add(log_file, format=format, level=log_level.upper(), colorize=True)
@@ -178,23 +180,17 @@ def setup_logger(
def get_logger():
"""
Get the global logger. This function is shared across submodules such as
training and inference to access the global logger instance. Raises if the
logger has not been set.
Returns:
The global logger.
"""
global _LOGGER
if _LOGGER is None:
raise RuntimeError("Logger not set. Please call `set_logger` first.")
_LOGGER = setup_logger()
return _LOGGER
def reset_logger():
"""Reset the global logger. Useful mainly in test to clear loggers between tests."""
"""Reset the logger. Useful mainly in tests."""
global _LOGGER, _JSON_LOGGING
if _LOGGER is not None:
_LOGGER.remove()
_LOGGER = None
_JSON_LOGGING = False
+104
View File
@@ -0,0 +1,104 @@
from pathlib import Path
from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_no_error
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 900 # 15 minutes
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
return f"test-rl-moe-{branch_name}"
# --- MoE with HF impl (default) ---
@pytest.fixture(scope="module")
def moe_hf_output_dir(output_dir: Path) -> Path:
d = output_dir / "rl_moe_hf"
d.mkdir(parents=True, exist_ok=True)
return d
@pytest.fixture(scope="module")
def moe_hf_process(
run_process: Callable[..., ProcessResult],
moe_hf_output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/integration/rl_moe/start.toml",
"--trainer.model.impl",
"hf",
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-hf",
"--output-dir",
moe_hf_output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error_hf(moe_hf_process: ProcessResult, moe_hf_output_dir: Path):
check_no_error(moe_hf_process, moe_hf_output_dir)
def test_moe_hf_runs(moe_hf_process: ProcessResult, test_no_error_hf):
"""MoE RL with HF model impl completes without error."""
# --- MoE with custom impl ---
@pytest.fixture(scope="module")
def moe_custom_output_dir(output_dir: Path) -> Path:
d = output_dir / "rl_moe_custom"
d.mkdir(parents=True, exist_ok=True)
return d
@pytest.fixture(scope="module")
def moe_custom_process(
run_process: Callable[..., ProcessResult],
moe_custom_output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/integration/rl_moe/start.toml",
"--trainer.model.impl",
"custom",
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-custom",
"--output-dir",
moe_custom_output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error_custom(moe_custom_process: ProcessResult, moe_custom_output_dir: Path):
check_no_error(moe_custom_process, moe_custom_output_dir)
def test_moe_custom_runs(moe_custom_process: ProcessResult, test_no_error_custom):
"""MoE RL with custom model impl completes without error."""
+9 -1
View File
@@ -7,12 +7,20 @@ from pydantic import ValidationError
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.trainer.rl.config import RLTrainerConfig
from prime_rl.trainer.sft.config import SFTTrainerConfig
from prime_rl.utils.pydantic_config import parse_argv
# All config config classes
CONFIG_CLASSES = [RLConfig, RLTrainerConfig, SFTTrainerConfig, OrchestratorConfig, InferenceConfig]
CONFIG_CLASSES = [
RLConfig,
RLTrainerConfig,
SFTTrainerConfig,
OrchestratorConfig,
InferenceConfig,
RLSLURMConfig,
]
def get_config_files() -> list[Path]:
-15
View File
@@ -118,21 +118,6 @@ def test_glm4_moe() -> None:
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
with torch.device("cuda"), default_dtype(torch.float32):
hf_from_prime_model = HFGlm4MoeForCausalLM._from_config(hf_model.config)
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
hf_from_prime_model.load_state_dict(converted_state_dict)
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids)
hf_from_prime_output.logits.sum().backward()
logits_diff = hf_from_prime_output.logits - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
if __name__ == "__main__":
test_glm4_moe_mlp_only()
-15
View File
@@ -117,21 +117,6 @@ def test_qwen3_moe():
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
with torch.device("cuda"), default_dtype(torch.float32):
hf_from_prime_model = HFQwen3MoeForCausalLM._from_config(hf_model.config)
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
hf_from_prime_model.load_state_dict(converted_state_dict)
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids)
hf_from_prime_output.logits.sum().backward()
logits_diff = hf_from_prime_output.logits - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
if __name__ == "__main__":
test_qwen3_moe_mlp_only()
Generated
+15
View File
@@ -1481,6 +1481,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c1/80/a61f99dc3a936413c3ee4e1eecac96c0da5ed07ad56fd975f1a9da5bc630/MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87", size = 15601, upload-time = "2024-10-18T15:21:23.499Z" },
]
[[package]]
name = "math-env"
version = "0.1.2"
source = { registry = "https://hub.primeintellect.ai/primeintellect/simple/" }
dependencies = [
{ name = "math-verify" },
{ name = "prime-sandboxes" },
{ name = "verifiers" },
]
wheels = [
{ url = "https://hub.primeintellect.ai/primeintellect/math-env/@07fdeaab/math_env-0.1.2-py3-none-any.whl", hash = "sha256:87003ca56c65818e7a7707f12e80511180038190abe4df5ec66cb2012d38b6d9" },
]
[[package]]
name = "math-verify"
version = "0.8.0"
@@ -2285,6 +2298,7 @@ dependencies = [
{ name = "jaxtyping" },
{ name = "liger-kernel" },
{ name = "loguru" },
{ name = "math-env" },
{ name = "numpy" },
{ name = "openai" },
{ name = "prime" },
@@ -2340,6 +2354,7 @@ requires-dist = [
{ name = "jaxtyping", specifier = ">=0.3.2" },
{ name = "liger-kernel", specifier = ">=0.5.10" },
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "math-env", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
{ name = "numpy", specifier = ">=2.2.6" },
{ name = "openai", specifier = ">=1.106.1" },
{ name = "prime", specifier = ">=0.5.37" },