Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- __init__.py +114 -0
- layers/__init__.py +66 -0
- layers/abc.py +232 -0
- layers/attn.py +174 -0
- layers/based.py +94 -0
- layers/bitattn.py +163 -0
- layers/comba.py +332 -0
- layers/delta_net.py +290 -0
- layers/deltaformer.py +153 -0
- layers/forgetting_attn.py +134 -0
- layers/gated_deltanet.py +319 -0
- layers/gated_deltaproduct.py +291 -0
- layers/gka.py +744 -0
- layers/gka_attn.py +303 -0
- layers/gla.py +300 -0
- layers/gsa.py +240 -0
- layers/hgrn.py +176 -0
- layers/hgrn2.py +212 -0
- layers/lightnet.py +223 -0
- layers/linear_attn.py +165 -0
- layers/log_linear_mamba2.py +650 -0
- layers/mamba.py +335 -0
- layers/mamba2.py +613 -0
- layers/mask_gdn.py +1058 -0
- layers/mesa_net.py +224 -0
- layers/mla.py +226 -0
- layers/mom.py +834 -0
- layers/multiscale_retention.py +305 -0
- layers/nsa.py +138 -0
- layers/path_attn.py +216 -0
- layers/path_test.py +217 -0
- log.md +2 -0
- models/abc/__init__.py +13 -0
- models/abc/configuration_abc.py +107 -0
- models/abc/modeling_abc.py +374 -0
- models/bitnet/__init__.py +13 -0
- models/bitnet/configuration_bitnet.py +83 -0
- models/bitnet/modeling_bitnet.py +397 -0
- models/comba/__init__.py +12 -0
- models/comba/configuration_comba.py +107 -0
- models/comba/modeling_comba.py +381 -0
- models/delta_net/__init__.py +12 -0
- models/delta_net/configuration_delta_net.py +107 -0
- models/delta_net/modeling_delta_net.py +371 -0
- models/deltaformer/__init__.py +12 -0
- models/deltaformer/configuration_deltaformer.py +107 -0
- models/deltaformer/modeling_deltaformer.py +318 -0
- models/forgetting_transformer/__init__.py +16 -0
- models/forgetting_transformer/modeling_forgetting_transformer.py +361 -0
- models/gated_deltanet/configuration_gated_deltanet.py +102 -0
__init__.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from .layers import (
|
| 4 |
+
# ABCAttention,
|
| 5 |
+
# Attention,
|
| 6 |
+
# BasedLinearAttention,
|
| 7 |
+
# BitAttention,
|
| 8 |
+
# Comba,
|
| 9 |
+
# DeltaFormerAttention,
|
| 10 |
+
# DeltaNet,
|
| 11 |
+
# GatedDeltaNet,
|
| 12 |
+
# GatedDeltaProduct,
|
| 13 |
+
# GatedLinearAttention,
|
| 14 |
+
# GatedSlotAttention,
|
| 15 |
+
# HGRN2Attention,
|
| 16 |
+
# HGRNAttention,
|
| 17 |
+
# LightNetAttention,
|
| 18 |
+
# LinearAttention,
|
| 19 |
+
# LogLinearMamba2,
|
| 20 |
+
# MesaNet,
|
| 21 |
+
# MomAttention,
|
| 22 |
+
# MultiheadLatentAttention,
|
| 23 |
+
# MultiScaleRetention,
|
| 24 |
+
# NativeSparseAttention,
|
| 25 |
+
# PaTHAttention,
|
| 26 |
+
# ReBasedLinearAttention,
|
| 27 |
+
# RodimusAttention,
|
| 28 |
+
# RWKV6Attention,
|
| 29 |
+
# RWKV7Attention
|
| 30 |
+
mask_gdn
|
| 31 |
+
)
|
| 32 |
+
from .models import (
|
| 33 |
+
# ABCForCausalLM,
|
| 34 |
+
# ABCModel,
|
| 35 |
+
# BitNetForCausalLM,
|
| 36 |
+
# BitNetModel,
|
| 37 |
+
# CombaForCausalLM,
|
| 38 |
+
# CombaModel,
|
| 39 |
+
# DeltaFormerForCausalLM,
|
| 40 |
+
# DeltaFormerModel,
|
| 41 |
+
# DeltaNetForCausalLM,
|
| 42 |
+
# DeltaNetModel,
|
| 43 |
+
# GatedDeltaNetForCausalLM,
|
| 44 |
+
# GatedDeltaNetModel,
|
| 45 |
+
# GatedDeltaProductForCausalLM,
|
| 46 |
+
# GatedDeltaProductModel,
|
| 47 |
+
# GLAForCausalLM,
|
| 48 |
+
# GLAModel,
|
| 49 |
+
# GSAForCausalLM,
|
| 50 |
+
# GSAModel,
|
| 51 |
+
# HGRN2ForCausalLM,
|
| 52 |
+
# HGRN2Model,
|
| 53 |
+
# HGRNForCausalLM,
|
| 54 |
+
# HGRNModel,
|
| 55 |
+
# LightNetForCausalLM,
|
| 56 |
+
# LightNetModel,
|
| 57 |
+
# LinearAttentionForCausalLM,
|
| 58 |
+
# LinearAttentionModel,
|
| 59 |
+
# LogLinearMamba2ForCausalLM,
|
| 60 |
+
# LogLinearMamba2Model,
|
| 61 |
+
# MesaNetForCausalLM,
|
| 62 |
+
# MesaNetModel,
|
| 63 |
+
# MLAForCausalLM,
|
| 64 |
+
# MLAModel,
|
| 65 |
+
# MomForCausalLM,
|
| 66 |
+
# MomModel,
|
| 67 |
+
# NSAForCausalLM,
|
| 68 |
+
# NSAModel,
|
| 69 |
+
# PaTHAttentionForCausalLM,
|
| 70 |
+
# PaTHAttentionModel,
|
| 71 |
+
# RetNetForCausalLM,
|
| 72 |
+
# RetNetModel,
|
| 73 |
+
mask_gdnForCausalLM,
|
| 74 |
+
mask_gdnModel,
|
| 75 |
+
# RodimusForCausalLM,
|
| 76 |
+
# RodimusModel,
|
| 77 |
+
# RWKV6ForCausalLM,
|
| 78 |
+
# RWKV6Model,
|
| 79 |
+
# RWKV7ForCausalLM,
|
| 80 |
+
# RWKV7Model,
|
| 81 |
+
# TransformerForCausalLM,
|
| 82 |
+
# TransformerModel
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# __all__ = [
|
| 86 |
+
# 'ABCAttention', 'ABCForCausalLM', 'ABCModel',
|
| 87 |
+
# 'Attention', 'TransformerForCausalLM', 'TransformerModel',
|
| 88 |
+
# 'BasedLinearAttention',
|
| 89 |
+
# 'BitAttention', 'BitNetForCausalLM', 'BitNetModel',
|
| 90 |
+
# 'Comba', 'CombaForCausalLM', 'CombaModel',
|
| 91 |
+
# 'DeltaNet', 'DeltaNetForCausalLM', 'DeltaNetModel',
|
| 92 |
+
# 'DeltaFormerAttention', 'DeltaFormerForCausalLM', 'DeltaFormerModel',
|
| 93 |
+
# 'GatedDeltaNet', 'GatedDeltaNetForCausalLM', 'GatedDeltaNetModel',
|
| 94 |
+
# 'GatedDeltaProduct', 'GatedDeltaProductForCausalLM', 'GatedDeltaProductModel',
|
| 95 |
+
# 'GatedLinearAttention', 'GLAForCausalLM', 'GLAModel',
|
| 96 |
+
# 'GatedSlotAttention', 'GSAForCausalLM', 'GSAModel',
|
| 97 |
+
# 'HGRNAttention', 'HGRNForCausalLM', 'HGRNModel',
|
| 98 |
+
# 'HGRN2Attention', 'HGRN2ForCausalLM', 'HGRN2Model',
|
| 99 |
+
# 'LightNetAttention', 'LightNetForCausalLM', 'LightNetModel',
|
| 100 |
+
# 'LinearAttention', 'LinearAttentionForCausalLM', 'LinearAttentionModel',
|
| 101 |
+
# 'LogLinearMamba2', 'LogLinearMamba2ForCausalLM', 'LogLinearMamba2Model',
|
| 102 |
+
# 'MesaNet', 'MesaNetForCausalLM', 'MesaNetModel',
|
| 103 |
+
# 'MomAttention', 'MomForCausalLM', 'MomModel',
|
| 104 |
+
# 'MultiheadLatentAttention', 'MLAForCausalLM', 'MLAModel',
|
| 105 |
+
# 'MultiScaleRetention', 'RetNetForCausalLM', 'RetNetModel',
|
| 106 |
+
# 'NativeSparseAttention', 'NSAForCausalLM', 'NSAModel',
|
| 107 |
+
# 'PaTHAttention', 'PaTHAttentionForCausalLM', 'PaTHAttentionModel',
|
| 108 |
+
# 'ReBasedLinearAttention',
|
| 109 |
+
# 'RodimusAttention', 'RodimusForCausalLM', 'RodimusModel',
|
| 110 |
+
# 'RWKV6Attention', 'RWKV6ForCausalLM', 'RWKV6Model',
|
| 111 |
+
# 'RWKV7Attention', 'RWKV7ForCausalLM', 'RWKV7Model',
|
| 112 |
+
# ]
|
| 113 |
+
|
| 114 |
+
__version__ = '0.3.2'
|
layers/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# from .abc import ABCAttention
|
| 5 |
+
# from .attn import Attention
|
| 6 |
+
# from .based import BasedLinearAttention
|
| 7 |
+
# from .bitattn import BitAttention
|
| 8 |
+
# from .comba import Comba
|
| 9 |
+
# from .delta_net import DeltaNet
|
| 10 |
+
# from .deltaformer import DeltaFormerAttention
|
| 11 |
+
# from .forgetting_attn import ForgettingAttention
|
| 12 |
+
# from .gated_deltanet import GatedDeltaNet
|
| 13 |
+
# from .gated_deltaproduct import GatedDeltaProduct
|
| 14 |
+
# from .gla import GatedLinearAttention
|
| 15 |
+
# from .gsa import GatedSlotAttention
|
| 16 |
+
# from .hgrn import HGRNAttention
|
| 17 |
+
# from .hgrn2 import HGRN2Attention
|
| 18 |
+
# from .lightnet import LightNetAttention
|
| 19 |
+
# from .linear_attn import LinearAttention
|
| 20 |
+
# from .log_linear_mamba2 import LogLinearMamba2
|
| 21 |
+
# from .mamba import Mamba
|
| 22 |
+
# from .mamba2 import Mamba2
|
| 23 |
+
# from .mesa_net import MesaNet
|
| 24 |
+
# from .mla import MultiheadLatentAttention
|
| 25 |
+
# from .mom import MomAttention
|
| 26 |
+
# from .multiscale_retention import MultiScaleRetention
|
| 27 |
+
# from .nsa import NativeSparseAttention
|
| 28 |
+
# from .path_attn import PaTHAttention
|
| 29 |
+
# from .rebased import ReBasedLinearAttention
|
| 30 |
+
# from .rodimus import RodimusAttention, SlidingWindowSharedKeyAttention
|
| 31 |
+
# from .rwkv6 import RWKV6Attention
|
| 32 |
+
# from .rwkv7 import RWKV7Attention
|
| 33 |
+
from .mask_gdn import mask_gdn
|
| 34 |
+
# __all__ = [
|
| 35 |
+
# 'ABCAttention',
|
| 36 |
+
# 'Attention',
|
| 37 |
+
# 'BasedLinearAttention',
|
| 38 |
+
# 'BitAttention',
|
| 39 |
+
# 'Comba',
|
| 40 |
+
# 'DeltaNet',
|
| 41 |
+
# 'ForgettingAttention',
|
| 42 |
+
# 'GatedDeltaNet',
|
| 43 |
+
# 'GatedDeltaProduct',
|
| 44 |
+
# 'GatedLinearAttention',
|
| 45 |
+
# 'GatedSlotAttention',
|
| 46 |
+
# 'HGRNAttention',
|
| 47 |
+
# 'HGRN2Attention',
|
| 48 |
+
# 'LightNetAttention',
|
| 49 |
+
# 'LinearAttention',
|
| 50 |
+
# 'LogLinearMamba2',
|
| 51 |
+
# 'Mamba',
|
| 52 |
+
# 'Mamba2',
|
| 53 |
+
# 'MesaNet',
|
| 54 |
+
# 'MomAttention',
|
| 55 |
+
# 'MultiheadLatentAttention',
|
| 56 |
+
# 'MultiScaleRetention',
|
| 57 |
+
# 'NativeSparseAttention',
|
| 58 |
+
# 'PaTHAttention',
|
| 59 |
+
# 'ReBasedLinearAttention',
|
| 60 |
+
# 'RodimusAttention',
|
| 61 |
+
# 'RWKV6Attention',
|
| 62 |
+
# 'RWKV7Attention',
|
| 63 |
+
# 'SlidingWindowSharedKeyAttention',
|
| 64 |
+
# 'DeltaFormerAttention',
|
| 65 |
+
# 'maskgdn',
|
| 66 |
+
# ]
|
layers/abc.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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right (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
|
| 13 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, RotaryEmbedding, ShortConvolution
|
| 14 |
+
from fla.modules.activations import swiglu, swish
|
| 15 |
+
from fla.ops.abc.chunk import chunk_abc
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from fla.models.utils import Cache
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ABCAttention(nn.Module):
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
hidden_size: int = 1024,
|
| 26 |
+
expand_k: float = 0.5,
|
| 27 |
+
expand_v: float = 1.0,
|
| 28 |
+
num_heads: int = 4,
|
| 29 |
+
use_short_conv: bool = False,
|
| 30 |
+
conv_size: int = 4,
|
| 31 |
+
conv_bias: bool = False,
|
| 32 |
+
num_slots: Optional[int] = None,
|
| 33 |
+
elementwise_affine: Optional[bool] = True,
|
| 34 |
+
norm_eps: float = 1e-5,
|
| 35 |
+
gate_low_rank_dim: int = 16,
|
| 36 |
+
gate_logit_normalizer: int = 16,
|
| 37 |
+
use_rope: bool = True,
|
| 38 |
+
use_input_gate: bool = False,
|
| 39 |
+
use_output_gate: bool = True,
|
| 40 |
+
use_norm: bool = True,
|
| 41 |
+
clamp_min: Optional[float] = -32,
|
| 42 |
+
clamp_max: Optional[float] = 32,
|
| 43 |
+
layer_idx: Optional[int] = None,
|
| 44 |
+
**kwargs
|
| 45 |
+
) -> ABCAttention:
|
| 46 |
+
super().__init__()
|
| 47 |
+
|
| 48 |
+
self.hidden_size = hidden_size
|
| 49 |
+
self.expand_k = expand_k
|
| 50 |
+
self.expand_v = expand_v
|
| 51 |
+
self.num_heads = num_heads
|
| 52 |
+
self.key_dim = int(self.hidden_size * self.expand_k)
|
| 53 |
+
self.value_dim = int(self.hidden_size * self.expand_v)
|
| 54 |
+
self.head_k_dim = self.key_dim // self.num_heads
|
| 55 |
+
self.head_v_dim = self.value_dim // self.num_heads
|
| 56 |
+
|
| 57 |
+
self.use_short_conv = use_short_conv
|
| 58 |
+
self.conv_size = conv_size
|
| 59 |
+
self.conv_bias = conv_bias
|
| 60 |
+
|
| 61 |
+
self.gate_low_rank_dim = gate_low_rank_dim
|
| 62 |
+
self.gate_logit_normalizer = gate_logit_normalizer
|
| 63 |
+
|
| 64 |
+
self.use_rope = use_rope
|
| 65 |
+
self.use_input_gate = use_input_gate
|
| 66 |
+
self.use_output_gate = use_output_gate
|
| 67 |
+
self.use_norm = use_norm
|
| 68 |
+
|
| 69 |
+
if num_slots is None:
|
| 70 |
+
num_slots = self.head_k_dim
|
| 71 |
+
self.num_slots = num_slots
|
| 72 |
+
|
| 73 |
+
self.norm_eps = norm_eps
|
| 74 |
+
|
| 75 |
+
self.clamp_min = clamp_min
|
| 76 |
+
self.clamp_max = clamp_max
|
| 77 |
+
self.layer_idx = layer_idx
|
| 78 |
+
|
| 79 |
+
if layer_idx is None:
|
| 80 |
+
warnings.warn(
|
| 81 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
| 82 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 83 |
+
"when creating this class."
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
| 87 |
+
self.k_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
| 88 |
+
self.v_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False)
|
| 89 |
+
|
| 90 |
+
if use_output_gate:
|
| 91 |
+
self.g_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False)
|
| 92 |
+
self.s_proj = nn.Linear(self.hidden_size, self.num_heads * self.num_slots, bias=False)
|
| 93 |
+
self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
|
| 94 |
+
|
| 95 |
+
if use_short_conv:
|
| 96 |
+
self.conv_size = conv_size
|
| 97 |
+
self.q_conv1d = ShortConvolution(
|
| 98 |
+
hidden_size=self.key_dim,
|
| 99 |
+
kernel_size=conv_size,
|
| 100 |
+
bias=conv_bias,
|
| 101 |
+
activation='silu'
|
| 102 |
+
)
|
| 103 |
+
self.k_conv1d = ShortConvolution(
|
| 104 |
+
hidden_size=self.key_dim,
|
| 105 |
+
kernel_size=conv_size,
|
| 106 |
+
bias=conv_bias,
|
| 107 |
+
activation='silu'
|
| 108 |
+
)
|
| 109 |
+
self.v_conv1d = ShortConvolution(
|
| 110 |
+
hidden_size=self.value_dim,
|
| 111 |
+
kernel_size=conv_size,
|
| 112 |
+
bias=conv_bias,
|
| 113 |
+
activation='silu'
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if self.use_norm:
|
| 117 |
+
if self.use_output_gate:
|
| 118 |
+
self.g_norm = FusedRMSNormGated(
|
| 119 |
+
hidden_size=self.head_v_dim,
|
| 120 |
+
elementwise_affine=elementwise_affine,
|
| 121 |
+
eps=norm_eps
|
| 122 |
+
)
|
| 123 |
+
else:
|
| 124 |
+
self.g_norm = RMSNorm(
|
| 125 |
+
hidden_size=self.head_v_dim,
|
| 126 |
+
elementwise_affine=elementwise_affine,
|
| 127 |
+
eps=norm_eps
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
if self.use_rope:
|
| 131 |
+
self.rotary = RotaryEmbedding(self.head_k_dim)
|
| 132 |
+
|
| 133 |
+
def forward(
|
| 134 |
+
self,
|
| 135 |
+
hidden_states: torch.Tensor,
|
| 136 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 137 |
+
past_key_values: Optional[Cache] = None,
|
| 138 |
+
use_cache: Optional[bool] = False,
|
| 139 |
+
output_attentions: Optional[bool] = False,
|
| 140 |
+
**kwargs
|
| 141 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 142 |
+
if attention_mask is not None:
|
| 143 |
+
assert len(attention_mask.shape) == 2, (
|
| 144 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 145 |
+
"for padding purposes (0 indicating padding). "
|
| 146 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
last_state = None
|
| 150 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 151 |
+
last_state = past_key_values[self.layer_idx]
|
| 152 |
+
|
| 153 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 154 |
+
if cu_seqlens is not None:
|
| 155 |
+
raise NotImplementedError("Training with cu_seqlens is not supported yet for ABCAttention")
|
| 156 |
+
if self.use_short_conv:
|
| 157 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 158 |
+
if last_state is not None:
|
| 159 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 160 |
+
conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
|
| 161 |
+
q, conv_state_q = self.q_conv1d(
|
| 162 |
+
x=self.q_proj(hidden_states),
|
| 163 |
+
mask=conv_mask,
|
| 164 |
+
cache=conv_state_q,
|
| 165 |
+
output_final_state=use_cache,
|
| 166 |
+
cu_seqlens=cu_seqlens
|
| 167 |
+
)
|
| 168 |
+
k, conv_state_k = self.k_conv1d(
|
| 169 |
+
x=self.k_proj(hidden_states),
|
| 170 |
+
mask=conv_mask,
|
| 171 |
+
cache=conv_state_k,
|
| 172 |
+
output_final_state=use_cache,
|
| 173 |
+
cu_seqlens=cu_seqlens
|
| 174 |
+
)
|
| 175 |
+
v, conv_state_v = self.v_conv1d(
|
| 176 |
+
x=self.v_proj(hidden_states),
|
| 177 |
+
mask=conv_mask,
|
| 178 |
+
cache=conv_state_v,
|
| 179 |
+
output_final_state=use_cache,
|
| 180 |
+
cu_seqlens=cu_seqlens
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
q = self.q_proj(hidden_states)
|
| 184 |
+
k = self.k_proj(hidden_states)
|
| 185 |
+
v = self.v_proj(hidden_states)
|
| 186 |
+
|
| 187 |
+
if self.use_input_gate:
|
| 188 |
+
q, k, v = map(lambda x: swish(x), (q, k, v))
|
| 189 |
+
# dealing with left-padding
|
| 190 |
+
if attention_mask is not None:
|
| 191 |
+
v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
|
| 192 |
+
|
| 193 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
|
| 194 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 195 |
+
if self.use_rope:
|
| 196 |
+
seqlen_offset = 0
|
| 197 |
+
if past_key_values is not None:
|
| 198 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 199 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset)
|
| 200 |
+
|
| 201 |
+
s = rearrange(self.s_proj(hidden_states), '... (h m) -> ... h m', m=self.num_slots)
|
| 202 |
+
s = s.clamp_(self.clamp_min, self.clamp_max)
|
| 203 |
+
|
| 204 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 205 |
+
o, recurrent_state = chunk_abc(
|
| 206 |
+
q=q,
|
| 207 |
+
k=k,
|
| 208 |
+
v=v,
|
| 209 |
+
s=s,
|
| 210 |
+
initial_state=recurrent_state,
|
| 211 |
+
output_final_state=use_cache,
|
| 212 |
+
)
|
| 213 |
+
if past_key_values is not None:
|
| 214 |
+
past_key_values.update(
|
| 215 |
+
recurrent_state=recurrent_state,
|
| 216 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 217 |
+
layer_idx=self.layer_idx,
|
| 218 |
+
offset=q.shape[1]
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
if self.use_norm and not self.use_output_gate:
|
| 222 |
+
o = self.g_norm(o)
|
| 223 |
+
elif self.use_output_gate:
|
| 224 |
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 225 |
+
o = self.g_norm(o, g) if self.use_norm else swiglu(g, o)
|
| 226 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 227 |
+
o = self.o_proj(o)
|
| 228 |
+
|
| 229 |
+
return o, None, past_key_values
|
| 230 |
+
|
| 231 |
+
def state_size(self, seq_len: int = 2048):
|
| 232 |
+
return 2 * self.num_slots * self.hidden_size
|
layers/attn.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 15 |
+
from fla.modules import RMSNorm, RotaryEmbedding
|
| 16 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from fla.models.utils import Cache
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 23 |
+
except ImportError:
|
| 24 |
+
warnings.warn(
|
| 25 |
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
| 26 |
+
category=ImportWarning
|
| 27 |
+
)
|
| 28 |
+
flash_attn_func = None
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Attention(nn.Module):
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
hidden_size: int = 2048,
|
| 38 |
+
num_heads: int = 32,
|
| 39 |
+
num_kv_heads: Optional[int] = None,
|
| 40 |
+
qkv_bias: bool = False,
|
| 41 |
+
qk_norm: bool = False,
|
| 42 |
+
window_size: Optional[int] = None,
|
| 43 |
+
rope_theta: Optional[float] = 10000.,
|
| 44 |
+
max_position_embeddings: Optional[int] = None,
|
| 45 |
+
layer_idx: int = None
|
| 46 |
+
):
|
| 47 |
+
super().__init__()
|
| 48 |
+
|
| 49 |
+
self.hidden_size = hidden_size
|
| 50 |
+
self.num_heads = num_heads
|
| 51 |
+
if num_kv_heads is None:
|
| 52 |
+
self.num_kv_heads = self.num_heads
|
| 53 |
+
else:
|
| 54 |
+
self.num_kv_heads = num_kv_heads
|
| 55 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 56 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 57 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 58 |
+
self.qkv_bias = qkv_bias
|
| 59 |
+
self.qk_norm = qk_norm
|
| 60 |
+
|
| 61 |
+
self.window_size = window_size
|
| 62 |
+
self.rope_theta = rope_theta
|
| 63 |
+
self.max_position_embeddings = max_position_embeddings
|
| 64 |
+
self.layer_idx = layer_idx
|
| 65 |
+
|
| 66 |
+
if flash_attn_func is None:
|
| 67 |
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
| 68 |
+
|
| 69 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
| 70 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 71 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 72 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 73 |
+
|
| 74 |
+
if qk_norm:
|
| 75 |
+
self.q_norm = RMSNorm(self.head_dim)
|
| 76 |
+
self.k_norm = RMSNorm(self.head_dim)
|
| 77 |
+
|
| 78 |
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
| 79 |
+
|
| 80 |
+
def forward(
|
| 81 |
+
self,
|
| 82 |
+
hidden_states: torch.Tensor,
|
| 83 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 84 |
+
past_key_values: Optional[Cache] = None,
|
| 85 |
+
output_attentions: bool = False,
|
| 86 |
+
use_cache: bool = False,
|
| 87 |
+
**kwargs,
|
| 88 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 89 |
+
if attention_mask is not None:
|
| 90 |
+
assert len(attention_mask.shape) == 2, (
|
| 91 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 92 |
+
"for padding purposes (0 indicating padding). "
|
| 93 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 97 |
+
|
| 98 |
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 99 |
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 100 |
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 101 |
+
|
| 102 |
+
if self.qk_norm:
|
| 103 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 104 |
+
|
| 105 |
+
# equivalent to cu_seqlens in `flash_attn`
|
| 106 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 107 |
+
|
| 108 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 109 |
+
if past_key_values is not None:
|
| 110 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 111 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 112 |
+
|
| 113 |
+
if attention_mask is not None:
|
| 114 |
+
# to deliminate the offsets of padding tokens
|
| 115 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 116 |
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
| 117 |
+
|
| 118 |
+
if self.max_position_embeddings is not None:
|
| 119 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 120 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 121 |
+
|
| 122 |
+
if past_key_values is not None:
|
| 123 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 124 |
+
k_cached, v_cached = past_key_values.update(
|
| 125 |
+
attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)),
|
| 126 |
+
layer_idx=self.layer_idx,
|
| 127 |
+
offset=q_len,
|
| 128 |
+
cache_kwargs=dict(window_size=self.window_size)
|
| 129 |
+
)['attn_state']
|
| 130 |
+
if cache_has_content:
|
| 131 |
+
k, v = k_cached, v_cached
|
| 132 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 133 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 134 |
+
|
| 135 |
+
# Contains at least one padding token in the sequence
|
| 136 |
+
if attention_mask is not None:
|
| 137 |
+
if q.shape[1] == 1 and self.window_size is not None:
|
| 138 |
+
attention_mask = attention_mask[:, -self.window_size:]
|
| 139 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len)
|
| 140 |
+
cu_seqlens_q, cu_seqlens_k = cu_seqlens
|
| 141 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 142 |
+
o = flash_attn_varlen_func(
|
| 143 |
+
q, k, v,
|
| 144 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 145 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 146 |
+
max_seqlen_q=max_seqlen_q,
|
| 147 |
+
max_seqlen_k=max_seqlen_k,
|
| 148 |
+
causal=True,
|
| 149 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 150 |
+
)
|
| 151 |
+
o = pad_input(o, indices_q, batch_size, q_len)
|
| 152 |
+
elif cu_seqlens is not None:
|
| 153 |
+
o = flash_attn_varlen_func(
|
| 154 |
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
| 155 |
+
cu_seqlens_q=cu_seqlens,
|
| 156 |
+
cu_seqlens_k=cu_seqlens,
|
| 157 |
+
max_seqlen_q=max_seqlen,
|
| 158 |
+
max_seqlen_k=max_seqlen,
|
| 159 |
+
causal=True,
|
| 160 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 161 |
+
).unsqueeze(0)
|
| 162 |
+
else:
|
| 163 |
+
o = flash_attn_func(
|
| 164 |
+
q, k, v,
|
| 165 |
+
causal=True,
|
| 166 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 167 |
+
)
|
| 168 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 169 |
+
o = self.o_proj(o)
|
| 170 |
+
|
| 171 |
+
if not output_attentions:
|
| 172 |
+
attentions = None
|
| 173 |
+
|
| 174 |
+
return o, attentions, past_key_values
|
layers/based.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
Linear attention in Based.
|
| 6 |
+
https://github.com/HazyResearch/zoology/blob/main/zoology/mixers/based.py
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
|
| 13 |
+
from fla.modules.feature_map import TaylorFeatureMap
|
| 14 |
+
from fla.ops.based import parallel_based
|
| 15 |
+
from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class BasedLinearAttention(nn.Module):
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
hidden_size: int,
|
| 23 |
+
feature_dim: int = 16,
|
| 24 |
+
num_key_value_heads: int = 12,
|
| 25 |
+
num_heads: int = 12,
|
| 26 |
+
feature_name: str = "taylor_exp",
|
| 27 |
+
eps: float = 1e-12,
|
| 28 |
+
causal: bool = True,
|
| 29 |
+
mode: str = "parallel",
|
| 30 |
+
):
|
| 31 |
+
super().__init__()
|
| 32 |
+
|
| 33 |
+
self.hidden_size = hidden_size
|
| 34 |
+
self.mode = mode
|
| 35 |
+
self.feature_name = feature_name
|
| 36 |
+
self.feature_dim = feature_dim
|
| 37 |
+
self.num_key_value_heads = num_key_value_heads
|
| 38 |
+
self.num_heads = num_heads
|
| 39 |
+
self.head_dim = self.hidden_size // self.num_key_value_heads
|
| 40 |
+
assert self.hidden_size % self.head_dim == 0
|
| 41 |
+
self.causal = causal
|
| 42 |
+
|
| 43 |
+
self.q_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
|
| 44 |
+
self.k_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
|
| 45 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 46 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 47 |
+
self.dropout = nn.Identity()
|
| 48 |
+
self.feature_map = TaylorFeatureMap(feature_dim)
|
| 49 |
+
self.eps = eps
|
| 50 |
+
|
| 51 |
+
def forward(self, hidden_states: torch.Tensor, **kwargs):
|
| 52 |
+
mode = self.mode
|
| 53 |
+
q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
|
| 54 |
+
q, k, v = map(lambda x: rearrange(x, "... (h d) -> ... h d", d=self.head_dim), [q, k, v])
|
| 55 |
+
if mode == "fused_chunk":
|
| 56 |
+
q, k = self.feature_map(q), self.feature_map(k)
|
| 57 |
+
o, _ = fused_chunk_linear_attn(q, k, v, normalize=True, scale=1)
|
| 58 |
+
elif mode == 'chunk':
|
| 59 |
+
q, k = self.feature_map(q), self.feature_map(k)
|
| 60 |
+
o, _ = chunk_linear_attn(q, k, v, normalize=True, scale=1)
|
| 61 |
+
elif mode == 'parallel':
|
| 62 |
+
assert q.shape[-1] <= 128
|
| 63 |
+
o = parallel_based(q, k, v, scale=1, use_norm=True)
|
| 64 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 65 |
+
o = self.o_proj(o)
|
| 66 |
+
o = self.dropout(o)
|
| 67 |
+
return o
|
| 68 |
+
|
| 69 |
+
def forward_reference(self, hidden_states: torch.Tensor, **kwargs):
|
| 70 |
+
"""
|
| 71 |
+
x (torch.Tensor): tensor of shape (b, d, t)
|
| 72 |
+
y (torch.Tensor): tensor of shape (b, d, t)
|
| 73 |
+
"""
|
| 74 |
+
# hidden_states = hidden_states.transpose(1, 2)
|
| 75 |
+
b, t, _ = hidden_states.size()
|
| 76 |
+
q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
|
| 77 |
+
|
| 78 |
+
q = q.view(b, t, self.num_heads, self.feature_dim).transpose(1, 2)
|
| 79 |
+
k = k.view(b, t, self.num_key_value_heads, self.feature_dim).transpose(1, 2)
|
| 80 |
+
v = v.view(b, t, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 81 |
+
|
| 82 |
+
# Linear attention
|
| 83 |
+
q, k = self.feature_map(q), self.feature_map(k)
|
| 84 |
+
q, k, v = q.unsqueeze(-2), k.unsqueeze(-2), v.unsqueeze(-1)
|
| 85 |
+
|
| 86 |
+
# Compute attention
|
| 87 |
+
if self.causal:
|
| 88 |
+
y = ((q * (k * v).cumsum(2)).sum(-1) / ((q * k.cumsum(2)).sum(-1) + self.eps))
|
| 89 |
+
else:
|
| 90 |
+
y = ((q * (k * v).sum(2, True)).sum(-1) / ((q * k.sum(2, True)).sum(-1) + self.eps))
|
| 91 |
+
y = rearrange(y, 'b h t d -> b t (h d)')
|
| 92 |
+
y = self.o_proj(y.to(hidden_states.dtype))
|
| 93 |
+
y = self.dropout(y)
|
| 94 |
+
return y.to(hidden_states.dtype)
|
layers/bitattn.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 15 |
+
from fla.modules import RotaryEmbedding
|
| 16 |
+
from fla.modules.fused_bitlinear import FusedBitLinear
|
| 17 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from fla.models.utils import Cache
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 24 |
+
except ImportError:
|
| 25 |
+
warnings.warn(
|
| 26 |
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
| 27 |
+
category=ImportWarning
|
| 28 |
+
)
|
| 29 |
+
flash_attn_func = None
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class BitAttention(nn.Module):
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
hidden_size: int = 2048,
|
| 39 |
+
num_heads: int = 32,
|
| 40 |
+
num_kv_heads: Optional[int] = None,
|
| 41 |
+
window_size: Optional[int] = None,
|
| 42 |
+
rope_theta: Optional[float] = 10000.,
|
| 43 |
+
max_position_embeddings: Optional[int] = None,
|
| 44 |
+
norm_eps: float = 1e-5,
|
| 45 |
+
layer_idx: int = None
|
| 46 |
+
):
|
| 47 |
+
super().__init__()
|
| 48 |
+
|
| 49 |
+
self.num_heads = num_heads
|
| 50 |
+
if num_kv_heads is None:
|
| 51 |
+
self.num_kv_heads = self.num_heads
|
| 52 |
+
else:
|
| 53 |
+
self.num_kv_heads = num_kv_heads
|
| 54 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 55 |
+
self.hidden_size = hidden_size
|
| 56 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 57 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 58 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 59 |
+
self.window_size = window_size
|
| 60 |
+
self.rope_theta = rope_theta
|
| 61 |
+
self.max_position_embeddings = max_position_embeddings
|
| 62 |
+
self.layer_idx = layer_idx
|
| 63 |
+
|
| 64 |
+
self.q_proj = FusedBitLinear(self.hidden_size, self.hidden_size, bias=False)
|
| 65 |
+
self.k_proj = FusedBitLinear(self.hidden_size, self.kv_dim, bias=False)
|
| 66 |
+
self.v_proj = FusedBitLinear(self.hidden_size, self.kv_dim, bias=False)
|
| 67 |
+
self.o_proj = FusedBitLinear(self.hidden_size, self.hidden_size, bias=False)
|
| 68 |
+
|
| 69 |
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
| 70 |
+
|
| 71 |
+
def forward(
|
| 72 |
+
self,
|
| 73 |
+
hidden_states: torch.Tensor,
|
| 74 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 75 |
+
past_key_values: Optional[Cache] = None,
|
| 76 |
+
output_attentions: bool = False,
|
| 77 |
+
use_cache: bool = False,
|
| 78 |
+
**kwargs,
|
| 79 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 80 |
+
if attention_mask is not None:
|
| 81 |
+
assert len(attention_mask.shape) == 2, (
|
| 82 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 83 |
+
"for padding purposes (0 indicating padding). "
|
| 84 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 88 |
+
|
| 89 |
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 90 |
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 91 |
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 92 |
+
|
| 93 |
+
# equivalent to cu_seqlens in `flash_attn`
|
| 94 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 95 |
+
|
| 96 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 97 |
+
if past_key_values is not None:
|
| 98 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 99 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 100 |
+
|
| 101 |
+
if attention_mask is not None:
|
| 102 |
+
# to deliminate the offsets of padding tokens
|
| 103 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 104 |
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
| 105 |
+
|
| 106 |
+
if self.max_position_embeddings is not None:
|
| 107 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 108 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 109 |
+
|
| 110 |
+
if past_key_values is not None:
|
| 111 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 112 |
+
k_cached, v_cached = past_key_values.update(
|
| 113 |
+
attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)),
|
| 114 |
+
layer_idx=self.layer_idx,
|
| 115 |
+
offset=q_len,
|
| 116 |
+
cache_kwargs=dict(window_size=self.window_size)
|
| 117 |
+
)['attn_state']
|
| 118 |
+
if cache_has_content:
|
| 119 |
+
k, v = k_cached, v_cached
|
| 120 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 121 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 122 |
+
|
| 123 |
+
if flash_attn_func is None:
|
| 124 |
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
| 125 |
+
|
| 126 |
+
# Contains at least one padding token in the sequence
|
| 127 |
+
if attention_mask is not None:
|
| 128 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len)
|
| 129 |
+
cu_seqlens_q, cu_seqlens_k = cu_seqlens
|
| 130 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 131 |
+
o = flash_attn_varlen_func(
|
| 132 |
+
q, k, v,
|
| 133 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 134 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 135 |
+
max_seqlen_q=max_seqlen_q,
|
| 136 |
+
max_seqlen_k=max_seqlen_k,
|
| 137 |
+
causal=True,
|
| 138 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 139 |
+
)
|
| 140 |
+
o = pad_input(o, indices_q, batch_size, q_len)
|
| 141 |
+
elif cu_seqlens is not None:
|
| 142 |
+
o = flash_attn_varlen_func(
|
| 143 |
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
| 144 |
+
cu_seqlens_q=cu_seqlens,
|
| 145 |
+
cu_seqlens_k=cu_seqlens,
|
| 146 |
+
max_seqlen_q=max_seqlen,
|
| 147 |
+
max_seqlen_k=max_seqlen,
|
| 148 |
+
causal=True,
|
| 149 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 150 |
+
).unsqueeze(0)
|
| 151 |
+
else:
|
| 152 |
+
o = flash_attn_func(
|
| 153 |
+
q, k, v,
|
| 154 |
+
causal=True,
|
| 155 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 156 |
+
)
|
| 157 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 158 |
+
o = self.o_proj(o)
|
| 159 |
+
|
| 160 |
+
if not output_attentions:
|
| 161 |
+
attentions = None
|
| 162 |
+
|
| 163 |
+
return o, attentions, past_key_values
|
layers/comba.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 7 |
+
import warnings
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from einops import rearrange, repeat
|
| 13 |
+
from torch.nn import functional as F
|
| 14 |
+
|
| 15 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 16 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 17 |
+
from fla.ops.comba import chunk_comba, fused_recurrent_comba
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from transformers.processing_utils import Unpack
|
| 21 |
+
|
| 22 |
+
from fla.models.utils import Cache
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Comba(nn.Module):
|
| 26 |
+
"""
|
| 27 |
+
The layer implementaion for [Comba: Improving Bilinear RNNs with Closed-loop Control](https://arxiv.org/abs/2506.02475).
|
| 28 |
+
|
| 29 |
+
Similar to Mamba2 and Gated-DeltaNet, each layer contains around 6*hidden_size*hidden_size parameters.
|
| 30 |
+
|
| 31 |
+
Parameter alloation when use_output_gate=True:
|
| 32 |
+
- 0.75 * hidden_size * hidden_size for the q_proj and k_proj each
|
| 33 |
+
- 1.5 * hidden_size * hidden_size for the v_proj, g_proj and o_proj each
|
| 34 |
+
- Others are ignorably small.
|
| 35 |
+
- In total = 0.75 * 2 + 1.5 * 3 = 6 * hidden_size * hidden_size
|
| 36 |
+
NOTE: num_heads * head_dim = 0.75 * hidden_size, please make sure to set the correct num_heads and head_dim.
|
| 37 |
+
|
| 38 |
+
Parameter allocation when use_output_gate=False:
|
| 39 |
+
- 1 * hidden_size * hidden_size for the q_proj and k_proj each
|
| 40 |
+
- 2 * hidden_size * hidden_size for the v_proj and o_proj each
|
| 41 |
+
- Others are ignorably small.
|
| 42 |
+
- In total = 1 * 2 + 2 * 2 = 6 * hidden_size * hidden_size
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
hidden_size (int, Optional):
|
| 46 |
+
The hidden size of the input. Default: 2048.
|
| 47 |
+
expand_v (float, Optional):
|
| 48 |
+
The expansion ratio for the value dim. Default: 2.0.
|
| 49 |
+
head_dim (int, Optional):
|
| 50 |
+
The dimension of each head. Default: 256.
|
| 51 |
+
num_heads (int, Optional):
|
| 52 |
+
The number of heads. Default: 4.
|
| 53 |
+
num_v_heads (int, Optional):
|
| 54 |
+
The number of heads for the value projection, equal to `num_heads` if `None`.
|
| 55 |
+
GVA is applied if `num_v_heads` > `num_heads`. Default: `None`.
|
| 56 |
+
mode (str, Optional):
|
| 57 |
+
Which Gated DeltaNet kernel to use.
|
| 58 |
+
Currently available: `chunk` and `fused_recurrent`.
|
| 59 |
+
Default: `chunk`.
|
| 60 |
+
use_beta (bool, Optional):
|
| 61 |
+
Whether to use beta. Default: `True`.
|
| 62 |
+
use_output_gate (bool, Optional):
|
| 63 |
+
Whether to use output gate. Default: `True`.
|
| 64 |
+
use_output_correction (bool, Optional):
|
| 65 |
+
Whether to use <q-dk>. Default: `True`.
|
| 66 |
+
use_short_conv (bool, Optional):
|
| 67 |
+
Whether to use short convolutions. Default: `True`.
|
| 68 |
+
conv_size (int, Optional):
|
| 69 |
+
The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
|
| 70 |
+
conv_bias (bool, Optional):
|
| 71 |
+
Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
|
| 72 |
+
layer_idx (int, Optional):
|
| 73 |
+
The index of the layer. Default: None.
|
| 74 |
+
norm_eps (float, Optional):
|
| 75 |
+
The epsilon value for the normalization layer. Default: 1e-5.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
hidden_size: int = 2048,
|
| 81 |
+
expand_v: float = 2,
|
| 82 |
+
head_dim: int = 256,
|
| 83 |
+
num_heads: int = 6,
|
| 84 |
+
num_v_heads: int = None,
|
| 85 |
+
mode: str = 'chunk',
|
| 86 |
+
use_short_conv: bool = True,
|
| 87 |
+
use_output_gate: bool = True,
|
| 88 |
+
use_output_correction: bool = True,
|
| 89 |
+
use_inner_decay: bool = True,
|
| 90 |
+
correction_factor: float = 1.,
|
| 91 |
+
conv_size: int = 4,
|
| 92 |
+
conv_bias: bool = False,
|
| 93 |
+
layer_idx: int = None,
|
| 94 |
+
norm_eps: float = 1e-5,
|
| 95 |
+
**kwargs
|
| 96 |
+
) -> Comba:
|
| 97 |
+
super().__init__()
|
| 98 |
+
|
| 99 |
+
self.mode = mode
|
| 100 |
+
|
| 101 |
+
self.hidden_size = hidden_size
|
| 102 |
+
self.expand_v = expand_v
|
| 103 |
+
|
| 104 |
+
self.use_short_conv = use_short_conv
|
| 105 |
+
self.use_output_gate = use_output_gate
|
| 106 |
+
self.use_output_correction = use_output_correction
|
| 107 |
+
self.use_inner_decay = use_inner_decay
|
| 108 |
+
self.conv_size = conv_size
|
| 109 |
+
self.conv_bias = conv_bias
|
| 110 |
+
|
| 111 |
+
self.head_dim = head_dim
|
| 112 |
+
self.num_heads = num_heads
|
| 113 |
+
self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
|
| 114 |
+
|
| 115 |
+
self.head_k_dim = head_dim
|
| 116 |
+
self.head_v_dim = int(self.head_dim * self.expand_v)
|
| 117 |
+
self.key_dim = int(self.num_heads * self.head_k_dim)
|
| 118 |
+
self.value_dim = int(self.num_v_heads * self.head_v_dim)
|
| 119 |
+
self.layer_idx = layer_idx
|
| 120 |
+
|
| 121 |
+
# Consistency check: Ensure expand_v produces integer values
|
| 122 |
+
if not math.isclose(self.num_v_heads * self.head_dim * expand_v, self.value_dim, rel_tol=1e-5):
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"expand_v={expand_v} does not produce an integer value when multiplied by key_dim={self.key_dim}. "
|
| 125 |
+
f"Resulting value_dim would be {self.num_v_heads * self.head_dim * expand_v}, which is invalid for nn.Linear."
|
| 126 |
+
)
|
| 127 |
+
if self.num_v_heads > self.num_heads and self.num_v_heads % self.num_heads != 0:
|
| 128 |
+
raise ValueError(
|
| 129 |
+
f"num_v_heads={self.num_v_heads} must be divisible by num_heads={self.num_heads}."
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
if not math.isclose(head_dim * expand_v, self.head_v_dim, rel_tol=1e-5):
|
| 133 |
+
raise ValueError(
|
| 134 |
+
f"expand_v={expand_v} does not produce an integer value when multiplied by head_dim={head_dim}. "
|
| 135 |
+
f"Resulting head_v_dim would be {head_dim * expand_v}, which is invalid for FusedRMSNormGated."
|
| 136 |
+
)
|
| 137 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 138 |
+
|
| 139 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 140 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 141 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 142 |
+
self.a_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False)
|
| 143 |
+
self.b_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False)
|
| 144 |
+
|
| 145 |
+
if use_inner_decay:
|
| 146 |
+
self.decay = nn.Parameter(torch.ones(self.num_heads))
|
| 147 |
+
|
| 148 |
+
if use_output_correction:
|
| 149 |
+
warnings.warn(
|
| 150 |
+
"The correction_factor is set to 1 by default similar to Mamba2. "
|
| 151 |
+
"However, we find that sometimes correction_factor = 0.02 works better for small-scale models. "
|
| 152 |
+
"In practice, we recommend trying both settings. "
|
| 153 |
+
)
|
| 154 |
+
self.D = nn.Parameter(torch.ones(self.num_heads) * correction_factor)
|
| 155 |
+
self.D._no_weight_decay = True
|
| 156 |
+
|
| 157 |
+
A = torch.empty(self.num_v_heads, dtype=torch.float32).uniform_(0, 16)
|
| 158 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 159 |
+
self.A_log._no_weight_decay = True
|
| 160 |
+
# hard coded for now
|
| 161 |
+
dt_min = 0.001
|
| 162 |
+
dt_max = 0.1
|
| 163 |
+
dt_init_floor = 1e-4
|
| 164 |
+
dt = torch.exp(
|
| 165 |
+
torch.rand(self.num_v_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 166 |
+
+ math.log(dt_min)
|
| 167 |
+
)
|
| 168 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 169 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 170 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 171 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 172 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 173 |
+
# name.endswith("bias") in param_grouping.py
|
| 174 |
+
self.dt_bias._no_weight_decay = True
|
| 175 |
+
|
| 176 |
+
if use_short_conv:
|
| 177 |
+
self.conv_size = conv_size
|
| 178 |
+
self.q_conv1d = ShortConvolution(
|
| 179 |
+
hidden_size=self.key_dim,
|
| 180 |
+
kernel_size=conv_size,
|
| 181 |
+
bias=conv_bias,
|
| 182 |
+
activation='silu'
|
| 183 |
+
)
|
| 184 |
+
self.k_conv1d = ShortConvolution(
|
| 185 |
+
hidden_size=self.key_dim,
|
| 186 |
+
kernel_size=conv_size,
|
| 187 |
+
bias=conv_bias,
|
| 188 |
+
activation='silu'
|
| 189 |
+
)
|
| 190 |
+
self.v_conv1d = ShortConvolution(
|
| 191 |
+
hidden_size=self.value_dim,
|
| 192 |
+
kernel_size=conv_size,
|
| 193 |
+
bias=conv_bias,
|
| 194 |
+
activation='silu'
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
warnings.warn(
|
| 198 |
+
"ShortConvolution is crucial to the performance. "
|
| 199 |
+
"Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing."
|
| 200 |
+
)
|
| 201 |
+
if use_output_gate:
|
| 202 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 203 |
+
self.o_norm = FusedRMSNormGated(self.head_v_dim, activation='sigmoid', eps=norm_eps)
|
| 204 |
+
else:
|
| 205 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 206 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 207 |
+
|
| 208 |
+
def forward(
|
| 209 |
+
self,
|
| 210 |
+
hidden_states: torch.Tensor,
|
| 211 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 212 |
+
past_key_values: Optional[Cache] = None,
|
| 213 |
+
use_cache: Optional[bool] = False,
|
| 214 |
+
output_attentions: Optional[bool] = False,
|
| 215 |
+
**kwargs: Unpack[Dict]
|
| 216 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 217 |
+
if attention_mask is not None:
|
| 218 |
+
assert len(attention_mask.shape) == 2, (
|
| 219 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 220 |
+
"for padding purposes (0 indicating padding). "
|
| 221 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 225 |
+
# change to inference mode.
|
| 226 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 227 |
+
if self.training:
|
| 228 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 229 |
+
|
| 230 |
+
last_state = None
|
| 231 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 232 |
+
last_state = past_key_values[self.layer_idx]
|
| 233 |
+
|
| 234 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 235 |
+
if attention_mask is not None:
|
| 236 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 237 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 238 |
+
|
| 239 |
+
if self.use_short_conv:
|
| 240 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 241 |
+
if last_state is not None:
|
| 242 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 243 |
+
q, conv_state_q = self.q_conv1d(
|
| 244 |
+
x=self.q_proj(hidden_states),
|
| 245 |
+
cache=conv_state_q,
|
| 246 |
+
output_final_state=use_cache,
|
| 247 |
+
cu_seqlens=cu_seqlens
|
| 248 |
+
)
|
| 249 |
+
k, conv_state_k = self.k_conv1d(
|
| 250 |
+
x=self.k_proj(hidden_states),
|
| 251 |
+
cache=conv_state_k,
|
| 252 |
+
output_final_state=use_cache,
|
| 253 |
+
cu_seqlens=cu_seqlens
|
| 254 |
+
)
|
| 255 |
+
v, conv_state_v = self.v_conv1d(
|
| 256 |
+
x=self.v_proj(hidden_states),
|
| 257 |
+
cache=conv_state_v,
|
| 258 |
+
output_final_state=use_cache,
|
| 259 |
+
cu_seqlens=cu_seqlens
|
| 260 |
+
)
|
| 261 |
+
else:
|
| 262 |
+
q = F.silu(self.q_proj(hidden_states))
|
| 263 |
+
k = F.silu(self.k_proj(hidden_states))
|
| 264 |
+
v = F.silu(self.v_proj(hidden_states))
|
| 265 |
+
|
| 266 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
|
| 267 |
+
|
| 268 |
+
if self.use_inner_decay:
|
| 269 |
+
p = k * self.decay[None, None, :, None].sigmoid()
|
| 270 |
+
else:
|
| 271 |
+
p = k
|
| 272 |
+
|
| 273 |
+
if self.use_output_correction:
|
| 274 |
+
q = q - self.D[None, None, :, None] * p
|
| 275 |
+
|
| 276 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 277 |
+
|
| 278 |
+
if self.num_v_heads > self.num_heads:
|
| 279 |
+
q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k))
|
| 280 |
+
|
| 281 |
+
beta = self.b_proj(hidden_states).sigmoid()
|
| 282 |
+
g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 283 |
+
|
| 284 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 285 |
+
if mode == 'chunk':
|
| 286 |
+
o, recurrent_state = chunk_comba(
|
| 287 |
+
q=q,
|
| 288 |
+
k=k,
|
| 289 |
+
v=v,
|
| 290 |
+
p=p,
|
| 291 |
+
g=g,
|
| 292 |
+
beta=beta,
|
| 293 |
+
initial_state=recurrent_state,
|
| 294 |
+
output_final_state=use_cache,
|
| 295 |
+
cu_seqlens=cu_seqlens,
|
| 296 |
+
use_qk_l2norm_in_kernel=True
|
| 297 |
+
)
|
| 298 |
+
elif mode == 'fused_recurrent':
|
| 299 |
+
o, recurrent_state = fused_recurrent_comba(
|
| 300 |
+
q=q,
|
| 301 |
+
k=k,
|
| 302 |
+
v=v,
|
| 303 |
+
p=p,
|
| 304 |
+
g=g,
|
| 305 |
+
beta=beta,
|
| 306 |
+
initial_state=recurrent_state,
|
| 307 |
+
output_final_state=use_cache,
|
| 308 |
+
cu_seqlens=cu_seqlens,
|
| 309 |
+
use_qk_l2norm_in_kernel=True
|
| 310 |
+
)
|
| 311 |
+
else:
|
| 312 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 313 |
+
|
| 314 |
+
if past_key_values is not None:
|
| 315 |
+
past_key_values.update(
|
| 316 |
+
recurrent_state=recurrent_state,
|
| 317 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 318 |
+
layer_idx=self.layer_idx,
|
| 319 |
+
offset=q_len
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
if self.use_output_gate:
|
| 323 |
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 324 |
+
o = self.o_norm(o, g)
|
| 325 |
+
else:
|
| 326 |
+
o = self.o_norm(o)
|
| 327 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 328 |
+
o = self.o_proj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| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 15 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 16 |
+
from fla.ops.delta_rule import chunk_delta_rule, fused_recurrent_delta_rule
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from transformers.processing_utils import Unpack
|
| 20 |
+
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def elu_p1(x):
|
| 25 |
+
return (F.elu(x, 1., False) + 1.).to(x)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def sum_norm(x):
|
| 29 |
+
return (x / x.sum(-1, keepdim=True)).to(x)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class DeltaNet(nn.Module):
|
| 33 |
+
r"""
|
| 34 |
+
The layer implementaion for [Parallelizing Linear Transformers with the Delta Rule over Sequence Length](https://arxiv.org/abs/2406.06484). # noqa:
|
| 35 |
+
DeltaNet was originally proposed in [Linear Transformers Are Secretly Fast Weight Programmers](https://arxiv.org/abs/2102.11174). # noqa
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
mode (str, Optional):
|
| 39 |
+
Which DeltaNet kernel to use.
|
| 40 |
+
Currently available: `chunk`, `fused_recurrent`, and `fused_chunk`.
|
| 41 |
+
Default: `chunk`.
|
| 42 |
+
hidden_size (int, Optional):
|
| 43 |
+
The hidden size of the input. Default: 1024.
|
| 44 |
+
expand_k (float, Optional):
|
| 45 |
+
The expansion ratio for the key dim. Default: 1.0.
|
| 46 |
+
expand_v (float, Optional):
|
| 47 |
+
The expansion ratio for the value dim. Default: 1.0.
|
| 48 |
+
num_heads (int, Optional):
|
| 49 |
+
The number of heads. Default: 4.
|
| 50 |
+
use_beta (bool, Optional):
|
| 51 |
+
Whether to use beta. Default: `True`.
|
| 52 |
+
use_gate (bool, Optional):
|
| 53 |
+
Whether to use output gate. Default: `False`.
|
| 54 |
+
use_short_conv (bool, Optional):
|
| 55 |
+
Whether to use short convolutions. Default: `True`.
|
| 56 |
+
conv_size (int, Optional):
|
| 57 |
+
The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
|
| 58 |
+
conv_bias (bool, Optional):
|
| 59 |
+
Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
|
| 60 |
+
allow_neg_eigval (bool, Optional):
|
| 61 |
+
Allow negative eigenvalues. Default: `False`. If set to `True`, the beta will be multiplied by 2.
|
| 62 |
+
See reference: [Unlocking State-Tracking in Linear RNNs Through Negative Eigenvalues](https://arxiv.org/abs/2411.12537)
|
| 63 |
+
layer_idx (int, Optional):
|
| 64 |
+
The index of the layer. Default: None.
|
| 65 |
+
norm_eps (float, Optional):
|
| 66 |
+
The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5.
|
| 67 |
+
qk_activation (str, Optional):
|
| 68 |
+
The activation function for the query and key. Default: `silu`.
|
| 69 |
+
qk_norm (str, Optional):
|
| 70 |
+
The normalization method for the query and key. Default: `l2`.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
mode: str = 'chunk',
|
| 76 |
+
d_model: int = None,
|
| 77 |
+
hidden_size: int = 1024,
|
| 78 |
+
expand_k: float = 1.0,
|
| 79 |
+
expand_v: float = 1.0,
|
| 80 |
+
num_heads: int = 4,
|
| 81 |
+
use_beta: bool = True,
|
| 82 |
+
use_gate: bool = False,
|
| 83 |
+
use_short_conv: bool = True,
|
| 84 |
+
conv_size: int = 4,
|
| 85 |
+
conv_bias: bool = False,
|
| 86 |
+
allow_neg_eigval: bool = False,
|
| 87 |
+
layer_idx: int = None,
|
| 88 |
+
qk_activation: str = 'silu',
|
| 89 |
+
qk_norm: str = 'l2',
|
| 90 |
+
norm_eps: float = 1e-5,
|
| 91 |
+
**kwargs
|
| 92 |
+
) -> DeltaNet:
|
| 93 |
+
super().__init__()
|
| 94 |
+
|
| 95 |
+
self.mode = mode
|
| 96 |
+
self.qk_activation = qk_activation
|
| 97 |
+
self.qk_norm = qk_norm
|
| 98 |
+
|
| 99 |
+
assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 100 |
+
assert self.qk_norm in ['l2', 'sum']
|
| 101 |
+
|
| 102 |
+
if d_model is not None:
|
| 103 |
+
hidden_size = d_model
|
| 104 |
+
self.hidden_size = hidden_size
|
| 105 |
+
self.expand_k = expand_k
|
| 106 |
+
self.expand_v = expand_v
|
| 107 |
+
self.num_heads = num_heads
|
| 108 |
+
self.use_gate = use_gate
|
| 109 |
+
self.use_short_conv = use_short_conv
|
| 110 |
+
self.conv_size = conv_size
|
| 111 |
+
self.conv_bias = conv_bias
|
| 112 |
+
self.allow_neg_eigval = allow_neg_eigval
|
| 113 |
+
|
| 114 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 115 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 116 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 117 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 118 |
+
self.layer_idx = layer_idx
|
| 119 |
+
|
| 120 |
+
if mode == 'fused_chunk':
|
| 121 |
+
raise NotImplementedError("fused_chunk_delta_rule is now deprecated. Please use `chunk_delta_rule` instead.")
|
| 122 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 123 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 124 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 125 |
+
|
| 126 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 127 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 128 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 129 |
+
|
| 130 |
+
self.use_beta = use_beta
|
| 131 |
+
if self.use_beta:
|
| 132 |
+
self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 133 |
+
if use_short_conv:
|
| 134 |
+
self.conv_size = conv_size
|
| 135 |
+
self.q_conv1d = ShortConvolution(
|
| 136 |
+
hidden_size=self.key_dim,
|
| 137 |
+
kernel_size=conv_size,
|
| 138 |
+
bias=conv_bias,
|
| 139 |
+
activation='silu' if qk_activation == 'silu' else None
|
| 140 |
+
)
|
| 141 |
+
self.k_conv1d = ShortConvolution(
|
| 142 |
+
hidden_size=self.key_dim,
|
| 143 |
+
kernel_size=conv_size,
|
| 144 |
+
bias=conv_bias,
|
| 145 |
+
activation='silu' if qk_activation == 'silu' else None
|
| 146 |
+
)
|
| 147 |
+
self.v_conv1d = ShortConvolution(
|
| 148 |
+
hidden_size=self.value_dim,
|
| 149 |
+
kernel_size=conv_size,
|
| 150 |
+
bias=conv_bias,
|
| 151 |
+
activation='silu'
|
| 152 |
+
)
|
| 153 |
+
else:
|
| 154 |
+
warnings.warn(
|
| 155 |
+
"ShortConvolution is crucial to the performance. "
|
| 156 |
+
"Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing."
|
| 157 |
+
)
|
| 158 |
+
if use_gate:
|
| 159 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 160 |
+
self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps)
|
| 161 |
+
else:
|
| 162 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 163 |
+
|
| 164 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 165 |
+
|
| 166 |
+
def forward(
|
| 167 |
+
self,
|
| 168 |
+
hidden_states: torch.Tensor,
|
| 169 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 170 |
+
past_key_values: Optional[Cache] = None,
|
| 171 |
+
use_cache: Optional[bool] = False,
|
| 172 |
+
output_attentions: Optional[bool] = False,
|
| 173 |
+
**kwargs: Unpack[Dict]
|
| 174 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 175 |
+
if attention_mask is not None:
|
| 176 |
+
assert len(attention_mask.shape) == 2, (
|
| 177 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 178 |
+
"for padding purposes (0 indicating padding). "
|
| 179 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 183 |
+
# change to inference mode.
|
| 184 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 185 |
+
|
| 186 |
+
last_state = None
|
| 187 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 188 |
+
last_state = past_key_values[self.layer_idx]
|
| 189 |
+
|
| 190 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 191 |
+
if attention_mask is not None:
|
| 192 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 193 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 194 |
+
|
| 195 |
+
if self.use_short_conv:
|
| 196 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 197 |
+
if last_state is not None:
|
| 198 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 199 |
+
q, conv_state_q = self.q_conv1d(
|
| 200 |
+
x=self.q_proj(hidden_states),
|
| 201 |
+
cache=conv_state_q,
|
| 202 |
+
output_final_state=use_cache,
|
| 203 |
+
cu_seqlens=cu_seqlens
|
| 204 |
+
)
|
| 205 |
+
k, conv_state_k = self.k_conv1d(
|
| 206 |
+
x=self.k_proj(hidden_states),
|
| 207 |
+
cache=conv_state_k,
|
| 208 |
+
output_final_state=use_cache,
|
| 209 |
+
cu_seqlens=cu_seqlens
|
| 210 |
+
)
|
| 211 |
+
v, conv_state_v = self.v_conv1d(
|
| 212 |
+
x=self.v_proj(hidden_states),
|
| 213 |
+
cache=conv_state_v,
|
| 214 |
+
output_final_state=use_cache,
|
| 215 |
+
cu_seqlens=cu_seqlens
|
| 216 |
+
)
|
| 217 |
+
else:
|
| 218 |
+
q = self.q_proj(hidden_states)
|
| 219 |
+
k = self.k_proj(hidden_states)
|
| 220 |
+
if self.qk_activation == 'silu':
|
| 221 |
+
q, k = F.silu(q), F.silu(k)
|
| 222 |
+
v = F.silu(self.v_proj(hidden_states))
|
| 223 |
+
|
| 224 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
|
| 225 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 226 |
+
if self.qk_activation != 'silu':
|
| 227 |
+
if self.qk_activation == 'relu':
|
| 228 |
+
q, k = q.relu(), k.relu()
|
| 229 |
+
elif self.qk_activation == 'elu':
|
| 230 |
+
q, k = elu_p1(q), elu_p1(k)
|
| 231 |
+
elif self.qk_activation != 'identity':
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
|
| 234 |
+
if self.qk_norm == 'sum':
|
| 235 |
+
q = sum_norm(q).to(q)
|
| 236 |
+
k = sum_norm(k).to(k)
|
| 237 |
+
|
| 238 |
+
if self.use_beta:
|
| 239 |
+
beta = self.b_proj(hidden_states).sigmoid()
|
| 240 |
+
else:
|
| 241 |
+
beta = torch.ones_like(q[..., 0])
|
| 242 |
+
|
| 243 |
+
if self.allow_neg_eigval:
|
| 244 |
+
beta = beta * 2.
|
| 245 |
+
|
| 246 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 247 |
+
if mode == 'fused_recurrent':
|
| 248 |
+
o, recurrent_state = fused_recurrent_delta_rule(
|
| 249 |
+
q=q,
|
| 250 |
+
k=k,
|
| 251 |
+
v=v,
|
| 252 |
+
beta=beta,
|
| 253 |
+
initial_state=recurrent_state,
|
| 254 |
+
output_final_state=use_cache,
|
| 255 |
+
cu_seqlens=cu_seqlens,
|
| 256 |
+
use_qk_l2norm_in_kernel=True if self.qk_norm == 'l2' else False
|
| 257 |
+
)
|
| 258 |
+
elif mode == 'chunk':
|
| 259 |
+
o, recurrent_state = chunk_delta_rule(
|
| 260 |
+
q=q,
|
| 261 |
+
k=k,
|
| 262 |
+
v=v,
|
| 263 |
+
beta=beta,
|
| 264 |
+
initial_state=recurrent_state,
|
| 265 |
+
output_final_state=use_cache,
|
| 266 |
+
cu_seqlens=cu_seqlens,
|
| 267 |
+
use_qk_l2norm_in_kernel=True if self.qk_norm == 'l2' else False
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 271 |
+
|
| 272 |
+
if past_key_values is not None:
|
| 273 |
+
past_key_values.update(
|
| 274 |
+
recurrent_state=recurrent_state,
|
| 275 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 276 |
+
layer_idx=self.layer_idx,
|
| 277 |
+
offset=q_len
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if self.use_gate:
|
| 281 |
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 282 |
+
o = self.o_norm(o, g)
|
| 283 |
+
else:
|
| 284 |
+
o = self.o_norm(o)
|
| 285 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 286 |
+
o = self.o_proj(o)
|
| 287 |
+
if attention_mask is not None:
|
| 288 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 289 |
+
|
| 290 |
+
return o, None, past_key_values
|
layers/deltaformer.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
from transformers.utils import logging
|
| 12 |
+
|
| 13 |
+
from fla.modules import RMSNorm, RotaryEmbedding
|
| 14 |
+
from fla.ops.deltaformer import deltaformer_attn
|
| 15 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from fla.models.utils import Cache
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DeltaFormerAttention(nn.Module):
|
| 24 |
+
|
| 25 |
+
r"""
|
| 26 |
+
The layer implementation for DeltaFormer,
|
| 27 |
+
[Understanding Transformer from the Perspective of Associative Memory]
|
| 28 |
+
(https://arxiv.org/pdf/2505.19488).
|
| 29 |
+
|
| 30 |
+
Notes
|
| 31 |
+
- DeltaFormer attention is implemented with Triton kernels in `fla.ops.deltaformer` and is tuned
|
| 32 |
+
for typical head dimensions (e.g., 64/128). It currently supports fixed-length inputs.
|
| 33 |
+
- For variable-length inputs (padding masks), the deltaformer computation falls back to using the
|
| 34 |
+
fixed-length path, while the second stage (softmax attention over U) uses FlashAttention's
|
| 35 |
+
varlen path when an attention mask is provided.
|
| 36 |
+
- K/V grouping (GQA) is supported natively by FlashAttention via `num_kv_heads`.
|
| 37 |
+
- Uses K-K similarity in deltaformer computation instead of Q-K similarity for better performance.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
hidden_size (int, Optional):
|
| 41 |
+
The hidden size of the input. Default: 2048.
|
| 42 |
+
num_heads (int, Optional):
|
| 43 |
+
The number of attention heads. Default: 32.
|
| 44 |
+
num_kv_heads (int, Optional):
|
| 45 |
+
The number of key/value heads for grouped-query attention. If None, equals `num_heads`.
|
| 46 |
+
Default: None.
|
| 47 |
+
qkv_bias (bool, Optional):
|
| 48 |
+
Whether to use bias for Q/K/V projections. Default: False.
|
| 49 |
+
qk_norm (bool, Optional):
|
| 50 |
+
Whether to apply per-head RMSNorm to Q and K before attention. Default: False.
|
| 51 |
+
rope_theta (float, Optional):
|
| 52 |
+
The base frequency for rotary position embedding. Default: 10000.
|
| 53 |
+
max_position_embeddings (int, Optional):
|
| 54 |
+
The maximum position embeddings. Default: None.
|
| 55 |
+
layer_idx (int, Optional):
|
| 56 |
+
The index of the layer (used for cache compatibility). Default: None.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
hidden_size: int = 2048,
|
| 62 |
+
num_heads: int = 32,
|
| 63 |
+
num_kv_heads: Optional[int] = None,
|
| 64 |
+
qkv_bias: bool = False,
|
| 65 |
+
qk_norm: bool = False,
|
| 66 |
+
rope_theta: float = 10000.,
|
| 67 |
+
max_position_embeddings: Optional[int] = None,
|
| 68 |
+
layer_idx: int | None = None,
|
| 69 |
+
):
|
| 70 |
+
super().__init__()
|
| 71 |
+
|
| 72 |
+
self.hidden_size = hidden_size
|
| 73 |
+
self.num_heads = num_heads
|
| 74 |
+
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
| 75 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 76 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 77 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 78 |
+
self.qkv_bias = qkv_bias
|
| 79 |
+
self.qk_norm = qk_norm
|
| 80 |
+
self.rope_theta = rope_theta
|
| 81 |
+
self.max_position_embeddings = max_position_embeddings
|
| 82 |
+
self.layer_idx = layer_idx
|
| 83 |
+
|
| 84 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
| 85 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 86 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 87 |
+
self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True)
|
| 88 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 89 |
+
|
| 90 |
+
if qk_norm:
|
| 91 |
+
self.q_norm = RMSNorm(self.head_dim)
|
| 92 |
+
self.k_norm = RMSNorm(self.head_dim)
|
| 93 |
+
|
| 94 |
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
| 95 |
+
|
| 96 |
+
def forward(
|
| 97 |
+
self,
|
| 98 |
+
hidden_states: torch.Tensor,
|
| 99 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 100 |
+
past_key_values: Optional[Cache] = None,
|
| 101 |
+
output_attentions: bool = False,
|
| 102 |
+
use_cache: bool = False,
|
| 103 |
+
**kwargs,
|
| 104 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 105 |
+
attentions = None
|
| 106 |
+
if attention_mask is not None:
|
| 107 |
+
assert len(attention_mask.shape) == 2, (
|
| 108 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 109 |
+
"for padding purposes (0 indicating padding). "
|
| 110 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 114 |
+
|
| 115 |
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 116 |
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 117 |
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 118 |
+
beta = self.b_proj(hidden_states)
|
| 119 |
+
|
| 120 |
+
if self.qk_norm:
|
| 121 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 122 |
+
|
| 123 |
+
cu_seqlens_kw = kwargs.get('cu_seqlens', None)
|
| 124 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 125 |
+
if past_key_values is not None:
|
| 126 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 127 |
+
max_seqlen = q_len + seqlen_offset
|
| 128 |
+
|
| 129 |
+
if attention_mask is not None:
|
| 130 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 131 |
+
max_seqlen = q_len + max(seqlen_offset)
|
| 132 |
+
|
| 133 |
+
if self.max_position_embeddings is not None:
|
| 134 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 135 |
+
|
| 136 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens_kw)
|
| 137 |
+
|
| 138 |
+
o = deltaformer_attn(
|
| 139 |
+
q=q,
|
| 140 |
+
k=k,
|
| 141 |
+
v=v,
|
| 142 |
+
beta=beta,
|
| 143 |
+
attention_mask=attention_mask,
|
| 144 |
+
cu_seqlens=cu_seqlens_kw
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 148 |
+
o = self.o_proj(o)
|
| 149 |
+
|
| 150 |
+
if not output_attentions:
|
| 151 |
+
attentions = None
|
| 152 |
+
|
| 153 |
+
return o, attentions, past_key_values
|
layers/forgetting_attn.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import torch.utils.checkpoint
|
| 12 |
+
from einops import rearrange
|
| 13 |
+
from transformers.utils import logging
|
| 14 |
+
|
| 15 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 16 |
+
from fla.modules import GroupNorm
|
| 17 |
+
from fla.ops.attn.decoding import attn_decoding_one_step
|
| 18 |
+
from fla.ops.forgetting_attn.parallel import parallel_forgetting_attn
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ForgettingAttention(nn.Module):
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
hidden_size: int = 2048,
|
| 31 |
+
num_heads: int = 32,
|
| 32 |
+
num_kv_heads: Optional[int] = None,
|
| 33 |
+
qkv_bias: bool = False,
|
| 34 |
+
qk_norm: bool = False,
|
| 35 |
+
window_size: Optional[int] = None,
|
| 36 |
+
use_output_gate: bool = False,
|
| 37 |
+
layer_idx: int = None
|
| 38 |
+
):
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
self.hidden_size = hidden_size
|
| 42 |
+
self.num_heads = num_heads
|
| 43 |
+
if num_kv_heads is None:
|
| 44 |
+
self.num_kv_heads = self.num_heads
|
| 45 |
+
else:
|
| 46 |
+
self.num_kv_heads = num_kv_heads
|
| 47 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 48 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 49 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 50 |
+
self.qkv_bias = qkv_bias
|
| 51 |
+
self.qk_norm = qk_norm
|
| 52 |
+
|
| 53 |
+
self.window_size = window_size
|
| 54 |
+
self.use_output_gate = use_output_gate
|
| 55 |
+
self.layer_idx = layer_idx
|
| 56 |
+
|
| 57 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
| 58 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 59 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 60 |
+
self.f_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True)
|
| 61 |
+
|
| 62 |
+
if use_output_gate:
|
| 63 |
+
self.g_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 64 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 65 |
+
|
| 66 |
+
if qk_norm:
|
| 67 |
+
self.q_norm = GroupNorm(
|
| 68 |
+
num_groups=self.num_heads,
|
| 69 |
+
hidden_size=self.hidden_size,
|
| 70 |
+
is_rms_norm=True,
|
| 71 |
+
)
|
| 72 |
+
self.k_norm = GroupNorm(
|
| 73 |
+
num_groups=self.num_kv_heads,
|
| 74 |
+
hidden_size=self.kv_dim,
|
| 75 |
+
is_rms_norm=True,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
def forward(
|
| 79 |
+
self,
|
| 80 |
+
hidden_states: torch.Tensor,
|
| 81 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 82 |
+
past_key_values: Optional[Cache] = None,
|
| 83 |
+
output_attentions: bool = False,
|
| 84 |
+
use_cache: bool = False,
|
| 85 |
+
**kwargs,
|
| 86 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 87 |
+
if attention_mask is not None:
|
| 88 |
+
assert len(attention_mask.shape) == 2, (
|
| 89 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 90 |
+
"for padding purposes (0 indicating padding). "
|
| 91 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 95 |
+
|
| 96 |
+
q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
|
| 97 |
+
f = F.logsigmoid(self.f_proj(hidden_states).float())
|
| 98 |
+
if self.qk_norm:
|
| 99 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 100 |
+
|
| 101 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 102 |
+
if past_key_values is not None:
|
| 103 |
+
assert cu_seqlens is None, "cu_seqlens should not be provided when past_key_values is not None"
|
| 104 |
+
state = past_key_values.update(
|
| 105 |
+
attn_state=(k, v, f),
|
| 106 |
+
layer_idx=self.layer_idx,
|
| 107 |
+
offset=q_len,
|
| 108 |
+
cache_kwargs=dict(window_size=self.window_size)
|
| 109 |
+
)
|
| 110 |
+
k, v, f = state['attn_state']
|
| 111 |
+
|
| 112 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 113 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 114 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 115 |
+
|
| 116 |
+
if attention_mask is not None:
|
| 117 |
+
q, (k, v, f), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v, f), attention_mask, q_len, keepdim=True)
|
| 118 |
+
_, cu_seqlens_k = cu_seqlens
|
| 119 |
+
cu_seqlens = cu_seqlens_k
|
| 120 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 121 |
+
if max_seqlen_q != max_seqlen_k:
|
| 122 |
+
assert max_seqlen_q == 1, "only support q_len == 1 for decoding"
|
| 123 |
+
o = attn_decoding_one_step(q, k, v, f, cu_seqlens=cu_seqlens)
|
| 124 |
+
else:
|
| 125 |
+
o = parallel_forgetting_attn(q, k, v, f, cu_seqlens=cu_seqlens)
|
| 126 |
+
else:
|
| 127 |
+
o = parallel_forgetting_attn(q, k, v, f, cu_seqlens=cu_seqlens)
|
| 128 |
+
if attention_mask is not None:
|
| 129 |
+
o = pad_input(o.squeeze(0), indices_q, batch_size, q_len)
|
| 130 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 131 |
+
if self.use_output_gate:
|
| 132 |
+
o = self.g_proj(hidden_states).sigmoid() * o
|
| 133 |
+
o = self.o_proj(o)
|
| 134 |
+
return o, None, past_key_values
|
layers/gated_deltanet.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
import warnings
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from einops import rearrange, repeat
|
| 13 |
+
from torch.nn import functional as F
|
| 14 |
+
|
| 15 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 16 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 17 |
+
from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from transformers.processing_utils import Unpack
|
| 21 |
+
|
| 22 |
+
from fla.models.utils import Cache
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@torch.compile
|
| 26 |
+
def elu_p1(x):
|
| 27 |
+
return (F.elu(x, 1., False) + 1.).to(x)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@torch.compile
|
| 31 |
+
def sum_norm(x):
|
| 32 |
+
return (x / x.sum(-1, keepdim=True)).to(x)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class GatedDeltaNet(nn.Module):
|
| 36 |
+
"""
|
| 37 |
+
The layer implementaion for [Gated Delta Networks: Improving Mamba2 with Delta Rule](https://arxiv.org/abs/2412.06464). # noqa
|
| 38 |
+
|
| 39 |
+
Similar to Mamba2, each layer contains around 6*hidden_size*hidden_size parameters.
|
| 40 |
+
|
| 41 |
+
Parameter alloation when use_gate=True:
|
| 42 |
+
- 0.75 * hidden_size * hidden_size for the q_proj and k_proj each
|
| 43 |
+
- 1.5 * hidden_size * hidden_size for the v_proj, g_proj and o_proj each
|
| 44 |
+
- Others are ignorably small.
|
| 45 |
+
- In total = 0.75 * 2 + 1.5 * 3 = 6 * hidden_size * hidden_size
|
| 46 |
+
NOTE: num_heads * head_dim = 0.75 * hidden_size, please make sure to set the correct num_heads and head_dim.
|
| 47 |
+
|
| 48 |
+
Parameter allocation when use_gate=False:
|
| 49 |
+
- 1 * hidden_size * hidden_size for the q_proj and k_proj each
|
| 50 |
+
- 2 * hidden_size * hidden_size for the v_proj and o_proj each
|
| 51 |
+
- Others are ignorably small.
|
| 52 |
+
- In total = 1 * 2 + 2 * 2 = 6 * hidden_size * hidden_size
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
hidden_size (int, Optional):
|
| 56 |
+
The hidden size of the input. Default: 2048.
|
| 57 |
+
expand_v (float, Optional):
|
| 58 |
+
The expansion ratio for the value dim. Default: 2.0.
|
| 59 |
+
head_dim (int, Optional):
|
| 60 |
+
The dimension of each head. Default: 256.
|
| 61 |
+
num_heads (int, Optional):
|
| 62 |
+
The number of heads. Default: 4.
|
| 63 |
+
num_v_heads (int, Optional):
|
| 64 |
+
The number of heads for the value projection, equal to `num_heads` if `None`.
|
| 65 |
+
GVA is applied if `num_v_heads` > `num_heads`. Default: `None`.
|
| 66 |
+
mode (str, Optional):
|
| 67 |
+
Which Gated DeltaNet kernel to use.
|
| 68 |
+
Currently available: `chunk` and `fused_recurrent`.
|
| 69 |
+
Default: `chunk`.
|
| 70 |
+
use_beta (bool, Optional):
|
| 71 |
+
Whether to use beta. Default: `True`.
|
| 72 |
+
use_gate (bool, Optional):
|
| 73 |
+
Whether to use output gate. Default: `True`.
|
| 74 |
+
use_short_conv (bool, Optional):
|
| 75 |
+
Whether to use short convolutions. Default: `True`.
|
| 76 |
+
allow_neg_eigval (bool, Optional):
|
| 77 |
+
Allow negative eigenvalues. Default: `False`. If set to `True`, the beta will be multiplied by 2.
|
| 78 |
+
See reference: [Unlocking State-Tracking in Linear RNNs Through Negative Eigenvalues](https://arxiv.org/abs/2411.12537)
|
| 79 |
+
conv_size (int, Optional):
|
| 80 |
+
The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
|
| 81 |
+
conv_bias (bool, Optional):
|
| 82 |
+
Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
|
| 83 |
+
layer_idx (int, Optional):
|
| 84 |
+
The index of the layer. Default: None.
|
| 85 |
+
norm_eps (float, Optional):
|
| 86 |
+
The epsilon value for the normalization layer. Default: 1e-5.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
hidden_size: int = 2048,
|
| 92 |
+
expand_v: float = 2,
|
| 93 |
+
head_dim: int = 256,
|
| 94 |
+
num_heads: int = 6,
|
| 95 |
+
num_v_heads: int = None,
|
| 96 |
+
mode: str = 'chunk',
|
| 97 |
+
use_gate: bool = True,
|
| 98 |
+
use_short_conv: bool = True,
|
| 99 |
+
allow_neg_eigval: bool = False,
|
| 100 |
+
conv_size: int = 4,
|
| 101 |
+
conv_bias: bool = False,
|
| 102 |
+
layer_idx: int = None,
|
| 103 |
+
norm_eps: float = 1e-5,
|
| 104 |
+
**kwargs
|
| 105 |
+
) -> GatedDeltaNet:
|
| 106 |
+
super().__init__()
|
| 107 |
+
|
| 108 |
+
self.mode = mode
|
| 109 |
+
self.allow_neg_eigval = allow_neg_eigval
|
| 110 |
+
self.hidden_size = hidden_size
|
| 111 |
+
self.expand_v = expand_v
|
| 112 |
+
|
| 113 |
+
self.use_gate = use_gate
|
| 114 |
+
self.use_short_conv = use_short_conv
|
| 115 |
+
self.conv_size = conv_size
|
| 116 |
+
self.conv_bias = conv_bias
|
| 117 |
+
|
| 118 |
+
self.head_dim = head_dim
|
| 119 |
+
self.num_heads = num_heads
|
| 120 |
+
self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
|
| 121 |
+
|
| 122 |
+
self.head_k_dim = head_dim
|
| 123 |
+
self.head_v_dim = int(self.head_dim * self.expand_v)
|
| 124 |
+
self.key_dim = int(self.num_heads * self.head_k_dim)
|
| 125 |
+
self.value_dim = int(self.num_v_heads * self.head_v_dim)
|
| 126 |
+
self.layer_idx = layer_idx
|
| 127 |
+
|
| 128 |
+
# Consistency check: Ensure expand_v produces integer values
|
| 129 |
+
if not math.isclose(self.num_v_heads * self.head_dim * expand_v, self.value_dim, rel_tol=1e-5):
|
| 130 |
+
raise ValueError(
|
| 131 |
+
f"expand_v={expand_v} does not produce an integer value when multiplied by key_dim={self.key_dim}. "
|
| 132 |
+
f"Resulting value_dim would be {self.num_v_heads * self.head_dim * expand_v}, which is invalid for nn.Linear."
|
| 133 |
+
)
|
| 134 |
+
if self.num_v_heads > self.num_heads and self.num_v_heads % self.num_heads != 0:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
f"num_v_heads={self.num_v_heads} must be divisible by num_heads={self.num_heads}."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if not math.isclose(head_dim * expand_v, self.head_v_dim, rel_tol=1e-5):
|
| 140 |
+
raise ValueError(
|
| 141 |
+
f"expand_v={expand_v} does not produce an integer value when multiplied by head_dim={head_dim}. "
|
| 142 |
+
f"Resulting head_v_dim would be {head_dim * expand_v}, which is invalid for FusedRMSNormGated."
|
| 143 |
+
)
|
| 144 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 145 |
+
|
| 146 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 147 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 148 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 149 |
+
self.a_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False)
|
| 150 |
+
self.b_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False)
|
| 151 |
+
|
| 152 |
+
A = torch.empty(self.num_v_heads, dtype=torch.float32).uniform_(0, 16)
|
| 153 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 154 |
+
self.A_log._no_weight_decay = True
|
| 155 |
+
# hard coded for now
|
| 156 |
+
dt_min = 0.001
|
| 157 |
+
dt_max = 0.1
|
| 158 |
+
dt_init_floor = 1e-4
|
| 159 |
+
dt = torch.exp(
|
| 160 |
+
torch.rand(self.num_v_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 161 |
+
+ math.log(dt_min)
|
| 162 |
+
)
|
| 163 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 164 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 165 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 166 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 167 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 168 |
+
# name.endswith("bias") in param_grouping.py
|
| 169 |
+
self.dt_bias._no_weight_decay = True
|
| 170 |
+
|
| 171 |
+
if use_short_conv:
|
| 172 |
+
self.conv_size = conv_size
|
| 173 |
+
self.q_conv1d = ShortConvolution(
|
| 174 |
+
hidden_size=self.key_dim,
|
| 175 |
+
kernel_size=conv_size,
|
| 176 |
+
bias=conv_bias,
|
| 177 |
+
activation='silu'
|
| 178 |
+
)
|
| 179 |
+
self.k_conv1d = ShortConvolution(
|
| 180 |
+
hidden_size=self.key_dim,
|
| 181 |
+
kernel_size=conv_size,
|
| 182 |
+
bias=conv_bias,
|
| 183 |
+
activation='silu'
|
| 184 |
+
)
|
| 185 |
+
self.v_conv1d = ShortConvolution(
|
| 186 |
+
hidden_size=self.value_dim,
|
| 187 |
+
kernel_size=conv_size,
|
| 188 |
+
bias=conv_bias,
|
| 189 |
+
activation='silu'
|
| 190 |
+
)
|
| 191 |
+
else:
|
| 192 |
+
warnings.warn(
|
| 193 |
+
"ShortConvolution is crucial to the performance. "
|
| 194 |
+
"Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing."
|
| 195 |
+
)
|
| 196 |
+
if use_gate:
|
| 197 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 198 |
+
self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps)
|
| 199 |
+
else:
|
| 200 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 201 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 202 |
+
|
| 203 |
+
def forward(
|
| 204 |
+
self,
|
| 205 |
+
hidden_states: torch.Tensor,
|
| 206 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 207 |
+
past_key_values: Optional[Cache] = None,
|
| 208 |
+
use_cache: Optional[bool] = False,
|
| 209 |
+
output_attentions: Optional[bool] = False,
|
| 210 |
+
**kwargs: Unpack[Dict]
|
| 211 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 212 |
+
if attention_mask is not None:
|
| 213 |
+
assert len(attention_mask.shape) == 2, (
|
| 214 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 215 |
+
"for padding purposes (0 indicating padding). "
|
| 216 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 220 |
+
# change to inference mode.
|
| 221 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 222 |
+
if self.training:
|
| 223 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 224 |
+
|
| 225 |
+
last_state = None
|
| 226 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 227 |
+
last_state = past_key_values[self.layer_idx]
|
| 228 |
+
|
| 229 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 230 |
+
if attention_mask is not None:
|
| 231 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 232 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 233 |
+
|
| 234 |
+
if self.use_short_conv:
|
| 235 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 236 |
+
if last_state is not None:
|
| 237 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 238 |
+
q, conv_state_q = self.q_conv1d(
|
| 239 |
+
x=self.q_proj(hidden_states),
|
| 240 |
+
cache=conv_state_q,
|
| 241 |
+
output_final_state=use_cache,
|
| 242 |
+
cu_seqlens=cu_seqlens
|
| 243 |
+
)
|
| 244 |
+
k, conv_state_k = self.k_conv1d(
|
| 245 |
+
x=self.k_proj(hidden_states),
|
| 246 |
+
cache=conv_state_k,
|
| 247 |
+
output_final_state=use_cache,
|
| 248 |
+
cu_seqlens=cu_seqlens
|
| 249 |
+
)
|
| 250 |
+
v, conv_state_v = self.v_conv1d(
|
| 251 |
+
x=self.v_proj(hidden_states),
|
| 252 |
+
cache=conv_state_v,
|
| 253 |
+
output_final_state=use_cache,
|
| 254 |
+
cu_seqlens=cu_seqlens
|
| 255 |
+
)
|
| 256 |
+
else:
|
| 257 |
+
q = F.silu(self.q_proj(hidden_states))
|
| 258 |
+
k = F.silu(self.k_proj(hidden_states))
|
| 259 |
+
v = F.silu(self.v_proj(hidden_states))
|
| 260 |
+
|
| 261 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
|
| 262 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 263 |
+
|
| 264 |
+
if self.num_v_heads > self.num_heads:
|
| 265 |
+
q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k))
|
| 266 |
+
|
| 267 |
+
beta = self.b_proj(hidden_states).sigmoid()
|
| 268 |
+
if self.allow_neg_eigval:
|
| 269 |
+
beta = beta * 2.
|
| 270 |
+
|
| 271 |
+
g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 272 |
+
|
| 273 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 274 |
+
if mode == 'chunk':
|
| 275 |
+
o, recurrent_state = chunk_gated_delta_rule(
|
| 276 |
+
q=q,
|
| 277 |
+
k=k,
|
| 278 |
+
v=v,
|
| 279 |
+
g=g,
|
| 280 |
+
beta=beta,
|
| 281 |
+
initial_state=recurrent_state,
|
| 282 |
+
output_final_state=use_cache,
|
| 283 |
+
cu_seqlens=cu_seqlens,
|
| 284 |
+
use_qk_l2norm_in_kernel=True
|
| 285 |
+
)
|
| 286 |
+
elif mode == 'fused_recurrent':
|
| 287 |
+
o, recurrent_state = fused_recurrent_gated_delta_rule(
|
| 288 |
+
q=q,
|
| 289 |
+
k=k,
|
| 290 |
+
v=v,
|
| 291 |
+
g=g,
|
| 292 |
+
beta=beta,
|
| 293 |
+
initial_state=recurrent_state,
|
| 294 |
+
output_final_state=use_cache,
|
| 295 |
+
cu_seqlens=cu_seqlens,
|
| 296 |
+
use_qk_l2norm_in_kernel=True
|
| 297 |
+
)
|
| 298 |
+
else:
|
| 299 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 300 |
+
|
| 301 |
+
if past_key_values is not None:
|
| 302 |
+
past_key_values.update(
|
| 303 |
+
recurrent_state=recurrent_state,
|
| 304 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 305 |
+
layer_idx=self.layer_idx,
|
| 306 |
+
offset=q_len
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
if self.use_gate:
|
| 310 |
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 311 |
+
o = self.o_norm(o, g)
|
| 312 |
+
else:
|
| 313 |
+
o = self.o_norm(o)
|
| 314 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 315 |
+
o = self.o_proj(o)
|
| 316 |
+
if attention_mask is not None:
|
| 317 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 318 |
+
|
| 319 |
+
return o, None, past_key_values
|
layers/gated_deltaproduct.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
import warnings
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from einops import rearrange, repeat
|
| 13 |
+
from torch.nn import functional as F
|
| 14 |
+
|
| 15 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 16 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 17 |
+
from fla.ops.gated_delta_product import chunk_gated_delta_product
|
| 18 |
+
from fla.ops.gated_delta_rule import fused_recurrent_gated_delta_rule
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from transformers.processing_utils import Unpack
|
| 22 |
+
|
| 23 |
+
from fla.models.utils import Cache
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class GatedDeltaProduct(nn.Module):
|
| 27 |
+
"""
|
| 28 |
+
Generalized version of GatedDoubleDeltaNet that supports arbitrary number of householder transformations.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
hidden_size: int = 2048,
|
| 34 |
+
expand_v: float = 2,
|
| 35 |
+
head_dim: int = 256,
|
| 36 |
+
num_heads: int = 6,
|
| 37 |
+
num_v_heads: int = None,
|
| 38 |
+
mode: str = 'chunk',
|
| 39 |
+
use_output_gate: bool = True,
|
| 40 |
+
use_short_conv: bool = True,
|
| 41 |
+
conv_size: int = 4,
|
| 42 |
+
conv_bias: bool = False,
|
| 43 |
+
layer_idx: int = None,
|
| 44 |
+
norm_eps: float = 1e-5,
|
| 45 |
+
use_forget_gate: bool = True,
|
| 46 |
+
allow_neg_eigval: bool = True,
|
| 47 |
+
num_householder: int = 2,
|
| 48 |
+
**kwargs
|
| 49 |
+
) -> GatedDeltaProduct:
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
self.mode = mode
|
| 53 |
+
|
| 54 |
+
self.hidden_size = hidden_size
|
| 55 |
+
self.expand_v = expand_v
|
| 56 |
+
|
| 57 |
+
self.use_forget_gate = use_forget_gate
|
| 58 |
+
self.allow_neg_eigval = allow_neg_eigval
|
| 59 |
+
self.num_householder = num_householder
|
| 60 |
+
self.use_output_gate = use_output_gate
|
| 61 |
+
self.use_short_conv = use_short_conv
|
| 62 |
+
self.conv_size = conv_size
|
| 63 |
+
self.conv_bias = conv_bias
|
| 64 |
+
|
| 65 |
+
self.head_dim = head_dim
|
| 66 |
+
self.num_heads = num_heads
|
| 67 |
+
self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
|
| 68 |
+
|
| 69 |
+
self.head_k_dim = head_dim
|
| 70 |
+
self.head_v_dim = int(self.head_dim * self.expand_v)
|
| 71 |
+
self.key_dim = int(self.num_heads * self.head_k_dim)
|
| 72 |
+
self.value_dim = int(self.num_v_heads * self.head_v_dim)
|
| 73 |
+
self.layer_idx = layer_idx
|
| 74 |
+
|
| 75 |
+
# Consistency check: Ensure expand_v produces integer values
|
| 76 |
+
if not math.isclose(self.num_v_heads * self.head_dim * expand_v, self.value_dim, rel_tol=1e-5):
|
| 77 |
+
raise ValueError(
|
| 78 |
+
f"expand_v={expand_v} does not produce an integer value when multiplied by key_dim={self.key_dim}. "
|
| 79 |
+
f"Resulting value_dim would be {self.num_v_heads * self.head_dim * expand_v}, which is invalid for nn.Linear."
|
| 80 |
+
)
|
| 81 |
+
if self.num_v_heads > self.num_heads and self.num_v_heads % self.num_heads != 0:
|
| 82 |
+
raise ValueError(
|
| 83 |
+
f"num_v_heads={self.num_v_heads} must be divisible by num_heads={self.num_heads}."
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
if not math.isclose(head_dim * expand_v, self.head_v_dim, rel_tol=1e-5):
|
| 87 |
+
raise ValueError(
|
| 88 |
+
f"expand_v={expand_v} does not produce an integer value when multiplied by head_dim={head_dim}. "
|
| 89 |
+
f"Resulting head_v_dim would be {head_dim * expand_v}, which is invalid for FusedRMSNormGated."
|
| 90 |
+
)
|
| 91 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 92 |
+
|
| 93 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 94 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim * num_householder, bias=False)
|
| 95 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim * num_householder, bias=False)
|
| 96 |
+
self.b_proj = nn.Linear(hidden_size, self.num_v_heads * num_householder, bias=False)
|
| 97 |
+
|
| 98 |
+
if self.use_forget_gate:
|
| 99 |
+
self.a_proj = nn.Linear(hidden_size, self.num_v_heads, bias=False)
|
| 100 |
+
A = torch.empty(self.num_v_heads, dtype=torch.float32).uniform_(0, 16)
|
| 101 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 102 |
+
self.A_log._no_weight_decay = True
|
| 103 |
+
# hard coded for now
|
| 104 |
+
dt_min = 0.001
|
| 105 |
+
dt_max = 0.1
|
| 106 |
+
dt_init_floor = 1e-4
|
| 107 |
+
dt = torch.exp(
|
| 108 |
+
torch.rand(self.num_v_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 109 |
+
+ math.log(dt_min)
|
| 110 |
+
)
|
| 111 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 112 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 113 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 114 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 115 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 116 |
+
# name.endswith("bias") in param_grouping.py
|
| 117 |
+
self.dt_bias._no_weight_decay = True
|
| 118 |
+
|
| 119 |
+
if use_short_conv:
|
| 120 |
+
self.conv_size = conv_size
|
| 121 |
+
self.q_conv1d = ShortConvolution(
|
| 122 |
+
hidden_size=self.key_dim,
|
| 123 |
+
kernel_size=conv_size,
|
| 124 |
+
bias=conv_bias,
|
| 125 |
+
activation='silu'
|
| 126 |
+
)
|
| 127 |
+
self.k_conv1d = ShortConvolution(
|
| 128 |
+
hidden_size=self.key_dim * num_householder,
|
| 129 |
+
kernel_size=conv_size,
|
| 130 |
+
bias=conv_bias,
|
| 131 |
+
activation='silu'
|
| 132 |
+
)
|
| 133 |
+
self.v_conv1d = ShortConvolution(
|
| 134 |
+
hidden_size=self.value_dim * num_householder,
|
| 135 |
+
kernel_size=conv_size,
|
| 136 |
+
bias=conv_bias,
|
| 137 |
+
activation='silu'
|
| 138 |
+
)
|
| 139 |
+
else:
|
| 140 |
+
warnings.warn(
|
| 141 |
+
"ShortConvolution is crucial to the performance. "
|
| 142 |
+
"Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing."
|
| 143 |
+
)
|
| 144 |
+
if use_output_gate:
|
| 145 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 146 |
+
self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps)
|
| 147 |
+
else:
|
| 148 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 149 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 150 |
+
|
| 151 |
+
def _initialize_weights(self, module: nn.Module):
|
| 152 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 153 |
+
return
|
| 154 |
+
if isinstance(module, nn.Linear):
|
| 155 |
+
nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 156 |
+
if module.bias is not None:
|
| 157 |
+
nn.init.zeros_(module.bias)
|
| 158 |
+
module._is_hf_initialized = True
|
| 159 |
+
|
| 160 |
+
def forward(
|
| 161 |
+
self,
|
| 162 |
+
hidden_states: torch.Tensor,
|
| 163 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 164 |
+
past_key_values: Optional[Cache] = None,
|
| 165 |
+
use_cache: Optional[bool] = False,
|
| 166 |
+
output_attentions: Optional[bool] = False,
|
| 167 |
+
**kwargs: Unpack[Dict]
|
| 168 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 169 |
+
if attention_mask is not None:
|
| 170 |
+
assert len(attention_mask.shape) == 2, (
|
| 171 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 172 |
+
"for padding purposes (0 indicating padding). "
|
| 173 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 177 |
+
# change to inference mode.
|
| 178 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 179 |
+
|
| 180 |
+
if self.training:
|
| 181 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 182 |
+
|
| 183 |
+
last_state = None
|
| 184 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 185 |
+
last_state = past_key_values[self.layer_idx]
|
| 186 |
+
|
| 187 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 188 |
+
if attention_mask is not None:
|
| 189 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 190 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 191 |
+
|
| 192 |
+
if self.use_short_conv:
|
| 193 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 194 |
+
if last_state is not None:
|
| 195 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 196 |
+
q, conv_state_q = self.q_conv1d(
|
| 197 |
+
x=self.q_proj(hidden_states),
|
| 198 |
+
cache=conv_state_q,
|
| 199 |
+
output_final_state=use_cache,
|
| 200 |
+
cu_seqlens=cu_seqlens
|
| 201 |
+
)
|
| 202 |
+
k, conv_state_k = self.k_conv1d(
|
| 203 |
+
x=self.k_proj(hidden_states),
|
| 204 |
+
cache=conv_state_k,
|
| 205 |
+
output_final_state=use_cache,
|
| 206 |
+
cu_seqlens=cu_seqlens
|
| 207 |
+
)
|
| 208 |
+
v, conv_state_v = self.v_conv1d(
|
| 209 |
+
x=self.v_proj(hidden_states),
|
| 210 |
+
cache=conv_state_v,
|
| 211 |
+
output_final_state=use_cache,
|
| 212 |
+
cu_seqlens=cu_seqlens
|
| 213 |
+
)
|
| 214 |
+
else:
|
| 215 |
+
q = F.silu(self.q_proj(hidden_states))
|
| 216 |
+
k = F.silu(self.k_proj(hidden_states))
|
| 217 |
+
v = F.silu(self.v_proj(hidden_states))
|
| 218 |
+
|
| 219 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 220 |
+
k = rearrange(k, '... t (n h d) -> ... (t n) h d', n=self.num_householder, d=self.head_k_dim)
|
| 221 |
+
v = rearrange(v, '... t (n h d) -> ... (t n) h d', n=self.num_householder, d=self.head_v_dim)
|
| 222 |
+
|
| 223 |
+
if self.num_v_heads > self.num_heads:
|
| 224 |
+
q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k))
|
| 225 |
+
|
| 226 |
+
beta = self.b_proj(hidden_states).sigmoid()
|
| 227 |
+
if self.allow_neg_eigval:
|
| 228 |
+
beta = beta * 2.
|
| 229 |
+
|
| 230 |
+
beta = rearrange(beta, '... t (n h) -> ... (t n) h', n=self.num_householder)
|
| 231 |
+
if self.use_forget_gate:
|
| 232 |
+
g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 233 |
+
else:
|
| 234 |
+
g = None
|
| 235 |
+
|
| 236 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 237 |
+
if mode == 'chunk':
|
| 238 |
+
o, recurrent_state = chunk_gated_delta_product(
|
| 239 |
+
q=q,
|
| 240 |
+
k=k,
|
| 241 |
+
v=v,
|
| 242 |
+
g=g,
|
| 243 |
+
beta=beta,
|
| 244 |
+
initial_state=recurrent_state,
|
| 245 |
+
output_final_state=use_cache,
|
| 246 |
+
cu_seqlens=cu_seqlens,
|
| 247 |
+
num_householder=self.num_householder,
|
| 248 |
+
use_qk_l2norm_in_kernel=True
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
elif mode == 'fused_recurrent':
|
| 252 |
+
if self.use_forget_gate:
|
| 253 |
+
g_new = g.new_zeros(g.shape[0], g.shape[1], self.num_householder, g.shape[2])
|
| 254 |
+
g_new[:, :, 0] = g
|
| 255 |
+
g = rearrange(g_new, '... t n h -> ... (t n) h')
|
| 256 |
+
|
| 257 |
+
q_new = q.new_zeros(q.shape[0], q.shape[1], self.num_householder, q.shape[2], q.shape[3])
|
| 258 |
+
q_new[:, :, -1] = q
|
| 259 |
+
q = rearrange(q_new, '... t n h d-> ... (t n) h d')
|
| 260 |
+
o, recurrent_state = fused_recurrent_gated_delta_rule(
|
| 261 |
+
q=q,
|
| 262 |
+
k=k,
|
| 263 |
+
v=v,
|
| 264 |
+
g=g,
|
| 265 |
+
beta=beta,
|
| 266 |
+
initial_state=recurrent_state,
|
| 267 |
+
output_final_state=use_cache,
|
| 268 |
+
cu_seqlens=cu_seqlens * self.num_householder if cu_seqlens is not None else None,
|
| 269 |
+
use_qk_l2norm_in_kernel=True
|
| 270 |
+
)
|
| 271 |
+
o = rearrange(o, '... (t n) h d -> ... t n h d', n=self.num_householder)[..., -1, :, :].contiguous()
|
| 272 |
+
|
| 273 |
+
if past_key_values is not None:
|
| 274 |
+
past_key_values.update(
|
| 275 |
+
recurrent_state=recurrent_state,
|
| 276 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 277 |
+
layer_idx=self.layer_idx,
|
| 278 |
+
offset=q_len
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
if self.use_output_gate:
|
| 282 |
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 283 |
+
o = self.o_norm(o, g)
|
| 284 |
+
else:
|
| 285 |
+
o = self.o_norm(o)
|
| 286 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 287 |
+
o = self.o_proj(o)
|
| 288 |
+
if attention_mask is not None:
|
| 289 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 290 |
+
|
| 291 |
+
return o, None, past_key_values
|
layers/gka.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gated KalmaNet (GKA) layer implementation with Grouped Query Attention (GQA) support.
|
| 3 |
+
|
| 4 |
+
This module implements the Gated KalmaNet layer from the paper:
|
| 5 |
+
"Gated KalmaNet: A Fading Memory Layer Through Test-Time Ridge Regression" (https://arxiv.org/abs/2511.21016).
|
| 6 |
+
|
| 7 |
+
Overview:
|
| 8 |
+
GKA is a state space model (SSM) that updates its state based on the entire history
|
| 9 |
+
of previously seen tokens, rather than just the current token. At each timestep t,
|
| 10 |
+
the optimal state S_t minimizes a ridge regression objective over all past tokens:
|
| 11 |
+
|
| 12 |
+
S_t = argmin_S { λ·||S||²_F + Σ(i=1 to t) η_i·||S·k_i - v_i||² }
|
| 13 |
+
|
| 14 |
+
where λ is the ridge regularization strength and η_i are exponentially decaying weights
|
| 15 |
+
controlled by forgetting gates. This has a closed-form solution:
|
| 16 |
+
|
| 17 |
+
S_t = U_t · (H_t + λI)^(-1)
|
| 18 |
+
|
| 19 |
+
where:
|
| 20 |
+
U_t = Σ(i=1 to t) η_i v_i k_i^T (cumulative value-key outer products)
|
| 21 |
+
H_t = Σ(i=1 to t) η_i k_i k_i^T (cumulative key-key covariance)
|
| 22 |
+
|
| 23 |
+
The output is computed as y_t = S_t · q_t, which reduces to solving the ridge
|
| 24 |
+
regression problem (H_t + λI)·x_t = q_t for x_t, then computing y_t = U_t · x_t.
|
| 25 |
+
This is solved numerically via the Chebyshev iteration algorithm.
|
| 26 |
+
|
| 27 |
+
The layer supports GQA-style head grouping where the number of key/value heads
|
| 28 |
+
can be different from the number of query heads. The hyperparameters in this module
|
| 29 |
+
are set so that we can initialize the module's weights from existing Attention layers.
|
| 30 |
+
|
| 31 |
+
Key Variables:
|
| 32 |
+
- head_dim: Head dimension (same for q/k/v)
|
| 33 |
+
- num_q_heads: Number of query heads
|
| 34 |
+
- num_k_heads: Number of key heads
|
| 35 |
+
- num_v_heads: Number of value heads
|
| 36 |
+
- expanded_num_heads: Maximum of num_q_heads, num_k_heads, num_v_heads
|
| 37 |
+
- num_q_groups: Repetition factor for Q heads, computed as expanded_num_heads // num_q_heads
|
| 38 |
+
- num_k_groups: Repetition factor for K heads, computed as expanded_num_heads // num_k_heads
|
| 39 |
+
- num_v_groups: Repetition factor for V heads, computed as expanded_num_heads // num_v_heads
|
| 40 |
+
- query_dim: Total query dimension, num_q_heads * head_dim
|
| 41 |
+
- key_dim: Total key dimension, num_k_heads * head_dim
|
| 42 |
+
- value_dim: Total value dimension, num_v_heads * head_dim
|
| 43 |
+
- expanded_dim: Expanded dimension, expanded_num_heads * head_dim
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
from __future__ import annotations
|
| 47 |
+
|
| 48 |
+
import math
|
| 49 |
+
from typing import TYPE_CHECKING, Any, Optional, Tuple
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
import torch.nn as nn
|
| 53 |
+
from einops import rearrange, repeat
|
| 54 |
+
from torch import Tensor
|
| 55 |
+
from torch.nn import functional as F
|
| 56 |
+
|
| 57 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 58 |
+
from fla.ops.simple_gla import chunk_simple_gla
|
| 59 |
+
from fla.models.utils import Cache
|
| 60 |
+
# from ..sp_p2p_utils import reorder_for_ssm_p2p
|
| 61 |
+
|
| 62 |
+
from ..ops.chebyshev.chunk_dk_backward_gating_sp import compute_kk_final_with_gating
|
| 63 |
+
# from .sequence_parallel.gka_sp_utils import (
|
| 64 |
+
# state_passing_gka_p2p,
|
| 65 |
+
# recompute_with_initial_states,
|
| 66 |
+
# )
|
| 67 |
+
|
| 68 |
+
from ..ops.chebyshev.gka_chebyshev_solve import (
|
| 69 |
+
gka_chebyshev_gla,
|
| 70 |
+
torch_decoding_one_step,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
from typing import Any, Optional
|
| 75 |
+
|
| 76 |
+
import torch
|
| 77 |
+
import torch.nn as nn
|
| 78 |
+
import torch.nn.init as init
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class LinearLowRank(nn.Module):
|
| 82 |
+
"""
|
| 83 |
+
Low-rank linear layer that factorizes a linear projection into two smaller ones:
|
| 84 |
+
y = linearB(act_fn(linearA(x)))
|
| 85 |
+
|
| 86 |
+
where linearA projects from in_features to rank, and linearB projects from rank to out_features.
|
| 87 |
+
|
| 88 |
+
linearB is zero-initialized so that the module outputs zeros at init time. This makes it safe
|
| 89 |
+
to use as a residual branch (e.g. added on top of a repeat/expand) without perturbing the
|
| 90 |
+
pretrained signal at the start of training.
|
| 91 |
+
|
| 92 |
+
Note: linearB is marked with ``_is_hf_initialized = True`` to prevent transformers'
|
| 93 |
+
``post_init`` from overwriting the zero initialization with a random normal.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
in_features: Input dimension.
|
| 97 |
+
out_features: Output dimension.
|
| 98 |
+
rank: Bottleneck dimension between the two linear layers.
|
| 99 |
+
act_fn: Optional activation applied between linearA and linearB. Defaults to Identity.
|
| 100 |
+
bias: Whether to include bias terms in both linear layers. Defaults to False.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
in_features: int,
|
| 106 |
+
out_features: int,
|
| 107 |
+
rank: int,
|
| 108 |
+
act_fn: Optional[Any] = None,
|
| 109 |
+
bias: bool = False,
|
| 110 |
+
):
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.linearA = nn.Linear(in_features, rank, bias=bias)
|
| 113 |
+
self.linearB = nn.Linear(rank, out_features, bias=bias)
|
| 114 |
+
|
| 115 |
+
self.in_features = in_features
|
| 116 |
+
self.out_features = out_features
|
| 117 |
+
self.rank = rank
|
| 118 |
+
self.bias = bias
|
| 119 |
+
self.act_fn = act_fn if act_fn is not None else nn.Identity()
|
| 120 |
+
|
| 121 |
+
# Initialize B weights and bias to zero
|
| 122 |
+
init.zeros_(self.linearB.weight)
|
| 123 |
+
if self.linearB.bias is not None:
|
| 124 |
+
init.zeros_(self.linearB.bias)
|
| 125 |
+
self.linearB._is_hf_initialized = (
|
| 126 |
+
True
|
| 127 |
+
) # prevent transformers' post_init from re-initializing
|
| 128 |
+
|
| 129 |
+
def forward(self, x: torch.Tensor):
|
| 130 |
+
return self.linearB(self.act_fn(self.linearA(x)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class GKANet(nn.Module):
|
| 134 |
+
"""
|
| 135 |
+
GKA layer with Chebyshev solver and GQA support.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
hidden_size: The hidden size of the input. Defaults to 2048.
|
| 139 |
+
head_dim: The dimension of each head. Assumes q/k/v have the same head dimension.
|
| 140 |
+
Defaults to 128.
|
| 141 |
+
num_q_heads: The number of query heads. Defaults to 16.
|
| 142 |
+
num_k_heads: The number of key heads for GQA. If None, defaults to num_q_heads.
|
| 143 |
+
Defaults to None.
|
| 144 |
+
num_v_heads: The number of value heads for GQA. If None, defaults to num_q_heads.
|
| 145 |
+
Defaults to None.
|
| 146 |
+
use_beta_gate: Whether to use beta gating mechanism. Defaults to True.
|
| 147 |
+
use_alpha_connection: Whether to use alpha connection for residual paths. Defaults to True.
|
| 148 |
+
use_v_conv: Whether to apply convolution to value vectors. Defaults to True.
|
| 149 |
+
use_forgetting_gate: Whether to use forgetting gate mechanism. Defaults to True.
|
| 150 |
+
use_forgetting_gate_kk: Whether to use forgetting gate for key-key interactions. Defaults to True.
|
| 151 |
+
gla_rescale: Whether to apply GLA-style rescaling. Defaults to True.
|
| 152 |
+
solver_type: Solver method. Currently, we only support "chebyshev". Defaults to "chebyshev".
|
| 153 |
+
bp_lambda: Whether to backpropagate through lambda parameters. Defaults to True.
|
| 154 |
+
num_iter: Number of iterations for iterative solvers. Defaults to 30.
|
| 155 |
+
ridge_strength: Regularization strength for ridge regression. Defaults to 0.02.
|
| 156 |
+
use_gate: Whether to use output gating mechanism. Defaults to True.
|
| 157 |
+
conv_size: Size of the convolution kernel. Defaults to 4.
|
| 158 |
+
layer_idx: The index of the layer. Used for caching during inference. Defaults to None.
|
| 159 |
+
norm_eps: The epsilon value for the normalization layer. Defaults to 1e-6.
|
| 160 |
+
chunk_size: Size of chunks for parallel processing in Triton kernels. Defaults to 64.
|
| 161 |
+
kv_proj_rank: Rank for low-rank KV projection to expand K/V heads. If None, uses
|
| 162 |
+
standard GQA repeat. Defaults to None.
|
| 163 |
+
kv_learnable_residual: Whether to use a learnable residual for the KV head expansion
|
| 164 |
+
instead of a fixed repeat. Only used when kv_proj_rank is set. Defaults to False.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
hidden_size: int = 2048,
|
| 170 |
+
head_dim: int = 128,
|
| 171 |
+
num_heads: int = 8,
|
| 172 |
+
num_q_heads: Optional[int] = None,
|
| 173 |
+
num_k_heads: Optional[int] = None,
|
| 174 |
+
num_v_heads: Optional[int] = None,
|
| 175 |
+
use_beta_gate: bool = True,
|
| 176 |
+
use_alpha_connection: bool = True,
|
| 177 |
+
use_v_conv: bool = True,
|
| 178 |
+
use_forgetting_gate: bool = True,
|
| 179 |
+
use_forgetting_gate_kk: bool = True,
|
| 180 |
+
gla_rescale: bool = True,
|
| 181 |
+
solver_type: str = "chebyshev",
|
| 182 |
+
bp_lambda: bool = True,
|
| 183 |
+
num_iter: int = 30,
|
| 184 |
+
ridge_strength: float = 0.02,
|
| 185 |
+
use_gate: bool = False,
|
| 186 |
+
conv_size: int = 4,
|
| 187 |
+
layer_idx: Optional[int] = None,
|
| 188 |
+
norm_eps: float = 1e-6,
|
| 189 |
+
chunk_size: int = 64,
|
| 190 |
+
kv_proj_rank: Optional[int] = None,
|
| 191 |
+
kv_learnable_residual: bool = False,
|
| 192 |
+
**kwargs,
|
| 193 |
+
) -> None:
|
| 194 |
+
super().__init__()
|
| 195 |
+
|
| 196 |
+
assert solver_type == "chebyshev", f"Received {solver_type=}. Currently, GKA only supports 'chebyshev' solver."
|
| 197 |
+
|
| 198 |
+
self.hidden_size = hidden_size
|
| 199 |
+
|
| 200 |
+
self.use_gate = use_gate
|
| 201 |
+
self.conv_size = conv_size
|
| 202 |
+
self.sequence_parallel_group = None
|
| 203 |
+
self.chunk_size = chunk_size
|
| 204 |
+
|
| 205 |
+
self.head_dim = head_dim
|
| 206 |
+
self.num_heads = num_heads
|
| 207 |
+
self.num_q_heads = num_q_heads if num_q_heads is not None else num_heads
|
| 208 |
+
self.num_k_heads = num_k_heads if num_k_heads is not None else num_heads
|
| 209 |
+
self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
|
| 210 |
+
self.expanded_num_heads = max(
|
| 211 |
+
self.num_q_heads, self.num_k_heads, self.num_v_heads
|
| 212 |
+
)
|
| 213 |
+
self.num_q_groups = self.expanded_num_heads // self.num_q_heads
|
| 214 |
+
self.num_k_groups = self.expanded_num_heads // self.num_k_heads
|
| 215 |
+
self.num_v_groups = self.expanded_num_heads // self.num_v_heads
|
| 216 |
+
|
| 217 |
+
self.query_dim = self.num_q_heads * self.head_dim
|
| 218 |
+
self.key_dim = self.num_k_heads * self.head_dim
|
| 219 |
+
self.value_dim = self.num_v_heads * self.head_dim
|
| 220 |
+
self.expanded_dim = self.expanded_num_heads * self.head_dim
|
| 221 |
+
|
| 222 |
+
self.layer_idx = layer_idx
|
| 223 |
+
|
| 224 |
+
self.ridge_strength = ridge_strength
|
| 225 |
+
self.num_iter = num_iter
|
| 226 |
+
self.use_beta_gate = use_beta_gate
|
| 227 |
+
self.use_alpha_connection = use_alpha_connection
|
| 228 |
+
self.solver_type = solver_type
|
| 229 |
+
self.bp_lambda = bp_lambda
|
| 230 |
+
self.use_v_conv = use_v_conv
|
| 231 |
+
self.use_forgetting_gate = use_forgetting_gate
|
| 232 |
+
self.use_forgetting_gate_kk = use_forgetting_gate_kk
|
| 233 |
+
|
| 234 |
+
if gla_rescale:
|
| 235 |
+
self.gla_scale = self.head_dim ** -0.5
|
| 236 |
+
else:
|
| 237 |
+
self.gla_scale = 1.0
|
| 238 |
+
|
| 239 |
+
# Projection layers
|
| 240 |
+
self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
|
| 241 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 242 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 243 |
+
|
| 244 |
+
self.a_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=False)
|
| 245 |
+
|
| 246 |
+
self.b_proj = (
|
| 247 |
+
nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 248 |
+
if self.use_beta_gate
|
| 249 |
+
else None
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if self.use_alpha_connection:
|
| 253 |
+
self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 254 |
+
|
| 255 |
+
# Initialize A parameter (log scale)
|
| 256 |
+
A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 257 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 258 |
+
self.A_log._no_weight_decay = True
|
| 259 |
+
|
| 260 |
+
# Initialize dt bias parameter
|
| 261 |
+
dt_min = 0.001
|
| 262 |
+
dt_max = 0.1
|
| 263 |
+
dt_init_floor = 1e-4
|
| 264 |
+
dt = torch.exp(
|
| 265 |
+
torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 266 |
+
+ math.log(dt_min)
|
| 267 |
+
)
|
| 268 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 269 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 270 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 271 |
+
|
| 272 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 273 |
+
self.dt_bias._no_weight_decay = True
|
| 274 |
+
|
| 275 |
+
# Short convolution layers
|
| 276 |
+
self.conv_size = conv_size
|
| 277 |
+
self.q_conv1d = ShortConvolution(
|
| 278 |
+
hidden_size=self.query_dim, kernel_size=conv_size, activation="silu"
|
| 279 |
+
)
|
| 280 |
+
self.k_conv1d = ShortConvolution(
|
| 281 |
+
hidden_size=self.key_dim, kernel_size=conv_size, activation="silu"
|
| 282 |
+
)
|
| 283 |
+
if self.use_v_conv:
|
| 284 |
+
self.v_conv1d = ShortConvolution(
|
| 285 |
+
hidden_size=self.value_dim, kernel_size=conv_size, activation="silu"
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# Output gating and normalization
|
| 289 |
+
if use_gate:
|
| 290 |
+
self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
|
| 291 |
+
self.o_norm = FusedRMSNormGated(self.head_dim, eps=norm_eps)
|
| 292 |
+
else:
|
| 293 |
+
self.o_norm = RMSNorm(self.head_dim, eps=norm_eps)
|
| 294 |
+
self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
|
| 295 |
+
|
| 296 |
+
# Optional KV projection for GQA
|
| 297 |
+
self.kv_proj_rank = kv_proj_rank
|
| 298 |
+
self.kv_learnable_residual = kv_learnable_residual
|
| 299 |
+
if self.kv_proj_rank is not None:
|
| 300 |
+
act_fn = nn.SiLU()
|
| 301 |
+
self.proj_k = LinearLowRank(
|
| 302 |
+
in_features=self.key_dim,
|
| 303 |
+
out_features=self.expanded_num_heads * self.head_dim,
|
| 304 |
+
rank=self.kv_proj_rank,
|
| 305 |
+
act_fn=act_fn,
|
| 306 |
+
)
|
| 307 |
+
self.proj_v = LinearLowRank(
|
| 308 |
+
in_features=self.value_dim,
|
| 309 |
+
out_features=self.expanded_num_heads * self.head_dim,
|
| 310 |
+
rank=self.kv_proj_rank,
|
| 311 |
+
act_fn=act_fn,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
if self.kv_learnable_residual:
|
| 315 |
+
# Learnable mixing matrices initialized to mimic repeat_kv
|
| 316 |
+
eye_k = torch.eye(self.num_k_heads)
|
| 317 |
+
ones_k = torch.ones((self.num_k_groups, 1))
|
| 318 |
+
self.k_rep = nn.Parameter(
|
| 319 |
+
torch.kron(eye_k, ones_k)
|
| 320 |
+
) # [expanded_num_heads, num_k_heads]
|
| 321 |
+
|
| 322 |
+
eye_v = torch.eye(self.num_v_heads)
|
| 323 |
+
ones_v = torch.ones((self.num_v_groups, 1))
|
| 324 |
+
self.v_rep = nn.Parameter(
|
| 325 |
+
torch.kron(eye_v, ones_v)
|
| 326 |
+
) # [expanded_num_heads, num_v_heads]
|
| 327 |
+
|
| 328 |
+
def _expand_kv(self, k: Tensor, v: Tensor) -> Tuple[Tensor, Tensor]:
|
| 329 |
+
"""
|
| 330 |
+
Expand k and v from their native head counts to expanded_num_heads.
|
| 331 |
+
|
| 332 |
+
Three modes:
|
| 333 |
+
1. kv_proj_rank + kv_learnable_residual: learnable mixing residual + low-rank projection
|
| 334 |
+
2. kv_proj_rank without learnable residual: plain repeat residual + low-rank projection
|
| 335 |
+
3. No projection: simple repeat (or rearrange if groups == 1). This is the standard GQA repeat.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
k: [B, L, Dk] raw key tensor (flat, not yet reshaped to heads)
|
| 339 |
+
v: [B, L, Dv] raw value tensor (flat, not yet reshaped to heads)
|
| 340 |
+
|
| 341 |
+
Returns:
|
| 342 |
+
k: [B, L, H, D] expanded keys
|
| 343 |
+
v: [B, L, H, D] expanded values
|
| 344 |
+
"""
|
| 345 |
+
if self.kv_proj_rank is not None and (
|
| 346 |
+
self.num_k_groups > 1 or self.num_v_groups > 1
|
| 347 |
+
):
|
| 348 |
+
# Build residual
|
| 349 |
+
if self.kv_learnable_residual:
|
| 350 |
+
k_heads = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 351 |
+
k_res = torch.einsum("eh,blhd->bled", self.k_rep, k_heads)
|
| 352 |
+
v_heads = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 353 |
+
v_res = torch.einsum("eh,blhd->bled", self.v_rep, v_heads)
|
| 354 |
+
else:
|
| 355 |
+
k_res = repeat(
|
| 356 |
+
rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads),
|
| 357 |
+
"... h d -> ... (h g) d",
|
| 358 |
+
g=self.num_k_groups,
|
| 359 |
+
)
|
| 360 |
+
v_res = repeat(
|
| 361 |
+
rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads),
|
| 362 |
+
"... h d -> ... (h g) d",
|
| 363 |
+
g=self.num_v_groups,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
# Low-rank projection to expanded dim + add residual
|
| 367 |
+
k = (
|
| 368 |
+
rearrange(
|
| 369 |
+
self.proj_k(k), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 370 |
+
)
|
| 371 |
+
+ k_res
|
| 372 |
+
)
|
| 373 |
+
v = (
|
| 374 |
+
rearrange(
|
| 375 |
+
self.proj_v(v), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 376 |
+
)
|
| 377 |
+
+ v_res
|
| 378 |
+
)
|
| 379 |
+
else:
|
| 380 |
+
# Plain rearrange + repeat
|
| 381 |
+
k = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 382 |
+
v = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 383 |
+
if self.num_k_groups > 1:
|
| 384 |
+
k = repeat(k, "... h d -> ... (h g) d", g=self.num_k_groups)
|
| 385 |
+
if self.num_v_groups > 1:
|
| 386 |
+
v = repeat(v, "... h d -> ... (h g) d", g=self.num_v_groups)
|
| 387 |
+
|
| 388 |
+
return k, v
|
| 389 |
+
|
| 390 |
+
def forward(
|
| 391 |
+
self,
|
| 392 |
+
hidden_states: Tensor,
|
| 393 |
+
attention_mask: Optional[Tensor] = None,
|
| 394 |
+
past_key_values: Optional[Cache] = None,
|
| 395 |
+
use_cache: Optional[bool] = False,
|
| 396 |
+
output_attentions: Optional[bool] = False,
|
| 397 |
+
**kwargs,
|
| 398 |
+
) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
|
| 399 |
+
"""
|
| 400 |
+
GKA forward pass with optional caching.
|
| 401 |
+
|
| 402 |
+
NOTE: We use the following variables for tensor shape hints:
|
| 403 |
+
- B: Input batch size
|
| 404 |
+
- L: Sequence length (full sequence length before SP distribution)
|
| 405 |
+
- Dh: Hidden dimension (self.hidden_size)
|
| 406 |
+
- H: Expanded number of heads (self.expanded_num_heads)
|
| 407 |
+
- Hq: Number of query heads (self.num_q_heads)
|
| 408 |
+
- Hk: Number of key heads (self.num_k_heads)
|
| 409 |
+
- Hv: Number of value heads (self.num_v_heads)
|
| 410 |
+
- D: Head dimension (self.head_dim)
|
| 411 |
+
- Dq: Query dimension (self.query_dim)
|
| 412 |
+
- Dk: Key dimension (self.key_dim)
|
| 413 |
+
- Dv: Value dimension (self.value_dim)
|
| 414 |
+
- Dexp: Expanded dimension (self.expanded_dim)
|
| 415 |
+
- C: Convolution size (self.conv_size)
|
| 416 |
+
- SP: Sequence parallel size. 1 if not using sequence parallel
|
| 417 |
+
|
| 418 |
+
- B_sp: Batch size after SP reordering. B_sp = B*2 if self.sequence_parallel_group else B_sp = B
|
| 419 |
+
- L_sp: Sequence length after SP reordering. L_sp = L/(SP*2) + C-1 if self.sequence_parallel_group else L_sp = L/SP
|
| 420 |
+
- Lp: Sequence length after SP reordering and conv padding removal. Lp = L/(SP*2) if self.sequence_parallel_group else Lp = L/SP
|
| 421 |
+
|
| 422 |
+
Args:
|
| 423 |
+
hidden_states: Input tensor with shape [B, L/SP, Dh].
|
| 424 |
+
attention_mask: Optional 0-1 mask. Not used.
|
| 425 |
+
past_key_values: Optional cache containing conv_state and recurrent_state
|
| 426 |
+
for inference. When provided, performs incremental decoding.
|
| 427 |
+
use_cache: Whether to return updated cache states. Defaults to False.
|
| 428 |
+
output_attentions: Whether to return attention weights (not used). Defaults to False.
|
| 429 |
+
**kwargs: Additional keyword arguments, may include cu_seqlens for packed sequences.
|
| 430 |
+
|
| 431 |
+
Returns:
|
| 432 |
+
Tuple of (output, attention_weights, past_key_values) where:
|
| 433 |
+
- output: Output tensor with same shape as hidden_states [B, L, Dh]
|
| 434 |
+
- attention_weights: None (not computed for GKA)
|
| 435 |
+
- past_key_values: Updated cache (same as input if provided, else None)
|
| 436 |
+
"""
|
| 437 |
+
# During inference, if attention_mask is not None, throw an error
|
| 438 |
+
if attention_mask is not None and not self.training:
|
| 439 |
+
raise NotImplementedError(
|
| 440 |
+
"GKA kernels currently do not support varlen inputs."
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 444 |
+
|
| 445 |
+
last_state = None
|
| 446 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 447 |
+
last_state = past_key_values[self.layer_idx]
|
| 448 |
+
|
| 449 |
+
cu_seqlens = kwargs.get("cu_seqlens", None)
|
| 450 |
+
|
| 451 |
+
# Apply P2P reordering to hidden_states first for custom zigzag SP
|
| 452 |
+
# if self.sequence_parallel_group is not None:
|
| 453 |
+
# assert (
|
| 454 |
+
# cu_seqlens is None
|
| 455 |
+
# ), "SP not implemented for cu_seqlens (variable length samples in a batch)."
|
| 456 |
+
# sp_size = torch.distributed.get_world_size(
|
| 457 |
+
# group=self.sequence_parallel_group
|
| 458 |
+
# )
|
| 459 |
+
# sp_rank = torch.distributed.get_rank(group=self.sequence_parallel_group)
|
| 460 |
+
|
| 461 |
+
# hidden_states = reorder_for_ssm_p2p(
|
| 462 |
+
# hidden_states,
|
| 463 |
+
# self.sequence_parallel_group,
|
| 464 |
+
# torch.cuda.Stream(),
|
| 465 |
+
# sp_size,
|
| 466 |
+
# sp_rank,
|
| 467 |
+
# self.conv_size,
|
| 468 |
+
# )
|
| 469 |
+
# # hidden_states: [B_sp, L_sp, Dh]
|
| 470 |
+
|
| 471 |
+
# Apply projections and convolutions
|
| 472 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 473 |
+
if last_state is not None:
|
| 474 |
+
conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
|
| 475 |
+
|
| 476 |
+
q, conv_state_q = self.q_conv1d(
|
| 477 |
+
x=self.q_proj(hidden_states),
|
| 478 |
+
cache=conv_state_q,
|
| 479 |
+
output_final_state=use_cache,
|
| 480 |
+
cu_seqlens=cu_seqlens,
|
| 481 |
+
)
|
| 482 |
+
# q: [B_sp, L_sp, Dq]
|
| 483 |
+
# conv_state_q: [B, Dq, C] or None
|
| 484 |
+
|
| 485 |
+
k, conv_state_k = self.k_conv1d(
|
| 486 |
+
x=self.k_proj(hidden_states),
|
| 487 |
+
cache=conv_state_k,
|
| 488 |
+
output_final_state=use_cache,
|
| 489 |
+
cu_seqlens=cu_seqlens,
|
| 490 |
+
)
|
| 491 |
+
# k: [B_sp, L_sp, Dk]
|
| 492 |
+
# conv_state_k: [B, Dk, C] or None
|
| 493 |
+
|
| 494 |
+
if self.use_v_conv:
|
| 495 |
+
v, conv_state_v = self.v_conv1d(
|
| 496 |
+
x=self.v_proj(hidden_states),
|
| 497 |
+
cache=conv_state_v,
|
| 498 |
+
output_final_state=use_cache,
|
| 499 |
+
cu_seqlens=cu_seqlens,
|
| 500 |
+
)
|
| 501 |
+
# v: [B_sp, L_sp, Dv]
|
| 502 |
+
# conv_state_v: [B, Dv, C] or None
|
| 503 |
+
else:
|
| 504 |
+
v = self.v_proj(hidden_states) # [B_sp, L_sp, Dv]
|
| 505 |
+
conv_state_v = None
|
| 506 |
+
|
| 507 |
+
# Remove padding for custom zigzag SP (first conv_size-1 tokens added by P2P)
|
| 508 |
+
# if self.sequence_parallel_group is not None:
|
| 509 |
+
# q = q[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dq]
|
| 510 |
+
# k = k[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dk]
|
| 511 |
+
# if self.use_v_conv:
|
| 512 |
+
# v = v[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dv]
|
| 513 |
+
# # Also remove padding from hidden_states so beta/alpha/g/gk match seq length
|
| 514 |
+
# hidden_states = hidden_states[
|
| 515 |
+
# :, self.conv_size - 1 :, :
|
| 516 |
+
# ].contiguous() # [B_sp, Lp, Dh]
|
| 517 |
+
|
| 518 |
+
# Reshape q to heads and expand k/v (handles projection + residual if configured)
|
| 519 |
+
q = rearrange(
|
| 520 |
+
q, "... (h d) -> ... h d", h=self.num_q_heads
|
| 521 |
+
) # [B_sp, Lp, Hq, D]
|
| 522 |
+
k, v = self._expand_kv(k, v) # [B_sp, Lp, H, D] each
|
| 523 |
+
|
| 524 |
+
# Apply GQA/head repeats for q to match expanded_num_heads
|
| 525 |
+
if self.num_q_groups > 1:
|
| 526 |
+
q = repeat(q, "... h d -> ... (h g) d", g=self.num_q_groups)
|
| 527 |
+
# q: [B_sp, Lp, H, D]
|
| 528 |
+
|
| 529 |
+
# Get recurrent state from cache
|
| 530 |
+
last_h_kk, last_h_kv = (
|
| 531 |
+
last_state["recurrent_state"] if last_state is not None else (None, None)
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
# Normalize queries and keys
|
| 535 |
+
qk_norm_eps = 1e-6
|
| 536 |
+
q = q / (
|
| 537 |
+
torch.linalg.vector_norm(q, dim=-1, keepdim=True).to(q) + qk_norm_eps
|
| 538 |
+
) # [B_sp, Lp, H, D]
|
| 539 |
+
k = k / (
|
| 540 |
+
torch.linalg.vector_norm(k, dim=-1, keepdim=True).to(k) + qk_norm_eps
|
| 541 |
+
) # [B_sp, Lp, H, D]
|
| 542 |
+
|
| 543 |
+
# Apply beta gating if enabled
|
| 544 |
+
if self.use_beta_gate:
|
| 545 |
+
beta = self.b_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 546 |
+
eps = 1e-6
|
| 547 |
+
k = ((beta[..., None] + eps) * k).to(k.dtype) # [B_sp, Lp, H, D]
|
| 548 |
+
v = ((beta[..., None] + eps) * v).to(v.dtype) # [B_sp, Lp, H, D]
|
| 549 |
+
|
| 550 |
+
# Compute alpha connection parameter
|
| 551 |
+
if self.use_alpha_connection:
|
| 552 |
+
alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 553 |
+
else:
|
| 554 |
+
alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
|
| 555 |
+
|
| 556 |
+
# Compute forgetting gate
|
| 557 |
+
if self.use_forgetting_gate:
|
| 558 |
+
g = -self.A_log.float().exp() * F.softplus(
|
| 559 |
+
self.a_proj(hidden_states).float() + self.dt_bias
|
| 560 |
+
) # [B_sp, Lp, H]
|
| 561 |
+
else:
|
| 562 |
+
g = None
|
| 563 |
+
|
| 564 |
+
gk = g if self.use_forgetting_gate_kk else None
|
| 565 |
+
|
| 566 |
+
# Backward kernels require sequence length to be divisible by chunk size
|
| 567 |
+
if gk is None and self.training:
|
| 568 |
+
seq_len = hidden_states.shape[1]
|
| 569 |
+
assert (
|
| 570 |
+
seq_len % self.chunk_size == 0
|
| 571 |
+
), f"Triton chunk size must divide the sequence length. Got seq_len={seq_len}, chunk_size={self.chunk_size}"
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
# Apply GKA Chebyshev solver
|
| 575 |
+
if last_state is None:
|
| 576 |
+
# if self.sequence_parallel_group is not None:
|
| 577 |
+
# # Custom zigzag SP: Compute h_kk first, pass states, then compute rest
|
| 578 |
+
|
| 579 |
+
# # 1. Compute h_kk locally (just k @ k^T cumsum) with zero initial state
|
| 580 |
+
# k_proj = k # [B_sp, Lp, H, D]
|
| 581 |
+
|
| 582 |
+
# if gk is not None:
|
| 583 |
+
# # For state passing, we only need the sum (equivalent to cumsum[-1])
|
| 584 |
+
# gkk_final = torch.sum(gk, dim=1) # [B_sp, H]
|
| 585 |
+
# else:
|
| 586 |
+
# gkk_final = torch.zeros(
|
| 587 |
+
# q.shape[0],
|
| 588 |
+
# self.expanded_num_heads,
|
| 589 |
+
# device=q.device,
|
| 590 |
+
# dtype=q.dtype,
|
| 591 |
+
# )
|
| 592 |
+
|
| 593 |
+
# # Extract g sum (total decay across chunk)
|
| 594 |
+
# if g is not None:
|
| 595 |
+
# g_cumsum_last = torch.sum(g, dim=1) # [B_sp, H]
|
| 596 |
+
# else:
|
| 597 |
+
# g_cumsum_last = None
|
| 598 |
+
|
| 599 |
+
# # Compute h_kk: cumsum of k @ k^T with gating
|
| 600 |
+
# with torch.cuda.device(q.device):
|
| 601 |
+
# if self.num_iter > 0:
|
| 602 |
+
# kk_final = compute_kk_final_with_gating(
|
| 603 |
+
# k_proj, gk, chunk_size=self.chunk_size
|
| 604 |
+
# )
|
| 605 |
+
# else:
|
| 606 |
+
# kk_final = torch.zeros(
|
| 607 |
+
# k_proj.shape[0],
|
| 608 |
+
# self.expanded_num_heads,
|
| 609 |
+
# k_proj.shape[3],
|
| 610 |
+
# k_proj.shape[3],
|
| 611 |
+
# device=q.device,
|
| 612 |
+
# dtype=q.dtype,
|
| 613 |
+
# )
|
| 614 |
+
# # kk_final: [B_sp, H, D, D]
|
| 615 |
+
|
| 616 |
+
# # Compute h_kv locally to get final state
|
| 617 |
+
# _, h_kv_final = chunk_simple_gla(
|
| 618 |
+
# q=q,
|
| 619 |
+
# k=k,
|
| 620 |
+
# v=v,
|
| 621 |
+
# scale=self.gla_scale,
|
| 622 |
+
# g=g,
|
| 623 |
+
# output_final_state=True,
|
| 624 |
+
# )
|
| 625 |
+
# # h_kv_final: [B_sp, H, D, D]
|
| 626 |
+
|
| 627 |
+
# # 2. Pass states via P2P in zigzag pattern
|
| 628 |
+
# bs = q.shape[0] # Batch size (B_sp, includes both chunks per GPU)
|
| 629 |
+
|
| 630 |
+
# # Ensure all inputs to state_passing are on the same device
|
| 631 |
+
# with torch.cuda.device(q.device):
|
| 632 |
+
# prev_kk, prev_h_kv = state_passing_gka_p2p(
|
| 633 |
+
# kk_final.to(q.device),
|
| 634 |
+
# gkk_final.to(q.device), # Local only, used for decay
|
| 635 |
+
# h_kv_final.to(q.device),
|
| 636 |
+
# g_cumsum_last.to(q.device)
|
| 637 |
+
# if g_cumsum_last is not None
|
| 638 |
+
# else None,
|
| 639 |
+
# self.sequence_parallel_group,
|
| 640 |
+
# sp_rank,
|
| 641 |
+
# sp_size,
|
| 642 |
+
# bs,
|
| 643 |
+
# )
|
| 644 |
+
# # prev_kk: [B_sp, H, D, D]
|
| 645 |
+
# # prev_h_kv: [B_sp, H, D, D]
|
| 646 |
+
|
| 647 |
+
# # 3. Now recompute with initial states from previous chunk
|
| 648 |
+
# # Ensure all tensors are on the same device before calling recompute
|
| 649 |
+
# with torch.cuda.device(q.device):
|
| 650 |
+
# o, h_kk, h_kv = recompute_with_initial_states(
|
| 651 |
+
# q=q,
|
| 652 |
+
# k=k,
|
| 653 |
+
# v=v,
|
| 654 |
+
# alpha=alpha,
|
| 655 |
+
# g=g,
|
| 656 |
+
# gk=gk,
|
| 657 |
+
# prev_kk=prev_kk.to(q.device),
|
| 658 |
+
# prev_h_kv=prev_h_kv.to(q.device),
|
| 659 |
+
# gla_scale=self.gla_scale,
|
| 660 |
+
# ridge_strength=self.ridge_strength,
|
| 661 |
+
# solver_type=self.solver_type,
|
| 662 |
+
# num_iter=self.num_iter,
|
| 663 |
+
# bp_lambda=self.bp_lambda,
|
| 664 |
+
# chunk_size=self.chunk_size,
|
| 665 |
+
# )
|
| 666 |
+
# # o: [B_sp, Lp, H, D]
|
| 667 |
+
# # h_kk: [B_sp, H, D, D]
|
| 668 |
+
# # h_kv: [B_sp, H, D, D]
|
| 669 |
+
# else:
|
| 670 |
+
# with torch.cuda.device(q.device):
|
| 671 |
+
o, h_kk, h_kv = gka_chebyshev_gla(
|
| 672 |
+
q=q,
|
| 673 |
+
k=k,
|
| 674 |
+
v=v,
|
| 675 |
+
alpha=alpha,###this alpha_connect
|
| 676 |
+
g=g,
|
| 677 |
+
gk=gk,
|
| 678 |
+
gla_scale=self.gla_scale,
|
| 679 |
+
ridge_strength=self.ridge_strength,
|
| 680 |
+
solver_type=self.solver_type,
|
| 681 |
+
num_iter=self.num_iter,
|
| 682 |
+
bp_lambda=self.bp_lambda,
|
| 683 |
+
chunk_size=self.chunk_size,
|
| 684 |
+
)
|
| 685 |
+
# o: [B_sp, Lp, H, D]
|
| 686 |
+
# h_kk: [B_sp, H, D, D]
|
| 687 |
+
# h_kv: [B_sp, H, D, D]
|
| 688 |
+
else:
|
| 689 |
+
# with torch.cuda.device(q.device):
|
| 690 |
+
o, h_kk, h_kv = torch_decoding_one_step(
|
| 691 |
+
q=q.squeeze(0),
|
| 692 |
+
k=k.squeeze(0),
|
| 693 |
+
v=v.squeeze(0),
|
| 694 |
+
alpha=alpha.squeeze(0),
|
| 695 |
+
g=g,
|
| 696 |
+
gk=gk,
|
| 697 |
+
gla_scale=self.gla_scale,
|
| 698 |
+
ridge_strength=self.ridge_strength,
|
| 699 |
+
solver_type=self.solver_type,
|
| 700 |
+
num_iter=self.num_iter,
|
| 701 |
+
prev_h_kk=last_h_kk,
|
| 702 |
+
prev_h_kv=last_h_kv,
|
| 703 |
+
)
|
| 704 |
+
# o: [Lp, H, D] (batch squeezed)
|
| 705 |
+
# h_kk: [H, D, D]
|
| 706 |
+
# h_kv: [H, D, D]
|
| 707 |
+
if len(o.shape) == 3:
|
| 708 |
+
o = o.unsqueeze(0) # [1, Lp, H, D]
|
| 709 |
+
|
| 710 |
+
o = o.to(q)
|
| 711 |
+
|
| 712 |
+
# Update cache
|
| 713 |
+
if past_key_values is not None:
|
| 714 |
+
past_key_values.update(
|
| 715 |
+
recurrent_state=(h_kk, h_kv),
|
| 716 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v),
|
| 717 |
+
layer_idx=self.layer_idx,
|
| 718 |
+
offset=q_len,
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
# Apply output gating and normalization
|
| 722 |
+
if self.use_gate:
|
| 723 |
+
g = rearrange(
|
| 724 |
+
self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim
|
| 725 |
+
) # [B_sp, Lp, H, D]
|
| 726 |
+
o = self.o_norm(o, g) # [B_sp, Lp, H, D]
|
| 727 |
+
else:
|
| 728 |
+
o = self.o_norm(o) # [B_sp, Lp, H, D]
|
| 729 |
+
|
| 730 |
+
# Reshape and project output
|
| 731 |
+
o = rearrange(o, "b t h d -> b t (h d)") # [B_sp, Lp, Dexp]
|
| 732 |
+
o = self.o_proj(o) # [B_sp, Lp, Dh]
|
| 733 |
+
|
| 734 |
+
# Scatter sequence if using sequence parallel
|
| 735 |
+
# if self.sequence_parallel_group is not None:
|
| 736 |
+
# # Recombine zigzag chunks to contiguous
|
| 737 |
+
# bz, len_o, dim = o.shape
|
| 738 |
+
# if bz == 2:
|
| 739 |
+
# o = o.view(bz // 2, len_o * 2, dim)
|
| 740 |
+
# else:
|
| 741 |
+
# o = torch.cat([o[: bz // 2], o[bz // 2 :]], dim=1).contiguous()
|
| 742 |
+
# o: [B, L/SP, Dh]
|
| 743 |
+
|
| 744 |
+
return o, None, past_key_values
|
layers/gka_attn.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 15 |
+
from fla.modules import RMSNorm, RotaryEmbedding
|
| 16 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 17 |
+
from fla.models.utils import Cache
|
| 18 |
+
|
| 19 |
+
from ..ops.chebyshev.chebyshev_iteration import ChebyshevIteration
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
import math
|
| 24 |
+
from torch.nn import functional as F
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 28 |
+
except ImportError:
|
| 29 |
+
warnings.warn(
|
| 30 |
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
| 31 |
+
category=ImportWarning
|
| 32 |
+
)
|
| 33 |
+
flash_attn_func = None
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@torch.compiler.disable
|
| 40 |
+
def latent_chebyshev(
|
| 41 |
+
k, q, ridge_strength=0.02, num_iter=30, solver_type="chebyshev", bp_lambda=True, gk=None, chunk_size=64
|
| 42 |
+
):
|
| 43 |
+
"""
|
| 44 |
+
Dispatcher for ridge regression solvers: (H_t + λI)·x_t = q_t.
|
| 45 |
+
|
| 46 |
+
Routes to different solver implementations based on solver_type. All solvers
|
| 47 |
+
aim to solve the same problem but with different speed/accuracy tradeoffs.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
k: Key tensor with shape [B, L, H, D]
|
| 51 |
+
q: Query tensor with shape [B, L, H, D]
|
| 52 |
+
ridge_strength: Regularization parameter λ
|
| 53 |
+
num_iter: Number of iterations for iterative solvers
|
| 54 |
+
solver_type: Solver method. Currently only supports 'chebyshev'.
|
| 55 |
+
bp_lambda: Whether to backprop through λ (for Chebyshev solvers)
|
| 56 |
+
gk: Forgetting gate for key-key covariance with shape [B, L, H]
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
x: Solution tensor with shape [B, L, H, D]
|
| 60 |
+
kk_final: Final key-key covariance H_T with shape [B, H, D, D]
|
| 61 |
+
"""
|
| 62 |
+
if solver_type == "chebyshev":
|
| 63 |
+
x, kk_final = ChebyshevIteration.apply(
|
| 64 |
+
k, q, gk, num_iter, ridge_strength, bp_lambda, None, chunk_size
|
| 65 |
+
)
|
| 66 |
+
else:
|
| 67 |
+
raise ValueError(f"Unknown GKA solver type: {solver_type}")
|
| 68 |
+
|
| 69 |
+
return x, kk_final
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# from ..ops.chebyshev.gka_chebyshev_solve import (
|
| 73 |
+
# gka_chebyshev_gla,
|
| 74 |
+
# torch_decoding_one_step,
|
| 75 |
+
# )
|
| 76 |
+
|
| 77 |
+
from ..ops.chebyshev.gka_chebyshev_solve import chebyshev_iteration_forward_triton_inference
|
| 78 |
+
# from ..ops.phi_kkt_approx.phi_kkt_solve import phi_kkt_solve
|
| 79 |
+
from ..ops.phi_kkt_approx.q_kkt_solve_abc import q_kkt_solve_approx as q_kkt_solve_approx_abc
|
| 80 |
+
class GKAAttention(nn.Module):
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
hidden_size: int = 2048,
|
| 84 |
+
num_heads: int = 8,
|
| 85 |
+
num_kv_heads: Optional[int] = None,
|
| 86 |
+
qkv_bias: bool = False,
|
| 87 |
+
qk_norm: bool = False,
|
| 88 |
+
window_size: Optional[int] = None,
|
| 89 |
+
rope_theta: Optional[float] = 10000.,
|
| 90 |
+
max_position_embeddings: Optional[int] = None,
|
| 91 |
+
layer_idx: int = None,
|
| 92 |
+
use_alpha_connection: bool = False,
|
| 93 |
+
learnable_abc: Tuple[float, ...] = (1.0, -0.5, 0.375),
|
| 94 |
+
random_init_abc: bool = True,
|
| 95 |
+
abc_requires_grad: bool = True,
|
| 96 |
+
**kwargs,
|
| 97 |
+
):
|
| 98 |
+
super().__init__()
|
| 99 |
+
|
| 100 |
+
self.hidden_size = hidden_size
|
| 101 |
+
self.num_heads = num_heads
|
| 102 |
+
if num_kv_heads is None:
|
| 103 |
+
self.num_kv_heads = self.num_heads
|
| 104 |
+
else:
|
| 105 |
+
self.num_kv_heads = num_kv_heads
|
| 106 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 107 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 108 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 109 |
+
self.qkv_bias = qkv_bias
|
| 110 |
+
self.qk_norm = qk_norm
|
| 111 |
+
|
| 112 |
+
self.use_alpha_connection = use_alpha_connection
|
| 113 |
+
self.window_size = window_size
|
| 114 |
+
self.rope_theta = rope_theta
|
| 115 |
+
self.max_position_embeddings = max_position_embeddings
|
| 116 |
+
self.layer_idx = layer_idx
|
| 117 |
+
|
| 118 |
+
if flash_attn_func is None:
|
| 119 |
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
| 120 |
+
|
| 121 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
| 122 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 123 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 124 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 125 |
+
|
| 126 |
+
if qk_norm:
|
| 127 |
+
self.q_norm = RMSNorm(self.head_dim)
|
| 128 |
+
self.k_norm = RMSNorm(self.head_dim)
|
| 129 |
+
|
| 130 |
+
self.expanded_num_heads = max(self.num_heads, self.num_kv_heads)
|
| 131 |
+
|
| 132 |
+
self.a_proj = nn.Linear(self.hidden_size, self.expanded_num_heads, bias=False)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if self.use_alpha_connection:
|
| 136 |
+
self.alpha_proj = nn.Linear(self.hidden_size, self.expanded_num_heads, bias=True)
|
| 137 |
+
|
| 138 |
+
# A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 139 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 140 |
+
# self.A_log._no_weight_decay = True
|
| 141 |
+
|
| 142 |
+
# # Initialize dt bias parameter
|
| 143 |
+
# dt_min = 0.001
|
| 144 |
+
# dt_max = 0.1
|
| 145 |
+
# dt_init_floor = 1e-4
|
| 146 |
+
# dt = torch.exp(
|
| 147 |
+
# torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 148 |
+
# + math.log(dt_min)
|
| 149 |
+
# )
|
| 150 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 151 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 152 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 153 |
+
|
| 154 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 155 |
+
# self.dt_bias._no_weight_decay = True
|
| 156 |
+
init_abc = torch.tensor(learnable_abc, dtype=torch.float32).reshape(-1)
|
| 157 |
+
n_coeff = int(init_abc.numel())
|
| 158 |
+
if n_coeff not in (3, 4):
|
| 159 |
+
raise ValueError(
|
| 160 |
+
f"learnable_abc must have 3 (abc) or 4 (abcd) coefficients, got {n_coeff}"
|
| 161 |
+
)
|
| 162 |
+
self.learnable_abc = nn.Parameter(
|
| 163 |
+
init_abc.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous()
|
| 164 |
+
)
|
| 165 |
+
if random_init_abc:
|
| 166 |
+
# a, c ~ U(0, 1); b, d ~ U(-1, 0)
|
| 167 |
+
signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
|
| 168 |
+
self.learnable_abc = nn.Parameter(
|
| 169 |
+
(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
|
| 170 |
+
)
|
| 171 |
+
print("random init abc")
|
| 172 |
+
print(self.learnable_abc)
|
| 173 |
+
print(self.learnable_abc.requires_grad)
|
| 174 |
+
else:
|
| 175 |
+
print("not random init abc")
|
| 176 |
+
print(self.learnable_abc)
|
| 177 |
+
print(self.learnable_abc.requires_grad)
|
| 178 |
+
self.learnable_abc._no_weight_decay = True
|
| 179 |
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
| 180 |
+
|
| 181 |
+
def forward(
|
| 182 |
+
self,
|
| 183 |
+
hidden_states: torch.Tensor,
|
| 184 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 185 |
+
past_key_values: Optional[Cache] = None,
|
| 186 |
+
output_attentions: bool = False,
|
| 187 |
+
use_cache: bool = False,
|
| 188 |
+
**kwargs,
|
| 189 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 190 |
+
if attention_mask is not None:
|
| 191 |
+
assert len(attention_mask.shape) == 2, (
|
| 192 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 193 |
+
"for padding purposes (0 indicating padding). "
|
| 194 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# g = -self.A_log.float().exp() * F.softplus(
|
| 202 |
+
# self.a_proj(hidden_states).float() + self.dt_bias
|
| 203 |
+
# ) # [B_sp, Lp, H]
|
| 204 |
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 205 |
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 206 |
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 207 |
+
|
| 208 |
+
if self.qk_norm:
|
| 209 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 210 |
+
|
| 211 |
+
if self.use_alpha_connection:
|
| 212 |
+
alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 213 |
+
else:
|
| 214 |
+
alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
|
| 215 |
+
|
| 216 |
+
# equivalent to cu_seqlens in `flash_attn`
|
| 217 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 221 |
+
if past_key_values is not None:
|
| 222 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 223 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 224 |
+
if attention_mask is not None:
|
| 225 |
+
# to deliminate the offsets of padding tokens
|
| 226 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 227 |
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
| 228 |
+
###这里应该改成cu_seqlens
|
| 229 |
+
last_state_h_kk = None
|
| 230 |
+
if past_key_values is not None:
|
| 231 |
+
last_state_h_kk = past_key_values[self.layer_idx]["recurrent_state"]
|
| 232 |
+
|
| 233 |
+
if self.max_position_embeddings is not None:
|
| 234 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 235 |
+
gk = torch.zeros(batch_size, q_len, self.expanded_num_heads, device=q.device, dtype=torch.float32)
|
| 236 |
+
q_, last_state_h_kk = q_kkt_solve_approx_abc.apply(
|
| 237 |
+
k, q, gk, 64, self.learnable_abc.to(torch.float32)
|
| 238 |
+
)
|
| 239 |
+
# if last_state_h_kk is None:
|
| 240 |
+
# q_, last_state_h_kk = latent_chebyshev(
|
| 241 |
+
# k, q, ridge_strength=0.02, num_iter=30, solver_type="chebyshev", bp_lambda=True, gk=g, chunk_size=64
|
| 242 |
+
# )
|
| 243 |
+
# else:
|
| 244 |
+
# q_, last_state_h_kk = chebyshev_iteration_forward_triton_inference(
|
| 245 |
+
# last_state_h_kk, k, q, g, num_iter=30, ridge_ratio=0.02
|
| 246 |
+
# )###这个为啥不考虑用wd变换替代
|
| 247 |
+
# q = q + alpha[..., None] * (q_ - q) # Equivalent to ⍺q_ + (1-⍺)q
|
| 248 |
+
q = q_
|
| 249 |
+
# q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 250 |
+
if past_key_values is not None:
|
| 251 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 252 |
+
k_cached, v_cached = past_key_values.update(
|
| 253 |
+
recurrent_state=last_state_h_kk,
|
| 254 |
+
attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)),
|
| 255 |
+
layer_idx=self.layer_idx,
|
| 256 |
+
offset=q_len,
|
| 257 |
+
cache_kwargs=dict(window_size=self.window_size)
|
| 258 |
+
)['attn_state']
|
| 259 |
+
if cache_has_content:
|
| 260 |
+
k, v = k_cached, v_cached
|
| 261 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 262 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 263 |
+
|
| 264 |
+
# Contains at least one padding token in the sequence
|
| 265 |
+
if attention_mask is not None:
|
| 266 |
+
if q.shape[1] == 1 and self.window_size is not None:
|
| 267 |
+
attention_mask = attention_mask[:, -self.window_size:]
|
| 268 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len)
|
| 269 |
+
cu_seqlens_q, cu_seqlens_k = cu_seqlens
|
| 270 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 271 |
+
o = flash_attn_varlen_func(
|
| 272 |
+
q, k, v,
|
| 273 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 274 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 275 |
+
max_seqlen_q=max_seqlen_q,
|
| 276 |
+
max_seqlen_k=max_seqlen_k,
|
| 277 |
+
causal=True,
|
| 278 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 279 |
+
)
|
| 280 |
+
o = pad_input(o, indices_q, batch_size, q_len)
|
| 281 |
+
elif cu_seqlens is not None:
|
| 282 |
+
o = flash_attn_varlen_func(
|
| 283 |
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
| 284 |
+
cu_seqlens_q=cu_seqlens,
|
| 285 |
+
cu_seqlens_k=cu_seqlens,
|
| 286 |
+
max_seqlen_q=max_seqlen,
|
| 287 |
+
max_seqlen_k=max_seqlen,
|
| 288 |
+
causal=True,
|
| 289 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 290 |
+
).unsqueeze(0)
|
| 291 |
+
else:
|
| 292 |
+
o = flash_attn_func(
|
| 293 |
+
q, k, v,
|
| 294 |
+
causal=True,
|
| 295 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 296 |
+
)
|
| 297 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 298 |
+
o = self.o_proj(o)
|
| 299 |
+
|
| 300 |
+
if not output_attentions:
|
| 301 |
+
attentions = None
|
| 302 |
+
|
| 303 |
+
return o, attentions, past_key_values
|
layers/gla.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from einops import rearrange, repeat
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 15 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 16 |
+
from fla.modules.activations import ACT2FN
|
| 17 |
+
from fla.ops.gla import chunk_gla, fused_chunk_gla
|
| 18 |
+
from ..ops.gla import fused_recurrent_gla
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from transformers.processing_utils import Unpack
|
| 22 |
+
|
| 23 |
+
from fla.models.utils import Cache
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class GatedLinearAttention(nn.Module):
|
| 27 |
+
r"""
|
| 28 |
+
The layer implementaion for [Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635). # noqa
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
mode (str, Optional):
|
| 32 |
+
Which GLA kernel to use.
|
| 33 |
+
Currently available: `chunk`, `fused_recurrent`, and `fused_chunk`.
|
| 34 |
+
Default: `chunk`.
|
| 35 |
+
hidden_size (int, Optional):
|
| 36 |
+
The hidden size of the input. Default: 1024.
|
| 37 |
+
expand_k (float, Optional):
|
| 38 |
+
The expansion ratio for the key dim. Default: 0.5.
|
| 39 |
+
expand_v (float, Optional):
|
| 40 |
+
The expansion ratio for the value dim. Default: 1.0.
|
| 41 |
+
num_heads (int, Optional):
|
| 42 |
+
The number of heads. Default: 4.
|
| 43 |
+
num_kv_heads (int, Optional):
|
| 44 |
+
The number of key/value heads, used for MQA. Default: None.
|
| 45 |
+
feature_map (str, Optional):
|
| 46 |
+
Feature map function applied to queries/keys. Default: None.
|
| 47 |
+
use_short_conv (bool, Optional):
|
| 48 |
+
Whether to use short convolutions. Default: `False`.
|
| 49 |
+
conv_size (int, Optional):
|
| 50 |
+
The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
|
| 51 |
+
conv_bias (bool, Optional):
|
| 52 |
+
Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
|
| 53 |
+
use_output_gate (bool, Optional):
|
| 54 |
+
Whether to use output gate. Default: `True`.
|
| 55 |
+
gate_fn (str, Optional):
|
| 56 |
+
The activation function for the output gate. Default: `swish`.
|
| 57 |
+
elementwise_affine (bool, Optional):
|
| 58 |
+
If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`.
|
| 59 |
+
norm_eps (float, Optional):
|
| 60 |
+
The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5.
|
| 61 |
+
gate_logit_normalizer (int, Optional):
|
| 62 |
+
The normalizer for the gate logits, appied after `logsigmoid`. Default: 16.
|
| 63 |
+
gate_low_rank_dim (int, Optional):
|
| 64 |
+
The low rank dim for the gate projection. Default: 16.
|
| 65 |
+
clamp_min (float, Optional):
|
| 66 |
+
The minimum value for the gate logits. Default: None.
|
| 67 |
+
fuse_norm (bool, Optional):
|
| 68 |
+
Whether to fuse the norm and the output gate for better memory footprint. Default: `True`.
|
| 69 |
+
layer_idx (int, Optional):
|
| 70 |
+
The index of the layer. Default: None.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
mode: str = 'chunk',
|
| 76 |
+
hidden_size: int = 1024,
|
| 77 |
+
expand_k: float = 0.5,
|
| 78 |
+
expand_v: float = 1.0,
|
| 79 |
+
num_heads: int = 4,
|
| 80 |
+
num_kv_heads: Optional[int] = None,
|
| 81 |
+
feature_map: Optional[str] = None,
|
| 82 |
+
use_short_conv: bool = False,
|
| 83 |
+
conv_size: int = 4,
|
| 84 |
+
conv_bias: bool = False,
|
| 85 |
+
use_output_gate: bool = True,
|
| 86 |
+
gate_fn: str = 'swish',
|
| 87 |
+
elementwise_affine: Optional[bool] = True,
|
| 88 |
+
norm_eps: float = 1e-5,
|
| 89 |
+
gate_logit_normalizer: int = 16,
|
| 90 |
+
gate_low_rank_dim: int = 16,
|
| 91 |
+
clamp_min: Optional[float] = None,
|
| 92 |
+
fuse_norm: bool = True,
|
| 93 |
+
layer_idx: int = None,
|
| 94 |
+
) -> GatedLinearAttention:
|
| 95 |
+
super().__init__()
|
| 96 |
+
|
| 97 |
+
self.mode = mode
|
| 98 |
+
self.hidden_size = hidden_size
|
| 99 |
+
self.expand_k = expand_k
|
| 100 |
+
self.expand_v = expand_v
|
| 101 |
+
self.num_heads = num_heads
|
| 102 |
+
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
| 103 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 104 |
+
self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
|
| 105 |
+
|
| 106 |
+
self.use_short_conv = use_short_conv
|
| 107 |
+
self.conv_size = conv_size
|
| 108 |
+
self.conv_bias = conv_bias
|
| 109 |
+
self.use_output_gate = use_output_gate
|
| 110 |
+
|
| 111 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 112 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 113 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 114 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 115 |
+
self.clamp_min = clamp_min
|
| 116 |
+
self.layer_idx = layer_idx
|
| 117 |
+
|
| 118 |
+
assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`."
|
| 119 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 120 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 121 |
+
|
| 122 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 123 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 124 |
+
|
| 125 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 126 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
|
| 127 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
|
| 128 |
+
if self.use_output_gate:
|
| 129 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 130 |
+
|
| 131 |
+
if use_short_conv:
|
| 132 |
+
self.conv_size = conv_size
|
| 133 |
+
self.q_conv1d = ShortConvolution(
|
| 134 |
+
hidden_size=self.key_dim,
|
| 135 |
+
kernel_size=conv_size,
|
| 136 |
+
bias=conv_bias,
|
| 137 |
+
activation='silu',
|
| 138 |
+
)
|
| 139 |
+
self.k_conv1d = ShortConvolution(
|
| 140 |
+
hidden_size=self.key_dim_per_group,
|
| 141 |
+
kernel_size=conv_size,
|
| 142 |
+
bias=conv_bias,
|
| 143 |
+
activation='silu',
|
| 144 |
+
)
|
| 145 |
+
self.v_conv1d = ShortConvolution(
|
| 146 |
+
hidden_size=self.value_dim_per_group,
|
| 147 |
+
kernel_size=conv_size,
|
| 148 |
+
bias=conv_bias,
|
| 149 |
+
activation='silu',
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
self.gk_proj = nn.Sequential(nn.Linear(hidden_size, gate_low_rank_dim, bias=False),
|
| 153 |
+
nn.Linear(gate_low_rank_dim, self.key_dim_per_group, bias=True))
|
| 154 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 155 |
+
|
| 156 |
+
if gate_fn == 'swish' and fuse_norm and use_output_gate:
|
| 157 |
+
self.g_norm_swish_gate = FusedRMSNormGated(
|
| 158 |
+
hidden_size=self.head_v_dim,
|
| 159 |
+
elementwise_affine=elementwise_affine,
|
| 160 |
+
eps=norm_eps
|
| 161 |
+
)
|
| 162 |
+
self.fuse_norm_and_gate = True
|
| 163 |
+
else:
|
| 164 |
+
self.fuse_norm_and_gate = False
|
| 165 |
+
self.g_norm = RMSNorm(
|
| 166 |
+
hidden_size=self.head_v_dim,
|
| 167 |
+
elementwise_affine=elementwise_affine,
|
| 168 |
+
eps=norm_eps
|
| 169 |
+
)
|
| 170 |
+
self.gate_fn = ACT2FN[gate_fn]
|
| 171 |
+
|
| 172 |
+
self.gate_logit_normalizer = gate_logit_normalizer
|
| 173 |
+
|
| 174 |
+
def forward(
|
| 175 |
+
self,
|
| 176 |
+
hidden_states: torch.Tensor,
|
| 177 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 178 |
+
past_key_values: Optional[Cache] = None,
|
| 179 |
+
use_cache: Optional[bool] = False,
|
| 180 |
+
output_attentions: Optional[bool] = False,
|
| 181 |
+
**kwargs: Unpack[Dict]
|
| 182 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 183 |
+
if attention_mask is not None:
|
| 184 |
+
assert len(attention_mask.shape) == 2, (
|
| 185 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 186 |
+
"for padding purposes (0 indicating padding). "
|
| 187 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 191 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 192 |
+
|
| 193 |
+
last_state = None
|
| 194 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 195 |
+
last_state = past_key_values[self.layer_idx]
|
| 196 |
+
|
| 197 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 198 |
+
if attention_mask is not None:
|
| 199 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 200 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 201 |
+
|
| 202 |
+
if self.use_short_conv:
|
| 203 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 204 |
+
if last_state is not None:
|
| 205 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 206 |
+
q, conv_state_q = self.q_conv1d(
|
| 207 |
+
x=self.q_proj(hidden_states),
|
| 208 |
+
cache=conv_state_q,
|
| 209 |
+
output_final_state=use_cache,
|
| 210 |
+
cu_seqlens=cu_seqlens
|
| 211 |
+
)
|
| 212 |
+
k, conv_state_k = self.k_conv1d(
|
| 213 |
+
x=self.k_proj(hidden_states),
|
| 214 |
+
cache=conv_state_k,
|
| 215 |
+
output_final_state=use_cache,
|
| 216 |
+
cu_seqlens=cu_seqlens
|
| 217 |
+
)
|
| 218 |
+
v, conv_state_v = self.v_conv1d(
|
| 219 |
+
x=self.v_proj(hidden_states),
|
| 220 |
+
cache=conv_state_v,
|
| 221 |
+
output_final_state=use_cache,
|
| 222 |
+
cu_seqlens=cu_seqlens
|
| 223 |
+
)
|
| 224 |
+
else:
|
| 225 |
+
q = self.q_proj(hidden_states)
|
| 226 |
+
k = self.k_proj(hidden_states)
|
| 227 |
+
v = self.v_proj(hidden_states)
|
| 228 |
+
gk = self.gk_proj(hidden_states)
|
| 229 |
+
|
| 230 |
+
if self.feature_map_fn is not None:
|
| 231 |
+
q, k = map(self.feature_map_fn, (q, k))
|
| 232 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 233 |
+
if self.num_kv_groups > 1:
|
| 234 |
+
k, gk = (repeat(x, '... (h d) -> ... (h g) d', g=self.num_kv_groups, d=self.head_k_dim) for x in (k, gk))
|
| 235 |
+
v = repeat(v, '... (h d) -> ... (h g) d', g=self.num_kv_groups, d=self.head_v_dim)
|
| 236 |
+
else:
|
| 237 |
+
k, gk = (rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim) for x in (k, gk))
|
| 238 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 239 |
+
gk = F.logsigmoid(gk) / self.gate_logit_normalizer
|
| 240 |
+
|
| 241 |
+
if self.clamp_min is not None:
|
| 242 |
+
gk = torch.clamp_min(gk, self.clamp_min)
|
| 243 |
+
|
| 244 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 245 |
+
if mode == 'fused_recurrent':
|
| 246 |
+
o, recurrent_state = fused_recurrent_gla(
|
| 247 |
+
q=q,
|
| 248 |
+
k=k,
|
| 249 |
+
v=v,
|
| 250 |
+
gk=gk,
|
| 251 |
+
initial_state=recurrent_state,
|
| 252 |
+
output_final_state=use_cache,
|
| 253 |
+
cu_seqlens=cu_seqlens,
|
| 254 |
+
)
|
| 255 |
+
elif mode == 'fused_chunk':
|
| 256 |
+
o, recurrent_state = fused_chunk_gla(
|
| 257 |
+
q=q,
|
| 258 |
+
k=k,
|
| 259 |
+
v=v,
|
| 260 |
+
g=gk,
|
| 261 |
+
initial_state=recurrent_state,
|
| 262 |
+
output_final_state=use_cache,
|
| 263 |
+
)
|
| 264 |
+
elif mode == 'chunk':
|
| 265 |
+
o, recurrent_state = chunk_gla(
|
| 266 |
+
q=q,
|
| 267 |
+
k=k,
|
| 268 |
+
v=v,
|
| 269 |
+
g=gk,
|
| 270 |
+
initial_state=recurrent_state,
|
| 271 |
+
output_final_state=use_cache,
|
| 272 |
+
cu_seqlens=cu_seqlens,
|
| 273 |
+
)
|
| 274 |
+
else:
|
| 275 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 276 |
+
|
| 277 |
+
if past_key_values is not None:
|
| 278 |
+
past_key_values.update(
|
| 279 |
+
recurrent_state=recurrent_state,
|
| 280 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 281 |
+
layer_idx=self.layer_idx,
|
| 282 |
+
offset=q_len
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
if self.use_output_gate:
|
| 286 |
+
g = self.g_proj(hidden_states)
|
| 287 |
+
if self.fuse_norm_and_gate:
|
| 288 |
+
g = rearrange(g, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 289 |
+
o = self.g_norm_swish_gate(o, g)
|
| 290 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 291 |
+
else:
|
| 292 |
+
o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
|
| 293 |
+
o = o * self.gate_fn(g)
|
| 294 |
+
else:
|
| 295 |
+
o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
|
| 296 |
+
o = self.o_proj(o)
|
| 297 |
+
if attention_mask is not None:
|
| 298 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 299 |
+
|
| 300 |
+
return o, None, past_key_values
|
layers/gsa.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from einops import rearrange, repeat
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 15 |
+
from fla.modules import RMSNorm, ShortConvolution
|
| 16 |
+
from fla.modules.feature_map import ReLUFeatureMap, SwishFeatureMap, T2RFeatureMap
|
| 17 |
+
from fla.modules.layernorm import rms_norm_linear
|
| 18 |
+
from fla.ops.gsa import chunk_gsa, fused_recurrent_gsa
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from transformers.processing_utils import Unpack
|
| 22 |
+
|
| 23 |
+
from fla.models.utils import Cache
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class GatedSlotAttention(nn.Module):
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
mode: str = 'chunk',
|
| 31 |
+
hidden_size: int = 1024,
|
| 32 |
+
expand_k: float = 1.,
|
| 33 |
+
expand_v: float = 1.,
|
| 34 |
+
num_heads: int = 4,
|
| 35 |
+
num_kv_heads: Optional[int] = None,
|
| 36 |
+
use_short_conv: bool = False,
|
| 37 |
+
conv_size: int = 4,
|
| 38 |
+
conv_bias: bool = False,
|
| 39 |
+
num_slots: Optional[int] = None,
|
| 40 |
+
elementwise_affine: Optional[bool] = True,
|
| 41 |
+
norm_eps: float = 1e-5,
|
| 42 |
+
gate_logit_normalizer: int = 8,
|
| 43 |
+
feature_map: str = 'swish',
|
| 44 |
+
use_output_gate: bool = False,
|
| 45 |
+
use_norm: bool = True,
|
| 46 |
+
layer_idx: Optional[int] = None,
|
| 47 |
+
scale: Optional[float] = 1.,
|
| 48 |
+
**kwargs
|
| 49 |
+
) -> GatedSlotAttention:
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
self.mode = mode
|
| 53 |
+
self.hidden_size = hidden_size
|
| 54 |
+
self.expand_k = expand_k
|
| 55 |
+
self.expand_v = expand_v
|
| 56 |
+
self.num_heads = num_heads
|
| 57 |
+
self.num_kv_heads = num_heads if num_kv_heads is None else num_kv_heads
|
| 58 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 59 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 60 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 61 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 62 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 63 |
+
self.head_k_dim = self.key_dim // self.num_heads
|
| 64 |
+
self.head_v_dim = self.value_dim // self.num_heads
|
| 65 |
+
|
| 66 |
+
self.use_short_conv = use_short_conv
|
| 67 |
+
self.conv_size = conv_size
|
| 68 |
+
self.conv_bias = conv_bias
|
| 69 |
+
|
| 70 |
+
self.gate_logit_normalizer = gate_logit_normalizer
|
| 71 |
+
|
| 72 |
+
self.use_output_gate = use_output_gate
|
| 73 |
+
self.use_norm = use_norm
|
| 74 |
+
self.scale = scale
|
| 75 |
+
|
| 76 |
+
if num_slots is None:
|
| 77 |
+
num_slots = self.head_k_dim
|
| 78 |
+
self.num_slots = num_slots
|
| 79 |
+
|
| 80 |
+
self.layer_idx = layer_idx
|
| 81 |
+
|
| 82 |
+
if layer_idx is None:
|
| 83 |
+
warnings.warn(
|
| 84 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
| 85 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 86 |
+
"when creating this class."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
self.register_module('feature_map', None)
|
| 90 |
+
if feature_map == 'swish':
|
| 91 |
+
self.feature_map = SwishFeatureMap()
|
| 92 |
+
elif feature_map == 'relu':
|
| 93 |
+
self.feature_map = ReLUFeatureMap()
|
| 94 |
+
elif feature_map == 't2r':
|
| 95 |
+
self.feature_map = T2RFeatureMap(self.head_k_dim, self.head_k_dim)
|
| 96 |
+
else:
|
| 97 |
+
raise NotImplementedError(f"Feature map `{feature_map}` is not supported now.")
|
| 98 |
+
|
| 99 |
+
self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
| 100 |
+
self.k_proj = nn.Linear(self.hidden_size, self.key_dim_per_group, bias=False)
|
| 101 |
+
self.v_proj = nn.Linear(self.hidden_size, self.value_dim_per_group, bias=False)
|
| 102 |
+
self.f_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.num_slots, bias=False)
|
| 103 |
+
|
| 104 |
+
if use_short_conv:
|
| 105 |
+
self.conv_size = conv_size
|
| 106 |
+
self.q_conv1d = ShortConvolution(
|
| 107 |
+
hidden_size=self.key_dim,
|
| 108 |
+
kernel_size=conv_size,
|
| 109 |
+
bias=conv_bias,
|
| 110 |
+
activation='silu',
|
| 111 |
+
)
|
| 112 |
+
self.k_conv1d = ShortConvolution(
|
| 113 |
+
hidden_size=self.key_dim_per_group,
|
| 114 |
+
kernel_size=conv_size,
|
| 115 |
+
bias=conv_bias,
|
| 116 |
+
activation='silu',
|
| 117 |
+
)
|
| 118 |
+
self.v_conv1d = ShortConvolution(
|
| 119 |
+
hidden_size=self.value_dim_per_group,
|
| 120 |
+
kernel_size=conv_size,
|
| 121 |
+
bias=conv_bias,
|
| 122 |
+
activation='silu',
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
self.g_norm = RMSNorm(self.hidden_size, elementwise_affine, eps=norm_eps)
|
| 126 |
+
self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
|
| 127 |
+
|
| 128 |
+
def forward(
|
| 129 |
+
self,
|
| 130 |
+
hidden_states: torch.Tensor,
|
| 131 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 132 |
+
past_key_values: Optional[Cache] = None,
|
| 133 |
+
use_cache: Optional[bool] = False,
|
| 134 |
+
output_attentions: Optional[bool] = False,
|
| 135 |
+
**kwargs: Unpack[Dict]
|
| 136 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 137 |
+
if attention_mask is not None:
|
| 138 |
+
assert len(attention_mask.shape) == 2, (
|
| 139 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 140 |
+
"for padding purposes (0 indicating padding). "
|
| 141 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 145 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 146 |
+
|
| 147 |
+
last_state = None
|
| 148 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 149 |
+
last_state = past_key_values[self.layer_idx]
|
| 150 |
+
|
| 151 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 152 |
+
if attention_mask is not None:
|
| 153 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 154 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 155 |
+
|
| 156 |
+
if self.use_short_conv:
|
| 157 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 158 |
+
if last_state is not None:
|
| 159 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 160 |
+
q, conv_state_q = self.q_conv1d(
|
| 161 |
+
x=self.q_proj(hidden_states),
|
| 162 |
+
cache=conv_state_q,
|
| 163 |
+
output_final_state=use_cache,
|
| 164 |
+
cu_seqlens=cu_seqlens
|
| 165 |
+
)
|
| 166 |
+
k, conv_state_k = self.k_conv1d(
|
| 167 |
+
x=self.k_proj(hidden_states),
|
| 168 |
+
cache=conv_state_k,
|
| 169 |
+
output_final_state=use_cache,
|
| 170 |
+
cu_seqlens=cu_seqlens
|
| 171 |
+
)
|
| 172 |
+
v, conv_state_v = self.v_conv1d(
|
| 173 |
+
x=self.v_proj(hidden_states),
|
| 174 |
+
cache=conv_state_v,
|
| 175 |
+
output_final_state=use_cache,
|
| 176 |
+
cu_seqlens=cu_seqlens
|
| 177 |
+
)
|
| 178 |
+
else:
|
| 179 |
+
q = self.q_proj(hidden_states)
|
| 180 |
+
k = self.k_proj(hidden_states)
|
| 181 |
+
v = self.v_proj(hidden_states)
|
| 182 |
+
f = self.f_proj(hidden_states)
|
| 183 |
+
|
| 184 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 185 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 186 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 187 |
+
f = rearrange(f, '... (h m) -> ... h m', m=self.num_slots)
|
| 188 |
+
|
| 189 |
+
if self.feature_map is not None:
|
| 190 |
+
q, k = map(lambda x: self.feature_map(x), (q, k))
|
| 191 |
+
v = F.silu(v)
|
| 192 |
+
|
| 193 |
+
f = F.logsigmoid(f) / self.gate_logit_normalizer
|
| 194 |
+
s = (1 - f.exp()).to(f.dtype)
|
| 195 |
+
|
| 196 |
+
if self.num_kv_groups > 1:
|
| 197 |
+
k, v, f, s = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_kv_groups), (k, v, f, s))
|
| 198 |
+
|
| 199 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 200 |
+
if mode == 'fused_recurrent':
|
| 201 |
+
o, recurrent_state = fused_recurrent_gsa(
|
| 202 |
+
q=q,
|
| 203 |
+
k=k,
|
| 204 |
+
v=v,
|
| 205 |
+
s=s,
|
| 206 |
+
g=f,
|
| 207 |
+
initial_state=recurrent_state,
|
| 208 |
+
output_final_state=use_cache,
|
| 209 |
+
scale=self.scale,
|
| 210 |
+
cu_seqlens=cu_seqlens,
|
| 211 |
+
)
|
| 212 |
+
elif mode == 'chunk':
|
| 213 |
+
o, recurrent_state = chunk_gsa(
|
| 214 |
+
q=q,
|
| 215 |
+
k=k,
|
| 216 |
+
v=v,
|
| 217 |
+
s=s,
|
| 218 |
+
g=f,
|
| 219 |
+
initial_state=recurrent_state,
|
| 220 |
+
output_final_state=use_cache,
|
| 221 |
+
scale=self.scale,
|
| 222 |
+
cu_seqlens=cu_seqlens,
|
| 223 |
+
)
|
| 224 |
+
else:
|
| 225 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 226 |
+
|
| 227 |
+
if past_key_values is not None:
|
| 228 |
+
past_key_values.update(
|
| 229 |
+
recurrent_state=recurrent_state,
|
| 230 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 231 |
+
layer_idx=self.layer_idx,
|
| 232 |
+
offset=q_len
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 236 |
+
o = rms_norm_linear(F.silu(o), self.g_norm.weight, self.g_norm.bias, self.o_proj.weight, self.o_proj.bias)
|
| 237 |
+
if attention_mask is not None:
|
| 238 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 239 |
+
|
| 240 |
+
return o, None, past_key_values
|
layers/hgrn.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# "Hierarchically Gated Recurrent Neural Network for Sequence Modeling" [https://arxiv.org/abs/2311.04823]
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
from fla.modules import FusedRMSNormGated, ShortConvolution
|
| 15 |
+
from fla.modules.activations import swiglu
|
| 16 |
+
from fla.ops.hgrn import chunk_hgrn, fused_recurrent_hgrn
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from transformers.processing_utils import Unpack
|
| 20 |
+
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class HGRNAttention(nn.Module):
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
mode: str = 'chunk',
|
| 29 |
+
hidden_size: int = 1024,
|
| 30 |
+
expand_ratio: Optional[int] = 1,
|
| 31 |
+
use_short_conv: bool = False,
|
| 32 |
+
conv_size: int = 4,
|
| 33 |
+
conv_bias: bool = False,
|
| 34 |
+
elementwise_affine: Optional[bool] = True,
|
| 35 |
+
norm_eps: float = 1e-5,
|
| 36 |
+
layer_idx: int = None
|
| 37 |
+
) -> HGRNAttention:
|
| 38 |
+
super().__init__()
|
| 39 |
+
|
| 40 |
+
self.mode = mode
|
| 41 |
+
self.hidden_size = hidden_size
|
| 42 |
+
self.expand_ratio = expand_ratio
|
| 43 |
+
self.input_dim = int(hidden_size * expand_ratio)
|
| 44 |
+
|
| 45 |
+
self.use_short_conv = use_short_conv
|
| 46 |
+
self.conv_size = conv_size
|
| 47 |
+
self.conv_bias = conv_bias
|
| 48 |
+
|
| 49 |
+
self.layer_idx = layer_idx
|
| 50 |
+
|
| 51 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 52 |
+
|
| 53 |
+
self.i_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 54 |
+
self.f_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 55 |
+
self.g_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 56 |
+
|
| 57 |
+
if use_short_conv:
|
| 58 |
+
self.conv_size = conv_size
|
| 59 |
+
self.f_conv1d = ShortConvolution(
|
| 60 |
+
hidden_size=self.input_dim,
|
| 61 |
+
kernel_size=conv_size,
|
| 62 |
+
bias=conv_bias,
|
| 63 |
+
activation=None,
|
| 64 |
+
)
|
| 65 |
+
self.i_conv1d = ShortConvolution(
|
| 66 |
+
hidden_size=self.input_dim,
|
| 67 |
+
kernel_size=conv_size,
|
| 68 |
+
bias=conv_bias,
|
| 69 |
+
activation=None,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
self.g_norm = FusedRMSNormGated(
|
| 73 |
+
hidden_size=self.input_dim,
|
| 74 |
+
elementwise_affine=elementwise_affine,
|
| 75 |
+
eps=norm_eps
|
| 76 |
+
)
|
| 77 |
+
self.o_proj = nn.Linear(self.input_dim, hidden_size, bias=False)
|
| 78 |
+
|
| 79 |
+
def forward(
|
| 80 |
+
self,
|
| 81 |
+
hidden_states: torch.Tensor,
|
| 82 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 83 |
+
past_key_values: Optional[Cache] = None,
|
| 84 |
+
use_cache: Optional[bool] = False,
|
| 85 |
+
output_attentions: Optional[bool] = False,
|
| 86 |
+
lower_bound: Optional[torch.Tensor] = None,
|
| 87 |
+
**kwargs: Unpack[Dict]
|
| 88 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 89 |
+
if attention_mask is not None:
|
| 90 |
+
assert len(attention_mask.shape) == 2, (
|
| 91 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 92 |
+
"for padding purposes (0 indicating padding). "
|
| 93 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# launching the triton kernel for just one token will actually be slower
|
| 97 |
+
mode = 'fused_recurrent' if not self.training and hidden_states.shape[1] <= 64 else self.mode
|
| 98 |
+
|
| 99 |
+
last_state = None
|
| 100 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 101 |
+
last_state = past_key_values[self.layer_idx]
|
| 102 |
+
|
| 103 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 104 |
+
if self.use_short_conv:
|
| 105 |
+
conv_state_i, conv_state_f = None, None
|
| 106 |
+
if last_state is not None:
|
| 107 |
+
conv_state_i, conv_state_f = last_state['conv_state']
|
| 108 |
+
conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
|
| 109 |
+
i, conv_state_i = self.i_conv1d(
|
| 110 |
+
x=self.i_proj(hidden_states),
|
| 111 |
+
mask=conv_mask,
|
| 112 |
+
cache=conv_state_i,
|
| 113 |
+
output_final_state=use_cache,
|
| 114 |
+
cu_seqlens=cu_seqlens
|
| 115 |
+
)
|
| 116 |
+
f, conv_state_f = self.f_conv1d(
|
| 117 |
+
x=self.f_proj(hidden_states),
|
| 118 |
+
mask=conv_mask,
|
| 119 |
+
cache=conv_state_f,
|
| 120 |
+
output_final_state=use_cache,
|
| 121 |
+
cu_seqlens=cu_seqlens
|
| 122 |
+
)
|
| 123 |
+
else:
|
| 124 |
+
i = self.i_proj(hidden_states)
|
| 125 |
+
f = self.f_proj(hidden_states)
|
| 126 |
+
|
| 127 |
+
f = F.logsigmoid(f)
|
| 128 |
+
# the lower bound for the first layer is zero
|
| 129 |
+
if lower_bound is not None and self.layer_idx > 0:
|
| 130 |
+
f = torch.logaddexp(lower_bound.log(), torch.log1p(-lower_bound) + f).to(f)
|
| 131 |
+
i = swiglu(i, 1 - f.exp())
|
| 132 |
+
|
| 133 |
+
# dealing with left-padding
|
| 134 |
+
if attention_mask is not None:
|
| 135 |
+
i = i.mul_(attention_mask[:, -i.shape[-2]:, None])
|
| 136 |
+
|
| 137 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 138 |
+
if mode == 'chunk':
|
| 139 |
+
if cu_seqlens is not None:
|
| 140 |
+
raise NotImplementedError("Chunk mode does not support variable-length sequences.")
|
| 141 |
+
o, recurrent_state = chunk_hgrn(
|
| 142 |
+
x=i,
|
| 143 |
+
g=f,
|
| 144 |
+
initial_state=recurrent_state,
|
| 145 |
+
output_final_state=use_cache,
|
| 146 |
+
)
|
| 147 |
+
elif mode == 'fused_recurrent':
|
| 148 |
+
o, recurrent_state = fused_recurrent_hgrn(
|
| 149 |
+
x=i,
|
| 150 |
+
g=f,
|
| 151 |
+
initial_state=recurrent_state,
|
| 152 |
+
output_final_state=use_cache,
|
| 153 |
+
cu_seqlens=cu_seqlens
|
| 154 |
+
)
|
| 155 |
+
else:
|
| 156 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 157 |
+
|
| 158 |
+
if past_key_values is not None:
|
| 159 |
+
past_key_values.update(
|
| 160 |
+
recurrent_state=recurrent_state,
|
| 161 |
+
conv_state=(conv_state_i, conv_state_f) if self.use_short_conv else None,
|
| 162 |
+
layer_idx=self.layer_idx,
|
| 163 |
+
offset=i.shape[2]
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
o = self.g_norm(o, self.g_proj(hidden_states))
|
| 167 |
+
o = self.o_proj(o)
|
| 168 |
+
|
| 169 |
+
return o, None, past_key_values
|
| 170 |
+
|
| 171 |
+
def state_size(self, **kwargs) -> int:
|
| 172 |
+
state_size = self.hidden_size
|
| 173 |
+
for module in self.children():
|
| 174 |
+
if isinstance(module, ShortConvolution):
|
| 175 |
+
state_size += module.state_size
|
| 176 |
+
return state_size
|
layers/hgrn2.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from einops import rearrange
|
| 14 |
+
|
| 15 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 16 |
+
from fla.modules import RMSNorm, ShortConvolution
|
| 17 |
+
from fla.modules.activations import swish
|
| 18 |
+
from fla.modules.layernorm import rms_norm_linear
|
| 19 |
+
from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from transformers.processing_utils import Unpack
|
| 23 |
+
|
| 24 |
+
from fla.models.utils import Cache
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class HGRN2Attention(nn.Module):
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
mode: str = 'chunk',
|
| 32 |
+
hidden_size: int = 1024,
|
| 33 |
+
num_heads: Optional[int] = None,
|
| 34 |
+
expand_ratio: Optional[int] = 128,
|
| 35 |
+
use_short_conv: bool = False,
|
| 36 |
+
conv_size: int = 4,
|
| 37 |
+
conv_bias: bool = False,
|
| 38 |
+
elementwise_affine: Optional[bool] = True,
|
| 39 |
+
norm_eps: float = 1e-5,
|
| 40 |
+
layer_idx: int = None
|
| 41 |
+
) -> HGRN2Attention:
|
| 42 |
+
super().__init__()
|
| 43 |
+
|
| 44 |
+
self.mode = mode
|
| 45 |
+
self.hidden_size = hidden_size
|
| 46 |
+
|
| 47 |
+
if expand_ratio is not None:
|
| 48 |
+
num_heads = hidden_size // expand_ratio
|
| 49 |
+
elif expand_ratio is None and num_heads is not None:
|
| 50 |
+
expand_ratio = hidden_size // num_heads
|
| 51 |
+
elif expand_ratio is None and num_heads is None:
|
| 52 |
+
raise RuntimeError("One of `expand_ratio` or `num_heads` should be provided.")
|
| 53 |
+
self.num_heads = num_heads
|
| 54 |
+
self.expand_ratio = expand_ratio
|
| 55 |
+
|
| 56 |
+
self.use_short_conv = use_short_conv
|
| 57 |
+
self.conv_size = conv_size
|
| 58 |
+
self.conv_bias = conv_bias
|
| 59 |
+
|
| 60 |
+
self.forget_dim = int(self.num_heads * self.expand_ratio)
|
| 61 |
+
self.input_dim = hidden_size
|
| 62 |
+
self.layer_idx = layer_idx
|
| 63 |
+
|
| 64 |
+
assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`."
|
| 65 |
+
assert self.forget_dim % num_heads == 0, f"forget dim must be divisible by num_heads of {num_heads}"
|
| 66 |
+
assert self.input_dim % num_heads == 0, f"input dim must be divisible by num_heads of {num_heads}"
|
| 67 |
+
|
| 68 |
+
self.head_f_dim = self.expand_ratio
|
| 69 |
+
self.head_i_dim = self.hidden_size // num_heads
|
| 70 |
+
|
| 71 |
+
self.q_proj = nn.Linear(hidden_size, self.forget_dim, bias=False)
|
| 72 |
+
self.f_proj = nn.Linear(hidden_size, self.forget_dim, bias=False)
|
| 73 |
+
self.i_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 74 |
+
|
| 75 |
+
if use_short_conv:
|
| 76 |
+
self.conv_size = conv_size
|
| 77 |
+
self.q_conv1d = ShortConvolution(
|
| 78 |
+
hidden_size=self.forget_dim,
|
| 79 |
+
kernel_size=conv_size,
|
| 80 |
+
bias=conv_bias,
|
| 81 |
+
activation=None,
|
| 82 |
+
)
|
| 83 |
+
self.f_conv1d = ShortConvolution(
|
| 84 |
+
hidden_size=self.forget_dim,
|
| 85 |
+
kernel_size=conv_size,
|
| 86 |
+
bias=conv_bias,
|
| 87 |
+
activation=None,
|
| 88 |
+
)
|
| 89 |
+
self.i_conv1d = ShortConvolution(
|
| 90 |
+
hidden_size=self.input_dim,
|
| 91 |
+
kernel_size=conv_size,
|
| 92 |
+
bias=conv_bias,
|
| 93 |
+
activation=None,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self.g_norm = RMSNorm(hidden_size=self.hidden_size, elementwise_affine=elementwise_affine, eps=norm_eps)
|
| 97 |
+
self.o_proj = nn.Linear(self.input_dim, hidden_size, bias=False)
|
| 98 |
+
|
| 99 |
+
def forward(
|
| 100 |
+
self,
|
| 101 |
+
hidden_states: torch.Tensor,
|
| 102 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 103 |
+
past_key_values: Optional[Cache] = None,
|
| 104 |
+
use_cache: Optional[bool] = False,
|
| 105 |
+
output_attentions: Optional[bool] = False,
|
| 106 |
+
lower_bound: Optional[torch.Tensor] = None,
|
| 107 |
+
**kwargs: Unpack[Dict]
|
| 108 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 109 |
+
if attention_mask is not None:
|
| 110 |
+
assert len(attention_mask.shape) == 2, (
|
| 111 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 112 |
+
"for padding purposes (0 indicating padding). "
|
| 113 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 117 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 118 |
+
|
| 119 |
+
last_state = None
|
| 120 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 121 |
+
last_state = past_key_values[self.layer_idx]
|
| 122 |
+
|
| 123 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 124 |
+
if attention_mask is not None:
|
| 125 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 126 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 127 |
+
|
| 128 |
+
if self.use_short_conv:
|
| 129 |
+
conv_state_q, conv_state_f, conv_state_i = None, None, None
|
| 130 |
+
if last_state is not None:
|
| 131 |
+
conv_state_q, conv_state_f, conv_state_i = last_state['conv_state']
|
| 132 |
+
q, conv_state_q = self.q_conv1d(
|
| 133 |
+
x=self.q_proj(hidden_states),
|
| 134 |
+
cache=conv_state_q,
|
| 135 |
+
output_final_state=use_cache,
|
| 136 |
+
cu_seqlens=cu_seqlens
|
| 137 |
+
)
|
| 138 |
+
f, conv_state_f = self.f_conv1d(
|
| 139 |
+
x=self.f_proj(hidden_states),
|
| 140 |
+
cache=conv_state_f,
|
| 141 |
+
output_final_state=use_cache,
|
| 142 |
+
cu_seqlens=cu_seqlens
|
| 143 |
+
)
|
| 144 |
+
i, conv_state_i = self.i_conv1d(
|
| 145 |
+
x=self.i_proj(hidden_states),
|
| 146 |
+
cache=conv_state_i,
|
| 147 |
+
output_final_state=use_cache,
|
| 148 |
+
cu_seqlens=cu_seqlens
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
q = self.q_proj(hidden_states)
|
| 152 |
+
f = self.f_proj(hidden_states)
|
| 153 |
+
i = self.i_proj(hidden_states)
|
| 154 |
+
|
| 155 |
+
q = swish(q)
|
| 156 |
+
|
| 157 |
+
g = F.logsigmoid(f)
|
| 158 |
+
# the lower bound for the first layer is zero
|
| 159 |
+
if lower_bound is not None and self.layer_idx > 0:
|
| 160 |
+
g = torch.logaddexp(lower_bound.log(), torch.log1p(-lower_bound) + g)
|
| 161 |
+
k = 1 - g.exp()
|
| 162 |
+
|
| 163 |
+
q, k, g = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_f_dim), (q, k.to(i), g))
|
| 164 |
+
i = rearrange(i, '... (h d) -> ... h d', d=self.head_i_dim)
|
| 165 |
+
|
| 166 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 167 |
+
if mode == 'fused_recurrent':
|
| 168 |
+
o, recurrent_state = fused_recurrent_gla(
|
| 169 |
+
q=q,
|
| 170 |
+
k=k,
|
| 171 |
+
v=i,
|
| 172 |
+
gk=g,
|
| 173 |
+
initial_state=recurrent_state,
|
| 174 |
+
output_final_state=use_cache,
|
| 175 |
+
cu_seqlens=cu_seqlens,
|
| 176 |
+
)
|
| 177 |
+
elif mode == 'fused_chunk':
|
| 178 |
+
o, recurrent_state = fused_chunk_gla(
|
| 179 |
+
q=q,
|
| 180 |
+
k=k,
|
| 181 |
+
v=i,
|
| 182 |
+
g=g,
|
| 183 |
+
initial_state=recurrent_state,
|
| 184 |
+
output_final_state=use_cache,
|
| 185 |
+
)
|
| 186 |
+
elif mode == 'chunk':
|
| 187 |
+
o, recurrent_state = chunk_gla(
|
| 188 |
+
q=q,
|
| 189 |
+
k=k,
|
| 190 |
+
v=i,
|
| 191 |
+
g=g,
|
| 192 |
+
initial_state=recurrent_state,
|
| 193 |
+
output_final_state=use_cache,
|
| 194 |
+
cu_seqlens=cu_seqlens,
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 198 |
+
|
| 199 |
+
if past_key_values is not None:
|
| 200 |
+
past_key_values.update(
|
| 201 |
+
recurrent_state=recurrent_state,
|
| 202 |
+
conv_state=(conv_state_q, conv_state_f, conv_state_i) if self.use_short_conv else None,
|
| 203 |
+
layer_idx=self.layer_idx,
|
| 204 |
+
offset=q_len
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 208 |
+
o = rms_norm_linear(o, self.g_norm.weight, self.g_norm.bias, self.o_proj.weight, self.o_proj.bias)
|
| 209 |
+
if attention_mask is not None:
|
| 210 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 211 |
+
|
| 212 |
+
return o, None, past_key_values
|
layers/lightnet.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# ["You Only Scan Once: Efficient Multi-dimension Sequential Modeling with LightNet"](https://arxiv.org/abs/2405.21022)
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from einops import rearrange
|
| 14 |
+
|
| 15 |
+
from fla.modules import FusedRMSNormGated, ShortConvolution
|
| 16 |
+
from fla.modules.fused_norm_gate import rms_norm_swish_gate_linear
|
| 17 |
+
from fla.ops.gla import chunk_gla, fused_recurrent_gla
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from transformers.processing_utils import Unpack
|
| 21 |
+
|
| 22 |
+
from fla.models.utils import Cache
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class LightNetAttention(nn.Module):
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
mode: str = 'chunk',
|
| 30 |
+
hidden_size: int = 1024,
|
| 31 |
+
num_heads: Optional[int] = None,
|
| 32 |
+
expand_ratio: Optional[int] = 128,
|
| 33 |
+
use_short_conv: bool = False,
|
| 34 |
+
conv_size: int = 4,
|
| 35 |
+
conv_bias: bool = False,
|
| 36 |
+
gate_low_rank_dim: int = 128,
|
| 37 |
+
elementwise_affine: Optional[bool] = True,
|
| 38 |
+
norm_eps: float = 1e-5,
|
| 39 |
+
layer_idx: int = None
|
| 40 |
+
) -> LightNetAttention:
|
| 41 |
+
super().__init__()
|
| 42 |
+
|
| 43 |
+
self.mode = mode
|
| 44 |
+
self.hidden_size = hidden_size
|
| 45 |
+
|
| 46 |
+
if expand_ratio is None and num_heads is not None:
|
| 47 |
+
expand_ratio = hidden_size // num_heads
|
| 48 |
+
elif expand_ratio is not None and num_heads is None:
|
| 49 |
+
num_heads = hidden_size // expand_ratio
|
| 50 |
+
elif expand_ratio is None and num_heads is None:
|
| 51 |
+
raise RuntimeError("One of `expand_ratio` or `num_heads` should be provided.")
|
| 52 |
+
self.num_heads = num_heads
|
| 53 |
+
self.expand_ratio = expand_ratio
|
| 54 |
+
|
| 55 |
+
self.use_short_conv = use_short_conv
|
| 56 |
+
self.conv_size = conv_size
|
| 57 |
+
self.conv_bias = conv_bias
|
| 58 |
+
|
| 59 |
+
self.key_dim = int(self.num_heads * self.expand_ratio)
|
| 60 |
+
self.value_dim = hidden_size
|
| 61 |
+
self.gate_low_rank_dim = gate_low_rank_dim
|
| 62 |
+
self.layer_idx = layer_idx
|
| 63 |
+
|
| 64 |
+
assert mode in ['chunk', 'fused_chunk'], f"Not supported mode `{mode}`."
|
| 65 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 66 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 67 |
+
|
| 68 |
+
self.head_f_dim = self.expand_ratio
|
| 69 |
+
self.head_i_dim = self.hidden_size // num_heads
|
| 70 |
+
|
| 71 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 72 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 73 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 74 |
+
|
| 75 |
+
if use_short_conv:
|
| 76 |
+
self.conv_size = conv_size
|
| 77 |
+
self.q_conv1d = ShortConvolution(
|
| 78 |
+
hidden_size=self.key_dim,
|
| 79 |
+
kernel_size=conv_size,
|
| 80 |
+
bias=conv_bias,
|
| 81 |
+
activation=None,
|
| 82 |
+
)
|
| 83 |
+
self.k_conv1d = ShortConvolution(
|
| 84 |
+
hidden_size=self.key_dim,
|
| 85 |
+
kernel_size=conv_size,
|
| 86 |
+
bias=conv_bias,
|
| 87 |
+
activation=None,
|
| 88 |
+
)
|
| 89 |
+
self.v_conv1d = ShortConvolution(
|
| 90 |
+
hidden_size=self.value_dim,
|
| 91 |
+
kernel_size=conv_size,
|
| 92 |
+
bias=conv_bias,
|
| 93 |
+
activation=None,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self.g_proj = nn.Sequential(
|
| 97 |
+
nn.Linear(hidden_size, gate_low_rank_dim, bias=False),
|
| 98 |
+
nn.Linear(gate_low_rank_dim, hidden_size, bias=False)
|
| 99 |
+
)
|
| 100 |
+
self.g_norm = FusedRMSNormGated(
|
| 101 |
+
hidden_size=hidden_size,
|
| 102 |
+
elementwise_affine=elementwise_affine,
|
| 103 |
+
eps=norm_eps
|
| 104 |
+
)
|
| 105 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 106 |
+
|
| 107 |
+
def forward(
|
| 108 |
+
self,
|
| 109 |
+
hidden_states: torch.Tensor,
|
| 110 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 111 |
+
past_key_values: Optional[Cache] = None,
|
| 112 |
+
use_cache: Optional[bool] = False,
|
| 113 |
+
output_attentions: Optional[bool] = False,
|
| 114 |
+
**kwargs: Unpack[Dict]
|
| 115 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 116 |
+
if attention_mask is not None:
|
| 117 |
+
assert len(attention_mask.shape) == 2, (
|
| 118 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 119 |
+
"for padding purposes (0 indicating padding). "
|
| 120 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# launching the triton kernel for just one token will actually be slower
|
| 124 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 125 |
+
|
| 126 |
+
last_state = None
|
| 127 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 128 |
+
last_state = past_key_values[self.layer_idx]
|
| 129 |
+
|
| 130 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 131 |
+
if self.use_short_conv:
|
| 132 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 133 |
+
if last_state is not None:
|
| 134 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 135 |
+
conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
|
| 136 |
+
q, conv_state_q = self.q_conv1d(
|
| 137 |
+
x=self.q_proj(hidden_states),
|
| 138 |
+
mask=conv_mask,
|
| 139 |
+
cache=conv_state_q,
|
| 140 |
+
output_final_state=use_cache,
|
| 141 |
+
cu_seqlens=cu_seqlens
|
| 142 |
+
)
|
| 143 |
+
k, conv_state_k = self.k_conv1d(
|
| 144 |
+
x=self.k_proj(hidden_states),
|
| 145 |
+
mask=conv_mask,
|
| 146 |
+
cache=conv_state_k,
|
| 147 |
+
output_final_state=use_cache,
|
| 148 |
+
cu_seqlens=cu_seqlens
|
| 149 |
+
)
|
| 150 |
+
v, conv_state_v = self.v_conv1d(
|
| 151 |
+
x=self.v_proj(hidden_states),
|
| 152 |
+
mask=conv_mask,
|
| 153 |
+
cache=conv_state_v,
|
| 154 |
+
output_final_state=use_cache,
|
| 155 |
+
cu_seqlens=cu_seqlens
|
| 156 |
+
)
|
| 157 |
+
else:
|
| 158 |
+
q = self.q_proj(hidden_states)
|
| 159 |
+
k = self.k_proj(hidden_states)
|
| 160 |
+
v = self.v_proj(hidden_states)
|
| 161 |
+
|
| 162 |
+
# dealing with left-padding
|
| 163 |
+
if attention_mask is not None:
|
| 164 |
+
v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
|
| 165 |
+
|
| 166 |
+
q = F.silu(q)
|
| 167 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_f_dim), (q, k))
|
| 168 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_i_dim)
|
| 169 |
+
# TODO: this 2 steps took huge amount of time, which should be optimized
|
| 170 |
+
z = k.float().logcumsumexp(1)
|
| 171 |
+
|
| 172 |
+
if cu_seqlens is not None:
|
| 173 |
+
raise NotImplementedError("LightNet does not support variable-length sequences for now.")
|
| 174 |
+
k, g = torch.exp(k - z).to(k.dtype), (torch.cat((z[:, :1], z[:, :-1]), 1) - z).to(k.dtype)
|
| 175 |
+
|
| 176 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 177 |
+
if mode == 'fused_recurrent':
|
| 178 |
+
o, recurrent_state = fused_recurrent_gla(
|
| 179 |
+
q=q,
|
| 180 |
+
k=k,
|
| 181 |
+
v=v,
|
| 182 |
+
gk=g,
|
| 183 |
+
initial_state=recurrent_state,
|
| 184 |
+
output_final_state=use_cache,
|
| 185 |
+
cu_seqlens=cu_seqlens,
|
| 186 |
+
)
|
| 187 |
+
elif mode == 'chunk':
|
| 188 |
+
o, recurrent_state = chunk_gla(
|
| 189 |
+
q=q,
|
| 190 |
+
k=k,
|
| 191 |
+
v=v,
|
| 192 |
+
g=g,
|
| 193 |
+
initial_state=recurrent_state,
|
| 194 |
+
output_final_state=use_cache,
|
| 195 |
+
cu_seqlens=cu_seqlens,
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 199 |
+
|
| 200 |
+
if past_key_values is not None:
|
| 201 |
+
past_key_values.update(
|
| 202 |
+
recurrent_state=recurrent_state,
|
| 203 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 204 |
+
layer_idx=self.layer_idx,
|
| 205 |
+
offset=q.shape[1]
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
o = rms_norm_swish_gate_linear(
|
| 209 |
+
rearrange(o, 'b t h d -> b t (h d)'),
|
| 210 |
+
self.g_proj(hidden_states),
|
| 211 |
+
self.g_norm.weight,
|
| 212 |
+
self.g_norm.bias,
|
| 213 |
+
self.o_proj.weight,
|
| 214 |
+
self.o_proj.bias
|
| 215 |
+
)
|
| 216 |
+
return o, None, past_key_values
|
| 217 |
+
|
| 218 |
+
def state_size(self, **kwargs) -> int:
|
| 219 |
+
state_size = self.key_dim * self.head_i_dim
|
| 220 |
+
for module in self.children():
|
| 221 |
+
if isinstance(module, ShortConvolution):
|
| 222 |
+
state_size += module.state_size
|
| 223 |
+
return state_size
|
layers/linear_attn.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from einops import rearrange, repeat
|
| 10 |
+
|
| 11 |
+
from fla.modules import RMSNorm
|
| 12 |
+
from fla.modules.feature_map import DPFPFeatureMap, HadamardFeatureMap, HedgehogFeatureMap, T2RFeatureMap
|
| 13 |
+
from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn, fused_recurrent_linear_attn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class LinearAttention(nn.Module):
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
mode: str = 'chunk',
|
| 21 |
+
hidden_size: str = 1024,
|
| 22 |
+
expand_k: float = 1.0,
|
| 23 |
+
expand_v: float = 1.0,
|
| 24 |
+
num_heads: int = 8,
|
| 25 |
+
num_kv_heads: Optional[int] = None,
|
| 26 |
+
feature_map: str = 'elementwise_product',
|
| 27 |
+
tie_feature_map_qk: bool = False,
|
| 28 |
+
output_norm: str = 'rmsnorm',
|
| 29 |
+
norm_q: bool = False,
|
| 30 |
+
norm_k: bool = False,
|
| 31 |
+
do_feature_map_norm: bool = False,
|
| 32 |
+
elementwise_affine: bool = True,
|
| 33 |
+
norm_eps: float = 1e-5,
|
| 34 |
+
**kwargs
|
| 35 |
+
):
|
| 36 |
+
super().__init__()
|
| 37 |
+
|
| 38 |
+
self.hidden_size = hidden_size
|
| 39 |
+
self.mode = mode
|
| 40 |
+
self.num_heads = num_heads
|
| 41 |
+
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
| 42 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 43 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 44 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 45 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 46 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 47 |
+
|
| 48 |
+
assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 49 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 50 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 51 |
+
|
| 52 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 53 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 54 |
+
self.do_feature_map_norm = do_feature_map_norm
|
| 55 |
+
|
| 56 |
+
if feature_map == 'hedgehog':
|
| 57 |
+
if tie_feature_map_qk:
|
| 58 |
+
self.feature_map_q = self.feature_map_k = HedgehogFeatureMap(head_dim=self.head_k_dim)
|
| 59 |
+
else:
|
| 60 |
+
self.feature_map_q = HedgehogFeatureMap(head_dim=self.head_k_dim)
|
| 61 |
+
self.feature_map_k = HedgehogFeatureMap(head_dim=self.head_k_dim)
|
| 62 |
+
|
| 63 |
+
elif feature_map == 't2r':
|
| 64 |
+
if tie_feature_map_qk:
|
| 65 |
+
self.feature_map_q = self.feature_map_k = T2RFeatureMap(head_dim=self.head_k_dim)
|
| 66 |
+
else:
|
| 67 |
+
self.feature_map_q = T2RFeatureMap(head_dim=self.head_k_dim)
|
| 68 |
+
self.feature_map_k = T2RFeatureMap(head_dim=self.head_k_dim)
|
| 69 |
+
|
| 70 |
+
elif feature_map == 'elementwise_product':
|
| 71 |
+
if tie_feature_map_qk:
|
| 72 |
+
self.feature_map_q = self.feature_map_k = HadamardFeatureMap(head_dim=self.head_k_dim)
|
| 73 |
+
else:
|
| 74 |
+
self.feature_map_q = HadamardFeatureMap(head_dim=self.head_k_dim)
|
| 75 |
+
self.feature_map_k = HadamardFeatureMap(head_dim=self.head_k_dim)
|
| 76 |
+
|
| 77 |
+
elif feature_map == 'dpfp':
|
| 78 |
+
self.feature_map_q = DPFPFeatureMap(head_dim=self.head_k_dim)
|
| 79 |
+
self.feature_map_k = DPFPFeatureMap(head_dim=self.head_k_dim)
|
| 80 |
+
|
| 81 |
+
elif feature_map == 'elu':
|
| 82 |
+
def elu(x):
|
| 83 |
+
return F.elu(x) + 1
|
| 84 |
+
self.feature_map_q = elu
|
| 85 |
+
self.feature_map_k = elu
|
| 86 |
+
|
| 87 |
+
elif feature_map == 'relu':
|
| 88 |
+
self.feature_map_q = nn.ReLU()
|
| 89 |
+
self.feature_map_k = nn.ReLU()
|
| 90 |
+
|
| 91 |
+
elif feature_map == 'identity':
|
| 92 |
+
self.feature_map_q = nn.Identity()
|
| 93 |
+
self.feature_map_k = nn.Identity()
|
| 94 |
+
else:
|
| 95 |
+
raise NotImplementedError(f"Not supported feature map `{feature_map}`.")
|
| 96 |
+
|
| 97 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 98 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
|
| 99 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
|
| 100 |
+
|
| 101 |
+
if output_norm == 'rmsnorm':
|
| 102 |
+
self.norm = RMSNorm(hidden_size=self.head_v_dim, elementwise_affine=elementwise_affine, eps=norm_eps)
|
| 103 |
+
elif output_norm == 'identity':
|
| 104 |
+
self.norm = nn.Identity()
|
| 105 |
+
else:
|
| 106 |
+
raise NotImplementedError(f"Not supported output norm `{output_norm}`.")
|
| 107 |
+
|
| 108 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 109 |
+
|
| 110 |
+
self.norm_q = norm_q
|
| 111 |
+
self.norm_k = norm_k
|
| 112 |
+
|
| 113 |
+
def forward(
|
| 114 |
+
self,
|
| 115 |
+
hidden_states: torch.Tensor,
|
| 116 |
+
**kwargs
|
| 117 |
+
) -> torch.Tensor:
|
| 118 |
+
mode = self.mode
|
| 119 |
+
q = self.q_proj(hidden_states)
|
| 120 |
+
k = self.k_proj(hidden_states)
|
| 121 |
+
v = self.v_proj(hidden_states)
|
| 122 |
+
|
| 123 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 124 |
+
if self.num_kv_groups > 1:
|
| 125 |
+
k = repeat(k, '... (h d) -> ... (h g) d', d=self.head_k_dim, g=self.num_kv_groups)
|
| 126 |
+
v = repeat(v, '... (h d) -> ... (h g) d', d=self.head_v_dim, g=self.num_kv_groups)
|
| 127 |
+
else:
|
| 128 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 129 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 130 |
+
|
| 131 |
+
q = self.feature_map_q(q)
|
| 132 |
+
k = self.feature_map_k(k)
|
| 133 |
+
|
| 134 |
+
if self.norm_q:
|
| 135 |
+
q = q / (q.sum(-1, True) + 1e-4)
|
| 136 |
+
if self.norm_k:
|
| 137 |
+
k = k / (k.sum(-1, True) + 1e-4)
|
| 138 |
+
|
| 139 |
+
if mode == 'chunk':
|
| 140 |
+
o, final_state = chunk_linear_attn(
|
| 141 |
+
q=q,
|
| 142 |
+
k=k,
|
| 143 |
+
v=v,
|
| 144 |
+
normalize=self.do_feature_map_norm,
|
| 145 |
+
)
|
| 146 |
+
elif mode == 'fused_chunk':
|
| 147 |
+
o, final_state = fused_chunk_linear_attn(
|
| 148 |
+
q=q,
|
| 149 |
+
k=k,
|
| 150 |
+
v=v,
|
| 151 |
+
normalize=self.do_feature_map_norm,
|
| 152 |
+
)
|
| 153 |
+
elif mode == 'fused_recurrent':
|
| 154 |
+
o, final_state = fused_recurrent_linear_attn(
|
| 155 |
+
q=q,
|
| 156 |
+
k=k,
|
| 157 |
+
v=v,
|
| 158 |
+
normalize=self.do_feature_map_norm,
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
raise NotImplementedError
|
| 162 |
+
o = self.norm(o)
|
| 163 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 164 |
+
o = self.o_proj(o)
|
| 165 |
+
return o
|
layers/log_linear_mamba2.py
ADDED
|
@@ -0,0 +1,650 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from transformers.activations import ACT2FN
|
| 8 |
+
from transformers.utils import logging
|
| 9 |
+
|
| 10 |
+
from fla.layers.mamba2 import apply_mask_to_padding_states, causal_conv1d_fn, causal_conv1d_update, is_fast_path_available
|
| 11 |
+
from fla.modules.layernorm_gated import RMSNormGated, rmsnorm_fn
|
| 12 |
+
from fla.ops.log_linear_attn.chunk import LogLinearAttentionState, chunk_log_linear_attn
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from fla.models.log_linear_mamba2.modeling_log_linear_mamba2 import LogLinearMamba2Cache
|
| 16 |
+
|
| 17 |
+
logger = logging.get_logger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def ceil_log(x: int, b: int) -> int:
|
| 21 |
+
return math.ceil(math.log(x, b))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_num_levels(length: int, base: int) -> int:
|
| 25 |
+
return ceil_log(length, base) + 1
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
MAX_SEQUENCE_LENGTH = 2048 * 8
|
| 29 |
+
LAMBDA_LEVEL_BASE = 2
|
| 30 |
+
MAX_NUM_LEVELS = get_num_levels(length=MAX_SEQUENCE_LENGTH, base=LAMBDA_LEVEL_BASE)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def hmamba_chunk_scan_combined(
|
| 34 |
+
x: torch.Tensor,
|
| 35 |
+
dt: torch.Tensor,
|
| 36 |
+
A: torch.Tensor,
|
| 37 |
+
B: torch.Tensor,
|
| 38 |
+
C: torch.Tensor,
|
| 39 |
+
dl: torch.Tensor,
|
| 40 |
+
L: torch.Tensor,
|
| 41 |
+
chunk_size: int,
|
| 42 |
+
D: Optional[torch.Tensor] = None,
|
| 43 |
+
z: Optional[torch.Tensor] = None,
|
| 44 |
+
dt_bias: Optional[torch.Tensor] = None,
|
| 45 |
+
initial_states: Optional[LogLinearAttentionState] = None,
|
| 46 |
+
seq_idx: Optional[torch.Tensor] = None,
|
| 47 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 48 |
+
dt_softplus: bool = False,
|
| 49 |
+
dt_limit: Tuple[float, float] = (0.0, float("inf")),
|
| 50 |
+
return_final_states: bool = False,
|
| 51 |
+
):
|
| 52 |
+
if z is not None:
|
| 53 |
+
raise NotImplementedError
|
| 54 |
+
if seq_idx is not None:
|
| 55 |
+
raise NotImplementedError
|
| 56 |
+
if cu_seqlens is not None:
|
| 57 |
+
raise NotImplementedError
|
| 58 |
+
if dt_softplus is not True:
|
| 59 |
+
raise NotImplementedError
|
| 60 |
+
if tuple(dt_limit) != (0.0, float("inf")):
|
| 61 |
+
raise NotImplementedError
|
| 62 |
+
if chunk_size != 64:
|
| 63 |
+
raise NotImplementedError
|
| 64 |
+
if not B.shape == C.shape:
|
| 65 |
+
raise ValueError("B and C must have the same shape")
|
| 66 |
+
|
| 67 |
+
if D is not None:
|
| 68 |
+
if D.dim() != 1:
|
| 69 |
+
raise ValueError
|
| 70 |
+
D = rearrange(D, "h -> 1 1 h 1")
|
| 71 |
+
D_residual = x * D
|
| 72 |
+
|
| 73 |
+
if dt_bias is not None:
|
| 74 |
+
dt = dt + rearrange(dt_bias, "h -> 1 1 h")
|
| 75 |
+
if dt_softplus:
|
| 76 |
+
dt = torch.nn.functional.softplus(dt)
|
| 77 |
+
if dt_limit != (0.0, float("inf")):
|
| 78 |
+
dt = torch.clamp(dt, min=dt_limit[0], max=dt_limit[1])
|
| 79 |
+
x = (x * rearrange(dt, "b l h -> b l h 1")).to(x.dtype)
|
| 80 |
+
A = rearrange(A, "h -> 1 1 h") * dt
|
| 81 |
+
|
| 82 |
+
L = torch.nn.functional.softplus(rearrange(L, "h ell -> 1 1 h ell") * dl).to(L.dtype)
|
| 83 |
+
|
| 84 |
+
y, state = chunk_log_linear_attn(
|
| 85 |
+
q=C,
|
| 86 |
+
k=B,
|
| 87 |
+
v=x,
|
| 88 |
+
g=A,
|
| 89 |
+
level_scales=L,
|
| 90 |
+
initial_state=initial_states,
|
| 91 |
+
output_final_state=return_final_states,
|
| 92 |
+
cu_seqlens=cu_seqlens,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
if D is not None:
|
| 96 |
+
y = y + D_residual
|
| 97 |
+
|
| 98 |
+
return y, state
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def hmamba_split_conv1d_scan_combined(
|
| 102 |
+
zxbcdtdl: torch.Tensor,
|
| 103 |
+
conv1d_weight: torch.Tensor,
|
| 104 |
+
conv1d_bias: torch.Tensor,
|
| 105 |
+
dt_bias: torch.Tensor,
|
| 106 |
+
A: torch.Tensor,
|
| 107 |
+
L: torch.Tensor,
|
| 108 |
+
D: torch.Tensor,
|
| 109 |
+
chunk_size: int,
|
| 110 |
+
initial_states: Optional[torch.Tensor] = None,
|
| 111 |
+
seq_idx: Optional[torch.Tensor] = None,
|
| 112 |
+
dt_limit: Tuple[float, float] = (0.0, float("inf")),
|
| 113 |
+
return_final_states: bool = False,
|
| 114 |
+
activation: str = "silu",
|
| 115 |
+
rmsnorm_weight: Optional[torch.Tensor] = None,
|
| 116 |
+
rmsnorm_eps: float = 1e-6,
|
| 117 |
+
outproj_weight: Optional[torch.Tensor] = None,
|
| 118 |
+
outproj_bias: Optional[torch.Tensor] = None,
|
| 119 |
+
headdim: Optional[int] = None,
|
| 120 |
+
ngroups: int = 1,
|
| 121 |
+
norm_before_gate: bool = True,
|
| 122 |
+
) -> torch.Tensor:
|
| 123 |
+
"""
|
| 124 |
+
Argument:
|
| 125 |
+
zxbcdtdl: (batch, seqlen, 2 * dim + 2 * ngroups * dstate + nheads) where dim == nheads * headdim
|
| 126 |
+
conv1d_weight: (dim + 2 * ngroups * dstate, width)
|
| 127 |
+
conv1d_bias: (dim + 2 * ngroups * dstate,)
|
| 128 |
+
dt_bias: (nheads,)
|
| 129 |
+
A: (nheads)
|
| 130 |
+
L: (nheads, nlevels)
|
| 131 |
+
D: (nheads, headdim) or (nheads,)
|
| 132 |
+
initial_states: (batch, nheads, headdim, dstate)
|
| 133 |
+
seq_idx: (batch, seqlen), int32
|
| 134 |
+
rmsnorm_weight: (dim,)
|
| 135 |
+
outproj_weight: (out_dim, dim)
|
| 136 |
+
outproj_bias: (out_dim,)
|
| 137 |
+
headdim: if D is 1D, headdim must be passed in
|
| 138 |
+
norm_before_gate: if True, we do RMSNorm(x) * F.silu(z). If False, we do RMSNorm(x * F.silu(z))
|
| 139 |
+
Return:
|
| 140 |
+
out: (batch, seqlen, dim)
|
| 141 |
+
"""
|
| 142 |
+
if initial_states is not None:
|
| 143 |
+
raise NotImplementedError
|
| 144 |
+
if seq_idx is not None:
|
| 145 |
+
raise NotImplementedError
|
| 146 |
+
if dt_limit != (0.0, float("inf")):
|
| 147 |
+
raise NotImplementedError
|
| 148 |
+
if return_final_states is not False:
|
| 149 |
+
raise NotImplementedError
|
| 150 |
+
if norm_before_gate is not False:
|
| 151 |
+
raise NotImplementedError
|
| 152 |
+
if rmsnorm_weight is None:
|
| 153 |
+
raise NotImplementedError
|
| 154 |
+
if activation not in ["silu", "swish"]:
|
| 155 |
+
raise NotImplementedError
|
| 156 |
+
|
| 157 |
+
batch, seqlen, _ = zxbcdtdl.shape
|
| 158 |
+
dlambda = L.shape[-1]
|
| 159 |
+
(nheads,) = D.shape
|
| 160 |
+
dim = nheads * headdim
|
| 161 |
+
dstate = (zxbcdtdl.shape[-1] - 2 * dim - nheads - nheads * dlambda) // ngroups // 2
|
| 162 |
+
|
| 163 |
+
if D.dim() != 1:
|
| 164 |
+
raise ValueError
|
| 165 |
+
if headdim is None:
|
| 166 |
+
raise ValueError
|
| 167 |
+
if nheads % ngroups != 0:
|
| 168 |
+
raise ValueError
|
| 169 |
+
if zxbcdtdl.shape != (
|
| 170 |
+
batch,
|
| 171 |
+
seqlen,
|
| 172 |
+
2 * dim + 2 * ngroups * dstate + nheads + nheads * dlambda,
|
| 173 |
+
):
|
| 174 |
+
raise ValueError
|
| 175 |
+
if dt_bias.shape != (nheads,):
|
| 176 |
+
raise ValueError
|
| 177 |
+
if A.shape != (nheads,):
|
| 178 |
+
raise ValueError
|
| 179 |
+
if L.shape != (nheads, dlambda):
|
| 180 |
+
raise ValueError
|
| 181 |
+
if D.shape != (nheads,):
|
| 182 |
+
raise ValueError
|
| 183 |
+
if rmsnorm_weight is None:
|
| 184 |
+
raise ValueError
|
| 185 |
+
|
| 186 |
+
zxBCdtl_splits = [dim, dim + 2 * ngroups * dstate, nheads, nheads * dlambda]
|
| 187 |
+
xBC_splits = [dim, ngroups * dstate, ngroups * dstate]
|
| 188 |
+
z, xBC, dt, dl = torch.split(zxbcdtdl, zxBCdtl_splits, dim=-1)
|
| 189 |
+
xBC = rearrange(
|
| 190 |
+
causal_conv1d_fn(
|
| 191 |
+
rearrange(xBC, "b s d -> b d s"),
|
| 192 |
+
conv1d_weight,
|
| 193 |
+
bias=conv1d_bias,
|
| 194 |
+
activation=activation,
|
| 195 |
+
seq_idx=seq_idx,
|
| 196 |
+
),
|
| 197 |
+
"b d s -> b s d",
|
| 198 |
+
)
|
| 199 |
+
x, B, C = torch.split(xBC, xBC_splits, dim=-1)
|
| 200 |
+
x = rearrange(x, "b l (h p) -> b l h p", h=nheads, p=headdim)
|
| 201 |
+
B = rearrange(B, "b l (g n) -> b l g n", g=ngroups, n=dstate)
|
| 202 |
+
C = rearrange(C, "b l (g n) -> b l g n", g=ngroups, n=dstate)
|
| 203 |
+
dl = rearrange(dl, "b l (h ell) -> b l h ell", h=nheads, ell=dlambda)
|
| 204 |
+
y, _ = hmamba_chunk_scan_combined(
|
| 205 |
+
x=x,
|
| 206 |
+
dt=dt,
|
| 207 |
+
A=A,
|
| 208 |
+
B=B,
|
| 209 |
+
C=C,
|
| 210 |
+
dl=dl,
|
| 211 |
+
L=L,
|
| 212 |
+
chunk_size=chunk_size,
|
| 213 |
+
D=D,
|
| 214 |
+
z=z if rmsnorm_weight is None else None,
|
| 215 |
+
dt_bias=dt_bias,
|
| 216 |
+
dt_softplus=True,
|
| 217 |
+
seq_idx=seq_idx,
|
| 218 |
+
cu_seqlens=None,
|
| 219 |
+
dt_limit=dt_limit,
|
| 220 |
+
return_final_states=return_final_states,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
y = rearrange(y, "b l h p -> b l (h p)")
|
| 224 |
+
if rmsnorm_weight is not None:
|
| 225 |
+
y = rmsnorm_fn(
|
| 226 |
+
x=y,
|
| 227 |
+
weight=rmsnorm_weight,
|
| 228 |
+
bias=None,
|
| 229 |
+
z=z,
|
| 230 |
+
eps=rmsnorm_eps,
|
| 231 |
+
group_size=None,
|
| 232 |
+
norm_before_gate=False,
|
| 233 |
+
)
|
| 234 |
+
out = torch.nn.functional.linear(y, outproj_weight, outproj_bias)
|
| 235 |
+
return out
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class LogLinearMamba2(nn.Module):
|
| 239 |
+
"""
|
| 240 |
+
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
|
| 241 |
+
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
|
| 242 |
+
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
|
| 243 |
+
and is why Mamba is called **selective** state spaces)
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
def __init__(
|
| 247 |
+
self,
|
| 248 |
+
num_heads: int,
|
| 249 |
+
head_dim: int = 64,
|
| 250 |
+
hidden_size: int = 2048,
|
| 251 |
+
state_size: int = 128,
|
| 252 |
+
expand: int = 2,
|
| 253 |
+
n_groups: int = 1,
|
| 254 |
+
conv_kernel: int = 4,
|
| 255 |
+
use_conv_bias: bool = False,
|
| 256 |
+
hidden_act: str = "silu",
|
| 257 |
+
rms_norm: bool = True,
|
| 258 |
+
chunk_size: int = 64,
|
| 259 |
+
time_step_rank: float = 256,
|
| 260 |
+
time_step_limit: Tuple[float, float] = (0.0, float("inf")),
|
| 261 |
+
time_step_min: float = 0.001,
|
| 262 |
+
time_step_max: float = 0.1,
|
| 263 |
+
use_bias: bool = True,
|
| 264 |
+
norm_eps: float = 1e-5,
|
| 265 |
+
layer_idx: int = None,
|
| 266 |
+
):
|
| 267 |
+
super().__init__()
|
| 268 |
+
self.num_heads = num_heads
|
| 269 |
+
self.hidden_size = hidden_size
|
| 270 |
+
self.ssm_state_size = state_size
|
| 271 |
+
self.conv_kernel_size = conv_kernel
|
| 272 |
+
self.intermediate_size = int(expand * self.hidden_size)
|
| 273 |
+
self.time_step_rank = int(time_step_rank)
|
| 274 |
+
self.layer_idx = layer_idx
|
| 275 |
+
self.use_conv_bias = use_conv_bias
|
| 276 |
+
self.activation = hidden_act
|
| 277 |
+
self.act = ACT2FN[hidden_act]
|
| 278 |
+
|
| 279 |
+
self.layer_norm_epsilon = norm_eps
|
| 280 |
+
self.rms_norm = rms_norm
|
| 281 |
+
|
| 282 |
+
self.n_groups = n_groups
|
| 283 |
+
self.head_dim = head_dim
|
| 284 |
+
self.chunk_size = chunk_size
|
| 285 |
+
|
| 286 |
+
self.time_step_limit = time_step_limit
|
| 287 |
+
self.time_step_min = time_step_min
|
| 288 |
+
self.time_step_max = time_step_max
|
| 289 |
+
|
| 290 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 291 |
+
self.conv1d = nn.Conv1d(
|
| 292 |
+
in_channels=self.conv_dim,
|
| 293 |
+
out_channels=self.conv_dim,
|
| 294 |
+
bias=use_conv_bias,
|
| 295 |
+
kernel_size=conv_kernel,
|
| 296 |
+
groups=self.conv_dim,
|
| 297 |
+
padding=conv_kernel - 1,
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
self.num_lambda_dims = MAX_NUM_LEVELS
|
| 301 |
+
self.lambda_level_module = None
|
| 302 |
+
|
| 303 |
+
# projection of the input hidden states
|
| 304 |
+
projection_size = (
|
| 305 |
+
self.intermediate_size
|
| 306 |
+
+ self.conv_dim
|
| 307 |
+
+ self.num_heads * (self.num_lambda_dims + 1)
|
| 308 |
+
)
|
| 309 |
+
self.in_proj = nn.Linear(
|
| 310 |
+
self.hidden_size,
|
| 311 |
+
projection_size,
|
| 312 |
+
bias=use_bias,
|
| 313 |
+
)
|
| 314 |
+
# selective projection used to make dt, B and C input dependant
|
| 315 |
+
|
| 316 |
+
# time step projection (discretization)
|
| 317 |
+
# instantiate once and copy inv_dt in init_weights of PretrainedModel
|
| 318 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 319 |
+
|
| 320 |
+
# S4D real initialization. These are not discretized!
|
| 321 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 322 |
+
A = torch.arange(1, self.num_heads + 1)
|
| 323 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 324 |
+
self.A_log._no_weight_decay = True
|
| 325 |
+
|
| 326 |
+
self.lambda_mode = "positive"
|
| 327 |
+
L = torch.ones(self.num_heads, self.num_lambda_dims)
|
| 328 |
+
self.L = nn.Parameter(L)
|
| 329 |
+
self.L._no_weight_decay = True
|
| 330 |
+
|
| 331 |
+
self.norm = RMSNormGated(
|
| 332 |
+
self.intermediate_size, eps=self.layer_norm_epsilon, norm_before_gate=False
|
| 333 |
+
)
|
| 334 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 335 |
+
self.D._no_weight_decay = True
|
| 336 |
+
|
| 337 |
+
self.out_proj = nn.Linear(
|
| 338 |
+
self.intermediate_size, self.hidden_size, bias=use_bias
|
| 339 |
+
)
|
| 340 |
+
self.use_bias = use_bias
|
| 341 |
+
|
| 342 |
+
if not is_fast_path_available:
|
| 343 |
+
logger.warning_once(
|
| 344 |
+
"The fast path is not available because one of "
|
| 345 |
+
"`(selective_state_update, causal_conv1d_fn, causal_conv1d_update)` is None. "
|
| 346 |
+
"Falling back to the naive implementation. "
|
| 347 |
+
"To install follow https://github.com/state-spaces/mamba/#installation and"
|
| 348 |
+
"https://github.com/Dao-AILab/causal-conv1d"
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
def cuda_kernels_forward(
|
| 352 |
+
self,
|
| 353 |
+
hidden_states: torch.Tensor,
|
| 354 |
+
cache_params: Optional["LogLinearMamba2Cache"] = None,
|
| 355 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 356 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 357 |
+
):
|
| 358 |
+
if attention_mask is not None:
|
| 359 |
+
# only supporting this in decoding
|
| 360 |
+
if cache_params is None:
|
| 361 |
+
raise NotImplementedError
|
| 362 |
+
if self.activation not in ["silu", "swish"]:
|
| 363 |
+
raise ValueError
|
| 364 |
+
|
| 365 |
+
# 1. Gated MLP's linear projection
|
| 366 |
+
hidden_states = apply_mask_to_padding_states(
|
| 367 |
+
hidden_states=hidden_states,
|
| 368 |
+
attention_mask=attention_mask,
|
| 369 |
+
)
|
| 370 |
+
projected_states = self.in_proj(hidden_states)
|
| 371 |
+
|
| 372 |
+
# Set up dimensions for reshapes later
|
| 373 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 374 |
+
groups_time_state_size = self.n_groups * self.ssm_state_size
|
| 375 |
+
d_mlp = (
|
| 376 |
+
projected_states.shape[-1]
|
| 377 |
+
- 2 * self.intermediate_size
|
| 378 |
+
- 2 * self.n_groups * self.ssm_state_size
|
| 379 |
+
- self.num_heads * (self.num_lambda_dims + 1)
|
| 380 |
+
) // 2
|
| 381 |
+
if d_mlp != 0:
|
| 382 |
+
raise ValueError
|
| 383 |
+
|
| 384 |
+
# Single step calculations via cache
|
| 385 |
+
if (
|
| 386 |
+
cache_params is not None
|
| 387 |
+
and cache_position is not None
|
| 388 |
+
and cache_position[0] > 0
|
| 389 |
+
):
|
| 390 |
+
if hidden_states.shape[1] != 1:
|
| 391 |
+
raise ValueError
|
| 392 |
+
|
| 393 |
+
gate, xBC, dt, dl = torch.split(
|
| 394 |
+
projected_states.squeeze(1),
|
| 395 |
+
[
|
| 396 |
+
self.intermediate_size,
|
| 397 |
+
self.conv_dim,
|
| 398 |
+
self.num_heads,
|
| 399 |
+
self.num_heads * self.num_lambda_dims,
|
| 400 |
+
],
|
| 401 |
+
dim=-1,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
# 2. Convolution sequence transformation
|
| 405 |
+
xBC = causal_conv1d_update(
|
| 406 |
+
xBC,
|
| 407 |
+
cache_params.conv_states[self.layer_idx],
|
| 408 |
+
rearrange(self.conv1d.weight, "d 1 w -> d w"),
|
| 409 |
+
self.conv1d.bias,
|
| 410 |
+
self.activation,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
x, B, C = torch.split(
|
| 414 |
+
xBC,
|
| 415 |
+
[
|
| 416 |
+
self.intermediate_size,
|
| 417 |
+
groups_time_state_size,
|
| 418 |
+
groups_time_state_size,
|
| 419 |
+
],
|
| 420 |
+
dim=-1,
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
# 3. SSM transformation
|
| 424 |
+
A = -torch.exp(self.A_log.float()) # (nheads,)
|
| 425 |
+
B = rearrange(
|
| 426 |
+
B,
|
| 427 |
+
"b (g n) -> b g n",
|
| 428 |
+
b=batch_size,
|
| 429 |
+
g=self.n_groups,
|
| 430 |
+
n=self.ssm_state_size,
|
| 431 |
+
)
|
| 432 |
+
C = rearrange(
|
| 433 |
+
C,
|
| 434 |
+
"b (g n) -> b g n",
|
| 435 |
+
b=batch_size,
|
| 436 |
+
g=self.n_groups,
|
| 437 |
+
n=self.ssm_state_size,
|
| 438 |
+
)
|
| 439 |
+
x_reshaped = rearrange(
|
| 440 |
+
x,
|
| 441 |
+
"b (h p) -> b h p",
|
| 442 |
+
b=batch_size,
|
| 443 |
+
h=self.num_heads,
|
| 444 |
+
p=self.head_dim,
|
| 445 |
+
)
|
| 446 |
+
dl_reshaped = rearrange(
|
| 447 |
+
dl,
|
| 448 |
+
"b (h ell) -> b h ell",
|
| 449 |
+
b=batch_size,
|
| 450 |
+
h=self.num_heads,
|
| 451 |
+
ell=self.num_lambda_dims,
|
| 452 |
+
)
|
| 453 |
+
y, hssm_state = hmamba_chunk_scan_combined(
|
| 454 |
+
x_reshaped,
|
| 455 |
+
dt=dt,
|
| 456 |
+
A=A,
|
| 457 |
+
B=B,
|
| 458 |
+
C=C,
|
| 459 |
+
dl=dl_reshaped,
|
| 460 |
+
L=self.L,
|
| 461 |
+
D=self.D,
|
| 462 |
+
z=None,
|
| 463 |
+
dt_bias=self.dt_bias,
|
| 464 |
+
dt_softplus=True,
|
| 465 |
+
initial_states=cache_params.hssm_states[self.layer_idx],
|
| 466 |
+
return_final_states=True,
|
| 467 |
+
)
|
| 468 |
+
cache_params.update_hssm_state(
|
| 469 |
+
layer_idx=self.layer_idx,
|
| 470 |
+
new_hssm_state=hssm_state,
|
| 471 |
+
)
|
| 472 |
+
y = rearrange(
|
| 473 |
+
y,
|
| 474 |
+
"b h p -> b (h p)",
|
| 475 |
+
b=batch_size,
|
| 476 |
+
h=self.num_heads,
|
| 477 |
+
p=self.head_dim,
|
| 478 |
+
)
|
| 479 |
+
y = self.norm(y, gate)
|
| 480 |
+
|
| 481 |
+
# 4. Final linear projection
|
| 482 |
+
out = self.out_proj(y)[:, None, ...]
|
| 483 |
+
|
| 484 |
+
# Fused calculations or step by step if no initialized cache is found
|
| 485 |
+
else:
|
| 486 |
+
A = -torch.exp(
|
| 487 |
+
self.A_log.float()
|
| 488 |
+
) # (num_heads) or (intermediate_size, state_size)
|
| 489 |
+
dt_limit_kwargs = (
|
| 490 |
+
{}
|
| 491 |
+
if self.time_step_limit == (0.0, float("inf"))
|
| 492 |
+
else {"dt_limit": self.time_step_limit}
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
# 2-4. Fused kernel for conv1d, SSM, and the final projection
|
| 496 |
+
if self.training and cache_params is None:
|
| 497 |
+
out = torch.utils.checkpoint.checkpoint(
|
| 498 |
+
hmamba_split_conv1d_scan_combined,
|
| 499 |
+
use_reentrant=False,
|
| 500 |
+
# function arguments
|
| 501 |
+
zxbcdtdl=projected_states,
|
| 502 |
+
conv1d_weight=rearrange(self.conv1d.weight, "d 1 w -> d w"),
|
| 503 |
+
conv1d_bias=self.conv1d.bias,
|
| 504 |
+
dt_bias=self.dt_bias,
|
| 505 |
+
A=A,
|
| 506 |
+
L=self.L,
|
| 507 |
+
D=self.D,
|
| 508 |
+
chunk_size=self.chunk_size,
|
| 509 |
+
seq_idx=None, # was seq_idx
|
| 510 |
+
activation=self.activation,
|
| 511 |
+
rmsnorm_weight=self.norm.weight,
|
| 512 |
+
rmsnorm_eps=self.norm.eps,
|
| 513 |
+
outproj_weight=self.out_proj.weight,
|
| 514 |
+
outproj_bias=self.out_proj.bias,
|
| 515 |
+
headdim=self.head_dim,
|
| 516 |
+
ngroups=self.n_groups,
|
| 517 |
+
norm_before_gate=False,
|
| 518 |
+
return_final_states=False,
|
| 519 |
+
**dt_limit_kwargs,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
else:
|
| 523 |
+
gate, xBC, dt, dl = torch.split(
|
| 524 |
+
projected_states,
|
| 525 |
+
[
|
| 526 |
+
self.intermediate_size,
|
| 527 |
+
self.conv_dim,
|
| 528 |
+
self.num_heads,
|
| 529 |
+
self.num_heads * self.num_lambda_dims,
|
| 530 |
+
],
|
| 531 |
+
dim=-1,
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
# 2. Convolution sequence transformation
|
| 535 |
+
# Init cache
|
| 536 |
+
if cache_params is not None:
|
| 537 |
+
xBC_t = rearrange(xBC, "b l d -> b d l")
|
| 538 |
+
conv_states = torch.nn.functional.pad(
|
| 539 |
+
xBC_t,
|
| 540 |
+
(cache_params.conv_kernel_size - xBC_t.shape[-1], 0),
|
| 541 |
+
)
|
| 542 |
+
cache_params.update_conv_state(
|
| 543 |
+
layer_idx=self.layer_idx,
|
| 544 |
+
new_conv_state=conv_states,
|
| 545 |
+
cache_init=True,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
xBC = causal_conv1d_fn(
|
| 549 |
+
x=xBC.transpose(1, 2),
|
| 550 |
+
weight=rearrange(self.conv1d.weight, "d 1 w -> d w"),
|
| 551 |
+
bias=self.conv1d.bias,
|
| 552 |
+
activation=self.activation,
|
| 553 |
+
).transpose(1, 2)
|
| 554 |
+
|
| 555 |
+
xBC = apply_mask_to_padding_states(
|
| 556 |
+
hidden_states=xBC,
|
| 557 |
+
attention_mask=attention_mask,
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
x, B, C = torch.split(
|
| 561 |
+
xBC,
|
| 562 |
+
[
|
| 563 |
+
self.intermediate_size,
|
| 564 |
+
groups_time_state_size,
|
| 565 |
+
groups_time_state_size,
|
| 566 |
+
],
|
| 567 |
+
dim=-1,
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
# 3. SSM transformation
|
| 571 |
+
y, hssm_state = hmamba_chunk_scan_combined(
|
| 572 |
+
rearrange(
|
| 573 |
+
x,
|
| 574 |
+
"b l (h p) -> b l h p",
|
| 575 |
+
b=batch_size,
|
| 576 |
+
l=seq_len,
|
| 577 |
+
p=self.head_dim,
|
| 578 |
+
),
|
| 579 |
+
dt=dt,
|
| 580 |
+
A=A,
|
| 581 |
+
B=rearrange(
|
| 582 |
+
B,
|
| 583 |
+
"b l (g n) -> b l g n",
|
| 584 |
+
b=batch_size,
|
| 585 |
+
l=seq_len,
|
| 586 |
+
g=self.n_groups,
|
| 587 |
+
),
|
| 588 |
+
C=rearrange(
|
| 589 |
+
C,
|
| 590 |
+
"b l (g n) -> b l g n",
|
| 591 |
+
b=batch_size,
|
| 592 |
+
l=seq_len,
|
| 593 |
+
g=self.n_groups,
|
| 594 |
+
),
|
| 595 |
+
dl=rearrange(
|
| 596 |
+
dl,
|
| 597 |
+
"b l (h ell) -> b l h ell",
|
| 598 |
+
b=batch_size,
|
| 599 |
+
h=self.num_heads,
|
| 600 |
+
ell=self.num_lambda_dims,
|
| 601 |
+
),
|
| 602 |
+
L=self.L,
|
| 603 |
+
chunk_size=self.chunk_size,
|
| 604 |
+
D=self.D,
|
| 605 |
+
z=None,
|
| 606 |
+
seq_idx=None,
|
| 607 |
+
return_final_states=True,
|
| 608 |
+
dt_bias=self.dt_bias,
|
| 609 |
+
dt_softplus=True,
|
| 610 |
+
**dt_limit_kwargs,
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
# Init cache
|
| 614 |
+
if hssm_state is not None and cache_params is not None:
|
| 615 |
+
cache_params.update_hssm_state(
|
| 616 |
+
layer_idx=self.layer_idx,
|
| 617 |
+
new_hssm_state=hssm_state,
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
y = rearrange(
|
| 621 |
+
y,
|
| 622 |
+
"b l h p -> b l (h p)",
|
| 623 |
+
b=batch_size,
|
| 624 |
+
l=seq_len,
|
| 625 |
+
h=self.num_heads,
|
| 626 |
+
p=self.head_dim,
|
| 627 |
+
)
|
| 628 |
+
# Multiply "gate" branch and apply extra normalization layer
|
| 629 |
+
y = self.norm(y, gate)
|
| 630 |
+
|
| 631 |
+
# 4. Final linear projection
|
| 632 |
+
out = self.out_proj(y)
|
| 633 |
+
|
| 634 |
+
return out
|
| 635 |
+
|
| 636 |
+
def forward(
|
| 637 |
+
self,
|
| 638 |
+
hidden_states,
|
| 639 |
+
cache_params: Optional["LogLinearMamba2Cache"] = None,
|
| 640 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 641 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 642 |
+
):
|
| 643 |
+
if "cuda" in self.in_proj.weight.device.type:
|
| 644 |
+
return self.cuda_kernels_forward(
|
| 645 |
+
hidden_states=hidden_states,
|
| 646 |
+
cache_params=cache_params,
|
| 647 |
+
cache_position=cache_position,
|
| 648 |
+
attention_mask=attention_mask,
|
| 649 |
+
)
|
| 650 |
+
raise NotImplementedError
|
layers/mamba.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Dict, Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.utils import logging
|
| 12 |
+
|
| 13 |
+
from fla.modules.activations import ACT2FN
|
| 14 |
+
|
| 15 |
+
with warnings.catch_warnings():
|
| 16 |
+
warnings.simplefilter('ignore')
|
| 17 |
+
try:
|
| 18 |
+
from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, selective_scan_fn
|
| 19 |
+
from mamba_ssm.ops.triton.selective_state_update import selective_state_update
|
| 20 |
+
except ImportError:
|
| 21 |
+
selective_state_update, selective_scan_fn, mamba_inner_fn = None, None, None
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
|
| 25 |
+
except ImportError:
|
| 26 |
+
causal_conv1d_update, causal_conv1d_fn = None, None
|
| 27 |
+
is_fast_path_available = all((
|
| 28 |
+
selective_state_update,
|
| 29 |
+
selective_scan_fn,
|
| 30 |
+
mamba_inner_fn
|
| 31 |
+
))
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from transformers.processing_utils import Unpack
|
| 34 |
+
|
| 35 |
+
from fla.models.mamba.modeling_mamba import MambaCache
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class Mamba(nn.Module):
|
| 41 |
+
"""
|
| 42 |
+
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
|
| 43 |
+
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
|
| 44 |
+
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
|
| 45 |
+
and is why Mamba is called **selective** state spaces)
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
hidden_size: int = 2048,
|
| 51 |
+
state_size: int = 16,
|
| 52 |
+
conv_kernel: int = 4,
|
| 53 |
+
use_conv_bias: bool = True,
|
| 54 |
+
intermediate_size: int = 2048,
|
| 55 |
+
time_step_rank: int = 256,
|
| 56 |
+
use_bias: bool = True,
|
| 57 |
+
hidden_act: str = "silu",
|
| 58 |
+
layer_idx: int = None,
|
| 59 |
+
backend: str = "cuda",
|
| 60 |
+
):
|
| 61 |
+
super().__init__()
|
| 62 |
+
|
| 63 |
+
self.hidden_size = hidden_size
|
| 64 |
+
self.ssm_state_size = state_size
|
| 65 |
+
self.conv_kernel_size = conv_kernel
|
| 66 |
+
self.use_conv_bias = use_conv_bias
|
| 67 |
+
self.intermediate_size = intermediate_size
|
| 68 |
+
self.time_step_rank = time_step_rank
|
| 69 |
+
self.use_bias = use_bias
|
| 70 |
+
|
| 71 |
+
self.conv1d = nn.Conv1d(
|
| 72 |
+
in_channels=self.intermediate_size,
|
| 73 |
+
out_channels=self.intermediate_size,
|
| 74 |
+
bias=use_conv_bias,
|
| 75 |
+
kernel_size=conv_kernel,
|
| 76 |
+
groups=self.intermediate_size,
|
| 77 |
+
padding=conv_kernel - 1,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
self.activation = hidden_act
|
| 81 |
+
self.act = ACT2FN[hidden_act]
|
| 82 |
+
|
| 83 |
+
self.layer_idx = layer_idx
|
| 84 |
+
|
| 85 |
+
# projection of the input hidden states
|
| 86 |
+
self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=use_bias)
|
| 87 |
+
# selective projection used to make dt, B and C input dependant
|
| 88 |
+
self.x_proj = nn.Linear(self.intermediate_size, self.time_step_rank + self.ssm_state_size * 2, bias=False)
|
| 89 |
+
# time step projection (discretization)
|
| 90 |
+
self.dt_proj = nn.Linear(self.time_step_rank, self.intermediate_size, bias=True)
|
| 91 |
+
|
| 92 |
+
# S4D real initialization. These are not discretized!
|
| 93 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 94 |
+
A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :]
|
| 95 |
+
A = A.expand(self.intermediate_size, -1).contiguous()
|
| 96 |
+
|
| 97 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 98 |
+
self.D = nn.Parameter(torch.ones(self.intermediate_size))
|
| 99 |
+
self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=use_bias)
|
| 100 |
+
|
| 101 |
+
if not is_fast_path_available:
|
| 102 |
+
logger.warning_once(
|
| 103 |
+
"The fast path is not available because on of "
|
| 104 |
+
"`(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
|
| 105 |
+
" is None. Falling back to the naive implementation. "
|
| 106 |
+
"To install follow https://github.com/state-spaces/mamba/#installation and"
|
| 107 |
+
" https://github.com/Dao-AILab/causal-conv1d"
|
| 108 |
+
)
|
| 109 |
+
import os
|
| 110 |
+
backend = os.environ.get('FLA_CONV_BACKEND', backend)
|
| 111 |
+
assert backend in ['cuda', 'triton'], f"Unsupported backend: {backend}"
|
| 112 |
+
if backend == 'cuda' and causal_conv1d_fn is None:
|
| 113 |
+
logger.warning_once(
|
| 114 |
+
"The CUDA backend is not available because `causal_conv1d` is None. "
|
| 115 |
+
"Falling back to the Triton backend. "
|
| 116 |
+
"To install follow https://github.com/Dao-AILab/causal-conv1d"
|
| 117 |
+
)
|
| 118 |
+
backend = 'triton'
|
| 119 |
+
if backend == 'triton':
|
| 120 |
+
from fla.modules.convolution import causal_conv1d as causal_conv1d_triton
|
| 121 |
+
from fla.modules.convolution import causal_conv1d_update as causal_conv1d_update_triton
|
| 122 |
+
self.causal_conv1d_fn = causal_conv1d_triton
|
| 123 |
+
self.causal_conv1d_update = causal_conv1d_update_triton
|
| 124 |
+
else:
|
| 125 |
+
self.causal_conv1d_fn = causal_conv1d_fn
|
| 126 |
+
self.causal_conv1d_update = causal_conv1d_update
|
| 127 |
+
self.backend = backend
|
| 128 |
+
|
| 129 |
+
def cuda_kernels_forward(
|
| 130 |
+
self,
|
| 131 |
+
hidden_states: torch.Tensor,
|
| 132 |
+
cache_params: Optional[MambaCache] = None,
|
| 133 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 134 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 135 |
+
**kwargs: Unpack[Dict]
|
| 136 |
+
):
|
| 137 |
+
# 1. Gated MLP's linear projection
|
| 138 |
+
projected_states = self.in_proj(hidden_states).transpose(1, 2)
|
| 139 |
+
|
| 140 |
+
if self.training and cache_params is None: # Doesn't support outputting the states -> used for training
|
| 141 |
+
contextualized_states = mamba_inner_fn(
|
| 142 |
+
projected_states,
|
| 143 |
+
self.conv1d.weight,
|
| 144 |
+
self.conv1d.bias if self.use_conv_bias else None,
|
| 145 |
+
self.x_proj.weight,
|
| 146 |
+
self.dt_proj.weight,
|
| 147 |
+
self.out_proj.weight,
|
| 148 |
+
self.out_proj.bias.float() if self.use_bias else None,
|
| 149 |
+
-torch.exp(self.A_log.float()),
|
| 150 |
+
None, # input-dependent B
|
| 151 |
+
None, # input-dependent C
|
| 152 |
+
self.D.float(),
|
| 153 |
+
delta_bias=self.dt_proj.bias.float(),
|
| 154 |
+
delta_softplus=True,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
else:
|
| 158 |
+
hidden_states, gate = projected_states.chunk(2, dim=1)
|
| 159 |
+
|
| 160 |
+
if attention_mask is not None:
|
| 161 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 162 |
+
|
| 163 |
+
# 2. Convolution sequence transformation
|
| 164 |
+
conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2))
|
| 165 |
+
if cache_params is not None and cache_position[0] > 0:
|
| 166 |
+
hidden_states = self.causal_conv1d_update(
|
| 167 |
+
hidden_states.squeeze(-1),
|
| 168 |
+
cache_params.conv_states[self.layer_idx],
|
| 169 |
+
conv_weights,
|
| 170 |
+
self.conv1d.bias,
|
| 171 |
+
self.activation,
|
| 172 |
+
)
|
| 173 |
+
hidden_states = hidden_states.unsqueeze(-1)
|
| 174 |
+
else:
|
| 175 |
+
if cache_params is not None:
|
| 176 |
+
conv_states = nn.functional.pad(
|
| 177 |
+
hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0)
|
| 178 |
+
)
|
| 179 |
+
cache_params.update_conv_state(self.layer_idx, conv_states, cache_position)
|
| 180 |
+
hidden_states = self.causal_conv1d_fn(
|
| 181 |
+
hidden_states, conv_weights, self.conv1d.bias, activation=self.activation
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
if attention_mask is not None:
|
| 185 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 186 |
+
|
| 187 |
+
# 3. State Space Model sequence transformation
|
| 188 |
+
# 3.a. input varying initialization of time_step, B and C
|
| 189 |
+
ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
|
| 190 |
+
time_step, B, C = torch.split(
|
| 191 |
+
ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
|
| 192 |
+
)
|
| 193 |
+
discrete_time_step = self.dt_proj.weight @ time_step.transpose(1, 2)
|
| 194 |
+
|
| 195 |
+
A = -torch.exp(self.A_log.float())
|
| 196 |
+
# 3.c perform the recurrence y ← SSM(A, B, C)(x)
|
| 197 |
+
time_proj_bias = self.dt_proj.bias.float() if hasattr(self.dt_proj, "bias") else None
|
| 198 |
+
if cache_params is not None and cache_position[0] > 0:
|
| 199 |
+
scan_outputs = selective_state_update(
|
| 200 |
+
cache_params.ssm_states[self.layer_idx],
|
| 201 |
+
hidden_states[..., 0],
|
| 202 |
+
discrete_time_step[..., 0],
|
| 203 |
+
A,
|
| 204 |
+
B[:, 0],
|
| 205 |
+
C[:, 0],
|
| 206 |
+
self.D,
|
| 207 |
+
gate[..., 0],
|
| 208 |
+
time_proj_bias,
|
| 209 |
+
dt_softplus=True,
|
| 210 |
+
).unsqueeze(-1)
|
| 211 |
+
else:
|
| 212 |
+
scan_outputs, ssm_state = selective_scan_fn(
|
| 213 |
+
hidden_states,
|
| 214 |
+
discrete_time_step,
|
| 215 |
+
A,
|
| 216 |
+
B.transpose(1, 2),
|
| 217 |
+
C.transpose(1, 2),
|
| 218 |
+
self.D.float(),
|
| 219 |
+
gate,
|
| 220 |
+
time_proj_bias,
|
| 221 |
+
delta_softplus=True,
|
| 222 |
+
return_last_state=True,
|
| 223 |
+
)
|
| 224 |
+
if ssm_state is not None and cache_params is not None:
|
| 225 |
+
cache_params.update_ssm_state(self.layer_idx, ssm_state)
|
| 226 |
+
|
| 227 |
+
# 4. Final linear projection
|
| 228 |
+
contextualized_states = self.out_proj(scan_outputs.transpose(1, 2))
|
| 229 |
+
return contextualized_states
|
| 230 |
+
|
| 231 |
+
def slow_forward(
|
| 232 |
+
self,
|
| 233 |
+
input_states,
|
| 234 |
+
cache_params: Optional[MambaCache] = None,
|
| 235 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 236 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 237 |
+
**kwargs: Unpack[Dict]
|
| 238 |
+
):
|
| 239 |
+
batch_size, seq_len, _ = input_states.shape
|
| 240 |
+
dtype = input_states.dtype
|
| 241 |
+
# 1. Gated MLP's linear projection
|
| 242 |
+
# [batch, 2 * intermediate_size, seq_len]
|
| 243 |
+
projected_states = self.in_proj(input_states).transpose(1, 2)
|
| 244 |
+
hidden_states, gate = projected_states.chunk(2, dim=1)
|
| 245 |
+
|
| 246 |
+
if attention_mask is not None:
|
| 247 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 248 |
+
|
| 249 |
+
# 2. Convolution sequence transformation
|
| 250 |
+
if cache_params is not None:
|
| 251 |
+
ssm_state = cache_params.ssm_states[self.layer_idx].clone()
|
| 252 |
+
ssm_state = ssm_state.to(hidden_states.device)
|
| 253 |
+
# use `cache_position.shape[0]` to check whether we are in prefill
|
| 254 |
+
# stage, it's equivalent to check `cache_position[0] == 0`, which
|
| 255 |
+
# breaks dynamo fullgraph constraints
|
| 256 |
+
if cache_position.shape[0] == self.conv_kernel_size:
|
| 257 |
+
conv_state = nn.functional.pad(
|
| 258 |
+
hidden_states,
|
| 259 |
+
(self.conv_kernel_size - hidden_states.shape[-1], 0)
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
cache_params.update_conv_state(self.layer_idx, conv_state, cache_position)
|
| 263 |
+
# [batch, intermediate_size, seq_len]
|
| 264 |
+
hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
|
| 265 |
+
else:
|
| 266 |
+
conv_state = cache_params.update_conv_state(self.layer_idx, hidden_states, cache_position)
|
| 267 |
+
hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
|
| 268 |
+
if self.use_conv_bias:
|
| 269 |
+
hidden_states += self.conv1d.bias
|
| 270 |
+
# [batch, intermediate_size, 1] : decoding
|
| 271 |
+
hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1)
|
| 272 |
+
else:
|
| 273 |
+
ssm_state = torch.zeros(
|
| 274 |
+
(batch_size, self.intermediate_size, self.ssm_state_size),
|
| 275 |
+
device=hidden_states.device, dtype=dtype
|
| 276 |
+
)
|
| 277 |
+
# [batch, intermediate_size, seq_len]
|
| 278 |
+
hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
|
| 279 |
+
|
| 280 |
+
if attention_mask is not None:
|
| 281 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 282 |
+
|
| 283 |
+
# 3. State Space Model sequence transformation
|
| 284 |
+
# 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2]
|
| 285 |
+
ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
|
| 286 |
+
time_step, B, C = torch.split(
|
| 287 |
+
ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
|
| 288 |
+
)
|
| 289 |
+
# [batch, seq_len, intermediate_size]
|
| 290 |
+
discrete_time_step = self.dt_proj(time_step)
|
| 291 |
+
# [batch, intermediate_size, seq_len]
|
| 292 |
+
discrete_time_step = nn.functional.softplus(discrete_time_step).transpose(1, 2)
|
| 293 |
+
|
| 294 |
+
# 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM)
|
| 295 |
+
# [intermediate_size, ssm_state_size]
|
| 296 |
+
A = -torch.exp(self.A_log.float())
|
| 297 |
+
# [batch, intermediate_size, seq_len, ssm_state_size]
|
| 298 |
+
discrete_A = torch.exp(A[None, :, None, :] * discrete_time_step[:, :, :, None])
|
| 299 |
+
# [batch, intermediate_size, seq_len, ssm_state_size]
|
| 300 |
+
discrete_B = discrete_time_step[:, :, :, None] * B[:, None, :, :].float()
|
| 301 |
+
deltaB_u = discrete_B * hidden_states[:, :, :, None].float()
|
| 302 |
+
|
| 303 |
+
# 3.c perform the recurrence y ← SSM(A, B, C)(x)
|
| 304 |
+
scan_outputs = []
|
| 305 |
+
for i in range(seq_len):
|
| 306 |
+
# [batch, intermediade_size, ssm_state]
|
| 307 |
+
ssm_state = discrete_A[:, :, i, :] * ssm_state + deltaB_u[:, :, i, :]
|
| 308 |
+
# [batch, intermediade_size, 1]
|
| 309 |
+
scan_output = torch.matmul(ssm_state.to(dtype), C[:, i, :].unsqueeze(-1))
|
| 310 |
+
scan_outputs.append(scan_output[:, :, 0])
|
| 311 |
+
# [batch, seq_len, intermediade_size]
|
| 312 |
+
scan_output = torch.stack(scan_outputs, dim=-1)
|
| 313 |
+
scan_output = scan_output + (hidden_states * self.D[None, :, None])
|
| 314 |
+
scan_output = (scan_output * self.act(gate))
|
| 315 |
+
|
| 316 |
+
if cache_params is not None:
|
| 317 |
+
cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
|
| 318 |
+
|
| 319 |
+
# 4. Final linear projection
|
| 320 |
+
# [batch, seq_len, hidden_size]
|
| 321 |
+
contextualized_states = self.out_proj(scan_output.transpose(1, 2))
|
| 322 |
+
return contextualized_states
|
| 323 |
+
# fmt: on
|
| 324 |
+
|
| 325 |
+
def forward(
|
| 326 |
+
self,
|
| 327 |
+
hidden_states,
|
| 328 |
+
cache_params: Optional[MambaCache] = None,
|
| 329 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 330 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 331 |
+
**kwargs: Unpack[Dict]
|
| 332 |
+
):
|
| 333 |
+
if is_fast_path_available and "cuda" in self.x_proj.weight.device.type:
|
| 334 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, **kwargs)
|
| 335 |
+
return self.slow_forward(hidden_states, cache_params, cache_position, attention_mask, **kwargs)
|
layers/mamba2.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.utils import logging
|
| 12 |
+
|
| 13 |
+
from fla.modules.activations import ACT2FN
|
| 14 |
+
from fla.modules.layernorm_gated import RMSNormGated
|
| 15 |
+
|
| 16 |
+
with warnings.catch_warnings():
|
| 17 |
+
warnings.simplefilter('ignore')
|
| 18 |
+
try:
|
| 19 |
+
from mamba_ssm.ops.triton.selective_state_update import selective_state_update
|
| 20 |
+
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
|
| 21 |
+
except ImportError:
|
| 22 |
+
selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined = None, None, None
|
| 23 |
+
try:
|
| 24 |
+
from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
|
| 25 |
+
except ImportError:
|
| 26 |
+
causal_conv1d_update, causal_conv1d_fn = None, None
|
| 27 |
+
is_fast_path_available = selective_state_update is not None
|
| 28 |
+
|
| 29 |
+
if TYPE_CHECKING:
|
| 30 |
+
from fla.models.mamba2.modeling_mamba2 import Mamba2Cache
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def apply_mask_to_padding_states(hidden_states, attention_mask):
|
| 36 |
+
"""
|
| 37 |
+
Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 38 |
+
"""
|
| 39 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 40 |
+
dtype = hidden_states.dtype
|
| 41 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 42 |
+
|
| 43 |
+
return hidden_states
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
|
| 47 |
+
"""
|
| 48 |
+
Padding x tensor with `pad_size` on the seq_len dim (dim=1)
|
| 49 |
+
|
| 50 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 51 |
+
"""
|
| 52 |
+
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)
|
| 53 |
+
|
| 54 |
+
return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def reshape_into_chunks(input_tensor, pad_size, chunk_size):
|
| 58 |
+
"""
|
| 59 |
+
Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
|
| 60 |
+
simultaneously splitting it into chunk sequences.
|
| 61 |
+
|
| 62 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 63 |
+
"""
|
| 64 |
+
# [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
|
| 65 |
+
input_tensor = pad_tensor_by_size(input_tensor, pad_size)
|
| 66 |
+
|
| 67 |
+
if len(input_tensor.shape) == 3:
|
| 68 |
+
# [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
|
| 69 |
+
return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
|
| 70 |
+
else:
|
| 71 |
+
# [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] ->
|
| 72 |
+
# [bsz, -1, chunk_size, num_heads, head_dim or state_size]
|
| 73 |
+
return input_tensor.reshape(
|
| 74 |
+
input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def segment_sum(input_tensor):
|
| 79 |
+
"""
|
| 80 |
+
More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
|
| 81 |
+
"""
|
| 82 |
+
chunk_size = input_tensor.size(-1)
|
| 83 |
+
# 1. expand input tensor to have an additional dimension and repeat along that dimension
|
| 84 |
+
# [..., chunk_size] -> [..., chunk_size, chunk_size]
|
| 85 |
+
input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
|
| 86 |
+
# 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
|
| 87 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
|
| 88 |
+
input_tensor = input_tensor.masked_fill(~mask, 0)
|
| 89 |
+
# 3. compute actual cumsum
|
| 90 |
+
tensor_segsum = torch.cumsum(input_tensor, dim=-2)
|
| 91 |
+
|
| 92 |
+
# 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
|
| 93 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
|
| 94 |
+
tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
|
| 95 |
+
return tensor_segsum
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class Mamba2(nn.Module):
|
| 99 |
+
"""
|
| 100 |
+
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
|
| 101 |
+
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
|
| 102 |
+
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
|
| 103 |
+
and is why Mamba is called **selective** state spaces)
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
num_heads: int,
|
| 109 |
+
head_dim: int = 64,
|
| 110 |
+
hidden_size: int = 2048,
|
| 111 |
+
state_size: int = 128,
|
| 112 |
+
expand: int = 2,
|
| 113 |
+
n_groups: int = 1,
|
| 114 |
+
conv_kernel: int = 4,
|
| 115 |
+
use_conv_bias: bool = False,
|
| 116 |
+
hidden_act: str = "silu",
|
| 117 |
+
rms_norm: bool = True,
|
| 118 |
+
chunk_size: int = 256,
|
| 119 |
+
time_step_rank: float = 256,
|
| 120 |
+
time_step_limit: Tuple[float, float] = (0.0, float("inf")),
|
| 121 |
+
time_step_min: float = 0.001,
|
| 122 |
+
time_step_max: float = 0.1,
|
| 123 |
+
use_bias: bool = True,
|
| 124 |
+
norm_eps: float = 1e-5,
|
| 125 |
+
layer_idx: int = None,
|
| 126 |
+
backend: str = "cuda",
|
| 127 |
+
) -> Mamba2:
|
| 128 |
+
super().__init__()
|
| 129 |
+
|
| 130 |
+
self.num_heads = num_heads
|
| 131 |
+
self.head_dim = head_dim
|
| 132 |
+
self.hidden_size = hidden_size
|
| 133 |
+
self.ssm_state_size = state_size
|
| 134 |
+
self.expand = expand
|
| 135 |
+
self.intermediate_size = int(expand * hidden_size)
|
| 136 |
+
self.n_groups = n_groups
|
| 137 |
+
|
| 138 |
+
self.conv_kernel_size = conv_kernel
|
| 139 |
+
self.use_conv_bias = use_conv_bias
|
| 140 |
+
self.activation = hidden_act
|
| 141 |
+
self.act = ACT2FN[hidden_act]
|
| 142 |
+
|
| 143 |
+
self.rms_norm = rms_norm
|
| 144 |
+
self.norm_eps = norm_eps
|
| 145 |
+
|
| 146 |
+
self.chunk_size = chunk_size
|
| 147 |
+
|
| 148 |
+
self.time_step_rank = int(time_step_rank)
|
| 149 |
+
self.time_step_limit = time_step_limit
|
| 150 |
+
self.time_step_min = time_step_min
|
| 151 |
+
self.time_step_max = time_step_max
|
| 152 |
+
|
| 153 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 154 |
+
self.conv1d = nn.Conv1d(
|
| 155 |
+
in_channels=self.conv_dim,
|
| 156 |
+
out_channels=self.conv_dim,
|
| 157 |
+
bias=use_conv_bias,
|
| 158 |
+
kernel_size=conv_kernel,
|
| 159 |
+
groups=self.conv_dim,
|
| 160 |
+
padding=conv_kernel - 1,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# projection of the input hidden states
|
| 164 |
+
projection_size = self.intermediate_size + self.conv_dim + self.num_heads
|
| 165 |
+
self.in_proj = nn.Linear(
|
| 166 |
+
self.hidden_size,
|
| 167 |
+
projection_size,
|
| 168 |
+
bias=use_bias,
|
| 169 |
+
)
|
| 170 |
+
# selective projection used to make dt, B and C input dependant
|
| 171 |
+
|
| 172 |
+
# time step projection (discretization)
|
| 173 |
+
# instantiate once and copy inv_dt in init_weights of PretrainedModel
|
| 174 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 175 |
+
|
| 176 |
+
# S4D real initialization. These are not discretized!
|
| 177 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 178 |
+
A = torch.arange(1, self.num_heads + 1)
|
| 179 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 180 |
+
self.A_log._no_weight_decay = True
|
| 181 |
+
self.norm = RMSNormGated(
|
| 182 |
+
self.intermediate_size, eps=self.norm_eps, norm_before_gate=False
|
| 183 |
+
)
|
| 184 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 185 |
+
self.D._no_weight_decay = True
|
| 186 |
+
|
| 187 |
+
self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=use_bias)
|
| 188 |
+
self.use_bias = use_bias
|
| 189 |
+
|
| 190 |
+
self.layer_idx = layer_idx
|
| 191 |
+
|
| 192 |
+
if not is_fast_path_available:
|
| 193 |
+
logger.warning_once(
|
| 194 |
+
"The fast path is not available because one of "
|
| 195 |
+
"`(selective_state_update)` is None. "
|
| 196 |
+
"Falling back to the naive implementation. "
|
| 197 |
+
"To install follow https://github.com/state-spaces/mamba/#installation"
|
| 198 |
+
)
|
| 199 |
+
import os
|
| 200 |
+
backend = os.environ.get('FLA_CONV_BACKEND', backend)
|
| 201 |
+
assert backend in ['cuda', 'triton'], f"Unsupported backend: {backend}"
|
| 202 |
+
if backend == 'cuda' and causal_conv1d_fn is None:
|
| 203 |
+
logger.warning_once(
|
| 204 |
+
"The CUDA backend is not available because `causal_conv1d` is None. "
|
| 205 |
+
"Falling back to the Triton backend. "
|
| 206 |
+
"To install follow https://github.com/Dao-AILab/causal-conv1d"
|
| 207 |
+
)
|
| 208 |
+
backend = 'triton'
|
| 209 |
+
if backend == 'triton':
|
| 210 |
+
from fla.modules.convolution import causal_conv1d as causal_conv1d_triton
|
| 211 |
+
from fla.modules.convolution import causal_conv1d_update as causal_conv1d_update_triton
|
| 212 |
+
self.causal_conv1d_fn = causal_conv1d_triton
|
| 213 |
+
self.causal_conv1d_update = causal_conv1d_update_triton
|
| 214 |
+
logger.warning(
|
| 215 |
+
"Mamba2 does not recommend using Triton's conv1d backend, "
|
| 216 |
+
"as it is untested and may contain bugs."
|
| 217 |
+
)
|
| 218 |
+
else:
|
| 219 |
+
self.causal_conv1d_fn = causal_conv1d_fn
|
| 220 |
+
self.causal_conv1d_update = causal_conv1d_update
|
| 221 |
+
self.backend = backend
|
| 222 |
+
|
| 223 |
+
def cuda_kernels_forward(
|
| 224 |
+
self,
|
| 225 |
+
hidden_states: torch.Tensor,
|
| 226 |
+
cache_params: Optional[Mamba2Cache] = None,
|
| 227 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 228 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 229 |
+
):
|
| 230 |
+
# 1. Gated MLP's linear projection
|
| 231 |
+
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
| 232 |
+
projected_states = self.in_proj(hidden_states)
|
| 233 |
+
|
| 234 |
+
# Set up dimensions for reshapes later
|
| 235 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 236 |
+
groups_time_state_size = self.n_groups * self.ssm_state_size
|
| 237 |
+
d_mlp = (
|
| 238 |
+
projected_states.shape[-1]
|
| 239 |
+
- 2 * self.intermediate_size
|
| 240 |
+
- 2 * self.n_groups * self.ssm_state_size
|
| 241 |
+
- self.num_heads
|
| 242 |
+
) // 2
|
| 243 |
+
|
| 244 |
+
# Single step calculations via cache
|
| 245 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 246 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
|
| 247 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
# 2. Convolution sequence transformation
|
| 251 |
+
hidden_states_B_C = self.causal_conv1d_update(
|
| 252 |
+
hidden_states_B_C.contiguous(),
|
| 253 |
+
cache_params.conv_states[self.layer_idx],
|
| 254 |
+
self.conv1d.weight.squeeze(1),
|
| 255 |
+
self.conv1d.bias,
|
| 256 |
+
self.activation,
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
hidden_states, B, C = torch.split(
|
| 260 |
+
hidden_states_B_C,
|
| 261 |
+
[
|
| 262 |
+
self.intermediate_size,
|
| 263 |
+
groups_time_state_size,
|
| 264 |
+
groups_time_state_size,
|
| 265 |
+
],
|
| 266 |
+
dim=-1,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# 3. SSM transformation
|
| 270 |
+
A = -torch.exp(self.A_log.float()) # (nheads,)
|
| 271 |
+
A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 272 |
+
dt = dt[:, :, None].expand(-1, -1, self.head_dim)
|
| 273 |
+
dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
|
| 274 |
+
D = self.D[:, None, ...].expand(-1, self.head_dim)
|
| 275 |
+
B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
|
| 276 |
+
C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
|
| 277 |
+
hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
|
| 278 |
+
|
| 279 |
+
hidden_states = selective_state_update(
|
| 280 |
+
cache_params.ssm_states[self.layer_idx],
|
| 281 |
+
hidden_states_reshaped,
|
| 282 |
+
dt,
|
| 283 |
+
A,
|
| 284 |
+
B,
|
| 285 |
+
C,
|
| 286 |
+
D,
|
| 287 |
+
z=None,
|
| 288 |
+
dt_bias=dt_bias,
|
| 289 |
+
dt_softplus=True,
|
| 290 |
+
)
|
| 291 |
+
hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
|
| 292 |
+
hidden_states = self.norm(hidden_states, gate)
|
| 293 |
+
|
| 294 |
+
# 4. Final linear projection
|
| 295 |
+
out = self.out_proj(hidden_states)[:, None, ...]
|
| 296 |
+
|
| 297 |
+
# Fused calculations or step by step if no initialized cache is found
|
| 298 |
+
else:
|
| 299 |
+
A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
|
| 300 |
+
dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
|
| 301 |
+
|
| 302 |
+
# 2-4. Fused kernel for conv1d, SSM, and the final projection
|
| 303 |
+
if self.training and cache_params is None:
|
| 304 |
+
out = mamba_split_conv1d_scan_combined(
|
| 305 |
+
projected_states,
|
| 306 |
+
self.conv1d.weight.squeeze(1),
|
| 307 |
+
self.conv1d.bias,
|
| 308 |
+
self.dt_bias,
|
| 309 |
+
A,
|
| 310 |
+
D=self.D,
|
| 311 |
+
chunk_size=self.chunk_size,
|
| 312 |
+
seq_idx=None, # was seq_idx
|
| 313 |
+
activation=self.activation,
|
| 314 |
+
rmsnorm_weight=self.norm.weight,
|
| 315 |
+
rmsnorm_eps=self.norm.eps,
|
| 316 |
+
outproj_weight=self.out_proj.weight,
|
| 317 |
+
outproj_bias=self.out_proj.bias,
|
| 318 |
+
headdim=self.head_dim,
|
| 319 |
+
ngroups=self.n_groups,
|
| 320 |
+
norm_before_gate=False,
|
| 321 |
+
return_final_states=False,
|
| 322 |
+
**dt_limit_kwargs,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
else:
|
| 326 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.split(
|
| 327 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
# 2. Convolution sequence transformation
|
| 331 |
+
# Init cache
|
| 332 |
+
if cache_params is not None:
|
| 333 |
+
hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
|
| 334 |
+
conv_states = nn.functional.pad(
|
| 335 |
+
hidden_states_B_C_transposed,
|
| 336 |
+
(cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
|
| 337 |
+
)
|
| 338 |
+
cache_params.update_conv_state(
|
| 339 |
+
layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
if self.activation not in ["silu", "swish"]:
|
| 343 |
+
hidden_states_B_C = self.act(
|
| 344 |
+
self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
|
| 345 |
+
)
|
| 346 |
+
else:
|
| 347 |
+
_conv1d_output = self.causal_conv1d_fn(
|
| 348 |
+
x=hidden_states_B_C.transpose(1, 2).contiguous(),
|
| 349 |
+
weight=self.conv1d.weight.squeeze(1),
|
| 350 |
+
bias=self.conv1d.bias,
|
| 351 |
+
activation=self.activation,
|
| 352 |
+
)
|
| 353 |
+
if self.backend == 'cuda':
|
| 354 |
+
hidden_states_B_C = _conv1d_output
|
| 355 |
+
hidden_states_B_C = hidden_states_B_C.transpose(1, 2)
|
| 356 |
+
elif self.backend == 'triton':
|
| 357 |
+
hidden_states_B_C, _ = _conv1d_output
|
| 358 |
+
hidden_states_B_C = hidden_states_B_C.transpose(1, 2).contiguous()
|
| 359 |
+
else:
|
| 360 |
+
raise ValueError(f"Unsupported backend: {self.backend}")
|
| 361 |
+
|
| 362 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 363 |
+
hidden_states, B, C = torch.split(
|
| 364 |
+
hidden_states_B_C,
|
| 365 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 366 |
+
dim=-1,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
# 3. SSM transformation
|
| 370 |
+
scan_output, ssm_state = mamba_chunk_scan_combined(
|
| 371 |
+
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
| 372 |
+
dt,
|
| 373 |
+
A,
|
| 374 |
+
B.view(batch_size, seq_len, self.n_groups, -1),
|
| 375 |
+
C.view(batch_size, seq_len, self.n_groups, -1),
|
| 376 |
+
chunk_size=self.chunk_size,
|
| 377 |
+
D=self.D,
|
| 378 |
+
z=None,
|
| 379 |
+
seq_idx=None,
|
| 380 |
+
return_final_states=True,
|
| 381 |
+
dt_bias=self.dt_bias,
|
| 382 |
+
dt_softplus=True,
|
| 383 |
+
**dt_limit_kwargs,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
# Init cache
|
| 387 |
+
if ssm_state is not None and cache_params is not None:
|
| 388 |
+
cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
|
| 389 |
+
|
| 390 |
+
scan_output = scan_output.view(batch_size, seq_len, -1)
|
| 391 |
+
# Multiply "gate" branch and apply extra normalization layer
|
| 392 |
+
scan_output = self.norm(scan_output, gate)
|
| 393 |
+
|
| 394 |
+
# 4. Final linear projection
|
| 395 |
+
out = self.out_proj(scan_output)
|
| 396 |
+
return out
|
| 397 |
+
|
| 398 |
+
# fmt: off
|
| 399 |
+
def torch_forward(
|
| 400 |
+
self,
|
| 401 |
+
input_states,
|
| 402 |
+
cache_params: Optional[Mamba2Cache] = None,
|
| 403 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.Tensor] = None
|
| 405 |
+
):
|
| 406 |
+
batch_size, seq_len, _ = input_states.shape
|
| 407 |
+
dtype = input_states.dtype
|
| 408 |
+
|
| 409 |
+
# 1. Gated MLP's linear projection
|
| 410 |
+
input_states = apply_mask_to_padding_states(input_states, attention_mask)
|
| 411 |
+
projected_states = self.in_proj(input_states)
|
| 412 |
+
d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size -
|
| 413 |
+
2 * self.n_groups * self.ssm_state_size - self.num_heads) // 2
|
| 414 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.split(
|
| 415 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# 2. Convolution sequence transformation
|
| 419 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 420 |
+
cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
|
| 421 |
+
|
| 422 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 423 |
+
conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
|
| 424 |
+
|
| 425 |
+
hidden_states_B_C = torch.sum(
|
| 426 |
+
conv_states * self.conv1d.weight.squeeze(1), dim=-1
|
| 427 |
+
)
|
| 428 |
+
if self.use_conv_bias:
|
| 429 |
+
hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
|
| 430 |
+
hidden_states_B_C = self.act(hidden_states_B_C)
|
| 431 |
+
else:
|
| 432 |
+
# Init cache
|
| 433 |
+
if cache_params is not None:
|
| 434 |
+
hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
|
| 435 |
+
conv_states = nn.functional.pad(
|
| 436 |
+
hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
|
| 437 |
+
)
|
| 438 |
+
cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
|
| 439 |
+
|
| 440 |
+
hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
|
| 441 |
+
|
| 442 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 443 |
+
hidden_states, B, C = torch.split(
|
| 444 |
+
hidden_states_B_C,
|
| 445 |
+
[self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
|
| 446 |
+
dim=-1
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
# 3. SSM transformation
|
| 450 |
+
A = -torch.exp(self.A_log.float()) # [num_heads]
|
| 451 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 452 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 453 |
+
cache_device = cache_params.ssm_states.device
|
| 454 |
+
|
| 455 |
+
# Note: there is no need to pad parameter matrices here, as there is just one new token
|
| 456 |
+
# for batched generation
|
| 457 |
+
dt = dt[:, 0, :][:, None, ...]
|
| 458 |
+
dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
|
| 459 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 460 |
+
dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
|
| 461 |
+
|
| 462 |
+
dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
|
| 463 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 464 |
+
A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 465 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 466 |
+
dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
|
| 467 |
+
|
| 468 |
+
# Discretize B
|
| 469 |
+
# [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
|
| 470 |
+
# -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
|
| 471 |
+
B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 472 |
+
B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
|
| 473 |
+
B = B.reshape(batch_size, -1, B.shape[-1])
|
| 474 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 475 |
+
dB = dt[..., None] * B[..., None, :]
|
| 476 |
+
|
| 477 |
+
# Discretize x into dB
|
| 478 |
+
# [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
|
| 479 |
+
hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
|
| 480 |
+
dBx = (dB * hidden_states[..., None]).to(device=cache_device)
|
| 481 |
+
|
| 482 |
+
# State calculation
|
| 483 |
+
cache_params.update_ssm_state(
|
| 484 |
+
layer_idx=self.layer_idx,
|
| 485 |
+
new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# Subsequent output
|
| 489 |
+
# [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
|
| 490 |
+
C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 491 |
+
C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
|
| 492 |
+
C = C.reshape(batch_size, -1, C.shape[-1])
|
| 493 |
+
# [bsz, num_heads, head_dim]
|
| 494 |
+
|
| 495 |
+
ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
|
| 496 |
+
# Reshape ssm_states to merge the first two dimensions
|
| 497 |
+
# Shape: [b*h, d, n]
|
| 498 |
+
ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size)
|
| 499 |
+
C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
|
| 500 |
+
y = torch.bmm(ssm_states_reshaped, C_reshaped)
|
| 501 |
+
y = y.view(batch_size, self.num_heads, self.head_dim)
|
| 502 |
+
|
| 503 |
+
# D skip connection
|
| 504 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 505 |
+
D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
|
| 506 |
+
y = (y + hidden_states * D).to(y.dtype)
|
| 507 |
+
|
| 508 |
+
# [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
|
| 509 |
+
y = y.reshape(batch_size, -1)[:, None, ...]
|
| 510 |
+
else:
|
| 511 |
+
# begin ssd naive implementation without einsums
|
| 512 |
+
dt = nn.functional.softplus(dt + self.dt_bias)
|
| 513 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 514 |
+
hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
|
| 515 |
+
B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 516 |
+
C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 517 |
+
B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
|
| 518 |
+
C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
|
| 519 |
+
pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
|
| 520 |
+
|
| 521 |
+
D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
|
| 522 |
+
|
| 523 |
+
# Discretize x and A
|
| 524 |
+
hidden_states = hidden_states * dt[..., None]
|
| 525 |
+
A = A.to(hidden_states.dtype) * dt
|
| 526 |
+
|
| 527 |
+
# Rearrange into blocks/chunks
|
| 528 |
+
hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
|
| 529 |
+
|
| 530 |
+
# [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
|
| 531 |
+
A = A.permute(0, 3, 1, 2)
|
| 532 |
+
A_cumsum = torch.cumsum(A, dim=-1)
|
| 533 |
+
|
| 534 |
+
# 1. Compute the output for each intra-chunk (diagonal blocks)
|
| 535 |
+
# This is the analog of a causal mask
|
| 536 |
+
L = torch.exp(segment_sum(A))
|
| 537 |
+
|
| 538 |
+
# Contraction of C and B to get G (attention-weights like)
|
| 539 |
+
# shape: (b, c, l, s, h, n)
|
| 540 |
+
G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :]
|
| 541 |
+
G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
|
| 542 |
+
|
| 543 |
+
# Compute M, equivalent to applying attention mask to weights
|
| 544 |
+
M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
|
| 545 |
+
M = M_intermediate.sum(dim=-1)
|
| 546 |
+
|
| 547 |
+
# Compute Y_diag (apply to values)
|
| 548 |
+
Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
|
| 549 |
+
|
| 550 |
+
# 2. Compute the state for each intra-chunk
|
| 551 |
+
# (right term of low-rank factorization of off-diagonal blocks; B terms)
|
| 552 |
+
decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
|
| 553 |
+
B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
|
| 554 |
+
states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
|
| 555 |
+
|
| 556 |
+
# 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
|
| 557 |
+
# (middle term of factorization of off-diag blocks; A terms)
|
| 558 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 559 |
+
previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
|
| 560 |
+
else:
|
| 561 |
+
previous_states = torch.zeros_like(states[:, :1])
|
| 562 |
+
states = torch.cat([previous_states, states], dim=1)
|
| 563 |
+
decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
|
| 564 |
+
decay_chunk = decay_chunk.transpose(1, 3)
|
| 565 |
+
new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
|
| 566 |
+
states, ssm_state = new_states[:, :-1], new_states[:, -1]
|
| 567 |
+
|
| 568 |
+
# 4. Compute state -> output conversion per chunk
|
| 569 |
+
# (left term of low-rank factorization of off-diagonal blocks; C terms)
|
| 570 |
+
state_decay_out = torch.exp(A_cumsum)
|
| 571 |
+
C_times_states = (C[..., None, :] * states[:, :, None, ...])
|
| 572 |
+
state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
|
| 573 |
+
Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
|
| 574 |
+
|
| 575 |
+
# Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
|
| 576 |
+
y = Y_diag + Y_off
|
| 577 |
+
# [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
|
| 578 |
+
y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
|
| 579 |
+
|
| 580 |
+
y = y + D_residual
|
| 581 |
+
# Cutting off padded chunks
|
| 582 |
+
if pad_size > 0:
|
| 583 |
+
y = y[:, :seq_len, :, :]
|
| 584 |
+
y = y.reshape(batch_size, seq_len, -1)
|
| 585 |
+
|
| 586 |
+
# Init cache
|
| 587 |
+
if ssm_state is not None and cache_params is not None:
|
| 588 |
+
cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
|
| 589 |
+
|
| 590 |
+
scan_output = self.norm(y, gate)
|
| 591 |
+
|
| 592 |
+
# end ssd naive
|
| 593 |
+
|
| 594 |
+
# 4. Final linear projection
|
| 595 |
+
contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
|
| 596 |
+
return contextualized_states
|
| 597 |
+
# fmt: on
|
| 598 |
+
|
| 599 |
+
def forward(
|
| 600 |
+
self,
|
| 601 |
+
hidden_states,
|
| 602 |
+
cache_params: Optional[Mamba2Cache] = None,
|
| 603 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 604 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 605 |
+
):
|
| 606 |
+
if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
|
| 607 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
|
| 608 |
+
dtype = hidden_states.dtype
|
| 609 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 610 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 611 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 612 |
+
|
| 613 |
+
return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
|
layers/mask_gdn.py
ADDED
|
@@ -0,0 +1,1058 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from einops import rearrange, repeat
|
| 10 |
+
from ..modules import FusedRMSNormSwishGate, RMSNorm
|
| 11 |
+
from fla.modules import ShortConvolution
|
| 12 |
+
import torch.nn.init as init
|
| 13 |
+
import math
|
| 14 |
+
from ..modules.l2norm import l2norm
|
| 15 |
+
from einops import rearrange
|
| 16 |
+
from fla.models.utils import Cache
|
| 17 |
+
from transformers.processing_utils import Unpack
|
| 18 |
+
import math
|
| 19 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 20 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 21 |
+
# from ..modules import RotaryEmbedding
|
| 22 |
+
# from ..ops.gla import chunk_gla,fused_recurrent_gla
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def simple_norm(x):
|
| 26 |
+
return (F.normalize(x, dim=-1) * x.shape[-1] ** 0.5).to(x)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# @torch.jit.script
|
| 30 |
+
def elu_p1(x):
|
| 31 |
+
return (F.elu(x, 1., False) + 1.).to(x)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# @torch.jit.script
|
| 35 |
+
def sum_norm(x):
|
| 36 |
+
return (x / x.sum(-1, keepdim=True)).to(x)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# @torch.jit.script
|
| 40 |
+
def elu_norm(x):
|
| 41 |
+
dtype = x.dtype
|
| 42 |
+
x = F.elu(x, 1., False) + 1.
|
| 43 |
+
return (x / x.sum(-1, keepdim=True)).to(dtype)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# from ..ops.mask_gated_delta_rule import mask_gated_chunk_delta_rule
|
| 47 |
+
# class mask_gdn(nn.Module):
|
| 48 |
+
# def __init__(
|
| 49 |
+
# self,
|
| 50 |
+
# d_model: int = None,
|
| 51 |
+
# hidden_size: int = 1024,
|
| 52 |
+
# expand_k: float = 1.0,
|
| 53 |
+
# expand_v: float = 1.0,
|
| 54 |
+
# num_heads: int = 4,
|
| 55 |
+
# mode: str = 'chunk',
|
| 56 |
+
# chunk_size: int = 64,
|
| 57 |
+
# use_beta: bool = True,
|
| 58 |
+
# use_gate: bool = False,
|
| 59 |
+
# use_output_norm: bool = True,
|
| 60 |
+
# use_elu: bool = False,
|
| 61 |
+
# use_short_conv: bool = True,
|
| 62 |
+
# conv_size: int = 4,
|
| 63 |
+
# conv_bias: bool = False,
|
| 64 |
+
# layer_idx: int = None,
|
| 65 |
+
# qk_activation: str = 'silu',
|
| 66 |
+
# qk_norm: str = 'l2',
|
| 67 |
+
# norm_first: bool = False,
|
| 68 |
+
# norm_eps: float = 1e-6,
|
| 69 |
+
# ratio :int = 2,
|
| 70 |
+
# topk : int = 1 ,
|
| 71 |
+
# **kwargs
|
| 72 |
+
# ) :
|
| 73 |
+
# super().__init__()
|
| 74 |
+
|
| 75 |
+
# self.mode = mode
|
| 76 |
+
# self.qk_activation = qk_activation
|
| 77 |
+
# self.qk_norm = qk_norm
|
| 78 |
+
|
| 79 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 80 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 81 |
+
|
| 82 |
+
# if d_model is not None:
|
| 83 |
+
# hidden_size = d_model
|
| 84 |
+
# self.hidden_size = hidden_size
|
| 85 |
+
# self.expand_k = expand_k
|
| 86 |
+
# self.expand_v = expand_v
|
| 87 |
+
# self.num_heads = num_heads
|
| 88 |
+
# self.chunk_size = chunk_size
|
| 89 |
+
# self.use_gate = use_gate
|
| 90 |
+
# self.use_output_norm = use_output_norm
|
| 91 |
+
# self.use_short_conv = use_short_conv
|
| 92 |
+
# self.conv_size = conv_size
|
| 93 |
+
# self.conv_bias = conv_bias
|
| 94 |
+
|
| 95 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 96 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 97 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 98 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 99 |
+
# self.norm_first = norm_first
|
| 100 |
+
# self.layer_idx = layer_idx
|
| 101 |
+
# self.top_k = topk
|
| 102 |
+
# self.silu = nn.SiLU()
|
| 103 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 104 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 105 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 106 |
+
# if norm_first:
|
| 107 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 108 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 109 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 110 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 111 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 112 |
+
|
| 113 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 114 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 115 |
+
# self.A_log._no_weight_decay = True
|
| 116 |
+
# # hard coded for now
|
| 117 |
+
# dt_min = 0.001
|
| 118 |
+
# dt_max = 0.1
|
| 119 |
+
# dt_init_floor = 1e-4
|
| 120 |
+
# dt = torch.exp(
|
| 121 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 122 |
+
# + math.log(dt_min)
|
| 123 |
+
# )
|
| 124 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 125 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 126 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 127 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 128 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 129 |
+
# # name.endswith("bias") in param_grouping.py
|
| 130 |
+
# self.dt_bias._no_weight_decay = True
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# self.use_beta = use_beta
|
| 134 |
+
# self.use_elu = use_elu
|
| 135 |
+
# if self.use_beta:
|
| 136 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 137 |
+
# if use_short_conv:
|
| 138 |
+
# self.conv_size = conv_size
|
| 139 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 140 |
+
# conv_size,
|
| 141 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 142 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 143 |
+
# conv_size,
|
| 144 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 145 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 146 |
+
# if use_gate:
|
| 147 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 148 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 149 |
+
# else:
|
| 150 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 151 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 152 |
+
# r = self.r = 4
|
| 153 |
+
# self.mask = nn.Parameter(torch.empty([r,r],dtype=self.o_proj.weight.dtype),requires_grad=True)
|
| 154 |
+
# self.mask_requiregrad = True
|
| 155 |
+
# print('mask_gdn_learn_mask_qk_r4')
|
| 156 |
+
# init.kaiming_uniform_(self.mask, a=math.sqrt(5))
|
| 157 |
+
# assert self.head_qk_dim % r == 0
|
| 158 |
+
# self.apply(self._initialize_weights)
|
| 159 |
+
|
| 160 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 161 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 162 |
+
# return
|
| 163 |
+
# if isinstance(module, nn.Linear):
|
| 164 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 165 |
+
# if module.bias is not None:
|
| 166 |
+
# nn.init.zeros_(module.bias)
|
| 167 |
+
# module._is_hf_initialized = True
|
| 168 |
+
|
| 169 |
+
# def delta_rule_recurrence(self,q, k, v, beta, mask,initial_state=None,output_final_state=True):
|
| 170 |
+
# b, h, l, d_k = q.shape
|
| 171 |
+
# d_v = v.shape[-1]
|
| 172 |
+
# r = mask.shape[-1]
|
| 173 |
+
# o = torch.zeros_like(v)
|
| 174 |
+
# if initial_state == None:
|
| 175 |
+
# S = torch.zeros(b, h, d_k, d_v).to(v).float()
|
| 176 |
+
# else:
|
| 177 |
+
# S = initial_state
|
| 178 |
+
# q = q * (d_k ** -0.5)
|
| 179 |
+
# if beta.ndim < v.ndim:
|
| 180 |
+
# beta = beta[..., None]
|
| 181 |
+
# if self.training:
|
| 182 |
+
# for i in range(l):
|
| 183 |
+
# _k = k[:, :, i]
|
| 184 |
+
# _q = q[:, :, i]
|
| 185 |
+
# _v = v[:, :, i].clone()
|
| 186 |
+
# beta_i = beta[:, :, i]
|
| 187 |
+
# _v = _v * beta_i
|
| 188 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 189 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 190 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 191 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 192 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 193 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2)
|
| 194 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
|
| 195 |
+
# return o,S
|
| 196 |
+
# else:
|
| 197 |
+
# for i in range(l):
|
| 198 |
+
# _k = k[:, :, i]
|
| 199 |
+
# _q = q[:, :, i]
|
| 200 |
+
# _v = v[:, :, i]
|
| 201 |
+
# beta_i = beta[:, :, i]
|
| 202 |
+
# _v = _v * beta_i
|
| 203 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 204 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 205 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 206 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 207 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 208 |
+
# 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()
|
| 209 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype)
|
| 210 |
+
# return o,S
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# def forward(
|
| 214 |
+
# self,
|
| 215 |
+
# hidden_states: torch.Tensor,
|
| 216 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 217 |
+
# past_key_values: Optional[Cache] = None,
|
| 218 |
+
# use_cache: Optional[bool] = False,
|
| 219 |
+
# output_attentions: Optional[bool] = False,
|
| 220 |
+
# **kwargs
|
| 221 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 222 |
+
# # change to inference mode.
|
| 223 |
+
# mode = 'chunk'#'recurrent' if hidden_states.shape[1] < 64 else self.mode
|
| 224 |
+
# b,q_len,d = hidden_states.shape
|
| 225 |
+
# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states)
|
| 226 |
+
# if self.norm_first:
|
| 227 |
+
# hidden_states = self.norm(hidden_states)
|
| 228 |
+
|
| 229 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 230 |
+
# # if attention_mask is not None:
|
| 231 |
+
# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 232 |
+
# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 233 |
+
# last_state = None
|
| 234 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 235 |
+
# last_state = past_key_values[self.layer_idx]
|
| 236 |
+
# offset = past_key_values.get_seq_length()
|
| 237 |
+
# # if attention_mask is not None:
|
| 238 |
+
# # if attention_mask.shape[-1] != hidden_states.shape[-2]:
|
| 239 |
+
# # attention_mask = attention_mask[:, -1:]
|
| 240 |
+
# if self.use_short_conv:
|
| 241 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 242 |
+
# if last_state is not None:
|
| 243 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 244 |
+
# q = self.q_proj(hidden_states)
|
| 245 |
+
# k = self.k_proj(hidden_states)
|
| 246 |
+
# v = self.v_proj(hidden_states)
|
| 247 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 248 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 249 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 250 |
+
# else:
|
| 251 |
+
# q = self.q_proj(hidden_states)
|
| 252 |
+
# k = self.k_proj(hidden_states)
|
| 253 |
+
# v = self.v_proj(hidden_states)
|
| 254 |
+
# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v))
|
| 255 |
+
# if self.qk_activation != 'silu':
|
| 256 |
+
# if self.qk_activation == 'relu':
|
| 257 |
+
# q, k = q.relu(), k.relu()
|
| 258 |
+
# elif self.qk_activation == 'elu':
|
| 259 |
+
# q, k = elu_p1(q), elu_p1(k)
|
| 260 |
+
# elif self.qk_activation == 'identity':
|
| 261 |
+
# pass
|
| 262 |
+
# else:
|
| 263 |
+
# raise NotImplementedError
|
| 264 |
+
# if self.qk_norm is not None:
|
| 265 |
+
# if self.qk_norm == 'l2':
|
| 266 |
+
# q = l2_norm_fn(q)
|
| 267 |
+
# k = l2_norm_fn(k)
|
| 268 |
+
# elif self.qk_norm == 'sum':
|
| 269 |
+
# q = sum_norm(q).to(v)
|
| 270 |
+
# k = sum_norm(k).to(v)
|
| 271 |
+
# recurrent_state = None
|
| 272 |
+
# if last_state is not None:
|
| 273 |
+
# recurrent_state = last_state['recurrent_state']
|
| 274 |
+
|
| 275 |
+
# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid()
|
| 276 |
+
# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l')
|
| 277 |
+
|
| 278 |
+
# amask = torch.softmax(self.mask,dim=-1)#未必需要r r-1#适配2*2 4*4
|
| 279 |
+
# r = self.r
|
| 280 |
+
# target_matrix = torch.zeros(r, r, dtype=amask.dtype, device=k.device)
|
| 281 |
+
# mask = torch.ones(r,r, dtype=torch.bool, device=amask.device)
|
| 282 |
+
# target_matrix[mask] = amask.flatten()
|
| 283 |
+
|
| 284 |
+
# eye_mask = torch.eye(r, dtype=torch.bool, device=amask.device)
|
| 285 |
+
# target_matrix[eye_mask] = 1.0
|
| 286 |
+
|
| 287 |
+
# 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)
|
| 288 |
+
# o = rearrange(o,'b h l d-> b l h d')
|
| 289 |
+
# if past_key_values is not None:
|
| 290 |
+
# past_key_values.update(
|
| 291 |
+
# recurrent_state=(recurrent_state),
|
| 292 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 293 |
+
# layer_idx=self.layer_idx,
|
| 294 |
+
# offset=q_len
|
| 295 |
+
# )
|
| 296 |
+
# if self.use_gate:
|
| 297 |
+
# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 298 |
+
# o = self.o_norm(o, g)
|
| 299 |
+
# else:
|
| 300 |
+
# o = self.o_norm(o)
|
| 301 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 302 |
+
# o = self.o_proj(o)
|
| 303 |
+
# return o, None, past_key_values,None
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# from ..ops.mask_gated_delta_rule import mask_gated_chunk_delta_rule
|
| 307 |
+
# class mask_gdn(nn.Module):
|
| 308 |
+
# def __init__(
|
| 309 |
+
# self,
|
| 310 |
+
# d_model: int = None,
|
| 311 |
+
# hidden_size: int = 1024,
|
| 312 |
+
# expand_k: float = 1.0,
|
| 313 |
+
# expand_v: float = 1.0,
|
| 314 |
+
# num_heads: int = 4,
|
| 315 |
+
# mode: str = 'chunk',
|
| 316 |
+
# chunk_size: int = 64,
|
| 317 |
+
# use_beta: bool = True,
|
| 318 |
+
# use_gate: bool = False,
|
| 319 |
+
# use_output_norm: bool = True,
|
| 320 |
+
# use_elu: bool = False,
|
| 321 |
+
# use_short_conv: bool = True,
|
| 322 |
+
# conv_size: int = 4,
|
| 323 |
+
# conv_bias: bool = False,
|
| 324 |
+
# layer_idx: int = None,
|
| 325 |
+
# qk_activation: str = 'silu',
|
| 326 |
+
# qk_norm: str = 'l2',
|
| 327 |
+
# norm_first: bool = False,
|
| 328 |
+
# norm_eps: float = 1e-6,
|
| 329 |
+
# ratio :int = 2,
|
| 330 |
+
# topk : int = 1 ,
|
| 331 |
+
# **kwargs
|
| 332 |
+
# ) :
|
| 333 |
+
# super().__init__()
|
| 334 |
+
|
| 335 |
+
# self.mode = mode
|
| 336 |
+
# self.qk_activation = qk_activation
|
| 337 |
+
# self.qk_norm = qk_norm
|
| 338 |
+
|
| 339 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 340 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 341 |
+
|
| 342 |
+
# if d_model is not None:
|
| 343 |
+
# hidden_size = d_model
|
| 344 |
+
# self.hidden_size = hidden_size
|
| 345 |
+
# self.expand_k = expand_k
|
| 346 |
+
# self.expand_v = expand_v
|
| 347 |
+
# self.num_heads = num_heads
|
| 348 |
+
# self.chunk_size = chunk_size
|
| 349 |
+
# self.use_gate = use_gate
|
| 350 |
+
# self.use_output_norm = use_output_norm
|
| 351 |
+
# self.use_short_conv = use_short_conv
|
| 352 |
+
# self.conv_size = conv_size
|
| 353 |
+
# self.conv_bias = conv_bias
|
| 354 |
+
|
| 355 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 356 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 357 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 358 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 359 |
+
# self.norm_first = norm_first
|
| 360 |
+
# self.layer_idx = layer_idx
|
| 361 |
+
# self.top_k = topk
|
| 362 |
+
# self.silu = nn.SiLU()
|
| 363 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 364 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 365 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 366 |
+
# if norm_first:
|
| 367 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 368 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 369 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 370 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 371 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 372 |
+
|
| 373 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 374 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 375 |
+
# self.A_log._no_weight_decay = True
|
| 376 |
+
# # hard coded for now
|
| 377 |
+
# dt_min = 0.001
|
| 378 |
+
# dt_max = 0.1
|
| 379 |
+
# dt_init_floor = 1e-4
|
| 380 |
+
# dt = torch.exp(
|
| 381 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 382 |
+
# + math.log(dt_min)
|
| 383 |
+
# )
|
| 384 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 385 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 386 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 387 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 388 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 389 |
+
# # name.endswith("bias") in param_grouping.py
|
| 390 |
+
# self.dt_bias._no_weight_decay = True
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
# self.use_beta = use_beta
|
| 394 |
+
# self.use_elu = use_elu
|
| 395 |
+
# if self.use_beta:
|
| 396 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 397 |
+
# if use_short_conv:
|
| 398 |
+
# self.conv_size = conv_size
|
| 399 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 400 |
+
# conv_size,
|
| 401 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 402 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 403 |
+
# conv_size,
|
| 404 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 405 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 406 |
+
# if use_gate:
|
| 407 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 408 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 409 |
+
# else:
|
| 410 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 411 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 412 |
+
# r = self.r = 2
|
| 413 |
+
# self.mask = nn.Parameter(torch.empty([r,r],dtype=self.o_proj.weight.dtype),requires_grad=True)
|
| 414 |
+
# self.mask_requiregrad = True
|
| 415 |
+
# print('mask_gdn_learn_mask_qk_r2')
|
| 416 |
+
# init.kaiming_uniform_(self.mask, a=math.sqrt(5))
|
| 417 |
+
# assert self.head_qk_dim % r == 0
|
| 418 |
+
# self.apply(self._initialize_weights)
|
| 419 |
+
|
| 420 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 421 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 422 |
+
# return
|
| 423 |
+
# if isinstance(module, nn.Linear):
|
| 424 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 425 |
+
# if module.bias is not None:
|
| 426 |
+
# nn.init.zeros_(module.bias)
|
| 427 |
+
# module._is_hf_initialized = True
|
| 428 |
+
|
| 429 |
+
# def delta_rule_recurrence(self,q, k, v, beta, mask,initial_state=None,output_final_state=True):
|
| 430 |
+
# b, h, l, d_k = q.shape
|
| 431 |
+
# d_v = v.shape[-1]
|
| 432 |
+
# r = mask.shape[-1]
|
| 433 |
+
# o = torch.zeros_like(v)
|
| 434 |
+
# if initial_state == None:
|
| 435 |
+
# S = torch.zeros(b, h, d_k, d_v).to(v).float()
|
| 436 |
+
# else:
|
| 437 |
+
# S = initial_state
|
| 438 |
+
# q = q * (d_k ** -0.5)
|
| 439 |
+
# if beta.ndim < v.ndim:
|
| 440 |
+
# beta = beta[..., None]
|
| 441 |
+
# if self.training:
|
| 442 |
+
# for i in range(l):
|
| 443 |
+
# _k = k[:, :, i]
|
| 444 |
+
# _q = q[:, :, i]
|
| 445 |
+
# _v = v[:, :, i].clone()
|
| 446 |
+
# beta_i = beta[:, :, i]
|
| 447 |
+
# _v = _v * beta_i
|
| 448 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 449 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 450 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 451 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 452 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 453 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2)
|
| 454 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
|
| 455 |
+
# return o,S
|
| 456 |
+
# else:
|
| 457 |
+
# for i in range(l):
|
| 458 |
+
# _k = k[:, :, i]
|
| 459 |
+
# _q = q[:, :, i]
|
| 460 |
+
# _v = v[:, :, i]
|
| 461 |
+
# beta_i = beta[:, :, i]
|
| 462 |
+
# _v = _v * beta_i
|
| 463 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 464 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 465 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 466 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 467 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 468 |
+
# 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()
|
| 469 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype)
|
| 470 |
+
# return o,S
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
# def forward(
|
| 474 |
+
# self,
|
| 475 |
+
# hidden_states: torch.Tensor,
|
| 476 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 477 |
+
# past_key_values: Optional[Cache] = None,
|
| 478 |
+
# use_cache: Optional[bool] = False,
|
| 479 |
+
# output_attentions: Optional[bool] = False,
|
| 480 |
+
# **kwargs
|
| 481 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 482 |
+
# # change to inference mode.
|
| 483 |
+
# mode = 'chunk'#'recurrent' if hidden_states.shape[1] < 64 else self.mode
|
| 484 |
+
# b,q_len,d = hidden_states.shape
|
| 485 |
+
# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states)
|
| 486 |
+
# if self.norm_first:
|
| 487 |
+
# hidden_states = self.norm(hidden_states)
|
| 488 |
+
|
| 489 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 490 |
+
# # if attention_mask is not None:
|
| 491 |
+
# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 492 |
+
# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 493 |
+
# last_state = None
|
| 494 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 495 |
+
# last_state = past_key_values[self.layer_idx]
|
| 496 |
+
# offset = past_key_values.get_seq_length()
|
| 497 |
+
# # if attention_mask is not None:
|
| 498 |
+
# # if attention_mask.shape[-1] != hidden_states.shape[-2]:
|
| 499 |
+
# # attention_mask = attention_mask[:, -1:]
|
| 500 |
+
# if self.use_short_conv:
|
| 501 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 502 |
+
# if last_state is not None:
|
| 503 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 504 |
+
# q = self.q_proj(hidden_states)
|
| 505 |
+
# k = self.k_proj(hidden_states)
|
| 506 |
+
# v = self.v_proj(hidden_states)
|
| 507 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 508 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 509 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 510 |
+
# else:
|
| 511 |
+
# q = self.q_proj(hidden_states)
|
| 512 |
+
# k = self.k_proj(hidden_states)
|
| 513 |
+
# v = self.v_proj(hidden_states)
|
| 514 |
+
# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v))
|
| 515 |
+
# if self.qk_activation != 'silu':
|
| 516 |
+
# if self.qk_activation == 'relu':
|
| 517 |
+
# q, k = q.relu(), k.relu()
|
| 518 |
+
# elif self.qk_activation == 'elu':
|
| 519 |
+
# q, k = elu_p1(q), elu_p1(k)
|
| 520 |
+
# elif self.qk_activation == 'identity':
|
| 521 |
+
# pass
|
| 522 |
+
# else:
|
| 523 |
+
# raise NotImplementedError
|
| 524 |
+
# if self.qk_norm is not None:
|
| 525 |
+
# if self.qk_norm == 'l2':
|
| 526 |
+
# q = l2_norm_fn(q)
|
| 527 |
+
# k = l2_norm_fn(k)
|
| 528 |
+
# elif self.qk_norm == 'sum':
|
| 529 |
+
# q = sum_norm(q).to(v)
|
| 530 |
+
# k = sum_norm(k).to(v)
|
| 531 |
+
# recurrent_state = None
|
| 532 |
+
# if last_state is not None:
|
| 533 |
+
# recurrent_state = last_state['recurrent_state']
|
| 534 |
+
|
| 535 |
+
# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid()
|
| 536 |
+
# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l')
|
| 537 |
+
|
| 538 |
+
# amask = torch.softmax(self.mask,dim=-1)#未必需要r r-1#适配2*2 4*4
|
| 539 |
+
# r = self.r
|
| 540 |
+
# target_matrix = torch.zeros(r, r, dtype=amask.dtype, device=k.device)
|
| 541 |
+
# mask = torch.ones(r,r, dtype=torch.bool, device=amask.device)
|
| 542 |
+
# target_matrix[mask] = amask.flatten()
|
| 543 |
+
|
| 544 |
+
# eye_mask = torch.eye(r, dtype=torch.bool, device=amask.device)
|
| 545 |
+
# target_matrix[eye_mask] = 1.0
|
| 546 |
+
|
| 547 |
+
# 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)
|
| 548 |
+
# o = rearrange(o,'b h l d-> b l h d')
|
| 549 |
+
# if past_key_values is not None:
|
| 550 |
+
# past_key_values.update(
|
| 551 |
+
# recurrent_state=(recurrent_state),
|
| 552 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 553 |
+
# layer_idx=self.layer_idx,
|
| 554 |
+
# offset=q_len
|
| 555 |
+
# )
|
| 556 |
+
# if self.use_gate:
|
| 557 |
+
# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 558 |
+
# o = self.o_norm(o, g)
|
| 559 |
+
# else:
|
| 560 |
+
# o = self.o_norm(o)
|
| 561 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 562 |
+
# o = self.o_proj(o)
|
| 563 |
+
# return o, None, past_key_values,None
|
| 564 |
+
|
| 565 |
+
# from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule
|
| 566 |
+
from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule,mask_fused_recurrent_gated_delta_rule
|
| 567 |
+
class mask_gdn(nn.Module):
|
| 568 |
+
def __init__(
|
| 569 |
+
self,
|
| 570 |
+
d_model: int = None,
|
| 571 |
+
hidden_size: int = 1024,
|
| 572 |
+
expand_k: float = 1.0,
|
| 573 |
+
expand_v: float = 1.0,
|
| 574 |
+
num_heads: int = 4,
|
| 575 |
+
mode: str = 'chunk',
|
| 576 |
+
chunk_size: int = 64,
|
| 577 |
+
use_beta: bool = True,
|
| 578 |
+
use_gate: bool = False,
|
| 579 |
+
use_output_norm: bool = True,
|
| 580 |
+
use_elu: bool = False,
|
| 581 |
+
use_short_conv: bool = True,
|
| 582 |
+
conv_size: int = 4,
|
| 583 |
+
conv_bias: bool = False,
|
| 584 |
+
layer_idx: int = None,
|
| 585 |
+
qk_activation: str = 'silu',
|
| 586 |
+
qk_norm: str = 'l2',
|
| 587 |
+
norm_first: bool = False,
|
| 588 |
+
norm_eps: float = 1e-6,
|
| 589 |
+
ratio :int = 4,
|
| 590 |
+
topk : int = 1,
|
| 591 |
+
**kwargs
|
| 592 |
+
) :
|
| 593 |
+
super().__init__()
|
| 594 |
+
|
| 595 |
+
self.mode = mode
|
| 596 |
+
self.qk_activation = qk_activation
|
| 597 |
+
self.qk_norm = qk_norm
|
| 598 |
+
|
| 599 |
+
assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 600 |
+
assert self.qk_norm in ['l2', 'sum']
|
| 601 |
+
|
| 602 |
+
if d_model is not None:
|
| 603 |
+
hidden_size = d_model
|
| 604 |
+
self.hidden_size = hidden_size
|
| 605 |
+
self.expand_k = expand_k
|
| 606 |
+
self.expand_v = expand_v
|
| 607 |
+
self.num_heads = num_heads
|
| 608 |
+
self.chunk_size = chunk_size
|
| 609 |
+
self.use_gate = use_gate
|
| 610 |
+
self.use_output_norm = use_output_norm
|
| 611 |
+
self.use_short_conv = use_short_conv
|
| 612 |
+
self.conv_size = conv_size
|
| 613 |
+
self.conv_bias = conv_bias
|
| 614 |
+
|
| 615 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 616 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 617 |
+
self.head_qk_dim = self.key_dim // num_heads
|
| 618 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 619 |
+
self.norm_first = norm_first
|
| 620 |
+
self.layer_idx = layer_idx
|
| 621 |
+
self.top_k = topk
|
| 622 |
+
self.silu = nn.SiLU()
|
| 623 |
+
assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 624 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 625 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 626 |
+
if norm_first:
|
| 627 |
+
self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 628 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 629 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 630 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 631 |
+
self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 632 |
+
|
| 633 |
+
A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 634 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 635 |
+
self.A_log._no_weight_decay = True
|
| 636 |
+
# hard coded for now
|
| 637 |
+
dt_min = 0.001
|
| 638 |
+
dt_max = 0.1
|
| 639 |
+
dt_init_floor = 1e-4
|
| 640 |
+
dt = torch.exp(
|
| 641 |
+
torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 642 |
+
+ math.log(dt_min)
|
| 643 |
+
)
|
| 644 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 645 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 646 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 647 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 648 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 649 |
+
# name.endswith("bias") in param_grouping.py
|
| 650 |
+
self.dt_bias._no_weight_decay = True
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
self.use_beta = use_beta
|
| 654 |
+
self.use_elu = use_elu
|
| 655 |
+
if self.use_beta:
|
| 656 |
+
self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 657 |
+
if use_short_conv:
|
| 658 |
+
self.conv_size = conv_size
|
| 659 |
+
self.q_conv1d = ShortConvolution(self.key_dim,
|
| 660 |
+
conv_size,
|
| 661 |
+
activation='silu' if qk_activation == 'silu' else None)
|
| 662 |
+
self.k_conv1d = ShortConvolution(self.key_dim,
|
| 663 |
+
conv_size,
|
| 664 |
+
activation='silu' if qk_activation == 'silu' else None)
|
| 665 |
+
self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 666 |
+
if use_gate:
|
| 667 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 668 |
+
self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 669 |
+
else:
|
| 670 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 671 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 672 |
+
r = self.r = ratio
|
| 673 |
+
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)
|
| 674 |
+
self.mask_requiregrad = True
|
| 675 |
+
print('mask_gdn_learn_mask_by_t_fla4____'+str(self.r))
|
| 676 |
+
assert self.head_qk_dim % r == 0
|
| 677 |
+
self.apply(self._initialize_weights)
|
| 678 |
+
|
| 679 |
+
def _initialize_weights(self, module: nn.Module):
|
| 680 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 681 |
+
return
|
| 682 |
+
if isinstance(module, nn.Linear):
|
| 683 |
+
nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 684 |
+
if module.bias is not None:
|
| 685 |
+
nn.init.zeros_(module.bias)
|
| 686 |
+
module._is_hf_initialized = True
|
| 687 |
+
|
| 688 |
+
def forward(
|
| 689 |
+
self,
|
| 690 |
+
hidden_states: torch.Tensor,
|
| 691 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 692 |
+
past_key_values: Optional[Cache] = None,
|
| 693 |
+
use_cache: Optional[bool] = False,
|
| 694 |
+
output_attentions: Optional[bool] = False,
|
| 695 |
+
**kwargs
|
| 696 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 697 |
+
# change to inference mode.
|
| 698 |
+
if attention_mask is not None:
|
| 699 |
+
assert len(attention_mask.shape) == 2, (
|
| 700 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 701 |
+
"for padding purposes (0 indicating padding). "
|
| 702 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 703 |
+
)
|
| 704 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 705 |
+
# change to inference mode.
|
| 706 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 707 |
+
if self.training:
|
| 708 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 709 |
+
|
| 710 |
+
last_state = None
|
| 711 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 712 |
+
last_state = past_key_values[self.layer_idx]
|
| 713 |
+
|
| 714 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 715 |
+
if attention_mask is not None:
|
| 716 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 717 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 718 |
+
|
| 719 |
+
if self.use_short_conv:
|
| 720 |
+
conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 721 |
+
if last_state is not None:
|
| 722 |
+
conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 723 |
+
q = self.q_proj(hidden_states)
|
| 724 |
+
k = self.k_proj(hidden_states)
|
| 725 |
+
v = self.v_proj(hidden_states)
|
| 726 |
+
q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 727 |
+
k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 728 |
+
v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 729 |
+
else:
|
| 730 |
+
q = F.silu(self.q_proj(hidden_states))
|
| 731 |
+
k = F.silu(self.k_proj(hidden_states))
|
| 732 |
+
v = F.silu(self.v_proj(hidden_states))
|
| 733 |
+
|
| 734 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
|
| 735 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 736 |
+
|
| 737 |
+
# if self.num_v_heads > self.num_heads:
|
| 738 |
+
# q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k))
|
| 739 |
+
|
| 740 |
+
beta = self.b_proj(hidden_states).sigmoid()
|
| 741 |
+
# if self.allow_neg_eigval:
|
| 742 |
+
# beta = beta * 2.
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
q = l2norm(q)
|
| 746 |
+
k = l2norm(k)
|
| 747 |
+
recurrent_state = None
|
| 748 |
+
if last_state is not None:
|
| 749 |
+
recurrent_state = last_state['recurrent_state']
|
| 750 |
+
g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 751 |
+
r = self.r
|
| 752 |
+
target_matrix = self.mask(hidden_states).abs()
|
| 753 |
+
target_matrix = rearrange(target_matrix,'b l (h r c)->b l h r c',r=r,h=self.num_heads)#bhlrr
|
| 754 |
+
target_matrix = l2norm(target_matrix)
|
| 755 |
+
target_matrix = target_matrix@target_matrix.transpose(-1,-2)
|
| 756 |
+
# target_matrix = self.mask.abs()
|
| 757 |
+
# target_matrix = l2_norm_fn(target_matrix)
|
| 758 |
+
# target_matrix = target_matrix@target_matrix.transpose(-1,-2)
|
| 759 |
+
# target_matrix = target_matrix.unsqueeze(1).unsqueeze(0).expand(batch,self.num_heads,q_len,self.r,self.r)
|
| 760 |
+
if mode == 'recurrent':
|
| 761 |
+
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)
|
| 762 |
+
else:
|
| 763 |
+
if r==8:
|
| 764 |
+
BT = 16
|
| 765 |
+
else:
|
| 766 |
+
BT = 32
|
| 767 |
+
o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),
|
| 768 |
+
v.contiguous(),
|
| 769 |
+
beta.contiguous(),
|
| 770 |
+
g.contiguous(),
|
| 771 |
+
target_matrix.contiguous(),
|
| 772 |
+
BT = BT,
|
| 773 |
+
initial_state=recurrent_state,
|
| 774 |
+
output_final_state=use_cache,
|
| 775 |
+
cu_seqlens=cu_seqlens,
|
| 776 |
+
use_qk_l2norm_in_kernel=False)
|
| 777 |
+
if past_key_values is not None:
|
| 778 |
+
past_key_values.update(
|
| 779 |
+
recurrent_state=(recurrent_state),
|
| 780 |
+
conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 781 |
+
layer_idx=self.layer_idx,
|
| 782 |
+
offset=q_len
|
| 783 |
+
)
|
| 784 |
+
if self.use_gate:
|
| 785 |
+
g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 786 |
+
o = self.o_norm(o, g)
|
| 787 |
+
else:
|
| 788 |
+
o = self.o_norm(o)
|
| 789 |
+
o = rearrange(o, 'b l h d -> b l (h d)')
|
| 790 |
+
# print(o.shape)
|
| 791 |
+
o = self.o_proj(o)
|
| 792 |
+
if attention_mask is not None:
|
| 793 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 794 |
+
return o, None, past_key_values,None
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
# from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule
|
| 800 |
+
# class mask_gdn(nn.Module):
|
| 801 |
+
# def __init__(
|
| 802 |
+
# self,
|
| 803 |
+
# d_model: int = None,
|
| 804 |
+
# hidden_size: int = 1024,
|
| 805 |
+
# expand_k: float = 1.0,
|
| 806 |
+
# expand_v: float = 1.0,
|
| 807 |
+
# num_heads: int = 4,
|
| 808 |
+
# mode: str = 'chunk',
|
| 809 |
+
# chunk_size: int = 64,
|
| 810 |
+
# use_beta: bool = True,
|
| 811 |
+
# use_gate: bool = False,
|
| 812 |
+
# use_output_norm: bool = True,
|
| 813 |
+
# use_elu: bool = False,
|
| 814 |
+
# use_short_conv: bool = True,
|
| 815 |
+
# conv_size: int = 4,
|
| 816 |
+
# conv_bias: bool = False,
|
| 817 |
+
# layer_idx: int = None,
|
| 818 |
+
# qk_activation: str = 'silu',
|
| 819 |
+
# qk_norm: str = 'l2',
|
| 820 |
+
# norm_first: bool = False,
|
| 821 |
+
# norm_eps: float = 1e-6,
|
| 822 |
+
# ratio :int = 2,
|
| 823 |
+
# topk : int = 1 ,
|
| 824 |
+
# **kwargs
|
| 825 |
+
# ) :
|
| 826 |
+
# super().__init__()
|
| 827 |
+
|
| 828 |
+
# self.mode = mode
|
| 829 |
+
# self.qk_activation = qk_activation
|
| 830 |
+
# self.qk_norm = qk_norm
|
| 831 |
+
|
| 832 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 833 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 834 |
+
|
| 835 |
+
# if d_model is not None:
|
| 836 |
+
# hidden_size = d_model
|
| 837 |
+
# self.hidden_size = hidden_size
|
| 838 |
+
# self.expand_k = expand_k
|
| 839 |
+
# self.expand_v = expand_v
|
| 840 |
+
# self.num_heads = num_heads
|
| 841 |
+
# self.chunk_size = chunk_size
|
| 842 |
+
# self.use_gate = use_gate
|
| 843 |
+
# self.use_output_norm = use_output_norm
|
| 844 |
+
# self.use_short_conv = use_short_conv
|
| 845 |
+
# self.conv_size = conv_size
|
| 846 |
+
# self.conv_bias = conv_bias
|
| 847 |
+
|
| 848 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 849 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 850 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 851 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 852 |
+
# self.norm_first = norm_first
|
| 853 |
+
# self.layer_idx = layer_idx
|
| 854 |
+
# self.top_k = topk
|
| 855 |
+
# self.silu = nn.SiLU()
|
| 856 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 857 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 858 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 859 |
+
# if norm_first:
|
| 860 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 861 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 862 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 863 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 864 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 865 |
+
|
| 866 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 867 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 868 |
+
# self.A_log._no_weight_decay = True
|
| 869 |
+
# # hard coded for now
|
| 870 |
+
# dt_min = 0.001
|
| 871 |
+
# dt_max = 0.1
|
| 872 |
+
# dt_init_floor = 1e-4
|
| 873 |
+
# dt = torch.exp(
|
| 874 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 875 |
+
# + math.log(dt_min)
|
| 876 |
+
# )
|
| 877 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 878 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 879 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 880 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 881 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 882 |
+
# # name.endswith("bias") in param_grouping.py
|
| 883 |
+
# self.dt_bias._no_weight_decay = True
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
# self.use_beta = use_beta
|
| 887 |
+
# self.use_elu = use_elu
|
| 888 |
+
# if self.use_beta:
|
| 889 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 890 |
+
# if use_short_conv:
|
| 891 |
+
# self.conv_size = conv_size
|
| 892 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 893 |
+
# conv_size,
|
| 894 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 895 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 896 |
+
# conv_size,
|
| 897 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 898 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 899 |
+
# if use_gate:
|
| 900 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 901 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 902 |
+
# else:
|
| 903 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 904 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 905 |
+
# r = self.r = 4
|
| 906 |
+
# self.mask = nn.Parameter(torch.empty([self.num_heads,r,r],dtype=self.o_proj.weight.dtype),requires_grad=True)
|
| 907 |
+
# self.mask_requiregrad = True
|
| 908 |
+
|
| 909 |
+
# print('mask_gdn_learn_mask_r4_hrr')
|
| 910 |
+
# init.kaiming_uniform_(self.mask, a=math.sqrt(5))
|
| 911 |
+
# assert self.head_qk_dim % r == 0
|
| 912 |
+
# self.apply(self._initialize_weights)
|
| 913 |
+
|
| 914 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 915 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 916 |
+
# return
|
| 917 |
+
# if isinstance(module, nn.Linear):
|
| 918 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 919 |
+
# if module.bias is not None:
|
| 920 |
+
# nn.init.zeros_(module.bias)
|
| 921 |
+
# module._is_hf_initialized = True
|
| 922 |
+
|
| 923 |
+
# def delta_rule_recurrence(self,q, k, v, beta, g, mask,initial_state=None,output_final_state=True):
|
| 924 |
+
# b, h, l, d_k = q.shape
|
| 925 |
+
# d_v = v.shape[-1]
|
| 926 |
+
# r = mask.shape[-1]
|
| 927 |
+
# o = torch.zeros_like(v)
|
| 928 |
+
# if initial_state == None:
|
| 929 |
+
# S = torch.zeros(b, h, d_k, d_v,device=k.device,dtype=torch.float32)
|
| 930 |
+
# else:
|
| 931 |
+
# S = initial_state
|
| 932 |
+
# q = q * (d_k ** -0.5)
|
| 933 |
+
# if beta.ndim < v.ndim:
|
| 934 |
+
# beta = beta[..., None]
|
| 935 |
+
# g = torch.exp(g)
|
| 936 |
+
# if self.training:
|
| 937 |
+
# for i in range(l):
|
| 938 |
+
# _k = k[:, :, i]
|
| 939 |
+
# _q = q[:, :, i]
|
| 940 |
+
# _v = v[:, :, i].clone()
|
| 941 |
+
# beta_i = beta[:, :, i]
|
| 942 |
+
# _v = _v * beta_i
|
| 943 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 944 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 945 |
+
# kkt = torch.einsum('b h r d l v,b h r l->b h r d l v',kkt,mask[:,:,i,:,:].to(kkt))
|
| 946 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 947 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 948 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2)
|
| 949 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
|
| 950 |
+
# return o,S
|
| 951 |
+
# else:
|
| 952 |
+
# for i in range(l):
|
| 953 |
+
# _k = k[:, :, i]
|
| 954 |
+
# _q = q[:, :, i]
|
| 955 |
+
# _v = v[:, :, i]
|
| 956 |
+
# beta_i = beta[:, :, i]
|
| 957 |
+
# _v = _v * beta_i
|
| 958 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 959 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 960 |
+
# kkt = torch.einsum('b h r d l v,b h r l->b h r d l v',kkt,mask[:,:,i,:,:].to(kkt))
|
| 961 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 962 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 963 |
+
# 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()
|
| 964 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype)
|
| 965 |
+
# return o,S
|
| 966 |
+
|
| 967 |
+
# def forward(
|
| 968 |
+
# self,
|
| 969 |
+
# hidden_states: torch.Tensor,
|
| 970 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 971 |
+
# past_key_values: Optional[Cache] = None,
|
| 972 |
+
# use_cache: Optional[bool] = False,
|
| 973 |
+
# output_attentions: Optional[bool] = False,
|
| 974 |
+
# **kwargs
|
| 975 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 976 |
+
# # change to inference mode.
|
| 977 |
+
# mode = 'recurrent' if hidden_states.shape[1] < 32 else self.mode
|
| 978 |
+
# batch,q_len,d = hidden_states.shape
|
| 979 |
+
# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states)
|
| 980 |
+
# if self.norm_first:
|
| 981 |
+
# hidden_states = self.norm(hidden_states)
|
| 982 |
+
|
| 983 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 984 |
+
# # if attention_mask is not None:
|
| 985 |
+
# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 986 |
+
# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 987 |
+
# last_state = None
|
| 988 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 989 |
+
# last_state = past_key_values[self.layer_idx]
|
| 990 |
+
# offset = past_key_values.get_seq_length()
|
| 991 |
+
# # if attention_mask is not None:
|
| 992 |
+
# # if attention_mask.shape[-1] != hidden_states.shape[-2]:
|
| 993 |
+
# # attention_mask = attention_mask[:, -1:]
|
| 994 |
+
# if self.use_short_conv:
|
| 995 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 996 |
+
# if last_state is not None:
|
| 997 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 998 |
+
# q = self.q_proj(hidden_states)
|
| 999 |
+
# k = self.k_proj(hidden_states)
|
| 1000 |
+
# v = self.v_proj(hidden_states)
|
| 1001 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1002 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1003 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1004 |
+
# else:
|
| 1005 |
+
# q = self.q_proj(hidden_states)
|
| 1006 |
+
# k = self.k_proj(hidden_states)
|
| 1007 |
+
# v = self.v_proj(hidden_states)
|
| 1008 |
+
# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v))
|
| 1009 |
+
# if self.qk_activation != 'silu':
|
| 1010 |
+
# if self.qk_activation == 'relu':
|
| 1011 |
+
# q, k = q.relu(), k.relu()
|
| 1012 |
+
# elif self.qk_activation == 'elu':
|
| 1013 |
+
# q, k = elu_p1(q), elu_p1(k)
|
| 1014 |
+
# elif self.qk_activation == 'identity':
|
| 1015 |
+
# pass
|
| 1016 |
+
# else:
|
| 1017 |
+
# raise NotImplementedError
|
| 1018 |
+
# if self.qk_norm is not None:
|
| 1019 |
+
# if self.qk_norm == 'l2':
|
| 1020 |
+
# q = l2_norm_fn(q)
|
| 1021 |
+
# k = l2_norm_fn(k)
|
| 1022 |
+
# elif self.qk_norm == 'sum':
|
| 1023 |
+
# q = sum_norm(q).to(v)
|
| 1024 |
+
# k = sum_norm(k).to(v)
|
| 1025 |
+
# recurrent_state = None
|
| 1026 |
+
# if last_state is not None:
|
| 1027 |
+
# recurrent_state = last_state['recurrent_state']
|
| 1028 |
+
|
| 1029 |
+
# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid()
|
| 1030 |
+
# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l')
|
| 1031 |
+
|
| 1032 |
+
# r = self.r
|
| 1033 |
+
# target_matrix = self.mask#hrr
|
| 1034 |
+
# target_matrix = torch.softmax(target_matrix,dim=-1)#h r c
|
| 1035 |
+
# eye_mask = torch.eye(r, dtype=torch.bool, device=target_matrix.device).unsqueeze(0)
|
| 1036 |
+
# target_matrix = torch.where(eye_mask, torch.tensor(1.0, device=target_matrix.device), target_matrix)
|
| 1037 |
+
# target_matrix = target_matrix.unsqueeze(1).unsqueeze(0).expand(batch,self.num_heads,q_len,self.r,self.r)
|
| 1038 |
+
|
| 1039 |
+
# if mode == 'recurrent':
|
| 1040 |
+
# 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)
|
| 1041 |
+
# else:
|
| 1042 |
+
# 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)
|
| 1043 |
+
# o = rearrange(o,'b h l d-> b l h d')
|
| 1044 |
+
# if past_key_values is not None:
|
| 1045 |
+
# past_key_values.update(
|
| 1046 |
+
# recurrent_state=(recurrent_state),
|
| 1047 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 1048 |
+
# layer_idx=self.layer_idx,
|
| 1049 |
+
# offset=q_len
|
| 1050 |
+
# )
|
| 1051 |
+
# if self.use_gate:
|
| 1052 |
+
# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 1053 |
+
# o = self.o_norm(o, g)
|
| 1054 |
+
# else:
|
| 1055 |
+
# o = self.o_norm(o)
|
| 1056 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 1057 |
+
# o = self.o_proj(o)
|
| 1058 |
+
# return o, None, past_key_values,None
|
layers/mesa_net.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
from torch.nn import functional as F
|
| 12 |
+
|
| 13 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 14 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 15 |
+
from fla.modules.l2norm import l2_norm
|
| 16 |
+
from fla.ops.mesa_net import chunk_mesa_net, mesa_net_decoding_one_step
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from transformers.processing_utils import Unpack
|
| 20 |
+
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class MesaNet(nn.Module):
|
| 25 |
+
"""
|
| 26 |
+
The layer implementaion for [MesaNet: Sequence Modeling by Locally Optimal Test-Time Training]. # noqa
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
hidden_size (int, Optional):
|
| 30 |
+
The hidden size of the input. Default: 2048.
|
| 31 |
+
expand_v (float, Optional):
|
| 32 |
+
The expansion ratio for the value dim. Default: 1.
|
| 33 |
+
num_heads (int, Optional):
|
| 34 |
+
The number of heads. Default: 16.
|
| 35 |
+
mode (str, Optional):
|
| 36 |
+
Which MesaNet kernel to use.
|
| 37 |
+
Currently available: `chunk`.
|
| 38 |
+
Default: `chunk`.
|
| 39 |
+
use_output_gate (bool, Optional):
|
| 40 |
+
Whether to use output gate. Default: `False`.
|
| 41 |
+
conv_size (int):
|
| 42 |
+
The kernel size of the short convolution. Default: 4.
|
| 43 |
+
layer_idx (int, Optional):
|
| 44 |
+
The index of the layer. Default: None.
|
| 45 |
+
norm_eps (float, Optional):
|
| 46 |
+
The epsilon value for the normalization layer. Default: 1e-5.
|
| 47 |
+
lambda_lower_bound (float):
|
| 48 |
+
The lower bound for the lambda parameter. Default: 0.25.
|
| 49 |
+
max_cg_step_training (int):
|
| 50 |
+
The maximum number of CG steps for training. Default: 30.
|
| 51 |
+
max_cg_step_decoding (int):
|
| 52 |
+
The maximum number of CG steps for decoding. Default: 30.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
hidden_size: int = 2048,
|
| 58 |
+
num_heads: int = 16,
|
| 59 |
+
head_dim: int = 128,
|
| 60 |
+
mode: str = 'chunk',
|
| 61 |
+
use_output_gate: bool = False,
|
| 62 |
+
use_short_conv: bool = True,
|
| 63 |
+
conv_size: int = 4,
|
| 64 |
+
conv_bias: bool = False,
|
| 65 |
+
layer_idx: int = None,
|
| 66 |
+
norm_eps: float = 1e-5,
|
| 67 |
+
lambda_lower_bound: float = 0.25,
|
| 68 |
+
max_cg_step_training: int = 30,
|
| 69 |
+
max_cg_step_decoding: int = 30,
|
| 70 |
+
**kwargs
|
| 71 |
+
) -> MesaNet:
|
| 72 |
+
super().__init__()
|
| 73 |
+
|
| 74 |
+
self.mode = mode
|
| 75 |
+
self.hidden_size = hidden_size
|
| 76 |
+
self.use_output_gate = use_output_gate
|
| 77 |
+
self.use_short_conv = use_short_conv
|
| 78 |
+
self.conv_size = conv_size
|
| 79 |
+
self.conv_bias = conv_bias
|
| 80 |
+
self.num_heads = num_heads
|
| 81 |
+
self.head_dim = head_dim
|
| 82 |
+
self.key_dim = self.num_heads * self.head_dim
|
| 83 |
+
self.value_dim = self.key_dim
|
| 84 |
+
self.head_k_dim = self.head_dim
|
| 85 |
+
self.head_v_dim = self.head_dim
|
| 86 |
+
self.layer_idx = layer_idx
|
| 87 |
+
self.lambda_lower_bound = lambda_lower_bound
|
| 88 |
+
self.max_cg_step_training = max_cg_step_training
|
| 89 |
+
self.max_cg_step_decoding = max_cg_step_decoding
|
| 90 |
+
|
| 91 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 92 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 93 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 94 |
+
self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=True)
|
| 95 |
+
self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=True)
|
| 96 |
+
|
| 97 |
+
lambda_initial_value = 1.0
|
| 98 |
+
init_lamb_value = torch.log(torch.exp(torch.tensor(lambda_initial_value - lambda_lower_bound)) - 1.0)
|
| 99 |
+
init_lamb_params = torch.empty(self.key_dim, dtype=torch.float32).fill_(init_lamb_value)
|
| 100 |
+
|
| 101 |
+
self.lambda_params = nn.Parameter(init_lamb_params)
|
| 102 |
+
self.lambda_params._no_weight_decay = True
|
| 103 |
+
|
| 104 |
+
self.conv_size = conv_size
|
| 105 |
+
self.q_conv1d = ShortConvolution(
|
| 106 |
+
hidden_size=self.key_dim,
|
| 107 |
+
kernel_size=conv_size,
|
| 108 |
+
bias=self.conv_bias,
|
| 109 |
+
activation='silu',
|
| 110 |
+
)
|
| 111 |
+
self.k_conv1d = ShortConvolution(
|
| 112 |
+
hidden_size=self.key_dim,
|
| 113 |
+
kernel_size=conv_size,
|
| 114 |
+
bias=self.conv_bias,
|
| 115 |
+
activation='silu',
|
| 116 |
+
)
|
| 117 |
+
if use_output_gate:
|
| 118 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 119 |
+
self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps)
|
| 120 |
+
else:
|
| 121 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 122 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 123 |
+
|
| 124 |
+
def forward(
|
| 125 |
+
self,
|
| 126 |
+
hidden_states: torch.Tensor,
|
| 127 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 128 |
+
past_key_values: Optional[Cache] = None,
|
| 129 |
+
use_cache: Optional[bool] = False,
|
| 130 |
+
output_attentions: Optional[bool] = False,
|
| 131 |
+
**kwargs: Unpack[Dict]
|
| 132 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 133 |
+
if attention_mask is not None:
|
| 134 |
+
assert len(attention_mask.shape) == 2, (
|
| 135 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 136 |
+
"for padding purposes (0 indicating padding). "
|
| 137 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 141 |
+
last_state = None
|
| 142 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 143 |
+
last_state = past_key_values[self.layer_idx]
|
| 144 |
+
|
| 145 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 146 |
+
if attention_mask is not None:
|
| 147 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 148 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 149 |
+
|
| 150 |
+
conv_state_q, conv_state_k = None, None
|
| 151 |
+
if last_state is not None:
|
| 152 |
+
conv_state_q, conv_state_k = last_state['conv_state']
|
| 153 |
+
q, conv_state_q = self.q_conv1d(
|
| 154 |
+
x=self.q_proj(hidden_states),
|
| 155 |
+
cache=conv_state_q,
|
| 156 |
+
output_final_state=use_cache,
|
| 157 |
+
cu_seqlens=cu_seqlens
|
| 158 |
+
)
|
| 159 |
+
k, conv_state_k = self.k_conv1d(
|
| 160 |
+
x=self.k_proj(hidden_states),
|
| 161 |
+
cache=conv_state_k,
|
| 162 |
+
output_final_state=use_cache,
|
| 163 |
+
cu_seqlens=cu_seqlens
|
| 164 |
+
)
|
| 165 |
+
v = self.v_proj(hidden_states)
|
| 166 |
+
|
| 167 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
|
| 168 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 169 |
+
beta = self.b_proj(hidden_states).float().sigmoid()
|
| 170 |
+
g = F.logsigmoid(self.a_proj(hidden_states).float())
|
| 171 |
+
lamb = F.softplus(self.lambda_params.float()) + self.lambda_lower_bound
|
| 172 |
+
lamb = lamb.reshape(self.num_heads, -1)
|
| 173 |
+
|
| 174 |
+
last_h_kk, last_h_kv = last_state['recurrent_state'] if last_state is not None else (None, None)
|
| 175 |
+
|
| 176 |
+
# prefilling or training
|
| 177 |
+
# Note that QK will be normalized inside the kernel to avoid saving the activations, thereby reducing the memory usage.
|
| 178 |
+
if last_state is None:
|
| 179 |
+
o, h_kk, h_kv = chunk_mesa_net(
|
| 180 |
+
q=q,
|
| 181 |
+
k=k,
|
| 182 |
+
v=v,
|
| 183 |
+
g=g,
|
| 184 |
+
beta=beta,
|
| 185 |
+
lamb=lamb,
|
| 186 |
+
output_final_state=use_cache,
|
| 187 |
+
max_CG_iteration=self.max_cg_step_training,
|
| 188 |
+
use_qk_l2norm_in_kernel=True,
|
| 189 |
+
cu_seqlens=cu_seqlens,
|
| 190 |
+
)
|
| 191 |
+
# decoding
|
| 192 |
+
else:
|
| 193 |
+
q = l2_norm(q)
|
| 194 |
+
k = l2_norm(k)
|
| 195 |
+
o, h_kk, h_kv = mesa_net_decoding_one_step(
|
| 196 |
+
q=q.squeeze(0),
|
| 197 |
+
k=k.squeeze(0),
|
| 198 |
+
v=v.squeeze(0),
|
| 199 |
+
g=g.squeeze(0),
|
| 200 |
+
beta=beta.squeeze(0),
|
| 201 |
+
lamb=lamb,
|
| 202 |
+
prev_h_kk=last_h_kk,
|
| 203 |
+
prev_h_kv=last_h_kv,
|
| 204 |
+
max_CG_iteration=self.max_cg_step_decoding
|
| 205 |
+
)
|
| 206 |
+
o = o.unsqueeze(0).to(q)
|
| 207 |
+
|
| 208 |
+
if past_key_values is not None:
|
| 209 |
+
past_key_values.update(
|
| 210 |
+
recurrent_state=(h_kk, h_kv),
|
| 211 |
+
conv_state=(conv_state_q, conv_state_k),
|
| 212 |
+
layer_idx=self.layer_idx,
|
| 213 |
+
offset=q_len
|
| 214 |
+
)
|
| 215 |
+
if self.use_output_gate:
|
| 216 |
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 217 |
+
o = self.o_norm(o, g)
|
| 218 |
+
else:
|
| 219 |
+
o = self.o_norm(o)
|
| 220 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 221 |
+
o = self.o_proj(o)
|
| 222 |
+
if attention_mask is not None:
|
| 223 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 224 |
+
return o, None, past_key_values
|
layers/mla.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
""" Implementing the Deepseek Multi Latent Attention (MLA) module. Reference:
|
| 5 |
+
|
| 6 |
+
https://github.com/huggingface/transformers/blob/main/src/transformers/models/deepseek_v3/modeling_deepseek_v3.py#L328
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import math
|
| 12 |
+
import warnings
|
| 13 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from einops import rearrange, repeat
|
| 19 |
+
from transformers.utils import logging
|
| 20 |
+
|
| 21 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 22 |
+
from fla.modules import RMSNorm, RotaryEmbedding
|
| 23 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from fla.models.utils import Cache
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 30 |
+
except ImportError:
|
| 31 |
+
warnings.warn(
|
| 32 |
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
| 33 |
+
category=ImportWarning
|
| 34 |
+
)
|
| 35 |
+
flash_attn_func = None
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def yarn_get_mscale(scale=1, mscale=1):
|
| 41 |
+
if scale <= 1:
|
| 42 |
+
return 1.0
|
| 43 |
+
return 0.1 * mscale * math.log(scale) + 1.0
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class MultiheadLatentAttention(nn.Module):
|
| 47 |
+
r"""
|
| 48 |
+
Multi-headed attention from [Deepseek V2](https://arxiv.org/abs/2405.04434)
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
hidden_size: int = 2048,
|
| 54 |
+
num_heads: int = 16,
|
| 55 |
+
q_lora_rank: Optional[int] = 1536, # q lora rank is optional, None indicates no q lora
|
| 56 |
+
qk_rope_head_dim: int = 64,
|
| 57 |
+
kv_lora_rank: int = 512, # following the original Deepseek paper
|
| 58 |
+
v_head_dim: int = 128,
|
| 59 |
+
qk_nope_head_dim: int = 128,
|
| 60 |
+
qk_head_dim: Optional[int] = 192, # qk_nope_head_dim + qk_rope_head_dim
|
| 61 |
+
window_size: Optional[int] = None,
|
| 62 |
+
rope_theta: float = 10000.,
|
| 63 |
+
max_position_embeddings: Optional[int] = None,
|
| 64 |
+
rope_scaling: Optional[dict] = None,
|
| 65 |
+
layer_idx: int = None
|
| 66 |
+
) -> MultiheadLatentAttention:
|
| 67 |
+
super().__init__()
|
| 68 |
+
|
| 69 |
+
# sanity check
|
| 70 |
+
if qk_head_dim is not None:
|
| 71 |
+
assert qk_head_dim == qk_nope_head_dim + qk_rope_head_dim, \
|
| 72 |
+
f"qk_head_dim {qk_head_dim} != qk_nope_head_dim {qk_nope_head_dim} + qk_rope_head_dim {qk_rope_head_dim}"
|
| 73 |
+
else:
|
| 74 |
+
qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
| 75 |
+
|
| 76 |
+
# attention params info
|
| 77 |
+
self.hidden_size = hidden_size
|
| 78 |
+
self.num_heads = num_heads
|
| 79 |
+
self.q_lora_rank = q_lora_rank
|
| 80 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
| 81 |
+
self.kv_lora_rank = kv_lora_rank
|
| 82 |
+
self.v_head_dim = v_head_dim
|
| 83 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
| 84 |
+
self.qk_head_dim = qk_head_dim
|
| 85 |
+
|
| 86 |
+
self.window_size = window_size
|
| 87 |
+
self.rope_theta = rope_theta
|
| 88 |
+
self.max_position_embeddings = max_position_embeddings
|
| 89 |
+
self.layer_idx = layer_idx
|
| 90 |
+
|
| 91 |
+
if flash_attn_func is None:
|
| 92 |
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
| 93 |
+
|
| 94 |
+
if q_lora_rank is not None:
|
| 95 |
+
self.q_proj = nn.Sequential(
|
| 96 |
+
nn.Linear(hidden_size, q_lora_rank, bias=False),
|
| 97 |
+
RMSNorm(q_lora_rank),
|
| 98 |
+
nn.Linear(q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
| 99 |
+
)
|
| 100 |
+
else:
|
| 101 |
+
self.q_proj = nn.Linear(hidden_size, self.num_heads * self.qk_head_dim, bias=False)
|
| 102 |
+
|
| 103 |
+
self.k_rope = nn.Linear(hidden_size, self.qk_rope_head_dim, bias=False)
|
| 104 |
+
self.kv_proj = nn.Sequential(
|
| 105 |
+
nn.Linear(hidden_size, self.kv_lora_rank, bias=False),
|
| 106 |
+
RMSNorm(self.kv_lora_rank),
|
| 107 |
+
nn.Linear(self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False)
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, hidden_size, bias=False)
|
| 111 |
+
|
| 112 |
+
self.scaling = self.qk_head_dim ** (-0.5)
|
| 113 |
+
if rope_scaling is not None:
|
| 114 |
+
mscale_all_dim = rope_scaling.get("mscale_all_dim", 0)
|
| 115 |
+
scaling_factor = rope_scaling["factor"]
|
| 116 |
+
if mscale_all_dim:
|
| 117 |
+
mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
|
| 118 |
+
self.scaling = self.scaling * mscale * mscale
|
| 119 |
+
|
| 120 |
+
self.rotary = RotaryEmbedding(dim=self.qk_rope_head_dim, base=self.rope_theta)
|
| 121 |
+
|
| 122 |
+
def forward(
|
| 123 |
+
self,
|
| 124 |
+
hidden_states: torch.Tensor,
|
| 125 |
+
attention_mask: Optional[torch.Tensor],
|
| 126 |
+
past_key_values: Optional[Cache] = None,
|
| 127 |
+
output_attentions: bool = False,
|
| 128 |
+
use_cache: bool = False,
|
| 129 |
+
**kwargs,
|
| 130 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 131 |
+
# if attention_mask is not None, this is doing inference
|
| 132 |
+
if attention_mask is not None:
|
| 133 |
+
assert len(attention_mask.shape) == 2, (
|
| 134 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 135 |
+
"for padding purposes (0 indicating padding). "
|
| 136 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# prepare q, k, v
|
| 140 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 141 |
+
|
| 142 |
+
q_states = self.q_proj(hidden_states)
|
| 143 |
+
q_states = rearrange(q_states, '... (h d) -> ... h d', d=self.qk_head_dim)
|
| 144 |
+
q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
| 145 |
+
k_pass, k_rot = self.kv_proj(hidden_states), self.k_rope(hidden_states)
|
| 146 |
+
|
| 147 |
+
k_rot = rearrange(k_rot, 'b t d -> b t 1 d')
|
| 148 |
+
k_pass = rearrange(k_pass, '... (h d) -> ... h d', d=self.qk_nope_head_dim + self.v_head_dim)
|
| 149 |
+
k_pass, v = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 150 |
+
|
| 151 |
+
# apply rotary position embedding
|
| 152 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 153 |
+
if past_key_values is not None:
|
| 154 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 155 |
+
max_seqlen = q_len + seqlen_offset
|
| 156 |
+
|
| 157 |
+
if attention_mask is not None:
|
| 158 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 159 |
+
max_seqlen = q_len + max(seqlen_offset)
|
| 160 |
+
|
| 161 |
+
if self.max_position_embeddings is not None:
|
| 162 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 163 |
+
cu_seqlens = kwargs.get("cu_seqlens", None)
|
| 164 |
+
q_rot, k_rot = self.rotary(
|
| 165 |
+
q_rot, k_rot, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
k_rot = repeat(k_rot, 'b t 1 d -> b t h d', h=self.num_heads)
|
| 169 |
+
q = torch.cat((q_pass, q_rot), dim=-1)
|
| 170 |
+
k = torch.cat((k_pass, k_rot), dim=-1)
|
| 171 |
+
|
| 172 |
+
# TODO: instead of caching the full k, v, we can actually only cache the compressed_kv and k_rot
|
| 173 |
+
# and recover the full k, v from compressed_kv and k_rot
|
| 174 |
+
if past_key_values is not None:
|
| 175 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 176 |
+
k_cached, v_cached = past_key_values.update(
|
| 177 |
+
attn_state=(k, v),
|
| 178 |
+
layer_idx=self.layer_idx,
|
| 179 |
+
offset=q_len,
|
| 180 |
+
)['attn_state']
|
| 181 |
+
if cache_has_content:
|
| 182 |
+
k, v = k_cached, v_cached
|
| 183 |
+
|
| 184 |
+
# Head dim match to use flash-attn
|
| 185 |
+
if self.qk_head_dim != self.v_head_dim:
|
| 186 |
+
v = F.pad(v, [0, self.qk_head_dim - self.v_head_dim])
|
| 187 |
+
|
| 188 |
+
# Contains at least one padding token in the sequence
|
| 189 |
+
if attention_mask is not None:
|
| 190 |
+
if q.shape[1] == 1 and self.window_size is not None:
|
| 191 |
+
attention_mask = attention_mask[:, -self.window_size:]
|
| 192 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len)
|
| 193 |
+
cu_seqlens_q, cu_seqlens_k = cu_seqlens
|
| 194 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 195 |
+
o = flash_attn_varlen_func(
|
| 196 |
+
q, k, v,
|
| 197 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 198 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 199 |
+
max_seqlen_q=max_seqlen_q,
|
| 200 |
+
max_seqlen_k=max_seqlen_k,
|
| 201 |
+
causal=True,
|
| 202 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 203 |
+
)
|
| 204 |
+
o = pad_input(o, indices_q, batch_size, q_len)
|
| 205 |
+
elif cu_seqlens is not None:
|
| 206 |
+
o = flash_attn_varlen_func(
|
| 207 |
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
| 208 |
+
cu_seqlens_q=cu_seqlens,
|
| 209 |
+
cu_seqlens_k=cu_seqlens,
|
| 210 |
+
max_seqlen_q=max_seqlen,
|
| 211 |
+
max_seqlen_k=max_seqlen,
|
| 212 |
+
causal=True,
|
| 213 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 214 |
+
).unsqueeze(0)
|
| 215 |
+
else:
|
| 216 |
+
o = flash_attn_func(
|
| 217 |
+
q, k, v,
|
| 218 |
+
causal=True,
|
| 219 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
if self.qk_head_dim != self.v_head_dim:
|
| 223 |
+
o = o[:, :, :, :self.v_head_dim]
|
| 224 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 225 |
+
o = self.o_proj(o)
|
| 226 |
+
return o, None, past_key_values
|
layers/mom.py
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
from torch.nn import functional as F
|
| 12 |
+
|
| 13 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 14 |
+
from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from transformers.processing_utils import Unpack
|
| 18 |
+
|
| 19 |
+
from fla.models.utils import Cache
|
| 20 |
+
|
| 21 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input, unpad_input
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _upad_input(
|
| 25 |
+
query_layer: torch.Tensor,
|
| 26 |
+
key_layer: torch.Tensor,
|
| 27 |
+
value_layer: torch.Tensor,
|
| 28 |
+
gate_layer: torch.Tensor,
|
| 29 |
+
beta_layer: torch.Tensor,
|
| 30 |
+
attention_mask: torch.Tensor,
|
| 31 |
+
):
|
| 32 |
+
"""
|
| 33 |
+
Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to
|
| 34 |
+
different batches.
|
| 35 |
+
|
| 36 |
+
This function is used instead of `flash_attn.bert_padding.unpad_input` in order to avoid the recomputation
|
| 37 |
+
of the same intermediary
|
| 38 |
+
tensors for query, key, value tensors.
|
| 39 |
+
|
| 40 |
+
Arguments:
|
| 41 |
+
query_layer (`torch.Tensor`):
|
| 42 |
+
Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim).
|
| 43 |
+
key_layer (`torch.Tensor`):
|
| 44 |
+
Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
|
| 45 |
+
value_layer (`torch.Tensor`):
|
| 46 |
+
Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
|
| 47 |
+
attention_mask (`torch.Tensor`):
|
| 48 |
+
Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
|
| 49 |
+
query_length (`int`):
|
| 50 |
+
Target length.
|
| 51 |
+
|
| 52 |
+
Return:
|
| 53 |
+
query_layer (`torch.Tensor`):
|
| 54 |
+
Query state without padding. Shape: (total_target_length, num_heads, head_dim).
|
| 55 |
+
key_layer (`torch.Tensor`):
|
| 56 |
+
Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
|
| 57 |
+
value_layer (`torch.Tensor`):
|
| 58 |
+
Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
|
| 59 |
+
indices_q (`torch.Tensor`):
|
| 60 |
+
The indices of non-masked tokens from the flattened input target sequence.
|
| 61 |
+
(cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`):
|
| 62 |
+
The cumulative sequence lengths for the target (query) and source (key, value), used to index
|
| 63 |
+
into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,).
|
| 64 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`):
|
| 65 |
+
Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query,
|
| 66 |
+
`max_seqlen_in_batch_k` for the source sequence i.e. key/value).
|
| 67 |
+
"""
|
| 68 |
+
query_length = query_layer.shape[1]
|
| 69 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = get_unpad_data(attention_mask)
|
| 70 |
+
batch_size, kv_seq_len, dim = key_layer.shape
|
| 71 |
+
v_dim = value_layer.shape[-1]
|
| 72 |
+
|
| 73 |
+
key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, dim), indices_k)
|
| 74 |
+
value_layer = index_first_axis(
|
| 75 |
+
value_layer.reshape(batch_size * kv_seq_len, v_dim), indices_k
|
| 76 |
+
)
|
| 77 |
+
gate_layer = index_first_axis(gate_layer.reshape(batch_size * kv_seq_len, -1), indices_k)
|
| 78 |
+
beta_layer = index_first_axis(beta_layer.reshape(batch_size * kv_seq_len, -1), indices_k)
|
| 79 |
+
if query_length == kv_seq_len:
|
| 80 |
+
query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, dim), indices_k)
|
| 81 |
+
cu_seqlens_q = cu_seqlens_k
|
| 82 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 83 |
+
indices_q = indices_k
|
| 84 |
+
elif query_length == 1:
|
| 85 |
+
max_seqlen_in_batch_q = 1
|
| 86 |
+
cu_seqlens_q = torch.arange(
|
| 87 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 88 |
+
) # There is a memcpy here, that is very bad.
|
| 89 |
+
indices_q = cu_seqlens_q[:-1]
|
| 90 |
+
query_layer = query_layer.squeeze(1)
|
| 91 |
+
else:
|
| 92 |
+
# The -q_len: slice assumes left padding.
|
| 93 |
+
attention_mask = attention_mask[:, -query_length:]
|
| 94 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 95 |
+
|
| 96 |
+
return (
|
| 97 |
+
query_layer,
|
| 98 |
+
key_layer,
|
| 99 |
+
value_layer,
|
| 100 |
+
gate_layer,
|
| 101 |
+
beta_layer,
|
| 102 |
+
indices_q,
|
| 103 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 104 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def transform(
|
| 109 |
+
x: torch.Tensor,
|
| 110 |
+
routing_mask: torch.Tensor,
|
| 111 |
+
num_memories: int,
|
| 112 |
+
selected_memories: torch.Tensor,
|
| 113 |
+
attention_mask: torch.Tensor,
|
| 114 |
+
):
|
| 115 |
+
"""
|
| 116 |
+
Reorganize token embeddings into memory-aligned chunks.
|
| 117 |
+
|
| 118 |
+
Steps:
|
| 119 |
+
- Expand for top-k routing if needed.
|
| 120 |
+
- Mask out padded tokens via `attention_mask`.
|
| 121 |
+
- Sort tokens by (batch, memory).
|
| 122 |
+
- Gather and pad tokens per memory slot.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
x: (batch, seq, hidden) input embeddings.
|
| 126 |
+
routing_mask: (batch, seq, num_memories) binary routing mask.
|
| 127 |
+
num_memories: number of memory slots.
|
| 128 |
+
selected_memories: memory indices per token,
|
| 129 |
+
(batch, seq) if k=1 else (batch, seq, topk).
|
| 130 |
+
attention_mask: (batch, seq) valid-token mask.
|
| 131 |
+
|
| 132 |
+
Returns:
|
| 133 |
+
transformed_x: (num_memories, batch, max_len, hidden) reorganized tokens.
|
| 134 |
+
truncation_indices: (batch*num_memories, max_len) gather indices.
|
| 135 |
+
sorted_indices: (batch*seq*topk,) global sort order.
|
| 136 |
+
max_len: int, max tokens per memory.
|
| 137 |
+
mask: (batch*num_memories, max_len) validity mask.
|
| 138 |
+
mask_2: (num_memories, batch, max_len) validity mask reshaped.
|
| 139 |
+
"""
|
| 140 |
+
if selected_memories.dim() == 3:
|
| 141 |
+
# (batch, seq, topk)
|
| 142 |
+
topk = selected_memories.shape[2]
|
| 143 |
+
# x (batch, seq, hidden)
|
| 144 |
+
x = x.repeat_interleave(topk, dim=1)
|
| 145 |
+
# x (batch, seq * topk, hidden)
|
| 146 |
+
# (batch, seq, topk)
|
| 147 |
+
selected_memories = selected_memories.reshape(selected_memories.shape[0], -1)
|
| 148 |
+
# (batch, seq * topk)
|
| 149 |
+
|
| 150 |
+
if attention_mask is not None:
|
| 151 |
+
attention_mask = attention_mask[:, -routing_mask.shape[1]:]
|
| 152 |
+
# mask out the masked tokens
|
| 153 |
+
routing_mask[attention_mask.bitwise_not().unsqueeze(-1).expand(-1, -1, num_memories)] = 0
|
| 154 |
+
|
| 155 |
+
b, s, d = x.shape
|
| 156 |
+
x_flat = x.reshape(b * s, d) # [b*s, d]
|
| 157 |
+
|
| 158 |
+
with torch.no_grad():
|
| 159 |
+
batch_indices = torch.arange(b, device=x.device).unsqueeze(-1)
|
| 160 |
+
batch_indices = batch_indices.repeat(1, s).reshape(-1)
|
| 161 |
+
if attention_mask is not None:
|
| 162 |
+
# sort the masked tokens to the end
|
| 163 |
+
batch_indices[attention_mask.repeat_interleave(topk, dim=1).bitwise_not().flatten()] = b
|
| 164 |
+
# (b * s)
|
| 165 |
+
memories_flat = selected_memories.reshape(-1) # [b*s]
|
| 166 |
+
|
| 167 |
+
combined = batch_indices * (memories_flat.max() + 1) + memories_flat
|
| 168 |
+
sorted_indices = combined.argsort()
|
| 169 |
+
|
| 170 |
+
x_sorted = x_flat[sorted_indices] # [b*s, d]
|
| 171 |
+
# (b*s, hidden) -> (b, s, hidd)
|
| 172 |
+
with torch.no_grad():
|
| 173 |
+
# routing_mask (b, s, num_memories)
|
| 174 |
+
batch_memory_tokens = routing_mask.sum(dim=1)
|
| 175 |
+
# (b, num_memories)
|
| 176 |
+
flatten_offset = batch_memory_tokens.flatten().cumsum(dim=0)
|
| 177 |
+
max_len = batch_memory_tokens.max()
|
| 178 |
+
indices = (
|
| 179 |
+
torch.arange(max_len, device=flatten_offset.device).unsqueeze(0).expand(b * num_memories, -1)
|
| 180 |
+
+ torch.cat([torch.tensor([0], device=flatten_offset.device), flatten_offset[:-1]], dim=0).unsqueeze(1)
|
| 181 |
+
)
|
| 182 |
+
mask = indices < flatten_offset.unsqueeze(-1)
|
| 183 |
+
truncation_indices = torch.where(mask, indices, torch.zeros_like(indices))
|
| 184 |
+
|
| 185 |
+
gathered_x = torch.gather(x_sorted, 0, truncation_indices.reshape(-1).unsqueeze(-1).expand(-1, d))
|
| 186 |
+
transformed_x = gathered_x.reshape(b * num_memories, -1, d).reshape((b, num_memories, max_len, d)).transpose(0, 1)
|
| 187 |
+
# transformed_x = transformed_x * mask.unsqueeze(-1).expand_as(transformed_x)
|
| 188 |
+
# pad_x = torch.zeros((b * num_memories, capacity_len-max_len, d), dtype=transformed_x.dtype, device=transformed_x.device)
|
| 189 |
+
# pad_mask = torch.zeros((b * num_memories, capacity_len-max_len), dtype=transformed_x.dtype, device=transformed_x.device)
|
| 190 |
+
# left pad
|
| 191 |
+
# transformed_x = torch.cat((pad_x, transformed_x), dim=1).reshape((b, num_memories, capacity_len, d)).transpose(0, 1)
|
| 192 |
+
mask_2 = mask.reshape((b, num_memories, max_len)).transpose(0, 1)
|
| 193 |
+
# truncation_indices += capacity_len-max_len
|
| 194 |
+
# if attention_mask is not None:
|
| 195 |
+
# mask_2
|
| 196 |
+
|
| 197 |
+
return transformed_x, truncation_indices, sorted_indices, max_len, mask, mask_2
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def reconstruct(
|
| 201 |
+
transformed_x,
|
| 202 |
+
indices: torch.Tensor,
|
| 203 |
+
sorted_indices: torch.Tensor,
|
| 204 |
+
batch_size: int,
|
| 205 |
+
seq_len: int,
|
| 206 |
+
topk: int,
|
| 207 |
+
routing_weights: torch.Tensor,
|
| 208 |
+
mask: torch.Tensor
|
| 209 |
+
):
|
| 210 |
+
'''
|
| 211 |
+
Reconstruct and mix transformed outputs back into the original input sequence shape.
|
| 212 |
+
|
| 213 |
+
Key operations:
|
| 214 |
+
1. Reshapes and transposes `transformed_x` to prepare for scattering.
|
| 215 |
+
2. Applies the `mask` to zero out invalid positions.
|
| 216 |
+
3. Uses `torch.scatter_add_` to scatter and sum the transformed outputs back to their original positions
|
| 217 |
+
based on `indices`.
|
| 218 |
+
4. Rearranges the scattered outputs using `sorted_indices` to ensure correct ordering.
|
| 219 |
+
5. Applies the `routing_weights` to weight the outputs.
|
| 220 |
+
6. Sums over the `topk` dimension to produce the final reconstructed output.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
transformed_x (torch.Tensor):
|
| 224 |
+
The transformed output tensor from memory units or experts.
|
| 225 |
+
Shape: (num_memories, batch_size, capacity_len, hidden_size)
|
| 226 |
+
indices (torch.Tensor):
|
| 227 |
+
Indices used for scattering the transformed outputs back to their corresponding positions.
|
| 228 |
+
Shape: (batch*num_memories, max_len)
|
| 229 |
+
sorted_indices (torch.Tensor):
|
| 230 |
+
Sorting indices used to rearrange the scattered outputs back into the original sequence order.
|
| 231 |
+
Shape: (batch_size*seq_len*topk)
|
| 232 |
+
batch_size (int):
|
| 233 |
+
The size of the batch.
|
| 234 |
+
seq_len (int):
|
| 235 |
+
The length of the input sequence.
|
| 236 |
+
topk (int):
|
| 237 |
+
The number of top elements selected (`topk`) per token during the selection process.
|
| 238 |
+
routing_weights (torch.Tensor):
|
| 239 |
+
Routing weights assigned to the top-k selected outputs when reconstructing the final output.
|
| 240 |
+
Shape: (batch_size, seq_len, topk)
|
| 241 |
+
mask (torch.Tensor):
|
| 242 |
+
Boolean mask indicating valid positions in the sequence.
|
| 243 |
+
Shape: (batch*num_memories, max_len)
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
restored_x (torch.Tensor):
|
| 247 |
+
The reconstructed output tensor in the original input sequence shape.
|
| 248 |
+
Shape: (batch_size, seq_len, hidden_size)
|
| 249 |
+
'''
|
| 250 |
+
transformed_x = transformed_x.transpose(0, 1).reshape(
|
| 251 |
+
(-1, transformed_x.shape[2], transformed_x.shape[3]))
|
| 252 |
+
b, s, k, d = batch_size, seq_len, topk, transformed_x.shape[2]
|
| 253 |
+
gathered_x = transformed_x.reshape(
|
| 254 |
+
(transformed_x.shape[0] * transformed_x.shape[1], transformed_x.shape[2]))
|
| 255 |
+
mask_expanded = mask.reshape(-1).unsqueeze(-1).expand_as(gathered_x)
|
| 256 |
+
gathered_x = gathered_x * mask_expanded
|
| 257 |
+
|
| 258 |
+
assert (indices >= 0).all(), "Indices should be non-negative"
|
| 259 |
+
|
| 260 |
+
resortd_x = torch.zeros((b * s * k, d), device=gathered_x.device, dtype=gathered_x.dtype).scatter_add_(
|
| 261 |
+
0,
|
| 262 |
+
indices.reshape(-1).unsqueeze(-1).expand(-1, d),
|
| 263 |
+
gathered_x,
|
| 264 |
+
)
|
| 265 |
+
assert (indices < resortd_x.size(0)).all(), "Indices should be less than resortd_x size"
|
| 266 |
+
|
| 267 |
+
inverse_indices = sorted_indices.argsort()
|
| 268 |
+
rearranged_x_flat = resortd_x[inverse_indices]
|
| 269 |
+
restored_x = rearranged_x_flat.reshape((b, s * k, d))
|
| 270 |
+
restored_x = restored_x.reshape(b, s, k, d) * routing_weights.reshape(b, s, k).unsqueeze(-1)
|
| 271 |
+
restored_x = restored_x.sum(dim=2)
|
| 272 |
+
return restored_x
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class MomAttention(nn.Module):
|
| 276 |
+
"""
|
| 277 |
+
The layer implementaion for [MoM: Linear Sequence Modeling with Mixture-of-Memories](https://arxiv.org/abs/2502.13685).
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
def __init__(
|
| 281 |
+
self,
|
| 282 |
+
hidden_size: int = 2048,
|
| 283 |
+
head_dim: int = 256,
|
| 284 |
+
num_heads: int = 4,
|
| 285 |
+
expand_v: float = 2,
|
| 286 |
+
mode: str = 'chunk',
|
| 287 |
+
use_output_gate: bool = True,
|
| 288 |
+
use_short_conv: bool = True,
|
| 289 |
+
conv_size: int = 4,
|
| 290 |
+
conv_bias: bool = False,
|
| 291 |
+
layer_idx: int = None,
|
| 292 |
+
norm_eps: float = 1e-5,
|
| 293 |
+
num_memories: int = 8,
|
| 294 |
+
topk: int = 2,
|
| 295 |
+
capacity: float = 1.0,
|
| 296 |
+
shared_mem: bool = False,
|
| 297 |
+
single_kv_proj: bool = False,
|
| 298 |
+
**kwargs
|
| 299 |
+
) -> MomAttention:
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.num_memories = num_memories
|
| 302 |
+
self.topk = topk
|
| 303 |
+
self.capacity = capacity
|
| 304 |
+
self.shared_mem = shared_mem
|
| 305 |
+
self.single_kv_proj = single_kv_proj
|
| 306 |
+
|
| 307 |
+
self.mode = mode
|
| 308 |
+
|
| 309 |
+
self.hidden_size = hidden_size
|
| 310 |
+
self.expand_v = expand_v
|
| 311 |
+
|
| 312 |
+
self.use_output_gate = use_output_gate
|
| 313 |
+
self.use_short_conv = use_short_conv
|
| 314 |
+
self.conv_size = conv_size
|
| 315 |
+
self.conv_bias = conv_bias
|
| 316 |
+
|
| 317 |
+
self.head_dim = head_dim
|
| 318 |
+
self.num_heads = num_heads
|
| 319 |
+
|
| 320 |
+
self.key_dim = int(self.num_heads * self.head_dim)
|
| 321 |
+
self.value_dim = int(self.key_dim * self.expand_v)
|
| 322 |
+
self.head_qk_dim = head_dim
|
| 323 |
+
self.head_v_dim = int(head_dim * self.expand_v)
|
| 324 |
+
self.layer_idx = layer_idx
|
| 325 |
+
self.silu = nn.SiLU()
|
| 326 |
+
|
| 327 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 328 |
+
|
| 329 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 330 |
+
self.gate = nn.Linear(self.hidden_size, self.num_memories, bias=False)
|
| 331 |
+
if self.single_kv_proj:
|
| 332 |
+
self.shared_k = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 333 |
+
self.shared_v = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 334 |
+
self.shared_b = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 335 |
+
self.shared_a = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 336 |
+
else:
|
| 337 |
+
self.k_proj = nn.ModuleList([
|
| 338 |
+
nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
| 339 |
+
for _ in range(self.num_memories)
|
| 340 |
+
])
|
| 341 |
+
self.v_proj = nn.ModuleList([
|
| 342 |
+
nn.Linear(self.hidden_size, self.value_dim, bias=False)
|
| 343 |
+
for _ in range(self.num_memories)
|
| 344 |
+
])
|
| 345 |
+
self.b_proj = nn.ModuleList([
|
| 346 |
+
nn.Linear(self.hidden_size, self.num_heads, bias=False)
|
| 347 |
+
for _ in range(self.num_memories)
|
| 348 |
+
])
|
| 349 |
+
self.a_proj = nn.ModuleList([
|
| 350 |
+
nn.Linear(self.hidden_size, self.num_heads, bias=False)
|
| 351 |
+
for _ in range(self.num_memories)
|
| 352 |
+
])
|
| 353 |
+
if self.shared_mem:
|
| 354 |
+
self.shared_k = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 355 |
+
self.shared_v = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 356 |
+
self.shared_b = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 357 |
+
self.shared_a = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 358 |
+
|
| 359 |
+
A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 360 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 361 |
+
self.A_log._no_weight_decay = True
|
| 362 |
+
# hard coded for now
|
| 363 |
+
dt_min = 0.001
|
| 364 |
+
dt_max = 0.1
|
| 365 |
+
dt_init_floor = 1e-4
|
| 366 |
+
dt = torch.exp(
|
| 367 |
+
torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 368 |
+
+ math.log(dt_min)
|
| 369 |
+
)
|
| 370 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 371 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 372 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 373 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 374 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 375 |
+
# name.endswith("bias") in param_grouping.py
|
| 376 |
+
self.dt_bias._no_weight_decay = True
|
| 377 |
+
|
| 378 |
+
if use_short_conv:
|
| 379 |
+
self.conv_size = conv_size
|
| 380 |
+
self.q_conv1d = ShortConvolution(
|
| 381 |
+
hidden_size=self.key_dim,
|
| 382 |
+
kernel_size=conv_size,
|
| 383 |
+
bias=conv_bias,
|
| 384 |
+
activation='silu'
|
| 385 |
+
)
|
| 386 |
+
self.k_conv1d = ShortConvolution(
|
| 387 |
+
hidden_size=self.key_dim,
|
| 388 |
+
kernel_size=conv_size,
|
| 389 |
+
bias=conv_bias,
|
| 390 |
+
activation='silu'
|
| 391 |
+
)
|
| 392 |
+
self.v_conv1d = ShortConvolution(
|
| 393 |
+
hidden_size=self.value_dim,
|
| 394 |
+
kernel_size=conv_size,
|
| 395 |
+
bias=conv_bias,
|
| 396 |
+
activation='silu'
|
| 397 |
+
)
|
| 398 |
+
else:
|
| 399 |
+
raise UserWarning(
|
| 400 |
+
"ShortConvolution is crucial to the performance. "
|
| 401 |
+
"Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing."
|
| 402 |
+
)
|
| 403 |
+
if use_output_gate:
|
| 404 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 405 |
+
self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps)
|
| 406 |
+
else:
|
| 407 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 408 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 409 |
+
self.apply(self._initialize_weights)
|
| 410 |
+
|
| 411 |
+
def _initialize_weights(self, module: nn.Module):
|
| 412 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 413 |
+
return
|
| 414 |
+
if isinstance(module, nn.Linear):
|
| 415 |
+
nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 416 |
+
if module.bias is not None:
|
| 417 |
+
nn.init.zeros_(module.bias)
|
| 418 |
+
module._is_hf_initialized = True
|
| 419 |
+
|
| 420 |
+
def forward(
|
| 421 |
+
self,
|
| 422 |
+
hidden_states: torch.Tensor,
|
| 423 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 424 |
+
past_key_values: Optional[Cache] = None,
|
| 425 |
+
use_cache: Optional[bool] = False,
|
| 426 |
+
output_attentions: Optional[bool] = False,
|
| 427 |
+
**kwargs: Unpack[Dict]
|
| 428 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 429 |
+
if attention_mask is not None:
|
| 430 |
+
attention_mask = (attention_mask == 1)
|
| 431 |
+
assert len(attention_mask.shape) == 2, (
|
| 432 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 433 |
+
"for padding purposes (0 indicating padding). "
|
| 434 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
origin_cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 438 |
+
if origin_cu_seqlens is not None:
|
| 439 |
+
hidden_states, attention_mask = self.cu2pad(hidden_states, origin_cu_seqlens)
|
| 440 |
+
|
| 441 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 442 |
+
if self.training:
|
| 443 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 444 |
+
|
| 445 |
+
last_state = None
|
| 446 |
+
# _, q_len = hidden_states.shape[0], hidden_states.shape[1]
|
| 447 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 448 |
+
last_state = past_key_values[self.layer_idx]
|
| 449 |
+
|
| 450 |
+
# 🔍 topk gating
|
| 451 |
+
router_logits = self.gate(hidden_states) # (bsz, q_len, num_memories)
|
| 452 |
+
scores = F.softmax(router_logits, dim=2, dtype=torch.float)
|
| 453 |
+
routing_weights, selected_memories = torch.topk(scores, self.topk, dim=-1) # (bsz, seq, topk)
|
| 454 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 455 |
+
routing_weights = routing_weights.to(hidden_states.dtype) # we cast back to the input dtype
|
| 456 |
+
routing_weights_full = torch.zeros(
|
| 457 |
+
routing_weights.shape[0],
|
| 458 |
+
routing_weights.shape[1],
|
| 459 |
+
self.num_memories,
|
| 460 |
+
dtype=routing_weights.dtype,
|
| 461 |
+
device=routing_weights.device
|
| 462 |
+
).scatter(-1, selected_memories, routing_weights)
|
| 463 |
+
routing_mask = routing_weights_full.bool().int()
|
| 464 |
+
|
| 465 |
+
# if self.use_output_gate:
|
| 466 |
+
# o_g = self.g_proj(hidden_states)
|
| 467 |
+
|
| 468 |
+
batch_size, seq_len = hidden_states.shape[0], hidden_states.shape[1]
|
| 469 |
+
|
| 470 |
+
shared_hidden_states = hidden_states
|
| 471 |
+
hidden_states, indices, sorted_indices, max_len, mask, mask_2 = transform(
|
| 472 |
+
hidden_states, routing_mask, self.num_memories, selected_memories, attention_mask)
|
| 473 |
+
|
| 474 |
+
q = self.q_proj(hidden_states)
|
| 475 |
+
if self.single_kv_proj:
|
| 476 |
+
k = self.shared_k(hidden_states)
|
| 477 |
+
v = self.shared_v(hidden_states)
|
| 478 |
+
beta = self.shared_b(hidden_states).sigmoid()
|
| 479 |
+
g = -self.A_log.float().exp() * F.softplus(self.shared_a(hidden_states).float() + self.dt_bias)
|
| 480 |
+
else:
|
| 481 |
+
k = torch.stack([k_expert(hidden_states[i]) for i, k_expert in enumerate(self.k_proj)], dim=0)
|
| 482 |
+
v = torch.stack([v_expert(hidden_states[i]) for i, v_expert in enumerate(self.v_proj)], dim=0)
|
| 483 |
+
beta = torch.stack([b_expert(hidden_states[i]).sigmoid() for i, b_expert in enumerate(self.b_proj)], dim=0)
|
| 484 |
+
g = torch.stack([-self.A_log.float().exp() * F.softplus(a_expert(hidden_states[i]).float() + self.dt_bias)
|
| 485 |
+
for i, a_expert in enumerate(self.a_proj)], dim=0)
|
| 486 |
+
|
| 487 |
+
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))
|
| 488 |
+
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)
|
| 489 |
+
cu_seqlens, reverse_indices = cu_seqlen_all[0].to(torch.long).unique(return_inverse=True)
|
| 490 |
+
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))
|
| 491 |
+
|
| 492 |
+
if self.use_short_conv:
|
| 493 |
+
conv_state_q, conv_state_k, conv_state_v = [None, None], [None, None], [None, None]
|
| 494 |
+
if last_state is not None:
|
| 495 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 496 |
+
|
| 497 |
+
conv_cu_seqlens = cu_seqlens
|
| 498 |
+
padded = False
|
| 499 |
+
if self.training:
|
| 500 |
+
conv_cu_seqlens = None
|
| 501 |
+
elif seq_len != 1 and (cu_seqlens[1:] - cu_seqlens[:-1]).min().item() < self.conv_size:
|
| 502 |
+
padded = True
|
| 503 |
+
conv_cu_seqlens, cu_q, cu_k, cu_v, pad_lengths = self.pad_for_conv(cu_seqlens, cu_q, cu_k, cu_v)
|
| 504 |
+
|
| 505 |
+
conv_q = self.prepare_recurrent_state(
|
| 506 |
+
conv_state_q[0],
|
| 507 |
+
conv_cu_seqlens,
|
| 508 |
+
cu_seqlen_all[0],
|
| 509 |
+
reverse_indices,
|
| 510 |
+
batch_size
|
| 511 |
+
)
|
| 512 |
+
cu_q, conv_q_new = self.q_conv1d(
|
| 513 |
+
x=cu_q,
|
| 514 |
+
cache=conv_q,
|
| 515 |
+
output_final_state=use_cache,
|
| 516 |
+
cu_seqlens=conv_cu_seqlens,
|
| 517 |
+
)
|
| 518 |
+
conv_state_q[0] = self.handle_recurrent_state(
|
| 519 |
+
conv_state_q[0],
|
| 520 |
+
conv_q_new,
|
| 521 |
+
conv_cu_seqlens,
|
| 522 |
+
cu_seqlen_all[0],
|
| 523 |
+
reverse_indices
|
| 524 |
+
)
|
| 525 |
+
conv_k = self.prepare_recurrent_state(
|
| 526 |
+
conv_state_k[0],
|
| 527 |
+
conv_cu_seqlens,
|
| 528 |
+
cu_seqlen_all[0],
|
| 529 |
+
reverse_indices,
|
| 530 |
+
batch_size
|
| 531 |
+
)
|
| 532 |
+
cu_k, conv_k_new = self.k_conv1d(
|
| 533 |
+
x=cu_k,
|
| 534 |
+
cache=conv_k,
|
| 535 |
+
output_final_state=use_cache,
|
| 536 |
+
cu_seqlens=conv_cu_seqlens,
|
| 537 |
+
)
|
| 538 |
+
conv_state_k[0] = self.handle_recurrent_state(
|
| 539 |
+
conv_state_k[0],
|
| 540 |
+
conv_k_new,
|
| 541 |
+
conv_cu_seqlens,
|
| 542 |
+
cu_seqlen_all[0],
|
| 543 |
+
reverse_indices
|
| 544 |
+
)
|
| 545 |
+
conv_v = self.prepare_recurrent_state(
|
| 546 |
+
conv_state_v[0],
|
| 547 |
+
conv_cu_seqlens,
|
| 548 |
+
cu_seqlen_all[0],
|
| 549 |
+
reverse_indices,
|
| 550 |
+
batch_size
|
| 551 |
+
)
|
| 552 |
+
cu_v, conv_v_new = self.v_conv1d(
|
| 553 |
+
x=cu_v,
|
| 554 |
+
cache=conv_v,
|
| 555 |
+
output_final_state=use_cache,
|
| 556 |
+
cu_seqlens=conv_cu_seqlens,
|
| 557 |
+
)
|
| 558 |
+
conv_state_v[0] = self.handle_recurrent_state(
|
| 559 |
+
conv_state_v[0],
|
| 560 |
+
conv_v_new, conv_cu_seqlens,
|
| 561 |
+
cu_seqlen_all[0],
|
| 562 |
+
reverse_indices
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
if padded:
|
| 566 |
+
cu_q, cu_k, cu_v = self.unpad_after_conv(conv_cu_seqlens, cu_seqlens, cu_q, cu_k, cu_v, pad_lengths)
|
| 567 |
+
|
| 568 |
+
else:
|
| 569 |
+
q, k, v = self.silu(q), self.silu(k), self.silu(v),
|
| 570 |
+
|
| 571 |
+
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))
|
| 572 |
+
|
| 573 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else [
|
| 574 |
+
None for _ in range(1 + self.shared_mem)]
|
| 575 |
+
if mode == 'chunk':
|
| 576 |
+
o, recurrent_state_ = chunk_gated_delta_rule(
|
| 577 |
+
q=cu_q,
|
| 578 |
+
k=cu_k,
|
| 579 |
+
v=cu_v,
|
| 580 |
+
g=cu_g,
|
| 581 |
+
beta=cu_beta,
|
| 582 |
+
initial_state=recurrent_state[0],
|
| 583 |
+
output_final_state=use_cache,
|
| 584 |
+
use_qk_l2norm_in_kernel=True,
|
| 585 |
+
cu_seqlens=cu_seqlens,
|
| 586 |
+
)
|
| 587 |
+
recurrent_state[0] = self.handle_recurrent_state(
|
| 588 |
+
recurrent_state[0],
|
| 589 |
+
recurrent_state_,
|
| 590 |
+
cu_seqlens,
|
| 591 |
+
cu_seqlen_all[0],
|
| 592 |
+
reverse_indices,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
elif mode == 'fused_recurrent':
|
| 596 |
+
memories = self.prepare_recurrent_state(
|
| 597 |
+
recurrent_state[0],
|
| 598 |
+
cu_seqlens, cu_seqlen_all[0],
|
| 599 |
+
reverse_indices, batch_size
|
| 600 |
+
)
|
| 601 |
+
o, recurrent_state_ = fused_recurrent_gated_delta_rule(
|
| 602 |
+
q=cu_q,
|
| 603 |
+
k=cu_k,
|
| 604 |
+
v=cu_v,
|
| 605 |
+
g=cu_g,
|
| 606 |
+
beta=cu_beta,
|
| 607 |
+
initial_state=memories,
|
| 608 |
+
output_final_state=use_cache,
|
| 609 |
+
use_qk_l2norm_in_kernel=True,
|
| 610 |
+
cu_seqlens=cu_seqlens,
|
| 611 |
+
)
|
| 612 |
+
recurrent_state[0] = self.handle_recurrent_state(
|
| 613 |
+
recurrent_state[0],
|
| 614 |
+
recurrent_state_,
|
| 615 |
+
cu_seqlens,
|
| 616 |
+
cu_seqlen_all[0],
|
| 617 |
+
reverse_indices,
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
o = o.squeeze(0).contiguous()
|
| 621 |
+
o = pad_input(o, indices_q, batch_size*self.num_memories, max_len)
|
| 622 |
+
o = rearrange(o, '(e b) l h d -> e b l (h d)', b=batch_size)
|
| 623 |
+
o = reconstruct(o, indices=indices, sorted_indices=sorted_indices, batch_size=batch_size,
|
| 624 |
+
seq_len=seq_len, topk=self.topk, routing_weights=routing_weights, mask=mask)
|
| 625 |
+
o = rearrange(o, 'b l (h d) -> b l h d', h=self.num_heads)
|
| 626 |
+
|
| 627 |
+
if self.shared_mem:
|
| 628 |
+
shared_o = self.shared_o(shared_hidden_states, attention_mask, recurrent_state,
|
| 629 |
+
use_cache, conv_state_q, conv_state_k, conv_state_v)
|
| 630 |
+
o += shared_o
|
| 631 |
+
|
| 632 |
+
if past_key_values is not None:
|
| 633 |
+
past_key_values.update(
|
| 634 |
+
recurrent_state=recurrent_state,
|
| 635 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 636 |
+
layer_idx=self.layer_idx,
|
| 637 |
+
offset=q.shape[2]
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
if self.use_output_gate:
|
| 641 |
+
g = rearrange(self.g_proj(shared_hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 642 |
+
o = self.o_norm(o, g)
|
| 643 |
+
else:
|
| 644 |
+
o = self.o_norm(o)
|
| 645 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 646 |
+
o = self.o_proj(o)
|
| 647 |
+
|
| 648 |
+
if origin_cu_seqlens is not None:
|
| 649 |
+
indices, _, _ = get_unpad_data(attention_mask[:, -seq_len:])
|
| 650 |
+
o = index_first_axis(rearrange(o, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 651 |
+
|
| 652 |
+
return o, None, past_key_values, router_logits.view(-1, self.num_memories)
|
| 653 |
+
|
| 654 |
+
def shared_o(
|
| 655 |
+
self,
|
| 656 |
+
hidden_states: torch.Tensor,
|
| 657 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 658 |
+
recurrent_state=None,
|
| 659 |
+
use_cache: Optional[bool] = False,
|
| 660 |
+
conv_state_q=[None, None],
|
| 661 |
+
conv_state_k=[None, None],
|
| 662 |
+
conv_state_v=[None, None],
|
| 663 |
+
**kwargs
|
| 664 |
+
) -> torch.Tensor:
|
| 665 |
+
if attention_mask is not None:
|
| 666 |
+
assert len(attention_mask.shape) == 2, (
|
| 667 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 668 |
+
"for padding purposes (0 indicating padding). "
|
| 669 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 673 |
+
if self.training:
|
| 674 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 675 |
+
|
| 676 |
+
cu_seqlens = None
|
| 677 |
+
if attention_mask is not None:
|
| 678 |
+
batch_size, q_len = hidden_states.shape[0], hidden_states.shape[1]
|
| 679 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 680 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 681 |
+
|
| 682 |
+
if self.use_short_conv:
|
| 683 |
+
q, conv_state_q[1] = self.q_conv1d(
|
| 684 |
+
x=self.q_proj(hidden_states),
|
| 685 |
+
cache=conv_state_q[1],
|
| 686 |
+
output_final_state=use_cache,
|
| 687 |
+
cu_seqlens=cu_seqlens
|
| 688 |
+
)
|
| 689 |
+
k, conv_state_k[1] = self.k_conv1d(
|
| 690 |
+
x=self.shared_k(hidden_states),
|
| 691 |
+
cache=conv_state_k[1],
|
| 692 |
+
output_final_state=use_cache,
|
| 693 |
+
cu_seqlens=cu_seqlens
|
| 694 |
+
)
|
| 695 |
+
v, conv_state_v[1] = self.v_conv1d(
|
| 696 |
+
x=self.shared_v(hidden_states),
|
| 697 |
+
cache=conv_state_v[1],
|
| 698 |
+
output_final_state=use_cache,
|
| 699 |
+
cu_seqlens=cu_seqlens
|
| 700 |
+
)
|
| 701 |
+
else:
|
| 702 |
+
q = self.silu(self.q_proj(hidden_states))
|
| 703 |
+
k = self.silu(self.shared_k(hidden_states))
|
| 704 |
+
v = self.silu(self.shared_v(hidden_states))
|
| 705 |
+
|
| 706 |
+
q, k, v = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', h=self.num_heads), (q, k, v))
|
| 707 |
+
beta = self.shared_b(hidden_states).sigmoid()
|
| 708 |
+
g = -self.A_log.float().exp() * F.softplus(self.shared_a(hidden_states).float() + self.dt_bias)
|
| 709 |
+
|
| 710 |
+
if mode == 'chunk':
|
| 711 |
+
o, recurrent_state[-1] = chunk_gated_delta_rule(
|
| 712 |
+
q=q,
|
| 713 |
+
k=k,
|
| 714 |
+
v=v,
|
| 715 |
+
g=g,
|
| 716 |
+
beta=beta,
|
| 717 |
+
initial_state=recurrent_state[-1],
|
| 718 |
+
output_final_state=use_cache,
|
| 719 |
+
cu_seqlens=cu_seqlens,
|
| 720 |
+
use_qk_l2norm_in_kernel=True
|
| 721 |
+
)
|
| 722 |
+
elif mode == 'fused_recurrent':
|
| 723 |
+
o, recurrent_state[-1] = fused_recurrent_gated_delta_rule(
|
| 724 |
+
q=q,
|
| 725 |
+
k=k,
|
| 726 |
+
v=v,
|
| 727 |
+
g=g,
|
| 728 |
+
beta=beta,
|
| 729 |
+
initial_state=recurrent_state[-1],
|
| 730 |
+
output_final_state=use_cache,
|
| 731 |
+
cu_seqlens=cu_seqlens,
|
| 732 |
+
use_qk_l2norm_in_kernel=True
|
| 733 |
+
)
|
| 734 |
+
else:
|
| 735 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 736 |
+
|
| 737 |
+
if attention_mask is not None:
|
| 738 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 739 |
+
return o
|
| 740 |
+
|
| 741 |
+
def cu2pad(self, x, cu_seqlens):
|
| 742 |
+
batch_size = cu_seqlens.shape[0] - 1
|
| 743 |
+
max_len = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
|
| 744 |
+
indices = torch.tensor([], dtype=torch.long, device=x.device)
|
| 745 |
+
attention_mask = torch.ones((batch_size, max_len), dtype=torch.bool, device=x.device)
|
| 746 |
+
for i in range(batch_size):
|
| 747 |
+
seq_len = cu_seqlens[i+1] - cu_seqlens[i]
|
| 748 |
+
pad_len = max_len - seq_len
|
| 749 |
+
batch_indices = torch.arange(pad_len, max_len, device=x.device)
|
| 750 |
+
batch_indices = batch_indices + i * max_len
|
| 751 |
+
indices = torch.cat([indices, batch_indices])
|
| 752 |
+
attention_mask[i, :pad_len] = False
|
| 753 |
+
x = pad_input(x.squeeze(0), indices, batch_size, max_len)
|
| 754 |
+
return x, attention_mask
|
| 755 |
+
|
| 756 |
+
def pad_for_conv(self, cu_seqlens, cu_q, cu_k, cu_v):
|
| 757 |
+
lengths = cu_seqlens[1:] - cu_seqlens[:-1]
|
| 758 |
+
pad_lengths = torch.clamp(self.conv_size - lengths, min=0)
|
| 759 |
+
new_lengths = lengths + pad_lengths
|
| 760 |
+
new_cu_seqlens = torch.cat([
|
| 761 |
+
torch.tensor([0], device=cu_seqlens.device, dtype=cu_seqlens.dtype),
|
| 762 |
+
torch.cumsum(new_lengths, dim=0)
|
| 763 |
+
])
|
| 764 |
+
final_total_len = new_cu_seqlens[-1].item()
|
| 765 |
+
new_q = torch.zeros((1, final_total_len, cu_q.shape[-1]), dtype=cu_q.dtype, device=cu_q.device)
|
| 766 |
+
new_k = torch.zeros((1, final_total_len, cu_k.shape[-1]), dtype=cu_k.dtype, device=cu_k.device)
|
| 767 |
+
new_v = torch.zeros((1, final_total_len, cu_v.shape[-1]), dtype=cu_v.dtype, device=cu_v.device)
|
| 768 |
+
num_sequences = len(lengths)
|
| 769 |
+
for i in range(num_sequences):
|
| 770 |
+
src_start = cu_seqlens[i]
|
| 771 |
+
src_end = cu_seqlens[i+1]
|
| 772 |
+
dest_start = new_cu_seqlens[i] + pad_lengths[i]
|
| 773 |
+
dest_end = new_cu_seqlens[i+1]
|
| 774 |
+
new_q[:, dest_start:dest_end, ...] = cu_q[:, src_start:src_end, ...]
|
| 775 |
+
new_k[:, dest_start:dest_end, ...] = cu_k[:, src_start:src_end, ...]
|
| 776 |
+
new_v[:, dest_start:dest_end, ...] = cu_v[:, src_start:src_end, ...]
|
| 777 |
+
|
| 778 |
+
return new_cu_seqlens, new_q, new_k, new_v, pad_lengths
|
| 779 |
+
|
| 780 |
+
def unpad_after_conv(self, conv_cu_seqlens, cu_seqlens, cu_q, cu_k, cu_v, pad_lengths):
|
| 781 |
+
original_total_len = cu_seqlens[-1].item()
|
| 782 |
+
orig_q = torch.empty((1, original_total_len, cu_q.shape[-1]), dtype=cu_q.dtype, device=cu_q.device)
|
| 783 |
+
orig_k = torch.empty((1, original_total_len, cu_k.shape[-1]), dtype=cu_k.dtype, device=cu_k.device)
|
| 784 |
+
orig_v = torch.empty((1, original_total_len, cu_v.shape[-1]), dtype=cu_v.dtype, device=cu_v.device)
|
| 785 |
+
|
| 786 |
+
num_sequences = len(pad_lengths)
|
| 787 |
+
for i in range(num_sequences):
|
| 788 |
+
dest_start = cu_seqlens[i]
|
| 789 |
+
dest_end = cu_seqlens[i+1]
|
| 790 |
+
src_start = conv_cu_seqlens[i] + pad_lengths[i]
|
| 791 |
+
src_end = conv_cu_seqlens[i+1]
|
| 792 |
+
|
| 793 |
+
orig_q[:, dest_start:dest_end, ...] = cu_q[:, src_start:src_end, ...]
|
| 794 |
+
orig_k[:, dest_start:dest_end, ...] = cu_k[:, src_start:src_end, ...]
|
| 795 |
+
orig_v[:, dest_start:dest_end, ...] = cu_v[:, src_start:src_end, ...]
|
| 796 |
+
return orig_q, orig_k, orig_v
|
| 797 |
+
|
| 798 |
+
def prepare_recurrent_state(self, recurrent_state, cu_seqlens, cu_seqlen_all, reverse_indices, batch_size):
|
| 799 |
+
if recurrent_state is None:
|
| 800 |
+
return None
|
| 801 |
+
|
| 802 |
+
if cu_seqlens is None:
|
| 803 |
+
return recurrent_state
|
| 804 |
+
|
| 805 |
+
total_len = len(cu_seqlen_all)
|
| 806 |
+
if len(cu_seqlens) != total_len:
|
| 807 |
+
# select memories that are activated
|
| 808 |
+
memories = torch.zeros_like(recurrent_state[:self.topk*batch_size])
|
| 809 |
+
mem_id = 0
|
| 810 |
+
for i in range(total_len-1):
|
| 811 |
+
if cu_seqlen_all[i] != cu_seqlen_all[i+1]:
|
| 812 |
+
memories[mem_id] = recurrent_state[i]
|
| 813 |
+
mem_id += 1
|
| 814 |
+
assert mem_id == self.topk * batch_size, f"The number of memories {mem_id} is not correct."
|
| 815 |
+
else:
|
| 816 |
+
memories = recurrent_state
|
| 817 |
+
|
| 818 |
+
return memories
|
| 819 |
+
|
| 820 |
+
def handle_recurrent_state(self, recurrent_state, recurrent_state_new, cu_seqlens, cu_seqlen_all, reverse_indices):
|
| 821 |
+
if recurrent_state_new is None:
|
| 822 |
+
return None
|
| 823 |
+
if cu_seqlens is None:
|
| 824 |
+
return recurrent_state_new
|
| 825 |
+
if recurrent_state is None:
|
| 826 |
+
recurrent_state = torch.zeros_like(recurrent_state_new[reverse_indices[1:]-1])
|
| 827 |
+
total_len = len(cu_seqlen_all)
|
| 828 |
+
if len(cu_seqlens) != total_len:
|
| 829 |
+
for i in range(total_len-1):
|
| 830 |
+
if cu_seqlen_all[i] != cu_seqlen_all[i+1]:
|
| 831 |
+
recurrent_state[i] = recurrent_state_new[reverse_indices[i+1]-1]
|
| 832 |
+
else:
|
| 833 |
+
recurrent_state = recurrent_state_new
|
| 834 |
+
return recurrent_state
|
layers/multiscale_retention.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from einops import rearrange, repeat
|
| 11 |
+
from transformers.activations import ACT2FN
|
| 12 |
+
|
| 13 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 14 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 15 |
+
from fla.modules.rotary import RotaryEmbedding
|
| 16 |
+
from fla.ops.retention import chunk_retention, fused_chunk_retention, fused_recurrent_retention, parallel_retention
|
| 17 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from transformers.processing_utils import Unpack
|
| 21 |
+
|
| 22 |
+
from fla.models.utils import Cache
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MultiScaleRetention(nn.Module):
|
| 26 |
+
r"""
|
| 27 |
+
The layer implementaion for [Retentive Network: A Successor to Transformer for Large Language Models](https://arxiv.org/pdf/2307.08621.pdf). # noqa
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
mode (str, Optional):
|
| 31 |
+
Which Retention kernel to use.
|
| 32 |
+
Currently available: `chunk`, `fused_recurrent`, `parallel`, and `fused_chunk`.
|
| 33 |
+
Default: `chunk`.
|
| 34 |
+
hidden_size (int, Optional):
|
| 35 |
+
The hidden size of the input. Default: 1024.
|
| 36 |
+
expand_k (float, Optional):
|
| 37 |
+
The expansion ratio for the key dim. Default: 1.0.
|
| 38 |
+
expand_v (float, Optional):
|
| 39 |
+
The expansion ratio for the value dim. Default: 2.0.
|
| 40 |
+
num_heads (int, Optional):
|
| 41 |
+
The number of heads. Default: 8.
|
| 42 |
+
num_kv_heads (int, Optional):
|
| 43 |
+
The number of key/value heads, used for MQA. Default: None.
|
| 44 |
+
feature_map (str, Optional):
|
| 45 |
+
Feature map function applied to queries/keys. Default: None.
|
| 46 |
+
use_short_conv (bool, Optional):
|
| 47 |
+
Whether to use short convolutions. Default: `False`.
|
| 48 |
+
conv_size (int, Optional):
|
| 49 |
+
The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
|
| 50 |
+
conv_bias (bool, Optional):
|
| 51 |
+
Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
|
| 52 |
+
use_output_gate (bool, Optional):
|
| 53 |
+
Whether to use output gate. Default: `True`.
|
| 54 |
+
gate_fn (str, Optional):
|
| 55 |
+
The activation function for the output gate. Default: `swish`.
|
| 56 |
+
elementwise_affine (bool, Optional):
|
| 57 |
+
If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`.
|
| 58 |
+
norm_eps (float, Optional):
|
| 59 |
+
The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5.
|
| 60 |
+
fuse_norm (bool, Optional):
|
| 61 |
+
Whether to fuse the norm and the output gate for better memory footprint. Default: `True`.
|
| 62 |
+
layer_idx (int, Optional):
|
| 63 |
+
The index of the layer. Default: None.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
mode: str = 'chunk',
|
| 69 |
+
hidden_size: int = 1024,
|
| 70 |
+
expand_k: float = 1.0,
|
| 71 |
+
expand_v: float = 2.0,
|
| 72 |
+
num_heads: int = 8,
|
| 73 |
+
num_kv_heads: Optional[int] = None,
|
| 74 |
+
feature_map: Optional[str] = None,
|
| 75 |
+
use_short_conv: bool = False,
|
| 76 |
+
conv_size: int = 4,
|
| 77 |
+
conv_bias: bool = False,
|
| 78 |
+
use_output_gate: bool = True,
|
| 79 |
+
gate_fn: str = 'swish',
|
| 80 |
+
elementwise_affine: Optional[bool] = True,
|
| 81 |
+
norm_eps: float = 1e-5,
|
| 82 |
+
fuse_norm: bool = True,
|
| 83 |
+
layer_idx: int = None,
|
| 84 |
+
**kwargs
|
| 85 |
+
) -> MultiScaleRetention:
|
| 86 |
+
super().__init__()
|
| 87 |
+
|
| 88 |
+
self.mode = mode
|
| 89 |
+
self.hidden_size = hidden_size
|
| 90 |
+
self.expand_k = expand_k
|
| 91 |
+
self.expand_v = expand_v
|
| 92 |
+
self.num_heads = num_heads
|
| 93 |
+
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
| 94 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 95 |
+
self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
|
| 96 |
+
|
| 97 |
+
self.use_short_conv = use_short_conv
|
| 98 |
+
self.conv_size = conv_size
|
| 99 |
+
self.conv_bias = conv_bias
|
| 100 |
+
self.use_output_gate = use_output_gate
|
| 101 |
+
|
| 102 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 103 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 104 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 105 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 106 |
+
self.layer_idx = layer_idx
|
| 107 |
+
|
| 108 |
+
assert mode in ['chunk', 'fused_chunk', 'parallel', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 109 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 110 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 111 |
+
|
| 112 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 113 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 114 |
+
|
| 115 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 116 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
|
| 117 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
|
| 118 |
+
if self.use_output_gate:
|
| 119 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 120 |
+
|
| 121 |
+
if use_short_conv:
|
| 122 |
+
self.conv_size = conv_size
|
| 123 |
+
self.q_conv1d = ShortConvolution(
|
| 124 |
+
hidden_size=self.key_dim,
|
| 125 |
+
kernel_size=conv_size,
|
| 126 |
+
bias=conv_bias,
|
| 127 |
+
activation='silu'
|
| 128 |
+
)
|
| 129 |
+
self.k_conv1d = ShortConvolution(
|
| 130 |
+
hidden_size=self.key_dim_per_group,
|
| 131 |
+
kernel_size=conv_size,
|
| 132 |
+
bias=conv_bias,
|
| 133 |
+
activation='silu'
|
| 134 |
+
)
|
| 135 |
+
self.v_conv1d = ShortConvolution(
|
| 136 |
+
hidden_size=self.value_dim_per_group,
|
| 137 |
+
kernel_size=conv_size,
|
| 138 |
+
bias=conv_bias,
|
| 139 |
+
activation='silu'
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 143 |
+
|
| 144 |
+
if gate_fn == 'swish' and fuse_norm and use_output_gate:
|
| 145 |
+
self.g_norm_swish_gate = FusedRMSNormGated(
|
| 146 |
+
hidden_size=self.head_v_dim,
|
| 147 |
+
elementwise_affine=elementwise_affine,
|
| 148 |
+
eps=norm_eps
|
| 149 |
+
)
|
| 150 |
+
self.fuse_norm_and_gate = True
|
| 151 |
+
else:
|
| 152 |
+
self.fuse_norm_and_gate = False
|
| 153 |
+
self.g_norm = RMSNorm(
|
| 154 |
+
hidden_size=self.head_v_dim,
|
| 155 |
+
elementwise_affine=elementwise_affine,
|
| 156 |
+
eps=norm_eps
|
| 157 |
+
)
|
| 158 |
+
self.gate_fn = ACT2FN[gate_fn]
|
| 159 |
+
|
| 160 |
+
# TODO: fix this issue
|
| 161 |
+
# https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/ops/triton/rotary.py#L180
|
| 162 |
+
# Ideally, we would want to support arbitrary d_head_qk
|
| 163 |
+
assert self.head_k_dim <= 256, "head_k_dim must be less than or equal to 256"
|
| 164 |
+
self.rotary = RotaryEmbedding(dim=self.head_k_dim)
|
| 165 |
+
|
| 166 |
+
def forward(
|
| 167 |
+
self,
|
| 168 |
+
hidden_states: torch.Tensor,
|
| 169 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 170 |
+
past_key_values: Optional[Cache] = None,
|
| 171 |
+
use_cache: Optional[bool] = False,
|
| 172 |
+
output_attentions: Optional[bool] = False,
|
| 173 |
+
**kwargs: Unpack[Dict]
|
| 174 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 175 |
+
if attention_mask is not None:
|
| 176 |
+
assert len(attention_mask.shape) == 2, (
|
| 177 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 178 |
+
"for padding purposes (0 indicating padding). "
|
| 179 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 183 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 184 |
+
|
| 185 |
+
last_state = None
|
| 186 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 187 |
+
last_state = past_key_values[self.layer_idx]
|
| 188 |
+
|
| 189 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 190 |
+
if attention_mask is not None:
|
| 191 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 192 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 193 |
+
|
| 194 |
+
if self.use_short_conv:
|
| 195 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 196 |
+
if last_state is not None:
|
| 197 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 198 |
+
q, conv_state_q = self.q_conv1d(
|
| 199 |
+
x=self.q_proj(hidden_states),
|
| 200 |
+
cache=conv_state_q,
|
| 201 |
+
output_final_state=use_cache,
|
| 202 |
+
cu_seqlens=cu_seqlens
|
| 203 |
+
)
|
| 204 |
+
k, conv_state_k = self.k_conv1d(
|
| 205 |
+
x=self.k_proj(hidden_states),
|
| 206 |
+
cache=conv_state_k,
|
| 207 |
+
output_final_state=use_cache,
|
| 208 |
+
cu_seqlens=cu_seqlens
|
| 209 |
+
)
|
| 210 |
+
v, conv_state_v = self.v_conv1d(
|
| 211 |
+
x=self.v_proj(hidden_states),
|
| 212 |
+
cache=conv_state_v,
|
| 213 |
+
output_final_state=use_cache,
|
| 214 |
+
cu_seqlens=cu_seqlens
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
q = self.q_proj(hidden_states)
|
| 218 |
+
k = self.k_proj(hidden_states)
|
| 219 |
+
v = self.v_proj(hidden_states)
|
| 220 |
+
|
| 221 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 222 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 223 |
+
if self.feature_map_fn is not None:
|
| 224 |
+
q, k = map(self.feature_map_fn, (q, k))
|
| 225 |
+
|
| 226 |
+
seqlen_offset, max_seqlen = 0, q.shape[1]
|
| 227 |
+
if past_key_values is not None:
|
| 228 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 229 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 230 |
+
|
| 231 |
+
if attention_mask is not None and seqlen_offset > 0:
|
| 232 |
+
# to deliminate the offsets of padding tokens
|
| 233 |
+
seqlen_offset = prepare_lens_from_mask(attention_mask) - q_len
|
| 234 |
+
max_seqlen = q.shape[1] + seqlen_offset.max().item()
|
| 235 |
+
|
| 236 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 237 |
+
|
| 238 |
+
if self.num_kv_groups > 1:
|
| 239 |
+
k = repeat(k, '... h d -> ... (h g) d', g=self.num_kv_groups)
|
| 240 |
+
v = repeat(v, '... (h d) -> ... (h g) d', d=self.head_v_dim, g=self.num_kv_groups)
|
| 241 |
+
else:
|
| 242 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 243 |
+
|
| 244 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 245 |
+
if mode == 'chunk':
|
| 246 |
+
o, recurrent_state = chunk_retention(
|
| 247 |
+
q=q,
|
| 248 |
+
k=k,
|
| 249 |
+
v=v,
|
| 250 |
+
initial_state=recurrent_state,
|
| 251 |
+
output_final_state=use_cache,
|
| 252 |
+
cu_seqlens=cu_seqlens,
|
| 253 |
+
)
|
| 254 |
+
elif mode == 'fused_chunk':
|
| 255 |
+
o, recurrent_state = fused_chunk_retention(
|
| 256 |
+
q=q,
|
| 257 |
+
k=k,
|
| 258 |
+
v=v,
|
| 259 |
+
initial_state=recurrent_state,
|
| 260 |
+
output_final_state=use_cache,
|
| 261 |
+
cu_seqlens=cu_seqlens,
|
| 262 |
+
)
|
| 263 |
+
elif mode == 'parallel':
|
| 264 |
+
o, recurrent_state = parallel_retention(
|
| 265 |
+
q=q,
|
| 266 |
+
k=k,
|
| 267 |
+
v=v,
|
| 268 |
+
cu_seqlens=cu_seqlens,
|
| 269 |
+
)
|
| 270 |
+
elif mode == 'fused_recurrent':
|
| 271 |
+
o, recurrent_state = fused_recurrent_retention(
|
| 272 |
+
q=q,
|
| 273 |
+
k=k,
|
| 274 |
+
v=v,
|
| 275 |
+
initial_state=recurrent_state,
|
| 276 |
+
output_final_state=use_cache,
|
| 277 |
+
cu_seqlens=cu_seqlens,
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 281 |
+
|
| 282 |
+
if past_key_values is not None:
|
| 283 |
+
past_key_values.update(
|
| 284 |
+
recurrent_state=recurrent_state,
|
| 285 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 286 |
+
layer_idx=self.layer_idx,
|
| 287 |
+
offset=q_len
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
if self.use_output_gate:
|
| 291 |
+
g = self.g_proj(hidden_states)
|
| 292 |
+
if self.fuse_norm_and_gate:
|
| 293 |
+
g = rearrange(g, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 294 |
+
o = self.g_norm_swish_gate(o, g)
|
| 295 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 296 |
+
else:
|
| 297 |
+
o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
|
| 298 |
+
o = o * self.gate_fn(g)
|
| 299 |
+
else:
|
| 300 |
+
o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
|
| 301 |
+
o = self.o_proj(o)
|
| 302 |
+
if attention_mask is not None:
|
| 303 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 304 |
+
|
| 305 |
+
return o, None, past_key_values
|
layers/nsa.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Optional, Tuple, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
from transformers.utils import logging
|
| 12 |
+
|
| 13 |
+
from fla.modules import RotaryEmbedding
|
| 14 |
+
from fla.ops.nsa.parallel import parallel_nsa
|
| 15 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from fla.models.utils import Cache
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class NativeSparseAttention(nn.Module):
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
hidden_size: int = 2048,
|
| 28 |
+
num_heads: int = 64,
|
| 29 |
+
num_kv_heads: Optional[int] = 4,
|
| 30 |
+
head_dim: int = 64,
|
| 31 |
+
qkv_bias: bool = False,
|
| 32 |
+
block_size: Optional[int] = 64,
|
| 33 |
+
block_counts: Optional[Union[torch.LongTensor, int]] = 16,
|
| 34 |
+
window_size: Optional[int] = 512,
|
| 35 |
+
rope_theta: Optional[float] = 10000.,
|
| 36 |
+
max_position_embeddings: Optional[int] = None,
|
| 37 |
+
layer_idx: int = None
|
| 38 |
+
):
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
self.hidden_size = hidden_size
|
| 42 |
+
self.num_heads = num_heads
|
| 43 |
+
if num_kv_heads is None:
|
| 44 |
+
self.num_kv_heads = self.num_heads
|
| 45 |
+
else:
|
| 46 |
+
self.num_kv_heads = num_kv_heads
|
| 47 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 48 |
+
self.head_dim = head_dim
|
| 49 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 50 |
+
self.qkv_bias = qkv_bias
|
| 51 |
+
|
| 52 |
+
self.block_size = block_size
|
| 53 |
+
self.block_counts = block_counts
|
| 54 |
+
self.window_size = window_size
|
| 55 |
+
self.rope_theta = rope_theta
|
| 56 |
+
self.max_position_embeddings = max_position_embeddings
|
| 57 |
+
self.layer_idx = layer_idx
|
| 58 |
+
|
| 59 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.qkv_bias)
|
| 60 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 61 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 62 |
+
self.g_proj = nn.Linear(self.hidden_size, self.num_heads * 3, bias=False)
|
| 63 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 64 |
+
|
| 65 |
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
| 66 |
+
|
| 67 |
+
def forward(
|
| 68 |
+
self,
|
| 69 |
+
hidden_states: torch.Tensor,
|
| 70 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 71 |
+
past_key_values: Optional[Cache] = None,
|
| 72 |
+
output_attentions: bool = False,
|
| 73 |
+
use_cache: bool = False,
|
| 74 |
+
**kwargs,
|
| 75 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 76 |
+
if attention_mask is not None:
|
| 77 |
+
assert len(attention_mask.shape) == 2, (
|
| 78 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 79 |
+
"for padding purposes (0 indicating padding). "
|
| 80 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
batch_size, seq_len, _ = hidden_states.size()
|
| 84 |
+
|
| 85 |
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 86 |
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 87 |
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 88 |
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=3)
|
| 89 |
+
g_cmp, g_slc, g_swa = g.sigmoid().unbind(-1)
|
| 90 |
+
|
| 91 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 92 |
+
|
| 93 |
+
seqlen_offset, max_seqlen = 0, seq_len
|
| 94 |
+
if past_key_values is not None:
|
| 95 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 96 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 97 |
+
|
| 98 |
+
if attention_mask is not None:
|
| 99 |
+
# to deliminate the offsets of padding tokens
|
| 100 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 101 |
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
| 102 |
+
|
| 103 |
+
if self.max_position_embeddings is not None:
|
| 104 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 105 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 106 |
+
|
| 107 |
+
if past_key_values is not None:
|
| 108 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 109 |
+
k_cached, v_cached = past_key_values.update(
|
| 110 |
+
attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)),
|
| 111 |
+
layer_idx=self.layer_idx,
|
| 112 |
+
offset=seq_len,
|
| 113 |
+
cache_kwargs=dict(window_size=self.window_size)
|
| 114 |
+
)['attn_state']
|
| 115 |
+
if cache_has_content:
|
| 116 |
+
k, v = k_cached, v_cached
|
| 117 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 118 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 119 |
+
|
| 120 |
+
o = parallel_nsa(
|
| 121 |
+
q=q,
|
| 122 |
+
k=k,
|
| 123 |
+
v=v,
|
| 124 |
+
g_cmp=g_cmp,
|
| 125 |
+
g_slc=g_slc,
|
| 126 |
+
g_swa=g_swa,
|
| 127 |
+
block_size=self.block_size,
|
| 128 |
+
block_counts=self.block_counts,
|
| 129 |
+
window_size=self.window_size,
|
| 130 |
+
cu_seqlens=cu_seqlens,
|
| 131 |
+
)
|
| 132 |
+
o = o.reshape(batch_size, seq_len, -1)
|
| 133 |
+
o = self.o_proj(o)
|
| 134 |
+
|
| 135 |
+
if not output_attentions:
|
| 136 |
+
attentions = None
|
| 137 |
+
|
| 138 |
+
return o, attentions, past_key_values
|
layers/path_attn.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 15 |
+
from fla.modules import RMSNorm, ShortConvolution
|
| 16 |
+
from fla.modules.l2norm import l2_norm
|
| 17 |
+
from fla.ops.attn.decoding import attn_decoding_one_step
|
| 18 |
+
from fla.ops.path_attn.parallel import parallel_path_attn
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PaTHAttention(nn.Module):
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
hidden_size: int = 2048,
|
| 30 |
+
num_heads: int = 32,
|
| 31 |
+
num_kv_heads: Optional[int] = None,
|
| 32 |
+
use_forget_gate: bool = False,
|
| 33 |
+
use_qk_norm: bool = False,
|
| 34 |
+
layer_idx: int = None,
|
| 35 |
+
use_low_rank_w: bool = True,
|
| 36 |
+
use_w_shortconv: bool = True,
|
| 37 |
+
conv_size: int = 3,
|
| 38 |
+
conv_bias: bool = False,
|
| 39 |
+
):
|
| 40 |
+
super().__init__()
|
| 41 |
+
|
| 42 |
+
self.hidden_size = hidden_size
|
| 43 |
+
self.num_heads = num_heads
|
| 44 |
+
if num_kv_heads is None:
|
| 45 |
+
self.num_kv_heads = self.num_heads
|
| 46 |
+
else:
|
| 47 |
+
self.num_kv_heads = num_kv_heads
|
| 48 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 49 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 50 |
+
|
| 51 |
+
self.layer_idx = layer_idx
|
| 52 |
+
|
| 53 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 54 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 55 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 56 |
+
|
| 57 |
+
# We use low-rank parameterization for the w_proj to reduce parameters in MHA settings.
|
| 58 |
+
if use_low_rank_w:
|
| 59 |
+
self.w_proj = nn.Sequential(
|
| 60 |
+
nn.Linear(self.hidden_size, 32, bias=False),
|
| 61 |
+
nn.Linear(32, self.kv_dim, bias=False)
|
| 62 |
+
)
|
| 63 |
+
# In MQA/GQA settings, key/value heads are shared, so we use a standard linear projection
|
| 64 |
+
# which doesn't introduce too many parameters
|
| 65 |
+
else:
|
| 66 |
+
self.w_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 67 |
+
|
| 68 |
+
# TODO: per head norm?
|
| 69 |
+
if use_qk_norm:
|
| 70 |
+
self.maybe_q_norm = RMSNorm(self.hidden_size)
|
| 71 |
+
self.maybe_k_norm = RMSNorm(self.kv_dim)
|
| 72 |
+
else:
|
| 73 |
+
self.maybe_q_norm = nn.Identity()
|
| 74 |
+
self.maybe_k_norm = nn.Identity()
|
| 75 |
+
|
| 76 |
+
if use_w_shortconv:
|
| 77 |
+
self.w_conv1d = ShortConvolution(hidden_size=self.kv_dim, kernel_size=conv_size, bias=conv_bias, activation='silu')
|
| 78 |
+
self.use_w_shortconv = use_w_shortconv
|
| 79 |
+
self.bt_proj = nn.Linear(self.hidden_size, self.num_kv_heads, bias=True)
|
| 80 |
+
self.use_forget_gate = use_forget_gate
|
| 81 |
+
if use_forget_gate:
|
| 82 |
+
self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True)
|
| 83 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 84 |
+
|
| 85 |
+
def forward(
|
| 86 |
+
self,
|
| 87 |
+
hidden_states: torch.Tensor,
|
| 88 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 89 |
+
past_key_values: Optional[Cache] = None,
|
| 90 |
+
output_attentions: bool = False,
|
| 91 |
+
use_cache: bool = False,
|
| 92 |
+
**kwargs,
|
| 93 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 94 |
+
if use_cache:
|
| 95 |
+
assert past_key_values is not None, "past_key_values must be provided when use_cache is True"
|
| 96 |
+
if attention_mask is not None:
|
| 97 |
+
assert len(attention_mask.shape) == 2, (
|
| 98 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 99 |
+
"for padding purposes (0 indicating padding). "
|
| 100 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 101 |
+
)
|
| 102 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 103 |
+
q = self.q_proj(hidden_states)
|
| 104 |
+
k = self.k_proj(hidden_states)
|
| 105 |
+
v = self.v_proj(hidden_states)
|
| 106 |
+
w = self.w_proj(hidden_states)
|
| 107 |
+
beta = self.bt_proj(hidden_states).sigmoid() * 2 # allowing negative eigenvalues
|
| 108 |
+
g = F.logsigmoid(self.g_proj(hidden_states).float()) if self.use_forget_gate else None
|
| 109 |
+
q, k = self.maybe_q_norm(q), self.maybe_k_norm(k)
|
| 110 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 111 |
+
assert not (cu_seqlens is not None and attention_mask is not None), (
|
| 112 |
+
"cu_seqlens should not be provided when attention_mask is not None"
|
| 113 |
+
)
|
| 114 |
+
# Training
|
| 115 |
+
if attention_mask is None:
|
| 116 |
+
assert use_cache is False, "use_cache should be False in training"
|
| 117 |
+
if self.use_w_shortconv:
|
| 118 |
+
w, _ = self.w_conv1d(w, cache=None, output_final_state=False, cu_seqlens=cu_seqlens)
|
| 119 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 120 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 121 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 122 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)####this 需要额外的分头,设定一个r的分块,d-》r*d//r
|
| 123 |
+
w = l2_norm(w)
|
| 124 |
+
o, _ = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g, cu_seqlens=cu_seqlens)####here
|
| 125 |
+
|
| 126 |
+
# Prefilling or decoding
|
| 127 |
+
else:
|
| 128 |
+
assert self.training is False, "attention mask is not supported in training. Please use variable length input."
|
| 129 |
+
try:
|
| 130 |
+
last_state = past_key_values[self.layer_idx]
|
| 131 |
+
except KeyError:
|
| 132 |
+
last_state = None
|
| 133 |
+
# Decoding
|
| 134 |
+
if last_state is not None:
|
| 135 |
+
if g is not None:
|
| 136 |
+
past_k, past_v, past_g = last_state['attn_state']
|
| 137 |
+
else:
|
| 138 |
+
past_k, past_v = last_state['attn_state']
|
| 139 |
+
w_conv_state = last_state['conv_state']
|
| 140 |
+
past_k = rearrange(past_k, '... (h d) -> ... h d', d=self.head_dim)
|
| 141 |
+
if self.use_w_shortconv:
|
| 142 |
+
w, w_conv_state = self.w_conv1d(w, cache=w_conv_state, output_final_state=use_cache, cu_seqlens=cu_seqlens)
|
| 143 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)
|
| 144 |
+
w = l2_norm(w)
|
| 145 |
+
|
| 146 |
+
@torch.compile
|
| 147 |
+
def rank_one_update(k, w, beta):
|
| 148 |
+
original_dtype = k.dtype
|
| 149 |
+
k = k.float()
|
| 150 |
+
w = w.float()
|
| 151 |
+
beta = beta.float()
|
| 152 |
+
k = k - beta[..., None].float() * (k * w).sum(-1, keepdim=True) * w
|
| 153 |
+
return k.to(original_dtype)
|
| 154 |
+
|
| 155 |
+
past_k = rank_one_update(past_k, w, beta)
|
| 156 |
+
past_k = rearrange(past_k, '... h d -> ... (h d)')
|
| 157 |
+
k = torch.cat([past_k, k], dim=1)
|
| 158 |
+
v = torch.cat([past_v, v], dim=1)
|
| 159 |
+
g = torch.cat([past_g, g], dim=1) if g is not None else None
|
| 160 |
+
past_key_values[self.layer_idx]['attn_state'] = (k, v, g) if g is not None else (k, v)
|
| 161 |
+
past_key_values.update(
|
| 162 |
+
conv_state=w_conv_state,
|
| 163 |
+
layer_idx=self.layer_idx,
|
| 164 |
+
offset=q_len
|
| 165 |
+
)
|
| 166 |
+
if g is not None:
|
| 167 |
+
q, (k, v, g), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 168 |
+
q, (k, v, g), attention_mask, q_len, keepdim=True)
|
| 169 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 170 |
+
else:
|
| 171 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 172 |
+
q, (k, v), attention_mask, q_len, keepdim=True)
|
| 173 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 174 |
+
_, cu_seqlens = cu_seqlens
|
| 175 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 176 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 177 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 178 |
+
assert max_seqlen_q == 1, "only support q_len == 1 for decoding"
|
| 179 |
+
o = attn_decoding_one_step(q, k, v, g, cu_seqlens=cu_seqlens, do_gate_scale=True) # reduced to fox's decoding
|
| 180 |
+
# Prefilling
|
| 181 |
+
else:
|
| 182 |
+
v_cache = v.clone()
|
| 183 |
+
g_cache = g.clone() if g is not None else None
|
| 184 |
+
if g is None:
|
| 185 |
+
q, (k, v, w, beta), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 186 |
+
q, (k, v, w, beta), attention_mask, q_len, keepdim=True)
|
| 187 |
+
else:
|
| 188 |
+
q, (k, v, w, beta, g), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 189 |
+
q, (k, v, w, beta, g), attention_mask, q_len, keepdim=True)
|
| 190 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 191 |
+
assert max_seqlen_q == max_seqlen_k, "max_seqlen_q should be equal to max_seqlen_k in prefilling"
|
| 192 |
+
_, cu_seqlens = cu_seqlens
|
| 193 |
+
if self.use_w_shortconv:
|
| 194 |
+
w, w_conv_state = self.w_conv1d(w, cache=None, output_final_state=use_cache, cu_seqlens=cu_seqlens)
|
| 195 |
+
else:
|
| 196 |
+
w_conv_state = None
|
| 197 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 198 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 199 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 200 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)
|
| 201 |
+
w = l2_norm(w)
|
| 202 |
+
o, k_cache = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g,
|
| 203 |
+
cu_seqlens=cu_seqlens, use_cache=use_cache)
|
| 204 |
+
if use_cache:
|
| 205 |
+
k_cache = pad_input(k_cache.squeeze(0), indices_q, batch_size, q_len)
|
| 206 |
+
k_cache = rearrange(k_cache, '... h d -> ... (h d)')
|
| 207 |
+
past_key_values.update(
|
| 208 |
+
attn_state=(k_cache, v_cache, g_cache) if g_cache is not None else (k_cache, v_cache),
|
| 209 |
+
conv_state=w_conv_state,
|
| 210 |
+
layer_idx=self.layer_idx,
|
| 211 |
+
offset=q_len
|
| 212 |
+
)
|
| 213 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 15 |
+
from fla.modules import RMSNorm, ShortConvolution
|
| 16 |
+
from fla.modules.l2norm import l2_norm
|
| 17 |
+
from fla.ops.attn.decoding import attn_decoding_one_step
|
| 18 |
+
from fla.ops.path_attn.parallel import parallel_path_attn
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PaTHAttention(nn.Module):
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
hidden_size: int = 2048,
|
| 30 |
+
num_heads: int = 32,
|
| 31 |
+
num_w_heads: Optional[int] = None , ###额外的分头操作
|
| 32 |
+
num_kv_heads: Optional[int] = None,
|
| 33 |
+
use_forget_gate: bool = False,
|
| 34 |
+
use_qk_norm: bool = False,
|
| 35 |
+
layer_idx: int = None,
|
| 36 |
+
use_low_rank_w: bool = True,
|
| 37 |
+
use_w_shortconv: bool = True,
|
| 38 |
+
conv_size: int = 3,
|
| 39 |
+
conv_bias: bool = False,
|
| 40 |
+
):
|
| 41 |
+
super().__init__()
|
| 42 |
+
|
| 43 |
+
self.hidden_size = hidden_size
|
| 44 |
+
self.num_heads = num_heads
|
| 45 |
+
if num_kv_heads is None:
|
| 46 |
+
self.num_kv_heads = self.num_heads
|
| 47 |
+
else:
|
| 48 |
+
self.num_kv_heads = num_kv_heads
|
| 49 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 50 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 51 |
+
|
| 52 |
+
self.layer_idx = layer_idx
|
| 53 |
+
|
| 54 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 55 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 56 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 57 |
+
|
| 58 |
+
# We use low-rank parameterization for the w_proj to reduce parameters in MHA settings.
|
| 59 |
+
if use_low_rank_w:
|
| 60 |
+
self.w_proj = nn.Sequential(
|
| 61 |
+
nn.Linear(self.hidden_size, 32, bias=False),
|
| 62 |
+
nn.Linear(32, self.kv_dim, bias=False)
|
| 63 |
+
)
|
| 64 |
+
# In MQA/GQA settings, key/value heads are shared, so we use a standard linear projection
|
| 65 |
+
# which doesn't introduce too many parameters
|
| 66 |
+
else:
|
| 67 |
+
self.w_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 68 |
+
|
| 69 |
+
# TODO: per head norm?
|
| 70 |
+
if use_qk_norm:
|
| 71 |
+
self.maybe_q_norm = RMSNorm(self.hidden_size)
|
| 72 |
+
self.maybe_k_norm = RMSNorm(self.kv_dim)
|
| 73 |
+
else:
|
| 74 |
+
self.maybe_q_norm = nn.Identity()
|
| 75 |
+
self.maybe_k_norm = nn.Identity()
|
| 76 |
+
|
| 77 |
+
if use_w_shortconv:
|
| 78 |
+
self.w_conv1d = ShortConvolution(hidden_size=self.kv_dim, kernel_size=conv_size, bias=conv_bias, activation='silu')
|
| 79 |
+
self.use_w_shortconv = use_w_shortconv
|
| 80 |
+
self.bt_proj = nn.Linear(self.hidden_size, self.num_kv_heads, bias=True)
|
| 81 |
+
self.use_forget_gate = use_forget_gate
|
| 82 |
+
if use_forget_gate:
|
| 83 |
+
self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True)
|
| 84 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 85 |
+
|
| 86 |
+
def forward(
|
| 87 |
+
self,
|
| 88 |
+
hidden_states: torch.Tensor,
|
| 89 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 90 |
+
past_key_values: Optional[Cache] = None,
|
| 91 |
+
output_attentions: bool = False,
|
| 92 |
+
use_cache: bool = False,
|
| 93 |
+
**kwargs,
|
| 94 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 95 |
+
if use_cache:
|
| 96 |
+
assert past_key_values is not None, "past_key_values must be provided when use_cache is True"
|
| 97 |
+
if attention_mask is not None:
|
| 98 |
+
assert len(attention_mask.shape) == 2, (
|
| 99 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 100 |
+
"for padding purposes (0 indicating padding). "
|
| 101 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 102 |
+
)
|
| 103 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 104 |
+
q = self.q_proj(hidden_states)
|
| 105 |
+
k = self.k_proj(hidden_states)
|
| 106 |
+
v = self.v_proj(hidden_states)
|
| 107 |
+
w = self.w_proj(hidden_states)
|
| 108 |
+
beta = self.bt_proj(hidden_states).sigmoid() * 2 # allowing negative eigenvalues
|
| 109 |
+
g = F.logsigmoid(self.g_proj(hidden_states).float()) if self.use_forget_gate else None
|
| 110 |
+
q, k = self.maybe_q_norm(q), self.maybe_k_norm(k)
|
| 111 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 112 |
+
assert not (cu_seqlens is not None and attention_mask is not None), (
|
| 113 |
+
"cu_seqlens should not be provided when attention_mask is not None"
|
| 114 |
+
)
|
| 115 |
+
# Training
|
| 116 |
+
if attention_mask is None:
|
| 117 |
+
assert use_cache is False, "use_cache should be False in training"
|
| 118 |
+
if self.use_w_shortconv:
|
| 119 |
+
w, _ = self.w_conv1d(w, cache=None, output_final_state=False, cu_seqlens=cu_seqlens)
|
| 120 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 121 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 122 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 123 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)
|
| 124 |
+
w = l2_norm(w)
|
| 125 |
+
o, _ = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g, cu_seqlens=cu_seqlens)####here
|
| 126 |
+
|
| 127 |
+
# Prefilling or decoding
|
| 128 |
+
else:
|
| 129 |
+
assert self.training is False, "attention mask is not supported in training. Please use variable length input."
|
| 130 |
+
try:
|
| 131 |
+
last_state = past_key_values[self.layer_idx]
|
| 132 |
+
except KeyError:
|
| 133 |
+
last_state = None
|
| 134 |
+
# Decoding
|
| 135 |
+
if last_state is not None:
|
| 136 |
+
if g is not None:
|
| 137 |
+
past_k, past_v, past_g = last_state['attn_state']
|
| 138 |
+
else:
|
| 139 |
+
past_k, past_v = last_state['attn_state']
|
| 140 |
+
w_conv_state = last_state['conv_state']
|
| 141 |
+
past_k = rearrange(past_k, '... (h d) -> ... h d', d=self.head_dim)
|
| 142 |
+
if self.use_w_shortconv:
|
| 143 |
+
w, w_conv_state = self.w_conv1d(w, cache=w_conv_state, output_final_state=use_cache, cu_seqlens=cu_seqlens)
|
| 144 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)
|
| 145 |
+
w = l2_norm(w)
|
| 146 |
+
|
| 147 |
+
@torch.compile
|
| 148 |
+
def rank_one_update(k, w, beta):
|
| 149 |
+
original_dtype = k.dtype
|
| 150 |
+
k = k.float()
|
| 151 |
+
w = w.float()
|
| 152 |
+
beta = beta.float()
|
| 153 |
+
k = k - beta[..., None].float() * (k * w).sum(-1, keepdim=True) * w
|
| 154 |
+
return k.to(original_dtype)
|
| 155 |
+
|
| 156 |
+
past_k = rank_one_update(past_k, w, beta)
|
| 157 |
+
past_k = rearrange(past_k, '... h d -> ... (h d)')
|
| 158 |
+
k = torch.cat([past_k, k], dim=1)
|
| 159 |
+
v = torch.cat([past_v, v], dim=1)
|
| 160 |
+
g = torch.cat([past_g, g], dim=1) if g is not None else None
|
| 161 |
+
past_key_values[self.layer_idx]['attn_state'] = (k, v, g) if g is not None else (k, v)
|
| 162 |
+
past_key_values.update(
|
| 163 |
+
conv_state=w_conv_state,
|
| 164 |
+
layer_idx=self.layer_idx,
|
| 165 |
+
offset=q_len
|
| 166 |
+
)
|
| 167 |
+
if g is not None:
|
| 168 |
+
q, (k, v, g), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 169 |
+
q, (k, v, g), attention_mask, q_len, keepdim=True)
|
| 170 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 171 |
+
else:
|
| 172 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 173 |
+
q, (k, v), attention_mask, q_len, keepdim=True)
|
| 174 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 175 |
+
_, cu_seqlens = cu_seqlens
|
| 176 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 177 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 178 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 179 |
+
assert max_seqlen_q == 1, "only support q_len == 1 for decoding"
|
| 180 |
+
o = attn_decoding_one_step(q, k, v, g, cu_seqlens=cu_seqlens, do_gate_scale=True) # reduced to fox's decoding
|
| 181 |
+
# Prefilling
|
| 182 |
+
else:
|
| 183 |
+
v_cache = v.clone()
|
| 184 |
+
g_cache = g.clone() if g is not None else None
|
| 185 |
+
if g is None:
|
| 186 |
+
q, (k, v, w, beta), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 187 |
+
q, (k, v, w, beta), attention_mask, q_len, keepdim=True)
|
| 188 |
+
else:
|
| 189 |
+
q, (k, v, w, beta, g), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 190 |
+
q, (k, v, w, beta, g), attention_mask, q_len, keepdim=True)
|
| 191 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 192 |
+
assert max_seqlen_q == max_seqlen_k, "max_seqlen_q should be equal to max_seqlen_k in prefilling"
|
| 193 |
+
_, cu_seqlens = cu_seqlens
|
| 194 |
+
if self.use_w_shortconv:
|
| 195 |
+
w, w_conv_state = self.w_conv1d(w, cache=None, output_final_state=use_cache, cu_seqlens=cu_seqlens)
|
| 196 |
+
else:
|
| 197 |
+
w_conv_state = None
|
| 198 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 199 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 200 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 201 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)
|
| 202 |
+
w = l2_norm(w)
|
| 203 |
+
o, k_cache = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g,
|
| 204 |
+
cu_seqlens=cu_seqlens, use_cache=use_cache)
|
| 205 |
+
if use_cache:
|
| 206 |
+
k_cache = pad_input(k_cache.squeeze(0), indices_q, batch_size, q_len)
|
| 207 |
+
k_cache = rearrange(k_cache, '... h d -> ... (h d)')
|
| 208 |
+
past_key_values.update(
|
| 209 |
+
attn_state=(k_cache, v_cache, g_cache) if g_cache is not None else (k_cache, v_cache),
|
| 210 |
+
conv_state=w_conv_state,
|
| 211 |
+
layer_idx=self.layer_idx,
|
| 212 |
+
offset=q_len
|
| 213 |
+
)
|
| 214 |
+
o = pad_input(o.squeeze(0), indices_q, batch_size, q_len)
|
| 215 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 216 |
+
o = self.o_proj(o)
|
| 217 |
+
return o, None, past_key_values
|
log.md
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
记录当前task
|
| 2 |
+
1. 对于需要额外分头的操作,line122 修改head
|
models/abc/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
|
| 4 |
+
|
| 5 |
+
from fla.models.abc.configuration_abc import ABCConfig
|
| 6 |
+
from fla.models.abc.modeling_abc import ABCForCausalLM, ABCModel
|
| 7 |
+
|
| 8 |
+
AutoConfig.register(ABCConfig.model_type, ABCConfig, exist_ok=True)
|
| 9 |
+
AutoModel.register(ABCConfig, ABCModel, exist_ok=True)
|
| 10 |
+
AutoModelForCausalLM.register(ABCConfig, ABCForCausalLM, exist_ok=True)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = ['ABCConfig', 'ABCForCausalLM', 'ABCModel']
|
models/abc/configuration_abc.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Dict, Optional
|
| 5 |
+
|
| 6 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ABCConfig(PretrainedConfig):
|
| 10 |
+
|
| 11 |
+
model_type = 'abc'
|
| 12 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
hidden_size: int = 2048,
|
| 17 |
+
gate_low_rank_dim: int = 16,
|
| 18 |
+
clamp_min: float = -32,
|
| 19 |
+
clamp_max: float = 32,
|
| 20 |
+
hidden_ratio: Optional[int] = 4,
|
| 21 |
+
intermediate_size: Optional[int] = None,
|
| 22 |
+
num_hidden_layers: int = 24,
|
| 23 |
+
num_heads: int = 4,
|
| 24 |
+
num_slots: Optional[int] = 64,
|
| 25 |
+
use_short_conv: bool = False,
|
| 26 |
+
conv_size: int = 4,
|
| 27 |
+
exapnd_k: float = 0.5,
|
| 28 |
+
exapnd_v: float = 1,
|
| 29 |
+
hidden_act: str = "swish",
|
| 30 |
+
max_position_embeddings: int = 2048,
|
| 31 |
+
elementwise_affine: Optional[bool] = True,
|
| 32 |
+
norm_eps: float = 1e-6,
|
| 33 |
+
use_rope: bool = True,
|
| 34 |
+
attn: Optional[Dict] = None,
|
| 35 |
+
use_cache: bool = True,
|
| 36 |
+
pad_token_id: Optional[int] = None,
|
| 37 |
+
bos_token_id: int = 1,
|
| 38 |
+
eos_token_id: int = 2,
|
| 39 |
+
tie_word_embeddings: bool = False,
|
| 40 |
+
initializer_range: float = 0.02,
|
| 41 |
+
fuse_norm: bool = True,
|
| 42 |
+
fuse_swiglu: bool = True,
|
| 43 |
+
fuse_cross_entropy: bool = True,
|
| 44 |
+
fuse_linear_cross_entropy: bool = False,
|
| 45 |
+
use_l2warp: bool = False,
|
| 46 |
+
vocab_size: int = 32000,
|
| 47 |
+
**kwargs
|
| 48 |
+
):
|
| 49 |
+
self.hidden_size = hidden_size
|
| 50 |
+
self.gate_low_rank_dim = gate_low_rank_dim
|
| 51 |
+
self.clamp_min = clamp_min
|
| 52 |
+
self.clamp_max = clamp_max
|
| 53 |
+
self.hidden_ratio = hidden_ratio
|
| 54 |
+
self.intermediate_size = intermediate_size
|
| 55 |
+
self.num_hidden_layers = num_hidden_layers
|
| 56 |
+
self.num_heads = num_heads
|
| 57 |
+
self.num_slots = num_slots
|
| 58 |
+
self.use_short_conv = use_short_conv
|
| 59 |
+
self.conv_size = conv_size
|
| 60 |
+
self.expand_k = exapnd_k
|
| 61 |
+
self.expand_v = exapnd_v
|
| 62 |
+
self.hidden_act = hidden_act
|
| 63 |
+
self.max_position_embeddings = max_position_embeddings
|
| 64 |
+
self.elementwise_affine = elementwise_affine
|
| 65 |
+
self.norm_eps = norm_eps
|
| 66 |
+
self.use_rope = use_rope
|
| 67 |
+
self.attn = attn
|
| 68 |
+
self.use_cache = use_cache
|
| 69 |
+
self.initializer_range = initializer_range
|
| 70 |
+
|
| 71 |
+
self.fuse_norm = fuse_norm
|
| 72 |
+
self.fuse_swiglu = fuse_swiglu
|
| 73 |
+
self.fuse_cross_entropy = fuse_cross_entropy
|
| 74 |
+
self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
|
| 75 |
+
self.use_l2warp = use_l2warp
|
| 76 |
+
self.vocab_size = vocab_size
|
| 77 |
+
|
| 78 |
+
if fuse_cross_entropy and fuse_linear_cross_entropy:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
|
| 81 |
+
)
|
| 82 |
+
if fuse_linear_cross_entropy:
|
| 83 |
+
warnings.warn(
|
| 84 |
+
"`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
|
| 85 |
+
"at the potential cost of reduced precision. "
|
| 86 |
+
"If you observe issues like loss divergence, consider disabling this setting."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if attn is not None:
|
| 90 |
+
if not isinstance(attn, Dict):
|
| 91 |
+
raise ValueError("attn must be a dictionary")
|
| 92 |
+
if 'layers' not in attn:
|
| 93 |
+
raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
|
| 94 |
+
if 'num_heads' not in attn:
|
| 95 |
+
raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
|
| 96 |
+
attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
|
| 97 |
+
attn['qkv_bias'] = attn.get('qkv_bias', False)
|
| 98 |
+
attn['window_size'] = attn.get('window_size', None)
|
| 99 |
+
attn['rope_theta'] = attn.get('rope_theta', 10000.)
|
| 100 |
+
|
| 101 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 12 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 13 |
+
from transformers.utils import logging
|
| 14 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 15 |
+
|
| 16 |
+
from fla.layers.abc import ABCAttention
|
| 17 |
+
from fla.layers.attn import Attention
|
| 18 |
+
from fla.models.abc.configuration_abc import ABCConfig
|
| 19 |
+
from fla.models.utils import Cache, FLAGenerationMixin
|
| 20 |
+
from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
|
| 21 |
+
from fla.modules import GatedMLP as ABCMLP
|
| 22 |
+
from fla.modules import RMSNorm
|
| 23 |
+
from fla.modules.l2warp import l2_warp
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
except ImportError:
|
| 28 |
+
from fla.models.modeling_layers import GradientCheckpointingLayer
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from transformers.processing_utils import Unpack
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ABCBlock(GradientCheckpointingLayer):
|
| 37 |
+
|
| 38 |
+
def __init__(self, config: ABCConfig, layer_idx: int):
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
self.config = config
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
|
| 44 |
+
self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 45 |
+
if config.attn is not None and layer_idx in config.attn['layers']:
|
| 46 |
+
self.attn = Attention(
|
| 47 |
+
hidden_size=config.hidden_size,
|
| 48 |
+
num_heads=config.attn['num_heads'],
|
| 49 |
+
num_kv_heads=config.attn['num_kv_heads'],
|
| 50 |
+
qkv_bias=config.attn['qkv_bias'],
|
| 51 |
+
window_size=config.attn['window_size'],
|
| 52 |
+
rope_theta=config.attn['rope_theta'],
|
| 53 |
+
max_position_embeddings=config.max_position_embeddings,
|
| 54 |
+
layer_idx=layer_idx
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
self.attn = ABCAttention(
|
| 58 |
+
hidden_size=config.hidden_size,
|
| 59 |
+
expand_k=config.expand_k,
|
| 60 |
+
expand_v=config.expand_v,
|
| 61 |
+
num_heads=config.num_heads,
|
| 62 |
+
num_slots=config.num_slots,
|
| 63 |
+
use_short_conv=config.use_short_conv,
|
| 64 |
+
conv_size=config.conv_size,
|
| 65 |
+
gate_fn=config.hidden_act,
|
| 66 |
+
elementwise_affine=config.elementwise_affine,
|
| 67 |
+
norm_eps=config.norm_eps,
|
| 68 |
+
use_rope=config.use_rope,
|
| 69 |
+
clamp_min=config.clamp_min,
|
| 70 |
+
clamp_max=config.clamp_max,
|
| 71 |
+
fuse_norm=config.fuse_norm,
|
| 72 |
+
layer_idx=layer_idx
|
| 73 |
+
)
|
| 74 |
+
self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 75 |
+
self.mlp = ABCMLP(
|
| 76 |
+
hidden_size=config.hidden_size,
|
| 77 |
+
hidden_ratio=config.hidden_ratio,
|
| 78 |
+
intermediate_size=config.intermediate_size,
|
| 79 |
+
hidden_act=config.hidden_act,
|
| 80 |
+
fuse_swiglu=config.fuse_swiglu
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def forward(
|
| 84 |
+
self,
|
| 85 |
+
hidden_states: torch.Tensor,
|
| 86 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 87 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 88 |
+
use_cache: Optional[bool] = False,
|
| 89 |
+
output_attentions: Optional[bool] = False,
|
| 90 |
+
**kwargs: Unpack[Dict]
|
| 91 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 92 |
+
|
| 93 |
+
residual = hidden_states
|
| 94 |
+
|
| 95 |
+
hidden_states = self.attn_norm(hidden_states)
|
| 96 |
+
hidden_states, attentions, past_key_values = self.attn(
|
| 97 |
+
hidden_states=hidden_states,
|
| 98 |
+
attention_mask=attention_mask,
|
| 99 |
+
past_key_values=past_key_values,
|
| 100 |
+
use_cache=use_cache,
|
| 101 |
+
output_attentions=output_attentions,
|
| 102 |
+
**kwargs
|
| 103 |
+
)
|
| 104 |
+
if self.config.fuse_norm:
|
| 105 |
+
hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
|
| 106 |
+
else:
|
| 107 |
+
hidden_states = residual + hidden_states
|
| 108 |
+
residual = hidden_states
|
| 109 |
+
hidden_states = self.mlp_norm(hidden_states)
|
| 110 |
+
hidden_states = self.mlp(hidden_states)
|
| 111 |
+
hidden_states = residual + hidden_states
|
| 112 |
+
|
| 113 |
+
outputs = (hidden_states, attentions, past_key_values)
|
| 114 |
+
|
| 115 |
+
return outputs
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class ABCPreTrainedModel(PreTrainedModel):
|
| 119 |
+
|
| 120 |
+
config_class = ABCConfig
|
| 121 |
+
base_model_prefix = 'model'
|
| 122 |
+
supports_gradient_checkpointing = True
|
| 123 |
+
_no_split_modules = ['ABCBlock']
|
| 124 |
+
_supports_cache_class = True
|
| 125 |
+
|
| 126 |
+
def __init__(self, *inputs, **kwargs):
|
| 127 |
+
super().__init__(*inputs, **kwargs)
|
| 128 |
+
|
| 129 |
+
def _init_weights(
|
| 130 |
+
self,
|
| 131 |
+
module: nn.Module,
|
| 132 |
+
prenorm_residual_strategy: Optional[str] = None,
|
| 133 |
+
num_residuals_per_layer: int = 2,
|
| 134 |
+
):
|
| 135 |
+
if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 136 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 137 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 138 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 139 |
+
if module.bias is not None:
|
| 140 |
+
nn.init.zeros_(module.bias)
|
| 141 |
+
elif isinstance(module, nn.Embedding):
|
| 142 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 143 |
+
elif hasattr(module, 'reset_parameters'):
|
| 144 |
+
module.reset_parameters()
|
| 145 |
+
|
| 146 |
+
if prenorm_residual_strategy is not None:
|
| 147 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 148 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 149 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 150 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 151 |
+
#
|
| 152 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 153 |
+
p = None
|
| 154 |
+
if hasattr(module, 'o_proj'):
|
| 155 |
+
p = module.o_proj.weight
|
| 156 |
+
elif hasattr(module, 'down_proj'):
|
| 157 |
+
p = module.down_proj.weight
|
| 158 |
+
if p is not None:
|
| 159 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 160 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 161 |
+
# We need to reinit p since this code could be called multiple times
|
| 162 |
+
# Having just p *= scale would repeatedly scale it down
|
| 163 |
+
if prenorm_residual_strategy == 'rescale':
|
| 164 |
+
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 165 |
+
with torch.no_grad():
|
| 166 |
+
p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
|
| 167 |
+
elif prenorm_residual_strategy == 'zero':
|
| 168 |
+
nn.init.zeros_(p)
|
| 169 |
+
else:
|
| 170 |
+
raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class ABCModel(ABCPreTrainedModel):
|
| 174 |
+
|
| 175 |
+
def __init__(self, config: ABCConfig):
|
| 176 |
+
super().__init__(config)
|
| 177 |
+
self.padding_idx = config.pad_token_id
|
| 178 |
+
self.vocab_size = config.vocab_size
|
| 179 |
+
|
| 180 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 181 |
+
self.layers = nn.ModuleList([ABCBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 182 |
+
self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 183 |
+
|
| 184 |
+
self.gradient_checkpointing = False
|
| 185 |
+
|
| 186 |
+
self.post_init()
|
| 187 |
+
|
| 188 |
+
def get_input_embeddings(self):
|
| 189 |
+
return self.embeddings
|
| 190 |
+
|
| 191 |
+
def set_input_embeddings(self, value):
|
| 192 |
+
self.embeddings = value
|
| 193 |
+
|
| 194 |
+
def forward(
|
| 195 |
+
self,
|
| 196 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 197 |
+
attention_mask: Optional[torch.Tensor] = None, # noqa
|
| 198 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 199 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 200 |
+
use_cache: Optional[bool] = None,
|
| 201 |
+
output_attentions: Optional[bool] = None,
|
| 202 |
+
output_hidden_states: Optional[bool] = None,
|
| 203 |
+
return_dict: Optional[bool] = None,
|
| 204 |
+
**kwargs: Unpack[Dict]
|
| 205 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 206 |
+
if output_attentions:
|
| 207 |
+
warnings.warn("`ABCModel` does not `output_attentions` now, setting it to `False`.")
|
| 208 |
+
output_attentions = False
|
| 209 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 210 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 211 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 212 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 213 |
+
|
| 214 |
+
# retrieve input_ids and inputs_embeds
|
| 215 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 216 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 217 |
+
if input_ids is None and inputs_embeds is None:
|
| 218 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 219 |
+
|
| 220 |
+
if inputs_embeds is None:
|
| 221 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 222 |
+
hidden_states = inputs_embeds
|
| 223 |
+
|
| 224 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
| 225 |
+
past_key_values = Cache.from_legacy_cache(past_key_values)
|
| 226 |
+
|
| 227 |
+
all_hidden_states = () if output_hidden_states else None
|
| 228 |
+
all_attns = () if output_attentions else None
|
| 229 |
+
for layer in self.layers:
|
| 230 |
+
if output_hidden_states:
|
| 231 |
+
all_hidden_states += (hidden_states,)
|
| 232 |
+
|
| 233 |
+
hidden_states, attentions, past_key_values = layer(
|
| 234 |
+
hidden_states,
|
| 235 |
+
attention_mask,
|
| 236 |
+
past_key_values=past_key_values,
|
| 237 |
+
use_cache=use_cache,
|
| 238 |
+
output_attentions=output_attentions,
|
| 239 |
+
**kwargs
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
if output_attentions:
|
| 243 |
+
all_attns += (attentions,)
|
| 244 |
+
|
| 245 |
+
hidden_states = self.norm(hidden_states)
|
| 246 |
+
|
| 247 |
+
# add hidden states from the last decoder layer
|
| 248 |
+
if output_hidden_states:
|
| 249 |
+
all_hidden_states += (hidden_states,)
|
| 250 |
+
|
| 251 |
+
if not return_dict:
|
| 252 |
+
return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
|
| 253 |
+
return BaseModelOutputWithPast(
|
| 254 |
+
last_hidden_state=hidden_states,
|
| 255 |
+
past_key_values=past_key_values,
|
| 256 |
+
hidden_states=all_hidden_states,
|
| 257 |
+
attentions=all_attns
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class ABCForCausalLM(ABCPreTrainedModel, FLAGenerationMixin):
|
| 262 |
+
|
| 263 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 264 |
+
|
| 265 |
+
def __init__(self, config):
|
| 266 |
+
super().__init__(config)
|
| 267 |
+
self.model = ABCModel(config)
|
| 268 |
+
self.vocab_size = config.vocab_size
|
| 269 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 270 |
+
self.criterion = None
|
| 271 |
+
|
| 272 |
+
# Initialize weights and apply final processing
|
| 273 |
+
self.post_init()
|
| 274 |
+
|
| 275 |
+
def get_input_embeddings(self):
|
| 276 |
+
return self.model.embeddings
|
| 277 |
+
|
| 278 |
+
def set_input_embeddings(self, value):
|
| 279 |
+
self.model.embeddings = value
|
| 280 |
+
|
| 281 |
+
def get_output_embeddings(self):
|
| 282 |
+
return self.lm_head
|
| 283 |
+
|
| 284 |
+
def set_output_embeddings(self, new_embeddings):
|
| 285 |
+
self.lm_head = new_embeddings
|
| 286 |
+
|
| 287 |
+
def set_decoder(self, decoder):
|
| 288 |
+
self.model = decoder
|
| 289 |
+
|
| 290 |
+
def get_decoder(self):
|
| 291 |
+
return self.model
|
| 292 |
+
|
| 293 |
+
def generate(self, *args, **kwargs):
|
| 294 |
+
try:
|
| 295 |
+
return super().generate(*args, **kwargs)
|
| 296 |
+
except AttributeError as exception:
|
| 297 |
+
if 'past_key_values' in str(exception):
|
| 298 |
+
raise AttributeError(
|
| 299 |
+
f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
|
| 300 |
+
f"which is not supported for {self.__class__.__name__}. "
|
| 301 |
+
f"Try another generation strategy instead. "
|
| 302 |
+
f"For the available generation strategies, check this doc: "
|
| 303 |
+
f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
|
| 304 |
+
)
|
| 305 |
+
else:
|
| 306 |
+
raise exception
|
| 307 |
+
|
| 308 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 309 |
+
def forward(
|
| 310 |
+
self,
|
| 311 |
+
input_ids: torch.LongTensor = None,
|
| 312 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 313 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 314 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 315 |
+
labels: Optional[torch.LongTensor] = None,
|
| 316 |
+
use_cache: Optional[bool] = None,
|
| 317 |
+
output_attentions: Optional[bool] = None,
|
| 318 |
+
output_hidden_states: Optional[bool] = None,
|
| 319 |
+
return_dict: Optional[bool] = None,
|
| 320 |
+
logits_to_keep: Optional[int] = 0,
|
| 321 |
+
**kwargs: Unpack[Dict]
|
| 322 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 323 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 324 |
+
output_hidden_states = (
|
| 325 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 326 |
+
)
|
| 327 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 328 |
+
|
| 329 |
+
outputs = self.model(
|
| 330 |
+
input_ids=input_ids,
|
| 331 |
+
attention_mask=attention_mask,
|
| 332 |
+
inputs_embeds=inputs_embeds,
|
| 333 |
+
past_key_values=past_key_values,
|
| 334 |
+
use_cache=use_cache,
|
| 335 |
+
output_attentions=output_attentions,
|
| 336 |
+
output_hidden_states=output_hidden_states,
|
| 337 |
+
return_dict=return_dict,
|
| 338 |
+
**kwargs
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
hidden_states = outputs[0]
|
| 342 |
+
|
| 343 |
+
loss, logits = None, None
|
| 344 |
+
if not self.config.fuse_linear_cross_entropy or labels is None:
|
| 345 |
+
logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
|
| 346 |
+
if labels is not None:
|
| 347 |
+
if getattr(self, 'criterion', None) is None:
|
| 348 |
+
if self.config.fuse_linear_cross_entropy:
|
| 349 |
+
criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
|
| 350 |
+
elif self.config.fuse_cross_entropy:
|
| 351 |
+
criterion = FusedCrossEntropyLoss(inplace_backward=True)
|
| 352 |
+
else:
|
| 353 |
+
criterion = nn.CrossEntropyLoss()
|
| 354 |
+
else:
|
| 355 |
+
criterion = self.criterion
|
| 356 |
+
labels = labels.to(hidden_states.device)
|
| 357 |
+
labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
|
| 358 |
+
if self.config.fuse_linear_cross_entropy:
|
| 359 |
+
loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
|
| 360 |
+
else:
|
| 361 |
+
loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
|
| 362 |
+
loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
|
| 363 |
+
|
| 364 |
+
if not return_dict:
|
| 365 |
+
output = (logits,) + outputs[1:]
|
| 366 |
+
return (loss,) + output if loss is not None else output
|
| 367 |
+
|
| 368 |
+
return CausalLMOutputWithPast(
|
| 369 |
+
loss=loss,
|
| 370 |
+
logits=logits,
|
| 371 |
+
past_key_values=outputs.past_key_values,
|
| 372 |
+
hidden_states=outputs.hidden_states,
|
| 373 |
+
attentions=outputs.attentions,
|
| 374 |
+
)
|
models/bitnet/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
|
| 4 |
+
|
| 5 |
+
from fla.models.bitnet.configuration_bitnet import BitNetConfig
|
| 6 |
+
from fla.models.bitnet.modeling_bitnet import BitNetForCausalLM, BitNetModel
|
| 7 |
+
|
| 8 |
+
AutoConfig.register(BitNetConfig.model_type, BitNetConfig, exist_ok=True)
|
| 9 |
+
AutoModel.register(BitNetConfig, BitNetModel, exist_ok=True)
|
| 10 |
+
AutoModelForCausalLM.register(BitNetConfig, BitNetForCausalLM, exist_ok=True)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = ['BitNetConfig', 'BitNetForCausalLM', 'BitNetModel']
|
models/bitnet/configuration_bitnet.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class BitNetConfig(PretrainedConfig):
|
| 10 |
+
|
| 11 |
+
model_type = 'bitnet'
|
| 12 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
hidden_size: int = 2048,
|
| 17 |
+
num_hidden_layers: int = 24,
|
| 18 |
+
num_heads: int = 32,
|
| 19 |
+
num_kv_heads: Optional[int] = None,
|
| 20 |
+
window_size: Optional[int] = None,
|
| 21 |
+
rope_theta: Optional[float] = 10000.,
|
| 22 |
+
max_position_embeddings: int = 2048,
|
| 23 |
+
hidden_ratio: Optional[int] = 4,
|
| 24 |
+
intermediate_size: Optional[int] = None,
|
| 25 |
+
hidden_act: str = "swish",
|
| 26 |
+
initializer_range: float = 0.02,
|
| 27 |
+
elementwise_affine: Optional[bool] = True,
|
| 28 |
+
norm_eps: float = 1e-6,
|
| 29 |
+
use_cache: bool = True,
|
| 30 |
+
pad_token_id: Optional[int] = None,
|
| 31 |
+
bos_token_id: int = 1,
|
| 32 |
+
eos_token_id: int = 2,
|
| 33 |
+
tie_word_embeddings: bool = False,
|
| 34 |
+
fuse_norm: bool = True,
|
| 35 |
+
fuse_swiglu: bool = True,
|
| 36 |
+
fuse_cross_entropy: bool = True,
|
| 37 |
+
fuse_linear_cross_entropy: bool = False,
|
| 38 |
+
use_l2warp: bool = False,
|
| 39 |
+
vocab_size: int = 32000,
|
| 40 |
+
**kwargs,
|
| 41 |
+
):
|
| 42 |
+
self.hidden_size = hidden_size
|
| 43 |
+
self.num_hidden_layers = num_hidden_layers
|
| 44 |
+
self.num_heads = num_heads
|
| 45 |
+
self.num_kv_heads = num_kv_heads
|
| 46 |
+
self.window_size = window_size
|
| 47 |
+
self.rope_theta = rope_theta
|
| 48 |
+
self.max_position_embeddings = max_position_embeddings
|
| 49 |
+
|
| 50 |
+
self.hidden_ratio = hidden_ratio
|
| 51 |
+
self.intermediate_size = intermediate_size
|
| 52 |
+
self.hidden_act = hidden_act
|
| 53 |
+
|
| 54 |
+
self.initializer_range = initializer_range
|
| 55 |
+
self.elementwise_affine = elementwise_affine
|
| 56 |
+
self.norm_eps = norm_eps
|
| 57 |
+
self.use_cache = use_cache
|
| 58 |
+
|
| 59 |
+
self.fuse_norm = fuse_norm
|
| 60 |
+
self.fuse_swiglu = fuse_swiglu
|
| 61 |
+
self.fuse_cross_entropy = fuse_cross_entropy
|
| 62 |
+
self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
|
| 63 |
+
self.use_l2warp = use_l2warp
|
| 64 |
+
self.vocab_size = vocab_size
|
| 65 |
+
|
| 66 |
+
if fuse_cross_entropy and fuse_linear_cross_entropy:
|
| 67 |
+
raise ValueError(
|
| 68 |
+
"`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
|
| 69 |
+
)
|
| 70 |
+
if fuse_linear_cross_entropy:
|
| 71 |
+
warnings.warn(
|
| 72 |
+
"`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
|
| 73 |
+
"at the potential cost of reduced precision. "
|
| 74 |
+
"If you observe issues like loss divergence, consider disabling this setting."
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
super().__init__(
|
| 78 |
+
pad_token_id=pad_token_id,
|
| 79 |
+
bos_token_id=bos_token_id,
|
| 80 |
+
eos_token_id=eos_token_id,
|
| 81 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 82 |
+
**kwargs,
|
| 83 |
+
)
|
models/bitnet/modeling_bitnet.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 12 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 13 |
+
from transformers.utils import logging
|
| 14 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 15 |
+
|
| 16 |
+
from fla.layers.bitattn import BitAttention
|
| 17 |
+
from fla.models.bitnet.configuration_bitnet import BitNetConfig
|
| 18 |
+
from fla.models.utils import Cache, FLAGenerationMixin
|
| 19 |
+
from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss, RMSNorm
|
| 20 |
+
from fla.modules.activations import swiglu
|
| 21 |
+
from fla.modules.fused_bitlinear import FusedBitLinear
|
| 22 |
+
from fla.modules.l2warp import l2_warp
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from transformers.processing_utils import Unpack
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 30 |
+
except ImportError:
|
| 31 |
+
from fla.models.modeling_layers import GradientCheckpointingLayer
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class BitNetMLP(nn.Module):
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
hidden_size: int,
|
| 41 |
+
hidden_ratio: Optional[int] = None,
|
| 42 |
+
intermediate_size: Optional[int] = None,
|
| 43 |
+
hidden_act: str = 'swish',
|
| 44 |
+
fuse_swiglu: bool = True
|
| 45 |
+
) -> BitNetMLP:
|
| 46 |
+
super().__init__()
|
| 47 |
+
|
| 48 |
+
self.hidden_size = hidden_size
|
| 49 |
+
# the final number of params is `hidden_ratio * hidden_size^2`
|
| 50 |
+
# `intermediate_size` is chosen to be a multiple of 256 closest to `2/3 * hidden_size * hidden_ratio`
|
| 51 |
+
if hidden_ratio is None:
|
| 52 |
+
hidden_ratio = 4
|
| 53 |
+
if intermediate_size is None:
|
| 54 |
+
intermediate_size = int(hidden_size * hidden_ratio * 2 / 3)
|
| 55 |
+
intermediate_size = 256 * ((intermediate_size + 256 - 1) // 256)
|
| 56 |
+
self.hidden_ratio = hidden_ratio
|
| 57 |
+
self.intermediate_size = intermediate_size
|
| 58 |
+
self.hidden_act = hidden_act
|
| 59 |
+
self.fuse_swiglu = fuse_swiglu
|
| 60 |
+
|
| 61 |
+
if hidden_act != 'swish':
|
| 62 |
+
raise ValueError(f'Unsupported hidden_act: {hidden_act}')
|
| 63 |
+
|
| 64 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 65 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 66 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 67 |
+
|
| 68 |
+
def forward(
|
| 69 |
+
self,
|
| 70 |
+
x: torch.Tensor,
|
| 71 |
+
**kwargs: Unpack[Any]
|
| 72 |
+
) -> torch.Tensor:
|
| 73 |
+
gate, y = self.gate_proj(x), self.up_proj(x)
|
| 74 |
+
return self.down_proj(swiglu(gate, y))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class BitNetBlock(GradientCheckpointingLayer):
|
| 78 |
+
|
| 79 |
+
def __init__(self, config: BitNetConfig, layer_idx: int):
|
| 80 |
+
super().__init__()
|
| 81 |
+
|
| 82 |
+
self.config = config
|
| 83 |
+
self.layer_idx = layer_idx
|
| 84 |
+
|
| 85 |
+
self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 86 |
+
self.attn = BitAttention(
|
| 87 |
+
hidden_size=config.hidden_size,
|
| 88 |
+
num_heads=config.num_heads,
|
| 89 |
+
num_kv_heads=config.num_kv_heads,
|
| 90 |
+
window_size=config.window_size,
|
| 91 |
+
rope_theta=config.rope_theta,
|
| 92 |
+
max_position_embeddings=config.max_position_embeddings,
|
| 93 |
+
layer_idx=layer_idx
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 97 |
+
self.mlp = BitNetMLP(
|
| 98 |
+
hidden_size=config.hidden_size,
|
| 99 |
+
hidden_ratio=config.hidden_ratio,
|
| 100 |
+
intermediate_size=config.intermediate_size,
|
| 101 |
+
hidden_act=config.hidden_act,
|
| 102 |
+
fuse_swiglu=config.fuse_swiglu
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
def forward(
|
| 106 |
+
self,
|
| 107 |
+
hidden_states: torch.Tensor,
|
| 108 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 109 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
| 110 |
+
output_attentions: Optional[bool] = False,
|
| 111 |
+
use_cache: Optional[bool] = False,
|
| 112 |
+
**kwargs: Unpack[Any]
|
| 113 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 114 |
+
|
| 115 |
+
residual = hidden_states
|
| 116 |
+
hidden_states = self.attn_norm(hidden_states)
|
| 117 |
+
hidden_states, attentions, past_key_values = self.attn(
|
| 118 |
+
hidden_states=hidden_states,
|
| 119 |
+
attention_mask=attention_mask,
|
| 120 |
+
past_key_values=past_key_values,
|
| 121 |
+
use_cache=use_cache,
|
| 122 |
+
output_attentions=output_attentions,
|
| 123 |
+
**kwargs
|
| 124 |
+
)
|
| 125 |
+
if self.config.fuse_norm:
|
| 126 |
+
hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
|
| 127 |
+
else:
|
| 128 |
+
hidden_states = residual + hidden_states
|
| 129 |
+
residual = hidden_states
|
| 130 |
+
hidden_states = self.mlp_norm(hidden_states)
|
| 131 |
+
hidden_states = self.mlp(hidden_states, **kwargs)
|
| 132 |
+
hidden_states = residual + hidden_states
|
| 133 |
+
|
| 134 |
+
outputs = (hidden_states,)
|
| 135 |
+
|
| 136 |
+
if output_attentions:
|
| 137 |
+
outputs += (attentions,)
|
| 138 |
+
|
| 139 |
+
if use_cache:
|
| 140 |
+
outputs += (past_key_values,)
|
| 141 |
+
|
| 142 |
+
return outputs
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class BitNetPreTrainedModel(PreTrainedModel):
|
| 146 |
+
|
| 147 |
+
config_class = BitNetConfig
|
| 148 |
+
base_model_prefix = 'model'
|
| 149 |
+
supports_gradient_checkpointing = True
|
| 150 |
+
_no_split_modules = ['BitNetBlock']
|
| 151 |
+
_supports_cache_class = True
|
| 152 |
+
|
| 153 |
+
def __init__(self, *inputs, **kwargs):
|
| 154 |
+
super().__init__(*inputs, **kwargs)
|
| 155 |
+
|
| 156 |
+
def _init_weights(
|
| 157 |
+
self,
|
| 158 |
+
module: nn.Module,
|
| 159 |
+
rescale_prenorm_residual: bool = False,
|
| 160 |
+
num_residuals_per_layer: int = 2,
|
| 161 |
+
):
|
| 162 |
+
if isinstance(module, (nn.Linear, FusedBitLinear, nn.Conv1d)):
|
| 163 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 164 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 165 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 166 |
+
if module.bias is not None:
|
| 167 |
+
nn.init.zeros_(module.bias)
|
| 168 |
+
elif isinstance(module, nn.Embedding):
|
| 169 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 170 |
+
elif hasattr(module, 'reset_parameters'):
|
| 171 |
+
module.reset_parameters()
|
| 172 |
+
|
| 173 |
+
if rescale_prenorm_residual:
|
| 174 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 175 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 176 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 177 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 178 |
+
#
|
| 179 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 180 |
+
p = None
|
| 181 |
+
if hasattr(module, 'o_proj'):
|
| 182 |
+
p = module.o_proj.weight
|
| 183 |
+
elif hasattr(module, 'down_proj'):
|
| 184 |
+
p = module.down_proj.weight
|
| 185 |
+
if p is not None:
|
| 186 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 187 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 188 |
+
# We need to reinit p since this code could be called multiple times
|
| 189 |
+
# Having just p *= scale would repeatedly scale it down
|
| 190 |
+
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 191 |
+
with torch.no_grad():
|
| 192 |
+
p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class BitNetModel(BitNetPreTrainedModel):
|
| 196 |
+
|
| 197 |
+
def __init__(
|
| 198 |
+
self,
|
| 199 |
+
config: BitNetConfig
|
| 200 |
+
) -> BitNetModel:
|
| 201 |
+
super().__init__(config)
|
| 202 |
+
self.padding_idx = config.pad_token_id
|
| 203 |
+
self.vocab_size = config.vocab_size
|
| 204 |
+
|
| 205 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 206 |
+
self.layers = nn.ModuleList([BitNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 207 |
+
self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 208 |
+
|
| 209 |
+
self.gradient_checkpointing = False
|
| 210 |
+
|
| 211 |
+
self.post_init()
|
| 212 |
+
|
| 213 |
+
def get_input_embeddings(self):
|
| 214 |
+
return self.embeddings
|
| 215 |
+
|
| 216 |
+
def set_input_embeddings(self, value):
|
| 217 |
+
self.embeddings = value
|
| 218 |
+
|
| 219 |
+
def forward(
|
| 220 |
+
self,
|
| 221 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 222 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 223 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 224 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 225 |
+
use_cache: Optional[bool] = None,
|
| 226 |
+
output_attentions: Optional[bool] = None,
|
| 227 |
+
output_hidden_states: Optional[bool] = None,
|
| 228 |
+
return_dict: Optional[bool] = None,
|
| 229 |
+
**kwargs: Unpack[Any]
|
| 230 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 231 |
+
if output_attentions:
|
| 232 |
+
warnings.warn(
|
| 233 |
+
"`BitNetModel` does not support output attention weights now, so `output_attentions` is set to `False`."
|
| 234 |
+
)
|
| 235 |
+
output_attentions = False
|
| 236 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 237 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 238 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 239 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 240 |
+
|
| 241 |
+
# retrieve input_ids and inputs_embeds
|
| 242 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 243 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 244 |
+
elif input_ids is None and inputs_embeds is None:
|
| 245 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 246 |
+
|
| 247 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
| 248 |
+
past_key_values = Cache.from_legacy_cache(past_key_values)
|
| 249 |
+
|
| 250 |
+
if inputs_embeds is None:
|
| 251 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 252 |
+
|
| 253 |
+
# embed positions
|
| 254 |
+
hidden_states = inputs_embeds
|
| 255 |
+
|
| 256 |
+
all_hidden_states = () if output_hidden_states else None
|
| 257 |
+
all_attns = () if output_attentions else None
|
| 258 |
+
next_cache = None
|
| 259 |
+
|
| 260 |
+
for layer in self.layers:
|
| 261 |
+
if output_hidden_states:
|
| 262 |
+
all_hidden_states += (hidden_states,)
|
| 263 |
+
|
| 264 |
+
layer_outputs = layer(
|
| 265 |
+
hidden_states,
|
| 266 |
+
attention_mask=attention_mask,
|
| 267 |
+
past_key_values=past_key_values,
|
| 268 |
+
output_attentions=output_attentions,
|
| 269 |
+
use_cache=use_cache,
|
| 270 |
+
**kwargs
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
hidden_states = layer_outputs[0]
|
| 274 |
+
|
| 275 |
+
if use_cache:
|
| 276 |
+
next_cache = layer_outputs[2 if output_attentions else 1]
|
| 277 |
+
|
| 278 |
+
if output_attentions:
|
| 279 |
+
all_attns += (layer_outputs[1],)
|
| 280 |
+
|
| 281 |
+
hidden_states = self.norm(hidden_states)
|
| 282 |
+
|
| 283 |
+
# add hidden states from the last decoder layer
|
| 284 |
+
if output_hidden_states:
|
| 285 |
+
all_hidden_states += (hidden_states,)
|
| 286 |
+
|
| 287 |
+
if not return_dict:
|
| 288 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attns] if v is not None)
|
| 289 |
+
|
| 290 |
+
return BaseModelOutputWithPast(
|
| 291 |
+
last_hidden_state=hidden_states,
|
| 292 |
+
past_key_values=next_cache,
|
| 293 |
+
hidden_states=all_hidden_states,
|
| 294 |
+
attentions=all_attns
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class BitNetForCausalLM(BitNetPreTrainedModel, FLAGenerationMixin):
|
| 299 |
+
|
| 300 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 301 |
+
|
| 302 |
+
def __init__(self, config):
|
| 303 |
+
super().__init__(config)
|
| 304 |
+
self.model = BitNetModel(config)
|
| 305 |
+
self.vocab_size = config.vocab_size
|
| 306 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 307 |
+
self.criterion = None
|
| 308 |
+
|
| 309 |
+
# Initialize weights and apply final processing
|
| 310 |
+
self.post_init()
|
| 311 |
+
|
| 312 |
+
def get_input_embeddings(self):
|
| 313 |
+
return self.model.embeddings
|
| 314 |
+
|
| 315 |
+
def set_input_embeddings(self, value):
|
| 316 |
+
self.model.embeddings = value
|
| 317 |
+
|
| 318 |
+
def get_output_embeddings(self):
|
| 319 |
+
return self.lm_head
|
| 320 |
+
|
| 321 |
+
def set_output_embeddings(self, new_embeddings):
|
| 322 |
+
self.lm_head = new_embeddings
|
| 323 |
+
|
| 324 |
+
def set_decoder(self, decoder):
|
| 325 |
+
self.model = decoder
|
| 326 |
+
|
| 327 |
+
def get_decoder(self):
|
| 328 |
+
return self.model
|
| 329 |
+
|
| 330 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 331 |
+
def forward(
|
| 332 |
+
self,
|
| 333 |
+
input_ids: torch.LongTensor = None,
|
| 334 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 335 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 336 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 337 |
+
labels: Optional[torch.LongTensor] = None,
|
| 338 |
+
use_cache: Optional[bool] = None,
|
| 339 |
+
output_attentions: Optional[bool] = None,
|
| 340 |
+
output_hidden_states: Optional[bool] = None,
|
| 341 |
+
return_dict: Optional[bool] = None,
|
| 342 |
+
logits_to_keep: Optional[int] = 0,
|
| 343 |
+
**kwargs: Unpack[Any]
|
| 344 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 345 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 346 |
+
output_hidden_states = (
|
| 347 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 348 |
+
)
|
| 349 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 350 |
+
|
| 351 |
+
outputs = self.model(
|
| 352 |
+
input_ids=input_ids,
|
| 353 |
+
attention_mask=attention_mask,
|
| 354 |
+
past_key_values=past_key_values,
|
| 355 |
+
inputs_embeds=inputs_embeds,
|
| 356 |
+
use_cache=use_cache,
|
| 357 |
+
output_attentions=output_attentions,
|
| 358 |
+
output_hidden_states=output_hidden_states,
|
| 359 |
+
return_dict=return_dict,
|
| 360 |
+
**kwargs
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
hidden_states = outputs[0]
|
| 364 |
+
|
| 365 |
+
logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:])
|
| 366 |
+
|
| 367 |
+
loss = None
|
| 368 |
+
if labels is not None:
|
| 369 |
+
if getattr(self, 'criterion', None) is None:
|
| 370 |
+
if self.config.fuse_linear_cross_entropy:
|
| 371 |
+
criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
|
| 372 |
+
elif self.config.fuse_cross_entropy:
|
| 373 |
+
criterion = FusedCrossEntropyLoss(inplace_backward=True)
|
| 374 |
+
else:
|
| 375 |
+
criterion = nn.CrossEntropyLoss()
|
| 376 |
+
else:
|
| 377 |
+
criterion = self.criterion
|
| 378 |
+
|
| 379 |
+
labels = labels.to(hidden_states.device)
|
| 380 |
+
labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
|
| 381 |
+
if self.config.fuse_linear_cross_entropy:
|
| 382 |
+
loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
|
| 383 |
+
else:
|
| 384 |
+
loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
|
| 385 |
+
loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
|
| 386 |
+
|
| 387 |
+
if not return_dict:
|
| 388 |
+
output = (logits,) + outputs[1:]
|
| 389 |
+
return (loss,) + output if loss is not None else output
|
| 390 |
+
|
| 391 |
+
return CausalLMOutputWithPast(
|
| 392 |
+
loss=loss,
|
| 393 |
+
logits=logits,
|
| 394 |
+
past_key_values=outputs.past_key_values,
|
| 395 |
+
hidden_states=outputs.hidden_states,
|
| 396 |
+
attentions=outputs.attentions,
|
| 397 |
+
)
|
models/comba/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
|
| 4 |
+
|
| 5 |
+
from fla.models.comba.configuration_comba import CombaConfig
|
| 6 |
+
from fla.models.comba.modeling_comba import CombaForCausalLM, CombaModel
|
| 7 |
+
|
| 8 |
+
AutoConfig.register(CombaConfig.model_type, CombaConfig, exist_ok=True)
|
| 9 |
+
AutoModel.register(CombaConfig, CombaModel, exist_ok=True)
|
| 10 |
+
AutoModelForCausalLM.register(CombaConfig, CombaForCausalLM, exist_ok=True)
|
| 11 |
+
|
| 12 |
+
__all__ = ['CombaConfig', 'CombaForCausalLM', 'CombaModel']
|
models/comba/configuration_comba.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Dict, Optional
|
| 5 |
+
|
| 6 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CombaConfig(PretrainedConfig):
|
| 10 |
+
model_type = 'comba'
|
| 11 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
attn_mode: str = "chunk",
|
| 16 |
+
hidden_size: int = 2048,
|
| 17 |
+
conv_size: int = 4,
|
| 18 |
+
head_dim: int = 256,
|
| 19 |
+
num_heads: int = 6,
|
| 20 |
+
num_v_heads: Optional[int] = None,
|
| 21 |
+
expand_v: float = 2.0,
|
| 22 |
+
use_output_gate: bool = True,
|
| 23 |
+
use_short_conv: bool = True,
|
| 24 |
+
use_output_correction: bool = True,
|
| 25 |
+
use_inner_decay: bool = True,
|
| 26 |
+
correction_factor: float = 1.,
|
| 27 |
+
max_position_embeddings: int = 2048,
|
| 28 |
+
hidden_ratio: Optional[int] = 4,
|
| 29 |
+
intermediate_size: Optional[int] = None,
|
| 30 |
+
hidden_act: str = "swish",
|
| 31 |
+
num_hidden_layers: int = 21,
|
| 32 |
+
norm_eps: float = 1e-6,
|
| 33 |
+
attn: Optional[Dict] = None,
|
| 34 |
+
use_cache: bool = True,
|
| 35 |
+
pad_token_id: Optional[int] = None,
|
| 36 |
+
bos_token_id: int = 1,
|
| 37 |
+
eos_token_id: int = 2,
|
| 38 |
+
tie_word_embeddings: bool = False,
|
| 39 |
+
initializer_range: float = 0.02,
|
| 40 |
+
fuse_norm: bool = True,
|
| 41 |
+
fuse_swiglu: bool = True,
|
| 42 |
+
fuse_cross_entropy: bool = True,
|
| 43 |
+
fuse_linear_cross_entropy: bool = False,
|
| 44 |
+
use_l2warp: bool = False,
|
| 45 |
+
vocab_size: int = 32000,
|
| 46 |
+
**kwargs
|
| 47 |
+
):
|
| 48 |
+
self.attn_mode = attn_mode
|
| 49 |
+
self.hidden_size = hidden_size
|
| 50 |
+
self.conv_size = conv_size
|
| 51 |
+
self.head_dim = head_dim
|
| 52 |
+
self.num_heads = num_heads
|
| 53 |
+
self.num_v_heads = num_v_heads
|
| 54 |
+
self.expand_v = expand_v
|
| 55 |
+
self.use_output_gate = use_output_gate
|
| 56 |
+
self.use_short_conv = use_short_conv
|
| 57 |
+
self.use_output_correction = use_output_correction
|
| 58 |
+
self.correction_factor = correction_factor
|
| 59 |
+
self.use_inner_decay = use_inner_decay
|
| 60 |
+
self.max_position_embeddings = max_position_embeddings
|
| 61 |
+
|
| 62 |
+
self.hidden_ratio = hidden_ratio
|
| 63 |
+
self.intermediate_size = intermediate_size
|
| 64 |
+
self.hidden_act = hidden_act
|
| 65 |
+
self.num_hidden_layers = num_hidden_layers
|
| 66 |
+
self.norm_eps = norm_eps
|
| 67 |
+
self.attn = attn
|
| 68 |
+
self.use_cache = use_cache
|
| 69 |
+
self.initializer_range = initializer_range
|
| 70 |
+
|
| 71 |
+
self.fuse_norm = fuse_norm
|
| 72 |
+
self.fuse_swiglu = fuse_swiglu
|
| 73 |
+
self.fuse_cross_entropy = fuse_cross_entropy
|
| 74 |
+
self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
|
| 75 |
+
self.use_l2warp = use_l2warp
|
| 76 |
+
self.vocab_size = vocab_size
|
| 77 |
+
|
| 78 |
+
if fuse_cross_entropy and fuse_linear_cross_entropy:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
|
| 81 |
+
)
|
| 82 |
+
if fuse_linear_cross_entropy:
|
| 83 |
+
warnings.warn(
|
| 84 |
+
"`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
|
| 85 |
+
"at the potential cost of reduced precision. "
|
| 86 |
+
"If you observe issues like loss divergence, consider disabling this setting."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if attn is not None:
|
| 90 |
+
if not isinstance(attn, Dict):
|
| 91 |
+
raise ValueError("attn must be a dictionary")
|
| 92 |
+
if 'layers' not in attn:
|
| 93 |
+
raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
|
| 94 |
+
if 'num_heads' not in attn:
|
| 95 |
+
raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
|
| 96 |
+
attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
|
| 97 |
+
attn['qkv_bias'] = attn.get('qkv_bias', False)
|
| 98 |
+
attn['window_size'] = attn.get('window_size', None)
|
| 99 |
+
attn['rope_theta'] = attn.get('rope_theta', 10000.)
|
| 100 |
+
|
| 101 |
+
super().__init__(
|
| 102 |
+
pad_token_id=pad_token_id,
|
| 103 |
+
bos_token_id=bos_token_id,
|
| 104 |
+
eos_token_id=eos_token_id,
|
| 105 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 106 |
+
**kwargs,
|
| 107 |
+
)
|
models/comba/modeling_comba.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 12 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 13 |
+
from transformers.utils import logging
|
| 14 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 15 |
+
|
| 16 |
+
from fla.layers.attn import Attention
|
| 17 |
+
from fla.layers.comba import Comba
|
| 18 |
+
from fla.models.comba.configuration_comba import CombaConfig
|
| 19 |
+
from fla.models.utils import Cache, FLAGenerationMixin
|
| 20 |
+
from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
|
| 21 |
+
from fla.modules import GatedMLP as CombaMLP
|
| 22 |
+
from fla.modules import RMSNorm
|
| 23 |
+
from fla.modules.l2warp import l2_warp
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from transformers.processing_utils import Unpack
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
except ImportError:
|
| 32 |
+
from fla.models.modeling_layers import GradientCheckpointingLayer
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class CombaBlock(GradientCheckpointingLayer):
|
| 38 |
+
|
| 39 |
+
def __init__(self, config: CombaConfig, layer_idx: int):
|
| 40 |
+
super().__init__()
|
| 41 |
+
|
| 42 |
+
self.config = config
|
| 43 |
+
self.layer_idx = layer_idx
|
| 44 |
+
|
| 45 |
+
self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 46 |
+
if config.attn is not None and layer_idx in config.attn['layers']:
|
| 47 |
+
self.attn = Attention(
|
| 48 |
+
hidden_size=config.hidden_size,
|
| 49 |
+
num_heads=config.attn['num_heads'],
|
| 50 |
+
num_kv_heads=config.attn['num_kv_heads'],
|
| 51 |
+
qkv_bias=config.attn['qkv_bias'],
|
| 52 |
+
window_size=config.attn['window_size'],
|
| 53 |
+
rope_theta=config.attn['rope_theta'],
|
| 54 |
+
max_position_embeddings=config.max_position_embeddings,
|
| 55 |
+
layer_idx=layer_idx
|
| 56 |
+
)
|
| 57 |
+
else:
|
| 58 |
+
self.attn = Comba(
|
| 59 |
+
mode=config.attn_mode,
|
| 60 |
+
hidden_size=config.hidden_size,
|
| 61 |
+
expand_v=config.expand_v,
|
| 62 |
+
head_dim=config.head_dim,
|
| 63 |
+
num_heads=config.num_heads,
|
| 64 |
+
num_v_heads=config.num_v_heads,
|
| 65 |
+
use_output_gate=config.use_output_gate,
|
| 66 |
+
use_short_conv=config.use_short_conv,
|
| 67 |
+
conv_size=config.conv_size,
|
| 68 |
+
norm_eps=config.norm_eps,
|
| 69 |
+
layer_idx=layer_idx
|
| 70 |
+
)
|
| 71 |
+
self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 72 |
+
self.mlp = CombaMLP(
|
| 73 |
+
hidden_size=config.hidden_size,
|
| 74 |
+
hidden_ratio=config.hidden_ratio,
|
| 75 |
+
intermediate_size=config.intermediate_size,
|
| 76 |
+
hidden_act=config.hidden_act,
|
| 77 |
+
fuse_swiglu=config.fuse_swiglu
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def forward(
|
| 81 |
+
self,
|
| 82 |
+
hidden_states: torch.Tensor,
|
| 83 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 84 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 85 |
+
use_cache: Optional[bool] = False,
|
| 86 |
+
output_attentions: Optional[bool] = False,
|
| 87 |
+
**kwargs: Unpack[Dict]
|
| 88 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 89 |
+
residual = hidden_states
|
| 90 |
+
hidden_states = self.attn_norm(hidden_states)
|
| 91 |
+
hidden_states, attentions, past_key_values = self.attn(
|
| 92 |
+
hidden_states=hidden_states,
|
| 93 |
+
attention_mask=attention_mask,
|
| 94 |
+
past_key_values=past_key_values,
|
| 95 |
+
use_cache=use_cache,
|
| 96 |
+
output_attentions=output_attentions,
|
| 97 |
+
**kwargs
|
| 98 |
+
)
|
| 99 |
+
if self.config.fuse_norm:
|
| 100 |
+
hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
|
| 101 |
+
else:
|
| 102 |
+
hidden_states = residual + hidden_states
|
| 103 |
+
residual = hidden_states
|
| 104 |
+
hidden_states = self.mlp_norm(hidden_states)
|
| 105 |
+
hidden_states = self.mlp(hidden_states, **kwargs)
|
| 106 |
+
hidden_states = residual + hidden_states
|
| 107 |
+
|
| 108 |
+
outputs = (hidden_states, attentions, past_key_values)
|
| 109 |
+
|
| 110 |
+
return outputs
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class CombaPreTrainedModel(PreTrainedModel):
|
| 114 |
+
|
| 115 |
+
config_class = CombaConfig
|
| 116 |
+
base_model_prefix = 'model'
|
| 117 |
+
supports_gradient_checkpointing = True
|
| 118 |
+
_no_split_modules = ['CombaBlock']
|
| 119 |
+
_supports_cache_class = True
|
| 120 |
+
|
| 121 |
+
def __init__(self, *inputs, **kwargs):
|
| 122 |
+
super().__init__(*inputs, **kwargs)
|
| 123 |
+
|
| 124 |
+
def _init_weights(
|
| 125 |
+
self,
|
| 126 |
+
module: nn.Module,
|
| 127 |
+
prenorm_residual_strategy: Optional[str] = None,
|
| 128 |
+
num_residuals_per_layer: int = 2,
|
| 129 |
+
):
|
| 130 |
+
if isinstance(module, Comba) and next(module.parameters()).device.type != 'meta':
|
| 131 |
+
with torch.no_grad():
|
| 132 |
+
module.A_log.copy_(nn.init.uniform_(module.A_log, a=0, b=16).log())
|
| 133 |
+
module.A_log._no_weight_decay = True
|
| 134 |
+
dt = torch.exp(
|
| 135 |
+
nn.init.uniform_(module.dt_bias) * (math.log(0.1) - math.log(0.001)) + math.log(0.001)
|
| 136 |
+
).clamp(min=1e-4)
|
| 137 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 138 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 139 |
+
module.dt_bias.copy_(inv_dt)
|
| 140 |
+
module.dt_bias._no_weight_decay = True
|
| 141 |
+
|
| 142 |
+
elif isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 143 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 144 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 145 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 146 |
+
if module.bias is not None:
|
| 147 |
+
nn.init.zeros_(module.bias)
|
| 148 |
+
elif isinstance(module, nn.Embedding):
|
| 149 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 150 |
+
elif hasattr(module, 'reset_parameters'):
|
| 151 |
+
module.reset_parameters()
|
| 152 |
+
|
| 153 |
+
if prenorm_residual_strategy is not None:
|
| 154 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 155 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 156 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 157 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 158 |
+
#
|
| 159 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 160 |
+
p = None
|
| 161 |
+
if hasattr(module, 'o_proj'):
|
| 162 |
+
p = module.o_proj.weight
|
| 163 |
+
elif hasattr(module, 'down_proj'):
|
| 164 |
+
p = module.down_proj.weight
|
| 165 |
+
if p is not None:
|
| 166 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 167 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 168 |
+
# We need to reinit p since this code could be called multiple times
|
| 169 |
+
# Having just p *= scale would repeatedly scale it down
|
| 170 |
+
if prenorm_residual_strategy == 'rescale':
|
| 171 |
+
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 172 |
+
with torch.no_grad():
|
| 173 |
+
p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
|
| 174 |
+
elif prenorm_residual_strategy == 'zero':
|
| 175 |
+
nn.init.zeros_(p)
|
| 176 |
+
else:
|
| 177 |
+
raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class CombaModel(CombaPreTrainedModel):
|
| 181 |
+
|
| 182 |
+
def __init__(self, config: CombaConfig):
|
| 183 |
+
super().__init__(config)
|
| 184 |
+
self.padding_idx = config.pad_token_id
|
| 185 |
+
self.vocab_size = config.vocab_size
|
| 186 |
+
|
| 187 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 188 |
+
self.layers = nn.ModuleList([CombaBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 189 |
+
self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 190 |
+
|
| 191 |
+
self.gradient_checkpointing = False
|
| 192 |
+
|
| 193 |
+
self.post_init()
|
| 194 |
+
|
| 195 |
+
def get_input_embeddings(self):
|
| 196 |
+
return self.embeddings
|
| 197 |
+
|
| 198 |
+
def set_input_embeddings(self, value):
|
| 199 |
+
self.embeddings = value
|
| 200 |
+
|
| 201 |
+
def forward(
|
| 202 |
+
self,
|
| 203 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 204 |
+
attention_mask: Optional[torch.Tensor] = None, # noqa
|
| 205 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 206 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 207 |
+
use_cache: Optional[bool] = None,
|
| 208 |
+
output_attentions: Optional[bool] = None,
|
| 209 |
+
output_hidden_states: Optional[bool] = None,
|
| 210 |
+
return_dict: Optional[bool] = None,
|
| 211 |
+
**kwargs: Unpack[Dict]
|
| 212 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 213 |
+
if output_attentions:
|
| 214 |
+
warnings.warn("`CombaModel` does not `output_attentions` now, setting it to `False`.")
|
| 215 |
+
output_attentions = False
|
| 216 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 217 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 218 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 219 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 220 |
+
|
| 221 |
+
# retrieve input_ids and inputs_embeds
|
| 222 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 223 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 224 |
+
if input_ids is None and inputs_embeds is None:
|
| 225 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 226 |
+
|
| 227 |
+
if inputs_embeds is None:
|
| 228 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 229 |
+
hidden_states = inputs_embeds
|
| 230 |
+
|
| 231 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
| 232 |
+
past_key_values = Cache.from_legacy_cache(past_key_values)
|
| 233 |
+
|
| 234 |
+
all_hidden_states = () if output_hidden_states else None
|
| 235 |
+
all_attns = () if output_attentions else None
|
| 236 |
+
for layer in self.layers:
|
| 237 |
+
if output_hidden_states:
|
| 238 |
+
all_hidden_states += (hidden_states,)
|
| 239 |
+
|
| 240 |
+
hidden_states, attentions, past_key_values = layer(
|
| 241 |
+
hidden_states,
|
| 242 |
+
attention_mask=attention_mask,
|
| 243 |
+
past_key_values=past_key_values,
|
| 244 |
+
use_cache=use_cache,
|
| 245 |
+
output_attentions=output_attentions,
|
| 246 |
+
**kwargs
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
if output_attentions:
|
| 250 |
+
all_attns += (attentions,)
|
| 251 |
+
|
| 252 |
+
hidden_states = self.norm(hidden_states)
|
| 253 |
+
|
| 254 |
+
# add hidden states from the last decoder layer
|
| 255 |
+
if output_hidden_states:
|
| 256 |
+
all_hidden_states += (hidden_states,)
|
| 257 |
+
|
| 258 |
+
if not return_dict:
|
| 259 |
+
return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
|
| 260 |
+
return BaseModelOutputWithPast(
|
| 261 |
+
last_hidden_state=hidden_states,
|
| 262 |
+
past_key_values=past_key_values,
|
| 263 |
+
hidden_states=all_hidden_states,
|
| 264 |
+
attentions=all_attns
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class CombaForCausalLM(CombaPreTrainedModel, FLAGenerationMixin):
|
| 269 |
+
|
| 270 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 271 |
+
|
| 272 |
+
def __init__(self, config):
|
| 273 |
+
super().__init__(config)
|
| 274 |
+
self.model = CombaModel(config)
|
| 275 |
+
self.vocab_size = config.vocab_size
|
| 276 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 277 |
+
self.criterion = None
|
| 278 |
+
|
| 279 |
+
# Initialize weights and apply final processing
|
| 280 |
+
self.post_init()
|
| 281 |
+
|
| 282 |
+
def get_input_embeddings(self):
|
| 283 |
+
return self.model.embeddings
|
| 284 |
+
|
| 285 |
+
def set_input_embeddings(self, value):
|
| 286 |
+
self.model.embeddings = value
|
| 287 |
+
|
| 288 |
+
def get_output_embeddings(self):
|
| 289 |
+
return self.lm_head
|
| 290 |
+
|
| 291 |
+
def set_output_embeddings(self, new_embeddings):
|
| 292 |
+
self.lm_head = new_embeddings
|
| 293 |
+
|
| 294 |
+
def set_decoder(self, decoder):
|
| 295 |
+
self.model = decoder
|
| 296 |
+
|
| 297 |
+
def get_decoder(self):
|
| 298 |
+
return self.model
|
| 299 |
+
|
| 300 |
+
def generate(self, *args, **kwargs):
|
| 301 |
+
try:
|
| 302 |
+
return super().generate(*args, **kwargs)
|
| 303 |
+
except AttributeError as exception:
|
| 304 |
+
if 'past_key_values' in str(exception):
|
| 305 |
+
raise AttributeError(
|
| 306 |
+
f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
|
| 307 |
+
f"which is not supported for {self.__class__.__name__}. "
|
| 308 |
+
f"Try another generation strategy instead. "
|
| 309 |
+
f"For the available generation strategies, check this doc: "
|
| 310 |
+
f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
|
| 311 |
+
)
|
| 312 |
+
else:
|
| 313 |
+
raise exception
|
| 314 |
+
|
| 315 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 316 |
+
def forward(
|
| 317 |
+
self,
|
| 318 |
+
input_ids: torch.LongTensor = None,
|
| 319 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 320 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 321 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 322 |
+
labels: Optional[torch.LongTensor] = None,
|
| 323 |
+
use_cache: Optional[bool] = None,
|
| 324 |
+
output_attentions: Optional[bool] = None,
|
| 325 |
+
output_hidden_states: Optional[bool] = None,
|
| 326 |
+
return_dict: Optional[bool] = None,
|
| 327 |
+
logits_to_keep: Optional[int] = 0,
|
| 328 |
+
**kwargs: Unpack[Dict]
|
| 329 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 330 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 331 |
+
output_hidden_states = (
|
| 332 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 333 |
+
)
|
| 334 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 335 |
+
|
| 336 |
+
outputs = self.model(
|
| 337 |
+
input_ids=input_ids,
|
| 338 |
+
attention_mask=attention_mask,
|
| 339 |
+
inputs_embeds=inputs_embeds,
|
| 340 |
+
past_key_values=past_key_values,
|
| 341 |
+
use_cache=use_cache,
|
| 342 |
+
output_attentions=output_attentions,
|
| 343 |
+
output_hidden_states=output_hidden_states,
|
| 344 |
+
return_dict=return_dict,
|
| 345 |
+
**kwargs
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
hidden_states = outputs[0]
|
| 349 |
+
|
| 350 |
+
loss, logits = None, None
|
| 351 |
+
if not self.config.fuse_linear_cross_entropy or labels is None:
|
| 352 |
+
logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
|
| 353 |
+
if labels is not None:
|
| 354 |
+
if getattr(self, 'criterion', None) is None:
|
| 355 |
+
if self.config.fuse_linear_cross_entropy:
|
| 356 |
+
criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
|
| 357 |
+
elif self.config.fuse_cross_entropy:
|
| 358 |
+
criterion = FusedCrossEntropyLoss(inplace_backward=True)
|
| 359 |
+
else:
|
| 360 |
+
criterion = nn.CrossEntropyLoss()
|
| 361 |
+
else:
|
| 362 |
+
criterion = self.criterion
|
| 363 |
+
labels = labels.to(hidden_states.device)
|
| 364 |
+
labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
|
| 365 |
+
if self.config.fuse_linear_cross_entropy:
|
| 366 |
+
loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
|
| 367 |
+
else:
|
| 368 |
+
loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
|
| 369 |
+
loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
|
| 370 |
+
|
| 371 |
+
if not return_dict:
|
| 372 |
+
output = (logits,) + outputs[1:]
|
| 373 |
+
return (loss,) + output if loss is not None else output
|
| 374 |
+
|
| 375 |
+
return CausalLMOutputWithPast(
|
| 376 |
+
loss=loss,
|
| 377 |
+
logits=logits,
|
| 378 |
+
past_key_values=outputs.past_key_values,
|
| 379 |
+
hidden_states=outputs.hidden_states,
|
| 380 |
+
attentions=outputs.attentions,
|
| 381 |
+
)
|
models/delta_net/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
|
| 4 |
+
|
| 5 |
+
from fla.models.delta_net.configuration_delta_net import DeltaNetConfig
|
| 6 |
+
from fla.models.delta_net.modeling_delta_net import DeltaNetForCausalLM, DeltaNetModel
|
| 7 |
+
|
| 8 |
+
AutoConfig.register(DeltaNetConfig.model_type, DeltaNetConfig, exist_ok=True)
|
| 9 |
+
AutoModel.register(DeltaNetConfig, DeltaNetModel, exist_ok=True)
|
| 10 |
+
AutoModelForCausalLM.register(DeltaNetConfig, DeltaNetForCausalLM, exist_ok=True)
|
| 11 |
+
|
| 12 |
+
__all__ = ['DeltaNetConfig', 'DeltaNetForCausalLM', 'DeltaNetModel']
|
models/delta_net/configuration_delta_net.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Dict, Optional
|
| 5 |
+
|
| 6 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DeltaNetConfig(PretrainedConfig):
|
| 10 |
+
|
| 11 |
+
model_type = 'delta_net'
|
| 12 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
attn_mode: str = "chunk",
|
| 17 |
+
hidden_size: int = 2048,
|
| 18 |
+
expand_k: float = 1.0,
|
| 19 |
+
expand_v: float = 1.0,
|
| 20 |
+
use_gate: bool = False,
|
| 21 |
+
use_short_conv: bool = True,
|
| 22 |
+
conv_size: int = 4,
|
| 23 |
+
use_beta: bool = True,
|
| 24 |
+
use_output_norm: bool = True,
|
| 25 |
+
num_heads: int = 16,
|
| 26 |
+
qk_norm: str = 'l2',
|
| 27 |
+
qk_activation: str = 'silu',
|
| 28 |
+
max_position_embeddings: int = 2048,
|
| 29 |
+
hidden_ratio: Optional[int] = 4,
|
| 30 |
+
intermediate_size: Optional[int] = None,
|
| 31 |
+
hidden_act: str = "swish",
|
| 32 |
+
num_hidden_layers: int = 24,
|
| 33 |
+
norm_eps: float = 1e-6,
|
| 34 |
+
attn: Optional[Dict] = None,
|
| 35 |
+
use_cache: bool = True,
|
| 36 |
+
pad_token_id: Optional[int] = None,
|
| 37 |
+
bos_token_id: int = 1,
|
| 38 |
+
eos_token_id: int = 2,
|
| 39 |
+
tie_word_embeddings: bool = False,
|
| 40 |
+
initializer_range: float = 0.02,
|
| 41 |
+
fuse_norm: bool = True,
|
| 42 |
+
fuse_swiglu: bool = True,
|
| 43 |
+
fuse_cross_entropy: bool = True,
|
| 44 |
+
fuse_linear_cross_entropy: bool = False,
|
| 45 |
+
use_l2warp: bool = False,
|
| 46 |
+
vocab_size: int = 32000,
|
| 47 |
+
**kwargs
|
| 48 |
+
):
|
| 49 |
+
self.attn_mode = attn_mode
|
| 50 |
+
self.hidden_size = hidden_size
|
| 51 |
+
self.expand_k = expand_k
|
| 52 |
+
self.expand_v = expand_v
|
| 53 |
+
self.use_gate = use_gate
|
| 54 |
+
self.use_short_conv = use_short_conv
|
| 55 |
+
self.conv_size = conv_size
|
| 56 |
+
self.use_beta = use_beta
|
| 57 |
+
self.use_output_norm = use_output_norm
|
| 58 |
+
self.num_heads = num_heads
|
| 59 |
+
self.qk_norm = qk_norm
|
| 60 |
+
self.qk_activation = qk_activation
|
| 61 |
+
self.max_position_embeddings = max_position_embeddings
|
| 62 |
+
|
| 63 |
+
self.hidden_ratio = hidden_ratio
|
| 64 |
+
self.intermediate_size = intermediate_size
|
| 65 |
+
self.hidden_act = hidden_act
|
| 66 |
+
self.num_hidden_layers = num_hidden_layers
|
| 67 |
+
self.norm_eps = norm_eps
|
| 68 |
+
self.attn = attn
|
| 69 |
+
self.use_cache = use_cache
|
| 70 |
+
self.initializer_range = initializer_range
|
| 71 |
+
self.fuse_norm = fuse_norm
|
| 72 |
+
self.fuse_swiglu = fuse_swiglu
|
| 73 |
+
self.fuse_cross_entropy = fuse_cross_entropy
|
| 74 |
+
self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
|
| 75 |
+
self.use_l2warp = use_l2warp
|
| 76 |
+
self.vocab_size = vocab_size
|
| 77 |
+
|
| 78 |
+
if fuse_cross_entropy and fuse_linear_cross_entropy:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
|
| 81 |
+
)
|
| 82 |
+
if fuse_linear_cross_entropy:
|
| 83 |
+
warnings.warn(
|
| 84 |
+
"`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
|
| 85 |
+
"at the potential cost of reduced precision. "
|
| 86 |
+
"If you observe issues like loss divergence, consider disabling this setting."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if attn is not None:
|
| 90 |
+
if not isinstance(attn, Dict):
|
| 91 |
+
raise ValueError("attn must be a dictionary")
|
| 92 |
+
if 'layers' not in attn:
|
| 93 |
+
raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
|
| 94 |
+
if 'num_heads' not in attn:
|
| 95 |
+
raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
|
| 96 |
+
attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
|
| 97 |
+
attn['qkv_bias'] = attn.get('qkv_bias', False)
|
| 98 |
+
attn['window_size'] = attn.get('window_size', None)
|
| 99 |
+
attn['rope_theta'] = attn.get('rope_theta', 10000.)
|
| 100 |
+
|
| 101 |
+
super().__init__(
|
| 102 |
+
pad_token_id=pad_token_id,
|
| 103 |
+
bos_token_id=bos_token_id,
|
| 104 |
+
eos_token_id=eos_token_id,
|
| 105 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 106 |
+
**kwargs,
|
| 107 |
+
)
|
models/delta_net/modeling_delta_net.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 12 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 13 |
+
from transformers.utils import logging
|
| 14 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 15 |
+
|
| 16 |
+
from fla.layers.attn import Attention
|
| 17 |
+
from fla.layers.delta_net import DeltaNet
|
| 18 |
+
from fla.models.delta_net.configuration_delta_net import DeltaNetConfig
|
| 19 |
+
from fla.models.utils import Cache, FLAGenerationMixin
|
| 20 |
+
from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
|
| 21 |
+
from fla.modules import GatedMLP as DeltaNetMLP
|
| 22 |
+
from fla.modules import RMSNorm
|
| 23 |
+
from fla.modules.l2warp import l2_warp
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
except ImportError:
|
| 28 |
+
from fla.models.modeling_layers import GradientCheckpointingLayer
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from transformers.processing_utils import Unpack
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class DeltaNetBlock(GradientCheckpointingLayer):
|
| 37 |
+
|
| 38 |
+
def __init__(self, config: DeltaNetConfig, layer_idx: int):
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
self.config = config
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
|
| 44 |
+
self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 45 |
+
if config.attn is not None and layer_idx in config.attn['layers']:
|
| 46 |
+
self.attn = Attention(
|
| 47 |
+
hidden_size=config.hidden_size,
|
| 48 |
+
num_heads=config.attn['num_heads'],
|
| 49 |
+
num_kv_heads=config.attn['num_kv_heads'],
|
| 50 |
+
qkv_bias=config.attn['qkv_bias'],
|
| 51 |
+
window_size=config.attn['window_size'],
|
| 52 |
+
rope_theta=config.attn['rope_theta'],
|
| 53 |
+
max_position_embeddings=config.max_position_embeddings,
|
| 54 |
+
layer_idx=layer_idx
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
self.attn = DeltaNet(
|
| 58 |
+
mode=config.attn_mode,
|
| 59 |
+
hidden_size=config.hidden_size,
|
| 60 |
+
expand_k=config.expand_k,
|
| 61 |
+
expand_v=config.expand_v,
|
| 62 |
+
num_heads=config.num_heads,
|
| 63 |
+
use_gate=config.use_gate,
|
| 64 |
+
use_beta=config.use_beta,
|
| 65 |
+
use_short_conv=config.use_short_conv,
|
| 66 |
+
use_output_norm=config.use_output_norm,
|
| 67 |
+
conv_size=config.conv_size,
|
| 68 |
+
qk_norm=config.qk_norm,
|
| 69 |
+
qk_activation=config.qk_activation,
|
| 70 |
+
norm_eps=config.norm_eps,
|
| 71 |
+
layer_idx=layer_idx
|
| 72 |
+
)
|
| 73 |
+
self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 74 |
+
self.mlp = DeltaNetMLP(
|
| 75 |
+
hidden_size=config.hidden_size,
|
| 76 |
+
hidden_ratio=config.hidden_ratio,
|
| 77 |
+
intermediate_size=config.intermediate_size,
|
| 78 |
+
hidden_act=config.hidden_act,
|
| 79 |
+
fuse_swiglu=config.fuse_swiglu
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
def forward(
|
| 83 |
+
self,
|
| 84 |
+
hidden_states: torch.Tensor,
|
| 85 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 86 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 87 |
+
use_cache: Optional[bool] = False,
|
| 88 |
+
output_attentions: Optional[bool] = False,
|
| 89 |
+
**kwargs: Unpack[Dict]
|
| 90 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 91 |
+
residual = hidden_states
|
| 92 |
+
hidden_states = self.attn_norm(hidden_states)
|
| 93 |
+
hidden_states, attentions, past_key_values = self.attn(
|
| 94 |
+
hidden_states=hidden_states,
|
| 95 |
+
attention_mask=attention_mask,
|
| 96 |
+
past_key_values=past_key_values,
|
| 97 |
+
use_cache=use_cache,
|
| 98 |
+
output_attentions=output_attentions,
|
| 99 |
+
**kwargs
|
| 100 |
+
)
|
| 101 |
+
if self.config.fuse_norm:
|
| 102 |
+
hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
|
| 103 |
+
else:
|
| 104 |
+
hidden_states = residual + hidden_states
|
| 105 |
+
residual = hidden_states
|
| 106 |
+
hidden_states = self.mlp_norm(hidden_states)
|
| 107 |
+
hidden_states = self.mlp(hidden_states, **kwargs)
|
| 108 |
+
hidden_states = residual + hidden_states
|
| 109 |
+
|
| 110 |
+
outputs = (hidden_states, attentions, past_key_values)
|
| 111 |
+
|
| 112 |
+
return outputs
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class DeltaNetPreTrainedModel(PreTrainedModel):
|
| 116 |
+
|
| 117 |
+
config_class = DeltaNetConfig
|
| 118 |
+
base_model_prefix = 'model'
|
| 119 |
+
supports_gradient_checkpointing = True
|
| 120 |
+
_no_split_modules = ['DeltaNetBlock']
|
| 121 |
+
_supports_cache_class = True
|
| 122 |
+
|
| 123 |
+
def __init__(self, *inputs, **kwargs):
|
| 124 |
+
super().__init__(*inputs, **kwargs)
|
| 125 |
+
|
| 126 |
+
def _init_weights(
|
| 127 |
+
self,
|
| 128 |
+
module: nn.Module,
|
| 129 |
+
prenorm_residual_strategy: Optional[str] = None,
|
| 130 |
+
num_residuals_per_layer: int = 2,
|
| 131 |
+
):
|
| 132 |
+
if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 133 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 134 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 135 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 136 |
+
if module.bias is not None:
|
| 137 |
+
nn.init.zeros_(module.bias)
|
| 138 |
+
elif isinstance(module, nn.Embedding):
|
| 139 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 140 |
+
elif hasattr(module, 'reset_parameters'):
|
| 141 |
+
module.reset_parameters()
|
| 142 |
+
|
| 143 |
+
if prenorm_residual_strategy is not None:
|
| 144 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 145 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 146 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 147 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 148 |
+
#
|
| 149 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 150 |
+
p = None
|
| 151 |
+
if hasattr(module, 'o_proj'):
|
| 152 |
+
p = module.o_proj.weight
|
| 153 |
+
elif hasattr(module, 'down_proj'):
|
| 154 |
+
p = module.down_proj.weight
|
| 155 |
+
if p is not None:
|
| 156 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 157 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 158 |
+
# We need to reinit p since this code could be called multiple times
|
| 159 |
+
# Having just p *= scale would repeatedly scale it down
|
| 160 |
+
if prenorm_residual_strategy == 'rescale':
|
| 161 |
+
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 162 |
+
with torch.no_grad():
|
| 163 |
+
p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
|
| 164 |
+
elif prenorm_residual_strategy == 'zero':
|
| 165 |
+
nn.init.zeros_(p)
|
| 166 |
+
else:
|
| 167 |
+
raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class DeltaNetModel(DeltaNetPreTrainedModel):
|
| 171 |
+
|
| 172 |
+
def __init__(self, config: DeltaNetConfig):
|
| 173 |
+
super().__init__(config)
|
| 174 |
+
self.padding_idx = config.pad_token_id
|
| 175 |
+
self.vocab_size = config.vocab_size
|
| 176 |
+
|
| 177 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 178 |
+
self.layers = nn.ModuleList([DeltaNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 179 |
+
self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 180 |
+
|
| 181 |
+
self.gradient_checkpointing = False
|
| 182 |
+
|
| 183 |
+
self.post_init()
|
| 184 |
+
|
| 185 |
+
def get_input_embeddings(self):
|
| 186 |
+
return self.embeddings
|
| 187 |
+
|
| 188 |
+
def set_input_embeddings(self, value):
|
| 189 |
+
self.embeddings = value
|
| 190 |
+
|
| 191 |
+
def forward(
|
| 192 |
+
self,
|
| 193 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 194 |
+
attention_mask: Optional[torch.Tensor] = None, # noqa
|
| 195 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 196 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 197 |
+
use_cache: Optional[bool] = None,
|
| 198 |
+
output_attentions: Optional[bool] = None,
|
| 199 |
+
output_hidden_states: Optional[bool] = None,
|
| 200 |
+
return_dict: Optional[bool] = None,
|
| 201 |
+
**kwargs: Unpack[Dict]
|
| 202 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 203 |
+
if output_attentions:
|
| 204 |
+
warnings.warn("`DeltaNetModel` does not `output_attentions` now, setting it to `False`.")
|
| 205 |
+
output_attentions = False
|
| 206 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 207 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 208 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 209 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 210 |
+
|
| 211 |
+
# retrieve input_ids and inputs_embeds
|
| 212 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 213 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 214 |
+
if input_ids is None and inputs_embeds is None:
|
| 215 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 216 |
+
|
| 217 |
+
if inputs_embeds is None:
|
| 218 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 219 |
+
hidden_states = inputs_embeds
|
| 220 |
+
|
| 221 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
| 222 |
+
past_key_values = Cache.from_legacy_cache(past_key_values)
|
| 223 |
+
|
| 224 |
+
all_hidden_states = () if output_hidden_states else None
|
| 225 |
+
all_attns = () if output_attentions else None
|
| 226 |
+
for layer in self.layers:
|
| 227 |
+
if output_hidden_states:
|
| 228 |
+
all_hidden_states += (hidden_states,)
|
| 229 |
+
|
| 230 |
+
hidden_states, attentions, past_key_values = layer(
|
| 231 |
+
hidden_states,
|
| 232 |
+
attention_mask=attention_mask,
|
| 233 |
+
past_key_values=past_key_values,
|
| 234 |
+
use_cache=use_cache,
|
| 235 |
+
output_attentions=output_attentions,
|
| 236 |
+
**kwargs
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
if output_attentions:
|
| 240 |
+
all_attns += (attentions,)
|
| 241 |
+
|
| 242 |
+
hidden_states = self.norm(hidden_states)
|
| 243 |
+
|
| 244 |
+
# add hidden states from the last decoder layer
|
| 245 |
+
if output_hidden_states:
|
| 246 |
+
all_hidden_states += (hidden_states,)
|
| 247 |
+
|
| 248 |
+
if not return_dict:
|
| 249 |
+
return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
|
| 250 |
+
return BaseModelOutputWithPast(
|
| 251 |
+
last_hidden_state=hidden_states,
|
| 252 |
+
past_key_values=past_key_values,
|
| 253 |
+
hidden_states=all_hidden_states,
|
| 254 |
+
attentions=all_attns
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class DeltaNetForCausalLM(DeltaNetPreTrainedModel, FLAGenerationMixin):
|
| 259 |
+
|
| 260 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 261 |
+
|
| 262 |
+
def __init__(self, config):
|
| 263 |
+
super().__init__(config)
|
| 264 |
+
self.model = DeltaNetModel(config)
|
| 265 |
+
self.vocab_size = config.vocab_size
|
| 266 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 267 |
+
self.criterion = None
|
| 268 |
+
|
| 269 |
+
# Initialize weights and apply final processing
|
| 270 |
+
self.post_init()
|
| 271 |
+
|
| 272 |
+
def get_input_embeddings(self):
|
| 273 |
+
return self.model.embeddings
|
| 274 |
+
|
| 275 |
+
def set_input_embeddings(self, value):
|
| 276 |
+
self.model.embeddings = value
|
| 277 |
+
|
| 278 |
+
def get_output_embeddings(self):
|
| 279 |
+
return self.lm_head
|
| 280 |
+
|
| 281 |
+
def set_output_embeddings(self, new_embeddings):
|
| 282 |
+
self.lm_head = new_embeddings
|
| 283 |
+
|
| 284 |
+
def set_decoder(self, decoder):
|
| 285 |
+
self.model = decoder
|
| 286 |
+
|
| 287 |
+
def get_decoder(self):
|
| 288 |
+
return self.model
|
| 289 |
+
|
| 290 |
+
def generate(self, *args, **kwargs):
|
| 291 |
+
try:
|
| 292 |
+
return super().generate(*args, **kwargs)
|
| 293 |
+
except AttributeError as exception:
|
| 294 |
+
if 'past_key_values' in str(exception):
|
| 295 |
+
raise AttributeError(
|
| 296 |
+
f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
|
| 297 |
+
f"which is not supported for {self.__class__.__name__}. "
|
| 298 |
+
f"Try another generation strategy instead. "
|
| 299 |
+
f"For the available generation strategies, check this doc: "
|
| 300 |
+
f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
|
| 301 |
+
)
|
| 302 |
+
else:
|
| 303 |
+
raise exception
|
| 304 |
+
|
| 305 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 306 |
+
def forward(
|
| 307 |
+
self,
|
| 308 |
+
input_ids: torch.LongTensor = None,
|
| 309 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 310 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 311 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 312 |
+
labels: Optional[torch.LongTensor] = None,
|
| 313 |
+
use_cache: Optional[bool] = None,
|
| 314 |
+
output_attentions: Optional[bool] = None,
|
| 315 |
+
output_hidden_states: Optional[bool] = None,
|
| 316 |
+
return_dict: Optional[bool] = None,
|
| 317 |
+
logits_to_keep: Optional[int] = 0,
|
| 318 |
+
**kwargs: Unpack[Dict]
|
| 319 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 320 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 321 |
+
output_hidden_states = (
|
| 322 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 323 |
+
)
|
| 324 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 325 |
+
|
| 326 |
+
outputs = self.model(
|
| 327 |
+
input_ids=input_ids,
|
| 328 |
+
attention_mask=attention_mask,
|
| 329 |
+
inputs_embeds=inputs_embeds,
|
| 330 |
+
past_key_values=past_key_values,
|
| 331 |
+
use_cache=use_cache,
|
| 332 |
+
output_attentions=output_attentions,
|
| 333 |
+
output_hidden_states=output_hidden_states,
|
| 334 |
+
return_dict=return_dict,
|
| 335 |
+
**kwargs
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
hidden_states = outputs[0]
|
| 339 |
+
|
| 340 |
+
loss, logits = None, None
|
| 341 |
+
if not self.config.fuse_linear_cross_entropy or labels is None:
|
| 342 |
+
logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
|
| 343 |
+
if labels is not None:
|
| 344 |
+
if getattr(self, 'criterion', None) is None:
|
| 345 |
+
if self.config.fuse_linear_cross_entropy:
|
| 346 |
+
criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
|
| 347 |
+
elif self.config.fuse_cross_entropy:
|
| 348 |
+
criterion = FusedCrossEntropyLoss(inplace_backward=True)
|
| 349 |
+
else:
|
| 350 |
+
criterion = nn.CrossEntropyLoss()
|
| 351 |
+
else:
|
| 352 |
+
criterion = self.criterion
|
| 353 |
+
labels = labels.to(hidden_states.device)
|
| 354 |
+
labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
|
| 355 |
+
if self.config.fuse_linear_cross_entropy:
|
| 356 |
+
loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
|
| 357 |
+
else:
|
| 358 |
+
loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
|
| 359 |
+
loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
|
| 360 |
+
|
| 361 |
+
if not return_dict:
|
| 362 |
+
output = (logits,) + outputs[1:]
|
| 363 |
+
return (loss,) + output if loss is not None else output
|
| 364 |
+
|
| 365 |
+
return CausalLMOutputWithPast(
|
| 366 |
+
loss=loss,
|
| 367 |
+
logits=logits,
|
| 368 |
+
past_key_values=outputs.past_key_values,
|
| 369 |
+
hidden_states=outputs.hidden_states,
|
| 370 |
+
attentions=outputs.attentions,
|
| 371 |
+
)
|
models/deltaformer/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
|
| 4 |
+
|
| 5 |
+
from fla.models.deltaformer.configuration_deltaformer import DeltaFormerConfig
|
| 6 |
+
from fla.models.deltaformer.modeling_deltaformer import DeltaFormerForCausalLM, DeltaFormerModel
|
| 7 |
+
|
| 8 |
+
AutoConfig.register(DeltaFormerConfig.model_type, DeltaFormerConfig, exist_ok=True)
|
| 9 |
+
AutoModel.register(DeltaFormerConfig, DeltaFormerModel, exist_ok=True)
|
| 10 |
+
AutoModelForCausalLM.register(DeltaFormerConfig, DeltaFormerForCausalLM, exist_ok=True)
|
| 11 |
+
|
| 12 |
+
__all__ = ['DeltaFormerConfig', 'DeltaFormerForCausalLM', 'DeltaFormerModel']
|
models/deltaformer/configuration_deltaformer.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import Dict, Optional
|
| 7 |
+
|
| 8 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DeltaFormerConfig(PretrainedConfig):
|
| 12 |
+
model_type = 'deltaformer'
|
| 13 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
hidden_size: int = 2048,
|
| 18 |
+
hidden_ratio: Optional[int] = 4,
|
| 19 |
+
intermediate_size: Optional[int] = None,
|
| 20 |
+
num_hidden_layers: int = 24,
|
| 21 |
+
num_heads: int = 8,
|
| 22 |
+
num_kv_heads: Optional[int] = None,
|
| 23 |
+
attn_mode: str = "chunk",
|
| 24 |
+
hidden_act: str = "swish",
|
| 25 |
+
max_position_embeddings: int = 2048,
|
| 26 |
+
elementwise_affine: Optional[bool] = True,
|
| 27 |
+
norm_eps: float = 1e-6,
|
| 28 |
+
qkv_bias: bool = False,
|
| 29 |
+
qk_norm: bool = False,
|
| 30 |
+
rope_theta: float = 10000.,
|
| 31 |
+
rope_max_position_embeddings: Optional[int] = None,
|
| 32 |
+
attn: Optional[Dict] = None,
|
| 33 |
+
use_cache: bool = True,
|
| 34 |
+
pad_token_id: Optional[int] = None,
|
| 35 |
+
bos_token_id: int = 1,
|
| 36 |
+
eos_token_id: int = 2,
|
| 37 |
+
tie_word_embeddings: bool = False,
|
| 38 |
+
initializer_range: float = 0.02,
|
| 39 |
+
fuse_norm: bool = True,
|
| 40 |
+
fuse_swiglu: bool = True,
|
| 41 |
+
fuse_cross_entropy: bool = True,
|
| 42 |
+
fuse_linear_cross_entropy: bool = False,
|
| 43 |
+
use_l2warp: bool = False,
|
| 44 |
+
vocab_size: int = 32000,
|
| 45 |
+
output_attentions: bool = False,
|
| 46 |
+
output_hidden_states: bool = False,
|
| 47 |
+
**kwargs
|
| 48 |
+
):
|
| 49 |
+
self.hidden_size = hidden_size
|
| 50 |
+
self.hidden_ratio = hidden_ratio
|
| 51 |
+
self.intermediate_size = intermediate_size
|
| 52 |
+
self.num_hidden_layers = num_hidden_layers
|
| 53 |
+
self.num_heads = num_heads
|
| 54 |
+
self.num_kv_heads = num_kv_heads
|
| 55 |
+
self.attn_mode = attn_mode
|
| 56 |
+
self.hidden_act = hidden_act
|
| 57 |
+
self.max_position_embeddings = max_position_embeddings
|
| 58 |
+
self.elementwise_affine = elementwise_affine
|
| 59 |
+
self.norm_eps = norm_eps
|
| 60 |
+
self.qkv_bias = qkv_bias
|
| 61 |
+
self.qk_norm = qk_norm
|
| 62 |
+
self.rope_theta = rope_theta
|
| 63 |
+
self.rope_max_position_embeddings = rope_max_position_embeddings
|
| 64 |
+
self.attn = attn
|
| 65 |
+
self.use_cache = use_cache
|
| 66 |
+
self.initializer_range = initializer_range
|
| 67 |
+
|
| 68 |
+
self.fuse_norm = fuse_norm
|
| 69 |
+
self.fuse_swiglu = fuse_swiglu
|
| 70 |
+
self.fuse_cross_entropy = fuse_cross_entropy
|
| 71 |
+
self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
|
| 72 |
+
self.use_l2warp = use_l2warp
|
| 73 |
+
self.vocab_size = vocab_size
|
| 74 |
+
|
| 75 |
+
self.output_attentions = output_attentions
|
| 76 |
+
self.output_hidden_states = output_hidden_states
|
| 77 |
+
|
| 78 |
+
if fuse_cross_entropy and fuse_linear_cross_entropy:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
|
| 81 |
+
)
|
| 82 |
+
if fuse_linear_cross_entropy:
|
| 83 |
+
warnings.warn(
|
| 84 |
+
"`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
|
| 85 |
+
"at the potential cost of reduced precision. "
|
| 86 |
+
"If you observe issues like loss divergence, consider disabling this setting."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if attn is not None:
|
| 90 |
+
if not isinstance(attn, Dict):
|
| 91 |
+
raise ValueError("attn must be a dictionary")
|
| 92 |
+
if 'layers' not in attn:
|
| 93 |
+
raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
|
| 94 |
+
if 'num_heads' not in attn:
|
| 95 |
+
raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
|
| 96 |
+
attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
|
| 97 |
+
attn['qkv_bias'] = attn.get('qkv_bias', False)
|
| 98 |
+
attn['window_size'] = attn.get('window_size', None)
|
| 99 |
+
attn['rope_theta'] = attn.get('rope_theta', 10000.)
|
| 100 |
+
|
| 101 |
+
super().__init__(
|
| 102 |
+
pad_token_id=pad_token_id,
|
| 103 |
+
bos_token_id=bos_token_id,
|
| 104 |
+
eos_token_id=eos_token_id,
|
| 105 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 106 |
+
**kwargs,
|
| 107 |
+
)
|
models/deltaformer/modeling_deltaformer.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 11 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 14 |
+
|
| 15 |
+
from fla.layers.deltaformer import DeltaFormerAttention
|
| 16 |
+
from fla.models.deltaformer.configuration_deltaformer import DeltaFormerConfig
|
| 17 |
+
from fla.models.utils import Cache, FLAGenerationMixin
|
| 18 |
+
from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
|
| 19 |
+
from fla.modules import GatedMLP as DeltaFormerMLP
|
| 20 |
+
from fla.modules import RMSNorm
|
| 21 |
+
from fla.modules.l2warp import l2_warp
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 25 |
+
except ImportError:
|
| 26 |
+
from fla.models.modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
if TYPE_CHECKING:
|
| 31 |
+
from transformers.processing_utils import Unpack
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class DeltaFormerBlock(GradientCheckpointingLayer):
|
| 35 |
+
|
| 36 |
+
def __init__(self, config: DeltaFormerConfig, layer_idx: int):
|
| 37 |
+
super().__init__()
|
| 38 |
+
|
| 39 |
+
self.config = config
|
| 40 |
+
self.layer_idx = layer_idx
|
| 41 |
+
|
| 42 |
+
self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 43 |
+
self.attn = DeltaFormerAttention(
|
| 44 |
+
hidden_size=config.hidden_size,
|
| 45 |
+
num_heads=config.num_heads,
|
| 46 |
+
num_kv_heads=config.num_kv_heads,
|
| 47 |
+
qkv_bias=config.qkv_bias,
|
| 48 |
+
qk_norm=config.qk_norm,
|
| 49 |
+
rope_theta=config.rope_theta,
|
| 50 |
+
max_position_embeddings=config.rope_max_position_embeddings,
|
| 51 |
+
layer_idx=layer_idx,
|
| 52 |
+
)
|
| 53 |
+
self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 54 |
+
self.mlp = DeltaFormerMLP(
|
| 55 |
+
hidden_size=config.hidden_size,
|
| 56 |
+
hidden_ratio=config.hidden_ratio,
|
| 57 |
+
intermediate_size=config.intermediate_size,
|
| 58 |
+
hidden_act=config.hidden_act,
|
| 59 |
+
fuse_swiglu=config.fuse_swiglu
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def forward(
|
| 63 |
+
self,
|
| 64 |
+
hidden_states: torch.Tensor,
|
| 65 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 66 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 67 |
+
use_cache: Optional[bool] = False,
|
| 68 |
+
output_attentions: Optional[bool] = False,
|
| 69 |
+
**kwargs: Unpack[Dict]
|
| 70 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 71 |
+
residual = hidden_states
|
| 72 |
+
hidden_states = self.attn_norm(hidden_states)
|
| 73 |
+
hidden_states, _, past_key_values = self.attn(
|
| 74 |
+
hidden_states=hidden_states,
|
| 75 |
+
attention_mask=attention_mask,
|
| 76 |
+
past_key_values=past_key_values,
|
| 77 |
+
use_cache=use_cache,
|
| 78 |
+
output_attentions=output_attentions,
|
| 79 |
+
**kwargs,
|
| 80 |
+
)
|
| 81 |
+
if self.config.fuse_norm:
|
| 82 |
+
hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
|
| 83 |
+
else:
|
| 84 |
+
hidden_states = residual + hidden_states
|
| 85 |
+
residual = hidden_states
|
| 86 |
+
hidden_states = self.mlp_norm(hidden_states)
|
| 87 |
+
hidden_states = self.mlp(hidden_states, **kwargs)
|
| 88 |
+
hidden_states = residual + hidden_states
|
| 89 |
+
outputs = (hidden_states, None, past_key_values)
|
| 90 |
+
return outputs
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class DeltaFormerPreTrainedModel(PreTrainedModel):
|
| 94 |
+
|
| 95 |
+
config_class = DeltaFormerConfig
|
| 96 |
+
base_model_prefix = 'model'
|
| 97 |
+
supports_gradient_checkpointing = True
|
| 98 |
+
_no_split_modules = ['DeltaFormerBlock']
|
| 99 |
+
_supports_cache_class = True
|
| 100 |
+
|
| 101 |
+
def __init__(self, *inputs, **kwargs):
|
| 102 |
+
super().__init__(*inputs, **kwargs)
|
| 103 |
+
|
| 104 |
+
def _init_weights(
|
| 105 |
+
self,
|
| 106 |
+
module: nn.Module,
|
| 107 |
+
prenorm_residual_strategy: Optional[str] = None,
|
| 108 |
+
num_residuals_per_layer: int = 2,
|
| 109 |
+
):
|
| 110 |
+
if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 111 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 112 |
+
if module.bias is not None:
|
| 113 |
+
nn.init.zeros_(module.bias)
|
| 114 |
+
elif isinstance(module, nn.Embedding):
|
| 115 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 116 |
+
elif hasattr(module, 'reset_parameters'):
|
| 117 |
+
module.reset_parameters()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class DeltaFormerModel(DeltaFormerPreTrainedModel):
|
| 121 |
+
|
| 122 |
+
def __init__(self, config: DeltaFormerConfig):
|
| 123 |
+
super().__init__(config)
|
| 124 |
+
self.padding_idx = config.pad_token_id
|
| 125 |
+
self.vocab_size = config.vocab_size
|
| 126 |
+
|
| 127 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 128 |
+
self.layers = nn.ModuleList([DeltaFormerBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 129 |
+
self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 130 |
+
|
| 131 |
+
self.gradient_checkpointing = False
|
| 132 |
+
|
| 133 |
+
self.post_init()
|
| 134 |
+
|
| 135 |
+
def get_input_embeddings(self):
|
| 136 |
+
return self.embeddings
|
| 137 |
+
|
| 138 |
+
def set_input_embeddings(self, value):
|
| 139 |
+
self.embeddings = value
|
| 140 |
+
|
| 141 |
+
def forward(
|
| 142 |
+
self,
|
| 143 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 144 |
+
attention_mask: Optional[torch.Tensor] = None, # noqa
|
| 145 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 146 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 147 |
+
use_cache: Optional[bool] = None,
|
| 148 |
+
output_attentions: Optional[bool] = None,
|
| 149 |
+
output_hidden_states: Optional[bool] = None,
|
| 150 |
+
return_dict: Optional[bool] = None,
|
| 151 |
+
**kwargs: Unpack[Dict]
|
| 152 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 153 |
+
if output_attentions:
|
| 154 |
+
warnings.warn(
|
| 155 |
+
"`DeltaFormerModel` does not support output attention weights now, "
|
| 156 |
+
"so `output_attentions` is set to `False`."
|
| 157 |
+
)
|
| 158 |
+
output_attentions = False
|
| 159 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 160 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 161 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 162 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 163 |
+
|
| 164 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 165 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 166 |
+
if input_ids is None and inputs_embeds is None:
|
| 167 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 168 |
+
|
| 169 |
+
if inputs_embeds is None:
|
| 170 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 171 |
+
hidden_states = inputs_embeds
|
| 172 |
+
|
| 173 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
| 174 |
+
past_key_values = Cache.from_legacy_cache(past_key_values)
|
| 175 |
+
|
| 176 |
+
all_hidden_states = () if output_hidden_states else None
|
| 177 |
+
all_attns = () if output_attentions else None
|
| 178 |
+
for layer in self.layers:
|
| 179 |
+
if output_hidden_states:
|
| 180 |
+
all_hidden_states += (hidden_states,)
|
| 181 |
+
|
| 182 |
+
hidden_states, attentions, past_key_values = layer(
|
| 183 |
+
hidden_states,
|
| 184 |
+
attention_mask=attention_mask,
|
| 185 |
+
past_key_values=past_key_values,
|
| 186 |
+
use_cache=use_cache,
|
| 187 |
+
output_attentions=output_attentions,
|
| 188 |
+
**kwargs
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if output_attentions:
|
| 192 |
+
all_attns += (attentions,)
|
| 193 |
+
|
| 194 |
+
hidden_states = self.norm(hidden_states)
|
| 195 |
+
|
| 196 |
+
if output_hidden_states:
|
| 197 |
+
all_hidden_states += (hidden_states,)
|
| 198 |
+
|
| 199 |
+
if not return_dict:
|
| 200 |
+
return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
|
| 201 |
+
return BaseModelOutputWithPast(
|
| 202 |
+
last_hidden_state=hidden_states,
|
| 203 |
+
past_key_values=past_key_values,
|
| 204 |
+
hidden_states=all_hidden_states,
|
| 205 |
+
attentions=all_attns
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class DeltaFormerForCausalLM(DeltaFormerPreTrainedModel, FLAGenerationMixin):
|
| 210 |
+
|
| 211 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 212 |
+
|
| 213 |
+
def __init__(self, config: DeltaFormerConfig):
|
| 214 |
+
super().__init__(config)
|
| 215 |
+
self.model = DeltaFormerModel(config)
|
| 216 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 217 |
+
self.criterion = None
|
| 218 |
+
|
| 219 |
+
self.post_init()
|
| 220 |
+
|
| 221 |
+
def get_input_embeddings(self):
|
| 222 |
+
return self.model.get_input_embeddings()
|
| 223 |
+
|
| 224 |
+
def set_input_embeddings(self, value):
|
| 225 |
+
self.model.set_input_embeddings(value)
|
| 226 |
+
|
| 227 |
+
def tie_weights(self):
|
| 228 |
+
self._tie_or_clone_weights(self.lm_head, self.get_input_embeddings())
|
| 229 |
+
|
| 230 |
+
def get_output_embeddings(self):
|
| 231 |
+
return self.lm_head
|
| 232 |
+
|
| 233 |
+
def set_output_embeddings(self, new_embeddings):
|
| 234 |
+
self.lm_head = new_embeddings
|
| 235 |
+
|
| 236 |
+
def set_decoder(self, decoder):
|
| 237 |
+
self.model = decoder
|
| 238 |
+
|
| 239 |
+
def get_decoder(self):
|
| 240 |
+
return self.model
|
| 241 |
+
|
| 242 |
+
def generate(self, *args, **kwargs):
|
| 243 |
+
try:
|
| 244 |
+
return super().generate(*args, **kwargs)
|
| 245 |
+
except AttributeError as exception:
|
| 246 |
+
if 'past_key_values' in str(exception):
|
| 247 |
+
raise AttributeError(
|
| 248 |
+
f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
|
| 249 |
+
f"which is not supported for {self.__class__.__name__}. "
|
| 250 |
+
f"Try another generation strategy instead. "
|
| 251 |
+
f"For the available generation strategies, check this doc: "
|
| 252 |
+
f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
|
| 253 |
+
)
|
| 254 |
+
else:
|
| 255 |
+
raise exception
|
| 256 |
+
|
| 257 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 258 |
+
def forward(
|
| 259 |
+
self,
|
| 260 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 261 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 262 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 263 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 264 |
+
use_cache: Optional[bool] = None,
|
| 265 |
+
output_attentions: Optional[bool] = None,
|
| 266 |
+
output_hidden_states: Optional[bool] = None,
|
| 267 |
+
return_dict: Optional[bool] = None,
|
| 268 |
+
labels: Optional[torch.LongTensor] = None,
|
| 269 |
+
logits_to_keep: Optional[int] = 0,
|
| 270 |
+
**kwargs: Unpack[Dict]
|
| 271 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 272 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 273 |
+
|
| 274 |
+
outputs = self.model(
|
| 275 |
+
input_ids=input_ids,
|
| 276 |
+
attention_mask=attention_mask,
|
| 277 |
+
inputs_embeds=inputs_embeds,
|
| 278 |
+
past_key_values=past_key_values,
|
| 279 |
+
use_cache=use_cache,
|
| 280 |
+
output_attentions=output_attentions,
|
| 281 |
+
output_hidden_states=output_hidden_states,
|
| 282 |
+
return_dict=return_dict,
|
| 283 |
+
**kwargs
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
hidden_states = outputs[0]
|
| 287 |
+
# For fused linear cross-entropy we do not materialize logits for the full sequence
|
| 288 |
+
logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:])
|
| 289 |
+
|
| 290 |
+
loss = None
|
| 291 |
+
if labels is not None:
|
| 292 |
+
if getattr(self, 'criterion', None) is None:
|
| 293 |
+
if self.config.fuse_linear_cross_entropy:
|
| 294 |
+
criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
|
| 295 |
+
elif self.config.fuse_cross_entropy:
|
| 296 |
+
criterion = FusedCrossEntropyLoss(inplace_backward=True)
|
| 297 |
+
else:
|
| 298 |
+
criterion = nn.CrossEntropyLoss()
|
| 299 |
+
else:
|
| 300 |
+
criterion = self.criterion
|
| 301 |
+
labels = labels.to(hidden_states.device)
|
| 302 |
+
labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
|
| 303 |
+
if self.config.fuse_linear_cross_entropy:
|
| 304 |
+
loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
|
| 305 |
+
else:
|
| 306 |
+
loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
|
| 307 |
+
loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
|
| 308 |
+
|
| 309 |
+
if not return_dict:
|
| 310 |
+
output = (logits,) + outputs[1:]
|
| 311 |
+
return ((loss,) + output) if loss is not None else output
|
| 312 |
+
return CausalLMOutputWithPast(
|
| 313 |
+
loss=loss,
|
| 314 |
+
logits=logits,
|
| 315 |
+
past_key_values=outputs.past_key_values,
|
| 316 |
+
hidden_states=outputs.hidden_states,
|
| 317 |
+
attentions=outputs.attentions,
|
| 318 |
+
)
|
models/forgetting_transformer/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
|
| 4 |
+
|
| 5 |
+
from fla.models.forgetting_transformer.configuration_forgetting_transformer import ForgettingTransformerConfig
|
| 6 |
+
from fla.models.forgetting_transformer.modeling_forgetting_transformer import (
|
| 7 |
+
ForgettingTransformerForCausalLM,
|
| 8 |
+
ForgettingTransformerModel
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
AutoConfig.register(ForgettingTransformerConfig.model_type, ForgettingTransformerConfig, exist_ok=True)
|
| 12 |
+
AutoModel.register(ForgettingTransformerConfig, ForgettingTransformerModel, exist_ok=True)
|
| 13 |
+
AutoModelForCausalLM.register(ForgettingTransformerConfig, ForgettingTransformerForCausalLM, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = ['ForgettingTransformerConfig', 'ForgettingTransformerForCausalLM', 'ForgettingTransformerModel']
|
models/forgetting_transformer/modeling_forgetting_transformer.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 5 |
+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 12 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 13 |
+
from transformers.utils import logging
|
| 14 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 15 |
+
|
| 16 |
+
from fla.layers.forgetting_attn import ForgettingAttention
|
| 17 |
+
from fla.models.forgetting_transformer.configuration_forgetting_transformer import ForgettingTransformerConfig
|
| 18 |
+
from fla.models.utils import Cache, FLAGenerationMixin
|
| 19 |
+
from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
|
| 20 |
+
from fla.modules import GatedMLP as ForgettingTransformerMLP
|
| 21 |
+
from fla.modules import RMSNorm
|
| 22 |
+
from fla.modules.l2warp import l2_warp
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from transformers.processing_utils import Unpack
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 30 |
+
except ImportError:
|
| 31 |
+
from fla.models.modeling_layers import GradientCheckpointingLayer
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ForgettingTransformerBlock(GradientCheckpointingLayer):
|
| 37 |
+
|
| 38 |
+
def __init__(self, config: ForgettingTransformerConfig, layer_idx: int):
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
self.config = config
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
|
| 44 |
+
self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 45 |
+
self.attn = ForgettingAttention(
|
| 46 |
+
hidden_size=config.hidden_size,
|
| 47 |
+
num_heads=config.num_heads,
|
| 48 |
+
num_kv_heads=config.num_kv_heads,
|
| 49 |
+
qkv_bias=config.qkv_bias,
|
| 50 |
+
qk_norm=config.qk_norm,
|
| 51 |
+
window_size=config.window_size,
|
| 52 |
+
use_output_gate=config.use_output_gate,
|
| 53 |
+
layer_idx=layer_idx
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 57 |
+
self.mlp = ForgettingTransformerMLP(
|
| 58 |
+
hidden_size=config.hidden_size,
|
| 59 |
+
hidden_ratio=config.hidden_ratio,
|
| 60 |
+
intermediate_size=config.intermediate_size,
|
| 61 |
+
hidden_act=config.hidden_act,
|
| 62 |
+
fuse_swiglu=config.fuse_swiglu
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def forward(
|
| 66 |
+
self,
|
| 67 |
+
hidden_states: torch.Tensor,
|
| 68 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 69 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
| 70 |
+
output_attentions: Optional[bool] = False,
|
| 71 |
+
use_cache: Optional[bool] = False,
|
| 72 |
+
**kwargs: Unpack[Any]
|
| 73 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 74 |
+
|
| 75 |
+
residual = hidden_states
|
| 76 |
+
hidden_states = self.attn_norm(hidden_states)
|
| 77 |
+
hidden_states, attentions, past_key_values = self.attn(
|
| 78 |
+
hidden_states=hidden_states,
|
| 79 |
+
attention_mask=attention_mask,
|
| 80 |
+
past_key_values=past_key_values,
|
| 81 |
+
use_cache=use_cache,
|
| 82 |
+
output_attentions=output_attentions,
|
| 83 |
+
**kwargs
|
| 84 |
+
)
|
| 85 |
+
if self.config.fuse_norm:
|
| 86 |
+
hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
|
| 87 |
+
else:
|
| 88 |
+
hidden_states = residual + hidden_states
|
| 89 |
+
residual = hidden_states
|
| 90 |
+
hidden_states = self.mlp_norm(hidden_states)
|
| 91 |
+
hidden_states = self.mlp(hidden_states, **kwargs)
|
| 92 |
+
hidden_states = residual + hidden_states
|
| 93 |
+
|
| 94 |
+
outputs = (hidden_states,)
|
| 95 |
+
|
| 96 |
+
if output_attentions:
|
| 97 |
+
outputs += (attentions,)
|
| 98 |
+
|
| 99 |
+
if use_cache:
|
| 100 |
+
outputs += (past_key_values,)
|
| 101 |
+
|
| 102 |
+
return outputs
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class ForgettingTransformerPreTrainedModel(PreTrainedModel):
|
| 106 |
+
|
| 107 |
+
config_class = ForgettingTransformerConfig
|
| 108 |
+
base_model_prefix = 'model'
|
| 109 |
+
supports_gradient_checkpointing = True
|
| 110 |
+
_no_split_modules = ['ForgettingTransformerBlock']
|
| 111 |
+
_supports_cache_class = True
|
| 112 |
+
|
| 113 |
+
def __init__(self, *inputs, **kwargs):
|
| 114 |
+
super().__init__(*inputs, **kwargs)
|
| 115 |
+
|
| 116 |
+
def _init_weights(
|
| 117 |
+
self,
|
| 118 |
+
module: nn.Module,
|
| 119 |
+
rescale_prenorm_residual: bool = False,
|
| 120 |
+
num_residuals_per_layer: int = 2,
|
| 121 |
+
):
|
| 122 |
+
if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 123 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 124 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 125 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 126 |
+
if module.bias is not None:
|
| 127 |
+
nn.init.zeros_(module.bias)
|
| 128 |
+
elif isinstance(module, nn.Embedding):
|
| 129 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 130 |
+
elif hasattr(module, 'reset_parameters'):
|
| 131 |
+
module.reset_parameters()
|
| 132 |
+
|
| 133 |
+
if rescale_prenorm_residual:
|
| 134 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 135 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 136 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 137 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 138 |
+
#
|
| 139 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 140 |
+
p = None
|
| 141 |
+
if hasattr(module, 'o_proj'):
|
| 142 |
+
p = module.o_proj.weight
|
| 143 |
+
elif hasattr(module, 'down_proj'):
|
| 144 |
+
p = module.down_proj.weight
|
| 145 |
+
if p is not None:
|
| 146 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per ForgettingTransformer Block
|
| 147 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 148 |
+
# We need to reinit p since this code could be called multiple times
|
| 149 |
+
# Having just p *= scale would repeatedly scale it down
|
| 150 |
+
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 151 |
+
with torch.no_grad():
|
| 152 |
+
p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class ForgettingTransformerModel(ForgettingTransformerPreTrainedModel):
|
| 156 |
+
|
| 157 |
+
def __init__(
|
| 158 |
+
self,
|
| 159 |
+
config: ForgettingTransformerConfig
|
| 160 |
+
) -> ForgettingTransformerModel:
|
| 161 |
+
super().__init__(config)
|
| 162 |
+
self.padding_idx = config.pad_token_id
|
| 163 |
+
self.vocab_size = config.vocab_size
|
| 164 |
+
|
| 165 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 166 |
+
self.layers = nn.ModuleList([
|
| 167 |
+
ForgettingTransformerBlock(config, layer_idx)
|
| 168 |
+
for layer_idx in range(config.num_hidden_layers)
|
| 169 |
+
])
|
| 170 |
+
self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
|
| 171 |
+
|
| 172 |
+
self.gradient_checkpointing = False
|
| 173 |
+
|
| 174 |
+
self.post_init()
|
| 175 |
+
|
| 176 |
+
def get_input_embeddings(self):
|
| 177 |
+
return self.embeddings
|
| 178 |
+
|
| 179 |
+
def set_input_embeddings(self, value):
|
| 180 |
+
self.embeddings = value
|
| 181 |
+
|
| 182 |
+
def forward(
|
| 183 |
+
self,
|
| 184 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 185 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 186 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 187 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 188 |
+
use_cache: Optional[bool] = None,
|
| 189 |
+
output_attentions: Optional[bool] = None,
|
| 190 |
+
output_hidden_states: Optional[bool] = None,
|
| 191 |
+
return_dict: Optional[bool] = None,
|
| 192 |
+
**kwargs: Unpack[Any]
|
| 193 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 194 |
+
if output_attentions:
|
| 195 |
+
warnings.warn(
|
| 196 |
+
"`ForgettingTransformerModel` does not support output attention weights now, "
|
| 197 |
+
"so `output_attentions` is set to `False`."
|
| 198 |
+
)
|
| 199 |
+
output_attentions = False
|
| 200 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 201 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 202 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 203 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 204 |
+
|
| 205 |
+
# retrieve input_ids and inputs_embeds
|
| 206 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 207 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 208 |
+
elif input_ids is None and inputs_embeds is None:
|
| 209 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 210 |
+
|
| 211 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
| 212 |
+
past_key_values = Cache.from_legacy_cache(past_key_values)
|
| 213 |
+
|
| 214 |
+
if inputs_embeds is None:
|
| 215 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 216 |
+
|
| 217 |
+
# embed positions
|
| 218 |
+
hidden_states = inputs_embeds
|
| 219 |
+
|
| 220 |
+
all_hidden_states = () if output_hidden_states else None
|
| 221 |
+
all_attns = () if output_attentions else None
|
| 222 |
+
next_cache = None
|
| 223 |
+
|
| 224 |
+
for layer in self.layers:
|
| 225 |
+
if output_hidden_states:
|
| 226 |
+
all_hidden_states += (hidden_states,)
|
| 227 |
+
|
| 228 |
+
layer_outputs = layer(
|
| 229 |
+
hidden_states,
|
| 230 |
+
attention_mask=attention_mask,
|
| 231 |
+
past_key_values=past_key_values,
|
| 232 |
+
output_attentions=output_attentions,
|
| 233 |
+
use_cache=use_cache,
|
| 234 |
+
**kwargs
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
hidden_states = layer_outputs[0]
|
| 238 |
+
|
| 239 |
+
if use_cache:
|
| 240 |
+
next_cache = layer_outputs[2 if output_attentions else 1]
|
| 241 |
+
|
| 242 |
+
if output_attentions:
|
| 243 |
+
all_attns += (layer_outputs[1],)
|
| 244 |
+
|
| 245 |
+
hidden_states = self.norm(hidden_states)
|
| 246 |
+
|
| 247 |
+
# add hidden states from the last decoder layer
|
| 248 |
+
if output_hidden_states:
|
| 249 |
+
all_hidden_states += (hidden_states,)
|
| 250 |
+
|
| 251 |
+
if not return_dict:
|
| 252 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attns] if v is not None)
|
| 253 |
+
|
| 254 |
+
return BaseModelOutputWithPast(
|
| 255 |
+
last_hidden_state=hidden_states,
|
| 256 |
+
past_key_values=next_cache,
|
| 257 |
+
hidden_states=all_hidden_states,
|
| 258 |
+
attentions=all_attns
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class ForgettingTransformerForCausalLM(ForgettingTransformerPreTrainedModel, FLAGenerationMixin):
|
| 263 |
+
|
| 264 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 265 |
+
|
| 266 |
+
def __init__(self, config):
|
| 267 |
+
super().__init__(config)
|
| 268 |
+
self.model = ForgettingTransformerModel(config)
|
| 269 |
+
self.vocab_size = config.vocab_size
|
| 270 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 271 |
+
self.criterion = None
|
| 272 |
+
|
| 273 |
+
# Initialize weights and apply final processing
|
| 274 |
+
self.post_init()
|
| 275 |
+
|
| 276 |
+
def get_input_embeddings(self):
|
| 277 |
+
return self.model.embeddings
|
| 278 |
+
|
| 279 |
+
def set_input_embeddings(self, value):
|
| 280 |
+
self.model.embeddings = value
|
| 281 |
+
|
| 282 |
+
def get_output_embeddings(self):
|
| 283 |
+
return self.lm_head
|
| 284 |
+
|
| 285 |
+
def set_output_embeddings(self, new_embeddings):
|
| 286 |
+
self.lm_head = new_embeddings
|
| 287 |
+
|
| 288 |
+
def set_decoder(self, decoder):
|
| 289 |
+
self.model = decoder
|
| 290 |
+
|
| 291 |
+
def get_decoder(self):
|
| 292 |
+
return self.model
|
| 293 |
+
|
| 294 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 295 |
+
def forward(
|
| 296 |
+
self,
|
| 297 |
+
input_ids: torch.LongTensor = None,
|
| 298 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 299 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 300 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 301 |
+
labels: Optional[torch.LongTensor] = None,
|
| 302 |
+
use_cache: Optional[bool] = None,
|
| 303 |
+
output_attentions: Optional[bool] = None,
|
| 304 |
+
output_hidden_states: Optional[bool] = None,
|
| 305 |
+
return_dict: Optional[bool] = None,
|
| 306 |
+
logits_to_keep: Optional[int] = 0,
|
| 307 |
+
**kwargs: Unpack[Any]
|
| 308 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 309 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 310 |
+
output_hidden_states = (
|
| 311 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 312 |
+
)
|
| 313 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 314 |
+
|
| 315 |
+
outputs = self.model(
|
| 316 |
+
input_ids=input_ids,
|
| 317 |
+
attention_mask=attention_mask,
|
| 318 |
+
past_key_values=past_key_values,
|
| 319 |
+
inputs_embeds=inputs_embeds,
|
| 320 |
+
use_cache=use_cache,
|
| 321 |
+
output_attentions=output_attentions,
|
| 322 |
+
output_hidden_states=output_hidden_states,
|
| 323 |
+
return_dict=return_dict,
|
| 324 |
+
**kwargs
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
hidden_states = outputs[0]
|
| 328 |
+
|
| 329 |
+
logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:])
|
| 330 |
+
|
| 331 |
+
loss = None
|
| 332 |
+
if labels is not None:
|
| 333 |
+
if getattr(self, 'criterion', None) is None:
|
| 334 |
+
if self.config.fuse_linear_cross_entropy:
|
| 335 |
+
criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
|
| 336 |
+
elif self.config.fuse_cross_entropy:
|
| 337 |
+
criterion = FusedCrossEntropyLoss(inplace_backward=True)
|
| 338 |
+
else:
|
| 339 |
+
criterion = nn.CrossEntropyLoss()
|
| 340 |
+
else:
|
| 341 |
+
criterion = self.criterion
|
| 342 |
+
# Enable model parallelism
|
| 343 |
+
labels = labels.to(hidden_states.device)
|
| 344 |
+
labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
|
| 345 |
+
if self.config.fuse_linear_cross_entropy:
|
| 346 |
+
loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
|
| 347 |
+
else:
|
| 348 |
+
loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
|
| 349 |
+
loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
|
| 350 |
+
|
| 351 |
+
if not return_dict:
|
| 352 |
+
output = (logits,) + outputs[1:]
|
| 353 |
+
return (loss,) + output if loss is not None else output
|
| 354 |
+
|
| 355 |
+
return CausalLMOutputWithPast(
|
| 356 |
+
loss=loss,
|
| 357 |
+
logits=logits,
|
| 358 |
+
past_key_values=outputs.past_key_values,
|
| 359 |
+
hidden_states=outputs.hidden_states,
|
| 360 |
+
attentions=outputs.attentions,
|
| 361 |
+
)
|
models/gated_deltanet/configuration_gated_deltanet.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Dict, Optional
|
| 5 |
+
|
| 6 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
class GatedDeltaNetConfig(PretrainedConfig):
|
| 9 |
+
model_type = 'gated_deltanet'
|
| 10 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 11 |
+
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
attn_mode: str = "chunk",
|
| 15 |
+
hidden_size: int = 2048,
|
| 16 |
+
expand_v: float = 2.0,
|
| 17 |
+
use_gate: bool = True,
|
| 18 |
+
use_short_conv: bool = True,
|
| 19 |
+
allow_neg_eigval: bool = False,
|
| 20 |
+
conv_size: int = 4,
|
| 21 |
+
head_dim: int = 256,
|
| 22 |
+
num_heads: int = 6,
|
| 23 |
+
num_v_heads: Optional[int] = None,
|
| 24 |
+
max_position_embeddings: int = 2048,
|
| 25 |
+
hidden_ratio: Optional[int] = 4,
|
| 26 |
+
intermediate_size: Optional[int] = None,
|
| 27 |
+
hidden_act: str = "swish",
|
| 28 |
+
num_hidden_layers: int = 21,
|
| 29 |
+
norm_eps: float = 1e-6,
|
| 30 |
+
attn: Optional[Dict] = None,
|
| 31 |
+
use_cache: bool = True,
|
| 32 |
+
pad_token_id: Optional[int] = None,
|
| 33 |
+
bos_token_id: int = 1,
|
| 34 |
+
eos_token_id: int = 2,
|
| 35 |
+
tie_word_embeddings: bool = False,
|
| 36 |
+
initializer_range: float = 0.02,
|
| 37 |
+
fuse_norm: bool = True,
|
| 38 |
+
fuse_swiglu: bool = True,
|
| 39 |
+
fuse_cross_entropy: bool = True,
|
| 40 |
+
fuse_linear_cross_entropy: bool = False,
|
| 41 |
+
use_l2warp: bool = False,
|
| 42 |
+
vocab_size: int = 32000,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
self.attn_mode = attn_mode
|
| 46 |
+
self.hidden_size = hidden_size
|
| 47 |
+
self.expand_v = expand_v
|
| 48 |
+
self.use_gate = use_gate
|
| 49 |
+
self.use_short_conv = use_short_conv
|
| 50 |
+
self.conv_size = conv_size
|
| 51 |
+
self.head_dim = head_dim
|
| 52 |
+
self.num_heads = num_heads
|
| 53 |
+
self.num_v_heads = num_v_heads
|
| 54 |
+
self.max_position_embeddings = max_position_embeddings
|
| 55 |
+
|
| 56 |
+
self.hidden_ratio = hidden_ratio
|
| 57 |
+
self.intermediate_size = intermediate_size
|
| 58 |
+
self.hidden_act = hidden_act
|
| 59 |
+
self.num_hidden_layers = num_hidden_layers
|
| 60 |
+
self.norm_eps = norm_eps
|
| 61 |
+
self.attn = attn
|
| 62 |
+
self.use_cache = use_cache
|
| 63 |
+
self.initializer_range = initializer_range
|
| 64 |
+
|
| 65 |
+
self.fuse_norm = fuse_norm
|
| 66 |
+
self.fuse_swiglu = fuse_swiglu
|
| 67 |
+
self.fuse_cross_entropy = fuse_cross_entropy
|
| 68 |
+
self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
|
| 69 |
+
self.use_l2warp = use_l2warp
|
| 70 |
+
self.vocab_size = vocab_size
|
| 71 |
+
self.allow_neg_eigval = allow_neg_eigval
|
| 72 |
+
|
| 73 |
+
if fuse_cross_entropy and fuse_linear_cross_entropy:
|
| 74 |
+
raise ValueError(
|
| 75 |
+
"`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
|
| 76 |
+
)
|
| 77 |
+
if fuse_linear_cross_entropy:
|
| 78 |
+
warnings.warn(
|
| 79 |
+
"`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
|
| 80 |
+
"at the potential cost of reduced precision. "
|
| 81 |
+
"If you observe issues like loss divergence, consider disabling this setting."
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
if attn is not None:
|
| 85 |
+
if not isinstance(attn, Dict):
|
| 86 |
+
raise ValueError("attn must be a dictionary")
|
| 87 |
+
if 'layers' not in attn:
|
| 88 |
+
raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
|
| 89 |
+
if 'num_heads' not in attn:
|
| 90 |
+
raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
|
| 91 |
+
attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
|
| 92 |
+
attn['qkv_bias'] = attn.get('qkv_bias', False)
|
| 93 |
+
attn['window_size'] = attn.get('window_size', None)
|
| 94 |
+
attn['rope_theta'] = attn.get('rope_theta', 10000.)
|
| 95 |
+
|
| 96 |
+
super().__init__(
|
| 97 |
+
pad_token_id=pad_token_id,
|
| 98 |
+
bos_token_id=bos_token_id,
|
| 99 |
+
eos_token_id=eos_token_id,
|
| 100 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 101 |
+
**kwargs,
|
| 102 |
+
)
|