from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl from ..L1.rms_norm import RMSNorm from ..L2.kimi_delta_attention import KimiDeltaAttention from ..L2.kimi_mla_attention import KimiMLAAttention from ..L2.kimi_moe import KimiMoE from ..L2.llama_mlp import LlamaMLP @triton.jit def _clone_rms_norm_kernel( x_ptr, weight_ptr, out_ptr, residual_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) tl.store(residual_ptr + offsets, x, mask=mask) x_f32 = x.to(tl.float32) variance = tl.sum(x_f32 * x_f32, axis=0) / n_cols rstd = tl.rsqrt(variance + eps) weight = tl.load(weight_ptr + cols, mask=mask, other=0.0).to(tl.float32) tl.store(out_ptr + offsets, x_f32 * rstd * weight, mask=mask) class KimiLinearDecoderLayer(nn.Module): def __init__(self, config, layer_idx: int, quant_config: dict | None = None): super().__init__() self.layer_idx = layer_idx self.is_kda = config.is_kda_layer(layer_idx) if self.is_kda: self.self_attn = KimiDeltaAttention( config, layer_idx=layer_idx, quant_config=quant_config, ) else: self.self_attn = KimiMLAAttention( config, quant_config=quant_config, ) if config.is_moe_layer(layer_idx): self.block_sparse_moe = KimiMoE(config, quant_config=quant_config) self.mlp = self.block_sparse_moe else: 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, ) def forward(self, hidden_states, residual, state_manager=None): if ( residual is None and hidden_states.is_cuda and hidden_states.dtype == torch.bfloat16 and hidden_states.is_contiguous() and hidden_states.shape[-1] == 2304 ): residual = torch.empty_like(hidden_states) normalized = torch.empty_like(hidden_states) _clone_rms_norm_kernel[(hidden_states.numel() // 2304,)]( hidden_states, self.input_layernorm.weight, normalized, residual, n_cols=2304, eps=self.input_layernorm.eps, BLOCK_N=4096, num_warps=8, ) hidden_states = normalized elif residual is None: residual = hidden_states.clone() hidden_states = self.input_layernorm(hidden_states) else: hidden_states, residual = self.input_layernorm(hidden_states, residual) hidden_states = self.self_attn( hidden_states, state_manager=state_manager, ) hidden_states, residual = self.post_attention_layernorm( hidden_states, residual, ) hidden_states = self.mlp(hidden_states) return hidden_states, residual