msj19 commited on
Commit
ddf3e26
·
verified ·
1 Parent(s): 3f589d5

Add files using upload-large-folder tool

Browse files
__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
+ # ]
__pycache__/__init__.cpython-312.pyc ADDED
Binary file (208 Bytes). View file
 
__pycache__/abc.cpython-312.pyc ADDED
Binary file (9.64 kB). View file
 
__pycache__/attn.cpython-310.pyc ADDED
Binary file (4.49 kB). View file
 
__pycache__/deltaformer.cpython-312.pyc ADDED
Binary file (7.4 kB). View file
 
__pycache__/linear_attn.cpython-312.pyc ADDED
Binary file (7.48 kB). View file
 
__pycache__/mamba.cpython-312.pyc ADDED
Binary file (15.4 kB). View file
 
__pycache__/mesa_net.cpython-312.pyc ADDED
Binary file (10.2 kB). View file
 
__pycache__/path_attn.cpython-312.pyc ADDED
Binary file (10.8 kB). View file
 
__pycache__/rebased.cpython-312.pyc ADDED
Binary file (6.76 kB). View file
 
__pycache__/rwkv6.cpython-312.pyc ADDED
Binary file (17.5 kB). View file
 
__pycache__/sigma_gka.cpython-312.pyc ADDED
Binary file (27.3 kB). View file
 
abc.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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
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
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)
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
comba.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.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(o)
329
+ if attention_mask is not None:
330
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
331
+
332
+ return o, None, past_key_values
delta_net.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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
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
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
gated_deltanet.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
gated_deltaproduct.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
gla.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # 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
log_linear_mamba2.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
mesa_net.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
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
path_test.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
rebased.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ """
5
+ https://github.com/corl-team/rebased/blob/main/flash_linear_attention/fla/layers/rebased_fast.py
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Optional
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from einops import rearrange
15
+
16
+ from fla.modules.feature_map import RebasedFeatureMap
17
+ from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn
18
+ from fla.ops.rebased import parallel_rebased
19
+
20
+
21
+ class ReBasedLinearAttention(nn.Module):
22
+
23
+ def __init__(
24
+ self,
25
+ hidden_size: int,
26
+ l_max: int = 2048,
27
+ feature_dim: int = 16,
28
+ num_key_value_heads: int = 16,
29
+ num_heads: int = 16,
30
+ use_gamma: Optional[bool] = True,
31
+ use_beta: Optional[bool] = True,
32
+ normalize: Optional[bool] = True,
33
+ causal: bool = True,
34
+ eps: float = 1e-5,
35
+ mode: str = "parallel",
36
+ layer_idx: Optional[int] = None,
37
+ **kwargs
38
+ ) -> ReBasedLinearAttention:
39
+ super().__init__()
40
+ self.hidden_size = hidden_size
41
+ self.l_max = l_max
42
+ self.mode = mode
43
+ assert self.mode in ["fused_chunk", "parallel", 'chunk']
44
+
45
+ self.feature_dim = feature_dim
46
+ self.num_key_value_heads = num_key_value_heads
47
+ self.num_heads = num_heads
48
+ self.head_dim = self.hidden_size // self.num_key_value_heads
49
+ self.use_gamma = use_gamma
50
+ self.use_beta = use_beta
51
+ self.normalize = normalize
52
+ self.causal = causal
53
+ self.eps = eps
54
+ self.mode = mode
55
+ self.layer_idx = layer_idx
56
+
57
+ self.feature_map = RebasedFeatureMap(self.feature_dim, use_gamma, use_beta, normalize)
58
+ self.q_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
59
+ self.k_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
60
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
61
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
62
+ self.dropout = nn.Identity()
63
+
64
+ def forward(self, hidden_states: torch.Tensor, **kwargs):
65
+ mode = self.mode
66
+ q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
67
+ q, k, v = map(lambda x: rearrange(x, "... (h d) -> ... h d", d=self.head_dim), [q, k, v])
68
+ q, k = self.feature_map(q, flatten=(mode != 'parallel')), self.feature_map(k, flatten=(mode != 'parallel'))
69
+ if mode == "fused_chunk":
70
+ o = fused_chunk_linear_attn(
71
+ q=q,
72
+ k=k,
73
+ v=v,
74
+ normalize=True,
75
+ scale=1,
76
+ )
77
+ elif mode == 'chunk':
78
+ o = chunk_linear_attn(
79
+ q=q,
80
+ k=k,
81
+ v=v,
82
+ normalize=True,
83
+ scale=1,
84
+ )
85
+ elif mode == 'parallel':
86
+ assert q.shape[-1] <= 128
87
+ o = parallel_rebased(
88
+ q=q,
89
+ k=k,
90
+ v=v,
91
+ eps=self.eps,
92
+ use_scale=True,
93
+ use_normalize=True,
94
+ )
95
+ o = self.o_proj(o)
96
+ o = self.dropout(o)
97
+ return o
98
+
99
+ # https://github.com/HazyResearch/zoology/blob/main/zoology/mixers/based.py#L119
100
+ def forward_reference(
101
+ self,
102
+ hidden_states: torch.Tensor,
103
+ filters: torch.Tensor = None,
104
+ *args,
105
+ **kwargs
106
+ ):
107
+ """
108
+ x (torch.Tensor): tensor of shape (b, d, t)
109
+ y (torch.Tensor): tensor of shape (b, d, t)
110
+ """
111
+ b, t, _ = hidden_states.size()
112
+ q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
113
+
114
+ q = q.view(b, t, -1, self.feature_dim).transpose(1, 2)
115
+ k = k.view(b, t, -1, self.feature_dim).transpose(1, 2)
116
+ v = v.view(b, t, -1, self.head_dim).transpose(1, 2)
117
+
118
+ # Linear attention
119
+ q, k = self.feature_map(q), self.feature_map(k)
120
+ q, k, v = q.unsqueeze(-2), k.unsqueeze(-2), v.unsqueeze(-1)
121
+
122
+ # Compute attention
123
+ if self.causal:
124
+ y = ((q * (k * v).cumsum(2)).sum(-1) / ((q * k.cumsum(2)).sum(-1) + self.eps))
125
+ else:
126
+ y = ((q * (k * v).sum(2, True)).sum(-1) / ((q * k.sum(2, True)).sum(-1) + self.eps))
127
+ y = rearrange(y, 'b h t d -> b t (h d)')
128
+ y = self.o_proj(y.to(hidden_states.dtype))
129
+ y = self.dropout(y)
130
+ return y.to(hidden_states.dtype)
state_org.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # 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 ..ops.state_org import chunk_state_org, fused_chunk_state_org, fused_recurrent_state_org
18
+ from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
19
+ if TYPE_CHECKING:
20
+ from transformers.processing_utils import Unpack
21
+
22
+ from fla.models.utils import Cache
23
+
24
+
25
+ class StateOrg(nn.Module):
26
+ r"""
27
+ The layer implementaion for [Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635). # noqa
28
+
29
+ Args:
30
+ mode (str, Optional):
31
+ Which GLA kernel to use.
32
+ Currently available: `chunk`, `fused_recurrent`, 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: 0.5.
38
+ expand_v (float, Optional):
39
+ The expansion ratio for the value dim. Default: 1.0.
40
+ num_heads (int, Optional):
41
+ The number of heads. Default: 4.
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
+ gate_logit_normalizer (int, Optional):
61
+ The normalizer for the gate logits, appied after `logsigmoid`. Default: 16.
62
+ gate_low_rank_dim (int, Optional):
63
+ The low rank dim for the gate projection. Default: 16.
64
+ clamp_min (float, Optional):
65
+ The minimum value for the gate logits. Default: None.
66
+ fuse_norm (bool, Optional):
67
+ Whether to fuse the norm and the output gate for better memory footprint. Default: `True`.
68
+ layer_idx (int, Optional):
69
+ The index of the layer. Default: None.
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ mode: str = 'chunk',
75
+ hidden_size: int = 1024,
76
+ expand_k: float = 0.5,
77
+ expand_v: float = 1.0,
78
+ num_heads: int = 4,
79
+ num_kv_heads: Optional[int] = None,
80
+ feature_map: Optional[str] = None,
81
+ use_short_conv: bool = False,
82
+ conv_size: int = 4,
83
+ conv_bias: bool = False,
84
+ use_output_gate: bool = True,
85
+ gate_fn: str = 'swish',
86
+ elementwise_affine: Optional[bool] = True,
87
+ norm_eps: float = 1e-5,
88
+ gate_logit_normalizer: int = 16,
89
+ gate_low_rank_dim: int = 16,
90
+ clamp_min: Optional[float] = None,
91
+ fuse_norm: bool = True,
92
+ layer_idx: int = None,
93
+ ) -> StateOrg:
94
+ super().__init__()
95
+
96
+ self.mode = mode
97
+ self.hidden_size = hidden_size
98
+ self.expand_k = expand_k
99
+ self.expand_v = expand_v
100
+ self.num_heads = num_heads
101
+ self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
102
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
103
+ self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
104
+
105
+ self.use_short_conv = use_short_conv
106
+ self.conv_size = conv_size
107
+ self.conv_bias = conv_bias
108
+ self.use_output_gate = use_output_gate
109
+
110
+ self.key_dim = int(hidden_size * expand_k)
111
+ self.value_dim = int(hidden_size * expand_v)
112
+ self.key_dim_per_group = self.key_dim // self.num_kv_groups
113
+ self.value_dim_per_group = self.value_dim // self.num_kv_groups
114
+ self.clamp_min = clamp_min
115
+ self.layer_idx = layer_idx
116
+
117
+ assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`."
118
+ assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
119
+ assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
120
+
121
+ self.head_k_dim = self.key_dim // num_heads
122
+ self.head_v_dim = self.value_dim // num_heads
123
+
124
+ self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
125
+ self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
126
+ self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
127
+ if self.use_output_gate:
128
+ self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
129
+
130
+ if use_short_conv:
131
+ self.conv_size = conv_size
132
+ self.q_conv1d = ShortConvolution(
133
+ hidden_size=self.key_dim,
134
+ kernel_size=conv_size,
135
+ bias=conv_bias,
136
+ activation='silu',
137
+ )
138
+ self.k_conv1d = ShortConvolution(
139
+ hidden_size=self.key_dim_per_group,
140
+ kernel_size=conv_size,
141
+ bias=conv_bias,
142
+ activation='silu',
143
+ )
144
+ self.v_conv1d = ShortConvolution(
145
+ hidden_size=self.value_dim_per_group,
146
+ kernel_size=conv_size,
147
+ bias=conv_bias,
148
+ activation='silu',
149
+ )
150
+
151
+ self.gk_proj = nn.Sequential(nn.Linear(hidden_size, gate_low_rank_dim, bias=False),
152
+ nn.Linear(gate_low_rank_dim, self.key_dim_per_group, bias=True))
153
+ self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
154
+
155
+ if gate_fn == 'swish' and fuse_norm and use_output_gate:
156
+ self.g_norm_swish_gate = FusedRMSNormGated(
157
+ hidden_size=self.head_v_dim,
158
+ elementwise_affine=elementwise_affine,
159
+ eps=norm_eps
160
+ )
161
+ self.fuse_norm_and_gate = True
162
+ else:
163
+ self.fuse_norm_and_gate = False
164
+ self.g_norm = RMSNorm(
165
+ hidden_size=self.head_v_dim,
166
+ elementwise_affine=elementwise_affine,
167
+ eps=norm_eps
168
+ )
169
+ self.gate_fn = ACT2FN[gate_fn]
170
+
171
+ self.gate_logit_normalizer = gate_logit_normalizer
172
+ self.chunk_size = 128
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
+ ####input q, k, v, g, scale, initial_state, output_final_state, cu_seqlens
277
+ q,k,v,gk = map(lambda x: rearrange(x, 'b (n c) ...-> b n c ...', c=self.chunk_size), (q,k,v,gk))
278
+ o = []
279
+ for i in range(q.shape[1]):
280
+ o_i, recurrent_state = chunk_gla(
281
+ q=q[:, i],
282
+ k=k[:, i],
283
+ v=v[:, i],
284
+ g=gk[:, i],
285
+ initial_state=recurrent_state,
286
+ output_final_state=True,
287
+ cu_seqlens=None,
288
+ )
289
+ o.append(o_i)
290
+ #####为recurrent进行正则化操作###recurrent_state shape B,H,DK,DV
291
+ for j in range(recurrent_state.shape[1]):
292
+ if j == 0:###对state进行muon正则化
293
+ state = recurrent_state[j]
294
+ ###计算F范数
295
+ f_norm = ((state**2).sum(axis=(-2,-1),keepdim=True)+1e-20)**0.5
296
+ state = state / f_norm
297
+
298
+
299
+ if j == 1:###对state进行clip,remove占据小的特征值
300
+
301
+ recurrent_state = recurrent_state.contiguous()
302
+
303
+
304
+
305
+
306
+ o = torch.cat(o, dim=1)
307
+ if past_key_values is not None:
308
+ past_key_values.update(
309
+ recurrent_state=recurrent_state,
310
+ conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
311
+ layer_idx=self.layer_idx,
312
+ offset=q_len
313
+ )
314
+
315
+ if self.use_output_gate:
316
+ g = self.g_proj(hidden_states)
317
+ if self.fuse_norm_and_gate:
318
+ g = rearrange(g, '... (h d) -> ... h d', d=self.head_v_dim)
319
+ o = self.g_norm_swish_gate(o, g)
320
+ o = rearrange(o, '... h d -> ... (h d)')
321
+ else:
322
+ o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
323
+ o = o * self.gate_fn(g)
324
+ else:
325
+ o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
326
+ o = self.o_proj(o)
327
+ if attention_mask is not None:
328
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
329
+
330
+ return o, None, past_key_values