Compare commits

...
Author SHA1 Message Date
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
7 changed files with 81 additions and 78 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"),
+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
+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
@@ -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),
+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"))