Selective activation checkpointing (#2055)
Release / Push CUDA image to Docker (push) Canceled after 0s

* selective ac

* ruff

* fix

* some changes

* some changes

* some more

* fix

* some more

* some more

* small

* simplify

* address comments

* clean

* fix

* address comment

* address comments

* add attn_proj and mlp targets, remove attention_sdpa

Replace attention_sdpa (checkpointing the attention kernel saves zero
memory with flash attention) with two new selective AC targets:

- attn_proj: checkpoints QKV projections, QK norms, RoPE, and output
  projection — everything in attention except the kernel
- mlp: checkpoints the entire dense MLP forward (skipped for MoE layers)

Refactor FlashAttention and SDPAAttention to extract _attn_projections
and _output_proj methods as checkpoint boundaries.

* fix: add rms_norm re-export for nemotron_h compatibility

The selective AC refactoring moved RMSNorm/RMSNormConfig to norms.py,
but nemotron_h (added in main) imports from rms_norm.py. Add a
re-export shim to keep both paths working.

* fix: handle position_embeddings=None in SDPAAttention

NemotronH passes position_embeddings=None since it uses its own rotary
scheme. The FlashAttention path already guarded for this but
SDPAAttention._attn_projections and both forward() signatures were
missing the None handling.

* fix: handle LatentMoE in buffer reset and allow impl=auto for selective AC

- _reset_runtime_moe_buffers now checks (MoE, LatentMoE) like all other
  MoE instance checks in the file
- selective_ac_only_with_custom_impl accepts ("custom", "auto") matching
  the pattern used by ep_only_with_custom_impl and
  router_replay_only_with_custom_impl

* Fix selective AC LatentMoE target detection

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

* Delete tests/unit/train/models/test_selective_checkpointing.py

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>

* fixes for nemotron and GDN models

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
This commit is contained in:
faresobeid
2026-03-26 13:21:04 +00:00
committed by GitHub
co-authored by faresobeid Cursor Agent
parent effa509cb3
commit d7afbaa6f3
18 changed files with 675 additions and 304 deletions
+1
View File
@@ -7,6 +7,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently `norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
+13 -3
View File
@@ -62,9 +62,15 @@ class BenchmarkConfig(BaseConfig):
seq_len: Annotated[int, Field(ge=1, description="Sequence length")] = 512
ac: Annotated[Literal["Recompute", "Offload", "None"], Field(description="Activation checkpointing type")] = (
"Recompute"
)
ac: Annotated[
Literal["Recompute", "Selective", "Offload"] | None,
Field(description="Activation checkpointing type"),
] = "Recompute"
selective_targets: Annotated[
list[str] | None,
Field(description="Selective activation checkpoint targets when ac=Selective"),
] = None
attention: Annotated[
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
@@ -141,6 +147,10 @@ def build_command(config: BenchmarkConfig) -> list[str]:
# Add activation checkpointing if enabled
if config.ac == "Recompute":
cmd.append("--model.ac")
elif config.ac == "Selective":
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
if config.selective_targets:
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
elif config.ac == "Offload":
cmd.append("--model.ac-offloading")
+27 -1
View File
@@ -28,14 +28,34 @@ _ATTN_ALIASES = {"flash_attention_4": "fa4"}
class ActivationCheckpointConfig(BaseConfig):
"""Configures activation checkpointing."""
mode: Annotated[
Literal["full", "selective"],
Field(
description="Whether to checkpoint whole transformer blocks (`full`) or selected subcomponents inside supported custom decoder layers (`selective`).",
),
] = "full"
freq: Annotated[
int,
Field(
ge=1,
description="Applies activation checkpointing to every `freq` layers. Defaults to 1, which will is full activation checkpointing.",
description="Applies activation checkpointing to every `freq` layers. Defaults to 1.",
),
] = 1
targets: Annotated[
list[str],
Field(
description="Selective checkpoint targets. `norm` checkpoints every norm module inside selected layers (decoder, attention, MLA, etc.). `attn_proj` checkpoints QKV projections, QK norms, RoPE, and output projection — everything in the attention layer except the kernel. `mlp` checkpoints the entire dense MLP forward (not applicable to MoE layers). `mla_up_proj` checkpoints MLA Q/KV up-projection work where supported. `routed_experts` checkpoints routed expert compute in MoE layers (including LatentMoE). `mamba` checkpoints the Mamba mixer forward in NemotronH Mamba layers. `linear_attn` checkpoints the GatedDeltaNet forward in Qwen3.5-MoE linear attention layers.",
),
] = ["norm"]
@model_validator(mode="after")
def validate_selective_targets(self):
if self.mode == "selective" and not self.targets:
raise ValueError("Selective activation checkpointing requires at least one target.")
return self
class ActivationOffloadingConfig(BaseConfig):
"""Configures the activation offloading."""
@@ -309,6 +329,12 @@ class ModelConfig(BaseModelConfig):
self.ac = ActivationCheckpointConfig()
return self
@model_validator(mode="after")
def selective_ac_only_with_custom_impl(self):
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
return self
@model_validator(mode="after")
def cpu_offload_mutual_exclusion(self):
if self.fsdp_cpu_offload and self.optim_cpu_offload:
+51 -2
View File
@@ -31,6 +31,11 @@ from prime_rl.trainer.models import (
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.layers.checkpointing import (
get_supported_targets,
set_selective_activation_checkpointing,
supports_selective_activation_checkpointing,
)
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
from prime_rl.trainer.parallel_dims import ParallelDims
@@ -600,12 +605,49 @@ def reshard_module(model: nn.Module):
def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
logger = get_logger()
language_model = get_language_model(model)
selective_layers = 0
full_layers = 0
fallback_layer_types: set[str] = set()
model_supported_targets: set[str] = set()
for layer_id, (layer_name, transformer_block) in enumerate(language_model.layers.named_children()):
if layer_id % ac_config.freq == 0:
if layer_id % ac_config.freq != 0:
continue
if ac_config.mode == "selective" and supports_selective_activation_checkpointing(transformer_block):
model_supported_targets.update(get_supported_targets(transformer_block))
set_selective_activation_checkpointing(transformer_block, ac_config.targets)
selective_layers += 1
else:
if ac_config.mode == "selective":
fallback_layer_types.add(type(transformer_block).__name__)
transformer_block = checkpoint_wrapper(transformer_block, preserve_rng_state=False)
full_layers += 1
language_model.layers.register_module(layer_name, transformer_block)
get_logger().info(f"Applied activation checkpointing (freq={ac_config.freq})")
if ac_config.mode == "selective":
unsupported_targets = frozenset(ac_config.targets) - model_supported_targets
if unsupported_targets:
raise ValueError(
f"Selective activation checkpoint targets {sorted(unsupported_targets)} are not supported "
f"by the selected model layers. Supported targets across the model: {sorted(model_supported_targets)}"
)
if fallback_layer_types:
logger.warning(
"Selective activation checkpointing is not supported for layer types "
f"{sorted(fallback_layer_types)}; falling back to full checkpointing for those layers."
)
logger.info(
"Applied selective activation checkpointing "
f"(freq={ac_config.freq}, targets={ac_config.targets}, selective_layers={selective_layers}, "
f"full_fallback_layers={full_layers})"
)
return
logger.info(f"Applied activation checkpointing (freq={ac_config.freq})")
def apply_compile(model: nn.Module, compile_config: CompileConfig):
@@ -638,6 +680,12 @@ def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
buffer.data = buffer.data.to("cuda")
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
for module in model.modules():
if isinstance(module, (MoE, LatentMoE)) and module.tokens_per_expert.device.type != "meta":
module.tokens_per_expert.zero_()
def _validate_flash_attn_4_installed() -> None:
"""Validate that flash-attn-cute is installed and not overwritten by flash-attn.
@@ -760,6 +808,7 @@ def setup_model(
else:
load_dcp_from_hf(model, config, parallel_dims)
_reset_runtime_moe_buffers(model)
return model
@@ -22,7 +22,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import (
RotaryEmbedding,
RotaryEmbeddingConfig,
@@ -146,6 +146,24 @@ class AfmoeAttentionBase(nn.Module):
class AfmoeSDPAAttention(AfmoeAttentionBase):
"""AFMoE attention using PyTorch's scaled_dot_product_attention."""
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
dropout_p: float = 0.0,
) -> torch.Tensor:
return F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
dropout_p=dropout_p,
is_causal=attention_mask is None,
scale=self.scaling,
)
def forward(
self,
hidden_states: torch.Tensor,
@@ -159,14 +177,12 @@ class AfmoeSDPAAttention(AfmoeAttentionBase):
)
dropout_p = self.attention_dropout if self.training else 0.0
attn_output = F.scaled_dot_product_attention(
attn_output = self._attention_core(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
attention_mask=attention_mask,
dropout_p=dropout_p,
is_causal=attention_mask is None, # Use causal if no explicit mask
scale=self.scaling,
)
return self._finalize_output(attn_output, gate_states, input_shape)
@@ -202,6 +218,16 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
out = out[0]
return out
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.Tensor:
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
def forward(
self,
hidden_states: torch.Tensor,
@@ -229,9 +255,14 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = out.contiguous().view(*input_shape, -1)
attn_output = self._attention_core(
query_states,
key_states,
value_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
attn_output = self.o_proj(attn_output)
return attn_output, None
@@ -37,7 +37,7 @@ from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
@@ -2,7 +2,6 @@ import warnings
from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
@@ -21,193 +20,39 @@ from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
convert_tt_layer_to_vllm_kernel,
convert_tt_to_hf_moe,
)
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import (
RotaryEmbedding,
RotaryEmbeddingConfig,
apply_rotary_pos_emb_interleave,
)
try:
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
except ImportError:
sparse_mla_fwd_interface = None # type: ignore
sparse_mla_bwd = None # type: ignore
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
class _SparseMLA(torch.autograd.Function):
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
@staticmethod
def forward(ctx, q, kv, indices, sm_scale):
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
ctx.save_for_backward(q, kv, out, indices, lse)
ctx.sm_scale = sm_scale
return out
@staticmethod
def backward(ctx, do):
q, kv, out, indices, lse = ctx.saved_tensors
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
return dq, dkv, None, None
class LayerNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.dim = dim
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
self.bias = nn.Parameter(torch.zeros(dim, dtype=torch.float32))
def forward(self, x: torch.Tensor):
return F.layer_norm(x.float(), (self.dim,), self.weight.float(), self.bias.float(), self.eps).type_as(x)
class Indexer(nn.Module):
def __init__(self, config: GlmMoeDsaConfig):
super().__init__()
if config.q_lora_rank is None:
raise ValueError("Sparse indexer requires q_lora_rank to be set")
self.n_head = config.index_n_heads
self.head_dim = config.index_head_dim
self.rope_dim = config.qk_rope_head_dim
self.wq_b = nn.Linear(config.q_lora_rank, self.n_head * self.head_dim, bias=False)
self.wk = nn.Linear(config.hidden_size, self.head_dim, bias=config.attention_bias)
self.k_norm = LayerNorm(dim=self.head_dim, eps=1e-6)
self.weights_proj = nn.Linear(config.hidden_size, self.n_head, bias=False)
self.weight_scale = (self.head_dim**-0.5) * (self.n_head**-0.5)
@torch.no_grad()
def compute_sparse_indices(
self,
hidden_states: torch.Tensor,
q_latent: torch.Tensor,
ks: torch.Tensor,
ke: torch.Tensor,
index_topk: int,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
total_tokens = hidden_states.shape[1]
assert index_topk % 64 == 0, f"index_topk must be divisible by 64 (block_I), got {index_topk}"
q_idx = self.wq_b(q_latent[0]).view(total_tokens, self.n_head, self.head_dim)
k_idx = self.k_norm(self.wk(hidden_states[0]))
w = self.weights_proj(hidden_states[0])
q_pe = q_idx[..., : self.rope_dim]
q_nope = q_idx[..., self.rope_dim :]
k_pe = k_idx[..., : self.rope_dim]
k_nope = k_idx[..., self.rope_dim :]
cos, sin = position_embeddings
q_pe = q_pe.unsqueeze(0).transpose(1, 2)
k_pe = k_pe.unsqueeze(0).unsqueeze(1)
q_pe, k_pe = apply_rotary_pos_emb_interleave(q_pe, k_pe, cos, sin)
q_pe = q_pe.transpose(1, 2).squeeze(0)
k_pe = k_pe.squeeze(1).squeeze(0)
q_idx = torch.cat([q_pe, q_nope], dim=-1)
k_idx = torch.cat([k_pe, k_nope], dim=-1)
indices = fp8_indexer(q_idx, k_idx, w, ks, ke, index_topk, self.weight_scale)
return indices.view(1, total_tokens, 1, index_topk)
class GlmMoeDsaAttention(nn.Module):
def __init__(self, config: GlmMoeDsaConfig):
super().__init__()
self.config = config
self.num_heads = config.num_attention_heads
self.kv_lora_rank = config.kv_lora_rank
self.qk_rope_head_dim = config.qk_rope_head_dim
self.qk_nope_head_dim = config.qk_nope_head_dim
self.qk_head_dim = config.qk_head_dim
self.v_head_dim = config.v_head_dim
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
self.q_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
self.kv_a_proj_with_mqa = nn.Linear(
config.hidden_size,
self.kv_lora_rank + self.qk_rope_head_dim,
bias=config.attention_bias,
)
self.kv_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=self.kv_lora_rank, eps=config.rms_norm_eps))
self.kv_b_proj = nn.Linear(
self.kv_lora_rank,
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
bias=False,
)
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=config.attention_bias)
self.indexer = Indexer(config)
self.scaling = self.qk_head_dim ** (-0.5)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
ks: torch.Tensor | None = None,
ke: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
batch_size, total_tokens, _ = hidden_states.shape
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
q_full = self.q_b_proj(q_latent).view(batch_size, total_tokens, self.num_heads, self.qk_head_dim)
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
k_compressed_normed = self.kv_a_layernorm(k_compressed)
q_rope_r = q_rope.transpose(1, 2)
k_rope_r = k_rope.unsqueeze(1)
cos, sin = position_embeddings
q_rope_r, k_rope_r = apply_rotary_pos_emb_interleave(q_rope_r, k_rope_r, cos, sin)
q_rope = q_rope_r.transpose(1, 2)
k_rope = k_rope_r.squeeze(1)
indices = self.indexer.compute_sparse_indices(
hidden_states, q_latent, ks, ke, self.config.index_topk, position_embeddings
)
# KV absorption
kv_b_w = self.kv_b_proj.weight.view(self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank)
w_k_nope = kv_b_w[:, : self.qk_nope_head_dim, :]
w_v = kv_b_w[:, self.qk_nope_head_dim :, :]
q_absorbed = torch.einsum("bshd,hdk->bshk", q_nope, w_k_nope)
sparse_q = torch.cat([q_absorbed, q_rope], dim=-1)
sparse_kv = torch.cat([k_compressed_normed, k_rope], dim=-1).unsqueeze(2)
# Sentinel zero-token so padded indices (= total_tokens) are in-bounds
sentinel = torch.zeros(batch_size, 1, 1, sparse_kv.shape[-1], dtype=sparse_kv.dtype, device=sparse_kv.device)
sparse_kv = torch.cat([sparse_kv, sentinel], dim=1)
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
# Un-absorb
out = torch.einsum("bshk,hdk->bshd", out, w_v)
out = out.reshape(batch_size, total_tokens, -1)
return self.o_proj(out), None
def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArgs:
if config.q_lora_rank is None:
raise ValueError("Sparse MLA attention requires q_lora_rank to be set")
return SparseMlaAttentionArgs(
hidden_size=config.hidden_size,
num_attention_heads=config.num_attention_heads,
kv_lora_rank=config.kv_lora_rank,
q_lora_rank=config.q_lora_rank,
qk_rope_head_dim=config.qk_rope_head_dim,
qk_nope_head_dim=config.qk_nope_head_dim,
qk_head_dim=config.qk_head_dim,
v_head_dim=config.v_head_dim,
attention_bias=config.attention_bias,
rms_norm_eps=config.rms_norm_eps,
index_n_heads=config.index_n_heads,
index_head_dim=config.index_head_dim,
index_topk=config.index_topk,
)
class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: GlmMoeDsaConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GlmMoeDsaAttention(config)
self.self_attn = GlmMoeDsaAttention(_sparse_mla_attention_args(config))
moe_args = MoEArgs(
num_experts=config.n_routed_experts,
@@ -0,0 +1,196 @@
from dataclasses import dataclass
import torch
from torch import nn
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb_interleave
try:
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
except ImportError:
sparse_mla_fwd_interface = None # type: ignore
sparse_mla_bwd = None # type: ignore
@dataclass(frozen=True)
class SparseMlaAttentionArgs:
hidden_size: int
num_attention_heads: int
kv_lora_rank: int
q_lora_rank: int
qk_rope_head_dim: int
qk_nope_head_dim: int
qk_head_dim: int
v_head_dim: int
attention_bias: bool
rms_norm_eps: float
index_n_heads: int
index_head_dim: int
index_topk: int
class _SparseMLA(torch.autograd.Function):
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
@staticmethod
def forward(ctx, q, kv, indices, sm_scale):
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
ctx.save_for_backward(q, kv, out, indices, lse)
ctx.sm_scale = sm_scale
return out
@staticmethod
def backward(ctx, do):
q, kv, out, indices, lse = ctx.saved_tensors
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
return dq, dkv, None, None
class Indexer(nn.Module):
def __init__(self, args: SparseMlaAttentionArgs):
super().__init__()
self.n_head = args.index_n_heads
self.head_dim = args.index_head_dim
self.rope_dim = args.qk_rope_head_dim
self.wq_b = nn.Linear(args.q_lora_rank, self.n_head * self.head_dim, bias=False)
self.wk = nn.Linear(args.hidden_size, self.head_dim, bias=args.attention_bias)
self.k_norm = LayerNorm(dim=self.head_dim, eps=1e-6)
self.weights_proj = nn.Linear(args.hidden_size, self.n_head, bias=False)
self.weight_scale = (self.head_dim**-0.5) * (self.n_head**-0.5)
@torch.no_grad()
def compute_sparse_indices(
self,
hidden_states: torch.Tensor,
q_latent: torch.Tensor,
ks: torch.Tensor,
ke: torch.Tensor,
index_topk: int,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
total_tokens = hidden_states.shape[1]
assert index_topk % 64 == 0, f"index_topk must be divisible by 64 (block_I), got {index_topk}"
q_idx = self.wq_b(q_latent[0]).view(total_tokens, self.n_head, self.head_dim)
k_idx = self.k_norm(self.wk(hidden_states[0]))
w = self.weights_proj(hidden_states[0])
q_pe = q_idx[..., : self.rope_dim]
q_nope = q_idx[..., self.rope_dim :]
k_pe = k_idx[..., : self.rope_dim]
k_nope = k_idx[..., self.rope_dim :]
cos, sin = position_embeddings
q_pe = q_pe.unsqueeze(0).transpose(1, 2)
k_pe = k_pe.unsqueeze(0).unsqueeze(1)
q_pe, k_pe = apply_rotary_pos_emb_interleave(q_pe, k_pe, cos, sin)
q_pe = q_pe.transpose(1, 2).squeeze(0)
k_pe = k_pe.squeeze(1).squeeze(0)
q_idx = torch.cat([q_pe, q_nope], dim=-1)
k_idx = torch.cat([k_pe, k_nope], dim=-1)
indices = fp8_indexer(q_idx, k_idx, w, ks, ke, index_topk, self.weight_scale)
return indices.view(1, total_tokens, 1, index_topk)
class GlmMoeDsaAttention(nn.Module):
def __init__(self, args: SparseMlaAttentionArgs):
super().__init__()
self.args = args
self.num_heads = args.num_attention_heads
self.kv_lora_rank = args.kv_lora_rank
self.qk_rope_head_dim = args.qk_rope_head_dim
self.qk_nope_head_dim = args.qk_nope_head_dim
self.qk_head_dim = args.qk_head_dim
self.v_head_dim = args.v_head_dim
self.q_a_proj = nn.Linear(args.hidden_size, args.q_lora_rank, bias=args.attention_bias)
self.q_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=args.q_lora_rank, eps=args.rms_norm_eps))
self.q_b_proj = nn.Linear(args.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
self.kv_a_proj_with_mqa = nn.Linear(
args.hidden_size,
self.kv_lora_rank + self.qk_rope_head_dim,
bias=args.attention_bias,
)
self.kv_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=self.kv_lora_rank, eps=args.rms_norm_eps))
self.kv_b_proj = nn.Linear(
self.kv_lora_rank,
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
bias=False,
)
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
self.indexer = Indexer(args)
self.scaling = self.qk_head_dim ** (-0.5)
def _mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
return q_latent, self.kv_a_layernorm(k_compressed), k_rope
def _mla_up_proj(
self,
q_latent: torch.Tensor,
k_compressed_normed: torch.Tensor,
k_rope: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
batch_size, total_tokens, _ = q_latent.shape
q_full = self.q_b_proj(q_latent).view(batch_size, total_tokens, self.num_heads, self.qk_head_dim)
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
q_rope_r = q_rope.transpose(1, 2)
k_rope_r = k_rope.unsqueeze(1)
cos, sin = position_embeddings
q_rope_r, k_rope_r = apply_rotary_pos_emb_interleave(q_rope_r, k_rope_r, cos, sin)
q_rope = q_rope_r.transpose(1, 2)
k_rope = k_rope_r.squeeze(1)
kv_b_w = self.kv_b_proj.weight.view(self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank)
w_k_nope = kv_b_w[:, : self.qk_nope_head_dim, :]
w_v = kv_b_w[:, self.qk_nope_head_dim :, :]
q_absorbed = torch.einsum("bshd,hdk->bshk", q_nope, w_k_nope)
sparse_q = torch.cat([q_absorbed, q_rope], dim=-1)
sparse_kv = torch.cat([k_compressed_normed, k_rope], dim=-1).unsqueeze(2)
sentinel = torch.zeros(batch_size, 1, 1, sparse_kv.shape[-1], dtype=sparse_kv.dtype, device=sparse_kv.device)
sparse_kv = torch.cat([sparse_kv, sentinel], dim=1)
return sparse_q, sparse_kv, w_v
def _mla_unabsorb(self, out: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
return torch.einsum("bshk,hdk->bshd", out, w_v)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
ks: torch.Tensor | None = None,
ke: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
batch_size, total_tokens, _ = hidden_states.shape
q_latent, k_compressed_normed, k_rope = self._mla_latents(hidden_states)
indices = self.indexer.compute_sparse_indices(
hidden_states, q_latent, ks, ke, self.args.index_topk, position_embeddings
)
sparse_q, sparse_kv, w_v = self._mla_up_proj(
q_latent,
k_compressed_normed,
k_rope,
position_embeddings=position_embeddings,
)
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
out = self._mla_unabsorb(out, w_v)
out = out.reshape(batch_size, total_tokens, -1)
return self.o_proj(out), None
+66 -26
View File
@@ -6,7 +6,7 @@ import torch
import torch.nn.functional as F
from torch import nn
from .rms_norm import RMSNorm, RMSNormConfig
from .norms import RMSNorm, RMSNormConfig
from .rotary_emb import apply_rotary_pos_emb
# flash-attention-2
@@ -105,13 +105,22 @@ class FlashAttention(nn.Module):
out = out[0]
return out
def forward(
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.Tensor:
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
return out.contiguous().view(1, out.shape[0], -1)
def _attn_projections(
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,
) -> tuple[torch.Tensor, torch.Tensor | None]:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
@@ -144,14 +153,29 @@ class FlashAttention(nn.Module):
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
return query_states, key_states, value_states
out = out.contiguous()
attn_output = out.view(1, out.shape[0], -1)
attn_weights = None
def _output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
return self.o_proj(attn_output)
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
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,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self._attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(
query_states,
key_states,
value_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
attn_output = self._output_proj(attn_output)
return attn_output, None
class SDPAAttention(nn.Module):
@@ -188,19 +212,17 @@ class SDPAAttention(nn.Module):
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
def forward(
def _attn_projections(
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,
) -> tuple[torch.Tensor, torch.Tensor | None]:
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states: torch.Tensor = self.q_proj(hidden_states)
key_states: torch.Tensor = self.k_proj(hidden_states)
value_states: torch.Tensor = self.v_proj(hidden_states)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
@@ -222,17 +244,35 @@ class SDPAAttention(nn.Module):
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
# TODO: Can we optimize the rotary application instead of double transpose?
return query_states, key_states, value_states
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
) -> torch.Tensor:
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
out = F.scaled_dot_product_attention(query_states, key_states, value_states, is_causal=True)
out = out.transpose(1, 2).contiguous() # .view(out.shape[0], out.shape[1], -1)
attn_output = out.view(out.shape[0], out.shape[1], -1)
attn_weights = None
out = out.transpose(1, 2).contiguous()
return out.view(out.shape[0], out.shape[1], -1)
# attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
def _output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
return self.o_proj(attn_output)
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,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self._attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(query_states, key_states, value_states)
attn_output = self._output_proj(attn_output)
return attn_output, None
ATTN_IMPL2CLASS = {
@@ -0,0 +1,106 @@
from collections.abc import Iterable
from functools import wraps
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "routed_experts", "mamba", "linear_attn"})
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
def _is_norm_module(module: nn.Module) -> bool:
return "norm" in type(module).__name__.lower()
def _should_checkpoint(module: nn.Module) -> bool:
return torch.is_grad_enabled() and module.training
def checkpoint_method(module: nn.Module, method_name: str) -> None:
patched_methods = frozenset(getattr(module, _PATCHED_METHODS_ATTR, ()))
if method_name in patched_methods:
return
original = getattr(module, method_name)
@wraps(original)
def checkpointed(*args, **kwargs):
if not _should_checkpoint(module):
return original(*args, **kwargs)
def fn(*checkpoint_args):
return original(*checkpoint_args, **kwargs)
return checkpoint(fn, *args, use_reentrant=False, preserve_rng_state=False)
setattr(module, method_name, checkpointed)
setattr(module, _PATCHED_METHODS_ATTR, patched_methods.union({method_name}))
def _configure_norm_checkpointing(layer: nn.Module) -> None:
for module in layer.modules():
if module is layer or not _is_norm_module(module):
continue
checkpoint_method(module, "forward")
def _is_dense_mlp(mlp: nn.Module) -> bool:
return not hasattr(mlp, "_run_routed_experts") and not hasattr(mlp, "tokens_per_expert")
def get_supported_targets(layer: nn.Module) -> frozenset[str]:
supported_targets = {"norm"}
self_attn = getattr(layer, "self_attn", None)
mlp = getattr(layer, "mlp", None)
mamba = getattr(layer, "mamba", None)
linear_attn = getattr(layer, "linear_attn", None)
if self_attn is not None and hasattr(self_attn, "_attn_projections"):
supported_targets.add("attn_proj")
if self_attn is not None and hasattr(self_attn, "_mla_up_proj"):
supported_targets.add("mla_up_proj")
if mlp is not None and _is_dense_mlp(mlp):
supported_targets.add("mlp")
if mlp is not None and hasattr(mlp, "_run_routed_experts"):
supported_targets.add("routed_experts")
if mamba is not None:
supported_targets.add("mamba")
if linear_attn is not None:
supported_targets.add("linear_attn")
return frozenset(supported_targets)
def set_selective_activation_checkpointing(layer: nn.Module, targets: Iterable[str]) -> None:
normalized_targets = frozenset(targets)
invalid_targets = normalized_targets - SELECTIVE_AC_TARGETS
if invalid_targets:
raise ValueError(f"Unsupported selective activation checkpoint targets: {sorted(invalid_targets)}")
enabled_targets = normalized_targets & get_supported_targets(layer)
self_attn = getattr(layer, "self_attn", None)
mlp = getattr(layer, "mlp", None)
mamba = getattr(layer, "mamba", None)
linear_attn = getattr(layer, "linear_attn", None)
if self_attn is not None and "attn_proj" in enabled_targets:
checkpoint_method(self_attn, "_attn_projections")
checkpoint_method(self_attn, "_output_proj")
if self_attn is not None and "mla_up_proj" in enabled_targets:
checkpoint_method(self_attn, "_mla_up_proj")
if mlp is not None and "mlp" in enabled_targets:
checkpoint_method(mlp, "forward")
if mlp is not None and "routed_experts" in enabled_targets:
checkpoint_method(mlp, "_run_routed_experts")
if mamba is not None and "mamba" in enabled_targets:
checkpoint_method(mamba, "forward")
if linear_attn is not None and "linear_attn" in enabled_targets:
checkpoint_method(linear_attn, "forward")
if "norm" in enabled_targets:
_configure_norm_checkpointing(layer)
def supports_selective_activation_checkpointing(layer: nn.Module) -> bool:
return type(layer).__module__.startswith("prime_rl.trainer.models.")
+63 -38
View File
@@ -375,7 +375,32 @@ class MoE(nn.Module):
persistent=False,
)
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
def _run_routed_experts(
self,
x: torch.Tensor,
token_indices_experts_sorted: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
top_scores_experts_sorted: torch.Tensor,
) -> torch.Tensor:
dim = x.shape[-1]
routed_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
routed_input = torch.gather(x, dim=0, index=routed_indices)
if self.score_before_experts:
routed_input = (routed_input.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
routed_output = self.experts(routed_input, num_tokens_per_expert)
if not self.score_before_experts:
routed_output = (routed_output.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
return routed_output
def forward(
self,
x: torch.Tensor,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
"""
Args:
x (torch.Tensor): Input tensor with shape ``(bs, slen, dim)``.
@@ -403,9 +428,9 @@ class MoE(nn.Module):
# tokens_per_expert will be used to update the expert bias for load balancing.
# and also to count the expert usage
# TODO: Activation Checkpointing has the side effect of double counting tokens_per_expert --
# first in the forward pass, and then in the backward pass. However, this has no
# effect on the expert bias update thanks to the torch.sign() operator.
# Full block checkpointing can double count tokens_per_expert because it reruns the router
# in backward. The selective MoE path avoids that by checkpointing only the
# routed expert compute below.
with torch.no_grad():
self.tokens_per_expert.add_(num_tokens_per_expert)
@@ -423,28 +448,19 @@ class MoE(nn.Module):
num_tokens_per_expert,
) = self.reorderer(top_scores, selected_experts_indices)
# shape (bs*slen*top_k, dim)
token_indices_experts_sorted = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
# shape (bs*slen*top_k, dim)
routed_input = torch.gather(x, dim=0, index=token_indices_experts_sorted)
if self.score_before_experts:
routed_input = (routed_input.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
# shape (bs*slen*top_k, dim)
routed_output = self.experts(routed_input, num_tokens_per_expert)
if not self.score_before_experts:
routed_output = (routed_output.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
# shared expert
routed_output = self._run_routed_experts(
x,
token_indices_experts_sorted,
num_tokens_per_expert,
top_scores_experts_sorted,
)
if self.shared_expert is not None:
out = self.shared_expert(x)
else:
out = torch.zeros_like(x)
out = out.scatter_add(dim=0, index=token_indices_experts_sorted, src=routed_output)
routed_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
out = out.scatter_add(dim=0, index=routed_indices, src=routed_output)
out = out.reshape(bs, slen, dim)
return out
@@ -693,6 +709,26 @@ class LatentMoE(nn.Module):
persistent=False,
)
def _run_routed_experts(
self,
x: torch.Tensor,
token_indices_experts_sorted: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
top_scores_experts_sorted: torch.Tensor,
) -> torch.Tensor:
dim = x.shape[-1]
token_indices_expanded = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
routed_input = torch.gather(x, dim=0, index=token_indices_expanded)
routed_input = self.fc1_latent_proj(routed_input)
routed_output = self.experts(routed_input, num_tokens_per_expert)
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
routed_output = routed_output * self.routed_scaling_factor
routed_output = self.fc2_latent_proj(routed_output)
return routed_output
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
bs, slen, dim = x.shape
x_flat = x.view(-1, dim)
@@ -708,24 +744,13 @@ class LatentMoE(nn.Module):
num_tokens_per_expert,
) = self.reorderer(top_scores, selected_experts_indices)
token_indices_expanded = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
routed_input = torch.gather(x_flat, dim=0, index=token_indices_expanded)
routed_output = self._run_routed_experts(
x_flat,
token_indices_experts_sorted,
num_tokens_per_expert,
top_scores_experts_sorted,
)
# Apply latent projection before expert computation
routed_input = self.fc1_latent_proj(routed_input)
routed_output = self.experts(routed_input, num_tokens_per_expert)
# Apply scores after expert computation (matches vLLM's fused kernel behavior)
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
# Apply routed_scaling_factor after expert output
routed_output = routed_output * self.routed_scaling_factor
# Project back from latent space
routed_output = self.fc2_latent_proj(routed_output)
# Shared expert
out = self.shared_expert(x_flat)
token_indices_full = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
@@ -0,0 +1,45 @@
from dataclasses import dataclass
import torch
import torch.nn.functional as F
from torch import nn
from transformers.integrations import use_kernel_forward_from_hub
@dataclass
class RMSNormConfig:
hidden_size: int
eps: float = 1e-6
@use_kernel_forward_from_hub("RMSNorm")
class RMSNorm(nn.Module):
def __init__(self, config: RMSNormConfig) -> None:
"""
Glm4MoeRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(config.hidden_size))
self.variance_epsilon = config.eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
class LayerNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.dim = dim
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
self.bias = nn.Parameter(torch.zeros(dim, dtype=torch.float32))
def forward(self, x: torch.Tensor):
return F.layer_norm(x.float(), (self.dim,), self.weight.float(), self.bias.float(), self.eps).type_as(x)
+2 -31
View File
@@ -1,32 +1,3 @@
from dataclasses import dataclass
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
import torch
from torch import nn
from transformers.integrations import use_kernel_forward_from_hub
@dataclass
class RMSNormConfig:
hidden_size: int
eps: float = 1e-6
@use_kernel_forward_from_hub("RMSNorm")
class RMSNorm(nn.Module):
def __init__(self, config: RMSNormConfig) -> None:
"""
Glm4MoeRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(config.hidden_size))
self.variance_epsilon = config.eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
__all__ = ["RMSNorm", "RMSNormConfig"]
@@ -38,7 +38,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
logger = logging.get_logger(__name__)
@@ -13,7 +13,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
@@ -378,6 +378,22 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using PyTorch's scaled_dot_product_attention."""
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
) -> torch.Tensor:
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
return F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
is_causal=True,
scale=self.scaling,
)
def forward(
self,
hidden_states: torch.Tensor,
@@ -401,17 +417,7 @@ class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
attn_output = F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
is_causal=True,
scale=self.scaling,
)
attn_output = self._attention_core(query_states, key_states, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
@@ -446,6 +452,16 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
out = out[0]
return out
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.Tensor:
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
def forward(
self,
hidden_states: torch.Tensor,
@@ -474,9 +490,14 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = out.contiguous().view(*input_shape, -1)
attn_output = self._attention_core(
query_states,
key_states,
value_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output)
return attn_output, None
@@ -31,7 +31,7 @@ from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
from prime_rl.trainer.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig
from prime_rl.trainer.models.qwen3_moe.converting_qwen3_moe import (
+5
View File
@@ -154,3 +154,8 @@ def test_cli_overrides_toml(tmp_path):
def test_removed_fused_lm_head_chunk_size_field_is_rejected():
with pytest.raises(ValidationError, match="fused_lm_head_chunk_size"):
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
def test_selective_activation_checkpointing_requires_custom_impl():
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})