Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bad80b1a30 |
+1
-1
@@ -112,7 +112,7 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
|
||||
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all (DeepSeek V4, GPT-OSS), is rejected at setup.
|
||||
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
|
||||
+5
-1
@@ -62,6 +62,7 @@ gpu = [
|
||||
"dion ; sys_platform == 'linux'",
|
||||
"tilelang>=0.1.8 ; sys_platform == 'linux'",
|
||||
"flash-linear-attention ; sys_platform == 'linux'",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
"torchao>=0.18.0 ; sys_platform == 'linux'",
|
||||
"modelexpress==0.3.0 ; sys_platform == 'linux'",
|
||||
@@ -139,6 +140,8 @@ environments = [
|
||||
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
|
||||
# See: https://github.com/pytorch/pytorch/issues/166122
|
||||
override-dependencies = [
|
||||
# Keep vLLM's TileLang version; Nemotron uses Mamba-2's Triton kernels.
|
||||
"tilelang==0.1.12",
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
@@ -285,12 +288,13 @@ prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
||||
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
|
||||
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
mamba-ssm = ["torch>=2.13.0"]
|
||||
|
||||
[tool.uv.extra-build-variables]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
@@ -59,10 +59,10 @@ See the `kernels` skill.
|
||||
### NemotronH (Mamba SSD kernels)
|
||||
|
||||
```bash
|
||||
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
|
||||
uv sync --extra gpu
|
||||
```
|
||||
|
||||
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
|
||||
Native NemotronH uses Mamba2 Triton SSD kernels and FLA's packed causal convolution. The pinned `mamba-ssm` source installs without `nvcc`; no separate `causal-conv1d` installation is needed. `uv sync --all-extras` includes these dependencies.
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ if _hub_kernels is not None:
|
||||
try:
|
||||
return _original_lazy_load_kernel(kernel_name, mapping)
|
||||
except OfflineModeIsEnabled:
|
||||
# Return None so NemotronH skips hub kernels; prime-rl's
|
||||
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
|
||||
# Return None so callers can use their non-hub implementation.
|
||||
mapping[kernel_name] = None
|
||||
return None
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
|
||||
HF's forward hardcodes seq_idx=None for causal_conv1d and omits cu_seqlens
|
||||
for chunk_gated_delta_rule, so packed RL training sees ~0.23 Mismatch KL vs
|
||||
vLLM (target <0.01). Mirrors the NemotronH mamba fix.
|
||||
vLLM (target <0.01).
|
||||
"""
|
||||
import torch.nn.functional as F
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import (
|
||||
@@ -633,15 +633,6 @@ def get_model(
|
||||
|
||||
logger.debug(f"Loaded model config ({model_config.to_dict()})")
|
||||
|
||||
# NemotronH: transformers' Mamba2 mixer __init__ calls lazy_load_kernel("mamba-ssm" /
|
||||
# "causal-conv1d") whenever config.use_mamba_kernels is set. That hub-kernel path is gated only
|
||||
# by whether the `kernels` package is importable (NOT by USE_HUB_KERNELS) and resolves from the
|
||||
# HF Hub, which hard-crashes under HF_HUB_OFFLINE=1. prime-rl swaps in its own mamba_ssm Triton
|
||||
# SSD kernels via _patch_mamba2_use_triton_ssd, so the hub kernels are redundant; disable them
|
||||
# to keep model init offline-safe.
|
||||
if getattr(model_config, "model_type", "") == "nemotron_h":
|
||||
model_config.use_mamba_kernels = False
|
||||
|
||||
if config.debug.num_layers is not None:
|
||||
# VLM configs nest num_hidden_layers under text_config
|
||||
target_config = getattr(model_config, "text_config", model_config)
|
||||
|
||||
@@ -27,10 +27,9 @@ Design constraints:
|
||||
* **Every op is present-guarded** — it no-ops when its inputs are absent — so
|
||||
the same per-layer op list can be emitted for every layer and simply skips
|
||||
dense / non-matching layers, exactly as the imperative loops did.
|
||||
* **"Backward" means "what the imperative ``*_to_hf`` did"**, not a strict
|
||||
mathematical inverse: a few conversions are intentionally lossy (e.g.
|
||||
NemotronH shifts a router bias one way and does not undo it). Such ops carry
|
||||
an explicit backward (see :class:`MapValue`).
|
||||
* **"Backward" means "what the imperative ``*_to_hf`` did"**, not necessarily
|
||||
a strict mathematical inverse. Value transforms can provide an explicit
|
||||
backward through :class:`MapValue`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
"""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
|
||||
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
|
||||
|
||||
|
||||
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 = all_to_all_single_equal(x, 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 = all_to_all_single_equal(x, 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 _all_to_all_seq_to_head(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 _all_to_all_head_to_seq(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def mamba_cp_forward(
|
||||
mixer,
|
||||
hidden_states: torch.Tensor,
|
||||
cp_group: dist.ProcessGroup,
|
||||
cp_rank: int,
|
||||
cp_size: int,
|
||||
cu_seqlens: torch.Tensor,
|
||||
):
|
||||
"""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)
|
||||
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
|
||||
|
||||
# ── 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
|
||||
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. 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
|
||||
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=seq_idx,
|
||||
return_final_states=False,
|
||||
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)
|
||||
@@ -15,9 +15,8 @@ Ulysses is the simpler alternative to ring attention for context parallelism:
|
||||
[S/cp, H, D] ◀── all-to-all ── [S, H/cp, D]
|
||||
(seq ↔ heads)
|
||||
|
||||
Key benefit: the attention kernel itself does not need to be CP-aware. The
|
||||
all-to-all is purely on Q/K/V tensors, so this works out of the box with
|
||||
softmax flash-attn, linear attention, mamba, etc., without rewriting kernels.
|
||||
The softmax-attention kernel itself does not need to be CP-aware. Hybrid models
|
||||
use the same sequence/head redistribution in their owned recurrent modules.
|
||||
|
||||
GQA models with fewer KV heads than cp_size (e.g. NemotronH: 32 query heads, 2
|
||||
KV heads) are handled by replicating each KV head cp_size / num_key_value_heads
|
||||
|
||||
@@ -2,217 +2,142 @@ from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class NemotronHConfig(PretrainedConfig):
|
||||
"""Configuration for NemotronH (Nemotron-3-Super-120B-A12B) hybrid Mamba-Transformer-MoE model.
|
||||
|
||||
The model architecture is defined by `layers_block_type`, a list where each element is
|
||||
one of "mamba", "attention", or "moe". The 120B model uses a pattern like MEMEMEM*EMEMEMEM*...
|
||||
(M=Mamba-2, E=MoE with latent projections, *=Attention) repeated across 88 layers.
|
||||
|
||||
Args:
|
||||
vocab_size: Vocabulary size.
|
||||
hidden_size: Dimension of the hidden representations.
|
||||
layers_block_type: Explicit list of layer types. Determines num_hidden_layers.
|
||||
tie_word_embeddings: Whether to tie input/output embeddings.
|
||||
pad_token_id: Padding token id.
|
||||
bos_token_id: Beginning of sequence token id.
|
||||
eos_token_id: End of sequence token id.
|
||||
num_attention_heads: Number of attention heads.
|
||||
num_key_value_heads: Number of key/value heads for GQA.
|
||||
head_dim: Dimension of each attention head.
|
||||
max_position_embeddings: Maximum sequence length.
|
||||
attention_bias: Whether to use bias in attention layers.
|
||||
intermediate_size: MLP intermediate dimension (for shared expert).
|
||||
mlp_hidden_act: Activation function for MLP layers.
|
||||
mlp_bias: Whether to use bias in MLP layers.
|
||||
use_mamba_kernels: Whether to use fast mamba CUDA kernels.
|
||||
ssm_state_size: Mamba state space dimension.
|
||||
mamba_num_heads: Number of mamba heads.
|
||||
mamba_n_groups: Number of groups in mamba.
|
||||
mamba_head_dim: Dimension per mamba head.
|
||||
mamba_d_conv: Convolution kernel size.
|
||||
mamba_expand: Expansion factor.
|
||||
mamba_hidden_act: Activation for mamba layers.
|
||||
mamba_dt_min: Time step minimum.
|
||||
mamba_dt_max: Time step maximum.
|
||||
mamba_dt_limit: Time step limits.
|
||||
mamba_dt_init_floor: Floor for time step initialization.
|
||||
mamba_conv_bias: Whether to use bias in mamba convolution.
|
||||
mamba_proj_bias: Whether to use bias in mamba projections.
|
||||
mamba_chunk_size: Chunk size for mamba processing.
|
||||
n_routed_experts: Number of routed experts.
|
||||
n_shared_experts: Number of shared experts.
|
||||
moe_intermediate_size: Expert intermediate dimension.
|
||||
moe_shared_expert_intermediate_size: Shared expert intermediate dimension.
|
||||
moe_latent_size: Latent projection size (None means use hidden_size).
|
||||
num_experts_per_tok: Top-k routing parameter.
|
||||
routed_scaling_factor: Scaling factor for routed expert outputs.
|
||||
norm_topk_prob: Whether to normalize top-k probabilities.
|
||||
use_bias: Global bias setting.
|
||||
initializer_range: Standard deviation for weight initialization.
|
||||
layer_norm_epsilon: Epsilon for layer normalization.
|
||||
residual_in_fp32: Whether to keep residuals in fp32.
|
||||
rescale_prenorm_residual: Whether to rescale pre-norm residuals.
|
||||
load_balance_coeff: Auxiliary-loss-free load balancing coefficient.
|
||||
"""
|
||||
|
||||
model_type = "nemotron_h"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
PATTERN_MAP = {"M": "mamba", "E": "moe", "*": "attention"}
|
||||
REVERSE_PATTERN_MAP = {"mamba": "M", "moe": "E", "attention": "*"}
|
||||
PATTERN_TO_LAYER_TYPE = {
|
||||
"M": "mamba",
|
||||
"E": "moe",
|
||||
"*": "attention",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
# General
|
||||
vocab_size=131072,
|
||||
hidden_size=4096,
|
||||
layers_block_type=None,
|
||||
num_hidden_layers=None,
|
||||
tie_word_embeddings=False,
|
||||
pad_token_id=0,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
# Attention
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=8,
|
||||
head_dim=128,
|
||||
max_position_embeddings=4096,
|
||||
attention_bias=False,
|
||||
# MLP
|
||||
intermediate_size=21504,
|
||||
mlp_hidden_act="relu2",
|
||||
mlp_bias=False,
|
||||
# Mamba
|
||||
use_mamba_kernels=True,
|
||||
ssm_state_size=128,
|
||||
mamba_num_heads=128,
|
||||
mamba_n_groups=8,
|
||||
mamba_head_dim=64,
|
||||
mamba_d_conv=4,
|
||||
mamba_expand=2,
|
||||
mamba_hidden_act="silu",
|
||||
mamba_dt_min=0.001,
|
||||
mamba_dt_max=0.1,
|
||||
mamba_dt_limit=(0.0, float("inf")),
|
||||
mamba_dt_init_floor=1e-4,
|
||||
mamba_conv_bias=True,
|
||||
mamba_proj_bias=False,
|
||||
mamba_chunk_size=128,
|
||||
# MoE
|
||||
n_routed_experts=8,
|
||||
n_shared_experts=1,
|
||||
moe_intermediate_size=7688,
|
||||
moe_shared_expert_intermediate_size=7688,
|
||||
moe_latent_size=None,
|
||||
num_experts_per_tok=2,
|
||||
routed_scaling_factor=1.0,
|
||||
norm_topk_prob=True,
|
||||
# General training
|
||||
use_bias=False,
|
||||
initializer_range=0.02,
|
||||
layer_norm_epsilon=1e-5,
|
||||
residual_in_fp32=False,
|
||||
rescale_prenorm_residual=True,
|
||||
# PrimeRL training features
|
||||
load_balance_coeff=None,
|
||||
# RoPE
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
vocab_size: int = 131072,
|
||||
hidden_size: int = 4096,
|
||||
num_hidden_layers: int | None = None,
|
||||
hybrid_override_pattern: str | None = None,
|
||||
layers_block_type: list[str] | None = None,
|
||||
num_attention_heads: int = 32,
|
||||
num_key_value_heads: int = 8,
|
||||
head_dim: int = 128,
|
||||
max_position_embeddings: int = 4096,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
intermediate_size: int = 21504,
|
||||
mlp_hidden_act: str = "relu2",
|
||||
mlp_bias: bool = False,
|
||||
ssm_state_size: int = 128,
|
||||
mamba_num_heads: int = 128,
|
||||
mamba_head_dim: int = 64,
|
||||
mamba_hidden_act: str = "silu",
|
||||
n_groups: int = 8,
|
||||
conv_kernel: int = 4,
|
||||
expand: int = 2,
|
||||
time_step_min: float = 0.001,
|
||||
time_step_max: float = 0.1,
|
||||
time_step_limit: tuple[float, float] | list[float] | None = (0.0, float("inf")),
|
||||
time_step_floor: float = 1e-4,
|
||||
use_conv_bias: bool = True,
|
||||
chunk_size: int = 128,
|
||||
mamba_proj_bias: bool = False,
|
||||
n_routed_experts: int = 8,
|
||||
n_shared_experts: int = 1,
|
||||
moe_intermediate_size: int = 7688,
|
||||
moe_shared_expert_intermediate_size: int = 7688,
|
||||
moe_latent_size: int | None = None,
|
||||
moe_shared_expert_overlap: bool = True,
|
||||
num_experts_per_tok: int = 2,
|
||||
routed_scaling_factor: float = 1.0,
|
||||
n_group: int = 1,
|
||||
topk_group: int = 1,
|
||||
norm_topk_prob: bool = True,
|
||||
use_bias: bool = False,
|
||||
initializer_range: float = 0.02,
|
||||
layer_norm_epsilon: float = 1e-5,
|
||||
residual_in_fp32: bool = False,
|
||||
hidden_dropout: float = 0.0,
|
||||
rescale_prenorm_residual: bool = True,
|
||||
load_balance_coeff: float | None = None,
|
||||
tie_word_embeddings: bool = False,
|
||||
pad_token_id: int | None = 0,
|
||||
bos_token_id: int | None = 1,
|
||||
eos_token_id: int | list[int] | None = 2,
|
||||
**kwargs,
|
||||
):
|
||||
# Handle hybrid_override_pattern for backward compatibility
|
||||
if "hybrid_override_pattern" in kwargs:
|
||||
pattern = kwargs.pop("hybrid_override_pattern")
|
||||
if layers_block_type is None:
|
||||
layers_block_type = [self.PATTERN_MAP[c] for c in pattern]
|
||||
|
||||
) -> None:
|
||||
if layers_block_type is None:
|
||||
layers_block_type = ["mamba", "moe", "attention", "moe"]
|
||||
|
||||
pattern = hybrid_override_pattern or "ME*E"
|
||||
layers_block_type = [self.PATTERN_TO_LAYER_TYPE[token] for token in pattern]
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.layers_block_type = layers_block_type
|
||||
|
||||
# Attention config
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.attention_bias = attention_bias
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
# MLP config
|
||||
self.intermediate_size = intermediate_size
|
||||
self.mlp_hidden_act = mlp_hidden_act
|
||||
self.mlp_bias = mlp_bias
|
||||
|
||||
# Mamba config - stored with HF-compatible attribute names used by NemotronHMamba2Mixer
|
||||
self.use_mamba_kernels = use_mamba_kernels
|
||||
self.ssm_state_size = ssm_state_size
|
||||
self.mamba_num_heads = mamba_num_heads
|
||||
self.n_groups = mamba_n_groups
|
||||
self.mamba_head_dim = mamba_head_dim
|
||||
self.conv_kernel = mamba_d_conv
|
||||
self.expand = mamba_expand
|
||||
self.mamba_hidden_act = mamba_hidden_act
|
||||
self.time_step_min = mamba_dt_min
|
||||
self.time_step_max = mamba_dt_max
|
||||
self.time_step_limit = mamba_dt_limit
|
||||
self.time_step_floor = mamba_dt_init_floor
|
||||
self.use_conv_bias = mamba_conv_bias
|
||||
self.n_groups = n_groups
|
||||
self.conv_kernel = conv_kernel
|
||||
self.expand = expand
|
||||
self.time_step_min = time_step_min
|
||||
self.time_step_max = time_step_max
|
||||
self.time_step_limit = time_step_limit
|
||||
self.time_step_floor = time_step_floor
|
||||
self.use_conv_bias = use_conv_bias
|
||||
self.chunk_size = chunk_size
|
||||
self.mamba_proj_bias = mamba_proj_bias
|
||||
self.chunk_size = mamba_chunk_size
|
||||
|
||||
# Zamba2MambaMixer compat aliases (read by parent __init__ before NemotronHMamba2Mixer overrides).
|
||||
# mamba_expand must give the correct intermediate_size = mamba_num_heads * mamba_head_dim
|
||||
# when Zamba2 computes int(mamba_expand * hidden_size); the config's raw "expand" field
|
||||
# does not satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
|
||||
self.mamba_d_state = ssm_state_size
|
||||
self.mamba_d_conv = mamba_d_conv
|
||||
self.mamba_expand = (mamba_num_heads * mamba_head_dim) / hidden_size
|
||||
self.mamba_ngroups = mamba_n_groups
|
||||
self.mamba_headdim = mamba_head_dim
|
||||
self.n_mamba_heads = mamba_num_heads
|
||||
self.use_mem_eff_path = True
|
||||
self.add_bias_linear = use_bias
|
||||
|
||||
# MoE config
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
|
||||
self.moe_latent_size = moe_latent_size
|
||||
self.moe_shared_expert_overlap = moe_shared_expert_overlap
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
|
||||
# General training config
|
||||
self.use_bias = use_bias
|
||||
self.initializer_range = initializer_range
|
||||
self.layer_norm_epsilon = layer_norm_epsilon
|
||||
self.residual_in_fp32 = residual_in_fp32
|
||||
self.hidden_dropout = hidden_dropout
|
||||
self.rescale_prenorm_residual = rescale_prenorm_residual
|
||||
|
||||
# PrimeRL training features
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def layer_types(self) -> list[str]:
|
||||
return self.layers_block_type
|
||||
|
||||
@property
|
||||
def num_hidden_layers(self) -> int:
|
||||
return len(self.layers_block_type)
|
||||
|
||||
@num_hidden_layers.setter
|
||||
def num_hidden_layers(self, value):
|
||||
if value is not None and value < len(self.layers_block_type):
|
||||
self.layers_block_type = self.layers_block_type[:value]
|
||||
def num_hidden_layers(self, value: int | None) -> None:
|
||||
if value is None or not hasattr(self, "layers_block_type"):
|
||||
return
|
||||
self.layers_block_type = self.layers_block_type[:value]
|
||||
|
||||
|
||||
__all__ = ["NemotronHConfig"]
|
||||
|
||||
@@ -1,100 +1,55 @@
|
||||
"""Declarative HF<->prime conversion chain for NemotronH.
|
||||
from torch import Tensor
|
||||
|
||||
NemotronH is the most involved conversion: a unified HF ``mixer`` namespace is
|
||||
split into prime's ``mamba`` / ``self_attn`` / ``mlp`` by layer type, the
|
||||
checkpoint uses a ``backbone.`` prefix, and the MoE router bias is shifted by
|
||||
its per-tensor min on the way in (and intentionally *not* restored on the way
|
||||
out — a lossy roundtrip the chain reproduces via a :class:`MapValue` whose
|
||||
backward is the identity). Experts are up/down only, with no gate projection.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import (
|
||||
Conditional,
|
||||
ConvOp,
|
||||
Drop,
|
||||
MapValue,
|
||||
PrefixRename,
|
||||
Rename,
|
||||
Stack,
|
||||
key_present,
|
||||
)
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, PrefixRename, Rename, Stack
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
|
||||
|
||||
def _moe_layer_ops(prefix: str) -> list[ConvOp]:
|
||||
return [
|
||||
# Router gate and selection bias.
|
||||
# plus the load-balancing bias which is shifted by its min on the way in
|
||||
# and not undone on the way out (MapValue backward = identity).
|
||||
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
|
||||
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.selection_bias"),
|
||||
MapValue(
|
||||
f"{prefix}.mlp.router.selection_bias",
|
||||
forward=lambda x: x - x.min(),
|
||||
backward=lambda x: x,
|
||||
),
|
||||
# Experts are up/down only. HF is either per-expert weights or
|
||||
# a 3-D fused-at-experts-level up_proj/down_proj. Backward always emits
|
||||
# per-expert (the predicate's HF key is absent in prime -> else branch).
|
||||
Conditional(
|
||||
predicate=key_present(f"{prefix}.mixer.experts.up_proj"),
|
||||
then=[
|
||||
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.up_proj"),
|
||||
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.down_proj"),
|
||||
],
|
||||
else_=[
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.up_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
|
||||
),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.down_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
|
||||
),
|
||||
],
|
||||
),
|
||||
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
|
||||
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
|
||||
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
|
||||
]
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return "backbone.embeddings.weight" in state_dict or any(".mixer." in name for name in state_dict)
|
||||
|
||||
|
||||
def _layer_op(prefix: str) -> ConvOp:
|
||||
"""One uniform op for any layer: detect its type from a signature key and
|
||||
dispatch. No ``layers_block_type`` needed — the unified HF ``mixer.``
|
||||
namespace is disambiguated by which sub-key is present (and, on the way
|
||||
back, by which prime namespace is present, so the predicates work both
|
||||
directions). Mamba/attention keep a bulk ``PrefixRename`` (robust to params
|
||||
we didn't enumerate); MoE needs its specific ops."""
|
||||
is_attention = lambda sd: ( # noqa: E731
|
||||
f"{prefix}.mixer.q_proj.weight" in sd or f"{prefix}.self_attn.q_proj.weight" in sd
|
||||
)
|
||||
is_moe = lambda sd: ( # noqa: E731
|
||||
f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate.weight" in sd
|
||||
)
|
||||
return Conditional(
|
||||
is_attention,
|
||||
then=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn.")],
|
||||
else_=[
|
||||
Conditional(
|
||||
is_moe,
|
||||
then=_moe_layer_ops(prefix),
|
||||
else_=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.mamba.")],
|
||||
)
|
||||
],
|
||||
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return "model.embed_tokens.weight" in state_dict or any(
|
||||
namespace in name for name in state_dict for namespace in (".mamba.", ".self_attn.", ".mlp.router.")
|
||||
)
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
"""Uniform per-layer dispatch — no ``layers_block_type`` required."""
|
||||
def conversion_chain(config: NemotronHConfig) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = [
|
||||
# Global. Listed first so the backbone<->model swap is played LAST on the
|
||||
# way back (everything must be in model.* form before re-prefixing).
|
||||
PrefixRename("backbone.", "model."),
|
||||
Drop("mtp.", is_prefix=True),
|
||||
Rename("model.embeddings.weight", "model.embed_tokens.weight"),
|
||||
Rename("model.norm_f.weight", "model.norm.weight"),
|
||||
]
|
||||
ops.extend(_layer_op(f"model.layers.{i}") for i in range(config.num_hidden_layers))
|
||||
|
||||
for layer_idx, layer_type in enumerate(config.layer_types):
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
if layer_type == "mamba":
|
||||
ops.append(PrefixRename(f"{prefix}.mixer.", f"{prefix}.mamba."))
|
||||
elif layer_type == "attention":
|
||||
ops.append(PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn."))
|
||||
elif layer_type == "moe":
|
||||
ops.extend(
|
||||
[
|
||||
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
|
||||
Rename(
|
||||
f"{prefix}.mixer.gate.e_score_correction_bias",
|
||||
f"{prefix}.mlp.router.selection_bias",
|
||||
),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.up_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
|
||||
),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.down_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
|
||||
),
|
||||
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
|
||||
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
|
||||
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
|
||||
]
|
||||
)
|
||||
return ops
|
||||
|
||||
|
||||
__all__ = ["conversion_chain", "is_hf_state_dict", "is_prime_state_dict"]
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Nemotron-H Mamba-2 and context-parallel execution.
|
||||
|
||||
Packed training needs the convolution and state-space scan to reset at every
|
||||
document boundary. Under Ulysses context parallelism, each rank also needs the
|
||||
full sequence for its local Mamba heads because recurrent state cannot be split
|
||||
along the sequence.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
|
||||
|
||||
def sequence_to_head_parallel(
|
||||
tensor: torch.Tensor,
|
||||
process_group: dist.ProcessGroup,
|
||||
world_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Redistribute ``[B, S/world, D]`` into ``[B, S, D/world]``."""
|
||||
batch_size, local_sequence_length, feature_size = tensor.shape
|
||||
local_feature_size = feature_size // world_size
|
||||
tensor = tensor.reshape(batch_size, local_sequence_length, world_size, local_feature_size)
|
||||
tensor = tensor.permute(2, 0, 1, 3).contiguous()
|
||||
tensor = all_to_all_single_equal(tensor, process_group)
|
||||
return tensor.permute(1, 0, 2, 3).reshape(
|
||||
batch_size,
|
||||
world_size * local_sequence_length,
|
||||
local_feature_size,
|
||||
)
|
||||
|
||||
|
||||
def head_to_sequence_parallel(
|
||||
tensor: torch.Tensor,
|
||||
process_group: dist.ProcessGroup,
|
||||
world_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Redistribute ``[B, S, D/world]`` into ``[B, S/world, D]``."""
|
||||
batch_size, sequence_length, local_feature_size = tensor.shape
|
||||
local_sequence_length = sequence_length // world_size
|
||||
tensor = tensor.reshape(batch_size, world_size, local_sequence_length, local_feature_size)
|
||||
tensor = tensor.permute(1, 0, 2, 3).contiguous()
|
||||
tensor = all_to_all_single_equal(tensor, process_group)
|
||||
return tensor.permute(1, 2, 0, 3).reshape(
|
||||
batch_size,
|
||||
local_sequence_length,
|
||||
world_size * local_feature_size,
|
||||
)
|
||||
|
||||
|
||||
class GatedRMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size: int, group_size: int, eps: float) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.group_size = group_size
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
gate: torch.Tensor,
|
||||
weight: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.float() * torch.nn.functional.silu(gate.float())
|
||||
group_count = hidden_states.shape[-1] // self.group_size
|
||||
grouped_states = hidden_states.reshape(*hidden_states.shape[:-1], group_count, self.group_size)
|
||||
variance = grouped_states.square().mean(dim=-1, keepdim=True)
|
||||
hidden_states = (grouped_states * torch.rsqrt(variance + self.variance_epsilon)).flatten(-2)
|
||||
return (self.weight if weight is None else weight) * hidden_states.to(input_dtype)
|
||||
|
||||
|
||||
class NemotronHMamba2(nn.Module):
|
||||
def __init__(self, config: NemotronHConfig) -> None:
|
||||
super().__init__()
|
||||
from fla.modules.conv import causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
|
||||
|
||||
self.hidden_size = config.hidden_size
|
||||
self.state_size = config.ssm_state_size
|
||||
self.num_heads = config.mamba_num_heads
|
||||
self.head_dim = config.mamba_head_dim
|
||||
self.num_groups = config.n_groups
|
||||
self.intermediate_size = self.num_heads * self.head_dim
|
||||
self.group_state_size = self.num_groups * self.state_size
|
||||
self.conv_size = self.intermediate_size + 2 * self.group_state_size
|
||||
self.chunk_size = config.chunk_size
|
||||
self.time_step_limit = config.time_step_limit
|
||||
self.activation = config.mamba_hidden_act
|
||||
|
||||
projection_size = self.intermediate_size + self.conv_size + self.num_heads
|
||||
self.in_proj = nn.Linear(config.hidden_size, projection_size, bias=config.use_bias)
|
||||
self.conv1d = nn.Conv1d(
|
||||
self.conv_size,
|
||||
self.conv_size,
|
||||
kernel_size=config.conv_kernel,
|
||||
groups=self.conv_size,
|
||||
padding=config.conv_kernel - 1,
|
||||
bias=config.use_conv_bias,
|
||||
)
|
||||
self.dt_bias = nn.Parameter(torch.empty(self.num_heads))
|
||||
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
|
||||
self.D = nn.Parameter(torch.ones(self.num_heads, dtype=torch.float32))
|
||||
self.norm = GatedRMSNorm(
|
||||
self.intermediate_size,
|
||||
group_size=self.intermediate_size // self.num_groups,
|
||||
eps=config.layer_norm_epsilon,
|
||||
)
|
||||
self.out_proj = nn.Linear(self.intermediate_size, config.hidden_size, bias=config.use_bias)
|
||||
self.causal_conv1d = causal_conv1d
|
||||
self.prepare_sequence_ids = prepare_sequence_ids
|
||||
self.scan = mamba_chunk_scan_combined
|
||||
|
||||
time_steps = torch.exp(
|
||||
torch.rand(self.num_heads, dtype=torch.float32)
|
||||
* (math.log(config.time_step_max) - math.log(config.time_step_min))
|
||||
+ math.log(config.time_step_min)
|
||||
).clamp(min=config.time_step_floor)
|
||||
with torch.no_grad():
|
||||
self.dt_bias.copy_((time_steps + torch.log(-torch.expm1(-time_steps))).to(self.dt_bias.dtype))
|
||||
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
self.process_group = process_group
|
||||
self.context_parallel_rank = rank
|
||||
self.context_parallel_world_size = world_size
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, sequence_length, _ = hidden_states.shape
|
||||
projected_states = self.in_proj(hidden_states)
|
||||
gate, convolution_input, time_step = torch.split(
|
||||
projected_states,
|
||||
[self.intermediate_size, self.conv_size, self.num_heads],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
num_heads = self.num_heads
|
||||
num_groups = self.num_groups
|
||||
intermediate_size = self.intermediate_size
|
||||
conv_weight = self.conv1d.weight
|
||||
conv_bias = self.conv1d.bias
|
||||
state_decay = -torch.exp(self.A_log.float())
|
||||
skip = self.D
|
||||
dt_bias = self.dt_bias
|
||||
norm_weight = self.norm.weight
|
||||
|
||||
if hasattr(self, "process_group"):
|
||||
world_size = self.context_parallel_world_size
|
||||
rank = self.context_parallel_rank
|
||||
gate = sequence_to_head_parallel(gate, self.process_group, world_size)
|
||||
time_step = sequence_to_head_parallel(time_step, self.process_group, world_size)
|
||||
|
||||
recurrent_input, state_input, state_output = torch.split(
|
||||
convolution_input,
|
||||
[self.intermediate_size, self.group_state_size, self.group_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
convolution_input = torch.cat(
|
||||
[
|
||||
sequence_to_head_parallel(recurrent_input, self.process_group, world_size),
|
||||
sequence_to_head_parallel(state_input, self.process_group, world_size),
|
||||
sequence_to_head_parallel(state_output, self.process_group, world_size),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
num_heads //= world_size
|
||||
num_groups //= world_size
|
||||
intermediate_size //= world_size
|
||||
head_start = rank * num_heads
|
||||
group_start = rank * num_groups * self.state_size
|
||||
intermediate_start = rank * intermediate_size
|
||||
|
||||
state_decay = state_decay[head_start : head_start + num_heads]
|
||||
skip = skip[head_start : head_start + num_heads]
|
||||
dt_bias = dt_bias[head_start : head_start + num_heads]
|
||||
norm_weight = norm_weight[intermediate_start : intermediate_start + intermediate_size]
|
||||
|
||||
state_input_start = self.intermediate_size + group_start
|
||||
state_output_start = self.intermediate_size + self.group_state_size + group_start
|
||||
conv_weight = torch.cat(
|
||||
[
|
||||
conv_weight[intermediate_start : intermediate_start + intermediate_size],
|
||||
conv_weight[state_input_start : state_input_start + num_groups * self.state_size],
|
||||
conv_weight[state_output_start : state_output_start + num_groups * self.state_size],
|
||||
]
|
||||
)
|
||||
if conv_bias is not None:
|
||||
conv_bias = torch.cat(
|
||||
[
|
||||
conv_bias[intermediate_start : intermediate_start + intermediate_size],
|
||||
conv_bias[state_input_start : state_input_start + num_groups * self.state_size],
|
||||
conv_bias[state_output_start : state_output_start + num_groups * self.state_size],
|
||||
]
|
||||
)
|
||||
sequence_length = convolution_input.shape[1]
|
||||
|
||||
convolution_output, _ = self.causal_conv1d(
|
||||
x=convolution_input,
|
||||
weight=conv_weight.squeeze(1),
|
||||
bias=conv_bias,
|
||||
activation=self.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
local_group_state_size = num_groups * self.state_size
|
||||
hidden_states, state_input, state_output = torch.split(
|
||||
convolution_output,
|
||||
[intermediate_size, local_group_state_size, local_group_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
scan_kwargs = {}
|
||||
if self.time_step_limit is not None:
|
||||
scan_kwargs["dt_limit"] = self.time_step_limit
|
||||
hidden_states = self.scan(
|
||||
hidden_states.reshape(batch_size, sequence_length, num_heads, self.head_dim),
|
||||
time_step,
|
||||
state_decay,
|
||||
state_input.reshape(batch_size, sequence_length, num_groups, self.state_size),
|
||||
state_output.reshape(batch_size, sequence_length, num_groups, self.state_size),
|
||||
chunk_size=self.chunk_size,
|
||||
D=skip,
|
||||
z=None,
|
||||
seq_idx=self.prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0),
|
||||
return_final_states=False,
|
||||
dt_bias=dt_bias,
|
||||
dt_softplus=True,
|
||||
**scan_kwargs,
|
||||
).reshape(batch_size, sequence_length, intermediate_size)
|
||||
hidden_states = self.norm(hidden_states, gate, weight=norm_weight)
|
||||
|
||||
if hasattr(self, "process_group"):
|
||||
hidden_states = head_to_sequence_parallel(
|
||||
hidden_states,
|
||||
self.process_group,
|
||||
self.context_parallel_world_size,
|
||||
)
|
||||
return self.out_proj(hidden_states)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedRMSNorm",
|
||||
"NemotronHMamba2",
|
||||
"head_to_sequence_parallel",
|
||||
"sequence_to_head_parallel",
|
||||
]
|
||||
@@ -1,576 +1,268 @@
|
||||
"""PrimeRL implementation of NemotronH (Nemotron-3-Super-120B-A12B).
|
||||
|
||||
Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
|
||||
- Mamba-2 layers (using NemotronHMamba2Mixer from HF transformers)
|
||||
- MoE layers with non-gated experts and latent projections
|
||||
- Attention layers (using shared FlashAttention/SDPA from prime-rl)
|
||||
"""
|
||||
|
||||
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
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.models.nemotron_h.modular_nemotron_h import NemotronHMamba2Mixer
|
||||
from transformers.utils import auto_docstring, logging
|
||||
from transformers.modeling_outputs import BaseModelOutput
|
||||
|
||||
from prime_rl.trainer.models.base import CPSupport, 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.lm_head import PrimeLmOutput, VanillaOutputLinear
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
GroupedExperts,
|
||||
MoE,
|
||||
TokenChoiceTopKRouter,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import conversion_chain
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
|
||||
conversion_chain,
|
||||
is_hf_state_dict,
|
||||
is_prime_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
_patch_applied = False
|
||||
|
||||
|
||||
def _patch_mamba2_use_triton_ssd():
|
||||
"""Patch NemotronHMamba2Mixer to use mamba_ssm Triton SSD kernels.
|
||||
|
||||
The HF torch_forward computes softplus in model dtype (bf16), while vLLM's
|
||||
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 fla's Triton causal_conv1d for
|
||||
convolution. Requires mamba_ssm installed.
|
||||
"""
|
||||
global _patch_applied
|
||||
if _patch_applied:
|
||||
return
|
||||
|
||||
if not torch.cuda.is_available():
|
||||
logger.warning_once("CUDA not available; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
|
||||
return
|
||||
|
||||
try:
|
||||
from mamba_ssm.ops.triton.ssd_combined import (
|
||||
mamba_chunk_scan_combined as _mamba_chunk_scan_combined,
|
||||
)
|
||||
except ImportError:
|
||||
logger.warning_once("mamba_ssm not installed; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
|
||||
return
|
||||
|
||||
if _mamba_chunk_scan_combined is None:
|
||||
logger.warning_once("mamba_ssm not available; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
|
||||
return
|
||||
|
||||
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:
|
||||
- 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
|
||||
assert batch_size == 1, "varlen mamba expects batch_size=1 (packed)"
|
||||
groups_time_state_size = self.n_groups * self.ssm_state_size
|
||||
|
||||
# 1. Input projection (pointwise, no cross-seq mixing)
|
||||
projected_states = self.in_proj(hidden_states)
|
||||
A = -torch.exp(self.A_log.float())
|
||||
dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
|
||||
|
||||
gate, hidden_states_B_C, time_step = torch.split(
|
||||
projected_states,
|
||||
[self.intermediate_size, self.conv_dim, self.num_heads],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# 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,
|
||||
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# 3. SSM with seq_idx so state resets at sequence boundaries
|
||||
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),
|
||||
time_step,
|
||||
A,
|
||||
B.view(batch_size, seq_len, self.n_groups, -1),
|
||||
C.view(batch_size, seq_len, self.n_groups, -1),
|
||||
chunk_size=self.chunk_size,
|
||||
D=self.D,
|
||||
z=None,
|
||||
seq_idx=seq_idx,
|
||||
return_final_states=False,
|
||||
dt_bias=self.dt_bias,
|
||||
dt_softplus=True,
|
||||
**dt_limit_kwargs,
|
||||
)
|
||||
scan_output = scan_output.view(batch_size, seq_len, -1)
|
||||
scan_output = self.norm(scan_output, gate)
|
||||
return self.out_proj(scan_output)
|
||||
|
||||
def _patched_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
|
||||
if cu_seqlens is not None and cache_params is None and "cuda" in self.in_proj.weight.device.type:
|
||||
return _varlen_mamba_forward(self, hidden_states, cu_seqlens)
|
||||
if "cuda" in self.in_proj.weight.device.type:
|
||||
# Disable fused training path (needs causal_conv1d CUDA extension)
|
||||
orig = self.use_mem_eff_path
|
||||
self.use_mem_eff_path = False
|
||||
result = self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
|
||||
self.use_mem_eff_path = orig
|
||||
return result
|
||||
return self.torch_forward(hidden_states, cache_params, attention_mask)
|
||||
|
||||
NemotronHMamba2Mixer.forward = _patched_forward
|
||||
_patch_applied = True
|
||||
logger.info("Patched NemotronHMamba2Mixer: Triton SSD kernels + varlen (cu_seqlens) support")
|
||||
|
||||
|
||||
def _ensure_zamba2_compat(config: NemotronHConfig):
|
||||
"""Add Zamba2-compatible attribute aliases to NemotronHConfig.
|
||||
|
||||
The HF modular NemotronHMamba2Mixer inherits from Zamba2MambaMixer, whose
|
||||
__init__ reads Zamba2-style attribute names before the NemotronH child
|
||||
overrides them. We set the missing aliases so the parent __init__ doesn't
|
||||
crash.
|
||||
|
||||
Critically, ``mamba_expand`` must give ``mamba_num_heads * mamba_head_dim``
|
||||
when multiplied by ``hidden_size``; the config's ``expand`` field does not
|
||||
satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
|
||||
"""
|
||||
correct_intermediate = config.mamba_num_heads * config.mamba_head_dim
|
||||
correct_expand = correct_intermediate / config.hidden_size
|
||||
|
||||
aliases = {
|
||||
"mamba_d_state": config.ssm_state_size,
|
||||
"mamba_d_conv": config.conv_kernel,
|
||||
"mamba_ngroups": config.n_groups,
|
||||
"mamba_headdim": config.mamba_head_dim,
|
||||
"n_mamba_heads": config.mamba_num_heads,
|
||||
"add_bias_linear": getattr(config, "use_bias", False),
|
||||
"use_mem_eff_path": True,
|
||||
}
|
||||
for attr, value in aliases.items():
|
||||
if not hasattr(config, attr):
|
||||
setattr(config, attr, value)
|
||||
|
||||
config.mamba_expand = correct_expand
|
||||
|
||||
|
||||
class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
"""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__()
|
||||
_patch_mamba2_use_triton_ssd()
|
||||
_ensure_zamba2_compat(config)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
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,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
global_cu_seqlens = (
|
||||
cu_seqlens if cu_seqlens is not None and cu_seqlens_are_pre_shard else ULYSSES_PARAMS["cu_seqlens"]
|
||||
)
|
||||
hidden_states = mamba_cp_forward(
|
||||
self.mamba,
|
||||
hidden_states,
|
||||
self._cp_group,
|
||||
self._cp_rank,
|
||||
self._cp_world_size,
|
||||
global_cu_seqlens,
|
||||
)
|
||||
else:
|
||||
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
|
||||
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
class NemotronHMoE(MoE):
|
||||
def __init__(self, *, hidden_size: int, latent_size: int, **kwargs):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
hidden_size: int,
|
||||
latent_size: int,
|
||||
projection_bias: bool,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(**kwargs)
|
||||
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=False)
|
||||
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=False)
|
||||
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=projection_bias)
|
||||
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=projection_bias)
|
||||
|
||||
def prepare_expert_input(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc1_latent_proj(x)
|
||||
def prepare_expert_input(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc1_latent_proj(hidden_states)
|
||||
|
||||
def prepare_expert_output(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc2_latent_proj(x)
|
||||
def prepare_expert_output(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc2_latent_proj(hidden_states)
|
||||
|
||||
|
||||
class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
"""MoE layer with latent routed experts."""
|
||||
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
class NemotronHDecoderLayer(nn.Module):
|
||||
def __init__(self, config: NemotronHConfig, layer_idx: int) -> None:
|
||||
super().__init__()
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
effective_latent_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
selection_bias=True,
|
||||
topk_sorted=False,
|
||||
)
|
||||
router.fp32_gate = True
|
||||
experts = GroupedExperts(
|
||||
dim=effective_latent_dim,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
)
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_shared_expert_intermediate_size,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
)
|
||||
moe_kwargs = dict(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=shared_expert,
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
)
|
||||
if config.moe_latent_size is None:
|
||||
self.mlp = MoE(**moe_kwargs)
|
||||
else:
|
||||
self.mlp = NemotronHMoE(
|
||||
hidden_size=config.hidden_size,
|
||||
latent_size=config.moe_latent_size,
|
||||
**moe_kwargs,
|
||||
|
||||
if self.layer_type == "mamba":
|
||||
self.mamba = NemotronHMamba2(config)
|
||||
elif self.layer_type == "attention":
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](
|
||||
AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
output_bias=config.attention_bias,
|
||||
use_qk_norm=False,
|
||||
rms_norm_eps=config.layer_norm_epsilon,
|
||||
)
|
||||
)
|
||||
elif self.layer_type == "moe":
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
selection_bias=True,
|
||||
topk_sorted=False,
|
||||
)
|
||||
expert_size = config.moe_latent_size or config.hidden_size
|
||||
experts = GroupedExperts(
|
||||
dim=expert_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
bias=config.mlp_bias,
|
||||
)
|
||||
experts.init_weights(config.initializer_range)
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_shared_expert_intermediate_size,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
bias=config.mlp_bias,
|
||||
)
|
||||
moe_kwargs = {
|
||||
"router": router,
|
||||
"experts": experts,
|
||||
"shared_expert": shared_expert,
|
||||
"score_before_experts": False,
|
||||
"load_balance_coeff": config.load_balance_coeff,
|
||||
}
|
||||
if config.moe_latent_size is None:
|
||||
self.mlp = MoE(**moe_kwargs)
|
||||
else:
|
||||
self.mlp = NemotronHMoE(
|
||||
hidden_size=config.hidden_size,
|
||||
latent_size=config.moe_latent_size,
|
||||
projection_bias=config.mlp_bias,
|
||||
**moe_kwargs,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
|
||||
if self.layer_type == "mamba":
|
||||
hidden_states = self.mamba(hidden_states, cu_seqlens)
|
||||
elif self.layer_type == "attention":
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
else:
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
class NemotronHAttentionLayer(GradientCheckpointingLayer):
|
||||
"""Attention layer: norm -> FlashAttention/SDPA -> residual."""
|
||||
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
super().__init__()
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
attn_config = AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
use_qk_norm=False,
|
||||
rms_norm_eps=config.layer_norm_epsilon,
|
||||
)
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
|
||||
self.mlp = None # No MoE in this layer type
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
BLOCK_TYPE_MAP = {
|
||||
"mamba": NemotronHMambaLayer,
|
||||
"moe": NemotronHMoELayer,
|
||||
"attention": NemotronHAttentionLayer,
|
||||
}
|
||||
|
||||
|
||||
def _build_layer(config: NemotronHConfig, layer_idx: int):
|
||||
layer_type = config.layers_block_type[layer_idx]
|
||||
cls = BLOCK_TYPE_MAP[layer_type]
|
||||
if layer_type == "mamba":
|
||||
return cls(config, layer_idx=layer_idx)
|
||||
return cls(config)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: NemotronHConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["NemotronHMambaLayer", "NemotronHMoELayer", "NemotronHAttentionLayer"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = False
|
||||
_can_compile_fullgraph = False
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset({"ulysses"}),
|
||||
"ring CP is a softmax-attention algorithm and cannot run this model's Mamba layers, "
|
||||
"whereas ulysses' all-to-all on Q/K/V leaves the SSM kernel unchanged",
|
||||
"Mamba layers require Ulysses to reconstruct full sequences while sharding Mamba heads",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.selection_bias"))
|
||||
|
||||
def _init_weights(self, module):
|
||||
std = self.config.initializer_range
|
||||
if isinstance(module, nn.Linear):
|
||||
module.weight.data.normal_(mean=0.0, std=std)
|
||||
if module.bias is not None:
|
||||
module.bias.data.zero_()
|
||||
elif isinstance(module, nn.Embedding):
|
||||
module.weight.data.normal_(mean=0.0, std=std)
|
||||
if module.padding_idx is not None:
|
||||
module.weight.data[module.padding_idx].zero_()
|
||||
elif isinstance(module, (GroupedExperts, TokenChoiceTopKRouter)):
|
||||
module.init_weights(std)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mixer." in name for name in state_dict) or any("backbone." in name for name in state_dict)
|
||||
return is_hf_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
"mamba." in name
|
||||
or "mlp.experts.up_proj" in name
|
||||
or "self_attn." in name
|
||||
or "model.embed_tokens." in name
|
||||
or "model.norm." in name
|
||||
for name in state_dict
|
||||
)
|
||||
return is_prime_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
def conversion_chain(cls, config: NemotronHConfig):
|
||||
return conversion_chain(config)
|
||||
|
||||
@classmethod
|
||||
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
# HF NemotronH unifies attention/mlp under a single `mixer` attribute per layer.
|
||||
import re
|
||||
|
||||
rename = [
|
||||
(re.compile(r"(\.layers\.\d+)\.mlp\."), r"\1.mixer."),
|
||||
(re.compile(r"(\.layers\.\d+)\.self_attn\."), r"\1.mixer."),
|
||||
]
|
||||
for old_key in list(state_dict.keys()):
|
||||
new_key = old_key
|
||||
for pattern, repl in rename:
|
||||
new_key = pattern.sub(repl, new_key)
|
||||
if new_key != old_key:
|
||||
state_dict[new_key] = state_dict.pop(old_key)
|
||||
for name in list(state_dict):
|
||||
hf_name = re.sub(r"(\.layers\.\d+)\.(?:self_attn|mlp|mamba)\.", r"\1.mixer.", name)
|
||||
if hf_name != name:
|
||||
state_dict[hf_name] = state_dict.pop(name)
|
||||
return state_dict
|
||||
|
||||
|
||||
class NemotronHModel(NemotronHPreTrainedModel):
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
def __init__(self, config: NemotronHConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList([_build_layer(config, i) for i in range(config.num_hidden_layers)])
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
||||
self.layers = nn.ModuleList(
|
||||
NemotronHDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)
|
||||
)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
|
||||
# NemotronH does not use RoPE - position information comes from Mamba layers
|
||||
self.rotary_emb = None
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
for module in self.layers.modules():
|
||||
if isinstance(module, NemotronHMamba2):
|
||||
module.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
self.gradient_checkpointing = False
|
||||
self.post_init()
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
for layer in self.layers.modules():
|
||||
if isinstance(layer, NemotronHMambaLayer):
|
||||
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
input_ids: torch.LongTensor,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
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, indexed by global layer index. Only used for router replay; slots
|
||||
for non-MoE (Mamba/attention) layers are ignored.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
) -> BaseModelOutput:
|
||||
hidden_states = self.embed_tokens(input_ids)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
seq_lens.to(device=hidden_states.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else hidden_states.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids) if self.rotary_emb is not None else None
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
# routed_experts is indexed by global layer index; non-MoE layers ignore it.
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
cu_seqlens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
cu_seqlens,
|
||||
max_seqlen,
|
||||
routed_experts=layer_routed_experts,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
return BaseModelOutput(last_hidden_state=self.norm(hidden_states))
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
class NemotronHForCausalLM(NemotronHPreTrainedModel):
|
||||
def __init__(self, config: NemotronHConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.model = NemotronHModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.post_init()
|
||||
self.lm_head = VanillaOutputLinear(config.hidden_size, config.vocab_size)
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
self.model.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: int = 0,
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
input_ids: torch.LongTensor,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
temperature: torch.Tensor | None = None,
|
||||
sampling_mask: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs,
|
||||
) -> PrimeLmOutput:
|
||||
if position_ids is None:
|
||||
if inputs_embeds is not None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
else:
|
||||
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
|
||||
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
outputs.last_hidden_state,
|
||||
labels,
|
||||
temperature=temperature,
|
||||
sampling_mask=sampling_mask,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self):
|
||||
pass
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
for module in self.modules():
|
||||
if isinstance(module, MoE):
|
||||
module.tokens_per_expert.zero_()
|
||||
module.routing_confidence_sum.zero_()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"NemotronHDecoderLayer",
|
||||
"NemotronHForCausalLM",
|
||||
"NemotronHMoE",
|
||||
"NemotronHModel",
|
||||
"NemotronHPreTrainedModel",
|
||||
]
|
||||
|
||||
@@ -1,85 +1,50 @@
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers import cp_mamba
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig
|
||||
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
class _FakeMixer(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.intermediate_size = 1
|
||||
self.conv_dim = 3
|
||||
self.num_heads = 1
|
||||
self.n_groups = 1
|
||||
self.ssm_state_size = 1
|
||||
self.head_dim = 1
|
||||
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]]))
|
||||
self.A_log = torch.nn.Parameter(torch.zeros(1))
|
||||
self.D = torch.nn.Parameter(torch.ones(1))
|
||||
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, device="cuda"), variance_epsilon=self.variance_epsilon, group_size=1
|
||||
)
|
||||
self.out_proj = torch.nn.Identity()
|
||||
@pytest.fixture
|
||||
def mamba():
|
||||
torch.manual_seed(0)
|
||||
config = NemotronHConfig(
|
||||
hidden_size=256,
|
||||
hybrid_override_pattern="M",
|
||||
mamba_num_heads=8,
|
||||
mamba_head_dim=64,
|
||||
n_groups=2,
|
||||
ssm_state_size=64,
|
||||
conv_kernel=4,
|
||||
chunk_size=64,
|
||||
)
|
||||
return NemotronHMamba2(config).cuda().to(torch.bfloat16)
|
||||
|
||||
|
||||
def _install_fake_scan(monkeypatch, seen_seq_idx: list[torch.Tensor]) -> None:
|
||||
def fake_scan(hidden_states, time_step, A, B, C, **kwargs):
|
||||
assert kwargs["return_final_states"] is False
|
||||
seen_seq_idx.append(kwargs["seq_idx"].clone())
|
||||
return hidden_states
|
||||
def test_mamba_resets_conv_and_scan_at_packed_boundaries(mamba):
|
||||
cu_seqlens = torch.tensor([0, 3, 8], dtype=torch.int32, device="cuda")
|
||||
first = torch.randn(1, 8, 256, device="cuda", dtype=torch.bfloat16, requires_grad=True)
|
||||
second = first.detach().clone()
|
||||
second[:, :3] *= 20
|
||||
|
||||
ssd_combined = types.ModuleType("mamba_ssm.ops.triton.ssd_combined")
|
||||
ssd_combined.mamba_chunk_scan_combined = fake_scan
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm", types.ModuleType("mamba_ssm"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops", types.ModuleType("mamba_ssm.ops"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton", types.ModuleType("mamba_ssm.ops.triton"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton.ssd_combined", ssd_combined)
|
||||
first_output = mamba(first, cu_seqlens)
|
||||
second_output = mamba(second, cu_seqlens)
|
||||
torch.testing.assert_close(first_output[:, 3:], second_output[:, 3:])
|
||||
first_output[:, 3:].float().square().sum().backward()
|
||||
assert torch.count_nonzero(first.grad[:, :3]) == 0
|
||||
|
||||
|
||||
def test_mamba_cp_forward_resets_conv_and_scan_at_packed_boundaries(monkeypatch):
|
||||
"""Changing document A must not change document B under Ulysses CP."""
|
||||
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)
|
||||
|
||||
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, 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_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)
|
||||
|
||||
def test_mamba_builds_sequence_ids_for_uneven_packs(mamba):
|
||||
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"))
|
||||
hidden_states = torch.randn(1, 6, 256, device="cuda", dtype=torch.bfloat16)
|
||||
packed = mamba(hidden_states, cu_seqlens)
|
||||
separate = torch.cat(
|
||||
[
|
||||
mamba(hidden_states[:, start:end], torch.tensor([0, end - start], dtype=torch.int32, device="cuda"))
|
||||
for start, end in [(0, 1), (1, 4), (4, 6)]
|
||||
],
|
||||
dim=1,
|
||||
)
|
||||
torch.testing.assert_close(packed, separate, rtol=1e-2, atol=1e-2)
|
||||
|
||||
@@ -2,24 +2,17 @@ from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers.models.nemotron_h.configuration_nemotron_h import NemotronHConfig as HFNemotronHConfig
|
||||
from transformers.models.nemotron_h.modeling_nemotron_h import (
|
||||
NemotronHAttention,
|
||||
)
|
||||
from transformers.models.nemotron_h.modeling_nemotron_h import (
|
||||
NemotronHForCausalLM as HFNemotronHForCausalLM,
|
||||
)
|
||||
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h.modeling_nemotron_h import NemotronHAttentionLayer, NemotronHMambaLayer
|
||||
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
|
||||
from prime_rl.utils.cp import setup_model_cp
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
# Shared small-model hyperparams (satisfy mamba_expand * hidden_size == mamba_num_heads * mamba_head_dim)
|
||||
_BASE = dict(
|
||||
attn_implementation="flash_attention_2",
|
||||
vocab_size=256,
|
||||
hidden_size=256,
|
||||
num_attention_heads=4,
|
||||
@@ -27,13 +20,13 @@ _BASE = dict(
|
||||
head_dim=64,
|
||||
max_position_embeddings=128,
|
||||
intermediate_size=512,
|
||||
mamba_expand=2,
|
||||
expand=2,
|
||||
mamba_num_heads=8,
|
||||
mamba_head_dim=64,
|
||||
ssm_state_size=64,
|
||||
mamba_n_groups=1,
|
||||
mamba_d_conv=4,
|
||||
mamba_chunk_size=64,
|
||||
n_groups=1,
|
||||
conv_kernel=4,
|
||||
chunk_size=64,
|
||||
n_routed_experts=4,
|
||||
n_shared_experts=1,
|
||||
moe_intermediate_size=256,
|
||||
@@ -49,66 +42,11 @@ def _seq_lens(input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return torch.tensor([input_ids.shape[1]], device=input_ids.device)
|
||||
|
||||
|
||||
def get_model_pairs():
|
||||
"""Create an HF model and a PrimeRL model with shared weights."""
|
||||
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
prime_config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
prime_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
hf_model = HFNemotronHForCausalLM._from_config(hf_config)
|
||||
prime_model = NemotronHForCausalLM._from_config(prime_config)
|
||||
|
||||
with torch.no_grad():
|
||||
state_dict = hf_model.state_dict()
|
||||
prime_state_keys = prime_model.state_dict().keys()
|
||||
prime_model.convert_to_prime(state_dict)
|
||||
prime_model.load_state_dict(state_dict)
|
||||
|
||||
inject_prime_lm_head(prime_model, chunk_size=None)
|
||||
assert set(prime_state_keys) - set(state_dict.keys()) == set()
|
||||
return hf_model, prime_model
|
||||
|
||||
|
||||
def test_nemotron_h_mamba_moe_only():
|
||||
"""Test Mamba and MoE layers produce identical outputs (attention bypassed)."""
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
# Bypass attention layers in both models so only Mamba+MoE are exercised
|
||||
for layer in hf_model.model.layers:
|
||||
if isinstance(layer.mixer, NemotronHAttention):
|
||||
layer.forward = lambda hidden_states, **kwargs: hidden_states
|
||||
|
||||
for layer in prime_model.model.layers:
|
||||
if isinstance(layer, NemotronHAttentionLayer):
|
||||
layer.forward = lambda hidden_states, **kwargs: hidden_states
|
||||
|
||||
torch.manual_seed(42)
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
input_ids = torch.randint(0, 256, (1, 32))
|
||||
position_ids = torch.arange(0, 32).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embeddings.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=1000), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_nemotron_h_reverse():
|
||||
"""PrimeRL weights convert back to the source checkpoint layout."""
|
||||
_, prime_model = get_model_pairs()
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
with torch.device("meta"):
|
||||
prime_model = NemotronHForCausalLM(config)
|
||||
converted = prime_model.convert_to_hf(dict(prime_model.state_dict()))
|
||||
|
||||
assert prime_model.is_hf_state_dict(converted)
|
||||
@@ -116,34 +54,14 @@ def test_nemotron_h_reverse():
|
||||
assert not any("mlp.experts.up_proj" in name for name in converted)
|
||||
|
||||
|
||||
def test_nemotron_h():
|
||||
"""Test full model (Mamba + MoE + Attention) produces close outputs."""
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
input_ids = torch.randint(0, 256, (1, 32))
|
||||
position_ids = torch.arange(0, 32).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
|
||||
# Slightly larger tolerance due to different SDPA attention implementations
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
|
||||
|
||||
def test_nemotron_h_backward():
|
||||
"""Verify all parameters receive non-zero gradients."""
|
||||
prime_config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
prime_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM(prime_config)
|
||||
inject_prime_lm_head(model)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 16), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 16), device="cuda")
|
||||
output = model(input_ids, seq_lens=_seq_lens(input_ids))
|
||||
output["logits"].sum().backward()
|
||||
|
||||
@@ -158,10 +76,7 @@ def test_nemotron_h_backward():
|
||||
|
||||
def test_nemotron_h_weight_conversion_roundtrip():
|
||||
"""Verify PrimeRL -> HF -> PrimeRL conversion preserves all weights."""
|
||||
prime_config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
prime_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
model = NemotronHForCausalLM(prime_config).to("cuda")
|
||||
original_sd = {k: v.clone() for k, v in model.state_dict().items()}
|
||||
|
||||
@@ -176,46 +91,49 @@ def test_nemotron_h_weight_conversion_roundtrip():
|
||||
assert torch.equal(original_sd[key], sd[key]), f"Value mismatch for {key}"
|
||||
|
||||
|
||||
def test_nemotron_h_hybrid_override_pattern():
|
||||
"""Verify hybrid_override_pattern correctly maps to layers_block_type."""
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
assert config.layers_block_type == ["mamba", "moe", "attention", "moe"]
|
||||
assert config.num_hidden_layers == 4
|
||||
def test_nemotron_h_layer_types():
|
||||
expected = ["mamba", "moe", "attention", "moe"]
|
||||
pattern_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
list_config = NemotronHConfig(**_BASE, layers_block_type=expected)
|
||||
|
||||
assert pattern_config.layer_types == expected
|
||||
assert list_config.layer_types == expected
|
||||
assert pattern_config.num_hidden_layers == list_config.num_hidden_layers == 4
|
||||
|
||||
|
||||
def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
|
||||
config = NemotronHConfig(
|
||||
**(_BASE | {"mamba_n_groups": 2}),
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
**(_BASE | {"n_groups": 2}),
|
||||
hybrid_override_pattern="ME*E",
|
||||
)
|
||||
with torch.device("meta"):
|
||||
model = NemotronHForCausalLM(config)
|
||||
|
||||
mamba_layer = model.model.layers[0]
|
||||
assert isinstance(mamba_layer, NemotronHMambaLayer)
|
||||
assert isinstance(mamba_layer.mamba, NemotronHMamba2)
|
||||
model.model.layers[0] = torch.nn.Sequential(mamba_layer)
|
||||
|
||||
cp_group = MagicMock()
|
||||
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
|
||||
|
||||
assert mamba_layer._cp_group is cp_group
|
||||
assert mamba_layer._cp_rank == 1
|
||||
assert mamba_layer._cp_world_size == 2
|
||||
assert mamba_layer.mamba.process_group is cp_group
|
||||
assert mamba_layer.mamba.context_parallel_rank == 1
|
||||
assert mamba_layer.mamba.context_parallel_world_size == 2
|
||||
|
||||
|
||||
def test_nemotron_h_no_latent_projection():
|
||||
"""Verify model works without latent projections (moe_latent_size=None)."""
|
||||
prime_config = NemotronHConfig(
|
||||
**{**_BASE, "moe_latent_size": None},
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
hybrid_override_pattern="ME*E",
|
||||
)
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM(prime_config)
|
||||
inject_prime_lm_head(model)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 16), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 16), device="cuda")
|
||||
output = model(input_ids, seq_lens=_seq_lens(input_ids))
|
||||
assert output["logits"].shape == (2, 16, 256)
|
||||
assert output["logits"].shape == (1, 16, 256)
|
||||
|
||||
output["logits"].sum().backward()
|
||||
for name, p in model.named_parameters():
|
||||
|
||||
@@ -29,13 +29,13 @@ _BASE = dict(
|
||||
head_dim=64,
|
||||
max_position_embeddings=128,
|
||||
intermediate_size=512,
|
||||
mamba_expand=2,
|
||||
expand=2,
|
||||
mamba_num_heads=8,
|
||||
mamba_head_dim=64,
|
||||
ssm_state_size=64,
|
||||
mamba_n_groups=1,
|
||||
mamba_d_conv=4,
|
||||
mamba_chunk_size=64,
|
||||
n_groups=1,
|
||||
conv_kernel=4,
|
||||
chunk_size=64,
|
||||
n_routed_experts=4,
|
||||
n_shared_experts=1,
|
||||
moe_intermediate_size=256,
|
||||
@@ -48,13 +48,10 @@ _BASE = dict(
|
||||
|
||||
|
||||
def _make_model(device="cuda"):
|
||||
config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
with torch.device(device), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM._from_config(config)
|
||||
model = NemotronHForCausalLM(config)
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
return model
|
||||
|
||||
@@ -88,7 +85,7 @@ def test_kl_zero_when_identical():
|
||||
"""Two identical models should have zero KL mismatch."""
|
||||
model = _make_model()
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
|
||||
logprobs = _get_logprobs_vanilla(model, input_ids)
|
||||
|
||||
loss_mask = torch.ones(32, dtype=torch.bool, device="cuda")
|
||||
@@ -121,7 +118,7 @@ def test_kl_positive_after_perturbation():
|
||||
policy_model.load_state_dict(ref_model.state_dict())
|
||||
_perturb_model(policy_model, scale=0.05)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
|
||||
|
||||
ref_logprobs = _get_logprobs_vanilla(ref_model, input_ids)
|
||||
policy_logprobs = _get_logprobs_vanilla(policy_model, input_ids)
|
||||
@@ -182,14 +179,11 @@ def test_kl_increases_with_larger_perturbation():
|
||||
|
||||
def test_kl_with_fused_lm_head():
|
||||
"""FusedOutputLinear should produce same logprobs as VanillaOutputLinear."""
|
||||
config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM._from_config(config)
|
||||
model = NemotronHForCausalLM(config)
|
||||
|
||||
# Get logits from vanilla head
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
@@ -296,7 +290,7 @@ def test_kl_mismatch_formula_sanity():
|
||||
ref_model.load_state_dict(model.state_dict())
|
||||
_perturb_model(model, scale=0.1)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
|
||||
|
||||
trainer_logprobs = _get_logprobs_vanilla(model, input_ids)
|
||||
inference_logprobs = _get_logprobs_vanilla(ref_model, input_ids)
|
||||
|
||||
@@ -142,6 +142,7 @@ overrides = [
|
||||
{ name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'", specifier = ">=9.15" },
|
||||
{ name = "nvidia-cutlass-dsl", specifier = "==4.6.2" },
|
||||
{ name = "openenv-core" },
|
||||
{ name = "tilelang", specifier = "==0.1.12" },
|
||||
{ name = "torch", marker = "sys_platform != 'linux'", specifier = ">=2.13.0" },
|
||||
{ name = "torch", marker = "sys_platform == 'linux'", specifier = ">=2.13.0", index = "https://download.pytorch.org/whl/cu130" },
|
||||
{ name = "transformers", specifier = "==5.6.2" },
|
||||
@@ -396,6 +397,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6d/3d/4b9226cd45aa800a6904603dda9b323d728f3c3869952a673f3483b78b19/apache_tvm_ffi-0.1.11.tar.gz", hash = "sha256:153cd2c5a9717804cb0bcd9b2709f22a1e5f80ed05b5a490faf5949b136eedba", size = 2798354, upload-time = "2026-05-04T17:48:43.852Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/05/9d/0f81ca556e5836b3ca64818cdae3f47dc7822bd35d22ddef7a54106d801d/apache_tvm_ffi-0.1.11-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:6ae51cc7df415b5f373a9df4baa1165a65608e519bea81e7dd23428f00eeb689", size = 2418793, upload-time = "2026-05-04T17:47:57.879Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/a9/f48e5dd4ae1f6f0c5ffac259c0a9531b7d6a7c0a4c45bc2229d55de6adf8/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:da2c8d07fdc737d1ba75f4de25c29f156905b9dc980f1da90c395b4db525f522", size = 2605176, upload-time = "2026-05-04T17:47:59.676Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/99/2848df4e8ed5bf51df1d286d1718510584fa61e88adbc9c5b23d71b38f7c/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:78aa1857b04a2ea718317041ab3f01288b3d496e6036eb1b99ebdc9da0fdaef5", size = 2725887, upload-time = "2026-05-04T17:48:01.381Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7d/80/963c991934a4eb0fa0c0178f51963333fe14a96b732009da642b6bf6b42e/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a8b845c8dff498fb981c1dda36c954549204191b485a385845e604966594d0b2", size = 2513121, upload-time = "2026-05-04T17:48:03.43Z" },
|
||||
@@ -3311,18 +3313,20 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "mamba-ssm"
|
||||
version = "2.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
version = "2.3.2.post1"
|
||||
source = { git = "https://github.com/state-spaces/mamba?rev=f577286#f577286d052741c35d39cd43bdc3fad27120f22c" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
{ name = "einops" },
|
||||
{ name = "ninja" },
|
||||
{ name = "packaging" },
|
||||
{ name = "quack-kernels" },
|
||||
{ name = "setuptools" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "transformers" },
|
||||
{ name = "triton" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/34/67/ec89aa703da194a813e35d2ea2de8f74a7ce6991a120a29f3a0c5e30d4b9/mamba_ssm-2.3.1.tar.gz", hash = "sha256:4d529477ad94753962216d583fc8f1c127c717b7d7c875d6bbb9376366d0d761", size = 121707, upload-time = "2026-03-10T09:27:34.798Z" }
|
||||
|
||||
[[package]]
|
||||
name = "markdown"
|
||||
@@ -3584,6 +3588,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/4a/c27b42ed9b1c7d13d9ba8b6905dece787d6259152f2309338aed29b2447b/ml_dtypes-0.5.4.tar.gz", hash = "sha256:8ab06a50fb9bf9666dd0fe5dfb4676fa2b0ac0f31ecff72a6c3af8e22c063453", size = 692314, upload-time = "2025-11-17T22:32:31.031Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/b8/3c70881695e056f8a32f8b941126cf78775d9a4d7feba8abcb52cb7b04f2/ml_dtypes-0.5.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a174837a64f5b16cab6f368171a1a03a27936b31699d167684073ff1c4237dac", size = 676927, upload-time = "2025-11-17T22:31:48.182Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/54/0f/428ef6881782e5ebb7eca459689448c0394fa0a80bea3aa9262cba5445ea/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a7f7c643e8b1320fd958bf098aa7ecf70623a42ec5154e3be3be673f4c34d900", size = 5028464, upload-time = "2025-11-17T22:31:50.135Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/cb/28ce52eb94390dda42599c98ea0204d74799e4d8047a0eb559b6fd648056/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ad459e99793fa6e13bd5b7e6792c8f9190b4e5a1b45c63aba14a4d0a7f1d5ff", size = 5009002, upload-time = "2025-11-17T22:31:52.001Z" },
|
||||
]
|
||||
@@ -5033,6 +5038,7 @@ all = [
|
||||
{ name = "flash-attn-3", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl", marker = "sys_platform == 'linux'" },
|
||||
@@ -5040,7 +5046,7 @@ all = [
|
||||
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
|
||||
{ name = "quack-kernels", marker = "sys_platform == 'linux'" },
|
||||
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchao", version = "0.18.0+git5f2baf9d5", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5084,12 +5090,13 @@ flash-attn-cute = [
|
||||
gpu = [
|
||||
{ name = "dion", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
|
||||
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchao", version = "0.18.0+git5f2baf9d5", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5144,6 +5151,7 @@ requires-dist = [
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/fla-org/flash-linear-attention" },
|
||||
{ name = "jaxtyping", specifier = ">=0.3.2" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/state-spaces/mamba?rev=f577286" },
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = "==0.3.0" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.3.10.post2" },
|
||||
{ name = "msgspec", specifier = ">=0.18" },
|
||||
@@ -5214,7 +5222,7 @@ dev = [
|
||||
{ name = "pytest-asyncio", specifier = ">=0.23" },
|
||||
{ name = "ruff", specifier = ">=0.12.1" },
|
||||
]
|
||||
mamba-ssm = [{ name = "mamba-ssm", marker = "sys_platform == 'linux'", specifier = ">=2.3.0" }]
|
||||
mamba-ssm = [{ name = "mamba-ssm", marker = "sys_platform == 'linux'", git = "https://github.com/state-spaces/mamba?rev=f577286" }]
|
||||
|
||||
[[package]]
|
||||
name = "prime-rl-configs"
|
||||
@@ -7139,7 +7147,9 @@ dependencies = [
|
||||
{ name = "ml-dtypes" },
|
||||
{ name = "numpy" },
|
||||
{ name = "psutil" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "setuptools", marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "torch-c-dlpack-ext" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "typing-extensions" },
|
||||
@@ -7147,6 +7157,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6d/9a/5776adb5b6e03e141c8cff020e16c45b87c9b7a7a5bdfe83416d6cc23933/tilelang-0.1.12.tar.gz", hash = "sha256:595b39581d099a53f875bd8d553863e7e4f58998052b58764f5472cbfbb87043", size = 93565090, upload-time = "2026-07-08T04:22:52.901Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/13/51/4ae1fb532406082a4ebf16c890f5f98db14b8588f2c486334ba23578b4bc/tilelang-0.1.12-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:8741d6cd519782645d55c17abd8986402c62948bc2122d3417c445d11de5dd16", size = 38347295, upload-time = "2026-07-08T04:22:35.691Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/53/f281a0bd9ee7e03d6a97828fc0e443321ed26ea2b0bd74bf9f1d9451d30f/tilelang-0.1.12-cp38-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bbeb5573cbe2544a51a5c9a6cc737c5e3b5c2d95411caa3687fd9b08eb9d5f97", size = 50501074, upload-time = "2026-07-08T04:22:39.973Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fb/a4/ff0b14d00d29fe418063cd97490f55aa9cad6f981a6fbbf29124b024637d/tilelang-0.1.12-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:a1701eba4ad603d73f1b128b88f6a2350f1b1161729e5b2d1e540a1ec7a82d52", size = 46281933, upload-time = "2026-07-08T04:22:44.244Z" },
|
||||
]
|
||||
@@ -7289,10 +7300,12 @@ name = "torch-c-dlpack-ext"
|
||||
version = "0.1.5"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/37/de/921b6491efce5c389a5ef9bbed3d2d6660005840dae488124173180859ab/torch_c_dlpack_ext-0.1.5.tar.gz", hash = "sha256:d06f0357d575d22a168cc77acb9020fc4bae30968ceb6718a055dcbe92bacabe", size = 12913, upload-time = "2026-01-12T11:25:08.484Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b1/67/10d236698525d7b7db4d74ec0a4b01f5b2db33968995fdd9ac6b4635e327/torch_c_dlpack_ext-0.1.5-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:c0f2bd51fcd99c0e5b50314e1985f2728c4941bfa821f065e6c30951d1f995ca", size = 5291237, upload-time = "2026-01-12T11:24:44.011Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/06/8d760997307a5c3be4384424667bf31aae0a42060838c532c7d846516175/torch_c_dlpack_ext-0.1.5-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3562ee411258676f9c38b8ad39306d1c8d027b6a86f6a87c920d2d009a9d1510", size = 443069, upload-time = "2026-01-12T11:24:45.451Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e2/79/a914539b4785f3e44f891aa012a886edb8bc10fe081c440981c57543ce21/torch_c_dlpack_ext-0.1.5-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e6f9da4bb9af70e27facc777458be62e10dbbbddda7672d16138db0553c5a524", size = 897846, upload-time = "2026-01-12T11:24:48.168Z" },
|
||||
]
|
||||
@@ -8647,6 +8660,7 @@ version = "4.15.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8a/8e/0c8f17309549d2e5cde9a3ccefa6365437f1e7bafe71878eaf9478e47b18/z3_solver-4.15.4.0.tar.gz", hash = "sha256:928c29b58c4eb62106da51c1914f6a4a55d0441f8f48a81b9da07950434a8946", size = 5018600, upload-time = "2025-10-29T18:12:03.062Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/33/a3d5d2eaeb0f7b3174d57d405437eabb2075d4d50bd9ea0957696c435c7b/z3_solver-4.15.4.0-py3-none-macosx_13_0_arm64.whl", hash = "sha256:407e825cc9211f95ef46bdc8d151bf630e7ab2d62a21d24cd74c09cc5b73f3aa", size = 37052538, upload-time = "2025-10-29T18:11:46.233Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/c9/bb51a96af0091324c81b803f16c49f719f9f6ea0b0bb52200f5c97ec4892/z3_solver-4.15.4.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e103a6f203f505b8b8b8e5c931cc407c95b61556512d4921c1ddc0b3f41b08e", size = 29268352, upload-time = "2025-10-29T18:11:53.032Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/2e/0b49f7e4e53817cfb09a0f6585012b782dfe0b666e8abefcb4fac0570606/z3_solver-4.15.4.0-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:62c7e9cbdd711932301f29919ad9158de9b2f58b4d281dd259bbcd0a2f408ba1", size = 27226534, upload-time = "2025-10-29T18:11:55.59Z" },
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user