"""Decoder layer: attention + MLP with RMSNorm residual connections. Unified across Llama, Qwen2, and Qwen3 architectures: - bias: Qwen2 uses bias=True on QKV projection. - qk_norm: Qwen3 applies per-head RMSNorm to Q and K before RoPE. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl from ....infra.cuda_ext import lazy_op from ..L1.rms_norm import RMSNorm from ..L2.attention import LlamaAttention from ..L2.llama_mlp import LlamaMLP _C = lazy_op("candidate_llama_decoder", "llama_decoder.cu") @triton.jit def _rms_norm_kernel( x_ptr, weight_ptr, out_ptr, n_cols: tl.constexpr, eps: tl.constexpr, BLOCK_N: tl.constexpr, ): row = tl.program_id(0) cols = tl.arange(0, BLOCK_N) mask = cols < n_cols offsets = row * n_cols + cols x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32) variance = tl.sum(x * x, axis=0) / n_cols normalized = (x * tl.rsqrt(variance + eps)).to(tl.bfloat16) weight = tl.load(weight_ptr + cols, mask=mask, other=0.0) tl.store(out_ptr + offsets, normalized * weight, mask=mask) @triton.jit def _fused_add_rms_norm_kernel( x_ptr, residual_ptr, weight_ptr, n_cols: tl.constexpr, eps: tl.constexpr, BLOCK_N: tl.constexpr, ): row = tl.program_id(0) cols = tl.arange(0, BLOCK_N) mask = cols < n_cols offsets = row * n_cols + cols x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32) residual = tl.load( residual_ptr + offsets, mask=mask, other=0.0, ).to(tl.float32) summed = (x + residual).to(tl.bfloat16) tl.store(residual_ptr + offsets, summed, mask=mask) summed_f32 = summed.to(tl.float32) variance = tl.sum(summed_f32 * summed_f32, axis=0) / n_cols normalized = ( summed_f32 * tl.rsqrt(variance + eps) ).to(tl.bfloat16) weight = tl.load(weight_ptr + cols, mask=mask, other=0.0) tl.store(x_ptr + offsets, normalized * weight, mask=mask) class LlamaDecoderLayer(nn.Module): def __init__(self, config, rotary_emb: nn.Module | None = None, bias: bool = False, qk_norm: bool = False, quant_config: dict | None = None): super().__init__() self.self_attn = LlamaAttention( config.hidden_size, config.num_attention_heads, config.num_key_value_heads, config.head_dim, rotary_emb=rotary_emb, bias=bias, qk_norm=qk_norm, rms_norm_eps=config.rms_norm_eps, quant_config=quant_config, ) self.mlp = LlamaMLP(config, quant_config=quant_config) self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) @staticmethod def _norm(layer, hidden_states, residual=None): n_cols = hidden_states.shape[-1] n_rows = hidden_states.numel() // n_cols block_n = triton.next_power_of_2(n_cols) if residual is None: out = torch.empty_like(hidden_states) _rms_norm_kernel[(n_rows,)]( hidden_states, layer.weight, out, n_cols, layer.eps, BLOCK_N=block_n, num_warps=8, ) return out if ( hidden_states.is_cuda and hidden_states.dtype == torch.bfloat16 and hidden_states.is_contiguous() and residual.is_contiguous() and n_cols == 4096 ): _C.fused_add_rms_norm_bf16( hidden_states, residual, layer.weight, layer.eps ) return hidden_states, residual _fused_add_rms_norm_kernel[(n_rows,)]( hidden_states, residual, layer.weight, n_cols, layer.eps, BLOCK_N=block_n, num_warps=8, ) return hidden_states, residual def _mlp(self, hidden_states): gate_up = self.mlp.gate_up_proj down = self.mlp.down_proj if ( hidden_states.is_cuda and hidden_states.dtype == torch.bfloat16 and not gate_up.use_fp8 and not down.use_fp8 and down.tp_size == 1 ): projected = torch._C._nn.linear( hidden_states, gate_up.weight, gate_up.bias ) activated = torch.empty( (*projected.shape[:-1], projected.shape[-1] // 2), dtype=projected.dtype, device=projected.device, ) _C.silu_and_mul_bf16(projected, activated) return torch._C._nn.linear( activated, down.weight, down.bias ) return self.mlp(hidden_states) def forward(self, positions, hidden_states, residual): if residual is None: hidden_states, residual = ( self._norm(self.input_layernorm, hidden_states), hidden_states ) else: hidden_states, residual = self._norm( self.input_layernorm, hidden_states, residual ) hidden_states = self.self_attn(positions, hidden_states) hidden_states, residual = self._norm( self.post_attention_layernorm, hidden_states, residual ) hidden_states = self._mlp(hidden_states) return hidden_states, residual