Compare commits

...
Author SHA1 Message Date
Matej SirovatkaandGitHub 2c54d5c834 Feat: fix cpu offloading patch to match upstream and remove a segfault (#2300)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 11:21:32 +02:00
3a6b46189a fix: always ensure X-Session-ID and propagate extra_headers_from_state in elastic pool (#2283)
Release / Push CUDA image to Docker (push) Canceled after 0s
Two fixes:
- Use setdefault so X-Session-ID: example_id is always present for
  sticky DP-aware routing, even if user provides other
  extra_headers_from_state entries
- Propagate extra_headers_from_state when rebuilding clients in the
  elastic pool, so session headers survive pool refreshes

Keeps dp_rank_count as-is for direct DP rank routing.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:11:58 -07:00
JannikStandGitHub ba86b9ba88 Support runtime verifiers version override (#2274)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Support runtime verifiers version override via VERIFIERS_VERSION env var

When set, the entrypoint reinstalls verifiers from the specified git ref
(tag, branch, or commit) before starting the main process.

* Drop --no-deps so transitive deps are updated with verifiers override

* Use --reinstall-package to only reinstall verifiers, not the entire dep tree
2026-04-16 09:38:18 -07:00
halleriteandGitHub 2d659eecc7 feat: context parallelism for NemotronH Mamba layers (#2231)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-16 09:12:49 +02:00
9 changed files with 319 additions and 24 deletions
+8
View File
@@ -4,5 +4,13 @@ set -e
# Set higher ulimit for file descriptors to prevent API timeout issues
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
"verifiers @ git+https://github.com/PrimeIntellect-ai/verifiers.git@${VERIFIERS_VERSION}"
fi
# Execute the main command
exec "$@"
+2 -3
View File
@@ -742,9 +742,8 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
return self
@model_validator(mode="after")
+14 -17
View File
@@ -957,18 +957,15 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
def monkey_patch_offloading_connector_cpu_block_count():
"""Fix CPU block count miscalculation in OffloadingConnector.
CPUOffloadingSpec erroneously multiplies page_size_bytes by
len(kv_cache_config.kv_cache_tensors) when computing kv_bytes_per_block.
For UniformTypeKVCacheSpecs the page_size is already the total per-block
size across all layers, so the extra multiplier makes num_blocks far too
small. When the OffloadingManager later allocates block IDs past the
undersized CPU tensor, swap_blocks (cuMemcpyDtoHAsync_v2) segfaults on the
invalid pinned address.
CPUOffloadingSpec derives kv_bytes_per_block from page_size_bytes multiplied
by len(kv_cache_config.kv_cache_tensors), which double-counts: page_size is
already aggregated across layers in the group. The undersized CPU pool then
produces out-of-bounds block mappings and swap_blocks segfaults.
Fix: remove the num_tensors multiplier.
Fix: derive kv_bytes_per_block from the actual total GPU KV tensor size
divided by num_blocks, matching the upstream PR.
Upstream: https://github.com/vllm-project/vllm/pull/38395
Related: https://github.com/vllm-project/vllm/issues/39500
Upstream: https://github.com/vllm-project/vllm/pull/39617
"""
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
@@ -977,18 +974,18 @@ def monkey_patch_offloading_connector_cpu_block_count():
def _patched_init(self, vllm_config, kv_cache_config):
_original_init(self, vllm_config, kv_cache_config)
# Recalculate num_blocks WITHOUT the erroneous num_tensors multiplier.
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
if not cpu_bytes_to_use:
return
page_sizes = {g.kv_cache_spec.page_size_bytes for g in kv_cache_config.kv_cache_groups}
assert len(page_sizes) == 1
page_size_bytes = page_sizes.pop()
if kv_cache_config.num_blocks > 0:
total_gpu_kv_bytes = sum(t.size for t in kv_cache_config.kv_cache_tensors)
kv_bytes_per_block = (
total_gpu_kv_bytes // kv_cache_config.num_blocks
) * vllm_config.parallel_config.world_size
else:
kv_bytes_per_block = 0
# page_size_bytes already covers all layers in the group.
# Only multiply by world_size (each TP rank stores its own copy).
kv_bytes_per_block = page_size_bytes * vllm_config.parallel_config.world_size
kv_bytes_per_offloaded_block = kv_bytes_per_block * self.block_size_factor
self.num_blocks = (
int(cpu_bytes_to_use) // kv_bytes_per_offloaded_block if kv_bytes_per_offloaded_block > 0 else 0
@@ -0,0 +1,240 @@
"""All-to-all context parallelism for Mamba-2 SSM layers.
Transposes between sequence-parallel and head-parallel layouts so that each
CP rank processes the full sequence on a subset of heads, then transposes
back. This avoids materializing the full [S, full_heads] tensor on any GPU.
Communication pattern per Mamba layer:
1. in_proj (token-parallel, no comm)
2. all-to-all: [B, S/cp, D] -> [B, S, D/cp] (seq-to-head)
3. conv1d + SSM on full sequence, local heads
4. all-to-all: [B, S, D/cp] -> [B, S/cp, D] (head-to-seq)
5. out_proj (token-parallel, no comm)
"""
from __future__ import annotations
import torch
import torch.distributed as dist
class _SeqToHeadParallel(torch.autograd.Function):
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
@staticmethod
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
ctx.cp_group = cp_group
ctx.cp_size = cp_size
return _all_to_all_seq_to_head(x, cp_group, cp_size)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
return _all_to_all_head_to_seq(grad_output, ctx.cp_group, ctx.cp_size), None, None
class _HeadToSeqParallel(torch.autograd.Function):
"""[B, S, D/cp] -> [B, S/cp, D] via all-to-all."""
@staticmethod
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
ctx.cp_group = cp_group
ctx.cp_size = cp_size
return _all_to_all_head_to_seq(x, cp_group, cp_size)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
return _all_to_all_seq_to_head(grad_output, ctx.cp_group, ctx.cp_size), None, None
def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""Transpose [B, S_local, D] -> [B, S_global, D_local] via all-to-all.
Each rank sends its S_local tokens split into cp_size chunks along D,
and receives one D_local chunk from each of the cp_size ranks.
"""
B, S_local, D = x.shape
D_local = D // cp_size
# Split D into cp_size chunks, put cp dim first for all_to_all scatter
# [B, S_local, D] -> [B, S_local, cp, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, S_local, cp_size, D_local).permute(2, 0, 1, 3).contiguous()
output = torch.empty_like(x)
dist.all_to_all_single(output, x, group=cp_group)
# output[i] = data from rank i (its S_local tokens, our D_local slice)
# [cp, B, S_local, D_local] -> [B, cp, S_local, D_local] -> [B, cp*S_local, D_local]
return output.permute(1, 0, 2, 3).reshape(B, cp_size * S_local, D_local).contiguous()
def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""Transpose [B, S_global, D_local] -> [B, S_local, D] via all-to-all.
Inverse of _all_to_all_seq_to_head.
"""
B, S_global, D_local = x.shape
S_local = S_global // cp_size
# Split S_global into cp_size chunks (one per rank), put cp dim first for scatter
# [B, S_global, D_local] -> [B, cp, S_local, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, cp_size, S_local, D_local).permute(1, 0, 2, 3).contiguous()
output = torch.empty_like(x)
dist.all_to_all_single(output, x, group=cp_group)
# Each rank now has cp chunks of [B, S_local, D_local] — one D_local slice from each rank
# [cp, B, S_local, D_local] -> [B, S_local, cp, D_local] -> [B, S_local, D]
return output.permute(1, 2, 0, 3).reshape(B, S_local, cp_size * D_local).contiguous()
def seq_to_head_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S/cp, D] -> [B, S, D/cp] with correct backward."""
return _SeqToHeadParallel.apply(x, cp_group, cp_size)
def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S, D/cp] -> [B, S/cp, D] with correct backward."""
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup, cp_rank: int, cp_size: int):
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
sliced at runtime so FSDP / checkpoint shapes are unchanged.
"""
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
batch_size, seq_len, _ = hidden_states.shape # seq_len = S/cp here
# ── 1. in_proj (token-parallel, no communication needed) ──
projected_states = mixer.in_proj(hidden_states)
A = -torch.exp(mixer.A_log.float())
gate, hidden_states_B_C, time_step = torch.split(
projected_states,
[mixer.intermediate_size, mixer.conv_dim, mixer.num_heads],
dim=-1,
)
# ── 2. All-to-all: seq-parallel -> head-parallel ──
# gate: [B, S/cp, nheads * hdim] -> [B, S, (nheads/cp) * hdim]
# hidden_states_B_C: [B, S/cp, nheads*hdim + 2*ngroups*dstate] -> [B, S, ...]
# time_step: [B, S/cp, nheads] -> [B, S, nheads/cp]
gate = seq_to_head_parallel(gate, cp_group, cp_size)
time_step = seq_to_head_parallel(time_step, cp_group, cp_size)
# hidden_states_B_C needs special handling: x part shards by heads, B/C parts shard by groups
# conv_dim = intermediate_size + 2 * ngroups * dstate
groups_time_state_size = mixer.n_groups * mixer.ssm_state_size
x_part, B_part, C_part = torch.split(
hidden_states_B_C,
[mixer.intermediate_size, groups_time_state_size, groups_time_state_size],
dim=-1,
)
x_part = seq_to_head_parallel(x_part, cp_group, cp_size)
B_part = seq_to_head_parallel(B_part, cp_group, cp_size)
C_part = seq_to_head_parallel(C_part, cp_group, cp_size)
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
# ── 3. Local head dimensions ──
local_num_heads = mixer.num_heads // cp_size
local_intermediate_size = local_num_heads * mixer.head_dim
local_n_groups = mixer.n_groups // cp_size
# Slice parameters for local heads
head_start = cp_rank * local_num_heads
head_end = head_start + local_num_heads
local_A = A[head_start:head_end]
local_D = mixer.D[head_start:head_end]
local_dt_bias = mixer.dt_bias[head_start:head_end]
# Slice conv1d weight/bias for local channels
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
local_conv_dim = local_intermediate_size + 2 * local_n_groups * mixer.ssm_state_size
conv_x_start = cp_rank * local_intermediate_size
conv_x_end = conv_x_start + local_intermediate_size
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
conv_b_end = conv_b_start + local_n_groups * mixer.ssm_state_size
conv_c_start = mixer.intermediate_size + groups_time_state_size + cp_rank * local_n_groups * mixer.ssm_state_size
conv_c_end = conv_c_start + local_n_groups * mixer.ssm_state_size
conv_indices = torch.cat(
[
torch.arange(conv_x_start, conv_x_end, device=mixer.conv1d.weight.device),
torch.arange(conv_b_start, conv_b_end, device=mixer.conv1d.weight.device),
torch.arange(conv_c_start, conv_c_end, device=mixer.conv1d.weight.device),
]
)
local_conv_weight = mixer.conv1d.weight[conv_indices]
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
# ── 4. Conv1d on full sequence, local heads ──
hidden_states_B_C = torch.nn.functional.silu(
torch.nn.functional.conv1d(
hidden_states_B_C.transpose(1, 2),
local_conv_weight,
local_conv_bias,
groups=local_conv_dim,
padding=mixer.conv1d.weight.shape[2] - 1,
).transpose(1, 2)[:, :full_seq_len]
)
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
hidden_states_local, B_local, C_local = torch.split(
hidden_states_B_C,
[local_intermediate_size, local_groups_time_state_size, local_groups_time_state_size],
dim=-1,
)
# ── 5. SSM scan on full sequence, local heads ──
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
scan_output, _ = mamba_chunk_scan_combined(
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
time_step,
local_A,
B_local.view(batch_size, full_seq_len, local_n_groups, -1),
C_local.view(batch_size, full_seq_len, local_n_groups, -1),
chunk_size=mixer.chunk_size,
D=local_D,
z=None,
seq_idx=None,
return_final_states=True,
dt_bias=local_dt_bias,
dt_softplus=True,
**dt_limit_kwargs,
)
scan_output = scan_output.view(batch_size, full_seq_len, local_intermediate_size)
# ── 6. Gated RMSNorm with local weights ──
# Zamba2RMSNormGated normalizes within groups of size `group_size`.
# In head-parallel mode, we have local_intermediate_size features.
# The group_size stays the same, but group_count is reduced.
local_norm_weight = mixer.norm.weight[cp_rank * local_intermediate_size : (cp_rank + 1) * local_intermediate_size]
scan_output = _gated_rms_norm(
scan_output, gate, local_norm_weight, mixer.norm.variance_epsilon, mixer.norm.group_size
)
# ── 7. All-to-all: head-parallel -> seq-parallel ──
scan_output = head_to_seq_parallel(scan_output, cp_group, cp_size)
# ── 8. out_proj (token-parallel, no communication needed) ──
return mixer.out_proj(scan_output)
def _gated_rms_norm(
x: torch.Tensor, gate: torch.Tensor, weight: torch.Tensor, eps: float, group_size: int
) -> torch.Tensor:
"""Gated RMSNorm matching Zamba2RMSNormGated: gate -> group-wise RMSNorm -> weight."""
input_dtype = x.dtype
x = x.to(torch.float32)
if gate is not None:
x = x * torch.nn.functional.silu(gate.to(torch.float32))
*prefix_dims, last_dim = x.shape
group_count = last_dim // group_size
x_grouped = x.view(*prefix_dims, group_count, group_size)
variance = x_grouped.pow(2).mean(-1, keepdim=True)
x_grouped = x_grouped * torch.rsqrt(variance + eps)
x = x_grouped.view(*prefix_dims, last_dim)
return (weight * x).to(input_dtype)
@@ -9,6 +9,7 @@ Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
from typing import Optional
import torch
import torch.distributed as dist
from torch import Tensor, nn
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
@@ -18,6 +19,7 @@ from transformers.utils import auto_docstring, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGatedGroupedExperts
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
@@ -113,7 +115,12 @@ def _ensure_zamba2_compat(config: NemotronHConfig):
class NemotronHMambaLayer(GradientCheckpointingLayer):
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual."""
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual.
With context parallelism, uses all-to-all head partitioning: transposes
from sequence-parallel to head-parallel before the SSM, so each CP rank
processes the full sequence on a subset of heads, then transposes back.
"""
def __init__(self, config: NemotronHConfig, layer_idx: int):
super().__init__()
@@ -123,6 +130,21 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
self.mamba = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
self.mlp = None # No MoE in this layer type
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
assert self.mamba.num_heads % cp_world_size == 0, (
f"num_heads ({self.mamba.num_heads}) must be divisible by cp_world_size ({cp_world_size})"
)
assert self.mamba.n_groups % cp_world_size == 0, (
f"n_groups ({self.mamba.n_groups}) must be divisible by cp_world_size ({cp_world_size})"
)
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
@property
def cp_enabled(self) -> bool:
return hasattr(self, "_cp_group")
def forward(
self,
hidden_states: torch.Tensor,
@@ -132,7 +154,12 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
hidden_states = self.mamba(hidden_states)
if self.cp_enabled:
hidden_states = mamba_cp_forward(
self.mamba, hidden_states, self._cp_group, self._cp_rank, self._cp_world_size
)
else:
hidden_states = self.mamba(hidden_states)
return residual + hidden_states
+2 -1
View File
@@ -188,10 +188,11 @@ def train(config: TrainerConfig):
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_hybrid_cp, setup_sparse_mla_cp
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Optionally, resume training from a checkpoint
progress = Progress()
+2 -1
View File
@@ -109,7 +109,7 @@ def train(config: SFTConfig):
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_hybrid_cp, setup_sparse_mla_cp
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
# Set up checkpoint manager
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
@@ -131,6 +131,7 @@ def train(config: SFTConfig):
if parallel_dims.cp_enabled:
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
if config.model.lora is not None:
multi_run_manager = get_multi_run_manager()
+21
View File
@@ -36,6 +36,27 @@ def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int,
get_logger().info(f"Configured hybrid CP on {count} DeltaNet modules (fla native state passing)")
def setup_nemotron_h_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Configure NemotronH Mamba layers for context-parallel gather/scatter."""
layers = None
if hasattr(model, "model") and hasattr(model.model, "layers"):
layers = model.model.layers
if layers is None:
return
count = 0
for layer in layers:
if hasattr(layer, "mamba") and hasattr(layer, "set_context_parallel_attributes"):
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 NemotronH CP on {count} Mamba layers (all-to-all head partitioning)")
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."""
+1
View File
@@ -183,6 +183,7 @@ class ElasticInferencePool:
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
dp_rank_count=self.client_config.dp_rank_count,
extra_headers_from_state=self.client_config.extra_headers_from_state,
)
self._train_clients = setup_clients(url_config, client_type=self.train_client_type) if urls else []
self._eval_clients = setup_clients(url_config, client_type=self.eval_client_type) if urls else []