Compare commits

...
Author SHA1 Message Date
9f4eef81a3 perf(optim): reuse pinned CPU buffers in CPUOffloadOptimizer (#3552)
Allocate `CPUOffloadOptimizer`'s CPU-side buffers once, pinned, and copy
optimizer state into them non-blocking, instead of allocating a fresh
pageable buffer plus a fresh pinned buffer on every step.

- The old path copied each state tensor into fresh pageable memory
blocking, then `.pin_memory()` allocated a second buffer and copied
again host to host. `Tensor.to` cannot allocate pinned memory, and
`non_blocking` was set to `not self.pin_memory`, which disabled the
async path in the one case where a pinned destination would have made it
work.
- Buffers are keyed by `(parameter, state key)` and reallocated if a
state tensor's shape or dtype changes, which covers `load_state_dict`.
- One `torch.cuda.synchronize()` now ends the offload, replacing the
per-tensor stall. The `pin_memory=False` path and the host-to-device
direction are unchanged, the latter deliberately: those tensors must be
freshly allocated for the GPU memory to be released between steps.
- The first commit adds the tests with the buffer-reuse one marked
`xfail`, since the three correctness tests pass on the old code and only
that one exposes the bug. The second commit drops the `xfail`.
- Measured on DS V4-Flash SFT, one node of 8x H200 at 6 layers,
`seq_len` 131072, `cp=8`, `ep=8`, micro-batch 1, 10 steps, steady-state
medians, with the fix as the only change from production defaults:
optimizer 26.9 s to 3.0 s and whole step 30.9 s to 6.5 s, at an
unchanged 103.8 GiB peak. Trace of the old 26.7 s window: 18.2 s
pageable D2H at 2.2 GB/s, 5.4 s `pin_memory` re-copy, 1.5 s pinned H2D,
and 0.15 s of AdamW kernels. Per-rank optimizer state is what sizes this
window, and the 6-layer proxy carries 4.93e9 parameters per rank against
production's 4.44e9, so it is not a scaled-down number.

Verified on an H200: 3 passed / 1 xfailed at the test commit, 4 passed
at the fix commit, with `tests/unit/train/test_cpu_adam.py` and
`tests/unit/test_configs.py -k offload` still green.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 16:02:32 -07:00
1d9ab255eb fix(docker): drop removed gpt-oss extra from uv sync (#3549)
#3424 removed the gpt-oss optional-dependency group from pyproject.toml,
but Dockerfile.cuda still passed --extra gpt-oss to uv sync, which fails
on undefined extras and broke every image build since.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile alignment with pyproject extras; no application
or dependency logic changes beyond fixing the sync command.
> 
> **Overview**
> Repairs **CUDA Docker image builds** that broke after the `gpt-oss`
optional extra was removed from `pyproject.toml` (#3424).
> 
> Both `uv sync` steps in `Dockerfile.cuda` (the cached third-party
layer and the full workspace sync after sources are copied) no longer
pass `--extra gpt-oss`. **`uv` was failing** on an undefined extra; the
remaining extras (`gpu`, flash-attn variants, `disagg`, `quack`,
`kernels`, `mamba-ssm`, etc.) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b340617baed2ffb69a2a1adc800e9264f4c32ba2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:03:42 -07:00
samsjaandGitHub eff12f2483 chore: glm-4.5-air swe example to muon + 2 trainer / 4 inference nodes (#3546)
## Summary

Updates the GLM-4.5-Air `scaleswe` advanced example to mirror the
research-prod air ablation base config (research-prod PR #198): 2
trainer nodes with Muon instead of the single-node sign-SGD setup, and 4
one-node inference replicas. Router replay, `max_off_policy_steps`, and
the length-penalty weights stay unchanged.

## Changes

- **Deployment**: `1 train + 3 infer replicas` -> `2 train + 4 infer
replicas` (one-node replicas)
- **Optimizer**: `sign_sgd` -> `muon`; drop the sign-SGD-era
`optim_cpu_offload = false` / `full_offload = true` and `[trainer.ckpt]
skip_optimizer` (optimizer state is checkpointed again, so runs can
resume)
- **Trainer memory**: `fused_lm_head_token_chunk_size` (8192) and
`optim_cpu_offload` (true) use their defaults (per review); keep cp=4
(ulysses) and activation checkpointing + offloading
- **Orchestrator**: unchanged (`batch_size = 256`, `group_size = 16`,
`max_off_policy_steps = 32`, linear length penalty with
`num_output_tokens_weight = 0.0`, input/turns weights 0.1)
- **Router replay**: unchanged, stays enabled
(`trainer.enable_router_replay` +
`inference.vllm.enable_return_routed_experts`)
- **Inference**: added `enable_expert_parallel = true` and
`gpu_memory_utilization = 0.85` (TP=8 + EP)

## Validation

- `uv run rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example TOML only; no application code, auth, or data-path changes.
> 
> **Overview**
> Updates **`examples/advanced/glm-4.5-air/swe.toml`** to match the
research-prod air ablation base (research-prod PR #198) instead of the
old single-node sign-SGD layout.
> 
> **Deployment** scales to **2 trainer nodes** and **4 inference
replicas** (was 1 train / 3 infer). **Training** switches the optimizer
from **`sign_sgd` to `muon`**, drops sign-SGD-only trainer settings
(`full_offload`, explicit LM-head chunk size, **`skip_optimizer`**
checkpointing), so **optimizer state is saved again** and jobs can
resume. Comments now describe Muon + two-node training and default
LM-head chunking / CPU optimizer offload.
> 
> **Inference** adds **`enable_expert_parallel = true`** and
**`gpu_memory_utilization = 0.85`** alongside existing TP=8 and router
replay. GRPO batch/group sizes, length-penalty weights, and router
replay behavior are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91c71d25ac6b277aa1ddd5631384e40fb080f53f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-14 17:18:28 -07:00
e0886c152d chore(trainer): unify context-parallel setup across models (#3533)
Unifies all context parallel setup so that a single frozen `CPContext`
dataclass is shared by all cp-aware modules, stored under a
`self.cp_contex: CPContext` attr.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 14:03:40 -04:00
9ef21a64f1 docs(examples): restore launch READMEs, add vlm section, slim advanced examples (#3537)
## What

Related changes to `examples/` and `configs/`:

### 1. Launch walkthroughs for the advanced examples

`#3085` restructured `examples/` into `basic/` + `advanced/` and dropped
the per-example READMEs — the step-by-step launch guides. Since then the
advanced folders had no how-to-start documentation. This PR restores
them, rewritten against current usage (not copied from history):

- **`examples/advanced/glm-4.5-air/README.md`** — config-by-config table
(train/eval sources, node topology), sandbox setup (Prime Intellect
Sandboxes by default, swap `env.agent.runtime` for your own),
`SERPER_API_KEY` forwarding, launch via `uv run rl @ ...` with built-in
sbatch submission, `uv run dashboard` how-to, resume/export.
- **`examples/advanced/glm-5.2/README.md`** — 32-node RL configs, the
llm-d + Mooncake variant, the `infer/` pre-flights; documents that
`swe.toml` declares **no train source** and must be composed with a
source overlay.
- **`examples/advanced/qwen3-30b-a3b/README.md`** — same format: math
(subprocess runtime, no sandbox), SWE (sandbox), tool use (Modal
runtime, `modal setup`).

Why rewritten and not resurrected: `scripts/tmux.sh` was removed
(`#3351`, replaced by `uv run dashboard`), the `.env` auto-sourcing is
gone, `--wandb.*` became `--monitors.wandb.*`, and HF weight upload was
replaced by DCP checkpoints + `tools/convert_dcp_to_bf16.py`. Every
claim was checked against the configs on `main` and `docs/training.md` /
`docs/scaling.md`.

### 2. Refined `examples/README.md`

Proper `basic/`, `extra/`, and `advanced/` sections with per-example
one-liners (domains, node counts, context length), a where-to-start
pointer (reverse-text first), and a related-configs section.

### 3. `extra/` section

`dynamo/` (external Dynamo inference + NCCL weight updates) and the VLM
SFT configs (moved from the `examples/` root, `vlm_sft`/`vlm_sft_moe`)
now live in **`examples/extra/`** — material that doesn't follow the
basic eval → SFT → RL walk-through pattern. `basic/` keeps only the
core-environment walk-throughs.

### 4. Config-only folders move to `configs/`

- `minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`:
`examples/advanced/` → **`configs/advanced/`** — frontier configs
without tutorials are configs, not examples.
- `examples/evals/` → **`configs/evals/`** — standalone evals (`uv run
evals @ configs/evals/swe.toml`) are configs too; the reference in
`skills/training/start-run/SKILL.md` is updated.

All other references updated: root `README.md` (advanced list:
Qwen3-30B-A3B, GLM-4.5-Air, GLM-5), `examples/README.md`,
`configs/README.md`, `docs/configuration.md`, `docs/scaling.md`. Moves
are pure `git mv`; no config content changed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and config path reorganization only; VLM loss-mask TOML
changes are equivalent defaults with clearer comments.
> 
> **Overview**
> Restores **step-by-step launch READMEs** for
`examples/advanced/glm-4.5-air`, `glm-5.2`, and `qwen3-30b-a3b` (SLURM
launch, sandboxes/Modal, dashboard, resume/export), and **reorganizes**
`examples/README.md` into `basic/`, `advanced/`, and new **`extra/`**
(`dynamo/`, `vlm/`).
> 
> Frontier configs **without** walkthroughs move from
`examples/advanced/` to **`configs/advanced/`** (`minimax-m2.5`,
`nemotron-3-super`, `deepseek-v4-flash`); standalone evals move to
**`configs/evals/`** (e.g. `swe.toml` path in comments and docs).
Cross-links update in the root README, `configs/README.md`,
`docs/configuration.md`, and `docs/scaling.md` (Nemotron/MiniMax now
point at `configs/advanced/`; advanced list trimmed/relabelled for
GLM-5).
> 
> Adds **`examples/extra/vlm/README.md`** and tightens VLM SFT TOMLs
with explicit `[data.loss_mask] assistant = true` (replacing the full
mask table in the MoE config). **`dynamo`** launch path updates to
`examples/extra/dynamo/rl.toml`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ed086f6797af9755e61acce6b672df50387f3b6d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: samsja <samsja@users.noreply.github.com>
2026-09-12 19:35:47 -07:00
42 changed files with 673 additions and 337 deletions
+1
View File
@@ -5,6 +5,7 @@
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
- **Zen of Python**: remember the Zen of Python when writing code.
```
Beautiful is better than ugly.
+2 -2
View File
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# mount here: .git would bust the cache every commit.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,7 +132,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
+1 -4
View File
@@ -204,10 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
3. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training with P/D disaggregation, the `llm-d` router, and FP8.
## Docs
+5
View File
@@ -6,6 +6,11 @@ Configurations for running prime-rl.
environments, sized to run on a single dev machine. Each mirrors the matching
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
vLLM serving pre-flight). For the tutorialized equivalents, see
[`examples/advanced/`](../examples/advanced).
- **`evals/`** — standalone eval configs, run with `uv run evals @ configs/evals/swe.toml`.
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
@@ -2,7 +2,7 @@
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ examples/evals/swe.toml
# uv run evals @ configs/evals/swe.toml
#
# The tasksets run in prime sandboxes (the default runtime), so the key also
# authenticates sandbox creation. External API endpoints expose no vLLM
+2 -2
View File
@@ -226,8 +226,8 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
+1 -1
View File
@@ -148,5 +148,5 @@ VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementatio
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
+1 -1
View File
@@ -232,7 +232,7 @@ gpus_per_node = 8
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
+34 -13
View File
@@ -2,17 +2,38 @@
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
optional SFT warmup → RL → eval), each with its own README:
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
- `alphabet-sort` — multi-turn, user simulator, LoRA
- `wiki-search` — multi-turn tool calling, LoRA
- `wordle` — multi-turn (~6-turn games)
- `hendrycks-sanity` — single-turn math, long-running
- `dynamo` — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
## advanced/ — frontier models, multi-node
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
- [`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.2/`](advanced/glm-5.2/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.
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.
## basic/ — 1 to 8 GPUs
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B)
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
## extra/ — beyond the core loop
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
## Related config folders
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
- Standalone eval configs live in [`configs/evals/`](../configs/evals).
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
+100
View File
@@ -0,0 +1,100 @@
# GLM-4.5-Air
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0).
| Config | Trains on | Evals on | Topology |
|---|---|---|---|
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe
```
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run (`<run_name>` from the launch) and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint, resume, export
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe \
--resume --max-steps 1000
```
Trainer checkpoints are DCP-sharded; export HF-format weights with:
```bash
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
```
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
+17 -20
View File
@@ -1,17 +1,18 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# 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.
# runtime; eval on SWE-Bench Verified. Follows the research-prod air ablation base config
# (research-prod PR #198): 2 trainer nodes with the Muon optimizer (instead of the single-node
# sign-SGD setup), 4 one-node inference replicas serving the bf16 checkpoint with TP=8 + expert
# parallelism, batch size 256 / group size 16, and the linear length penalty with the input-token
# and turns coefficients set to 0.1. Router replay stays enabled (trainer.enable_router_replay replays 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. Optimizer state is checkpointed so runs can resume.
#
# 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.
# GRPO uses the linear length penalty. Each term is pass_rate-scaled and normalized by the
# group's own max before the GRPO baseline subtraction.
#
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing.
# Two trainer nodes fit GLM-4.5-Air with Muon plus the memory improvements from the GLM-5.1 prod
# run (research-prod rlm5/prod.toml): activation checkpointing (freq=1) + activation offloading
# (max_inflight=1). LM-head token chunking (8192) and optimizer CPU offload run at their defaults.
# Concurrency is fully default: the controller derives its start from the measured KV budget and
# adapts from there.
@@ -31,9 +32,9 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
[deployment]
type = "multi_node"
num_train_nodes = 1
num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 3
num_infer_replicas = 4
[monitors.wandb]
project = "swe-ablations"
@@ -63,9 +64,6 @@ impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
@@ -74,11 +72,8 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
type = "muon"
# --- Orchestrator ---
@@ -128,6 +123,8 @@ VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
gpu_memory_utilization = 0.85
max_model_len = 131072
tensor_parallel_size = 8
enable_expert_parallel = true
enable_return_routed_experts = true
+102
View File
@@ -0,0 +1,102 @@
# GLM-5 family at scale
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
| Config | What it runs | Topology |
|---|---|---|
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
## Requirements
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in — it ships with prime-rl's dependencies:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
- `WANDB_API_KEY` — both RL configs log to W&B (`[monitors.wandb]`).
### Install llm-d (llmd variants only)
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
```bash
bash scripts/install_llmd.sh
```
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
# GLM-5.1 RL with llm-d + Mooncake (recommended)
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
# GLM-5 base plane — compose your train source onto it
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.toml
```
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
```bash
uv run inference @ examples/advanced/glm-5.2/infer/pd.toml
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
```
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint and resume
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
+106
View File
@@ -0,0 +1,106 @@
# Qwen3-30B-A3B
RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The Thinking checkpoint trains math and SWE; the tool config trains the Instruct checkpoint with colocated tools on [Modal](https://modal.com). All configs use the custom MoE trainer implementation with expert parallelism (`ep = 8`), the AdamW optimizer, NCCL weight broadcast, and W&B logging. `swe.toml` adds `cp = 2` context parallelism for its 131k context; the other two run at 32k.
| Config | Trains on | Evals on | Runtime | Topology |
|---|---|---|---|---|
| [`math.toml`](math.toml) | `i3_math` | `aime2025` (every 25 steps) | `subprocess` — runs locally, no sandbox | 2 train + 2 infer nodes |
| [`swe.toml`](swe.toml) | `r2e-gym` (`bash` harness) | `swebench-verified` (every 25 steps) | sandbox (Prime Intellect by default) | 2 train + 2 infer nodes |
| [`tool.toml`](tool.toml) | `general-agent` (colocated tools) | — | `modal` | 1 train + 1 infer node |
`tool.toml` is the odd one out: 400 steps, `group_size = 16`, checkpoints every 50 steps with `keep_last = 1`, and inference at `dp = 2` / `tp = 4`. `math.toml` and `swe.toml` run 512-task batches with checkpoints every 100 steps.
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in (it ships with prime-rl's dependencies):
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
- **Modal** (`tool.toml` only) — the tool agents run on Modal (`env.agent.runtime.type = "modal"`). Authenticate once:
```bash
uv run modal setup # or export MODAL_TOKEN_ID / MODAL_TOKEN_SECRET
```
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- None of the configs set a `[slurm] partition` — sbatch picks your cluster default. Override with `--slurm.partition <your-partition>`.
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
--output-dir /shared/outputs/qwen30b \
--run.name qwen30b-math
```
Swap `math.toml` for `swe.toml` or `tool.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs/qwen30b # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint, resume, export
Checkpoints land in `<run_dir>/checkpoints/step_<N>` — every 100 steps for `math.toml`/`swe.toml`, every 50 steps (`keep_last = 1`) for `tool.toml`. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
```bash
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
--output-dir /shared/outputs/qwen30b \
--run.name qwen30b-math \
--resume --max-steps 1000
```
Trainer checkpoints are DCP-sharded; export HF-format weights with:
```bash
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/checkpoints/step_100
```
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
@@ -67,7 +67,7 @@ discovery_url = "http://dynamo.example:9000"
After both endpoint checks pass, run Prime-RL from the repository in a third terminal. With no managed `[inference]` section, Prime-RL assigns GPU 0 to its single trainer process and leaves the external Dynamo worker on GPU 1:
```bash
uv run rl @ examples/basic/dynamo/rl.toml
uv run rl @ examples/extra/dynamo/rl.toml
```
The example stops after five optimizer steps. Outputs are written under `outputs/` unless `output_dir` is overridden.
+22
View File
@@ -0,0 +1,22 @@
# VLM SFT
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
| Config | Model | Hardware |
|---|---|---|
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
## Run it
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
```bash
uv run sft @ examples/extra/vlm/sft.toml
```
Notes:
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
@@ -34,10 +34,7 @@ micro_batch_size = 1 # required for VLM SFT
seq_len = 16384
[data.loss_mask]
system = false
user = false
assistant = true
tool = false
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
[optim]
lr = 1e-5
@@ -29,5 +29,8 @@ batch_size = 1
micro_batch_size = 1
seq_len = 16384
[data.loss_mask]
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
[optim]
lr = 1e-5
+1 -1
View File
@@ -128,7 +128,7 @@ interval = 10 # completed task groups between cursor saves
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `configs/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
+4
View File
@@ -4,6 +4,8 @@ from typing import Literal
from torch import Tensor
from transformers.modeling_utils import PreTrainedModel
from prime_rl.utils.cp import CPContext
CPStyle = Literal["ring", "ulysses"]
ALL_CP_STYLES: frozenset[CPStyle] = frozenset({"ring", "ulysses"})
@@ -25,6 +27,8 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
after loading with meta device.
"""
cp_context: CPContext = CPContext()
@classmethod
def cp_support(cls, config) -> CPSupport:
"""CP styles this architecture supports, given its config.
@@ -136,7 +136,7 @@ from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.utils.cp import gather_for_cp
from prime_rl.utils.cp import CPContext, gather_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
# Guarded because tilelang ships in the linux-gated `gpu` extra, so some installs lack it.
@@ -690,18 +690,7 @@ class DeepseekV4Attention(nn.Module):
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
self.compressor = compressor_class(config) if compressor_class is not None else None
self._cp_group: dist.ProcessGroup | None = None
self._cp_rank: int = 0
self._cp_world_size: int = 1
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
@property
def cp_enabled(self) -> bool:
return self._cp_world_size > 1
self.cp_context = CPContext()
def forward(self, hidden_states: torch.Tensor, packed: PackedContext) -> tuple[torch.Tensor, None]:
"""`packed` carries the document boundaries every pathway below is clipped at."""
@@ -730,13 +719,17 @@ class DeepseekV4Attention(nn.Module):
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
if self.cp_enabled:
kv = gather_for_cp(kv, self._cp_group) # (b, T, 1, d)
if self.cp_context.cp_enabled:
kv = gather_for_cp(kv, self.cp_context.cp_group) # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
compressed = (
self.compressor(
hidden_states, q_residual, packed, cp_group=self._cp_group, cp_world_size=self._cp_world_size
hidden_states,
q_residual,
packed,
cp_group=self.cp_context.cp_group,
cp_world_size=self.cp_context.cp_world_size,
)
if self.compressor is not None
else None
@@ -120,13 +120,17 @@ def eager_attention_forward(
kv = module.kv_norm(module.kv_proj(hidden_states))
kv = kv.view(*kv.shape[:2], 1, module.head_dim)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
if module.cp_enabled:
kv = dsv4_attention.gather_for_cp(kv, module._cp_group)
if module.cp_context.cp_enabled:
kv = dsv4_attention.gather_for_cp(kv, module.cp_context.cp_group)
kv = kv.transpose(1, 2)
compressed = (
module.compressor(
hidden_states, q_residual, packed, cp_group=module._cp_group, cp_world_size=module._cp_world_size
hidden_states,
q_residual,
packed,
cp_group=module.cp_context.cp_group,
cp_world_size=module.cp_context.cp_world_size,
)
if module.compressor is not None
else None
@@ -9,7 +9,6 @@ embedding all the way to `hc_head`, which collapses them back before the final n
from __future__ import annotations
import torch
import torch.distributed as dist
from torch import Tensor, nn
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
@@ -51,12 +50,6 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
self.attn_hc = DeepseekV4HyperConnection(config)
self.ffn_hc = DeepseekV4HyperConnection(config)
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def forward(
self,
hidden_states: torch.Tensor,
@@ -201,13 +194,6 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
self.post_init()
def get_cp_rank_and_world_size(self) -> tuple[int, int]:
if len(self.layers) == 0:
return 0, 1
layer = self.layers[0]
return getattr(layer, "_cp_rank", 0), getattr(layer, "_cp_world_size", 1)
def forward(
self,
input_ids: torch.LongTensor | None = None,
@@ -249,7 +235,7 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
"""
assert (input_ids is None) != (inputs_embeds is None), "pass exactly one of input_ids or inputs_embeds"
cp_rank, cp_world_size = self.get_cp_rank_and_world_size()
cp_rank, cp_world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
assert seq_lens_are_pre_shard == (cp_world_size > 1), (
f"seq_lens_are_pre_shard={seq_lens_are_pre_shard} disagrees with cp_world_size={cp_world_size}"
)
@@ -90,12 +90,6 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
def forward(
self,
@@ -192,13 +186,6 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
self.post_init()
def _context_parallel_state(self) -> tuple[dist.ProcessGroup | None, int, int]:
if len(self.layers) == 0:
return None, 0, 1
layer = self.layers[0]
return getattr(layer, "_cp_group", None), getattr(layer, "_cp_rank", 0), getattr(layer, "_cp_world_size", 1)
def _gather_position_ids_for_cp(
self,
position_ids: torch.LongTensor,
@@ -234,9 +221,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
cp_group, cp_rank, cp_world_size = self._context_parallel_state()
if cp_group is not None and cp_world_size > 1:
position_ids_full = self._gather_position_ids_for_cp(position_ids, cp_group, cp_world_size)
cp_rank, cp_world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
if self.cp_context.cp_enabled:
position_ids_full = self._gather_position_ids_for_cp(position_ids, self.cp_context.cp_group, cp_world_size)
else:
position_ids_full = position_ids
@@ -7,7 +7,7 @@ from torch import nn
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
from prime_rl.utils.cp import gather_for_cp
from prime_rl.utils.cp import CPContext, gather_for_cp
try:
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla
@@ -145,18 +145,7 @@ class GlmMoeDsaAttention(nn.Module):
self.skip_topk = args.skip_topk
self.scaling = self.qk_head_dim ** (-0.5)
self._cp_group: dist.ProcessGroup | None = None
self._cp_rank: int = 0
self._cp_world_size: int = 1
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
@property
def cp_enabled(self) -> bool:
return self._cp_world_size > 1
self.cp_context = CPContext()
def mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
@@ -178,9 +167,10 @@ class GlmMoeDsaAttention(nn.Module):
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
cos_full, sin_full = position_embeddings_full
if self.cp_enabled:
cos_local = cos_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
sin_local = sin_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
if self.cp_context.cp_enabled:
cp_rank = self.cp_context.cp_rank
cos_local = cos_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
sin_local = sin_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
else:
cos_local, sin_local = cos_full, sin_full
@@ -215,9 +205,9 @@ class GlmMoeDsaAttention(nn.Module):
) -> tuple[torch.Tensor, torch.Tensor | None]:
q_latent, k_compressed_normed, k_rope = self.mla_latents(hidden_states)
if self.cp_enabled:
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
k_rope = gather_for_cp(k_rope, self._cp_group)
if self.cp_context.cp_enabled:
k_compressed_normed = gather_for_cp(k_compressed_normed, self.cp_context.cp_group)
k_rope = gather_for_cp(k_rope, self.cp_context.cp_group)
indices = cached_indices
if not self.skip_topk:
@@ -228,9 +218,9 @@ class GlmMoeDsaAttention(nn.Module):
ke=ke,
index_topk=self.args.index_topk,
position_embeddings_full=position_embeddings,
cp_group=self._cp_group,
cp_world_size=self._cp_world_size,
cp_rank=self._cp_rank,
cp_group=self.cp_context.cp_group,
cp_world_size=self.cp_context.cp_world_size,
cp_rank=self.cp_context.cp_rank,
)
sparse_q, sparse_kv, w_v = self.mla_up_proj(
@@ -2,7 +2,7 @@ import torch
from torch import Tensor, nn
from transformers.modeling_outputs import BaseModelOutput
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.gpt_oss.attention import GptOssAttention
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
@@ -93,10 +93,6 @@ class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
_supports_attention_backend = True
_keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
@classmethod
def cp_support(cls, config) -> CPSupport:
return CPSupport(ALL_CP_STYLES)
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return is_hf_state_dict(state_dict)
+14 -20
View File
@@ -14,6 +14,7 @@ from torch import nn
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
from prime_rl.utils.cp import CPContext
def sequence_to_head_parallel(
@@ -124,15 +125,7 @@ class NemotronHMamba2(nn.Module):
with torch.no_grad():
self.dt_bias.copy_((time_steps + torch.log(-torch.expm1(-time_steps))).to(self.dt_bias.dtype))
def set_context_parallel_attributes(
self,
process_group: dist.ProcessGroup,
rank: int,
world_size: int,
) -> None:
self.process_group = process_group
self.context_parallel_rank = rank
self.context_parallel_world_size = world_size
self.cp_context = CPContext()
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
batch_size, sequence_length, _ = hidden_states.shape
@@ -153,11 +146,12 @@ class NemotronHMamba2(nn.Module):
dt_bias = self.dt_bias
norm_weight = self.norm.weight
if hasattr(self, "process_group"):
world_size = self.context_parallel_world_size
rank = self.context_parallel_rank
gate = sequence_to_head_parallel(gate, self.process_group, world_size)
time_step = sequence_to_head_parallel(time_step, self.process_group, world_size)
if self.cp_context.cp_enabled:
cp_group = self.cp_context.cp_group
world_size = self.cp_context.cp_world_size
rank = self.cp_context.cp_rank
gate = sequence_to_head_parallel(gate, cp_group, world_size)
time_step = sequence_to_head_parallel(time_step, cp_group, world_size)
recurrent_input, state_input, state_output = torch.split(
convolution_input,
@@ -166,9 +160,9 @@ class NemotronHMamba2(nn.Module):
)
convolution_input = torch.cat(
[
sequence_to_head_parallel(recurrent_input, self.process_group, world_size),
sequence_to_head_parallel(state_input, self.process_group, world_size),
sequence_to_head_parallel(state_output, self.process_group, world_size),
sequence_to_head_parallel(recurrent_input, cp_group, world_size),
sequence_to_head_parallel(state_input, cp_group, world_size),
sequence_to_head_parallel(state_output, cp_group, world_size),
],
dim=-1,
)
@@ -238,11 +232,11 @@ class NemotronHMamba2(nn.Module):
).reshape(batch_size, sequence_length, intermediate_size)
hidden_states = self.norm(hidden_states, gate, weight=norm_weight)
if hasattr(self, "process_group"):
if self.cp_context.cp_enabled:
hidden_states = head_to_sequence_parallel(
hidden_states,
self.process_group,
self.context_parallel_world_size,
self.cp_context.cp_group,
self.cp_context.cp_world_size,
)
return self.out_proj(hidden_states)
@@ -1,5 +1,4 @@
import torch
import torch.distributed as dist
from torch import Tensor, nn
from transformers.modeling_outputs import BaseModelOutput
@@ -175,16 +174,6 @@ class NemotronHModel(NemotronHPreTrainedModel):
)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
def set_context_parallel_attributes(
self,
process_group: dist.ProcessGroup,
rank: int,
world_size: int,
) -> None:
for module in self.layers.modules():
if isinstance(module, NemotronHMamba2):
module.set_context_parallel_attributes(process_group, rank, world_size)
def forward(
self,
input_ids: torch.LongTensor,
@@ -219,14 +208,6 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel):
self.model = NemotronHModel(config)
self.lm_head = VanillaOutputLinear(config.hidden_size, config.vocab_size)
def set_context_parallel_attributes(
self,
process_group: dist.ProcessGroup,
rank: int,
world_size: int,
) -> None:
self.model.set_context_parallel_attributes(process_group, rank, world_size)
def forward(
self,
input_ids: torch.LongTensor,
@@ -7,6 +7,7 @@ from fla.ops.gated_delta_rule import chunk_gated_delta_rule
from torch import nn
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from prime_rl.utils.cp import CPContext
# Dynamo lowers all-gather to concatenation, then fails to copy the result into
# FLA's stacked output buffer. Keep CP convolution eager until this is fixed:
@@ -47,12 +48,7 @@ class Qwen3_5GatedDeltaNet(nn.Module):
self.in_proj_z = nn.Linear(config.hidden_size, self.value_dim, bias=False)
self.in_proj_b = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
self.in_proj_a = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
self.context_parallel_group = None
self.context_parallel_world_size = 1
def set_context_parallel_attributes(self, process_group, world_size: int) -> None:
self.context_parallel_group = process_group
self.context_parallel_world_size = world_size
self.cp_context = CPContext()
def forward(
self,
@@ -68,10 +64,10 @@ class Qwen3_5GatedDeltaNet(nn.Module):
decay = -self.A_log.float().exp() * F.softplus(self.in_proj_a(hidden_states).float() + self.dt_bias)
context = None
if self.context_parallel_group is not None:
if self.cp_context.cp_enabled:
context = build_cp_context(
cu_seqlens=cu_seqlens.to(device=hidden_states.device, dtype=torch.int32),
group=self.context_parallel_group,
group=self.cp_context.cp_group,
conv1d_kernel_size=self.conv_kernel_size,
)
@@ -23,7 +23,7 @@ from prime_rl.trainer.models.qwen3_5.rotary_embedding import (
build_qwen3_5_mrope_position_ids,
)
from prime_rl.trainer.models.qwen3_5.vision import Qwen3_5VisionModel
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
from prime_rl.utils.cp import CPContext, setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -163,14 +163,6 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.embed_tokens = embeddings
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
self.context_parallel_group = process_group
self.context_parallel_rank = rank
self.context_parallel_world_size = world_size
for module in self.modules():
if isinstance(module, Qwen3_5GatedDeltaNet):
module.set_context_parallel_attributes(process_group, world_size)
def forward(
self,
input_ids: torch.LongTensor | None = None,
@@ -212,6 +204,7 @@ class Qwen3_5VLMModel(nn.Module):
self.config = config
self.visual = Qwen3_5VisionModel(config.vision_config)
self.language_model = Qwen3_5Model(config.text_config)
self.cp_context = CPContext()
def get_input_embeddings(self) -> nn.Embedding:
return self.language_model.get_input_embeddings()
@@ -219,9 +212,6 @@ class Qwen3_5VLMModel(nn.Module):
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.language_model.set_input_embeddings(embeddings)
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
self.language_model.set_context_parallel_attributes(process_group, rank, world_size)
def prepare_inputs(
self,
input_ids: torch.LongTensor,
@@ -295,11 +285,14 @@ class Qwen3_5VLMModel(nn.Module):
mm_token_type_ids,
seq_lens,
)
process_group = getattr(self.language_model, "context_parallel_group", None)
if image_grid_thw is not None and process_group is not None:
rank = self.language_model.context_parallel_rank
world_size = self.language_model.context_parallel_world_size
setup_cp_attention_params(position_ids, cp_group=process_group, cp_style="ulysses", seq_lens=seq_lens)
if image_grid_thw is not None and self.cp_context.cp_enabled:
rank, world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
setup_cp_attention_params(
position_ids,
cp_group=self.cp_context.cp_group,
cp_style=self.cp_context.cp_style,
seq_lens=seq_lens,
)
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=rank, cp_world_size=world_size)
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=rank, cp_world_size=world_size)
if routed_experts is not None:
@@ -335,9 +328,6 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel):
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.model.set_input_embeddings(embeddings)
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
self.model.set_context_parallel_attributes(process_group, rank, world_size)
def forward(
self,
input_ids: torch.LongTensor | None = None,
+16 -9
View File
@@ -19,6 +19,18 @@ class CPUOffloadOptimizer(OffloadOptimizer):
self.optimizer = optimizer
self.pin_memory = pin_memory
self._initialized = False
self._cpu_buffers: dict[tuple[torch.Tensor, str], torch.Tensor] = {}
def _offload_to_cpu(self, param: torch.Tensor, key: str, src: torch.Tensor) -> torch.Tensor:
if not self.pin_memory:
return src.to("cpu", non_blocking=True)
buffer = self._cpu_buffers.get((param, key))
if buffer is None or buffer.shape != src.shape or buffer.dtype != src.dtype:
buffer = torch.empty(src.shape, dtype=src.dtype, device="cpu", pin_memory=True)
self._cpu_buffers[(param, key)] = buffer
if buffer is not src:
buffer.copy_(src, non_blocking=True)
return buffer
def _move_states(self, device: str):
"""Move optimizer states to CPU or back to GPU (matching each parameter's device)."""
@@ -28,10 +40,7 @@ class CPUOffloadOptimizer(OffloadOptimizer):
if isinstance(value, DTensor):
local_tensor = value._local_tensor
if device == "cpu":
non_blocking = not self.pin_memory
new_local = local_tensor.to("cpu", non_blocking=non_blocking)
if self.pin_memory and not new_local.is_pinned():
new_local = new_local.pin_memory()
new_local = self._offload_to_cpu(param, key, local_tensor)
else:
new_local = local_tensor.to(device, non_blocking=True)
new_dtensor = copy.copy(value)
@@ -39,13 +48,11 @@ class CPUOffloadOptimizer(OffloadOptimizer):
state[key] = new_dtensor
elif isinstance(value, torch.Tensor):
if device == "cpu":
non_blocking = not self.pin_memory
cpu_tensor = value.to("cpu", non_blocking=non_blocking)
if self.pin_memory and not cpu_tensor.is_pinned():
cpu_tensor = cpu_tensor.pin_memory()
state[key] = cpu_tensor
state[key] = self._offload_to_cpu(param, key, value)
else:
state[key] = value.to(device, non_blocking=True)
if device == "cpu" and torch.cuda.is_initialized():
torch.cuda.synchronize()
def step(self, closure=None):
# First step initializes states on GPU - offload after
+2 -23
View File
@@ -8,7 +8,6 @@ from datetime import timedelta
# Import environment before any other imports
# ruff: noqa: I001
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
from prime_rl.utils.act_offloading import maybe_activation_offloading
import torch
@@ -22,6 +21,7 @@ from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.utils.cp import (
gather_for_cp,
gather_for_cp_wo_grad,
setup_context_parallel,
setup_cp_params,
shard_for_cp,
)
@@ -69,7 +69,6 @@ from prime_rl import monitors
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
from ring_flash_attn import substitute_hf_flash_attn
@clean_exit
@@ -192,27 +191,7 @@ def train(config: TrainerConfig):
logger.debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
if parallel_dims.cp_enabled:
cp_group = parallel_dims.world_mesh["cp"].get_group()
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
if config.model.cp_style == "ring":
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
else:
from prime_rl.trainer.models.layers.ulysses_attn import (
substitute_hf_ulysses_attn,
substitute_ulysses_attn,
)
substitute_hf_ulysses_attn(cp_group)
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
# sparse MLA is softmax (works with both ring and ulysses).
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Linear-attn / Mamba layers are only configured under ulysses; models that have them
# declare ulysses-only in `cp_support`, so `get_model` already rejected ring.
if config.model.cp_style == "ulysses":
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_context_parallel(model, config.model, parallel_dims)
# Fresh adapter init after FSDP materialization (the pretrained checkpoint
# carries no adapter weights); a checkpoint resume below overwrites it.
+2 -27
View File
@@ -7,13 +7,11 @@ from contextlib import nullcontext
from datetime import timedelta
from renderers.base import create_renderer
from ring_flash_attn import substitute_hf_flash_attn
from torch.nn import CrossEntropyLoss
# Import environment before any other imports
# ruff: noqa: I001
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.utils.act_offloading import maybe_activation_offloading
import torch
from torch.profiler import profile, ProfilerActivity, record_function
@@ -22,7 +20,7 @@ from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
from prime_rl.utils.cp import setup_context_parallel, setup_cp_params, shard_for_cp
from prime_rl.trainer.lora import get_lora_state
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.logger import format_time, setup_logger
@@ -35,7 +33,6 @@ from prime_rl.trainer.model import (
is_tt_moe_model,
setup_processor,
setup_tokenizer,
resolve_auto_attn,
setup_model,
)
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
@@ -124,25 +121,8 @@ def train(config: SFTConfig):
)
grad_accum_steps = total_micro_batches // micro_batches_per_step
# Resolve attn='auto' before CP setup so ring/ulysses patches use the correct kernel
resolve_auto_attn(config.model)
if parallel_dims.cp_enabled:
assert config.data.seq_len % parallel_dims.cp == 0, "Sequence length must be divisible by CP degree"
cp_group = parallel_dims.world_mesh["cp"].get_group()
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
if config.model.cp_style == "ring":
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
else:
from prime_rl.trainer.models.layers.ulysses_attn import (
substitute_hf_ulysses_attn,
substitute_ulysses_attn,
)
substitute_hf_ulysses_attn(cp_group)
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
# Set up checkpoint manager
logger.info(f"Initializing checkpoint manager ({config.ckpt})")
@@ -163,12 +143,7 @@ def train(config: SFTConfig):
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
if parallel_dims.cp_enabled:
# sparse MLA is softmax (works with both ring and ulysses).
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Linear-attn / Mamba layers are only configured under ulysses; models that have them
# declare ulysses-only in `cp_support`, so `get_model` already rejected ring.
if config.model.cp_style == "ulysses":
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_context_parallel(model, config.model, parallel_dims)
if config.model.lora is not None:
get_lora_state().reset_adapter_parameters()
+42 -51
View File
@@ -3,80 +3,71 @@ from __future__ import annotations
# ruff: noqa: I001 — `prime_rl._compat` must run before `ring_flash_attn` imports below.
import prime_rl._compat # noqa: F401
from dataclasses import dataclass
from typing import TYPE_CHECKING
import torch
import torch.distributed as dist
import torch.nn as nn
from ring_flash_attn import update_ring_flash_attn_params
from ring_flash_attn import substitute_hf_flash_attn, update_ring_flash_attn_params
from prime_rl.trainer.distributed.collectives import all_gather
from prime_rl.utils.logger import get_logger
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
if TYPE_CHECKING:
# `prime_rl.trainer.models` imports this module, so importing the model base eagerly would
# cycle. `from __future__ import annotations` keeps CPStyle out of the runtime path.
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.models.base import CPStyle
from prime_rl.trainer.parallel_dims import ParallelDims
def _has_linear_attn_layer(model: nn.Module) -> bool:
"""True if the model contains any non-softmax (linear/SSM) attention layer."""
inner = getattr(model, "model", model)
if hasattr(inner, "language_model"):
inner = inner.language_model
layers = getattr(inner, "layers", None)
if layers is None:
return False
layer_modules = layers.modules() if isinstance(layers, nn.Module) else layers
for layer in layer_modules:
# Qwen3.5 hybrid DeltaNet
if getattr(layer, "layer_type", None) == "linear_attention":
return True
# NemotronH Mamba
if hasattr(layer, "mamba"):
return True
return False
@dataclass(frozen=True)
class CPContext:
"""Context-parallel topology, shared by every module that consumes it."""
cp_group: dist.ProcessGroup | None = None
cp_rank: int = 0
cp_world_size: int = 1
cp_style: CPStyle | None = None
@property
def cp_enabled(self) -> bool:
return self.cp_world_size > 1
def setup_model_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Hand the CP topology to models whose layers need it (DeltaNet, Mamba).
def setup_context_parallel(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims) -> None:
cp_group = parallel_dims.world_mesh["cp"].get_group()
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
Such models expose ``set_context_parallel_attributes`` at the top level and
own their layer wiring; softmax-only models don't and need nothing.
"""
if hasattr(model, "set_context_parallel_attributes"):
model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
from prime_rl.utils.logger import get_logger
if config.cp_style == "ring":
# Delayed imports: both modules live under trainer.models, which imports back into
# prime_rl.utils — a top-level import would deadlock at startup.
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
get_logger().info("Configured model CP attributes")
elif _has_linear_attn_layer(model):
raise ValueError(
"Model has linear-attention/Mamba layers but does not implement "
"set_context_parallel_attributes; CP would silently misconfigure them"
)
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.attn)
elif config.cp_style == "ulysses":
from prime_rl.trainer.models.layers.ulysses_attn import substitute_hf_ulysses_attn, substitute_ulysses_attn
substitute_hf_ulysses_attn(cp_group)
substitute_ulysses_attn(cp_group, attn_impl=config.attn)
else:
raise ValueError(f"Unknown cp_style: {config.cp_style}")
def setup_sparse_mla_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Configure GLM-5 sparse MLA modules for context-parallel gather/scatter."""
count = 0
if not hasattr(model, "model"):
return
if not hasattr(model.model, "layers"):
return
for layer in model.model.layers:
if not hasattr(layer, "set_context_parallel_attributes"):
cp_context = CPContext(cp_group, cp_rank, parallel_dims.cp, config.cp_style)
for module in model.modules():
if not hasattr(module, "cp_context"):
continue
if not isinstance(module.cp_context, CPContext):
raise TypeError(
f"{type(module).__name__}.cp_context is {type(module.cp_context).__name__}, not a CPContext; "
"context-parallel setup claims that attribute name, so rename it"
)
module.cp_context = cp_context
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
count += 1
if count > 0:
from prime_rl.utils.logger import get_logger
get_logger().info(f"Configured sparse MLA CP on {count} DSA layers")
get_logger().info(f"Configured {config.cp_style} context parallelism (cp={parallel_dims.cp})")
def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int, seq_dim: int = 1) -> torch.Tensor:
+20 -27
View File
@@ -17,7 +17,7 @@ from prime_rl.trainer.models.qwen3_5 import (
Qwen3_5VisionConfig,
)
from prime_rl.trainer.models.qwen3_5.attention import Qwen3_5Attention
from prime_rl.utils.cp import setup_model_cp
from prime_rl.utils.cp import CPContext
def get_text_config(config_cls=Qwen3_5TextConfig) -> Qwen3_5TextConfig:
@@ -90,36 +90,29 @@ def test_context_parallel_setup_chain_text_and_vlm(text_config):
text_model = get_model(text_config, device="meta")
linear_layer = text_model.model.layers[0]
text_model.model.layers[0] = torch.nn.Sequential(linear_layer)
setup_model_cp(text_model, cp_group, cp_rank=1, cp_world_size=2)
assert text_model.model.context_parallel_group is cp_group
assert text_model.model.context_parallel_rank == 1
assert text_model.model.context_parallel_world_size == 2
assert linear_layer.linear_attn.context_parallel_group is cp_group
assert linear_layer.linear_attn.context_parallel_world_size == 2
text_cp_context = CPContext(cp_group, 1, 2, "ulysses")
for module in text_model.modules():
if hasattr(module, "cp_context"):
module.cp_context = text_cp_context
assert text_model.model.cp_context is text_cp_context
assert text_model.model.cp_context.cp_rank == 1
assert text_model.model.cp_context.cp_world_size == 2
assert text_model.model.cp_context.cp_style == "ulysses"
assert linear_layer.linear_attn.cp_context is text_cp_context
vlm_model = get_model(get_vlm_config(text_config), device="meta")
setup_model_cp(vlm_model, cp_group, cp_rank=0, cp_world_size=2)
assert vlm_model.model.language_model.context_parallel_group is cp_group
assert vlm_model.model.language_model.layers[0].linear_attn.context_parallel_world_size == 2
vlm_cp_context = CPContext(cp_group, 0, 2, "ulysses")
for module in vlm_model.modules():
if hasattr(module, "cp_context"):
module.cp_context = vlm_cp_context
def test_setup_model_cp_requires_hook_only_for_hybrid_models():
class HybridLayer(torch.nn.Module):
layer_type = "linear_attention"
class Inner:
layers = torch.nn.Sequential(torch.nn.Sequential(HybridLayer()))
class HybridNoHookModel:
model = Inner()
with pytest.raises(ValueError, match="set_context_parallel_attributes"):
setup_model_cp(HybridNoHookModel(), MagicMock(), cp_rank=0, cp_world_size=2)
class SoftmaxOnlyModel:
pass
setup_model_cp(SoftmaxOnlyModel(), MagicMock(), cp_rank=0, cp_world_size=2)
assert vlm_model.model.cp_context is vlm_cp_context
assert vlm_model.model.language_model.cp_context is vlm_cp_context
assert vlm_model.model.language_model.cp_context.cp_style == "ulysses"
assert vlm_model.model.language_model.layers[0].linear_attn.cp_context is vlm_cp_context
def test_ring_patches_flash_attention():
@@ -14,6 +14,7 @@ from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, P
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
from prime_rl.utils.cp import CPContext
from prime_rl.utils.utils import default_dtype
try:
@@ -1244,7 +1245,7 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
for cp_rank, chunk in enumerate(chunks):
gather, pending = _fake_gather_for_cp(projections, chunks, cp_rank)
monkeypatch.setattr(dsv4_attention, "gather_for_cp", gather)
module.set_context_parallel_attributes(MagicMock(), cp_rank, cp_world_size)
module.cp_context = CPContext(MagicMock(), cp_rank, cp_world_size, "ring")
packed = _packed_context(doc_lens, torch.float32, V4FLASH_CONFIG, cp_rank=cp_rank, cp_world_size=cp_world_size)
out_rank, _ = module(chunk, packed=packed)
+9 -5
View File
@@ -6,7 +6,7 @@ import torch
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
from prime_rl.utils.cp import setup_model_cp
from prime_rl.utils.cp import CPContext
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
@@ -114,11 +114,15 @@ def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
model.model.layers[0] = torch.nn.Sequential(mamba_layer)
cp_group = MagicMock()
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
assert mamba_layer.mamba.process_group is cp_group
assert mamba_layer.mamba.context_parallel_rank == 1
assert mamba_layer.mamba.context_parallel_world_size == 2
cp_context = CPContext(cp_group, 1, 2, "ulysses")
for module in model.modules():
if hasattr(module, "cp_context"):
module.cp_context = cp_context
assert mamba_layer.mamba.cp_context is cp_context
assert mamba_layer.mamba.cp_context.cp_rank == 1
assert mamba_layer.mamba.cp_context.cp_world_size == 2
def test_nemotron_h_no_latent_projection():
+114
View File
@@ -0,0 +1,114 @@
from typing import NamedTuple
import pytest
import torch
from torch.optim import Optimizer
from prime_rl.trainer.optim.state_offload import CPUOffloadOptimizer
pytestmark = [pytest.mark.gpu]
class TrainedPair(NamedTuple):
reference_model: torch.nn.Module
reference_optimizer: Optimizer
offloaded_model: torch.nn.Module
offloaded_optimizer: CPUOffloadOptimizer
def make_model(seed: int) -> torch.nn.Sequential:
torch.manual_seed(seed)
model = torch.nn.Sequential(torch.nn.Linear(64, 128), torch.nn.GELU(), torch.nn.Linear(128, 32))
return model.cuda()
def run_steps(model: torch.nn.Module, optimizer: Optimizer, num_steps: int, seed: int) -> None:
torch.manual_seed(seed)
for _ in range(num_steps):
batch = torch.randn(16, 64, device="cuda")
loss = model(batch).square().mean()
loss.backward()
optimizer.step()
optimizer.zero_grad()
def assert_params_equal(reference_model: torch.nn.Module, model: torch.nn.Module) -> None:
for (name, reference_param), (_, param) in zip(reference_model.named_parameters(), model.named_parameters()):
assert torch.equal(reference_param, param), f"param mismatch: {name}"
def assert_states_offloaded(optimizer: CPUOffloadOptimizer) -> None:
for param in optimizer.state:
for key, value in optimizer.state[param].items():
assert value.device.type == "cpu", f"state '{key}' on {value.device}, expected cpu"
assert value.is_pinned(), f"state '{key}' not pinned"
def assert_state_dicts_equal(saved: dict, restored: dict) -> None:
assert saved["param_groups"] == restored["param_groups"]
assert saved["state"].keys() == restored["state"].keys()
for index in saved["state"]:
assert saved["state"][index].keys() == restored["state"][index].keys()
for key, saved_value in saved["state"][index].items():
restored_value = restored["state"][index][key]
if isinstance(saved_value, torch.Tensor):
assert torch.equal(saved_value.cpu(), restored_value.cpu()), f"state[{index}]['{key}'] mismatch"
else:
assert saved_value == restored_value, f"state[{index}]['{key}'] mismatch"
def state_data_ptrs(optimizer: CPUOffloadOptimizer) -> dict[tuple[int, str], int]:
return {
(id(param), key): value.data_ptr() for param in optimizer.state for key, value in optimizer.state[param].items()
}
@pytest.fixture
def trained_pair() -> TrainedPair:
reference_model = make_model(0)
reference_optimizer = torch.optim.AdamW(reference_model.parameters(), lr=1e-2)
run_steps(reference_model, reference_optimizer, num_steps=3, seed=1)
offloaded_model = make_model(0)
offloaded_optimizer = CPUOffloadOptimizer(torch.optim.AdamW(offloaded_model.parameters(), lr=1e-2))
run_steps(offloaded_model, offloaded_optimizer, num_steps=3, seed=1)
return TrainedPair(reference_model, reference_optimizer, offloaded_model, offloaded_optimizer)
def test_offloaded_steps_match_plain_adamw(trained_pair: TrainedPair) -> None:
assert_params_equal(trained_pair.reference_model, trained_pair.offloaded_model)
def test_states_are_on_cpu_and_pinned_between_steps(trained_pair: TrainedPair) -> None:
assert_states_offloaded(trained_pair.offloaded_optimizer)
def test_state_dict_round_trip_is_exact_and_training_continues(trained_pair: TrainedPair) -> None:
optimizer = trained_pair.offloaded_optimizer
saved = optimizer.state_dict()
optimizer.load_state_dict(saved)
restored = optimizer.state_dict()
assert_state_dicts_equal(saved, restored)
assert_states_offloaded(optimizer)
run_steps(trained_pair.reference_model, trained_pair.reference_optimizer, num_steps=1, seed=2)
run_steps(trained_pair.offloaded_model, optimizer, num_steps=1, seed=2)
assert_params_equal(trained_pair.reference_model, trained_pair.offloaded_model)
def test_offload_reuses_pinned_buffers_across_steps() -> None:
model = make_model(0)
optimizer = CPUOffloadOptimizer(torch.optim.AdamW(model.parameters(), lr=1e-2))
run_steps(model, optimizer, num_steps=2, seed=1)
pointers_before = state_data_ptrs(optimizer)
run_steps(model, optimizer, num_steps=1, seed=2)
pointers_after = state_data_ptrs(optimizer)
assert pointers_before.keys() == pointers_after.keys()
for key, pointer in pointers_before.items():
assert pointers_after[key] == pointer, f"state buffer reallocated for {key}"