Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdb1480c66 | ||
|
|
f34efdbf49 | ||
|
|
9b47b777aa | ||
|
|
1877714656 | ||
|
|
77766bb59c | ||
|
|
1caebf8a1b | ||
|
|
db04385acf | ||
|
|
2bc136cf85 | ||
|
|
6bfbd64aef | ||
|
|
b453f40d8c | ||
|
|
1b028ca1d1 | ||
|
|
e96bbae2dd | ||
|
|
df2acf4874 | ||
|
|
5ff9abd8b5 | ||
|
|
5448f5a722 | ||
|
|
8a977ecc9c | ||
|
|
1ab29c0587 | ||
|
|
5e6b641574 | ||
|
|
16f5c7222b | ||
|
|
5c0a6dbdba | ||
|
|
dbe95b799a | ||
|
|
07e6bec87a |
@@ -25,7 +25,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --extra flash-attn --extra envs --locked
|
||||
- name: Run tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **fp32 MoE routing enabled by default**: `trainer.model.moe_router_dtype` (new field) defaults to `"float32"` — custom-impl MoE router gates keep fp32 weights through forward/backward (exempt from the FSDP bf16 cast) and compute the gate GEMM and routing logits in fp32. `inference.enable_fp32_router_logits` (new field) defaults to `true` — DeepSeek-family models served by vLLM (incl. GLM-5.x) emit fp32 router logits via `out_dtype=float32` on the gate. Both change MoE numerics for existing runs (routing logits are no longer rounded to bf16; near-tie expert selections can differ). Set `moe_router_dtype = "bfloat16"` / `enable_fp32_router_logits = false` to restore the previous behavior. Non-MoE and HF-impl models are unaffected. (2026-07-04)
|
||||
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
|
||||
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
|
||||
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
|
||||
|
||||
@@ -8,3 +8,6 @@ gpu_memory_utilization = 0.7
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
max_model_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ id = "reverse-text"
|
||||
interval = 10
|
||||
resume_step = -1
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -16,3 +16,6 @@ freq = 1
|
||||
|
||||
[model.compile]
|
||||
fullgraph = false
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 SEARCH-domain envs — bring-your-own-search QA, run
|
||||
# through the rlm harness (its built-in `search` skill) on a prime sandbox. GRPO + linear length
|
||||
# penalty. 2 train + 4 infer nodes. Single run label (glm45air-search) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-search"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-search" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.0
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
|
||||
|
||||
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
|
||||
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.env]]
|
||||
name = "openseeker"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "openseeker-v1"
|
||||
|
||||
[[orchestrator.train.env.taskset.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "redsearcher"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
[[orchestrator.train.env.taskset.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: BrowseComp held-out test, every 20 steps (incl. step 0) ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "browsecomp-v1"
|
||||
judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" }
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
+15
-19
@@ -3,9 +3,9 @@
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the output-token, input-token, and turns coefficients all
|
||||
# set to 0.1. Each term is pass_rate-scaled and normalized by the group's own max before the GRPO
|
||||
# baseline subtraction.
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
@@ -14,19 +14,18 @@
|
||||
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 65536
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/triton-cache-$USER-$SLURM_JOB_ID"
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -89,9 +88,9 @@ max_inflight_rollouts = 512
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
# Linear length penalty at coef 0.1 on all three terms (output tokens, input tokens, turns).
|
||||
[orchestrator.algo.length_penalty]
|
||||
num_output_tokens_weight = 0.1
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
@@ -101,8 +100,8 @@ thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
taskset = { id = "scaleswe-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
taskset = { id = "scaleswe-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
@@ -110,28 +109,25 @@ harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
skip_first_step = false
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 TERMINAL-domain envs — agentic shell/sandbox tasks
|
||||
# run through the rlm harness (ipython-only) on a prime sandbox. Each task ships its own Docker image
|
||||
# (NEEDS_CONTAINER) injected into the sandbox; grading is host-side inside the container. GRPO +
|
||||
# linear length penalty. 2 train + 4 infer nodes. Single run label (glm45air-terminal) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-terminal"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-terminal" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "tmax"
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "tmax-v1"
|
||||
|
||||
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: swebench-verified (avg@1) + terminal-bench-2 (full, avg@4) every 20 steps, incl. step 0 ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
use_prime_registry = true
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "terminal-bench-2-v1"
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -31,9 +31,9 @@ num_bytes = 1_000_000_000_000
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
|
||||
@@ -10,8 +10,8 @@ reasoning_parser = "glm45"
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 2
|
||||
gpus_per_node = 8
|
||||
|
||||
[slurm]
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: a5efbb97e4...5904fa24aa
Vendored
+1
-1
Submodule deps/research-environments updated: 1ed93baeca...3e3b5ac3d7
Vendored
+1
-1
Submodule deps/verifiers updated: 22d6333a00...fab50d5107
+1
-1
@@ -106,7 +106,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. To save the raw adapter alongside the merged HF weights:
|
||||
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
|
||||
|
||||
```toml
|
||||
[ckpt.weights]
|
||||
|
||||
+1
-1
@@ -157,7 +157,7 @@ At step $n = 1, 2, 3, \dots$:
|
||||
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
|
||||
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
|
||||
|
||||
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
|
||||
Step indices are 1-indexed; policy versions are 0-indexed, with $\pi_0$ the base model. At step 1 inference samples from $\pi_0$.
|
||||
|
||||
## Loss
|
||||
|
||||
|
||||
+9
-11
@@ -128,41 +128,39 @@ This configuration will run 2 vLLM processes, each with `data_parallel_size_loca
|
||||
|
||||
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
|
||||
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and choosing how many nodes each prefill and decode replica spans.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 2
|
||||
decode_nodes_per_replica = 2
|
||||
```
|
||||
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode stages. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of role replicas you want to run.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 2
|
||||
decode_nodes_per_replica = 2
|
||||
num_decode_replicas = 1
|
||||
```
|
||||
|
||||
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
|
||||
Now each prefill replica spans 2 nodes and each decode replica spans 2 nodes. With 2 prefill replicas and 1 decode replica, one inference island spans 6 nodes.
|
||||
|
||||
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
|
||||
For RL runs, the top-level deployment can multiply that whole inference island by setting `deployment.num_infer_replicas`. `deployment.num_infer_nodes` is inferred from the nested inference deployment when you omit it.
|
||||
|
||||
```toml
|
||||
[deployment] # this is a top-level RL deployment, not inference.deployment!!
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 6 # this is per-replica
|
||||
|
||||
num_infer_replicas = 3
|
||||
```
|
||||
|
||||
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
|
||||
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
|
||||
|
||||
|
||||
## Router
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
|
||||
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
|
||||
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
|
||||
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
+1
-1
@@ -208,7 +208,7 @@ uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_nodes = 1 # optional when inference.deployment defines the node topology
|
||||
gpus_per_node = 8 # default
|
||||
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
|
||||
```
|
||||
|
||||
+1
-1
@@ -226,7 +226,7 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
|
||||
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
|
||||
|
||||
```bash
|
||||
# First run: steps 0–10
|
||||
# First run: steps 1–10
|
||||
uv run rl @ rl.toml --max-steps 10 --ckpt
|
||||
|
||||
# Resume: continue to step 20
|
||||
|
||||
@@ -19,15 +19,14 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 16
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 1
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
# skip warmup for faster start in cost of some jit overhead early
|
||||
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
|
||||
|
||||
@@ -15,14 +15,13 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 8
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 2
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 4
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5-pd-disag"
|
||||
|
||||
@@ -274,25 +274,22 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
|
||||
|
||||
# Disaggregated prefill/decode inference. Each replica is split into separate
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
|
||||
# for request routing. Multi-replica: set ``num_prefill_replicas`` /
|
||||
# ``num_decode_replicas`` to run multiple independent vLLM instances within the
|
||||
# prefill / decode node groups. E.g. ``num_prefill_nodes=4, num_prefill_replicas=2``
|
||||
# creates two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a router for
|
||||
# request routing.
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
type: Literal["disaggregated"] = "disaggregated"
|
||||
|
||||
num_prefill_nodes: int = Field(1, ge=1)
|
||||
"""Total prefill nodes."""
|
||||
prefill_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each prefill vLLM instance."""
|
||||
|
||||
num_decode_nodes: int = Field(1, ge=1)
|
||||
"""Total decode nodes."""
|
||||
decode_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each decode vLLM instance."""
|
||||
|
||||
num_prefill_replicas: int = Field(1, ge=1)
|
||||
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
|
||||
"""Independent prefill vLLM instances."""
|
||||
|
||||
num_decode_replicas: int = Field(1, ge=1)
|
||||
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
|
||||
"""Independent decode vLLM instances."""
|
||||
|
||||
prefill_port: int = 8100
|
||||
"""Port for prefill vLLM instances."""
|
||||
@@ -312,24 +309,18 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
decode_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
|
||||
|
||||
@property
|
||||
def num_prefill_nodes(self) -> int:
|
||||
return self.prefill_nodes_per_replica * self.num_prefill_replicas
|
||||
|
||||
@property
|
||||
def num_decode_nodes(self) -> int:
|
||||
return self.decode_nodes_per_replica * self.num_decode_replicas
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_replicas_divide_nodes(self):
|
||||
if self.num_prefill_nodes % self.num_prefill_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_prefill_replicas ({self.num_prefill_replicas}) must evenly divide "
|
||||
f"num_prefill_nodes ({self.num_prefill_nodes})"
|
||||
)
|
||||
if self.num_decode_nodes % self.num_decode_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_decode_replicas ({self.num_decode_replicas}) must evenly divide "
|
||||
f"num_decode_nodes ({self.num_decode_nodes})"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
|
||||
@@ -416,6 +407,9 @@ class InferenceConfig(BaseConfig):
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
|
||||
|
||||
@@ -608,6 +602,10 @@ class InferenceConfig(BaseConfig):
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_lm_head"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
if self.enable_fp32_router_logits:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_router_logits"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
|
||||
@@ -111,7 +111,7 @@ class SharedModelConfig(BaseConfig):
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl", "filesystem"] = "filesystem"
|
||||
type: Literal["nccl", "filesystem"] = "nccl"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
port: int = 29501
|
||||
@@ -155,8 +155,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
num_train_nodes: int
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(ge=0)
|
||||
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
num_infer_nodes: int | None = Field(None, ge=0)
|
||||
"""Inference nodes per replica. If unset, inferred from ``inference.deployment``. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
|
||||
num_infer_replicas: int = Field(1, ge=1)
|
||||
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
|
||||
@@ -167,9 +167,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@property
|
||||
def infer_nodes_per_replica(self) -> int:
|
||||
return self.num_infer_nodes or 0
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
return self.infer_nodes_per_replica * self.num_infer_replicas
|
||||
|
||||
|
||||
DeploymentConfig: TypeAlias = Annotated[
|
||||
@@ -232,19 +236,47 @@ class RLConfig(BaseConfig):
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_infer_nodes(self):
|
||||
if self.deployment.type != "multi_node":
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
inferred_nodes = 0
|
||||
elif self.inference.deployment.type == "multi_node":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
elif self.inference.deployment.type == "disaggregated":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
else:
|
||||
inferred_nodes = 1
|
||||
|
||||
if self.deployment.num_infer_nodes is None:
|
||||
self.deployment.num_infer_nodes = inferred_nodes
|
||||
elif (
|
||||
self.inference is not None
|
||||
and self.inference.deployment.type == "multi_node"
|
||||
and self.deployment.num_infer_nodes != inferred_nodes
|
||||
):
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_nodes ({inferred_nodes}) for multi-node inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
if self.deployment.num_infer_nodes > 0 and not self.inference:
|
||||
num_infer_nodes = self.deployment.infer_nodes_per_replica
|
||||
if num_infer_nodes > 0 and not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
|
||||
if self.deployment.num_infer_nodes == 0 and self.inference:
|
||||
if num_infer_nodes == 0 and self.inference:
|
||||
raise ValueError(
|
||||
"Cannot configure inference with num_infer_nodes = 0. "
|
||||
"Either set num_infer_nodes > 0 or remove the inference config."
|
||||
)
|
||||
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
raise ValueError(
|
||||
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
|
||||
"since no orchestrator or inference server will be running."
|
||||
@@ -304,29 +336,38 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weight_broadcast(self):
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
|
||||
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,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
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)
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference.
|
||||
|
||||
Defaults to NCCL broadcast when no ``weight_broadcast`` is configured. Falls back to
|
||||
filesystem when LoRA is enabled (not yet supported with NCCL) or when no inference
|
||||
server is configured (NCCL requires a running inference pool).
|
||||
"""
|
||||
if self.weight_broadcast is None:
|
||||
if self.trainer.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
|
||||
else:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig()
|
||||
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,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
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)
|
||||
|
||||
@@ -531,7 +572,7 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
|
||||
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
|
||||
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
|
||||
expected_global_world_size = self.inference.parallel.dp * inference_tp
|
||||
if expected_global_world_size != total_infer_gpus:
|
||||
raise ValueError(
|
||||
@@ -593,12 +634,11 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
infer_deploy = self.inference.deployment
|
||||
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
|
||||
if self.deployment.num_infer_nodes != expected_infer_nodes:
|
||||
expected_infer_nodes = infer_deploy.num_nodes
|
||||
if self.deployment.infer_nodes_per_replica != expected_infer_nodes:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
|
||||
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal the derived "
|
||||
f"disaggregated inference nodes per replica ({expected_infer_nodes})."
|
||||
)
|
||||
|
||||
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
|
||||
@@ -58,6 +58,9 @@ class SlurmConfig(BaseConfig):
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
shared_fs: bool = True
|
||||
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
|
||||
|
||||
@property
|
||||
def template_vars(self) -> dict:
|
||||
"""Common template variables for all SLURM templates."""
|
||||
@@ -71,6 +74,7 @@ class SlurmConfig(BaseConfig):
|
||||
"time": self.time,
|
||||
"pre_run_command": self.pre_run_command,
|
||||
"cleanup_grace_period": self.cleanup_grace_period,
|
||||
"shared_fs": self.shared_fs,
|
||||
}
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -171,6 +171,9 @@ class ModelConfig(BaseModelConfig):
|
||||
reduce_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""dtype for gradient/parameter reductions."""
|
||||
|
||||
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
|
||||
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
@@ -649,7 +652,7 @@ class TrainerConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support this
|
||||
# TODO: Support NCCL broadcast with LoRA
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
|
||||
+8
-10
@@ -80,7 +80,6 @@ envs = [
|
||||
"deepdive-v1",
|
||||
"deepwiki-v1",
|
||||
"forth-lang-v1",
|
||||
"general-agent",
|
||||
"general-agent-v1",
|
||||
"glossary-v1",
|
||||
"gpqa-v1",
|
||||
@@ -114,7 +113,6 @@ envs = [
|
||||
"redsearcher-v1",
|
||||
"reverse-text",
|
||||
"reverse-text-v1",
|
||||
"rlm-search",
|
||||
"s1-deepresearch-v1",
|
||||
"scaleswe-v1",
|
||||
"simpleqa-v1",
|
||||
@@ -124,6 +122,7 @@ envs = [
|
||||
"swelego-v1",
|
||||
"tau2-bench-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"tmax-v1",
|
||||
"unscramble-v1",
|
||||
"uuid-ctf-v1",
|
||||
"verbatim-copy-v1",
|
||||
@@ -255,7 +254,6 @@ color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", ed
|
||||
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
|
||||
@@ -285,20 +283,20 @@ openthoughts-tblite-v1 = { path = "deps/research-environments/environments/opent
|
||||
papersearchqa-v1 = { path = "deps/research-environments/environments/papersearchqa_v1", editable = true }
|
||||
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/patterned_needle_in_haystack_v1", editable = true }
|
||||
prolog-v1 = { path = "deps/research-environments/environments/prolog_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/swe/r2e_gym_v1", editable = true }
|
||||
redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v1", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
s1-deepresearch-v1 = { path = "deps/research-environments/environments/s1_deepresearch_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/swe/scaleswe_v1", editable = true }
|
||||
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swe/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swe/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swe/swelego_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
|
||||
tmax-v1 = { path = "deps/research-environments/environments/tmax_v1", editable = true }
|
||||
unscramble-v1 = { path = "deps/research-environments/environments/unscramble_v1", editable = true }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
|
||||
verbatim-copy-v1 = { path = "deps/research-environments/environments/verbatim_copy_v1", editable = true }
|
||||
@@ -311,7 +309,7 @@ wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
|
||||
@@ -58,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the output dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{output_dir}/configs/` — resolved TOMLs (`rl.toml` has the full picture).
|
||||
- `{output_dir}/logs/` — see below.
|
||||
- `{output_dir}/rollouts/step_N/` — saved rollouts.
|
||||
- `{output_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
|
||||
|
||||
### Logs
|
||||
|
||||
@@ -130,21 +130,28 @@ curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
|
||||
```
|
||||
|
||||
### Rollouts
|
||||
### Traces
|
||||
|
||||
```
|
||||
{output_dir}/rollouts/step_N/
|
||||
├── train_rollouts.jsonl # all train rollouts (vf.RolloutOutput, trajectory excluded)
|
||||
├── eval_rollouts.jsonl # only present when eval ran
|
||||
└── train_rollouts.bin # binary batch consumed by the trainer
|
||||
{output_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
|
||||
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of `vf.Trace` records (training tensors excluded). `all` gets every completed
|
||||
rollout the moment it arrives — errored, filtered, and never-batched ones included — so it's
|
||||
crash-durable; `effective` gets the clean subset that went into the step's train batch (eval:
|
||||
the non-errored epoch cohort; multiple eval envs share the step file). Each record carries
|
||||
`kind`, `env_name`, `group_id`, `policy_version`, and `eval_step`, plus `runtime` (config +
|
||||
provisioned resource id, e.g. the sandbox id).
|
||||
|
||||
```bash
|
||||
wc -l {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
head -1 {output_dir}/rollouts/step_42/train_rollouts.jsonl | python -m json.tool
|
||||
jq '.reward' {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.errors != []) | {id, env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
A few warnings are normal. Escalate when errors are persistent, growing, or hit a large fraction of rollouts.
|
||||
|
||||
@@ -76,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars.update(
|
||||
num_prefill_nodes=config.deployment.num_prefill_nodes,
|
||||
num_decode_nodes=config.deployment.num_decode_nodes,
|
||||
prefill_nodes_per_replica=config.deployment.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=config.deployment.decode_nodes_per_replica,
|
||||
num_prefill_replicas=config.deployment.num_prefill_replicas,
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
|
||||
@@ -410,6 +410,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
num_prefill_nodes=infer_deploy.num_prefill_nodes,
|
||||
num_decode_nodes=infer_deploy.num_decode_nodes,
|
||||
prefill_nodes_per_replica=infer_deploy.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=infer_deploy.decode_nodes_per_replica,
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -441,11 +443,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
|
||||
infer_nodes_per_replica=config.deployment.num_infer_nodes,
|
||||
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
|
||||
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
@@ -496,7 +498,7 @@ def rl_slurm(config: RLConfig):
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
|
||||
has_infer = config.deployment.num_infer_nodes > 0
|
||||
has_infer = config.deployment.infer_nodes_per_replica > 0
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
|
||||
@@ -695,6 +695,45 @@ def monkey_patch_fp32_lm_head():
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_fp32_router_logits():
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
|
||||
|
||||
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
|
||||
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
|
||||
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
|
||||
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
|
||||
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
|
||||
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
|
||||
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
|
||||
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
|
||||
|
||||
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
|
||||
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
|
||||
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
|
||||
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
|
||||
branch, whose kernel wants matching dtypes).
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = DeepseekV2MoE.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
additional_config = get_current_vllm_config().additional_config or {}
|
||||
if not additional_config.get("fp32_router_logits", False):
|
||||
return
|
||||
if self.gate.out_dtype is None:
|
||||
self.gate.set_out_dtype(torch.float32)
|
||||
|
||||
DeepseekV2MoE.__init__ = _patched_init
|
||||
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_fp32_router_logits,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
)
|
||||
@@ -20,3 +21,6 @@ else:
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
|
||||
monkey_patch_fp32_router_logits()
|
||||
|
||||
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from prime_rl.configs.algorithm import EchoAlgoConfig
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -55,7 +56,9 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
(role tags, separators, tool-response wraps) is excluded. Nodes without
|
||||
attribution (the default renderer, or relay turns with no token ids)
|
||||
fall back to weighting the whole non-sampled span."""
|
||||
trainable_branches = [branch for branch in rollout.branches if any(branch.sampled_mask)]
|
||||
# Same branch selection as ``trace_to_samples``, so the zip with ``rollout.samples``
|
||||
# stays aligned when fork dedup drops a branch.
|
||||
trainable_branches = [branch for branch, _ in iter_trainable_branches(rollout)]
|
||||
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
|
||||
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
|
||||
weights = [0.0] * len(sample.token_ids)
|
||||
|
||||
@@ -75,7 +75,7 @@ from prime_rl.utils.client import init_nccl_broadcast
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
from prime_rl.utils.pathing import get_log_dir, get_trace_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
@@ -165,6 +165,8 @@ class Orchestrator:
|
||||
# Trigger timestamps so eval success logs can report epoch duration
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.component_tasks = []
|
||||
|
||||
# Optional attributes — ``setup()`` populates them when the relevant
|
||||
@@ -307,17 +309,21 @@ class Orchestrator:
|
||||
|
||||
if self.resume_step is not None and self.ckpt_manager is not None:
|
||||
self.ckpt_manager.load(self.progress, step=self.resume_step)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, self.progress.step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
config.output_dir, self.resume_step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.progress.step)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.resume_step)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = self.progress.step
|
||||
self.policy.version = self.resume_step
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
@@ -363,7 +369,7 @@ class Orchestrator:
|
||||
inference=self.policy_inference,
|
||||
observers=[self.dispatcher, self],
|
||||
lora_name=self.lora_name,
|
||||
ckpt_step=self.progress.step,
|
||||
ckpt_step=self.policy.version,
|
||||
)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
@@ -409,11 +415,11 @@ class Orchestrator:
|
||||
asyncio.create_task(self.watcher.start(), name="watcher"),
|
||||
]
|
||||
|
||||
# Default step-0 base-model eval — fires before any train rollouts
|
||||
# unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so step 0 measures startup → first batch
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
self.last_batch_at = time.perf_counter()
|
||||
|
||||
# ``clean_exit`` stays False if ``main_loop`` raises (signal-driven
|
||||
@@ -430,7 +436,11 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
self.monitor.save_final_summary()
|
||||
if self.ckpt_manager is not None:
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship).
|
||||
if self.ckpt_manager is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
self.ckpt_manager.save(self.progress, step=self.progress.step)
|
||||
await self.stop()
|
||||
@@ -455,6 +465,18 @@ class Orchestrator:
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
|
||||
# Every completed rollout — errored, filtered, or never batched — lands in the
|
||||
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
|
||||
# Train rollouts belong to the batch window currently collecting (``progress.step``),
|
||||
# eval rollouts to the step whose eval triggered them.
|
||||
step = rollout.eval_step if rollout.kind == "eval" else self.progress.step
|
||||
assert step is not None
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
[rollout.to_record()],
|
||||
get_trace_path(self.config.output_dir, step, rollout.kind, "all"),
|
||||
)
|
||||
|
||||
if rollout.kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
eval_batch = self.eval_sink.add(rollout)
|
||||
@@ -483,9 +505,7 @@ class Orchestrator:
|
||||
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
|
||||
self.last_batch_at = now
|
||||
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
if config.max_steps is not None and step > config.max_steps:
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_rollouts()
|
||||
@@ -516,21 +536,23 @@ class Orchestrator:
|
||||
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
|
||||
# drops the per-node training tensors — they're for training, not the rollout record, and
|
||||
# can't round-trip json (raw numpy bytes).
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
|
||||
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
|
||||
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
|
||||
# at ship time; the full arrival window already streamed into ``all`` on arrival.
|
||||
# to_record drops the per-node training tensors — they're for training, not the rollout
|
||||
# record, and can't round-trip json (raw numpy bytes).
|
||||
effective = batch.rollouts.effective
|
||||
records = [r.to_record() for r in effective]
|
||||
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.progress.step += 1
|
||||
self.update_dispatch_gate()
|
||||
# Checkpoint the step we just shipped (resume point: continue at step + 1).
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
trim_process_memory()
|
||||
|
||||
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
|
||||
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
|
||||
effective = batch.rollouts.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
@@ -557,6 +579,7 @@ class Orchestrator:
|
||||
"progress/total_tasks": self.progress.total_problems,
|
||||
"time/step": step_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
}
|
||||
for env_name, env_pool in batch.rollouts.by_env().items():
|
||||
@@ -568,6 +591,7 @@ class Orchestrator:
|
||||
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
|
||||
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
|
||||
self.monitor.log(metrics, step=step)
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.monitor.log_samples(effective.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
@@ -728,12 +752,13 @@ class Orchestrator:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
return
|
||||
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
|
||||
# The non-errored subset lands in the per-step ``effective`` trace file on epoch
|
||||
# completion (multiple eval envs share the step file — each epoch appends its cohort
|
||||
# once, and every record carries ``env_name``); the full returned cohort already
|
||||
# streamed into ``all`` on arrival.
|
||||
records = [r.to_record() for r in batch.rollouts.effective]
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
rollout_dicts,
|
||||
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
|
||||
save_rollouts, records, get_trace_path(self.config.output_dir, batch.step, "eval", "effective")
|
||||
)
|
||||
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
@@ -766,19 +791,13 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
async def maybe_save_ckpt(self, step: int) -> float:
|
||||
"""Save the checkpoint if we're at an interval boundary. Returns
|
||||
"""Checkpoint the step just shipped if it's an interval boundary. Returns
|
||||
elapsed time (0.0 when no save happened)."""
|
||||
if self.ckpt_manager is None or self.config.ckpt is None or not self.config.ckpt.interval:
|
||||
return 0.0
|
||||
if step <= 0:
|
||||
return 0.0
|
||||
# Skip only the drain-entry step (step == max_steps, which never ships):
|
||||
# it would double-save with the final checkpoint in ``start()`` (also at
|
||||
# progress.step == max_steps). The last *shipped* step (max_steps - 1) is
|
||||
# NOT skipped — the trainer saves there (its is_last_step is max_steps),
|
||||
# so the orchestrator must too or resume from that interval ckpt breaks.
|
||||
near_end = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
if near_end:
|
||||
# The final step's checkpoint is written once in ``start()``'s teardown; skip it here so
|
||||
# we don't double-save. This mirrors the trainer (its is_last_step skips the in-loop save).
|
||||
if self.config.max_steps is not None and step >= self.config.max_steps:
|
||||
return 0.0
|
||||
if step % self.config.ckpt.interval != 0:
|
||||
return 0.0
|
||||
@@ -791,19 +810,34 @@ class Orchestrator:
|
||||
"""Pause/resume the dispatcher based on how far the in-flight batch runs
|
||||
ahead of ``policy.version``. ``progress.step`` is always the batch being
|
||||
collected — advanced right after shipping — so both call sites (ship time
|
||||
here, policy update in ``on_new_version``) share one lead formula."""
|
||||
lead = self.progress.step - self.policy.version
|
||||
here, policy update in ``on_new_version``) share one lead formula. Steps
|
||||
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
|
||||
count is ``progress.step - 1``."""
|
||||
lead = (self.progress.step - 1) - self.policy.version
|
||||
# The trainer skips the final NCCL weight broadcast (inference group is
|
||||
# torn down), so policy.version never reaches the last step. Without this
|
||||
# the gate deadlocks waiting for a version that will never be published.
|
||||
# The last batch uses the penultimate policy anyway, so let it through.
|
||||
building_final_batch_nccl = (
|
||||
self.config.weight_broadcast.type == "nccl"
|
||||
and self.config.max_steps is not None
|
||||
and self.progress.step >= self.config.max_steps - 1
|
||||
)
|
||||
gate = self.dispatcher.dispatch_allowed
|
||||
was_set = gate.is_set()
|
||||
if lead > TARGET_LAG:
|
||||
if lead > TARGET_LAG and not building_final_batch_nccl:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
gate.clear()
|
||||
else:
|
||||
if not was_set:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
if self.gate_closed_at is not None:
|
||||
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
|
||||
self.gate_closed_at = None
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
|
||||
@@ -15,6 +15,8 @@ the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
@@ -64,6 +66,29 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
|
||||
"""Yield each branch that yields a training sample, with its trainable-token mask.
|
||||
|
||||
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
|
||||
(a mid-trajectory fork) is trainable only in the first branch containing it; later
|
||||
branches carry its tokens as context (mask False). Branches left with no trainable
|
||||
tokens are skipped, so consumers pairing branches with `trace_to_samples` output
|
||||
(e.g. echo's observation weighting) must filter through here to stay aligned.
|
||||
"""
|
||||
trained_nodes: set[int] = set()
|
||||
for branch in trace.branches:
|
||||
mask: list[bool] = []
|
||||
for node in branch.nodes:
|
||||
if node.sampled and any(node.mask) and id(node) in trained_nodes:
|
||||
mask.extend([False] * len(node.mask))
|
||||
else:
|
||||
if node.sampled and any(node.mask):
|
||||
trained_nodes.add(id(node))
|
||||
mask.extend(node.mask)
|
||||
if any(mask):
|
||||
yield branch, mask
|
||||
|
||||
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
@@ -82,10 +107,7 @@ def trace_to_samples(
|
||||
yield nothing.
|
||||
"""
|
||||
samples: list[TrainingSample] = []
|
||||
for branch in trace.branches:
|
||||
mask = branch.sampled_mask
|
||||
if not any(mask):
|
||||
continue
|
||||
for branch, mask in iter_trainable_branches(trace):
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
@@ -27,9 +27,9 @@ class Policy:
|
||||
|
||||
@dataclass
|
||||
class Progress:
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step."""
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step (1-indexed)."""
|
||||
|
||||
step: int = 0
|
||||
step: int = 1
|
||||
total_tokens: int = 0
|
||||
total_samples: int = 0
|
||||
total_problems: int = 0
|
||||
@@ -73,8 +73,8 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
|
||||
orchestration metadata lives on it directly (set by the dispatcher once the rollout
|
||||
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
|
||||
``results.jsonl`` is unchanged.
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace on the wire;
|
||||
:meth:`to_record` adds the small metadata fields back for the on-disk trace files.
|
||||
|
||||
It is also the single currency the scoring hooks receive: a hook reads the trace
|
||||
directly (``rollout.reward``, ``rollout.nodes``, ``rollout.num_turns``) and writes
|
||||
@@ -98,6 +98,19 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
|
||||
eval_step: int | None = Field(default=None, exclude=True)
|
||||
|
||||
def to_record(self) -> dict:
|
||||
"""The plain trace record plus the orchestration metadata (excluded from the pydantic
|
||||
dump), so a record stays fully placeable — kind, env, policy — even when trace files
|
||||
are merged or read away from their paths. ``eval_step`` is the eval trigger step (None
|
||||
for train rollouts)."""
|
||||
return super().to_record() | {
|
||||
"kind": self.kind,
|
||||
"env_name": self.env_name,
|
||||
"group_id": str(self.group_id),
|
||||
"policy_version": self.policy_version,
|
||||
"eval_step": self.eval_step,
|
||||
}
|
||||
|
||||
def assign_advantages(self, values: float | list[float]) -> None:
|
||||
"""Write the rl advantage stream: a scalar broadcast over the
|
||||
rollout's trainable (mask-True) tokens (0.0 elsewhere), or a per-token
|
||||
|
||||
@@ -51,10 +51,12 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[dict], path: Path) -> None:
|
||||
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
|
||||
"""Append rollouts (Trace record dicts, already JSON-serializable) to a JSONL file.
|
||||
The trace streams are append-only: ``all`` grows one rollout at a time as they
|
||||
complete, ``effective`` one batch at a time on finalize."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
with open(path, "ab") as f:
|
||||
for rollout in rollouts:
|
||||
f.write(orjson.dumps(rollout, default=str, option=opts))
|
||||
|
||||
|
||||
@@ -34,8 +34,8 @@ export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_REPLICA=$((NUM_PREFILL_NODES + NUM_DECODE_NODES))
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
@@ -61,7 +61,17 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras
|
||||
{% endif %}
|
||||
|
||||
# Print inference URLs
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
|
||||
@@ -41,8 +41,8 @@ export NUM_PREFILL_NODES={{ num_prefill_nodes }}
|
||||
export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
@@ -144,7 +144,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
@@ -48,9 +48,17 @@ 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
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if pre_run_command %}
|
||||
|
||||
@@ -45,7 +45,7 @@ from prime_rl.trainer.models.layers.checkpointing import (
|
||||
)
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.weights import (
|
||||
load_state_dict,
|
||||
@@ -351,6 +351,29 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
"""Cast MoE router gates to fp32 so routing runs in fp32 in forward and backward.
|
||||
|
||||
The FSDP bf16 cast exemption is applied separately in `setup_fsdp`.
|
||||
"""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
mlp.router.to(torch.float32)
|
||||
if isinstance(mlp.router, TokenChoiceTopKRouter):
|
||||
mlp.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
|
||||
# No-op for non-MoE and HF-impl models: moe_router_dtype='float32' is the default,
|
||||
# so absence of custom-impl MoE routers is the common case, not an error.
|
||||
if num_routers > 0:
|
||||
logger.info(f"Running {num_routers} MoE router gates in fp32")
|
||||
|
||||
|
||||
def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
"""Freeze DSA sparse-attention indexer parameters.
|
||||
|
||||
@@ -681,6 +704,17 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
|
||||
block_mlp.experts.set_gradient_divide_factor(parallel_dims.fsdp_gradient_divide_factor)
|
||||
|
||||
if config.moe_router_dtype == "float32" and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
# Own FSDP unit with an fp32 policy so the gate weight is not cast to
|
||||
# bf16 for forward and its gradients reduce in fp32.
|
||||
fully_shard(
|
||||
block_mlp.router,
|
||||
mesh=hsdp_mesh,
|
||||
mp_policy=MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32),
|
||||
offload_policy=offload_policy,
|
||||
reshard_after_forward=config.reshard_after_forward,
|
||||
)
|
||||
|
||||
fully_shard(
|
||||
transformer_block,
|
||||
mesh=hsdp_mesh,
|
||||
@@ -734,7 +768,11 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
if next_transformer_block is not None:
|
||||
next_mlp = getattr(next_transformer_block, "mlp", None)
|
||||
if next_mlp is not None and isinstance(next_mlp, (MoE, LatentMoE)):
|
||||
transformer_block.set_modules_to_forward_prefetch([next_transformer_block, next_mlp.experts])
|
||||
prefetch_modules = [next_transformer_block]
|
||||
if isinstance(next_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(next_mlp.router)
|
||||
prefetch_modules.append(next_mlp.experts)
|
||||
transformer_block.set_modules_to_forward_prefetch(prefetch_modules)
|
||||
else:
|
||||
transformer_block.set_modules_to_forward_prefetch([next_transformer_block])
|
||||
elif language_model.norm is not None and model.lm_head is not None:
|
||||
@@ -755,7 +793,10 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
if prev_transformer_block is not None:
|
||||
prev_mlp = getattr(prev_transformer_block, "mlp", None)
|
||||
if prev_mlp is not None and isinstance(prev_mlp, (MoE, LatentMoE)):
|
||||
transformer_block.set_modules_to_backward_prefetch([prev_transformer_block, prev_mlp.experts])
|
||||
prefetch_modules = [prev_transformer_block, prev_mlp.experts]
|
||||
if isinstance(prev_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(prev_mlp.router)
|
||||
transformer_block.set_modules_to_backward_prefetch(prefetch_modules)
|
||||
else:
|
||||
transformer_block.set_modules_to_backward_prefetch([prev_transformer_block])
|
||||
elif embed_module is not None:
|
||||
@@ -1111,6 +1152,9 @@ def setup_model(
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
if config.moe_router_dtype == "float32":
|
||||
apply_fp32_moe_router(model)
|
||||
|
||||
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
|
||||
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
|
||||
# save/resume. No-op for models without a sparse indexer.
|
||||
|
||||
@@ -8,6 +8,7 @@ from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAuto
|
||||
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
|
||||
from transformers.models.llama.configuration_llama import LlamaConfig
|
||||
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
@@ -20,6 +21,7 @@ from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
|
||||
|
||||
@@ -31,6 +33,7 @@ AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_text", Qwen3_5TextConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
|
||||
# GptOssConfig is just HF's class - already registered by transformers, no override needed.
|
||||
|
||||
@@ -44,6 +47,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(LagunaConfig, LagunaForCausalLM, exist_ok=Tru
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5TextConfig, Qwen3_5ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GptOssConfig, GptOssForCausalLM, exist_ok=True)
|
||||
|
||||
|
||||
@@ -340,3 +340,7 @@ def substitute_ring_attn(
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
|
||||
Qwen3_5MoeGatedFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
@@ -426,6 +426,9 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
self.route_norm = route_norm
|
||||
self.route_scale = route_scale
|
||||
self.force_balanced = False
|
||||
# Set via model.moe_router_dtype='float32': the gate weight is kept in fp32
|
||||
# (exempt from FSDP bf16 casting) and the gate GEMM runs in fp32.
|
||||
self.fp32_gate = False
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None, routed_experts: torch.Tensor | None = None
|
||||
@@ -452,7 +455,7 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
|
||||
f"routed_experts shape: {routed_experts.shape}, top_k: {self.top_k}"
|
||||
)
|
||||
scores = self.gate(x)
|
||||
scores = self.gate(x.to(torch.float32)) if self.fp32_gate else self.gate(x)
|
||||
|
||||
# By default, sigmoid or softmax is performed in float32 to avoid loss explosion
|
||||
if self.score_func == "sigmoid":
|
||||
|
||||
@@ -189,6 +189,10 @@ def substitute_ulysses_attn(
|
||||
|
||||
Qwen3_5MoeGatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
|
||||
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
|
||||
"""Patch HF's `_flash_attention_forward` to use Ulysses all-to-all + local FA2.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .modeling_qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model, Qwen3_5PreTrainedModel
|
||||
|
||||
__all__ = ["Qwen3_5ForCausalLM", "Qwen3_5Model", "Qwen3_5PreTrainedModel"]
|
||||
@@ -0,0 +1,305 @@
|
||||
import functools
|
||||
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.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import (
|
||||
Qwen3_5PreTrainedModel as HFQwen3_5PreTrainedModel,
|
||||
)
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeGatedAttentionConfig,
|
||||
Qwen3_5MoeGatedDeltaNet,
|
||||
Qwen3_5MoeGatedFlashAttention,
|
||||
Qwen3_5MoeGatedSDPAAttention,
|
||||
Qwen3_5MoeRMSNorm,
|
||||
Qwen3_5MoeRotaryEmbedding,
|
||||
normalize_qwen3_5_attn_implementation,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class Qwen3_5GatedSDPAAttention(Qwen3_5MoeGatedSDPAAttention):
|
||||
pass
|
||||
|
||||
|
||||
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
|
||||
pass
|
||||
|
||||
|
||||
QWEN35_ATTN_IMPL2CLASS = {
|
||||
"sdpa": Qwen3_5GatedSDPAAttention,
|
||||
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
|
||||
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
|
||||
"fa4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
|
||||
}
|
||||
|
||||
|
||||
def _get_gated_attention(config: Qwen3_5TextConfig) -> nn.Module:
|
||||
attn_config = Qwen3_5MoeGatedAttentionConfig(
|
||||
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,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
attention_bias=config.attention_bias,
|
||||
attention_dropout=config.attention_dropout,
|
||||
)
|
||||
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
config._attn_implementation = attn_impl
|
||||
|
||||
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5 attention does not support '{config._attn_implementation}'. "
|
||||
f"Supported implementations: {supported}."
|
||||
)
|
||||
|
||||
return QWEN35_ATTN_IMPL2CLASS[attn_impl](attn_config)
|
||||
|
||||
|
||||
def _create_rotary_emb(config: Qwen3_5TextConfig) -> Qwen3_5MoeRotaryEmbedding:
|
||||
return Qwen3_5MoeRotaryEmbedding(config)
|
||||
|
||||
|
||||
class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: Qwen3_5TextConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
self.linear_attn = Qwen3_5MoeGatedDeltaNet(config)
|
||||
elif self.layer_type == "full_attention":
|
||||
self.self_attn = _get_gated_attention(config)
|
||||
else:
|
||||
raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}")
|
||||
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
hidden_states = self.linear_attn(hidden_states, cu_seqlens=cu_seqlens)
|
||||
else:
|
||||
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)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
config_class = Qwen3_5TextConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["Qwen3_5DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_flex_attn = False
|
||||
_supports_attention_backend = True
|
||||
_can_compile_fullgraph = False
|
||||
_can_record_outputs = {
|
||||
"hidden_states": Qwen3_5DecoderLayer,
|
||||
}
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
|
||||
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5 attention does not support '{attn_implementation}'. Supported implementations: {supported}."
|
||||
)
|
||||
return attn_impl
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
|
||||
class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
def __init__(self, config: Qwen3_5TextConfig):
|
||||
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
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(
|
||||
[Qwen3_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = _create_rotary_emb(config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
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 position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
if flash_attn_enabled:
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
cu_seqlens = None
|
||||
max_seqlen = None
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.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)
|
||||
|
||||
|
||||
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_checkpoint_conversion_mapping = {}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config, **kwargs):
|
||||
super().__init__(config, **kwargs)
|
||||
self.model = Qwen3_5Model(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.model.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.model.embed_tokens = value
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
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,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
temperature: Union[torch.Tensor, None] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5 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)
|
||||
elif input_ids is not None:
|
||||
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
|
||||
|
||||
outputs = 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):
|
||||
lm_rope = self.model.rotary_emb
|
||||
if hasattr(lm_rope, "rope_init_fn"):
|
||||
inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device)
|
||||
lm_rope.inv_freq.copy_(inv_freq)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Qwen3_5ForCausalLM",
|
||||
"Qwen3_5GatedFlashAttention",
|
||||
"Qwen3_5Model",
|
||||
"Qwen3_5PreTrainedModel",
|
||||
]
|
||||
@@ -551,6 +551,14 @@ QWEN35MOE_ATTN_IMPL2CLASS = {
|
||||
}
|
||||
|
||||
|
||||
def normalize_qwen3_5_attn_implementation(attn_impl: str) -> str:
|
||||
if attn_impl == "eager":
|
||||
return "sdpa"
|
||||
if attn_impl == "kernels-community/vllm-flash-attn3":
|
||||
return "flash_attention_3"
|
||||
return attn_impl
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Decoder layer
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -567,9 +575,8 @@ def _get_gated_attention(config: Qwen3_5MoeConfig) -> nn.Module:
|
||||
attention_dropout=config.attention_dropout,
|
||||
)
|
||||
|
||||
attn_impl = config._attn_implementation
|
||||
if attn_impl == "eager":
|
||||
attn_impl = "sdpa"
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
config._attn_implementation = attn_impl
|
||||
|
||||
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
|
||||
@@ -783,6 +790,17 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
"hidden_states": Qwen3_5MoeDecoderLayer,
|
||||
}
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
|
||||
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5-MoE attention does not support '{attn_implementation}'. Supported implementations: {supported}."
|
||||
)
|
||||
return attn_impl
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
@@ -819,6 +837,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
def __init__(self, config: Qwen3_5MoeConfig):
|
||||
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
@@ -116,7 +116,9 @@ class MultiCheckpointManager:
|
||||
scheduler: "MultiLoRAScheduler",
|
||||
) -> None:
|
||||
for idx in self.multi_run_manager.used_idxs:
|
||||
step = self.multi_run_manager.progress[idx].step
|
||||
# pack() already advanced progress to the next step, so the step just finished
|
||||
# (and its broadcasts/step_{step} weights) is progress - 1.
|
||||
step = self.multi_run_manager.progress[idx].step - 1
|
||||
if not self._should_save(idx, step):
|
||||
continue
|
||||
|
||||
|
||||
@@ -68,9 +68,11 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
# TODO: Broadcast ready to update in sync, then we dont need to gather on not ready
|
||||
if self.world.is_master:
|
||||
try:
|
||||
# pack() already advanced progress to the next step, so the model we just
|
||||
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
|
||||
save_dir = get_step_path(
|
||||
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
|
||||
self.multi_run_manager.progress[idx].step,
|
||||
self.multi_run_manager.progress[idx].step - 1,
|
||||
)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -112,6 +114,6 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
for idx in self.multi_run_manager.used_idxs:
|
||||
maybe_clean(
|
||||
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
|
||||
self.multi_run_manager.progress[idx].step,
|
||||
self.multi_run_manager.progress[idx].step - 1,
|
||||
interval_to_keep,
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from typing import Callable, Generator, cast
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.distributed.tensor import DTensor
|
||||
@@ -200,7 +201,7 @@ class NCCLWeightBroadcast(WeightBroadcast):
|
||||
# `_compute_notified_runs` is a pure function of SPMD-replicated state on
|
||||
# multi_run_manager, so every trainer rank derives the same list. Only
|
||||
# the master touches the filesystem to notify the orchestrator, but all
|
||||
# ranks must wait on NCCL_READY before entering the broadcast path:
|
||||
# ranks must wait for the inference pool before entering the broadcast path:
|
||||
# the broadcast preparation (DTensor resolution, quantization) enqueues
|
||||
# collectives on non-master ranks, and if those ranks start prep before
|
||||
# the orchestrator has paused inference, the collectives sit unmatched
|
||||
@@ -208,7 +209,9 @@ class NCCLWeightBroadcast(WeightBroadcast):
|
||||
notified_runs = self._compute_notified_runs()
|
||||
if self.world.is_master:
|
||||
self._notify_orchestrator(notified_runs)
|
||||
self._wait_for_nccl_ready(notified_runs)
|
||||
self._wait_for_nccl_ready(notified_runs)
|
||||
if self.world.world_size > 1:
|
||||
dist.barrier()
|
||||
self.nccl_broadcast_sender.broadcast_weights(model, step)
|
||||
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
|
||||
|
||||
@@ -224,9 +227,11 @@ class NCCLWeightBroadcast(WeightBroadcast):
|
||||
if not self.multi_run_manager.ready_to_update[idx]:
|
||||
continue
|
||||
try:
|
||||
# pack() already advanced progress to the next step, so the model we just
|
||||
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
|
||||
save_dir = get_step_path(
|
||||
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
|
||||
self.multi_run_manager.progress[idx].step,
|
||||
self.multi_run_manager.progress[idx].step - 1,
|
||||
)
|
||||
notified_runs.append((idx, save_dir))
|
||||
except FileNotFoundError:
|
||||
|
||||
@@ -222,6 +222,8 @@ def train(config: TrainerConfig):
|
||||
progress = Progress()
|
||||
if checkpoint_step is not None:
|
||||
ckpt_manager.load(checkpoint_step, model, [optimizer], scheduler, progress)
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
progress.step += 1
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
|
||||
logger.info(
|
||||
@@ -248,7 +250,6 @@ def train(config: TrainerConfig):
|
||||
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
|
||||
|
||||
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
|
||||
is_first_step = True
|
||||
maybe_record_function = nullcontext
|
||||
if config.trace_path:
|
||||
logger.info(f"Tracing to {config.trace_path}")
|
||||
@@ -261,73 +262,6 @@ def train(config: TrainerConfig):
|
||||
gc_handler.run(progress.step)
|
||||
is_last_step = config.max_steps is not None and progress.step == config.max_steps
|
||||
|
||||
# Broadcast weights every step except:
|
||||
# - step 0: nothing has changed yet, the orchestrator has the base model.
|
||||
# - the final NCCL broadcast: with a 1-step async barrier the orchestrator's last step
|
||||
# uses the trainer's penultimate ckpt, so the trainer's last broadcast has no receiver
|
||||
# (the inference NCCL group has been torn down). Filesystem broadcast still writes the
|
||||
# final step so we can resume from the broadcast directory.
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
nccl_broadcast_unused = (
|
||||
config.weight_broadcast.type == "nccl"
|
||||
and config.max_steps is not None
|
||||
and progress.step >= config.max_steps - 1
|
||||
)
|
||||
if progress.step > 0 and not nccl_broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
interval_to_keep = config.ckpt and config.ckpt.interval
|
||||
weight_broadcast.maybe_clean(interval_to_keep)
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = False
|
||||
|
||||
if config.max_concurrent_runs > 1:
|
||||
# Multi-run: Save per-run checkpoints using each run's orchestrator config.
|
||||
# Trainer-level ckpt config can be set by the combined rl entrypoint,
|
||||
# but MultiCheckpointManager has a different save signature.
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(optimizer, scheduler)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
ckpt_manager.maybe_clean()
|
||||
elif (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not (is_first_step or is_last_step)
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Single-run: Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Break if we have reached the maximum number of steps
|
||||
if config.max_steps is not None and progress.step >= config.max_steps:
|
||||
break
|
||||
|
||||
logger.debug(f"Starting training step {progress.step}")
|
||||
step_start_time = time.perf_counter()
|
||||
|
||||
@@ -620,6 +554,69 @@ def train(config: TrainerConfig):
|
||||
current_lr = optimizer.get_current_lr()
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
|
||||
# sample its next step from it. Skip the final NCCL broadcasts: with a 1-step async barrier
|
||||
# the orchestrator's last step uses the trainer's penultimate ckpt, so they have no receiver
|
||||
# (the inference NCCL group is torn down). Filesystem broadcast still writes them so we can
|
||||
# resume from the broadcast directory.
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
nccl_broadcast_unused = (
|
||||
config.weight_broadcast.type == "nccl"
|
||||
and config.max_steps is not None
|
||||
and progress.step >= config.max_steps - 1
|
||||
)
|
||||
if not nccl_broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
interval_to_keep = config.ckpt and config.ckpt.interval
|
||||
weight_broadcast.maybe_clean(interval_to_keep)
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = False
|
||||
|
||||
# Checkpoint the step we just finished (model = policy v{progress.step}).
|
||||
if config.max_concurrent_runs > 1:
|
||||
# Multi-run: save per-run checkpoints every step (interval-gated inside
|
||||
# MultiCheckpointManager); there is no after-loop final save for multi-run.
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(optimizer, scheduler)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
ckpt_manager.maybe_clean()
|
||||
elif (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
# the last step is written once after the loop (final ckpt), so skip it here
|
||||
and not is_last_step
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Single-run: Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Optionally, dump memory snapshot
|
||||
if memory_profiler is not None:
|
||||
memory_profiler.step()
|
||||
@@ -737,13 +734,14 @@ def train(config: TrainerConfig):
|
||||
run_stats=run_stats,
|
||||
)
|
||||
|
||||
progress.step += 1
|
||||
is_first_step = False
|
||||
|
||||
# Send heartbeat if configured
|
||||
if heart is not None:
|
||||
heart.beat()
|
||||
|
||||
if is_last_step:
|
||||
break
|
||||
progress.step += 1
|
||||
|
||||
if config.trace_path:
|
||||
prof.__exit__(None, None, None)
|
||||
config.trace_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -20,7 +20,7 @@ if TYPE_CHECKING:
|
||||
|
||||
@dataclass
|
||||
class Progress:
|
||||
step: int = 0
|
||||
step: int = 1
|
||||
total_tokens: int = 0
|
||||
total_samples: int = 0
|
||||
|
||||
@@ -278,16 +278,17 @@ class MultiRunManager:
|
||||
|
||||
# Set progress based on resume_step config (match orchestrator behavior)
|
||||
self.progress[new_id] = Progress()
|
||||
# ``step_S`` means step S finished; resume continues at S+1.
|
||||
if config.ckpt is None or config.ckpt.resume_step is None:
|
||||
self.progress[new_id].step = 0
|
||||
self.progress[new_id].step = 1
|
||||
elif config.ckpt.resume_step == -1:
|
||||
ckpt_dir = self.get_run_dir(new_id) / "checkpoints"
|
||||
# In multi-run, the trainer writes STABLE after saving LoRA weights to the run's checkpoint dir.
|
||||
# In single-run, only the orchestrator writes checkpoints here (trainer has its own dir), so no STABLE exists.
|
||||
steps = get_stable_ckpt_steps(ckpt_dir) if self.max_runs > 1 else get_all_ckpt_steps(ckpt_dir)
|
||||
self.progress[new_id].step = max(steps) if steps else 0
|
||||
self.progress[new_id].step = max(steps) + 1 if steps else 1
|
||||
else:
|
||||
self.progress[new_id].step = config.ckpt.resume_step
|
||||
self.progress[new_id].step = config.ckpt.resume_step + 1
|
||||
|
||||
# Store the parsed config
|
||||
self.config[new_id] = config
|
||||
|
||||
@@ -215,6 +215,9 @@ def train(config: SFTConfig):
|
||||
dataloader=dataloader if not config.ckpt.skip_dataloader else None,
|
||||
)
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
if not config.ckpt.skip_progress:
|
||||
progress.step += 1
|
||||
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
|
||||
if config.ckpt.skip_scheduler:
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
|
||||
@@ -347,37 +350,6 @@ def train(config: SFTConfig):
|
||||
gc_handler.run(progress.step)
|
||||
is_last_step = config.max_steps is not None and progress.step == config.max_steps
|
||||
|
||||
if (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not (is_first_step or is_last_step)
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Break if we have reached the maximum number of steps
|
||||
if config.max_steps is not None and progress.step >= config.max_steps:
|
||||
break
|
||||
|
||||
memory_profiler = (
|
||||
MemoryProfiler(progress.step, config.memory_profiler_path) if config.memory_profiler_path else None
|
||||
)
|
||||
@@ -482,6 +454,35 @@ def train(config: SFTConfig):
|
||||
current_lr = optimizer.param_groups[0]["lr"]
|
||||
scheduler.step()
|
||||
|
||||
# Checkpoint the step we just finished. The last step's checkpoint is written once after
|
||||
# the loop, so skip it here to avoid a double-save.
|
||||
if (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not is_last_step
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Optionally, dump memory snapshot
|
||||
if memory_profiler is not None:
|
||||
memory_profiler.step()
|
||||
@@ -585,12 +586,15 @@ def train(config: SFTConfig):
|
||||
monitor.log({**moe_log_metrics, "step": progress.step}, step=progress.step)
|
||||
|
||||
is_first_step = False
|
||||
progress.step += 1
|
||||
|
||||
# Send heartbeat if configured
|
||||
if heart is not None:
|
||||
heart.beat()
|
||||
|
||||
if is_last_step:
|
||||
break
|
||||
progress.step += 1
|
||||
|
||||
if config.trace_path:
|
||||
prof.__exit__(None, None, None)
|
||||
config.trace_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -16,6 +16,7 @@ import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from verifiers.v1.push import trace_to_sample
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
@@ -325,36 +326,29 @@ class PrimeMonitor(Monitor):
|
||||
)
|
||||
|
||||
def _rollouts_to_parquet_bytes(self, rollouts: list[Rollout], step: int) -> bytes | None:
|
||||
"""Convert rollouts to Parquet bytes for upload. One row per rollout, built from the
|
||||
message graph: the conversation is the unit (no prompt/completion split — meaningless in
|
||||
a multi-turn branch), so `completion` carries the main (last) branch's full message list
|
||||
and `trajectory` carries one message list per branch (`trace.branches`)."""
|
||||
"""Convert rollouts to Parquet bytes for upload. One row per rollout. The conversation
|
||||
is the unit (no prompt/completion split — meaningless mid-branch): `completion` is the
|
||||
last branch's messages and `trajectory` is one message list per branch. Shares
|
||||
`verifiers.v1.push.trace_to_sample` with verifiers' eval `--push`, so a training-run
|
||||
sample and an eval sample land on the platform identically; the RFT-only columns
|
||||
(run/step/advantage/problem_id/env_name) are layered on here."""
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = []
|
||||
|
||||
for sample_id, rollout in enumerate(rollouts):
|
||||
branches = rollout.branches
|
||||
if not branches:
|
||||
sample = trace_to_sample(rollout, rollout_number=sample_id + 1)
|
||||
trajectory = sample["trajectory"]
|
||||
if not trajectory: # no branches (e.g. a rollout that errored before any message)
|
||||
continue
|
||||
main_messages = [m.model_dump(mode="json") for m in branches[-1].messages]
|
||||
advantage = rollout.scalar_advantage()
|
||||
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
|
||||
|
||||
task_idx = rollout.task.idx
|
||||
example_id = sample["example_id"]
|
||||
try:
|
||||
problem_id = int(task_idx) if task_idx is not None else sample_id
|
||||
problem_id = int(example_id) if example_id is not None else sample_id
|
||||
except (TypeError, ValueError):
|
||||
problem_id = sample_id
|
||||
|
||||
trajectory_data = [
|
||||
{
|
||||
"messages": [m.model_dump(mode="json") for m in branch.messages],
|
||||
"reward": rollout.reward,
|
||||
"advantage": rollout.scalar_advantage(),
|
||||
"num_input_tokens": branch.num_input_tokens,
|
||||
"num_output_tokens": branch.num_output_tokens,
|
||||
}
|
||||
for branch in branches
|
||||
]
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"run_id": self.run_id,
|
||||
@@ -363,18 +357,18 @@ class PrimeMonitor(Monitor):
|
||||
"problem_id": problem_id,
|
||||
"sample_id": sample_id,
|
||||
"prompt": "",
|
||||
"completion": json.dumps(main_messages),
|
||||
"trajectory": json.dumps(trajectory_data),
|
||||
"completion": json.dumps(sample["completion"]),
|
||||
"trajectory": json.dumps(trajectory),
|
||||
"answer": "",
|
||||
"env_name": rollout.env_name,
|
||||
"task": rollout.task.model_dump_json(),
|
||||
"task": json.dumps(sample["task"]),
|
||||
"info": json.dumps(rollout.info),
|
||||
"reward": rollout.reward,
|
||||
"advantage": rollout.scalar_advantage(),
|
||||
"metrics": json.dumps(rollout.metrics),
|
||||
"timing": rollout.timing.model_dump_json(),
|
||||
"num_input_tokens": branches[-1].num_input_tokens,
|
||||
"num_output_tokens": branches[-1].num_output_tokens,
|
||||
"reward": sample["reward"],
|
||||
"advantage": advantage,
|
||||
"metrics": json.dumps(sample["metrics"]),
|
||||
"timing": json.dumps(sample["timing"]),
|
||||
"num_input_tokens": trajectory[-1]["num_input_tokens"],
|
||||
"num_output_tokens": trajectory[-1]["num_output_tokens"],
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -313,6 +313,7 @@ PERFORMANCE_METRICS = [
|
||||
"perf/mfu",
|
||||
"time/step",
|
||||
"time/wait_for_batch",
|
||||
"time/wait_for_policy",
|
||||
"inference/agg/throughput",
|
||||
"inference/agg/running_requests",
|
||||
"inference/agg/waiting_requests",
|
||||
|
||||
@@ -73,6 +73,13 @@ def get_rollout_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "rollouts"
|
||||
|
||||
|
||||
def get_trace_path(output_dir: Path, step: int, kind: str, subset: str) -> Path:
|
||||
"""Where one trace file lives: ``rollouts/step_{n}/{train,eval}/{all,effective}/traces.jsonl``.
|
||||
``all`` is appended per rollout the moment it completes; ``effective`` is written at once
|
||||
per finalized train batch / eval epoch."""
|
||||
return get_step_path(get_rollout_dir(output_dir), step) / kind / subset / "traces.jsonl"
|
||||
|
||||
|
||||
def get_eval_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "evals"
|
||||
|
||||
@@ -150,7 +157,7 @@ def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool, ckpt_o
|
||||
|
||||
|
||||
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
|
||||
"""Remove stale rollouts and broadcasts past ``resume_step``.
|
||||
"""Remove stale rollouts, broadcasts, and traces past ``resume_step``.
|
||||
|
||||
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import inspect
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForCausalLM as HFQwen3_5ForCausalLM
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
|
||||
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
|
||||
|
||||
|
||||
def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
|
||||
config = Qwen3_5TextConfig(
|
||||
vocab_size=128,
|
||||
hidden_size=64,
|
||||
intermediate_size=128,
|
||||
num_hidden_layers=2,
|
||||
layer_types=["linear_attention", "full_attention"],
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=16,
|
||||
max_position_embeddings=128,
|
||||
linear_key_head_dim=8,
|
||||
linear_value_head_dim=8,
|
||||
linear_num_key_heads=4,
|
||||
linear_num_value_heads=8,
|
||||
linear_conv_kernel_dim=4,
|
||||
)
|
||||
config._attn_implementation = attn_impl
|
||||
return config
|
||||
|
||||
|
||||
def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
|
||||
config = Qwen3_5MoeConfig(
|
||||
vocab_size=128,
|
||||
hidden_size=64,
|
||||
num_hidden_layers=2,
|
||||
layer_types=["linear_attention", "full_attention"],
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=16,
|
||||
max_position_embeddings=128,
|
||||
linear_key_head_dim=8,
|
||||
linear_value_head_dim=8,
|
||||
linear_num_key_heads=4,
|
||||
linear_num_value_heads=8,
|
||||
linear_conv_kernel_dim=4,
|
||||
moe_intermediate_size=128,
|
||||
shared_expert_intermediate_size=128,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
config._attn_implementation = attn_impl
|
||||
return config
|
||||
|
||||
|
||||
def test_qwen3_5_dense_matches_hf_state_keys_on_meta():
|
||||
config = _tiny_text_config()
|
||||
with torch.device("meta"):
|
||||
hf_model = HFQwen3_5ForCausalLM(config)
|
||||
prime_model = Qwen3_5ForCausalLM(config)
|
||||
|
||||
assert set(prime_model.state_dict()) == set(hf_model.state_dict())
|
||||
for name, tensor in prime_model.state_dict().items():
|
||||
assert tensor.shape == hf_model.state_dict()[name].shape, name
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attn_impl", ["flash_attention_3", "kernels-community/vllm-flash-attn3"])
|
||||
def test_qwen3_5_full_attention_uses_custom_class(attn_impl: str):
|
||||
config = _tiny_text_config(attn_impl=attn_impl)
|
||||
with torch.device("meta"):
|
||||
model = Qwen3_5Model(config)
|
||||
|
||||
assert isinstance(model.layers[1].self_attn, Qwen3_5GatedFlashAttention)
|
||||
assert model.config._attn_implementation == "flash_attention_3"
|
||||
assert "ALL_ATTENTION_FUNCTIONS" not in inspect.getsource(type(model.layers[1].self_attn).forward)
|
||||
|
||||
|
||||
def test_qwen3_5_moe_full_attention_normalizes_fa3_hub_alias():
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeGatedFlashAttention,
|
||||
Qwen3_5MoeModel,
|
||||
)
|
||||
|
||||
config = _tiny_moe_config(attn_impl="kernels-community/vllm-flash-attn3")
|
||||
with torch.device("meta"):
|
||||
model = Qwen3_5MoeModel(config)
|
||||
|
||||
assert isinstance(model.layers[1].self_attn, Qwen3_5MoeGatedFlashAttention)
|
||||
assert model.config._attn_implementation == "flash_attention_3"
|
||||
|
||||
|
||||
def test_qwen3_5_ring_patches_dense_flash_attention():
|
||||
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
|
||||
originals = {
|
||||
cls: cls._compute_attention
|
||||
for cls in (FlashAttention, AfmoeFlashAttention, Qwen3_5MoeGatedFlashAttention, Qwen3_5GatedFlashAttention)
|
||||
}
|
||||
try:
|
||||
substitute_ring_attn(process_group=MagicMock(), heads_k_stride=1)
|
||||
assert Qwen3_5GatedFlashAttention._compute_attention is not originals[Qwen3_5GatedFlashAttention]
|
||||
finally:
|
||||
for cls, method in originals.items():
|
||||
cls._compute_attention = method
|
||||
@@ -97,19 +97,20 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
start_step=0,
|
||||
)
|
||||
|
||||
packer.buffers[run_idx].append((make_training_sample(), 0))
|
||||
packer.buffers[run_idx].append((make_training_sample(), 0))
|
||||
# Steps are 1-indexed: a fresh run starts at step 1, so the first batch's samples carry step 1.
|
||||
packer.buffers[run_idx].append((make_training_sample(), 1))
|
||||
packer.buffers[run_idx].append((make_training_sample(), 1))
|
||||
|
||||
packer.pack()
|
||||
|
||||
progress = manager.progress[run_idx]
|
||||
assert progress.total_samples == 2
|
||||
assert progress.total_tokens == 4
|
||||
assert progress.step == 1
|
||||
assert progress.step == 2
|
||||
|
||||
sender = sender_holder["sender"]
|
||||
assert len(sender.sent) == 1
|
||||
assert len(sender.sent[0][0]) == 1
|
||||
micro_batch = sender.sent[0][0][0]
|
||||
assert micro_batch.run_id == "run_test123"
|
||||
assert micro_batch.run_step == 0
|
||||
assert micro_batch.run_step == 1
|
||||
|
||||
Reference in New Issue
Block a user