Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
738eb5016a | ||
|
|
06eb91d7c8 |
@@ -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")
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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"))
|
||||
|
||||
Reference in New Issue
Block a user