Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4487ef3d7d | ||
|
|
4b3319f3a0 | ||
|
|
82fb5e1943 | ||
|
|
40e0fcea90 | ||
|
|
7c9d4744cd | ||
|
|
52455b41fc | ||
|
|
4f4d7e4402 | ||
|
|
1e5318108d |
@@ -6,9 +6,6 @@
|
||||
#
|
||||
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
|
||||
#
|
||||
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
|
||||
# conversion cache, which takes far longer than the 3600s default.
|
||||
#
|
||||
# To buy memory back for quicker testing on fewer nodes, set `offload = "full"` under `[model]`,
|
||||
# which keeps the fp32 masters, moments and gradients in CPU RAM and disables gradient clipping;
|
||||
# the lighter `offload = "optimizer"` is already the default here.
|
||||
@@ -17,7 +14,6 @@
|
||||
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
|
||||
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
|
||||
|
||||
dist_timeout_seconds = 14400
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
|
||||
+3
-1
@@ -192,7 +192,7 @@ The orchestrator stamps each sample's component membership as per-token weight s
|
||||
|
||||
### IPO Loss
|
||||
|
||||
The default RL loss is Importance Policy Optimization (IPO). It is an importance-weighted policy-gradient term. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
|
||||
The default RL loss is INTELLECT Policy Optimization (IPO). It is an importance-weighted policy-gradient term. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
|
||||
@@ -211,6 +211,8 @@ The knobs under `[trainer.loss]` are:
|
||||
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
See [IPO](ipo.md) for why IPO masks by probability instead of ratio, and the GLM-4.5-Air ablation against IcePop behind `eps = 0.3`.
|
||||
|
||||
### IcePop Loss
|
||||
|
||||
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 228 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 357 KiB |
+74
@@ -0,0 +1,74 @@
|
||||
# IPO
|
||||
|
||||
IPO (INTELLECT Policy Optimization) is the default RL loss in prime-rl. This page explains why it masks tokens by probability instead of ratio, and shows the ablation behind the default `eps = 0.3`. The loss definition and its knobs are in [Algorithms § IPO Loss](algorithms.md#ipo-loss).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Masking by Probability, Not Ratio](#masking-by-probability-not-ratio)
|
||||
- [Ablation: IPO vs IcePop](#ablation-ipo-vs-icepop)
|
||||
- [Choosing `eps`](#choosing-eps)
|
||||
- [Reproducing](#reproducing)
|
||||
|
||||
## Masking by Probability, Not Ratio
|
||||
|
||||
In async RL, the trainer and the inference engine never agree exactly on a token's probability. The usual fix keeps importance sampling but drops the tokens where the two disagree too much. [IcePop](algorithms.md#icepop-loss) measures disagreement as a ratio and masks a token when $\pi_{\text{train}}/\pi_{\text{infer}}$ falls outside a fixed band $[\alpha, \beta]$. IPO masks a token when its absolute probability moved too much:
|
||||
|
||||
$$
|
||||
\left|\pi_{\text{train}}(y_t) - \pi_{\text{infer}}(y_t)\right| > \epsilon
|
||||
$$
|
||||
|
||||
```python
|
||||
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
is_masked = probs_diff.abs() > eps # double-sided, independent of the advantage sign
|
||||
```
|
||||
|
||||
A ratio treats every token the same regardless of its probability, which behaves badly at both ends:
|
||||
|
||||
- A rare token going from 0.01 to 0.06 has a ratio of 6×, so IcePop masks it, although it moved only 0.05 of probability mass.
|
||||
- A likely token going from 0.90 to 0.20 has a ratio of 0.22, so IcePop keeps it, although it moved 0.70 of probability mass.
|
||||
|
||||
Treat the vocabulary as two outcomes, *this token* and *everything else*. Then $|\pi_{\text{train}} - \pi_{\text{infer}}|$ is the total-variation distance between the two engines on that split. The mask is double-sided and has one knob. [KPop](https://ringtech.notion.site/kpop) reached the same diagnosis independently and uses a binary KL instead.
|
||||
|
||||
## Ablation: IPO vs IcePop
|
||||
|
||||
GLM-4.5-Air on agentic SWE RL, with every arm on the same recipe and only `[trainer.loss]` changing:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Model | `zai-org/GLM-4.5-Air` (100B MoE), BF16 training and inference |
|
||||
| Task | `scaleswe` with the `bash` harness, taskset reward; eval on SWE-Bench Verified |
|
||||
| Topology | 2 trainer nodes (Muon, CP 4 ulysses), 4 single-node TP=8 inference replicas with expert parallelism |
|
||||
| Batch | 256 rollouts (16 groups of 16) at 131k context |
|
||||
| Off-policy | up to 64 steps (`max_off_policy_steps = 64`), no router replay |
|
||||
| Algorithm | GRPO with a linear length penalty (output tokens, input tokens, and turns at 0.1) |
|
||||
| Arms | IcePop with $[\alpha, \beta] = [0.2, 5]$; IPO with `eps = 0.2` and `eps = 0.3` |
|
||||
|
||||

|
||||
|
||||
For the first 1k steps the arms are indistinguishable. IcePop's trainer–inference KL then creeps up and explodes around step 1.2k, more than 20× its baseline, and the solve rate falls from about 0.8 to about 0.3. Both IPO arms keep the mismatch low through the same window and keep training.
|
||||
|
||||
IcePop masks very little before it breaks: at steps 678–679 it masked 72 of 2.16M tokens (0.003%). Under a ratio band, the masked fraction stays tiny while the gap widens, so nothing pushes back once drift starts.
|
||||
|
||||
## Choosing `eps`
|
||||
|
||||
The first IPO default was `eps = 0.1`. On the run above it masked about 2% of tokens, and by step 1k its entropy had collapsed. To pick a new value without a sweep of full runs, we replayed the trainer and inference probabilities of 1.8M sampled tokens and measured what each `eps` would have masked:
|
||||
|
||||

|
||||
|
||||
| `eps` | 0.1 | 0.2 | **0.3** | 0.5 | IcePop [0.2, 5] |
|
||||
|---|---|---|---|---|---|
|
||||
| tokens masked | 1.98% | 0.64% | **0.25%** | 0.047% | 0.06% |
|
||||
|
||||
The IPO band has the same width in probability everywhere. The IcePop cone is very narrow near zero, where it masks rare tokens that barely moved, and very wide near one, where it keeps likely tokens that lost most of their mass. `eps = 0.3` masks only the tail and targets the tokens IcePop lets through. Both 0.2 and 0.3 were stable in full runs; 0.3 kept the highest entropy with the lowest mismatch KL, so it is the default.
|
||||
|
||||
## Reproducing
|
||||
|
||||
The configs are in [`examples/advanced/glm-4.5-air/ipo-ablation/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air/ipo-ablation): a shared `base.toml` and one overlay per loss. See the [GLM-4.5-Air README](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) for cluster setup.
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/ipo.toml
|
||||
uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/ipo.toml --trainer.loss.eps 0.2
|
||||
uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/icepop.toml
|
||||
```
|
||||
|
||||
Compare `mismatch_kl/all/mean` and the training solve rate across arms.
|
||||
@@ -11,6 +11,7 @@
|
||||
"inference",
|
||||
"scaling",
|
||||
"algorithms",
|
||||
"ipo",
|
||||
"advanced",
|
||||
"development"
|
||||
]
|
||||
|
||||
@@ -17,6 +17,7 @@ This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster
|
||||
- [Optimizer Offloading](#optimizer-offloading)
|
||||
- [LM Head Chunking](#lm-head-chunking)
|
||||
- [Memory-Tight Recipe](#memory-tight-recipe)
|
||||
- [Max Trainer Throughput Recipe](#max-trainer-throughput-recipe)
|
||||
- [SLURM](#slurm)
|
||||
- [Activation](#activation)
|
||||
- [`[deployment]` Block](#deployment-block)
|
||||
@@ -173,6 +174,27 @@ max_inflight_activations = 1
|
||||
|
||||
The defaults already cover: fused LM head chunking (`8192`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
|
||||
|
||||
## Max Trainer Throughput Recipe
|
||||
|
||||
The trainer defaults are tuned for memory, not speed: optimizer CPU offload, AC offloading, and `torch.compile` without `fullgraph` let large models fit on few GPUs, at a throughput cost. When you have enough GPUs to keep the model state and activations on GPU, turn them off:
|
||||
|
||||
```toml
|
||||
[model]
|
||||
offload = "none" # optimizer states stay on GPU
|
||||
ac_offloading = "None" # activations stay on GPU
|
||||
moe_router_dtype = "bfloat16" # fullgraph needs the router inside the block's FSDP unit; an fp32 router is not
|
||||
|
||||
[model.compile]
|
||||
fullgraph = true # compile each block as a single graph
|
||||
```
|
||||
|
||||
Then add nodes instead of CP (`cp = 1`) and run one full-length sequence per GPU (`micro_batch_size = 1`). Keep full AC unless selective AC fits. The SFT default router dtype is already `bfloat16`. RL defaults to an fp32 router, so check that bf16 routing is acceptable for your model before using `fullgraph` in RL.
|
||||
|
||||
Examples:
|
||||
|
||||
- [`examples/advanced/qwen3-235b-a22b/sft-max-perf.toml`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-235b-a22b): Qwen3-235B-A22B SFT on 4 x 8 B300 at 16k, around 46% MFU.
|
||||
- [`examples/advanced/glm-5.3/sft/h200/16k-12-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/sft/h200): the same recipe as an overlay for GLM-5.3 SFT on 12 H200 nodes.
|
||||
|
||||
## SLURM
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
|
||||
|
||||
@@ -12,6 +12,7 @@ Larger runs on frontier models, one folder per model, each with a launch README
|
||||
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
|
||||
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
|
||||
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
|
||||
- [`qwen3-235b-a22b/`](advanced/qwen3-235b-a22b/README.md) — SFT max trainer perf: `Qwen3-235B-A22B` on 4 trainer nodes at 16k context, a throughput reference using the max trainer throughput recipe.
|
||||
|
||||
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
|
||||
|
||||
|
||||
@@ -9,6 +9,9 @@ RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a
|
||||
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
|
||||
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
|
||||
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
|
||||
| [`ipo-ablation/`](ipo-ablation) `base.toml` + `ipo.toml` / `icepop.toml` | `scaleswe` (`bash` harness), no router replay, 64 steps off-policy | `swebench-verified` | 2 train + 4 infer nodes |
|
||||
|
||||
The `ipo-ablation/` configs reproduce the IPO vs IcePop loss ablation in [docs/ipo.md](../../../docs/ipo.md).
|
||||
|
||||
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# IPO vs IcePop ablation on GLM-4.5-Air agentic SWE RL (see docs/ipo.md). Shared base: compose with one
|
||||
# loss overlay from this folder, e.g.
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/icepop.toml
|
||||
#
|
||||
# The arms differ only in [trainer.loss]. Same recipe as ../swe.toml with three changes that make the
|
||||
# trainer-inference mismatch harder to handle: router replay off, up to 64 steps off-policy, and an
|
||||
# output-token term in the length penalty. 2 trainer nodes (Muon, CP 4 ulysses) and 4 single-node
|
||||
# TP=8 BF16 inference replicas, batch 256 x group 16 at 131k context.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
[slurm]
|
||||
partition = "all"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[monitors.wandb]
|
||||
project = "ipo-ablation"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
[resume]
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
enable_router_replay = false
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
max_off_policy_steps = 64
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.train.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.1
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
group_size = 1
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
@@ -0,0 +1,12 @@
|
||||
# IcePop arm: mask a token when p_train / p_infer falls outside [ratio_low, ratio_high].
|
||||
|
||||
[slurm]
|
||||
job_name = "ipo-ablation-icepop"
|
||||
|
||||
[monitors.wandb]
|
||||
name = "icepop"
|
||||
|
||||
[trainer.loss]
|
||||
type = "icepop"
|
||||
ratio_low = 0.2
|
||||
ratio_high = 5.0
|
||||
@@ -0,0 +1,12 @@
|
||||
# IPO arm: mask a token when |p_train - p_infer| > eps. eps = 0.3 is the default; the ablation also ran
|
||||
# eps = 0.2 (`--trainer.loss.eps 0.2`).
|
||||
|
||||
[slurm]
|
||||
job_name = "ipo-ablation-ipo"
|
||||
|
||||
[monitors.wandb]
|
||||
name = "ipo-eps-0.3"
|
||||
|
||||
[trainer.loss]
|
||||
type = "ipo"
|
||||
eps = 0.3
|
||||
@@ -0,0 +1,25 @@
|
||||
# Qwen3-235B-A22B: SFT max trainer perf
|
||||
|
||||
A throughput reference for the SFT trainer on a large MoE: `Qwen/Qwen3-235B-A22B-Thinking-2507` on 4 nodes x 8 B300 at 16k context. It applies the [Max Trainer Throughput Recipe](../../../docs/scaling.md#max-trainer-throughput-recipe): everything on GPU, no offloading, `fullgraph` compile. It runs 20 steps on balanced routing and writes no checkpoint. Use it to check a cluster or a trainer change against a known number, around 46% MFU.
|
||||
|
||||
| Config | What it runs | Topology |
|
||||
|---|---|---|
|
||||
| [`sft-max-perf.toml`](sft-max-perf.toml) | 20 SFT steps, seq 16384, EP 8, full AC, fp32 AdamW, balanced routing | 4 train nodes |
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 4 nodes x 8 B300 and a shared filesystem.
|
||||
- `HF_TOKEN` exported in the launch shell. The first run downloads the checkpoint and builds the HF -> prime-rl conversion cache, which `dist_timeout_seconds = 14400` covers.
|
||||
|
||||
## Launch
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/advanced/qwen3-235b-a22b/sft-max-perf.toml
|
||||
```
|
||||
|
||||
Read `time/step`, `perf/mfu`, `perf/throughput_per_gpu`, and `perf/peak_memory` from `outputs/<run>/monitors/file/metrics.jsonl`, skipping the first few warmup steps.
|
||||
|
||||
Variants:
|
||||
|
||||
- Real routing: remove `[model.debug]`. Expect it to be noticeably slower, since routing imbalance dominates at this size.
|
||||
- Other clusters: set `[slurm] partition` and point `HF_HOME` at a shared cache via `[env_vars]`.
|
||||
@@ -0,0 +1,61 @@
|
||||
# SFT max trainer perf: Qwen3-235B-A22B on 4 nodes x 8 B300 at seq 16k.
|
||||
#
|
||||
# FSDP over 32 GPUs with EP 8, one packed 16384-token sample per GPU per step (32 x 16384 tokens),
|
||||
# full activation checkpointing, AdamW with fp32 master weights and fp32 optimizer states, bf16
|
||||
# compute, fp32 gradient reduce, FA4 varlen attention, torch.compile with fullgraph per block,
|
||||
# everything on GPU (no CPU offloading), 20 steps. Routing is forced round-robin balanced so the
|
||||
# step time does not depend on the data; drop [model.debug] for the checkpoint's real routing.
|
||||
# See docs/scaling.md#max-trainer-throughput-recipe. Around 46% MFU on 4 x 8 B300.
|
||||
#
|
||||
# uv run sft @ examples/advanced/qwen3-235b-a22b/sft-max-perf.toml
|
||||
#
|
||||
# There is no [ckpt] block: this run measures step time, it does not produce a usable checkpoint.
|
||||
# `dist_timeout_seconds` covers the first run, which builds the HF -> prime-rl conversion cache.
|
||||
|
||||
dist_timeout_seconds = 14400
|
||||
max_steps = 20
|
||||
|
||||
# The renderer registry lists Qwen/Qwen3-235B-A22B but not the 2507 Thinking variant, which uses
|
||||
# the same Qwen3 chat template.
|
||||
[renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-235B-A22B-Thinking-2507"
|
||||
seq_len = 16384
|
||||
ep = 8
|
||||
offload = "none"
|
||||
ac_offloading = "None"
|
||||
# fullgraph needs the router inside the block's FSDP unit, which the fp32 router is not.
|
||||
moe_router_dtype = "bfloat16"
|
||||
|
||||
# Selective AC does not fit at seq 16384 on 4 nodes with fp32 AdamW states and the torch dispatch.
|
||||
[model.ac]
|
||||
mode = "full"
|
||||
freq = 1
|
||||
|
||||
[model.compile]
|
||||
fullgraph = true
|
||||
|
||||
[model.moe.dispatch]
|
||||
type = "torch"
|
||||
|
||||
[model.debug]
|
||||
force_balanced_routing = true
|
||||
|
||||
[data]
|
||||
name = "PrimeIntellect/Reverse-Text-SFT"
|
||||
seq_len = 16384
|
||||
batch_size = 32
|
||||
micro_batch_size = 1
|
||||
|
||||
[optim]
|
||||
type = "adamw"
|
||||
lr = 1e-5
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "qwen3-235b-sft-max-perf"
|
||||
@@ -326,8 +326,8 @@ class SFTConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
dist_timeout_seconds: int = 900
|
||||
"""Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
@@ -42,11 +42,10 @@ class ActivationCheckpointConfig(BaseConfig):
|
||||
|
||||
|
||||
class ActivationOffloadingConfig(BaseConfig):
|
||||
pin_memory: bool = True
|
||||
"""Pin offloaded activations to CPU memory."""
|
||||
"""Offload tensors saved for backward to pinned CPU memory during the forward pass."""
|
||||
|
||||
max_inflight_activations: int = Field(5, ge=1)
|
||||
"""Max activations kept in flight while offloading. More activations smooth overlap at the cost of GPU memory."""
|
||||
"""Max activations kept on GPU while their offload copies are in flight on the side stream. Higher values give more copy/compute overlap at the cost of GPU memory."""
|
||||
|
||||
|
||||
OffloadMode: TypeAlias = Literal["none", "optimizer", "full"]
|
||||
@@ -283,6 +282,9 @@ class ModelConfig(BaseModelConfig):
|
||||
moe_router_dtype: Literal["bfloat16", "float32", "auto"] = "auto"
|
||||
"""Compute dtype for MoE router gates. ``float32`` 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. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. A no-op for non-MoE models."""
|
||||
|
||||
reduce_scatter_max_input_buffers: int = Field(1, ge=1)
|
||||
"""Maximum number of FSDP gradient reduce-scatter input buffers kept in flight. Raising it trades memory (about one layer's gradients per extra buffer) for overlap when reduce-scatters are exposed, e.g. MoE without EP or full activation checkpointing."""
|
||||
|
||||
quantization: QuantizationConfig | None = None
|
||||
|
||||
dsa_backend: DSABackend = "tilelang"
|
||||
@@ -613,8 +615,8 @@ class TrainerConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
dist_timeout_seconds: int = 900
|
||||
"""Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
@@ -28,6 +28,8 @@ def apply_shared_vllm_patches():
|
||||
# Set by `server()` when the LoRA target modules include no expert layers.
|
||||
if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
monkey_patch_no_moe_lora()
|
||||
monkey_patch_deepseek_v4_c128_boundary()
|
||||
monkey_patch_deepseek_v4_attn_sink_loading()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
@@ -47,6 +49,87 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_c128_boundary():
|
||||
"""Fix DeepSeek V4 long-context KV corruption under piecewise CUDA graphs.
|
||||
|
||||
On vLLM 0.30+, including the pinned 0.31.0, the piecewise CUDA graphs are captured on a step
|
||||
that skips writing C128 compressed KV, so every replay skips it too. Mixed batches of up to
|
||||
512 tokens never store their C128 entries, later queries attend over stale compressed KV, and
|
||||
long-context rollouts drift from the trainer, inflating mismatch KL.
|
||||
|
||||
The skip is an optimization: ``DeepseekCompressor.forward`` returns early when
|
||||
``_get_c128_boundary`` reports that no request completes a 128-token block this step.
|
||||
vllm-project/vllm#55353 made that helper return a bool under Model Runner V2, so capture on
|
||||
dummy batches records the early return. Returning None instead disables the skip, which is
|
||||
the path vLLM already takes under async speculative decoding and the one 0.29 always took.
|
||||
|
||||
The upstream fix, vllm-project/vllm#59709, keeps the skip on eager steps and only stops it
|
||||
from being captured. That change sits inline in ``forward``, so matching it here would mean
|
||||
copying the whole method. Patching the helper costs one extra compress kernel launch on eager
|
||||
steps that complete no block, and the kernel already skips those tokens on the GPU.
|
||||
|
||||
Remove this patch once vllm-project/vllm#59709 lands in the pinned vLLM version.
|
||||
"""
|
||||
from vllm.logger import init_logger
|
||||
from vllm.models.deepseek_v4 import compressor
|
||||
|
||||
if getattr(compressor._get_c128_boundary, "_prime_rl_always_compresses", False):
|
||||
return
|
||||
|
||||
def _get_c128_boundary(metadata):
|
||||
return None
|
||||
|
||||
_get_c128_boundary._prime_rl_always_compresses = True
|
||||
compressor._get_c128_boundary = _get_c128_boundary
|
||||
init_logger("vllm.prime_rl.deepseek_v4").info("DeepSeek V4 C128 compressor store runs on every step.")
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_attn_sink_loading():
|
||||
"""Fix DeepSeek V4 weight updates silently keeping the boot-time attention sinks.
|
||||
|
||||
``DeepseekV4Model.load_weights`` writes the sinks with a bare slice copy instead of
|
||||
``param.weight_loader``. Layerwise reload moves parameters to meta and only buffers writes
|
||||
that go through a loader, so the copy is silently dropped. This pads this rank's heads back
|
||||
to the full parameter with ``-inf`` (no sink) and loads that through ``param.weight_loader``.
|
||||
|
||||
Remove this patch once vllm-project/vllm#57797 lands in the pinned vLLM version. Only
|
||||
``nvidia/model.py`` is covered, not the MTP, DSpark or non-NVIDIA variants.
|
||||
"""
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.models.deepseek_v4.nvidia import model as dsv4_model
|
||||
|
||||
original_load_weights = dsv4_model.DeepseekV4Model.load_weights
|
||||
if getattr(original_load_weights, "_prime_rl_uses_weight_loaders", False):
|
||||
return
|
||||
|
||||
def load_weights(self, weights):
|
||||
params = dict(self.named_parameters())
|
||||
tp_size = dsv4_model.get_tensor_model_parallel_world_size()
|
||||
heads_per_rank = self.config.num_attention_heads // tp_size
|
||||
head_start = heads_per_rank * dsv4_model.get_tensor_model_parallel_rank()
|
||||
loaded_params: set[str] = set()
|
||||
|
||||
def remaining_weights():
|
||||
for name, weight in weights:
|
||||
if "attn_sink" not in name or dsv4_model.is_pp_missing_parameter(name, self):
|
||||
yield name, weight
|
||||
continue
|
||||
param = params[name]
|
||||
sink = weight.new_full(tuple(param.shape), -float("inf"))
|
||||
sink[:heads_per_rank] = weight[head_start : head_start + heads_per_rank]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, sink)
|
||||
loaded_params.add(name)
|
||||
|
||||
loaded_params.update(original_load_weights(self, remaining_weights()))
|
||||
return loaded_params
|
||||
|
||||
load_weights._prime_rl_uses_weight_loaders = True
|
||||
dsv4_model.DeepseekV4Model.load_weights = load_weights
|
||||
init_logger("vllm.prime_rl.deepseek_v4").info("DeepSeek V4 attn_sink loads through param.weight_loader.")
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ from prime_rl.trainer.models.fusions import (
|
||||
write_back_loaded_packed_optimizer_state,
|
||||
)
|
||||
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
|
||||
from prime_rl.trainer.utils import get_dcp_group
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
@@ -204,11 +205,11 @@ class CheckpointManager:
|
||||
# FileExistsError (EEXIST + stale is_dir() metadata).
|
||||
if self.world.is_master:
|
||||
dataloader_dir.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
torch.distributed.barrier(group=get_dcp_group())
|
||||
torch.save(dataloader.state_dict(), dataloader_dir / f"rank_{self.world.rank}.pt")
|
||||
|
||||
# Save sharded state
|
||||
dcp_save(state_dict, checkpoint_id=path)
|
||||
dcp_save(state_dict, checkpoint_id=path, process_group=get_dcp_group())
|
||||
|
||||
self.logger.debug(f"Saved training checkpoint in {format_time(time.perf_counter() - start_time)}")
|
||||
|
||||
@@ -228,7 +229,7 @@ class CheckpointManager:
|
||||
# Load sharded state
|
||||
app_state = AppState(model, optimizers if not self.skip_optimizer else [], scheduler, progress)
|
||||
state_dict = {"app": app_state}
|
||||
dcp_load(state_dict=state_dict, checkpoint_id=path)
|
||||
dcp_load(state_dict=state_dict, checkpoint_id=path, process_group=get_dcp_group())
|
||||
if self.skip_optimizer:
|
||||
for optimizer in optimizers:
|
||||
if isinstance(optimizer, OffloadOptimizer):
|
||||
@@ -282,7 +283,7 @@ class CheckpointManager:
|
||||
# re-raise FileExistsError on a parallel FS (see save_to_path).
|
||||
if self.world.is_master:
|
||||
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
torch.distributed.barrier(group=get_dcp_group())
|
||||
|
||||
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
|
||||
@@ -16,7 +16,6 @@ import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Int
|
||||
from torch import Tensor
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
@@ -63,7 +62,8 @@ from prime_rl.trainer.models.qwen3_8_flash_next.indexer import SparseAttentionIn
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
|
||||
from prime_rl.trainer.moe_runtime import configure_moe_runtime
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.utils import get_dcp_group
|
||||
from prime_rl.trainer.world import get_world, wait_for_master
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
@@ -108,6 +108,9 @@ DTYPE_MAP = {
|
||||
"float32": torch.float32,
|
||||
}
|
||||
|
||||
# The one-time HF <-> PrimeRL conversion runs on the master alone and can take hours for large models.
|
||||
CONVERSION_TIMEOUT_S = 4 * 3600
|
||||
|
||||
# We increase the torch.compile recompile limit and cache size as we found this
|
||||
# necessary for training INTELLECT-3 with Muon.
|
||||
torch._dynamo.config.recompile_limit = 16 # default: 8
|
||||
@@ -586,8 +589,6 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
reshard_after_forward=config.reshard_after_forward,
|
||||
shard_placement_fn=shard_placement_fn,
|
||||
)
|
||||
# Keep the router reduction from waiting for the expert reduction's input buffer.
|
||||
block_mlp.router.set_reduce_scatter_max_input_buffers(2)
|
||||
|
||||
fully_shard(
|
||||
transformer_block,
|
||||
@@ -633,6 +634,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
reshard_after_forward=config.reshard_after_forward,
|
||||
shard_placement_fn=shard_placement_fn,
|
||||
)
|
||||
model.set_reduce_scatter_max_input_buffers(config.reduce_scatter_max_input_buffers)
|
||||
|
||||
if not parallel_dims.ep_enabled:
|
||||
return
|
||||
@@ -752,7 +754,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
del snapshot_state_dict
|
||||
|
||||
# All ranks wait for master rank to finish conversion
|
||||
torch.distributed.barrier()
|
||||
wait_for_master(f"model_conversion:{config.name}", timeout=CONVERSION_TIMEOUT_S)
|
||||
if snapshot_path.name == "prime" and not (snapshot_path / ".prime-v1").is_file():
|
||||
raise RuntimeError(f"PrimeRL conversion cache {snapshot_path} is missing the required .prime-v1 marker")
|
||||
|
||||
@@ -765,6 +767,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
dcp_load(
|
||||
state_dict,
|
||||
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
|
||||
process_group=get_dcp_group(),
|
||||
)
|
||||
write_back_loaded_packed_parameters(model, state_dict)
|
||||
|
||||
@@ -832,16 +835,8 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
mark_dynamic_int_args()
|
||||
language_model = get_language_model(model)
|
||||
for layer_id in range(len(language_model.layers)):
|
||||
layer = language_model.layers[layer_id]
|
||||
if isinstance(layer, CheckpointWrapper) and any(
|
||||
isinstance(module, FSDPModule) for module in layer._checkpoint_wrapped_module.modules()
|
||||
):
|
||||
# A nested FSDP unit's hooks always break the graph, and a break inside a compiled checkpoint
|
||||
# sends the block to eager, so keep AC eager around the compiled block. pytorch/pytorch#196626
|
||||
# removes the fp32 router's nested unit by letting it join the block's FSDP unit.
|
||||
layer = layer._checkpoint_wrapped_module
|
||||
# Doing it in-place avoids mangled fqn which can break checkpoint loading
|
||||
layer.compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
get_logger().info(
|
||||
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
|
||||
)
|
||||
@@ -993,15 +988,14 @@ def setup_model(
|
||||
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
|
||||
)
|
||||
|
||||
# the right order is AC -> FSDP -> Compile: compile needs to see which blocks hold nested FSDP units
|
||||
# the right order is AC -> Compile -> FSDP
|
||||
if config.ac is not None:
|
||||
apply_ac(model, config.ac)
|
||||
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
|
||||
if loading_from_checkpoint_later:
|
||||
logger.warning(
|
||||
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
|
||||
|
||||
@@ -5,6 +5,7 @@ import shutil
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from datetime import timedelta
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -24,6 +25,7 @@ if TYPE_CHECKING:
|
||||
from prime_rl.trainer.optim import GradientOffloadManager
|
||||
|
||||
DEFAULT_TIMEOUT = timedelta(seconds=600)
|
||||
DCP_TIMEOUT = timedelta(hours=4)
|
||||
|
||||
|
||||
class GarbageCollection:
|
||||
@@ -203,6 +205,15 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
|
||||
get_logger().debug(f"Initialized torch distributed in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
@cache
|
||||
def get_dcp_group() -> dist.ProcessGroup:
|
||||
"""A gloo group for DCP checkpoint save/load. DCP's collectives wait for the slowest rank's
|
||||
writes or reads (and, on the first HF load, its download), which can outlast
|
||||
``dist_timeout_seconds``; on this group they wait up to ``DCP_TIMEOUT`` instead. Every rank must
|
||||
make its first call at the same point."""
|
||||
return dist.new_group(backend="gloo", timeout=DCP_TIMEOUT)
|
||||
|
||||
|
||||
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
|
||||
"""
|
||||
Visualize the loss mask of a tokenized sample using rich.
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
import torch.distributed as dist
|
||||
|
||||
|
||||
class World:
|
||||
@@ -42,3 +45,15 @@ def get_world() -> World:
|
||||
def reset_world():
|
||||
global _WORLD
|
||||
_WORLD = None
|
||||
|
||||
|
||||
def wait_for_master(key: str, timeout: float) -> None:
|
||||
"""A barrier for work only the master does, which can outlast ``dist_timeout_seconds`` (a model
|
||||
conversion, waiting for a weight broadcast's receiver). The other ranks wait on the c10d store,
|
||||
not in an NCCL collective, whose watchdog kills them after ``dist_timeout_seconds``. The master
|
||||
calls it with the same ``key`` when it is done."""
|
||||
store = dist.distributed_c10d._get_default_store()
|
||||
if get_world().is_master:
|
||||
store.set(key, "done")
|
||||
else:
|
||||
store.wait([key], timedelta(seconds=timeout))
|
||||
|
||||
@@ -10,7 +10,7 @@ import torch.nn as nn
|
||||
|
||||
from prime_rl.configs.shared import WeightBroadcastConfig
|
||||
from prime_rl.orchestrator.clients import AdminPlane
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.world import get_world, wait_for_master
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_broadcast_dir, get_step_path
|
||||
|
||||
@@ -63,6 +63,7 @@ class WeightSender(ABC):
|
||||
(step_dir / SENDER_READY_MARKER).touch()
|
||||
self._wait_for_receiver_ready(step_dir)
|
||||
(step_dir / STARTED_MARKER).touch()
|
||||
wait_for_master(f"weight_broadcast/{step}", self.timeout)
|
||||
self._broadcast(model, step, step_dir)
|
||||
if self.world.is_master:
|
||||
(step_dir / FINISHED_MARKER).touch()
|
||||
@@ -94,9 +95,8 @@ class WeightSender(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
"""Move v{step}'s weights to the consumer. Rank synchronization is the
|
||||
transport's own job — non-master ranks must be held back until the
|
||||
master finished the handshake (see ``NCCLWeightSender._broadcast``)."""
|
||||
"""Move v{step}'s weights to the consumer. All ranks enter only after
|
||||
the master finished the handshake."""
|
||||
|
||||
def _clean(self, step: int) -> None:
|
||||
"""Remove old broadcast dirs, keeping ``step`` and ``step - 1`` (a
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
@@ -52,7 +51,6 @@ class FileSystemWeightSender(WeightSender):
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
else:
|
||||
dist.barrier()
|
||||
state_dict = gather_weights_parallel(model)
|
||||
state_dict = convert_state_dict_to_hf(model, state_dict)
|
||||
self.logger.debug(f"Saving weights to {step_dir}")
|
||||
|
||||
@@ -3,7 +3,6 @@ from pathlib import Path
|
||||
from typing import Callable, Generator
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.distributed.tensor import DTensor
|
||||
@@ -189,13 +188,6 @@ class NCCLWeightSender(WeightSender):
|
||||
|
||||
@torch.no_grad()
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
# The master enters only after the receiver acknowledged the handshake,
|
||||
# but all ranks must be held back until then: the broadcast preparation
|
||||
# (DTensor resolution, checkpoint conversion) enqueues collectives on non-master
|
||||
# ranks, and if those start before the receiver has paused inference,
|
||||
# the collectives sit unmatched until NCCL's watchdog kills the process.
|
||||
if self.world.world_size > 1:
|
||||
dist.barrier()
|
||||
self.nccl_broadcast_sender.send(model)
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ from prime_rl.configs.shared import NIXLWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.clients import init_nixl_broadcast
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.world import wait_for_master
|
||||
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
|
||||
from prime_rl.transports.weights.nixl.agent import (
|
||||
NixlAgent,
|
||||
@@ -394,6 +395,8 @@ class NIXLWeightSender(WeightSender):
|
||||
inference_metadata = None
|
||||
|
||||
if startup:
|
||||
# The master's ModelExpress discovery can outlast the NCCL timeout; hold the others on the store.
|
||||
wait_for_master(f"weight_broadcast/nixl_discovery/{step}", self.config.timeout)
|
||||
objects = [inference_metadata]
|
||||
dist.broadcast_object_list(objects, src=0)
|
||||
if self.is_serving_rank:
|
||||
@@ -442,6 +445,7 @@ class NIXLWeightSender(WeightSender):
|
||||
policy_notification(step, "complete"),
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
wait_for_master(f"weight_broadcast/nixl_complete/{step}", self.config.timeout)
|
||||
dist.barrier()
|
||||
self.broadcast_count += 1
|
||||
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
|
||||
|
||||
@@ -324,7 +324,4 @@ def maybe_activation_offloading(config: ActivationOffloadingConfig | None) -> Of
|
||||
if config is None:
|
||||
return nullcontext()
|
||||
|
||||
return OffloadActivations(
|
||||
use_pin_memory=config.pin_memory,
|
||||
max_fwd_stash_size=config.max_inflight_activations,
|
||||
)
|
||||
return OffloadActivations(max_fwd_stash_size=config.max_inflight_activations)
|
||||
|
||||
@@ -28,6 +28,11 @@ DEFAULT_COMMON_ENV_VARS: dict[str, str] = {
|
||||
|
||||
DEFAULT_TRAINER_ENV_VARS: dict[str, str] = {
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
||||
# NCCL flight recorder: on a collective timeout every rank dumps its last 2000 collectives
|
||||
# to /tmp/nccl_trace_<uid>_rank_<rank> (read with `torchfrtrace`), showing which rank hung where.
|
||||
"TORCH_FR_BUFFER_SIZE": "2000",
|
||||
"TORCH_NCCL_DUMP_ON_TIMEOUT": "1",
|
||||
"TORCH_FR_DUMP_TEMP_FILE": f"/tmp/nccl_trace_{os.getuid()}_rank_",
|
||||
}
|
||||
|
||||
DEFAULT_INFERENCE_ENV_VARS: dict[str, str] = {
|
||||
|
||||
@@ -325,13 +325,15 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
|
||||
meta_model = DeepseekV4ForCausalLM(MODEL_CONFIG)
|
||||
expected = tables[0]
|
||||
|
||||
def fake_dcp_load(state_dict, storage_reader=None):
|
||||
def fake_dcp_load(state_dict, storage_reader=None, process_group=None):
|
||||
buffer = state_dict["model.layers.0.mlp.router.tid2eid"]
|
||||
buffer.copy_(expected.to(device=buffer.device))
|
||||
|
||||
monkeypatch.setattr("prime_rl.trainer.model.dcp_load", fake_dcp_load)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.load_state_dict_keys", lambda path: meta_model.state_dict().keys())
|
||||
monkeypatch.setattr("torch.distributed.barrier", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.wait_for_master", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.get_dcp_group", lambda: None)
|
||||
|
||||
load_dcp_from_hf(meta_model, ModelConfig(name=str(tmp_path)), parallel_dims=MagicMock())
|
||||
|
||||
|
||||
@@ -35,13 +35,15 @@ def test_load_dcp_from_hf_keeps_checkpoint_selection_bias(model, tmp_path, monke
|
||||
"""Checkpoint values for the persistent selection bias must survive loading."""
|
||||
expected = torch.tensor([0.1, 0.2, 0.3, 0.4])
|
||||
|
||||
def fake_dcp_load(state_dict, storage_reader=None):
|
||||
def fake_dcp_load(state_dict, storage_reader=None, process_group=None):
|
||||
buffer = state_dict["model.layers.1.mlp.router.selection_bias"]
|
||||
buffer.copy_(expected.to(device=buffer.device, dtype=buffer.dtype))
|
||||
|
||||
monkeypatch.setattr("prime_rl.trainer.model.dcp_load", fake_dcp_load)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.load_state_dict_keys", lambda path: model.state_dict().keys())
|
||||
monkeypatch.setattr("torch.distributed.barrier", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.wait_for_master", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.get_dcp_group", lambda: None)
|
||||
|
||||
load_dcp_from_hf(model, ModelConfig(name=str(tmp_path)), parallel_dims=MagicMock())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user