Compare commits

..
Author SHA1 Message Date
samsjaandGitHub fb31b51e84 fix: disable dynamo on Ulysses all-to-all to prevent FSDP×compile NCCL deadlock (#3195)
When torch.compile is used with Ulysses context parallelism and FSDP,
the all-to-all collectives are traced into the compiled backward graph
while FSDP's reduce-scatter hooks fire eagerly via the autograd engine.
The compiler may reorder the all-to-all backward differently across
ranks, causing rank 0 to wait on reduce_scatter while rank 1 waits on
all_to_all — a classic collective ordering mismatch that deadlocks NCCL
after the 1-hour watchdog timeout (PR #3186, job 1578).

Wrapping _all_to_all_seq_to_head and _all_to_all_head_to_seq with
torch._dynamo.disable forces a graph break around the collectives so
they execute eagerly in the autograd engine, restoring a single
consistent backward ordering between the two collective systems.
2026-08-05 21:43:25 -07:00
samsjaandGitHub 33b7d19cb1 Revert "chore: release v0.8.0 (#3207)" (#3208)
This reverts commit 56a9402953.
2026-08-05 20:53:32 -07:00
samsjaandGitHub 56a9402953 chore: release v0.8.0 (#3207) 2026-08-05 20:42:26 -07:00
0c0b92f99c chore: remove padded vLLM input scrub (#3203)
The scrub from #2506 was a temporary mitigation for NaN logits caused by
stale padded decode inputs poisoning CUDA-graph replay. The root cause is
fixed in the pinned vLLM 0.26.0: the non-contiguous logits bug in the
native Triton top-k/top-p kernel (vllm-project/vllm#42739) is included,
and _preprocess now zeros the padded positions tail natively.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:53:27 -07:00
samsjaandGitHub 84ce4d6677 fix: add eval.retrigger_on_resume to re-fire evals at checkpoint step on resume (#3123)
On resume, the orchestrator defaults to assuming a clean exit where all
evals already completed. When a run crashes mid-eval, the user can set
eval.retrigger_on_resume=True to re-trigger interval-aligned evals
at the checkpoint step instead of the next interval boundary.

No changes to EvalSource — the existing first_trigger = not is_resumed
already skips the base eval on resume and just checks step % interval,
so passing resume_step to trigger() is sufficient.
2026-08-05 15:49:32 -07:00
01e959596a feat: auto-resolve parsers for Laguna, gpt-oss, and Trinity (#3201)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:06:50 -07:00
HubertandGitHub 738eb5016a fix(nemotron-h): use fla causal_conv1d for packed Mamba conv (#3192)
Both NemotronH Mamba paths built their packed-document metadata with a
`cu_seqlens.tolist()` and a Python loop over documents, once per Mamba
layer. On Super that is 40 host-device syncs per forward (80 with
activation recompute): each one blocks the Python thread until the CUDA
stream drains, so the CPU never runs ahead and, under context
parallelism, every rank re-synchronizes to its slowest CP partner at
every layer instead of absorbing jitter in queue depth.

Replace the per-document conv loop and the hand-built seq_idx with
fla's Triton `causal_conv1d` and `prepare_sequence_ids`, matching the
call shape already used for Qwen3.5 GDN in `trainer/model.py` and
`qwen3_5_moe`. Both fla helpers derive boundaries from `cu_seqlens`
directly and are `@tensor_cache`d by argument identity, so the 40
layers of a forward share one build.

fla is already a required dependency and its Triton backend needs no
arch-specific CUDA compilation, which was the stated reason for
avoiding a fused conv here.
2026-08-04 20:41:49 -07:00
06eb91d7c8 fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward (#3197)
* fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward

The fused LM head wrapper forwards seq_lens/seq_lens_are_pre_shard to the
inner model, but only GlmMoeDsaForCausalLM accepted them.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* review: drop inline comment above seq_lens kwargs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 20:21:03 -07:00
14 changed files with 100 additions and 299 deletions
@@ -301,6 +301,11 @@ class EvalConfig(BaseConfig):
"""If True, skip the startup eval that otherwise runs before any
train rollouts."""
retrigger_on_resume: bool = False
"""If True, re-trigger evals at the checkpoint step on resume (e.g. after a
crash that left in-flight evals unfinished). By default, assumes a clean
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
@@ -2,12 +2,17 @@ import re
# (regex, parser_name) — first match wins.
TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
(re.compile(r"^zai-org/GLM-4\.7"), "glm47"),
(re.compile(r"^zai-org/GLM-5"), "glm47"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2"),
(re.compile(r"^openai/gpt-oss"), "openai"),
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
@@ -18,9 +23,13 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
]
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
# openai/gpt-oss has no entry here — vLLM's harmony serving path splits reasoning natively.
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
-3
View File
@@ -1,7 +1,5 @@
import torch
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
def apply_shared_vllm_patches():
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
@@ -16,7 +14,6 @@ def apply_shared_vllm_patches():
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_qwen3_coder_param_newline_trim()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
monkey_patch_online_fp8_parameter_cast()
+4 -8
View File
@@ -10,14 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
# Nemotron-Nano SWE, PR #2506; upstream fix vllm#42779 is still unmerged). V1 keeps
# the scrub effective for every model and is also required for routed-experts capture
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
# stays overridable.
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
@@ -1,88 +0,0 @@
from __future__ import annotations
import logging
import threading
from collections.abc import Sequence
from typing import Any
logger = logging.getLogger(__name__)
_INSTALL_LOCK = threading.Lock()
_INSTALLED = False
def monkey_patch_vllm_padded_input_scrub() -> None:
"""Zero vLLM's padded model inputs before graph replay.
vLLM pads decode batches up to CUDA graph capture sizes. Some kernels read
model-input tensors past the scheduled-token prefix, so stale values in the
padded tail can affect replayed decode graphs. Keep this shim until the
vLLM-side fix is available in the pinned runtime.
Remove this patch once https://github.com/vllm-project/vllm/pull/42779 is
included in the vLLM release we pin/use.
"""
global _INSTALLED
with _INSTALL_LOCK:
if _INSTALLED:
return
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
if getattr(GPUModelRunner, "_prime_rl_padded_input_scrub", False):
_INSTALLED = True
return
original_preprocess = GPUModelRunner._preprocess
def _patched_preprocess(
self: Any,
scheduler_output: Any,
num_input_tokens: int,
intermediate_tensors: Any | None = None,
) -> tuple[Any, ...]:
result = original_preprocess(
self,
scheduler_output,
num_input_tokens,
intermediate_tensors,
)
num_scheduled_tokens = int(scheduler_output.total_num_scheduled_tokens)
_zero_padded_model_inputs(
result,
num_scheduled_tokens,
int(num_input_tokens),
)
return result
GPUModelRunner._preprocess = _patched_preprocess
GPUModelRunner._prime_rl_padded_input_scrub = True
_INSTALLED = True
logger.warning("Enabled vLLM padded model-input scrub.")
def _zero_padded_model_inputs(
preprocess_result: Sequence[Any],
num_scheduled_tokens: int,
num_input_tokens: int,
) -> None:
"""Zero the model-input tail beyond scheduled tokens in-place."""
if num_input_tokens <= num_scheduled_tokens:
return
input_ids = preprocess_result[0]
inputs_embeds = preprocess_result[1]
positions = preprocess_result[2]
pad_slice = slice(num_scheduled_tokens, num_input_tokens)
if input_ids is not None:
input_ids[pad_slice].zero_()
if inputs_embeds is not None:
inputs_embeds[pad_slice].zero_()
if positions is not None:
if positions.ndim == 1:
positions[pad_slice].zero_()
else:
positions[..., pad_slice].zero_()
-4
View File
@@ -25,7 +25,6 @@ from prime_rl.inference.patches import (
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
monkey_patch_vllm_padded_input_scrub,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
@@ -37,9 +36,6 @@ monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
monkey_patch_nano_v3_reasoning_parser()
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
# is available in our pinned runtime.
monkey_patch_vllm_padded_input_scrub()
# NOTE: routed_experts are consumed only via the serialized /generate path (router
# replay). The chat-completions path encodes them as a base64 np.save string the PD
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
+5 -1
View File
@@ -470,7 +470,11 @@ class Orchestrator:
]
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
# interval-aligned evals at the checkpoint step (e.g. after a crash).
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
self.maybe_trigger_eval(self.resume_step)
self.maybe_trigger_eval(self.progress.step)
# Anchor step-time clock so the first step measures startup → first batch
@@ -207,10 +207,17 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: Optional[torch.LongTensor] = None,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token in the sequence. Only used for router replay.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`, *optional*):
Per-document lengths of the packed row (PrimeRL packed-batch contract). Unused.
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries. Unused.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+12 -44
View File
@@ -16,45 +16,8 @@ from __future__ import annotations
import torch
import torch.distributed as dist
def _build_seq_idx(boundaries: list[int], seq_len: int, device: torch.device) -> torch.Tensor:
"""Return the packed-document id for each token in a full CP sequence."""
if boundaries[0] != 0 or boundaries[-1] != seq_len:
raise ValueError(f"cu_seqlens must span the full sequence length {seq_len}, got {boundaries}")
seq_idx = torch.empty(seq_len, dtype=torch.int32, device=device)
for sequence_id, (start, end) in enumerate(zip(boundaries[:-1], boundaries[1:])):
if end <= start:
raise ValueError(f"cu_seqlens must be strictly increasing, got {boundaries}")
seq_idx[start:end] = sequence_id
return seq_idx.unsqueeze(0)
def _causal_conv1d_varlen(
hidden_states: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor | None,
boundaries: list[int],
) -> torch.Tensor:
"""Apply a depthwise causal convolution independently to packed documents."""
batch_size, _, channels = hidden_states.shape
if batch_size != 1:
raise ValueError(f"packed CP Mamba expects batch_size=1, got {batch_size}")
inputs = hidden_states.transpose(1, 2)
outputs = []
for start, end in zip(boundaries[:-1], boundaries[1:]):
convolved = torch.nn.functional.conv1d(
inputs[:, :, start:end],
weight,
bias,
groups=channels,
padding=weight.shape[2] - 1,
)
outputs.append(convolved[:, :, : end - start])
return torch.cat(outputs, dim=-1).transpose(1, 2)
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.utils import prepare_sequence_ids
class _SeqToHeadParallel(torch.autograd.Function):
@@ -180,8 +143,7 @@ def mamba_cp_forward(
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)
boundaries = cu_seqlens.tolist()
seq_idx = _build_seq_idx(boundaries, full_seq_len, hidden_states.device)
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
# ── 3. Local head dimensions ──
local_num_heads = mixer.num_heads // cp_size
@@ -216,9 +178,15 @@ def mamba_cp_forward(
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 each packed document, local heads ──
hidden_states_B_C = torch.nn.functional.silu(
_causal_conv1d_varlen(hidden_states_B_C, local_conv_weight, local_conv_bias, boundaries)
# ── 4. Causal conv1d on the full sequence, local heads ──
# Must reset at sequence boundaries for packed batches, otherwise the
# kernel-1 left pad leaks state across sequences.
hidden_states_B_C, _ = fla_causal_conv1d(
x=hidden_states_B_C,
weight=local_conv_weight.squeeze(1),
bias=local_conv_bias,
activation=mixer.activation,
cu_seqlens=cu_seqlens,
)
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
@@ -68,11 +68,18 @@ def _replicate_kv_heads(t: torch.Tensor, cp_size: int) -> torch.Tensor:
return t.repeat_interleave(cp_size // h, dim=1)
@torch._dynamo.disable
def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
"""Redistribute [S_local, H, D] -> [S_global, H_local, D].
Splits the head dim into cp_size groups and exchanges them so each rank
ends up with the full sequence but only H/cp_size heads. Differentiable.
Disabled for dynamo: the collective must execute eagerly so it is scheduled
by the autograd engine in a consistent order across ranks, not reordered by
the compiled backward graph. Otherwise FSDP's post_backward reduce-scatter
and the all-to-all backward can interleave differently per rank, deadlocking
NCCL (see PR #3186 job 1578).
"""
s_local, h, d = t.shape
assert h % cp_size == 0, (
@@ -90,6 +97,7 @@ def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
return out.reshape(cp_size * s_local, h_local, d)
@torch._dynamo.disable
def _all_to_all_head_to_seq(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
"""Inverse of `_all_to_all_seq_to_head`: [S_global, H_local, D] -> [S_local, H, D]."""
s_global, h_local, d = t.shape
@@ -10,6 +10,8 @@ from typing import Optional
import torch
import torch.distributed as dist
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.utils import prepare_sequence_ids
from torch import Tensor, nn
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
@@ -40,10 +42,8 @@ def _patch_mamba2_use_triton_ssd():
Triton kernels and mamba_ssm use fp32. This causes ~0.4 KL divergence.
This patch makes the mixer use mamba_chunk_scan_combined (Triton, fp32
softplus) for the SSD computation, with PyTorch nn.Conv1d for convolution.
Requires mamba_ssm installed; causal_conv1d should NOT be installed (it
needs arch-specific CUDA compilation). The HF cuda_kernels_forward
already falls back to PyTorch nn.Conv1d when causal_conv1d is absent.
softplus) for the SSD computation, with fla's Triton causal_conv1d for
convolution. Requires mamba_ssm installed.
"""
global _patch_applied
if _patch_applied:
@@ -68,7 +68,7 @@ def _patch_mamba2_use_triton_ssd():
def _varlen_mamba_forward(self, hidden_states, cu_seqlens):
"""Varlen-aware mamba forward. `cu_seqlens` is required: shape [num_seq+1],
e.g. [0, s1, s1+s2, ...]. Handles packed batches by:
- applying conv1d per-sequence (with kernel-1 leading zeros)
- passing cu_seqlens to causal_conv1d (conv state resets at boundaries)
- passing seq_idx to mamba_chunk_scan_combined (SSM state resets at boundaries)
"""
batch_size, seq_len, _ = hidden_states.shape
@@ -86,20 +86,15 @@ def _patch_mamba2_use_triton_ssd():
dim=-1,
)
# 2. Per-sequence causal conv1d. self.conv1d already has padding=kernel-1 so
# applying it to each segment independently gives the correct causal output
# without cross-sequence history.
hbc_t = hidden_states_B_C.transpose(1, 2) # (1, C, L)
cu = cu_seqlens.tolist()
conv_outs = []
for i in range(len(cu) - 1):
s, e = cu[i], cu[i + 1]
if s == e:
continue
seg = hbc_t[:, :, s:e]
conv_out = self.conv1d(seg)[:, :, : e - s]
conv_outs.append(conv_out)
hidden_states_B_C = self.act(torch.cat(conv_outs, dim=-1).transpose(1, 2))
# 2. Causal conv1d — must reset at sequence boundaries for packed batches,
# otherwise the kernel-1 left pad leaks state across sequences.
hidden_states_B_C, _ = fla_causal_conv1d(
x=hidden_states_B_C,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cu_seqlens=cu_seqlens,
)
hidden_states, B, C = torch.split(
hidden_states_B_C,
@@ -108,12 +103,7 @@ def _patch_mamba2_use_triton_ssd():
)
# 3. SSM with seq_idx so state resets at sequence boundaries
seq_idx = torch.zeros(seq_len, dtype=torch.int32, device=hidden_states.device)
for i in range(len(cu) - 1):
s, e = cu[i], cu[i + 1]
if e > s:
seq_idx[s:e] = i
seq_idx = seq_idx.unsqueeze(0) # (1, L)
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
scan_output = _mamba_chunk_scan_combined(
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
@@ -1,118 +0,0 @@
from types import SimpleNamespace
import torch
import prime_rl.inference.vllm.padded_input_scrub as padded_input_scrub
from prime_rl.inference.vllm.padded_input_scrub import (
_zero_padded_model_inputs,
monkey_patch_vllm_padded_input_scrub,
)
def test_monkey_patch_preprocess_matches_vllm_preprocess_signature(monkeypatch):
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
calls = {}
def fake_preprocess(
self,
scheduler_output,
num_input_tokens,
intermediate_tensors=None,
):
calls["args"] = (
self,
scheduler_output,
num_input_tokens,
intermediate_tensors,
)
return (
torch.tensor([10, 11, 12, 991, 992]),
None,
torch.tensor([0, 1, 2, 991, 992]),
intermediate_tensors,
{},
None,
)
monkeypatch.setattr(padded_input_scrub, "_INSTALLED", False)
monkeypatch.setattr(GPUModelRunner, "_preprocess", fake_preprocess)
monkeypatch.setattr(
GPUModelRunner,
"_prime_rl_padded_input_scrub",
False,
raising=False,
)
monkey_patch_vllm_padded_input_scrub()
self = object()
scheduler_output = SimpleNamespace(total_num_scheduled_tokens=3)
intermediate_tensors = object()
result = GPUModelRunner._preprocess(self, scheduler_output, 5, intermediate_tensors)
assert calls["args"] == (
self,
scheduler_output,
5,
intermediate_tensors,
)
assert result[0].tolist() == [10, 11, 12, 0, 0]
assert result[2].tolist() == [0, 1, 2, 0, 0]
def test_zero_padded_model_inputs_leaves_scheduled_prefix_intact():
input_ids = torch.tensor([10, 11, 12, 991, 992])
positions = torch.tensor([0, 1, 2, 991, 992])
preprocess_result = (input_ids, None, positions, None, {}, None)
_zero_padded_model_inputs(
preprocess_result,
num_scheduled_tokens=3,
num_input_tokens=5,
)
assert input_ids.tolist() == [10, 11, 12, 0, 0]
assert positions.tolist() == [0, 1, 2, 0, 0]
def test_zero_padded_model_inputs_zeroes_embeddings_and_mrope_positions():
inputs_embeds = torch.ones((5, 4))
inputs_embeds[3:] = 7
positions = torch.tensor(
[
[0, 1, 2, 991, 992],
[0, 1, 2, 993, 994],
[0, 1, 2, 995, 996],
]
)
preprocess_result = (None, inputs_embeds, positions, None, {}, None)
_zero_padded_model_inputs(
preprocess_result,
num_scheduled_tokens=3,
num_input_tokens=5,
)
torch.testing.assert_close(inputs_embeds[:3], torch.ones((3, 4)))
torch.testing.assert_close(inputs_embeds[3:], torch.zeros((2, 4)))
assert positions.tolist() == [
[0, 1, 2, 0, 0],
[0, 1, 2, 0, 0],
[0, 1, 2, 0, 0],
]
def test_zero_padded_model_inputs_noops_without_padding():
input_ids = torch.tensor([10, 11, 12])
positions = torch.tensor([0, 1, 2])
preprocess_result = (input_ids, None, positions, None, {}, None)
_zero_padded_model_inputs(
preprocess_result,
num_scheduled_tokens=3,
num_input_tokens=3,
)
assert input_ids.tolist() == [10, 11, 12]
assert positions.tolist() == [0, 1, 2]
+13
View File
@@ -5,6 +5,11 @@ from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_p
# (model_name, expected_tool_call_parser, expected_reasoning_parser)
EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
# Arcee Trinity
("arcee-ai/Trinity-Large-Thinking", "qwen3_coder", "deepseek_r1"),
("arcee-ai/Trinity-Large-Preview", "hermes", None),
("arcee-ai/Trinity-Mini", "hermes", "deepseek_r1"),
("arcee-ai/Trinity-Nano-Preview", "hermes", "deepseek_r1"),
# DeepSeek
("deepseek-ai/DeepSeek-V3.2", "deepseek_v32", "deepseek_r1"),
("deepseek-ai/DeepSeek-V3.2-Exp", "deepseek_v32", "deepseek_r1"),
@@ -33,6 +38,14 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
("MiniMaxAI/MiniMax-M2", "minimax_m2", "minimax_m2_append_think"),
("MiniMaxAI/MiniMax-M2.1", "minimax_m2", "minimax_m2_append_think"),
("MiniMaxAI/MiniMax-M2.5", "minimax_m2", "minimax_m2_append_think"),
# gpt-oss (reasoning handled natively by vLLM's harmony path)
("openai/gpt-oss-20b", "openai", None),
("openai/gpt-oss-120b", "openai", None),
# Poolside Laguna
("poolside/Laguna-S-2.1", "poolside_v1", "poolside_v1"),
("poolside/Laguna-S-2.1-FP8", "poolside_v1", "poolside_v1"),
("poolside/Laguna-XS-2.1", "poolside_v1", "poolside_v1"),
("poolside/Laguna-M.1", "poolside_v1", "poolside_v1"),
# INTELLECT-3
("PrimeIntellect/INTELLECT-3", "qwen3_coder", "deepseek_r1"),
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
+22 -8
View File
@@ -6,6 +6,8 @@ import torch
from prime_rl.trainer.models.layers import cp_mamba
pytestmark = [pytest.mark.gpu]
class _FakeMixer(torch.nn.Module):
def __init__(self):
@@ -19,6 +21,7 @@ class _FakeMixer(torch.nn.Module):
self.chunk_size = 1
self.time_step_limit = None
self.variance_epsilon = 1e-5
self.activation = "silu"
self.in_proj = torch.nn.Linear(1, 5, bias=False)
self.in_proj.weight.data.copy_(torch.tensor([[1.0], [1.0], [1.0], [1.0], [1.0]]))
@@ -27,7 +30,9 @@ class _FakeMixer(torch.nn.Module):
self.dt_bias = torch.nn.Parameter(torch.zeros(1))
self.conv1d = torch.nn.Conv1d(3, 3, kernel_size=2, groups=3, bias=False)
self.conv1d.weight.data.fill_(1.0)
self.norm = types.SimpleNamespace(weight=torch.ones(1), variance_epsilon=self.variance_epsilon, group_size=1)
self.norm = types.SimpleNamespace(
weight=torch.ones(1, device="cuda"), variance_epsilon=self.variance_epsilon, group_size=1
)
self.out_proj = torch.nn.Identity()
@@ -52,20 +57,29 @@ def test_mamba_cp_forward_resets_conv_and_scan_at_packed_boundaries(monkeypatch)
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
mixer = _FakeMixer()
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32)
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]])
mixer = _FakeMixer().cuda()
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32, device="cuda")
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]], device="cuda")
second = first.clone()
second[0, 1, 0] = 200.0
first_out = cp_mamba.mamba_cp_forward(mixer, first, None, 0, 1, cu_seqlens)
second_out = cp_mamba.mamba_cp_forward(mixer, second, None, 0, 1, cu_seqlens)
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32))
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32, device="cuda"))
assert torch.equal(seen_seq_idx[1], seen_seq_idx[0])
torch.testing.assert_close(first_out[:, 2:], second_out[:, 2:])
def test_mamba_cp_forward_rejects_local_boundaries():
with pytest.raises(ValueError, match="full sequence length 4"):
cp_mamba._build_seq_idx([0, 2], 4, torch.device("cpu"))
def test_mamba_cp_forward_builds_seq_idx_for_uneven_packs(monkeypatch):
seen_seq_idx: list[torch.Tensor] = []
_install_fake_scan(monkeypatch, seen_seq_idx)
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
cu_seqlens = torch.tensor([0, 1, 4, 6], dtype=torch.int32, device="cuda")
hidden_states = torch.arange(6, dtype=torch.float32, device="cuda").reshape(1, 6, 1)
cp_mamba.mamba_cp_forward(_FakeMixer().cuda(), hidden_states, None, 0, 1, cu_seqlens)
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 1, 1, 1, 2, 2]], dtype=torch.int32, device="cuda"))