diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9446f8263d1bb4736ccf4d5a0ddf4daffb63fc89 --- /dev/null +++ b/__init__.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- + +from .layers import ( + # ABCAttention, + # Attention, + # BasedLinearAttention, + # BitAttention, + # Comba, + # DeltaFormerAttention, + # DeltaNet, + # GatedDeltaNet, + # GatedDeltaProduct, + # GatedLinearAttention, + # GatedSlotAttention, + # HGRN2Attention, + # HGRNAttention, + # LightNetAttention, + # LinearAttention, + # LogLinearMamba2, + # MesaNet, + # MomAttention, + # MultiheadLatentAttention, + # MultiScaleRetention, + # NativeSparseAttention, + # PaTHAttention, + # ReBasedLinearAttention, + # RodimusAttention, + # RWKV6Attention, + # RWKV7Attention + mask_gdn +) +from .models import ( + # ABCForCausalLM, + # ABCModel, + # BitNetForCausalLM, + # BitNetModel, + # CombaForCausalLM, + # CombaModel, + # DeltaFormerForCausalLM, + # DeltaFormerModel, + # DeltaNetForCausalLM, + # DeltaNetModel, + # GatedDeltaNetForCausalLM, + # GatedDeltaNetModel, + # GatedDeltaProductForCausalLM, + # GatedDeltaProductModel, + # GLAForCausalLM, + # GLAModel, + # GSAForCausalLM, + # GSAModel, + # HGRN2ForCausalLM, + # HGRN2Model, + # HGRNForCausalLM, + # HGRNModel, + # LightNetForCausalLM, + # LightNetModel, + # LinearAttentionForCausalLM, + # LinearAttentionModel, + # LogLinearMamba2ForCausalLM, + # LogLinearMamba2Model, + # MesaNetForCausalLM, + # MesaNetModel, + # MLAForCausalLM, + # MLAModel, + # MomForCausalLM, + # MomModel, + # NSAForCausalLM, + # NSAModel, + # PaTHAttentionForCausalLM, + # PaTHAttentionModel, + # RetNetForCausalLM, + # RetNetModel, + mask_gdnForCausalLM, + mask_gdnModel, + # RodimusForCausalLM, + # RodimusModel, + # RWKV6ForCausalLM, + # RWKV6Model, + # RWKV7ForCausalLM, + # RWKV7Model, + # TransformerForCausalLM, + # TransformerModel +) + +# __all__ = [ +# 'ABCAttention', 'ABCForCausalLM', 'ABCModel', +# 'Attention', 'TransformerForCausalLM', 'TransformerModel', +# 'BasedLinearAttention', +# 'BitAttention', 'BitNetForCausalLM', 'BitNetModel', +# 'Comba', 'CombaForCausalLM', 'CombaModel', +# 'DeltaNet', 'DeltaNetForCausalLM', 'DeltaNetModel', +# 'DeltaFormerAttention', 'DeltaFormerForCausalLM', 'DeltaFormerModel', +# 'GatedDeltaNet', 'GatedDeltaNetForCausalLM', 'GatedDeltaNetModel', +# 'GatedDeltaProduct', 'GatedDeltaProductForCausalLM', 'GatedDeltaProductModel', +# 'GatedLinearAttention', 'GLAForCausalLM', 'GLAModel', +# 'GatedSlotAttention', 'GSAForCausalLM', 'GSAModel', +# 'HGRNAttention', 'HGRNForCausalLM', 'HGRNModel', +# 'HGRN2Attention', 'HGRN2ForCausalLM', 'HGRN2Model', +# 'LightNetAttention', 'LightNetForCausalLM', 'LightNetModel', +# 'LinearAttention', 'LinearAttentionForCausalLM', 'LinearAttentionModel', +# 'LogLinearMamba2', 'LogLinearMamba2ForCausalLM', 'LogLinearMamba2Model', +# 'MesaNet', 'MesaNetForCausalLM', 'MesaNetModel', +# 'MomAttention', 'MomForCausalLM', 'MomModel', +# 'MultiheadLatentAttention', 'MLAForCausalLM', 'MLAModel', +# 'MultiScaleRetention', 'RetNetForCausalLM', 'RetNetModel', +# 'NativeSparseAttention', 'NSAForCausalLM', 'NSAModel', +# 'PaTHAttention', 'PaTHAttentionForCausalLM', 'PaTHAttentionModel', +# 'ReBasedLinearAttention', +# 'RodimusAttention', 'RodimusForCausalLM', 'RodimusModel', +# 'RWKV6Attention', 'RWKV6ForCausalLM', 'RWKV6Model', +# 'RWKV7Attention', 'RWKV7ForCausalLM', 'RWKV7Model', +# ] + +__version__ = '0.3.2' diff --git a/layers/__init__.py b/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ea9e082a8051f097c5a901b35de105b5d4aa59 --- /dev/null +++ b/layers/__init__.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +# from .abc import ABCAttention +# from .attn import Attention +# from .based import BasedLinearAttention +# from .bitattn import BitAttention +# from .comba import Comba +# from .delta_net import DeltaNet +# from .deltaformer import DeltaFormerAttention +# from .forgetting_attn import ForgettingAttention +# from .gated_deltanet import GatedDeltaNet +# from .gated_deltaproduct import GatedDeltaProduct +# from .gla import GatedLinearAttention +# from .gsa import GatedSlotAttention +# from .hgrn import HGRNAttention +# from .hgrn2 import HGRN2Attention +# from .lightnet import LightNetAttention +# from .linear_attn import LinearAttention +# from .log_linear_mamba2 import LogLinearMamba2 +# from .mamba import Mamba +# from .mamba2 import Mamba2 +# from .mesa_net import MesaNet +# from .mla import MultiheadLatentAttention +# from .mom import MomAttention +# from .multiscale_retention import MultiScaleRetention +# from .nsa import NativeSparseAttention +# from .path_attn import PaTHAttention +# from .rebased import ReBasedLinearAttention +# from .rodimus import RodimusAttention, SlidingWindowSharedKeyAttention +# from .rwkv6 import RWKV6Attention +# from .rwkv7 import RWKV7Attention +from .mask_gdn import mask_gdn +# __all__ = [ +# 'ABCAttention', +# 'Attention', +# 'BasedLinearAttention', +# 'BitAttention', +# 'Comba', +# 'DeltaNet', +# 'ForgettingAttention', +# 'GatedDeltaNet', +# 'GatedDeltaProduct', +# 'GatedLinearAttention', +# 'GatedSlotAttention', +# 'HGRNAttention', +# 'HGRN2Attention', +# 'LightNetAttention', +# 'LinearAttention', +# 'LogLinearMamba2', +# 'Mamba', +# 'Mamba2', +# 'MesaNet', +# 'MomAttention', +# 'MultiheadLatentAttention', +# 'MultiScaleRetention', +# 'NativeSparseAttention', +# 'PaTHAttention', +# 'ReBasedLinearAttention', +# 'RodimusAttention', +# 'RWKV6Attention', +# 'RWKV7Attention', +# 'SlidingWindowSharedKeyAttention', +# 'DeltaFormerAttention', +# 'maskgdn', +# ] diff --git a/layers/abc.py b/layers/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..765a8e367390703ef6c3feefef76517a96c5a368 --- /dev/null +++ b/layers/abc.py @@ -0,0 +1,232 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange + +from fla.modules import FusedRMSNormGated, RMSNorm, RotaryEmbedding, ShortConvolution +from fla.modules.activations import swiglu, swish +from fla.ops.abc.chunk import chunk_abc + +if TYPE_CHECKING: + from fla.models.utils import Cache + + +class ABCAttention(nn.Module): + + def __init__( + self, + hidden_size: int = 1024, + expand_k: float = 0.5, + expand_v: float = 1.0, + num_heads: int = 4, + use_short_conv: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + num_slots: Optional[int] = None, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-5, + gate_low_rank_dim: int = 16, + gate_logit_normalizer: int = 16, + use_rope: bool = True, + use_input_gate: bool = False, + use_output_gate: bool = True, + use_norm: bool = True, + clamp_min: Optional[float] = -32, + clamp_max: Optional[float] = 32, + layer_idx: Optional[int] = None, + **kwargs + ) -> ABCAttention: + super().__init__() + + self.hidden_size = hidden_size + self.expand_k = expand_k + self.expand_v = expand_v + self.num_heads = num_heads + self.key_dim = int(self.hidden_size * self.expand_k) + self.value_dim = int(self.hidden_size * self.expand_v) + self.head_k_dim = self.key_dim // self.num_heads + self.head_v_dim = self.value_dim // self.num_heads + + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.gate_low_rank_dim = gate_low_rank_dim + self.gate_logit_normalizer = gate_logit_normalizer + + self.use_rope = use_rope + self.use_input_gate = use_input_gate + self.use_output_gate = use_output_gate + self.use_norm = use_norm + + if num_slots is None: + num_slots = self.head_k_dim + self.num_slots = num_slots + + self.norm_eps = norm_eps + + self.clamp_min = clamp_min + self.clamp_max = clamp_max + self.layer_idx = layer_idx + + if layer_idx is None: + warnings.warn( + f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " + "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " + "when creating this class." + ) + + self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False) + + if use_output_gate: + self.g_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False) + self.s_proj = nn.Linear(self.hidden_size, self.num_heads * self.num_slots, bias=False) + self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False) + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + + if self.use_norm: + if self.use_output_gate: + self.g_norm = FusedRMSNormGated( + hidden_size=self.head_v_dim, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + else: + self.g_norm = RMSNorm( + hidden_size=self.head_v_dim, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + + if self.use_rope: + self.rotary = RotaryEmbedding(self.head_k_dim) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if cu_seqlens is not None: + raise NotImplementedError("Training with cu_seqlens is not supported yet for ABCAttention") + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + mask=conv_mask, + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + mask=conv_mask, + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + mask=conv_mask, + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + + if self.use_input_gate: + q, k, v = map(lambda x: swish(x), (q, k, v)) + # dealing with left-padding + if attention_mask is not None: + v = v.mul_(attention_mask[:, -v.shape[-2]:, None]) + + q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k)) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + if self.use_rope: + seqlen_offset = 0 + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + q, k = self.rotary(q, k, seqlen_offset=seqlen_offset) + + s = rearrange(self.s_proj(hidden_states), '... (h m) -> ... h m', m=self.num_slots) + s = s.clamp_(self.clamp_min, self.clamp_max) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + o, recurrent_state = chunk_abc( + q=q, + k=k, + v=v, + s=s, + initial_state=recurrent_state, + output_final_state=use_cache, + ) + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q.shape[1] + ) + + if self.use_norm and not self.use_output_gate: + o = self.g_norm(o) + elif self.use_output_gate: + g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim) + o = self.g_norm(o, g) if self.use_norm else swiglu(g, o) + o = rearrange(o, '... h d -> ... (h d)') + o = self.o_proj(o) + + return o, None, past_key_values + + def state_size(self, seq_len: int = 2048): + return 2 * self.num_slots * self.hidden_size diff --git a/layers/attn.py b/layers/attn.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd5d5bed314738fcba80c898b19f215d75240f7 --- /dev/null +++ b/layers/attn.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from transformers.utils import logging + +from fla.layers.utils import pad_input, unpad_input +from fla.modules import RMSNorm, RotaryEmbedding +from fla.ops.utils.index import prepare_lens_from_mask + +if TYPE_CHECKING: + from fla.models.utils import Cache + +try: + from flash_attn import flash_attn_func, flash_attn_varlen_func +except ImportError: + warnings.warn( + "Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`", + category=ImportWarning + ) + flash_attn_func = None + +logger = logging.get_logger(__name__) + + +class Attention(nn.Module): + + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 32, + num_kv_heads: Optional[int] = None, + qkv_bias: bool = False, + qk_norm: bool = False, + window_size: Optional[int] = None, + rope_theta: Optional[float] = 10000., + max_position_embeddings: Optional[int] = None, + layer_idx: int = None + ): + super().__init__() + + self.hidden_size = hidden_size + self.num_heads = num_heads + if num_kv_heads is None: + self.num_kv_heads = self.num_heads + else: + self.num_kv_heads = num_kv_heads + self.num_kv_groups = num_heads // self.num_kv_heads + self.head_dim = self.hidden_size // self.num_heads + self.kv_dim = self.num_kv_heads * self.head_dim + self.qkv_bias = qkv_bias + self.qk_norm = qk_norm + + self.window_size = window_size + self.rope_theta = rope_theta + self.max_position_embeddings = max_position_embeddings + self.layer_idx = layer_idx + + if flash_attn_func is None: + raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first") + + self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias) + self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + + if qk_norm: + self.q_norm = RMSNorm(self.head_dim) + self.k_norm = RMSNorm(self.head_dim) + + self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.size() + + q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + + if self.qk_norm: + q, k = self.q_norm(q), self.k_norm(k) + + # equivalent to cu_seqlens in `flash_attn` + cu_seqlens = kwargs.get('cu_seqlens', None) + + seqlen_offset, max_seqlen = 0, q_len + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + max_seqlen = q.shape[1] + seqlen_offset + + if attention_mask is not None: + # to deliminate the offsets of padding tokens + seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1] + max_seqlen = q.shape[1] + max(seqlen_offset) + + if self.max_position_embeddings is not None: + max_seqlen = max(max_seqlen, self.max_position_embeddings) + q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens) + + if past_key_values is not None: + cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0 + k_cached, v_cached = past_key_values.update( + attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)), + layer_idx=self.layer_idx, + offset=q_len, + cache_kwargs=dict(window_size=self.window_size) + )['attn_state'] + if cache_has_content: + k, v = k_cached, v_cached + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + + # Contains at least one padding token in the sequence + if attention_mask is not None: + if q.shape[1] == 1 and self.window_size is not None: + attention_mask = attention_mask[:, -self.window_size:] + q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len) + cu_seqlens_q, cu_seqlens_k = cu_seqlens + max_seqlen_q, max_seqlen_k = max_seq_lens + o = flash_attn_varlen_func( + q, k, v, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + o = pad_input(o, indices_q, batch_size, q_len) + elif cu_seqlens is not None: + o = flash_attn_varlen_func( + q.squeeze(0), k.squeeze(0), v.squeeze(0), + cu_seqlens_q=cu_seqlens, + cu_seqlens_k=cu_seqlens, + max_seqlen_q=max_seqlen, + max_seqlen_k=max_seqlen, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ).unsqueeze(0) + else: + o = flash_attn_func( + q, k, v, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + o = o.reshape(batch_size, q_len, -1) + o = self.o_proj(o) + + if not output_attentions: + attentions = None + + return o, attentions, past_key_values diff --git a/layers/based.py b/layers/based.py new file mode 100644 index 0000000000000000000000000000000000000000..d21613a7c3ed01f0b9cb19a3b488d3f4b4d240c1 --- /dev/null +++ b/layers/based.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +""" +Linear attention in Based. +https://github.com/HazyResearch/zoology/blob/main/zoology/mixers/based.py +""" + +import torch +import torch.nn as nn +from einops import rearrange + +from fla.modules.feature_map import TaylorFeatureMap +from fla.ops.based import parallel_based +from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn + + +class BasedLinearAttention(nn.Module): + + def __init__( + self, + hidden_size: int, + feature_dim: int = 16, + num_key_value_heads: int = 12, + num_heads: int = 12, + feature_name: str = "taylor_exp", + eps: float = 1e-12, + causal: bool = True, + mode: str = "parallel", + ): + super().__init__() + + self.hidden_size = hidden_size + self.mode = mode + self.feature_name = feature_name + self.feature_dim = feature_dim + self.num_key_value_heads = num_key_value_heads + self.num_heads = num_heads + self.head_dim = self.hidden_size // self.num_key_value_heads + assert self.hidden_size % self.head_dim == 0 + self.causal = causal + + self.q_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) + self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) + self.dropout = nn.Identity() + self.feature_map = TaylorFeatureMap(feature_dim) + self.eps = eps + + def forward(self, hidden_states: torch.Tensor, **kwargs): + mode = self.mode + q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states) + q, k, v = map(lambda x: rearrange(x, "... (h d) -> ... h d", d=self.head_dim), [q, k, v]) + if mode == "fused_chunk": + q, k = self.feature_map(q), self.feature_map(k) + o, _ = fused_chunk_linear_attn(q, k, v, normalize=True, scale=1) + elif mode == 'chunk': + q, k = self.feature_map(q), self.feature_map(k) + o, _ = chunk_linear_attn(q, k, v, normalize=True, scale=1) + elif mode == 'parallel': + assert q.shape[-1] <= 128 + o = parallel_based(q, k, v, scale=1, use_norm=True) + o = rearrange(o, 'b t h d -> b t (h d)') + o = self.o_proj(o) + o = self.dropout(o) + return o + + def forward_reference(self, hidden_states: torch.Tensor, **kwargs): + """ + x (torch.Tensor): tensor of shape (b, d, t) + y (torch.Tensor): tensor of shape (b, d, t) + """ + # hidden_states = hidden_states.transpose(1, 2) + b, t, _ = hidden_states.size() + q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states) + + q = q.view(b, t, self.num_heads, self.feature_dim).transpose(1, 2) + k = k.view(b, t, self.num_key_value_heads, self.feature_dim).transpose(1, 2) + v = v.view(b, t, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + # Linear attention + q, k = self.feature_map(q), self.feature_map(k) + q, k, v = q.unsqueeze(-2), k.unsqueeze(-2), v.unsqueeze(-1) + + # Compute attention + if self.causal: + y = ((q * (k * v).cumsum(2)).sum(-1) / ((q * k.cumsum(2)).sum(-1) + self.eps)) + else: + y = ((q * (k * v).sum(2, True)).sum(-1) / ((q * k.sum(2, True)).sum(-1) + self.eps)) + y = rearrange(y, 'b h t d -> b t (h d)') + y = self.o_proj(y.to(hidden_states.dtype)) + y = self.dropout(y) + return y.to(hidden_states.dtype) diff --git a/layers/bitattn.py b/layers/bitattn.py new file mode 100644 index 0000000000000000000000000000000000000000..a6d130b22932e058978423ed12f2d6e68bef2c8e --- /dev/null +++ b/layers/bitattn.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from transformers.utils import logging + +from fla.layers.utils import pad_input, unpad_input +from fla.modules import RotaryEmbedding +from fla.modules.fused_bitlinear import FusedBitLinear +from fla.ops.utils.index import prepare_lens_from_mask + +if TYPE_CHECKING: + from fla.models.utils import Cache + +try: + from flash_attn import flash_attn_func, flash_attn_varlen_func +except ImportError: + warnings.warn( + "Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`", + category=ImportWarning + ) + flash_attn_func = None + +logger = logging.get_logger(__name__) + + +class BitAttention(nn.Module): + + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 32, + num_kv_heads: Optional[int] = None, + window_size: Optional[int] = None, + rope_theta: Optional[float] = 10000., + max_position_embeddings: Optional[int] = None, + norm_eps: float = 1e-5, + layer_idx: int = None + ): + super().__init__() + + self.num_heads = num_heads + if num_kv_heads is None: + self.num_kv_heads = self.num_heads + else: + self.num_kv_heads = num_kv_heads + self.num_kv_groups = num_heads // self.num_kv_heads + self.hidden_size = hidden_size + self.head_dim = self.hidden_size // self.num_heads + self.kv_dim = self.num_kv_heads * self.head_dim + self.kv_dim = self.num_kv_heads * self.head_dim + self.window_size = window_size + self.rope_theta = rope_theta + self.max_position_embeddings = max_position_embeddings + self.layer_idx = layer_idx + + self.q_proj = FusedBitLinear(self.hidden_size, self.hidden_size, bias=False) + self.k_proj = FusedBitLinear(self.hidden_size, self.kv_dim, bias=False) + self.v_proj = FusedBitLinear(self.hidden_size, self.kv_dim, bias=False) + self.o_proj = FusedBitLinear(self.hidden_size, self.hidden_size, bias=False) + + self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.size() + + q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + + # equivalent to cu_seqlens in `flash_attn` + cu_seqlens = kwargs.get('cu_seqlens', None) + + seqlen_offset, max_seqlen = 0, q_len + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + max_seqlen = q.shape[1] + seqlen_offset + + if attention_mask is not None: + # to deliminate the offsets of padding tokens + seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1] + max_seqlen = q.shape[1] + max(seqlen_offset) + + if self.max_position_embeddings is not None: + max_seqlen = max(max_seqlen, self.max_position_embeddings) + q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens) + + if past_key_values is not None: + cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0 + k_cached, v_cached = past_key_values.update( + attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)), + layer_idx=self.layer_idx, + offset=q_len, + cache_kwargs=dict(window_size=self.window_size) + )['attn_state'] + if cache_has_content: + k, v = k_cached, v_cached + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + + if flash_attn_func is None: + raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first") + + # Contains at least one padding token in the sequence + if attention_mask is not None: + q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len) + cu_seqlens_q, cu_seqlens_k = cu_seqlens + max_seqlen_q, max_seqlen_k = max_seq_lens + o = flash_attn_varlen_func( + q, k, v, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + o = pad_input(o, indices_q, batch_size, q_len) + elif cu_seqlens is not None: + o = flash_attn_varlen_func( + q.squeeze(0), k.squeeze(0), v.squeeze(0), + cu_seqlens_q=cu_seqlens, + cu_seqlens_k=cu_seqlens, + max_seqlen_q=max_seqlen, + max_seqlen_k=max_seqlen, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ).unsqueeze(0) + else: + o = flash_attn_func( + q, k, v, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + o = o.reshape(batch_size, q_len, -1) + o = self.o_proj(o) + + if not output_attentions: + attentions = None + + return o, attentions, past_key_values diff --git a/layers/comba.py b/layers/comba.py new file mode 100644 index 0000000000000000000000000000000000000000..45e26c51615bce0cf71fe45ca5c66917623e5551 --- /dev/null +++ b/layers/comba.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange, repeat +from torch.nn import functional as F + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.ops.comba import chunk_comba, fused_recurrent_comba + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class Comba(nn.Module): + """ + The layer implementaion for [Comba: Improving Bilinear RNNs with Closed-loop Control](https://arxiv.org/abs/2506.02475). + + Similar to Mamba2 and Gated-DeltaNet, each layer contains around 6*hidden_size*hidden_size parameters. + + Parameter alloation when use_output_gate=True: + - 0.75 * hidden_size * hidden_size for the q_proj and k_proj each + - 1.5 * hidden_size * hidden_size for the v_proj, g_proj and o_proj each + - Others are ignorably small. + - In total = 0.75 * 2 + 1.5 * 3 = 6 * hidden_size * hidden_size + NOTE: num_heads * head_dim = 0.75 * hidden_size, please make sure to set the correct num_heads and head_dim. + + Parameter allocation when use_output_gate=False: + - 1 * hidden_size * hidden_size for the q_proj and k_proj each + - 2 * hidden_size * hidden_size for the v_proj and o_proj each + - Others are ignorably small. + - In total = 1 * 2 + 2 * 2 = 6 * hidden_size * hidden_size + + Args: + hidden_size (int, Optional): + The hidden size of the input. Default: 2048. + expand_v (float, Optional): + The expansion ratio for the value dim. Default: 2.0. + head_dim (int, Optional): + The dimension of each head. Default: 256. + num_heads (int, Optional): + The number of heads. Default: 4. + num_v_heads (int, Optional): + The number of heads for the value projection, equal to `num_heads` if `None`. + GVA is applied if `num_v_heads` > `num_heads`. Default: `None`. + mode (str, Optional): + Which Gated DeltaNet kernel to use. + Currently available: `chunk` and `fused_recurrent`. + Default: `chunk`. + use_beta (bool, Optional): + Whether to use beta. Default: `True`. + use_output_gate (bool, Optional): + Whether to use output gate. Default: `True`. + use_output_correction (bool, Optional): + Whether to use . Default: `True`. + use_short_conv (bool, Optional): + Whether to use short convolutions. Default: `True`. + conv_size (int, Optional): + The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4. + conv_bias (bool, Optional): + Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`. + layer_idx (int, Optional): + The index of the layer. Default: None. + norm_eps (float, Optional): + The epsilon value for the normalization layer. Default: 1e-5. + """ + + def __init__( + self, + hidden_size: int = 2048, + expand_v: float = 2, + head_dim: int = 256, + num_heads: int = 6, + num_v_heads: int = None, + mode: str = 'chunk', + use_short_conv: bool = True, + use_output_gate: bool = True, + use_output_correction: bool = True, + use_inner_decay: bool = True, + correction_factor: float = 1., + conv_size: int = 4, + conv_bias: bool = False, + layer_idx: int = None, + norm_eps: float = 1e-5, + **kwargs + ) -> Comba: + super().__init__() + + self.mode = mode + + self.hidden_size = hidden_size + self.expand_v = expand_v + + self.use_short_conv = use_short_conv + self.use_output_gate = use_output_gate + self.use_output_correction = use_output_correction + self.use_inner_decay = use_inner_decay + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.head_dim = head_dim + self.num_heads = num_heads + self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads + + self.head_k_dim = head_dim + self.head_v_dim = int(self.head_dim * self.expand_v) + self.key_dim = int(self.num_heads * self.head_k_dim) + self.value_dim = int(self.num_v_heads * self.head_v_dim) + self.layer_idx = layer_idx + + # Consistency check: Ensure expand_v produces integer values + if not math.isclose(self.num_v_heads * self.head_dim * expand_v, self.value_dim, rel_tol=1e-5): + raise ValueError( + f"expand_v={expand_v} does not produce an integer value when multiplied by key_dim={self.key_dim}. " + f"Resulting value_dim would be {self.num_v_heads * self.head_dim * expand_v}, which is invalid for nn.Linear." + ) + if self.num_v_heads > self.num_heads and self.num_v_heads % self.num_heads != 0: + raise ValueError( + f"num_v_heads={self.num_v_heads} must be divisible by num_heads={self.num_heads}." + ) + + if not math.isclose(head_dim * expand_v, self.head_v_dim, rel_tol=1e-5): + raise ValueError( + f"expand_v={expand_v} does not produce an integer value when multiplied by head_dim={head_dim}. " + f"Resulting head_v_dim would be {head_dim * expand_v}, which is invalid for FusedRMSNormGated." + ) + assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`." + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.a_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False) + self.b_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False) + + if use_inner_decay: + self.decay = nn.Parameter(torch.ones(self.num_heads)) + + if use_output_correction: + warnings.warn( + "The correction_factor is set to 1 by default similar to Mamba2. " + "However, we find that sometimes correction_factor = 0.02 works better for small-scale models. " + "In practice, we recommend trying both settings. " + ) + self.D = nn.Parameter(torch.ones(self.num_heads) * correction_factor) + self.D._no_weight_decay = True + + A = torch.empty(self.num_v_heads, dtype=torch.float32).uniform_(0, 16) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + # hard coded for now + dt_min = 0.001 + dt_max = 0.1 + dt_init_floor = 1e-4 + dt = torch.exp( + torch.rand(self.num_v_heads) * (math.log(dt_max) - math.log(dt_min)) + + math.log(dt_min) + ) + dt = torch.clamp(dt, min=dt_init_floor) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + self.dt_bias = nn.Parameter(inv_dt) + # Just to be explicit. Without this we already don't put wd on dt_bias because of the check + # name.endswith("bias") in param_grouping.py + self.dt_bias._no_weight_decay = True + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + else: + warnings.warn( + "ShortConvolution is crucial to the performance. " + "Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing." + ) + if use_output_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.o_norm = FusedRMSNormGated(self.head_v_dim, activation='sigmoid', eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + # change to inference mode. + mode = 'fused_recurrent' if q_len <= 64 else self.mode + if self.training: + assert mode == 'chunk', "Only chunk mode is supported in training." + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = F.silu(self.q_proj(hidden_states)) + k = F.silu(self.k_proj(hidden_states)) + v = F.silu(self.v_proj(hidden_states)) + + q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k)) + + if self.use_inner_decay: + p = k * self.decay[None, None, :, None].sigmoid() + else: + p = k + + if self.use_output_correction: + q = q - self.D[None, None, :, None] * p + + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + + if self.num_v_heads > self.num_heads: + q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k)) + + beta = self.b_proj(hidden_states).sigmoid() + g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'chunk': + o, recurrent_state = chunk_comba( + q=q, + k=k, + v=v, + p=p, + g=g, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True + ) + elif mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_comba( + q=q, + k=k, + v=v, + p=p, + g=g, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + if self.use_output_gate: + g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim) + o = self.o_norm(o, g) + else: + o = self.o_norm(o) + o = rearrange(o, 'b t h d -> b t (h d)') + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/delta_net.py b/layers/delta_net.py new file mode 100644 index 0000000000000000000000000000000000000000..3b69154f5d3da455aa3a7c21c8c353e943904063 --- /dev/null +++ b/layers/delta_net.py @@ -0,0 +1,290 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from torch.nn import functional as F + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.ops.delta_rule import chunk_delta_rule, fused_recurrent_delta_rule + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +def elu_p1(x): + return (F.elu(x, 1., False) + 1.).to(x) + + +def sum_norm(x): + return (x / x.sum(-1, keepdim=True)).to(x) + + +class DeltaNet(nn.Module): + r""" + The layer implementaion for [Parallelizing Linear Transformers with the Delta Rule over Sequence Length](https://arxiv.org/abs/2406.06484). # noqa: + DeltaNet was originally proposed in [Linear Transformers Are Secretly Fast Weight Programmers](https://arxiv.org/abs/2102.11174). # noqa + + Args: + mode (str, Optional): + Which DeltaNet kernel to use. + Currently available: `chunk`, `fused_recurrent`, and `fused_chunk`. + Default: `chunk`. + hidden_size (int, Optional): + The hidden size of the input. Default: 1024. + expand_k (float, Optional): + The expansion ratio for the key dim. Default: 1.0. + expand_v (float, Optional): + The expansion ratio for the value dim. Default: 1.0. + num_heads (int, Optional): + The number of heads. Default: 4. + use_beta (bool, Optional): + Whether to use beta. Default: `True`. + use_gate (bool, Optional): + Whether to use output gate. Default: `False`. + use_short_conv (bool, Optional): + Whether to use short convolutions. Default: `True`. + conv_size (int, Optional): + The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4. + conv_bias (bool, Optional): + Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`. + allow_neg_eigval (bool, Optional): + Allow negative eigenvalues. Default: `False`. If set to `True`, the beta will be multiplied by 2. + See reference: [Unlocking State-Tracking in Linear RNNs Through Negative Eigenvalues](https://arxiv.org/abs/2411.12537) + layer_idx (int, Optional): + The index of the layer. Default: None. + norm_eps (float, Optional): + The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5. + qk_activation (str, Optional): + The activation function for the query and key. Default: `silu`. + qk_norm (str, Optional): + The normalization method for the query and key. Default: `l2`. + """ + + def __init__( + self, + mode: str = 'chunk', + d_model: int = None, + hidden_size: int = 1024, + expand_k: float = 1.0, + expand_v: float = 1.0, + num_heads: int = 4, + use_beta: bool = True, + use_gate: bool = False, + use_short_conv: bool = True, + conv_size: int = 4, + conv_bias: bool = False, + allow_neg_eigval: bool = False, + layer_idx: int = None, + qk_activation: str = 'silu', + qk_norm: str = 'l2', + norm_eps: float = 1e-5, + **kwargs + ) -> DeltaNet: + super().__init__() + + self.mode = mode + self.qk_activation = qk_activation + self.qk_norm = qk_norm + + assert self.qk_activation in ['silu', 'relu', 'elu', 'identity'] + assert self.qk_norm in ['l2', 'sum'] + + if d_model is not None: + hidden_size = d_model + self.hidden_size = hidden_size + self.expand_k = expand_k + self.expand_v = expand_v + self.num_heads = num_heads + self.use_gate = use_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + self.allow_neg_eigval = allow_neg_eigval + + self.key_dim = int(hidden_size * expand_k) + self.value_dim = int(hidden_size * expand_v) + self.head_k_dim = self.key_dim // num_heads + self.head_v_dim = self.value_dim // num_heads + self.layer_idx = layer_idx + + if mode == 'fused_chunk': + raise NotImplementedError("fused_chunk_delta_rule is now deprecated. Please use `chunk_delta_rule` instead.") + assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`." + assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" + assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + + self.use_beta = use_beta + if self.use_beta: + self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False) + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' if qk_activation == 'silu' else None + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' if qk_activation == 'silu' else None + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + else: + warnings.warn( + "ShortConvolution is crucial to the performance. " + "Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing." + ) + if use_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) + + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + # change to inference mode. + mode = 'fused_recurrent' if q_len <= 64 else self.mode + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + if self.qk_activation == 'silu': + q, k = F.silu(q), F.silu(k) + v = F.silu(self.v_proj(hidden_states)) + + q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k)) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + if self.qk_activation != 'silu': + if self.qk_activation == 'relu': + q, k = q.relu(), k.relu() + elif self.qk_activation == 'elu': + q, k = elu_p1(q), elu_p1(k) + elif self.qk_activation != 'identity': + raise NotImplementedError + + if self.qk_norm == 'sum': + q = sum_norm(q).to(q) + k = sum_norm(k).to(k) + + if self.use_beta: + beta = self.b_proj(hidden_states).sigmoid() + else: + beta = torch.ones_like(q[..., 0]) + + if self.allow_neg_eigval: + beta = beta * 2. + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_delta_rule( + q=q, + k=k, + v=v, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True if self.qk_norm == 'l2' else False + ) + elif mode == 'chunk': + o, recurrent_state = chunk_delta_rule( + q=q, + k=k, + v=v, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True if self.qk_norm == 'l2' else False + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + if self.use_gate: + g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim) + o = self.o_norm(o, g) + else: + o = self.o_norm(o) + o = rearrange(o, 'b t h d -> b t (h d)') + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/deltaformer.py b/layers/deltaformer.py new file mode 100644 index 0000000000000000000000000000000000000000..8c83e1751204fc8cff1ebe4a1a518cf933d7345e --- /dev/null +++ b/layers/deltaformer.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from transformers.utils import logging + +from fla.modules import RMSNorm, RotaryEmbedding +from fla.ops.deltaformer import deltaformer_attn +from fla.ops.utils.index import prepare_lens_from_mask + +if TYPE_CHECKING: + from fla.models.utils import Cache + +logger = logging.get_logger(__name__) + + +class DeltaFormerAttention(nn.Module): + + r""" + The layer implementation for DeltaFormer, + [Understanding Transformer from the Perspective of Associative Memory] + (https://arxiv.org/pdf/2505.19488). + + Notes + - DeltaFormer attention is implemented with Triton kernels in `fla.ops.deltaformer` and is tuned + for typical head dimensions (e.g., 64/128). It currently supports fixed-length inputs. + - For variable-length inputs (padding masks), the deltaformer computation falls back to using the + fixed-length path, while the second stage (softmax attention over U) uses FlashAttention's + varlen path when an attention mask is provided. + - K/V grouping (GQA) is supported natively by FlashAttention via `num_kv_heads`. + - Uses K-K similarity in deltaformer computation instead of Q-K similarity for better performance. + + Args: + hidden_size (int, Optional): + The hidden size of the input. Default: 2048. + num_heads (int, Optional): + The number of attention heads. Default: 32. + num_kv_heads (int, Optional): + The number of key/value heads for grouped-query attention. If None, equals `num_heads`. + Default: None. + qkv_bias (bool, Optional): + Whether to use bias for Q/K/V projections. Default: False. + qk_norm (bool, Optional): + Whether to apply per-head RMSNorm to Q and K before attention. Default: False. + rope_theta (float, Optional): + The base frequency for rotary position embedding. Default: 10000. + max_position_embeddings (int, Optional): + The maximum position embeddings. Default: None. + layer_idx (int, Optional): + The index of the layer (used for cache compatibility). Default: None. + """ + + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 32, + num_kv_heads: Optional[int] = None, + qkv_bias: bool = False, + qk_norm: bool = False, + rope_theta: float = 10000., + max_position_embeddings: Optional[int] = None, + layer_idx: int | None = None, + ): + super().__init__() + + self.hidden_size = hidden_size + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads + self.num_kv_groups = num_heads // self.num_kv_heads + self.head_dim = self.hidden_size // self.num_heads + self.kv_dim = self.num_kv_heads * self.head_dim + self.qkv_bias = qkv_bias + self.qk_norm = qk_norm + self.rope_theta = rope_theta + self.max_position_embeddings = max_position_embeddings + self.layer_idx = layer_idx + + self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias) + self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + + if qk_norm: + self.q_norm = RMSNorm(self.head_dim) + self.k_norm = RMSNorm(self.head_dim) + + self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + attentions = None + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.size() + + q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + beta = self.b_proj(hidden_states) + + if self.qk_norm: + q, k = self.q_norm(q), self.k_norm(k) + + cu_seqlens_kw = kwargs.get('cu_seqlens', None) + seqlen_offset, max_seqlen = 0, q_len + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + max_seqlen = q_len + seqlen_offset + + if attention_mask is not None: + seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1] + max_seqlen = q_len + max(seqlen_offset) + + if self.max_position_embeddings is not None: + max_seqlen = max(max_seqlen, self.max_position_embeddings) + + q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens_kw) + + o = deltaformer_attn( + q=q, + k=k, + v=v, + beta=beta, + attention_mask=attention_mask, + cu_seqlens=cu_seqlens_kw + ) + + o = o.reshape(batch_size, q_len, -1) + o = self.o_proj(o) + + if not output_attentions: + attentions = None + + return o, attentions, past_key_values diff --git a/layers/forgetting_attn.py b/layers/forgetting_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..add32d96ffb3b0a5d6394ca156d2f67b2f8ab994 --- /dev/null +++ b/layers/forgetting_attn.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint +from einops import rearrange +from transformers.utils import logging + +from fla.layers.utils import pad_input, unpad_input +from fla.modules import GroupNorm +from fla.ops.attn.decoding import attn_decoding_one_step +from fla.ops.forgetting_attn.parallel import parallel_forgetting_attn + +if TYPE_CHECKING: + from fla.models.utils import Cache + +logger = logging.get_logger(__name__) + + +class ForgettingAttention(nn.Module): + + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 32, + num_kv_heads: Optional[int] = None, + qkv_bias: bool = False, + qk_norm: bool = False, + window_size: Optional[int] = None, + use_output_gate: bool = False, + layer_idx: int = None + ): + super().__init__() + + self.hidden_size = hidden_size + self.num_heads = num_heads + if num_kv_heads is None: + self.num_kv_heads = self.num_heads + else: + self.num_kv_heads = num_kv_heads + self.num_kv_groups = num_heads // self.num_kv_heads + self.head_dim = self.hidden_size // self.num_heads + self.kv_dim = self.num_kv_heads * self.head_dim + self.qkv_bias = qkv_bias + self.qk_norm = qk_norm + + self.window_size = window_size + self.use_output_gate = use_output_gate + self.layer_idx = layer_idx + + self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias) + self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.f_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True) + + if use_output_gate: + self.g_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + + if qk_norm: + self.q_norm = GroupNorm( + num_groups=self.num_heads, + hidden_size=self.hidden_size, + is_rms_norm=True, + ) + self.k_norm = GroupNorm( + num_groups=self.num_kv_heads, + hidden_size=self.kv_dim, + is_rms_norm=True, + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.size() + + q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states) + f = F.logsigmoid(self.f_proj(hidden_states).float()) + if self.qk_norm: + q, k = self.q_norm(q), self.k_norm(k) + + cu_seqlens = kwargs.get('cu_seqlens', None) + if past_key_values is not None: + assert cu_seqlens is None, "cu_seqlens should not be provided when past_key_values is not None" + state = past_key_values.update( + attn_state=(k, v, f), + layer_idx=self.layer_idx, + offset=q_len, + cache_kwargs=dict(window_size=self.window_size) + ) + k, v, f = state['attn_state'] + + q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + + if attention_mask is not None: + q, (k, v, f), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v, f), attention_mask, q_len, keepdim=True) + _, cu_seqlens_k = cu_seqlens + cu_seqlens = cu_seqlens_k + max_seqlen_q, max_seqlen_k = max_seq_lens + if max_seqlen_q != max_seqlen_k: + assert max_seqlen_q == 1, "only support q_len == 1 for decoding" + o = attn_decoding_one_step(q, k, v, f, cu_seqlens=cu_seqlens) + else: + o = parallel_forgetting_attn(q, k, v, f, cu_seqlens=cu_seqlens) + else: + o = parallel_forgetting_attn(q, k, v, f, cu_seqlens=cu_seqlens) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices_q, batch_size, q_len) + o = rearrange(o, '... h d -> ... (h d)') + if self.use_output_gate: + o = self.g_proj(hidden_states).sigmoid() * o + o = self.o_proj(o) + return o, None, past_key_values diff --git a/layers/gated_deltanet.py b/layers/gated_deltanet.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2ce346116ee9f167b1c18ef7fb1b06dcca3f81 --- /dev/null +++ b/layers/gated_deltanet.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange, repeat +from torch.nn import functional as F + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +@torch.compile +def elu_p1(x): + return (F.elu(x, 1., False) + 1.).to(x) + + +@torch.compile +def sum_norm(x): + return (x / x.sum(-1, keepdim=True)).to(x) + + +class GatedDeltaNet(nn.Module): + """ + The layer implementaion for [Gated Delta Networks: Improving Mamba2 with Delta Rule](https://arxiv.org/abs/2412.06464). # noqa + + Similar to Mamba2, each layer contains around 6*hidden_size*hidden_size parameters. + + Parameter alloation when use_gate=True: + - 0.75 * hidden_size * hidden_size for the q_proj and k_proj each + - 1.5 * hidden_size * hidden_size for the v_proj, g_proj and o_proj each + - Others are ignorably small. + - In total = 0.75 * 2 + 1.5 * 3 = 6 * hidden_size * hidden_size + NOTE: num_heads * head_dim = 0.75 * hidden_size, please make sure to set the correct num_heads and head_dim. + + Parameter allocation when use_gate=False: + - 1 * hidden_size * hidden_size for the q_proj and k_proj each + - 2 * hidden_size * hidden_size for the v_proj and o_proj each + - Others are ignorably small. + - In total = 1 * 2 + 2 * 2 = 6 * hidden_size * hidden_size + + Args: + hidden_size (int, Optional): + The hidden size of the input. Default: 2048. + expand_v (float, Optional): + The expansion ratio for the value dim. Default: 2.0. + head_dim (int, Optional): + The dimension of each head. Default: 256. + num_heads (int, Optional): + The number of heads. Default: 4. + num_v_heads (int, Optional): + The number of heads for the value projection, equal to `num_heads` if `None`. + GVA is applied if `num_v_heads` > `num_heads`. Default: `None`. + mode (str, Optional): + Which Gated DeltaNet kernel to use. + Currently available: `chunk` and `fused_recurrent`. + Default: `chunk`. + use_beta (bool, Optional): + Whether to use beta. Default: `True`. + use_gate (bool, Optional): + Whether to use output gate. Default: `True`. + use_short_conv (bool, Optional): + Whether to use short convolutions. Default: `True`. + allow_neg_eigval (bool, Optional): + Allow negative eigenvalues. Default: `False`. If set to `True`, the beta will be multiplied by 2. + See reference: [Unlocking State-Tracking in Linear RNNs Through Negative Eigenvalues](https://arxiv.org/abs/2411.12537) + conv_size (int, Optional): + The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4. + conv_bias (bool, Optional): + Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`. + layer_idx (int, Optional): + The index of the layer. Default: None. + norm_eps (float, Optional): + The epsilon value for the normalization layer. Default: 1e-5. + """ + + def __init__( + self, + hidden_size: int = 2048, + expand_v: float = 2, + head_dim: int = 256, + num_heads: int = 6, + num_v_heads: int = None, + mode: str = 'chunk', + use_gate: bool = True, + use_short_conv: bool = True, + allow_neg_eigval: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + layer_idx: int = None, + norm_eps: float = 1e-5, + **kwargs + ) -> GatedDeltaNet: + super().__init__() + + self.mode = mode + self.allow_neg_eigval = allow_neg_eigval + self.hidden_size = hidden_size + self.expand_v = expand_v + + self.use_gate = use_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.head_dim = head_dim + self.num_heads = num_heads + self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads + + self.head_k_dim = head_dim + self.head_v_dim = int(self.head_dim * self.expand_v) + self.key_dim = int(self.num_heads * self.head_k_dim) + self.value_dim = int(self.num_v_heads * self.head_v_dim) + self.layer_idx = layer_idx + + # Consistency check: Ensure expand_v produces integer values + if not math.isclose(self.num_v_heads * self.head_dim * expand_v, self.value_dim, rel_tol=1e-5): + raise ValueError( + f"expand_v={expand_v} does not produce an integer value when multiplied by key_dim={self.key_dim}. " + f"Resulting value_dim would be {self.num_v_heads * self.head_dim * expand_v}, which is invalid for nn.Linear." + ) + if self.num_v_heads > self.num_heads and self.num_v_heads % self.num_heads != 0: + raise ValueError( + f"num_v_heads={self.num_v_heads} must be divisible by num_heads={self.num_heads}." + ) + + if not math.isclose(head_dim * expand_v, self.head_v_dim, rel_tol=1e-5): + raise ValueError( + f"expand_v={expand_v} does not produce an integer value when multiplied by head_dim={head_dim}. " + f"Resulting head_v_dim would be {head_dim * expand_v}, which is invalid for FusedRMSNormGated." + ) + assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`." + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.a_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False) + self.b_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False) + + A = torch.empty(self.num_v_heads, dtype=torch.float32).uniform_(0, 16) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + # hard coded for now + dt_min = 0.001 + dt_max = 0.1 + dt_init_floor = 1e-4 + dt = torch.exp( + torch.rand(self.num_v_heads) * (math.log(dt_max) - math.log(dt_min)) + + math.log(dt_min) + ) + dt = torch.clamp(dt, min=dt_init_floor) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + self.dt_bias = nn.Parameter(inv_dt) + # Just to be explicit. Without this we already don't put wd on dt_bias because of the check + # name.endswith("bias") in param_grouping.py + self.dt_bias._no_weight_decay = True + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + else: + warnings.warn( + "ShortConvolution is crucial to the performance. " + "Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing." + ) + if use_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + # change to inference mode. + mode = 'fused_recurrent' if q_len <= 64 else self.mode + if self.training: + assert mode == 'chunk', "Only chunk mode is supported in training." + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = F.silu(self.q_proj(hidden_states)) + k = F.silu(self.k_proj(hidden_states)) + v = F.silu(self.v_proj(hidden_states)) + + q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k)) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + + if self.num_v_heads > self.num_heads: + q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k)) + + beta = self.b_proj(hidden_states).sigmoid() + if self.allow_neg_eigval: + beta = beta * 2. + + g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'chunk': + o, recurrent_state = chunk_gated_delta_rule( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True + ) + elif mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_gated_delta_rule( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + if self.use_gate: + g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim) + o = self.o_norm(o, g) + else: + o = self.o_norm(o) + o = rearrange(o, 'b t h d -> b t (h d)') + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/gated_deltaproduct.py b/layers/gated_deltaproduct.py new file mode 100644 index 0000000000000000000000000000000000000000..33a8d61f616062ac8e9e625eb27aeebaf9282c91 --- /dev/null +++ b/layers/gated_deltaproduct.py @@ -0,0 +1,291 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange, repeat +from torch.nn import functional as F + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.ops.gated_delta_product import chunk_gated_delta_product +from fla.ops.gated_delta_rule import fused_recurrent_gated_delta_rule + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class GatedDeltaProduct(nn.Module): + """ + Generalized version of GatedDoubleDeltaNet that supports arbitrary number of householder transformations. + """ + + def __init__( + self, + hidden_size: int = 2048, + expand_v: float = 2, + head_dim: int = 256, + num_heads: int = 6, + num_v_heads: int = None, + mode: str = 'chunk', + use_output_gate: bool = True, + use_short_conv: bool = True, + conv_size: int = 4, + conv_bias: bool = False, + layer_idx: int = None, + norm_eps: float = 1e-5, + use_forget_gate: bool = True, + allow_neg_eigval: bool = True, + num_householder: int = 2, + **kwargs + ) -> GatedDeltaProduct: + super().__init__() + + self.mode = mode + + self.hidden_size = hidden_size + self.expand_v = expand_v + + self.use_forget_gate = use_forget_gate + self.allow_neg_eigval = allow_neg_eigval + self.num_householder = num_householder + self.use_output_gate = use_output_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.head_dim = head_dim + self.num_heads = num_heads + self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads + + self.head_k_dim = head_dim + self.head_v_dim = int(self.head_dim * self.expand_v) + self.key_dim = int(self.num_heads * self.head_k_dim) + self.value_dim = int(self.num_v_heads * self.head_v_dim) + self.layer_idx = layer_idx + + # Consistency check: Ensure expand_v produces integer values + if not math.isclose(self.num_v_heads * self.head_dim * expand_v, self.value_dim, rel_tol=1e-5): + raise ValueError( + f"expand_v={expand_v} does not produce an integer value when multiplied by key_dim={self.key_dim}. " + f"Resulting value_dim would be {self.num_v_heads * self.head_dim * expand_v}, which is invalid for nn.Linear." + ) + if self.num_v_heads > self.num_heads and self.num_v_heads % self.num_heads != 0: + raise ValueError( + f"num_v_heads={self.num_v_heads} must be divisible by num_heads={self.num_heads}." + ) + + if not math.isclose(head_dim * expand_v, self.head_v_dim, rel_tol=1e-5): + raise ValueError( + f"expand_v={expand_v} does not produce an integer value when multiplied by head_dim={head_dim}. " + f"Resulting head_v_dim would be {head_dim * expand_v}, which is invalid for FusedRMSNormGated." + ) + assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`." + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim * num_householder, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim * num_householder, bias=False) + self.b_proj = nn.Linear(hidden_size, self.num_v_heads * num_householder, bias=False) + + if self.use_forget_gate: + self.a_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False) + A = torch.empty(self.num_v_heads, dtype=torch.float32).uniform_(0, 16) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + # hard coded for now + dt_min = 0.001 + dt_max = 0.1 + dt_init_floor = 1e-4 + dt = torch.exp( + torch.rand(self.num_v_heads) * (math.log(dt_max) - math.log(dt_min)) + + math.log(dt_min) + ) + dt = torch.clamp(dt, min=dt_init_floor) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + self.dt_bias = nn.Parameter(inv_dt) + # Just to be explicit. Without this we already don't put wd on dt_bias because of the check + # name.endswith("bias") in param_grouping.py + self.dt_bias._no_weight_decay = True + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim * num_householder, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim * num_householder, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + else: + warnings.warn( + "ShortConvolution is crucial to the performance. " + "Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing." + ) + if use_output_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + def _initialize_weights(self, module: nn.Module): + if getattr(module, "_is_hf_initialized", False): + return + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5) + if module.bias is not None: + nn.init.zeros_(module.bias) + module._is_hf_initialized = True + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + # change to inference mode. + mode = 'fused_recurrent' if q_len <= 64 else self.mode + + if self.training: + assert mode == 'chunk', "Only chunk mode is supported in training." + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = F.silu(self.q_proj(hidden_states)) + k = F.silu(self.k_proj(hidden_states)) + v = F.silu(self.v_proj(hidden_states)) + + q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim) + k = rearrange(k, '... t (n h d) -> ... (t n) h d', n=self.num_householder, d=self.head_k_dim) + v = rearrange(v, '... t (n h d) -> ... (t n) h d', n=self.num_householder, d=self.head_v_dim) + + if self.num_v_heads > self.num_heads: + q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k)) + + beta = self.b_proj(hidden_states).sigmoid() + if self.allow_neg_eigval: + beta = beta * 2. + + beta = rearrange(beta, '... t (n h) -> ... (t n) h', n=self.num_householder) + if self.use_forget_gate: + g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias) + else: + g = None + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'chunk': + o, recurrent_state = chunk_gated_delta_product( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + num_householder=self.num_householder, + use_qk_l2norm_in_kernel=True + ) + + elif mode == 'fused_recurrent': + if self.use_forget_gate: + g_new = g.new_zeros(g.shape[0], g.shape[1], self.num_householder, g.shape[2]) + g_new[:, :, 0] = g + g = rearrange(g_new, '... t n h -> ... (t n) h') + + q_new = q.new_zeros(q.shape[0], q.shape[1], self.num_householder, q.shape[2], q.shape[3]) + q_new[:, :, -1] = q + q = rearrange(q_new, '... t n h d-> ... (t n) h d') + o, recurrent_state = fused_recurrent_gated_delta_rule( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens * self.num_householder if cu_seqlens is not None else None, + use_qk_l2norm_in_kernel=True + ) + o = rearrange(o, '... (t n) h d -> ... t n h d', n=self.num_householder)[..., -1, :, :].contiguous() + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + if self.use_output_gate: + g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim) + o = self.o_norm(o, g) + else: + o = self.o_norm(o) + o = rearrange(o, 'b t h d -> b t (h d)') + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/gka.py b/layers/gka.py new file mode 100644 index 0000000000000000000000000000000000000000..70fc79f20ab4ba0b026f005c9524ef035a69392e --- /dev/null +++ b/layers/gka.py @@ -0,0 +1,744 @@ +""" +Gated KalmaNet (GKA) layer implementation with Grouped Query Attention (GQA) support. + +This module implements the Gated KalmaNet layer from the paper: +"Gated KalmaNet: A Fading Memory Layer Through Test-Time Ridge Regression" (https://arxiv.org/abs/2511.21016). + +Overview: + GKA is a state space model (SSM) that updates its state based on the entire history + of previously seen tokens, rather than just the current token. At each timestep t, + the optimal state S_t minimizes a ridge regression objective over all past tokens: + + S_t = argmin_S { λ·||S||²_F + Σ(i=1 to t) η_i·||S·k_i - v_i||² } + + where λ is the ridge regularization strength and η_i are exponentially decaying weights + controlled by forgetting gates. This has a closed-form solution: + + S_t = U_t · (H_t + λI)^(-1) + + where: + U_t = Σ(i=1 to t) η_i v_i k_i^T (cumulative value-key outer products) + H_t = Σ(i=1 to t) η_i k_i k_i^T (cumulative key-key covariance) + + The output is computed as y_t = S_t · q_t, which reduces to solving the ridge + regression problem (H_t + λI)·x_t = q_t for x_t, then computing y_t = U_t · x_t. + This is solved numerically via the Chebyshev iteration algorithm. + + The layer supports GQA-style head grouping where the number of key/value heads + can be different from the number of query heads. The hyperparameters in this module + are set so that we can initialize the module's weights from existing Attention layers. + +Key Variables: + - head_dim: Head dimension (same for q/k/v) + - num_q_heads: Number of query heads + - num_k_heads: Number of key heads + - num_v_heads: Number of value heads + - expanded_num_heads: Maximum of num_q_heads, num_k_heads, num_v_heads + - num_q_groups: Repetition factor for Q heads, computed as expanded_num_heads // num_q_heads + - num_k_groups: Repetition factor for K heads, computed as expanded_num_heads // num_k_heads + - num_v_groups: Repetition factor for V heads, computed as expanded_num_heads // num_v_heads + - query_dim: Total query dimension, num_q_heads * head_dim + - key_dim: Total key dimension, num_k_heads * head_dim + - value_dim: Total value dimension, num_v_heads * head_dim + - expanded_dim: Expanded dimension, expanded_num_heads * head_dim +""" + +from __future__ import annotations + +import math +from typing import TYPE_CHECKING, Any, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange, repeat +from torch import Tensor +from torch.nn import functional as F + +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.ops.simple_gla import chunk_simple_gla +from fla.models.utils import Cache +# from ..sp_p2p_utils import reorder_for_ssm_p2p + +from ..ops.chebyshev.chunk_dk_backward_gating_sp import compute_kk_final_with_gating +# from .sequence_parallel.gka_sp_utils import ( +# state_passing_gka_p2p, +# recompute_with_initial_states, +# ) + +from ..ops.chebyshev.gka_chebyshev_solve import ( + gka_chebyshev_gla, + torch_decoding_one_step, +) + + +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.init as init + + +class LinearLowRank(nn.Module): + """ + Low-rank linear layer that factorizes a linear projection into two smaller ones: + y = linearB(act_fn(linearA(x))) + + where linearA projects from in_features to rank, and linearB projects from rank to out_features. + + linearB is zero-initialized so that the module outputs zeros at init time. This makes it safe + to use as a residual branch (e.g. added on top of a repeat/expand) without perturbing the + pretrained signal at the start of training. + + Note: linearB is marked with ``_is_hf_initialized = True`` to prevent transformers' + ``post_init`` from overwriting the zero initialization with a random normal. + + Args: + in_features: Input dimension. + out_features: Output dimension. + rank: Bottleneck dimension between the two linear layers. + act_fn: Optional activation applied between linearA and linearB. Defaults to Identity. + bias: Whether to include bias terms in both linear layers. Defaults to False. + """ + + def __init__( + self, + in_features: int, + out_features: int, + rank: int, + act_fn: Optional[Any] = None, + bias: bool = False, + ): + super().__init__() + self.linearA = nn.Linear(in_features, rank, bias=bias) + self.linearB = nn.Linear(rank, out_features, bias=bias) + + self.in_features = in_features + self.out_features = out_features + self.rank = rank + self.bias = bias + self.act_fn = act_fn if act_fn is not None else nn.Identity() + + # Initialize B weights and bias to zero + init.zeros_(self.linearB.weight) + if self.linearB.bias is not None: + init.zeros_(self.linearB.bias) + self.linearB._is_hf_initialized = ( + True + ) # prevent transformers' post_init from re-initializing + + def forward(self, x: torch.Tensor): + return self.linearB(self.act_fn(self.linearA(x))) + + +class GKANet(nn.Module): + """ + GKA layer with Chebyshev solver and GQA support. + + Args: + hidden_size: The hidden size of the input. Defaults to 2048. + head_dim: The dimension of each head. Assumes q/k/v have the same head dimension. + Defaults to 128. + num_q_heads: The number of query heads. Defaults to 16. + num_k_heads: The number of key heads for GQA. If None, defaults to num_q_heads. + Defaults to None. + num_v_heads: The number of value heads for GQA. If None, defaults to num_q_heads. + Defaults to None. + use_beta_gate: Whether to use beta gating mechanism. Defaults to True. + use_alpha_connection: Whether to use alpha connection for residual paths. Defaults to True. + use_v_conv: Whether to apply convolution to value vectors. Defaults to True. + use_forgetting_gate: Whether to use forgetting gate mechanism. Defaults to True. + use_forgetting_gate_kk: Whether to use forgetting gate for key-key interactions. Defaults to True. + gla_rescale: Whether to apply GLA-style rescaling. Defaults to True. + solver_type: Solver method. Currently, we only support "chebyshev". Defaults to "chebyshev". + bp_lambda: Whether to backpropagate through lambda parameters. Defaults to True. + num_iter: Number of iterations for iterative solvers. Defaults to 30. + ridge_strength: Regularization strength for ridge regression. Defaults to 0.02. + use_gate: Whether to use output gating mechanism. Defaults to True. + conv_size: Size of the convolution kernel. Defaults to 4. + layer_idx: The index of the layer. Used for caching during inference. Defaults to None. + norm_eps: The epsilon value for the normalization layer. Defaults to 1e-6. + chunk_size: Size of chunks for parallel processing in Triton kernels. Defaults to 64. + kv_proj_rank: Rank for low-rank KV projection to expand K/V heads. If None, uses + standard GQA repeat. Defaults to None. + kv_learnable_residual: Whether to use a learnable residual for the KV head expansion + instead of a fixed repeat. Only used when kv_proj_rank is set. Defaults to False. + """ + + def __init__( + self, + hidden_size: int = 2048, + head_dim: int = 128, + num_heads: int = 8, + num_q_heads: Optional[int] = None, + num_k_heads: Optional[int] = None, + num_v_heads: Optional[int] = None, + use_beta_gate: bool = True, + use_alpha_connection: bool = True, + use_v_conv: bool = True, + use_forgetting_gate: bool = True, + use_forgetting_gate_kk: bool = True, + gla_rescale: bool = True, + solver_type: str = "chebyshev", + bp_lambda: bool = True, + num_iter: int = 30, + ridge_strength: float = 0.02, + use_gate: bool = False, + conv_size: int = 4, + layer_idx: Optional[int] = None, + norm_eps: float = 1e-6, + chunk_size: int = 64, + kv_proj_rank: Optional[int] = None, + kv_learnable_residual: bool = False, + **kwargs, + ) -> None: + super().__init__() + + assert solver_type == "chebyshev", f"Received {solver_type=}. Currently, GKA only supports 'chebyshev' solver." + + self.hidden_size = hidden_size + + self.use_gate = use_gate + self.conv_size = conv_size + self.sequence_parallel_group = None + self.chunk_size = chunk_size + + self.head_dim = head_dim + self.num_heads = num_heads + self.num_q_heads = num_q_heads if num_q_heads is not None else num_heads + self.num_k_heads = num_k_heads if num_k_heads is not None else num_heads + self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads + self.expanded_num_heads = max( + self.num_q_heads, self.num_k_heads, self.num_v_heads + ) + self.num_q_groups = self.expanded_num_heads // self.num_q_heads + self.num_k_groups = self.expanded_num_heads // self.num_k_heads + self.num_v_groups = self.expanded_num_heads // self.num_v_heads + + self.query_dim = self.num_q_heads * self.head_dim + self.key_dim = self.num_k_heads * self.head_dim + self.value_dim = self.num_v_heads * self.head_dim + self.expanded_dim = self.expanded_num_heads * self.head_dim + + self.layer_idx = layer_idx + + self.ridge_strength = ridge_strength + self.num_iter = num_iter + self.use_beta_gate = use_beta_gate + self.use_alpha_connection = use_alpha_connection + self.solver_type = solver_type + self.bp_lambda = bp_lambda + self.use_v_conv = use_v_conv + self.use_forgetting_gate = use_forgetting_gate + self.use_forgetting_gate_kk = use_forgetting_gate_kk + + if gla_rescale: + self.gla_scale = self.head_dim ** -0.5 + else: + self.gla_scale = 1.0 + + # Projection layers + self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + + self.a_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=False) + + self.b_proj = ( + nn.Linear(hidden_size, self.expanded_num_heads, bias=True) + if self.use_beta_gate + else None + ) + + if self.use_alpha_connection: + self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True) + + # Initialize A parameter (log scale) + A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + + # Initialize dt bias parameter + dt_min = 0.001 + dt_max = 0.1 + dt_init_floor = 1e-4 + dt = torch.exp( + torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min)) + + math.log(dt_min) + ) + dt = torch.clamp(dt, min=dt_init_floor) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + + self.dt_bias = nn.Parameter(inv_dt) + self.dt_bias._no_weight_decay = True + + # Short convolution layers + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.query_dim, kernel_size=conv_size, activation="silu" + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, kernel_size=conv_size, activation="silu" + ) + if self.use_v_conv: + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim, kernel_size=conv_size, activation="silu" + ) + + # Output gating and normalization + if use_gate: + self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False) + self.o_norm = FusedRMSNormGated(self.head_dim, eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_dim, eps=norm_eps) + self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False) + + # Optional KV projection for GQA + self.kv_proj_rank = kv_proj_rank + self.kv_learnable_residual = kv_learnable_residual + if self.kv_proj_rank is not None: + act_fn = nn.SiLU() + self.proj_k = LinearLowRank( + in_features=self.key_dim, + out_features=self.expanded_num_heads * self.head_dim, + rank=self.kv_proj_rank, + act_fn=act_fn, + ) + self.proj_v = LinearLowRank( + in_features=self.value_dim, + out_features=self.expanded_num_heads * self.head_dim, + rank=self.kv_proj_rank, + act_fn=act_fn, + ) + + if self.kv_learnable_residual: + # Learnable mixing matrices initialized to mimic repeat_kv + eye_k = torch.eye(self.num_k_heads) + ones_k = torch.ones((self.num_k_groups, 1)) + self.k_rep = nn.Parameter( + torch.kron(eye_k, ones_k) + ) # [expanded_num_heads, num_k_heads] + + eye_v = torch.eye(self.num_v_heads) + ones_v = torch.ones((self.num_v_groups, 1)) + self.v_rep = nn.Parameter( + torch.kron(eye_v, ones_v) + ) # [expanded_num_heads, num_v_heads] + + def _expand_kv(self, k: Tensor, v: Tensor) -> Tuple[Tensor, Tensor]: + """ + Expand k and v from their native head counts to expanded_num_heads. + + Three modes: + 1. kv_proj_rank + kv_learnable_residual: learnable mixing residual + low-rank projection + 2. kv_proj_rank without learnable residual: plain repeat residual + low-rank projection + 3. No projection: simple repeat (or rearrange if groups == 1). This is the standard GQA repeat. + + Args: + k: [B, L, Dk] raw key tensor (flat, not yet reshaped to heads) + v: [B, L, Dv] raw value tensor (flat, not yet reshaped to heads) + + Returns: + k: [B, L, H, D] expanded keys + v: [B, L, H, D] expanded values + """ + if self.kv_proj_rank is not None and ( + self.num_k_groups > 1 or self.num_v_groups > 1 + ): + # Build residual + if self.kv_learnable_residual: + k_heads = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads) + k_res = torch.einsum("eh,blhd->bled", self.k_rep, k_heads) + v_heads = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads) + v_res = torch.einsum("eh,blhd->bled", self.v_rep, v_heads) + else: + k_res = repeat( + rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads), + "... h d -> ... (h g) d", + g=self.num_k_groups, + ) + v_res = repeat( + rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads), + "... h d -> ... (h g) d", + g=self.num_v_groups, + ) + + # Low-rank projection to expanded dim + add residual + k = ( + rearrange( + self.proj_k(k), "... (h d) -> ... h d", h=self.expanded_num_heads + ) + + k_res + ) + v = ( + rearrange( + self.proj_v(v), "... (h d) -> ... h d", h=self.expanded_num_heads + ) + + v_res + ) + else: + # Plain rearrange + repeat + k = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads) + v = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads) + if self.num_k_groups > 1: + k = repeat(k, "... h d -> ... (h g) d", g=self.num_k_groups) + if self.num_v_groups > 1: + v = repeat(v, "... h d -> ... (h g) d", g=self.num_v_groups) + + return k, v + + def forward( + self, + hidden_states: Tensor, + attention_mask: Optional[Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs, + ) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]: + """ + GKA forward pass with optional caching. + + NOTE: We use the following variables for tensor shape hints: + - B: Input batch size + - L: Sequence length (full sequence length before SP distribution) + - Dh: Hidden dimension (self.hidden_size) + - H: Expanded number of heads (self.expanded_num_heads) + - Hq: Number of query heads (self.num_q_heads) + - Hk: Number of key heads (self.num_k_heads) + - Hv: Number of value heads (self.num_v_heads) + - D: Head dimension (self.head_dim) + - Dq: Query dimension (self.query_dim) + - Dk: Key dimension (self.key_dim) + - Dv: Value dimension (self.value_dim) + - Dexp: Expanded dimension (self.expanded_dim) + - C: Convolution size (self.conv_size) + - SP: Sequence parallel size. 1 if not using sequence parallel + + - B_sp: Batch size after SP reordering. B_sp = B*2 if self.sequence_parallel_group else B_sp = B + - L_sp: Sequence length after SP reordering. L_sp = L/(SP*2) + C-1 if self.sequence_parallel_group else L_sp = L/SP + - Lp: Sequence length after SP reordering and conv padding removal. Lp = L/(SP*2) if self.sequence_parallel_group else Lp = L/SP + + Args: + hidden_states: Input tensor with shape [B, L/SP, Dh]. + attention_mask: Optional 0-1 mask. Not used. + past_key_values: Optional cache containing conv_state and recurrent_state + for inference. When provided, performs incremental decoding. + use_cache: Whether to return updated cache states. Defaults to False. + output_attentions: Whether to return attention weights (not used). Defaults to False. + **kwargs: Additional keyword arguments, may include cu_seqlens for packed sequences. + + Returns: + Tuple of (output, attention_weights, past_key_values) where: + - output: Output tensor with same shape as hidden_states [B, L, Dh] + - attention_weights: None (not computed for GKA) + - past_key_values: Updated cache (same as input if provided, else None) + """ + # During inference, if attention_mask is not None, throw an error + if attention_mask is not None and not self.training: + raise NotImplementedError( + "GKA kernels currently do not support varlen inputs." + ) + + batch_size, q_len, _ = hidden_states.shape + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get("cu_seqlens", None) + + # Apply P2P reordering to hidden_states first for custom zigzag SP + # if self.sequence_parallel_group is not None: + # assert ( + # cu_seqlens is None + # ), "SP not implemented for cu_seqlens (variable length samples in a batch)." + # sp_size = torch.distributed.get_world_size( + # group=self.sequence_parallel_group + # ) + # sp_rank = torch.distributed.get_rank(group=self.sequence_parallel_group) + + # hidden_states = reorder_for_ssm_p2p( + # hidden_states, + # self.sequence_parallel_group, + # torch.cuda.Stream(), + # sp_size, + # sp_rank, + # self.conv_size, + # ) + # # hidden_states: [B_sp, L_sp, Dh] + + # Apply projections and convolutions + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"] + + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + # q: [B_sp, L_sp, Dq] + # conv_state_q: [B, Dq, C] or None + + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + # k: [B_sp, L_sp, Dk] + # conv_state_k: [B, Dk, C] or None + + if self.use_v_conv: + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + # v: [B_sp, L_sp, Dv] + # conv_state_v: [B, Dv, C] or None + else: + v = self.v_proj(hidden_states) # [B_sp, L_sp, Dv] + conv_state_v = None + + # Remove padding for custom zigzag SP (first conv_size-1 tokens added by P2P) + # if self.sequence_parallel_group is not None: + # q = q[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dq] + # k = k[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dk] + # if self.use_v_conv: + # v = v[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dv] + # # Also remove padding from hidden_states so beta/alpha/g/gk match seq length + # hidden_states = hidden_states[ + # :, self.conv_size - 1 :, : + # ].contiguous() # [B_sp, Lp, Dh] + + # Reshape q to heads and expand k/v (handles projection + residual if configured) + q = rearrange( + q, "... (h d) -> ... h d", h=self.num_q_heads + ) # [B_sp, Lp, Hq, D] + k, v = self._expand_kv(k, v) # [B_sp, Lp, H, D] each + + # Apply GQA/head repeats for q to match expanded_num_heads + if self.num_q_groups > 1: + q = repeat(q, "... h d -> ... (h g) d", g=self.num_q_groups) + # q: [B_sp, Lp, H, D] + + # Get recurrent state from cache + last_h_kk, last_h_kv = ( + last_state["recurrent_state"] if last_state is not None else (None, None) + ) + + # Normalize queries and keys + qk_norm_eps = 1e-6 + q = q / ( + torch.linalg.vector_norm(q, dim=-1, keepdim=True).to(q) + qk_norm_eps + ) # [B_sp, Lp, H, D] + k = k / ( + torch.linalg.vector_norm(k, dim=-1, keepdim=True).to(k) + qk_norm_eps + ) # [B_sp, Lp, H, D] + + # Apply beta gating if enabled + if self.use_beta_gate: + beta = self.b_proj(hidden_states).sigmoid() # [B_sp, Lp, H] + eps = 1e-6 + k = ((beta[..., None] + eps) * k).to(k.dtype) # [B_sp, Lp, H, D] + v = ((beta[..., None] + eps) * v).to(v.dtype) # [B_sp, Lp, H, D] + + # Compute alpha connection parameter + if self.use_alpha_connection: + alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H] + else: + alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H] + + # Compute forgetting gate + if self.use_forgetting_gate: + g = -self.A_log.float().exp() * F.softplus( + self.a_proj(hidden_states).float() + self.dt_bias + ) # [B_sp, Lp, H] + else: + g = None + + gk = g if self.use_forgetting_gate_kk else None + + # Backward kernels require sequence length to be divisible by chunk size + if gk is None and self.training: + seq_len = hidden_states.shape[1] + assert ( + seq_len % self.chunk_size == 0 + ), f"Triton chunk size must divide the sequence length. Got seq_len={seq_len}, chunk_size={self.chunk_size}" + + + # Apply GKA Chebyshev solver + if last_state is None: + # if self.sequence_parallel_group is not None: + # # Custom zigzag SP: Compute h_kk first, pass states, then compute rest + + # # 1. Compute h_kk locally (just k @ k^T cumsum) with zero initial state + # k_proj = k # [B_sp, Lp, H, D] + + # if gk is not None: + # # For state passing, we only need the sum (equivalent to cumsum[-1]) + # gkk_final = torch.sum(gk, dim=1) # [B_sp, H] + # else: + # gkk_final = torch.zeros( + # q.shape[0], + # self.expanded_num_heads, + # device=q.device, + # dtype=q.dtype, + # ) + + # # Extract g sum (total decay across chunk) + # if g is not None: + # g_cumsum_last = torch.sum(g, dim=1) # [B_sp, H] + # else: + # g_cumsum_last = None + + # # Compute h_kk: cumsum of k @ k^T with gating + # with torch.cuda.device(q.device): + # if self.num_iter > 0: + # kk_final = compute_kk_final_with_gating( + # k_proj, gk, chunk_size=self.chunk_size + # ) + # else: + # kk_final = torch.zeros( + # k_proj.shape[0], + # self.expanded_num_heads, + # k_proj.shape[3], + # k_proj.shape[3], + # device=q.device, + # dtype=q.dtype, + # ) + # # kk_final: [B_sp, H, D, D] + + # # Compute h_kv locally to get final state + # _, h_kv_final = chunk_simple_gla( + # q=q, + # k=k, + # v=v, + # scale=self.gla_scale, + # g=g, + # output_final_state=True, + # ) + # # h_kv_final: [B_sp, H, D, D] + + # # 2. Pass states via P2P in zigzag pattern + # bs = q.shape[0] # Batch size (B_sp, includes both chunks per GPU) + + # # Ensure all inputs to state_passing are on the same device + # with torch.cuda.device(q.device): + # prev_kk, prev_h_kv = state_passing_gka_p2p( + # kk_final.to(q.device), + # gkk_final.to(q.device), # Local only, used for decay + # h_kv_final.to(q.device), + # g_cumsum_last.to(q.device) + # if g_cumsum_last is not None + # else None, + # self.sequence_parallel_group, + # sp_rank, + # sp_size, + # bs, + # ) + # # prev_kk: [B_sp, H, D, D] + # # prev_h_kv: [B_sp, H, D, D] + + # # 3. Now recompute with initial states from previous chunk + # # Ensure all tensors are on the same device before calling recompute + # with torch.cuda.device(q.device): + # o, h_kk, h_kv = recompute_with_initial_states( + # q=q, + # k=k, + # v=v, + # alpha=alpha, + # g=g, + # gk=gk, + # prev_kk=prev_kk.to(q.device), + # prev_h_kv=prev_h_kv.to(q.device), + # gla_scale=self.gla_scale, + # ridge_strength=self.ridge_strength, + # solver_type=self.solver_type, + # num_iter=self.num_iter, + # bp_lambda=self.bp_lambda, + # chunk_size=self.chunk_size, + # ) + # # o: [B_sp, Lp, H, D] + # # h_kk: [B_sp, H, D, D] + # # h_kv: [B_sp, H, D, D] + # else: + # with torch.cuda.device(q.device): + o, h_kk, h_kv = gka_chebyshev_gla( + q=q, + k=k, + v=v, + alpha=alpha,###this alpha_connect + g=g, + gk=gk, + gla_scale=self.gla_scale, + ridge_strength=self.ridge_strength, + solver_type=self.solver_type, + num_iter=self.num_iter, + bp_lambda=self.bp_lambda, + chunk_size=self.chunk_size, + ) + # o: [B_sp, Lp, H, D] + # h_kk: [B_sp, H, D, D] + # h_kv: [B_sp, H, D, D] + else: + # with torch.cuda.device(q.device): + o, h_kk, h_kv = torch_decoding_one_step( + q=q.squeeze(0), + k=k.squeeze(0), + v=v.squeeze(0), + alpha=alpha.squeeze(0), + g=g, + gk=gk, + gla_scale=self.gla_scale, + ridge_strength=self.ridge_strength, + solver_type=self.solver_type, + num_iter=self.num_iter, + prev_h_kk=last_h_kk, + prev_h_kv=last_h_kv, + ) + # o: [Lp, H, D] (batch squeezed) + # h_kk: [H, D, D] + # h_kv: [H, D, D] + if len(o.shape) == 3: + o = o.unsqueeze(0) # [1, Lp, H, D] + + o = o.to(q) + + # Update cache + if past_key_values is not None: + past_key_values.update( + recurrent_state=(h_kk, h_kv), + conv_state=(conv_state_q, conv_state_k, conv_state_v), + layer_idx=self.layer_idx, + offset=q_len, + ) + + # Apply output gating and normalization + if self.use_gate: + g = rearrange( + self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim + ) # [B_sp, Lp, H, D] + o = self.o_norm(o, g) # [B_sp, Lp, H, D] + else: + o = self.o_norm(o) # [B_sp, Lp, H, D] + + # Reshape and project output + o = rearrange(o, "b t h d -> b t (h d)") # [B_sp, Lp, Dexp] + o = self.o_proj(o) # [B_sp, Lp, Dh] + + # Scatter sequence if using sequence parallel + # if self.sequence_parallel_group is not None: + # # Recombine zigzag chunks to contiguous + # bz, len_o, dim = o.shape + # if bz == 2: + # o = o.view(bz // 2, len_o * 2, dim) + # else: + # o = torch.cat([o[: bz // 2], o[bz // 2 :]], dim=1).contiguous() + # o: [B, L/SP, Dh] + + return o, None, past_key_values diff --git a/layers/gka_attn.py b/layers/gka_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..d19635e3d525349791ad5caec5af086edf78603f --- /dev/null +++ b/layers/gka_attn.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from transformers.utils import logging + +from fla.layers.utils import pad_input, unpad_input +from fla.modules import RMSNorm, RotaryEmbedding +from fla.ops.utils.index import prepare_lens_from_mask +from fla.models.utils import Cache + +from ..ops.chebyshev.chebyshev_iteration import ChebyshevIteration +if TYPE_CHECKING: + from fla.models.utils import Cache + +import math +from torch.nn import functional as F + +try: + from flash_attn import flash_attn_func, flash_attn_varlen_func +except ImportError: + warnings.warn( + "Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`", + category=ImportWarning + ) + flash_attn_func = None + +logger = logging.get_logger(__name__) + + + +@torch.compiler.disable +def latent_chebyshev( + k, q, ridge_strength=0.02, num_iter=30, solver_type="chebyshev", bp_lambda=True, gk=None, chunk_size=64 +): + """ + Dispatcher for ridge regression solvers: (H_t + λI)·x_t = q_t. + + Routes to different solver implementations based on solver_type. All solvers + aim to solve the same problem but with different speed/accuracy tradeoffs. + + Args: + k: Key tensor with shape [B, L, H, D] + q: Query tensor with shape [B, L, H, D] + ridge_strength: Regularization parameter λ + num_iter: Number of iterations for iterative solvers + solver_type: Solver method. Currently only supports 'chebyshev'. + bp_lambda: Whether to backprop through λ (for Chebyshev solvers) + gk: Forgetting gate for key-key covariance with shape [B, L, H] + + Returns: + x: Solution tensor with shape [B, L, H, D] + kk_final: Final key-key covariance H_T with shape [B, H, D, D] + """ + if solver_type == "chebyshev": + x, kk_final = ChebyshevIteration.apply( + k, q, gk, num_iter, ridge_strength, bp_lambda, None, chunk_size + ) + else: + raise ValueError(f"Unknown GKA solver type: {solver_type}") + + return x, kk_final + + +# from ..ops.chebyshev.gka_chebyshev_solve import ( +# gka_chebyshev_gla, +# torch_decoding_one_step, +# ) + +from ..ops.chebyshev.gka_chebyshev_solve import chebyshev_iteration_forward_triton_inference +# from ..ops.phi_kkt_approx.phi_kkt_solve import phi_kkt_solve +from ..ops.phi_kkt_approx.q_kkt_solve_abc import q_kkt_solve_approx as q_kkt_solve_approx_abc +class GKAAttention(nn.Module): + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 8, + num_kv_heads: Optional[int] = None, + qkv_bias: bool = False, + qk_norm: bool = False, + window_size: Optional[int] = None, + rope_theta: Optional[float] = 10000., + max_position_embeddings: Optional[int] = None, + layer_idx: int = None, + use_alpha_connection: bool = False, + learnable_abc: Tuple[float, ...] = (1.0, -0.5, 0.375), + random_init_abc: bool = True, + abc_requires_grad: bool = True, + **kwargs, + ): + super().__init__() + + self.hidden_size = hidden_size + self.num_heads = num_heads + if num_kv_heads is None: + self.num_kv_heads = self.num_heads + else: + self.num_kv_heads = num_kv_heads + self.num_kv_groups = num_heads // self.num_kv_heads + self.head_dim = self.hidden_size // self.num_heads + self.kv_dim = self.num_kv_heads * self.head_dim + self.qkv_bias = qkv_bias + self.qk_norm = qk_norm + + self.use_alpha_connection = use_alpha_connection + self.window_size = window_size + self.rope_theta = rope_theta + self.max_position_embeddings = max_position_embeddings + self.layer_idx = layer_idx + + if flash_attn_func is None: + raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first") + + self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias) + self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + + if qk_norm: + self.q_norm = RMSNorm(self.head_dim) + self.k_norm = RMSNorm(self.head_dim) + + self.expanded_num_heads = max(self.num_heads, self.num_kv_heads) + + self.a_proj = nn.Linear(self.hidden_size, self.expanded_num_heads, bias=False) + + + if self.use_alpha_connection: + self.alpha_proj = nn.Linear(self.hidden_size, self.expanded_num_heads, bias=True) + + # A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16) + # self.A_log = nn.Parameter(torch.log(A)) + # self.A_log._no_weight_decay = True + + # # Initialize dt bias parameter + # dt_min = 0.001 + # dt_max = 0.1 + # dt_init_floor = 1e-4 + # dt = torch.exp( + # torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min)) + # + math.log(dt_min) + # ) + # dt = torch.clamp(dt, min=dt_init_floor) + # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + # inv_dt = dt + torch.log(-torch.expm1(-dt)) + + # self.dt_bias = nn.Parameter(inv_dt) + # self.dt_bias._no_weight_decay = True + init_abc = torch.tensor(learnable_abc, dtype=torch.float32).reshape(-1) + n_coeff = int(init_abc.numel()) + if n_coeff not in (3, 4): + raise ValueError( + f"learnable_abc must have 3 (abc) or 4 (abcd) coefficients, got {n_coeff}" + ) + self.learnable_abc = nn.Parameter( + init_abc.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous() + ) + if random_init_abc: + # a, c ~ U(0, 1); b, d ~ U(-1, 0) + signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32) + self.learnable_abc = nn.Parameter( + (torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad + ) + print("random init abc") + print(self.learnable_abc) + print(self.learnable_abc.requires_grad) + else: + print("not random init abc") + print(self.learnable_abc) + print(self.learnable_abc.requires_grad) + self.learnable_abc._no_weight_decay = True + self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.size() + + + + # g = -self.A_log.float().exp() * F.softplus( + # self.a_proj(hidden_states).float() + self.dt_bias + # ) # [B_sp, Lp, H] + q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + + if self.qk_norm: + q, k = self.q_norm(q), self.k_norm(k) + + if self.use_alpha_connection: + alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H] + else: + alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H] + + # equivalent to cu_seqlens in `flash_attn` + cu_seqlens = kwargs.get('cu_seqlens', None) + + + seqlen_offset, max_seqlen = 0, q_len + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + max_seqlen = q.shape[1] + seqlen_offset + if attention_mask is not None: + # to deliminate the offsets of padding tokens + seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1] + max_seqlen = q.shape[1] + max(seqlen_offset) + ###这里应该改成cu_seqlens + last_state_h_kk = None + if past_key_values is not None: + last_state_h_kk = past_key_values[self.layer_idx]["recurrent_state"] + + if self.max_position_embeddings is not None: + max_seqlen = max(max_seqlen, self.max_position_embeddings) + gk = torch.zeros(batch_size, q_len, self.expanded_num_heads, device=q.device, dtype=torch.float32) + q_, last_state_h_kk = q_kkt_solve_approx_abc.apply( + k, q, gk, 64, self.learnable_abc.to(torch.float32) + ) + # if last_state_h_kk is None: + # q_, last_state_h_kk = latent_chebyshev( + # k, q, ridge_strength=0.02, num_iter=30, solver_type="chebyshev", bp_lambda=True, gk=g, chunk_size=64 + # ) + # else: + # q_, last_state_h_kk = chebyshev_iteration_forward_triton_inference( + # last_state_h_kk, k, q, g, num_iter=30, ridge_ratio=0.02 + # )###这个为啥不考虑用wd变换替代 + # q = q + alpha[..., None] * (q_ - q) # Equivalent to ⍺q_ + (1-⍺)q + q = q_ + # q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens) + if past_key_values is not None: + cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0 + k_cached, v_cached = past_key_values.update( + recurrent_state=last_state_h_kk, + attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)), + layer_idx=self.layer_idx, + offset=q_len, + cache_kwargs=dict(window_size=self.window_size) + )['attn_state'] + if cache_has_content: + k, v = k_cached, v_cached + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + + # Contains at least one padding token in the sequence + if attention_mask is not None: + if q.shape[1] == 1 and self.window_size is not None: + attention_mask = attention_mask[:, -self.window_size:] + q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len) + cu_seqlens_q, cu_seqlens_k = cu_seqlens + max_seqlen_q, max_seqlen_k = max_seq_lens + o = flash_attn_varlen_func( + q, k, v, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + o = pad_input(o, indices_q, batch_size, q_len) + elif cu_seqlens is not None: + o = flash_attn_varlen_func( + q.squeeze(0), k.squeeze(0), v.squeeze(0), + cu_seqlens_q=cu_seqlens, + cu_seqlens_k=cu_seqlens, + max_seqlen_q=max_seqlen, + max_seqlen_k=max_seqlen, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ).unsqueeze(0) + else: + o = flash_attn_func( + q, k, v, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + o = o.reshape(batch_size, q_len, -1) + o = self.o_proj(o) + + if not output_attentions: + attentions = None + + return o, attentions, past_key_values diff --git a/layers/gla.py b/layers/gla.py new file mode 100644 index 0000000000000000000000000000000000000000..6b328115312bb09262a12c73ad1c5c9ff90a1849 --- /dev/null +++ b/layers/gla.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.modules.activations import ACT2FN +from fla.ops.gla import chunk_gla, fused_chunk_gla +from ..ops.gla import fused_recurrent_gla + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class GatedLinearAttention(nn.Module): + r""" + The layer implementaion for [Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635). # noqa + + Args: + mode (str, Optional): + Which GLA kernel to use. + Currently available: `chunk`, `fused_recurrent`, and `fused_chunk`. + Default: `chunk`. + hidden_size (int, Optional): + The hidden size of the input. Default: 1024. + expand_k (float, Optional): + The expansion ratio for the key dim. Default: 0.5. + expand_v (float, Optional): + The expansion ratio for the value dim. Default: 1.0. + num_heads (int, Optional): + The number of heads. Default: 4. + num_kv_heads (int, Optional): + The number of key/value heads, used for MQA. Default: None. + feature_map (str, Optional): + Feature map function applied to queries/keys. Default: None. + use_short_conv (bool, Optional): + Whether to use short convolutions. Default: `False`. + conv_size (int, Optional): + The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4. + conv_bias (bool, Optional): + Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`. + use_output_gate (bool, Optional): + Whether to use output gate. Default: `True`. + gate_fn (str, Optional): + The activation function for the output gate. Default: `swish`. + elementwise_affine (bool, Optional): + If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`. + norm_eps (float, Optional): + The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5. + gate_logit_normalizer (int, Optional): + The normalizer for the gate logits, appied after `logsigmoid`. Default: 16. + gate_low_rank_dim (int, Optional): + The low rank dim for the gate projection. Default: 16. + clamp_min (float, Optional): + The minimum value for the gate logits. Default: None. + fuse_norm (bool, Optional): + Whether to fuse the norm and the output gate for better memory footprint. Default: `True`. + layer_idx (int, Optional): + The index of the layer. Default: None. + """ + + def __init__( + self, + mode: str = 'chunk', + hidden_size: int = 1024, + expand_k: float = 0.5, + expand_v: float = 1.0, + num_heads: int = 4, + num_kv_heads: Optional[int] = None, + feature_map: Optional[str] = None, + use_short_conv: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + use_output_gate: bool = True, + gate_fn: str = 'swish', + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-5, + gate_logit_normalizer: int = 16, + gate_low_rank_dim: int = 16, + clamp_min: Optional[float] = None, + fuse_norm: bool = True, + layer_idx: int = None, + ) -> GatedLinearAttention: + super().__init__() + + self.mode = mode + self.hidden_size = hidden_size + self.expand_k = expand_k + self.expand_v = expand_v + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads + self.num_kv_groups = self.num_heads // self.num_kv_heads + self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None + + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + self.use_output_gate = use_output_gate + + self.key_dim = int(hidden_size * expand_k) + self.value_dim = int(hidden_size * expand_v) + self.key_dim_per_group = self.key_dim // self.num_kv_groups + self.value_dim_per_group = self.value_dim // self.num_kv_groups + self.clamp_min = clamp_min + self.layer_idx = layer_idx + + assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`." + assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" + assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" + + self.head_k_dim = self.key_dim // num_heads + self.head_v_dim = self.value_dim // num_heads + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False) + if self.use_output_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu', + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim_per_group, + kernel_size=conv_size, + bias=conv_bias, + activation='silu', + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim_per_group, + kernel_size=conv_size, + bias=conv_bias, + activation='silu', + ) + + self.gk_proj = nn.Sequential(nn.Linear(hidden_size, gate_low_rank_dim, bias=False), + nn.Linear(gate_low_rank_dim, self.key_dim_per_group, bias=True)) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + if gate_fn == 'swish' and fuse_norm and use_output_gate: + self.g_norm_swish_gate = FusedRMSNormGated( + hidden_size=self.head_v_dim, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + self.fuse_norm_and_gate = True + else: + self.fuse_norm_and_gate = False + self.g_norm = RMSNorm( + hidden_size=self.head_v_dim, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + self.gate_fn = ACT2FN[gate_fn] + + self.gate_logit_normalizer = gate_logit_normalizer + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + gk = self.gk_proj(hidden_states) + + if self.feature_map_fn is not None: + q, k = map(self.feature_map_fn, (q, k)) + q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim) + if self.num_kv_groups > 1: + k, gk = (repeat(x, '... (h d) -> ... (h g) d', g=self.num_kv_groups, d=self.head_k_dim) for x in (k, gk)) + v = repeat(v, '... (h d) -> ... (h g) d', g=self.num_kv_groups, d=self.head_v_dim) + else: + k, gk = (rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim) for x in (k, gk)) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + gk = F.logsigmoid(gk) / self.gate_logit_normalizer + + if self.clamp_min is not None: + gk = torch.clamp_min(gk, self.clamp_min) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_gla( + q=q, + k=k, + v=v, + gk=gk, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + elif mode == 'fused_chunk': + o, recurrent_state = fused_chunk_gla( + q=q, + k=k, + v=v, + g=gk, + initial_state=recurrent_state, + output_final_state=use_cache, + ) + elif mode == 'chunk': + o, recurrent_state = chunk_gla( + q=q, + k=k, + v=v, + g=gk, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + if self.use_output_gate: + g = self.g_proj(hidden_states) + if self.fuse_norm_and_gate: + g = rearrange(g, '... (h d) -> ... h d', d=self.head_v_dim) + o = self.g_norm_swish_gate(o, g) + o = rearrange(o, '... h d -> ... (h d)') + else: + o = rearrange(self.g_norm(o), '... h d -> ... (h d)') + o = o * self.gate_fn(g) + else: + o = rearrange(self.g_norm(o), '... h d -> ... (h d)') + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/gsa.py b/layers/gsa.py new file mode 100644 index 0000000000000000000000000000000000000000..c9690e6acccbd967f6bef9af562243663dfd0e3c --- /dev/null +++ b/layers/gsa.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import RMSNorm, ShortConvolution +from fla.modules.feature_map import ReLUFeatureMap, SwishFeatureMap, T2RFeatureMap +from fla.modules.layernorm import rms_norm_linear +from fla.ops.gsa import chunk_gsa, fused_recurrent_gsa + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class GatedSlotAttention(nn.Module): + + def __init__( + self, + mode: str = 'chunk', + hidden_size: int = 1024, + expand_k: float = 1., + expand_v: float = 1., + num_heads: int = 4, + num_kv_heads: Optional[int] = None, + use_short_conv: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + num_slots: Optional[int] = None, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-5, + gate_logit_normalizer: int = 8, + feature_map: str = 'swish', + use_output_gate: bool = False, + use_norm: bool = True, + layer_idx: Optional[int] = None, + scale: Optional[float] = 1., + **kwargs + ) -> GatedSlotAttention: + super().__init__() + + self.mode = mode + self.hidden_size = hidden_size + self.expand_k = expand_k + self.expand_v = expand_v + self.num_heads = num_heads + self.num_kv_heads = num_heads if num_kv_heads is None else num_kv_heads + self.num_kv_groups = self.num_heads // self.num_kv_heads + self.key_dim = int(hidden_size * expand_k) + self.value_dim = int(hidden_size * expand_v) + self.key_dim_per_group = self.key_dim // self.num_kv_groups + self.value_dim_per_group = self.value_dim // self.num_kv_groups + self.head_k_dim = self.key_dim // self.num_heads + self.head_v_dim = self.value_dim // self.num_heads + + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.gate_logit_normalizer = gate_logit_normalizer + + self.use_output_gate = use_output_gate + self.use_norm = use_norm + self.scale = scale + + if num_slots is None: + num_slots = self.head_k_dim + self.num_slots = num_slots + + self.layer_idx = layer_idx + + if layer_idx is None: + warnings.warn( + f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " + "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " + "when creating this class." + ) + + self.register_module('feature_map', None) + if feature_map == 'swish': + self.feature_map = SwishFeatureMap() + elif feature_map == 'relu': + self.feature_map = ReLUFeatureMap() + elif feature_map == 't2r': + self.feature_map = T2RFeatureMap(self.head_k_dim, self.head_k_dim) + else: + raise NotImplementedError(f"Feature map `{feature_map}` is not supported now.") + + self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.key_dim_per_group, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.value_dim_per_group, bias=False) + self.f_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.num_slots, bias=False) + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu', + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim_per_group, + kernel_size=conv_size, + bias=conv_bias, + activation='silu', + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim_per_group, + kernel_size=conv_size, + bias=conv_bias, + activation='silu', + ) + + self.g_norm = RMSNorm(self.hidden_size, elementwise_affine, eps=norm_eps) + self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + f = self.f_proj(hidden_states) + + q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + f = rearrange(f, '... (h m) -> ... h m', m=self.num_slots) + + if self.feature_map is not None: + q, k = map(lambda x: self.feature_map(x), (q, k)) + v = F.silu(v) + + f = F.logsigmoid(f) / self.gate_logit_normalizer + s = (1 - f.exp()).to(f.dtype) + + if self.num_kv_groups > 1: + k, v, f, s = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_kv_groups), (k, v, f, s)) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_gsa( + q=q, + k=k, + v=v, + s=s, + g=f, + initial_state=recurrent_state, + output_final_state=use_cache, + scale=self.scale, + cu_seqlens=cu_seqlens, + ) + elif mode == 'chunk': + o, recurrent_state = chunk_gsa( + q=q, + k=k, + v=v, + s=s, + g=f, + initial_state=recurrent_state, + output_final_state=use_cache, + scale=self.scale, + cu_seqlens=cu_seqlens, + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + o = rearrange(o, '... h d -> ... (h d)') + o = rms_norm_linear(F.silu(o), self.g_norm.weight, self.g_norm.bias, self.o_proj.weight, self.o_proj.bias) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/hgrn.py b/layers/hgrn.py new file mode 100644 index 0000000000000000000000000000000000000000..f127b790d7ff397ecee699765194981d832d74ac --- /dev/null +++ b/layers/hgrn.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +# "Hierarchically Gated Recurrent Neural Network for Sequence Modeling" [https://arxiv.org/abs/2311.04823] + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from fla.modules import FusedRMSNormGated, ShortConvolution +from fla.modules.activations import swiglu +from fla.ops.hgrn import chunk_hgrn, fused_recurrent_hgrn + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class HGRNAttention(nn.Module): + + def __init__( + self, + mode: str = 'chunk', + hidden_size: int = 1024, + expand_ratio: Optional[int] = 1, + use_short_conv: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-5, + layer_idx: int = None + ) -> HGRNAttention: + super().__init__() + + self.mode = mode + self.hidden_size = hidden_size + self.expand_ratio = expand_ratio + self.input_dim = int(hidden_size * expand_ratio) + + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.layer_idx = layer_idx + + assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`." + + self.i_proj = nn.Linear(hidden_size, self.input_dim, bias=False) + self.f_proj = nn.Linear(hidden_size, self.input_dim, bias=False) + self.g_proj = nn.Linear(hidden_size, self.input_dim, bias=False) + + if use_short_conv: + self.conv_size = conv_size + self.f_conv1d = ShortConvolution( + hidden_size=self.input_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + self.i_conv1d = ShortConvolution( + hidden_size=self.input_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + + self.g_norm = FusedRMSNormGated( + hidden_size=self.input_dim, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + self.o_proj = nn.Linear(self.input_dim, hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + lower_bound: Optional[torch.Tensor] = None, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + # launching the triton kernel for just one token will actually be slower + mode = 'fused_recurrent' if not self.training and hidden_states.shape[1] <= 64 else self.mode + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if self.use_short_conv: + conv_state_i, conv_state_f = None, None + if last_state is not None: + conv_state_i, conv_state_f = last_state['conv_state'] + conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None + i, conv_state_i = self.i_conv1d( + x=self.i_proj(hidden_states), + mask=conv_mask, + cache=conv_state_i, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + f, conv_state_f = self.f_conv1d( + x=self.f_proj(hidden_states), + mask=conv_mask, + cache=conv_state_f, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + i = self.i_proj(hidden_states) + f = self.f_proj(hidden_states) + + f = F.logsigmoid(f) + # the lower bound for the first layer is zero + if lower_bound is not None and self.layer_idx > 0: + f = torch.logaddexp(lower_bound.log(), torch.log1p(-lower_bound) + f).to(f) + i = swiglu(i, 1 - f.exp()) + + # dealing with left-padding + if attention_mask is not None: + i = i.mul_(attention_mask[:, -i.shape[-2]:, None]) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'chunk': + if cu_seqlens is not None: + raise NotImplementedError("Chunk mode does not support variable-length sequences.") + o, recurrent_state = chunk_hgrn( + x=i, + g=f, + initial_state=recurrent_state, + output_final_state=use_cache, + ) + elif mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_hgrn( + x=i, + g=f, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_i, conv_state_f) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=i.shape[2] + ) + + o = self.g_norm(o, self.g_proj(hidden_states)) + o = self.o_proj(o) + + return o, None, past_key_values + + def state_size(self, **kwargs) -> int: + state_size = self.hidden_size + for module in self.children(): + if isinstance(module, ShortConvolution): + state_size += module.state_size + return state_size diff --git a/layers/hgrn2.py b/layers/hgrn2.py new file mode 100644 index 0000000000000000000000000000000000000000..0bae98a9f45fdc19fa87580f0f550158a0e4667b --- /dev/null +++ b/layers/hgrn2.py @@ -0,0 +1,212 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +# "HGRN2: Gated Linear RNNs with State Expansion"[https://arxiv.org/abs/2404.07904] + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import RMSNorm, ShortConvolution +from fla.modules.activations import swish +from fla.modules.layernorm import rms_norm_linear +from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class HGRN2Attention(nn.Module): + + def __init__( + self, + mode: str = 'chunk', + hidden_size: int = 1024, + num_heads: Optional[int] = None, + expand_ratio: Optional[int] = 128, + use_short_conv: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-5, + layer_idx: int = None + ) -> HGRN2Attention: + super().__init__() + + self.mode = mode + self.hidden_size = hidden_size + + if expand_ratio is not None: + num_heads = hidden_size // expand_ratio + elif expand_ratio is None and num_heads is not None: + expand_ratio = hidden_size // num_heads + elif expand_ratio is None and num_heads is None: + raise RuntimeError("One of `expand_ratio` or `num_heads` should be provided.") + self.num_heads = num_heads + self.expand_ratio = expand_ratio + + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.forget_dim = int(self.num_heads * self.expand_ratio) + self.input_dim = hidden_size + self.layer_idx = layer_idx + + assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`." + assert self.forget_dim % num_heads == 0, f"forget dim must be divisible by num_heads of {num_heads}" + assert self.input_dim % num_heads == 0, f"input dim must be divisible by num_heads of {num_heads}" + + self.head_f_dim = self.expand_ratio + self.head_i_dim = self.hidden_size // num_heads + + self.q_proj = nn.Linear(hidden_size, self.forget_dim, bias=False) + self.f_proj = nn.Linear(hidden_size, self.forget_dim, bias=False) + self.i_proj = nn.Linear(hidden_size, self.input_dim, bias=False) + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.forget_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + self.f_conv1d = ShortConvolution( + hidden_size=self.forget_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + self.i_conv1d = ShortConvolution( + hidden_size=self.input_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + + self.g_norm = RMSNorm(hidden_size=self.hidden_size, elementwise_affine=elementwise_affine, eps=norm_eps) + self.o_proj = nn.Linear(self.input_dim, hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + lower_bound: Optional[torch.Tensor] = None, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_f, conv_state_i = None, None, None + if last_state is not None: + conv_state_q, conv_state_f, conv_state_i = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + f, conv_state_f = self.f_conv1d( + x=self.f_proj(hidden_states), + cache=conv_state_f, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + i, conv_state_i = self.i_conv1d( + x=self.i_proj(hidden_states), + cache=conv_state_i, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.q_proj(hidden_states) + f = self.f_proj(hidden_states) + i = self.i_proj(hidden_states) + + q = swish(q) + + g = F.logsigmoid(f) + # the lower bound for the first layer is zero + if lower_bound is not None and self.layer_idx > 0: + g = torch.logaddexp(lower_bound.log(), torch.log1p(-lower_bound) + g) + k = 1 - g.exp() + + q, k, g = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_f_dim), (q, k.to(i), g)) + i = rearrange(i, '... (h d) -> ... h d', d=self.head_i_dim) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_gla( + q=q, + k=k, + v=i, + gk=g, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + elif mode == 'fused_chunk': + o, recurrent_state = fused_chunk_gla( + q=q, + k=k, + v=i, + g=g, + initial_state=recurrent_state, + output_final_state=use_cache, + ) + elif mode == 'chunk': + o, recurrent_state = chunk_gla( + q=q, + k=k, + v=i, + g=g, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_f, conv_state_i) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + o = rearrange(o, '... h d -> ... (h d)') + o = rms_norm_linear(o, self.g_norm.weight, self.g_norm.bias, self.o_proj.weight, self.o_proj.bias) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/lightnet.py b/layers/lightnet.py new file mode 100644 index 0000000000000000000000000000000000000000..4646da7c3eadf75c3cc04f1983b3d53d3643c157 --- /dev/null +++ b/layers/lightnet.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +# ["You Only Scan Once: Efficient Multi-dimension Sequential Modeling with LightNet"](https://arxiv.org/abs/2405.21022) + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange + +from fla.modules import FusedRMSNormGated, ShortConvolution +from fla.modules.fused_norm_gate import rms_norm_swish_gate_linear +from fla.ops.gla import chunk_gla, fused_recurrent_gla + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class LightNetAttention(nn.Module): + + def __init__( + self, + mode: str = 'chunk', + hidden_size: int = 1024, + num_heads: Optional[int] = None, + expand_ratio: Optional[int] = 128, + use_short_conv: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + gate_low_rank_dim: int = 128, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-5, + layer_idx: int = None + ) -> LightNetAttention: + super().__init__() + + self.mode = mode + self.hidden_size = hidden_size + + if expand_ratio is None and num_heads is not None: + expand_ratio = hidden_size // num_heads + elif expand_ratio is not None and num_heads is None: + num_heads = hidden_size // expand_ratio + elif expand_ratio is None and num_heads is None: + raise RuntimeError("One of `expand_ratio` or `num_heads` should be provided.") + self.num_heads = num_heads + self.expand_ratio = expand_ratio + + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.key_dim = int(self.num_heads * self.expand_ratio) + self.value_dim = hidden_size + self.gate_low_rank_dim = gate_low_rank_dim + self.layer_idx = layer_idx + + assert mode in ['chunk', 'fused_chunk'], f"Not supported mode `{mode}`." + assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" + assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" + + self.head_f_dim = self.expand_ratio + self.head_i_dim = self.hidden_size // num_heads + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim, + kernel_size=conv_size, + bias=conv_bias, + activation=None, + ) + + self.g_proj = nn.Sequential( + nn.Linear(hidden_size, gate_low_rank_dim, bias=False), + nn.Linear(gate_low_rank_dim, hidden_size, bias=False) + ) + self.g_norm = FusedRMSNormGated( + hidden_size=hidden_size, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + # launching the triton kernel for just one token will actually be slower + mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + mask=conv_mask, + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + mask=conv_mask, + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + mask=conv_mask, + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + + # dealing with left-padding + if attention_mask is not None: + v = v.mul_(attention_mask[:, -v.shape[-2]:, None]) + + q = F.silu(q) + q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_f_dim), (q, k)) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_i_dim) + # TODO: this 2 steps took huge amount of time, which should be optimized + z = k.float().logcumsumexp(1) + + if cu_seqlens is not None: + raise NotImplementedError("LightNet does not support variable-length sequences for now.") + k, g = torch.exp(k - z).to(k.dtype), (torch.cat((z[:, :1], z[:, :-1]), 1) - z).to(k.dtype) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_gla( + q=q, + k=k, + v=v, + gk=g, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + elif mode == 'chunk': + o, recurrent_state = chunk_gla( + q=q, + k=k, + v=v, + g=g, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q.shape[1] + ) + + o = rms_norm_swish_gate_linear( + rearrange(o, 'b t h d -> b t (h d)'), + self.g_proj(hidden_states), + self.g_norm.weight, + self.g_norm.bias, + self.o_proj.weight, + self.o_proj.bias + ) + return o, None, past_key_values + + def state_size(self, **kwargs) -> int: + state_size = self.key_dim * self.head_i_dim + for module in self.children(): + if isinstance(module, ShortConvolution): + state_size += module.state_size + return state_size diff --git a/layers/linear_attn.py b/layers/linear_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..d723bc9a2bfa33a4343930c0a401b86fd74b321d --- /dev/null +++ b/layers/linear_attn.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat + +from fla.modules import RMSNorm +from fla.modules.feature_map import DPFPFeatureMap, HadamardFeatureMap, HedgehogFeatureMap, T2RFeatureMap +from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn, fused_recurrent_linear_attn + + +class LinearAttention(nn.Module): + + def __init__( + self, + mode: str = 'chunk', + hidden_size: str = 1024, + expand_k: float = 1.0, + expand_v: float = 1.0, + num_heads: int = 8, + num_kv_heads: Optional[int] = None, + feature_map: str = 'elementwise_product', + tie_feature_map_qk: bool = False, + output_norm: str = 'rmsnorm', + norm_q: bool = False, + norm_k: bool = False, + do_feature_map_norm: bool = False, + elementwise_affine: bool = True, + norm_eps: float = 1e-5, + **kwargs + ): + super().__init__() + + self.hidden_size = hidden_size + self.mode = mode + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads + self.num_kv_groups = self.num_heads // self.num_kv_heads + self.key_dim = int(hidden_size * expand_k) + self.value_dim = int(hidden_size * expand_v) + self.key_dim_per_group = self.key_dim // self.num_kv_groups + self.value_dim_per_group = self.value_dim // self.num_kv_groups + + assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not supported mode `{mode}`." + assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" + assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" + + self.head_k_dim = self.key_dim // num_heads + self.head_v_dim = self.value_dim // num_heads + self.do_feature_map_norm = do_feature_map_norm + + if feature_map == 'hedgehog': + if tie_feature_map_qk: + self.feature_map_q = self.feature_map_k = HedgehogFeatureMap(head_dim=self.head_k_dim) + else: + self.feature_map_q = HedgehogFeatureMap(head_dim=self.head_k_dim) + self.feature_map_k = HedgehogFeatureMap(head_dim=self.head_k_dim) + + elif feature_map == 't2r': + if tie_feature_map_qk: + self.feature_map_q = self.feature_map_k = T2RFeatureMap(head_dim=self.head_k_dim) + else: + self.feature_map_q = T2RFeatureMap(head_dim=self.head_k_dim) + self.feature_map_k = T2RFeatureMap(head_dim=self.head_k_dim) + + elif feature_map == 'elementwise_product': + if tie_feature_map_qk: + self.feature_map_q = self.feature_map_k = HadamardFeatureMap(head_dim=self.head_k_dim) + else: + self.feature_map_q = HadamardFeatureMap(head_dim=self.head_k_dim) + self.feature_map_k = HadamardFeatureMap(head_dim=self.head_k_dim) + + elif feature_map == 'dpfp': + self.feature_map_q = DPFPFeatureMap(head_dim=self.head_k_dim) + self.feature_map_k = DPFPFeatureMap(head_dim=self.head_k_dim) + + elif feature_map == 'elu': + def elu(x): + return F.elu(x) + 1 + self.feature_map_q = elu + self.feature_map_k = elu + + elif feature_map == 'relu': + self.feature_map_q = nn.ReLU() + self.feature_map_k = nn.ReLU() + + elif feature_map == 'identity': + self.feature_map_q = nn.Identity() + self.feature_map_k = nn.Identity() + else: + raise NotImplementedError(f"Not supported feature map `{feature_map}`.") + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False) + + if output_norm == 'rmsnorm': + self.norm = RMSNorm(hidden_size=self.head_v_dim, elementwise_affine=elementwise_affine, eps=norm_eps) + elif output_norm == 'identity': + self.norm = nn.Identity() + else: + raise NotImplementedError(f"Not supported output norm `{output_norm}`.") + + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + self.norm_q = norm_q + self.norm_k = norm_k + + def forward( + self, + hidden_states: torch.Tensor, + **kwargs + ) -> torch.Tensor: + mode = self.mode + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + + q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim) + if self.num_kv_groups > 1: + k = repeat(k, '... (h d) -> ... (h g) d', d=self.head_k_dim, g=self.num_kv_groups) + v = repeat(v, '... (h d) -> ... (h g) d', d=self.head_v_dim, g=self.num_kv_groups) + else: + k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + + q = self.feature_map_q(q) + k = self.feature_map_k(k) + + if self.norm_q: + q = q / (q.sum(-1, True) + 1e-4) + if self.norm_k: + k = k / (k.sum(-1, True) + 1e-4) + + if mode == 'chunk': + o, final_state = chunk_linear_attn( + q=q, + k=k, + v=v, + normalize=self.do_feature_map_norm, + ) + elif mode == 'fused_chunk': + o, final_state = fused_chunk_linear_attn( + q=q, + k=k, + v=v, + normalize=self.do_feature_map_norm, + ) + elif mode == 'fused_recurrent': + o, final_state = fused_recurrent_linear_attn( + q=q, + k=k, + v=v, + normalize=self.do_feature_map_norm, + ) + else: + raise NotImplementedError + o = self.norm(o) + o = rearrange(o, '... h d -> ... (h d)') + o = self.o_proj(o) + return o diff --git a/layers/log_linear_mamba2.py b/layers/log_linear_mamba2.py new file mode 100644 index 0000000000000000000000000000000000000000..7e21047efb2145804c39f6542a9fb50a1a056cbd --- /dev/null +++ b/layers/log_linear_mamba2.py @@ -0,0 +1,650 @@ +import math +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from transformers.activations import ACT2FN +from transformers.utils import logging + +from fla.layers.mamba2 import apply_mask_to_padding_states, causal_conv1d_fn, causal_conv1d_update, is_fast_path_available +from fla.modules.layernorm_gated import RMSNormGated, rmsnorm_fn +from fla.ops.log_linear_attn.chunk import LogLinearAttentionState, chunk_log_linear_attn + +if TYPE_CHECKING: + from fla.models.log_linear_mamba2.modeling_log_linear_mamba2 import LogLinearMamba2Cache + +logger = logging.get_logger(__name__) + + +def ceil_log(x: int, b: int) -> int: + return math.ceil(math.log(x, b)) + + +def get_num_levels(length: int, base: int) -> int: + return ceil_log(length, base) + 1 + + +MAX_SEQUENCE_LENGTH = 2048 * 8 +LAMBDA_LEVEL_BASE = 2 +MAX_NUM_LEVELS = get_num_levels(length=MAX_SEQUENCE_LENGTH, base=LAMBDA_LEVEL_BASE) + + +def hmamba_chunk_scan_combined( + x: torch.Tensor, + dt: torch.Tensor, + A: torch.Tensor, + B: torch.Tensor, + C: torch.Tensor, + dl: torch.Tensor, + L: torch.Tensor, + chunk_size: int, + D: Optional[torch.Tensor] = None, + z: Optional[torch.Tensor] = None, + dt_bias: Optional[torch.Tensor] = None, + initial_states: Optional[LogLinearAttentionState] = None, + seq_idx: Optional[torch.Tensor] = None, + cu_seqlens: Optional[torch.Tensor] = None, + dt_softplus: bool = False, + dt_limit: Tuple[float, float] = (0.0, float("inf")), + return_final_states: bool = False, +): + if z is not None: + raise NotImplementedError + if seq_idx is not None: + raise NotImplementedError + if cu_seqlens is not None: + raise NotImplementedError + if dt_softplus is not True: + raise NotImplementedError + if tuple(dt_limit) != (0.0, float("inf")): + raise NotImplementedError + if chunk_size != 64: + raise NotImplementedError + if not B.shape == C.shape: + raise ValueError("B and C must have the same shape") + + if D is not None: + if D.dim() != 1: + raise ValueError + D = rearrange(D, "h -> 1 1 h 1") + D_residual = x * D + + if dt_bias is not None: + dt = dt + rearrange(dt_bias, "h -> 1 1 h") + if dt_softplus: + dt = torch.nn.functional.softplus(dt) + if dt_limit != (0.0, float("inf")): + dt = torch.clamp(dt, min=dt_limit[0], max=dt_limit[1]) + x = (x * rearrange(dt, "b l h -> b l h 1")).to(x.dtype) + A = rearrange(A, "h -> 1 1 h") * dt + + L = torch.nn.functional.softplus(rearrange(L, "h ell -> 1 1 h ell") * dl).to(L.dtype) + + y, state = chunk_log_linear_attn( + q=C, + k=B, + v=x, + g=A, + level_scales=L, + initial_state=initial_states, + output_final_state=return_final_states, + cu_seqlens=cu_seqlens, + ) + + if D is not None: + y = y + D_residual + + return y, state + + +def hmamba_split_conv1d_scan_combined( + zxbcdtdl: torch.Tensor, + conv1d_weight: torch.Tensor, + conv1d_bias: torch.Tensor, + dt_bias: torch.Tensor, + A: torch.Tensor, + L: torch.Tensor, + D: torch.Tensor, + chunk_size: int, + initial_states: Optional[torch.Tensor] = None, + seq_idx: Optional[torch.Tensor] = None, + dt_limit: Tuple[float, float] = (0.0, float("inf")), + return_final_states: bool = False, + activation: str = "silu", + rmsnorm_weight: Optional[torch.Tensor] = None, + rmsnorm_eps: float = 1e-6, + outproj_weight: Optional[torch.Tensor] = None, + outproj_bias: Optional[torch.Tensor] = None, + headdim: Optional[int] = None, + ngroups: int = 1, + norm_before_gate: bool = True, +) -> torch.Tensor: + """ + Argument: + zxbcdtdl: (batch, seqlen, 2 * dim + 2 * ngroups * dstate + nheads) where dim == nheads * headdim + conv1d_weight: (dim + 2 * ngroups * dstate, width) + conv1d_bias: (dim + 2 * ngroups * dstate,) + dt_bias: (nheads,) + A: (nheads) + L: (nheads, nlevels) + D: (nheads, headdim) or (nheads,) + initial_states: (batch, nheads, headdim, dstate) + seq_idx: (batch, seqlen), int32 + rmsnorm_weight: (dim,) + outproj_weight: (out_dim, dim) + outproj_bias: (out_dim,) + headdim: if D is 1D, headdim must be passed in + norm_before_gate: if True, we do RMSNorm(x) * F.silu(z). If False, we do RMSNorm(x * F.silu(z)) + Return: + out: (batch, seqlen, dim) + """ + if initial_states is not None: + raise NotImplementedError + if seq_idx is not None: + raise NotImplementedError + if dt_limit != (0.0, float("inf")): + raise NotImplementedError + if return_final_states is not False: + raise NotImplementedError + if norm_before_gate is not False: + raise NotImplementedError + if rmsnorm_weight is None: + raise NotImplementedError + if activation not in ["silu", "swish"]: + raise NotImplementedError + + batch, seqlen, _ = zxbcdtdl.shape + dlambda = L.shape[-1] + (nheads,) = D.shape + dim = nheads * headdim + dstate = (zxbcdtdl.shape[-1] - 2 * dim - nheads - nheads * dlambda) // ngroups // 2 + + if D.dim() != 1: + raise ValueError + if headdim is None: + raise ValueError + if nheads % ngroups != 0: + raise ValueError + if zxbcdtdl.shape != ( + batch, + seqlen, + 2 * dim + 2 * ngroups * dstate + nheads + nheads * dlambda, + ): + raise ValueError + if dt_bias.shape != (nheads,): + raise ValueError + if A.shape != (nheads,): + raise ValueError + if L.shape != (nheads, dlambda): + raise ValueError + if D.shape != (nheads,): + raise ValueError + if rmsnorm_weight is None: + raise ValueError + + zxBCdtl_splits = [dim, dim + 2 * ngroups * dstate, nheads, nheads * dlambda] + xBC_splits = [dim, ngroups * dstate, ngroups * dstate] + z, xBC, dt, dl = torch.split(zxbcdtdl, zxBCdtl_splits, dim=-1) + xBC = rearrange( + causal_conv1d_fn( + rearrange(xBC, "b s d -> b d s"), + conv1d_weight, + bias=conv1d_bias, + activation=activation, + seq_idx=seq_idx, + ), + "b d s -> b s d", + ) + x, B, C = torch.split(xBC, xBC_splits, dim=-1) + x = rearrange(x, "b l (h p) -> b l h p", h=nheads, p=headdim) + B = rearrange(B, "b l (g n) -> b l g n", g=ngroups, n=dstate) + C = rearrange(C, "b l (g n) -> b l g n", g=ngroups, n=dstate) + dl = rearrange(dl, "b l (h ell) -> b l h ell", h=nheads, ell=dlambda) + y, _ = hmamba_chunk_scan_combined( + x=x, + dt=dt, + A=A, + B=B, + C=C, + dl=dl, + L=L, + chunk_size=chunk_size, + D=D, + z=z if rmsnorm_weight is None else None, + dt_bias=dt_bias, + dt_softplus=True, + seq_idx=seq_idx, + cu_seqlens=None, + dt_limit=dt_limit, + return_final_states=return_final_states, + ) + + y = rearrange(y, "b l h p -> b l (h p)") + if rmsnorm_weight is not None: + y = rmsnorm_fn( + x=y, + weight=rmsnorm_weight, + bias=None, + z=z, + eps=rmsnorm_eps, + group_size=None, + norm_before_gate=False, + ) + out = torch.nn.functional.linear(y, outproj_weight, outproj_bias) + return out + + +class LogLinearMamba2(nn.Module): + """ + Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`. + A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective) + ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4, + and is why Mamba is called **selective** state spaces) + """ + + def __init__( + self, + num_heads: int, + head_dim: int = 64, + hidden_size: int = 2048, + state_size: int = 128, + expand: int = 2, + n_groups: int = 1, + conv_kernel: int = 4, + use_conv_bias: bool = False, + hidden_act: str = "silu", + rms_norm: bool = True, + chunk_size: int = 64, + time_step_rank: float = 256, + time_step_limit: Tuple[float, float] = (0.0, float("inf")), + time_step_min: float = 0.001, + time_step_max: float = 0.1, + use_bias: bool = True, + norm_eps: float = 1e-5, + layer_idx: int = None, + ): + super().__init__() + self.num_heads = num_heads + self.hidden_size = hidden_size + self.ssm_state_size = state_size + self.conv_kernel_size = conv_kernel + self.intermediate_size = int(expand * self.hidden_size) + self.time_step_rank = int(time_step_rank) + self.layer_idx = layer_idx + self.use_conv_bias = use_conv_bias + self.activation = hidden_act + self.act = ACT2FN[hidden_act] + + self.layer_norm_epsilon = norm_eps + self.rms_norm = rms_norm + + self.n_groups = n_groups + self.head_dim = head_dim + self.chunk_size = chunk_size + + self.time_step_limit = time_step_limit + self.time_step_min = time_step_min + self.time_step_max = time_step_max + + self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.conv1d = nn.Conv1d( + in_channels=self.conv_dim, + out_channels=self.conv_dim, + bias=use_conv_bias, + kernel_size=conv_kernel, + groups=self.conv_dim, + padding=conv_kernel - 1, + ) + + self.num_lambda_dims = MAX_NUM_LEVELS + self.lambda_level_module = None + + # projection of the input hidden states + projection_size = ( + self.intermediate_size + + self.conv_dim + + self.num_heads * (self.num_lambda_dims + 1) + ) + self.in_proj = nn.Linear( + self.hidden_size, + projection_size, + bias=use_bias, + ) + # selective projection used to make dt, B and C input dependant + + # time step projection (discretization) + # instantiate once and copy inv_dt in init_weights of PretrainedModel + self.dt_bias = nn.Parameter(torch.ones(self.num_heads)) + + # S4D real initialization. These are not discretized! + # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded + A = torch.arange(1, self.num_heads + 1) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + + self.lambda_mode = "positive" + L = torch.ones(self.num_heads, self.num_lambda_dims) + self.L = nn.Parameter(L) + self.L._no_weight_decay = True + + self.norm = RMSNormGated( + self.intermediate_size, eps=self.layer_norm_epsilon, norm_before_gate=False + ) + self.D = nn.Parameter(torch.ones(self.num_heads)) + self.D._no_weight_decay = True + + self.out_proj = nn.Linear( + self.intermediate_size, self.hidden_size, bias=use_bias + ) + self.use_bias = use_bias + + if not is_fast_path_available: + logger.warning_once( + "The fast path is not available because one of " + "`(selective_state_update, causal_conv1d_fn, causal_conv1d_update)` is None. " + "Falling back to the naive implementation. " + "To install follow https://github.com/state-spaces/mamba/#installation and" + "https://github.com/Dao-AILab/causal-conv1d" + ) + + def cuda_kernels_forward( + self, + hidden_states: torch.Tensor, + cache_params: Optional["LogLinearMamba2Cache"] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + ): + if attention_mask is not None: + # only supporting this in decoding + if cache_params is None: + raise NotImplementedError + if self.activation not in ["silu", "swish"]: + raise ValueError + + # 1. Gated MLP's linear projection + hidden_states = apply_mask_to_padding_states( + hidden_states=hidden_states, + attention_mask=attention_mask, + ) + projected_states = self.in_proj(hidden_states) + + # Set up dimensions for reshapes later + batch_size, seq_len, _ = hidden_states.shape + groups_time_state_size = self.n_groups * self.ssm_state_size + d_mlp = ( + projected_states.shape[-1] + - 2 * self.intermediate_size + - 2 * self.n_groups * self.ssm_state_size + - self.num_heads * (self.num_lambda_dims + 1) + ) // 2 + if d_mlp != 0: + raise ValueError + + # Single step calculations via cache + if ( + cache_params is not None + and cache_position is not None + and cache_position[0] > 0 + ): + if hidden_states.shape[1] != 1: + raise ValueError + + gate, xBC, dt, dl = torch.split( + projected_states.squeeze(1), + [ + self.intermediate_size, + self.conv_dim, + self.num_heads, + self.num_heads * self.num_lambda_dims, + ], + dim=-1, + ) + + # 2. Convolution sequence transformation + xBC = causal_conv1d_update( + xBC, + cache_params.conv_states[self.layer_idx], + rearrange(self.conv1d.weight, "d 1 w -> d w"), + self.conv1d.bias, + self.activation, + ) + + x, B, C = torch.split( + xBC, + [ + self.intermediate_size, + groups_time_state_size, + groups_time_state_size, + ], + dim=-1, + ) + + # 3. SSM transformation + A = -torch.exp(self.A_log.float()) # (nheads,) + B = rearrange( + B, + "b (g n) -> b g n", + b=batch_size, + g=self.n_groups, + n=self.ssm_state_size, + ) + C = rearrange( + C, + "b (g n) -> b g n", + b=batch_size, + g=self.n_groups, + n=self.ssm_state_size, + ) + x_reshaped = rearrange( + x, + "b (h p) -> b h p", + b=batch_size, + h=self.num_heads, + p=self.head_dim, + ) + dl_reshaped = rearrange( + dl, + "b (h ell) -> b h ell", + b=batch_size, + h=self.num_heads, + ell=self.num_lambda_dims, + ) + y, hssm_state = hmamba_chunk_scan_combined( + x_reshaped, + dt=dt, + A=A, + B=B, + C=C, + dl=dl_reshaped, + L=self.L, + D=self.D, + z=None, + dt_bias=self.dt_bias, + dt_softplus=True, + initial_states=cache_params.hssm_states[self.layer_idx], + return_final_states=True, + ) + cache_params.update_hssm_state( + layer_idx=self.layer_idx, + new_hssm_state=hssm_state, + ) + y = rearrange( + y, + "b h p -> b (h p)", + b=batch_size, + h=self.num_heads, + p=self.head_dim, + ) + y = self.norm(y, gate) + + # 4. Final linear projection + out = self.out_proj(y)[:, None, ...] + + # Fused calculations or step by step if no initialized cache is found + else: + A = -torch.exp( + self.A_log.float() + ) # (num_heads) or (intermediate_size, state_size) + dt_limit_kwargs = ( + {} + if self.time_step_limit == (0.0, float("inf")) + else {"dt_limit": self.time_step_limit} + ) + + # 2-4. Fused kernel for conv1d, SSM, and the final projection + if self.training and cache_params is None: + out = torch.utils.checkpoint.checkpoint( + hmamba_split_conv1d_scan_combined, + use_reentrant=False, + # function arguments + zxbcdtdl=projected_states, + conv1d_weight=rearrange(self.conv1d.weight, "d 1 w -> d w"), + conv1d_bias=self.conv1d.bias, + dt_bias=self.dt_bias, + A=A, + L=self.L, + D=self.D, + chunk_size=self.chunk_size, + seq_idx=None, # was seq_idx + activation=self.activation, + rmsnorm_weight=self.norm.weight, + rmsnorm_eps=self.norm.eps, + outproj_weight=self.out_proj.weight, + outproj_bias=self.out_proj.bias, + headdim=self.head_dim, + ngroups=self.n_groups, + norm_before_gate=False, + return_final_states=False, + **dt_limit_kwargs, + ) + + else: + gate, xBC, dt, dl = torch.split( + projected_states, + [ + self.intermediate_size, + self.conv_dim, + self.num_heads, + self.num_heads * self.num_lambda_dims, + ], + dim=-1, + ) + + # 2. Convolution sequence transformation + # Init cache + if cache_params is not None: + xBC_t = rearrange(xBC, "b l d -> b d l") + conv_states = torch.nn.functional.pad( + xBC_t, + (cache_params.conv_kernel_size - xBC_t.shape[-1], 0), + ) + cache_params.update_conv_state( + layer_idx=self.layer_idx, + new_conv_state=conv_states, + cache_init=True, + ) + + xBC = causal_conv1d_fn( + x=xBC.transpose(1, 2), + weight=rearrange(self.conv1d.weight, "d 1 w -> d w"), + bias=self.conv1d.bias, + activation=self.activation, + ).transpose(1, 2) + + xBC = apply_mask_to_padding_states( + hidden_states=xBC, + attention_mask=attention_mask, + ) + + x, B, C = torch.split( + xBC, + [ + self.intermediate_size, + groups_time_state_size, + groups_time_state_size, + ], + dim=-1, + ) + + # 3. SSM transformation + y, hssm_state = hmamba_chunk_scan_combined( + rearrange( + x, + "b l (h p) -> b l h p", + b=batch_size, + l=seq_len, + p=self.head_dim, + ), + dt=dt, + A=A, + B=rearrange( + B, + "b l (g n) -> b l g n", + b=batch_size, + l=seq_len, + g=self.n_groups, + ), + C=rearrange( + C, + "b l (g n) -> b l g n", + b=batch_size, + l=seq_len, + g=self.n_groups, + ), + dl=rearrange( + dl, + "b l (h ell) -> b l h ell", + b=batch_size, + h=self.num_heads, + ell=self.num_lambda_dims, + ), + L=self.L, + chunk_size=self.chunk_size, + D=self.D, + z=None, + seq_idx=None, + return_final_states=True, + dt_bias=self.dt_bias, + dt_softplus=True, + **dt_limit_kwargs, + ) + + # Init cache + if hssm_state is not None and cache_params is not None: + cache_params.update_hssm_state( + layer_idx=self.layer_idx, + new_hssm_state=hssm_state, + ) + + y = rearrange( + y, + "b l h p -> b l (h p)", + b=batch_size, + l=seq_len, + h=self.num_heads, + p=self.head_dim, + ) + # Multiply "gate" branch and apply extra normalization layer + y = self.norm(y, gate) + + # 4. Final linear projection + out = self.out_proj(y) + + return out + + def forward( + self, + hidden_states, + cache_params: Optional["LogLinearMamba2Cache"] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + ): + if "cuda" in self.in_proj.weight.device.type: + return self.cuda_kernels_forward( + hidden_states=hidden_states, + cache_params=cache_params, + cache_position=cache_position, + attention_mask=attention_mask, + ) + raise NotImplementedError diff --git a/layers/mamba.py b/layers/mamba.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2f6fce44829a102260fecb64c0561cca99f640 --- /dev/null +++ b/layers/mamba.py @@ -0,0 +1,335 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Dict, Optional + +import torch +import torch.nn as nn +from transformers.utils import logging + +from fla.modules.activations import ACT2FN + +with warnings.catch_warnings(): + warnings.simplefilter('ignore') + try: + from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, selective_scan_fn + from mamba_ssm.ops.triton.selective_state_update import selective_state_update + except ImportError: + selective_state_update, selective_scan_fn, mamba_inner_fn = None, None, None + + try: + from causal_conv1d import causal_conv1d_fn, causal_conv1d_update + except ImportError: + causal_conv1d_update, causal_conv1d_fn = None, None + is_fast_path_available = all(( + selective_state_update, + selective_scan_fn, + mamba_inner_fn + )) +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.mamba.modeling_mamba import MambaCache + +logger = logging.get_logger(__name__) + + +class Mamba(nn.Module): + """ + Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`. + A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective) + ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4, + and is why Mamba is called **selective** state spaces) + """ + + def __init__( + self, + hidden_size: int = 2048, + state_size: int = 16, + conv_kernel: int = 4, + use_conv_bias: bool = True, + intermediate_size: int = 2048, + time_step_rank: int = 256, + use_bias: bool = True, + hidden_act: str = "silu", + layer_idx: int = None, + backend: str = "cuda", + ): + super().__init__() + + self.hidden_size = hidden_size + self.ssm_state_size = state_size + self.conv_kernel_size = conv_kernel + self.use_conv_bias = use_conv_bias + self.intermediate_size = intermediate_size + self.time_step_rank = time_step_rank + self.use_bias = use_bias + + self.conv1d = nn.Conv1d( + in_channels=self.intermediate_size, + out_channels=self.intermediate_size, + bias=use_conv_bias, + kernel_size=conv_kernel, + groups=self.intermediate_size, + padding=conv_kernel - 1, + ) + + self.activation = hidden_act + self.act = ACT2FN[hidden_act] + + self.layer_idx = layer_idx + + # projection of the input hidden states + self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=use_bias) + # selective projection used to make dt, B and C input dependant + self.x_proj = nn.Linear(self.intermediate_size, self.time_step_rank + self.ssm_state_size * 2, bias=False) + # time step projection (discretization) + self.dt_proj = nn.Linear(self.time_step_rank, self.intermediate_size, bias=True) + + # S4D real initialization. These are not discretized! + # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded + A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :] + A = A.expand(self.intermediate_size, -1).contiguous() + + self.A_log = nn.Parameter(torch.log(A)) + self.D = nn.Parameter(torch.ones(self.intermediate_size)) + self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=use_bias) + + if not is_fast_path_available: + logger.warning_once( + "The fast path is not available because on of " + "`(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`" + " is None. Falling back to the naive implementation. " + "To install follow https://github.com/state-spaces/mamba/#installation and" + " https://github.com/Dao-AILab/causal-conv1d" + ) + import os + backend = os.environ.get('FLA_CONV_BACKEND', backend) + assert backend in ['cuda', 'triton'], f"Unsupported backend: {backend}" + if backend == 'cuda' and causal_conv1d_fn is None: + logger.warning_once( + "The CUDA backend is not available because `causal_conv1d` is None. " + "Falling back to the Triton backend. " + "To install follow https://github.com/Dao-AILab/causal-conv1d" + ) + backend = 'triton' + if backend == 'triton': + from fla.modules.convolution import causal_conv1d as causal_conv1d_triton + from fla.modules.convolution import causal_conv1d_update as causal_conv1d_update_triton + self.causal_conv1d_fn = causal_conv1d_triton + self.causal_conv1d_update = causal_conv1d_update_triton + else: + self.causal_conv1d_fn = causal_conv1d_fn + self.causal_conv1d_update = causal_conv1d_update + self.backend = backend + + def cuda_kernels_forward( + self, + hidden_states: torch.Tensor, + cache_params: Optional[MambaCache] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.LongTensor] = None, + **kwargs: Unpack[Dict] + ): + # 1. Gated MLP's linear projection + projected_states = self.in_proj(hidden_states).transpose(1, 2) + + if self.training and cache_params is None: # Doesn't support outputting the states -> used for training + contextualized_states = mamba_inner_fn( + projected_states, + self.conv1d.weight, + self.conv1d.bias if self.use_conv_bias else None, + self.x_proj.weight, + self.dt_proj.weight, + self.out_proj.weight, + self.out_proj.bias.float() if self.use_bias else None, + -torch.exp(self.A_log.float()), + None, # input-dependent B + None, # input-dependent C + self.D.float(), + delta_bias=self.dt_proj.bias.float(), + delta_softplus=True, + ) + + else: + hidden_states, gate = projected_states.chunk(2, dim=1) + + if attention_mask is not None: + hidden_states = hidden_states * attention_mask.unsqueeze(1) + + # 2. Convolution sequence transformation + conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2)) + if cache_params is not None and cache_position[0] > 0: + hidden_states = self.causal_conv1d_update( + hidden_states.squeeze(-1), + cache_params.conv_states[self.layer_idx], + conv_weights, + self.conv1d.bias, + self.activation, + ) + hidden_states = hidden_states.unsqueeze(-1) + else: + if cache_params is not None: + conv_states = nn.functional.pad( + hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0) + ) + cache_params.update_conv_state(self.layer_idx, conv_states, cache_position) + hidden_states = self.causal_conv1d_fn( + hidden_states, conv_weights, self.conv1d.bias, activation=self.activation + ) + + if attention_mask is not None: + hidden_states = hidden_states * attention_mask.unsqueeze(1) + + # 3. State Space Model sequence transformation + # 3.a. input varying initialization of time_step, B and C + ssm_parameters = self.x_proj(hidden_states.transpose(1, 2)) + time_step, B, C = torch.split( + ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1 + ) + discrete_time_step = self.dt_proj.weight @ time_step.transpose(1, 2) + + A = -torch.exp(self.A_log.float()) + # 3.c perform the recurrence y ← SSM(A, B, C)(x) + time_proj_bias = self.dt_proj.bias.float() if hasattr(self.dt_proj, "bias") else None + if cache_params is not None and cache_position[0] > 0: + scan_outputs = selective_state_update( + cache_params.ssm_states[self.layer_idx], + hidden_states[..., 0], + discrete_time_step[..., 0], + A, + B[:, 0], + C[:, 0], + self.D, + gate[..., 0], + time_proj_bias, + dt_softplus=True, + ).unsqueeze(-1) + else: + scan_outputs, ssm_state = selective_scan_fn( + hidden_states, + discrete_time_step, + A, + B.transpose(1, 2), + C.transpose(1, 2), + self.D.float(), + gate, + time_proj_bias, + delta_softplus=True, + return_last_state=True, + ) + if ssm_state is not None and cache_params is not None: + cache_params.update_ssm_state(self.layer_idx, ssm_state) + + # 4. Final linear projection + contextualized_states = self.out_proj(scan_outputs.transpose(1, 2)) + return contextualized_states + + def slow_forward( + self, + input_states, + cache_params: Optional[MambaCache] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.LongTensor] = None, + **kwargs: Unpack[Dict] + ): + batch_size, seq_len, _ = input_states.shape + dtype = input_states.dtype + # 1. Gated MLP's linear projection + # [batch, 2 * intermediate_size, seq_len] + projected_states = self.in_proj(input_states).transpose(1, 2) + hidden_states, gate = projected_states.chunk(2, dim=1) + + if attention_mask is not None: + hidden_states = hidden_states * attention_mask.unsqueeze(1) + + # 2. Convolution sequence transformation + if cache_params is not None: + ssm_state = cache_params.ssm_states[self.layer_idx].clone() + ssm_state = ssm_state.to(hidden_states.device) + # use `cache_position.shape[0]` to check whether we are in prefill + # stage, it's equivalent to check `cache_position[0] == 0`, which + # breaks dynamo fullgraph constraints + if cache_position.shape[0] == self.conv_kernel_size: + conv_state = nn.functional.pad( + hidden_states, + (self.conv_kernel_size - hidden_states.shape[-1], 0) + ) + + cache_params.update_conv_state(self.layer_idx, conv_state, cache_position) + # [batch, intermediate_size, seq_len] + hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) + else: + conv_state = cache_params.update_conv_state(self.layer_idx, hidden_states, cache_position) + hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1) + if self.use_conv_bias: + hidden_states += self.conv1d.bias + # [batch, intermediate_size, 1] : decoding + hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1) + else: + ssm_state = torch.zeros( + (batch_size, self.intermediate_size, self.ssm_state_size), + device=hidden_states.device, dtype=dtype + ) + # [batch, intermediate_size, seq_len] + hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) + + if attention_mask is not None: + hidden_states = hidden_states * attention_mask.unsqueeze(1) + + # 3. State Space Model sequence transformation + # 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2] + ssm_parameters = self.x_proj(hidden_states.transpose(1, 2)) + time_step, B, C = torch.split( + ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1 + ) + # [batch, seq_len, intermediate_size] + discrete_time_step = self.dt_proj(time_step) + # [batch, intermediate_size, seq_len] + discrete_time_step = nn.functional.softplus(discrete_time_step).transpose(1, 2) + + # 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM) + # [intermediate_size, ssm_state_size] + A = -torch.exp(self.A_log.float()) + # [batch, intermediate_size, seq_len, ssm_state_size] + discrete_A = torch.exp(A[None, :, None, :] * discrete_time_step[:, :, :, None]) + # [batch, intermediate_size, seq_len, ssm_state_size] + discrete_B = discrete_time_step[:, :, :, None] * B[:, None, :, :].float() + deltaB_u = discrete_B * hidden_states[:, :, :, None].float() + + # 3.c perform the recurrence y ← SSM(A, B, C)(x) + scan_outputs = [] + for i in range(seq_len): + # [batch, intermediade_size, ssm_state] + ssm_state = discrete_A[:, :, i, :] * ssm_state + deltaB_u[:, :, i, :] + # [batch, intermediade_size, 1] + scan_output = torch.matmul(ssm_state.to(dtype), C[:, i, :].unsqueeze(-1)) + scan_outputs.append(scan_output[:, :, 0]) + # [batch, seq_len, intermediade_size] + scan_output = torch.stack(scan_outputs, dim=-1) + scan_output = scan_output + (hidden_states * self.D[None, :, None]) + scan_output = (scan_output * self.act(gate)) + + if cache_params is not None: + cache_params.ssm_states[self.layer_idx].copy_(ssm_state) + + # 4. Final linear projection + # [batch, seq_len, hidden_size] + contextualized_states = self.out_proj(scan_output.transpose(1, 2)) + return contextualized_states + # fmt: on + + def forward( + self, + hidden_states, + cache_params: Optional[MambaCache] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.LongTensor] = None, + **kwargs: Unpack[Dict] + ): + if is_fast_path_available and "cuda" in self.x_proj.weight.device.type: + return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, **kwargs) + return self.slow_forward(hidden_states, cache_params, cache_position, attention_mask, **kwargs) diff --git a/layers/mamba2.py b/layers/mamba2.py new file mode 100644 index 0000000000000000000000000000000000000000..f563a24b6553921f1adea7b16795900fdb190f3c --- /dev/null +++ b/layers/mamba2.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +from transformers.utils import logging + +from fla.modules.activations import ACT2FN +from fla.modules.layernorm_gated import RMSNormGated + +with warnings.catch_warnings(): + warnings.simplefilter('ignore') + try: + from mamba_ssm.ops.triton.selective_state_update import selective_state_update + from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined + except ImportError: + selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined = None, None, None + try: + from causal_conv1d import causal_conv1d_fn, causal_conv1d_update + except ImportError: + causal_conv1d_update, causal_conv1d_fn = None, None + is_fast_path_available = selective_state_update is not None + +if TYPE_CHECKING: + from fla.models.mamba2.modeling_mamba2 import Mamba2Cache + +logger = logging.get_logger(__name__) + + +def apply_mask_to_padding_states(hidden_states, attention_mask): + """ + Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66 + """ + if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1: + dtype = hidden_states.dtype + hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype) + + return hidden_states + + +def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int): + """ + Padding x tensor with `pad_size` on the seq_len dim (dim=1) + + Assumes that we only have tensors of either size 4 or 3 + """ + pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0) + + return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0) + + +def reshape_into_chunks(input_tensor, pad_size, chunk_size): + """ + Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and + simultaneously splitting it into chunk sequences. + + Assumes that we only have tensors of either size 4 or 3 + """ + # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...] + input_tensor = pad_tensor_by_size(input_tensor, pad_size) + + if len(input_tensor.shape) == 3: + # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads] + return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2]) + else: + # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> + # [bsz, -1, chunk_size, num_heads, head_dim or state_size] + return input_tensor.reshape( + input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3] + ) + + +def segment_sum(input_tensor): + """ + More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions. + """ + chunk_size = input_tensor.size(-1) + # 1. expand input tensor to have an additional dimension and repeat along that dimension + # [..., chunk_size] -> [..., chunk_size, chunk_size] + input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size) + # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag + mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1) + input_tensor = input_tensor.masked_fill(~mask, 0) + # 3. compute actual cumsum + tensor_segsum = torch.cumsum(input_tensor, dim=-2) + + # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time) + mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0) + tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf) + return tensor_segsum + + +class Mamba2(nn.Module): + """ + Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`. + A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective) + ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4, + and is why Mamba is called **selective** state spaces) + """ + + def __init__( + self, + num_heads: int, + head_dim: int = 64, + hidden_size: int = 2048, + state_size: int = 128, + expand: int = 2, + n_groups: int = 1, + conv_kernel: int = 4, + use_conv_bias: bool = False, + hidden_act: str = "silu", + rms_norm: bool = True, + chunk_size: int = 256, + time_step_rank: float = 256, + time_step_limit: Tuple[float, float] = (0.0, float("inf")), + time_step_min: float = 0.001, + time_step_max: float = 0.1, + use_bias: bool = True, + norm_eps: float = 1e-5, + layer_idx: int = None, + backend: str = "cuda", + ) -> Mamba2: + super().__init__() + + self.num_heads = num_heads + self.head_dim = head_dim + self.hidden_size = hidden_size + self.ssm_state_size = state_size + self.expand = expand + self.intermediate_size = int(expand * hidden_size) + self.n_groups = n_groups + + self.conv_kernel_size = conv_kernel + self.use_conv_bias = use_conv_bias + self.activation = hidden_act + self.act = ACT2FN[hidden_act] + + self.rms_norm = rms_norm + self.norm_eps = norm_eps + + self.chunk_size = chunk_size + + self.time_step_rank = int(time_step_rank) + self.time_step_limit = time_step_limit + self.time_step_min = time_step_min + self.time_step_max = time_step_max + + self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.conv1d = nn.Conv1d( + in_channels=self.conv_dim, + out_channels=self.conv_dim, + bias=use_conv_bias, + kernel_size=conv_kernel, + groups=self.conv_dim, + padding=conv_kernel - 1, + ) + + # projection of the input hidden states + projection_size = self.intermediate_size + self.conv_dim + self.num_heads + self.in_proj = nn.Linear( + self.hidden_size, + projection_size, + bias=use_bias, + ) + # selective projection used to make dt, B and C input dependant + + # time step projection (discretization) + # instantiate once and copy inv_dt in init_weights of PretrainedModel + self.dt_bias = nn.Parameter(torch.ones(self.num_heads)) + + # S4D real initialization. These are not discretized! + # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded + A = torch.arange(1, self.num_heads + 1) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + self.norm = RMSNormGated( + self.intermediate_size, eps=self.norm_eps, norm_before_gate=False + ) + self.D = nn.Parameter(torch.ones(self.num_heads)) + self.D._no_weight_decay = True + + self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=use_bias) + self.use_bias = use_bias + + self.layer_idx = layer_idx + + if not is_fast_path_available: + logger.warning_once( + "The fast path is not available because one of " + "`(selective_state_update)` is None. " + "Falling back to the naive implementation. " + "To install follow https://github.com/state-spaces/mamba/#installation" + ) + import os + backend = os.environ.get('FLA_CONV_BACKEND', backend) + assert backend in ['cuda', 'triton'], f"Unsupported backend: {backend}" + if backend == 'cuda' and causal_conv1d_fn is None: + logger.warning_once( + "The CUDA backend is not available because `causal_conv1d` is None. " + "Falling back to the Triton backend. " + "To install follow https://github.com/Dao-AILab/causal-conv1d" + ) + backend = 'triton' + if backend == 'triton': + from fla.modules.convolution import causal_conv1d as causal_conv1d_triton + from fla.modules.convolution import causal_conv1d_update as causal_conv1d_update_triton + self.causal_conv1d_fn = causal_conv1d_triton + self.causal_conv1d_update = causal_conv1d_update_triton + logger.warning( + "Mamba2 does not recommend using Triton's conv1d backend, " + "as it is untested and may contain bugs." + ) + else: + self.causal_conv1d_fn = causal_conv1d_fn + self.causal_conv1d_update = causal_conv1d_update + self.backend = backend + + def cuda_kernels_forward( + self, + hidden_states: torch.Tensor, + cache_params: Optional[Mamba2Cache] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + ): + # 1. Gated MLP's linear projection + hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask) + projected_states = self.in_proj(hidden_states) + + # Set up dimensions for reshapes later + batch_size, seq_len, _ = hidden_states.shape + groups_time_state_size = self.n_groups * self.ssm_state_size + d_mlp = ( + projected_states.shape[-1] + - 2 * self.intermediate_size + - 2 * self.n_groups * self.ssm_state_size + - self.num_heads + ) // 2 + + # Single step calculations via cache + if cache_params is not None and cache_position is not None and cache_position[0] > 0: + _, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split( + [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1 + ) + + # 2. Convolution sequence transformation + hidden_states_B_C = self.causal_conv1d_update( + hidden_states_B_C.contiguous(), + cache_params.conv_states[self.layer_idx], + self.conv1d.weight.squeeze(1), + self.conv1d.bias, + self.activation, + ) + + 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 transformation + A = -torch.exp(self.A_log.float()) # (nheads,) + A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32) + dt = dt[:, :, None].expand(-1, -1, self.head_dim) + dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim) + D = self.D[:, None, ...].expand(-1, self.head_dim) + B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups) + C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups) + hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim) + + hidden_states = selective_state_update( + cache_params.ssm_states[self.layer_idx], + hidden_states_reshaped, + dt, + A, + B, + C, + D, + z=None, + dt_bias=dt_bias, + dt_softplus=True, + ) + hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim) + hidden_states = self.norm(hidden_states, gate) + + # 4. Final linear projection + out = self.out_proj(hidden_states)[:, None, ...] + + # Fused calculations or step by step if no initialized cache is found + else: + A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size) + dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit} + + # 2-4. Fused kernel for conv1d, SSM, and the final projection + if self.training and cache_params is None: + out = mamba_split_conv1d_scan_combined( + projected_states, + self.conv1d.weight.squeeze(1), + self.conv1d.bias, + self.dt_bias, + A, + D=self.D, + chunk_size=self.chunk_size, + seq_idx=None, # was seq_idx + activation=self.activation, + rmsnorm_weight=self.norm.weight, + rmsnorm_eps=self.norm.eps, + outproj_weight=self.out_proj.weight, + outproj_bias=self.out_proj.bias, + headdim=self.head_dim, + ngroups=self.n_groups, + norm_before_gate=False, + return_final_states=False, + **dt_limit_kwargs, + ) + + else: + _, _, gate, hidden_states_B_C, dt = projected_states.split( + [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1 + ) + + # 2. Convolution sequence transformation + # Init cache + if cache_params is not None: + hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2) + conv_states = nn.functional.pad( + hidden_states_B_C_transposed, + (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0), + ) + cache_params.update_conv_state( + layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True + ) + + if self.activation not in ["silu", "swish"]: + hidden_states_B_C = self.act( + self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2) + ) + else: + _conv1d_output = self.causal_conv1d_fn( + x=hidden_states_B_C.transpose(1, 2).contiguous(), + weight=self.conv1d.weight.squeeze(1), + bias=self.conv1d.bias, + activation=self.activation, + ) + if self.backend == 'cuda': + hidden_states_B_C = _conv1d_output + hidden_states_B_C = hidden_states_B_C.transpose(1, 2) + elif self.backend == 'triton': + hidden_states_B_C, _ = _conv1d_output + hidden_states_B_C = hidden_states_B_C.transpose(1, 2).contiguous() + else: + raise ValueError(f"Unsupported backend: {self.backend}") + + hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask) + 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 transformation + scan_output, ssm_state = mamba_chunk_scan_combined( + hidden_states.view(batch_size, seq_len, -1, self.head_dim), + dt, + 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=None, + return_final_states=True, + dt_bias=self.dt_bias, + dt_softplus=True, + **dt_limit_kwargs, + ) + + # Init cache + if ssm_state is not None and cache_params is not None: + cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state) + + scan_output = scan_output.view(batch_size, seq_len, -1) + # Multiply "gate" branch and apply extra normalization layer + scan_output = self.norm(scan_output, gate) + + # 4. Final linear projection + out = self.out_proj(scan_output) + return out + + # fmt: off + def torch_forward( + self, + input_states, + cache_params: Optional[Mamba2Cache] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None + ): + batch_size, seq_len, _ = input_states.shape + dtype = input_states.dtype + + # 1. Gated MLP's linear projection + input_states = apply_mask_to_padding_states(input_states, attention_mask) + projected_states = self.in_proj(input_states) + d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - + 2 * self.n_groups * self.ssm_state_size - self.num_heads) // 2 + _, _, gate, hidden_states_B_C, dt = projected_states.split( + [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1 + ) + + # 2. Convolution sequence transformation + if cache_params is not None and cache_position is not None and cache_position[0] > 0: + cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False) + + # We need to guarantee that anything regarding the cache is on the same device + conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device) + + hidden_states_B_C = torch.sum( + conv_states * self.conv1d.weight.squeeze(1), dim=-1 + ) + if self.use_conv_bias: + hidden_states_B_C = hidden_states_B_C + self.conv1d.bias + hidden_states_B_C = self.act(hidden_states_B_C) + else: + # Init cache + if cache_params is not None: + hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2) + conv_states = nn.functional.pad( + hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0) + ) + cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True) + + hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)) + + hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask) + hidden_states, B, C = torch.split( + hidden_states_B_C, + [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], + dim=-1 + ) + + # 3. SSM transformation + A = -torch.exp(self.A_log.float()) # [num_heads] + if cache_params is not None and cache_position is not None and cache_position[0] > 0: + # We need to guarantee that anything regarding the cache is on the same device + cache_device = cache_params.ssm_states.device + + # Note: there is no need to pad parameter matrices here, as there is just one new token + # for batched generation + dt = dt[:, 0, :][:, None, ...] + dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim) + # [num_heads] -> [num_heads, head_dim] + dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim) + + dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype)) + dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1]) + A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32) + # [bsz, num_heads, head_dim, state_size] + dA = (torch.exp(dt[..., None] * A)).to(device=cache_device) + + # Discretize B + # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] -> + # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size] + B = B.reshape(batch_size, self.n_groups, -1)[..., None, :] + B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous() + B = B.reshape(batch_size, -1, B.shape[-1]) + # [bsz, num_heads, head_dim, state_size] + dB = dt[..., None] * B[..., None, :] + + # Discretize x into dB + # [bsz, intermediate_size] -> [bsz, num_heads, head_dim] + hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim) + dBx = (dB * hidden_states[..., None]).to(device=cache_device) + + # State calculation + cache_params.update_ssm_state( + layer_idx=self.layer_idx, + new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx + ) + + # Subsequent output + # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size] + C = C.reshape(batch_size, self.n_groups, -1)[..., None, :] + C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous() + C = C.reshape(batch_size, -1, C.shape[-1]) + # [bsz, num_heads, head_dim] + + ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n] + # Reshape ssm_states to merge the first two dimensions + # Shape: [b*h, d, n] + ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) + C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1] + y = torch.bmm(ssm_states_reshaped, C_reshaped) + y = y.view(batch_size, self.num_heads, self.head_dim) + + # D skip connection + # [num_heads] -> [num_heads, head_dim] + D = self.D[..., None].expand(self.D.shape[0], self.head_dim) + y = (y + hidden_states * D).to(y.dtype) + + # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size] + y = y.reshape(batch_size, -1)[:, None, ...] + else: + # begin ssd naive implementation without einsums + dt = nn.functional.softplus(dt + self.dt_bias) + dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1]) + hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float() + B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float() + C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float() + B = B.repeat(1, 1, self.num_heads // self.n_groups, 1) + C = C.repeat(1, 1, self.num_heads // self.n_groups, 1) + pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size + + D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size) + + # Discretize x and A + hidden_states = hidden_states * dt[..., None] + A = A.to(hidden_states.dtype) * dt + + # Rearrange into blocks/chunks + hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)] + + # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size] + A = A.permute(0, 3, 1, 2) + A_cumsum = torch.cumsum(A, dim=-1) + + # 1. Compute the output for each intra-chunk (diagonal blocks) + # This is the analog of a causal mask + L = torch.exp(segment_sum(A)) + + # Contraction of C and B to get G (attention-weights like) + # shape: (b, c, l, s, h, n) + G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] + G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h) + + # Compute M, equivalent to applying attention mask to weights + M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None] + M = M_intermediate.sum(dim=-1) + + # Compute Y_diag (apply to values) + Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3) + + # 2. Compute the state for each intra-chunk + # (right term of low-rank factorization of off-diagonal blocks; B terms) + decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum)) + B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None] + states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2) + + # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries + # (middle term of factorization of off-diag blocks; A terms) + if cache_params is not None and cache_position is not None and cache_position[0] > 0: + previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device) + else: + previous_states = torch.zeros_like(states[:, :1]) + states = torch.cat([previous_states, states], dim=1) + decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0)))) + decay_chunk = decay_chunk.transpose(1, 3) + new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1) + states, ssm_state = new_states[:, :-1], new_states[:, -1] + + # 4. Compute state -> output conversion per chunk + # (left term of low-rank factorization of off-diagonal blocks; C terms) + state_decay_out = torch.exp(A_cumsum) + C_times_states = (C[..., None, :] * states[:, :, None, ...]) + state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1) + Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None]) + + # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks) + y = Y_diag + Y_off + # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim] + y = y.reshape(batch_size, -1, self.num_heads, self.head_dim) + + y = y + D_residual + # Cutting off padded chunks + if pad_size > 0: + y = y[:, :seq_len, :, :] + y = y.reshape(batch_size, seq_len, -1) + + # Init cache + if ssm_state is not None and cache_params is not None: + cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state) + + scan_output = self.norm(y, gate) + + # end ssd naive + + # 4. Final linear projection + contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size] + return contextualized_states + # fmt: on + + def forward( + self, + hidden_states, + cache_params: Optional[Mamba2Cache] = None, + cache_position: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + ): + if is_fast_path_available and "cuda" in self.in_proj.weight.device.type: + return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask) + dtype = hidden_states.dtype + if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1: + # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66 + hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype) + + return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask) diff --git a/layers/mask_gdn.py b/layers/mask_gdn.py new file mode 100644 index 0000000000000000000000000000000000000000..46c9da8204b2489495057946c8bc5949a40dc535 --- /dev/null +++ b/layers/mask_gdn.py @@ -0,0 +1,1058 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat +from ..modules import FusedRMSNormSwishGate, RMSNorm +from fla.modules import ShortConvolution +import torch.nn.init as init +import math +from ..modules.l2norm import l2norm +from einops import rearrange +from fla.models.utils import Cache +from transformers.processing_utils import Unpack +import math +from typing import TYPE_CHECKING, Dict, Optional, Tuple +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +# from ..modules import RotaryEmbedding +# from ..ops.gla import chunk_gla,fused_recurrent_gla + + +def simple_norm(x): + return (F.normalize(x, dim=-1) * x.shape[-1] ** 0.5).to(x) + + +# @torch.jit.script +def elu_p1(x): + return (F.elu(x, 1., False) + 1.).to(x) + + +# @torch.jit.script +def sum_norm(x): + return (x / x.sum(-1, keepdim=True)).to(x) + + +# @torch.jit.script +def elu_norm(x): + dtype = x.dtype + x = F.elu(x, 1., False) + 1. + return (x / x.sum(-1, keepdim=True)).to(dtype) + + +# from ..ops.mask_gated_delta_rule import mask_gated_chunk_delta_rule +# class mask_gdn(nn.Module): +# def __init__( +# self, +# d_model: int = None, +# hidden_size: int = 1024, +# expand_k: float = 1.0, +# expand_v: float = 1.0, +# num_heads: int = 4, +# mode: str = 'chunk', +# chunk_size: int = 64, +# use_beta: bool = True, +# use_gate: bool = False, +# use_output_norm: bool = True, +# use_elu: bool = False, +# use_short_conv: bool = True, +# conv_size: int = 4, +# conv_bias: bool = False, +# layer_idx: int = None, +# qk_activation: str = 'silu', +# qk_norm: str = 'l2', +# norm_first: bool = False, +# norm_eps: float = 1e-6, +# ratio :int = 2, +# topk : int = 1 , +# **kwargs +# ) : +# super().__init__() + +# self.mode = mode +# self.qk_activation = qk_activation +# self.qk_norm = qk_norm + +# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity'] +# assert self.qk_norm in ['l2', 'sum'] + +# if d_model is not None: +# hidden_size = d_model +# self.hidden_size = hidden_size +# self.expand_k = expand_k +# self.expand_v = expand_v +# self.num_heads = num_heads +# self.chunk_size = chunk_size +# self.use_gate = use_gate +# self.use_output_norm = use_output_norm +# self.use_short_conv = use_short_conv +# self.conv_size = conv_size +# self.conv_bias = conv_bias + +# self.key_dim = int(hidden_size * expand_k) +# self.value_dim = int(hidden_size * expand_v) +# self.head_qk_dim = self.key_dim // num_heads +# self.head_v_dim = self.value_dim // num_heads +# self.norm_first = norm_first +# self.layer_idx = layer_idx +# self.top_k = topk +# self.silu = nn.SiLU() +# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`." +# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" +# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" +# if norm_first: +# self.norm = RMSNorm(self.hidden_size, eps=norm_eps) +# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) +# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) +# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) +# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False) + +# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16) +# self.A_log = nn.Parameter(torch.log(A)) +# self.A_log._no_weight_decay = True +# # hard coded for now +# dt_min = 0.001 +# dt_max = 0.1 +# dt_init_floor = 1e-4 +# dt = torch.exp( +# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min)) +# + math.log(dt_min) +# ) +# dt = torch.clamp(dt, min=dt_init_floor) +# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 +# inv_dt = dt + torch.log(-torch.expm1(-dt)) +# self.dt_bias = nn.Parameter(inv_dt) +# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check +# # name.endswith("bias") in param_grouping.py +# self.dt_bias._no_weight_decay = True + + +# self.use_beta = use_beta +# self.use_elu = use_elu +# if self.use_beta: +# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False) +# if use_short_conv: +# self.conv_size = conv_size +# self.q_conv1d = ShortConvolution(self.key_dim, +# conv_size, +# activation='silu' if qk_activation == 'silu' else None) +# self.k_conv1d = ShortConvolution(self.key_dim, +# conv_size, +# activation='silu' if qk_activation == 'silu' else None) +# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu') +# if use_gate: +# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) +# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps) +# else: +# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) +# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) +# r = self.r = 4 +# self.mask = nn.Parameter(torch.empty([r,r],dtype=self.o_proj.weight.dtype),requires_grad=True) +# self.mask_requiregrad = True +# print('mask_gdn_learn_mask_qk_r4') +# init.kaiming_uniform_(self.mask, a=math.sqrt(5)) +# assert self.head_qk_dim % r == 0 +# self.apply(self._initialize_weights) + +# def _initialize_weights(self, module: nn.Module): +# if getattr(module, "_is_hf_initialized", False): +# return +# if isinstance(module, nn.Linear): +# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5) +# if module.bias is not None: +# nn.init.zeros_(module.bias) +# module._is_hf_initialized = True + +# def delta_rule_recurrence(self,q, k, v, beta, mask,initial_state=None,output_final_state=True): +# b, h, l, d_k = q.shape +# d_v = v.shape[-1] +# r = mask.shape[-1] +# o = torch.zeros_like(v) +# if initial_state == None: +# S = torch.zeros(b, h, d_k, d_v).to(v).float() +# else: +# S = initial_state +# q = q * (d_k ** -0.5) +# if beta.ndim < v.ndim: +# beta = beta[..., None] +# if self.training: +# for i in range(l): +# _k = k[:, :, i] +# _q = q[:, :, i] +# _v = v[:, :, i].clone() +# beta_i = beta[:, :, i] +# _v = _v * beta_i +# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k) +# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r) +# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt)) +# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)') +# iplr = torch.eye(d_k).to(q)-kkt +# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2) +# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S) +# return o,S +# else: +# for i in range(l): +# _k = k[:, :, i] +# _q = q[:, :, i] +# _v = v[:, :, i] +# beta_i = beta[:, :, i] +# _v = _v * beta_i +# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k) +# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r) +# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt)) +# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)') +# iplr = torch.eye(d_k).to(q)-kkt +# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr.float(),S) + _k.unsqueeze(-1).float() * _v.unsqueeze(-2).float() +# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype) +# return o,S + + +# def forward( +# self, +# hidden_states: torch.Tensor, +# attention_mask: Optional[torch.Tensor] = None, +# past_key_values: Optional[Cache] = None, +# use_cache: Optional[bool] = False, +# output_attentions: Optional[bool] = False, +# **kwargs +# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: +# # change to inference mode. +# mode = 'chunk'#'recurrent' if hidden_states.shape[1] < 64 else self.mode +# b,q_len,d = hidden_states.shape +# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states) +# if self.norm_first: +# hidden_states = self.norm(hidden_states) + +# cu_seqlens = kwargs.get('cu_seqlens', None) +# # if attention_mask is not None: +# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) +# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) +# last_state = None +# if past_key_values is not None and len(past_key_values) > self.layer_idx: +# last_state = past_key_values[self.layer_idx] +# offset = past_key_values.get_seq_length() +# # if attention_mask is not None: +# # if attention_mask.shape[-1] != hidden_states.shape[-2]: +# # attention_mask = attention_mask[:, -1:] +# if self.use_short_conv: +# conv_state_q , conv_state_k , conv_state_v = None,None,None +# if last_state is not None: +# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state'] +# q = self.q_proj(hidden_states) +# k = self.k_proj(hidden_states) +# v = self.v_proj(hidden_states) +# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# else: +# q = self.q_proj(hidden_states) +# k = self.k_proj(hidden_states) +# v = self.v_proj(hidden_states) +# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v)) +# if self.qk_activation != 'silu': +# if self.qk_activation == 'relu': +# q, k = q.relu(), k.relu() +# elif self.qk_activation == 'elu': +# q, k = elu_p1(q), elu_p1(k) +# elif self.qk_activation == 'identity': +# pass +# else: +# raise NotImplementedError +# if self.qk_norm is not None: +# if self.qk_norm == 'l2': +# q = l2_norm_fn(q) +# k = l2_norm_fn(k) +# elif self.qk_norm == 'sum': +# q = sum_norm(q).to(v) +# k = sum_norm(k).to(v) +# recurrent_state = None +# if last_state is not None: +# recurrent_state = last_state['recurrent_state'] + +# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid() +# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l') + +# amask = torch.softmax(self.mask,dim=-1)#未必需要r r-1#适配2*2 4*4 +# r = self.r +# target_matrix = torch.zeros(r, r, dtype=amask.dtype, device=k.device) +# mask = torch.ones(r,r, dtype=torch.bool, device=amask.device) +# target_matrix[mask] = amask.flatten() + +# eye_mask = torch.eye(r, dtype=torch.bool, device=amask.device) +# target_matrix[eye_mask] = 1.0 + +# o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,BT=32,output_final_state=True) +# o = rearrange(o,'b h l d-> b l h d') +# if past_key_values is not None: +# past_key_values.update( +# recurrent_state=(recurrent_state), +# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None, +# layer_idx=self.layer_idx, +# offset=q_len +# ) +# if self.use_gate: +# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads) +# o = self.o_norm(o, g) +# else: +# o = self.o_norm(o) +# o = rearrange(o, 'b l h d -> b l (h d)') +# o = self.o_proj(o) +# return o, None, past_key_values,None + + +# from ..ops.mask_gated_delta_rule import mask_gated_chunk_delta_rule +# class mask_gdn(nn.Module): +# def __init__( +# self, +# d_model: int = None, +# hidden_size: int = 1024, +# expand_k: float = 1.0, +# expand_v: float = 1.0, +# num_heads: int = 4, +# mode: str = 'chunk', +# chunk_size: int = 64, +# use_beta: bool = True, +# use_gate: bool = False, +# use_output_norm: bool = True, +# use_elu: bool = False, +# use_short_conv: bool = True, +# conv_size: int = 4, +# conv_bias: bool = False, +# layer_idx: int = None, +# qk_activation: str = 'silu', +# qk_norm: str = 'l2', +# norm_first: bool = False, +# norm_eps: float = 1e-6, +# ratio :int = 2, +# topk : int = 1 , +# **kwargs +# ) : +# super().__init__() + +# self.mode = mode +# self.qk_activation = qk_activation +# self.qk_norm = qk_norm + +# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity'] +# assert self.qk_norm in ['l2', 'sum'] + +# if d_model is not None: +# hidden_size = d_model +# self.hidden_size = hidden_size +# self.expand_k = expand_k +# self.expand_v = expand_v +# self.num_heads = num_heads +# self.chunk_size = chunk_size +# self.use_gate = use_gate +# self.use_output_norm = use_output_norm +# self.use_short_conv = use_short_conv +# self.conv_size = conv_size +# self.conv_bias = conv_bias + +# self.key_dim = int(hidden_size * expand_k) +# self.value_dim = int(hidden_size * expand_v) +# self.head_qk_dim = self.key_dim // num_heads +# self.head_v_dim = self.value_dim // num_heads +# self.norm_first = norm_first +# self.layer_idx = layer_idx +# self.top_k = topk +# self.silu = nn.SiLU() +# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`." +# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" +# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" +# if norm_first: +# self.norm = RMSNorm(self.hidden_size, eps=norm_eps) +# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) +# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) +# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) +# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False) + +# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16) +# self.A_log = nn.Parameter(torch.log(A)) +# self.A_log._no_weight_decay = True +# # hard coded for now +# dt_min = 0.001 +# dt_max = 0.1 +# dt_init_floor = 1e-4 +# dt = torch.exp( +# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min)) +# + math.log(dt_min) +# ) +# dt = torch.clamp(dt, min=dt_init_floor) +# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 +# inv_dt = dt + torch.log(-torch.expm1(-dt)) +# self.dt_bias = nn.Parameter(inv_dt) +# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check +# # name.endswith("bias") in param_grouping.py +# self.dt_bias._no_weight_decay = True + + +# self.use_beta = use_beta +# self.use_elu = use_elu +# if self.use_beta: +# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False) +# if use_short_conv: +# self.conv_size = conv_size +# self.q_conv1d = ShortConvolution(self.key_dim, +# conv_size, +# activation='silu' if qk_activation == 'silu' else None) +# self.k_conv1d = ShortConvolution(self.key_dim, +# conv_size, +# activation='silu' if qk_activation == 'silu' else None) +# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu') +# if use_gate: +# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) +# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps) +# else: +# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) +# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) +# r = self.r = 2 +# self.mask = nn.Parameter(torch.empty([r,r],dtype=self.o_proj.weight.dtype),requires_grad=True) +# self.mask_requiregrad = True +# print('mask_gdn_learn_mask_qk_r2') +# init.kaiming_uniform_(self.mask, a=math.sqrt(5)) +# assert self.head_qk_dim % r == 0 +# self.apply(self._initialize_weights) + +# def _initialize_weights(self, module: nn.Module): +# if getattr(module, "_is_hf_initialized", False): +# return +# if isinstance(module, nn.Linear): +# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5) +# if module.bias is not None: +# nn.init.zeros_(module.bias) +# module._is_hf_initialized = True + +# def delta_rule_recurrence(self,q, k, v, beta, mask,initial_state=None,output_final_state=True): +# b, h, l, d_k = q.shape +# d_v = v.shape[-1] +# r = mask.shape[-1] +# o = torch.zeros_like(v) +# if initial_state == None: +# S = torch.zeros(b, h, d_k, d_v).to(v).float() +# else: +# S = initial_state +# q = q * (d_k ** -0.5) +# if beta.ndim < v.ndim: +# beta = beta[..., None] +# if self.training: +# for i in range(l): +# _k = k[:, :, i] +# _q = q[:, :, i] +# _v = v[:, :, i].clone() +# beta_i = beta[:, :, i] +# _v = _v * beta_i +# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k) +# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r) +# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt)) +# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)') +# iplr = torch.eye(d_k).to(q)-kkt +# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2) +# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S) +# return o,S +# else: +# for i in range(l): +# _k = k[:, :, i] +# _q = q[:, :, i] +# _v = v[:, :, i] +# beta_i = beta[:, :, i] +# _v = _v * beta_i +# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k) +# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r) +# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt)) +# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)') +# iplr = torch.eye(d_k).to(q)-kkt +# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr.float(),S) + _k.unsqueeze(-1).float() * _v.unsqueeze(-2).float() +# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype) +# return o,S + + +# def forward( +# self, +# hidden_states: torch.Tensor, +# attention_mask: Optional[torch.Tensor] = None, +# past_key_values: Optional[Cache] = None, +# use_cache: Optional[bool] = False, +# output_attentions: Optional[bool] = False, +# **kwargs +# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: +# # change to inference mode. +# mode = 'chunk'#'recurrent' if hidden_states.shape[1] < 64 else self.mode +# b,q_len,d = hidden_states.shape +# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states) +# if self.norm_first: +# hidden_states = self.norm(hidden_states) + +# cu_seqlens = kwargs.get('cu_seqlens', None) +# # if attention_mask is not None: +# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) +# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) +# last_state = None +# if past_key_values is not None and len(past_key_values) > self.layer_idx: +# last_state = past_key_values[self.layer_idx] +# offset = past_key_values.get_seq_length() +# # if attention_mask is not None: +# # if attention_mask.shape[-1] != hidden_states.shape[-2]: +# # attention_mask = attention_mask[:, -1:] +# if self.use_short_conv: +# conv_state_q , conv_state_k , conv_state_v = None,None,None +# if last_state is not None: +# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state'] +# q = self.q_proj(hidden_states) +# k = self.k_proj(hidden_states) +# v = self.v_proj(hidden_states) +# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# else: +# q = self.q_proj(hidden_states) +# k = self.k_proj(hidden_states) +# v = self.v_proj(hidden_states) +# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v)) +# if self.qk_activation != 'silu': +# if self.qk_activation == 'relu': +# q, k = q.relu(), k.relu() +# elif self.qk_activation == 'elu': +# q, k = elu_p1(q), elu_p1(k) +# elif self.qk_activation == 'identity': +# pass +# else: +# raise NotImplementedError +# if self.qk_norm is not None: +# if self.qk_norm == 'l2': +# q = l2_norm_fn(q) +# k = l2_norm_fn(k) +# elif self.qk_norm == 'sum': +# q = sum_norm(q).to(v) +# k = sum_norm(k).to(v) +# recurrent_state = None +# if last_state is not None: +# recurrent_state = last_state['recurrent_state'] + +# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid() +# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l') + +# amask = torch.softmax(self.mask,dim=-1)#未必需要r r-1#适配2*2 4*4 +# r = self.r +# target_matrix = torch.zeros(r, r, dtype=amask.dtype, device=k.device) +# mask = torch.ones(r,r, dtype=torch.bool, device=amask.device) +# target_matrix[mask] = amask.flatten() + +# eye_mask = torch.eye(r, dtype=torch.bool, device=amask.device) +# target_matrix[eye_mask] = 1.0 + +# o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,BT=32,output_final_state=True) +# o = rearrange(o,'b h l d-> b l h d') +# if past_key_values is not None: +# past_key_values.update( +# recurrent_state=(recurrent_state), +# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None, +# layer_idx=self.layer_idx, +# offset=q_len +# ) +# if self.use_gate: +# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads) +# o = self.o_norm(o, g) +# else: +# o = self.o_norm(o) +# o = rearrange(o, 'b l h d -> b l (h d)') +# o = self.o_proj(o) +# return o, None, past_key_values,None + +# from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule +from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule,mask_fused_recurrent_gated_delta_rule +class mask_gdn(nn.Module): + def __init__( + self, + d_model: int = None, + hidden_size: int = 1024, + expand_k: float = 1.0, + expand_v: float = 1.0, + num_heads: int = 4, + mode: str = 'chunk', + chunk_size: int = 64, + use_beta: bool = True, + use_gate: bool = False, + use_output_norm: bool = True, + use_elu: bool = False, + use_short_conv: bool = True, + conv_size: int = 4, + conv_bias: bool = False, + layer_idx: int = None, + qk_activation: str = 'silu', + qk_norm: str = 'l2', + norm_first: bool = False, + norm_eps: float = 1e-6, + ratio :int = 4, + topk : int = 1, + **kwargs + ) : + super().__init__() + + self.mode = mode + self.qk_activation = qk_activation + self.qk_norm = qk_norm + + assert self.qk_activation in ['silu', 'relu', 'elu', 'identity'] + assert self.qk_norm in ['l2', 'sum'] + + if d_model is not None: + hidden_size = d_model + self.hidden_size = hidden_size + self.expand_k = expand_k + self.expand_v = expand_v + self.num_heads = num_heads + self.chunk_size = chunk_size + self.use_gate = use_gate + self.use_output_norm = use_output_norm + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.key_dim = int(hidden_size * expand_k) + self.value_dim = int(hidden_size * expand_v) + self.head_qk_dim = self.key_dim // num_heads + self.head_v_dim = self.value_dim // num_heads + self.norm_first = norm_first + self.layer_idx = layer_idx + self.top_k = topk + self.silu = nn.SiLU() + assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`." + assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" + assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" + if norm_first: + self.norm = RMSNorm(self.hidden_size, eps=norm_eps) + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False) + + A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + # hard coded for now + dt_min = 0.001 + dt_max = 0.1 + dt_init_floor = 1e-4 + dt = torch.exp( + torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min)) + + math.log(dt_min) + ) + dt = torch.clamp(dt, min=dt_init_floor) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + self.dt_bias = nn.Parameter(inv_dt) + # Just to be explicit. Without this we already don't put wd on dt_bias because of the check + # name.endswith("bias") in param_grouping.py + self.dt_bias._no_weight_decay = True + + + self.use_beta = use_beta + self.use_elu = use_elu + if self.use_beta: + self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False) + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution(self.key_dim, + conv_size, + activation='silu' if qk_activation == 'silu' else None) + self.k_conv1d = ShortConvolution(self.key_dim, + conv_size, + activation='silu' if qk_activation == 'silu' else None) + self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu') + if use_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + r = self.r = ratio + self.mask = nn.Linear(hidden_size, (self.num_heads*r*r), bias=False) #nn.Parameter(torch.empty([r,r-1],dtype=self.o_proj.weight.dtype),requires_grad=True) + self.mask_requiregrad = True + print('mask_gdn_learn_mask_by_t_fla4____'+str(self.r)) + assert self.head_qk_dim % r == 0 + self.apply(self._initialize_weights) + + def _initialize_weights(self, module: nn.Module): + if getattr(module, "_is_hf_initialized", False): + return + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5) + if module.bias is not None: + nn.init.zeros_(module.bias) + module._is_hf_initialized = True + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + # change to inference mode. + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + batch_size, q_len, _ = hidden_states.shape + # change to inference mode. + mode = 'fused_recurrent' if q_len <= 64 else self.mode + if self.training: + assert mode == 'chunk', "Only chunk mode is supported in training." + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q , conv_state_k , conv_state_v = None,None,None + if last_state is not None: + conv_state_q , conv_state_k , conv_state_v = last_state['conv_state'] + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens) + k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens) + v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens) + else: + q = F.silu(self.q_proj(hidden_states)) + k = F.silu(self.k_proj(hidden_states)) + v = F.silu(self.v_proj(hidden_states)) + + q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k)) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + + # if self.num_v_heads > self.num_heads: + # q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k)) + + beta = self.b_proj(hidden_states).sigmoid() + # if self.allow_neg_eigval: + # beta = beta * 2. + + + q = l2norm(q) + k = l2norm(k) + recurrent_state = None + if last_state is not None: + recurrent_state = last_state['recurrent_state'] + g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias) + r = self.r + target_matrix = self.mask(hidden_states).abs() + target_matrix = rearrange(target_matrix,'b l (h r c)->b l h r c',r=r,h=self.num_heads)#bhlrr + target_matrix = l2norm(target_matrix) + target_matrix = target_matrix@target_matrix.transpose(-1,-2) + # target_matrix = self.mask.abs() + # target_matrix = l2_norm_fn(target_matrix) + # target_matrix = target_matrix@target_matrix.transpose(-1,-2) + # target_matrix = target_matrix.unsqueeze(1).unsqueeze(0).expand(batch,self.num_heads,q_len,self.r,self.r) + if mode == 'recurrent': + o,recurrent_state_sf = mask_fused_recurrent_gated_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state_sf,output_final_state=True) + else: + if r==8: + BT = 16 + else: + BT = 32 + o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(), + v.contiguous(), + beta.contiguous(), + g.contiguous(), + target_matrix.contiguous(), + BT = BT, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=False) + if past_key_values is not None: + past_key_values.update( + recurrent_state=(recurrent_state), + conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + if self.use_gate: + g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads) + o = self.o_norm(o, g) + else: + o = self.o_norm(o) + o = rearrange(o, 'b l h d -> b l (h d)') + # print(o.shape) + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + return o, None, past_key_values,None + + + + +# from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule +# class mask_gdn(nn.Module): +# def __init__( +# self, +# d_model: int = None, +# hidden_size: int = 1024, +# expand_k: float = 1.0, +# expand_v: float = 1.0, +# num_heads: int = 4, +# mode: str = 'chunk', +# chunk_size: int = 64, +# use_beta: bool = True, +# use_gate: bool = False, +# use_output_norm: bool = True, +# use_elu: bool = False, +# use_short_conv: bool = True, +# conv_size: int = 4, +# conv_bias: bool = False, +# layer_idx: int = None, +# qk_activation: str = 'silu', +# qk_norm: str = 'l2', +# norm_first: bool = False, +# norm_eps: float = 1e-6, +# ratio :int = 2, +# topk : int = 1 , +# **kwargs +# ) : +# super().__init__() + +# self.mode = mode +# self.qk_activation = qk_activation +# self.qk_norm = qk_norm + +# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity'] +# assert self.qk_norm in ['l2', 'sum'] + +# if d_model is not None: +# hidden_size = d_model +# self.hidden_size = hidden_size +# self.expand_k = expand_k +# self.expand_v = expand_v +# self.num_heads = num_heads +# self.chunk_size = chunk_size +# self.use_gate = use_gate +# self.use_output_norm = use_output_norm +# self.use_short_conv = use_short_conv +# self.conv_size = conv_size +# self.conv_bias = conv_bias + +# self.key_dim = int(hidden_size * expand_k) +# self.value_dim = int(hidden_size * expand_v) +# self.head_qk_dim = self.key_dim // num_heads +# self.head_v_dim = self.value_dim // num_heads +# self.norm_first = norm_first +# self.layer_idx = layer_idx +# self.top_k = topk +# self.silu = nn.SiLU() +# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`." +# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" +# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" +# if norm_first: +# self.norm = RMSNorm(self.hidden_size, eps=norm_eps) +# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) +# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) +# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) +# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False) + +# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16) +# self.A_log = nn.Parameter(torch.log(A)) +# self.A_log._no_weight_decay = True +# # hard coded for now +# dt_min = 0.001 +# dt_max = 0.1 +# dt_init_floor = 1e-4 +# dt = torch.exp( +# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min)) +# + math.log(dt_min) +# ) +# dt = torch.clamp(dt, min=dt_init_floor) +# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 +# inv_dt = dt + torch.log(-torch.expm1(-dt)) +# self.dt_bias = nn.Parameter(inv_dt) +# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check +# # name.endswith("bias") in param_grouping.py +# self.dt_bias._no_weight_decay = True + + +# self.use_beta = use_beta +# self.use_elu = use_elu +# if self.use_beta: +# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False) +# if use_short_conv: +# self.conv_size = conv_size +# self.q_conv1d = ShortConvolution(self.key_dim, +# conv_size, +# activation='silu' if qk_activation == 'silu' else None) +# self.k_conv1d = ShortConvolution(self.key_dim, +# conv_size, +# activation='silu' if qk_activation == 'silu' else None) +# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu') +# if use_gate: +# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) +# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps) +# else: +# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) +# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) +# r = self.r = 4 +# self.mask = nn.Parameter(torch.empty([self.num_heads,r,r],dtype=self.o_proj.weight.dtype),requires_grad=True) +# self.mask_requiregrad = True + +# print('mask_gdn_learn_mask_r4_hrr') +# init.kaiming_uniform_(self.mask, a=math.sqrt(5)) +# assert self.head_qk_dim % r == 0 +# self.apply(self._initialize_weights) + +# def _initialize_weights(self, module: nn.Module): +# if getattr(module, "_is_hf_initialized", False): +# return +# if isinstance(module, nn.Linear): +# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5) +# if module.bias is not None: +# nn.init.zeros_(module.bias) +# module._is_hf_initialized = True + +# def delta_rule_recurrence(self,q, k, v, beta, g, mask,initial_state=None,output_final_state=True): +# b, h, l, d_k = q.shape +# d_v = v.shape[-1] +# r = mask.shape[-1] +# o = torch.zeros_like(v) +# if initial_state == None: +# S = torch.zeros(b, h, d_k, d_v,device=k.device,dtype=torch.float32) +# else: +# S = initial_state +# q = q * (d_k ** -0.5) +# if beta.ndim < v.ndim: +# beta = beta[..., None] +# g = torch.exp(g) +# if self.training: +# for i in range(l): +# _k = k[:, :, i] +# _q = q[:, :, i] +# _v = v[:, :, i].clone() +# beta_i = beta[:, :, i] +# _v = _v * beta_i +# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k) +# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r) +# kkt = torch.einsum('b h r d l v,b h r l->b h r d l v',kkt,mask[:,:,i,:,:].to(kkt)) +# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)') +# iplr = torch.eye(d_k).to(q)-kkt +# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2) +# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S) +# return o,S +# else: +# for i in range(l): +# _k = k[:, :, i] +# _q = q[:, :, i] +# _v = v[:, :, i] +# beta_i = beta[:, :, i] +# _v = _v * beta_i +# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k) +# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r) +# kkt = torch.einsum('b h r d l v,b h r l->b h r d l v',kkt,mask[:,:,i,:,:].to(kkt)) +# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)') +# iplr = torch.eye(d_k).to(q)-kkt +# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr.float(),S) + _k.unsqueeze(-1).float() * _v.unsqueeze(-2).float() +# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype) +# return o,S + +# def forward( +# self, +# hidden_states: torch.Tensor, +# attention_mask: Optional[torch.Tensor] = None, +# past_key_values: Optional[Cache] = None, +# use_cache: Optional[bool] = False, +# output_attentions: Optional[bool] = False, +# **kwargs +# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: +# # change to inference mode. +# mode = 'recurrent' if hidden_states.shape[1] < 32 else self.mode +# batch,q_len,d = hidden_states.shape +# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states) +# if self.norm_first: +# hidden_states = self.norm(hidden_states) + +# cu_seqlens = kwargs.get('cu_seqlens', None) +# # if attention_mask is not None: +# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) +# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) +# last_state = None +# if past_key_values is not None and len(past_key_values) > self.layer_idx: +# last_state = past_key_values[self.layer_idx] +# offset = past_key_values.get_seq_length() +# # if attention_mask is not None: +# # if attention_mask.shape[-1] != hidden_states.shape[-2]: +# # attention_mask = attention_mask[:, -1:] +# if self.use_short_conv: +# conv_state_q , conv_state_k , conv_state_v = None,None,None +# if last_state is not None: +# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state'] +# q = self.q_proj(hidden_states) +# k = self.k_proj(hidden_states) +# v = self.v_proj(hidden_states) +# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens) +# else: +# q = self.q_proj(hidden_states) +# k = self.k_proj(hidden_states) +# v = self.v_proj(hidden_states) +# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v)) +# if self.qk_activation != 'silu': +# if self.qk_activation == 'relu': +# q, k = q.relu(), k.relu() +# elif self.qk_activation == 'elu': +# q, k = elu_p1(q), elu_p1(k) +# elif self.qk_activation == 'identity': +# pass +# else: +# raise NotImplementedError +# if self.qk_norm is not None: +# if self.qk_norm == 'l2': +# q = l2_norm_fn(q) +# k = l2_norm_fn(k) +# elif self.qk_norm == 'sum': +# q = sum_norm(q).to(v) +# k = sum_norm(k).to(v) +# recurrent_state = None +# if last_state is not None: +# recurrent_state = last_state['recurrent_state'] + +# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid() +# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l') + +# r = self.r +# target_matrix = self.mask#hrr +# target_matrix = torch.softmax(target_matrix,dim=-1)#h r c +# eye_mask = torch.eye(r, dtype=torch.bool, device=target_matrix.device).unsqueeze(0) +# target_matrix = torch.where(eye_mask, torch.tensor(1.0, device=target_matrix.device), target_matrix) +# target_matrix = target_matrix.unsqueeze(1).unsqueeze(0).expand(batch,self.num_heads,q_len,self.r,self.r) + +# if mode == 'recurrent': +# o,recurrent_state = self.delta_rule_recurrence(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,output_final_state=True) +# else: +# o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,BT=32,output_final_state=True) +# o = rearrange(o,'b h l d-> b l h d') +# if past_key_values is not None: +# past_key_values.update( +# recurrent_state=(recurrent_state), +# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None, +# layer_idx=self.layer_idx, +# offset=q_len +# ) +# if self.use_gate: +# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads) +# o = self.o_norm(o, g) +# else: +# o = self.o_norm(o) +# o = rearrange(o, 'b l h d -> b l (h d)') +# o = self.o_proj(o) + # return o, None, past_key_values,None diff --git a/layers/mesa_net.py b/layers/mesa_net.py new file mode 100644 index 0000000000000000000000000000000000000000..c8813aeaec57b9b51cac090f3bb8a4db9590161d --- /dev/null +++ b/layers/mesa_net.py @@ -0,0 +1,224 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from torch.nn import functional as F + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.modules.l2norm import l2_norm +from fla.ops.mesa_net import chunk_mesa_net, mesa_net_decoding_one_step + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class MesaNet(nn.Module): + """ + The layer implementaion for [MesaNet: Sequence Modeling by Locally Optimal Test-Time Training]. # noqa + + Args: + hidden_size (int, Optional): + The hidden size of the input. Default: 2048. + expand_v (float, Optional): + The expansion ratio for the value dim. Default: 1. + num_heads (int, Optional): + The number of heads. Default: 16. + mode (str, Optional): + Which MesaNet kernel to use. + Currently available: `chunk`. + Default: `chunk`. + use_output_gate (bool, Optional): + Whether to use output gate. Default: `False`. + conv_size (int): + The kernel size of the short convolution. Default: 4. + layer_idx (int, Optional): + The index of the layer. Default: None. + norm_eps (float, Optional): + The epsilon value for the normalization layer. Default: 1e-5. + lambda_lower_bound (float): + The lower bound for the lambda parameter. Default: 0.25. + max_cg_step_training (int): + The maximum number of CG steps for training. Default: 30. + max_cg_step_decoding (int): + The maximum number of CG steps for decoding. Default: 30. + """ + + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 16, + head_dim: int = 128, + mode: str = 'chunk', + use_output_gate: bool = False, + use_short_conv: bool = True, + conv_size: int = 4, + conv_bias: bool = False, + layer_idx: int = None, + norm_eps: float = 1e-5, + lambda_lower_bound: float = 0.25, + max_cg_step_training: int = 30, + max_cg_step_decoding: int = 30, + **kwargs + ) -> MesaNet: + super().__init__() + + self.mode = mode + self.hidden_size = hidden_size + self.use_output_gate = use_output_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + self.num_heads = num_heads + self.head_dim = head_dim + self.key_dim = self.num_heads * self.head_dim + self.value_dim = self.key_dim + self.head_k_dim = self.head_dim + self.head_v_dim = self.head_dim + self.layer_idx = layer_idx + self.lambda_lower_bound = lambda_lower_bound + self.max_cg_step_training = max_cg_step_training + self.max_cg_step_decoding = max_cg_step_decoding + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=True) + self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=True) + + lambda_initial_value = 1.0 + init_lamb_value = torch.log(torch.exp(torch.tensor(lambda_initial_value - lambda_lower_bound)) - 1.0) + init_lamb_params = torch.empty(self.key_dim, dtype=torch.float32).fill_(init_lamb_value) + + self.lambda_params = nn.Parameter(init_lamb_params) + self.lambda_params._no_weight_decay = True + + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=self.conv_bias, + activation='silu', + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=self.conv_bias, + activation='silu', + ) + if use_output_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + conv_state_q, conv_state_k = None, None + if last_state is not None: + conv_state_q, conv_state_k = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v = self.v_proj(hidden_states) + + q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k)) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + beta = self.b_proj(hidden_states).float().sigmoid() + g = F.logsigmoid(self.a_proj(hidden_states).float()) + lamb = F.softplus(self.lambda_params.float()) + self.lambda_lower_bound + lamb = lamb.reshape(self.num_heads, -1) + + last_h_kk, last_h_kv = last_state['recurrent_state'] if last_state is not None else (None, None) + + # prefilling or training + # Note that QK will be normalized inside the kernel to avoid saving the activations, thereby reducing the memory usage. + if last_state is None: + o, h_kk, h_kv = chunk_mesa_net( + q=q, + k=k, + v=v, + g=g, + beta=beta, + lamb=lamb, + output_final_state=use_cache, + max_CG_iteration=self.max_cg_step_training, + use_qk_l2norm_in_kernel=True, + cu_seqlens=cu_seqlens, + ) + # decoding + else: + q = l2_norm(q) + k = l2_norm(k) + o, h_kk, h_kv = mesa_net_decoding_one_step( + q=q.squeeze(0), + k=k.squeeze(0), + v=v.squeeze(0), + g=g.squeeze(0), + beta=beta.squeeze(0), + lamb=lamb, + prev_h_kk=last_h_kk, + prev_h_kv=last_h_kv, + max_CG_iteration=self.max_cg_step_decoding + ) + o = o.unsqueeze(0).to(q) + + if past_key_values is not None: + past_key_values.update( + recurrent_state=(h_kk, h_kv), + conv_state=(conv_state_q, conv_state_k), + layer_idx=self.layer_idx, + offset=q_len + ) + if self.use_output_gate: + g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim) + o = self.o_norm(o, g) + else: + o = self.o_norm(o) + o = rearrange(o, 'b t h d -> b t (h d)') + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + return o, None, past_key_values diff --git a/layers/mla.py b/layers/mla.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae33286bcc7a8293f10bc8f6389b9bc4a97cb1b --- /dev/null +++ b/layers/mla.py @@ -0,0 +1,226 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +""" Implementing the Deepseek Multi Latent Attention (MLA) module. Reference: + +https://github.com/huggingface/transformers/blob/main/src/transformers/models/deepseek_v3/modeling_deepseek_v3.py#L328 +""" + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat +from transformers.utils import logging + +from fla.layers.utils import pad_input, unpad_input +from fla.modules import RMSNorm, RotaryEmbedding +from fla.ops.utils.index import prepare_lens_from_mask + +if TYPE_CHECKING: + from fla.models.utils import Cache + +try: + from flash_attn import flash_attn_func, flash_attn_varlen_func +except ImportError: + warnings.warn( + "Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`", + category=ImportWarning + ) + flash_attn_func = None + +logger = logging.get_logger(__name__) + + +def yarn_get_mscale(scale=1, mscale=1): + if scale <= 1: + return 1.0 + return 0.1 * mscale * math.log(scale) + 1.0 + + +class MultiheadLatentAttention(nn.Module): + r""" + Multi-headed attention from [Deepseek V2](https://arxiv.org/abs/2405.04434) + """ + + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 16, + q_lora_rank: Optional[int] = 1536, # q lora rank is optional, None indicates no q lora + qk_rope_head_dim: int = 64, + kv_lora_rank: int = 512, # following the original Deepseek paper + v_head_dim: int = 128, + qk_nope_head_dim: int = 128, + qk_head_dim: Optional[int] = 192, # qk_nope_head_dim + qk_rope_head_dim + window_size: Optional[int] = None, + rope_theta: float = 10000., + max_position_embeddings: Optional[int] = None, + rope_scaling: Optional[dict] = None, + layer_idx: int = None + ) -> MultiheadLatentAttention: + super().__init__() + + # sanity check + if qk_head_dim is not None: + assert qk_head_dim == qk_nope_head_dim + qk_rope_head_dim, \ + f"qk_head_dim {qk_head_dim} != qk_nope_head_dim {qk_nope_head_dim} + qk_rope_head_dim {qk_rope_head_dim}" + else: + qk_head_dim = qk_nope_head_dim + qk_rope_head_dim + + # attention params info + self.hidden_size = hidden_size + self.num_heads = num_heads + self.q_lora_rank = q_lora_rank + self.qk_rope_head_dim = qk_rope_head_dim + self.kv_lora_rank = kv_lora_rank + self.v_head_dim = v_head_dim + self.qk_nope_head_dim = qk_nope_head_dim + self.qk_head_dim = qk_head_dim + + self.window_size = window_size + self.rope_theta = rope_theta + self.max_position_embeddings = max_position_embeddings + self.layer_idx = layer_idx + + if flash_attn_func is None: + raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first") + + if q_lora_rank is not None: + self.q_proj = nn.Sequential( + nn.Linear(hidden_size, q_lora_rank, bias=False), + RMSNorm(q_lora_rank), + nn.Linear(q_lora_rank, self.num_heads * self.qk_head_dim, bias=False) + ) + else: + self.q_proj = nn.Linear(hidden_size, self.num_heads * self.qk_head_dim, bias=False) + + self.k_rope = nn.Linear(hidden_size, self.qk_rope_head_dim, bias=False) + self.kv_proj = nn.Sequential( + nn.Linear(hidden_size, self.kv_lora_rank, bias=False), + RMSNorm(self.kv_lora_rank), + 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, hidden_size, bias=False) + + self.scaling = self.qk_head_dim ** (-0.5) + if rope_scaling is not None: + mscale_all_dim = rope_scaling.get("mscale_all_dim", 0) + scaling_factor = rope_scaling["factor"] + if mscale_all_dim: + mscale = yarn_get_mscale(scaling_factor, mscale_all_dim) + self.scaling = self.scaling * mscale * mscale + + self.rotary = RotaryEmbedding(dim=self.qk_rope_head_dim, base=self.rope_theta) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor], + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + # if attention_mask is not None, this is doing inference + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + # prepare q, k, v + batch_size, q_len, _ = hidden_states.shape + + q_states = self.q_proj(hidden_states) + q_states = rearrange(q_states, '... (h d) -> ... h d', d=self.qk_head_dim) + q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1) + k_pass, k_rot = self.kv_proj(hidden_states), self.k_rope(hidden_states) + + k_rot = rearrange(k_rot, 'b t d -> b t 1 d') + k_pass = rearrange(k_pass, '... (h d) -> ... h d', d=self.qk_nope_head_dim + self.v_head_dim) + k_pass, v = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1) + + # apply rotary position embedding + seqlen_offset, max_seqlen = 0, q_len + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + max_seqlen = q_len + seqlen_offset + + if attention_mask is not None: + seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1] + max_seqlen = q_len + max(seqlen_offset) + + if self.max_position_embeddings is not None: + max_seqlen = max(max_seqlen, self.max_position_embeddings) + cu_seqlens = kwargs.get("cu_seqlens", None) + q_rot, k_rot = self.rotary( + q_rot, k_rot, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens + ) + + k_rot = repeat(k_rot, 'b t 1 d -> b t h d', h=self.num_heads) + q = torch.cat((q_pass, q_rot), dim=-1) + k = torch.cat((k_pass, k_rot), dim=-1) + + # TODO: instead of caching the full k, v, we can actually only cache the compressed_kv and k_rot + # and recover the full k, v from compressed_kv and k_rot + if past_key_values is not None: + cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0 + k_cached, v_cached = past_key_values.update( + attn_state=(k, v), + layer_idx=self.layer_idx, + offset=q_len, + )['attn_state'] + if cache_has_content: + k, v = k_cached, v_cached + + # Head dim match to use flash-attn + if self.qk_head_dim != self.v_head_dim: + v = F.pad(v, [0, self.qk_head_dim - self.v_head_dim]) + + # Contains at least one padding token in the sequence + if attention_mask is not None: + if q.shape[1] == 1 and self.window_size is not None: + attention_mask = attention_mask[:, -self.window_size:] + q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len) + cu_seqlens_q, cu_seqlens_k = cu_seqlens + max_seqlen_q, max_seqlen_k = max_seq_lens + o = flash_attn_varlen_func( + q, k, v, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + o = pad_input(o, indices_q, batch_size, q_len) + elif cu_seqlens is not None: + o = flash_attn_varlen_func( + q.squeeze(0), k.squeeze(0), v.squeeze(0), + cu_seqlens_q=cu_seqlens, + cu_seqlens_k=cu_seqlens, + max_seqlen_q=max_seqlen, + max_seqlen_k=max_seqlen, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ).unsqueeze(0) + else: + o = flash_attn_func( + q, k, v, + causal=True, + window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0) + ) + + if self.qk_head_dim != self.v_head_dim: + o = o[:, :, :, :self.v_head_dim] + o = o.reshape(batch_size, q_len, -1) + o = self.o_proj(o) + return o, None, past_key_values diff --git a/layers/mom.py b/layers/mom.py new file mode 100644 index 0000000000000000000000000000000000000000..6813bdb462cc486f7d92c3eda9f5fd75a34dd236 --- /dev/null +++ b/layers/mom.py @@ -0,0 +1,834 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import math +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange +from torch.nn import functional as F + +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input, unpad_input + + +def _upad_input( + query_layer: torch.Tensor, + key_layer: torch.Tensor, + value_layer: torch.Tensor, + gate_layer: torch.Tensor, + beta_layer: torch.Tensor, + attention_mask: torch.Tensor, +): + """ + Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to + different batches. + + This function is used instead of `flash_attn.bert_padding.unpad_input` in order to avoid the recomputation + of the same intermediary + tensors for query, key, value tensors. + + Arguments: + query_layer (`torch.Tensor`): + Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim). + key_layer (`torch.Tensor`): + Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim). + value_layer (`torch.Tensor`): + Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim). + attention_mask (`torch.Tensor`): + Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid. + query_length (`int`): + Target length. + + Return: + query_layer (`torch.Tensor`): + Query state without padding. Shape: (total_target_length, num_heads, head_dim). + key_layer (`torch.Tensor`): + Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim). + value_layer (`torch.Tensor`): + Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim). + indices_q (`torch.Tensor`): + The indices of non-masked tokens from the flattened input target sequence. + (cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`): + The cumulative sequence lengths for the target (query) and source (key, value), used to index + into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,). + (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`): + Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query, + `max_seqlen_in_batch_k` for the source sequence i.e. key/value). + """ + query_length = query_layer.shape[1] + indices_k, cu_seqlens_k, max_seqlen_in_batch_k = get_unpad_data(attention_mask) + batch_size, kv_seq_len, dim = key_layer.shape + v_dim = value_layer.shape[-1] + + key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, dim), indices_k) + value_layer = index_first_axis( + value_layer.reshape(batch_size * kv_seq_len, v_dim), indices_k + ) + gate_layer = index_first_axis(gate_layer.reshape(batch_size * kv_seq_len, -1), indices_k) + beta_layer = index_first_axis(beta_layer.reshape(batch_size * kv_seq_len, -1), indices_k) + if query_length == kv_seq_len: + query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, dim), indices_k) + cu_seqlens_q = cu_seqlens_k + max_seqlen_in_batch_q = max_seqlen_in_batch_k + indices_q = indices_k + elif query_length == 1: + max_seqlen_in_batch_q = 1 + cu_seqlens_q = torch.arange( + batch_size + 1, dtype=torch.int32, device=query_layer.device + ) # There is a memcpy here, that is very bad. + indices_q = cu_seqlens_q[:-1] + query_layer = query_layer.squeeze(1) + else: + # The -q_len: slice assumes left padding. + attention_mask = attention_mask[:, -query_length:] + query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) + + return ( + query_layer, + key_layer, + value_layer, + gate_layer, + beta_layer, + indices_q, + (cu_seqlens_q, cu_seqlens_k), + (max_seqlen_in_batch_q, max_seqlen_in_batch_k), + ) + + +def transform( + x: torch.Tensor, + routing_mask: torch.Tensor, + num_memories: int, + selected_memories: torch.Tensor, + attention_mask: torch.Tensor, +): + """ + Reorganize token embeddings into memory-aligned chunks. + + Steps: + - Expand for top-k routing if needed. + - Mask out padded tokens via `attention_mask`. + - Sort tokens by (batch, memory). + - Gather and pad tokens per memory slot. + + Args: + x: (batch, seq, hidden) input embeddings. + routing_mask: (batch, seq, num_memories) binary routing mask. + num_memories: number of memory slots. + selected_memories: memory indices per token, + (batch, seq) if k=1 else (batch, seq, topk). + attention_mask: (batch, seq) valid-token mask. + + Returns: + transformed_x: (num_memories, batch, max_len, hidden) reorganized tokens. + truncation_indices: (batch*num_memories, max_len) gather indices. + sorted_indices: (batch*seq*topk,) global sort order. + max_len: int, max tokens per memory. + mask: (batch*num_memories, max_len) validity mask. + mask_2: (num_memories, batch, max_len) validity mask reshaped. + """ + if selected_memories.dim() == 3: + # (batch, seq, topk) + topk = selected_memories.shape[2] + # x (batch, seq, hidden) + x = x.repeat_interleave(topk, dim=1) + # x (batch, seq * topk, hidden) + # (batch, seq, topk) + selected_memories = selected_memories.reshape(selected_memories.shape[0], -1) + # (batch, seq * topk) + + if attention_mask is not None: + attention_mask = attention_mask[:, -routing_mask.shape[1]:] + # mask out the masked tokens + routing_mask[attention_mask.bitwise_not().unsqueeze(-1).expand(-1, -1, num_memories)] = 0 + + b, s, d = x.shape + x_flat = x.reshape(b * s, d) # [b*s, d] + + with torch.no_grad(): + batch_indices = torch.arange(b, device=x.device).unsqueeze(-1) + batch_indices = batch_indices.repeat(1, s).reshape(-1) + if attention_mask is not None: + # sort the masked tokens to the end + batch_indices[attention_mask.repeat_interleave(topk, dim=1).bitwise_not().flatten()] = b + # (b * s) + memories_flat = selected_memories.reshape(-1) # [b*s] + + combined = batch_indices * (memories_flat.max() + 1) + memories_flat + sorted_indices = combined.argsort() + + x_sorted = x_flat[sorted_indices] # [b*s, d] + # (b*s, hidden) -> (b, s, hidd) + with torch.no_grad(): + # routing_mask (b, s, num_memories) + batch_memory_tokens = routing_mask.sum(dim=1) + # (b, num_memories) + flatten_offset = batch_memory_tokens.flatten().cumsum(dim=0) + max_len = batch_memory_tokens.max() + indices = ( + torch.arange(max_len, device=flatten_offset.device).unsqueeze(0).expand(b * num_memories, -1) + + torch.cat([torch.tensor([0], device=flatten_offset.device), flatten_offset[:-1]], dim=0).unsqueeze(1) + ) + mask = indices < flatten_offset.unsqueeze(-1) + truncation_indices = torch.where(mask, indices, torch.zeros_like(indices)) + + gathered_x = torch.gather(x_sorted, 0, truncation_indices.reshape(-1).unsqueeze(-1).expand(-1, d)) + transformed_x = gathered_x.reshape(b * num_memories, -1, d).reshape((b, num_memories, max_len, d)).transpose(0, 1) + # transformed_x = transformed_x * mask.unsqueeze(-1).expand_as(transformed_x) + # pad_x = torch.zeros((b * num_memories, capacity_len-max_len, d), dtype=transformed_x.dtype, device=transformed_x.device) + # pad_mask = torch.zeros((b * num_memories, capacity_len-max_len), dtype=transformed_x.dtype, device=transformed_x.device) + # left pad + # transformed_x = torch.cat((pad_x, transformed_x), dim=1).reshape((b, num_memories, capacity_len, d)).transpose(0, 1) + mask_2 = mask.reshape((b, num_memories, max_len)).transpose(0, 1) + # truncation_indices += capacity_len-max_len + # if attention_mask is not None: + # mask_2 + + return transformed_x, truncation_indices, sorted_indices, max_len, mask, mask_2 + + +def reconstruct( + transformed_x, + indices: torch.Tensor, + sorted_indices: torch.Tensor, + batch_size: int, + seq_len: int, + topk: int, + routing_weights: torch.Tensor, + mask: torch.Tensor +): + ''' + Reconstruct and mix transformed outputs back into the original input sequence shape. + + Key operations: + 1. Reshapes and transposes `transformed_x` to prepare for scattering. + 2. Applies the `mask` to zero out invalid positions. + 3. Uses `torch.scatter_add_` to scatter and sum the transformed outputs back to their original positions + based on `indices`. + 4. Rearranges the scattered outputs using `sorted_indices` to ensure correct ordering. + 5. Applies the `routing_weights` to weight the outputs. + 6. Sums over the `topk` dimension to produce the final reconstructed output. + + Args: + transformed_x (torch.Tensor): + The transformed output tensor from memory units or experts. + Shape: (num_memories, batch_size, capacity_len, hidden_size) + indices (torch.Tensor): + Indices used for scattering the transformed outputs back to their corresponding positions. + Shape: (batch*num_memories, max_len) + sorted_indices (torch.Tensor): + Sorting indices used to rearrange the scattered outputs back into the original sequence order. + Shape: (batch_size*seq_len*topk) + batch_size (int): + The size of the batch. + seq_len (int): + The length of the input sequence. + topk (int): + The number of top elements selected (`topk`) per token during the selection process. + routing_weights (torch.Tensor): + Routing weights assigned to the top-k selected outputs when reconstructing the final output. + Shape: (batch_size, seq_len, topk) + mask (torch.Tensor): + Boolean mask indicating valid positions in the sequence. + Shape: (batch*num_memories, max_len) + + Returns: + restored_x (torch.Tensor): + The reconstructed output tensor in the original input sequence shape. + Shape: (batch_size, seq_len, hidden_size) + ''' + transformed_x = transformed_x.transpose(0, 1).reshape( + (-1, transformed_x.shape[2], transformed_x.shape[3])) + b, s, k, d = batch_size, seq_len, topk, transformed_x.shape[2] + gathered_x = transformed_x.reshape( + (transformed_x.shape[0] * transformed_x.shape[1], transformed_x.shape[2])) + mask_expanded = mask.reshape(-1).unsqueeze(-1).expand_as(gathered_x) + gathered_x = gathered_x * mask_expanded + + assert (indices >= 0).all(), "Indices should be non-negative" + + resortd_x = torch.zeros((b * s * k, d), device=gathered_x.device, dtype=gathered_x.dtype).scatter_add_( + 0, + indices.reshape(-1).unsqueeze(-1).expand(-1, d), + gathered_x, + ) + assert (indices < resortd_x.size(0)).all(), "Indices should be less than resortd_x size" + + inverse_indices = sorted_indices.argsort() + rearranged_x_flat = resortd_x[inverse_indices] + restored_x = rearranged_x_flat.reshape((b, s * k, d)) + restored_x = restored_x.reshape(b, s, k, d) * routing_weights.reshape(b, s, k).unsqueeze(-1) + restored_x = restored_x.sum(dim=2) + return restored_x + + +class MomAttention(nn.Module): + """ + The layer implementaion for [MoM: Linear Sequence Modeling with Mixture-of-Memories](https://arxiv.org/abs/2502.13685). + """ + + def __init__( + self, + hidden_size: int = 2048, + head_dim: int = 256, + num_heads: int = 4, + expand_v: float = 2, + mode: str = 'chunk', + use_output_gate: bool = True, + use_short_conv: bool = True, + conv_size: int = 4, + conv_bias: bool = False, + layer_idx: int = None, + norm_eps: float = 1e-5, + num_memories: int = 8, + topk: int = 2, + capacity: float = 1.0, + shared_mem: bool = False, + single_kv_proj: bool = False, + **kwargs + ) -> MomAttention: + super().__init__() + self.num_memories = num_memories + self.topk = topk + self.capacity = capacity + self.shared_mem = shared_mem + self.single_kv_proj = single_kv_proj + + self.mode = mode + + self.hidden_size = hidden_size + self.expand_v = expand_v + + self.use_output_gate = use_output_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + + self.head_dim = head_dim + self.num_heads = num_heads + + self.key_dim = int(self.num_heads * self.head_dim) + self.value_dim = int(self.key_dim * self.expand_v) + self.head_qk_dim = head_dim + self.head_v_dim = int(head_dim * self.expand_v) + self.layer_idx = layer_idx + self.silu = nn.SiLU() + + assert mode in ['chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`." + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.gate = nn.Linear(self.hidden_size, self.num_memories, bias=False) + if self.single_kv_proj: + self.shared_k = nn.Linear(hidden_size, self.key_dim, bias=False) + self.shared_v = nn.Linear(hidden_size, self.value_dim, bias=False) + self.shared_b = nn.Linear(hidden_size, self.num_heads, bias=False) + self.shared_a = nn.Linear(hidden_size, self.num_heads, bias=False) + else: + self.k_proj = nn.ModuleList([ + nn.Linear(self.hidden_size, self.key_dim, bias=False) + for _ in range(self.num_memories) + ]) + self.v_proj = nn.ModuleList([ + nn.Linear(self.hidden_size, self.value_dim, bias=False) + for _ in range(self.num_memories) + ]) + self.b_proj = nn.ModuleList([ + nn.Linear(self.hidden_size, self.num_heads, bias=False) + for _ in range(self.num_memories) + ]) + self.a_proj = nn.ModuleList([ + nn.Linear(self.hidden_size, self.num_heads, bias=False) + for _ in range(self.num_memories) + ]) + if self.shared_mem: + self.shared_k = nn.Linear(hidden_size, self.key_dim, bias=False) + self.shared_v = nn.Linear(hidden_size, self.value_dim, bias=False) + self.shared_b = nn.Linear(hidden_size, self.num_heads, bias=False) + self.shared_a = nn.Linear(hidden_size, self.num_heads, bias=False) + + A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16) + self.A_log = nn.Parameter(torch.log(A)) + self.A_log._no_weight_decay = True + # hard coded for now + dt_min = 0.001 + dt_max = 0.1 + dt_init_floor = 1e-4 + dt = torch.exp( + torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min)) + + math.log(dt_min) + ) + dt = torch.clamp(dt, min=dt_init_floor) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + self.dt_bias = nn.Parameter(inv_dt) + # Just to be explicit. Without this we already don't put wd on dt_bias because of the check + # name.endswith("bias") in param_grouping.py + self.dt_bias._no_weight_decay = True + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + else: + raise UserWarning( + "ShortConvolution is crucial to the performance. " + "Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing." + ) + if use_output_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps) + else: + self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps) + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + self.apply(self._initialize_weights) + + def _initialize_weights(self, module: nn.Module): + if getattr(module, "_is_hf_initialized", False): + return + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5) + if module.bias is not None: + nn.init.zeros_(module.bias) + module._is_hf_initialized = True + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + attention_mask = (attention_mask == 1) + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + origin_cu_seqlens = kwargs.get('cu_seqlens', None) + if origin_cu_seqlens is not None: + hidden_states, attention_mask = self.cu2pad(hidden_states, origin_cu_seqlens) + + mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode + if self.training: + assert mode == 'chunk', "Only chunk mode is supported in training." + + last_state = None + # _, q_len = hidden_states.shape[0], hidden_states.shape[1] + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + # 🔍 topk gating + router_logits = self.gate(hidden_states) # (bsz, q_len, num_memories) + scores = F.softmax(router_logits, dim=2, dtype=torch.float) + routing_weights, selected_memories = torch.topk(scores, self.topk, dim=-1) # (bsz, seq, topk) + routing_weights /= routing_weights.sum(dim=-1, keepdim=True) + routing_weights = routing_weights.to(hidden_states.dtype) # we cast back to the input dtype + routing_weights_full = torch.zeros( + routing_weights.shape[0], + routing_weights.shape[1], + self.num_memories, + dtype=routing_weights.dtype, + device=routing_weights.device + ).scatter(-1, selected_memories, routing_weights) + routing_mask = routing_weights_full.bool().int() + + # if self.use_output_gate: + # o_g = self.g_proj(hidden_states) + + batch_size, seq_len = hidden_states.shape[0], hidden_states.shape[1] + + shared_hidden_states = hidden_states + hidden_states, indices, sorted_indices, max_len, mask, mask_2 = transform( + hidden_states, routing_mask, self.num_memories, selected_memories, attention_mask) + + q = self.q_proj(hidden_states) + if self.single_kv_proj: + k = self.shared_k(hidden_states) + v = self.shared_v(hidden_states) + beta = self.shared_b(hidden_states).sigmoid() + g = -self.A_log.float().exp() * F.softplus(self.shared_a(hidden_states).float() + self.dt_bias) + else: + k = torch.stack([k_expert(hidden_states[i]) for i, k_expert in enumerate(self.k_proj)], dim=0) + v = torch.stack([v_expert(hidden_states[i]) for i, v_expert in enumerate(self.v_proj)], dim=0) + beta = torch.stack([b_expert(hidden_states[i]).sigmoid() for i, b_expert in enumerate(self.b_proj)], dim=0) + g = torch.stack([-self.A_log.float().exp() * F.softplus(a_expert(hidden_states[i]).float() + self.dt_bias) + for i, a_expert in enumerate(self.a_proj)], dim=0) + + q, k, v, g, beta, mask_2 = (rearrange(x, 'e b l ... -> (e b) l ...') for x in (q, k, v, g, beta, mask_2)) + cu_q, cu_k, cu_v, cu_g, cu_beta, indices_q, cu_seqlen_all, max_seq_lens = _upad_input(q, k, v, g, beta, mask_2) + cu_seqlens, reverse_indices = cu_seqlen_all[0].to(torch.long).unique(return_inverse=True) + cu_q, cu_k, cu_v, cu_g, cu_beta = (x.unsqueeze(0).contiguous() for x in (cu_q, cu_k, cu_v, cu_g, cu_beta)) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = [None, None], [None, None], [None, None] + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + + conv_cu_seqlens = cu_seqlens + padded = False + if self.training: + conv_cu_seqlens = None + elif seq_len != 1 and (cu_seqlens[1:] - cu_seqlens[:-1]).min().item() < self.conv_size: + padded = True + conv_cu_seqlens, cu_q, cu_k, cu_v, pad_lengths = self.pad_for_conv(cu_seqlens, cu_q, cu_k, cu_v) + + conv_q = self.prepare_recurrent_state( + conv_state_q[0], + conv_cu_seqlens, + cu_seqlen_all[0], + reverse_indices, + batch_size + ) + cu_q, conv_q_new = self.q_conv1d( + x=cu_q, + cache=conv_q, + output_final_state=use_cache, + cu_seqlens=conv_cu_seqlens, + ) + conv_state_q[0] = self.handle_recurrent_state( + conv_state_q[0], + conv_q_new, + conv_cu_seqlens, + cu_seqlen_all[0], + reverse_indices + ) + conv_k = self.prepare_recurrent_state( + conv_state_k[0], + conv_cu_seqlens, + cu_seqlen_all[0], + reverse_indices, + batch_size + ) + cu_k, conv_k_new = self.k_conv1d( + x=cu_k, + cache=conv_k, + output_final_state=use_cache, + cu_seqlens=conv_cu_seqlens, + ) + conv_state_k[0] = self.handle_recurrent_state( + conv_state_k[0], + conv_k_new, + conv_cu_seqlens, + cu_seqlen_all[0], + reverse_indices + ) + conv_v = self.prepare_recurrent_state( + conv_state_v[0], + conv_cu_seqlens, + cu_seqlen_all[0], + reverse_indices, + batch_size + ) + cu_v, conv_v_new = self.v_conv1d( + x=cu_v, + cache=conv_v, + output_final_state=use_cache, + cu_seqlens=conv_cu_seqlens, + ) + conv_state_v[0] = self.handle_recurrent_state( + conv_state_v[0], + conv_v_new, conv_cu_seqlens, + cu_seqlen_all[0], + reverse_indices + ) + + if padded: + cu_q, cu_k, cu_v = self.unpad_after_conv(conv_cu_seqlens, cu_seqlens, cu_q, cu_k, cu_v, pad_lengths) + + else: + q, k, v = self.silu(q), self.silu(k), self.silu(v), + + cu_q, cu_k, cu_v = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', h=self.num_heads), (cu_q, cu_k, cu_v)) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else [ + None for _ in range(1 + self.shared_mem)] + if mode == 'chunk': + o, recurrent_state_ = chunk_gated_delta_rule( + q=cu_q, + k=cu_k, + v=cu_v, + g=cu_g, + beta=cu_beta, + initial_state=recurrent_state[0], + output_final_state=use_cache, + use_qk_l2norm_in_kernel=True, + cu_seqlens=cu_seqlens, + ) + recurrent_state[0] = self.handle_recurrent_state( + recurrent_state[0], + recurrent_state_, + cu_seqlens, + cu_seqlen_all[0], + reverse_indices, + ) + + elif mode == 'fused_recurrent': + memories = self.prepare_recurrent_state( + recurrent_state[0], + cu_seqlens, cu_seqlen_all[0], + reverse_indices, batch_size + ) + o, recurrent_state_ = fused_recurrent_gated_delta_rule( + q=cu_q, + k=cu_k, + v=cu_v, + g=cu_g, + beta=cu_beta, + initial_state=memories, + output_final_state=use_cache, + use_qk_l2norm_in_kernel=True, + cu_seqlens=cu_seqlens, + ) + recurrent_state[0] = self.handle_recurrent_state( + recurrent_state[0], + recurrent_state_, + cu_seqlens, + cu_seqlen_all[0], + reverse_indices, + ) + + o = o.squeeze(0).contiguous() + o = pad_input(o, indices_q, batch_size*self.num_memories, max_len) + o = rearrange(o, '(e b) l h d -> e b l (h d)', b=batch_size) + o = reconstruct(o, indices=indices, sorted_indices=sorted_indices, batch_size=batch_size, + seq_len=seq_len, topk=self.topk, routing_weights=routing_weights, mask=mask) + o = rearrange(o, 'b l (h d) -> b l h d', h=self.num_heads) + + if self.shared_mem: + shared_o = self.shared_o(shared_hidden_states, attention_mask, recurrent_state, + use_cache, conv_state_q, conv_state_k, conv_state_v) + o += shared_o + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q.shape[2] + ) + + if self.use_output_gate: + g = rearrange(self.g_proj(shared_hidden_states), '... (h d) -> ... h d', d=self.head_v_dim) + o = self.o_norm(o, g) + else: + o = self.o_norm(o) + o = rearrange(o, 'b t h d -> b t (h d)') + o = self.o_proj(o) + + if origin_cu_seqlens is not None: + indices, _, _ = get_unpad_data(attention_mask[:, -seq_len:]) + o = index_first_axis(rearrange(o, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + return o, None, past_key_values, router_logits.view(-1, self.num_memories) + + def shared_o( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + recurrent_state=None, + use_cache: Optional[bool] = False, + conv_state_q=[None, None], + conv_state_k=[None, None], + conv_state_v=[None, None], + **kwargs + ) -> torch.Tensor: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode + if self.training: + assert mode == 'chunk', "Only chunk mode is supported in training." + + cu_seqlens = None + if attention_mask is not None: + batch_size, q_len = hidden_states.shape[0], hidden_states.shape[1] + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + q, conv_state_q[1] = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q[1], + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k[1] = self.k_conv1d( + x=self.shared_k(hidden_states), + cache=conv_state_k[1], + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v[1] = self.v_conv1d( + x=self.shared_v(hidden_states), + cache=conv_state_v[1], + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.silu(self.q_proj(hidden_states)) + k = self.silu(self.shared_k(hidden_states)) + v = self.silu(self.shared_v(hidden_states)) + + q, k, v = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', h=self.num_heads), (q, k, v)) + beta = self.shared_b(hidden_states).sigmoid() + g = -self.A_log.float().exp() * F.softplus(self.shared_a(hidden_states).float() + self.dt_bias) + + if mode == 'chunk': + o, recurrent_state[-1] = chunk_gated_delta_rule( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=recurrent_state[-1], + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True + ) + elif mode == 'fused_recurrent': + o, recurrent_state[-1] = fused_recurrent_gated_delta_rule( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=recurrent_state[-1], + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + return o + + def cu2pad(self, x, cu_seqlens): + batch_size = cu_seqlens.shape[0] - 1 + max_len = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item() + indices = torch.tensor([], dtype=torch.long, device=x.device) + attention_mask = torch.ones((batch_size, max_len), dtype=torch.bool, device=x.device) + for i in range(batch_size): + seq_len = cu_seqlens[i+1] - cu_seqlens[i] + pad_len = max_len - seq_len + batch_indices = torch.arange(pad_len, max_len, device=x.device) + batch_indices = batch_indices + i * max_len + indices = torch.cat([indices, batch_indices]) + attention_mask[i, :pad_len] = False + x = pad_input(x.squeeze(0), indices, batch_size, max_len) + return x, attention_mask + + def pad_for_conv(self, cu_seqlens, cu_q, cu_k, cu_v): + lengths = cu_seqlens[1:] - cu_seqlens[:-1] + pad_lengths = torch.clamp(self.conv_size - lengths, min=0) + new_lengths = lengths + pad_lengths + new_cu_seqlens = torch.cat([ + torch.tensor([0], device=cu_seqlens.device, dtype=cu_seqlens.dtype), + torch.cumsum(new_lengths, dim=0) + ]) + final_total_len = new_cu_seqlens[-1].item() + new_q = torch.zeros((1, final_total_len, cu_q.shape[-1]), dtype=cu_q.dtype, device=cu_q.device) + new_k = torch.zeros((1, final_total_len, cu_k.shape[-1]), dtype=cu_k.dtype, device=cu_k.device) + new_v = torch.zeros((1, final_total_len, cu_v.shape[-1]), dtype=cu_v.dtype, device=cu_v.device) + num_sequences = len(lengths) + for i in range(num_sequences): + src_start = cu_seqlens[i] + src_end = cu_seqlens[i+1] + dest_start = new_cu_seqlens[i] + pad_lengths[i] + dest_end = new_cu_seqlens[i+1] + new_q[:, dest_start:dest_end, ...] = cu_q[:, src_start:src_end, ...] + new_k[:, dest_start:dest_end, ...] = cu_k[:, src_start:src_end, ...] + new_v[:, dest_start:dest_end, ...] = cu_v[:, src_start:src_end, ...] + + return new_cu_seqlens, new_q, new_k, new_v, pad_lengths + + def unpad_after_conv(self, conv_cu_seqlens, cu_seqlens, cu_q, cu_k, cu_v, pad_lengths): + original_total_len = cu_seqlens[-1].item() + orig_q = torch.empty((1, original_total_len, cu_q.shape[-1]), dtype=cu_q.dtype, device=cu_q.device) + orig_k = torch.empty((1, original_total_len, cu_k.shape[-1]), dtype=cu_k.dtype, device=cu_k.device) + orig_v = torch.empty((1, original_total_len, cu_v.shape[-1]), dtype=cu_v.dtype, device=cu_v.device) + + num_sequences = len(pad_lengths) + for i in range(num_sequences): + dest_start = cu_seqlens[i] + dest_end = cu_seqlens[i+1] + src_start = conv_cu_seqlens[i] + pad_lengths[i] + src_end = conv_cu_seqlens[i+1] + + orig_q[:, dest_start:dest_end, ...] = cu_q[:, src_start:src_end, ...] + orig_k[:, dest_start:dest_end, ...] = cu_k[:, src_start:src_end, ...] + orig_v[:, dest_start:dest_end, ...] = cu_v[:, src_start:src_end, ...] + return orig_q, orig_k, orig_v + + def prepare_recurrent_state(self, recurrent_state, cu_seqlens, cu_seqlen_all, reverse_indices, batch_size): + if recurrent_state is None: + return None + + if cu_seqlens is None: + return recurrent_state + + total_len = len(cu_seqlen_all) + if len(cu_seqlens) != total_len: + # select memories that are activated + memories = torch.zeros_like(recurrent_state[:self.topk*batch_size]) + mem_id = 0 + for i in range(total_len-1): + if cu_seqlen_all[i] != cu_seqlen_all[i+1]: + memories[mem_id] = recurrent_state[i] + mem_id += 1 + assert mem_id == self.topk * batch_size, f"The number of memories {mem_id} is not correct." + else: + memories = recurrent_state + + return memories + + def handle_recurrent_state(self, recurrent_state, recurrent_state_new, cu_seqlens, cu_seqlen_all, reverse_indices): + if recurrent_state_new is None: + return None + if cu_seqlens is None: + return recurrent_state_new + if recurrent_state is None: + recurrent_state = torch.zeros_like(recurrent_state_new[reverse_indices[1:]-1]) + total_len = len(cu_seqlen_all) + if len(cu_seqlens) != total_len: + for i in range(total_len-1): + if cu_seqlen_all[i] != cu_seqlen_all[i+1]: + recurrent_state[i] = recurrent_state_new[reverse_indices[i+1]-1] + else: + recurrent_state = recurrent_state_new + return recurrent_state diff --git a/layers/multiscale_retention.py b/layers/multiscale_retention.py new file mode 100644 index 0000000000000000000000000000000000000000..08fc6402fafa1d2c237de71e968de2cb51c86d75 --- /dev/null +++ b/layers/multiscale_retention.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Optional, Tuple + +import torch +import torch.nn as nn +from einops import rearrange, repeat +from transformers.activations import ACT2FN + +from fla.layers.utils import get_unpad_data, index_first_axis, pad_input +from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution +from fla.modules.rotary import RotaryEmbedding +from fla.ops.retention import chunk_retention, fused_chunk_retention, fused_recurrent_retention, parallel_retention +from fla.ops.utils.index import prepare_lens_from_mask + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + from fla.models.utils import Cache + + +class MultiScaleRetention(nn.Module): + r""" + The layer implementaion for [Retentive Network: A Successor to Transformer for Large Language Models](https://arxiv.org/pdf/2307.08621.pdf). # noqa + + Args: + mode (str, Optional): + Which Retention kernel to use. + Currently available: `chunk`, `fused_recurrent`, `parallel`, and `fused_chunk`. + Default: `chunk`. + hidden_size (int, Optional): + The hidden size of the input. Default: 1024. + expand_k (float, Optional): + The expansion ratio for the key dim. Default: 1.0. + expand_v (float, Optional): + The expansion ratio for the value dim. Default: 2.0. + num_heads (int, Optional): + The number of heads. Default: 8. + num_kv_heads (int, Optional): + The number of key/value heads, used for MQA. Default: None. + feature_map (str, Optional): + Feature map function applied to queries/keys. Default: None. + use_short_conv (bool, Optional): + Whether to use short convolutions. Default: `False`. + conv_size (int, Optional): + The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4. + conv_bias (bool, Optional): + Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`. + use_output_gate (bool, Optional): + Whether to use output gate. Default: `True`. + gate_fn (str, Optional): + The activation function for the output gate. Default: `swish`. + elementwise_affine (bool, Optional): + If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`. + norm_eps (float, Optional): + The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5. + fuse_norm (bool, Optional): + Whether to fuse the norm and the output gate for better memory footprint. Default: `True`. + layer_idx (int, Optional): + The index of the layer. Default: None. + """ + + def __init__( + self, + mode: str = 'chunk', + hidden_size: int = 1024, + expand_k: float = 1.0, + expand_v: float = 2.0, + num_heads: int = 8, + num_kv_heads: Optional[int] = None, + feature_map: Optional[str] = None, + use_short_conv: bool = False, + conv_size: int = 4, + conv_bias: bool = False, + use_output_gate: bool = True, + gate_fn: str = 'swish', + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-5, + fuse_norm: bool = True, + layer_idx: int = None, + **kwargs + ) -> MultiScaleRetention: + super().__init__() + + self.mode = mode + self.hidden_size = hidden_size + self.expand_k = expand_k + self.expand_v = expand_v + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads + self.num_kv_groups = self.num_heads // self.num_kv_heads + self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None + + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.conv_bias = conv_bias + self.use_output_gate = use_output_gate + + self.key_dim = int(hidden_size * expand_k) + self.value_dim = int(hidden_size * expand_v) + self.key_dim_per_group = self.key_dim // self.num_kv_groups + self.value_dim_per_group = self.value_dim // self.num_kv_groups + self.layer_idx = layer_idx + + assert mode in ['chunk', 'fused_chunk', 'parallel', 'fused_recurrent'], f"Not supported mode `{mode}`." + assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}" + assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}" + + self.head_k_dim = self.key_dim // num_heads + self.head_v_dim = self.value_dim // num_heads + + self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False) + self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False) + self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False) + if self.use_output_gate: + self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False) + + if use_short_conv: + self.conv_size = conv_size + self.q_conv1d = ShortConvolution( + hidden_size=self.key_dim, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.k_conv1d = ShortConvolution( + hidden_size=self.key_dim_per_group, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + self.v_conv1d = ShortConvolution( + hidden_size=self.value_dim_per_group, + kernel_size=conv_size, + bias=conv_bias, + activation='silu' + ) + + self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False) + + if gate_fn == 'swish' and fuse_norm and use_output_gate: + self.g_norm_swish_gate = FusedRMSNormGated( + hidden_size=self.head_v_dim, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + self.fuse_norm_and_gate = True + else: + self.fuse_norm_and_gate = False + self.g_norm = RMSNorm( + hidden_size=self.head_v_dim, + elementwise_affine=elementwise_affine, + eps=norm_eps + ) + self.gate_fn = ACT2FN[gate_fn] + + # TODO: fix this issue + # https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/ops/triton/rotary.py#L180 + # Ideally, we would want to support arbitrary d_head_qk + assert self.head_k_dim <= 256, "head_k_dim must be less than or equal to 256" + self.rotary = RotaryEmbedding(dim=self.head_k_dim) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Cache] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, q_len, _ = hidden_states.shape + mode = 'fused_recurrent' if q_len <= 64 else self.mode + + last_state = None + if past_key_values is not None and len(past_key_values) > self.layer_idx: + last_state = past_key_values[self.layer_idx] + + cu_seqlens = kwargs.get('cu_seqlens', None) + if attention_mask is not None: + indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) + hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) + + if self.use_short_conv: + conv_state_q, conv_state_k, conv_state_v = None, None, None + if last_state is not None: + conv_state_q, conv_state_k, conv_state_v = last_state['conv_state'] + q, conv_state_q = self.q_conv1d( + x=self.q_proj(hidden_states), + cache=conv_state_q, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + k, conv_state_k = self.k_conv1d( + x=self.k_proj(hidden_states), + cache=conv_state_k, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + v, conv_state_v = self.v_conv1d( + x=self.v_proj(hidden_states), + cache=conv_state_v, + output_final_state=use_cache, + cu_seqlens=cu_seqlens + ) + else: + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + + q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim) + if self.feature_map_fn is not None: + q, k = map(self.feature_map_fn, (q, k)) + + seqlen_offset, max_seqlen = 0, q.shape[1] + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + max_seqlen = q.shape[1] + seqlen_offset + + if attention_mask is not None and seqlen_offset > 0: + # to deliminate the offsets of padding tokens + seqlen_offset = prepare_lens_from_mask(attention_mask) - q_len + max_seqlen = q.shape[1] + seqlen_offset.max().item() + + q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens) + + if self.num_kv_groups > 1: + k = repeat(k, '... h d -> ... (h g) d', g=self.num_kv_groups) + v = repeat(v, '... (h d) -> ... (h g) d', d=self.head_v_dim, g=self.num_kv_groups) + else: + v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim) + + recurrent_state = last_state['recurrent_state'] if last_state is not None else None + if mode == 'chunk': + o, recurrent_state = chunk_retention( + q=q, + k=k, + v=v, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + elif mode == 'fused_chunk': + o, recurrent_state = fused_chunk_retention( + q=q, + k=k, + v=v, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + elif mode == 'parallel': + o, recurrent_state = parallel_retention( + q=q, + k=k, + v=v, + cu_seqlens=cu_seqlens, + ) + elif mode == 'fused_recurrent': + o, recurrent_state = fused_recurrent_retention( + q=q, + k=k, + v=v, + initial_state=recurrent_state, + output_final_state=use_cache, + cu_seqlens=cu_seqlens, + ) + else: + raise NotImplementedError(f"Not supported mode `{mode}`.") + + if past_key_values is not None: + past_key_values.update( + recurrent_state=recurrent_state, + conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None, + layer_idx=self.layer_idx, + offset=q_len + ) + + if self.use_output_gate: + g = self.g_proj(hidden_states) + if self.fuse_norm_and_gate: + g = rearrange(g, '... (h d) -> ... h d', d=self.head_v_dim) + o = self.g_norm_swish_gate(o, g) + o = rearrange(o, '... h d -> ... (h d)') + else: + o = rearrange(self.g_norm(o), '... h d -> ... (h d)') + o = o * self.gate_fn(g) + else: + o = rearrange(self.g_norm(o), '... h d -> ... (h d)') + o = self.o_proj(o) + if attention_mask is not None: + o = pad_input(o.squeeze(0), indices, batch_size, q_len) + + return o, None, past_key_values diff --git a/layers/nsa.py b/layers/nsa.py new file mode 100644 index 0000000000000000000000000000000000000000..ae38498465a1a999fdcf5973066010bd804ebee2 --- /dev/null +++ b/layers/nsa.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional, Tuple, Union + +import torch +import torch.nn as nn +from einops import rearrange +from transformers.utils import logging + +from fla.modules import RotaryEmbedding +from fla.ops.nsa.parallel import parallel_nsa +from fla.ops.utils.index import prepare_lens_from_mask + +if TYPE_CHECKING: + from fla.models.utils import Cache + +logger = logging.get_logger(__name__) + + +class NativeSparseAttention(nn.Module): + + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 64, + num_kv_heads: Optional[int] = 4, + head_dim: int = 64, + qkv_bias: bool = False, + block_size: Optional[int] = 64, + block_counts: Optional[Union[torch.LongTensor, int]] = 16, + window_size: Optional[int] = 512, + rope_theta: Optional[float] = 10000., + max_position_embeddings: Optional[int] = None, + layer_idx: int = None + ): + super().__init__() + + self.hidden_size = hidden_size + self.num_heads = num_heads + if num_kv_heads is None: + self.num_kv_heads = self.num_heads + else: + self.num_kv_heads = num_kv_heads + self.num_kv_groups = num_heads // self.num_kv_heads + self.head_dim = head_dim + self.kv_dim = self.num_kv_heads * self.head_dim + self.qkv_bias = qkv_bias + + self.block_size = block_size + self.block_counts = block_counts + self.window_size = window_size + self.rope_theta = rope_theta + self.max_position_embeddings = max_position_embeddings + self.layer_idx = layer_idx + + self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.qkv_bias) + self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias) + self.g_proj = nn.Linear(self.hidden_size, self.num_heads * 3, bias=False) + self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) + + self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + + batch_size, seq_len, _ = hidden_states.size() + + q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim) + g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=3) + g_cmp, g_slc, g_swa = g.sigmoid().unbind(-1) + + cu_seqlens = kwargs.get('cu_seqlens', None) + + seqlen_offset, max_seqlen = 0, seq_len + if past_key_values is not None: + seqlen_offset = past_key_values.get_seq_length(self.layer_idx) + max_seqlen = q.shape[1] + seqlen_offset + + if attention_mask is not None: + # to deliminate the offsets of padding tokens + seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1] + max_seqlen = q.shape[1] + max(seqlen_offset) + + if self.max_position_embeddings is not None: + max_seqlen = max(max_seqlen, self.max_position_embeddings) + q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens) + + if past_key_values is not None: + cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0 + k_cached, v_cached = past_key_values.update( + attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)), + layer_idx=self.layer_idx, + offset=seq_len, + cache_kwargs=dict(window_size=self.window_size) + )['attn_state'] + if cache_has_content: + k, v = k_cached, v_cached + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + + o = parallel_nsa( + q=q, + k=k, + v=v, + g_cmp=g_cmp, + g_slc=g_slc, + g_swa=g_swa, + block_size=self.block_size, + block_counts=self.block_counts, + window_size=self.window_size, + cu_seqlens=cu_seqlens, + ) + o = o.reshape(batch_size, seq_len, -1) + o = self.o_proj(o) + + if not output_attentions: + attentions = None + + return o, attentions, past_key_values diff --git a/layers/path_attn.py b/layers/path_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a2955bbd391b910276f972f0fc9d0a4f143009 --- /dev/null +++ b/layers/path_attn.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from transformers.utils import logging + +from fla.layers.utils import pad_input, unpad_input +from fla.modules import RMSNorm, ShortConvolution +from fla.modules.l2norm import l2_norm +from fla.ops.attn.decoding import attn_decoding_one_step +from fla.ops.path_attn.parallel import parallel_path_attn + +if TYPE_CHECKING: + from fla.models.utils import Cache + +logger = logging.get_logger(__name__) + + +class PaTHAttention(nn.Module): + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 32, + num_kv_heads: Optional[int] = None, + use_forget_gate: bool = False, + use_qk_norm: bool = False, + layer_idx: int = None, + use_low_rank_w: bool = True, + use_w_shortconv: bool = True, + conv_size: int = 3, + conv_bias: bool = False, + ): + super().__init__() + + self.hidden_size = hidden_size + self.num_heads = num_heads + if num_kv_heads is None: + self.num_kv_heads = self.num_heads + else: + self.num_kv_heads = num_kv_heads + self.head_dim = self.hidden_size // self.num_heads + self.kv_dim = self.num_kv_heads * self.head_dim + + self.layer_idx = layer_idx + + self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False) + + # We use low-rank parameterization for the w_proj to reduce parameters in MHA settings. + if use_low_rank_w: + self.w_proj = nn.Sequential( + nn.Linear(self.hidden_size, 32, bias=False), + nn.Linear(32, self.kv_dim, bias=False) + ) + # In MQA/GQA settings, key/value heads are shared, so we use a standard linear projection + # which doesn't introduce too many parameters + else: + self.w_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False) + + # TODO: per head norm? + if use_qk_norm: + self.maybe_q_norm = RMSNorm(self.hidden_size) + self.maybe_k_norm = RMSNorm(self.kv_dim) + else: + self.maybe_q_norm = nn.Identity() + self.maybe_k_norm = nn.Identity() + + if use_w_shortconv: + self.w_conv1d = ShortConvolution(hidden_size=self.kv_dim, kernel_size=conv_size, bias=conv_bias, activation='silu') + self.use_w_shortconv = use_w_shortconv + self.bt_proj = nn.Linear(self.hidden_size, self.num_kv_heads, bias=True) + self.use_forget_gate = use_forget_gate + if use_forget_gate: + self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if use_cache: + assert past_key_values is not None, "past_key_values must be provided when use_cache is True" + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + batch_size, q_len, _ = hidden_states.size() + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + w = self.w_proj(hidden_states) + beta = self.bt_proj(hidden_states).sigmoid() * 2 # allowing negative eigenvalues + g = F.logsigmoid(self.g_proj(hidden_states).float()) if self.use_forget_gate else None + q, k = self.maybe_q_norm(q), self.maybe_k_norm(k) + cu_seqlens = kwargs.get('cu_seqlens', None) + assert not (cu_seqlens is not None and attention_mask is not None), ( + "cu_seqlens should not be provided when attention_mask is not None" + ) + # Training + if attention_mask is None: + assert use_cache is False, "use_cache should be False in training" + if self.use_w_shortconv: + w, _ = self.w_conv1d(w, cache=None, output_final_state=False, cu_seqlens=cu_seqlens) + q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)####this 需要额外的分头,设定一个r的分块,d-》r*d//r + w = l2_norm(w) + o, _ = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g, cu_seqlens=cu_seqlens)####here + + # Prefilling or decoding + else: + assert self.training is False, "attention mask is not supported in training. Please use variable length input." + try: + last_state = past_key_values[self.layer_idx] + except KeyError: + last_state = None + # Decoding + if last_state is not None: + if g is not None: + past_k, past_v, past_g = last_state['attn_state'] + else: + past_k, past_v = last_state['attn_state'] + w_conv_state = last_state['conv_state'] + past_k = rearrange(past_k, '... (h d) -> ... h d', d=self.head_dim) + if self.use_w_shortconv: + w, w_conv_state = self.w_conv1d(w, cache=w_conv_state, output_final_state=use_cache, cu_seqlens=cu_seqlens) + w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim) + w = l2_norm(w) + + @torch.compile + def rank_one_update(k, w, beta): + original_dtype = k.dtype + k = k.float() + w = w.float() + beta = beta.float() + k = k - beta[..., None].float() * (k * w).sum(-1, keepdim=True) * w + return k.to(original_dtype) + + past_k = rank_one_update(past_k, w, beta) + past_k = rearrange(past_k, '... h d -> ... (h d)') + k = torch.cat([past_k, k], dim=1) + v = torch.cat([past_v, v], dim=1) + g = torch.cat([past_g, g], dim=1) if g is not None else None + past_key_values[self.layer_idx]['attn_state'] = (k, v, g) if g is not None else (k, v) + past_key_values.update( + conv_state=w_conv_state, + layer_idx=self.layer_idx, + offset=q_len + ) + if g is not None: + q, (k, v, g), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v, g), attention_mask, q_len, keepdim=True) + max_seqlen_q, max_seqlen_k = max_seq_lens + else: + q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v), attention_mask, q_len, keepdim=True) + max_seqlen_q, max_seqlen_k = max_seq_lens + _, cu_seqlens = cu_seqlens + q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + assert max_seqlen_q == 1, "only support q_len == 1 for decoding" + o = attn_decoding_one_step(q, k, v, g, cu_seqlens=cu_seqlens, do_gate_scale=True) # reduced to fox's decoding + # Prefilling + else: + v_cache = v.clone() + g_cache = g.clone() if g is not None else None + if g is None: + q, (k, v, w, beta), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v, w, beta), attention_mask, q_len, keepdim=True) + else: + q, (k, v, w, beta, g), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v, w, beta, g), attention_mask, q_len, keepdim=True) + max_seqlen_q, max_seqlen_k = max_seq_lens + assert max_seqlen_q == max_seqlen_k, "max_seqlen_q should be equal to max_seqlen_k in prefilling" + _, cu_seqlens = cu_seqlens + if self.use_w_shortconv: + w, w_conv_state = self.w_conv1d(w, cache=None, output_final_state=use_cache, cu_seqlens=cu_seqlens) + else: + w_conv_state = None + q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim) + w = l2_norm(w) + o, k_cache = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g, + cu_seqlens=cu_seqlens, use_cache=use_cache) + if use_cache: + k_cache = pad_input(k_cache.squeeze(0), indices_q, batch_size, q_len) + k_cache = rearrange(k_cache, '... h d -> ... (h d)') + past_key_values.update( + attn_state=(k_cache, v_cache, g_cache) if g_cache is not None else (k_cache, v_cache), + conv_state=w_conv_state, + layer_idx=self.layer_idx, + offset=q_len + ) + o = pad_input(o.squeeze(0), indices_q, batch_size, q_len) + o = rearrange(o, '... h d -> ... (h d)') + o = self.o_proj(o) + return o, None, past_key_values diff --git a/layers/path_test.py b/layers/path_test.py new file mode 100644 index 0000000000000000000000000000000000000000..94cda846c16e6b2df68097475ca4c11c1bbe2016 --- /dev/null +++ b/layers/path_test.py @@ -0,0 +1,217 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from transformers.utils import logging + +from fla.layers.utils import pad_input, unpad_input +from fla.modules import RMSNorm, ShortConvolution +from fla.modules.l2norm import l2_norm +from fla.ops.attn.decoding import attn_decoding_one_step +from fla.ops.path_attn.parallel import parallel_path_attn + +if TYPE_CHECKING: + from fla.models.utils import Cache + +logger = logging.get_logger(__name__) + + +class PaTHAttention(nn.Module): + def __init__( + self, + hidden_size: int = 2048, + num_heads: int = 32, + num_w_heads: Optional[int] = None , ###额外的分头操作 + num_kv_heads: Optional[int] = None, + use_forget_gate: bool = False, + use_qk_norm: bool = False, + layer_idx: int = None, + use_low_rank_w: bool = True, + use_w_shortconv: bool = True, + conv_size: int = 3, + conv_bias: bool = False, + ): + super().__init__() + + self.hidden_size = hidden_size + self.num_heads = num_heads + if num_kv_heads is None: + self.num_kv_heads = self.num_heads + else: + self.num_kv_heads = num_kv_heads + self.head_dim = self.hidden_size // self.num_heads + self.kv_dim = self.num_kv_heads * self.head_dim + + self.layer_idx = layer_idx + + self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False) + + # We use low-rank parameterization for the w_proj to reduce parameters in MHA settings. + if use_low_rank_w: + self.w_proj = nn.Sequential( + nn.Linear(self.hidden_size, 32, bias=False), + nn.Linear(32, self.kv_dim, bias=False) + ) + # In MQA/GQA settings, key/value heads are shared, so we use a standard linear projection + # which doesn't introduce too many parameters + else: + self.w_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False) + + # TODO: per head norm? + if use_qk_norm: + self.maybe_q_norm = RMSNorm(self.hidden_size) + self.maybe_k_norm = RMSNorm(self.kv_dim) + else: + self.maybe_q_norm = nn.Identity() + self.maybe_k_norm = nn.Identity() + + if use_w_shortconv: + self.w_conv1d = ShortConvolution(hidden_size=self.kv_dim, kernel_size=conv_size, bias=conv_bias, activation='silu') + self.use_w_shortconv = use_w_shortconv + self.bt_proj = nn.Linear(self.hidden_size, self.num_kv_heads, bias=True) + self.use_forget_gate = use_forget_gate + if use_forget_gate: + self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if use_cache: + assert past_key_values is not None, "past_key_values must be provided when use_cache is True" + if attention_mask is not None: + assert len(attention_mask.shape) == 2, ( + "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] " + "for padding purposes (0 indicating padding). " + "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed." + ) + batch_size, q_len, _ = hidden_states.size() + q = self.q_proj(hidden_states) + k = self.k_proj(hidden_states) + v = self.v_proj(hidden_states) + w = self.w_proj(hidden_states) + beta = self.bt_proj(hidden_states).sigmoid() * 2 # allowing negative eigenvalues + g = F.logsigmoid(self.g_proj(hidden_states).float()) if self.use_forget_gate else None + q, k = self.maybe_q_norm(q), self.maybe_k_norm(k) + cu_seqlens = kwargs.get('cu_seqlens', None) + assert not (cu_seqlens is not None and attention_mask is not None), ( + "cu_seqlens should not be provided when attention_mask is not None" + ) + # Training + if attention_mask is None: + assert use_cache is False, "use_cache should be False in training" + if self.use_w_shortconv: + w, _ = self.w_conv1d(w, cache=None, output_final_state=False, cu_seqlens=cu_seqlens) + q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim) + w = l2_norm(w) + o, _ = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g, cu_seqlens=cu_seqlens)####here + + # Prefilling or decoding + else: + assert self.training is False, "attention mask is not supported in training. Please use variable length input." + try: + last_state = past_key_values[self.layer_idx] + except KeyError: + last_state = None + # Decoding + if last_state is not None: + if g is not None: + past_k, past_v, past_g = last_state['attn_state'] + else: + past_k, past_v = last_state['attn_state'] + w_conv_state = last_state['conv_state'] + past_k = rearrange(past_k, '... (h d) -> ... h d', d=self.head_dim) + if self.use_w_shortconv: + w, w_conv_state = self.w_conv1d(w, cache=w_conv_state, output_final_state=use_cache, cu_seqlens=cu_seqlens) + w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim) + w = l2_norm(w) + + @torch.compile + def rank_one_update(k, w, beta): + original_dtype = k.dtype + k = k.float() + w = w.float() + beta = beta.float() + k = k - beta[..., None].float() * (k * w).sum(-1, keepdim=True) * w + return k.to(original_dtype) + + past_k = rank_one_update(past_k, w, beta) + past_k = rearrange(past_k, '... h d -> ... (h d)') + k = torch.cat([past_k, k], dim=1) + v = torch.cat([past_v, v], dim=1) + g = torch.cat([past_g, g], dim=1) if g is not None else None + past_key_values[self.layer_idx]['attn_state'] = (k, v, g) if g is not None else (k, v) + past_key_values.update( + conv_state=w_conv_state, + layer_idx=self.layer_idx, + offset=q_len + ) + if g is not None: + q, (k, v, g), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v, g), attention_mask, q_len, keepdim=True) + max_seqlen_q, max_seqlen_k = max_seq_lens + else: + q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v), attention_mask, q_len, keepdim=True) + max_seqlen_q, max_seqlen_k = max_seq_lens + _, cu_seqlens = cu_seqlens + q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + assert max_seqlen_q == 1, "only support q_len == 1 for decoding" + o = attn_decoding_one_step(q, k, v, g, cu_seqlens=cu_seqlens, do_gate_scale=True) # reduced to fox's decoding + # Prefilling + else: + v_cache = v.clone() + g_cache = g.clone() if g is not None else None + if g is None: + q, (k, v, w, beta), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v, w, beta), attention_mask, q_len, keepdim=True) + else: + q, (k, v, w, beta, g), indices_q, cu_seqlens, max_seq_lens = unpad_input( + q, (k, v, w, beta, g), attention_mask, q_len, keepdim=True) + max_seqlen_q, max_seqlen_k = max_seq_lens + assert max_seqlen_q == max_seqlen_k, "max_seqlen_q should be equal to max_seqlen_k in prefilling" + _, cu_seqlens = cu_seqlens + if self.use_w_shortconv: + w, w_conv_state = self.w_conv1d(w, cache=None, output_final_state=use_cache, cu_seqlens=cu_seqlens) + else: + w_conv_state = None + q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim) + k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim) + v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) + w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim) + w = l2_norm(w) + o, k_cache = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g, + cu_seqlens=cu_seqlens, use_cache=use_cache) + if use_cache: + k_cache = pad_input(k_cache.squeeze(0), indices_q, batch_size, q_len) + k_cache = rearrange(k_cache, '... h d -> ... (h d)') + past_key_values.update( + attn_state=(k_cache, v_cache, g_cache) if g_cache is not None else (k_cache, v_cache), + conv_state=w_conv_state, + layer_idx=self.layer_idx, + offset=q_len + ) + o = pad_input(o.squeeze(0), indices_q, batch_size, q_len) + o = rearrange(o, '... h d -> ... (h d)') + o = self.o_proj(o) + return o, None, past_key_values diff --git a/log.md b/log.md new file mode 100644 index 0000000000000000000000000000000000000000..f5223ded65dbceb566df976615dd267c4c2dd2cb --- /dev/null +++ b/log.md @@ -0,0 +1,2 @@ +记录当前task +1. 对于需要额外分头的操作,line122 修改head \ No newline at end of file diff --git a/models/abc/__init__.py b/models/abc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2fe01b1cd1895c676eac9e29d9e99a835fc87bd --- /dev/null +++ b/models/abc/__init__.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.abc.configuration_abc import ABCConfig +from fla.models.abc.modeling_abc import ABCForCausalLM, ABCModel + +AutoConfig.register(ABCConfig.model_type, ABCConfig, exist_ok=True) +AutoModel.register(ABCConfig, ABCModel, exist_ok=True) +AutoModelForCausalLM.register(ABCConfig, ABCForCausalLM, exist_ok=True) + + +__all__ = ['ABCConfig', 'ABCForCausalLM', 'ABCModel'] diff --git a/models/abc/configuration_abc.py b/models/abc/configuration_abc.py new file mode 100644 index 0000000000000000000000000000000000000000..4feb51dde44b3d6cde69ef3e855ab8daf2f1aa32 --- /dev/null +++ b/models/abc/configuration_abc.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- + +import warnings +from typing import Dict, Optional + +from transformers.configuration_utils import PretrainedConfig + + +class ABCConfig(PretrainedConfig): + + model_type = 'abc' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + hidden_size: int = 2048, + gate_low_rank_dim: int = 16, + clamp_min: float = -32, + clamp_max: float = 32, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + num_hidden_layers: int = 24, + num_heads: int = 4, + num_slots: Optional[int] = 64, + use_short_conv: bool = False, + conv_size: int = 4, + exapnd_k: float = 0.5, + exapnd_v: float = 1, + hidden_act: str = "swish", + max_position_embeddings: int = 2048, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-6, + use_rope: bool = True, + attn: Optional[Dict] = None, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + initializer_range: float = 0.02, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + **kwargs + ): + self.hidden_size = hidden_size + self.gate_low_rank_dim = gate_low_rank_dim + self.clamp_min = clamp_min + self.clamp_max = clamp_max + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_heads = num_heads + self.num_slots = num_slots + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.expand_k = exapnd_k + self.expand_v = exapnd_v + self.hidden_act = hidden_act + self.max_position_embeddings = max_position_embeddings + self.elementwise_affine = elementwise_affine + self.norm_eps = norm_eps + self.use_rope = use_rope + self.attn = attn + self.use_cache = use_cache + self.initializer_range = initializer_range + + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + if attn is not None: + if not isinstance(attn, Dict): + raise ValueError("attn must be a dictionary") + if 'layers' not in attn: + raise ValueError("Layer indices must be provided to initialize hybrid attention layers") + if 'num_heads' not in attn: + raise ValueError("Number of heads must be provided to initialize hybrid attention layers") + attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads']) + attn['qkv_bias'] = attn.get('qkv_bias', False) + attn['window_size'] = attn.get('window_size', None) + attn['rope_theta'] = attn.get('rope_theta', 10000.) + + super().__init__( + 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, + ) diff --git a/models/abc/modeling_abc.py b/models/abc/modeling_abc.py new file mode 100644 index 0000000000000000000000000000000000000000..d74888fbcb4ae5b9c7593ff62c36d3376a2766d0 --- /dev/null +++ b/models/abc/modeling_abc.py @@ -0,0 +1,374 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.utils.deprecation import deprecate_kwarg + +from fla.layers.abc import ABCAttention +from fla.layers.attn import Attention +from fla.models.abc.configuration_abc import ABCConfig +from fla.models.utils import Cache, FLAGenerationMixin +from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss +from fla.modules import GatedMLP as ABCMLP +from fla.modules import RMSNorm +from fla.modules.l2warp import l2_warp + +try: + from transformers.modeling_layers import GradientCheckpointingLayer +except ImportError: + from fla.models.modeling_layers import GradientCheckpointingLayer + +logger = logging.get_logger(__name__) + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + +class ABCBlock(GradientCheckpointingLayer): + + def __init__(self, config: ABCConfig, layer_idx: int): + super().__init__() + + self.config = config + self.layer_idx = layer_idx + + self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + if config.attn is not None and layer_idx in config.attn['layers']: + self.attn = Attention( + hidden_size=config.hidden_size, + num_heads=config.attn['num_heads'], + num_kv_heads=config.attn['num_kv_heads'], + qkv_bias=config.attn['qkv_bias'], + window_size=config.attn['window_size'], + rope_theta=config.attn['rope_theta'], + max_position_embeddings=config.max_position_embeddings, + layer_idx=layer_idx + ) + else: + self.attn = ABCAttention( + hidden_size=config.hidden_size, + expand_k=config.expand_k, + expand_v=config.expand_v, + num_heads=config.num_heads, + num_slots=config.num_slots, + use_short_conv=config.use_short_conv, + conv_size=config.conv_size, + gate_fn=config.hidden_act, + elementwise_affine=config.elementwise_affine, + norm_eps=config.norm_eps, + use_rope=config.use_rope, + clamp_min=config.clamp_min, + clamp_max=config.clamp_max, + fuse_norm=config.fuse_norm, + layer_idx=layer_idx + ) + self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.mlp = ABCMLP( + hidden_size=config.hidden_size, + hidden_ratio=config.hidden_ratio, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + fuse_swiglu=config.fuse_swiglu + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + + residual = hidden_states + + hidden_states = self.attn_norm(hidden_states) + hidden_states, attentions, past_key_values = self.attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + if self.config.fuse_norm: + hidden_states, residual = self.mlp_norm(hidden_states, residual, True) + else: + hidden_states = residual + hidden_states + residual = hidden_states + hidden_states = self.mlp_norm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + outputs = (hidden_states, attentions, past_key_values) + + return outputs + + +class ABCPreTrainedModel(PreTrainedModel): + + config_class = ABCConfig + base_model_prefix = 'model' + supports_gradient_checkpointing = True + _no_split_modules = ['ABCBlock'] + _supports_cache_class = True + + def __init__(self, *inputs, **kwargs): + super().__init__(*inputs, **kwargs) + + def _init_weights( + self, + module: nn.Module, + prenorm_residual_strategy: Optional[str] = None, + num_residuals_per_layer: int = 2, + ): + if isinstance(module, (nn.Linear, nn.Conv1d)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + elif hasattr(module, 'reset_parameters'): + module.reset_parameters() + + if prenorm_residual_strategy is not None: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + p = None + if hasattr(module, 'o_proj'): + p = module.o_proj.weight + elif hasattr(module, 'down_proj'): + p = module.down_proj.weight + if p is not None: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) + # We need to reinit p since this code could be called multiple times + # Having just p *= scale would repeatedly scale it down + if prenorm_residual_strategy == 'rescale': + nn.init.kaiming_uniform_(p, a=math.sqrt(5)) + with torch.no_grad(): + p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers) + elif prenorm_residual_strategy == 'zero': + nn.init.zeros_(p) + else: + raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}") + + +class ABCModel(ABCPreTrainedModel): + + def __init__(self, config: ABCConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([ABCBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]) + self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + + self.gradient_checkpointing = False + + self.post_init() + + def get_input_embeddings(self): + return self.embeddings + + def set_input_embeddings(self, value): + self.embeddings = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, # noqa + inputs_embeds: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, BaseModelOutputWithPast]: + if output_attentions: + warnings.warn("`ABCModel` does not `output_attentions` now, setting it to `False`.") + output_attentions = False + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + if input_ids is None and inputs_embeds is None: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embeddings(input_ids) + hidden_states = inputs_embeds + + if use_cache and not isinstance(past_key_values, Cache): + past_key_values = Cache.from_legacy_cache(past_key_values) + + all_hidden_states = () if output_hidden_states else None + all_attns = () if output_attentions else None + for layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + hidden_states, attentions, past_key_values = layer( + hidden_states, + attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + + if output_attentions: + all_attns += (attentions,) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if not return_dict: + return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values, + hidden_states=all_hidden_states, + attentions=all_attns + ) + + +class ABCForCausalLM(ABCPreTrainedModel, FLAGenerationMixin): + + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = ABCModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.criterion = None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embeddings + + def set_input_embeddings(self, value): + self.model.embeddings = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + def generate(self, *args, **kwargs): + try: + return super().generate(*args, **kwargs) + except AttributeError as exception: + if 'past_key_values' in str(exception): + raise AttributeError( + f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, " + f"which is not supported for {self.__class__.__name__}. " + f"Try another generation strategy instead. " + f"For the available generation strategies, check this doc: " + f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies" + ) + else: + raise exception + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + logits_to_keep: Optional[int] = 0, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, CausalLMOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs + ) + + hidden_states = outputs[0] + + loss, logits = None, None + if not self.config.fuse_linear_cross_entropy or labels is None: + logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:]) + if labels is not None: + if getattr(self, 'criterion', None) is None: + if self.config.fuse_linear_cross_entropy: + criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp) + elif self.config.fuse_cross_entropy: + criterion = FusedCrossEntropyLoss(inplace_backward=True) + else: + criterion = nn.CrossEntropyLoss() + else: + criterion = self.criterion + labels = labels.to(hidden_states.device) + labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1) + if self.config.fuse_linear_cross_entropy: + loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias) + else: + loss = criterion(logits.view(labels.numel(), -1), labels.view(-1)) + loss = l2_warp(loss, logits) if self.config.use_l2warp else loss + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git a/models/bitnet/__init__.py b/models/bitnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..230e70fe6b0005a37580727b2bce50d57c12fb35 --- /dev/null +++ b/models/bitnet/__init__.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.bitnet.configuration_bitnet import BitNetConfig +from fla.models.bitnet.modeling_bitnet import BitNetForCausalLM, BitNetModel + +AutoConfig.register(BitNetConfig.model_type, BitNetConfig, exist_ok=True) +AutoModel.register(BitNetConfig, BitNetModel, exist_ok=True) +AutoModelForCausalLM.register(BitNetConfig, BitNetForCausalLM, exist_ok=True) + + +__all__ = ['BitNetConfig', 'BitNetForCausalLM', 'BitNetModel'] diff --git a/models/bitnet/configuration_bitnet.py b/models/bitnet/configuration_bitnet.py new file mode 100644 index 0000000000000000000000000000000000000000..5c024e1c8eb758246283b45811cea8fa0d52cc78 --- /dev/null +++ b/models/bitnet/configuration_bitnet.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- + +import warnings +from typing import Optional + +from transformers.configuration_utils import PretrainedConfig + + +class BitNetConfig(PretrainedConfig): + + model_type = 'bitnet' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + hidden_size: int = 2048, + num_hidden_layers: int = 24, + num_heads: int = 32, + num_kv_heads: Optional[int] = None, + window_size: Optional[int] = None, + rope_theta: Optional[float] = 10000., + max_position_embeddings: int = 2048, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + hidden_act: str = "swish", + initializer_range: float = 0.02, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-6, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + **kwargs, + ): + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.window_size = window_size + self.rope_theta = rope_theta + self.max_position_embeddings = max_position_embeddings + + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + + self.initializer_range = initializer_range + self.elementwise_affine = elementwise_affine + self.norm_eps = norm_eps + self.use_cache = use_cache + + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + super().__init__( + 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, + ) diff --git a/models/bitnet/modeling_bitnet.py b/models/bitnet/modeling_bitnet.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c597b5024755bad459bd0f9e91a8c4b737a951 --- /dev/null +++ b/models/bitnet/modeling_bitnet.py @@ -0,0 +1,397 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.utils.deprecation import deprecate_kwarg + +from fla.layers.bitattn import BitAttention +from fla.models.bitnet.configuration_bitnet import BitNetConfig +from fla.models.utils import Cache, FLAGenerationMixin +from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss, RMSNorm +from fla.modules.activations import swiglu +from fla.modules.fused_bitlinear import FusedBitLinear +from fla.modules.l2warp import l2_warp + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + +try: + from transformers.modeling_layers import GradientCheckpointingLayer +except ImportError: + from fla.models.modeling_layers import GradientCheckpointingLayer + +logger = logging.get_logger(__name__) + + +class BitNetMLP(nn.Module): + + def __init__( + self, + hidden_size: int, + hidden_ratio: Optional[int] = None, + intermediate_size: Optional[int] = None, + hidden_act: str = 'swish', + fuse_swiglu: bool = True + ) -> BitNetMLP: + super().__init__() + + self.hidden_size = hidden_size + # the final number of params is `hidden_ratio * hidden_size^2` + # `intermediate_size` is chosen to be a multiple of 256 closest to `2/3 * hidden_size * hidden_ratio` + if hidden_ratio is None: + hidden_ratio = 4 + if intermediate_size is None: + intermediate_size = int(hidden_size * hidden_ratio * 2 / 3) + intermediate_size = 256 * ((intermediate_size + 256 - 1) // 256) + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.fuse_swiglu = fuse_swiglu + + if hidden_act != 'swish': + raise ValueError(f'Unsupported hidden_act: {hidden_act}') + + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) + + def forward( + self, + x: torch.Tensor, + **kwargs: Unpack[Any] + ) -> torch.Tensor: + gate, y = self.gate_proj(x), self.up_proj(x) + return self.down_proj(swiglu(gate, y)) + + +class BitNetBlock(GradientCheckpointingLayer): + + def __init__(self, config: BitNetConfig, layer_idx: int): + super().__init__() + + self.config = config + self.layer_idx = layer_idx + + self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.attn = BitAttention( + hidden_size=config.hidden_size, + num_heads=config.num_heads, + num_kv_heads=config.num_kv_heads, + window_size=config.window_size, + rope_theta=config.rope_theta, + max_position_embeddings=config.max_position_embeddings, + layer_idx=layer_idx + ) + + self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.mlp = BitNetMLP( + hidden_size=config.hidden_size, + hidden_ratio=config.hidden_ratio, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + fuse_swiglu=config.fuse_swiglu + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + **kwargs: Unpack[Any] + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + + residual = hidden_states + hidden_states = self.attn_norm(hidden_states) + hidden_states, attentions, past_key_values = self.attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + if self.config.fuse_norm: + hidden_states, residual = self.mlp_norm(hidden_states, residual, True) + else: + hidden_states = residual + hidden_states + residual = hidden_states + hidden_states = self.mlp_norm(hidden_states) + hidden_states = self.mlp(hidden_states, **kwargs) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (attentions,) + + if use_cache: + outputs += (past_key_values,) + + return outputs + + +class BitNetPreTrainedModel(PreTrainedModel): + + config_class = BitNetConfig + base_model_prefix = 'model' + supports_gradient_checkpointing = True + _no_split_modules = ['BitNetBlock'] + _supports_cache_class = True + + def __init__(self, *inputs, **kwargs): + super().__init__(*inputs, **kwargs) + + def _init_weights( + self, + module: nn.Module, + rescale_prenorm_residual: bool = False, + num_residuals_per_layer: int = 2, + ): + if isinstance(module, (nn.Linear, FusedBitLinear, nn.Conv1d)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + elif hasattr(module, 'reset_parameters'): + module.reset_parameters() + + if rescale_prenorm_residual: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + p = None + if hasattr(module, 'o_proj'): + p = module.o_proj.weight + elif hasattr(module, 'down_proj'): + p = module.down_proj.weight + if p is not None: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) + # We need to reinit p since this code could be called multiple times + # Having just p *= scale would repeatedly scale it down + nn.init.kaiming_uniform_(p, a=math.sqrt(5)) + with torch.no_grad(): + p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers) + + +class BitNetModel(BitNetPreTrainedModel): + + def __init__( + self, + config: BitNetConfig + ) -> BitNetModel: + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([BitNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]) + self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + + self.gradient_checkpointing = False + + self.post_init() + + def get_input_embeddings(self): + return self.embeddings + + def set_input_embeddings(self, value): + self.embeddings = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + **kwargs: Unpack[Any] + ) -> Union[Tuple, CausalLMOutputWithPast]: + if output_attentions: + warnings.warn( + "`BitNetModel` does not support output attention weights now, so `output_attentions` is set to `False`." + ) + output_attentions = False + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is None and inputs_embeds is None: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if use_cache and not isinstance(past_key_values, Cache): + past_key_values = Cache.from_legacy_cache(past_key_values) + + if inputs_embeds is None: + inputs_embeds = self.embeddings(input_ids) + + # embed positions + hidden_states = inputs_embeds + + all_hidden_states = () if output_hidden_states else None + all_attns = () if output_attentions else None + next_cache = None + + for layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + layer_outputs = layer( + hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + **kwargs + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_cache = layer_outputs[2 if output_attentions else 1] + + if output_attentions: + all_attns += (layer_outputs[1],) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attns] if v is not None) + + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_attns + ) + + +class BitNetForCausalLM(BitNetPreTrainedModel, FLAGenerationMixin): + + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = BitNetModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.criterion = None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embeddings + + def set_input_embeddings(self, value): + self.model.embeddings = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + logits_to_keep: Optional[int] = 0, + **kwargs: Unpack[Any] + ) -> Union[Tuple, CausalLMOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs + ) + + hidden_states = outputs[0] + + logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:]) + + loss = None + if labels is not None: + if getattr(self, 'criterion', None) is None: + if self.config.fuse_linear_cross_entropy: + criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp) + elif self.config.fuse_cross_entropy: + criterion = FusedCrossEntropyLoss(inplace_backward=True) + else: + criterion = nn.CrossEntropyLoss() + else: + criterion = self.criterion + + labels = labels.to(hidden_states.device) + labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1) + if self.config.fuse_linear_cross_entropy: + loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias) + else: + loss = criterion(logits.view(labels.numel(), -1), labels.view(-1)) + loss = l2_warp(loss, logits) if self.config.use_l2warp else loss + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git a/models/comba/__init__.py b/models/comba/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f00fff672d21509ccfed25c918aacbf744947793 --- /dev/null +++ b/models/comba/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.comba.configuration_comba import CombaConfig +from fla.models.comba.modeling_comba import CombaForCausalLM, CombaModel + +AutoConfig.register(CombaConfig.model_type, CombaConfig, exist_ok=True) +AutoModel.register(CombaConfig, CombaModel, exist_ok=True) +AutoModelForCausalLM.register(CombaConfig, CombaForCausalLM, exist_ok=True) + +__all__ = ['CombaConfig', 'CombaForCausalLM', 'CombaModel'] diff --git a/models/comba/configuration_comba.py b/models/comba/configuration_comba.py new file mode 100644 index 0000000000000000000000000000000000000000..838fd0f8f56e800b9cd1b1624d3ab9677f1f1ffe --- /dev/null +++ b/models/comba/configuration_comba.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- + +import warnings +from typing import Dict, Optional + +from transformers.configuration_utils import PretrainedConfig + + +class CombaConfig(PretrainedConfig): + model_type = 'comba' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + attn_mode: str = "chunk", + hidden_size: int = 2048, + conv_size: int = 4, + head_dim: int = 256, + num_heads: int = 6, + num_v_heads: Optional[int] = None, + expand_v: float = 2.0, + use_output_gate: bool = True, + use_short_conv: bool = True, + use_output_correction: bool = True, + use_inner_decay: bool = True, + correction_factor: float = 1., + max_position_embeddings: int = 2048, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + hidden_act: str = "swish", + num_hidden_layers: int = 21, + norm_eps: float = 1e-6, + attn: Optional[Dict] = None, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + initializer_range: float = 0.02, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + **kwargs + ): + self.attn_mode = attn_mode + self.hidden_size = hidden_size + self.conv_size = conv_size + self.head_dim = head_dim + self.num_heads = num_heads + self.num_v_heads = num_v_heads + self.expand_v = expand_v + self.use_output_gate = use_output_gate + self.use_short_conv = use_short_conv + self.use_output_correction = use_output_correction + self.correction_factor = correction_factor + self.use_inner_decay = use_inner_decay + self.max_position_embeddings = max_position_embeddings + + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.num_hidden_layers = num_hidden_layers + self.norm_eps = norm_eps + self.attn = attn + self.use_cache = use_cache + self.initializer_range = initializer_range + + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + if attn is not None: + if not isinstance(attn, Dict): + raise ValueError("attn must be a dictionary") + if 'layers' not in attn: + raise ValueError("Layer indices must be provided to initialize hybrid attention layers") + if 'num_heads' not in attn: + raise ValueError("Number of heads must be provided to initialize hybrid attention layers") + attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads']) + attn['qkv_bias'] = attn.get('qkv_bias', False) + attn['window_size'] = attn.get('window_size', None) + attn['rope_theta'] = attn.get('rope_theta', 10000.) + + super().__init__( + 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, + ) diff --git a/models/comba/modeling_comba.py b/models/comba/modeling_comba.py new file mode 100644 index 0000000000000000000000000000000000000000..3738a760646f3596175863fbfc8c0386c6dedc55 --- /dev/null +++ b/models/comba/modeling_comba.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.utils.deprecation import deprecate_kwarg + +from fla.layers.attn import Attention +from fla.layers.comba import Comba +from fla.models.comba.configuration_comba import CombaConfig +from fla.models.utils import Cache, FLAGenerationMixin +from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss +from fla.modules import GatedMLP as CombaMLP +from fla.modules import RMSNorm +from fla.modules.l2warp import l2_warp + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + +try: + from transformers.modeling_layers import GradientCheckpointingLayer +except ImportError: + from fla.models.modeling_layers import GradientCheckpointingLayer + +logger = logging.get_logger(__name__) + + +class CombaBlock(GradientCheckpointingLayer): + + def __init__(self, config: CombaConfig, layer_idx: int): + super().__init__() + + self.config = config + self.layer_idx = layer_idx + + self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + if config.attn is not None and layer_idx in config.attn['layers']: + self.attn = Attention( + hidden_size=config.hidden_size, + num_heads=config.attn['num_heads'], + num_kv_heads=config.attn['num_kv_heads'], + qkv_bias=config.attn['qkv_bias'], + window_size=config.attn['window_size'], + rope_theta=config.attn['rope_theta'], + max_position_embeddings=config.max_position_embeddings, + layer_idx=layer_idx + ) + else: + self.attn = Comba( + mode=config.attn_mode, + hidden_size=config.hidden_size, + expand_v=config.expand_v, + head_dim=config.head_dim, + num_heads=config.num_heads, + num_v_heads=config.num_v_heads, + use_output_gate=config.use_output_gate, + use_short_conv=config.use_short_conv, + conv_size=config.conv_size, + norm_eps=config.norm_eps, + layer_idx=layer_idx + ) + self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.mlp = CombaMLP( + hidden_size=config.hidden_size, + hidden_ratio=config.hidden_ratio, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + fuse_swiglu=config.fuse_swiglu + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + residual = hidden_states + hidden_states = self.attn_norm(hidden_states) + hidden_states, attentions, past_key_values = self.attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + if self.config.fuse_norm: + hidden_states, residual = self.mlp_norm(hidden_states, residual, True) + else: + hidden_states = residual + hidden_states + residual = hidden_states + hidden_states = self.mlp_norm(hidden_states) + hidden_states = self.mlp(hidden_states, **kwargs) + hidden_states = residual + hidden_states + + outputs = (hidden_states, attentions, past_key_values) + + return outputs + + +class CombaPreTrainedModel(PreTrainedModel): + + config_class = CombaConfig + base_model_prefix = 'model' + supports_gradient_checkpointing = True + _no_split_modules = ['CombaBlock'] + _supports_cache_class = True + + def __init__(self, *inputs, **kwargs): + super().__init__(*inputs, **kwargs) + + def _init_weights( + self, + module: nn.Module, + prenorm_residual_strategy: Optional[str] = None, + num_residuals_per_layer: int = 2, + ): + if isinstance(module, Comba) and next(module.parameters()).device.type != 'meta': + with torch.no_grad(): + module.A_log.copy_(nn.init.uniform_(module.A_log, a=0, b=16).log()) + module.A_log._no_weight_decay = True + dt = torch.exp( + nn.init.uniform_(module.dt_bias) * (math.log(0.1) - math.log(0.001)) + math.log(0.001) + ).clamp(min=1e-4) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + module.dt_bias.copy_(inv_dt) + module.dt_bias._no_weight_decay = True + + elif isinstance(module, (nn.Linear, nn.Conv1d)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + elif hasattr(module, 'reset_parameters'): + module.reset_parameters() + + if prenorm_residual_strategy is not None: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + p = None + if hasattr(module, 'o_proj'): + p = module.o_proj.weight + elif hasattr(module, 'down_proj'): + p = module.down_proj.weight + if p is not None: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) + # We need to reinit p since this code could be called multiple times + # Having just p *= scale would repeatedly scale it down + if prenorm_residual_strategy == 'rescale': + nn.init.kaiming_uniform_(p, a=math.sqrt(5)) + with torch.no_grad(): + p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers) + elif prenorm_residual_strategy == 'zero': + nn.init.zeros_(p) + else: + raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}") + + +class CombaModel(CombaPreTrainedModel): + + def __init__(self, config: CombaConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([CombaBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]) + self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + + self.gradient_checkpointing = False + + self.post_init() + + def get_input_embeddings(self): + return self.embeddings + + def set_input_embeddings(self, value): + self.embeddings = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, # noqa + inputs_embeds: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, BaseModelOutputWithPast]: + if output_attentions: + warnings.warn("`CombaModel` does not `output_attentions` now, setting it to `False`.") + output_attentions = False + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + if input_ids is None and inputs_embeds is None: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embeddings(input_ids) + hidden_states = inputs_embeds + + if use_cache and not isinstance(past_key_values, Cache): + past_key_values = Cache.from_legacy_cache(past_key_values) + + all_hidden_states = () if output_hidden_states else None + all_attns = () if output_attentions else None + for layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + hidden_states, attentions, past_key_values = layer( + hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + + if output_attentions: + all_attns += (attentions,) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if not return_dict: + return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values, + hidden_states=all_hidden_states, + attentions=all_attns + ) + + +class CombaForCausalLM(CombaPreTrainedModel, FLAGenerationMixin): + + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = CombaModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.criterion = None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embeddings + + def set_input_embeddings(self, value): + self.model.embeddings = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + def generate(self, *args, **kwargs): + try: + return super().generate(*args, **kwargs) + except AttributeError as exception: + if 'past_key_values' in str(exception): + raise AttributeError( + f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, " + f"which is not supported for {self.__class__.__name__}. " + f"Try another generation strategy instead. " + f"For the available generation strategies, check this doc: " + f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies" + ) + else: + raise exception + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + logits_to_keep: Optional[int] = 0, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, CausalLMOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs + ) + + hidden_states = outputs[0] + + loss, logits = None, None + if not self.config.fuse_linear_cross_entropy or labels is None: + logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:]) + if labels is not None: + if getattr(self, 'criterion', None) is None: + if self.config.fuse_linear_cross_entropy: + criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp) + elif self.config.fuse_cross_entropy: + criterion = FusedCrossEntropyLoss(inplace_backward=True) + else: + criterion = nn.CrossEntropyLoss() + else: + criterion = self.criterion + labels = labels.to(hidden_states.device) + labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1) + if self.config.fuse_linear_cross_entropy: + loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias) + else: + loss = criterion(logits.view(labels.numel(), -1), labels.view(-1)) + loss = l2_warp(loss, logits) if self.config.use_l2warp else loss + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git a/models/delta_net/__init__.py b/models/delta_net/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd01a1c2892dab4a2745a602317dae57d7f28d --- /dev/null +++ b/models/delta_net/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.delta_net.configuration_delta_net import DeltaNetConfig +from fla.models.delta_net.modeling_delta_net import DeltaNetForCausalLM, DeltaNetModel + +AutoConfig.register(DeltaNetConfig.model_type, DeltaNetConfig, exist_ok=True) +AutoModel.register(DeltaNetConfig, DeltaNetModel, exist_ok=True) +AutoModelForCausalLM.register(DeltaNetConfig, DeltaNetForCausalLM, exist_ok=True) + +__all__ = ['DeltaNetConfig', 'DeltaNetForCausalLM', 'DeltaNetModel'] diff --git a/models/delta_net/configuration_delta_net.py b/models/delta_net/configuration_delta_net.py new file mode 100644 index 0000000000000000000000000000000000000000..2e0060f019f500a1a45b97ca869ab96f915bd1c7 --- /dev/null +++ b/models/delta_net/configuration_delta_net.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- + +import warnings +from typing import Dict, Optional + +from transformers.configuration_utils import PretrainedConfig + + +class DeltaNetConfig(PretrainedConfig): + + model_type = 'delta_net' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + attn_mode: str = "chunk", + hidden_size: int = 2048, + expand_k: float = 1.0, + expand_v: float = 1.0, + use_gate: bool = False, + use_short_conv: bool = True, + conv_size: int = 4, + use_beta: bool = True, + use_output_norm: bool = True, + num_heads: int = 16, + qk_norm: str = 'l2', + qk_activation: str = 'silu', + max_position_embeddings: int = 2048, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + hidden_act: str = "swish", + num_hidden_layers: int = 24, + norm_eps: float = 1e-6, + attn: Optional[Dict] = None, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + initializer_range: float = 0.02, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + **kwargs + ): + self.attn_mode = attn_mode + self.hidden_size = hidden_size + self.expand_k = expand_k + self.expand_v = expand_v + self.use_gate = use_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.use_beta = use_beta + self.use_output_norm = use_output_norm + self.num_heads = num_heads + self.qk_norm = qk_norm + self.qk_activation = qk_activation + self.max_position_embeddings = max_position_embeddings + + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.num_hidden_layers = num_hidden_layers + self.norm_eps = norm_eps + self.attn = attn + self.use_cache = use_cache + self.initializer_range = initializer_range + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + if attn is not None: + if not isinstance(attn, Dict): + raise ValueError("attn must be a dictionary") + if 'layers' not in attn: + raise ValueError("Layer indices must be provided to initialize hybrid attention layers") + if 'num_heads' not in attn: + raise ValueError("Number of heads must be provided to initialize hybrid attention layers") + attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads']) + attn['qkv_bias'] = attn.get('qkv_bias', False) + attn['window_size'] = attn.get('window_size', None) + attn['rope_theta'] = attn.get('rope_theta', 10000.) + + super().__init__( + 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, + ) diff --git a/models/delta_net/modeling_delta_net.py b/models/delta_net/modeling_delta_net.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4a0fbe7e026253ce52a4b3ecbf304522c974ae --- /dev/null +++ b/models/delta_net/modeling_delta_net.py @@ -0,0 +1,371 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.utils.deprecation import deprecate_kwarg + +from fla.layers.attn import Attention +from fla.layers.delta_net import DeltaNet +from fla.models.delta_net.configuration_delta_net import DeltaNetConfig +from fla.models.utils import Cache, FLAGenerationMixin +from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss +from fla.modules import GatedMLP as DeltaNetMLP +from fla.modules import RMSNorm +from fla.modules.l2warp import l2_warp + +try: + from transformers.modeling_layers import GradientCheckpointingLayer +except ImportError: + from fla.models.modeling_layers import GradientCheckpointingLayer + +logger = logging.get_logger(__name__) + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + +class DeltaNetBlock(GradientCheckpointingLayer): + + def __init__(self, config: DeltaNetConfig, layer_idx: int): + super().__init__() + + self.config = config + self.layer_idx = layer_idx + + self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + if config.attn is not None and layer_idx in config.attn['layers']: + self.attn = Attention( + hidden_size=config.hidden_size, + num_heads=config.attn['num_heads'], + num_kv_heads=config.attn['num_kv_heads'], + qkv_bias=config.attn['qkv_bias'], + window_size=config.attn['window_size'], + rope_theta=config.attn['rope_theta'], + max_position_embeddings=config.max_position_embeddings, + layer_idx=layer_idx + ) + else: + self.attn = DeltaNet( + mode=config.attn_mode, + hidden_size=config.hidden_size, + expand_k=config.expand_k, + expand_v=config.expand_v, + num_heads=config.num_heads, + use_gate=config.use_gate, + use_beta=config.use_beta, + use_short_conv=config.use_short_conv, + use_output_norm=config.use_output_norm, + conv_size=config.conv_size, + qk_norm=config.qk_norm, + qk_activation=config.qk_activation, + norm_eps=config.norm_eps, + layer_idx=layer_idx + ) + self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.mlp = DeltaNetMLP( + hidden_size=config.hidden_size, + hidden_ratio=config.hidden_ratio, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + fuse_swiglu=config.fuse_swiglu + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + residual = hidden_states + hidden_states = self.attn_norm(hidden_states) + hidden_states, attentions, past_key_values = self.attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + if self.config.fuse_norm: + hidden_states, residual = self.mlp_norm(hidden_states, residual, True) + else: + hidden_states = residual + hidden_states + residual = hidden_states + hidden_states = self.mlp_norm(hidden_states) + hidden_states = self.mlp(hidden_states, **kwargs) + hidden_states = residual + hidden_states + + outputs = (hidden_states, attentions, past_key_values) + + return outputs + + +class DeltaNetPreTrainedModel(PreTrainedModel): + + config_class = DeltaNetConfig + base_model_prefix = 'model' + supports_gradient_checkpointing = True + _no_split_modules = ['DeltaNetBlock'] + _supports_cache_class = True + + def __init__(self, *inputs, **kwargs): + super().__init__(*inputs, **kwargs) + + def _init_weights( + self, + module: nn.Module, + prenorm_residual_strategy: Optional[str] = None, + num_residuals_per_layer: int = 2, + ): + if isinstance(module, (nn.Linear, nn.Conv1d)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + elif hasattr(module, 'reset_parameters'): + module.reset_parameters() + + if prenorm_residual_strategy is not None: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + p = None + if hasattr(module, 'o_proj'): + p = module.o_proj.weight + elif hasattr(module, 'down_proj'): + p = module.down_proj.weight + if p is not None: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) + # We need to reinit p since this code could be called multiple times + # Having just p *= scale would repeatedly scale it down + if prenorm_residual_strategy == 'rescale': + nn.init.kaiming_uniform_(p, a=math.sqrt(5)) + with torch.no_grad(): + p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers) + elif prenorm_residual_strategy == 'zero': + nn.init.zeros_(p) + else: + raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}") + + +class DeltaNetModel(DeltaNetPreTrainedModel): + + def __init__(self, config: DeltaNetConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([DeltaNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]) + self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + + self.gradient_checkpointing = False + + self.post_init() + + def get_input_embeddings(self): + return self.embeddings + + def set_input_embeddings(self, value): + self.embeddings = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, # noqa + inputs_embeds: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, BaseModelOutputWithPast]: + if output_attentions: + warnings.warn("`DeltaNetModel` does not `output_attentions` now, setting it to `False`.") + output_attentions = False + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + if input_ids is None and inputs_embeds is None: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embeddings(input_ids) + hidden_states = inputs_embeds + + if use_cache and not isinstance(past_key_values, Cache): + past_key_values = Cache.from_legacy_cache(past_key_values) + + all_hidden_states = () if output_hidden_states else None + all_attns = () if output_attentions else None + for layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + hidden_states, attentions, past_key_values = layer( + hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + + if output_attentions: + all_attns += (attentions,) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if not return_dict: + return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values, + hidden_states=all_hidden_states, + attentions=all_attns + ) + + +class DeltaNetForCausalLM(DeltaNetPreTrainedModel, FLAGenerationMixin): + + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = DeltaNetModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.criterion = None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embeddings + + def set_input_embeddings(self, value): + self.model.embeddings = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + def generate(self, *args, **kwargs): + try: + return super().generate(*args, **kwargs) + except AttributeError as exception: + if 'past_key_values' in str(exception): + raise AttributeError( + f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, " + f"which is not supported for {self.__class__.__name__}. " + f"Try another generation strategy instead. " + f"For the available generation strategies, check this doc: " + f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies" + ) + else: + raise exception + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + logits_to_keep: Optional[int] = 0, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, CausalLMOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs + ) + + hidden_states = outputs[0] + + loss, logits = None, None + if not self.config.fuse_linear_cross_entropy or labels is None: + logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:]) + if labels is not None: + if getattr(self, 'criterion', None) is None: + if self.config.fuse_linear_cross_entropy: + criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp) + elif self.config.fuse_cross_entropy: + criterion = FusedCrossEntropyLoss(inplace_backward=True) + else: + criterion = nn.CrossEntropyLoss() + else: + criterion = self.criterion + labels = labels.to(hidden_states.device) + labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1) + if self.config.fuse_linear_cross_entropy: + loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias) + else: + loss = criterion(logits.view(labels.numel(), -1), labels.view(-1)) + loss = l2_warp(loss, logits) if self.config.use_l2warp else loss + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git a/models/deltaformer/__init__.py b/models/deltaformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18ed426900d1467bcbdbf7fc5fa6f2694d9f50d1 --- /dev/null +++ b/models/deltaformer/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.deltaformer.configuration_deltaformer import DeltaFormerConfig +from fla.models.deltaformer.modeling_deltaformer import DeltaFormerForCausalLM, DeltaFormerModel + +AutoConfig.register(DeltaFormerConfig.model_type, DeltaFormerConfig, exist_ok=True) +AutoModel.register(DeltaFormerConfig, DeltaFormerModel, exist_ok=True) +AutoModelForCausalLM.register(DeltaFormerConfig, DeltaFormerForCausalLM, exist_ok=True) + +__all__ = ['DeltaFormerConfig', 'DeltaFormerForCausalLM', 'DeltaFormerModel'] diff --git a/models/deltaformer/configuration_deltaformer.py b/models/deltaformer/configuration_deltaformer.py new file mode 100644 index 0000000000000000000000000000000000000000..bcba40d7c5f0e69f0f1eb667642f61c32c8a083c --- /dev/null +++ b/models/deltaformer/configuration_deltaformer.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import warnings +from typing import Dict, Optional + +from transformers.configuration_utils import PretrainedConfig + + +class DeltaFormerConfig(PretrainedConfig): + model_type = 'deltaformer' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + hidden_size: int = 2048, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + num_hidden_layers: int = 24, + num_heads: int = 8, + num_kv_heads: Optional[int] = None, + attn_mode: str = "chunk", + hidden_act: str = "swish", + max_position_embeddings: int = 2048, + elementwise_affine: Optional[bool] = True, + norm_eps: float = 1e-6, + qkv_bias: bool = False, + qk_norm: bool = False, + rope_theta: float = 10000., + rope_max_position_embeddings: Optional[int] = None, + attn: Optional[Dict] = None, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + initializer_range: float = 0.02, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + output_attentions: bool = False, + output_hidden_states: bool = False, + **kwargs + ): + self.hidden_size = hidden_size + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.attn_mode = attn_mode + self.hidden_act = hidden_act + self.max_position_embeddings = max_position_embeddings + self.elementwise_affine = elementwise_affine + self.norm_eps = norm_eps + self.qkv_bias = qkv_bias + self.qk_norm = qk_norm + self.rope_theta = rope_theta + self.rope_max_position_embeddings = rope_max_position_embeddings + self.attn = attn + self.use_cache = use_cache + self.initializer_range = initializer_range + + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + + self.output_attentions = output_attentions + self.output_hidden_states = output_hidden_states + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + if attn is not None: + if not isinstance(attn, Dict): + raise ValueError("attn must be a dictionary") + if 'layers' not in attn: + raise ValueError("Layer indices must be provided to initialize hybrid attention layers") + if 'num_heads' not in attn: + raise ValueError("Number of heads must be provided to initialize hybrid attention layers") + attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads']) + attn['qkv_bias'] = attn.get('qkv_bias', False) + attn['window_size'] = attn.get('window_size', None) + attn['rope_theta'] = attn.get('rope_theta', 10000.) + + super().__init__( + 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, + ) diff --git a/models/deltaformer/modeling_deltaformer.py b/models/deltaformer/modeling_deltaformer.py new file mode 100644 index 0000000000000000000000000000000000000000..624a6b640609f8d4fdc864329db2ee3a1d88dded --- /dev/null +++ b/models/deltaformer/modeling_deltaformer.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.utils.deprecation import deprecate_kwarg + +from fla.layers.deltaformer import DeltaFormerAttention +from fla.models.deltaformer.configuration_deltaformer import DeltaFormerConfig +from fla.models.utils import Cache, FLAGenerationMixin +from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss +from fla.modules import GatedMLP as DeltaFormerMLP +from fla.modules import RMSNorm +from fla.modules.l2warp import l2_warp + +try: + from transformers.modeling_layers import GradientCheckpointingLayer +except ImportError: + from fla.models.modeling_layers import GradientCheckpointingLayer + +logger = logging.get_logger(__name__) + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + +class DeltaFormerBlock(GradientCheckpointingLayer): + + def __init__(self, config: DeltaFormerConfig, layer_idx: int): + super().__init__() + + self.config = config + self.layer_idx = layer_idx + + self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.attn = DeltaFormerAttention( + hidden_size=config.hidden_size, + num_heads=config.num_heads, + num_kv_heads=config.num_kv_heads, + qkv_bias=config.qkv_bias, + qk_norm=config.qk_norm, + rope_theta=config.rope_theta, + max_position_embeddings=config.rope_max_position_embeddings, + layer_idx=layer_idx, + ) + self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.mlp = DeltaFormerMLP( + hidden_size=config.hidden_size, + hidden_ratio=config.hidden_ratio, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + fuse_swiglu=config.fuse_swiglu + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + residual = hidden_states + hidden_states = self.attn_norm(hidden_states) + hidden_states, _, past_key_values = self.attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs, + ) + if self.config.fuse_norm: + hidden_states, residual = self.mlp_norm(hidden_states, residual, True) + else: + hidden_states = residual + hidden_states + residual = hidden_states + hidden_states = self.mlp_norm(hidden_states) + hidden_states = self.mlp(hidden_states, **kwargs) + hidden_states = residual + hidden_states + outputs = (hidden_states, None, past_key_values) + return outputs + + +class DeltaFormerPreTrainedModel(PreTrainedModel): + + config_class = DeltaFormerConfig + base_model_prefix = 'model' + supports_gradient_checkpointing = True + _no_split_modules = ['DeltaFormerBlock'] + _supports_cache_class = True + + def __init__(self, *inputs, **kwargs): + super().__init__(*inputs, **kwargs) + + def _init_weights( + self, + module: nn.Module, + prenorm_residual_strategy: Optional[str] = None, + num_residuals_per_layer: int = 2, + ): + if isinstance(module, (nn.Linear, nn.Conv1d)): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + elif hasattr(module, 'reset_parameters'): + module.reset_parameters() + + +class DeltaFormerModel(DeltaFormerPreTrainedModel): + + def __init__(self, config: DeltaFormerConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([DeltaFormerBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]) + self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + + self.gradient_checkpointing = False + + self.post_init() + + def get_input_embeddings(self): + return self.embeddings + + def set_input_embeddings(self, value): + self.embeddings = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, # noqa + inputs_embeds: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, BaseModelOutputWithPast]: + if output_attentions: + warnings.warn( + "`DeltaFormerModel` does not support output attention weights now, " + "so `output_attentions` is set to `False`." + ) + output_attentions = False + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + if input_ids is None and inputs_embeds is None: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embeddings(input_ids) + hidden_states = inputs_embeds + + if use_cache and not isinstance(past_key_values, Cache): + past_key_values = Cache.from_legacy_cache(past_key_values) + + all_hidden_states = () if output_hidden_states else None + all_attns = () if output_attentions else None + for layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + hidden_states, attentions, past_key_values = layer( + hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + + if output_attentions: + all_attns += (attentions,) + + hidden_states = self.norm(hidden_states) + + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if not return_dict: + return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values, + hidden_states=all_hidden_states, + attentions=all_attns + ) + + +class DeltaFormerForCausalLM(DeltaFormerPreTrainedModel, FLAGenerationMixin): + + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config: DeltaFormerConfig): + super().__init__(config) + self.model = DeltaFormerModel(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.criterion = None + + self.post_init() + + def get_input_embeddings(self): + return self.model.get_input_embeddings() + + def set_input_embeddings(self, value): + self.model.set_input_embeddings(value) + + def tie_weights(self): + self._tie_or_clone_weights(self.lm_head, self.get_input_embeddings()) + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + def generate(self, *args, **kwargs): + try: + return super().generate(*args, **kwargs) + except AttributeError as exception: + if 'past_key_values' in str(exception): + raise AttributeError( + f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, " + f"which is not supported for {self.__class__.__name__}. " + f"Try another generation strategy instead. " + f"For the available generation strategies, check this doc: " + f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies" + ) + else: + raise exception + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + labels: Optional[torch.LongTensor] = None, + logits_to_keep: Optional[int] = 0, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, CausalLMOutputWithPast]: + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs + ) + + hidden_states = outputs[0] + # For fused linear cross-entropy we do not materialize logits for the full sequence + logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:]) + + loss = None + if labels is not None: + if getattr(self, 'criterion', None) is None: + if self.config.fuse_linear_cross_entropy: + criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp) + elif self.config.fuse_cross_entropy: + criterion = FusedCrossEntropyLoss(inplace_backward=True) + else: + criterion = nn.CrossEntropyLoss() + else: + criterion = self.criterion + labels = labels.to(hidden_states.device) + labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1) + if self.config.fuse_linear_cross_entropy: + loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias) + else: + loss = criterion(logits.view(labels.numel(), -1), labels.view(-1)) + loss = l2_warp(loss, logits) if self.config.use_l2warp else loss + + if not return_dict: + output = (logits,) + outputs[1:] + return ((loss,) + output) if loss is not None else output + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git a/models/forgetting_transformer/__init__.py b/models/forgetting_transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3fb36724b1a7658bd51da7cb46f4c391ed1f509 --- /dev/null +++ b/models/forgetting_transformer/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.forgetting_transformer.configuration_forgetting_transformer import ForgettingTransformerConfig +from fla.models.forgetting_transformer.modeling_forgetting_transformer import ( + ForgettingTransformerForCausalLM, + ForgettingTransformerModel +) + +AutoConfig.register(ForgettingTransformerConfig.model_type, ForgettingTransformerConfig, exist_ok=True) +AutoModel.register(ForgettingTransformerConfig, ForgettingTransformerModel, exist_ok=True) +AutoModelForCausalLM.register(ForgettingTransformerConfig, ForgettingTransformerForCausalLM, exist_ok=True) + + +__all__ = ['ForgettingTransformerConfig', 'ForgettingTransformerForCausalLM', 'ForgettingTransformerModel'] diff --git a/models/forgetting_transformer/modeling_forgetting_transformer.py b/models/forgetting_transformer/modeling_forgetting_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..3e01e31a75a63480fcadf522fa2cc7bfe438e295 --- /dev/null +++ b/models/forgetting_transformer/modeling_forgetting_transformer.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.utils.deprecation import deprecate_kwarg + +from fla.layers.forgetting_attn import ForgettingAttention +from fla.models.forgetting_transformer.configuration_forgetting_transformer import ForgettingTransformerConfig +from fla.models.utils import Cache, FLAGenerationMixin +from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss +from fla.modules import GatedMLP as ForgettingTransformerMLP +from fla.modules import RMSNorm +from fla.modules.l2warp import l2_warp + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + +try: + from transformers.modeling_layers import GradientCheckpointingLayer +except ImportError: + from fla.models.modeling_layers import GradientCheckpointingLayer + +logger = logging.get_logger(__name__) + + +class ForgettingTransformerBlock(GradientCheckpointingLayer): + + def __init__(self, config: ForgettingTransformerConfig, layer_idx: int): + super().__init__() + + self.config = config + self.layer_idx = layer_idx + + self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.attn = ForgettingAttention( + hidden_size=config.hidden_size, + num_heads=config.num_heads, + num_kv_heads=config.num_kv_heads, + qkv_bias=config.qkv_bias, + qk_norm=config.qk_norm, + window_size=config.window_size, + use_output_gate=config.use_output_gate, + layer_idx=layer_idx + ) + + self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.mlp = ForgettingTransformerMLP( + hidden_size=config.hidden_size, + hidden_ratio=config.hidden_ratio, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + fuse_swiglu=config.fuse_swiglu + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + **kwargs: Unpack[Any] + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + + residual = hidden_states + hidden_states = self.attn_norm(hidden_states) + hidden_states, attentions, past_key_values = self.attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + if self.config.fuse_norm: + hidden_states, residual = self.mlp_norm(hidden_states, residual, True) + else: + hidden_states = residual + hidden_states + residual = hidden_states + hidden_states = self.mlp_norm(hidden_states) + hidden_states = self.mlp(hidden_states, **kwargs) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (attentions,) + + if use_cache: + outputs += (past_key_values,) + + return outputs + + +class ForgettingTransformerPreTrainedModel(PreTrainedModel): + + config_class = ForgettingTransformerConfig + base_model_prefix = 'model' + supports_gradient_checkpointing = True + _no_split_modules = ['ForgettingTransformerBlock'] + _supports_cache_class = True + + def __init__(self, *inputs, **kwargs): + super().__init__(*inputs, **kwargs) + + def _init_weights( + self, + module: nn.Module, + rescale_prenorm_residual: bool = False, + num_residuals_per_layer: int = 2, + ): + if isinstance(module, (nn.Linear, nn.Conv1d)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + elif hasattr(module, 'reset_parameters'): + module.reset_parameters() + + if rescale_prenorm_residual: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + p = None + if hasattr(module, 'o_proj'): + p = module.o_proj.weight + elif hasattr(module, 'down_proj'): + p = module.down_proj.weight + if p is not None: + # Special Scaled Initialization --> There are 2 Layer Norms per ForgettingTransformer Block + # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) + # We need to reinit p since this code could be called multiple times + # Having just p *= scale would repeatedly scale it down + nn.init.kaiming_uniform_(p, a=math.sqrt(5)) + with torch.no_grad(): + p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers) + + +class ForgettingTransformerModel(ForgettingTransformerPreTrainedModel): + + def __init__( + self, + config: ForgettingTransformerConfig + ) -> ForgettingTransformerModel: + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([ + ForgettingTransformerBlock(config, layer_idx) + for layer_idx in range(config.num_hidden_layers) + ]) + self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + + self.gradient_checkpointing = False + + self.post_init() + + def get_input_embeddings(self): + return self.embeddings + + def set_input_embeddings(self, value): + self.embeddings = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + **kwargs: Unpack[Any] + ) -> Union[Tuple, CausalLMOutputWithPast]: + if output_attentions: + warnings.warn( + "`ForgettingTransformerModel` does not support output attention weights now, " + "so `output_attentions` is set to `False`." + ) + output_attentions = False + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is None and inputs_embeds is None: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if use_cache and not isinstance(past_key_values, Cache): + past_key_values = Cache.from_legacy_cache(past_key_values) + + if inputs_embeds is None: + inputs_embeds = self.embeddings(input_ids) + + # embed positions + hidden_states = inputs_embeds + + all_hidden_states = () if output_hidden_states else None + all_attns = () if output_attentions else None + next_cache = None + + for layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + layer_outputs = layer( + hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + **kwargs + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_cache = layer_outputs[2 if output_attentions else 1] + + if output_attentions: + all_attns += (layer_outputs[1],) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attns] if v is not None) + + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_attns + ) + + +class ForgettingTransformerForCausalLM(ForgettingTransformerPreTrainedModel, FLAGenerationMixin): + + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = ForgettingTransformerModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.criterion = None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embeddings + + def set_input_embeddings(self, value): + self.model.embeddings = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + logits_to_keep: Optional[int] = 0, + **kwargs: Unpack[Any] + ) -> Union[Tuple, CausalLMOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs + ) + + hidden_states = outputs[0] + + logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:]) + + loss = None + if labels is not None: + if getattr(self, 'criterion', None) is None: + if self.config.fuse_linear_cross_entropy: + criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp) + elif self.config.fuse_cross_entropy: + criterion = FusedCrossEntropyLoss(inplace_backward=True) + else: + criterion = nn.CrossEntropyLoss() + else: + criterion = self.criterion + # Enable model parallelism + labels = labels.to(hidden_states.device) + labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1) + if self.config.fuse_linear_cross_entropy: + loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias) + else: + loss = criterion(logits.view(labels.numel(), -1), labels.view(-1)) + loss = l2_warp(loss, logits) if self.config.use_l2warp else loss + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git a/models/gated_deltanet/configuration_gated_deltanet.py b/models/gated_deltanet/configuration_gated_deltanet.py new file mode 100644 index 0000000000000000000000000000000000000000..566d3a97f2fbb9769c0dc9f7f7a51a0b1bf6e036 --- /dev/null +++ b/models/gated_deltanet/configuration_gated_deltanet.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- + +import warnings +from typing import Dict, Optional + +from transformers.configuration_utils import PretrainedConfig + +class GatedDeltaNetConfig(PretrainedConfig): + model_type = 'gated_deltanet' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + attn_mode: str = "chunk", + hidden_size: int = 2048, + expand_v: float = 2.0, + use_gate: bool = True, + use_short_conv: bool = True, + allow_neg_eigval: bool = False, + conv_size: int = 4, + head_dim: int = 256, + num_heads: int = 6, + num_v_heads: Optional[int] = None, + max_position_embeddings: int = 2048, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + hidden_act: str = "swish", + num_hidden_layers: int = 21, + norm_eps: float = 1e-6, + attn: Optional[Dict] = None, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + initializer_range: float = 0.02, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + **kwargs + ): + self.attn_mode = attn_mode + self.hidden_size = hidden_size + self.expand_v = expand_v + self.use_gate = use_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.head_dim = head_dim + self.num_heads = num_heads + self.num_v_heads = num_v_heads + self.max_position_embeddings = max_position_embeddings + + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.num_hidden_layers = num_hidden_layers + self.norm_eps = norm_eps + self.attn = attn + self.use_cache = use_cache + self.initializer_range = initializer_range + + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + self.allow_neg_eigval = allow_neg_eigval + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + if attn is not None: + if not isinstance(attn, Dict): + raise ValueError("attn must be a dictionary") + if 'layers' not in attn: + raise ValueError("Layer indices must be provided to initialize hybrid attention layers") + if 'num_heads' not in attn: + raise ValueError("Number of heads must be provided to initialize hybrid attention layers") + attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads']) + attn['qkv_bias'] = attn.get('qkv_bias', False) + attn['window_size'] = attn.get('window_size', None) + attn['rope_theta'] = attn.get('rope_theta', 10000.) + + super().__init__( + 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, + ) diff --git a/models/gated_deltanet/modeling_gated_deltanet.py b/models/gated_deltanet/modeling_gated_deltanet.py new file mode 100644 index 0000000000000000000000000000000000000000..8168e12574ec8c527a38ee93378822fae8a22ba1 --- /dev/null +++ b/models/gated_deltanet/modeling_gated_deltanet.py @@ -0,0 +1,382 @@ +# -*- coding: utf-8 -*- + +from __future__ import annotations + +import math +import warnings +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import logging +from transformers.utils.deprecation import deprecate_kwarg + +from fla.layers.attn import Attention +from fla.layers.gated_deltanet import GatedDeltaNet +from fla.models.gated_deltanet.configuration_gated_deltanet import GatedDeltaNetConfig +from fla.models.utils import Cache, FLAGenerationMixin +from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss +from fla.modules import GatedMLP as GatedDeltaNetMLP +from fla.modules import RMSNorm +from fla.modules.l2warp import l2_warp + +if TYPE_CHECKING: + from transformers.processing_utils import Unpack + + +try: + from transformers.modeling_layers import GradientCheckpointingLayer +except ImportError: + from fla.models.modeling_layers import GradientCheckpointingLayer + +logger = logging.get_logger(__name__) + + +class GatedDeltaNetBlock(GradientCheckpointingLayer): + + def __init__(self, config: GatedDeltaNetConfig, layer_idx: int): + super().__init__() + + self.config = config + self.layer_idx = layer_idx + + self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + if config.attn is not None and layer_idx in config.attn['layers']: + self.attn = Attention( + hidden_size=config.hidden_size, + num_heads=config.attn['num_heads'], + num_kv_heads=config.attn['num_kv_heads'], + qkv_bias=config.attn['qkv_bias'], + window_size=config.attn['window_size'], + rope_theta=config.attn['rope_theta'], + max_position_embeddings=config.max_position_embeddings, + layer_idx=layer_idx + ) + else: + self.attn = GatedDeltaNet( + mode=config.attn_mode, + hidden_size=config.hidden_size, + expand_v=config.expand_v, + head_dim=config.head_dim, + num_heads=config.num_heads, + num_v_heads=config.num_v_heads, + use_gate=config.use_gate, + use_short_conv=config.use_short_conv, + allow_neg_eigval=config.allow_neg_eigval, + conv_size=config.conv_size, + norm_eps=config.norm_eps, + layer_idx=layer_idx + ) + self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + self.mlp = GatedDeltaNetMLP( + hidden_size=config.hidden_size, + hidden_ratio=config.hidden_ratio, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + fuse_swiglu=config.fuse_swiglu + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs: Unpack[Dict] + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + residual = hidden_states + hidden_states = self.attn_norm(hidden_states) + hidden_states, attentions, past_key_values = self.attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + if self.config.fuse_norm: + hidden_states, residual = self.mlp_norm(hidden_states, residual, True) + else: + hidden_states = residual + hidden_states + residual = hidden_states + hidden_states = self.mlp_norm(hidden_states) + hidden_states = self.mlp(hidden_states, **kwargs) + hidden_states = residual + hidden_states + + outputs = (hidden_states, attentions, past_key_values) + + return outputs + + +class GatedDeltaNetPreTrainedModel(PreTrainedModel): + + config_class = GatedDeltaNetConfig + base_model_prefix = 'model' + supports_gradient_checkpointing = True + _no_split_modules = ['GatedDeltaNetBlock'] + _supports_cache_class = True + + def __init__(self, *inputs, **kwargs): + super().__init__(*inputs, **kwargs) + + def _init_weights( + self, + module: nn.Module, + prenorm_residual_strategy: Optional[str] = None, + num_residuals_per_layer: int = 2, + ): + if isinstance(module, GatedDeltaNet) and next(module.parameters()).device.type != 'meta': + with torch.no_grad(): + module.A_log.copy_(nn.init.uniform_(module.A_log, a=0, b=16).log()) + module.A_log._no_weight_decay = True + dt = torch.exp( + nn.init.uniform_(module.dt_bias) * (math.log(0.1) - math.log(0.001)) + math.log(0.001) + ).clamp(min=1e-4) + # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 + inv_dt = dt + torch.log(-torch.expm1(-dt)) + module.dt_bias.copy_(inv_dt) + module.dt_bias._no_weight_decay = True + + elif isinstance(module, (nn.Linear, nn.Conv1d)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + elif hasattr(module, 'reset_parameters'): + module.reset_parameters() + + if prenorm_residual_strategy is not None: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + p = None + if hasattr(module, 'o_proj'): + p = module.o_proj.weight + elif hasattr(module, 'down_proj'): + p = module.down_proj.weight + if p is not None: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + # Following Pytorch init, except scale by 1/sqrt(2 * n_layer) + # We need to reinit p since this code could be called multiple times + # Having just p *= scale would repeatedly scale it down + if prenorm_residual_strategy == 'rescale': + nn.init.kaiming_uniform_(p, a=math.sqrt(5)) + with torch.no_grad(): + p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers) + elif prenorm_residual_strategy == 'zero': + nn.init.zeros_(p) + else: + raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}") + + +class GatedDeltaNetModel(GatedDeltaNetPreTrainedModel): + + def __init__(self, config: GatedDeltaNetConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([GatedDeltaNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]) + self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps) + + self.gradient_checkpointing = False + + self.post_init() + + def get_input_embeddings(self): + return self.embeddings + + def set_input_embeddings(self, value): + self.embeddings = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, # noqa + inputs_embeds: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, BaseModelOutputWithPast]: + if output_attentions: + warnings.warn("`GatedDeltaNetModel` does not `output_attentions` now, setting it to `False`.") + output_attentions = False + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + if input_ids is None and inputs_embeds is None: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embeddings(input_ids) + hidden_states = inputs_embeds + + if use_cache and not isinstance(past_key_values, Cache): + past_key_values = Cache.from_legacy_cache(past_key_values) + + all_hidden_states = () if output_hidden_states else None + all_attns = () if output_attentions else None + for layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + hidden_states, attentions, past_key_values = layer( + hidden_states, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs + ) + + if output_attentions: + all_attns += (attentions,) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if not return_dict: + return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values, + hidden_states=all_hidden_states, + attentions=all_attns + ) + + +class GatedDeltaNetForCausalLM(GatedDeltaNetPreTrainedModel, FLAGenerationMixin): + + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = GatedDeltaNetModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.criterion = None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embeddings + + def set_input_embeddings(self, value): + self.model.embeddings = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + def generate(self, *args, **kwargs): + try: + return super().generate(*args, **kwargs) + except AttributeError as exception: + if 'past_key_values' in str(exception): + raise AttributeError( + f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, " + f"which is not supported for {self.__class__.__name__}. " + f"Try another generation strategy instead. " + f"For the available generation strategies, check this doc: " + f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies" + ) + else: + raise exception + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + logits_to_keep: Optional[int] = 0, + **kwargs: Unpack[Dict] + ) -> Union[Tuple, CausalLMOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs + ) + + hidden_states = outputs[0] + + loss, logits = None, None + if not self.config.fuse_linear_cross_entropy or labels is None: + logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:]) + if labels is not None: + if getattr(self, 'criterion', None) is None: + if self.config.fuse_linear_cross_entropy: + criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp) + elif self.config.fuse_cross_entropy: + criterion = FusedCrossEntropyLoss(inplace_backward=True) + else: + criterion = nn.CrossEntropyLoss() + else: + criterion = self.criterion + labels = labels.to(hidden_states.device) + labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1) + if self.config.fuse_linear_cross_entropy: + loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias) + else: + loss = criterion(logits.view(labels.numel(), -1), labels.view(-1)) + loss = l2_warp(loss, logits) if self.config.use_l2warp else loss + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git a/models/gated_deltaproduct/__init__.py b/models/gated_deltaproduct/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c2e1a9f29bd23d7d39b4698e0bec0d9b1115b00 --- /dev/null +++ b/models/gated_deltaproduct/__init__.py @@ -0,0 +1,14 @@ +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.gated_deltaproduct.configuration_gated_deltaproduct import GatedDeltaProductConfig +from fla.models.gated_deltaproduct.modeling_gated_deltaproduct import GatedDeltaProductForCausalLM, GatedDeltaProductModel + +AutoConfig.register(GatedDeltaProductConfig.model_type, GatedDeltaProductConfig, exist_ok=True) +AutoModel.register(GatedDeltaProductConfig, GatedDeltaProductModel, exist_ok=True) +AutoModelForCausalLM.register(GatedDeltaProductConfig, GatedDeltaProductForCausalLM, exist_ok=True) + +__all__ = [ + "GatedDeltaProductConfig", + "GatedDeltaProductForCausalLM", + "GatedDeltaProductModel", +] diff --git a/models/gated_deltaproduct/configuration_gated_deltaproduct.py b/models/gated_deltaproduct/configuration_gated_deltaproduct.py new file mode 100644 index 0000000000000000000000000000000000000000..d13a35474a9a75065a70727090ae191ff33236dc --- /dev/null +++ b/models/gated_deltaproduct/configuration_gated_deltaproduct.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- + +import warnings +from typing import Dict, Optional + +from transformers.configuration_utils import PretrainedConfig + + +class GatedDeltaProductConfig(PretrainedConfig): + model_type = 'gated_deltaproduct' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + attn_mode: str = "chunk", + conv_size: int = 4, + head_dim: int = 256, + num_heads: int = 6, + hidden_size: int = 2048, + expand_v: float = 2.0, + use_output_gate: bool = True, + use_short_conv: bool = True, + max_position_embeddings: int = 2048, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + hidden_act: str = "swish", + num_hidden_layers: int = 21, + norm_eps: float = 1e-6, + attn: Optional[Dict] = None, + use_cache: bool = True, + pad_token_id: int = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + initializer_range: float = 0.02, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + use_forget_gate: bool = False, + allow_neg_eigval: bool = False, + num_householder: int = 1, + **kwargs, + ): + self.attn_mode = attn_mode + self.conv_size = conv_size + self.head_dim = head_dim + self.num_heads = num_heads + self.hidden_size = hidden_size + self.expand_v = expand_v + self.use_output_gate = use_output_gate + self.use_short_conv = use_short_conv + self.max_position_embeddings = max_position_embeddings + + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.num_hidden_layers = num_hidden_layers + self.norm_eps = norm_eps + self.attn = attn + self.use_cache = use_cache + self.initializer_range = initializer_range + + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + # DeltaProduct specific + self.allow_neg_eigval = allow_neg_eigval + self.num_householder = num_householder + self.use_forget_gate = use_forget_gate + + if attn is not None: + if not isinstance(attn, Dict): + raise ValueError("attn must be a dictionary") + if 'layers' not in attn: + raise ValueError("Layer indices must be provided to initialize hybrid attention layers") + if 'num_heads' not in attn: + raise ValueError("Number of heads must be provided to initialize hybrid attention layers") + attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads']) + attn['qkv_bias'] = attn.get('qkv_bias', False) + attn['window_size'] = attn.get('window_size', None) + attn['rope_theta'] = attn.get('rope_theta', 10000.) + + super().__init__( + 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, + ) diff --git a/models/gka_attn/configuration_gka_attn.py b/models/gka_attn/configuration_gka_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..32f09ae3b520b07d7b9ed1cec0cc39287aaf43b8 --- /dev/null +++ b/models/gka_attn/configuration_gka_attn.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- + +import warnings +from typing import Dict, Optional + +from transformers.configuration_utils import PretrainedConfig + + +class GKAAttentionConfig(PretrainedConfig): + model_type = 'gka_attn' + keys_to_ignore_at_inference = ['past_key_values'] + + def __init__( + self, + attn_mode: str = "chunk", + hidden_size: int = 2048, + use_output_gate: bool = False, + use_short_conv: bool = True, + conv_size: int = 4, + num_heads: int = 16, + head_dim: int = 128, + lambda_lower_bound: float = 0.25, + max_position_embeddings: int = 2048, + hidden_ratio: Optional[int] = 4, + intermediate_size: Optional[int] = None, + hidden_act: str = "swish", + num_hidden_layers: int = 24, + norm_eps: float = 1e-6, + attn: Optional[Dict] = None, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: int = 1, + eos_token_id: int = 2, + tie_word_embeddings: bool = False, + initializer_range: float = 0.02, + fuse_norm: bool = True, + fuse_swiglu: bool = True, + fuse_cross_entropy: bool = True, + fuse_linear_cross_entropy: bool = False, + use_l2warp: bool = False, + vocab_size: int = 32000, + max_cg_step_training: int = 30, + max_cg_step_decoding: int = 30, + **kwargs + ): + self.attn_mode = attn_mode + self.hidden_size = hidden_size + self.use_output_gate = use_output_gate + self.use_short_conv = use_short_conv + self.conv_size = conv_size + self.num_heads = num_heads + self.head_dim = head_dim + self.max_position_embeddings = max_position_embeddings + + self.hidden_ratio = hidden_ratio + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.num_hidden_layers = num_hidden_layers + self.norm_eps = norm_eps + self.attn = attn + self.use_cache = use_cache + self.initializer_range = initializer_range + self.lambda_lower_bound = lambda_lower_bound + + self.fuse_norm = fuse_norm + self.fuse_swiglu = fuse_swiglu + self.fuse_cross_entropy = fuse_cross_entropy + self.fuse_linear_cross_entropy = fuse_linear_cross_entropy + self.use_l2warp = use_l2warp + self.vocab_size = vocab_size + self.max_cg_step_training = max_cg_step_training + self.max_cg_step_decoding = max_cg_step_decoding + + if fuse_cross_entropy and fuse_linear_cross_entropy: + raise ValueError( + "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time." + ) + if fuse_linear_cross_entropy: + warnings.warn( + "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency " + "at the potential cost of reduced precision. " + "If you observe issues like loss divergence, consider disabling this setting." + ) + + if attn is not None: + if not isinstance(attn, Dict): + raise ValueError("attn must be a dictionary") + if 'layers' not in attn: + raise ValueError("Layer indices must be provided to initialize hybrid attention layers") + if 'num_heads' not in attn: + raise ValueError("Number of heads must be provided to initialize hybrid attention layers") + attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads']) + attn['qkv_bias'] = attn.get('qkv_bias', False) + attn['window_size'] = attn.get('window_size', None) + attn['rope_theta'] = attn.get('rope_theta', 10000.) + + super().__init__( + 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, + ) diff --git a/models/gka_net/__init__.py b/models/gka_net/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e02a3effab9b5181496f4dda2b2cb2c05e04272 --- /dev/null +++ b/models/gka_net/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from .configuration_gka_net import GKANetConfig +from .modeling_gka_net import GKANetForCausalLM, GKANetModel + +AutoConfig.register(GKANetConfig.model_type, GKANetConfig, exist_ok=True) +AutoModel.register(GKANetConfig, GKANetModel, exist_ok=True) +AutoModelForCausalLM.register(GKANetConfig, GKANetForCausalLM, exist_ok=True) + +__all__ = ['GKANetConfig', 'GKANetForCausalLM', 'GKANetModel'] diff --git a/models/gsa/__init__.py b/models/gsa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7309aca762ee67cd62f0fa31acc4d4538c2bf119 --- /dev/null +++ b/models/gsa/__init__.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +from transformers import AutoConfig, AutoModel, AutoModelForCausalLM + +from fla.models.gsa.configuration_gsa import GSAConfig +from fla.models.gsa.modeling_gsa import GSAForCausalLM, GSAModel + +AutoConfig.register(GSAConfig.model_type, GSAConfig, exist_ok=True) +AutoModel.register(GSAConfig, GSAModel, exist_ok=True) +AutoModelForCausalLM.register(GSAConfig, GSAForCausalLM, exist_ok=True) + + +__all__ = ['GSAConfig', 'GSAForCausalLM', 'GSAModel'] diff --git a/ops/path_attn_s_diag_block/parallel_path_bwd_inter_dqh.py b/ops/path_attn_s_diag_block/parallel_path_bwd_inter_dqh.py new file mode 100644 index 0000000000000000000000000000000000000000..43de503127edae1a3cc661dfece79ff224f6f66b --- /dev/null +++ b/ops/path_attn_s_diag_block/parallel_path_bwd_inter_dqh.py @@ -0,0 +1,200 @@ +import torch +import triton +import triton.language as tl + +from fla.ops.utils import prepare_chunk_indices, prepare_chunk_offsets +from fla.ops.utils.op import exp2 +from fla.utils import check_shared_mem + + +@triton.heuristics({ + 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None, + 'USE_GATE': lambda args: args['g_cumsum'] is not None, +}) +@triton.jit(do_not_specialize=['T']) +def parallel_path_bwd_dq_kernel( + q, + k, + v, + g_cumsum, + hc_whole, + scale, + L, + D, + dq, + do, + dhc_whole, + dg_cumsum, + cu_seqlens, + indices, + split_offsets, # varlen specific + T, + G: tl.constexpr, + HQ: tl.constexpr, + H: tl.constexpr, + K: tl.constexpr, + V: tl.constexpr, + BT: tl.constexpr, + BS: tl.constexpr, + BK: tl.constexpr, + BV: tl.constexpr, + S: tl.constexpr, # aka larger chunk size + NUM_BLOCKS: tl.constexpr, + IS_VARLEN: tl.constexpr, + USE_GATE: tl.constexpr +): + i_t, i_nh = tl.program_id(0), tl.program_id(1) + i_n, i_hq = i_nh // HQ, i_nh % HQ + i_h = i_hq // G + + if IS_VARLEN: + i_n, i_t = tl.load(indices + i_t * 2).to(tl.int32), tl.load(indices + i_t * 2 + 1).to(tl.int32) + boh_large = tl.load(split_offsets + i_n).to(tl.int32) + bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32) + T = eos - bos + else: + bos, eos = i_n * T, i_n * T + T + boh_large = i_n * tl.cdiv(T, S) + o_t = i_t * BT + tl.arange(0, BT) + m_t = o_t < T + + k += (bos * H + i_h) * K # GQA when H!=HQ + v += (bos * H + i_h) * V # GQA when H!=HQ + do += (bos * HQ + i_hq) * V + dq += (bos * HQ + i_hq) * K + hc_whole += (boh_large * H + i_h) * K * K + dhc_whole += (boh_large * HQ + i_hq) * K * K + L += (bos * HQ + i_hq) + D += (bos * HQ + i_hq) + if USE_GATE: + g_cumsum += (bos * HQ + i_hq) + dg_cumsum += (bos * HQ + i_hq) + + # constants + stride_h = H * K * K + stride_hq = HQ * K * K + sm_scale = scale * 1.44269504 + + # load query + p_do = tl.make_block_ptr(do, (T, V), (HQ*V, 1), (i_t * BT, 0), (BT, BV), (1, 0)) + b_do = tl.load(p_do, boundary_check=(0, 1)) + + p_l = tl.make_block_ptr(L, (T,), (HQ,), (i_t * BT,), (BT,), (0,)) + p_d = tl.make_block_ptr(D, (T,), (HQ,), (i_t * BT,), (BT,), (0,)) + b_l = tl.load(p_l, boundary_check=(0,)) + b_delta = tl.load(p_d, boundary_check=(0,)) + + if USE_GATE: + p_g_cumsum_q = tl.make_block_ptr(g_cumsum, (T,), (HQ,), (i_t * BT,), (BT,), (0,)) + b_g_cumsum_q = tl.load(p_g_cumsum_q, boundary_check=(0,)).to(tl.float32) + b_dg_cumsum_q = tl.zeros([BT,], dtype=tl.float32) + else: + b_g_cumsum_q = None + b_dg_cumsum_q = None + + curr_end = ((i_t * BT // S) * S).to(tl.int32) + b_dq = tl.zeros([BT, K], dtype=tl.float32) + + for offset_outer in range(0, curr_end, S): + idx_j = offset_outer // S + p_q = tl.make_block_ptr(q + ((bos * NUM_BLOCKS + idx_j + 1) * HQ + i_hq) * K, (T, K), + (HQ*K*NUM_BLOCKS, 1), (i_t * BT, 0), (BT, BK), (1, 0)) + b_q = tl.load(p_q, boundary_check=(0, 1)) + + b_dh = -tl.dot(tl.trans(b_q), b_dq.to(b_q.dtype)) + tl.atomic_add(dhc_whole + idx_j * stride_hq + tl.arange(0, K) + [:, None] * K + tl.arange(0, K)[None, :], b_dh, sem='relaxed') + p_h = tl.make_block_ptr(hc_whole + idx_j * stride_h, (K, K), (K, 1), (0, 0), (BK, BK), (1, 0)) + b_h = tl.load(p_h, boundary_check=(0, 1)) + b_dq = b_dq - tl.dot(b_dq.to(b_h.dtype), tl.trans(b_h)) + + for offset in range(offset_outer, min(offset_outer+S, i_t*BT), BS): + p_k = tl.make_block_ptr(k, (T, K), (H * K, 1), (offset, 0), (BS, BK), (1, 0)) + b_k = tl.load(p_k, boundary_check=(0, 1)) + b_A = tl.dot(b_q, tl.trans(b_k).to(b_q.dtype)) + if USE_GATE: + p_g_cumsum_k = tl.make_block_ptr(g_cumsum, (T,), (HQ,), (offset,), (BS,), (0,)) + b_g_cumsum_k = tl.load(p_g_cumsum_k, boundary_check=(0,)).to(tl.float32) + b_A = b_A + b_g_cumsum_q[:, None] - b_g_cumsum_k[None, :] + b_A = exp2(b_A * sm_scale - b_l[:, None]) + b_A = tl.where(m_t[:, None], b_A, 0) + p_v = tl.make_block_ptr(v, (V, T), (1, V*H), (0, offset), (BK, BS), (0, 1)) + b_v = tl.load(p_v, boundary_check=(0, 1)) + b_dp = tl.dot(b_do, b_v.to(b_do.dtype)) + b_dA = (b_dp - b_delta[:, None]) * b_A * scale + b_dq += tl.dot(b_dA.to(b_k.dtype), b_k) + if USE_GATE: + b_dg_cumsum_q += tl.sum(b_dA, axis=1) + + p_dq = tl.make_block_ptr(dq, (T, K), (K * HQ, 1), (i_t * BT, 0), (BT, BK), (1, 0)) + tl.store(p_dq, b_dq.to(dq.dtype.element_ty), boundary_check=(0, 1)) + if USE_GATE: + tl.atomic_add(dg_cumsum + o_t * HQ, b_dg_cumsum_q, mask=m_t, sem='relaxed') + + +def parallel_path_bwd_dq_fn( + q, + k, + v, + g_cumsum, + do, + dg_cumsum, + hc_whole, + scale, + L, + D, + cu_seqlens, + S, + BT, + BS, +): + B, T, num_blocks, HQ, K = q.shape + H, V = v.shape[-2:] + G = HQ // H + BK, BV = triton.next_power_of_2(K), triton.next_power_of_2(V) + + indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None + split_offsets = prepare_chunk_offsets(cu_seqlens, S) if cu_seqlens is not None else None + NT = triton.cdiv(T, BT) if cu_seqlens is None else len(indices) + + # should be NS + if cu_seqlens is not None: + assert split_offsets[-1] == hc_whole.shape[0] + dq = torch.empty(B, T, HQ, K, dtype=torch.float32, device=q.device) + + # [NS, HQ, K, K] instead of [NS, H, K, K] + # atomic add must be initialized to 0 + dhc_whole = torch.zeros(hc_whole.shape[0], HQ, K, K, dtype=torch.float32, device=q.device) + + parallel_path_bwd_dq_kernel[(NT, B*HQ)]( + q=q, + k=k, + v=v, + g_cumsum=g_cumsum, + hc_whole=hc_whole, + scale=scale, + L=L, + D=D, + dq=dq, + do=do, + dhc_whole=dhc_whole, + dg_cumsum=dg_cumsum, + cu_seqlens=cu_seqlens, + indices=indices, + split_offsets=split_offsets, + T=T, + S=S, + BT=BT, + BS=BS, + G=G, + HQ=HQ, + H=H, + K=K, + V=V, + BK=BK, + BV=BV, + NUM_BLOCKS=num_blocks, + num_warps=8 if (BT == 128 and K == 128) else 4, + num_stages=3 if check_shared_mem('ampere') else 2 + ) + return dq, dhc_whole, dg_cumsum diff --git a/ops/phi_kkt_approx_gla_trace/illegal_input_dump.py b/ops/phi_kkt_approx_gla_trace/illegal_input_dump.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f2e9b3400c996ae3da9f3c216f2c97b6945f8d --- /dev/null +++ b/ops/phi_kkt_approx_gla_trace/illegal_input_dump.py @@ -0,0 +1,267 @@ +"""Save phi-KKT inputs the first time a finite call produces a non-finite value. + +Training calls ``phi_kkt_solve_trace_gla``. This guard watches that call: + +- forward: every input is finite, and ``x`` / ``q_mix`` / ``o`` / state is not +- backward: gradients arriving at the outputs are finite, and a gradient + leaving into an input is not + +The snapshot is written once per process. Set ``PHI_KKT_NAN_GUARD=0`` to skip +the checks. Set ``PHI_KKT_ILLEGAL_DUMP`` to change the file. Set +``PHI_KKT_ILLEGAL_RAISE=0`` to keep training after the snapshot. +""" +from __future__ import annotations + +import os +import threading +from typing import Any, Dict, Mapping, Optional + +import torch +from torch import Tensor + +_DUMP_DIR = ( + "/mnt/jfzn/msj/flash-linear-attention/legacy/training/fla4/debug_dumps" +) +_LOCK = threading.Lock() +_TLS = threading.local() +_SAVED = False +_ANNOUNCED = False +_INHERITED_NOTED = False +_CALL_INDEX = 0 + + +def guard_enabled() -> bool: + return os.environ.get("PHI_KKT_NAN_GUARD", "1") != "0" and not _SAVED + + +def dump_path() -> str: + rank = os.environ.get("RANK", os.environ.get("LOCAL_RANK", "0")) + override = os.environ.get("PHI_KKT_ILLEGAL_DUMP") + if override: + root, ext = os.path.splitext(override) + if ext == "": + ext = ".pt" + return f"{root}_rank{rank}{ext}" + return os.path.join(_DUMP_DIR, f"phi_kkt_illegal_inputs_rank{rank}.pt") + + +def _illegal(tensor: Optional[Tensor]) -> bool: + """True when a floating tensor contains NaN or Inf. One device sync.""" + if tensor is None or not torch.is_tensor(tensor): + return False + if tensor.numel() == 0 or not tensor.is_floating_point(): + return False + minimum, maximum = torch.aminmax(tensor.detach()) + return not bool((torch.isfinite(minimum) & torch.isfinite(maximum)).item()) + + +def _stats(tensor: Any) -> Dict[str, Any]: + if not torch.is_tensor(tensor): + return {"present": tensor is not None, "type": type(tensor).__name__} + data = tensor.detach() + info: Dict[str, Any] = { + "shape": list(data.shape), + "dtype": str(data.dtype).removeprefix("torch."), + "numel": int(data.numel()), + } + if data.numel() == 0 or not data.is_floating_point(): + info["n_nonfinite"] = 0 + return info + finite = torch.isfinite(data) + n_bad = int((~finite).sum().item()) + info["n_nonfinite"] = n_bad + if n_bad < data.numel(): + vals = data[finite] + info["finite_min"] = float(vals.min().item()) + info["finite_max"] = float(vals.max().item()) + return info + + +def _to_cpu(tensor: Any) -> Any: + if not torch.is_tensor(tensor): + return tensor + return tensor.detach().cpu().contiguous() + + +def _announce() -> None: + global _ANNOUNCED + if _ANNOUNCED: + return + _ANNOUNCED = True + print( + f"[phi_kkt] illegal-value guard on; first bad call dumps inputs to {dump_path()}", + flush=True, + ) + + +def _note_inherited(layer_idx: Optional[int], bad_names) -> None: + global _INHERITED_NOTED + if _INHERITED_NOTED: + return + _INHERITED_NOTED = True + print( + f"[phi_kkt] layer {layer_idx} already received illegal inputs {bad_names}; " + "the transition happened before phi_kkt, inputs were not saved", + flush=True, + ) + + +def dump_once( + state: Mapping[str, Any], + stage: str, + bad_name: str, + outputs: Optional[Mapping[str, Any]] = None, + grad: Optional[Tensor] = None, +) -> None: + """Write the finite inputs that produced ``bad_name``. Runs at most once.""" + global _SAVED + with _LOCK: + if _SAVED: + return + # Block nested hooks and later layers before the copy finishes. + _SAVED = True + + payload: Dict[str, Any] = { + "stage": stage, + "bad_name": bad_name, + "layer_idx": state.get("layer_idx"), + "call_index": state.get("call_index"), + "fn": "phi_kkt_solve_trace_gla -> q_kkt_solve_trace_triton_safe_ver1 + chunk_gla", + "meta": dict(state.get("meta") or {}), + "input_stats": {}, + "output_stats": {}, + } + inputs = state.get("inputs") or {} + for name, tensor in inputs.items(): + payload["input_stats"][name] = _stats(tensor) + payload[name] = _to_cpu(tensor) + if outputs is not None: + for name, tensor in outputs.items(): + payload["output_stats"][name] = _stats(tensor) + if grad is not None: + payload["bad_grad_stats"] = _stats(grad) + + path = dump_path() + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + temporary = path + ".tmp" + try: + torch.save(payload, temporary) + os.replace(temporary, path) + except Exception: + _SAVED = False + raise + message = ( + f"[phi_kkt] layer {payload['layer_idx']} {stage} produced illegal `{bad_name}` " + f"from finite inputs (call {payload['call_index']}). saved {path}" + ) + print(message, flush=True) + if os.environ.get("PHI_KKT_ILLEGAL_RAISE", "1") != "0": + raise RuntimeError(message) + + +class _InWatch(torch.autograd.Function): + """Identity on an input. Backward sees the grad this call writes into it.""" + + @staticmethod + def forward(ctx, tensor: Tensor) -> Tensor: + ctx.state, ctx.name = _TLS.watch + return tensor + + @staticmethod + def backward(ctx, grad: Tensor): + state = ctx.state + if state.get("out_finite") is True and _illegal(grad): + dump_once(state, stage="backward", bad_name=f"grad_{ctx.name}", grad=grad) + return grad + + +class _OutMark(torch.autograd.Function): + """Identity on an output. Backward records whether the incoming grad is finite.""" + + @staticmethod + def forward(ctx, tensor: Tensor) -> Tensor: + ctx.state = _TLS.mark + return tensor + + @staticmethod + def backward(ctx, grad: Tensor): + finite = grad is None or not _illegal(grad) + previous = ctx.state.get("out_finite") + ctx.state["out_finite"] = finite if previous is None else (previous and finite) + return grad + + +class PhiKktGuard: + """Wrap one ``phi_kkt_solve_trace_gla`` call.""" + + def __init__( + self, + layer_idx: Optional[int], + inputs: Mapping[str, Any], + meta: Optional[Mapping[str, Any]] = None, + ) -> None: + global _CALL_INDEX + self.inputs = dict(inputs) + self.meta = dict(meta or {}) + self.active = guard_enabled() + self.input_finite = True + self._bad_inputs = [] + self._seen: Dict[int, Tensor] = {} + self.state: Dict[str, Any] = { + "out_finite": None, + "layer_idx": layer_idx, + "inputs": self.inputs, + "meta": self.meta, + "call_index": None, + } + if not self.active: + return + _CALL_INDEX += 1 + self.state["call_index"] = _CALL_INDEX + _announce() + shared: Dict[int, list] = {} + for name, tensor in self.inputs.items(): + if torch.is_tensor(tensor): + shared.setdefault(id(tensor), []).append(name) + aliases = [names for names in shared.values() if len(names) > 1] + if aliases: + self.meta["aliases"] = aliases + self.state["meta"] = self.meta + self._bad_inputs = [name for name, tensor in self.inputs.items() if _illegal(tensor)] + self.input_finite = not self._bad_inputs + + def wrap(self, name: str, tensor: Any) -> Any: + """Return ``tensor`` with a backward probe. Same object is wrapped once.""" + if not self.active or not self.input_finite: + return tensor + if tensor is None or not torch.is_tensor(tensor) or not tensor.requires_grad: + return tensor + key = id(tensor) + cached = self._seen.get(key) + if cached is not None: + return cached + _TLS.watch = (self.state, name) + wrapped = _InWatch.apply(tensor) + self._seen[key] = wrapped + return wrapped + + def mark(self, tensor: Optional[Tensor]) -> Optional[Tensor]: + """Return ``tensor`` with a probe on the gradient that enters this call.""" + if not self.active or not self.input_finite: + return tensor + if tensor is None or not torch.is_tensor(tensor) or not tensor.requires_grad: + return tensor + _TLS.mark = self.state + return _OutMark.apply(tensor) + + def check_forward(self, outputs: Mapping[str, Any]) -> None: + """Dump when finite inputs just produced a non-finite forward tensor.""" + if not self.active: + return + if not self.input_finite: + _note_inherited(self.state.get("layer_idx"), self._bad_inputs) + return + for name, tensor in outputs.items(): + if _illegal(tensor): + dump_once(self.state, stage="forward", bad_name=name, outputs=outputs) + return diff --git a/ops/phi_kkt_approx_gla_trace/q_kkt_solve_abc.py b/ops/phi_kkt_approx_gla_trace/q_kkt_solve_abc.py new file mode 100644 index 0000000000000000000000000000000000000000..9a02790a9c637ddf075459292e5585a69bdf0ce5 --- /dev/null +++ b/ops/phi_kkt_approx_gla_trace/q_kkt_solve_abc.py @@ -0,0 +1,255 @@ +"""Fused Phi-KKT (abc) + Simple-GLA autograd. + +One ``torch.autograd.Function`` owns both the polynomial apply + + x = a q + b (q @ H)/F + c (q @ H^2)/F^2 + +and the subsequent GLA recurrence. Matches GDN's checkpoint style: + +- ``k`` is saved once (not once per op). +- Mixed query ``q_gla = (1-α) q + α x`` is reconstructed in backward. +- GLA chunk state ``h_kv`` is recomputed, not stored. +- Chunk-level ``h_kk`` is dropped after forward and rebuilt in backward. +- Triton kernels are reused from ``phi_kkt_approx.q_kkt_solve_abc_fast_2``. +""" +from typing import Optional, Sequence, Tuple, Union + +import torch +from torch import Tensor + +from fla.ops.simple_gla.chunk import chunk_simple_gla_bwd, chunk_simple_gla_fwd +from fla.ops.utils import chunk_local_cumsum + +from ..phi_kkt_approx.q_kkt_solve_abc_fast_2 import ( + _bwd_dH_to_dk_dgk, + _bwd_prep_du_dv_alpha, + _normalize_abc, + q_kkt_solve_approx_backward_triton, + q_kkt_solve_approx_forward_triton, +) + + +def _poly_x_out( + q: Tensor, + o1: Tensor, + o2: Tensor, + abc_heads: Tensor, +) -> Tensor: + """Reconstruct x = a q + b o1 + c o2 in fp32, store as ``q.dtype``.""" + a = abc_heads[:, 0].view(1, 1, -1, 1) + b = abc_heads[:, 1].view(1, 1, -1, 1) + c = abc_heads[:, 2].view(1, 1, -1, 1) + return (a * q.float() + b * o1.float() + c * o2.float()).to(q.dtype) + + +def _mix_q(q: Tensor, x_out: Tensor, alpha: Tensor) -> Tensor: + return q + alpha[..., None] * (x_out - q) + + +def _cumsum_gates( + g: Optional[Tensor], + gk: Optional[Tensor], + chunk_size: int, +) -> Tuple[Optional[Tensor], Optional[Tensor]]: + """Cumsum GLA gate ``g`` and KKT gate ``gk``. Reuse storage when they alias.""" + gkk = chunk_local_cumsum(gk, chunk_size=chunk_size) if gk is not None else None + if g is None: + g_cum = None + elif gk is g: + g_cum = gkk + else: + g_cum = chunk_local_cumsum(g, chunk_size=chunk_size) + return g_cum, gkk + + +def _pack_abc_grad( + d_abc_h: Tensor, + abc_shape: Tuple[int, ...], + abc_dtype: torch.dtype, + abc_device: torch.device, +) -> Tensor: + if abc_shape == (3,) or (len(abc_shape) == 1 and abc_shape[0] == 3): + d_abc = d_abc_h.sum(dim=0) + else: + d_abc = d_abc_h + return d_abc.to(dtype=abc_dtype, device=abc_device).reshape(abc_shape) + + +class q_kkt_solve_approx(torch.autograd.Function): + """Fused abc polynomial apply + alpha mix + chunk Simple-GLA.""" + + @staticmethod + def forward( + ctx, + k: Tensor, + q: Tensor, + v: Tensor, + alpha: Tensor, + g: Optional[Tensor], + gk: Optional[Tensor], + chunk_size: int, + learnable_abc: Union[Tensor, Sequence[float]], + gla_scale: float, + h0_kk=None, + h0_kv=None, + output_final_state: bool = False, + ) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + B, T, H, _D = q.shape + assert torch.is_tensor(learnable_abc), "learnable_abc must be a tensor" + assert learnable_abc.dtype == torch.float32, ( + f"learnable_abc.dtype must be float32, got {learnable_abc.dtype}" + ) + ctx.abc_dtype = learnable_abc.dtype + ctx.abc_device = learnable_abc.device + ctx.abc_shape = tuple(learnable_abc.shape) + + abc_heads = _normalize_abc(learnable_abc, H, q.device, torch.float32) + g_cum, gkk = _cumsum_gates(g, gk, chunk_size) + + fro = torch.empty((B, T, H), dtype=torch.float32, device=q.device) + x_out, o1, o2, fro, h_kk, h_kk_final = q_kkt_solve_approx_forward_triton( + k, + q, + gkk, + fro, + learnable_abc=abc_heads, + chunk_size=chunk_size, + load_fro=0, + output_final_state=output_final_state, + h0=h0_kk, + ) + del h_kk + q_gla = _mix_q(q, x_out, alpha) + o, kv_final = chunk_simple_gla_fwd( + q=q_gla, + k=k, + v=v, + g=g_cum, + g_gamma=None, + scale=gla_scale, + initial_state=h0_kv, + output_final_state=output_final_state, + cu_seqlens=None, + chunk_size=chunk_size, + ) + + to_save = [k, q, v, alpha, o1, o2, fro, abc_heads] + if g_cum is not None: + to_save.append(g_cum) + if gk is not None: + to_save.append(gk) + if gkk is not None: + to_save.append(gkk) + if h0_kk is not None: + to_save.append(h0_kk) + if h0_kv is not None: + to_save.append(h0_kv) + ctx.save_for_backward(*to_save) + ctx.chunk_size = chunk_size + ctx.gla_scale = gla_scale + ctx.has_g_cum = g_cum is not None + ctx.has_gk = gk is not None + ctx.has_gkk = gkk is not None + ctx.has_h0_kk = h0_kk is not None + ctx.has_h0_kv = h0_kv is not None + return o.to(q.dtype), h_kk_final, kv_final + + @staticmethod + def backward( + ctx, + do: Tensor, + d_kk_final: Optional[Tensor] = None, + d_kv_final: Optional[Tensor] = None, + ): + saved = list(ctx.saved_tensors) + k, q, v, alpha, o1, o2, fro, abc_heads = saved[:8] + idx = 8 + g_cum = saved[idx] if ctx.has_g_cum else None + idx += int(ctx.has_g_cum) + gk = saved[idx] if ctx.has_gk else None + idx += int(ctx.has_gk) + gkk = saved[idx] if ctx.has_gkk else None + idx += int(ctx.has_gkk) + h0_kk = saved[idx] if ctx.has_h0_kk else None + idx += int(ctx.has_h0_kk) + h0_kv = saved[idx] if ctx.has_h0_kv else None + chunk_size = ctx.chunk_size + gla_scale = ctx.gla_scale + + x_out = _poly_x_out(q, o1, o2, abc_heads) + q_gla = _mix_q(q, x_out, alpha) + + dq_gla, dk_gla, dv, dg_cum, dh0_kv = chunk_simple_gla_bwd( + q=q_gla, + k=k, + v=v, + g=g_cum, + g_gamma=None, + initial_state=h0_kv, + do=do, + dht=d_kv_final, + scale=gla_scale, + cu_seqlens=None, + chunk_size=chunk_size, + ) + dg = None + if g_cum is not None: + dg = chunk_local_cumsum( + dg_cum, chunk_size=chunk_size, reverse=True, cu_seqlens=None + ).to(dtype=g_cum.dtype) + + dx_out = dq_gla * alpha[..., None] + dq_mix = dq_gla * (1.0 - alpha[..., None]) + d_alpha = (dq_gla * (x_out - q)).sum(dim=-1) + + dq_kkt, dx1, fro, h_kk, _ = q_kkt_solve_approx_backward_triton( + k, + dx_out, + gkk, + fro, + learnable_abc=abc_heads, + chunk_size=chunk_size, + load_fro=1, + output_final_state=False, + h0=h0_kk, + h_kk=None, + ) + need_dabc = bool(ctx.needs_input_grad[7]) + du, dv_poly, alpha_h, d_abc_h = _bwd_prep_du_dv_alpha( + q, o1, o2, dx_out, dx1, fro, abc_heads, chunk_size, need_dabc + ) + dk_kkt, dgk, dh0_kk = _bwd_dH_to_dk_dgk( + k, + q, + o1, + du, + dv_poly, + alpha_h, + gk, + gkk, + d_kk_final, + h_kk, + h0_kk, + chunk_size, + ) + d_abc = ( + _pack_abc_grad(d_abc_h, ctx.abc_shape, ctx.abc_dtype, ctx.abc_device) + if need_dabc + else None + ) + dq = dq_mix + dq_kkt + dk = dk_gla + dk_kkt + return ( + dk, + dq, + dv, + d_alpha, + dg, + dgk, + None, + d_abc, + None, + dh0_kk, + dh0_kv, + None, + ) diff --git a/ops/phi_kkt_approx_gla_trace_c16/__init__.py b/ops/phi_kkt_approx_gla_trace_c16/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c87a56deeae034c3da2f44eab4e205ef5a898a --- /dev/null +++ b/ops/phi_kkt_approx_gla_trace_c16/__init__.py @@ -0,0 +1,3 @@ +from .phi_kkt_solve_trace import phi_kkt_decoding_one_step, phi_kkt_solve_gla + +__all__ = ["phi_kkt_solve_gla", "phi_kkt_decoding_one_step"] diff --git a/ops/phi_kkt_approx_gla_trace_c16/phi_kkt_solve.py b/ops/phi_kkt_approx_gla_trace_c16/phi_kkt_solve.py new file mode 100644 index 0000000000000000000000000000000000000000..afdcef96755d19a90da857642bbd5ac47632e0ca --- /dev/null +++ b/ops/phi_kkt_approx_gla_trace_c16/phi_kkt_solve.py @@ -0,0 +1,167 @@ +""" +Fused Phi-KKT + Simple-GLA for Sigma GKA training. + +Same math as ``phi_kkt_approx.phi_kkt_solve_gla``, but KKT apply, alpha mix, +and chunk Simple-GLA share one ``autograd.Function`` (GDN-style): + +- ``k`` / cumsum gates are saved once. +- Mixed query is reconstructed in backward, not stored. +- GLA recurrent state ``h_kv`` and chunk-level ``h_kk`` are recomputed, not stored. +- ``output_final_state`` defaults to False so training does not materialize + ``H_T`` / ``U_T``. +""" +from typing import Optional, Sequence, Tuple, Union + +import torch +from torch import Tensor + +from fla.ops.simple_gla import fused_recurrent_simple_gla + +from .q_kkt_solve_abc import q_kkt_solve_approx as q_kkt_solve_approx_abc +from .q_kkt_solve_abcd import q_kkt_solve_approx as q_kkt_solve_approx_abcd +from ..phi_kkt_approx.q_kkt_solve_abc import ( + test_q_kkt_solve_approx as test_q_kkt_solve_approx_abc, +) +from ..phi_kkt_approx.q_kkt_solve_abc_3 import ( + test_q_kkt_solve_approx as test_q_kkt_solve_approx_abcd, +) + + +def _coeff_last_dim(learnable_abc: Union[Tensor, Sequence[float]]) -> int: + """Last dim of polynomial coefficients: 3 = abc, 4 = abcd.""" + if torch.is_tensor(learnable_abc): + if learnable_abc.ndim == 0: + raise ValueError( + "learnable_abc must be a vector or [H, n] tensor, got a scalar" + ) + return int(learnable_abc.shape[-1]) + return len(learnable_abc) + + +@torch.compiler.disable +def phi_kkt_solve_gla( + q: Tensor, + k: Tensor, + v: Tensor, + alpha: Tensor, + g: Tensor, + gk: Tensor, + gla_scale, + learnable_abc: torch.Tensor = torch.tensor([1.0, -0.5, 0.375]), + chunk_size: int = 16, + h0_kk: Optional[Tensor] = None, + h0_kv: Optional[Tensor] = None, + output_final_state: bool = False, +) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + """ + Fused Phi-KKT + GLA for parallel training. + + Solves q phi(k^T k) with phi(x) = x^(-1/2) (abc or abcd polynomial), + mixes with alpha, then runs chunk Simple-GLA — all in one autograd node. + + Args: + q: Query tensor with shape [B, L, H, D] + k: Key tensor with shape [B, L, H, D] + v: Value tensor with shape [B, L, H, D] + alpha: Mixing coefficient [B, L, H]. q_new = (1-α) q + α x + g: Forgetting gate for key-value state [B, L, H] + gk: Forgetting gate for key-key covariance [B, L, H] + gla_scale: Scaling factor for GLA, typically head_dim^(-0.5) + learnable_abc: Polynomial coefficients, last dim 3 (abc) or 4 (abcd) + chunk_size: Chunk size shared by KKT and GLA. Defaults to 16 + h0_kk: Optional initial H_kk [B, H, D, D] + h0_kv: Optional initial H_kv [B, H, D, D] + output_final_state: If True, return H_T and U_T. Defaults to False. + + Returns: + o: Output tensor [B, L, H, D] + kk_final: Final H_T [B, H, D, D], or None + kv_final: Final GLA state [B, H, D, D], or None + """ + n_coeff = _coeff_last_dim(learnable_abc) + if n_coeff == 3: + solver = q_kkt_solve_approx_abc + elif n_coeff == 4: + solver = q_kkt_solve_approx_abcd + else: + raise ValueError( + f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}" + ) + + o, kk_final, kv_final = solver.apply( + k, + q, + v, + alpha, + g, + gk, + chunk_size, + learnable_abc, + gla_scale, + h0_kk, + h0_kv, + output_final_state, + ) + return o, kk_final, kv_final + + +def phi_kkt_decoding_one_step( + q: Tensor, + k: Tensor, + v: Tensor, + alpha: Tensor, + g: Tensor, + gk: Tensor, + gla_scale, + learnable_abc: Tensor, + prev_h_kk: Tensor, + prev_h_kv: Tensor, +) -> Tuple[Tensor, Tensor, Tensor]: + """ + Single-step Sigma GKA inference with cached H_kk / H_kv. + + Token-by-token decoding is not fused; it reuses the same reference + recurrence as ``phi_kkt_approx.phi_kkt_decoding_one_step``. + """ + if q.dim() < 4: + q = q[None, ...] + k = k[None, ...] + v = v[None, ...] + if alpha is not None and alpha.dim() == 2: + alpha = alpha[None, ...] + if g is not None and g.dim() == 2: + g = g[None, ...] + if gk is not None and gk.dim() == 2: + gk = gk[None, ...] + + if prev_h_kv is not None and prev_h_kv.dim() == 3: + prev_h_kv = prev_h_kv.unsqueeze(0) + n_coeff = _coeff_last_dim(learnable_abc) + if n_coeff == 3: + solver = test_q_kkt_solve_approx_abc + elif n_coeff == 4: + solver = test_q_kkt_solve_approx_abcd + else: + raise ValueError( + f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}" + ) + + q_, states, _ = solver( + q, + k, + gk, + h0=prev_h_kk, + learnable_abc=learnable_abc, + ) + h_kk = states + q = q + alpha[..., None] * (q_ - q) + o, h_kv = fused_recurrent_simple_gla( + q=q, + k=k, + v=v, + scale=gla_scale, + g=g, + initial_state=prev_h_kv, + output_final_state=True, + ) + return o, h_kk, h_kv diff --git a/ops/phi_kkt_approx_gla_trace_c16/q_kkt_solve_trace_gla.py b/ops/phi_kkt_approx_gla_trace_c16/q_kkt_solve_trace_gla.py new file mode 100644 index 0000000000000000000000000000000000000000..efa98e040e305aaeccf84da1b2537e179339244f --- /dev/null +++ b/ops/phi_kkt_approx_gla_trace_c16/q_kkt_solve_trace_gla.py @@ -0,0 +1,77 @@ +"""Trace-phi + vector-gate GLA, composed so both train in one call. + +Phi uses ``q_kkt_solve_trace_triton`` (trace norm, per-dimension half-gate). +The value recurrence is ``chunk_gla``: + + Hkv_t = Hkv_{t-1} * exp(g_t) + k_t v_t^T (decay on the key axis) + o_t = scale * q_mix_t @ Hkv_t + q_mix = q + alpha * (x - q) + +``g`` / ``gk`` may be ``[B, T, H]`` (broadcast over D) or ``[B, T, H, D]``. +Coefficient count is the last dim of ``learnable_abc``: 3 or 4. +This path does not call ``simple_gla``. +""" +from typing import Optional, Sequence, Tuple, Union + +import torch +from torch import Tensor + +from fla.ops.gla import chunk_gla + +from ..phi_kkt_approx_trace.q_kkt_solve_trace_triton import q_kkt_solve_trace_triton + + +def _as_head_gate(gate: Optional[Tensor], like: Tensor) -> Optional[Tensor]: + """Broadcast ``[B, T, H]`` or ``[B, T, H, D]`` onto ``like``'s last dim.""" + if gate is None: + return None + if gate.shape == like.shape: + return gate + if gate.ndim == like.ndim - 1 and gate.shape == like.shape[:-1]: + return gate.unsqueeze(-1).expand_as(like) + raise ValueError( + f"gate must be {tuple(like.shape)} or {tuple(like.shape[:-1])}, got {tuple(gate.shape)}" + ) + + +def phi_kkt_solve_trace_gla( + q: Tensor, + k: Tensor, + v: Tensor, + alpha: Tensor, + g: Optional[Tensor], + gk: Optional[Tensor], + gla_scale: float, + learnable_abc: Union[Tensor, Sequence[float]], + chunk_size: int = 16, + h0_kk: Optional[Tensor] = None, + h0_kv: Optional[Tensor] = None, + output_final_state: bool = True, +) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + """x = phi_trace(q, k, gk), then vector-gate GLA on the alpha-mixed query. + + Returns ``o [B, T, H, D]``, ``H_kk`` (or None), ``H_kv`` (or None). + """ + if q.ndim != 4: + raise ValueError(f"q must be [B, T, H, D], got {tuple(q.shape)}") + gk_vec = _as_head_gate(gk, k) + g_vec = _as_head_gate(g, k) + if g_vec is None: + g_vec = torch.zeros_like(k, dtype=torch.float32) + x, h_kk = q_kkt_solve_trace_triton.apply( + k, q, gk_vec, chunk_size, learnable_abc, h0_kk, + ) + q_mix = q + alpha[..., None] * (x - q) + h0 = None if h0_kv is None else h0_kv.float().contiguous() + o, h_kv = chunk_gla( + q_mix, + k, + v, + g_vec, + scale=float(gla_scale), + initial_state=h0, + output_final_state=output_final_state, + ) + if not output_final_state: + h_kk = None + return o, h_kk, h_kv diff --git a/ops/phi_kkt_approx_trace/phi_kkt_solve.py b/ops/phi_kkt_approx_trace/phi_kkt_solve.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e44c808c285c7d632fb9d7b3437bf0842fe8e7 --- /dev/null +++ b/ops/phi_kkt_approx_trace/phi_kkt_solve.py @@ -0,0 +1,97 @@ + +from typing import Sequence, Tuple, Union + +import torch +from torch import Tensor + +from fla.ops.simple_gla import chunk_simple_gla +from .q_kkt_solve_abcd_fast_2 import q_kkt_solve_approx as q_kkt_solve_approx_abcd +from .q_kkt_solve_abc_fast_2 import q_kkt_solve_approx as q_kkt_solve_approx_abc +from .decoding_one_step import phi_kkt_decoding_one_step # noqa: F401 + +def _coeff_last_dim(learnable_abc: Union[Tensor, Sequence[float]]) -> int: + """Last dim of polynomial coefficients: 3 = abc, 4 = abcd.""" + if torch.is_tensor(learnable_abc): + if learnable_abc.ndim == 0: + raise ValueError("learnable_abc must be a vector or [H, n] tensor, got a scalar") + return int(learnable_abc.shape[-1]) + return len(learnable_abc) + + +@torch.compiler.disable +def phi_kkt_solve( + k, q, gk, chunk_size, learnable_abc, +): + """ + Solve q phi(k^T k) where phi(x) = x^(-1/2). + + Dispatches by coefficient count: + 3 (abc): x = a q + b (q@H)/F + c (q@H^2)/F^2 + 4 (abcd): x = a q + b (q@H)/F + c (q@H^2)/F^2 + d (q@H^3)/F^3 + + Returns: + x: Solution tensor with shape [B, L, H, D] + kk_final: Final key-key covariance H_T with shape [B, H, D, D] + """ + n_coeff = _coeff_last_dim(learnable_abc) + if n_coeff == 3: + solver = q_kkt_solve_approx_abc + elif n_coeff == 4: + solver = q_kkt_solve_approx_abcd + else: + raise ValueError( + f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}" + ) + + x, kk_final = solver.apply( + k, q, gk, chunk_size, learnable_abc, + ) + + return x, kk_final + + +def phi_kkt_solve_gla( + q: Tensor, + k: Tensor, + v: Tensor, + alpha: Tensor, + g: Tensor, + gk: Tensor, + gla_scale, + learnable_abc: torch.Tensor = torch.tensor([1.0, -0.5, 0.375]), + chunk_size: int = 64, +) -> Tuple[Tensor, Tensor, Tensor]: + """ + Phi-KKT solver for parallel training. + + Solves the Phi-KKT problem at each timestep, solve q phi(k^T k) where phi(x) = x^(-1/2). + then computes output via GLA recurrence. Processes entire sequences in parallel. + + Args: + q: Query tensor with shape [B, L, H, D] + k: Key tensor with shape [B, L, H, D] + v: Value tensor with shape [B, L, H, D] + alpha: Mixing coefficient with shape [B, L, H]. Controls interpolation: q_new = q + α·(x_t - q) + g: Forgetting gate for key-value state with shape [B, L, H] + gk: Forgetting gate for key-key covariance with shape [B, L, H] + gla_scale: Scaling factor for GLA, typically head_dim^(-0.5) + + Returns: + o: Output tensor with shape [B, L, H, D] + kk_final: Final key-key covariance (H_T in the regression problem) with shape + [B, H, D, D], or None if num_iter=0. + kv_final: Final key-value state from GLA with shape [B, H, D, D] + + Notes: + For single-step autoregressive inference, use phi_kkt_decoding_one_step instead. + """ + # q_ solves (H_t/||H_t||_F + I)^(-1/2) · q_ = q_t + q_, kk_final = phi_kkt_solve( + k, q, gk, chunk_size, learnable_abc, + ) + q = q + alpha[..., None] * (q_ - q) # Equivalent to ⍺q_ + (1-⍺)q + o, kv_final = chunk_simple_gla( + q=q, k=k, v=v, scale=gla_scale, g=g, output_final_state=True + ) + + return o, kk_final, kv_final diff --git a/ops/phi_kkt_approx_trace/q_kkt_solve_abcd_fast_2.py b/ops/phi_kkt_approx_trace/q_kkt_solve_abcd_fast_2.py new file mode 100644 index 0000000000000000000000000000000000000000..93f1aabc1b7dca36ef198239cb9fc730b34e092c --- /dev/null +++ b/ops/phi_kkt_approx_trace/q_kkt_solve_abcd_fast_2.py @@ -0,0 +1,1531 @@ +"""Store-o3 fork of ``q_kkt_solve_abcd_fast``. + +Do not edit ``q_kkt_solve_abcd_fast.py``. Change vs that file: + +Forward already stored o1 / o2; this fork also writes +``o3 = (o2 @ H) / F`` to a [B, L, H, D] buffer. Backward loads it for +``alpha`` / ``dabcd`` instead of reconstructing +``o3 = (x - a q - b o1 - c o2) / d``, which overflows when ``d`` is near 0. +""" +from typing import Optional, Sequence, Tuple, Union +import time +import torch +import triton +import triton.language as tl + + +from fla.ops.common.chunk_h import chunk_fwd_h +from fla.ops.utils import chunk_local_cumsum +from fla.ops.utils.op import exp + + +def _choose_block_d(D: int) -> int: + """Tile width along D. D=64 stays one 64x64 tile; larger D uses 32.""" + if D == 64: + return 64 + if D % 32 == 0: + return 32 + if D % 16 == 0: + return 16 + raise ValueError(f"head dim D={D} must be 64, or divisible by 16 or 32") + + +def _normalize_abcd( + learnable_abcd: Union[torch.Tensor, Sequence[float]], + H: int, + device: torch.device, + dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """Broadcast learnable_abcd to a contiguous [H, 4] tensor. + + Accepts a length-4 sequence / [4] tensor (shared by all heads) or [H, 4]. + """ + if torch.is_tensor(learnable_abcd): + t = learnable_abcd.detach().to(device=device, dtype=dtype) + else: + t = torch.tensor(list(learnable_abcd), device=device, dtype=dtype) + if t.numel() == 4: + t = t.reshape(1, 4).expand(H, 4).contiguous() + elif t.shape == (H, 4): + t = t.contiguous() + else: + raise ValueError( + f"learnable_abcd must be [4] or [H, 4] with H={H}, got {tuple(t.shape)}" + ) + return t + + +@triton.autotune( + configs=[ + triton.Config({}, num_warps=num_warps, num_stages=num_stages) + for num_warps in [2, 4, 8] + for num_stages in [1, 2, 3] + ], + key=["D", "BLOCK_D", "load_fro"], +) +@triton.jit(do_not_specialize=["T"]) +def q_kkt_solve_approx_gating_forward_kernel( + h_kk_ptr, + k_ptr, + q_ptr, + gkk_ptr, + abcd_ptr, + x_out_ptr, + o1_ptr, + o2_ptr, + o3_ptr, + fro_ptr, + T, + H: tl.constexpr, + D: tl.constexpr, + chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, + load_fro: tl.constexpr, +): + """Tiled GLA apply of phi(H) ~ a I + b H/F + c H^2/F^2 + d H^3/F^3. + + Grid: (num_chunks, B*H). D is walked in BLOCK_D tiles so D=128 stays + [C, BD] / [BD, BD] instead of a live [D, D] plus fro intermediates. + Stores o3 so backward does not reconstruct it via /d. + """ + chunk_id, bh_id = tl.program_id(0), tl.program_id(1) + b_id, h_id = bh_id // H, bh_id % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + + scalar_off = b_id * T * H + h_id + gkk_ptr += scalar_off + vec_off = scalar_off * D + q_ptr += vec_off + x_out_ptr += vec_off + o1_ptr += vec_off + o2_ptr += vec_off + o3_ptr += vec_off + k_ptr += vec_off + h_kk_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + + p_gkk = tl.make_block_ptr( + gkk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + gkk = tl.load(p_gkk, boundary_check=(0,)).to(tl.float32) + o_t = chunk_id * chunk_size + tl.arange(0, chunk_size) + m_t = o_t < T + mask = tl.where( + (o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :]), + exp(gkk[:, None] - gkk[None, :]), + 0.0, + ) + exp_gkk = exp(gkk[:, None]) + + if load_fro == 1: + fro_ptr += scalar_off + p_fro = tl.make_block_ptr( + fro_ptr, (T, 1), (H, 1), (chunk_id * chunk_size, 0), (chunk_size, 1), (1, 0) + ) + fro = tl.load(p_fro, boundary_check=(0, 1)).to(tl.float32) + else: + S_kk = _bwd_dot_xyT( + k_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + n0 = tl.zeros((1,), dtype=tl.float32) + vec = tl.zeros((chunk_size,), dtype=tl.float32) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + kh = _fwd_vh( + k_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D + ) + ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + vec += tl.sum(kh * ki, axis=1) + for j in tl.static_range(0, NUM_D): + d1 = j * BLOCK_D + h_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D) + n0 += tl.sum(tl.sum(h_tile * h_tile, axis=0), axis=0) + intra = tl.sum(tl.dot(mask, S_kk * S_kk) * mask, axis=1, keep_dims=True) + mixed = tl.sum(mask * vec[None, :], axis=1, keep_dims=True) + n0_s = tl.sum(n0) + fro = tl.sqrt(intra + exp_gkk * (exp_gkk * n0_s) + 2.0 * exp_gkk * mixed) + fro_ptr += scalar_off + p_fro = tl.make_block_ptr( + fro_ptr, (T, 1), (H, 1), (chunk_id * chunk_size, 0), (chunk_size, 1), (1, 0) + ) + tl.store( + p_fro, + fro.to(p_fro.dtype.element_ty, fp_downcast_rounding="rtne"), + boundary_check=(0, 1), + ) + + fro_safe = fro + 1e-12 + S_qk = _bwd_dot_xyT( + q_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + W = S_qk * mask + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + qh = _fwd_vh( + q_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D + ) + ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o1 = (exp_gkk * qh + tl.dot(W, ki)) / fro_safe + _bwd_store_vec(o1_ptr, o1, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + + S_o1k = _bwd_dot_xyT( + o1_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + W2 = S_o1k * mask + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + o1h = _fwd_vh( + o1_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D + ) + ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o2 = (exp_gkk * o1h + tl.dot(W2, ki)) / fro_safe + _bwd_store_vec(o2_ptr, o2, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + + S_o2k = _bwd_dot_xyT( + o2_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + W3 = S_o2k * mask + a = tl.load(abcd_ptr + h_id * 4 + 0).to(tl.float32) + b = tl.load(abcd_ptr + h_id * 4 + 1).to(tl.float32) + c = tl.load(abcd_ptr + h_id * 4 + 2).to(tl.float32) + d = tl.load(abcd_ptr + h_id * 4 + 3).to(tl.float32) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + o2h = _fwd_vh( + o2_ptr, h_kk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D, NUM_D + ) + ki = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o2i = _bwd_load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o1i = _bwd_load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + qi = _bwd_load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o3 = (exp_gkk * o2h + tl.dot(W3, ki)) / fro_safe + _bwd_store_vec(o3_ptr, o3, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + _bwd_store_vec( + x_out_ptr, + a * qi + b * o1i + c * o2i + d * o3, + T, + H, + D, + chunk_id, + chunk_size, + d0, + BLOCK_D, + ) + + +def q_kkt_solve_approx_forward_triton( + k: torch.Tensor, + q: torch.Tensor, + gkk: torch.Tensor, + fro: torch.Tensor, + learnable_abcd: list = [1.0, -0.5, 0.375, -0.3125], + chunk_size: int = 64, + load_fro: int = 0, + output_final_state: bool = False, + h0=None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Solves q phi(k^T k) where phi(x) = x^(-1/2) using chunked processing. + + Cubic polynomial: x = a q + b (q @ H)/F + c (q @ H^2)/F^2 + d (q @ H^3)/F^3. + Also stores o3 so backward does not reconstruct it via /d. + """ + h_kk, h_kk_final = chunk_fwd_h( + k=k, + v=k, + g=gkk, + gk=None, + gv=None, + h0=h0, + output_final_state=output_final_state, + states_in_fp32=False, + cu_seqlens=None, + chunk_size=chunk_size, + ) + + B, T, H, D = q.shape + + num_chunks = triton.cdiv(T, chunk_size) + grid = (num_chunks, H * B) + + x_out = torch.empty_like(q) + o1 = torch.empty_like(q) + o2 = torch.empty_like(q) + o3 = torch.empty_like(q) + + abcd_heads = _normalize_abcd(learnable_abcd, H, q.device, torch.float32) + block_d = _choose_block_d(D) + q_kkt_solve_approx_gating_forward_kernel[grid]( + h_kk, + k, + q, + gkk, + abcd_heads, + x_out, + o1, + o2, + o3, + fro, + T, + H, + D, + chunk_size, + block_d, + load_fro, + ) + + return x_out, o1, o2, o3, fro, h_kk, h_kk_final + + +def q_kkt_solve_approx_backward_triton( + k: torch.Tensor, + dx: torch.Tensor, + gkk: torch.Tensor, + fro: torch.Tensor, + learnable_abcd: list = [1.0, -0.5, 0.375, -0.3125], + chunk_size: int = 64, + load_fro: int = 1, + output_final_state: bool = False, + h0=None, + h_kk: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Fused backward apply of self-adjoint phi(H). + + dq = phi(H) dx = a dx + b (dx @ H)/F + c (dx @ H^2)/F^2 + d (dx @ H^3)/F^3 + dx1 = (dx @ H) / F + dx2 = (dx @ H^2) / F^2 + + Pass ``h_kk`` from the forward to skip recomputing ``chunk_fwd_h``. + """ + if h_kk is None: + h_kk, h_kk_final = chunk_fwd_h( + k=k, + v=k, + g=gkk, + gk=None, + gv=None, + h0=h0, + output_final_state=output_final_state, + states_in_fp32=False, + cu_seqlens=None, + chunk_size=chunk_size, + ) + else: + h_kk_final = None + + B, T, H, D = dx.shape + num_chunks = triton.cdiv(T, chunk_size) + grid = (num_chunks, H * B) + + dq = torch.empty_like(dx) + dx1 = torch.empty_like(dx) + dx2 = torch.empty_like(dx) + # Forward kernel now also stores o3; backward only needs dq / dx1 / dx2. + dx3 = torch.empty_like(dx) + + abcd_heads = _normalize_abcd(learnable_abcd, H, dx.device, torch.float32) + block_d = _choose_block_d(D) + q_kkt_solve_approx_gating_forward_kernel[grid]( + h_kk, + k, + dx, + gkk, + abcd_heads, + dq, + dx1, + dx2, + dx3, + fro, + T, + H, + D, + chunk_size, + block_d, + load_fro, + ) + + return dq, dx1, dx2, fro, h_kk, h_kk_final + + +@triton.jit +def _bwd_load_vec( + ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D: tl.constexpr +): + """Load a [chunk_size, BLOCK_D] tile as fp32. + + Storage may be bf16; promote to fp32 so G_partial / dgk accumulate + in TF32 MMA instead of truncating operands to bf16. + """ + p = tl.make_block_ptr( + ptr, + (T, D), + (H * D, 1), + (chunk_id * chunk_size, d0), + (chunk_size, BLOCK_D), + (1, 0), + ) + x = tl.load(p, boundary_check=(0, 1)).to(tl.float32) + return tl.where(m_t[:, None], x, 0.0) + + +@triton.jit +def _bwd_store_vec(ptr, val, T, H, D, chunk_id, chunk_size, d0, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr( + ptr, + (T, D), + (H * D, 1), + (chunk_id * chunk_size, d0), + (chunk_size, BLOCK_D), + (1, 0), + ) + tl.store( + p, + val.to(p.dtype.element_ty, fp_downcast_rounding="rtne"), + boundary_check=(0, 1), + ) + + +@triton.jit +def _bwd_load_mat(ptr, D, r0, c0, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr( + ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0) + ) + return tl.load(p, boundary_check=(0, 1)).to(tl.float32) + + +@triton.jit +def _bwd_store_mat(ptr, val, D, r0, c0, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr( + ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0) + ) + tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1)) + + +@triton.jit +def _bwd_dot_xyT( + x_ptr, + y_ptr, + T, + H, + D, + chunk_id, + chunk_size, + m_t, + BLOCK_D: tl.constexpr, + NUM_D: tl.constexpr, +): + S = tl.zeros((chunk_size, chunk_size), dtype=tl.float32) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + x = _bwd_load_vec(x_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + y = _bwd_load_vec(y_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + S += tl.dot(x, tl.trans(y)) + return S + + +@triton.jit +def _bwd_acc_weighted( + dk_ptr, + v_ptr, + A, + S, + T, + H, + D, + chunk_id, + chunk_size, + m_t, + BLOCK_D: tl.constexpr, + NUM_D: tl.constexpr, +): + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + v = _bwd_load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dk = _bwd_load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + _bwd_store_vec( + dk_ptr, + dk + tl.dot(tl.trans(A * S), v), + T, + H, + D, + chunk_id, + chunk_size, + d0, + BLOCK_D, + ) + + +@triton.jit +def _bwd_h0v( + v_ptr, + h0_ptr, + T, + H, + D, + chunk_id, + chunk_size, + d0, + m_t, + BLOCK_D: tl.constexpr, + NUM_D: tl.constexpr, +): + """(v @ h0^T)[:, d0:d0+BD] = sum_d1 v[:, d1] @ h0[d0, d1].T""" + acc = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + for j in tl.static_range(0, NUM_D): + d1 = j * BLOCK_D + v1 = _bwd_load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + h01 = _bwd_load_mat(h0_ptr, D, d0, d1, BLOCK_D) + acc += tl.dot(v1, tl.trans(h01)) + return acc + + +@triton.jit +def _fwd_vh( + v_ptr, + h_ptr, + T, + H, + D, + chunk_id, + chunk_size, + d0, + m_t, + BLOCK_D: tl.constexpr, + NUM_D: tl.constexpr, +): + """(v @ h)[:, d0:d0+BD] = sum_d1 v[:, d1] @ h[d1, d0].""" + acc = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + for j in tl.static_range(0, NUM_D): + d1 = j * BLOCK_D + v1 = _bwd_load_vec(v_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + h01 = _bwd_load_mat(h_ptr, D, d1, d0, BLOCK_D) + acc += tl.dot(v1, h01) + return acc + + +@triton.jit +def _bwd_gin_reverse_scan_kernel( + g_partial_ptr, + scale_last_ptr, + gin_ptr, + dht_ptr, + NC: tl.constexpr, + H: tl.constexpr, + D: tl.constexpr, + BLOCK_D: tl.constexpr, + HAS_DHT: tl.constexpr, +): + """gin[c] = g_partial[c+1] + scale_last[c+1] * gin[c+1], gin[-1] = dht. + + Grid: (B*H, NUM_D*NUM_D). Each program carries one [BLOCK_D, BLOCK_D] + tile; tiles are independent (scalar * matrix). D=64 uses one tile. + A full [128, 128] fp32 carry would exceed A100 SMEM. + """ + i_bh = tl.program_id(0) + i_tile = tl.program_id(1) + i_b, i_h = i_bh // H, i_bh % H + NUM_D: tl.constexpr = D // BLOCK_D + r0 = (i_tile // NUM_D) * BLOCK_D + c0 = (i_tile % NUM_D) * BLOCK_D + G = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32) + if HAS_DHT: + p_dht = tl.make_block_ptr( + dht_ptr + (i_b * H + i_h).to(tl.int64) * D * D, + (D, D), + (D, 1), + (r0, c0), + (BLOCK_D, BLOCK_D), + (1, 0), + ) + G = tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32) + last = NC - 1 + p_gin = tl.make_block_ptr( + gin_ptr + ((i_b * NC + last) * H + i_h).to(tl.int64) * D * D, + (D, D), + (D, 1), + (r0, c0), + (BLOCK_D, BLOCK_D), + (1, 0), + ) + tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1)) + # Triton range() does not reliably support a negative step; walk it=0..NC-2. + for it in tl.range(0, NC - 1): + cid = NC - 2 - it + src = cid + 1 + p_gp = tl.make_block_ptr( + g_partial_ptr + ((i_b * NC + src) * H + i_h).to(tl.int64) * D * D, + (D, D), + (D, 1), + (r0, c0), + (BLOCK_D, BLOCK_D), + (1, 0), + ) + gp = tl.load(p_gp, boundary_check=(0, 1)).to(tl.float32) + s = tl.load(scale_last_ptr + (i_b * NC + src) * H + i_h).to(tl.float32) + G = gp + s * G + p_gin = tl.make_block_ptr( + gin_ptr + ((i_b * NC + cid) * H + i_h).to(tl.int64) * D * D, + (D, D), + (D, 1), + (r0, c0), + (BLOCK_D, BLOCK_D), + (1, 0), + ) + tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1)) + + + +@triton.jit(do_not_specialize=["T"]) +def q_kkt_bwd_chunk_kernel( + h_kk_ptr, + k_ptr, + q_ptr, + o1_ptr, + du_ptr, + dv_ptr, + alpha_ptr, + gkk_ptr, + gin_ptr, + g_partial_ptr, + scale_last_ptr, + dk_ptr, + dgk_ptr, + T, + H: tl.constexpr, + D: tl.constexpr, + chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, + STAGE: tl.constexpr, + HAS_GK: tl.constexpr, +): + """Intra-chunk dk/dgk for the (q, o1, du, dv) terms. D is tiled by BLOCK_D. + + D=64 uses BLOCK_D=64 (one tile). D=128 uses BLOCK_D=32. + Cubic (o2, dw) terms stay in ``q_kkt_bwd_chunk_o2_kernel`` to keep SMEM + under A100's 163 KiB when BLOCK_D=64. + + STAGE 0: no G_in. Writes intra dk/dgk, G_partial, scale_last. + STAGE 1: loads per-chunk G_in (after reverse scan) and adds boundary terms. + + dgk_t = is formed with strictly-lower-triangular A + (previous tokens only), avoiding the unstable - 0.5 split. + """ + chunk_id, bh_id = tl.program_id(0), tl.program_id(1) + b_id, h_id = bh_id // H, bh_id % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + + scalar_off = b_id * T * H + h_id + gkk_ptr += scalar_off + alpha_ptr += scalar_off + dgk_ptr += scalar_off + vec_off = scalar_off * D + k_ptr += vec_off + q_ptr += vec_off + o1_ptr += vec_off + du_ptr += vec_off + dv_ptr += vec_off + dk_ptr += vec_off + mat_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + h_kk_ptr += mat_off + gin_ptr += mat_off + g_partial_ptr += mat_off + + p_gkk = tl.make_block_ptr( + gkk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + p_dgk = tl.make_block_ptr( + dgk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + gkk = tl.load(p_gkk, boundary_check=(0,)).to(tl.float32) + o_t = chunk_id * chunk_size + tl.arange(0, chunk_size) + m_t = o_t < T + A = tl.where( + (o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :]), + exp(gkk[:, None] - gkk[None, :]), + 0.0, + ) + # Strict causal: H_t - k_t k_t^T, so dgk_t = + # without subtracting (that cancellation is the dgk error source). + A_strict = tl.where(o_t[:, None] > o_t[None, :], A, 0.0) + scale = tl.where(m_t, exp(gkk), 0.0) + chunk_range = tl.arange(0, chunk_size) + last = tl.minimum(chunk_size, T - chunk_id * chunk_size) - 1 + is_last = chunk_range == last + w_last = tl.sum(tl.where(is_last[:, None], A, 0.0), axis=0) + scale_last = tl.sum(tl.where(is_last, scale, 0.0)) + + if STAGE == 0: + p_alpha = tl.make_block_ptr( + alpha_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + alpha = tl.where(m_t, tl.load(p_alpha, boundary_check=(0,)).to(tl.float32), 0.0) + + S_duk = _bwd_dot_xyT( + du_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + S_qk = _bwd_dot_xyT( + q_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + _bwd_acc_weighted( + dk_ptr, q_ptr, A, S_duk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + _bwd_acc_weighted( + dk_ptr, du_ptr, A, S_qk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + M = tl.dot(tl.trans(S_duk) * tl.trans(S_qk), A) + + S_dvk = _bwd_dot_xyT( + dv_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + S_o1k = _bwd_dot_xyT( + o1_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + _bwd_acc_weighted( + dk_ptr, o1_ptr, A, S_dvk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + _bwd_acc_weighted( + dk_ptr, dv_ptr, A, S_o1k, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + M += tl.dot(tl.trans(S_dvk) * tl.trans(S_o1k), A) + + beta = tl.sum(A * (alpha * scale)[:, None], axis=0) + z = tl.zeros((chunk_size,), dtype=tl.float32) + n0 = tl.zeros((1,), dtype=tl.float32) + vec_h0 = tl.zeros((chunk_size,), dtype=tl.float32) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + h0k = _bwd_h0v( + k_ptr, + h_kk_ptr, + T, + H, + D, + chunk_id, + chunk_size, + d0, + m_t, + BLOCK_D, + NUM_D, + ) + k0 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dk = _bwd_load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + _bwd_store_vec( + dk_ptr, + dk + 2.0 * beta[:, None] * h0k, + T, + H, + D, + chunk_id, + chunk_size, + d0, + BLOCK_D, + ) + z += tl.sum(h0k * k0, axis=1) + h0q = _bwd_h0v( + q_ptr, + h_kk_ptr, + T, + H, + D, + chunk_id, + chunk_size, + d0, + m_t, + BLOCK_D, + NUM_D, + ) + h0o1 = _bwd_h0v( + o1_ptr, + h_kk_ptr, + T, + H, + D, + chunk_id, + chunk_size, + d0, + m_t, + BLOCK_D, + NUM_D, + ) + du0 = _bwd_load_vec(du_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dv0 = _bwd_load_vec(dv_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + vec_h0 += tl.sum(h0q * du0, axis=1) + tl.sum(h0o1 * dv0, axis=1) + for j in tl.static_range(0, NUM_D): + d1 = j * BLOCK_D + h0_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D) + n0 += tl.sum(tl.sum(h0_tile * h0_tile, axis=0), axis=0) + + P = tl.dot(tl.trans(A), alpha[:, None] * A) + S_kk = _bwd_dot_xyT( + k_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + ones = tl.zeros((chunk_size, chunk_size), dtype=tl.float32) + 1.0 + _bwd_acc_weighted( + dk_ptr, + k_ptr, + 2.0 * (S_kk * P), + ones, + T, + H, + D, + chunk_id, + chunk_size, + m_t, + BLOCK_D, + NUM_D, + ) + + c0 = tl.sum(alpha * scale * scale) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + q0 = _bwd_load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o10 = _bwd_load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + k0 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + for j in tl.static_range(0, NUM_D): + d1 = j * BLOCK_D + du1 = _bwd_load_vec( + du_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D + ) + dv1 = _bwd_load_vec( + dv_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D + ) + k1 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + h0_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D) + Rout = tl.dot(tl.trans(scale[:, None] * q0), du1) + tl.dot( + tl.trans(scale[:, None] * o10), dv1 + ) + G_partial = ( + Rout + + c0 * h0_tile + + tl.dot(tl.trans(beta[:, None] * k0), k1) + ) + _bwd_store_mat(g_partial_ptr, G_partial, D, d0, d1, BLOCK_D) + tl.store(scale_last_ptr + (b_id * num_chunks + chunk_id) * H + h_id, scale_last) + + RH = scale * tl.sum(A * vec_h0[:, None], axis=0) + tl.sum( + A_strict * tl.trans(M), axis=1 + ) + Az = tl.sum(A * z[None, :], axis=1) + Az_prev = tl.sum(A_strict * z[None, :], axis=1) + N = tl.dot(A, tl.dot(S_kk * S_kk, tl.trans(A_strict))) + n0_s = tl.sum(n0) + HH = ( + n0_s * scale * beta + + Az_prev * beta + + scale * tl.sum(A * (alpha * Az)[:, None], axis=0) + + tl.sum(alpha[:, None] * A * N, axis=0) + ) + dgk = RH + HH + tl.store( + p_dgk, + tl.where(m_t, dgk, 0.0).to(p_dgk.dtype.element_ty, fp_downcast_rounding="rtne"), + boundary_check=(0,), + ) + else: + dgk0 = tl.load(p_dgk, boundary_check=(0,)).to(tl.float32) + u = tl.zeros((chunk_size,), dtype=tl.float32) + n_gh = tl.zeros((1,), dtype=tl.float32) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + acc = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + gink = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + k0 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + for j in tl.static_range(0, NUM_D): + d1 = j * BLOCK_D + k1 = _bwd_load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + G_d0d1 = _bwd_load_mat(gin_ptr, D, d0, d1, BLOCK_D) + G_d1d0 = _bwd_load_mat(gin_ptr, D, d1, d0, BLOCK_D) + h0_tile = _bwd_load_mat(h_kk_ptr, D, d0, d1, BLOCK_D) + acc += tl.dot(k1, G_d1d0) + tl.dot(k1, tl.trans(G_d0d1)) + gink += tl.dot(k1, tl.trans(G_d0d1)) + n_gh += tl.sum(tl.sum(G_d0d1 * h0_tile, axis=0), axis=0) + dk0 = _bwd_load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dk = dk0 + w_last[:, None] * acc + _bwd_store_vec(dk_ptr, dk, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + u += tl.sum(gink * k0, axis=1) + Gin_H = scale * tl.sum(n_gh) + tl.sum(A_strict * u[None, :], axis=1) + dgk = dgk0 + w_last * Gin_H + tl.store( + p_dgk, + tl.where(m_t, dgk, 0.0).to(p_dgk.dtype.element_ty, fp_downcast_rounding="rtne"), + boundary_check=(0,), + ) + + +@triton.jit(do_not_specialize=["T"]) +def q_kkt_bwd_chunk_o2_kernel( + h_kk_ptr, + k_ptr, + o2_ptr, + dw_ptr, + gkk_ptr, + g_partial_ptr, + dk_ptr, + dgk_ptr, + T, + H: tl.constexpr, + D: tl.constexpr, + chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, +): + """Add cubic (o2, dw) contributions onto STAGE-0 dk / G_partial / dgk. + + Same BLOCK_D tiling as ``q_kkt_bwd_chunk_kernel``. Kept separate so + A100 SMEM stays under 163 KiB when D=64 / BLOCK_D=64. + """ + chunk_id, bh_id = tl.program_id(0), tl.program_id(1) + b_id, h_id = bh_id // H, bh_id % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + + scalar_off = b_id * T * H + h_id + gkk_ptr += scalar_off + dgk_ptr += scalar_off + vec_off = scalar_off * D + k_ptr += vec_off + o2_ptr += vec_off + dw_ptr += vec_off + dk_ptr += vec_off + mat_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + h_kk_ptr += mat_off + g_partial_ptr += mat_off + + p_gkk = tl.make_block_ptr( + gkk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + p_dgk = tl.make_block_ptr( + dgk_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + gkk = tl.load(p_gkk, boundary_check=(0,)).to(tl.float32) + o_t = chunk_id * chunk_size + tl.arange(0, chunk_size) + m_t = o_t < T + A = tl.where( + (o_t[:, None] >= o_t[None, :]) & (m_t[:, None] & m_t[None, :]), + exp(gkk[:, None] - gkk[None, :]), + 0.0, + ) + A_strict = tl.where(o_t[:, None] > o_t[None, :], A, 0.0) + scale = tl.where(m_t, exp(gkk), 0.0) + + S_dwk = _bwd_dot_xyT( + dw_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + S_o2k = _bwd_dot_xyT( + o2_ptr, k_ptr, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + _bwd_acc_weighted( + dk_ptr, o2_ptr, A, S_dwk, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + _bwd_acc_weighted( + dk_ptr, dw_ptr, A, S_o2k, T, H, D, chunk_id, chunk_size, m_t, BLOCK_D, NUM_D + ) + + vec_h0 = tl.zeros((chunk_size,), dtype=tl.float32) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + h0o2 = _bwd_h0v( + o2_ptr, + h_kk_ptr, + T, + H, + D, + chunk_id, + chunk_size, + d0, + m_t, + BLOCK_D, + NUM_D, + ) + dw0 = _bwd_load_vec(dw_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + vec_h0 += tl.sum(h0o2 * dw0, axis=1) + + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + o20 = _bwd_load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + for j in tl.static_range(0, NUM_D): + d1 = j * BLOCK_D + dw1 = _bwd_load_vec( + dw_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D + ) + Rout = tl.dot(tl.trans(scale[:, None] * o20), dw1) + G = _bwd_load_mat(g_partial_ptr, D, d0, d1, BLOCK_D) + Rout + _bwd_store_mat(g_partial_ptr, G, D, d0, d1, BLOCK_D) + + M = tl.dot(tl.trans(S_dwk) * tl.trans(S_o2k), A) + RH = scale * tl.sum(A * vec_h0[:, None], axis=0) + tl.sum( + A_strict * tl.trans(M), axis=1 + ) + dgk0 = tl.load(p_dgk, boundary_check=(0,)).to(tl.float32) + dgk = dgk0 + RH + tl.store( + p_dgk, + tl.where(m_t, dgk, 0.0).to(p_dgk.dtype.element_ty, fp_downcast_rounding="rtne"), + boundary_check=(0,), + ) + + +def _bwd_dH_to_dk_dgk( + k: torch.Tensor, + q: torch.Tensor, + o1: torch.Tensor, + o2: torch.Tensor, + du: torch.Tensor, + dv: torch.Tensor, + dw: torch.Tensor, + alpha: torch.Tensor, + gk: Optional[torch.Tensor], + gkk: Optional[torch.Tensor], + dht: Optional[torch.Tensor], + h_kk: torch.Tensor, + h0, + chunk_size: int, + scan_mode: str = "gpu_scan", + block_d: Optional[int] = None, +) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]: + """ + Reverse-mode through H_t = exp(gk_t) H_{t-1} + k_t k_t^T. + + Intra-chunk work is a Triton kernel with grid (num_chunks, B*H). + D is tiled by BLOCK_D (64 for D=64, 32 for D=128). Cubic (o2, dw) terms + are a second kernel after STAGE 0. Inter-chunk G_in is a tiled reverse + scan (grid (B*H, NUM_D^2)). + + scan_mode: + python – STAGE 0 || o2 extra || host loop over chunks || STAGE 1 + gpu_scan – STAGE 0 || o2 extra || one Triton reverse-scan kernel || STAGE 1 + """ + B, T, nH, D = k.shape + block_d = int(block_d) if block_d is not None else _choose_block_d(D) + if D % block_d != 0: + raise ValueError(f"D={D} must be divisible by BLOCK_D={block_d}") + if scan_mode not in ("python", "gpu_scan"): + raise ValueError(f"unknown scan_mode={scan_mode!r}") + num_chunks = (T + chunk_size - 1) // chunk_size + k = k.contiguous() + q = q.contiguous() + o1 = o1.contiguous() + o2 = o2.contiguous() + du = du.contiguous() + dv = dv.contiguous() + dw = dw.contiguous() + alpha = alpha.contiguous() + h_kk = h_kk.contiguous() + if gkk is None: + gkk = torch.zeros(B, T, nH, device=k.device, dtype=torch.float32) + has_gk = gk is not None + dk = torch.zeros_like(k, dtype=torch.float32) + dgk = torch.zeros(B, T, nH, device=k.device, dtype=torch.float32) + # STAGE 0/1 have no autotune (would re-run and double-add into dk). + # Sweep on A100: (4 warps, 1–3 stages) all ~0.39 ms; 8 warps is slower. + launch = dict(num_warps=4, num_stages=1) + + g_partial = torch.empty(B, num_chunks, nH, D, D, device=k.device, dtype=torch.float32) + scale_last = torch.empty(B, num_chunks, nH, device=k.device, dtype=torch.float32) + gin = torch.empty(B, num_chunks, nH, D, D, device=k.device, dtype=torch.float32) + grid = (num_chunks, nH * B) + + q_kkt_bwd_chunk_kernel[grid]( + h_kk, + k, + q, + o1, + du, + dv, + alpha, + gkk, + gin, + g_partial, + scale_last, + dk, + dgk, + T, + nH, + D, + chunk_size, + block_d, + 0, + int(has_gk), + **launch, + ) + q_kkt_bwd_chunk_o2_kernel[grid]( + h_kk, + k, + o2, + dw, + gkk, + g_partial, + dk, + dgk, + T, + nH, + D, + chunk_size, + block_d, + **launch, + ) + if scan_mode == "python": + if dht is not None: + gin[:, -1] = dht.float() + else: + gin[:, -1] = 0 + for cid in range(num_chunks - 2, -1, -1): + gin[:, cid] = g_partial[:, cid + 1] + scale_last[ + :, cid + 1, :, None, None + ] * gin[:, cid + 1] + else: + dummy = h_kk.new_empty(B, nH, D, D) + dht_buf = dht.float().contiguous() if dht is not None else dummy + num_d = D // block_d + _bwd_gin_reverse_scan_kernel[(nH * B, num_d * num_d)]( + g_partial, + scale_last, + gin, + dht_buf, + num_chunks, + nH, + D, + block_d, + int(dht is not None), + num_warps=4, + num_stages=1, + ) + q_kkt_bwd_chunk_kernel[grid]( + h_kk, + k, + q, + o1, + du, + dv, + alpha, + gkk, + gin, + g_partial, + scale_last, + dk, + dgk, + T, + nH, + D, + chunk_size, + block_d, + 1, + int(has_gk), + **launch, + ) + dh0 = None + if h0 is not None: + dh0 = ( + g_partial[:, 0] + scale_last[:, 0, :, None, None] * gin[:, 0] + ).to(h0.dtype) + return ( + dk.to(k.dtype), + dgk.to(gk.dtype) if has_gk else None, + dh0, + ) + + +@triton.jit(do_not_specialize=["T"]) +def q_kkt_bwd_prep_kernel( + q_ptr, + o1_ptr, + o2_ptr, + o3_ptr, + dx_ptr, + dx1_ptr, + dx2_ptr, + fro_ptr, + abcd_ptr, + du_ptr, + dv_ptr, + dw_ptr, + alpha_ptr, + dabcd_ptr, + T, + H: tl.constexpr, + D: tl.constexpr, + chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, + NEED_DABCD: tl.constexpr, + EPS: tl.constexpr, +): + """Fuse stored o3 / du / dv / dw / alpha / partial dabcd for one (chunk, B*H).""" + chunk_id, bh_id = tl.program_id(0), tl.program_id(1) + b_id, h_id = bh_id // H, bh_id % H + NUM_D: tl.constexpr = D // BLOCK_D + num_chunks = tl.cdiv(T, chunk_size) + + scalar_off = b_id * T * H + h_id + fro_ptr += scalar_off + alpha_ptr += scalar_off + vec_off = scalar_off * D + q_ptr += vec_off + o1_ptr += vec_off + o2_ptr += vec_off + o3_ptr += vec_off + dx_ptr += vec_off + dx1_ptr += vec_off + dx2_ptr += vec_off + du_ptr += vec_off + dv_ptr += vec_off + dw_ptr += vec_off + + o_t = chunk_id * chunk_size + tl.arange(0, chunk_size) + m_t = o_t < T + p_fro = tl.make_block_ptr( + fro_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + fro = tl.where(m_t, tl.load(p_fro, boundary_check=(0,)).to(tl.float32), 0.0) + F = fro + EPS + b = tl.load(abcd_ptr + h_id * 4 + 1).to(tl.float32) + c = tl.load(abcd_ptr + h_id * 4 + 2).to(tl.float32) + d = tl.load(abcd_ptr + h_id * 4 + 3).to(tl.float32) + + s_o1dx = tl.zeros((chunk_size,), dtype=tl.float32) + s_o2dx = tl.zeros((chunk_size,), dtype=tl.float32) + s_o3dx = tl.zeros((chunk_size,), dtype=tl.float32) + da = tl.zeros((1,), dtype=tl.float32) + db = tl.zeros((1,), dtype=tl.float32) + dc = tl.zeros((1,), dtype=tl.float32) + dd = tl.zeros((1,), dtype=tl.float32) + for i in tl.static_range(0, NUM_D): + d0 = i * BLOCK_D + q = _bwd_load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o1 = _bwd_load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o2 = _bwd_load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o3 = _bwd_load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dx = _bwd_load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dx1 = _bwd_load_vec(dx1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dx2 = _bwd_load_vec(dx2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + _bwd_store_vec( + du_ptr, + (b * dx + c * dx1 + d * dx2) / F[:, None], + T, + H, + D, + chunk_id, + chunk_size, + d0, + BLOCK_D, + ) + _bwd_store_vec( + dv_ptr, + (c * dx + d * dx1) / F[:, None], + T, + H, + D, + chunk_id, + chunk_size, + d0, + BLOCK_D, + ) + _bwd_store_vec( + dw_ptr, (d * dx) / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D + ) + s_o1dx += tl.sum(o1 * dx, axis=1) + s_o2dx += tl.sum(o2 * dx, axis=1) + s_o3dx += tl.sum(o3 * dx, axis=1) + if NEED_DABCD: + da += tl.sum(tl.sum(dx * q, axis=0), axis=0) + db += tl.sum(tl.sum(dx * o1, axis=0), axis=0) + dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0) + dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0) + + alpha = -(b * s_o1dx + 2.0 * c * s_o2dx + 3.0 * d * s_o3dx) / (F * F) + p_alpha = tl.make_block_ptr( + alpha_ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,) + ) + tl.store( + p_alpha, + tl.where(m_t, alpha, 0.0).to(p_alpha.dtype.element_ty, fp_downcast_rounding="rtne"), + boundary_check=(0,), + ) + if NEED_DABCD: + off = ((b_id * num_chunks + chunk_id) * H + h_id) * 4 + tl.store(dabcd_ptr + off + 0, tl.sum(da)) + tl.store(dabcd_ptr + off + 1, tl.sum(db)) + tl.store(dabcd_ptr + off + 2, tl.sum(dc)) + tl.store(dabcd_ptr + off + 3, tl.sum(dd)) + + +def _bwd_prep_du_dv_dw_alpha( + q: torch.Tensor, + o1: torch.Tensor, + o2: torch.Tensor, + o3: torch.Tensor, + dx: torch.Tensor, + dx1: torch.Tensor, + dx2: torch.Tensor, + fro: torch.Tensor, + abcd_heads: torch.Tensor, + chunk_size: int, + need_dabcd: bool, +) -> Tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor] +]: + B, T, H, D = q.shape + block_d = _choose_block_d(D) + num_chunks = (T + chunk_size - 1) // chunk_size + du = torch.empty_like(q) + dv = torch.empty_like(q) + dw = torch.empty_like(q) + alpha = torch.empty(B, T, H, device=q.device, dtype=torch.float32) + dabcd = ( + torch.empty(B, num_chunks, H, 4, device=q.device, dtype=torch.float32) + if need_dabcd + else q.new_empty(1) + ) + q_kkt_bwd_prep_kernel[(num_chunks, H * B)]( + q, + o1, + o2, + o3, + dx, + dx1, + dx2, + fro, + abcd_heads, + du, + dv, + dw, + alpha, + dabcd, + T, + H, + D, + chunk_size, + block_d, + int(need_dabcd), + 1e-12, + num_warps=4, + num_stages=1, + ) + d_abcd_h = dabcd.sum(dim=(0, 1)) if need_dabcd else None + return du, dv, dw, alpha, d_abcd_h + + +class q_kkt_solve_approx(torch.autograd.Function): + """ + Autograd for x_t = q_t @ phi(H_t), phi(H) ~ a I + b H/F + c H^2/F^2 + d H^3/F^3. + + a, b, c, d are per-head learnable scalars packed as a tensor of shape [H, 4]. + A length-4 / [4] input is broadcast to all heads; its gradient is summed over heads. + """ + + @staticmethod + def forward( + ctx, + k: torch.Tensor, + q: torch.Tensor, + gk: Optional[torch.Tensor] = None, + chunk_size: int = 64, + learnable_abcd: Union[torch.Tensor, Sequence[float]] = ( + 1.0, + -0.5, + 0.375, + -0.3125, + ), + h0=None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + B, T, H, D = q.shape + fro = torch.empty((B, T, H), dtype=torch.float32, device=q.device) + abc_is_tensor = torch.is_tensor(learnable_abcd) + if abc_is_tensor: + ctx.abc_dtype = learnable_abcd.dtype + assert learnable_abcd.dtype == torch.float32, f"learnable_abcd.dtype must be float32, got {learnable_abcd.dtype}" + ctx.abc_device = learnable_abcd.device + ctx.abc_shape = tuple(learnable_abcd.shape) + else: + assert abc_is_tensor, "learnable_abcd must be a tensor" + + abcd_heads = _normalize_abcd(learnable_abcd, H, q.device, torch.float32) + gkk = chunk_local_cumsum(gk, chunk_size=chunk_size) if gk is not None else None + x_out, o1, o2, o3, fro, h_kk, h_kk_final = q_kkt_solve_approx_forward_triton( + k, + q, + gkk, + fro, + learnable_abcd=abcd_heads, + chunk_size=chunk_size, + load_fro=0, + output_final_state=True, + h0=h0, + ) + to_save = [k, q, o1, o2, o3, fro, abcd_heads, h_kk] + if gk is not None: + to_save.append(gk) + if gkk is not None: + to_save.append(gkk) + if h0 is not None: + to_save.append(h0) + ctx.save_for_backward(*to_save) + ctx.chunk_size = chunk_size + ctx.has_gk = gk is not None + ctx.has_gkk = gkk is not None + ctx.has_h0 = h0 is not None + return x_out, h_kk_final + + @staticmethod + def backward( + ctx, dx_out: torch.Tensor, d_kk_final: Optional[torch.Tensor] = None + ) -> Tuple[ + Optional[torch.Tensor], + Optional[torch.Tensor], + Optional[torch.Tensor], + None, + Optional[torch.Tensor], + Optional[torch.Tensor], + ]: + saved = list(ctx.saved_tensors) + k, q, o1, o2, o3, fro, abcd_heads, h_kk = saved[:8] + idx = 8 + gk = saved[idx] if ctx.has_gk else None + idx += int(ctx.has_gk) + gkk = saved[idx] if ctx.has_gkk else None + idx += int(ctx.has_gkk) + h0 = saved[idx] if ctx.has_h0 else None + chunk_size = ctx.chunk_size + + dq, dx1, dx2, fro, h_kk, _ = q_kkt_solve_approx_backward_triton( + k, + dx_out, + gkk, + fro, + learnable_abcd=abcd_heads, + chunk_size=chunk_size, + load_fro=1, + output_final_state=False, + h0=h0, + h_kk=h_kk, + ) + need_dabcd = bool(ctx.needs_input_grad[4]) + du, dv, dw, alpha, d_abcd_h = _bwd_prep_du_dv_dw_alpha( + q, + o1, + o2, + o3, + dx_out, + dx1, + dx2, + fro, + abcd_heads, + chunk_size, + need_dabcd, + ) + dk, dgk, dh0 = _bwd_dH_to_dk_dgk( + k, + q, + o1, + o2, + du, + dv, + dw, + alpha, + gk, + gkk, + d_kk_final, + h_kk, + h0, + chunk_size, + ) + d_abcd = None + if need_dabcd: + if ctx.abc_shape == (4,) or ( + len(ctx.abc_shape) == 1 and ctx.abc_shape[0] == 4 + ): + d_abcd = d_abcd_h.sum(dim=0) + else: + d_abcd = d_abcd_h + d_abcd = d_abcd.to(dtype=ctx.abc_dtype, device=ctx.abc_device).reshape( + ctx.abc_shape + ) + return dk, dq, dgk, None, d_abcd, dh0 + + +############# +def test_q_kkt_solve_approx(q, k, gk, a=1.0, b=-0.5, c=0.375, d=-0.3125): + """ + PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2). + + We follow the GLA recurrence to build the per-step key-key state + H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action + on q_t by a cubic polynomial in H_t / ||H_t||_F: + + q_t_out = a * q_t + + b * (q_t @ H_t) / ||H_t||_F + + c * (q_t @ H_t @ H_t) / ||H_t||_F^2 + + d * (q_t @ H_t @ H_t @ H_t) / ||H_t||_F^3 + + Args: + q: Query tensor with shape [B, T, H, D]. + k: Key tensor with shape [B, T, H, D]. + gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use. + a, b, c, d: Polynomial coefficients. Each may be a scalar or a length-H tensor. + + Returns: + o: Output tensor with shape [B, T, H, D]. + states: List of length T, each [B, H, D, D] (the per-step H_t). + fros: List of length T, each [B, H] (per-step Frobenius norm). + """ + B, T, H, D = q.shape + + def _coeff(x): + if torch.is_tensor(x): + t = x.reshape(-1) + if t.numel() == 1: + t = t.expand(H) + elif t.numel() != H: + raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}") + return t.to(device=q.device).view(1, H, 1) + return x + + a = _coeff(a) + b = _coeff(b) + c = _coeff(c) + d = _coeff(d) + state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device) + gkk = torch.exp(gk.float()).float() + + outs = [] + states = [] + fros = [] + + for i in range(T): + ki = k[:, i, :, :].float() # [B, H, D] + # GLA-style state update: H_t = exp(g_t) * H_{t-1} + k_t k_t^T + state = gkk[:, i, :].view(B, H, 1, 1).float() * state + ki.unsqueeze(-1).float() * ki.unsqueeze(-2).float() + F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float() + F_safe = F + 1e-12 + qi = q[:, i, :, :].float() # [B, H, D] + q_state = (qi.unsqueeze(-2) @ state).squeeze(-2).float() + q_state2 = (q_state.unsqueeze(-2) @ state).squeeze(-2).float() + q_state3 = (q_state2.unsqueeze(-2) @ state).squeeze(-2).float() + out = ( + a * qi + + b * q_state / F_safe + + c * q_state2 / (F_safe * F_safe) + + d * q_state3 / (F_safe * F_safe * F_safe) + ).to(q.dtype) + outs.append(out) + states.append(state.clone()) + fros.append(F.squeeze(-1).clone()) + o = torch.stack(outs, dim=1) + return o, states, fros + + +############## +if __name__ == "__main__": + k = torch.randn(1, 10, 1, 64) + q = torch.randn(1, 10, 1, 64) + gk = torch.randn(1, 10, 1) + a, b, c, d = 1.0, -0.5, 0.375, -0.3125 # Taylor (1+x)^(-1/2) through x^3 + + o_ref, states, fros = test_q_kkt_solve_approx(q, k, gk, a, b, c, d) + print("Reference output shape:", o_ref.shape) + print("Reference output:", o_ref) + print("Number of states:", len(states), "last state shape:", states[-1].shape) + print("Last Frobenius norm:", fros[-1]) + + + diff --git a/ops/phi_kkt_approx_trace/q_kkt_solve_trace_triton_safe_ver1.py b/ops/phi_kkt_approx_trace/q_kkt_solve_trace_triton_safe_ver1.py new file mode 100644 index 0000000000000000000000000000000000000000..6a33350c63916cb6c36b89df73015d98f59f7f7e --- /dev/null +++ b/ops/phi_kkt_approx_trace/q_kkt_solve_trace_triton_safe_ver1.py @@ -0,0 +1,2133 @@ +"""ver1 of the safe trace-KKT kernel. + +Same math as ``q_kkt_solve_trace_triton_safe_baseline``. For D == BLOCK_D and +at most two blocks per chunk, the polynomial orders share one load of each +key/gate tile (score and apply no longer reload it), and the six backward +``trace_z_kb`` launches collapse into two. + +Triton chunk implementation of trace-normalized phi-KKT, with KDA-style gates. + +Same recurrence as ``q_kkt_solve_trace_triton.py``. A chunk of 64 is two blocks +of 32 (chunk 16 stays at 16). Scores use one reference per block so the two factors of +``exp(Gam_t - Gam_i)`` stay inside the fp32 range: + + off-diagonal: reference = first token of the query block (both factors <= 1 + when gk is non-positive) + diagonal: reference = that token minus (BC - 1), the same shift KDA uses + for s = 2. The diagonal dot is tf32 when the matmul preset is + bf16, because a factor can exceed the bf16 range. + +The trace is the one-step recurrence ``d_t = exp(gk_t) d_{t-1} + k_t^2``. +``exp(-Gam)`` is never materialized. +""" +import os + +import torch +import triton +import triton.language as tl + +from fla.ops.common.chunk_h import chunk_fwd_h +from fla.ops.utils import chunk_local_cumsum + + +EPS = 1e-12 +# Matmul operand precision; gate math (exp, cumsums) is always fp32. +# bf16 operands cast to bf16, fp32 accumulate. Diagonal-block dots stay tf32. +# tf32 fp32 operands on TF32 tensor cores +# tf32x3 hand-written 3xTF32 +# The tf32 / tf32x3 values are bit masks over the ``_dot`` call sites (set bit = 3xTF32). +_PREC_MASKS = {"tf32": 0, "tf32x3": 0x7F, "bf16": 0x100} +DOT_PRECISION = _PREC_MASKS[os.environ.get("TRACE_KKT_DOT_PRECISION", "bf16")] +# 32-wide blocks for chunk >= 32. A 64-wide block is one diagonal tile and +# stays on tf32, which measured slower than 32-wide bf16 off-diagonal dots. +# exp over 31 steps of gk=-5 (exp(77.5)) still fits in fp32. +def _block_c(chunk_size: int, gk_abs_max: float = 5.0) -> int: + del gk_abs_max + return 32 if chunk_size >= 32 else 16 + + +def _launch_prec(block_c: int, gk_abs_max: float): + """Always the measured baseline: tf32 diagonal, shift = BC - 1.""" + del gk_abs_max + return DOT_PRECISION, float(block_c - 1) + + +def _choose_block_d(D: int) -> int: + if D % 64 == 0: + return 64 + if D % 32 == 0: + return 32 + if D % 16 == 0: + return 16 + raise ValueError(f"head dim D={D} must be divisible by 16, 32, or 64") + + +def _choose_intra_d(D: int) -> int: + """64-wide state tiles, same tensor-core tile as the original kernel. + + A 16-row score still reduces over the whole head inside ``_scores_block``. + """ + return _choose_block_d(D) + + +def _choose_scan_block(D: int) -> int: + return 8 if D >= 16 else D + + +def _normalize_coeff(coeff, H: int, device, dtype=torch.float32) -> torch.Tensor: + if torch.is_tensor(coeff): + t = coeff.detach().to(device=device, dtype=dtype) + else: + t = torch.tensor(list(coeff), device=device, dtype=dtype) + if t.dim() == 1: + t = t.reshape(1, -1).expand(H, -1).contiguous() + elif t.shape[0] != H: + raise ValueError(f"coeff must be [N] or [H, N] with H={H}, got {tuple(t.shape)}") + else: + t = t.contiguous() + if t.shape[-1] not in (3, 4): + raise ValueError(f"coeff last dim must be 3 or 4, got {t.shape[-1]}") + return t + + +# --------------------------------------------------------------------------- +# Loads / stores. Layout [B, T, H, D], pointer already at one (b, h). +# --------------------------------------------------------------------------- +@triton.jit +def _load_vec(ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr( + ptr, (T, D), (H * D, 1), + (chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0), + ) + x = tl.load(p, boundary_check=(0, 1)).to(tl.float32) + return tl.where(m_t[:, None], x, 0.0) + + +@triton.jit +def _store_vec(ptr, val, T, H, D, chunk_id, chunk_size, d0, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr( + ptr, (T, D), (H * D, 1), + (chunk_id * chunk_size, d0), (chunk_size, BLOCK_D), (1, 0), + ) + tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1)) + + +@triton.jit +def _load_bc(ptr, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr( + ptr, (T, D), (H * D, 1), + (chunk_id * chunk_size + s0, d0), (BLOCK_C, BLOCK_D), (1, 0), + ) + return tl.load(p, boundary_check=(0, 1)).to(tl.float32) + + +@triton.jit +def _store_bc(ptr, val, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C: tl.constexpr, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr( + ptr, (T, D), (H * D, 1), + (chunk_id * chunk_size + s0, d0), (BLOCK_C, BLOCK_D), (1, 0), + ) + tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1)) + + +@triton.jit +def _load_mat(ptr, D, r0, c0, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0)) + return tl.load(p, boundary_check=(0, 1)).to(tl.float32) + + +@triton.jit +def _store_mat(ptr, val, D, r0, c0, BLOCK_D: tl.constexpr): + p = tl.make_block_ptr(ptr, (D, D), (D, 1), (r0, c0), (BLOCK_D, BLOCK_D), (1, 0)) + tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0, 1)) + + +@triton.jit +def _load_row(ptr, T, H, chunk_id, chunk_size, m_t, other): + p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)) + return tl.where(m_t, tl.load(p, boundary_check=(0,)).to(tl.float32), other) + + +@triton.jit +def _store_row(ptr, val, T, H, chunk_id, chunk_size): + p = tl.make_block_ptr(ptr, (T,), (H,), (chunk_id * chunk_size,), (chunk_size,), (0,)) + tl.store(p, val.to(p.dtype.element_ty), boundary_check=(0,)) + + +@triton.jit +def _masks(chunk_id, chunk_size, T): + o_t = chunk_id * chunk_size + tl.arange(0, chunk_size) + m_t = o_t < T + return m_t + + +@triton.jit +def _suffix(x): + """Inclusive suffix sum over the chunk axis. x: [C, BD].""" + return tl.cumsum(x, axis=0, reverse=True) + + +@triton.jit +def _excl(x): + """Exclusive prefix sum over the chunk axis.""" + return tl.cumsum(x, axis=0) - x + + +@triton.jit +def _diag_of(tile, BLOCK_D: tl.constexpr): + ar = tl.arange(0, BLOCK_D) + return tl.sum(tl.where(ar[:, None] == ar[None, :], tile, 0.0), axis=1) + + +@triton.jit +def _split_tf32(x): + hi = (x.to(tl.uint32, bitcast=True) & 0xFFFFE000).to(tl.float32, bitcast=True) + return hi, x - hi + + +@triton.jit +def _dot(a, b, PREC: tl.constexpr, SITE: tl.constexpr): + """a @ b with fp32 accumulation. Bit 0x100 is bf16 operands; otherwise bit + SITE of PREC selects 3xTF32 over plain TF32.""" + if PREC & 0x100: + return tl.dot(a.to(tl.bfloat16), b.to(tl.bfloat16)) + elif (PREC >> SITE) & 1: + a_hi, a_lo = _split_tf32(a) + b_hi, b_lo = _split_tf32(b) + acc = tl.dot(a_lo, b_hi, input_precision="tf32") + acc = tl.dot(a_hi, b_lo, acc, input_precision="tf32") + return tl.dot(a_hi, b_hi, acc, input_precision="tf32") + else: + return tl.dot(a, b, input_precision="tf32") + + +@triton.jit +def _dot_block(a, b, DIAG: tl.constexpr, PREC: tl.constexpr, SITE: tl.constexpr): + """PREC 0x100 keeps the diagonal on tf32. 0x300 is bf16 on the diagonal too.""" + if DIAG and PREC == 0x100: + return tl.dot(a, b, input_precision="tf32") + else: + return _dot(a, b, PREC, SITE) + + +@triton.jit +def _load_tok(ptr, H, D, tok, d0, alive, BLOCK_D: tl.constexpr): + ar = tl.arange(0, BLOCK_D) + return tl.load(ptr + tok.to(tl.int64) * H * D + d0 + ar, mask=alive, other=0.0).to(tl.float32) + + +@triton.jit +def _load_f_bc(ptr, H, chunk_id, chunk_size, s0, BLOCK_C: tl.constexpr): + offs = chunk_id * chunk_size + s0 + tl.arange(0, BLOCK_C) + return tl.load(ptr + offs * H, mask=offs < (chunk_id * chunk_size + chunk_size), other=1.0).to(tl.float32) + + +@triton.jit +def _s_offs(BLOCK_C: tl.constexpr): + return tl.arange(0, BLOCK_C)[:, None] * BLOCK_C + tl.arange(0, BLOCK_C)[None, :] + + +@triton.jit +def _store_S(s_ptr, S, qb, kb, NUM_C: tl.constexpr, BLOCK_C: tl.constexpr): + base = (qb * NUM_C + kb) * BLOCK_C * BLOCK_C + tl.store(s_ptr + base + _s_offs(BLOCK_C), S) + + +@triton.jit +def _take_cols(S, sk, SRC: tl.constexpr, DST: tl.constexpr): + """Columns sk:sk+DST of an [M, SRC] tile.""" + src = tl.arange(0, SRC)[None, :] + dst = (sk + tl.arange(0, DST))[:, None] + return tl.sum(S[:, None, :] * (src == dst)[None, :, :], axis=2) + + +@triton.jit +def _load_S(s_ptr, qb, kb, NUM_C: tl.constexpr, BLOCK_C: tl.constexpr): + base = (qb * NUM_C + kb) * BLOCK_C * BLOCK_C + return tl.load(s_ptr + base + _s_offs(BLOCK_C)) + + +@triton.jit +def _ref_of(g, DIAG: tl.constexpr, SHIFT: tl.constexpr, BLOCK_C: tl.constexpr): + ref = tl.sum(tl.where(tl.arange(0, BLOCK_C)[:, None] == 0, g, 0.0), axis=0) + if DIAG: + ref = ref - SHIFT + return ref + + +@triton.jit +def _one_score( + v, gv, k, gk, s0_q, s0_k, n_valid, + DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, BLOCK_C: tl.constexpr, +): + """One D-tile of exp(Gam_t - Gam_i) = exp(Gam_t - C) exp(C - Gam_i).""" + ref = _ref_of(gv, DIAG, SHIFT, BLOCK_C) + valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid + valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid + gv_s = tl.where(valid_q[:, None], gv, ref[None, :]) + gk_s = tl.where(valid_k[:, None], gk, ref[None, :]) + vs = tl.where(valid_q[:, None], v * tl.exp(gv_s - ref[None, :]), 0.0) + ks = tl.where(valid_k[:, None], k * tl.exp(ref[None, :] - gk_s), 0.0) + S = _dot_block(vs, tl.trans(ks), DIAG, PREC, 0) + if DIAG: + tri = tl.arange(0, BLOCK_C)[:, None] >= tl.arange(0, BLOCK_C)[None, :] + S = tl.where(tri, S, 0.0) + return tl.where(valid_q[:, None] & valid_k[None, :], S, 0.0) + + +@triton.jit +def _scores_block( + v_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, s0_q, s0_k, n_valid, + BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, BLOCK_C: tl.constexpr, + DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, +): + S = tl.zeros((BLOCK_C, BLOCK_C), dtype=tl.float32) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + v = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, s0_q, d0, BLOCK_C, BLOCK_D) + gv = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0_q, d0, BLOCK_C, BLOCK_D) + k = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, s0_k, d0, BLOCK_C, BLOCK_D) + gk = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0_k, d0, BLOCK_C, BLOCK_D) + S += _one_score(v, gv, k, gk, s0_q, s0_k, n_valid, DIAG, SHIFT, PREC, BLOCK_C) + return S + + +@triton.jit +def _apply_block( + S, k, gk, gq, s0_q, s0_k, n_valid, + DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, BLOCK_C: tl.constexpr, +): + """sum_i S_ti * k_i * exp(Gam_t - Gam_i), with the same C used to build S.""" + ref = _ref_of(gq, DIAG, SHIFT, BLOCK_C) + valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid + valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid + gq_s = tl.where(valid_q[:, None], gq, ref[None, :]) + gk_s = tl.where(valid_k[:, None], gk, ref[None, :]) + ks = tl.where(valid_k[:, None], k * tl.exp(ref[None, :] - gk_s), 0.0) + acc = _dot_block(S, ks, DIAG, PREC, 2) + return tl.where(valid_q[:, None], tl.exp(gq_s - ref[None, :]) * acc, 0.0) + + +@triton.jit +def _z_pair( + S, y, gq, gk, s0_q, s0_k, n_valid, + DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, BLOCK_C: tl.constexpr, +): + """Key-block rows of sum_t S_ti * y_t * exp(Gam_t - Gam_i).""" + ref = _ref_of(gq, DIAG, SHIFT, BLOCK_C) + valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid + valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid + gq_s = tl.where(valid_q[:, None], gq, ref[None, :]) + gk_s = tl.where(valid_k[:, None], gk, ref[None, :]) + ys = tl.where(valid_q[:, None], y * tl.exp(gq_s - ref[None, :]), 0.0) + acc = _dot_block(tl.trans(S), ys, DIAG, PREC, 3) + return tl.where(valid_k[:, None], tl.exp(ref[None, :] - gk_s) * acc, 0.0) + + +@triton.jit +def _vh_rows( + v_ptr, h_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, n_valid, + BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, BLOCK_C: tl.constexpr, PREC: tl.constexpr, +): + """((v * E) @ H_in) for BLOCK_C query rows. E = exp(Gam) <= 1.""" + acc = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + valid = (s0 + tl.arange(0, BLOCK_C)) < n_valid + for j in tl.static_range(NUM_D): + d1 = j * BLOCK_D + g = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0, d1, BLOCK_C, BLOCK_D) + v = _load_bc(v_ptr, T, H, D, chunk_id, chunk_size, s0, d1, BLOCK_C, BLOCK_D) * tl.exp(g) + h = _load_mat(h_ptr, D, d1, d0, BLOCK_D) + acc += _dot(v, h, PREC, 1) + return tl.where(valid[:, None], acc, 0.0) + + +@triton.jit +def _pick_row(x, t, N: tl.constexpr): + return tl.sum(tl.where(tl.arange(0, N)[:, None] == t, x, 0.0), axis=0) + + +@triton.jit +def _pick_one(x, t, N: tl.constexpr): + return tl.sum(tl.where(tl.arange(0, N) == t, x, 0.0)) + + +@triton.jit +def _diag_rows( + k_ptr, gam_ptr, diag_in, T, H, D, chunk_id, chunk_size, d0, n_valid, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, +): + """diag(H_t) = exp(gk_t) diag(H_{t-1}) + k_t^2. + + One 16-row load, then the same per-step exp as the scalar scan. A 16-wide + step stays inside fp32 for gk = -5; the whole chunk is four of those. + """ + dstate = diag_in + gprev = tl.zeros((BLOCK_D,), dtype=tl.float32) + out = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + idx = tl.arange(0, chunk_size) + for bi in tl.static_range(4): + if bi < chunk_size // BLOCK_C: + s0 = bi * BLOCK_C + if s0 < n_valid: + kb = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D) + gb = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D) + for t in tl.static_range(BLOCK_C): + alive = (s0 + t) < n_valid + kt = _pick_row(kb, t, BLOCK_C) + gt = _pick_row(gb, t, BLOCK_C) + gt_s = tl.where(alive, gt, gprev) + d_new = tl.exp(2.0 * (gt_s - gprev)) * dstate + tl.where(alive, kt * kt, 0.0) + dstate = tl.where(alive, d_new, dstate) + gprev = tl.where(alive, gt, gprev) + out += tl.where((idx == (s0 + t))[:, None] & alive, d_new[None, :], 0.0) + return out + + +@triton.jit +def _R_rows( + alpha, gam_ptr, T, H, D, chunk_id, chunk_size, d0, n_valid, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, +): + """R_t = alpha_t + exp(gk_{t+1}) R_{t+1}, scanned backwards in blocks of 16.""" + Rstate = tl.zeros((BLOCK_D,), dtype=tl.float32) + g_next = tl.zeros((BLOCK_D,), dtype=tl.float32) + have = tl.zeros((1,), dtype=tl.float32) + out = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + idx = tl.arange(0, chunk_size) + for bi in tl.static_range(4): + bj = 3 - bi + if bj < chunk_size // BLOCK_C: + s0 = bj * BLOCK_C + if s0 < n_valid: + gb = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, s0, d0, BLOCK_C, BLOCK_D) + for ti in tl.static_range(BLOCK_C): + t = BLOCK_C - 1 - ti + alive = (s0 + t) < n_valid + gt = _pick_row(gb, t, BLOCK_C) + at = _pick_one(alpha, s0 + t, chunk_size) + use = tl.sum(have) > 0.5 + g_n = tl.where(use, g_next, gt) + step = tl.exp(2.0 * (g_n - gt)) + Rt = at + tl.where(use, step * Rstate, 0.0) + Rstate = tl.where(alive, Rt, Rstate) + g_next = tl.where(alive, gt, g_next) + have = tl.where(alive, 1.0, have) + out += tl.where((idx == (s0 + t))[:, None] & alive, Rt[None, :], 0.0) + return out + + +# --------------------------------------------------------------------------- +# Forward +# --------------------------------------------------------------------------- +@triton.jit(do_not_specialize=["T"]) +def trace_fwd_kernel( + h_ptr, k_ptr, q_ptr, gam_ptr, coeff_ptr, + x_ptr, o1_ptr, o2_ptr, o3_ptr, f_ptr, s1_ptr, s2_ptr, s3_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + N: tl.constexpr, EPS: tl.constexpr, PREC: tl.constexpr, +): + chunk_id = tl.program_id(0) + bh = tl.program_id(1) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + NUM_C: tl.constexpr = chunk_size // BLOCK_C + m_t = _masks(chunk_id, chunk_size, T) + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + + vec_off = (b_id * T * H + h_id) * D + q_ptr += vec_off + k_ptr += vec_off + gam_ptr += vec_off + x_ptr += vec_off + o1_ptr += vec_off + o2_ptr += vec_off + o3_ptr += vec_off + f_ptr += b_id * T * H + h_id + h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + + F = tl.zeros((chunk_size,), dtype=tl.float32) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + diag_in = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D) + diag = _diag_rows( + k_ptr, gam_ptr, diag_in, T, H, D, chunk_id, chunk_size, d0, n_valid, BLOCK_D, BLOCK_C, + ) + F += tl.sum(diag, axis=1) + F = tl.where(m_t, F + EPS, 0.0) + _store_row(f_ptr, F, T, H, chunk_id, chunk_size) + F = tl.where(m_t, F, 1.0) + + for m in tl.static_range(1, N): + if m == 1: + src = q_ptr + dst = o1_ptr + elif m == 2: + src = o1_ptr + dst = o2_ptr + else: + src = o2_ptr + dst = o3_ptr + s_base = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + if m == 1: + sp = s1_ptr + s_base + elif m == 2: + sp = s2_ptr + s_base + else: + sp = s3_ptr + s_base + # Intra term only. Each causal 16x16 score is formed once, then applied. + if NUM_D == 1: + for qb in tl.static_range(NUM_C): + sq = qb * BLOCK_C + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + for kb in tl.static_range(NUM_C): + sk = kb * BLOCK_C + if kb < qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + _store_S(sp, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + if kb == qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + _store_S(sp, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + _store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + else: + for qb in tl.static_range(NUM_C): + sq = qb * BLOCK_C + for di in tl.static_range(NUM_D): + d0 = di * BLOCK_D + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + for kb in tl.static_range(NUM_C): + sk = kb * BLOCK_C + if kb < qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + if di == 0: + _store_S(sp, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + rows += _apply_block( + S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C, + ) + if kb == qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + if di == 0: + _store_S(sp, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + rows += _apply_block( + S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C, + ) + _store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + tl.debug_barrier() + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + g = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + e = tl.exp(g) + inter = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + for j in tl.static_range(NUM_D): + d1 = j * BLOCK_D + v = _load_vec(src, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + v *= tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)) + inter += _dot(v, _load_mat(h_ptr, D, d1, d0, BLOCK_D), PREC, 1) + intra = _load_vec(dst, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + out = tl.where(m_t[:, None], (inter * e + intra) / F[:, None], 0.0) + _store_vec(dst, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + tl.debug_barrier() + + c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32) + c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32) + c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + acc = c0 * _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + acc += c1 * _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + acc += c2 * _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + if N > 3: + c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32) + acc += c3 * _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + _store_vec(x_ptr, acc, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + + +# --------------------------------------------------------------------------- +# Backward +# --------------------------------------------------------------------------- +@triton.jit(do_not_specialize=["T"]) +def trace_bwd_chunk_kernel( + h_ptr, k_ptr, gam_ptr, q_ptr, o1_ptr, o2_ptr, o3_ptr, dx_ptr, f_ptr, coeff_ptr, + p1_ptr, p2_ptr, p3_ptr, u1_ptr, u2_ptr, u3_ptr, + dq_ptr, dk_ptr, dgk_ptr, g_partial_ptr, dcoeff_ptr, alpha_ptr, s_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + N: tl.constexpr, PREC: tl.constexpr, +): + """Same splits as the forward. dk stores the E^{-1}-scaled low-rank term.""" + chunk_id = tl.program_id(0) + bh = tl.program_id(1) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + NUM_C: tl.constexpr = chunk_size // BLOCK_C + m_t = _masks(chunk_id, chunk_size, T) + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + + scalar = b_id * T * H + h_id + vec = scalar * D + k_ptr += vec + gam_ptr += vec + q_ptr += vec + o1_ptr += vec + o2_ptr += vec + o3_ptr += vec + dx_ptr += vec + p1_ptr += vec + p2_ptr += vec + p3_ptr += vec + u1_ptr += vec + u2_ptr += vec + u3_ptr += vec + dq_ptr += vec + dk_ptr += vec + dgk_ptr += vec + f_ptr += scalar + alpha_ptr += scalar + s_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + h_ptr += mat + g_partial_ptr += mat + + F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0) + c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32) + c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32) + c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32) + c3 = 0.0 + if N > 3: + c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32) + + # (1) p_{j+1} = p_j H / F, and Z += B_j^T Xt_j in the E^{-1} frame. + # Scores are written once and reused for both p and Z. + for j in tl.static_range(N - 1): + if j == 0: + src = dx_ptr + dst = p1_ptr + elif j == 1: + src = p1_ptr + dst = p2_ptr + else: + src = p2_ptr + dst = p3_ptr + ca = tl.load(coeff_ptr + h_id * N + j + 1).to(tl.float32) + cb = 0.0 + cc = 0.0 + if j + 2 < N: + cb = tl.load(coeff_ptr + h_id * N + j + 2).to(tl.float32) + if j + 3 < N: + cc = tl.load(coeff_ptr + h_id * N + j + 3).to(tl.float32) + if NUM_D == 1: + for qb in tl.static_range(NUM_C): + sq = qb * BLOCK_C + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + for kb in tl.static_range(NUM_C): + sk = kb * BLOCK_C + if kb < qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + if kb == qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + _store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + else: + for qb in tl.static_range(NUM_C): + sq = qb * BLOCK_C + for di in tl.static_range(NUM_D): + d0 = di * BLOCK_D + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + for kb in tl.static_range(NUM_C): + sk = kb * BLOCK_C + if kb < qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + if di == 0: + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + rows += _apply_block( + S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C, + ) + if kb == qb: + S = _scores_block( + src, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + if di == 0: + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + rows += _apply_block( + S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C, + ) + _store_bc(dst, rows, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + tl.debug_barrier() + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + g = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + e = tl.exp(g) + inter = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + for jj in tl.static_range(NUM_D): + d1 = jj * BLOCK_D + v = _load_vec(src, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + v *= tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)) + inter += _dot(v, _load_mat(h_ptr, D, d1, d0, BLOCK_D), PREC, 1) + intra = _load_vec(dst, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + out = tl.where(m_t[:, None], (inter * e + intra) / F[:, None], 0.0) + _store_vec(dst, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + tl.debug_barrier() + for kb in tl.static_range(NUM_C): + sk = kb * BLOCK_C + for di in tl.static_range(NUM_D): + d0 = di * BLOCK_D + zrows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sk < n_valid: + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + for qb in tl.static_range(NUM_C): + sq = qb * BLOCK_C + if qb >= kb and sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C) + xt = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + if j + 2 < N: + xt += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + if j + 3 < N: + xt += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + yb = xt / Fb[:, None] + if qb == kb: + S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C) + zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + else: + S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C) + zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + if j > 0: + zrows += _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + _store_bc(dk_ptr, zrows, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + tl.debug_barrier() + + # (2) dq, u_m, alpha, dcoeff and lin = sum_m o_{m-1} w_m + do_m o_m. + s = tl.zeros((chunk_size,), dtype=tl.float32) + da = tl.zeros((1,), dtype=tl.float32) + db = tl.zeros((1,), dtype=tl.float32) + dc = tl.zeros((1,), dtype=tl.float32) + dd = tl.zeros((1,), dtype=tl.float32) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + q = _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o1 = _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o2 = _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dx = _load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + p1 = _load_vec(p1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + p2 = _load_vec(p2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dq = c0 * dx + c1 * p1 + c2 * p2 + do1 = c1 * dx + c2 * p1 + do2 = c2 * dx + w1 = c1 * p1 + c2 * p2 + w2 = c2 * p1 + lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + if N > 3: + o3 = _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + p3 = _load_vec(p3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dq += c3 * p3 + do1 += c3 * p2 + do2 += c3 * p1 + do3 = c3 * dx + w1 += c3 * p3 + w2 += c3 * p2 + w3 = c3 * p1 + lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + o2 * w3 + do3 * o3 + _store_vec(u3_ptr, do3 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + s += tl.sum(o3 * do3, axis=1) + dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0) + _store_vec(dq_ptr, dq, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + _store_vec(u1_ptr, do1 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + _store_vec(u2_ptr, do2 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + _store_vec(dgk_ptr, lin, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + s += tl.sum(o1 * do1, axis=1) + tl.sum(o2 * do2, axis=1) + da += tl.sum(tl.sum(dx * q, axis=0), axis=0) + db += tl.sum(tl.sum(dx * o1, axis=0), axis=0) + dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0) + alpha = tl.where(m_t, -s / F, 0.0) + base = ((b_id * num_chunks + chunk_id) * H + h_id) * N + tl.store(dcoeff_ptr + base + 0, tl.sum(da)) + tl.store(dcoeff_ptr + base + 1, tl.sum(db)) + tl.store(dcoeff_ptr + base + 2, tl.sum(dc)) + if N > 3: + tl.store(dcoeff_ptr + base + 3, tl.sum(dd)) + tl.debug_barrier() + + _store_row(alpha_ptr, alpha, T, H, chunk_id, chunk_size) + tl.debug_barrier() + + # (3) Z += tril(X_m k'^T)^T Y_m, already multiplied by E^{-1}. + for m in tl.static_range(1, N): + if m == 1: + xs = q_ptr + us = u1_ptr + elif m == 2: + xs = o1_ptr + us = u2_ptr + else: + xs = o2_ptr + us = u3_ptr + for kb in tl.static_range(NUM_C): + sk = kb * BLOCK_C + for di in tl.static_range(NUM_D): + d0 = di * BLOCK_D + zrows = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + if sk < n_valid: + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + for qb in tl.static_range(NUM_C): + sq = qb * BLOCK_C + if qb >= kb and sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + yb = _load_bc(us, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + if qb == kb: + S = _scores_block( + xs, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + else: + S = _scores_block( + xs, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + zrows += _z_pair(S, yb, gq, gg, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + _store_bc(dk_ptr, zrows, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + tl.debug_barrier() + + # (4) g_partial. The trace term on dk / dgk is a separate epilogue. + eye = tl.arange(0, BLOCK_D) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + e = tl.exp(gam) + r0 = tl.sum(alpha[:, None] * e * e, axis=0) + for jd in tl.static_range(NUM_D): + d1 = jd * BLOCK_D + e1 = tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)) + g = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32) + for mm in tl.static_range(1, N): + if mm == 1: + xs = q_ptr + us = u1_ptr + elif mm == 2: + xs = o1_ptr + us = u2_ptr + else: + xs = o2_ptr + us = u3_ptr + x = _load_vec(xs, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e + y = _load_vec(us, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * e1 + g += _dot(tl.trans(x), y, PREC, 5) + if i == jd: + g += tl.where(eye[:, None] == eye[None, :], r0[:, None], 0.0) + _store_mat(g_partial_ptr, g, D, d0, d1, BLOCK_D) + + +@triton.jit +def _e_last_of(gam_ptr, b_id, h_id, cid, T, H: tl.constexpr, D: tl.constexpr, + chunk_size: tl.constexpr, d0, BLOCK: tl.constexpr): + """exp(Gam) at the last valid token of chunk ``cid``, dims d0:d0+BLOCK.""" + t_last = cid * chunk_size + tl.minimum(chunk_size, T - cid * chunk_size) - 1 + off = ((b_id * T + t_last) * H + h_id).to(tl.int64) * D + d0 + return tl.exp(tl.load(gam_ptr + off + tl.arange(0, BLOCK)).to(tl.float32)) + + +@triton.jit +def _gam_last_of(gam_ptr, b_id, h_id, cid, T, H: tl.constexpr, D: tl.constexpr, + chunk_size: tl.constexpr, d0, BLOCK: tl.constexpr): + t_last = cid * chunk_size + tl.minimum(chunk_size, T - cid * chunk_size) - 1 + off = ((b_id * T + t_last) * H + h_id).to(tl.int64) * D + d0 + return tl.load(gam_ptr + off + tl.arange(0, BLOCK)).to(tl.float32) + + +@triton.jit(do_not_specialize=["T"]) +def trace_bwd_scan_kernel( + g_partial_ptr, gam_ptr, gin_ptr, dht_ptr, + T, NC, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_S: tl.constexpr, HAS_DHT: tl.constexpr, +): + """gin[c] = g_partial[c+1] + Diag(E_last[c+1]) gin[c+1] Diag(E_last[c+1]).""" + i_bh = tl.program_id(0) + i_tile = tl.program_id(1) + i_b, i_h = i_bh // H, i_bh % H + NUM_S: tl.constexpr = D // BLOCK_S + r0 = (i_tile // NUM_S) * BLOCK_S + c0 = (i_tile % NUM_S) * BLOCK_S + G = tl.zeros((BLOCK_S, BLOCK_S), dtype=tl.float32) + if HAS_DHT: + p_dht = tl.make_block_ptr( + dht_ptr + (i_b * H + i_h).to(tl.int64) * D * D, + (D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0), + ) + G = tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32) + last = NC - 1 + p_gin = tl.make_block_ptr( + gin_ptr + ((i_b * NC + last) * H + i_h).to(tl.int64) * D * D, + (D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0), + ) + tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1)) + for it in tl.range(0, NC - 1): + cid = NC - 2 - it + src = cid + 1 + p_gp = tl.make_block_ptr( + g_partial_ptr + ((i_b * NC + src) * H + i_h).to(tl.int64) * D * D, + (D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0), + ) + gp = tl.load(p_gp, boundary_check=(0, 1)).to(tl.float32) + er = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, r0, BLOCK_S) + ec = _e_last_of(gam_ptr, i_b, i_h, src, T, H, D, chunk_size, c0, BLOCK_S) + G = gp + er[:, None] * G * ec[None, :] + p_gin = tl.make_block_ptr( + gin_ptr + ((i_b * NC + cid) * H + i_h).to(tl.int64) * D * D, + (D, D), (D, 1), (r0, c0), (BLOCK_S, BLOCK_S), (1, 0), + ) + tl.store(p_gin, G.to(p_gin.dtype.element_ty), boundary_check=(0, 1)) + + +@triton.jit(do_not_specialize=["T"]) +def trace_bwd_gin_kernel( + h_ptr, k_ptr, gam_ptr, gin_ptr, dk_ptr, dgk_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, PREC: tl.constexpr, +): + """Add S_in = Diag(E_C) (gin + gin^T) Diag(E_C) into dk and dgk. + + k is scaled by exp(Gam_last - Gam_t), which is <= 1 for non-positive gk. + """ + chunk_id = tl.program_id(0) + bh = tl.program_id(1) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + m_t = _masks(chunk_id, chunk_size, T) + + gam_base = gam_ptr + vec = (b_id * T * H + h_id) * D + k_ptr += vec + gam_ptr += vec + dk_ptr += vec + dgk_ptr += vec + mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + h_ptr += mat + gin_ptr += mat + + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + gam0 = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + el_log0 = _gam_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d0, BLOCK_D) + el0 = tl.exp(el_log0) + Za = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + v1 = tl.zeros((BLOCK_D,), dtype=tl.float32) + for j in tl.static_range(NUM_D): + d1 = j * BLOCK_D + gam1 = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + k1 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + el_log1 = _gam_last_of(gam_base, b_id, h_id, chunk_id, T, H, D, chunk_size, d1, BLOCK_D) + el1 = tl.exp(el_log1) + w1 = k1 * tl.exp(el_log1[None, :] - gam1) + sym = _load_mat(gin_ptr, D, d1, d0, BLOCK_D) + tl.trans(_load_mat(gin_ptr, D, d0, d1, BLOCK_D)) + Za += _dot(w1, sym, PREC, 6) + h_ij = _load_mat(h_ptr, D, d0, d1, BLOCK_D) + v1 += tl.sum(tl.trans(sym) * el1[None, :] * h_ij, axis=1) + scale0 = tl.exp(el_log0[None, :] - gam0) + dk = _load_vec(dk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + _store_vec(dk_ptr, dk + scale0 * Za, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + k0 = _load_vec(k_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dgk = _load_vec(dgk_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dgk += 0.5 * (v1[None, :] * el0[None, :] + _excl(k0 * scale0 * Za)) + _store_vec(dgk_ptr, dgk, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + + +@triton.jit(do_not_specialize=["T"]) +def trace_bwd_epilogue_kernel( + h_ptr, k_ptr, gam_ptr, alpha_ptr, diag_ptr, dk_ptr, dgk_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, +): + """dgk / dk trace term. One exp(gk) step at a time.""" + chunk_id = tl.program_id(0) + tile = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + scalar = b_id * T * H + h_id + vec = scalar * D + k_ptr += vec + gam_ptr += vec + dk_ptr += vec + dgk_ptr += vec + diag_ptr += vec + alpha_ptr += scalar + h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + base_tok = chunk_id * chunk_size + d0 = tile * BLOCK_D + dstate = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D) + gprev = tl.zeros((BLOCK_D,), dtype=tl.float32) + ar = tl.arange(0, BLOCK_D) + for t in tl.range(0, chunk_size): + alive = t < n_valid + tok = base_tok + t + kt = _load_tok(k_ptr, H, D, tok, d0, alive, BLOCK_D) + gt = _load_tok(gam_ptr, H, D, tok, d0, alive, BLOCK_D) + gt_s = tl.where(alive, gt, gprev) + d_new = tl.exp(2.0 * (gt_s - gprev)) * dstate + tl.where(alive, kt * kt, 0.0) + dstate = tl.where(alive, d_new, dstate) + gprev = gt_s + tl.store(diag_ptr + tok.to(tl.int64) * H * D + d0 + ar, tl.where(alive, d_new, 0.0), mask=alive) + tl.debug_barrier() + Rstate = tl.zeros((BLOCK_D,), dtype=tl.float32) + g_carry = tl.zeros((BLOCK_D,), dtype=tl.float32) + have = tl.zeros((BLOCK_D,), dtype=tl.float32) + suf = tl.zeros((BLOCK_D,), dtype=tl.float32) + for ti in tl.range(0, chunk_size): + t = chunk_size - 1 - ti + alive = t < n_valid + tok = base_tok + t + gt = _load_tok(gam_ptr, H, D, tok, d0, alive, BLOCK_D) + kt = _load_tok(k_ptr, H, D, tok, d0, alive, BLOCK_D) + zt = _load_tok(dk_ptr, H, D, tok, d0, alive, BLOCK_D) + lt = _load_tok(dgk_ptr, H, D, tok, d0, alive, BLOCK_D) + dh = _load_tok(diag_ptr, H, D, tok, d0, alive, BLOCK_D) + at = tl.load(alpha_ptr + tok.to(tl.int64) * H, mask=alive, other=0.0).to(tl.float32) + term = tl.where(alive, lt - kt * zt, 0.0) + suf_t = term + suf + suf = tl.where(alive, suf_t, suf) + g_n = have * g_carry + (1.0 - have) * gt + gt_s = tl.where(alive, gt, g_n) + step = tl.exp(2.0 * (g_n - gt_s)) + Rt = at + step * (have * Rstate) + Rstate = tl.where(alive, Rt, Rstate) + g_carry = tl.where(alive, gt, g_carry) + have = tl.where(alive, 1.0, have) + dg = 0.5 * suf_t + Rt * (dh - kt * kt) + dk = zt + 2.0 * Rt * kt + tl.store(dgk_ptr + tok.to(tl.int64) * H * D + d0 + ar, tl.where(alive, dg, 0.0), mask=alive) + tl.store(dk_ptr + tok.to(tl.int64) * H * D + d0 + ar, tl.where(alive, dk, 0.0), mask=alive) + + +@triton.jit(do_not_specialize=["T"]) +def trace_F_kernel( + h_ptr, k_ptr, gam_ptr, f_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, EPS: tl.constexpr, +): + chunk_id = tl.program_id(0) + bh = tl.program_id(1) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + vec = (b_id * T * H + h_id) * D + k_ptr += vec + gam_ptr += vec + f_ptr += b_id * T * H + h_id + h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + base_tok = chunk_id * chunk_size + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + dstate = _diag_of(_load_mat(h_ptr, D, d0, d0, BLOCK_D), BLOCK_D) + gprev = tl.zeros((BLOCK_D,), dtype=tl.float32) + for t in tl.range(0, chunk_size): + alive = t < n_valid + tok = base_tok + t + kt = _load_tok(k_ptr, H, D, tok, d0, alive, BLOCK_D) + gt = _load_tok(gam_ptr, H, D, tok, d0, alive, BLOCK_D) + gt_s = tl.where(alive, gt, gprev) + d_new = tl.exp(2.0 * (gt_s - gprev)) * dstate + tl.where(alive, kt * kt, 0.0) + dstate = tl.where(alive, d_new, dstate) + gprev = gt_s + slot = f_ptr + tok.to(tl.int64) * H + contrib = tl.sum(tl.where(alive, d_new, 0.0)) + if i == 0: + tl.store(slot, contrib + EPS, mask=alive) + else: + prev = tl.load(slot, mask=alive, other=0.0).to(tl.float32) + tl.store(slot, prev + contrib, mask=alive) + tl.debug_barrier() + + +@triton.jit(do_not_specialize=["T"]) +def trace_intra_qb_kernel( + src_ptr, k_ptr, gam_ptr, dst_ptr, s_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + PREC: tl.constexpr, STORE_S: tl.constexpr, +): + """One query block. Scores are formed once and applied to every D tile.""" + chunk_id = tl.program_id(0) + qb = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + NUM_C: tl.constexpr = chunk_size // BLOCK_C + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + vec = (b_id * T * H + h_id) * D + src_ptr += vec + k_ptr += vec + gam_ptr += vec + dst_ptr += vec + s_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + sq = qb * BLOCK_C + if NUM_D == 1: + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + for kb in tl.range(0, qb): + sk = kb * BLOCK_C + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + if STORE_S: + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + sk = sq + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + if STORE_S: + _store_S(s_ptr, S, qb, qb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + _store_bc(dst_ptr, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + else: + rows0 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + rows1 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + gq1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D) + for kb in tl.range(0, qb): + sk = kb * BLOCK_C + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + if STORE_S: + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + k0 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + g0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + k1 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D) + g1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D) + rows0 += _apply_block(S, k0, g0, gq0, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + rows1 += _apply_block(S, k1, g1, gq1, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + sk = sq + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + if STORE_S: + _store_S(s_ptr, S, qb, qb, NUM_C, BLOCK_C) + k0 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + g0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + k1 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D) + g1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D) + rows0 += _apply_block(S, k0, g0, gq0, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + rows1 += _apply_block(S, k1, g1, gq1, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + _store_bc(dst_ptr, rows0, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + _store_bc(dst_ptr, rows1, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D) + + +@triton.jit +def _phi_one_order( + src_ptr, dst_ptr, s_ptr, k_ptr, gam_ptr, h_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_id, chunk_size: tl.constexpr, + sq, n_valid, Fb, valid, + BLOCK_D: tl.constexpr, NUM_D: tl.constexpr, BLOCK_C: tl.constexpr, + NUM_C: tl.constexpr, qb, SHIFT: tl.constexpr, PREC: tl.constexpr, +): + if NUM_D == 1: + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + for kb in tl.range(0, qb): + sk = kb * BLOCK_C + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + sk = sq + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + _store_S(s_ptr, S, qb, qb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + vh = _vh_rows( + src_ptr, h_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, n_valid, + BLOCK_D, NUM_D, BLOCK_C, PREC, + ) + rows = (vh * tl.exp(gq) + rows) / Fb[:, None] + rows = tl.where(valid[:, None], rows, 0.0) + _store_bc(dst_ptr, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + else: + for di in tl.static_range(NUM_D): + d0 = di * BLOCK_D + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + for kb in tl.range(0, qb): + sk = kb * BLOCK_C + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + if di == 0: + _store_S(s_ptr, S, qb, kb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + sk = sq + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + if di == 0: + _store_S(s_ptr, S, qb, qb, NUM_C, BLOCK_C) + kk = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, d0, BLOCK_C, BLOCK_D) + rows += _apply_block(S, kk, gg, gq, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + vh = _vh_rows( + src_ptr, h_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, d0, n_valid, + BLOCK_D, NUM_D, BLOCK_C, PREC, + ) + rows = (vh * tl.exp(gq) + rows) / Fb[:, None] + rows = tl.where(valid[:, None], rows, 0.0) + _store_bc(dst_ptr, rows, T, H, D, chunk_id, chunk_size, sq, d0, BLOCK_C, BLOCK_D) + + +@triton.jit(do_not_specialize=["T"]) +def trace_phi_qb_kernel( + src0_ptr, src1_ptr, src2_ptr, dst0_ptr, dst1_ptr, dst2_ptr, + k_ptr, gam_ptr, h_ptr, f_ptr, s0_ptr, s1_ptr, s2_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + N: tl.constexpr, PREC: tl.constexpr, +): + """One query block, every polynomial order. + + Orders are a chain on this block's own rows, so one program walks them and + adds the carried state before the store. The next order reloads that store. + """ + chunk_id = tl.program_id(0) + qb = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + NUM_C: tl.constexpr = chunk_size // BLOCK_C + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + vec = (b_id * T * H + h_id) * D + src0_ptr += vec + src1_ptr += vec + src2_ptr += vec + dst0_ptr += vec + dst1_ptr += vec + dst2_ptr += vec + k_ptr += vec + gam_ptr += vec + f_ptr += b_id * T * H + h_id + h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + s_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + s0_ptr += s_off + s1_ptr += s_off + s2_ptr += s_off + sq = qb * BLOCK_C + Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C) + valid = (sq + tl.arange(0, BLOCK_C)) < n_valid + _phi_one_order( + src0_ptr, dst0_ptr, s0_ptr, k_ptr, gam_ptr, h_ptr, + T, H, D, chunk_id, chunk_size, sq, n_valid, Fb, valid, + BLOCK_D, NUM_D, BLOCK_C, NUM_C, qb, SHIFT, PREC, + ) + tl.debug_barrier() + if N > 2: + _phi_one_order( + src1_ptr, dst1_ptr, s1_ptr, k_ptr, gam_ptr, h_ptr, + T, H, D, chunk_id, chunk_size, sq, n_valid, Fb, valid, + BLOCK_D, NUM_D, BLOCK_C, NUM_C, qb, SHIFT, PREC, + ) + tl.debug_barrier() + if N > 3: + _phi_one_order( + src2_ptr, dst2_ptr, s2_ptr, k_ptr, gam_ptr, h_ptr, + T, H, D, chunk_id, chunk_size, sq, n_valid, Fb, valid, + BLOCK_D, NUM_D, BLOCK_C, NUM_C, qb, SHIFT, PREC, + ) + + +@triton.jit(do_not_specialize=["T"]) +def trace_combine_kernel( + h_ptr, src_ptr, gam_ptr, dst_ptr, f_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, PREC: tl.constexpr, +): + """Add the carried state to the intra term already stored in dst, then divide by F. + + One D tile per program. The inner reduction reuses one operand tile. + """ + chunk_id = tl.program_id(0) + tile = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + m_t = _masks(chunk_id, chunk_size, T) + vec = (b_id * T * H + h_id) * D + src_ptr += vec + gam_ptr += vec + dst_ptr += vec + f_ptr += b_id * T * H + h_id + h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0) + d0 = tile * BLOCK_D + g = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + e = tl.exp(g) + inter = tl.zeros((chunk_size, BLOCK_D), dtype=tl.float32) + for j in tl.range(0, NUM_D): + d1 = j * BLOCK_D + v = _load_vec(src_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) + v *= tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)) + inter += _dot(v, _load_mat(h_ptr, D, d1, d0, BLOCK_D), PREC, 1) + intra = _load_vec(dst_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + out = tl.where(m_t[:, None], (inter * e + intra) / F[:, None], 0.0) + _store_vec(dst_ptr, out, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + + +@triton.jit(do_not_specialize=["T"]) +def trace_mix_kernel( + q_ptr, o1_ptr, o2_ptr, o3_ptr, x_ptr, coeff_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, N: tl.constexpr, +): + chunk_id = tl.program_id(0) + bh = tl.program_id(1) + b_id, h_id = bh // H, bh % H + NUM_D: tl.constexpr = D // BLOCK_D + m_t = _masks(chunk_id, chunk_size, T) + vec = (b_id * T * H + h_id) * D + q_ptr += vec + o1_ptr += vec + o2_ptr += vec + o3_ptr += vec + x_ptr += vec + c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32) + c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32) + c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + acc = c0 * _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + acc += c1 * _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + acc += c2 * _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + if N > 3: + c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32) + acc += c3 * _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + _store_vec(x_ptr, acc, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + + +@triton.jit(do_not_specialize=["T"]) +def trace_z_kb_kernel( + src_ptr, k_ptr, gam_ptr, y_ptr, q_ptr, o1_ptr, o2_ptr, f_ptr, coeff_ptr, + dk_ptr, s_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + N: tl.constexpr, J: tl.constexpr, PREC: tl.constexpr, + LOAD_S: tl.constexpr, USE_COEFF: tl.constexpr, ACCUM: tl.constexpr, +): + """One key block of Z. S is either reloaded or rebuilt for this pair.""" + chunk_id = tl.program_id(0) + kb = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + NUM_C: tl.constexpr = chunk_size // BLOCK_C + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + vec = (b_id * T * H + h_id) * D + src_ptr += vec + k_ptr += vec + gam_ptr += vec + y_ptr += vec + q_ptr += vec + o1_ptr += vec + o2_ptr += vec + dk_ptr += vec + f_ptr += b_id * T * H + h_id + s_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + ca = 0.0 + cb = 0.0 + cc = 0.0 + if USE_COEFF: + ca = tl.load(coeff_ptr + h_id * N + J + 1).to(tl.float32) + if J + 2 < N: + cb = tl.load(coeff_ptr + h_id * N + J + 2).to(tl.float32) + if J + 3 < N: + cc = tl.load(coeff_ptr + h_id * N + J + 3).to(tl.float32) + sk = kb * BLOCK_C + if NUM_D == 1: + z = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if ACCUM: + z = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + if sk < n_valid: + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + for qb in tl.range(kb, NUM_C): + sq = qb * BLOCK_C + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + if USE_COEFF: + Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C) + yb = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + if J + 2 < N: + yb += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + if J + 3 < N: + yb += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + yb = yb / Fb[:, None] + else: + yb = _load_bc(y_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + if qb == kb: + if LOAD_S: + S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C) + else: + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + z += _z_pair(S, yb, gq, gg, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + else: + if LOAD_S: + S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C) + else: + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + z += _z_pair(S, yb, gq, gg, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + _store_bc(dk_ptr, z, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + else: + z0 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + z1 = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if ACCUM: + z0 = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + z1 = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D) + if sk < n_valid: + gg0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + gg1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D) + for qb in tl.range(kb, NUM_C): + sq = qb * BLOCK_C + if sq < n_valid: + gq0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + gq1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D) + if USE_COEFF: + Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C) + y0 = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + y1 = ca * _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D) + if J + 2 < N: + y0 += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + y1 += cb * _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D) + if J + 3 < N: + y0 += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + y1 += cc * _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D) + y0 = y0 / Fb[:, None] + y1 = y1 / Fb[:, None] + else: + y0 = _load_bc(y_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + y1 = _load_bc(y_ptr, T, H, D, chunk_id, chunk_size, sq, BLOCK_D, BLOCK_C, BLOCK_D) + if qb == kb: + if LOAD_S: + S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C) + else: + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, True, SHIFT, PREC, + ) + z0 += _z_pair(S, y0, gq0, gg0, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + z1 += _z_pair(S, y1, gq1, gg1, sq, sk, n_valid, True, SHIFT, PREC, BLOCK_C) + else: + if LOAD_S: + S = _load_S(s_ptr, qb, kb, NUM_C, BLOCK_C) + else: + S = _scores_block( + src_ptr, k_ptr, gam_ptr, T, H, D, chunk_id, chunk_size, sq, sk, n_valid, + BLOCK_D, NUM_D, BLOCK_C, False, SHIFT, PREC, + ) + z0 += _z_pair(S, y0, gq0, gg0, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + z1 += _z_pair(S, y1, gq1, gg1, sq, sk, n_valid, False, SHIFT, PREC, BLOCK_C) + _store_bc(dk_ptr, z0, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + _store_bc(dk_ptr, z1, T, H, D, chunk_id, chunk_size, sk, BLOCK_D, BLOCK_C, BLOCK_D) + + +@triton.jit(do_not_specialize=["T"]) +def trace_bwd_grad_kernel( + h_ptr, gam_ptr, q_ptr, o1_ptr, o2_ptr, o3_ptr, dx_ptr, f_ptr, coeff_ptr, + p1_ptr, p2_ptr, p3_ptr, u1_ptr, u2_ptr, u3_ptr, + dq_ptr, dgk_ptr, g_partial_ptr, dcoeff_ptr, alpha_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, N: tl.constexpr, PREC: tl.constexpr, +): + chunk_id = tl.program_id(0) + bh = tl.program_id(1) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_D: tl.constexpr = D // BLOCK_D + m_t = _masks(chunk_id, chunk_size, T) + scalar = b_id * T * H + h_id + vec = scalar * D + gam_ptr += vec + q_ptr += vec + o1_ptr += vec + o2_ptr += vec + o3_ptr += vec + dx_ptr += vec + p1_ptr += vec + p2_ptr += vec + p3_ptr += vec + u1_ptr += vec + u2_ptr += vec + u3_ptr += vec + dq_ptr += vec + dgk_ptr += vec + f_ptr += scalar + alpha_ptr += scalar + mat = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + h_ptr += mat + g_partial_ptr += mat + F = _load_row(f_ptr, T, H, chunk_id, chunk_size, m_t, 1.0) + c0 = tl.load(coeff_ptr + h_id * N + 0).to(tl.float32) + c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32) + c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32) + c3 = 0.0 + if N > 3: + c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32) + s = tl.zeros((chunk_size,), dtype=tl.float32) + da = tl.zeros((1,), dtype=tl.float32) + db = tl.zeros((1,), dtype=tl.float32) + dc = tl.zeros((1,), dtype=tl.float32) + dd = tl.zeros((1,), dtype=tl.float32) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + q = _load_vec(q_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o1 = _load_vec(o1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + o2 = _load_vec(o2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dx = _load_vec(dx_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + p1 = _load_vec(p1_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + p2 = _load_vec(p2_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dq = c0 * dx + c1 * p1 + c2 * p2 + do1 = c1 * dx + c2 * p1 + do2 = c2 * dx + w1 = c1 * p1 + c2 * p2 + w2 = c2 * p1 + lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + if N > 3: + o3 = _load_vec(o3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + p3 = _load_vec(p3_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + dq += c3 * p3 + do1 += c3 * p2 + do2 += c3 * p1 + do3 = c3 * dx + w1 += c3 * p3 + w2 += c3 * p2 + w3 = c3 * p1 + lin = q * w1 + do1 * o1 + o1 * w2 + do2 * o2 + o2 * w3 + do3 * o3 + _store_vec(u3_ptr, do3 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + s += tl.sum(o3 * do3, axis=1) + dd += tl.sum(tl.sum(dx * o3, axis=0), axis=0) + _store_vec(dq_ptr, dq, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + _store_vec(u1_ptr, do1 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + _store_vec(u2_ptr, do2 / F[:, None], T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + _store_vec(dgk_ptr, lin, T, H, D, chunk_id, chunk_size, d0, BLOCK_D) + s += tl.sum(o1 * do1, axis=1) + tl.sum(o2 * do2, axis=1) + da += tl.sum(tl.sum(dx * q, axis=0), axis=0) + db += tl.sum(tl.sum(dx * o1, axis=0), axis=0) + dc += tl.sum(tl.sum(dx * o2, axis=0), axis=0) + alpha = tl.where(m_t, -s / F, 0.0) + base = ((b_id * num_chunks + chunk_id) * H + h_id) * N + tl.store(dcoeff_ptr + base + 0, tl.sum(da)) + tl.store(dcoeff_ptr + base + 1, tl.sum(db)) + tl.store(dcoeff_ptr + base + 2, tl.sum(dc)) + if N > 3: + tl.store(dcoeff_ptr + base + 3, tl.sum(dd)) + _store_row(alpha_ptr, alpha, T, H, chunk_id, chunk_size) + tl.debug_barrier() + eye = tl.arange(0, BLOCK_D) + for i in tl.static_range(NUM_D): + d0 = i * BLOCK_D + gam = _load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) + e = tl.exp(gam) + r0 = tl.sum(alpha[:, None] * e * e, axis=0) + for jd in tl.static_range(NUM_D): + d1 = jd * BLOCK_D + e1 = tl.exp(_load_vec(gam_ptr, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D)) + g = tl.zeros((BLOCK_D, BLOCK_D), dtype=tl.float32) + for mm in tl.static_range(1, N): + if mm == 1: + xs, us = q_ptr, u1_ptr + elif mm == 2: + xs, us = o1_ptr, u2_ptr + else: + xs, us = o2_ptr, u3_ptr + x = _load_vec(xs, T, H, D, chunk_id, chunk_size, d0, m_t, BLOCK_D) * e + y = _load_vec(us, T, H, D, chunk_id, chunk_size, d1, m_t, BLOCK_D) * e1 + g += _dot(tl.trans(x), y, PREC, 5) + if i == jd: + g += tl.where(eye[:, None] == eye[None, :], r0[:, None], 0.0) + _store_mat(g_partial_ptr, g, D, d0, d1, BLOCK_D) + + +def _use_d1(D: int, block_d: int, chunk_size: int, block_c: int) -> bool: + """Fused path: one D tile, and at most two key blocks so both fit the unroll.""" + return block_d == D and (chunk_size // block_c) <= 2 + + +@triton.jit +def _pair_loaded( + v, gv, k, gk, s0_q, s0_k, n_valid, + DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, BLOCK_C: tl.constexpr, +): + """Score and apply from tiles already in registers. Same factors as + ``_one_score`` then ``_apply_block``.""" + ref = _ref_of(gv, DIAG, SHIFT, BLOCK_C) + valid_q = (s0_q + tl.arange(0, BLOCK_C)) < n_valid + valid_k = (s0_k + tl.arange(0, BLOCK_C)) < n_valid + gv_s = tl.where(valid_q[:, None], gv, ref[None, :]) + gk_s = tl.where(valid_k[:, None], gk, ref[None, :]) + eq = tl.exp(gv_s - ref[None, :]) + ek = tl.exp(ref[None, :] - gk_s) + vs = tl.where(valid_q[:, None], v * eq, 0.0) + ks = tl.where(valid_k[:, None], k * ek, 0.0) + S = _dot_block(vs, tl.trans(ks), DIAG, PREC, 0) + if DIAG: + tri = tl.arange(0, BLOCK_C)[:, None] >= tl.arange(0, BLOCK_C)[None, :] + S = tl.where(tri, S, 0.0) + S = tl.where(valid_q[:, None] & valid_k[None, :], S, 0.0) + acc = _dot_block(S, ks, DIAG, PREC, 2) + applied = tl.where(valid_q[:, None], eq * acc, 0.0) + return S, applied + + +@triton.jit +def _order_d1( + src, s_ptr, dst_ptr, + k0, g0, k1, g1, gq, eq, Fb, valid, h_tile, + T, H: tl.constexpr, D: tl.constexpr, chunk_id, chunk_size: tl.constexpr, + sq, n_valid, qb, SHIFT: tl.constexpr, PREC: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, NUM_C: tl.constexpr, +): + """One polynomial order. ``k0/g0`` is key block 0; ``k1/g1`` is block 1.""" + rows = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sq < n_valid: + if qb > 0: + S, app = _pair_loaded( + src, gq, k0, g0, sq, 0, n_valid, False, SHIFT, PREC, BLOCK_C, + ) + _store_S(s_ptr, S, qb, 0, NUM_C, BLOCK_C) + rows += app + if qb == 0: + kk, gg = k0, g0 + else: + kk, gg = k1, g1 + S, app = _pair_loaded( + src, gq, kk, gg, sq, sq, n_valid, True, SHIFT, PREC, BLOCK_C, + ) + _store_S(s_ptr, S, qb, qb, NUM_C, BLOCK_C) + rows += app + vh = _dot(src * eq, h_tile, PREC, 1) + rows = (vh * eq + rows) / Fb[:, None] + rows = tl.where(valid[:, None], rows, 0.0) + _store_bc(dst_ptr, rows, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + return rows + + +@triton.jit(do_not_specialize=["T"]) +def trace_phi_d1_kernel( + src0_ptr, src1_ptr, src2_ptr, dst0_ptr, dst1_ptr, dst2_ptr, + k_ptr, gam_ptr, h_ptr, f_ptr, s0_ptr, s1_ptr, s2_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + N: tl.constexpr, PREC: tl.constexpr, +): + """All polynomial orders for one query block when the head is one tile. + + ``src1`` is the store of order 0 and ``src2`` is the store of order 1, so + the next order consumes the rows just produced instead of reloading them. + Key and gate tiles are loaded once and reused for every order. + """ + chunk_id = tl.program_id(0) + qb = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_C: tl.constexpr = chunk_size // BLOCK_C + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + vec = (b_id * T * H + h_id) * D + src0_ptr += vec + dst0_ptr += vec + dst1_ptr += vec + dst2_ptr += vec + k_ptr += vec + gam_ptr += vec + f_ptr += b_id * T * H + h_id + h_ptr += ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * D * D + s_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + s0_ptr += s_off + s1_ptr += s_off + s2_ptr += s_off + sq = qb * BLOCK_C + Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C) + valid = (sq + tl.arange(0, BLOCK_C)) < n_valid + k0 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, 0, 0, BLOCK_C, BLOCK_D) + g0 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, 0, 0, BLOCK_C, BLOCK_D) + if NUM_C > 1: + k1 = _load_bc(k_ptr, T, H, D, chunk_id, chunk_size, BLOCK_C, 0, BLOCK_C, BLOCK_D) + g1 = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, BLOCK_C, 0, BLOCK_C, BLOCK_D) + else: + k1 = k0 + g1 = g0 + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + eq = tl.exp(gq) + h_tile = _load_mat(h_ptr, D, 0, 0, BLOCK_D) + src = _load_bc(src0_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + # Orders are chained in registers. Touch the unused reload pointers so the + # launch signature stays identical to ``trace_phi_qb_kernel``. + src1_ptr += 0 + src2_ptr += 0 + src = _order_d1( + src, s0_ptr, dst0_ptr, k0, g0, k1, g1, gq, eq, Fb, valid, h_tile, + T, H, D, chunk_id, chunk_size, sq, n_valid, qb, + SHIFT, PREC, BLOCK_D, BLOCK_C, NUM_C, + ) + if N > 2: + src = _order_d1( + src, s1_ptr, dst1_ptr, k0, g0, k1, g1, gq, eq, Fb, valid, h_tile, + T, H, D, chunk_id, chunk_size, sq, n_valid, qb, + SHIFT, PREC, BLOCK_D, BLOCK_C, NUM_C, + ) + if N > 3: + _order_d1( + src, s2_ptr, dst2_ptr, k0, g0, k1, g1, gq, eq, Fb, valid, h_tile, + T, H, D, chunk_id, chunk_size, sq, n_valid, qb, + SHIFT, PREC, BLOCK_D, BLOCK_C, NUM_C, + ) + + +@triton.jit +def _z_orders( + z, y0, y1, y2, gq, gg, sq, sk, n_valid, + s0_ptr, s1_ptr, s2_ptr, qb, kb, + DIAG: tl.constexpr, SHIFT: tl.constexpr, PREC: tl.constexpr, + N: tl.constexpr, BLOCK_C: tl.constexpr, NUM_C: tl.constexpr, +): + S0 = _load_S(s0_ptr, qb, kb, NUM_C, BLOCK_C) + z += _z_pair(S0, y0, gq, gg, sq, sk, n_valid, DIAG, SHIFT, PREC, BLOCK_C) + if N > 2: + S1 = _load_S(s1_ptr, qb, kb, NUM_C, BLOCK_C) + z += _z_pair(S1, y1, gq, gg, sq, sk, n_valid, DIAG, SHIFT, PREC, BLOCK_C) + if N > 3: + S2 = _load_S(s2_ptr, qb, kb, NUM_C, BLOCK_C) + z += _z_pair(S2, y2, gq, gg, sq, sk, n_valid, DIAG, SHIFT, PREC, BLOCK_C) + return z + + +@triton.jit(do_not_specialize=["T"]) +def trace_z_coeff_d1_kernel( + q_ptr, o1_ptr, o2_ptr, k_ptr, gam_ptr, f_ptr, coeff_ptr, dk_ptr, + s0_ptr, s1_ptr, s2_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + N: tl.constexpr, PREC: tl.constexpr, +): + """Every coeff-weighted Z order into ``dk``, one store.""" + chunk_id = tl.program_id(0) + kb = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_C: tl.constexpr = chunk_size // BLOCK_C + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + vec = (b_id * T * H + h_id) * D + q_ptr += vec + o1_ptr += vec + o2_ptr += vec + gam_ptr += vec + dk_ptr += vec + f_ptr += b_id * T * H + h_id + s_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + s0_ptr += s_off + s1_ptr += s_off + s2_ptr += s_off + c1 = tl.load(coeff_ptr + h_id * N + 1).to(tl.float32) + c2 = tl.load(coeff_ptr + h_id * N + 2).to(tl.float32) + c3 = 0.0 + if N > 3: + c3 = tl.load(coeff_ptr + h_id * N + 3).to(tl.float32) + sk = kb * BLOCK_C + z = tl.zeros((BLOCK_C, BLOCK_D), dtype=tl.float32) + if sk < n_valid: + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + for qb in tl.range(kb, NUM_C): + sq = qb * BLOCK_C + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + Fb = _load_f_bc(f_ptr, H, chunk_id, chunk_size, sq, BLOCK_C) + q = _load_bc(q_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + o1 = _load_bc(o1_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + o2 = q + if N > 3: + o2 = _load_bc(o2_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + inv = 1.0 / Fb[:, None] + y0 = (c1 * q + c2 * o1 + c3 * o2) * inv + y1 = (c2 * q + c3 * o1) * inv + y2 = (c3 * q) * inv + if qb == kb: + z = _z_orders( + z, y0, y1, y2, gq, gg, sq, sk, n_valid, + s0_ptr, s1_ptr, s2_ptr, qb, kb, + True, SHIFT, PREC, N, BLOCK_C, NUM_C, + ) + else: + z = _z_orders( + z, y0, y1, y2, gq, gg, sq, sk, n_valid, + s0_ptr, s1_ptr, s2_ptr, qb, kb, + False, SHIFT, PREC, N, BLOCK_C, NUM_C, + ) + _store_bc(dk_ptr, z, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + + +@triton.jit(do_not_specialize=["T"]) +def trace_z_y_d1_kernel( + u1_ptr, u2_ptr, u3_ptr, gam_ptr, dk_ptr, + s0_ptr, s1_ptr, s2_ptr, + T, H: tl.constexpr, D: tl.constexpr, chunk_size: tl.constexpr, + BLOCK_D: tl.constexpr, BLOCK_C: tl.constexpr, SHIFT: tl.constexpr, + N: tl.constexpr, PREC: tl.constexpr, +): + """Add the stored-y Z orders (u1, u2, u3) into ``dk``.""" + chunk_id = tl.program_id(0) + kb = tl.program_id(1) + bh = tl.program_id(2) + b_id, h_id = bh // H, bh % H + num_chunks = tl.cdiv(T, chunk_size) + NUM_C: tl.constexpr = chunk_size // BLOCK_C + n_valid = tl.minimum(chunk_size, T - chunk_id * chunk_size) + vec = (b_id * T * H + h_id) * D + u1_ptr += vec + u2_ptr += vec + u3_ptr += vec + gam_ptr += vec + dk_ptr += vec + s_off = ((b_id * num_chunks + chunk_id) * H + h_id).to(tl.int64) * (NUM_C * NUM_C * BLOCK_C * BLOCK_C) + s0_ptr += s_off + s1_ptr += s_off + s2_ptr += s_off + sk = kb * BLOCK_C + z = _load_bc(dk_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + if sk < n_valid: + gg = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + for qb in tl.range(kb, NUM_C): + sq = qb * BLOCK_C + if sq < n_valid: + gq = _load_bc(gam_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + y0 = _load_bc(u1_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + y1 = y0 + y2 = y0 + if N > 2: + y1 = _load_bc(u2_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + if N > 3: + y2 = _load_bc(u3_ptr, T, H, D, chunk_id, chunk_size, sq, 0, BLOCK_C, BLOCK_D) + if qb == kb: + z = _z_orders( + z, y0, y1, y2, gq, gg, sq, sk, n_valid, + s0_ptr, s1_ptr, s2_ptr, qb, kb, + True, SHIFT, PREC, N, BLOCK_C, NUM_C, + ) + else: + z = _z_orders( + z, y0, y1, y2, gq, gg, sq, sk, n_valid, + s0_ptr, s1_ptr, s2_ptr, qb, kb, + False, SHIFT, PREC, N, BLOCK_C, NUM_C, + ) + _store_bc(dk_ptr, z, T, H, D, chunk_id, chunk_size, sk, 0, BLOCK_C, BLOCK_D) + + +def _bwd(k, q, os, dx, F, coeff_h, gam, h, dht, h0, chunk_size, n_coeff, s_fwd, block_c, shift, prec): + """os = (o1, o2[, o3]) in fp32. p/u and dk/dgk stay fp32.""" + B, T, H, D = q.shape + C = chunk_size + N = n_coeff + nc = triton.cdiv(T, C) + block_d = _choose_intra_d(D) + gin_d = _choose_block_d(D) + num_c = C // block_c + f32 = dict(device=q.device, dtype=torch.float32) + o1, o2 = os[0], os[1] + o3 = os[2] if N == 4 else o2 + # p/u feed dgk. Rounding them to bf16 flips gk=-5 dgk (cos ~0.46). + p1 = torch.empty(B, T, H, D, **f32) + p2 = torch.empty(B, T, H, D, **f32) + p3 = torch.empty(B, T, H, D, **f32) if N == 4 else p2 + u1 = torch.empty(B, T, H, D, **f32) + u2 = torch.empty(B, T, H, D, **f32) + u3 = torch.empty(B, T, H, D, **f32) if N == 4 else u2 + dq = torch.empty_like(q) + dk = torch.empty(B, T, H, D, **f32) + dgk = torch.empty(B, T, H, D, **f32) + g_partial = torch.empty(B, nc, H, D, D, **f32) + gin = torch.empty(B, nc, H, D, D, **f32) + dcoeff_part = torch.empty(B, nc, H, N, **f32) + alpha = torch.empty(B, T, H, **f32) + diag_ws = torch.empty(B, T, H, D, **f32) + s_shape = (B, nc, H, num_c, num_c, block_c, block_c) + s_bwd = [torch.empty(*s_shape, **f32) for _ in range(N - 1)] + grid = (nc, B * H) + grid_b = (nc, num_c, B * H) + bwd_dst = [p1, p2, p3] + s2 = s_bwd[2] if N > 3 else s_bwd[0] + src2 = bwd_dst[1] if N > 3 else dx + dst2 = bwd_dst[2] if N > 3 else bwd_dst[1] + use_d1 = _use_d1(D, block_d, C, block_c) + phi_kn = trace_phi_d1_kernel if use_d1 else trace_phi_qb_kernel + phi_kn[grid_b]( + dx, p1, src2, p1, p2, dst2, + k, gam, h, F, s_bwd[0], s_bwd[min(1, N - 2)], s2, + T, H, D, C, block_d, block_c, shift, N, prec, + num_warps=4, num_stages=2, + ) + if use_d1: + trace_z_coeff_d1_kernel[grid_b]( + q, o1, o2, k, gam, F, coeff_h, dk, + s_bwd[0], s_bwd[min(1, N - 2)], s2, + T, H, D, C, block_d, block_c, shift, N, prec, + num_warps=4, num_stages=1, + ) + else: + for j in range(N - 1): + trace_z_kb_kernel[grid_b]( + q, k, gam, q, q, o1, o2, F, coeff_h, dk, s_bwd[j], + T, H, D, C, block_d, block_c, shift, N, j, prec, + True, True, j > 0, + num_warps=4, num_stages=1, + ) + trace_bwd_grad_kernel[grid]( + h, gam, q, o1, o2, o3, dx, F, coeff_h, + p1, p2, p3, u1, u2, u3, + dq, dgk, g_partial, dcoeff_part, alpha, + T, H, D, C, block_d, N, prec, + num_warps=8, num_stages=1, + ) + z_src = [q, o1, o2] + z_y = [u1, u2, u3] + if use_d1: + s_y2 = s_fwd[2] if N > 3 else s_fwd[0] + trace_z_y_d1_kernel[grid_b]( + u1, u2, u3, gam, dk, + s_fwd[0], s_fwd[min(1, N - 2)], s_y2, + T, H, D, C, block_d, block_c, shift, N, prec, + num_warps=4, num_stages=1, + ) + else: + for m in range(1, N): + trace_z_kb_kernel[grid_b]( + z_src[m - 1], k, gam, z_y[m - 1], q, o1, o2, F, coeff_h, dk, s_fwd[m - 1], + T, H, D, C, block_d, block_c, shift, N, 0, prec, + True, False, True, + num_warps=4, num_stages=1, + ) + trace_bwd_epilogue_kernel[(nc, D // block_d, B * H)]( + h, k, gam, alpha, diag_ws, dk, dgk, + T, H, D, C, block_d, + num_warps=4, num_stages=1, + ) + block_s = _choose_scan_block(D) + num_s = D // block_s + dht_buf = dht.float().contiguous() if dht is not None else gin.new_empty(1) + trace_bwd_scan_kernel[(B * H, num_s * num_s)]( + g_partial, gam, gin, dht_buf, + T, nc, H, D, C, block_s, int(dht is not None), + num_warps=1, num_stages=1, + ) + trace_bwd_gin_kernel[grid]( + h, k, gam, gin, dk, dgk, + T, H, D, C, gin_d, prec, num_warps=8, num_stages=1, + ) + dh0 = None + if h0 is not None: + e0 = gam[:, min(C, T) - 1].exp() + dh0 = g_partial[:, 0] + e0[..., :, None] * gin[:, 0] * e0[..., None, :] + dh0 = dh0.to(h0.dtype) + return dq, dk, dgk, dcoeff_part, dh0 + + +class q_kkt_solve_trace_triton_safe_ver1(torch.autograd.Function): + """x, H_T = phi(q, k, gk) with F = tr(H) and per-dimension decay. + + apply(k, q, gk, chunk_size, coeff, h0) -> (x [B, T, H, D], H_T [B, H, D, D]) + coeff is [N] or [H, N], N = 3 or 4. chunk_size must be 16, 32, or 64. + gk is non-positive; the block references rely on that. + """ + + @staticmethod + def forward(ctx, k, q, gk=None, chunk_size: int = 64, coeff=(1.0, -0.5, 0.375), h0=None): + if q.ndim != 4: + raise ValueError(f"q must be [B, T, H, D], got {tuple(q.shape)}") + if chunk_size not in (16, 32, 64): + raise ValueError(f"chunk_size must be 16, 32, or 64, got {chunk_size}") + k = k.contiguous() + q = q.contiguous() + B, T, H, D = q.shape + coeff_is_tensor = torch.is_tensor(coeff) + coeff_shape = tuple(coeff.shape) if coeff_is_tensor else None + coeff_dtype = coeff.dtype if coeff_is_tensor else None + coeff_h = _normalize_coeff(coeff, H, q.device) + n_coeff = coeff_h.shape[-1] + + if gk is None: + gam = torch.zeros(B, T, H, D, device=q.device, dtype=torch.float32) + gk_arg = gv_arg = None + else: + gk = gk.contiguous() + gam = chunk_local_cumsum(gk, chunk_size=chunk_size, scale=0.5, output_dtype=torch.float32) + gk_arg = gv_arg = gam + h, ht = chunk_fwd_h( + k=k, v=k, gk=gk_arg, gv=gv_arg, h0=h0, + output_final_state=True, chunk_size=chunk_size, states_in_fp32=True, + ) + f32 = dict(device=q.device, dtype=torch.float32) + x = torch.empty_like(q) + o1 = torch.empty(B, T, H, D, **f32) + o2 = torch.empty(B, T, H, D, **f32) + o3 = torch.empty(B, T, H, D, **f32) if n_coeff == 4 else o2 + F = torch.empty(B, T, H, **f32) + bd = _choose_intra_d(D) + nc = triton.cdiv(T, chunk_size) + block_c = _block_c(chunk_size) + prec, shift = _launch_prec(block_c, 0.0) + nC = chunk_size // block_c + trace_F_kernel[(nc, B * H)]( + h, k, gam, F, T, H, D, chunk_size, bd, EPS, num_warps=4, num_stages=1, + ) + s_fwd = [ + torch.empty(B, nc, H, nC, nC, block_c, block_c, **f32) + for _ in range(1, n_coeff) + ] + s2 = s_fwd[2] if n_coeff > 3 else s_fwd[0] + src2 = o2 if n_coeff > 3 else q + dst2 = o3 if n_coeff > 3 else o2 + phi_kn = trace_phi_d1_kernel if _use_d1(D, bd, chunk_size, block_c) else trace_phi_qb_kernel + phi_kn[(nc, nC, B * H)]( + q, o1, src2, o1, o2, dst2, + k, gam, h, F, s_fwd[0], s_fwd[min(1, n_coeff - 2)], s2, + T, H, D, chunk_size, bd, block_c, shift, n_coeff, prec, + num_warps=4, num_stages=2, + ) + trace_mix_kernel[(nc, B * H)]( + q, o1, o2, o3, x, coeff_h, T, H, D, chunk_size, bd, n_coeff, + num_warps=4, num_stages=1, + ) + + saved = [k, q, o1, o2, F, coeff_h, h, gam, *s_fwd] + if n_coeff == 4: + saved.append(o3) + if gk is not None: + saved.append(gk) + if h0 is not None: + saved.append(h0) + ctx.save_for_backward(*saved) + ctx.chunk_size = chunk_size + ctx.block_c = block_c + ctx.shift = shift + ctx.prec = prec + ctx.n_coeff = n_coeff + ctx.n_s = n_coeff - 1 + ctx.has_gk = gk is not None + ctx.has_h0 = h0 is not None + ctx.coeff_is_tensor = coeff_is_tensor + ctx.coeff_shape = coeff_shape + ctx.coeff_dtype = coeff_dtype + return x, ht + + @staticmethod + def backward(ctx, dx, dht=None): + saved = list(ctx.saved_tensors) + k, q, o1, o2, F, coeff_h, h, gam = saved[:8] + idx = 8 + s_fwd = saved[idx:idx + ctx.n_s] + idx += ctx.n_s + o3 = saved[idx] if ctx.n_coeff == 4 else None + idx += int(ctx.n_coeff == 4) + gk = saved[idx] if ctx.has_gk else None + idx += int(ctx.has_gk) + h0 = saved[idx] if ctx.has_h0 else None + os_ = [o1, o2] + ([o3] if o3 is not None else []) + dq, dk, dgk, dcoeff_part, dh0 = _bwd( + k, q, os_, dx.contiguous(), F, coeff_h, gam, h, + None if dht is None else dht.contiguous(), h0, ctx.chunk_size, ctx.n_coeff, s_fwd, + ctx.block_c, ctx.shift, ctx.prec, + ) + dcoeff = None + if ctx.coeff_is_tensor and ctx.needs_input_grad[4]: + dcoeff_h = dcoeff_part.sum(dim=(0, 1)) + if len(ctx.coeff_shape) == 1: + dcoeff_h = dcoeff_h.sum(0) + dcoeff = dcoeff_h.to(ctx.coeff_dtype).reshape(ctx.coeff_shape) + dgk_out = dgk.to(gk.dtype) if gk is not None else None + return dk.to(k.dtype), dq, dgk_out, None, dcoeff, dh0 + + +safe_ver1 = q_kkt_solve_trace_triton_safe_ver1 diff --git a/ops/retention/chunk.py b/ops/retention/chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7867a3706771fc7143c3055b9122004bcd45f7 --- /dev/null +++ b/ops/retention/chunk.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +import warnings +from typing import Optional, Tuple + +import torch + +from fla.ops.simple_gla.chunk import chunk_simple_gla + + +@torch.compiler.disable +def chunk_retention( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + scale: Optional[float] = None, + initial_state: Optional[torch.Tensor] = None, + output_final_state: bool = False, + cu_seqlens: Optional[torch.LongTensor] = None, + head_first: bool = False +) -> Tuple[torch.Tensor, torch.Tensor]: + r""" + Args: + q (torch.Tensor): + queries of shape `[B, T, H, K]`. + k (torch.Tensor): + keys of shape `[B, T, H, K]`. + v (torch.Tensor): + values of shape `[B, T, H, V]`. + scale (Optional[float]): + Scale factor for the attention scores. + If not provided, it will default to `1 / sqrt(K)`. Default: `None`. + initial_state (Optional[torch.Tensor]): + Initial state of shape `[N, H, K, V]` for `N` input sequences. + For equal-length input sequences, `N` equals the batch size `B`. + Default: `None`. + output_final_state (Optional[bool]): + Whether to output the final state of shape `[N, H, K, V]`. Default: `False`. + cu_seqlens (torch.LongTensor): + Cumulative sequence lengths of shape `[N+1]` used for variable-length training, + consistent with the FlashAttention API. + head_first (Optional[bool]): + Whether the inputs are in the head-first format. Default: `False`. + This argument has been deprecated. + + Returns: + o (torch.Tensor): + Outputs of shape `[B, T, H, V]`. + final_state (torch.Tensor): + Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`. + + """ + if head_first: + raise DeprecationWarning( + "head_first is deprecated and will be removed in a future version. " + "Please use head_first=False for now instead." + ) + if not head_first and q.shape[1] < q.shape[2]: + warnings.warn( + f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). " + "This may indicate the inputs were passed in head-first format [B, H, T, ...] " + "when head_first=False was specified. " + "Please verify your input tensor format matches the expected shape [B, T, H, ...]." + ) + g_gamma = (1 - q.new_tensor(2., dtype=torch.float).pow(-5. - q.new_tensor(range(q.shape[2]), dtype=torch.float))).log() + o, final_state = chunk_simple_gla( + q=q, + k=k, + v=v, + scale=scale, + g_gamma=g_gamma, + initial_state=initial_state, + output_final_state=output_final_state, + cu_seqlens=cu_seqlens + ) + return o, final_state diff --git a/ops/retention/fused_recurrent.py b/ops/retention/fused_recurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..d4cbf4aa5fc0afb4e9046e3217b0fa68fd4823b7 --- /dev/null +++ b/ops/retention/fused_recurrent.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from typing import Optional, Tuple + +import torch + +from fla.ops.simple_gla.fused_recurrent import fused_recurrent_simple_gla + + +def fused_recurrent_retention( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + scale: Optional[float] = None, + initial_state: Optional[torch.Tensor] = None, + output_final_state: bool = False, + reverse: bool = False, + cu_seqlens: Optional[torch.LongTensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + g_gamma = (1 - q.new_tensor(2., dtype=torch.float).pow(-5. - q.new_tensor(range(q.shape[2]), dtype=torch.float))).log() + o, final_state = fused_recurrent_simple_gla( + q=q, + k=k, + v=v, + g_gamma=g_gamma, + scale=scale, + initial_state=initial_state, + output_final_state=output_final_state, + reverse=reverse, + cu_seqlens=cu_seqlens, + ) + return o, final_state diff --git a/ops/simple_gla/naive.py b/ops/simple_gla/naive.py new file mode 100644 index 0000000000000000000000000000000000000000..e0632ae2d5690cfff014096d883b9cee115a8db4 --- /dev/null +++ b/ops/simple_gla/naive.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- + +from typing import Optional + +import torch +import torch.nn.functional as F +from einops import rearrange + + +def naive_chunk_simple_gla( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + g: torch.Tensor, + initial_state: Optional[torch.Tensor] = None, + output_final_state: bool = False, + chunk_size: int = 64, + scale: Optional[float] = None, +): + q, k, v, g = map(lambda x: rearrange(x, 'b t h ... -> b h t ...').to(torch.float32), [q, k, v, g]) + if scale is None: + scale = 1.0 / q.shape[-1] ** 0.5 + + T = q.shape[-2] + BT = chunk_size + pad_len = (BT - (T % BT)) % BT + if pad_len > 0: + # Pad all tensors + q = F.pad(q, (0, 0, 0, pad_len)) + k = F.pad(k, (0, 0, 0, pad_len)) + v = F.pad(v, (0, 0, 0, pad_len)) + g = F.pad(g, (0, pad_len)) + decay = g + B, H, T1, K = q.shape + V = v.shape[-1] + q = q * scale + q, k, v, decay = map(lambda x: rearrange(x, 'b h (n c) d -> b h n c d', c=chunk_size), [q, k, v, decay.unsqueeze(-1)]) + decay = decay.squeeze(-1).cumsum(-1) + L_mask = ((decay.unsqueeze(-1) - decay.unsqueeze(-2)).tril().exp().float()).tril() + S = k.new_zeros(B, H, K, V) + if initial_state is not None: + S = initial_state + o = torch.zeros_like(v) + for i in range(0, T1 // chunk_size): + q_i, k_i, v_i = q[:, :, i], k[:, :, i], v[:, :, i] + attn = (q_i @ k_i.transpose(-1, -2) * L_mask[:, :, i]) + o_inter = (q_i * decay[:, :, i, :, None].exp()) @ S + o[:, :, i] = o_inter + attn @ v_i + S = S * decay[:, :, i, -1, None, None].exp() + \ + (k_i * (decay[:, :, i, -1, None] - decay[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_i + if not output_final_state: + S = None + # unpad + o = rearrange(o, 'b h n c d -> b (n c) h d')[:, :T] + return o, S + + +def naive_recurrent_simple_gla( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + g: torch.Tensor, + scale: Optional[float] = None, + initial_state: Optional[torch.Tensor] = None, + output_final_state: bool = True +): + dtype = q.dtype + q, k, v, g = map(lambda x: x.transpose(1, 2).float(), (q, k, v, g)) + B, H, T, K = q.shape + V = v.shape[-1] + if scale is None: + scale = K ** -0.5 + q = q * scale + o = v.new_zeros(B, H, T, V) + + S = q.new_zeros(B, H, K, V) + if initial_state is not None: + S += initial_state + + for i in range(T): + gate = g[:, :, i].exp() + key = k[:, :, i] + value = v[:, :, i] + kv = key.unsqueeze(-1) * value.unsqueeze(-2) + S = S * gate.unsqueeze(-1).unsqueeze(-1) + kv + q_i = q[:, :, i, :] + o_i = (q_i.unsqueeze(-1) * S).sum(-2) + o[:, :, i] = o_i + if not output_final_state: + S = None + return o.transpose(1, 2).to(dtype), S + + +def naive_parallel_simple_gla( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + g: torch.Tensor, + scale: Optional[float] = None +): + q, k, v, g = map(lambda x: rearrange(x, 'b t h ... -> b h t ...').to(torch.float32), [q, k, v, g]) + if scale is None: + scale = 1.0 / q.shape[-1] ** 0.5 + dtype = q.dtype + A = (q @ k.transpose(-1, -2) * scale) + if g is not None: + g = g.cumsum(-1) + D = (g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().tril() + A = A * D + else: + A = A.tril() + o = A @ v + o = o.transpose(1, 2) + return o.to(dtype), A diff --git a/ops/titans/__init__.py b/ops/titans/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..55aa4e0588f0b27d61ba190c5987ae7d637ca3d8 --- /dev/null +++ b/ops/titans/__init__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- + +from .naive import chunk_titans_linear + +__all__ = [ + 'chunk_titans_linear' +] diff --git a/ops/ttt/__init__.py b/ops/ttt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d66e42f18785546b4e3be77abc2c91519e3bb9 --- /dev/null +++ b/ops/ttt/__init__.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- + +from .chunk import chunk_ttt_linear +from .fused_chunk import fused_chunk_ttt_linear + +__all__ = [ + 'fused_chunk_ttt_linear', + 'chunk_ttt_linear' +] diff --git a/ops/utils/constant.py b/ops/utils/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..c03800ce93ad7905b13c1ee7f6e53aa0ad658869 --- /dev/null +++ b/ops/utils/constant.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +# Approximate value of 1/ln(2), used for log/exp base conversion +# Best FP32 approximation: 1.4426950216 (hex 0x3FB8AA3B) +RCP_LN2 = 1.4426950216 diff --git a/ops/utils/logsumexp.py b/ops/utils/logsumexp.py new file mode 100644 index 0000000000000000000000000000000000000000..f6fd494d113f280bd0f01817f66c3a9339be77f5 --- /dev/null +++ b/ops/utils/logsumexp.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2024, Songlin Yang, Yu Zhang + +from typing import Optional + +import torch +import triton +import triton.language as tl + +from fla.ops.utils.op import exp, log +from fla.utils import autotune_cache_kwargs + + +@triton.heuristics({ + 'HAS_SCALE': lambda args: args['scale'] is not None +}) +@triton.autotune( + configs=[ + triton.Config({}, num_warps=num_warps) + for num_warps in [1, 2, 4, 8, 16, 32] + ], + key=['D'], + **autotune_cache_kwargs +) +@triton.jit +def logsumexp_fwd_kernel( + x, + z, + scale, + D: tl.constexpr, + B: tl.constexpr, + HAS_SCALE: tl.constexpr +): + i_n, i_d = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64) + o_d = i_d * B + tl.arange(0, B) + m_d = o_d < D + + b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=-float('inf')) + if HAS_SCALE: + b_x = b_x * scale + b_m = tl.max(b_x, 0) + b_z = log(tl.sum(exp(b_x - b_m), 0)) + b_m + tl.store(z + i_n * tl.cdiv(D, B) + i_d, b_z) + + +def logsumexp_fwd( + x, + scale: Optional[float] = None, + dtype: Optional[torch.dtype] = None +): + r""" + Compute the logsumexp of the input tensor over the last dimension. + + Args: + x (Tensor): + The input tensor of any shape. + scale (Optional[float]): + The scale applied to the input tensor. Default: `None`. + dtype (Optional[torch.dtype]): + The data type of the output tensor. Default: `None`. + Returns: + Tensor: The logsumexp of the input tensor. + """ + + shape = x.shape + x = x.view(-1, shape[-1]) + N, D = x.shape + B = min(triton.next_power_of_2(D), 64 * 1024) + ND = triton.cdiv(D, B) + + z = x.new_empty(N, ND, dtype=torch.float) + logsumexp_fwd_kernel[(N, ND)]( + x=x, + z=z, + scale=scale, + D=D, + B=B + ) + z = z.logsumexp(-1).view(*shape[:-1]) + if dtype is not None and dtype != torch.float: + z = z.to(dtype) + return z diff --git a/ops/utils/op.py b/ops/utils/op.py new file mode 100644 index 0000000000000000000000000000000000000000..d74a2963fb2366a5d0ced9ff07368daf048b0c4c --- /dev/null +++ b/ops/utils/op.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +import os + +import triton +import triton.language as tl +import triton.language.extra.libdevice as tldevice + +from fla.utils import is_gather_supported + +if os.environ.get('FLA_USE_FAST_OPS', '0') == '1': + exp = tldevice.fast_expf + exp2 = tldevice.exp2 + log = tldevice.fast_logf + log2 = tldevice.fast_log2f +else: + exp = tl.exp + exp2 = tl.math.exp2 + log = tl.log + log2 = tl.log2 + + +@triton.jit +def safe_exp(x): + return exp(tl.where(x <= 0, x, float('-inf'))) + + +if not is_gather_supported: + @triton.jit + def gather(src, index, axis, _builder=None): + """ + Gather operation that works when tl.gather is not supported. + This is a fallback implementation that returns None. + Just to make triton compiler happy. + """ + return None +else: + gather = tl.gather + + +if hasattr(triton.language, '_experimental_make_tensor_descriptor'): + # For Triton 3.3.x + make_tensor_descriptor = triton.language._experimental_make_tensor_descriptor +elif hasattr(triton.language, 'make_tensor_descriptor'): + # For Triton 3.4.x and later + make_tensor_descriptor = triton.language.make_tensor_descriptor +else: + """ + Fallback implementation when TMA is not supported. + Returns None to indicate TMA descriptors are unavailable. + Just make triton compiler happy. + """ + @triton.jit + def make_tensor_descriptor( + base, + shape, + strides, + block_shape, + _builder=None, + ): + return None diff --git a/ops/utils/pooling.py b/ops/utils/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1af83c3d3d87883da1495c4b8eef06c05d0bc9 --- /dev/null +++ b/ops/utils/pooling.py @@ -0,0 +1,209 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang + +from typing import Optional, Tuple + +import torch +import triton +import triton.language as tl + +from fla.ops.utils.index import prepare_chunk_indices +from fla.utils import autocast_custom_bwd, autocast_custom_fwd, autotune_cache_kwargs, input_guard + + +@triton.heuristics({ + 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None +}) +@triton.autotune( + configs=[ + triton.Config({'BD': BD}, num_warps=num_warps) + for BD in [16, 32, 64, 128] + for num_warps in [1, 2, 4, 8] + ], + key=['BT'], + **autotune_cache_kwargs +) +@triton.jit(do_not_specialize=['T']) +def mean_pooling_fwd_kernel( + x, + o, + cu_seqlens, + chunk_indices, + T, + H: tl.constexpr, + D: tl.constexpr, + BT: tl.constexpr, + BD: tl.constexpr, + IS_VARLEN: tl.constexpr +): + i_d, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2) + i_b, i_h = i_bh // H, i_bh % H + if IS_VARLEN: + i_tg = i_t + i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32) + bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32) + T = eos - bos + NT = tl.cdiv(T, BT) + else: + NT = tl.cdiv(T, BT) + i_tg = i_b * NT + i_t + bos, eos = i_b * T, i_b * T + T + + p_x = tl.make_block_ptr(x + (bos * H + i_h) * D, (T, D), (H*D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0)) + p_o = tl.make_block_ptr(o + (i_tg * H + i_h) * D, (D,), (1,), (i_d * BD,), (BD,), (0,)) + # [BT, BD] + b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32) + # [BD] + b_o = tl.sum(b_x, axis=0) / min(BT, T - i_t * BT) + tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0,)) + + +@triton.heuristics({ + 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None +}) +@triton.autotune( + configs=[ + triton.Config({'BD': BD}, num_warps=num_warps) + for BD in [16, 32, 64, 128] + for num_warps in [1, 2, 4, 8] + ], + key=['BT'], + **autotune_cache_kwargs +) +@triton.jit(do_not_specialize=['T']) +def mean_pooling_bwd_kernel( + do, + dx, + cu_seqlens, + chunk_indices, + T, + H: tl.constexpr, + D: tl.constexpr, + BT: tl.constexpr, + BD: tl.constexpr, + IS_VARLEN: tl.constexpr +): + i_d, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2) + i_b, i_h = i_bh // H, i_bh % H + if IS_VARLEN: + i_tg = i_t + i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32) + bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32) + T = eos - bos + NT = tl.cdiv(T, BT) + else: + NT = tl.cdiv(T, BT) + i_tg = i_b * NT + i_t + bos, eos = i_b * T, i_b * T + T + + p_dx = tl.make_block_ptr(dx + (bos * H + i_h) * D, (T, D), (H*D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0)) + p_do = tl.make_block_ptr(do + (i_tg * H + i_h) * D, (D,), (1,), (i_d * BD,), (BD,), (0,)) + # [BD] + b_do = tl.load(p_do, boundary_check=(0,)).to(tl.float32) + # [BT, BD] + b_dx = b_do / tl.full((BT,), min(BT, T - i_t * BT), dtype=tl.float32)[:, None] + tl.store(p_dx, b_dx.to(p_dx.dtype.element_ty), boundary_check=(0, 1)) + + +def mean_pooling_fwd( + x: torch.Tensor, + chunk_size: int, + cu_seqlens: Optional[torch.LongTensor] = None +) -> torch.Tensor: + B, T, H, D = x.shape + BT = chunk_size + chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None + NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices) + + o = x.new_empty(B, NT, H, D) + def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B * H) + mean_pooling_fwd_kernel[grid]( + x, + o, + cu_seqlens, + chunk_indices, + T=T, + H=H, + D=D, + BT=BT, + ) + return o + + +def mean_pooling_bwd( + do: torch.Tensor, + batch_size: int, + seq_len: int, + chunk_size: int, + cu_seqlens: Optional[torch.LongTensor] = None +) -> torch.Tensor: + B, T, H, D = batch_size, seq_len, *do.shape[-2:] + BT = chunk_size + chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None + NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices) + + dx = do.new_empty(B, T, H, D) + def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B * H) + mean_pooling_bwd_kernel[grid]( + do, + dx, + cu_seqlens, + chunk_indices, + T=T, + H=H, + D=D, + BT=BT, + ) + return dx + + +class MeanPoolingFunction(torch.autograd.Function): + + @staticmethod + @input_guard + @autocast_custom_fwd + def forward( + ctx, + x: torch.Tensor, + chunk_size: int, + cu_seqlens: Optional[torch.LongTensor] = None + ) -> torch.Tensor: + o = mean_pooling_fwd(x, chunk_size, cu_seqlens) + ctx.batch_size = x.shape[0] + ctx.seq_len = x.shape[1] + ctx.chunk_size = chunk_size + ctx.cu_seqlens = cu_seqlens + return o + + @staticmethod + @input_guard + @autocast_custom_bwd + def backward( + ctx, do + ) -> Tuple[torch.Tensor, None, None]: + batch_size = ctx.batch_size + seq_len = ctx.seq_len + chunk_size = ctx.chunk_size + cu_seqlens = ctx.cu_seqlens + dx = mean_pooling_bwd(do, batch_size, seq_len, chunk_size, cu_seqlens) + return dx, None, None + + +def mean_pooling( + x: torch.Tensor, + chunk_size: int, + cu_seqlens: Optional[torch.LongTensor] = None, + head_first: bool = False +) -> torch.Tensor: + if head_first: + x = x.transpose(1, 2) + if cu_seqlens is not None: + if x.shape[0] != 1: + raise ValueError( + f"The batch size is expected to be 1 rather than {x.shape[0]} when using `cu_seqlens`." + f"Please flatten variable-length inputs before processing." + ) + o = MeanPoolingFunction.apply(x, chunk_size, cu_seqlens) + if head_first: + o = o.transpose(1, 2) + return o diff --git a/utils.py b/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..68a73d65fc9434ce9095b03b9627f74f64dce8fb --- /dev/null +++ b/utils.py @@ -0,0 +1,467 @@ +# -*- coding: utf-8 -*- + +import contextlib +import functools +import inspect +import logging +import os +import sys +import warnings +from enum import Enum +from functools import lru_cache +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple + +import torch +import triton +from packaging import version + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from fla import __version__ + +FLA_CI_ENV = os.getenv("FLA_CI_ENV") == "1" +FLA_CACHE_RESULTS = os.getenv('FLA_CACHE_RESULTS', '1') == '1' + + +supports_autotune_cache = "cache_results" in inspect.signature(triton.autotune).parameters +autotune_cache_kwargs = {"cache_results": FLA_CACHE_RESULTS} if supports_autotune_cache else {} + + +@lru_cache(maxsize=1) +def check_environments(): + """ + Checks the current operating system, Triton version, and Python version, + issuing warnings if they don't meet recommendations. + This function's body only runs once due to lru_cache. + """ + # Check Operating System + if sys.platform == 'win32': + logger.warning( + "Detected Windows operating system. Triton does not have an official Windows release, " + "thus FLA will not be adapted for Windows, and any potential errors will not be fixed. " + "Please consider using a Linux environment for compatibility." + ) + + triton_version = version.parse(triton.__version__) + required_triton_version = version.parse("3.2.0") + + if triton_version < required_triton_version: + logger.warning( + f"Current Triton version {triton_version} is below the recommended 3.2.0 version. " + "Errors may occur and these issues will not be fixed. " + "Please consider upgrading Triton." + ) + + # Check Python version + py_version = version.parse(f"{sys.version_info.major}.{sys.version_info.minor}") + required_py_version = version.parse("3.11") + + if py_version < required_py_version: + logger.warning( + f"Current Python version {py_version} is below the recommended 3.11 version. " + "It is recommended to upgrade to Python 3.11 or higher for the best experience." + ) + + return None + + +check_environments() + + +def get_abs_err(x, y): + return (x.detach()-y.detach()).flatten().abs().max().item() + + +def get_err_ratio(x, y): + err = (x.detach()-y.detach()).flatten().square().mean().sqrt().item() + base = (x.detach()).flatten().square().mean().sqrt().item() + return err / (base + 1e-8) + + +def assert_close(prefix, ref, tri, ratio, warning=False, err_atol=1e-6): + abs_atol = get_abs_err(ref, tri) + msg = f"{prefix:>16} diff: {abs_atol:.6f} ratio: {get_err_ratio(ref, tri):.6f}" + logger.info(msg) + error_rate = get_err_ratio(ref, tri) + if abs_atol <= err_atol: + return + if warning or (FLA_CI_ENV and (error_rate < 0.01 or abs_atol <= 0.3)): + if error_rate > ratio: + warnings.warn(msg) + else: + assert error_rate < ratio, msg + + +def tensor_cache( + fn: Callable[..., torch.Tensor] +) -> Callable[..., torch.Tensor]: + """ + A decorator that caches the most recent result of a function with tensor inputs. + + This decorator will store the output of the decorated function for the most recent set of input tensors. + If the function is called again with the same input tensors, it will return the cached result. + + + Args: + fn (Callable[..., torch.Tensor]): + The function to be decorated. It should take tensor inputs and return tensor outputs. + + Returns: + Callable[..., torch.Tensor]: + A wrapped version of the input function with single-entry caching. + """ + last_args: Optional[Tuple] = None + last_kwargs: Optional[Dict] = None + last_result: Any = None + + @functools.wraps(fn) + def wrapper(*args: Any, **kwargs: Any) -> Any: + nonlocal last_args, last_kwargs, last_result + + if last_args is not None and last_kwargs is not None: + if len(args) == len(last_args) and len(kwargs) == len(last_kwargs): + if all(a is b for a, b in zip(args, last_args)) and \ + all(k in last_kwargs and v is last_kwargs[k] for k, v in kwargs.items()): + return last_result + + result = fn(*args, **kwargs) + last_args, last_kwargs, last_result = args, kwargs, result + return result + + return wrapper + + +def input_guard( + fn: Callable[..., torch.Tensor] +) -> Callable[..., torch.Tensor]: + """ + A decorator to make sure all input tensors are contiguous and set the device based on input tensors. + """ + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + contiguous_args = (i if not isinstance(i, torch.Tensor) else i.contiguous() for i in args) + contiguous_kwargs = {k: (v if not isinstance(v, torch.Tensor) else v.contiguous()) for k, v in kwargs.items()} + + tensor = None + for arg in args: + if isinstance(arg, torch.Tensor): + tensor = arg + break + if tensor is None: + for value in kwargs.values(): + if isinstance(value, torch.Tensor): + tensor = value + break + + if tensor is not None: + ctx = custom_device_ctx(tensor.device.index) + else: + ctx = contextlib.nullcontext() + + with ctx: + return fn(*contiguous_args, **contiguous_kwargs) + + return wrapper + + +contiguous = input_guard + + +def require_version(version, hint): + """ + Perform a runtime check of the dependency versions, using the exact same syntax used by pip. + """ + def decorator(fn): + @functools.wraps(fn) + def wrapper(ctx, *args, **kwargs): + from transformers.utils.versions import require_version + require_version(version, hint) + return fn(ctx, + *(i if not isinstance(i, torch.Tensor) else i.contiguous() for i in args), + **{k: (v if not isinstance(v, torch.Tensor) else v.contiguous()) for k, v in kwargs.items()}) + return wrapper + return decorator + + +class Action(Enum): + NONE = "none" + NOTIFY = "notify" + NOTIFY_ALWAYS = "notify_always" + RAISE = "raise" + + +def deprecate_kwarg( + old_name: str, + version: str, + new_name: Optional[str] = None, + warn_if_greater_or_equal_version: bool = False, + raise_if_greater_or_equal_version: bool = False, + raise_if_both_names: bool = False, + additional_message: Optional[str] = None, +): + """ + Decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified. + + This decorator allows you to: + - Notify users when a keyword argument is deprecated. + - Automatically replace deprecated keyword arguments with new ones. + - Raise an error if deprecated arguments are used, depending on the specified conditions. + + By default, the decorator notifies the user about the deprecated argument while the `fla.__version__` < specified `version` + in the decorator. To keep notifications with any version `warn_if_greater_or_equal_version=True` can be set. + + Args: + old_name (`str`): + Name of the deprecated keyword argument. + version (`str`): + The version in which the keyword argument was (or will be) deprecated. + new_name (`Optional[str]`, *optional*): + The new name for the deprecated keyword argument. + If specified, the deprecated keyword argument will be replaced with this new name. + warn_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`): + Whether to show warning if current `fla` version is greater or equal to the deprecated version. + raise_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`): + Whether to raise `ValueError` if current `fla` version is greater or equal to the deprecated version. + raise_if_both_names (`bool`, *optional*, defaults to `False`): + Whether to raise `ValueError` if both deprecated and new keyword arguments are set. + additional_message (`Optional[str]`, *optional*): + An additional message to append to the default deprecation message. + + Raises: + ValueError: + If `raise_if_greater_or_equal_version` is `True` and the current version >= the deprecated one, + or if `raise_if_both_names` is `True` and both old and new keyword arguments are provided. + + Returns: + Callable: + A wrapped function that handles the deprecated keyword arguments according to the specified parameters. + + Example usage with renaming argument: + + ```python + @deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="6.0.0") + def my_function(do_reduce_labels): + print(do_reduce_labels) + + my_function(reduce_labels=True) # Will show a deprecation warning and use do_reduce_labels=True + ``` + + Example usage without renaming argument: + + ```python + @deprecate_kwarg("max_size", version="6.0.0") + def my_function(max_size): + print(max_size) + + my_function(max_size=1333) # Will show a deprecation warning + ``` + + """ + deprecated_version = version.parse(version) + current_version = version.parse(__version__) + is_greater_or_equal_version = current_version >= deprecated_version + + if is_greater_or_equal_version: + version_message = f"and removed starting from version {version}" + else: + version_message = f"and will be removed in version {version}" + + def wrapper(func): + # Required for better warning message + sig = inspect.signature(func) + function_named_args = set(sig.parameters.keys()) + is_instance_method = "self" in function_named_args + is_class_method = "cls" in function_named_args + + @functools.wraps(func) + def wrapped_func(*args, **kwargs): + # Get class + function name (just for better warning message) + func_name = func.__name__ + if is_instance_method: + func_name = f"{args[0].__class__.__name__}.{func_name}" + elif is_class_method: + func_name = f"{args[0].__name__}.{func_name}" + + minimum_action = Action.NONE + message = None + + # deprecated kwarg and its new version are set for function call -> replace it with new name + if old_name in kwargs and new_name in kwargs: + minimum_action = Action.RAISE if raise_if_both_names else Action.NOTIFY_ALWAYS + message = ( + f"Both `{old_name}` and `{new_name}` are set for `{func_name}`. " + f"Using `{new_name}={kwargs[new_name]}` and ignoring deprecated `{old_name}={kwargs[old_name]}`." + ) + kwargs.pop(old_name) + + # only deprecated kwarg is set for function call -> replace it with new name + elif old_name in kwargs and new_name is not None and new_name not in kwargs: + minimum_action = Action.NOTIFY + message = ( + f"`{old_name}` is deprecated {version_message} for `{func_name}`. " + f"Use `{new_name}` instead." + ) + kwargs[new_name] = kwargs.pop(old_name) + + # deprecated kwarg is not set for function call and new name is not specified -> just notify + elif old_name in kwargs: + minimum_action = Action.NOTIFY + message = f"`{old_name}` is deprecated {version_message} for `{func_name}`." + + if message is not None and additional_message is not None: + message = f"{message} {additional_message}" + + # update minimum_action if argument is ALREADY deprecated (current version >= deprecated version) + if is_greater_or_equal_version: + # change to (NOTIFY, NOTIFY_ALWAYS) -> RAISE if specified + # in case we want to raise error for already deprecated arguments + if raise_if_greater_or_equal_version and minimum_action != Action.NONE: + minimum_action = Action.RAISE + + # change to NOTIFY -> NONE if specified (NOTIFY_ALWAYS can't be changed to NONE) + # in case we want to ignore notifications for already deprecated arguments + elif not warn_if_greater_or_equal_version and minimum_action == Action.NOTIFY: + minimum_action = Action.NONE + + # raise error or notify user + if minimum_action == Action.RAISE: + raise ValueError(message) + elif minimum_action in (Action.NOTIFY, Action.NOTIFY_ALWAYS): + # DeprecationWarning is ignored by default, so we use FutureWarning instead + warnings.warn(message, FutureWarning, stacklevel=2) + + return func(*args, **kwargs) + + return wrapped_func + + return wrapper + + +def checkpoint(fn): + def wrapper(*args, **kwargs): + return torch.utils.checkpoint.checkpoint(fn, *args, **kwargs) + return wrapper + + +@lru_cache(maxsize=None) +def check_pytorch_version(version_s: str = '2.4') -> bool: + return version.parse(torch.__version__) >= version.parse(version_s) + + +def _cpu_device_warning(): + warnings.warn(('Triton is not supported on current platform, roll back to CPU.'), stacklevel=1) + + +@lru_cache(maxsize=None) +def get_multiprocessor_count(tensor_idx: int = 0) -> int: + try: + return triton.runtime.driver.active.utils.get_device_properties(tensor_idx)['multiprocessor_count'] + except BaseException: + # Maybe we use a NPU device. + if triton.runtime.driver.active.get_current_target().backend == 'npu': + return triton.runtime.driver.active.utils.get_device_properties(tensor_idx)['num_vectorcore'] + else: + return 1 + + +@lru_cache(maxsize=None) +def get_available_device() -> str: + try: + return triton.runtime.driver.active.get_current_target().backend + except BaseException: + _cpu_device_warning() + return 'cpu' + + +def map_triton_backend_to_torch_device() -> str: + backend = get_available_device() # 'cuda' | 'hip' | 'xpu' | 'cpu' | ... + return {'cuda': 'cuda', 'hip': 'cuda', 'xpu': 'xpu'}.get(backend, backend) + + +# For AMD GPUs, the triton backend is 'hip', while for Nvidia GPUs, the triton backend is 'cuda'. +# However, the torch backend is 'cuda' for both Nvidia and AMD GPUs. +# Therefore, we need to check the triton backend to determine the actual GPU vendor. +device = get_available_device() if get_available_device() != 'hip' else 'cuda' +device_torch_lib = getattr(torch, device) +device_platform = get_available_device() +device_name = map_triton_backend_to_torch_device() + +is_amd = (device_platform == 'hip') +is_intel = (device_platform == 'xpu') +is_nvidia = (device_platform == 'cuda') +is_intel_alchemist = (is_intel and 'Intel(R) Arc(TM) A' in torch.xpu.get_device_name(0)) +is_nvidia_hopper = (is_nvidia and ('NVIDIA H' in torch.cuda.get_device_name(0) or torch.cuda.get_device_capability()[0] >= 9)) +use_cuda_graph = (is_nvidia and os.environ.get('FLA_USE_CUDA_GRAPH', '0') == '1') + +# Nvidia Ampere or newer, haven't check AMD and intel yet. +is_tf32_supported = (is_nvidia and torch.cuda.get_device_capability(0)[0] >= 8) +is_gather_supported = hasattr(triton.language, 'gather') +is_tma_supported = (is_nvidia and torch.cuda.get_device_capability(0)[0] >= 9) \ + and os.environ.get('FLA_NO_USE_TMA', '0') != '1' and \ + (hasattr(triton.language, '_experimental_make_tensor_descriptor') or hasattr(triton.language, 'make_tensor_descriptor')) + +if is_nvidia and not is_tf32_supported: + # Make old card happy, since triton will use tf32 by default. + # This is a workaround for old nvidia card. + os.environ['TRITON_F32_DEFAULT'] = 'ieee' + +if is_tma_supported: + logger.info('TMA is supported, using TMA by default.') + + def alloc_fn(size: int, alignment: int, stream: Optional[int]): + return torch.empty(size, device=torch.device(device_name, device_torch_lib.current_device()), dtype=torch.int8) + + triton.set_allocator(alloc_fn) + + +def get_all_max_shared_mem(): + try: + return [ + triton.runtime.driver.active.utils.get_device_properties(i)['max_shared_mem'] + for i in range(device_torch_lib.device_count()) + ] + except BaseException: + _cpu_device_warning() + return [-1] + + +class Backend(Enum): + ADA = 101376 # RTX 4090 + AMPERE = 166912 # A100 + HOPPER = 232448 # H100 + DEFAULT = 102400 # Default + + @classmethod + def get_shared_memory(cls, arch: str) -> int: + try: + return cls[arch.upper()].value + except KeyError: + return cls.DEFAULT.value + + +@lru_cache(maxsize=None) +def check_shared_mem(arch: str = "none", tensor_idx: int = 0) -> bool: + try: + device_shared_mem_list = get_all_max_shared_mem() + max_shared_memory = device_shared_mem_list[tensor_idx] + return max_shared_memory >= Backend.get_shared_memory(arch) + except Exception: + return False + + +if check_pytorch_version('2.4'): + device = 'cuda' if device == 'cpu' else device + autocast_custom_fwd = functools.partial(torch.amp.custom_fwd, device_type=device) + autocast_custom_bwd = functools.partial(torch.amp.custom_bwd, device_type=device) + + def custom_device_ctx(index: int): + return device_torch_lib.device(index) +else: + assert device == 'cuda', 'Only cuda device is supported for PyTorch version < 2.4.0.' + autocast_custom_fwd = device_torch_lib.amp.custom_fwd + autocast_custom_bwd = device_torch_lib.amp.custom_bwd + + def custom_device_ctx(index: int): + return torch.cuda.device(index)