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
4 changed files with 149 additions and 31 deletions
+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")]'
+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
+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
+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}"