bbbe9cb1bf
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / resolve-release (push) Canceled after 0s
Tag and Release / publish-release (push) Canceled after 0s
fix: release the allocator cache after every checkpoint load (#4053)
## Summary

- Release the CUDA allocator cache once after every checkpoint load:
`gc.collect()` + `torch.cuda.empty_cache()` right after `dcp_load`
returns in `CheckpointManager.load_from_path`.
- Remove the cleanup from `AppState.load_state_dict`. It ran only with
CPU offload, and the new cleanup now covers that path too.

Net diff: one `ckpt.py` change. The cleanup moves from the offload-only
path to every load path (SFT and RL, with and without CPU offload).

## Problem

Without CPU offload (`model.offload = "none"`), a resume peaks at much
more reserved memory than an uninterrupted run at the same step. A
24-node SFT run (192 ranks, 512K sequence length, 267.7 GiB GPUs)
showed:

| Step 901, same batch | Peak reserved |
|---|---|
| Fresh run, 900 steps in | 216.8 GiB |
| Resumed from step 900 | 257.0 GiB (96%) |

The resumed run logged `expandable_segments: memory mapping failed with
OOM` during its first step.

Cause: DCP's `_init_optim_state` builds the optimizer state with a
zero-grad `optimizer.step()`. This allocates a `zeros_like` gradient for
every parameter, so allocated memory peaks about one fp32 parameter
shard above the steady state during the load. When the load ends, those
blocks stay in the allocator cache. The first step does not reuse them
and reserves on top of them. Peak *allocated* memory does not change, so
the extra memory is cache fragmentation, not live tensors. With CPU
offload, the old cleanup in `AppState.load_state_dict` already released
the cache, so only the non-offload path was affected.

## Verification

Single-node runs: Qwen3-30B-A3B SFT on 1 node of H200s (6 trainer GPUs,
2 inference GPUs), online evals on, seq len 8192. A base run trains 1
step and saves a checkpoint. Each variant resumes from that checkpoint
and trains step 2. Each change was toggled with an env var, so all
variants share the same code and checkpoint. Numbers are rank 0, in GiB.

**`offload = "none"`.** Ablation of each candidate change (the first two
were in an earlier version of this PR):

| Step 2 | Reserved after load | Peak allocated | Peak reserved |
|---|---|---|---|
| Fresh run (no resume) | — | 83.7 | 93.6 |
| Resume, `main` | 80.0 | 83.5 | **114.9** (+21.3) |
| Resume, unconditional cleanup in `AppState.load_state_dict` | 60.5 |
83.5 | 95.4 (+1.9) |
| Resume, `empty_cache()` before the SFT startup broadcast | 80.0 | 83.5
| 93.5 |
| Resume, both of the above | 60.5 | 83.5 | 93.5 |
| **Resume, this PR** | **58.6** | 83.5 | **93.5** |

- Peak allocated is the same in every row. Only the cached, unused
memory changes.
- On `main`, the load leaves 21.4 GiB cached (reserved 80.0 vs allocated
58.6). Step 2 reserves about 31 GiB on top of it.
- With this PR, reserved memory after the load equals allocated memory,
and step 2 matches the fresh run.
- The cleanup inside `AppState.load_state_dict` leaves 1.9 GiB cached:
some load buffers are freed only after `dcp_load` returns.
- The `empty_cache()` before the startup broadcast also removes the gap,
but only because it runs right after the load, and only when online
evals are on. This PR does not need it.
- Memory outside the PyTorch cache stays at about 2.4 GiB in every run.
The cached blocks do not take memory away from NCCL or cuBLAS.
- The `offload = "none"` variants ran twice, with identical numbers.

**CPU offload.** Removing the cleanup from `AppState.load_state_dict`
changes nothing:

| Resume | Reserved after load | Step-2 peak reserved |
|---|---|---|
| `offload = "optimizer"`, `main` | 19.5 | 82.0 |
| `offload = "optimizer"`, this PR | 19.5 | 82.0 |
| `offload = "full"`, `main` | 9.8 | — (killed by an unrelated HF Hub
429 in inference) |
| `offload = "full"`, both cleanups | 9.8 | 35.1 |
| `offload = "full"`, this PR | 9.8 | 34.9 |

Not tested: RL resumes (they use the same
`CheckpointManager.load_from_path`), and the 24-node run above with this
exact diff.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is limited to memory reclamation after resume; no
changes to model, optimizer, or checkpoint I/O logic beyond when
`empty_cache` runs.
> 
> **Overview**
> **Moves GPU cache cleanup to run on every checkpoint resume**, not
only when optimizer CPU offload is enabled.
> 
> Post-load `gc.collect()` and `torch.cuda.empty_cache()` are removed
from `AppState.load_state_dict` (previously gated on `has_cpu_offload`,
with optional `state_dict.clear()`). The same cleanup now runs in
`CheckpointManager.load_from_path` immediately after `dcp_load`, with a
note that DCP’s optimizer materialization can leave gradient allocations
in the CUDA cache and inflate reserved memory on the first training step
after resume.
> 
> This targets inflated peak reserved memory (and near-OOM on large SFT
resumes with `model.offload = "none"`) without changing checkpoint
contents or load semantics.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9193c739e325a8764a33c9cb1617fa63eed47281. 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:49:01 -07:00
2025-07-13 13:42:43 +02:00
2026-10-13 15:19:05 -07:00
2026-10-13 15:19:05 -07:00

Prime Intellect Prime Intellect


prime-rl: Async RL Training at Scale



Style Test Test

Overview

prime-rl is a framework for large-scale reinforcement learning. It is designed to be easy to use and hackable, yet capable of scaling to 1000+ GPUs. Here is what we think sets it apart:

  1. Fully asynchronous RL for high-throughput agentic training at scale.
  2. Performant: built to train 1T+ MoE models on 1000+ GPUs with FSDP2 for training and vLLM for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
  3. Native integration with verifiers environments through the Environments Hub, including built-in support for SWE and agentic environments.
  4. End-to-end post-training: SFT, RL training, and evals.
  5. Multi-node deployment with Slurm support.
  6. Multimodal support for VLMs such as Qwen3.5.
  7. Hackable, modular, and extensible by design.
  8. One-line SLURM deployment for frontier models — e.g. GLM-5 FP8 with P/D disaggregation, the llm-d router, and Mooncake KV offload.

Models support

The trainer runs the PrimeRL model implementations under src/prime_rl/trainer/models/: dense Llama, Qwen3 and Qwen3.5, plus the families in the table below, with expert parallelism (EP) for MoE layers, context parallelism (CP) for long sequences, and additional kernels like quack-kernels. Other architectures fail at trainer setup.

Family Example IDs MoE EP CP
GLM-5 (glm_moe_dsa) zai-org/GLM-5, zai-org/GLM-5-FP8 yes ✅ ✅
Qwen3 MoE (qwen3_moe) Qwen/Qwen3-30B-A3B, … yes ✅ ✅
Qwen3.5 MoE (qwen3_5_moe) Qwen/Qwen3.5-35B-A3B, … yes ✅ ✅
Qwen3.5 VLMs see advanced.md (qwen3_5, qwen3_5_moe) MoE only on MoE VLMs MoE only ✅
Poolside Laguna (laguna) poolside/Laguna-XS.2 yes ✅ ✅
MiniMax M2 (minimax_m2) MiniMax/MiniMax-M2 yes ✅ ✅
Nemotron H (nemotron_h) nvidia/Nemotron-3-Nano-30B-A3B, nvidia/Nemotron-3-Super-120B-A12B, … yes ✅ ✅
Trinity (afmoe) arcee-ai/Trinity-Mini, … yes ✅ ✅
GLM-4 · GLM-4.5 MoE · INTELLECT-3 (glm4_moe) THUDM/GLM-4-9B-0414, zai-org/GLM-4.5-Air, zai-org/GLM-4.5, PrimeIntellect/INTELLECT-3, … yes ✅ ✅
GPT-OSS (gpt_oss) unsloth/gpt-oss-20b-BF16, … yes ✅ ✅

Setup

We develop and test on NVIDIA RTX 3090/4090/5090, A100, H100, H200, and B200. If your setup fails, please create an issue.

Prerequisites

Currently, you need at least one NVIDIA GPU to use prime-rl. If you don't already have access to one, we recommend our compute platform for everything from renting on-demand single GPUs for developing, debugging and small ablations, to reserving 1000+ GPU clusters for production-scale training.

Quick Setup

Set up prime-rl in a single command.

curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
Manual Setup
  1. Clone the repository
git clone https://github.com/PrimeIntellect-ai/prime-rl.git
cd prime-rl
  1. Initialize submodules
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
  1. Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env
  1. Install dependencies from the lock file
uv sync --all-extras

Note

: Environments are opt-in uv workspace members — uv sync --all-extras does not install them. To train on them, install all with uv sync --all-extras --all-packages, or a subset with uv sync --package prime-rl --package <env>.

Validate your environment setup
  1. Check that the environment uses Python 3.12
uv run python -V
  1. Check that flash-attn is installed
uv run python -c "import flash_attn"
  1. Check that you can run SFT trainer (this requires 1 GPU)
uv run sft @ configs/debug/fake/sft.toml
  1. Check that you can run the inference server (this requires 1 GPU)
uv run inference --vllm.model Qwen/Qwen3-0.6B
  1. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (this requires 2 GPUs)
uv run rl @ examples/basic/reverse-text/rl.toml

Additional Setup

  1. If you want to log your runs to W&B, log in
uv run wandb login
# Or set `export WANDB_API_KEY=...`
  1. If you require gated/ private models or datasets from HuggingFace, log in
uv run hf auth login
# Or set `export HF_TOKEN=...`

Training Examples

We provide end-to-end training examples in the examples directory to highlight features of the framework and guide you through the process of training your own models.

Basic Training: 1 to 8 GPUs

Follow this guide to learn the basics of prime-rl. You can train your own models on 1 to 8 GPUs. Ideal for getting started and exploring the capabilities of the framework. These guides cover most use cases -- single-turn, multi-turn, tool calling, etc. -- on toy environments and small models.

  1. Reverse Text: Train Qwen3-0.6B to reverse a small chunk of text. Demonstrates tiny-scale single-turn SFT and RL training. Can be trained on a single consumer GPU in a few minutes, and is ideal for getting started.
  2. Wordle: Train Qwen3-1.7B to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
  3. Alphabet Sort: Train Qwen3-4B-Instruct-2507 to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
  4. Wiki Search: Train Qwen3-4B-Instruct-2507 to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
  5. Hendrycks Sanity: Run a sanity check experiment on Qwen3-1.7B using a subset of MATH filtered to problems that DeepSeek-R1-Distill-Qwen-1.5B partially solves (20-80%). Useful for algorithm ablations.

Advanced Training: 32 - 2048 GPUs:

Follow this guide to train large models on hard reasoning and agentic tasks. These guides are designed to be run from a Slurm cluster.

  1. Qwen3-30B-A3B: Train Qwen3-30B-A3B on math, SWE, and agentic tool use.
  2. GLM-4.5-Air: Train GLM-4.5-Air on search, SWE, and terminal tasks.
  3. GLM-5: Large-scale GLM-5/GLM-5.3 training with P/D disaggregation, the llm-d router, and FP8.

Docs

Check out the docs directory for in-depth guides on how to use prime-rl.

  • Overview - Architecture, install, and a copy-pasteable end-to-end RL run
  • Configuration - TOML composition, CLI overrides, env vars, validation
  • Training - RL, SFT, checkpointing, observability, rules of thumb
  • Eval - Standalone evals against any inference server, online evals, resume, platform upload
  • Scaling - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
  • Algorithms - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
  • Advanced - Custom modeling, multimodal training, LoRA
  • Development - Test suite, pre-commit hooks, adding a new model

Contributing

We warmly welcome community contributions! We use issues to track bugs, feature requests, and share our internal roadmap. If you encounter bugs, have pain points during development, or have ideas for new features, please open an issue.

Contributions are welcome via PR. Please follow these guidelines:

  1. Install the pre-commit hooks to ensure your code is formatted correctly.
  2. Please keep your PR in "Draft" until it is ready for review.
  3. If your PR resolves an issue, please link the issue in the PR description
  4. If you can, try running the test suite locally to ensure your changes are working as expected.

Pre-Commit Hooks

Please install the pre-commit hooks to ensure your code is formatted correctly.

uv run pre-commit install

Tests

uv run pytest -v                    # everything
uv run pytest tests/unit -v         # unit only
uv run pytest tests/integration -v  # integration only
uv run pytest -v -m "not gpu"       # CPU-only (inverse of the gpu marker)

License

This project is licensed under the Apache 2.0 license, as found in the License file.

Citation

If you find our work useful, feel free to cite it using

@misc{primeintellect2025prime-rl,
  author = {Prime Intellect},
  title = {prime-rl},
  url = {https://github.com/PrimeIntellect-ai/prime-rl},
  year = {2025}
}
S
Description
Fork of PrimeIntellect-ai/prime-rl with Trinity patches
Readme Apache-2.0 Cite this repository
25 MiB
Languages
Python 95.9%
Jinja 2.5%
Shell 1.6%