"""GLA / RetNet decoder layer. Pre-norm residual: attn_norm -> GatedLinearAttention -> residual mlp_norm -> GLAMLP -> residual Forward signature mirrors FLA's ``GLABlock.forward`` (returns a tuple of ``(hidden_states, attentions, past_key_values)``) so that the same L3 block backs both GLA and RetNet — RetNet just uses ``decay_mode="fixed_per_head"`` and ``use_rotary=True`` in the attention layer. """ 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 ..L1 import chunk_gla as _chunk_gla from ..L2 import gla_attention as _gla_attention from ..L2.gla_attention import GatedLinearAttention from ..L2.gla_mlp import GLAMLP @triton.jit def _accurate_rms_silu_gate( x, gate, weight, out, n_rows, N: tl.constexpr, eps: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, ): rows = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) cols = tl.arange(0, BLOCK_N) offsets = rows[:, None] * N + cols[None, :] mask = (rows[:, None] < n_rows) & (cols[None, :] < N) values = tl.load(x + offsets, mask=mask, other=0.0).to(tl.float32) variance = tl.sum(values * values, axis=1) / N inv_rms = tl.rsqrt(variance + eps) scales = tl.load( weight + cols[None, :], mask=cols[None, :] < N, other=0.0, ).to(tl.float32) normalized = (values * inv_rms[:, None] * scales).to(tl.bfloat16) gates = tl.load(gate + offsets, mask=mask, other=0.0).to(tl.float32) activated = (gates * tl.sigmoid(gates)).to(tl.bfloat16) tl.store(out + offsets, normalized * activated, mask=mask) _gla_attention._rms_silu_gate = _accurate_rms_silu_gate @triton.jit def _accurate_log_sigmoid_kernel( x, out, n_elements: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < n_elements values = tl.load(x + offsets, mask=mask, other=0.0).to(tl.float32) result = tl.minimum(values, 0.0) - tl.log(1.0 + tl.exp(-tl.abs(values))) tl.store(out + offsets, result, mask=mask) class _AccurateLogSigmoid(nn.Module): def forward(self, x: torch.Tensor) -> torch.Tensor: out = torch.empty_like(x) n_elements = x.numel() block_size = 2048 if n_elements <= 2048 else 4096 _accurate_log_sigmoid_kernel[(triton.cdiv(n_elements, block_size),)]( x, out, n_elements, BLOCK_SIZE=block_size, num_warps=8, ) return out @triton.jit def _dense_states_no_final( k, v, gc, states, T: tl.constexpr, H: tl.constexpr, K: tl.constexpr, V: tl.constexpr, NT: tl.constexpr, BK: tl.constexpr, BV: tl.constexpr, ): i_k = tl.program_id(0) i_v = tl.program_id(1) i_bh = tl.program_id(2) i_b, i_h = i_bh // H, i_bh % H o_k = i_k * BK + tl.arange(0, BK) o_v = i_v * BV + tl.arange(0, BV) mask_kv = (o_k[:, None] < K) & (o_v[None, :] < V) state = tl.zeros((BK, BV), tl.float32) for chunk in range(NT): state_ptrs = ( states + ((i_b * NT + chunk) * H + i_h) * K * V + o_k[:, None] * V + o_v[None, :] ) tl.store(state_ptrs, state.to(tl.bfloat16), mask=mask_kv) tokens = chunk * 64 + tl.arange(0, 64) mask_kt = (o_k[:, None] < K) & (tokens[None, :] < T) mask_tv = (tokens[:, None] < T) & (o_v[None, :] < V) last = tl.minimum((chunk + 1) * 64, T) - 1 base_k = i_b * T * H * K + i_h * K base_v = i_b * T * H * V + i_h * V last_gate = tl.load( gc + base_k + last * H * K + o_k, mask=o_k < K, other=0.0, ) gates = tl.load( gc + base_k + tokens[None, :] * H * K + o_k[:, None], mask=mask_kt, other=0.0, ) keys = tl.load( k + base_k + tokens[None, :] * H * K + o_k[:, None], mask=mask_kt, other=0.0, ) values = tl.load( v + base_v + tokens[:, None] * H * V + o_v[None, :], mask=mask_tv, other=0.0, ) state *= tl.exp2(last_gate)[:, None] gated_keys = ( keys * tl.exp2(last_gate[:, None] - gates) ).to(tl.bfloat16) state += tl.dot(gated_keys, values) @triton.jit def _dense_score_offdiagonal( q, k, gc, scores, T: tl.constexpr, H: tl.constexpr, K: tl.constexpr, BC: tl.constexpr, BK: tl.constexpr, ): i_t = tl.program_id(0) i_pair = tl.program_id(1) i_bh = tl.program_id(2) i_b, i_h = i_bh // H, i_bh % H i_i, i_j = i_pair + 1, i_pair o_i = tl.arange(0, BC) o_j = tl.arange(0, BC) t_i = i_t * 64 + i_i * BC + o_i t_j = i_t * 64 + i_j * BC + o_j score_ptrs = ( scores + (i_b * T + t_i[:, None]) * H * 64 + i_h * 64 + i_j * BC + o_j[None, :] ) valid = (t_i[:, None] < T) & (t_j[None, :] < T) values = tl.zeros((BC, BC), tl.float32) base = i_b * T * H * K + i_h * K for block in range(tl.cdiv(K, BK)): o_k = block * BK + tl.arange(0, BK) mask_i = (t_i[:, None] < T) & (o_k[None, :] < K) mask_j = (o_k[:, None] < K) & (t_j[None, :] < T) mask_k = o_k < K anchor = tl.load( gc + base + (i_t * 64 + i_i * BC) * H * K + o_k, mask=mask_k, other=0.0, ) queries = tl.load( q + base + t_i[:, None] * H * K + o_k[None, :], mask=mask_i, other=0.0, ) query_gates = tl.load( gc + base + t_i[:, None] * H * K + o_k[None, :], mask=mask_i, other=0.0, ) keys = tl.load( k + base + t_j[None, :] * H * K + o_k[:, None], mask=mask_j, other=0.0, ) key_gates = tl.load( gc + base + t_j[None, :] * H * K + o_k[:, None], mask=mask_j, other=0.0, ) gated_queries = ( queries * tl.exp2(query_gates - anchor[None, :]) * 0.0625 ) gated_keys = keys * tl.exp2(anchor[:, None] - key_gates) values += tl.dot(gated_queries, gated_keys) tl.store(score_ptrs, values, mask=valid) @triton.jit def _dense_score_diagonal( q, k, gc, scores, T: tl.constexpr, H: tl.constexpr, K: tl.constexpr, BC: tl.constexpr, BK: tl.constexpr, ): i_t = tl.program_id(0) i_c = tl.program_id(1) i_bh = tl.program_id(2) i_b, i_h = i_bh // H, i_bh % H o_i = tl.arange(0, BC) o_k = tl.arange(0, BK) t_i = i_t * 64 + i_c * BC + o_i mask_i = (t_i[:, None] < T) & (o_k[None, :] < K) base = i_b * T * H * K + i_h * K queries = tl.load( q + base + t_i[:, None] * H * K + o_k[None, :], mask=mask_i, other=0.0, ) query_gates = tl.load( gc + base + t_i[:, None] * H * K + o_k[None, :], mask=mask_i, other=0.0, ) for j in range(BC): t_j = i_t * 64 + i_c * BC + j mask_j = (o_k < K) & (t_j < T) keys = tl.load( k + base + t_j * H * K + o_k, mask=mask_j, other=0.0, ).to(tl.float32) key_gates = tl.load( gc + base + t_j * H * K + o_k, mask=mask_j, other=0.0, ).to(tl.float32) values = tl.sum( queries * keys[None, :] * tl.exp2(query_gates - key_gates[None, :]), axis=1, ) * 0.0625 score_ptrs = ( scores + (i_b * T + t_i) * H * 64 + i_h * 64 + i_c * BC + j ) tl.store( score_ptrs, tl.where(o_i >= j, values, 0.0), mask=t_i < T, ) class _AccurateChunkGLA(nn.Module): def __init__(self, fallback: nn.Module): super().__init__() self.fallback = fallback def forward( self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, g: torch.Tensor, scale: float | None = None, initial_state: torch.Tensor | None = None, output_final_state: bool = False, cu_seqlens: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor | None]: total_t, heads, key_dim, value_dim = ( q.shape[1], q.shape[2], q.shape[3], v.shape[3], ) if cu_seqlens is not None or initial_state is not None or total_t <= 65: return self.fallback( q, k, v, g, scale, initial_state, output_final_state, cu_seqlens, ) batch = q.shape[0] chunks = triton.cdiv(total_t, 64) scanned_gates = torch.empty_like(g, dtype=torch.float32) states = torch.empty( (batch, chunks, heads, key_dim, value_dim), device=q.device, dtype=torch.bfloat16, ) scores = torch.empty( (batch, total_t, heads, 64), device=q.device, dtype=torch.float32, ) out = torch.empty_like(v) _chunk_gla._dense_gate_scan[ (triton.cdiv(key_dim, 64), chunks, batch * heads) ]( g, scanned_gates, total_t, heads, key_dim, BK=64, num_warps=2, ) state_grid = ( triton.cdiv(key_dim, 64), triton.cdiv(value_dim, 32), batch * heads, ) if output_final_state: final_state = torch.empty( (batch, heads, key_dim, value_dim), device=q.device, dtype=torch.float32, ) _chunk_gla._dense_states[state_grid]( k, v, scanned_gates, states, final_state, total_t, heads, key_dim, value_dim, chunks, BK=64, BV=32, num_warps=2, num_stages=2, ) else: final_state = None _dense_states_no_final[state_grid]( k, v, scanned_gates, states, total_t, heads, key_dim, value_dim, chunks, BK=64, BV=32, num_warps=2, num_stages=2, ) _chunk_gla._dense_scores[(chunks, batch * heads)]( q, k, scanned_gates, scores, total_t, heads, key_dim, BK=32, num_warps=8, num_stages=2, ) _dense_score_offdiagonal[(chunks, 1, batch * heads)]( q, k, scanned_gates, scores, total_t, heads, key_dim, BC=16, BK=64, num_warps=4, num_stages=2, ) _dense_score_diagonal[(chunks, 4, batch * heads)]( q, k, scanned_gates, scores, total_t, heads, key_dim, BC=16, BK=256, num_warps=8, ) _chunk_gla._dense_output[ (triton.cdiv(value_dim, 128), chunks, batch * heads) ]( q, v, scanned_gates, states, scores, out, total_t, heads, key_dim, value_dim, chunks, BK=64, BV=128, num_warps=8, num_stages=2, ) return out, final_state if output_final_state else None class GLADecoderLayer(nn.Module): def __init__(self, config, layer_idx: int): super().__init__() self.layer_idx = layer_idx self.attn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) self.attn = GatedLinearAttention( hidden_size=config.hidden_size, num_heads=config.num_heads, expand_k=config.expand_k, expand_v=config.expand_v, decay_mode=getattr(config, "decay_mode", "learned_low_rank"), gate_low_rank_dim=getattr(config, "gate_low_rank_dim", 16), gate_logit_normalizer=getattr(config, "gate_logit_normalizer", 16), use_rotary=getattr(config, "use_rotary", False), rotary_base=getattr(config, "rotary_base", 10000.0), rotary_max_position=getattr(config, "max_position_embeddings", 8192), norm_eps=config.norm_eps, ) if self.attn.decay_mode == "learned_low_rank": self.attn.log_sigmoid = _AccurateLogSigmoid() self.attn.chunk = _AccurateChunkGLA(self.attn.chunk) self.mlp_norm = RMSNorm(config.hidden_size, eps=config.norm_eps) self.mlp = GLAMLP(config.hidden_size, config.intermediate_size) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, past_key_values=None, use_cache: bool = False, **kwargs, ) -> tuple[torch.Tensor, None, object | None]: residual = hidden_states h = self.attn_norm( hidden_states.reshape(-1, hidden_states.size(-1)) ).reshape_as(hidden_states) if ( hidden_states.shape[0] == 1 and kwargs.get("cu_seqlens") is not None and kwargs["cu_seqlens"].numel() == 2 ): kwargs = dict(kwargs) kwargs.pop("cu_seqlens") h, attentions, past_key_values = self.attn( hidden_states=h, attention_mask=attention_mask, past_key_values=past_key_values, use_cache=use_cache and past_key_values is not None, **kwargs, ) h, residual = self.mlp_norm( h.reshape(-1, h.size(-1)), residual.reshape(-1, residual.size(-1)), ) h = h.reshape_as(hidden_states) residual = residual.reshape_as(hidden_states) hidden_states = residual.add_(self.mlp(h)) return hidden_states, attentions, past_key_values