msj19 commited on
Commit
b64301c
·
verified ·
1 Parent(s): a428563

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. layers/rwkv7.py +347 -0
  2. layers/utils.py +197 -0
  3. models/hgrn/configuration_hgrn.py +97 -0
  4. models/hgrn/modeling_hgrn.py +376 -0
  5. models/hgrn2/__init__.py +13 -0
  6. models/hgrn2/configuration_hgrn2.py +107 -0
  7. models/lightnet/__init__.py +13 -0
  8. models/lightnet/configuration_lightnet.py +99 -0
  9. models/lightnet/modeling_lightnet.py +367 -0
  10. models/linear_attn/__init__.py +12 -0
  11. models/linear_attn/modeling_linear_attn.py +368 -0
  12. models/log_linear_mamba2/__init__.py +17 -0
  13. models/log_linear_mamba2/modeling_log_linear_mamba2.py +485 -0
  14. models/mamba/__init__.py +13 -0
  15. models/mamba/configuration_mamba.py +181 -0
  16. models/mamba/modeling_mamba.py +513 -0
  17. models/mamba2/__init__.py +13 -0
  18. models/mamba2/configuration_mamba2.py +182 -0
  19. models/mamba2/modeling_mamba2.py +513 -0
  20. models/mask_gdn/__init__.py +12 -0
  21. models/mask_gdn/configuration_mask_gdn.py +96 -0
  22. models/mask_gdn/modeling_mask_gdn.py +535 -0
  23. models/mesa_net/__init__.py +12 -0
  24. models/mesa_net/configuration_mesa_net.py +103 -0
  25. models/mesa_net/modeling_mesa_net.py +370 -0
  26. models/mla/__init__.py +15 -0
  27. models/mla/configuration_mla.py +98 -0
  28. models/mla/modeling_mla.py +358 -0
  29. models/mom/__init__.py +12 -0
  30. models/mom/configuration_mom.py +101 -0
  31. models/mom/modeling_mom.py +474 -0
  32. models/nsa/__init__.py +15 -0
  33. models/nsa/configuration_nsa.py +91 -0
  34. models/nsa/modeling_nsa.py +355 -0
  35. models/past_gdn/__init__.py +12 -0
  36. models/past_gdn/configuration_past_gdn.py +96 -0
  37. models/past_gdn/modeling_past_gdn.py +535 -0
  38. models/path_attn/__init__.py +13 -0
  39. models/path_attn/configuration_path_attention.py +83 -0
  40. models/path_attn/modeling_path_attention.py +360 -0
  41. models/retnet/__init__.py +13 -0
  42. models/retnet/configuration_retnet.py +108 -0
  43. models/retnet/modeling_retnet.py +381 -0
  44. models/rodimus/__init__.py +13 -0
  45. models/rodimus/configuration_rodimus.py +118 -0
  46. models/rodimus/modeling_rodimus.py +563 -0
  47. models/rwkv6/__init__.py +13 -0
  48. models/rwkv6/configuration_rwkv6.py +98 -0
  49. models/rwkv7/__init__.py +13 -0
  50. models/rwkv7/configuration_rwkv7.py +121 -0
layers/rwkv7.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch.nn import functional as F
13
+
14
+ from fla.layers.rwkv6 import LoRA
15
+ from fla.modules import GroupNorm
16
+ from fla.modules.l2norm import l2_norm
17
+ from fla.modules.token_shift import token_shift
18
+ from fla.ops.rwkv7 import chunk_rwkv7, fused_mul_recurrent_rwkv7
19
+ from fla.ops.rwkv7.fused_addcmul import fused_addcmul_rwkv7
20
+ from fla.ops.rwkv7.fused_k_update import fused_k_rwkv7
21
+ from fla.ops.rwkv7.gate_output_correction import gate_output_correction
22
+
23
+ if TYPE_CHECKING:
24
+ from fla.models.utils import Cache
25
+
26
+
27
+ class RWKV7Attention(nn.Module):
28
+
29
+ def __init__(
30
+ self,
31
+ mode: str = 'chunk',
32
+ hidden_size: int = 1024,
33
+ head_dim: Optional[int] = 64,
34
+ num_heads: Optional[int] = None,
35
+ decay_low_rank_dim: Optional[int] = None,
36
+ gate_low_rank_dim: Optional[int] = None,
37
+ a_low_rank_dim: Optional[int] = None,
38
+ v_low_rank_dim: Optional[int] = None,
39
+ elementwise_affine: Optional[bool] = True,
40
+ norm_eps: float = 1e-5,
41
+ layer_idx: int = None,
42
+ fuse_norm: bool = False,
43
+ value_dim: int = None,
44
+ num_hidden_layers: int = None,
45
+ **kwargs
46
+ ) -> RWKV7Attention:
47
+ super().__init__()
48
+
49
+ self.mode = mode
50
+ assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
51
+ self.hidden_size = hidden_size
52
+
53
+ self.key_dim = hidden_size
54
+ self.value_dim = value_dim if value_dim is not None else hidden_size
55
+ if head_dim is None and num_heads is None:
56
+ raise ValueError("Either `head_dim` or `num_heads` must be specified.")
57
+ elif head_dim is not None:
58
+ self.head_dim = head_dim
59
+ self.num_heads = int(hidden_size // head_dim)
60
+ elif num_heads is not None:
61
+ self.head_dim = int(hidden_size // num_heads)
62
+ self.num_heads = num_heads
63
+ self.head_v_dim = int(self.value_dim // self.num_heads)
64
+
65
+ # Increase lora dimension for headdim>64
66
+ factor = self.head_dim / 64
67
+ if decay_low_rank_dim is None:
68
+ decay_low_rank_dim = max(32, int(round((2.5 * (hidden_size**0.5)) * factor / 32) * 32))
69
+ self.decay_low_rank_dim = decay_low_rank_dim
70
+ else:
71
+ self.decay_low_rank_dim = decay_low_rank_dim
72
+
73
+ if gate_low_rank_dim is None:
74
+ gate_low_rank_dim = max(32, int(round((5 * (hidden_size**0.5)) / 32) * 32))
75
+ self.gate_low_rank_dim = gate_low_rank_dim
76
+ else:
77
+ self.gate_low_rank_dim = gate_low_rank_dim
78
+
79
+ if a_low_rank_dim is None:
80
+ a_low_rank_dim = max(32, int(round((2.5 * (hidden_size**0.5)) * factor / 32) * 32))
81
+ self.a_low_rank_dim = a_low_rank_dim
82
+ else:
83
+ self.a_low_rank_dim = a_low_rank_dim
84
+
85
+ if v_low_rank_dim is None:
86
+ v_low_rank_dim = max(32, int(round((1.7 * (hidden_size**0.5)) * factor / 32) * 32))
87
+ self.v_low_rank_dim = v_low_rank_dim
88
+ else:
89
+ self.v_low_rank_dim = v_low_rank_dim
90
+
91
+ self.layer_idx = layer_idx
92
+ self.num_hidden_layers = num_hidden_layers
93
+ self.fuse_norm = fuse_norm
94
+
95
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
96
+ self.x_r = nn.Parameter(torch.zeros(1, 1, hidden_size))
97
+ self.x_w = nn.Parameter(torch.zeros(1, 1, hidden_size))
98
+ self.x_k = nn.Parameter(torch.zeros(1, 1, hidden_size))
99
+ self.x_v = nn.Parameter(torch.zeros(1, 1, hidden_size))
100
+ self.x_a = nn.Parameter(torch.zeros(1, 1, hidden_size))
101
+ self.x_g = nn.Parameter(torch.zeros(1, 1, hidden_size))
102
+
103
+ self.k_k = nn.Parameter(torch.zeros(self.key_dim))
104
+ self.k_a = nn.Parameter(torch.zeros(self.key_dim))
105
+ self.r_k = nn.Parameter(torch.zeros(self.num_heads, self.head_dim))
106
+
107
+ self.r_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
108
+ self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
109
+ self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
110
+ self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
111
+
112
+ self.w_lora = LoRA(hidden_size, self.key_dim, low_rank_dim=decay_low_rank_dim, activation='tanh')
113
+ if self.layer_idx != 0:
114
+ self.v_lora = LoRA(hidden_size, self.value_dim, low_rank_dim=v_low_rank_dim, activation=None)
115
+ self.a_lora = LoRA(hidden_size, self.key_dim, low_rank_dim=a_low_rank_dim, activation=None)
116
+ self.g_lora = LoRA(hidden_size, self.value_dim, low_rank_dim=gate_low_rank_dim, activation='sigmoid', bias=False)
117
+
118
+ if self.fuse_norm:
119
+ self.g_norm = GroupNorm(
120
+ num_groups=self.num_heads,
121
+ hidden_size=self.value_dim,
122
+ elementwise_affine=elementwise_affine,
123
+ eps=self.head_dim*norm_eps,
124
+ bias=True,
125
+ )
126
+ else:
127
+ self.g_norm = nn.GroupNorm(
128
+ num_groups=self.num_heads,
129
+ num_channels=self.value_dim,
130
+ eps=self.head_dim*norm_eps,
131
+ affine=elementwise_affine
132
+ )
133
+
134
+ try:
135
+ from transformers.modeling_utils import _init_weights
136
+ except ImportError:
137
+ _init_weights = True
138
+ if _init_weights:
139
+ self.apply(self._initialize_weights)
140
+ for name, module in self.named_modules():
141
+ module._in_rwkv_module = True
142
+
143
+ warnings.warn(
144
+ "According to Bo, you are using a potentially buggy FLA implementation of RWKV. "
145
+ "If you plan to report any numbers based on this implementation, we strongly recommend "
146
+ "cross-checking with the official repo: https://github.com/BlinkDL/RWKV-LM. "
147
+ "Bo may disagree with results reported from this version."
148
+ )
149
+
150
+ @torch.no_grad()
151
+ @torch.compiler.disable
152
+ def _initialize_weights(self, module: nn.Module):
153
+ if getattr(module, "_is_hf_initialized", False):
154
+ return
155
+
156
+ # Initialize only when we're processing the RWKV7Attention module itself
157
+ if isinstance(module, RWKV7Attention) and self.layer_idx is not None:
158
+ ratio_0_to_1 = self.layer_idx / (self.num_hidden_layers - 1) # 0 to 1
159
+ ratio_1_to_almost0 = 1.0 - (self.layer_idx / self.num_hidden_layers) # 1 to ~0
160
+
161
+ # Create position-based initialization tensor
162
+ ddd = torch.ones(1, 1, self.hidden_size, device=self.x_r.device)
163
+ www = torch.zeros(self.hidden_size, device=self.x_r.device)
164
+ zigzag = torch.zeros(self.hidden_size, device=self.x_r.device)
165
+ linear = torch.zeros(self.hidden_size, device=self.x_r.device)
166
+ for n in range(self.hidden_size):
167
+ linear[n] = n / (self.hidden_size-1) - 0.5
168
+ zigzag[n] = ((n % self.head_dim) - ((self.head_dim-1) / 2)) / ((self.head_dim-1) / 2)
169
+ zigzag[n] = zigzag[n] * abs(zigzag[n])
170
+ www[n] = -6 + 6 * (n / (self.hidden_size - 1)) ** (1 + 1 * ratio_0_to_1 ** 0.3)
171
+ ddd[0, 0, n] = n / self.hidden_size
172
+
173
+ # Initialize x_* parameters directly
174
+ self.x_r.data = (1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0)).to(self.x_r.dtype)
175
+ self.x_w.data = (1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0)).to(self.x_w.dtype)
176
+ self.x_k.data = (1.0 - torch.pow(ddd, 0.7 * ratio_1_to_almost0)).to(self.x_k.dtype)
177
+ self.x_v.data = (1.0 - torch.pow(ddd, 0.7 * ratio_1_to_almost0)).to(self.x_v.dtype)
178
+ self.x_a.data = (1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0)).to(self.x_a.dtype)
179
+ self.x_g.data = (1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0)).to(self.x_g.dtype)
180
+
181
+ # Initialize k_k, k_a, r_k
182
+ nn.init.constant_(self.k_a, 1.02)
183
+ nn.init.constant_(self.r_k, -0.04)
184
+ self.k_k.data.copy_((torch.zeros(self.hidden_size, device=self.k_k.device) +
185
+ 0.71 - linear*0.1).to(self.k_k.dtype))
186
+ # Set specific bias values for LoRA modules
187
+ # 0.5 comes from F.softplus
188
+ self.w_lora.set_bias_value(www + 0.5 + zigzag*2.5)
189
+ self.a_lora.set_bias_value(-0.19 + zigzag*0.3 + linear*0.4)
190
+
191
+ # v0 initialization - ones (for non-first layers)
192
+ if self.layer_idx != 0:
193
+ self.v_lora._initialize_weights(self.v_lora)
194
+ self.v_lora.set_bias_value(0.73 - linear*0.4)
195
+
196
+ # Initialize GroupNorm
197
+ self.g_norm.weight.data[:] = ((self.layer_idx + 1) / self.num_hidden_layers) ** 0.7
198
+
199
+ # Initialize Linear projections
200
+ self._orthogonal_init(self.r_proj.weight)
201
+ self._orthogonal_init(self.k_proj.weight, gain=0.1)
202
+ self._orthogonal_init(self.v_proj.weight)
203
+ self.o_proj.weight.data.zero_()
204
+
205
+ # Clean up temporary tensors to free memory
206
+ del ddd, www, zigzag, linear
207
+
208
+ module._is_hf_initialized = True
209
+
210
+ @staticmethod
211
+ def _orthogonal_init(weight, gain=1.0):
212
+ oringinal_dtype = weight.dtype
213
+ weight = weight.float()
214
+ nn.init.orthogonal_(weight, gain=gain)
215
+ weight = weight.to(oringinal_dtype)
216
+
217
+ def forward(
218
+ self,
219
+ hidden_states: torch.Tensor,
220
+ attention_mask: Optional[torch.Tensor] = None,
221
+ past_key_values: Optional[Cache] = None,
222
+ use_cache: Optional[bool] = False,
223
+ output_attentions: Optional[bool] = False,
224
+ v_first: torch.Tensor = None,
225
+ cu_seqlens: Optional[torch.LongTensor] = None,
226
+ **kwargs
227
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
228
+ batch_size, seq_len, _ = hidden_states.shape
229
+ if attention_mask is not None:
230
+ assert len(attention_mask.shape) == 2, (
231
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
232
+ "for padding purposes (0 indicating padding). "
233
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
234
+ )
235
+ am = attention_mask.narrow(1, attention_mask.size(1) - seq_len, seq_len).unsqueeze(-1)
236
+
237
+ last_state = None
238
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
239
+ last_state = past_key_values[self.layer_idx]
240
+
241
+ if attention_mask is not None:
242
+ hidden_states = hidden_states.mul(am)
243
+
244
+ # delta [batch_size, seq_len, hidden_size]
245
+ # conv_cache [N, D]
246
+ if last_state is None:
247
+ conv_cache = None
248
+ recurrent_state = None
249
+ else:
250
+ conv_cache = last_state['conv_state']
251
+ recurrent_state = last_state['recurrent_state']
252
+
253
+ delta, conv_state = token_shift(
254
+ hidden_states, cu_seqlens, output_cache=True, cache=conv_cache
255
+ )
256
+ xr, xw, xk, xv, xa, xg = fused_addcmul_rwkv7(hidden_states, delta, self.x_r, self.x_w,
257
+ self.x_k, self.x_v, self.x_a, self.x_g)
258
+
259
+ r = self.r_proj(xr)
260
+ # Using bf16 for LoRA computation is numerically safe here because:
261
+ # 1. After sigmoid activation:
262
+ # - Max absolute error (vs float32): 0.003
263
+ # - Mean absolute error: 0.0004
264
+ # 2. Subsequent scaling by -0.6065 will further reduce relative error
265
+ # (error scales linearly with constant multiplication)
266
+ # 3. Final compounded error remains within acceptable bounds for bf16 precision
267
+ # Empirical observation confirms bf16 introduces no practical degradation
268
+ w = -0.6065306597126334 * self.w_lora(xw).sigmoid()
269
+
270
+ k = self.k_proj(xk)
271
+ v = self.v_proj(xv)
272
+
273
+ if self.layer_idx == 0:
274
+ v_first = v
275
+ else:
276
+ v = torch.lerp(v, v_first, self.v_lora(xv).sigmoid())
277
+ a = self.a_lora(xa).sigmoid()
278
+ g = self.g_lora(xg)
279
+
280
+ if self.fuse_norm:
281
+ kk = l2_norm(rearrange(k * self.k_k, 'b t (h d) -> b t h d', d=self.head_dim))
282
+ else:
283
+ kk = F.normalize(rearrange(k * self.k_k, 'b t (h d) -> b t h d', d=self.head_dim), dim=-1, p=2.0)
284
+
285
+ # Prefer addcmul over expanded form for numerical stability in bf16:
286
+ # 1. Fused Multiply-Add (FMA) in addcmul reduces intermediate rounding:
287
+ # - Single op vs original 3 ops (mul, sub, mul)
288
+ # - 1 less intermediate value storage (bf16 write->read overhead)
289
+ # 2. Mathematically equivalent to k*(1 + (a-1)*self.k_a)
290
+ # but with better precision preservation
291
+ # 3. Particularly crucial for bf16 where intermediate values easily lose precision
292
+ # 4. Pytorch method: k = k.addcmul(k * (a - 1), self.k_a)
293
+ k = fused_k_rwkv7(k, a, self.k_a)
294
+
295
+ # dealing with left-padding
296
+ if attention_mask is not None:
297
+ v = v * am
298
+
299
+ r, w, k, a = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', d=self.head_dim), (r, w, k, a))
300
+ v = rearrange(v, 'b t (h d) -> b t h d', d=self.head_v_dim)
301
+
302
+ if self.training or seq_len >= 64:
303
+ # if training, use chunk mode no matter how short the sequence is
304
+ # launching the triton kernel for just one token will actually be slower
305
+ o, recurrent_state = chunk_rwkv7(
306
+ r=r,
307
+ w=w,
308
+ k=k,
309
+ v=v,
310
+ a=-kk,
311
+ b=kk * a,
312
+ scale=1.,
313
+ initial_state=recurrent_state,
314
+ output_final_state=use_cache,
315
+ cu_seqlens=cu_seqlens,
316
+ )
317
+ else:
318
+ o, recurrent_state = fused_mul_recurrent_rwkv7(
319
+ r=r,
320
+ w=w,
321
+ k=k,
322
+ v=v,
323
+ kk=kk,
324
+ a=a,
325
+ scale=1.,
326
+ initial_state=recurrent_state,
327
+ output_final_state=use_cache,
328
+ cu_seqlens=cu_seqlens,
329
+ )
330
+
331
+ if past_key_values is not None:
332
+ past_key_values.update(
333
+ recurrent_state=recurrent_state,
334
+ conv_state=conv_state,
335
+ layer_idx=self.layer_idx,
336
+ offset=r.shape[1]
337
+ )
338
+
339
+ if self.fuse_norm:
340
+ o = self.g_norm(rearrange(o, '... h d -> ... (h d)'))
341
+ else:
342
+ o = self.g_norm(rearrange(o, 'b t h d -> (b t) (h d)')).view(batch_size, seq_len, -1)
343
+
344
+ o = gate_output_correction(o, r, k, self.r_k, v, g)
345
+ o = self.o_proj(o)
346
+
347
+ return o, None, past_key_values, v_first
layers/utils.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ # Code is adapted from flash-attn.bert_padding.py
5
+
6
+ from typing import Tuple
7
+
8
+ import torch
9
+ from einops import rearrange, repeat
10
+
11
+ from fla.ops.utils.index import prepare_cu_seqlens_from_mask, prepare_lens_from_mask
12
+ from fla.utils import tensor_cache
13
+
14
+
15
+ class IndexFirstAxis(torch.autograd.Function):
16
+
17
+ @staticmethod
18
+ def forward(ctx, x, indices):
19
+ ctx.save_for_backward(indices)
20
+ assert x.ndim >= 2
21
+ ctx.first_axis_dim, other_shape = x.shape[0], x.shape[1:]
22
+ second_dim = other_shape.numel()
23
+ # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
24
+ # return x[indices]
25
+ return torch.gather(
26
+ rearrange(x, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim)
27
+ ).reshape(-1, *other_shape)
28
+
29
+ @staticmethod
30
+ def backward(ctx, do):
31
+ (indices,) = ctx.saved_tensors
32
+ assert do.ndim >= 2
33
+ other_shape = do.shape[1:]
34
+ do = rearrange(do, "b ... -> b (...)")
35
+ dx = torch.zeros(
36
+ [ctx.first_axis_dim, do.shape[1]],
37
+ device=do.device,
38
+ dtype=do.dtype,
39
+ )
40
+ # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
41
+ # dx[indices] = do
42
+ dx.scatter_(0, repeat(indices, "z -> z d", d=do.shape[1]), do)
43
+ return dx.reshape(ctx.first_axis_dim, *other_shape), None
44
+
45
+
46
+ index_first_axis = IndexFirstAxis.apply
47
+
48
+
49
+ class IndexPutFirstAxis(torch.autograd.Function):
50
+
51
+ @staticmethod
52
+ def forward(ctx, x, indices, first_axis_dim):
53
+ ctx.save_for_backward(indices)
54
+ assert indices.ndim == 1
55
+ assert x.ndim >= 2
56
+ y = torch.zeros(first_axis_dim, *x.shape[1:], device=x.device, dtype=x.dtype)
57
+ # TODO [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
58
+ y[indices] = x
59
+ # y.scatter_(0, repeat(indices, 'z -> z d', d=x.shape[1]), x)
60
+ return y
61
+
62
+ @staticmethod
63
+ def backward(ctx, do):
64
+ (indices,) = ctx.saved_tensors
65
+ # TODO [2022-03-04] For some reason torch.gather is a bit faster than indexing.
66
+ dx = do[indices]
67
+ # dx = torch.gather(do, 0, repeat(indices, 'z -> z d', d=do.shape[1]))
68
+ return dx, None, None
69
+
70
+
71
+ index_put_first_axis = IndexPutFirstAxis.apply
72
+
73
+
74
+ @tensor_cache
75
+ def get_unpad_data(
76
+ attention_mask: torch.Tensor
77
+ ) -> tuple[torch.Tensor, torch.Tensor, int]:
78
+ """
79
+ Retrieves indexing data required to repad unpadded (ragged) tensors.
80
+
81
+ Args:
82
+ attention_mask (`torch.Tensor`):
83
+ Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
84
+
85
+ Return:
86
+ indices (`torch.Tensor`):
87
+ The indices of non-masked tokens from the flattened input sequence.
88
+ cu_seqlens (`torch.Tensor`):
89
+ The cumulative sequence lengths, used to index into ragged (unpadded) tensors.
90
+ `cu_seqlens` shape is [batch_size + 1].
91
+ max_seqlen_in_batch (`int`):
92
+ Maximum sequence length in batch.
93
+ """
94
+ lens = prepare_lens_from_mask(attention_mask)
95
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
96
+ max_seqlen_in_batch = lens.max().item()
97
+ cu_seqlens = prepare_cu_seqlens_from_mask(attention_mask)
98
+ return indices, cu_seqlens, max_seqlen_in_batch
99
+
100
+
101
+ def unpad_input(
102
+ q: torch.Tensor,
103
+ states: Tuple[torch.Tensor],
104
+ attention_mask: torch.Tensor,
105
+ q_len: int,
106
+ keepdim: bool = False,
107
+ ):
108
+ """
109
+ Unpads query, key, and values tensors, using a single dimension for all tokens
110
+ even though they belong to different batches.
111
+
112
+
113
+ Arguments:
114
+ q (`torch.Tensor`):
115
+ Query state with padding. Shape: [batch_size, q_len, ...].
116
+ states (`Tuple[torch.Tensor]`):
117
+ Attention state with padding. Shape: [batch_size, seq_len, ...].
118
+ attention_mask (`torch.Tensor`):
119
+ Boolean or int tensor of shape [batch_size, sequence_length], 1 means valid and 0 means not valid.
120
+ q_len (`int`):
121
+ Target length.
122
+ keepdim (`bool`):
123
+ Whether to keep the batch dimension. Default: `False`.
124
+
125
+ Return:
126
+ q (`torch.Tensor`):
127
+ Query state without padding.
128
+ Shape: [1, total_target_length, ...] if `keepdim=True` else [total_target_length, ...].
129
+ states (`Tuple[torch.Tensor]`):
130
+ Attention state without padding.
131
+ Shape: [1, total_source_length, ...] if `keepdim=True` else [total_source_length, ...].
132
+ indices_q (`torch.Tensor`):
133
+ The indices of non-masked tokens from the flattened input target sequence.
134
+ (cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`):
135
+ The cumulative sequence lengths for the target (query) and source (key, value),
136
+ used to index into ragged (unpadded) tensors.
137
+ `cu_seqlens` shape is [batch_size + 1].
138
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`):
139
+ Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence
140
+ i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value).
141
+ """
142
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = get_unpad_data(attention_mask)
143
+ batch_size, seq_len, *_ = states[0].shape
144
+
145
+ state = tuple(
146
+ index_first_axis(rearrange(s, "b s ... -> (b s) ..."), indices_k)
147
+ for s in states
148
+ )
149
+
150
+ if q_len == seq_len:
151
+ q = index_first_axis(rearrange(q, "b s ... -> (b s) ..."), indices_k)
152
+ cu_seqlens_q = cu_seqlens_k
153
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
154
+ indices_q = indices_k
155
+ elif q_len == 1:
156
+ max_seqlen_in_batch_q = 1
157
+ cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=q.device)
158
+ indices_q = cu_seqlens_q[:-1]
159
+ q = q.squeeze(1)
160
+ else:
161
+ raise NotImplementedError("We only support either q_len == k_len (prefilling) or q_len == 1 (decoding)")
162
+
163
+ if keepdim:
164
+ q = q.unsqueeze(0)
165
+ state = tuple(s.unsqueeze(0) for s in state)
166
+
167
+ return (
168
+ q,
169
+ state,
170
+ indices_q,
171
+ (cu_seqlens_q, cu_seqlens_k),
172
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
173
+ )
174
+
175
+
176
+ def pad_input(
177
+ hidden_states: torch.Tensor,
178
+ indices: torch.LongTensor,
179
+ batch_size: int,
180
+ seq_len: int,
181
+ ) -> torch.Tensor:
182
+ """
183
+ Args:
184
+ hidden_states ([total_tokens, ...]):
185
+ where total_tokens denotes the number of tokens in selected in attention_mask.
186
+ indices ([total_tokens]):
187
+ the indices that represent the non-masked tokens of the original padded input sequence.
188
+ batch_size (int):
189
+ batch_size size for the padded sequence.
190
+ seq_len (int):
191
+ maximum sequence length for the padded sequence.
192
+
193
+ Return:
194
+ hidden_states of shape [batch_size, seq_len, ...]
195
+ """
196
+ output = index_put_first_axis(hidden_states, indices, batch_size * seq_len)
197
+ return rearrange(output, "(b s) ... -> b s ...", b=batch_size)
models/hgrn/configuration_hgrn.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class HGRNConfig(PretrainedConfig):
10
+
11
+ model_type = 'hgrn'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ attn_mode: str = "fused_recurrent",
17
+ hidden_size: int = 2048,
18
+ num_hidden_layers: int = 24,
19
+ expand_ratio: Optional[int] = 1,
20
+ use_short_conv: bool = False,
21
+ conv_size: int = 4,
22
+ use_lower_bound: bool = True,
23
+ max_position_embeddings: int = 2048,
24
+ hidden_ratio: Optional[int] = 4,
25
+ intermediate_size: Optional[int] = None,
26
+ hidden_act: str = "swish",
27
+ elementwise_affine: Optional[bool] = True,
28
+ norm_eps: float = 1e-6,
29
+ attn: Optional[Dict] = None,
30
+ use_cache: bool = True,
31
+ pad_token_id: Optional[int] = None,
32
+ bos_token_id: int = 1,
33
+ eos_token_id: int = 2,
34
+ tie_word_embeddings: bool = False,
35
+ initializer_range: float = 0.02,
36
+ fuse_norm: bool = True,
37
+ fuse_swiglu: bool = True,
38
+ fuse_cross_entropy: bool = True,
39
+ fuse_linear_cross_entropy: bool = False,
40
+ use_l2warp: bool = False,
41
+ vocab_size: int = 32000,
42
+ **kwargs
43
+ ):
44
+ self.attn_mode = attn_mode
45
+ self.hidden_size = hidden_size
46
+ self.num_hidden_layers = num_hidden_layers
47
+ self.expand_ratio = expand_ratio
48
+ self.use_short_conv = use_short_conv
49
+ self.conv_size = conv_size
50
+ self.use_lower_bound = use_lower_bound
51
+ self.max_position_embeddings = max_position_embeddings
52
+ self.hidden_ratio = hidden_ratio
53
+ self.intermediate_size = intermediate_size
54
+ self.elementwise_affine = elementwise_affine
55
+ self.attn = attn
56
+ self.norm_eps = norm_eps
57
+ self.hidden_act = hidden_act
58
+ self.use_cache = use_cache
59
+ self.initializer_range = initializer_range
60
+
61
+ self.fuse_norm = fuse_norm
62
+ self.fuse_swiglu = fuse_swiglu
63
+ self.fuse_cross_entropy = fuse_cross_entropy
64
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
65
+ self.use_l2warp = use_l2warp
66
+ self.vocab_size = vocab_size
67
+
68
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
69
+ raise ValueError(
70
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
71
+ )
72
+ if fuse_linear_cross_entropy:
73
+ warnings.warn(
74
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
75
+ "at the potential cost of reduced precision. "
76
+ "If you observe issues like loss divergence, consider disabling this setting."
77
+ )
78
+
79
+ if attn is not None:
80
+ if not isinstance(attn, Dict):
81
+ raise ValueError("attn must be a dictionary")
82
+ if 'layers' not in attn:
83
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
84
+ if 'num_heads' not in attn:
85
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
86
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
87
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
88
+ attn['window_size'] = attn.get('window_size', None)
89
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
90
+
91
+ super().__init__(
92
+ pad_token_id=pad_token_id,
93
+ bos_token_id=bos_token_id,
94
+ eos_token_id=eos_token_id,
95
+ tie_word_embeddings=tie_word_embeddings,
96
+ **kwargs,
97
+ )
models/hgrn/modeling_hgrn.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.hgrn import HGRNAttention
18
+ from fla.models.hgrn.configuration_hgrn import HGRNConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as HGRNMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class HGRNBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: HGRNConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = HGRNAttention(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ expand_ratio=config.expand_ratio,
62
+ use_short_conv=config.use_short_conv,
63
+ conv_size=config.conv_size,
64
+ elementwise_affine=config.elementwise_affine,
65
+ norm_eps=config.norm_eps,
66
+ layer_idx=layer_idx
67
+ )
68
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
69
+ self.mlp = HGRNMLP(
70
+ hidden_size=config.hidden_size,
71
+ hidden_ratio=config.hidden_ratio,
72
+ intermediate_size=config.intermediate_size,
73
+ hidden_act=config.hidden_act,
74
+ fuse_swiglu=config.fuse_swiglu
75
+ )
76
+
77
+ def forward(
78
+ self,
79
+ hidden_states: torch.Tensor,
80
+ attention_mask: Optional[torch.Tensor] = None,
81
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
82
+ use_cache: Optional[bool] = False,
83
+ output_attentions: Optional[bool] = False,
84
+ lower_bound: Optional[torch.Tensor] = False,
85
+ **kwargs: Unpack[Dict]
86
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
87
+ residual = hidden_states
88
+ hidden_states = self.attn_norm(hidden_states)
89
+ hidden_states, attentions, past_key_values = self.attn(
90
+ hidden_states=hidden_states,
91
+ attention_mask=attention_mask,
92
+ past_key_values=past_key_values,
93
+ use_cache=use_cache,
94
+ output_attentions=output_attentions,
95
+ lower_bound=lower_bound,
96
+ **kwargs
97
+ )
98
+ if self.config.fuse_norm:
99
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
100
+ else:
101
+ hidden_states = residual + hidden_states
102
+ residual = hidden_states
103
+ hidden_states = self.mlp_norm(hidden_states)
104
+ hidden_states = self.mlp(hidden_states, **kwargs)
105
+ hidden_states = residual + hidden_states
106
+
107
+ outputs = (hidden_states, attentions, past_key_values)
108
+
109
+ return outputs
110
+
111
+
112
+ class HGRNPreTrainedModel(PreTrainedModel):
113
+
114
+ config_class = HGRNConfig
115
+ base_model_prefix = 'model'
116
+ supports_gradient_checkpointing = True
117
+ _no_split_modules = ['HGRNBlock']
118
+ _supports_cache_class = True
119
+
120
+ def __init__(self, *inputs, **kwargs):
121
+ super().__init__(*inputs, **kwargs)
122
+
123
+ def _init_weights(
124
+ self,
125
+ module: nn.Module,
126
+ prenorm_residual_strategy: Optional[str] = None,
127
+ num_residuals_per_layer: int = 2,
128
+ ):
129
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
130
+ # Slightly different from the TF version which uses truncated_normal for initialization
131
+ # cf https://github.com/pytorch/pytorch/pull/5617
132
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
133
+ if module.bias is not None:
134
+ nn.init.zeros_(module.bias)
135
+ elif isinstance(module, nn.Embedding):
136
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
137
+ elif hasattr(module, 'reset_parameters'):
138
+ module.reset_parameters()
139
+
140
+ if prenorm_residual_strategy is not None:
141
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
142
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
143
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
144
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
145
+ #
146
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
147
+ p = None
148
+ if hasattr(module, 'o_proj'):
149
+ p = module.o_proj.weight
150
+ elif hasattr(module, 'down_proj'):
151
+ p = module.down_proj.weight
152
+ if p is not None:
153
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
154
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
155
+ # We need to reinit p since this code could be called multiple times
156
+ # Having just p *= scale would repeatedly scale it down
157
+ if prenorm_residual_strategy == 'rescale':
158
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
159
+ with torch.no_grad():
160
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
161
+ elif prenorm_residual_strategy == 'zero':
162
+ nn.init.zeros_(p)
163
+ else:
164
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
165
+
166
+
167
+ class HGRNModel(HGRNPreTrainedModel):
168
+
169
+ def __init__(self, config: HGRNConfig):
170
+ super().__init__(config)
171
+ self.padding_idx = config.pad_token_id
172
+ self.vocab_size = config.vocab_size
173
+
174
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
175
+ if config.use_lower_bound:
176
+ self.lower_bounds = nn.Parameter(torch.zeros(config.num_hidden_layers, config.hidden_size))
177
+ self.layers = nn.ModuleList([HGRNBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
178
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
179
+
180
+ self.gradient_checkpointing = False
181
+
182
+ self.post_init()
183
+
184
+ def get_input_embeddings(self):
185
+ return self.embeddings
186
+
187
+ def set_input_embeddings(self, value):
188
+ self.embeddings = value
189
+
190
+ def forward(
191
+ self,
192
+ input_ids: Optional[torch.LongTensor] = None,
193
+ attention_mask: Optional[torch.Tensor] = None, # noqa
194
+ inputs_embeds: Optional[torch.FloatTensor] = None,
195
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
196
+ use_cache: Optional[bool] = None,
197
+ output_attentions: Optional[bool] = None,
198
+ output_hidden_states: Optional[bool] = None,
199
+ return_dict: Optional[bool] = None,
200
+ **kwargs: Unpack[Dict]
201
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
202
+ if output_attentions:
203
+ warnings.warn("`HGRNModel` does not `output_attentions` now, setting it to `False`.")
204
+ output_attentions = False
205
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
206
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
207
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
208
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
209
+
210
+ # retrieve input_ids and inputs_embeds
211
+ if input_ids is not None and inputs_embeds is not None:
212
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
213
+ if input_ids is None and inputs_embeds is None:
214
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
215
+
216
+ if inputs_embeds is None:
217
+ inputs_embeds = self.embeddings(input_ids)
218
+ hidden_states = inputs_embeds
219
+
220
+ if use_cache and not isinstance(past_key_values, Cache):
221
+ past_key_values = Cache.from_legacy_cache(past_key_values)
222
+
223
+ all_hidden_states = () if output_hidden_states else None
224
+ all_attns = () if output_attentions else None
225
+
226
+ if self.config.use_lower_bound:
227
+ lower_bounds = self.lower_bounds.softmax(0, dtype=torch.float)
228
+ lower_bounds = lower_bounds.cumsum(0) - lower_bounds[0]
229
+ for i, layer in enumerate(self.layers):
230
+ if output_hidden_states:
231
+ all_hidden_states += (hidden_states,)
232
+
233
+ lower_bound = lower_bounds[i] if self.config.use_lower_bound else None
234
+ hidden_states, attentions, past_key_values = layer(
235
+ hidden_states,
236
+ attention_mask=attention_mask,
237
+ past_key_values=past_key_values,
238
+ use_cache=use_cache,
239
+ output_attentions=output_attentions,
240
+ lower_bound=lower_bound,
241
+ **kwargs
242
+ )
243
+
244
+ if output_attentions:
245
+ all_attns += (attentions,)
246
+
247
+ hidden_states = self.norm(hidden_states)
248
+
249
+ # add hidden states from the last decoder layer
250
+ if output_hidden_states:
251
+ all_hidden_states += (hidden_states,)
252
+
253
+ if not return_dict:
254
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
255
+ return BaseModelOutputWithPast(
256
+ last_hidden_state=hidden_states,
257
+ past_key_values=past_key_values,
258
+ hidden_states=all_hidden_states,
259
+ attentions=all_attns
260
+ )
261
+
262
+
263
+ class HGRNForCausalLM(HGRNPreTrainedModel, FLAGenerationMixin):
264
+
265
+ _tied_weights_keys = ["lm_head.weight"]
266
+
267
+ def __init__(self, config):
268
+ super().__init__(config)
269
+ self.model = HGRNModel(config)
270
+ self.vocab_size = config.vocab_size
271
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
272
+ self.criterion = None
273
+
274
+ # Initialize weights and apply final processing
275
+ self.post_init()
276
+
277
+ def get_input_embeddings(self):
278
+ return self.model.embeddings
279
+
280
+ def set_input_embeddings(self, value):
281
+ self.model.embeddings = value
282
+
283
+ def get_output_embeddings(self):
284
+ return self.lm_head
285
+
286
+ def set_output_embeddings(self, new_embeddings):
287
+ self.lm_head = new_embeddings
288
+
289
+ def set_decoder(self, decoder):
290
+ self.model = decoder
291
+
292
+ def get_decoder(self):
293
+ return self.model
294
+
295
+ def generate(self, *args, **kwargs):
296
+ try:
297
+ return super().generate(*args, **kwargs)
298
+ except AttributeError as exception:
299
+ if 'past_key_values' in str(exception):
300
+ raise AttributeError(
301
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
302
+ f"which is not supported for {self.__class__.__name__}. "
303
+ f"Try another generation strategy instead. "
304
+ f"For the available generation strategies, check this doc: "
305
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
306
+ )
307
+ else:
308
+ raise exception
309
+
310
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
311
+ def forward(
312
+ self,
313
+ input_ids: torch.LongTensor = None,
314
+ attention_mask: Optional[torch.Tensor] = None,
315
+ inputs_embeds: Optional[torch.Tensor] = None,
316
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
317
+ labels: Optional[torch.LongTensor] = None,
318
+ use_cache: Optional[bool] = None,
319
+ output_attentions: Optional[bool] = None,
320
+ output_hidden_states: Optional[bool] = None,
321
+ return_dict: Optional[bool] = None,
322
+ logits_to_keep: Optional[int] = 0,
323
+ **kwargs: Unpack[Dict]
324
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
325
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
326
+ output_hidden_states = (
327
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
328
+ )
329
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
330
+
331
+ outputs = self.model(
332
+ input_ids=input_ids,
333
+ attention_mask=attention_mask,
334
+ inputs_embeds=inputs_embeds,
335
+ past_key_values=past_key_values,
336
+ use_cache=use_cache,
337
+ output_attentions=output_attentions,
338
+ output_hidden_states=output_hidden_states,
339
+ return_dict=return_dict,
340
+ **kwargs
341
+ )
342
+
343
+ hidden_states = outputs[0]
344
+
345
+ loss, logits = None, None
346
+ if not self.config.fuse_linear_cross_entropy or labels is None:
347
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
348
+ if labels is not None:
349
+ if getattr(self, 'criterion', None) is None:
350
+ if self.config.fuse_linear_cross_entropy:
351
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
352
+ elif self.config.fuse_cross_entropy:
353
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
354
+ else:
355
+ criterion = nn.CrossEntropyLoss()
356
+ else:
357
+ criterion = self.criterion
358
+ labels = labels.to(hidden_states.device)
359
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
360
+ if self.config.fuse_linear_cross_entropy:
361
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
362
+ else:
363
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
364
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
365
+
366
+ if not return_dict:
367
+ output = (logits,) + outputs[1:]
368
+ return (loss,) + output if loss is not None else output
369
+
370
+ return CausalLMOutputWithPast(
371
+ loss=loss,
372
+ logits=logits,
373
+ past_key_values=outputs.past_key_values,
374
+ hidden_states=outputs.hidden_states,
375
+ attentions=outputs.attentions,
376
+ )
models/hgrn2/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.hgrn2.configuration_hgrn2 import HGRN2Config
6
+ from fla.models.hgrn2.modeling_hgrn2 import HGRN2ForCausalLM, HGRN2Model
7
+
8
+ AutoConfig.register(HGRN2Config.model_type, HGRN2Config, exist_ok=True)
9
+ AutoModel.register(HGRN2Config, HGRN2Model, exist_ok=True)
10
+ AutoModelForCausalLM.register(HGRN2Config, HGRN2ForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['HGRN2Config', 'HGRN2ForCausalLM', 'HGRN2Model']
models/hgrn2/configuration_hgrn2.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class HGRN2Config(PretrainedConfig):
10
+
11
+ model_type = 'hgrn2'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ num_hidden_layers: int = 24,
18
+ attn_mode: str = "chunk",
19
+ num_heads: Optional[int] = None,
20
+ expand_ratio: Optional[int] = 128,
21
+ use_short_conv: bool = False,
22
+ conv_size: int = 4,
23
+ use_lower_bound: bool = True,
24
+ hidden_ratio: Optional[int] = 4,
25
+ intermediate_size: Optional[int] = None,
26
+ hidden_act: str = "swish",
27
+ max_position_embeddings: int = 2048,
28
+ elementwise_affine: Optional[bool] = True,
29
+ norm_eps: float = 1e-6,
30
+ attn: Optional[Dict] = None,
31
+ use_cache: bool = True,
32
+ pad_token_id: Optional[int] = None,
33
+ bos_token_id: int = 1,
34
+ eos_token_id: int = 2,
35
+ tie_word_embeddings: bool = False,
36
+ initializer_range: float = 0.02,
37
+ fuse_norm: bool = True,
38
+ fuse_swiglu: bool = True,
39
+ fuse_cross_entropy: bool = True,
40
+ fuse_linear_cross_entropy: bool = False,
41
+ use_l2warp: bool = False,
42
+ vocab_size: int = 32000,
43
+ **kwargs
44
+ ):
45
+ self.hidden_size = hidden_size
46
+ self.num_hidden_layers = num_hidden_layers
47
+ self.attn_mode = attn_mode
48
+
49
+ if expand_ratio is None and num_heads is not None:
50
+ expand_ratio = hidden_size // num_heads
51
+ elif expand_ratio is not None and num_heads is None:
52
+ num_heads = hidden_size // expand_ratio
53
+ elif expand_ratio is None and num_heads is None:
54
+ raise RuntimeError("One of `expand_ratio` or `num_heads` should be provided.")
55
+ self.num_heads = num_heads
56
+ self.expand_ratio = expand_ratio
57
+
58
+ self.use_short_conv = use_short_conv
59
+ self.conv_size = conv_size
60
+ self.use_lower_bound = use_lower_bound
61
+ self.max_position_embeddings = max_position_embeddings
62
+ self.hidden_ratio = hidden_ratio
63
+ self.intermediate_size = intermediate_size
64
+ self.hidden_act = hidden_act
65
+ self.elementwise_affine = elementwise_affine
66
+ self.norm_eps = norm_eps
67
+ self.attn = attn
68
+ self.use_cache = use_cache
69
+ self.initializer_range = initializer_range
70
+
71
+ self.fuse_norm = fuse_norm
72
+ self.fuse_swiglu = fuse_swiglu
73
+ self.fuse_cross_entropy = fuse_cross_entropy
74
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
75
+ self.use_l2warp = use_l2warp
76
+ self.vocab_size = vocab_size
77
+
78
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
79
+ raise ValueError(
80
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
81
+ )
82
+ if fuse_linear_cross_entropy:
83
+ warnings.warn(
84
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
85
+ "at the potential cost of reduced precision. "
86
+ "If you observe issues like loss divergence, consider disabling this setting."
87
+ )
88
+
89
+ if attn is not None:
90
+ if not isinstance(attn, Dict):
91
+ raise ValueError("attn must be a dictionary")
92
+ if 'layers' not in attn:
93
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
94
+ if 'num_heads' not in attn:
95
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
96
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
97
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
98
+ attn['window_size'] = attn.get('window_size', None)
99
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
100
+
101
+ super().__init__(
102
+ pad_token_id=pad_token_id,
103
+ bos_token_id=bos_token_id,
104
+ eos_token_id=eos_token_id,
105
+ tie_word_embeddings=tie_word_embeddings,
106
+ **kwargs,
107
+ )
models/lightnet/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.lightnet.configuration_lightnet import LightNetConfig
6
+ from fla.models.lightnet.modeling_lightnet import LightNetForCausalLM, LightNetModel
7
+
8
+ AutoConfig.register(LightNetConfig.model_type, LightNetConfig, exist_ok=True)
9
+ AutoModel.register(LightNetConfig, LightNetModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(LightNetConfig, LightNetForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['LightNetConfig', 'LightNetForCausalLM', 'LightNetModel']
models/lightnet/configuration_lightnet.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class LightNetConfig(PretrainedConfig):
10
+
11
+ model_type = 'lightnet'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ num_hidden_layers: int = 24,
18
+ attn_mode: str = "chunk",
19
+ num_heads: Optional[int] = None,
20
+ expand_ratio: Optional[int] = 128,
21
+ use_short_conv: bool = False,
22
+ conv_size: int = 4,
23
+ hidden_ratio: Optional[int] = 4,
24
+ intermediate_size: Optional[int] = None,
25
+ hidden_act: str = "swish",
26
+ max_position_embeddings: int = 2048,
27
+ gate_low_rank_dim: int = 128,
28
+ elementwise_affine: Optional[bool] = True,
29
+ norm_eps: float = 1e-6,
30
+ attn: Optional[Dict] = None,
31
+ use_cache: bool = True,
32
+ pad_token_id: Optional[int] = None,
33
+ bos_token_id: int = 1,
34
+ eos_token_id: int = 2,
35
+ tie_word_embeddings: bool = False,
36
+ initializer_range: float = 0.02,
37
+ fuse_norm: bool = True,
38
+ fuse_swiglu: bool = True,
39
+ fuse_cross_entropy: bool = True,
40
+ fuse_linear_cross_entropy: bool = False,
41
+ use_l2warp: bool = False,
42
+ vocab_size: int = 32000,
43
+ **kwargs
44
+ ):
45
+ self.hidden_size = hidden_size
46
+ self.num_hidden_layers = num_hidden_layers
47
+ self.attn_mode = attn_mode
48
+ self.num_heads = num_heads
49
+ self.expand_ratio = expand_ratio
50
+ self.use_short_conv = use_short_conv
51
+ self.conv_size = conv_size
52
+ self.max_position_embeddings = max_position_embeddings
53
+ self.gate_low_rank_dim = gate_low_rank_dim
54
+ self.hidden_ratio = hidden_ratio
55
+ self.intermediate_size = intermediate_size
56
+ self.hidden_act = hidden_act
57
+ self.elementwise_affine = elementwise_affine
58
+ self.norm_eps = norm_eps
59
+ self.attn = attn
60
+ self.use_cache = use_cache
61
+ self.initializer_range = initializer_range
62
+
63
+ self.fuse_norm = fuse_norm
64
+ self.fuse_swiglu = fuse_swiglu
65
+ self.fuse_cross_entropy = fuse_cross_entropy
66
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
67
+ self.use_l2warp = use_l2warp
68
+ self.vocab_size = vocab_size
69
+
70
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
71
+ raise ValueError(
72
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
73
+ )
74
+ if fuse_linear_cross_entropy:
75
+ warnings.warn(
76
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
77
+ "at the potential cost of reduced precision. "
78
+ "If you observe issues like loss divergence, consider disabling this setting."
79
+ )
80
+
81
+ if attn is not None:
82
+ if not isinstance(attn, Dict):
83
+ raise ValueError("attn must be a dictionary")
84
+ if 'layers' not in attn:
85
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
86
+ if 'num_heads' not in attn:
87
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
88
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
89
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
90
+ attn['window_size'] = attn.get('window_size', None)
91
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
92
+
93
+ super().__init__(
94
+ pad_token_id=pad_token_id,
95
+ bos_token_id=bos_token_id,
96
+ eos_token_id=eos_token_id,
97
+ tie_word_embeddings=tie_word_embeddings,
98
+ **kwargs,
99
+ )
models/lightnet/modeling_lightnet.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.lightnet import LightNetAttention
18
+ from fla.models.lightnet.configuration_lightnet import LightNetConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as LightNetMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class LightNetBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: LightNetConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ max_position_embeddings=config.max_position_embeddings,
54
+ layer_idx=layer_idx
55
+ )
56
+ else:
57
+ self.attn = LightNetAttention(
58
+ mode=config.attn_mode,
59
+ hidden_size=config.hidden_size,
60
+ num_heads=config.num_heads,
61
+ expand_ratio=config.expand_ratio,
62
+ use_short_conv=config.use_short_conv,
63
+ conv_size=config.conv_size,
64
+ gate_low_rank_dim=config.gate_low_rank_dim,
65
+ elementwise_affine=config.elementwise_affine,
66
+ norm_eps=config.norm_eps,
67
+ layer_idx=layer_idx
68
+ )
69
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
70
+ self.mlp = LightNetMLP(
71
+ hidden_size=config.hidden_size,
72
+ hidden_ratio=config.hidden_ratio,
73
+ intermediate_size=config.intermediate_size,
74
+ hidden_act=config.hidden_act,
75
+ fuse_swiglu=config.fuse_swiglu
76
+ )
77
+
78
+ def forward(
79
+ self,
80
+ hidden_states: torch.Tensor,
81
+ attention_mask: Optional[torch.Tensor] = None,
82
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
83
+ use_cache: Optional[bool] = False,
84
+ output_attentions: Optional[bool] = False,
85
+ **kwargs: Unpack[Dict]
86
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
87
+ residual = hidden_states
88
+ hidden_states = self.attn_norm(hidden_states)
89
+ hidden_states, attentions, past_key_values = self.attn(
90
+ hidden_states=hidden_states,
91
+ attention_mask=attention_mask,
92
+ past_key_values=past_key_values,
93
+ use_cache=use_cache,
94
+ output_attentions=output_attentions,
95
+ **kwargs
96
+ )
97
+ if self.config.fuse_norm:
98
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
99
+ else:
100
+ hidden_states = residual + hidden_states
101
+ residual = hidden_states
102
+ hidden_states = self.mlp_norm(hidden_states)
103
+ hidden_states = self.mlp(hidden_states, **kwargs)
104
+ hidden_states = residual + hidden_states
105
+
106
+ outputs = (hidden_states, attentions, past_key_values)
107
+
108
+ return outputs
109
+
110
+
111
+ class LightNetPreTrainedModel(PreTrainedModel):
112
+
113
+ config_class = LightNetConfig
114
+ supports_gradient_checkpointing = True
115
+ _no_split_modules = ['LightNetBlock']
116
+ _supports_cache_class = True
117
+
118
+ def __init__(self, *inputs, **kwargs):
119
+ super().__init__(*inputs, **kwargs)
120
+
121
+ def _init_weights(
122
+ self,
123
+ module: nn.Module,
124
+ prenorm_residual_strategy: Optional[str] = None,
125
+ num_residuals_per_layer: int = 2,
126
+ ):
127
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
128
+ # Slightly different from the TF version which uses truncated_normal for initialization
129
+ # cf https://github.com/pytorch/pytorch/pull/5617
130
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
131
+ if module.bias is not None:
132
+ nn.init.zeros_(module.bias)
133
+ elif isinstance(module, nn.Embedding):
134
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
135
+ elif hasattr(module, 'reset_parameters'):
136
+ module.reset_parameters()
137
+
138
+ if prenorm_residual_strategy is not None:
139
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
140
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
141
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
142
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
143
+ #
144
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
145
+ p = None
146
+ if hasattr(module, 'o_proj'):
147
+ p = module.o_proj.weight
148
+ elif hasattr(module, 'down_proj'):
149
+ p = module.down_proj.weight
150
+ if p is not None:
151
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
152
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
153
+ # We need to reinit p since this code could be called multiple times
154
+ # Having just p *= scale would repeatedly scale it down
155
+ if prenorm_residual_strategy == 'rescale':
156
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
157
+ with torch.no_grad():
158
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
159
+ elif prenorm_residual_strategy == 'zero':
160
+ nn.init.zeros_(p)
161
+ else:
162
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
163
+
164
+
165
+ class LightNetModel(LightNetPreTrainedModel):
166
+
167
+ def __init__(self, config: LightNetConfig):
168
+ super().__init__(config)
169
+ self.padding_idx = config.pad_token_id
170
+ self.vocab_size = config.vocab_size
171
+
172
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
173
+ self.layers = nn.ModuleList([LightNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
174
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
175
+
176
+ self.gradient_checkpointing = False
177
+
178
+ self.post_init()
179
+
180
+ def get_input_embeddings(self):
181
+ return self.embeddings
182
+
183
+ def set_input_embeddings(self, value):
184
+ self.embeddings = value
185
+
186
+ def forward(
187
+ self,
188
+ input_ids: Optional[torch.LongTensor] = None,
189
+ attention_mask: Optional[torch.Tensor] = None, # noqa
190
+ inputs_embeds: Optional[torch.FloatTensor] = None,
191
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
192
+ use_cache: Optional[bool] = None,
193
+ output_attentions: Optional[bool] = None,
194
+ output_hidden_states: Optional[bool] = None,
195
+ return_dict: Optional[bool] = None,
196
+ **kwargs: Unpack[Dict]
197
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
198
+ if output_attentions:
199
+ warnings.warn("`LightNetModel` does not `output_attentions` now, setting it to `False`.")
200
+ output_attentions = False
201
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
202
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
203
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
204
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
205
+
206
+ # retrieve input_ids and inputs_embeds
207
+ if input_ids is not None and inputs_embeds is not None:
208
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
209
+ if input_ids is None and inputs_embeds is None:
210
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
211
+
212
+ if inputs_embeds is None:
213
+ inputs_embeds = self.embeddings(input_ids)
214
+ hidden_states = inputs_embeds
215
+
216
+ if use_cache and not isinstance(past_key_values, Cache):
217
+ past_key_values = Cache.from_legacy_cache(past_key_values)
218
+
219
+ all_hidden_states = () if output_hidden_states else None
220
+ all_attns = () if output_attentions else None
221
+
222
+ for i, layer in enumerate(self.layers):
223
+ if output_hidden_states:
224
+ all_hidden_states += (hidden_states,)
225
+
226
+ hidden_states, attentions, past_key_values = layer(
227
+ hidden_states,
228
+ attention_mask=attention_mask,
229
+ past_key_values=past_key_values,
230
+ use_cache=use_cache,
231
+ output_attentions=output_attentions,
232
+ **kwargs
233
+ )
234
+
235
+ if output_attentions:
236
+ all_attns += (attentions,)
237
+
238
+ hidden_states = self.norm(hidden_states)
239
+
240
+ # add hidden states from the last decoder layer
241
+ if output_hidden_states:
242
+ all_hidden_states += (hidden_states,)
243
+
244
+ if not return_dict:
245
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
246
+ return BaseModelOutputWithPast(
247
+ last_hidden_state=hidden_states,
248
+ past_key_values=past_key_values,
249
+ hidden_states=all_hidden_states,
250
+ attentions=all_attns
251
+ )
252
+
253
+
254
+ class LightNetForCausalLM(LightNetPreTrainedModel, FLAGenerationMixin):
255
+
256
+ _tied_weights_keys = ["lm_head.weight"]
257
+
258
+ def __init__(self, config):
259
+ super().__init__(config)
260
+ self.model = LightNetModel(config)
261
+ self.vocab_size = config.vocab_size
262
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
263
+ self.criterion = None
264
+
265
+ # Initialize weights and apply final processing
266
+ self.post_init()
267
+
268
+ def get_input_embeddings(self):
269
+ return self.model.embeddings
270
+
271
+ def set_input_embeddings(self, value):
272
+ self.model.embeddings = value
273
+
274
+ def get_output_embeddings(self):
275
+ return self.lm_head
276
+
277
+ def set_output_embeddings(self, new_embeddings):
278
+ self.lm_head = new_embeddings
279
+
280
+ def set_decoder(self, decoder):
281
+ self.model = decoder
282
+
283
+ def get_decoder(self):
284
+ return self.model
285
+
286
+ def generate(self, *args, **kwargs):
287
+ try:
288
+ return super().generate(*args, **kwargs)
289
+ except AttributeError as exception:
290
+ if 'past_key_values' in str(exception):
291
+ raise AttributeError(
292
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
293
+ f"which is not supported for {self.__class__.__name__}. "
294
+ f"Try another generation strategy instead. "
295
+ f"For the available generation strategies, check this doc: "
296
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
297
+ )
298
+ else:
299
+ raise exception
300
+
301
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
302
+ def forward(
303
+ self,
304
+ input_ids: torch.LongTensor = None,
305
+ attention_mask: Optional[torch.Tensor] = None,
306
+ inputs_embeds: Optional[torch.Tensor] = None,
307
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
308
+ labels: Optional[torch.LongTensor] = None,
309
+ use_cache: Optional[bool] = None,
310
+ output_attentions: Optional[bool] = None,
311
+ output_hidden_states: Optional[bool] = None,
312
+ return_dict: Optional[bool] = None,
313
+ logits_to_keep: Optional[int] = 0,
314
+ **kwargs: Unpack[Dict]
315
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
316
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
317
+ output_hidden_states = (
318
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
319
+ )
320
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
321
+
322
+ outputs = self.model(
323
+ input_ids=input_ids,
324
+ attention_mask=attention_mask,
325
+ inputs_embeds=inputs_embeds,
326
+ past_key_values=past_key_values,
327
+ use_cache=use_cache,
328
+ output_attentions=output_attentions,
329
+ output_hidden_states=output_hidden_states,
330
+ return_dict=return_dict,
331
+ **kwargs
332
+ )
333
+
334
+ hidden_states = outputs[0]
335
+
336
+ loss, logits = None, None
337
+ if not self.config.fuse_linear_cross_entropy or labels is None:
338
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
339
+ if labels is not None:
340
+ if getattr(self, 'criterion', None) is None:
341
+ if self.config.fuse_linear_cross_entropy:
342
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
343
+ elif self.config.fuse_cross_entropy:
344
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
345
+ else:
346
+ criterion = nn.CrossEntropyLoss()
347
+ else:
348
+ criterion = self.criterion
349
+ labels = labels.to(hidden_states.device)
350
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
351
+ if self.config.fuse_linear_cross_entropy:
352
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
353
+ else:
354
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
355
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
356
+
357
+ if not return_dict:
358
+ output = (logits,) + outputs[1:]
359
+ return (loss,) + output if loss is not None else output
360
+
361
+ return CausalLMOutputWithPast(
362
+ loss=loss,
363
+ logits=logits,
364
+ past_key_values=outputs.past_key_values,
365
+ hidden_states=outputs.hidden_states,
366
+ attentions=outputs.attentions,
367
+ )
models/linear_attn/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.linear_attn.configuration_linear_attn import LinearAttentionConfig
6
+ from fla.models.linear_attn.modeling_linear_attn import LinearAttentionForCausalLM, LinearAttentionModel
7
+
8
+ AutoConfig.register(LinearAttentionConfig.model_type, LinearAttentionConfig, exist_ok=True)
9
+ AutoModel.register(LinearAttentionConfig, LinearAttentionModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(LinearAttentionConfig, LinearAttentionForCausalLM, exist_ok=True)
11
+
12
+ __all__ = ['LinearAttentionConfig', 'LinearAttentionForCausalLM', 'LinearAttentionModel']
models/linear_attn/modeling_linear_attn.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.linear_attn import LinearAttention
18
+ from fla.models.linear_attn.configuration_linear_attn import LinearAttentionConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as LinearAttentionMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class LinearAttentionBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: LinearAttentionConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = LinearAttention(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ expand_k=config.expand_k,
62
+ expand_v=config.expand_v,
63
+ num_heads=config.num_heads,
64
+ num_kv_heads=config.num_kv_heads,
65
+ feature_map=config.feature_map,
66
+ tie_feature_map_qk=config.tie_feature_map_qk,
67
+ norm_q=config.norm_q,
68
+ norm_k=config.norm_k,
69
+ do_feature_map_norm=config.norm_feature_map,
70
+ elementwise_affine=config.elementwise_affine,
71
+ norm_eps=config.norm_eps,
72
+ layer_idx=layer_idx
73
+ )
74
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
75
+ self.mlp = LinearAttentionMLP(
76
+ hidden_size=config.hidden_size,
77
+ hidden_ratio=config.hidden_ratio,
78
+ intermediate_size=config.intermediate_size,
79
+ hidden_act=config.hidden_act,
80
+ fuse_swiglu=config.fuse_swiglu
81
+ )
82
+
83
+ def forward(
84
+ self,
85
+ hidden_states: torch.Tensor,
86
+ attention_mask: Optional[torch.Tensor] = None,
87
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
88
+ use_cache: Optional[bool] = False,
89
+ output_attentions: Optional[bool] = False,
90
+ **kwargs,
91
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
92
+ residual = hidden_states
93
+ # currently not supported
94
+ attentions, past_key_values = None, None
95
+ hidden_states = self.attn_norm(hidden_states)
96
+ hidden_states = self.attn(hidden_states=hidden_states, **kwargs)
97
+ if self.config.fuse_norm:
98
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
99
+ else:
100
+ hidden_states = residual + hidden_states
101
+ residual = hidden_states
102
+ hidden_states = self.mlp_norm(hidden_states)
103
+ hidden_states = self.mlp(hidden_states, **kwargs)
104
+ hidden_states = residual + hidden_states
105
+
106
+ outputs = (hidden_states, attentions, past_key_values)
107
+
108
+ return outputs
109
+
110
+
111
+ class LinearAttentionPreTrainedModel(PreTrainedModel):
112
+
113
+ config_class = LinearAttentionConfig
114
+ base_model_prefix = 'model'
115
+ supports_gradient_checkpointing = True
116
+ _no_split_modules = ['LinearAttentionBlock']
117
+ _supports_cache_class = True
118
+
119
+ def __init__(self, *inputs, **kwargs):
120
+ super().__init__(*inputs, **kwargs)
121
+
122
+ def _init_weights(
123
+ self,
124
+ module: nn.Module,
125
+ prenorm_residual_strategy: Optional[str] = None,
126
+ num_residuals_per_layer: int = 2,
127
+ ):
128
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
129
+ # Slightly different from the TF version which uses truncated_normal for initialization
130
+ # cf https://github.com/pytorch/pytorch/pull/5617
131
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
132
+ if module.bias is not None:
133
+ nn.init.zeros_(module.bias)
134
+ elif isinstance(module, nn.Embedding):
135
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
136
+ elif hasattr(module, 'reset_parameters'):
137
+ module.reset_parameters()
138
+
139
+ if prenorm_residual_strategy is not None:
140
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
141
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
142
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
143
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
144
+ #
145
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
146
+ p = None
147
+ if hasattr(module, 'o_proj'):
148
+ p = module.o_proj.weight
149
+ elif hasattr(module, 'down_proj'):
150
+ p = module.down_proj.weight
151
+ if p is not None:
152
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
153
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
154
+ # We need to reinit p since this code could be called multiple times
155
+ # Having just p *= scale would repeatedly scale it down
156
+ if prenorm_residual_strategy == 'rescale':
157
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
158
+ with torch.no_grad():
159
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
160
+ elif prenorm_residual_strategy == 'zero':
161
+ nn.init.zeros_(p)
162
+ else:
163
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
164
+
165
+
166
+ class LinearAttentionModel(LinearAttentionPreTrainedModel):
167
+
168
+ def __init__(self, config: LinearAttentionConfig):
169
+ super().__init__(config)
170
+ self.padding_idx = config.pad_token_id
171
+ self.vocab_size = config.vocab_size
172
+
173
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
174
+ self.layers = nn.ModuleList([LinearAttentionBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
175
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
176
+
177
+ self.gradient_checkpointing = False
178
+
179
+ self.post_init()
180
+
181
+ def get_input_embeddings(self):
182
+ return self.embeddings
183
+
184
+ def set_input_embeddings(self, value):
185
+ self.embeddings = value
186
+
187
+ def forward(
188
+ self,
189
+ input_ids: Optional[torch.LongTensor] = None,
190
+ attention_mask: Optional[torch.Tensor] = None, # noqa
191
+ inputs_embeds: Optional[torch.FloatTensor] = None,
192
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
193
+ use_cache: Optional[bool] = None,
194
+ output_attentions: Optional[bool] = None,
195
+ output_hidden_states: Optional[bool] = None,
196
+ return_dict: Optional[bool] = None
197
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
198
+ if output_attentions:
199
+ warnings.warn(
200
+ "`LinearAttentionModel` does not support output attention weights now, "
201
+ "so `output_attentions` is set to `False`."
202
+ )
203
+ output_attentions = False
204
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
205
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
206
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
207
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
208
+
209
+ # retrieve input_ids and inputs_embeds
210
+ if input_ids is not None and inputs_embeds is not None:
211
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
212
+ if input_ids is None and inputs_embeds is None:
213
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
214
+
215
+ if inputs_embeds is None:
216
+ inputs_embeds = self.embeddings(input_ids)
217
+ hidden_states = inputs_embeds
218
+
219
+ if use_cache and not isinstance(past_key_values, Cache):
220
+ past_key_values = Cache.from_legacy_cache(past_key_values)
221
+
222
+ all_hidden_states = () if output_hidden_states else None
223
+ all_attns = () if output_attentions else None
224
+
225
+ for i, layer in enumerate(self.layers):
226
+ if output_hidden_states:
227
+ all_hidden_states += (hidden_states,)
228
+
229
+ hidden_states, attentions, past_key_values = layer(
230
+ hidden_states,
231
+ attention_mask=attention_mask,
232
+ past_key_values=past_key_values,
233
+ use_cache=use_cache,
234
+ output_attentions=output_attentions
235
+ )
236
+
237
+ if output_attentions:
238
+ all_attns += (attentions,)
239
+
240
+ hidden_states = self.norm(hidden_states)
241
+
242
+ # add hidden states from the last decoder layer
243
+ if output_hidden_states:
244
+ all_hidden_states += (hidden_states,)
245
+
246
+ if not return_dict:
247
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
248
+ return BaseModelOutputWithPast(
249
+ last_hidden_state=hidden_states,
250
+ past_key_values=past_key_values,
251
+ hidden_states=all_hidden_states,
252
+ attentions=all_attns
253
+ )
254
+
255
+
256
+ class LinearAttentionForCausalLM(LinearAttentionPreTrainedModel, FLAGenerationMixin):
257
+
258
+ _tied_weights_keys = ["lm_head.weight"]
259
+
260
+ def __init__(self, config):
261
+ super().__init__(config)
262
+ self.model = LinearAttentionModel(config)
263
+ self.vocab_size = config.vocab_size
264
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
265
+ self.criterion = None
266
+
267
+ # Initialize weights and apply final processing
268
+ self.post_init()
269
+
270
+ def get_input_embeddings(self):
271
+ return self.model.embeddings
272
+
273
+ def set_input_embeddings(self, value):
274
+ self.model.embeddings = value
275
+
276
+ def get_output_embeddings(self):
277
+ return self.lm_head
278
+
279
+ def set_output_embeddings(self, new_embeddings):
280
+ self.lm_head = new_embeddings
281
+
282
+ def set_decoder(self, decoder):
283
+ self.model = decoder
284
+
285
+ def get_decoder(self):
286
+ return self.model
287
+
288
+ def generate(self, *args, **kwargs):
289
+ try:
290
+ return super().generate(*args, **kwargs)
291
+ except AttributeError as exception:
292
+ if 'past_key_values' in str(exception):
293
+ raise AttributeError(
294
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
295
+ f"which is not supported for {self.__class__.__name__}. "
296
+ f"Try another generation strategy instead. "
297
+ f"For the available generation strategies, check this doc: "
298
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
299
+ )
300
+ else:
301
+ raise exception
302
+
303
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
304
+ def forward(
305
+ self,
306
+ input_ids: torch.LongTensor = None,
307
+ attention_mask: Optional[torch.Tensor] = None,
308
+ inputs_embeds: Optional[torch.Tensor] = None,
309
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
310
+ labels: Optional[torch.LongTensor] = None,
311
+ use_cache: Optional[bool] = None,
312
+ output_attentions: Optional[bool] = None,
313
+ output_hidden_states: Optional[bool] = None,
314
+ return_dict: Optional[bool] = None,
315
+ logits_to_keep: Optional[int] = 0,
316
+ **kwargs: Unpack[Dict]
317
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
318
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
319
+ output_hidden_states = (
320
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
321
+ )
322
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
323
+
324
+ outputs = self.model(
325
+ input_ids=input_ids,
326
+ attention_mask=attention_mask,
327
+ inputs_embeds=inputs_embeds,
328
+ past_key_values=past_key_values,
329
+ use_cache=use_cache,
330
+ output_attentions=output_attentions,
331
+ output_hidden_states=output_hidden_states,
332
+ return_dict=return_dict
333
+ )
334
+
335
+ hidden_states = outputs[0]
336
+
337
+ loss, logits = None, None
338
+ if not self.config.fuse_linear_cross_entropy or labels is None:
339
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
340
+ if labels is not None:
341
+ if getattr(self, 'criterion', None) is None:
342
+ if self.config.fuse_linear_cross_entropy:
343
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
344
+ elif self.config.fuse_cross_entropy:
345
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
346
+ else:
347
+ criterion = nn.CrossEntropyLoss()
348
+ else:
349
+ criterion = self.criterion
350
+ labels = labels.to(hidden_states.device)
351
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
352
+ if self.config.fuse_linear_cross_entropy:
353
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
354
+ else:
355
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
356
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
357
+
358
+ if not return_dict:
359
+ output = (logits,) + outputs[1:]
360
+ return (loss,) + output if loss is not None else output
361
+
362
+ return CausalLMOutputWithPast(
363
+ loss=loss,
364
+ logits=logits,
365
+ past_key_values=outputs.past_key_values,
366
+ hidden_states=outputs.hidden_states,
367
+ attentions=outputs.attentions,
368
+ )
models/log_linear_mamba2/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.log_linear_mamba2.configuration_log_linear_mamba2 import LogLinearMamba2Config
6
+ from fla.models.log_linear_mamba2.modeling_log_linear_mamba2 import (
7
+ LogLinearMamba2Block,
8
+ LogLinearMamba2ForCausalLM,
9
+ LogLinearMamba2Model
10
+ )
11
+
12
+ AutoConfig.register(LogLinearMamba2Config.model_type, LogLinearMamba2Config, exist_ok=True)
13
+ AutoModel.register(LogLinearMamba2Config, LogLinearMamba2Model, exist_ok=True)
14
+ AutoModelForCausalLM.register(LogLinearMamba2Config, LogLinearMamba2ForCausalLM, exist_ok=True)
15
+
16
+
17
+ __all__ = ['LogLinearMamba2Config', 'LogLinearMamba2ForCausalLM', 'LogLinearMamba2Model', 'LogLinearMamba2Block']
models/log_linear_mamba2/modeling_log_linear_mamba2.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ from typing import Optional, Tuple, Union
4
+
5
+ import torch
6
+ from torch import nn
7
+ from transformers.modeling_utils import PreTrainedModel
8
+ from transformers.utils import logging
9
+ from transformers.utils.deprecation import deprecate_kwarg
10
+
11
+ from fla.layers.log_linear_mamba2 import LogLinearAttentionState, LogLinearMamba2
12
+ from fla.models.log_linear_mamba2.configuration_log_linear_mamba2 import LogLinearMamba2Config
13
+ from fla.models.mamba2.modeling_mamba2 import Mamba2Cache, Mamba2CausalLMOutput, Mamba2Output
14
+ from fla.models.utils import FLAGenerationMixin
15
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss, GatedMLP, RMSNorm
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ class LogLinearMamba2Cache(Mamba2Cache):
21
+ def __init__(
22
+ self,
23
+ config: LogLinearMamba2Config,
24
+ batch_size: int,
25
+ dtype: torch.dtype = torch.float16,
26
+ device: Optional[str] = None,
27
+ ):
28
+ self.dtype = dtype
29
+ self.conv_kernel_size = config.conv_kernel
30
+ self.n_groups = config.n_groups
31
+ self.state_size = config.state_size
32
+ self.num_heads = config.num_heads
33
+ self.head_dim = config.head_dim
34
+ self.intermediate_size = int(config.expand * config.hidden_size)
35
+
36
+ self.conv_states = {
37
+ i: torch.zeros(
38
+ batch_size,
39
+ self.intermediate_size + 2 * config.n_groups * config.state_size,
40
+ self.conv_kernel_size,
41
+ device=device,
42
+ dtype=dtype,
43
+ )
44
+ for i in range(config.num_hidden_layers)
45
+ }
46
+ self.hssm_states = {
47
+ i: None for i in range(config.num_hidden_layers)
48
+ }
49
+
50
+ def update_conv_state(
51
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
52
+ ) -> torch.Tensor:
53
+ if new_conv_state.dtype != self.conv_states[layer_idx].dtype:
54
+ warnings.warn(
55
+ f"`new_conv_state.dtype` ({new_conv_state.dtype}) does not match the cache's dtype "
56
+ f"({self.conv_states[layer_idx].dtype}), casting.",
57
+ stacklevel=2
58
+ )
59
+ new_conv_state = new_conv_state.to(dtype=self.conv_states[layer_idx].dtype)
60
+
61
+ if cache_init:
62
+ self.conv_states[layer_idx] = new_conv_state.to(
63
+ self.conv_states[layer_idx].device
64
+ )
65
+ else:
66
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(
67
+ shifts=-1, dims=-1
68
+ )
69
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(
70
+ self.conv_states[layer_idx].device
71
+ )
72
+ return self.conv_states[layer_idx]
73
+
74
+ def update_hssm_state(
75
+ self, layer_idx: int, new_hssm_state: LogLinearAttentionState
76
+ ) -> LogLinearAttentionState:
77
+ self.hssm_states[layer_idx] = new_hssm_state
78
+ return self.hssm_states[layer_idx]
79
+
80
+ def reset(self) -> None:
81
+ for k in self.conv_states.keys():
82
+ self.conv_states[k].zero_()
83
+ for k in self.hssm_states.keys():
84
+ self.hssm_states[k].reset_states()
85
+
86
+
87
+ class LogLinearMamba2Block(nn.Module):
88
+ def __init__(self, config: LogLinearMamba2Config, layer_idx: int) -> None:
89
+ super().__init__()
90
+ if config.residual_in_fp32:
91
+ raise NotImplementedError
92
+ self.config = config
93
+ self.layer_idx = layer_idx
94
+ self.mixer_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
95
+ self.mlp_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
96
+ self.mixer = LogLinearMamba2(
97
+ num_heads=config.num_heads,
98
+ head_dim=config.head_dim,
99
+ hidden_size=config.hidden_size,
100
+ state_size=config.state_size,
101
+ expand=config.expand,
102
+ n_groups=config.n_groups,
103
+ conv_kernel=config.conv_kernel,
104
+ use_conv_bias=config.use_conv_bias,
105
+ hidden_act=config.hidden_act,
106
+ rms_norm=config.rms_norm,
107
+ chunk_size=config.chunk_size,
108
+ time_step_rank=config.time_step_rank,
109
+ time_step_limit=config.time_step_limit,
110
+ time_step_min=config.time_step_min,
111
+ time_step_max=config.time_step_max,
112
+ use_bias=config.use_bias,
113
+ norm_eps=config.norm_eps,
114
+ layer_idx=layer_idx,
115
+ )
116
+ self.mlp = GatedMLP(
117
+ hidden_size=config.hidden_size,
118
+ hidden_ratio=4,
119
+ intermediate_size=None,
120
+ hidden_act="swish",
121
+ fuse_swiglu=True,
122
+ )
123
+
124
+ def forward(
125
+ self,
126
+ hidden_states,
127
+ cache_params: Optional[LogLinearMamba2Cache] = None,
128
+ cache_position: Optional[torch.LongTensor] = None,
129
+ attention_mask: Optional[torch.Tensor] = None,
130
+ ):
131
+ residual = hidden_states
132
+ hidden_states = self.mixer_norm(hidden_states)
133
+ hidden_states = self.mixer(
134
+ hidden_states,
135
+ cache_params=cache_params,
136
+ cache_position=cache_position,
137
+ attention_mask=attention_mask,
138
+ )
139
+ if self.config.fuse_norm:
140
+ hidden_states, residual = self.mlp_norm(
141
+ hidden_states, residual=residual, prenorm=True
142
+ )
143
+ else:
144
+ hidden_states = residual + hidden_states
145
+ residual = hidden_states
146
+ hidden_states = self.mlp_norm(hidden_states)
147
+ hidden_states = self.mlp(hidden_states)
148
+ hidden_states = residual + hidden_states
149
+ return hidden_states
150
+
151
+
152
+ class LogLinearMamba2PreTrainedModel(PreTrainedModel, FLAGenerationMixin):
153
+ """
154
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
155
+ models.
156
+ """
157
+
158
+ config_class = LogLinearMamba2Config
159
+ base_model_prefix = "backbone"
160
+ _no_split_modules = ["LogLinearMamba2Block"]
161
+ supports_gradient_checkpointing = True
162
+ _is_stateful = True
163
+
164
+ def _init_weights(
165
+ self,
166
+ module: nn.Module,
167
+ num_residuals_per_layer: int = 2, # HAttention + MLP
168
+ ):
169
+ """Initialize the weights."""
170
+ if isinstance(module, LogLinearMamba2):
171
+ # --- A_log ---
172
+ A = torch.arange(1, module.num_heads + 1)
173
+ with torch.no_grad():
174
+ if not isinstance(module.A_log, torch.distributed.tensor.DTensor):
175
+ module.A_log.copy_(torch.log(A))
176
+ else:
177
+ logger.warning_once("`A_log` is a DTensor, skipping initialization")
178
+ module.A_log._no_weight_decay = True
179
+
180
+ # --- D ---
181
+ nn.init.ones_(module.D)
182
+ module.D._no_weight_decay = True
183
+
184
+ # --- L ---
185
+ nn.init.ones_(module.L)
186
+ module.L._no_weight_decay = True
187
+
188
+ # --- dt_bias ---
189
+ dt = torch.exp(
190
+ torch.rand(self.config.num_heads)
191
+ * (
192
+ math.log(self.config.time_step_max)
193
+ - math.log(self.config.time_step_min)
194
+ )
195
+ + math.log(self.config.time_step_min)
196
+ ).clamp(min=self.config.time_step_floor)
197
+
198
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
199
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
200
+ with torch.no_grad():
201
+ if not isinstance(module.dt_bias, torch.distributed.tensor.DTensor):
202
+ module.dt_bias.copy_(inv_dt)
203
+ else:
204
+ logger.warning_once(
205
+ "`dt_bias` is a DTensor, skipping initialization"
206
+ )
207
+ module.dt_bias._no_reinit = True
208
+
209
+ elif isinstance(module, (nn.Linear, nn.Conv1d)):
210
+ # Slightly different from the TF version which uses truncated_normal for initialization
211
+ # cf https://github.com/pytorch/pytorch/pull/5617
212
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
213
+ if module.bias is not None:
214
+ nn.init.zeros_(module.bias)
215
+ # guard against deprecated behavior
216
+ if hasattr(module.bias, "_no_reinit"):
217
+ raise ValueError("This is not supposed to happen")
218
+ elif isinstance(module, nn.Embedding):
219
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
220
+ elif hasattr(module, "reset_parameters"):
221
+ module.reset_parameters()
222
+
223
+ if self.config.rescale_prenorm_residual:
224
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
225
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
226
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
227
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
228
+ #
229
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
230
+ p = None
231
+ if hasattr(module, "o_proj"):
232
+ # p = module.o_proj.weight
233
+ # guard against deprecated behavior
234
+ raise ValueError("This is not supposed to happen")
235
+ elif hasattr(module, "out_proj"):
236
+ p = module.out_proj.weight
237
+ elif hasattr(module, "down_proj"):
238
+ p = module.down_proj.weight
239
+ if p is not None:
240
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
241
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
242
+ # We need to reinit p since this code could be called multiple times
243
+ # Having just p *= scale would repeatedly scale it down
244
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
245
+ with torch.no_grad():
246
+ p /= math.sqrt(
247
+ num_residuals_per_layer * self.config.num_hidden_layers
248
+ )
249
+
250
+
251
+ class LogLinearMamba2Model(LogLinearMamba2PreTrainedModel):
252
+ def __init__(self, config):
253
+ super().__init__(config)
254
+
255
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
256
+ self.layers = nn.ModuleList(
257
+ [
258
+ LogLinearMamba2Block(config, layer_idx=idx)
259
+ for idx in range(config.num_hidden_layers)
260
+ ]
261
+ )
262
+
263
+ self.gradient_checkpointing = False
264
+ self.norm_f = RMSNorm(config.hidden_size, eps=config.norm_eps)
265
+ # Initialize weights and apply final processing
266
+ self._register_load_state_dict_pre_hook(self.load_hook)
267
+ self.post_init()
268
+
269
+ def load_hook(self, state_dict, prefix, *args):
270
+ for k in state_dict:
271
+ if "embedding." in k:
272
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
273
+ break
274
+
275
+ def get_input_embeddings(self):
276
+ return self.embeddings
277
+
278
+ def set_input_embeddings(self, new_embeddings):
279
+ self.embeddings = new_embeddings
280
+
281
+ def forward(
282
+ self,
283
+ input_ids: Optional[torch.LongTensor] = None,
284
+ inputs_embeds: Optional[torch.LongTensor] = None,
285
+ cache_params: Optional[LogLinearMamba2Cache] = None,
286
+ use_cache: Optional[bool] = None,
287
+ output_hidden_states: Optional[bool] = None,
288
+ return_dict: Optional[bool] = None,
289
+ cache_position: Optional[torch.LongTensor] = None,
290
+ attention_mask: Optional[torch.Tensor] = None,
291
+ **kwargs,
292
+ ) -> Union[Tuple, Mamba2Output]:
293
+ output_hidden_states = (
294
+ output_hidden_states
295
+ if output_hidden_states is not None
296
+ else self.config.output_hidden_states
297
+ )
298
+ use_cache = (
299
+ use_cache
300
+ if use_cache is not None
301
+ else (self.config.use_cache if not self.training else False)
302
+ )
303
+ return_dict = (
304
+ return_dict if return_dict is not None else self.config.use_return_dict
305
+ )
306
+
307
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
308
+ raise ValueError(
309
+ "You must specify exactly one of input_ids or inputs_embeds"
310
+ )
311
+
312
+ if inputs_embeds is None:
313
+ inputs_embeds = self.embeddings(input_ids)
314
+
315
+ if self.gradient_checkpointing and self.training and use_cache:
316
+ use_cache = False
317
+
318
+ if use_cache:
319
+ if cache_params is None:
320
+ cache_params = LogLinearMamba2Cache(
321
+ self.config,
322
+ inputs_embeds.size(0),
323
+ device=inputs_embeds.device,
324
+ dtype=inputs_embeds.dtype,
325
+ )
326
+ cache_position = torch.arange(
327
+ 0, self.config.conv_kernel, device=inputs_embeds.device
328
+ )
329
+ elif cache_position is None:
330
+ # cases when we do manual forward instead of using `model.generate` which will initiate
331
+ # `cache_position` and makes sure it is not None, throw error here instead of doing some
332
+ # hack to conjecture the current cache position
333
+ raise ValueError(
334
+ "You have to specify the `cache_position` manually when `use_cache=True` and `cache_params` is passed, "
335
+ "you don't have to pass a `cache_params` if you are in prefilling stage because in that case it will "
336
+ "be initialized for you automatically"
337
+ )
338
+ else:
339
+ cache_params = None
340
+
341
+ hidden_states = inputs_embeds
342
+ all_hidden_states = () if output_hidden_states else None
343
+ for mixer_block in self.layers:
344
+ if self.gradient_checkpointing and self.training:
345
+ hidden_states = self._gradient_checkpointing_func(
346
+ mixer_block.__call__,
347
+ hidden_states,
348
+ cache_params,
349
+ cache_position,
350
+ attention_mask,
351
+ )
352
+ else:
353
+ hidden_states = mixer_block(
354
+ hidden_states,
355
+ cache_params=cache_params,
356
+ cache_position=cache_position,
357
+ attention_mask=attention_mask,
358
+ )
359
+
360
+ if output_hidden_states:
361
+ all_hidden_states = all_hidden_states + (hidden_states,)
362
+
363
+ hidden_states = self.norm_f(hidden_states)
364
+
365
+ if output_hidden_states:
366
+ all_hidden_states = all_hidden_states + (hidden_states,)
367
+
368
+ if not return_dict:
369
+ return tuple(
370
+ v
371
+ for v in [hidden_states, cache_params, all_hidden_states]
372
+ if v is not None
373
+ )
374
+
375
+ return Mamba2Output(
376
+ last_hidden_state=hidden_states,
377
+ cache_params=cache_params if use_cache else None,
378
+ hidden_states=all_hidden_states,
379
+ )
380
+
381
+
382
+ class LogLinearMamba2ForCausalLM(LogLinearMamba2PreTrainedModel):
383
+ _tied_weights_keys = []
384
+
385
+ def __init__(self, config):
386
+ super().__init__(config)
387
+ self.backbone = LogLinearMamba2Model(config)
388
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
389
+ self.criterion = None
390
+
391
+ # Initialize weights and apply final processing
392
+ self.post_init()
393
+
394
+ def get_output_embeddings(self):
395
+ return self.lm_head
396
+
397
+ def set_output_embeddings(self, new_embeddings):
398
+ self.lm_head = new_embeddings
399
+
400
+ def get_input_embeddings(self):
401
+ return self.backbone.get_input_embeddings()
402
+
403
+ def set_input_embeddings(self, new_embeddings):
404
+ return self.backbone.set_input_embeddings(new_embeddings)
405
+
406
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
407
+ def forward(
408
+ self,
409
+ input_ids: Optional[torch.LongTensor] = None,
410
+ inputs_embeds: Optional[torch.FloatTensor] = None,
411
+ cache_params: Optional[LogLinearMamba2Cache] = None,
412
+ labels: Optional[torch.LongTensor] = None,
413
+ output_hidden_states: Optional[bool] = None,
414
+ return_dict: Optional[bool] = None,
415
+ use_cache: Optional[bool] = None,
416
+ cache_position: Optional[torch.Tensor] = None,
417
+ attention_mask: Optional[torch.Tensor] = None,
418
+ logits_to_keep: Optional[int] = 0,
419
+ **kwargs, # for now we need this for generation
420
+ ) -> Union[Tuple, Mamba2CausalLMOutput]:
421
+ r"""
422
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
423
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
424
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
425
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
426
+ """
427
+ return_dict = (
428
+ return_dict if return_dict is not None else self.config.use_return_dict
429
+ )
430
+
431
+ outputs = self.backbone(
432
+ input_ids,
433
+ cache_params=cache_params,
434
+ inputs_embeds=inputs_embeds,
435
+ output_hidden_states=output_hidden_states,
436
+ return_dict=return_dict,
437
+ use_cache=use_cache,
438
+ cache_position=cache_position,
439
+ attention_mask=attention_mask,
440
+ )
441
+ hidden_states = outputs[0]
442
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training
443
+
444
+ loss, logits = None, None
445
+ if not fuse_linear_and_cross_entropy or labels is None:
446
+ logits = self.lm_head(
447
+ hidden_states
448
+ if logits_to_keep is None
449
+ else hidden_states[:, -logits_to_keep:]
450
+ )
451
+ if labels is not None:
452
+ if getattr(self, "criterion", None) is None:
453
+ if fuse_linear_and_cross_entropy:
454
+ criterion = FusedLinearCrossEntropyLoss()
455
+ elif self.config.fuse_cross_entropy:
456
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
457
+ else:
458
+ criterion = nn.CrossEntropyLoss()
459
+ else:
460
+ criterion = self.criterion
461
+ labels = labels.to(hidden_states.device)
462
+ labels = torch.cat(
463
+ (
464
+ labels[..., 1:],
465
+ torch.full_like(labels[:, :1], criterion.ignore_index),
466
+ ),
467
+ 1,
468
+ )
469
+ if fuse_linear_and_cross_entropy:
470
+ loss = criterion(
471
+ hidden_states, labels, self.lm_head.weight, self.lm_head.bias
472
+ )
473
+ else:
474
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
475
+
476
+ if not return_dict:
477
+ output = (logits,) + outputs[1:]
478
+ return (loss,) + output if loss is not None else output
479
+
480
+ return Mamba2CausalLMOutput(
481
+ loss=loss,
482
+ logits=logits,
483
+ cache_params=outputs.cache_params,
484
+ hidden_states=outputs.hidden_states,
485
+ )
models/mamba/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.mamba.configuration_mamba import MambaConfig
6
+ from fla.models.mamba.modeling_mamba import MambaBlock, MambaForCausalLM, MambaModel
7
+
8
+ AutoConfig.register(MambaConfig.model_type, MambaConfig, exist_ok=True)
9
+ AutoModel.register(MambaConfig, MambaModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(MambaConfig, MambaForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['MambaConfig', 'MambaForCausalLM', 'MambaModel', 'MambaBlock']
models/mamba/configuration_mamba.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import math
17
+ import warnings
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+
21
+
22
+ class MambaConfig(PretrainedConfig):
23
+ """
24
+ This is the configuration class to store the configuration of a [`MambaModel`]. It is used to instantiate a MAMBA
25
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
26
+ defaults will yield a similar configuration to that of the MAMBA
27
+ [state-spaces/mamba-2.8b](https://huggingface.co/state-spaces/mamba-2.8b) architecture.
28
+
29
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
30
+ documentation from [`PretrainedConfig`] for more information.
31
+
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*):
35
+ Vocabulary size of the Mamba model.
36
+ hidden_size (`int`, *optional*):
37
+ Dimensionality of the embeddings and hidden states. Default: 2048.
38
+ state_size (`int`, *optional*):
39
+ Shape of the state space latents. Default: 16.
40
+ num_hidden_layers (`int`, *optional*):
41
+ Number of hidden layers in the model. Default: 48.
42
+ norm_eps (`float`, *optional*):
43
+ The epsilon to use in the layer normalization layers. Default: 1e-5.
44
+ pad_token_id (`int`, *optional*):
45
+ Padding token id. Default: 0.
46
+ bos_token_id (`int`, *optional*):
47
+ The id of the beginning of sentence token in the vocabulary. Default: 0.
48
+ eos_token_id (`int`, *optional*):
49
+ The id of the end of sentence token in the vocabulary. Default: 0.
50
+ expand (`int`, *optional*):
51
+ Expanding factor used to determine the intermediate size. Default: 2.
52
+ conv_kernel (`int`, *optional*):
53
+ Size of the convolution kernel. Default: 4.
54
+ use_bias (`bool`, *optional*):
55
+ Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block. Default: `False`.
56
+ use_conv_bias (`bool`, *optional*):
57
+ Whether or not to use bias in the convolution layer of the mixer block. Default: `True`.
58
+ hidden_act (`str`, *optional*):
59
+ The non-linear activation function (function or string) in the decoder. Default: `"silu"`.
60
+ initializer_range (`float`, *optional*):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices. Default: 0.02.
62
+ residual_in_fp32 (`bool`, *optional*):
63
+ Whether or not residuals should be in `float32`.
64
+ If set to `False` residuals will keep the same `dtype` as the rest of the model. Default: `True`.
65
+ time_step_rank (`Union[int,str]`, *optional*):
66
+ Rank of the the discretization projection matrix.
67
+ `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`. Default: `"auto"`.
68
+ time_step_scale (`float`, *optional*):
69
+ Scale used used to scale `dt_proj.bias`. Default: 1.0.
70
+ time_step_min (`float`, *optional*):
71
+ Minimum `time_step` used to bound `dt_proj.bias`. Default: 0.001.
72
+ time_step_max (`float`, *optional*):
73
+ Maximum `time_step` used to bound `dt_proj.bias`. Default: 0.1.
74
+ time_step_init_scheme (`float`, *optional*):
75
+ Init scheme used for `dt_proj.weight`. Should be one of `["random","uniform"]`. Default: `"random"`.
76
+ time_step_floor (`float`, *optional*):
77
+ Minimum clamping value of the `dt_proj.bias` layer initialization. Default: 0.0001.
78
+ window_size (`int`, *optional*):
79
+ The window size used for sliding window attention. Default: 2048.
80
+ rescale_prenorm_residual (`bool`, *optional*):
81
+ Whether or not to rescale `out_proj` weights when initializing. Default: `False`.
82
+ use_cache (`bool`, *optional*):
83
+ Whether or not the cache should be used. Default: `True`.
84
+
85
+
86
+ Example:
87
+
88
+ ```python
89
+ >>> from transformers import MambaConfig, MambaModel
90
+
91
+ >>> # Initializing a Mamba configuration
92
+ >>> configuration = MambaConfig()
93
+
94
+ >>> # Initializing a model (with random weights) from the configuration
95
+ >>> model = MambaModel(configuration)
96
+
97
+ >>> # Accessing the model configuration
98
+ >>> configuration = model.config
99
+ ```"""
100
+
101
+ model_type = "mamba"
102
+
103
+ def __init__(
104
+ self,
105
+ vocab_size: int = 32000,
106
+ hidden_size: int = 2048,
107
+ state_size: int = 16,
108
+ num_hidden_layers: int = 48,
109
+ norm_eps=1e-5,
110
+ pad_token_id: int = 0,
111
+ bos_token_id: int = 1,
112
+ eos_token_id: int = 2,
113
+ expand: int = 2,
114
+ conv_kernel: int = 4,
115
+ use_bias: bool = False,
116
+ use_conv_bias: bool = True,
117
+ hidden_act: str = "silu",
118
+ initializer_range: float = 0.02,
119
+ residual_in_fp32: bool = False,
120
+ time_step_rank: str = "auto",
121
+ time_step_scale: float = 1.0,
122
+ time_step_min: float = 0.001,
123
+ time_step_max: float = 0.1,
124
+ time_step_init_scheme: str = "random",
125
+ time_step_floor: float = 1e-4,
126
+ rescale_prenorm_residual: bool = False,
127
+ use_cache: bool = True,
128
+ fuse_norm: bool = True,
129
+ fuse_cross_entropy: bool = True,
130
+ fuse_linear_cross_entropy: bool = False,
131
+ use_l2warp: bool = False,
132
+ tie_word_embeddings: bool = False,
133
+ **kwargs,
134
+ ):
135
+ self.vocab_size = vocab_size
136
+ self.hidden_size = hidden_size
137
+ self.state_size = state_size
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.norm_eps = norm_eps
140
+ self.conv_kernel = conv_kernel
141
+ self.expand = expand
142
+ self.intermediate_size = int(expand * self.hidden_size)
143
+ self.bos_token_id = bos_token_id
144
+ self.eos_token_id = eos_token_id
145
+ self.pad_token_id = pad_token_id
146
+ self.use_bias = use_bias
147
+ self.use_conv_bias = use_conv_bias
148
+ self.hidden_act = hidden_act
149
+ self.initializer_range = initializer_range
150
+ self.time_step_rank = math.ceil(self.hidden_size / 16) if time_step_rank == "auto" else time_step_rank
151
+ self.time_step_scale = time_step_scale
152
+ self.time_step_min = time_step_min
153
+ self.time_step_max = time_step_max
154
+ self.time_step_init_scheme = time_step_init_scheme
155
+ self.time_step_floor = time_step_floor
156
+ self.rescale_prenorm_residual = rescale_prenorm_residual
157
+ self.residual_in_fp32 = residual_in_fp32
158
+ self.use_cache = use_cache
159
+ self.fuse_norm = fuse_norm
160
+ self.fuse_cross_entropy = fuse_cross_entropy
161
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
162
+ self.use_l2warp = use_l2warp
163
+
164
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
165
+ raise ValueError(
166
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
167
+ )
168
+ if fuse_linear_cross_entropy:
169
+ warnings.warn(
170
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
171
+ "at the potential cost of reduced precision. "
172
+ "If you observe issues like loss divergence, consider disabling this setting."
173
+ )
174
+
175
+ super().__init__(
176
+ bos_token_id=bos_token_id,
177
+ eos_token_id=eos_token_id,
178
+ pad_token_id=pad_token_id,
179
+ tie_word_embeddings=tie_word_embeddings,
180
+ **kwargs
181
+ )
models/mamba/modeling_mamba.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 state-spaces/mamba org and HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from dataclasses import dataclass
17
+ from typing import Any, Dict, Optional, Tuple, Union
18
+
19
+ import torch
20
+ from torch import nn
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.modeling_utils import PreTrainedModel
23
+ from transformers.utils import ModelOutput, logging
24
+ from transformers.utils.deprecation import deprecate_kwarg
25
+
26
+ from fla.layers.mamba import Mamba
27
+ from fla.models.mamba.configuration_mamba import MambaConfig
28
+ from fla.models.utils import FLAGenerationMixin
29
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss, RMSNorm
30
+ from fla.modules.l2warp import l2_warp
31
+
32
+ try:
33
+ from transformers.modeling_layers import GradientCheckpointingLayer
34
+ except ImportError:
35
+ from fla.models.modeling_layers import GradientCheckpointingLayer
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ class MambaCache:
41
+ """
42
+ Cache for mamba model which does not have attention mechanism and key value states.
43
+
44
+ Arguments:
45
+ config (`PretrainedConfig):
46
+ The configuration file defining the shape-related attributes required to initialize the static cache.
47
+ batch_size (`int`):
48
+ The batch size with which the model will be used. Note that a new instance must be instantiated if a
49
+ smaller batch size is used.
50
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
51
+ The default `dtype` to use when initializing the layer.
52
+ device (`torch.device` or `str`, *optional*):
53
+ The device on which the cache should be initialized. Should be the same as the layer.
54
+
55
+ Attributes:
56
+ dtype: (`torch.dtype`):
57
+ The default `dtype` used to initializing the cache.
58
+ intermediate_size: (`int`):
59
+ Model's intermediate_size taken from config.
60
+ ssm_state_size: (`int`):
61
+ Model's state_size taken from config.
62
+ conv_kernel_size: (`int`):
63
+ Model's convolution kernel size taken from config
64
+ conv_states: (`torch.Tensor`):
65
+ A tensor of shape `[layer_idx, batch_size, intermediate_size, conv_kernel_size]` that holds convolutional states.
66
+ ssm_states: (`torch.Tensor`):
67
+ A tensor of shape `[layer_idx, batch_size, intermediate_size, ssm_state_size]` that holds ssm states
68
+
69
+ Example:
70
+
71
+ ```python
72
+ >>> from transformers import AutoTokenizer, MambaForCausalLM, MambaCache
73
+
74
+ >>> model = MambaForCausalLM.from_pretrained("state-spaces/mamba-130m-hf")
75
+ >>> tokenizer = AutoTokenizer.from_pretrained("state-spaces/mamba-130m-hf")
76
+
77
+ >>> inputs = tokenizer(text="My name is Mamba", return_tensors="pt")
78
+
79
+ >>> # Prepare a cache class and pass it to model's forward
80
+ >>> past_key_values = MambaCache(config=model.config, batch_size=1, device=model.device, dtype=model.dtype)
81
+ >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
82
+ >>> outputs.past_key_values
83
+ MambaCache()
84
+ ```
85
+ """
86
+
87
+ # TODO (joao): remove `=None` in non-optional arguments in v4.46. Remove from `OBJECTS_TO_IGNORE` as well.
88
+ def __init__(
89
+ self,
90
+ config: PretrainedConfig,
91
+ batch_size: int = None,
92
+ dtype: torch.dtype = torch.float16,
93
+ device: Optional[Union[torch.device, str]] = None,
94
+ max_batch_size: Optional[int] = None,
95
+ ):
96
+ if max_batch_size is not None:
97
+ logger.warning_once(
98
+ f"The 'max_batch_size' argument of {self.__class__.__name__} is deprecated and will be removed in "
99
+ "v4.46. Use the more precisely named 'batch_size' argument instead."
100
+ )
101
+ self.dtype = dtype
102
+ self.batch_size = batch_size or max_batch_size
103
+ self.intermediate_size = config.intermediate_size
104
+ self.ssm_state_size = config.state_size
105
+ self.conv_kernel_size = config.conv_kernel
106
+
107
+ self.conv_states: torch.Tensor = torch.zeros(
108
+ config.num_hidden_layers,
109
+ self.batch_size,
110
+ self.intermediate_size,
111
+ self.conv_kernel_size,
112
+ device=device,
113
+ dtype=dtype,
114
+ )
115
+ self.ssm_states: torch.Tensor = torch.zeros(
116
+ config.num_hidden_layers,
117
+ self.batch_size,
118
+ self.intermediate_size,
119
+ self.ssm_state_size,
120
+ device=device,
121
+ dtype=dtype,
122
+ )
123
+
124
+ torch._dynamo.mark_static_address(self.conv_states)
125
+ torch._dynamo.mark_static_address(self.ssm_states)
126
+
127
+ def update_conv_state(
128
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_position: torch.LongTensor
129
+ ) -> torch.Tensor:
130
+ conv_state = self.conv_states[layer_idx]
131
+ cache_position = cache_position.clamp(0, self.conv_kernel_size - 1)
132
+
133
+ conv_state = conv_state.roll(shifts=-1, dims=-1)
134
+ conv_state[:, :, cache_position] = new_conv_state.to(conv_state.device)
135
+ self.conv_states[layer_idx].zero_()
136
+ self.conv_states[layer_idx] += conv_state
137
+ return self.conv_states[layer_idx]
138
+
139
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
140
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
141
+ return self.ssm_states[layer_idx]
142
+
143
+ def reset(self):
144
+ self.conv_states.zero_()
145
+ self.ssm_states.zero_()
146
+
147
+
148
+ class MambaBlock(GradientCheckpointingLayer):
149
+
150
+ def __init__(self, config, layer_idx):
151
+ super().__init__()
152
+ self.config = config
153
+ self.layer_idx = layer_idx
154
+ self.residual_in_fp32 = config.residual_in_fp32
155
+ self.norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
156
+ self.mixer = Mamba(
157
+ hidden_size=config.hidden_size,
158
+ state_size=config.state_size,
159
+ conv_kernel=config.conv_kernel,
160
+ intermediate_size=config.intermediate_size,
161
+ time_step_rank=config.time_step_rank,
162
+ use_bias=config.use_bias,
163
+ layer_idx=layer_idx
164
+ )
165
+
166
+ def forward(
167
+ self,
168
+ hidden_states,
169
+ cache_params: Optional[MambaCache] = None,
170
+ cache_position: Optional[torch.LongTensor] = None,
171
+ attention_mask: Optional[torch.LongTensor] = None,
172
+ ):
173
+ residual = hidden_states
174
+ hidden_states = self.norm(hidden_states)
175
+ if self.residual_in_fp32:
176
+ residual = residual.to(torch.float32)
177
+
178
+ hidden_states = self.mixer(
179
+ hidden_states, cache_params=cache_params, cache_position=cache_position, attention_mask=attention_mask
180
+ )
181
+ hidden_states = residual + hidden_states
182
+ if self.residual_in_fp32:
183
+ hidden_states = hidden_states.to(dtype=self.norm.weight.dtype)
184
+ return hidden_states
185
+
186
+
187
+ class MambaPreTrainedModel(PreTrainedModel):
188
+ """
189
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
190
+ models.
191
+ """
192
+
193
+ config_class = MambaConfig
194
+ base_model_prefix = 'backbone'
195
+ _no_split_modules = ['Mamba', 'MambaBlock']
196
+ supports_gradient_checkpointing = True
197
+ _is_stateful = True
198
+
199
+ def _init_weights(self, module):
200
+ """Initialize the weights."""
201
+ if isinstance(module, nn.Linear):
202
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
203
+ if module.bias is not None:
204
+ if not getattr(module.bias, "_no_reinit", False):
205
+ nn.init.zeros_(module.bias)
206
+ elif isinstance(module, Mamba):
207
+ module.A_log._no_weight_decay = True
208
+ module.D._no_weight_decay = True
209
+
210
+ dt_init_std = self.config.time_step_rank**-0.5 * self.config.time_step_scale
211
+ if self.config.time_step_init_scheme == "constant":
212
+ nn.init.constant_(module.dt_proj.weight, dt_init_std)
213
+ elif self.config.time_step_init_scheme == "random":
214
+ nn.init.uniform_(module.dt_proj.weight, -dt_init_std, dt_init_std)
215
+
216
+ dt = torch.exp(
217
+ torch.rand(self.config.intermediate_size)
218
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
219
+ + math.log(self.config.time_step_min)
220
+ ).clamp(min=self.config.time_step_floor)
221
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
222
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
223
+ with torch.no_grad():
224
+ module.dt_proj.bias.data = nn.Parameter(inv_dt.to(module.dt_proj.bias.device))
225
+ module.dt_proj.bias._no_reinit = True
226
+ elif isinstance(module, nn.Embedding):
227
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
228
+ elif hasattr(module, 'reset_parameters'):
229
+ module.reset_parameters()
230
+
231
+ if self.config.rescale_prenorm_residual:
232
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
233
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
234
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
235
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
236
+ #
237
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
238
+ for name, p in module.named_parameters():
239
+ if name in ["out_proj.weight"]:
240
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
241
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
242
+ # We need to reinit p since this code could be called multiple times
243
+ # Having just p *= scale would repeatedly scale it down
244
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
245
+ with torch.no_grad():
246
+ p /= math.sqrt(self.config.num_hidden_layers)
247
+
248
+
249
+ @dataclass
250
+ class MambaOutput(ModelOutput):
251
+ """
252
+ Class for the MAMBA model outputs.
253
+
254
+ Args:
255
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
256
+ Sequence of hidden-states at the output of the last layer of the model.
257
+ cache_params (`MambaCache`):
258
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
259
+ avoid providing the old `input_ids`.
260
+
261
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
262
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,
263
+ returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
264
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
265
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
266
+
267
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
268
+ """
269
+
270
+ last_hidden_state: Optional[torch.FloatTensor] = None
271
+ cache_params: Optional[MambaCache] = None
272
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
273
+
274
+
275
+ @dataclass
276
+ class MambaCausalLMOutput(ModelOutput):
277
+ """
278
+ Base class for causal language model (or autoregressive) outputs.
279
+
280
+ Args:
281
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
282
+ Language modeling loss (for next-token prediction).
283
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
284
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
285
+ cache_params (`MambaCache`):
286
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
287
+ avoid providing the old `input_ids`.
288
+
289
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
290
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,
291
+ returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
292
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
293
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
294
+
295
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
296
+ """
297
+
298
+ loss: Optional[torch.FloatTensor] = None
299
+ logits: Optional[torch.FloatTensor] = None
300
+ cache_params: Optional[MambaCache] = None
301
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
302
+
303
+
304
+ class MambaModel(MambaPreTrainedModel):
305
+ def __init__(self, config):
306
+ super().__init__(config)
307
+
308
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
309
+ self.layers = nn.ModuleList([MambaBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
310
+
311
+ self.gradient_checkpointing = False
312
+ self.norm_f = RMSNorm(config.hidden_size, eps=config.norm_eps)
313
+ # Initialize weights and apply final processing
314
+ self._register_load_state_dict_pre_hook(self.load_hook)
315
+ self.post_init()
316
+
317
+ def load_hook(self, state_dict, prefix, *args):
318
+ for k in state_dict:
319
+ if "embedding." in k:
320
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
321
+ break
322
+
323
+ def get_input_embeddings(self):
324
+ return self.embeddings
325
+
326
+ def set_input_embeddings(self, new_embeddings):
327
+ self.embeddings = new_embeddings
328
+
329
+ def forward(
330
+ self,
331
+ input_ids: Optional[torch.LongTensor] = None,
332
+ inputs_embeds: Optional[torch.LongTensor] = None,
333
+ cache_params: Optional[MambaCache] = None,
334
+ use_cache: Optional[bool] = None,
335
+ output_hidden_states: Optional[bool] = None,
336
+ return_dict: Optional[bool] = None,
337
+ cache_position: Optional[torch.LongTensor] = None,
338
+ attention_mask: Optional[torch.LongTensor] = None,
339
+ ) -> Union[Tuple, MambaOutput]:
340
+ output_hidden_states = (
341
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
342
+ )
343
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
344
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
345
+
346
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
347
+ raise ValueError(
348
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
349
+ )
350
+
351
+ if inputs_embeds is None:
352
+ inputs_embeds = self.embeddings(input_ids)
353
+
354
+ if use_cache:
355
+ if cache_params is None:
356
+ cache_params = MambaCache(
357
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
358
+ )
359
+ cache_position = torch.arange(0, self.config.conv_kernel, device=inputs_embeds.device)
360
+ elif cache_position is None:
361
+ # cases when we do manual forward instead of using `model.generate` which will initiate
362
+ # `cache_position` and makes sure it is not None, throw error here instead of doing some
363
+ # hack to conjecture the current cache position
364
+ raise ValueError(
365
+ "You have to specify the `cache_position` manually when `use_cache=True` and `cache_params` is passed, "
366
+ "you don't have to pass a `cache_params` if you are in prefilling stage because in that case it will "
367
+ "be initialized for you automatically"
368
+ )
369
+ else:
370
+ cache_params = None
371
+
372
+ hidden_states = inputs_embeds
373
+ all_hidden_states = () if output_hidden_states else None
374
+ for mixer_block in self.layers:
375
+ hidden_states = mixer_block(
376
+ hidden_states,
377
+ cache_params=cache_params,
378
+ cache_position=cache_position,
379
+ attention_mask=attention_mask,
380
+ )
381
+
382
+ if output_hidden_states:
383
+ all_hidden_states = all_hidden_states + (hidden_states,)
384
+
385
+ hidden_states = self.norm_f(hidden_states)
386
+
387
+ if output_hidden_states:
388
+ all_hidden_states = all_hidden_states + (hidden_states,)
389
+
390
+ if not return_dict:
391
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
392
+
393
+ return MambaOutput(
394
+ last_hidden_state=hidden_states,
395
+ cache_params=cache_params if use_cache else None,
396
+ hidden_states=all_hidden_states,
397
+ )
398
+
399
+
400
+ class MambaForCausalLM(MambaPreTrainedModel, FLAGenerationMixin):
401
+
402
+ _tied_weights_keys = ["lm_head.weight"]
403
+
404
+ def __init__(self, config):
405
+ super().__init__(config)
406
+ self.backbone = MambaModel(config)
407
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
408
+ self.criterion = None
409
+
410
+ # Initialize weights and apply final processing
411
+ self.post_init()
412
+
413
+ def get_output_embeddings(self):
414
+ return self.lm_head
415
+
416
+ def set_output_embeddings(self, new_embeddings):
417
+ self.lm_head = new_embeddings
418
+
419
+ def get_input_embeddings(self):
420
+ return self.backbone.get_input_embeddings()
421
+
422
+ def set_input_embeddings(self, new_embeddings):
423
+ return self.backbone.set_input_embeddings(new_embeddings)
424
+
425
+ def _update_model_kwargs_for_generation(
426
+ self, outputs: ModelOutput,
427
+ model_kwargs: Dict[str, Any],
428
+ num_new_tokens: int = 1,
429
+ **kwargs
430
+ ) -> Dict[str, Any]:
431
+ model_kwargs["cache_params"] = outputs.get("cache_params", None)
432
+ if (
433
+ model_kwargs.get("use_cache", True)
434
+ and "cache_position" in model_kwargs
435
+ and model_kwargs["cache_position"] is not None
436
+ ):
437
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
438
+
439
+ if "attention_mask" in model_kwargs:
440
+ attention_mask = model_kwargs["attention_mask"]
441
+ model_kwargs["attention_mask"] = torch.cat(
442
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
443
+ )
444
+
445
+ return model_kwargs
446
+
447
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
448
+ def forward(
449
+ self,
450
+ input_ids: Optional[torch.LongTensor] = None,
451
+ attention_mask: Optional[torch.LongTensor] = None,
452
+ inputs_embeds: Optional[torch.FloatTensor] = None,
453
+ cache_params: Optional[MambaCache] = None,
454
+ labels: Optional[torch.LongTensor] = None,
455
+ output_hidden_states: Optional[bool] = None,
456
+ return_dict: Optional[bool] = None,
457
+ use_cache: Optional[bool] = None,
458
+ cache_position: Optional[torch.Tensor] = None,
459
+ logits_to_keep: Optional[int] = 0,
460
+ **kwargs, # for now we need this for generation
461
+ ) -> Union[Tuple, MambaCausalLMOutput]:
462
+ r"""
463
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
464
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
465
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
466
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
467
+ """
468
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
469
+
470
+ mamba_outputs = self.backbone(
471
+ input_ids,
472
+ cache_params=cache_params,
473
+ inputs_embeds=inputs_embeds,
474
+ output_hidden_states=output_hidden_states,
475
+ return_dict=return_dict,
476
+ use_cache=use_cache,
477
+ cache_position=cache_position,
478
+ attention_mask=attention_mask,
479
+ )
480
+ hidden_states = mamba_outputs[0]
481
+
482
+ loss, logits = None, None
483
+ if not self.config.fuse_linear_cross_entropy or labels is None:
484
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
485
+ if labels is not None:
486
+ if getattr(self, 'criterion', None) is None:
487
+ if self.config.fuse_linear_cross_entropy:
488
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
489
+ elif self.config.fuse_cross_entropy:
490
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
491
+ else:
492
+ criterion = nn.CrossEntropyLoss()
493
+ else:
494
+ criterion = self.criterion
495
+ # Enable model parallelism
496
+ labels = labels.to(hidden_states.device)
497
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
498
+ if self.config.fuse_linear_cross_entropy:
499
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
500
+ else:
501
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
502
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
503
+
504
+ if not return_dict:
505
+ output = (logits,) + mamba_outputs[1:]
506
+ return (loss,) + output if loss is not None else output
507
+
508
+ return MambaCausalLMOutput(
509
+ loss=loss,
510
+ logits=logits,
511
+ cache_params=mamba_outputs.cache_params,
512
+ hidden_states=mamba_outputs.hidden_states,
513
+ )
models/mamba2/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.mamba2.configuration_mamba2 import Mamba2Config
6
+ from fla.models.mamba2.modeling_mamba2 import Mamba2ForCausalLM, Mamba2Model
7
+
8
+ AutoConfig.register(Mamba2Config.model_type, Mamba2Config, exist_ok=True)
9
+ AutoModel.register(Mamba2Config, Mamba2Model, exist_ok=True)
10
+ AutoModelForCausalLM.register(Mamba2Config, Mamba2ForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['Mamba2Config', 'Mamba2ForCausalLM', 'Mamba2Model']
models/mamba2/configuration_mamba2.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ import warnings
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+
20
+
21
+ class Mamba2Config(PretrainedConfig):
22
+ """
23
+ This is the configuration class to store the configuration of a [`Mamba2Model`]. It is used to instantiate a MAMBA2
24
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
25
+ defaults will yield a similar configuration to that of the MAMBA2
26
+ [state-spaces/mamba2-2.8b](https://huggingface.co/state-spaces/mamba2-2.8b) architecture.
27
+
28
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
29
+ documentation from [`PretrainedConfig`] for more information.
30
+
31
+
32
+ Args:
33
+ head_dim (`int`, *optional*, defaults to 64):
34
+ Dimension of each head.
35
+ vocab_size (`int`, *optional*, defaults to 32768):
36
+ Vocabulary size of the MAMBA2 model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`Mamba2Model`].
38
+ hidden_size (`int`, *optional*, defaults to 2048):
39
+ Dimensionality of the embeddings and hidden states.
40
+ state_size (`int`, *optional*, defaults to 128): shape of the state space latents.
41
+ num_hidden_layers (`int`, *optional*, defaults to 48):
42
+ Number of hidden layers in the model.
43
+ norm_eps (`float`, *optional*, defaults to 1e-05):
44
+ The epsilon to use in the layer normalization layers.
45
+ pad_token_id (`int`, *optional*, defaults to 0):
46
+ Padding token id.
47
+ bos_token_id (`int`, *optional*, defaults to 1):
48
+ The id of the beginning of sentence token in the vocabulary.
49
+ eos_token_id (`int`, *optional*, defaults to 2):
50
+ The id of the end of sentence token in the vocabulary.
51
+ expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size.
52
+ conv_kernel (`int`, *optional*, defaults to 4): Size of the convolution kernel.
53
+ n_groups (`int`, *optional*, defaults to 1):
54
+ Number of groups for the evolution matrices of mamba 2.
55
+ use_bias (`bool`, *optional*, defaults to `False`):
56
+ Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block
57
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
58
+ Whether or not to use bias in the convolution layer of the mixer block.
59
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
60
+ The non-linear activation function (function or string) in the decoder.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ residual_in_fp32 (`bool`, *optional*, defaults to `True`):
64
+ Whether or not residuals should be in `float32`.
65
+ If set to `False` residuals will keep the same `dtype` as the rest of the model
66
+ time_step_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
67
+ Rank of the discretization projection matrix.
68
+ `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
69
+ time_step_min (`float`, *optional*, defaults to 0.001):
70
+ Minimum `time_step` used to bound `dt_proj.bias`.
71
+ time_step_max (`float`, *optional*, defaults to 0.1):
72
+ Maximum `time_step` used to bound `dt_proj.bias`.
73
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
74
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
75
+ time_step_limit (`tuple`, *optional*, defaults to `(0.0, inf)`):
76
+ Accepted range of time step values.
77
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
78
+ Whether or not to rescale `out_proj` weights when initializing.
79
+ use_cache (`bool`, *optional*, defaults to `True`):
80
+ Whether or not the cache should be used.
81
+ rms_norm (`bool`, *optional*, defaults to `True`):
82
+ Whether to use RMS norm or not.
83
+ chunk_size (`int`, *optional*, defaults to 256):
84
+ Size of the chunks that will comprise the sequence.
85
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
86
+ Whether to tie word embeddings or not.
87
+ """
88
+
89
+ model_type = "mamba2"
90
+
91
+ def __init__(
92
+ self,
93
+ head_dim: int = 64,
94
+ vocab_size: int = 32000,
95
+ hidden_size: int = 2048,
96
+ state_size: int = 128,
97
+ num_hidden_layers: int = 48,
98
+ norm_eps: float = 1e-5,
99
+ pad_token_id: int = 0,
100
+ bos_token_id: int = 1,
101
+ eos_token_id: int = 2,
102
+ expand: int = 2,
103
+ conv_kernel: int = 4,
104
+ n_groups: int = 1,
105
+ use_bias: bool = False,
106
+ use_conv_bias: bool = True,
107
+ hidden_act: str = "silu",
108
+ initializer_range: float = 0.02,
109
+ residual_in_fp32: bool = True,
110
+ time_step_rank: str = "auto",
111
+ time_step_min: float = 0.001,
112
+ time_step_max: float = 0.1,
113
+ time_step_floor: float = 1e-4,
114
+ time_step_limit=(0.0, float("inf")),
115
+ rescale_prenorm_residual: bool = True,
116
+ use_cache: bool = True,
117
+ rms_norm: bool = True,
118
+ chunk_size: int = 256,
119
+ fuse_norm: bool = True,
120
+ fuse_cross_entropy: bool = True,
121
+ fuse_linear_cross_entropy: bool = False,
122
+ use_l2warp: bool = False,
123
+ tie_word_embeddings: bool = False,
124
+ **kwargs,
125
+ ):
126
+ self.vocab_size = vocab_size
127
+ self.hidden_size = hidden_size
128
+ self.state_size = state_size
129
+ self.num_hidden_layers = num_hidden_layers
130
+ self.norm_eps = norm_eps
131
+ self.conv_kernel = conv_kernel
132
+ self.expand = expand
133
+
134
+ self.bos_token_id = bos_token_id
135
+ self.eos_token_id = eos_token_id
136
+ self.pad_token_id = pad_token_id
137
+ self.use_bias = use_bias
138
+ self.use_conv_bias = use_conv_bias
139
+ self.hidden_act = hidden_act
140
+ self.initializer_range = initializer_range
141
+ self.time_step_rank = (
142
+ math.ceil(self.hidden_size / 16)
143
+ if time_step_rank == "auto"
144
+ else time_step_rank
145
+ )
146
+ self.time_step_min = time_step_min
147
+ self.time_step_max = time_step_max
148
+ self.time_step_floor = time_step_floor
149
+ self.rescale_prenorm_residual = rescale_prenorm_residual
150
+ self.residual_in_fp32 = residual_in_fp32
151
+ self.use_cache = use_cache
152
+ self.n_groups = n_groups
153
+ self.head_dim = head_dim
154
+ self.num_heads = int(self.expand * self.hidden_size / self.head_dim)
155
+ self.rms_norm = rms_norm
156
+ self.state_size = state_size
157
+ self.chunk_size = chunk_size
158
+ self.time_step_limit = time_step_limit
159
+ self.fuse_norm = fuse_norm
160
+ self.fuse_cross_entropy = fuse_cross_entropy
161
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
162
+ self.use_l2warp = use_l2warp
163
+ self.tie_word_embeddings = tie_word_embeddings
164
+
165
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
166
+ raise ValueError(
167
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
168
+ )
169
+ if fuse_linear_cross_entropy:
170
+ warnings.warn(
171
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
172
+ "at the potential cost of reduced precision. "
173
+ "If you observe issues like loss divergence, consider disabling this setting."
174
+ )
175
+
176
+ super().__init__(
177
+ bos_token_id=bos_token_id,
178
+ eos_token_id=eos_token_id,
179
+ pad_token_id=pad_token_id,
180
+ tie_word_embeddings=tie_word_embeddings,
181
+ **kwargs,
182
+ )
models/mamba2/modeling_mamba2.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 state-spaces/mamba2 org and HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from dataclasses import dataclass
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+ from torch import nn
21
+ from transformers.modeling_utils import PreTrainedModel
22
+ from transformers.utils import ModelOutput, logging
23
+ from transformers.utils.deprecation import deprecate_kwarg
24
+
25
+ from fla.layers.mamba2 import Mamba2
26
+ from fla.models.mamba2.configuration_mamba2 import Mamba2Config
27
+ from fla.models.utils import FLAGenerationMixin
28
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss, RMSNorm
29
+ from fla.modules.l2warp import l2_warp
30
+
31
+ try:
32
+ from torch.distributed.tensor import DTensor
33
+ except (ImportError, AttributeError):
34
+ DTensor = None
35
+
36
+ try:
37
+ from transformers.modeling_layers import GradientCheckpointingLayer
38
+ except ImportError:
39
+ from fla.models.modeling_layers import GradientCheckpointingLayer
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ class Mamba2Cache:
46
+ """
47
+ Arguments:
48
+ config: Mamba2Config
49
+ batch_size: int
50
+ dtype: torch.dtype
51
+ device: torch.device
52
+
53
+ Attributes:
54
+ dtype: (`torch.dtype`):
55
+ The default `dtype` used to initializing the cache.
56
+ conv_kernel_size: (`int`):
57
+ Model's convolution kernel size taken from config.
58
+ n_groups: (`int`):
59
+ Model's number of groups taken from the config - similar to tensor parallel in Transformer.
60
+ state_size: (`int`):
61
+ Model's SSM state size taken from config.
62
+ num_heads: (`int`):
63
+ The number of heads used in the linear attention / SSM.
64
+ head_dim: (`int`):
65
+ The respective dimension of the heads used in the linear attention / SSM.
66
+ intermediate_size: (`int`):
67
+ Model's intermediate_size based on (expand * hidden_dim) from config.
68
+ conv_states: (`torch.Tensor`):
69
+ A tensor of shape `[num_layers, batch_size, conv_kernel_size, intermediate_size + 2 * n_groups * state_size]`
70
+ that holds convolutional states.
71
+ ssm_states: (`torch.Tensor`):
72
+ A tensor of shape `[num_layers, batch_size, num_heads, head_dim, state_size]` that holds ssm states.
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ config: Mamba2Config,
78
+ batch_size: int,
79
+ dtype: torch.dtype = torch.float16,
80
+ device: Optional[str] = None,
81
+ ):
82
+ self.dtype = dtype
83
+ self.conv_kernel_size = config.conv_kernel
84
+ self.n_groups = config.n_groups
85
+ self.state_size = config.state_size
86
+ self.num_heads = config.num_heads
87
+ self.head_dim = config.head_dim
88
+ self.intermediate_size = int(config.expand * config.hidden_size)
89
+
90
+ self.conv_states = torch.zeros(
91
+ config.num_hidden_layers,
92
+ batch_size,
93
+ self.intermediate_size + 2 * self.n_groups * self.state_size,
94
+ self.conv_kernel_size,
95
+ device=device,
96
+ dtype=dtype,
97
+ )
98
+ self.ssm_states = torch.zeros(
99
+ config.num_hidden_layers,
100
+ batch_size,
101
+ self.num_heads,
102
+ self.head_dim,
103
+ self.state_size,
104
+ device=device,
105
+ dtype=dtype,
106
+ )
107
+
108
+ def update_conv_state(
109
+ self,
110
+ layer_idx: int,
111
+ new_conv_state: torch.Tensor,
112
+ cache_init: bool = False
113
+ ) -> torch.Tensor:
114
+ if cache_init:
115
+ self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
116
+ else:
117
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
118
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
119
+ return self.conv_states[layer_idx]
120
+
121
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
122
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
123
+ return self.ssm_states[layer_idx]
124
+
125
+ def reset(self):
126
+ self.conv_states.zero_()
127
+ self.ssm_states.zero_()
128
+
129
+
130
+ class Mamba2Block(GradientCheckpointingLayer):
131
+
132
+ def __init__(self, config, layer_idx):
133
+ super().__init__()
134
+ self.config = config
135
+ self.layer_idx = layer_idx
136
+ self.residual_in_fp32 = config.residual_in_fp32
137
+ self.norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
138
+ self.mixer = Mamba2(
139
+ num_heads=config.num_heads,
140
+ head_dim=config.head_dim,
141
+ hidden_size=config.hidden_size,
142
+ state_size=config.state_size,
143
+ expand=config.expand,
144
+ n_groups=config.n_groups,
145
+ conv_kernel=config.conv_kernel,
146
+ use_conv_bias=config.use_conv_bias,
147
+ hidden_act=config.hidden_act,
148
+ rms_norm=config.rms_norm,
149
+ chunk_size=config.chunk_size,
150
+ time_step_rank=config.time_step_rank,
151
+ time_step_limit=config.time_step_limit,
152
+ time_step_min=config.time_step_min,
153
+ time_step_max=config.time_step_max,
154
+ use_bias=config.use_bias,
155
+ norm_eps=config.norm_eps,
156
+ layer_idx=layer_idx,
157
+ )
158
+
159
+ def forward(
160
+ self,
161
+ hidden_states,
162
+ cache_params: Optional[Mamba2Cache] = None,
163
+ cache_position: Optional[torch.LongTensor] = None,
164
+ attention_mask: Optional[torch.Tensor] = None,
165
+ ):
166
+ residual = hidden_states
167
+ hidden_states = self.norm(hidden_states)
168
+ if self.residual_in_fp32:
169
+ residual = residual.to(torch.float32)
170
+
171
+ hidden_states = self.mixer(
172
+ hidden_states,
173
+ cache_params=cache_params,
174
+ cache_position=cache_position,
175
+ attention_mask=attention_mask,
176
+ )
177
+ hidden_states = residual + hidden_states
178
+ if self.residual_in_fp32:
179
+ hidden_states = hidden_states.to(dtype=self.norm.weight.dtype)
180
+ return hidden_states
181
+
182
+
183
+ class Mamba2PreTrainedModel(PreTrainedModel):
184
+ """
185
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
186
+ models.
187
+ """
188
+
189
+ config_class = Mamba2Config
190
+ base_model_prefix = "backbone"
191
+ _no_split_modules = ["Mamba2Block"]
192
+ supports_gradient_checkpointing = True
193
+ _is_stateful = True
194
+
195
+ def _init_weights(
196
+ self,
197
+ module: nn.Module,
198
+ num_residuals_per_layer: int = 1,
199
+ ):
200
+ """Initialize the weights."""
201
+ if isinstance(module, Mamba2):
202
+
203
+ # --- A_log ---
204
+ A = torch.arange(1, module.num_heads + 1)
205
+ with torch.no_grad():
206
+ if not isinstance(module.A_log, DTensor):
207
+ module.A_log.copy_(torch.log(A))
208
+ else:
209
+ logger.warning_once("`A_log` is a DTensor, skipping initialization")
210
+ module.A_log._no_weight_decay = True
211
+
212
+ # --- D ---
213
+ nn.init.ones_(module.D)
214
+ module.D._no_weight_decay = True
215
+
216
+ # --- dt_bias ---
217
+ dt = torch.exp(
218
+ torch.rand(self.config.num_heads)
219
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
220
+ + math.log(self.config.time_step_min)
221
+ ).clamp(min=self.config.time_step_floor)
222
+
223
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
224
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
225
+ with torch.no_grad():
226
+ if not isinstance(module.dt_bias, DTensor):
227
+ module.dt_bias.copy_(inv_dt)
228
+ else:
229
+ logger.warning_once("`dt_bias` is a DTensor, skipping initialization")
230
+ module.dt_bias._no_reinit = True
231
+
232
+ elif isinstance(module, (nn.Linear, nn.Conv1d)):
233
+ # Slightly different from the TF version which uses truncated_normal for initialization
234
+ # cf https://github.com/pytorch/pytorch/pull/5617
235
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
236
+ if module.bias is not None:
237
+ nn.init.zeros_(module.bias)
238
+ # guard against deprecated behavior
239
+ if hasattr(module.bias, "_no_reinit"):
240
+ raise ValueError("This is not supposed to happen")
241
+ elif isinstance(module, nn.Embedding):
242
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
243
+ elif hasattr(module, 'reset_parameters'):
244
+ module.reset_parameters()
245
+
246
+ if self.config.rescale_prenorm_residual:
247
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
248
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
249
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
250
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
251
+ #
252
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
253
+ p = None
254
+ if hasattr(module, 'o_proj'):
255
+ # p = module.o_proj.weight
256
+ # guard against deprecated behavior
257
+ raise ValueError("This is not supposed to happen")
258
+ elif hasattr(module, 'out_proj'):
259
+ p = module.out_proj.weight
260
+ elif hasattr(module, 'down_proj'):
261
+ p = module.down_proj.weight
262
+ if p is not None:
263
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
264
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
265
+ # We need to reinit p since this code could be called multiple times
266
+ # Having just p *= scale would repeatedly scale it down
267
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
268
+ with torch.no_grad():
269
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
270
+
271
+
272
+ @dataclass
273
+ # Copied from transformers.models.mamba.modeling_mamba.MambaOutput with MAMBA->MAMBA2,Mamba->Mamba2
274
+ class Mamba2Output(ModelOutput):
275
+ """
276
+ Class for the MAMBA2 model outputs.
277
+
278
+ Args:
279
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
280
+ Sequence of hidden-states at the output of the last layer of the model.
281
+ cache_params (`Mamba2Cache`):
282
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
283
+ avoid providing the old `input_ids`.
284
+
285
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
286
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,
287
+ returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
288
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
289
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
290
+
291
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
292
+ """
293
+
294
+ last_hidden_state: Optional[torch.FloatTensor] = None
295
+ cache_params: Optional[Mamba2Cache] = None
296
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
297
+
298
+
299
+ @dataclass
300
+ # Copied from transformers.models.mamba.modeling_mamba.MambaCausalLMOutput with Mamba->Mamba2
301
+ class Mamba2CausalLMOutput(ModelOutput):
302
+ """
303
+ Base class for causal language model (or autoregressive) outputs.
304
+
305
+ Args:
306
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
307
+ Language modeling loss (for next-token prediction).
308
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
309
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
310
+ cache_params (`Mamba2Cache`):
311
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
312
+ avoid providing the old `input_ids`.
313
+
314
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
315
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,
316
+ returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
317
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
318
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
319
+
320
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
321
+ """
322
+
323
+ loss: Optional[torch.FloatTensor] = None
324
+ logits: Optional[torch.FloatTensor] = None
325
+ cache_params: Optional[Mamba2Cache] = None
326
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
327
+
328
+
329
+ class Mamba2Model(Mamba2PreTrainedModel):
330
+ def __init__(self, config):
331
+ super().__init__(config)
332
+
333
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
334
+ self.layers = nn.ModuleList([Mamba2Block(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
335
+
336
+ self.gradient_checkpointing = False
337
+ self.norm_f = RMSNorm(config.hidden_size, eps=config.norm_eps)
338
+ # Initialize weights and apply final processing
339
+ self._register_load_state_dict_pre_hook(self.load_hook)
340
+ self.post_init()
341
+
342
+ def load_hook(self, state_dict, prefix, *args):
343
+ for k in state_dict:
344
+ if "embedding." in k:
345
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
346
+ break
347
+
348
+ def get_input_embeddings(self):
349
+ return self.embeddings
350
+
351
+ def set_input_embeddings(self, new_embeddings):
352
+ self.embeddings = new_embeddings
353
+
354
+ def forward(
355
+ self,
356
+ input_ids: Optional[torch.LongTensor] = None,
357
+ inputs_embeds: Optional[torch.LongTensor] = None,
358
+ cache_params: Optional[Mamba2Cache] = None,
359
+ use_cache: Optional[bool] = None,
360
+ output_hidden_states: Optional[bool] = None,
361
+ return_dict: Optional[bool] = None,
362
+ cache_position: Optional[torch.LongTensor] = None,
363
+ attention_mask: Optional[torch.Tensor] = None,
364
+ **kwargs,
365
+ ) -> Union[Tuple, Mamba2Output]:
366
+ output_hidden_states = (
367
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
368
+ )
369
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
370
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
371
+
372
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
373
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
374
+
375
+ if inputs_embeds is None:
376
+ inputs_embeds = self.embeddings(input_ids)
377
+
378
+ if use_cache:
379
+ if cache_params is None:
380
+ cache_params = Mamba2Cache(
381
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
382
+ )
383
+ cache_position = torch.arange(0, self.config.conv_kernel, device=inputs_embeds.device)
384
+ elif cache_position is None:
385
+ # cases when we do manual forward instead of using `model.generate` which will initiate
386
+ # `cache_position` and makes sure it is not None, throw error here instead of doing some
387
+ # hack to conjecture the current cache position
388
+ raise ValueError(
389
+ "You have to specify the `cache_position` manually when `use_cache=True` and `cache_params` is passed, "
390
+ "you don't have to pass a `cache_params` if you are in prefilling stage because in that case it will "
391
+ "be initialized for you automatically"
392
+ )
393
+ else:
394
+ cache_params = None
395
+
396
+ hidden_states = inputs_embeds
397
+ all_hidden_states = () if output_hidden_states else None
398
+ for mixer_block in self.layers:
399
+ hidden_states = mixer_block(
400
+ hidden_states,
401
+ cache_params=cache_params,
402
+ cache_position=cache_position,
403
+ attention_mask=attention_mask,
404
+ )
405
+
406
+ if output_hidden_states:
407
+ all_hidden_states = all_hidden_states + (hidden_states,)
408
+
409
+ hidden_states = self.norm_f(hidden_states)
410
+
411
+ if output_hidden_states:
412
+ all_hidden_states = all_hidden_states + (hidden_states,)
413
+
414
+ if not return_dict:
415
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
416
+
417
+ return Mamba2Output(
418
+ last_hidden_state=hidden_states,
419
+ cache_params=cache_params if use_cache else None,
420
+ hidden_states=all_hidden_states,
421
+ )
422
+
423
+
424
+ class Mamba2ForCausalLM(Mamba2PreTrainedModel, FLAGenerationMixin):
425
+ _tied_weights_keys = []
426
+
427
+ def __init__(self, config):
428
+ super().__init__(config)
429
+ self.backbone = Mamba2Model(config)
430
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
431
+ self.criterion = None
432
+
433
+ # Initialize weights and apply final processing
434
+ self.post_init()
435
+
436
+ def get_output_embeddings(self):
437
+ return self.lm_head
438
+
439
+ def set_output_embeddings(self, new_embeddings):
440
+ self.lm_head = new_embeddings
441
+
442
+ def get_input_embeddings(self):
443
+ return self.backbone.get_input_embeddings()
444
+
445
+ def set_input_embeddings(self, new_embeddings):
446
+ return self.backbone.set_input_embeddings(new_embeddings)
447
+
448
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
449
+ def forward(
450
+ self,
451
+ input_ids: Optional[torch.LongTensor] = None,
452
+ inputs_embeds: Optional[torch.FloatTensor] = None,
453
+ cache_params: Optional[Mamba2Cache] = None,
454
+ labels: Optional[torch.LongTensor] = None,
455
+ output_hidden_states: Optional[bool] = None,
456
+ return_dict: Optional[bool] = None,
457
+ use_cache: Optional[bool] = None,
458
+ cache_position: Optional[torch.Tensor] = None,
459
+ attention_mask: Optional[torch.Tensor] = None,
460
+ logits_to_keep: Optional[int] = 0,
461
+ **kwargs, # for now we need this for generation
462
+ ) -> Union[Tuple, Mamba2CausalLMOutput]:
463
+ r"""
464
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
465
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
466
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
467
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
468
+ """
469
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
470
+
471
+ outputs = self.backbone(
472
+ input_ids,
473
+ cache_params=cache_params,
474
+ inputs_embeds=inputs_embeds,
475
+ output_hidden_states=output_hidden_states,
476
+ return_dict=return_dict,
477
+ use_cache=use_cache,
478
+ cache_position=cache_position,
479
+ attention_mask=attention_mask,
480
+ )
481
+ hidden_states = outputs[0]
482
+
483
+ loss, logits = None, None
484
+ if not self.config.fuse_linear_cross_entropy or labels is None:
485
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
486
+ if labels is not None:
487
+ if getattr(self, 'criterion', None) is None:
488
+ if self.config.fuse_linear_cross_entropy:
489
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
490
+ elif self.config.fuse_cross_entropy:
491
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
492
+ else:
493
+ criterion = nn.CrossEntropyLoss()
494
+ else:
495
+ criterion = self.criterion
496
+ labels = labels.to(hidden_states.device)
497
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
498
+ if self.config.fuse_linear_cross_entropy:
499
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
500
+ else:
501
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
502
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
503
+
504
+ if not return_dict:
505
+ output = (logits,) + outputs[1:]
506
+ return (loss,) + output if loss is not None else output
507
+
508
+ return Mamba2CausalLMOutput(
509
+ loss=loss,
510
+ logits=logits,
511
+ cache_params=outputs.cache_params,
512
+ hidden_states=outputs.hidden_states,
513
+ )
models/mask_gdn/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from .configuration_mask_gdn import mask_gdnConfig
6
+ from .modeling_mask_gdn import mask_gdnForCausalLM, mask_gdnModel
7
+
8
+ AutoConfig.register(mask_gdnConfig.model_type, mask_gdnConfig)
9
+ AutoModel.register(mask_gdnConfig, mask_gdnModel)
10
+ AutoModelForCausalLM.register(mask_gdnConfig, mask_gdnForCausalLM)
11
+
12
+ __all__ = ['mask_gdnConfig', 'mask_gdnForCausalLM', 'mask_gdnModel']
models/mask_gdn/configuration_mask_gdn.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Dict, Optional
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+
8
+
9
+ class mask_gdnConfig(PretrainedConfig):
10
+ model_type = 'mask_gdn'
11
+ keys_to_ignore_at_inference = ['past_key_values']
12
+ def __init__(
13
+ self,
14
+ attn_mode: str = "chunk",
15
+ hidden_size: int = 2048,
16
+ expand_k: int = 1,
17
+ expand_v: int = 1,
18
+ use_gate: bool = False,
19
+ use_short_conv: bool = True,
20
+ conv_size: int = 4,
21
+ use_beta: bool = True,
22
+ use_output_norm: bool = True,
23
+ num_heads: int = 16,
24
+ qk_norm: str = 'l2',
25
+ qk_activation: str = 'silu',
26
+ max_position_embeddings: int = 2048,
27
+ hidden_ratio: Optional[int] = 4,
28
+ intermediate_size: Optional[int] = None,
29
+ hidden_act: str = "swish",
30
+ num_hidden_layers: int = 24,
31
+ norm_eps: float = 1e-6,
32
+ attn: Optional[Dict] = None,
33
+ use_cache: bool = True,
34
+ pad_token_id: int = None,
35
+ bos_token_id: int = 1,
36
+ eos_token_id: int = 2,
37
+ tie_word_embeddings: bool = False,
38
+ initializer_range: float = 0.02,
39
+ fuse_norm: bool = True,
40
+ fuse_swiglu: bool = True,
41
+ fuse_cross_entropy: bool = True,
42
+ vocab_size: int = 32000,
43
+ aux_loss_scale:float = 0.01,
44
+ ratio : int = 2,
45
+ topk : int = 1,
46
+ **kwargs
47
+ ):
48
+ self.attn_mode = attn_mode
49
+ self.aux_loss_scale = aux_loss_scale
50
+ self.hidden_size = hidden_size
51
+ self.expand_k = expand_k
52
+ self.expand_v = expand_v
53
+ self.use_gate = use_gate
54
+ self.use_short_conv = use_short_conv
55
+ self.conv_size = conv_size
56
+ self.use_beta = use_beta
57
+ self.use_output_norm = use_output_norm
58
+ self.num_heads = num_heads
59
+ self.qk_norm = qk_norm
60
+ self.qk_activation = qk_activation
61
+ self.max_position_embeddings = max_position_embeddings
62
+
63
+ self.hidden_ratio = hidden_ratio
64
+ self.intermediate_size = intermediate_size
65
+ self.hidden_act = hidden_act
66
+ self.num_hidden_layers = num_hidden_layers
67
+ self.norm_eps = norm_eps
68
+ self.attn = attn
69
+ self.use_cache = use_cache
70
+ self.initializer_range = initializer_range
71
+ self.fuse_norm = fuse_norm
72
+ self.fuse_swiglu = fuse_swiglu
73
+ self.fuse_cross_entropy = fuse_cross_entropy
74
+ self.vocab_size = vocab_size
75
+ self.ratio = ratio
76
+ self.topk = topk
77
+
78
+ if attn is not None:
79
+ if not isinstance(attn, Dict):
80
+ raise ValueError("attn must be a dictionary")
81
+ if 'layers' not in attn:
82
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
83
+ if 'num_heads' not in attn:
84
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
85
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
86
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
87
+ attn['window_size'] = attn.get('window_size', None)
88
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
89
+
90
+ super().__init__(
91
+ pad_token_id=pad_token_id,
92
+ bos_token_id=bos_token_id,
93
+ eos_token_id=eos_token_id,
94
+ tie_word_embeddings=tie_word_embeddings,
95
+ **kwargs,
96
+ )
models/mask_gdn/modeling_mask_gdn.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union,Iterable
8
+ from einops import rearrange
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.utils.checkpoint
12
+ from transformers.generation import GenerationMixin
13
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.utils import logging
16
+ from transformers.utils.deprecation import deprecate_kwarg
17
+
18
+ from ...layers.attn import Attention
19
+ from ...layers.mask_gdn import mask_gdn
20
+ from ...models.mask_gdn.configuration_mask_gdn import mask_gdnConfig
21
+ from fla.models.utils import Cache
22
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
23
+ from fla.modules import GatedMLP as mask_gdnMLP
24
+ from ...modules import RMSNorm
25
+ from ...modules import RotaryEmbedding
26
+ logger = logging.get_logger(__name__)
27
+
28
+ if TYPE_CHECKING:
29
+ from transformers.processing_utils import Unpack
30
+
31
+
32
+ class mask_gdnBlock(nn.Module):
33
+ def __init__(self, config: mask_gdnConfig, layer_idx: int):
34
+ super().__init__()
35
+
36
+ self.config = config
37
+ self.layer_idx = layer_idx
38
+ print(config)
39
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
40
+ if config.attn is not None and layer_idx in config.attn['layers']:
41
+ self.attn = Attention(
42
+ hidden_size=config.hidden_size,
43
+ num_heads=config.attn['num_heads'],
44
+ num_kv_heads=config.attn['num_kv_heads'],
45
+ qkv_bias=config.attn['qkv_bias'],
46
+ window_size=config.attn['window_size'],
47
+ rope_theta=config.attn['rope_theta'],
48
+ max_position_embeddings=config.max_position_embeddings,
49
+ layer_idx=layer_idx
50
+ )
51
+ else:
52
+ self.attn = mask_gdn(
53
+ mode=config.attn_mode,
54
+ hidden_size=config.hidden_size,
55
+ expand_k=config.expand_k,
56
+ expand_v=config.expand_v,
57
+ num_heads=config.num_heads,
58
+ use_gate=config.use_gate,
59
+ use_short_conv=config.use_short_conv,
60
+ use_output_norm=config.use_output_norm,
61
+ conv_size=config.conv_size,
62
+ norm_eps=config.norm_eps,
63
+ ratio = config.ratio,
64
+ topk = config.topk,
65
+ layer_idx=layer_idx
66
+ )
67
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
68
+ self.mlp = mask_gdnMLP(
69
+ hidden_size=config.hidden_size,
70
+ hidden_ratio=config.hidden_ratio,
71
+ intermediate_size=config.intermediate_size,
72
+ hidden_act=config.hidden_act,
73
+ fuse_swiglu=config.fuse_swiglu
74
+ )
75
+
76
+ def forward(
77
+ self,
78
+ hidden_states: torch.Tensor,
79
+ attention_mask: Optional[torch.Tensor] = None,
80
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
81
+ use_cache: Optional[bool] = False,
82
+ output_attentions: Optional[bool] = False,
83
+ **kwargs: Unpack[Dict]
84
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
85
+ residual = hidden_states
86
+ hidden_states = self.attn_norm(hidden_states)
87
+ hidden_states, attentions, past_key_values,router_logits = self.attn(
88
+ hidden_states=hidden_states,
89
+ attention_mask=attention_mask,
90
+ past_key_values=past_key_values,
91
+ use_cache=use_cache,
92
+ output_attentions=output_attentions,
93
+ **kwargs
94
+ )
95
+ if self.config.fuse_norm:
96
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
97
+ else:
98
+ hidden_states = residual + hidden_states
99
+ residual = hidden_states
100
+ hidden_states = self.mlp_norm(hidden_states)
101
+ hidden_states = self.mlp(hidden_states, **kwargs)
102
+ hidden_states = residual + hidden_states
103
+
104
+ outputs = (hidden_states, attentions, past_key_values,router_logits)
105
+
106
+ return outputs
107
+
108
+
109
+ class mask_gdnPreTrainedModel(PreTrainedModel):
110
+
111
+ config_class = mask_gdnConfig
112
+ base_model_prefix = 'model'
113
+ supports_gradient_checkpointing = True
114
+ _no_split_modules = ['mask_gdnBlock']
115
+ _supports_cache_class = True
116
+
117
+ def __init__(self, *inputs, **kwargs):
118
+ super().__init__(*inputs, **kwargs)
119
+
120
+ def _init_weights(
121
+ self,
122
+ module: nn.Module,
123
+ prenorm_residual_strategy: Optional[str] = 'rescale',
124
+ num_residuals_per_layer: int = 2,
125
+ ):
126
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
127
+ # Slightly different from the TF version which uses truncated_normal for initialization
128
+ # cf https://github.com/pytorch/pytorch/pull/5617
129
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
130
+ if module.bias is not None:
131
+ nn.init.zeros_(module.bias)
132
+ elif isinstance(module, nn.Embedding):
133
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
134
+ elif hasattr(module, 'reset_parameters'):
135
+ module.reset_parameters()
136
+
137
+ if prenorm_residual_strategy is not None:
138
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
139
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
140
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
141
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
142
+ #
143
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
144
+ p = None
145
+ if hasattr(module, 'o_proj'):
146
+ p = module.o_proj.weight
147
+ elif hasattr(module, 'down_proj'):
148
+ p = module.down_proj.weight
149
+ if p is not None:
150
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
151
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
152
+ # We need to reinit p since this code could be called multiple times
153
+ # Having just p *= scale would repeatedly scale it down
154
+ if prenorm_residual_strategy == 'rescale':
155
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
156
+ with torch.no_grad():
157
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
158
+ elif prenorm_residual_strategy == 'zero':
159
+ nn.init.zeros_(p)
160
+ else:
161
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
162
+
163
+
164
+ class mask_gdnModel(mask_gdnPreTrainedModel):
165
+
166
+ def __init__(self, config: mask_gdnConfig):
167
+ super().__init__(config)
168
+ self.padding_idx = config.pad_token_id
169
+ self.vocab_size = config.vocab_size
170
+
171
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
172
+ self.layers = nn.ModuleList([mask_gdnBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
173
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
174
+
175
+ self.gradient_checkpointing = False
176
+
177
+ self.post_init()
178
+
179
+ def get_input_embeddings(self):
180
+ return self.embeddings
181
+
182
+ def set_input_embeddings(self, value):
183
+ self.embeddings = value
184
+
185
+ def forward(
186
+ self,
187
+ input_ids: Optional[torch.LongTensor] = None,
188
+ attention_mask: Optional[torch.Tensor] = None, # noqa
189
+ inputs_embeds: Optional[torch.FloatTensor] = None,
190
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
191
+ use_cache: Optional[bool] = None,
192
+ output_attentions: Optional[bool] = None,
193
+ output_hidden_states: Optional[bool] = None,
194
+ return_dict: Optional[bool] = None,
195
+ **kwargs: Unpack[Dict]
196
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
197
+ if output_attentions:
198
+ warnings.warn("`mask_gdnModel` does not `output_attentions` now, setting it to `False`.")
199
+ output_attentions = False
200
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
201
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
202
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
203
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
204
+
205
+ # retrieve input_ids and inputs_embeds
206
+ if input_ids is not None and inputs_embeds is not None:
207
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
208
+ if input_ids is None and inputs_embeds is None:
209
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
210
+
211
+ if inputs_embeds is None:
212
+ inputs_embeds = self.embeddings(input_ids)
213
+ hidden_states = inputs_embeds
214
+
215
+ if use_cache and not isinstance(past_key_values, Cache):
216
+ past_key_values = Cache.from_legacy_cache(past_key_values)
217
+
218
+ if self.gradient_checkpointing and self.training and use_cache:
219
+ logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
220
+ use_cache = False
221
+
222
+ all_hidden_states = () if output_hidden_states else None
223
+ all_attns = () if output_attentions else None
224
+ all_router_logits = ()
225
+ for layer in self.layers:
226
+ if output_hidden_states:
227
+ all_hidden_states += (hidden_states,)
228
+
229
+ if self.gradient_checkpointing and self.training:
230
+ hidden_states, attentions, past_key_values, router_logits = self._gradient_checkpointing_func(
231
+ layer.__call__,
232
+ hidden_states,
233
+ attention_mask,
234
+ past_key_values,
235
+ use_cache,
236
+ output_attentions,
237
+ **kwargs
238
+ )
239
+ else:
240
+ hidden_states, attentions, past_key_values, router_logits = layer(
241
+ hidden_states,
242
+ attention_mask=attention_mask,
243
+ past_key_values=past_key_values,
244
+ use_cache=use_cache,
245
+ output_attentions=output_attentions,
246
+ **kwargs
247
+ )
248
+
249
+ if output_attentions:
250
+ all_attns += (attentions,)
251
+ all_router_logits += (router_logits,)
252
+ hidden_states = self.norm(hidden_states)
253
+
254
+ # add hidden states from the last decoder layer
255
+ if output_hidden_states:
256
+ all_hidden_states += (hidden_states,)
257
+
258
+ if not return_dict:
259
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
260
+ # return BaseModelOutputWithPast(
261
+ # last_hidden_state=hidden_states,
262
+ # past_key_values=past_key_values,
263
+ # hidden_states=all_hidden_states,
264
+ # attentions=all_attns
265
+ # )
266
+ return mask_gdnOutputWithPast(
267
+ last_hidden_state=hidden_states,
268
+ past_key_values=past_key_values,
269
+ hidden_states=all_hidden_states,
270
+ attentions=all_attns,
271
+ router_logits=all_router_logits
272
+ )
273
+
274
+
275
+ from dataclasses import dataclass
276
+ @dataclass
277
+ class mask_gdnOutputWithPast(BaseModelOutputWithPast):
278
+ router_logits: Optional[Tuple[torch.FloatTensor, ...]] = None
279
+
280
+
281
+ @dataclass
282
+ class mask_gdnCausalLMOutputWithPast(CausalLMOutputWithPast):
283
+ aux_loss: Optional[torch.FloatTensor] = None
284
+ router_logits: Optional[Tuple[torch.FloatTensor, ...]] = None
285
+
286
+ def load_balancing_loss_func(
287
+ gate_logits: Union[torch.Tensor, Tuple],
288
+ num_memories: torch.Tensor = None,
289
+ top_k=2,
290
+ use_layer_wise_balance=False,
291
+ ) -> torch.FloatTensor:
292
+ r"""
293
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
294
+
295
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
296
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
297
+ experts is too unbalanced.
298
+
299
+ Args:
300
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
301
+ Logits from the `gate`, should be a tuple of tensors. Shape: [batch_size, seqeunce_length, num_memories].
302
+ num_memories (`int`, *optional*):
303
+ Number of experts
304
+
305
+ Returns:
306
+ The auxiliary loss.
307
+ """
308
+ if gate_logits is None or (
309
+ isinstance(gate_logits, Iterable) and len(gate_logits) == 0
310
+ ):
311
+ return 0
312
+
313
+ # ✨ Here is the fix for balance loss in Mixtral.
314
+ # We should calculate the balance loss in a layer-wise manner otherwise it may lead to degenerated solutions.
315
+ if use_layer_wise_balance:
316
+ if not isinstance(gate_logits, Iterable):
317
+ gate_logits = (gate_logits,)
318
+ else:
319
+ if isinstance(gate_logits, Iterable):
320
+ gate_logits = (torch.cat(gate_logits, dim=0),)
321
+ else:
322
+ gate_logits = (gate_logits,)
323
+
324
+ all_balance_losses = []
325
+
326
+ for logits in gate_logits:
327
+ if logits.dim() == 4:
328
+ logits = rearrange(logits,'b h l r-> (b h) l r')
329
+ routing_weights, selected_experts = torch.topk(logits, top_k, dim=-1)
330
+ routing_weights = routing_weights.softmax(dim=-1).to(logits.dtype)
331
+ routing_weights_full = torch.zeros_like(logits).scatter(-1, selected_experts, routing_weights)
332
+
333
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
334
+ if selected_experts.dtype != torch.int64:
335
+ selected_experts = selected_experts.to(torch.int64)
336
+
337
+ if len(selected_experts.shape) == 2:
338
+ selected_experts = selected_experts.unsqueeze(2)
339
+
340
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_memories)
341
+
342
+ # For a given token, determine if it was routed to a given expert.
343
+ expert_mask = torch.max(expert_mask, axis=-2).values
344
+
345
+ # cast to float32 otherwise mean will fail
346
+ expert_mask = expert_mask.to(torch.float32)
347
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
348
+
349
+ router_prob_per_group_and_expert = torch.mean(routing_weights_full, axis=-2)
350
+
351
+ # ✨ balance loss for this layer
352
+ balance_loss = torch.mean(
353
+ tokens_per_group_and_expert * router_prob_per_group_and_expert
354
+ ) * (num_memories**2)
355
+ all_balance_losses.append(balance_loss.reshape(1))
356
+
357
+ all_balance_losses = torch.cat(all_balance_losses).mean() # ✨
358
+
359
+ return all_balance_losses
360
+
361
+
362
+ class mask_gdnForCausalLM(mask_gdnPreTrainedModel, GenerationMixin):
363
+
364
+ _tied_weights_keys = ["lm_head.weight"]
365
+
366
+ def __init__(self, config):
367
+ super().__init__(config)
368
+ self.model = mask_gdnModel(config)
369
+ self.vocab_size = config.vocab_size
370
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
371
+ self.criterion = None
372
+
373
+ # Initialize weights and apply final processing
374
+ self.post_init()
375
+
376
+ def get_input_embeddings(self):
377
+ return self.model.embeddings
378
+
379
+ def set_input_embeddings(self, value):
380
+ self.model.embeddings = value
381
+
382
+ def get_output_embeddings(self):
383
+ return self.lm_head
384
+
385
+ def set_output_embeddings(self, new_embeddings):
386
+ self.lm_head = new_embeddings
387
+
388
+ def set_decoder(self, decoder):
389
+ self.model = decoder
390
+
391
+ def get_decoder(self):
392
+ return self.model
393
+
394
+ def generate(self, *args, **kwargs):
395
+ try:
396
+ return super().generate(*args, **kwargs)
397
+ except AttributeError as exception:
398
+ if 'past_key_values' in str(exception):
399
+ raise AttributeError(
400
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
401
+ f"which is not supported for {self.__class__.__name__}. "
402
+ f"Try another generation strategy instead. "
403
+ f"For the available generation strategies, check this doc: "
404
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
405
+ )
406
+ else:
407
+ raise exception
408
+
409
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
410
+ def prepare_inputs_for_generation(
411
+ self,
412
+ input_ids: torch.LongTensor = None,
413
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ inputs_embeds: Optional[torch.Tensor] = None,
416
+ use_cache: bool = True,
417
+ logits_to_keep: Optional[int] = None,
418
+ **kwargs
419
+ ):
420
+ # only last token for `inputs_ids` if the `past_key_values` is not empty.
421
+ if past_key_values is not None and len(past_key_values) > 0:
422
+ input_ids = input_ids[:, -1:]
423
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
424
+ if inputs_embeds is not None and len(past_key_values) == 0:
425
+ model_inputs = {'inputs_embeds': inputs_embeds}
426
+ else:
427
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
428
+ # recompiles graphs as the stride of the inputs is a guard.
429
+ # Ref: https://github.com/huggingface/transformers/pull/29114
430
+ # TODO: use `next_tokens` directly instead.
431
+ model_inputs = {'input_ids': input_ids.contiguous()}
432
+
433
+ if logits_to_keep is not None:
434
+ model_inputs['logits_to_keep'] = logits_to_keep
435
+
436
+ model_inputs.update({
437
+ 'past_key_values': past_key_values,
438
+ 'use_cache': use_cache,
439
+ 'attention_mask': attention_mask,
440
+ })
441
+ return model_inputs
442
+
443
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
444
+ def forward(
445
+ self,
446
+ input_ids: torch.LongTensor = None,
447
+ attention_mask: Optional[torch.Tensor] = None,
448
+ inputs_embeds: Optional[torch.Tensor] = None,
449
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
450
+ labels: Optional[torch.LongTensor] = None,
451
+ use_cache: Optional[bool] = None,
452
+ output_attentions: Optional[bool] = None,
453
+ output_hidden_states: Optional[bool] = None,
454
+ return_dict: Optional[bool] = None,
455
+ logits_to_keep: Optional[int] = 0,
456
+ **kwargs: Unpack[Dict]
457
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
458
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
459
+ output_hidden_states = (
460
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
461
+ )
462
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
463
+
464
+ outputs = self.model(
465
+ input_ids=input_ids,
466
+ attention_mask=attention_mask,
467
+ inputs_embeds=inputs_embeds,
468
+ past_key_values=past_key_values,
469
+ use_cache=use_cache,
470
+ output_attentions=output_attentions,
471
+ output_hidden_states=output_hidden_states,
472
+ return_dict=return_dict,
473
+ **kwargs
474
+ )
475
+
476
+ hidden_states = outputs[0]
477
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training
478
+
479
+ loss, logits = None, None
480
+ if not fuse_linear_and_cross_entropy or labels is None:
481
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
482
+ if labels is not None:
483
+ if getattr(self, 'criterion', None) is None:
484
+ if fuse_linear_and_cross_entropy:
485
+ criterion = FusedLinearCrossEntropyLoss()
486
+ elif self.config.fuse_cross_entropy:
487
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
488
+ else:
489
+ criterion = nn.CrossEntropyLoss()
490
+ else:
491
+ criterion = self.criterion
492
+ labels = labels.to(hidden_states.device)
493
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
494
+ if fuse_linear_and_cross_entropy:
495
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
496
+ else:
497
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
498
+
499
+ valid_router_logits = tuple(
500
+ logits
501
+ for logits in (outputs.router_logits if return_dict else outputs[-1])
502
+ if logits is not None
503
+ )
504
+ aux_loss = load_balancing_loss_func(
505
+ valid_router_logits,
506
+ self.config.ratio,
507
+ self.config.topk,
508
+ use_layer_wise_balance=True,
509
+ )
510
+ aux_loss *= self.config.aux_loss_scale
511
+ # print('aux_loss:',aux_loss)
512
+ if aux_loss:
513
+ loss += aux_loss
514
+
515
+ if not return_dict:
516
+ output = (logits,) + outputs[1:]
517
+ return (loss,) + output if loss is not None else output
518
+
519
+ # return CausalLMOutputWithPast(
520
+ # loss=loss,
521
+ # logits=logits,
522
+ # past_key_values=outputs.past_key_values,
523
+ # hidden_states=outputs.hidden_states,
524
+ # attentions=outputs.attentions,
525
+ # )
526
+
527
+ return mask_gdnCausalLMOutputWithPast(
528
+ loss=loss,
529
+ logits=logits,
530
+ past_key_values=outputs.past_key_values,
531
+ hidden_states=outputs.hidden_states,
532
+ attentions=outputs.attentions,
533
+ router_logits=outputs.router_logits,
534
+ aux_loss=aux_loss
535
+ )
models/mesa_net/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.mesa_net.configuration_mesa_net import MesaNetConfig
6
+ from fla.models.mesa_net.modeling_mesa_net import MesaNetForCausalLM, MesaNetModel
7
+
8
+ AutoConfig.register(MesaNetConfig.model_type, MesaNetConfig, exist_ok=True)
9
+ AutoModel.register(MesaNetConfig, MesaNetModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(MesaNetConfig, MesaNetForCausalLM, exist_ok=True)
11
+
12
+ __all__ = ['MesaNetConfig', 'MesaNetForCausalLM', 'MesaNetModel']
models/mesa_net/configuration_mesa_net.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class MesaNetConfig(PretrainedConfig):
10
+ model_type = 'mesa_net'
11
+ keys_to_ignore_at_inference = ['past_key_values']
12
+
13
+ def __init__(
14
+ self,
15
+ attn_mode: str = "chunk",
16
+ hidden_size: int = 2048,
17
+ use_output_gate: bool = False,
18
+ use_short_conv: bool = True,
19
+ conv_size: int = 4,
20
+ num_heads: int = 16,
21
+ head_dim: int = 128,
22
+ lambda_lower_bound: float = 0.25,
23
+ max_position_embeddings: int = 2048,
24
+ hidden_ratio: Optional[int] = 4,
25
+ intermediate_size: Optional[int] = None,
26
+ hidden_act: str = "swish",
27
+ num_hidden_layers: int = 24,
28
+ norm_eps: float = 1e-6,
29
+ attn: Optional[Dict] = None,
30
+ use_cache: bool = True,
31
+ pad_token_id: Optional[int] = None,
32
+ bos_token_id: int = 1,
33
+ eos_token_id: int = 2,
34
+ tie_word_embeddings: bool = False,
35
+ initializer_range: float = 0.02,
36
+ fuse_norm: bool = True,
37
+ fuse_swiglu: bool = True,
38
+ fuse_cross_entropy: bool = True,
39
+ fuse_linear_cross_entropy: bool = False,
40
+ use_l2warp: bool = False,
41
+ vocab_size: int = 32000,
42
+ max_cg_step_training: int = 30,
43
+ max_cg_step_decoding: int = 30,
44
+ **kwargs
45
+ ):
46
+ self.attn_mode = attn_mode
47
+ self.hidden_size = hidden_size
48
+ self.use_output_gate = use_output_gate
49
+ self.use_short_conv = use_short_conv
50
+ self.conv_size = conv_size
51
+ self.num_heads = num_heads
52
+ self.head_dim = head_dim
53
+ self.max_position_embeddings = max_position_embeddings
54
+
55
+ self.hidden_ratio = hidden_ratio
56
+ self.intermediate_size = intermediate_size
57
+ self.hidden_act = hidden_act
58
+ self.num_hidden_layers = num_hidden_layers
59
+ self.norm_eps = norm_eps
60
+ self.attn = attn
61
+ self.use_cache = use_cache
62
+ self.initializer_range = initializer_range
63
+ self.lambda_lower_bound = lambda_lower_bound
64
+
65
+ self.fuse_norm = fuse_norm
66
+ self.fuse_swiglu = fuse_swiglu
67
+ self.fuse_cross_entropy = fuse_cross_entropy
68
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
69
+ self.use_l2warp = use_l2warp
70
+ self.vocab_size = vocab_size
71
+ self.max_cg_step_training = max_cg_step_training
72
+ self.max_cg_step_decoding = max_cg_step_decoding
73
+
74
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
75
+ raise ValueError(
76
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
77
+ )
78
+ if fuse_linear_cross_entropy:
79
+ warnings.warn(
80
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
81
+ "at the potential cost of reduced precision. "
82
+ "If you observe issues like loss divergence, consider disabling this setting."
83
+ )
84
+
85
+ if attn is not None:
86
+ if not isinstance(attn, Dict):
87
+ raise ValueError("attn must be a dictionary")
88
+ if 'layers' not in attn:
89
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
90
+ if 'num_heads' not in attn:
91
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
92
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
93
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
94
+ attn['window_size'] = attn.get('window_size', None)
95
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
96
+
97
+ super().__init__(
98
+ pad_token_id=pad_token_id,
99
+ bos_token_id=bos_token_id,
100
+ eos_token_id=eos_token_id,
101
+ tie_word_embeddings=tie_word_embeddings,
102
+ **kwargs,
103
+ )
models/mesa_net/modeling_mesa_net.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.mesa_net import MesaNet
18
+ from fla.models.mesa_net.configuration_mesa_net import MesaNetConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as MesaNetMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class MesaNetBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: MesaNetConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = MesaNet(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ num_heads=config.num_heads,
62
+ head_dim=config.head_dim,
63
+ use_output_gate=config.use_output_gate,
64
+ use_short_conv=config.use_short_conv,
65
+ conv_size=config.conv_size,
66
+ norm_eps=config.norm_eps,
67
+ lambda_lower_bound=config.lambda_lower_bound,
68
+ layer_idx=layer_idx,
69
+ max_cg_step_training=config.max_cg_step_training,
70
+ max_cg_step_decoding=config.max_cg_step_decoding
71
+ )
72
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
73
+ self.mlp = MesaNetMLP(
74
+ hidden_size=config.hidden_size,
75
+ hidden_ratio=config.hidden_ratio,
76
+ intermediate_size=config.intermediate_size,
77
+ hidden_act=config.hidden_act,
78
+ fuse_swiglu=config.fuse_swiglu
79
+ )
80
+
81
+ def forward(
82
+ self,
83
+ hidden_states: torch.Tensor,
84
+ attention_mask: Optional[torch.Tensor] = None,
85
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
86
+ use_cache: Optional[bool] = False,
87
+ output_attentions: Optional[bool] = False,
88
+ **kwargs: Unpack[Dict]
89
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
90
+ residual = hidden_states
91
+ hidden_states = self.attn_norm(hidden_states)
92
+ hidden_states, attentions, past_key_values = self.attn(
93
+ hidden_states=hidden_states,
94
+ attention_mask=attention_mask,
95
+ past_key_values=past_key_values,
96
+ use_cache=use_cache,
97
+ output_attentions=output_attentions,
98
+ **kwargs
99
+ )
100
+ if self.config.fuse_norm:
101
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
102
+ else:
103
+ hidden_states = residual + hidden_states
104
+ residual = hidden_states
105
+ hidden_states = self.mlp_norm(hidden_states)
106
+ hidden_states = self.mlp(hidden_states, **kwargs)
107
+ hidden_states = residual + hidden_states
108
+
109
+ outputs = (hidden_states, attentions, past_key_values)
110
+
111
+ return outputs
112
+
113
+
114
+ class MesaNetPreTrainedModel(PreTrainedModel):
115
+
116
+ config_class = MesaNetConfig
117
+ base_model_prefix = 'model'
118
+ supports_gradient_checkpointing = True
119
+ _no_split_modules = ['MesaNetBlock']
120
+ _supports_cache_class = True
121
+
122
+ def __init__(self, *inputs, **kwargs):
123
+ super().__init__(*inputs, **kwargs)
124
+
125
+ def _init_weights(
126
+ self,
127
+ module: nn.Module,
128
+ prenorm_residual_strategy: Optional[str] = None,
129
+ num_residuals_per_layer: int = 2,
130
+ ):
131
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
132
+ # Slightly different from the TF version which uses truncated_normal for initialization
133
+ # cf https://github.com/pytorch/pytorch/pull/5617
134
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
135
+ if module.bias is not None:
136
+ nn.init.zeros_(module.bias)
137
+ elif isinstance(module, nn.Embedding):
138
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
139
+ elif hasattr(module, 'reset_parameters'):
140
+ module.reset_parameters()
141
+
142
+ if prenorm_residual_strategy is not None:
143
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
144
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
145
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
146
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
147
+ #
148
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
149
+ p = None
150
+ if hasattr(module, 'o_proj'):
151
+ p = module.o_proj.weight
152
+ elif hasattr(module, 'down_proj'):
153
+ p = module.down_proj.weight
154
+ if p is not None:
155
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
156
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
157
+ # We need to reinit p since this code could be called multiple times
158
+ # Having just p *= scale would repeatedly scale it down
159
+ if prenorm_residual_strategy == 'rescale':
160
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
161
+ with torch.no_grad():
162
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
163
+ elif prenorm_residual_strategy == 'zero':
164
+ nn.init.zeros_(p)
165
+ else:
166
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
167
+
168
+
169
+ class MesaNetModel(MesaNetPreTrainedModel):
170
+
171
+ def __init__(self, config: MesaNetConfig):
172
+ super().__init__(config)
173
+ self.padding_idx = config.pad_token_id
174
+ self.vocab_size = config.vocab_size
175
+
176
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
177
+ self.layers = nn.ModuleList([MesaNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
178
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
179
+
180
+ self.gradient_checkpointing = False
181
+
182
+ self.post_init()
183
+
184
+ def get_input_embeddings(self):
185
+ return self.embeddings
186
+
187
+ def set_input_embeddings(self, value):
188
+ self.embeddings = value
189
+
190
+ def forward(
191
+ self,
192
+ input_ids: Optional[torch.LongTensor] = None,
193
+ attention_mask: Optional[torch.Tensor] = None, # noqa
194
+ inputs_embeds: Optional[torch.FloatTensor] = None,
195
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
196
+ use_cache: Optional[bool] = None,
197
+ output_attentions: Optional[bool] = None,
198
+ output_hidden_states: Optional[bool] = None,
199
+ return_dict: Optional[bool] = None,
200
+ **kwargs: Unpack[Dict]
201
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
202
+ if output_attentions:
203
+ warnings.warn("`MesaNetModel` does not `output_attentions` now, setting it to `False`.")
204
+ output_attentions = False
205
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
206
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
207
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
208
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
209
+
210
+ # retrieve input_ids and inputs_embeds
211
+ if input_ids is not None and inputs_embeds is not None:
212
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
213
+ if input_ids is None and inputs_embeds is None:
214
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
215
+
216
+ if inputs_embeds is None:
217
+ inputs_embeds = self.embeddings(input_ids)
218
+ hidden_states = inputs_embeds
219
+
220
+ if use_cache and not isinstance(past_key_values, Cache):
221
+ past_key_values = Cache.from_legacy_cache(past_key_values)
222
+
223
+ all_hidden_states = () if output_hidden_states else None
224
+ all_attns = () if output_attentions else None
225
+ for layer in self.layers:
226
+ if output_hidden_states:
227
+ all_hidden_states += (hidden_states,)
228
+
229
+ hidden_states, attentions, past_key_values = layer(
230
+ hidden_states,
231
+ attention_mask=attention_mask,
232
+ past_key_values=past_key_values,
233
+ use_cache=use_cache,
234
+ output_attentions=output_attentions,
235
+ **kwargs
236
+ )
237
+
238
+ if output_attentions:
239
+ all_attns += (attentions,)
240
+
241
+ hidden_states = self.norm(hidden_states)
242
+
243
+ # add hidden states from the last decoder layer
244
+ if output_hidden_states:
245
+ all_hidden_states += (hidden_states,)
246
+
247
+ if not return_dict:
248
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
249
+ return BaseModelOutputWithPast(
250
+ last_hidden_state=hidden_states,
251
+ past_key_values=past_key_values,
252
+ hidden_states=all_hidden_states,
253
+ attentions=all_attns
254
+ )
255
+
256
+
257
+ class MesaNetForCausalLM(MesaNetPreTrainedModel, FLAGenerationMixin):
258
+
259
+ _tied_weights_keys = ["lm_head.weight"]
260
+
261
+ def __init__(self, config):
262
+ super().__init__(config)
263
+ self.model = MesaNetModel(config)
264
+ self.vocab_size = config.vocab_size
265
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
266
+ self.criterion = None
267
+
268
+ # Initialize weights and apply final processing
269
+ self.post_init()
270
+
271
+ def get_input_embeddings(self):
272
+ return self.model.embeddings
273
+
274
+ def set_input_embeddings(self, value):
275
+ self.model.embeddings = value
276
+
277
+ def get_output_embeddings(self):
278
+ return self.lm_head
279
+
280
+ def set_output_embeddings(self, new_embeddings):
281
+ self.lm_head = new_embeddings
282
+
283
+ def set_decoder(self, decoder):
284
+ self.model = decoder
285
+
286
+ def get_decoder(self):
287
+ return self.model
288
+
289
+ def generate(self, *args, **kwargs):
290
+ try:
291
+ return super().generate(*args, **kwargs)
292
+ except AttributeError as exception:
293
+ if 'past_key_values' in str(exception):
294
+ raise AttributeError(
295
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
296
+ f"which is not supported for {self.__class__.__name__}. "
297
+ f"Try another generation strategy instead. "
298
+ f"For the available generation strategies, check this doc: "
299
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
300
+ )
301
+ else:
302
+ raise exception
303
+
304
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
305
+ def forward(
306
+ self,
307
+ input_ids: torch.LongTensor = None,
308
+ attention_mask: Optional[torch.Tensor] = None,
309
+ inputs_embeds: Optional[torch.Tensor] = None,
310
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
311
+ labels: Optional[torch.LongTensor] = None,
312
+ use_cache: Optional[bool] = None,
313
+ output_attentions: Optional[bool] = None,
314
+ output_hidden_states: Optional[bool] = None,
315
+ return_dict: Optional[bool] = None,
316
+ logits_to_keep: Optional[int] = 0,
317
+ **kwargs: Unpack[Dict]
318
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
319
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
320
+ output_hidden_states = (
321
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
322
+ )
323
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
324
+
325
+ outputs = self.model(
326
+ input_ids=input_ids,
327
+ attention_mask=attention_mask,
328
+ inputs_embeds=inputs_embeds,
329
+ past_key_values=past_key_values,
330
+ use_cache=use_cache,
331
+ output_attentions=output_attentions,
332
+ output_hidden_states=output_hidden_states,
333
+ return_dict=return_dict,
334
+ **kwargs
335
+ )
336
+
337
+ hidden_states = outputs[0]
338
+
339
+ loss, logits = None, None
340
+ if not self.config.fuse_linear_cross_entropy or labels is None:
341
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
342
+ if labels is not None:
343
+ if getattr(self, 'criterion', None) is None:
344
+ if self.config.fuse_linear_cross_entropy:
345
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
346
+ elif self.config.fuse_cross_entropy:
347
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
348
+ else:
349
+ criterion = nn.CrossEntropyLoss()
350
+ else:
351
+ criterion = self.criterion
352
+ labels = labels.to(hidden_states.device)
353
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
354
+ if self.config.fuse_linear_cross_entropy:
355
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
356
+ else:
357
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
358
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
359
+
360
+ if not return_dict:
361
+ output = (logits,) + outputs[1:]
362
+ return (loss,) + output if loss is not None else output
363
+
364
+ return CausalLMOutputWithPast(
365
+ loss=loss,
366
+ logits=logits,
367
+ past_key_values=outputs.past_key_values,
368
+ hidden_states=outputs.hidden_states,
369
+ attentions=outputs.attentions,
370
+ )
models/mla/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.mla.configuration_mla import MLAConfig
6
+ from fla.models.mla.modeling_mla import MLAForCausalLM, MLAModel
7
+
8
+ AutoConfig.register(MLAConfig.model_type, MLAConfig, exist_ok=True)
9
+ AutoModel.register(MLAConfig, MLAModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(MLAConfig, MLAForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = [
14
+ 'MLAConfig', 'MLAModel', 'MLAForCausalLM',
15
+ ]
models/mla/configuration_mla.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class MLAConfig(PretrainedConfig):
10
+
11
+ model_type = 'mla'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ num_hidden_layers: int = 24,
18
+ num_heads: int = 16,
19
+ q_lora_rank: Optional[int] = 64,
20
+ qk_rope_head_dim: int = 64,
21
+ kv_lora_rank: int = 512, # following the original Deepseek paper
22
+ v_head_dim: int = 128,
23
+ qk_nope_head_dim: int = 128,
24
+ qk_head_dim: Optional[int] = 192, # qk_nope_head_dim + qk_rope_head_dim
25
+ window_size: Optional[int] = None,
26
+ rope_theta: Optional[float] = 10000.,
27
+ max_position_embeddings: int = 2048,
28
+ rope_scaling: Optional[dict] = None,
29
+ hidden_ratio: Optional[int] = 4,
30
+ intermediate_size: Optional[int] = None,
31
+ hidden_act: str = "swish",
32
+ initializer_range: float = 0.02,
33
+ elementwise_affine: Optional[bool] = True,
34
+ norm_eps: float = 1e-6,
35
+ use_cache: bool = True,
36
+ pad_token_id: int = None,
37
+ bos_token_id: int = 1,
38
+ eos_token_id: int = 2,
39
+ tie_word_embeddings: bool = False,
40
+ fuse_norm: bool = True,
41
+ fuse_swiglu: bool = True,
42
+ fuse_cross_entropy: bool = True,
43
+ fuse_linear_cross_entropy: bool = False,
44
+ use_l2warp: bool = False,
45
+ vocab_size: int = 32000,
46
+ **kwargs,
47
+ ):
48
+ self.hidden_size = hidden_size
49
+ self.num_hidden_layers = num_hidden_layers
50
+ self.num_heads = num_heads
51
+
52
+ # MLA specific args
53
+ self.q_lora_rank = q_lora_rank
54
+ self.qk_rope_head_dim = qk_rope_head_dim
55
+ self.kv_lora_rank = kv_lora_rank
56
+ self.v_head_dim = v_head_dim
57
+ self.qk_nope_head_dim = qk_nope_head_dim
58
+ self.qk_head_dim = qk_head_dim
59
+ self.rope_scaling = rope_scaling
60
+
61
+ self.window_size = window_size
62
+ self.rope_theta = rope_theta
63
+ self.max_position_embeddings = max_position_embeddings
64
+
65
+ self.hidden_ratio = hidden_ratio
66
+ self.intermediate_size = intermediate_size
67
+ self.hidden_act = hidden_act
68
+
69
+ self.initializer_range = initializer_range
70
+ self.elementwise_affine = elementwise_affine
71
+ self.norm_eps = norm_eps
72
+ self.use_cache = use_cache
73
+
74
+ self.fuse_norm = fuse_norm
75
+ self.fuse_swiglu = fuse_swiglu
76
+ self.fuse_cross_entropy = fuse_cross_entropy
77
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
78
+ self.use_l2warp = use_l2warp
79
+ self.vocab_size = vocab_size
80
+
81
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
82
+ raise ValueError(
83
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
84
+ )
85
+ if fuse_linear_cross_entropy:
86
+ warnings.warn(
87
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
88
+ "at the potential cost of reduced precision. "
89
+ "If you observe issues like loss divergence, consider disabling this setting."
90
+ )
91
+
92
+ super().__init__(
93
+ pad_token_id=pad_token_id,
94
+ bos_token_id=bos_token_id,
95
+ eos_token_id=eos_token_id,
96
+ tie_word_embeddings=tie_word_embeddings,
97
+ **kwargs,
98
+ )
models/mla/modeling_mla.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.mla import MultiheadLatentAttention
17
+ from fla.models.mla.configuration_mla import MLAConfig
18
+ from fla.models.utils import Cache, FLAGenerationMixin
19
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
20
+ from fla.modules import GatedMLP as MLAMLP
21
+ from fla.modules import RMSNorm
22
+ from fla.modules.l2warp import l2_warp
23
+
24
+ if TYPE_CHECKING:
25
+ from transformers.processing_utils import Unpack
26
+
27
+
28
+ try:
29
+ from transformers.modeling_layers import GradientCheckpointingLayer
30
+ except ImportError:
31
+ from fla.models.modeling_layers import GradientCheckpointingLayer
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class MLABlock(GradientCheckpointingLayer):
37
+
38
+ def __init__(self, config: MLAConfig, layer_idx: int):
39
+ super().__init__()
40
+
41
+ self.config = config
42
+ self.layer_idx = layer_idx
43
+
44
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
45
+ self.attn = MultiheadLatentAttention(
46
+ hidden_size=config.hidden_size,
47
+ num_heads=config.num_heads,
48
+ q_lora_rank=config.q_lora_rank,
49
+ qk_rope_head_dim=config.qk_rope_head_dim,
50
+ kv_lora_rank=config.kv_lora_rank,
51
+ v_head_dim=config.v_head_dim,
52
+ qk_nope_head_dim=config.qk_nope_head_dim,
53
+ qk_head_dim=config.qk_head_dim,
54
+ window_size=config.window_size,
55
+ rope_theta=config.rope_theta,
56
+ max_position_embeddings=config.max_position_embeddings,
57
+ rope_scaling=config.rope_scaling,
58
+ layer_idx=layer_idx
59
+ )
60
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
61
+ self.mlp = MLAMLP(
62
+ hidden_size=config.hidden_size,
63
+ hidden_ratio=config.hidden_ratio,
64
+ intermediate_size=config.intermediate_size,
65
+ hidden_act=config.hidden_act,
66
+ fuse_swiglu=config.fuse_swiglu
67
+ )
68
+
69
+ def forward(
70
+ self,
71
+ hidden_states: torch.Tensor,
72
+ attention_mask: Optional[torch.Tensor] = None,
73
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
74
+ use_cache: Optional[bool] = False,
75
+ output_attentions: Optional[bool] = False,
76
+ **kwargs: Unpack[Dict]
77
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
78
+ residual = hidden_states
79
+ hidden_states = self.attn_norm(hidden_states)
80
+ hidden_states, attentions, past_key_values = self.attn(
81
+ hidden_states=hidden_states,
82
+ attention_mask=attention_mask,
83
+ past_key_values=past_key_values,
84
+ use_cache=use_cache,
85
+ output_attentions=output_attentions,
86
+ **kwargs
87
+ )
88
+ if self.config.fuse_norm:
89
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
90
+ else:
91
+ hidden_states = residual + hidden_states
92
+ residual = hidden_states
93
+ hidden_states = self.mlp_norm(hidden_states)
94
+ hidden_states = self.mlp(hidden_states, **kwargs)
95
+ hidden_states = residual + hidden_states
96
+
97
+ outputs = (hidden_states, attentions, past_key_values)
98
+
99
+ return outputs
100
+
101
+
102
+ class MLAPreTrainedModel(PreTrainedModel):
103
+
104
+ config_class = MLAConfig
105
+ base_model_prefix = 'model'
106
+ supports_gradient_checkpointing = True
107
+ _no_split_modules = ['MLABlock']
108
+ _supports_cache_class = True
109
+
110
+ def __init__(self, *inputs, **kwargs):
111
+ super().__init__(*inputs, **kwargs)
112
+
113
+ def _init_weights(
114
+ self,
115
+ module: nn.Module,
116
+ prenorm_residual_strategy: Optional[str] = None,
117
+ num_residuals_per_layer: int = 2,
118
+ ):
119
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
120
+ # Slightly different from the TF version which uses truncated_normal for initialization
121
+ # cf https://github.com/pytorch/pytorch/pull/5617
122
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
123
+ if module.bias is not None:
124
+ nn.init.zeros_(module.bias)
125
+ elif isinstance(module, nn.Embedding):
126
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
127
+ elif hasattr(module, 'reset_parameters'):
128
+ module.reset_parameters()
129
+
130
+ if prenorm_residual_strategy is not None:
131
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
132
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
133
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
134
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
135
+ #
136
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
137
+ p = None
138
+ if hasattr(module, 'o_proj'):
139
+ p = module.o_proj.weight
140
+ elif hasattr(module, 'down_proj'):
141
+ p = module.down_proj.weight
142
+ if p is not None:
143
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
144
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
145
+ # We need to reinit p since this code could be called multiple times
146
+ # Having just p *= scale would repeatedly scale it down
147
+ if prenorm_residual_strategy == 'rescale':
148
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
149
+ with torch.no_grad():
150
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
151
+ elif prenorm_residual_strategy == 'zero':
152
+ nn.init.zeros_(p)
153
+ else:
154
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
155
+
156
+
157
+ class MLAModel(MLAPreTrainedModel):
158
+
159
+ def __init__(self, config: MLAConfig):
160
+ super().__init__(config)
161
+ self.padding_idx = config.pad_token_id
162
+ self.vocab_size = config.vocab_size
163
+
164
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
165
+ self.layers = nn.ModuleList([MLABlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
166
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
167
+
168
+ self.gradient_checkpointing = False
169
+
170
+ self.post_init()
171
+
172
+ def get_input_embeddings(self):
173
+ return self.embeddings
174
+
175
+ def set_input_embeddings(self, value):
176
+ self.embeddings = value
177
+
178
+ def forward(
179
+ self,
180
+ input_ids: Optional[torch.LongTensor] = None,
181
+ attention_mask: Optional[torch.Tensor] = None, # noqa
182
+ inputs_embeds: Optional[torch.FloatTensor] = None,
183
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
184
+ use_cache: Optional[bool] = None,
185
+ output_attentions: Optional[bool] = None,
186
+ output_hidden_states: Optional[bool] = None,
187
+ return_dict: Optional[bool] = None,
188
+ **kwargs: Unpack[Dict]
189
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
190
+ if output_attentions:
191
+ warnings.warn("`MLAModel` does not `output_attentions` now, setting it to `False`.")
192
+ output_attentions = False
193
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
194
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
195
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
196
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
197
+
198
+ # retrieve input_ids and inputs_embeds
199
+ if input_ids is not None and inputs_embeds is not None:
200
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
201
+ if input_ids is None and inputs_embeds is None:
202
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
203
+
204
+ if inputs_embeds is None:
205
+ inputs_embeds = self.embeddings(input_ids)
206
+ hidden_states = inputs_embeds
207
+
208
+ if use_cache and not isinstance(past_key_values, Cache):
209
+ past_key_values = Cache.from_legacy_cache(past_key_values)
210
+
211
+ all_hidden_states = () if output_hidden_states else None
212
+ all_attns = () if output_attentions else None
213
+ for layer in self.layers:
214
+ if output_hidden_states:
215
+ all_hidden_states += (hidden_states,)
216
+
217
+ hidden_states, attentions, past_key_values = layer(
218
+ hidden_states,
219
+ attention_mask=attention_mask,
220
+ past_key_values=past_key_values,
221
+ use_cache=use_cache,
222
+ output_attentions=output_attentions,
223
+ **kwargs
224
+ )
225
+
226
+ if output_attentions:
227
+ all_attns += (attentions,)
228
+
229
+ hidden_states = self.norm(hidden_states)
230
+
231
+ # add hidden states from the last decoder layer
232
+ if output_hidden_states:
233
+ all_hidden_states += (hidden_states,)
234
+
235
+ if not return_dict:
236
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
237
+ return BaseModelOutputWithPast(
238
+ last_hidden_state=hidden_states,
239
+ past_key_values=past_key_values,
240
+ hidden_states=all_hidden_states,
241
+ attentions=all_attns
242
+ )
243
+
244
+
245
+ class MLAForCausalLM(MLAPreTrainedModel, FLAGenerationMixin):
246
+
247
+ _tied_weights_keys = ["lm_head.weight"]
248
+
249
+ def __init__(self, config: MLAConfig):
250
+ super().__init__(config)
251
+ self.model = MLAModel(config)
252
+ self.vocab_size = config.vocab_size
253
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
254
+ self.criterion = None
255
+
256
+ # Initialize weights and apply final processing
257
+ self.post_init()
258
+
259
+ def get_input_embeddings(self):
260
+ return self.model.embeddings
261
+
262
+ def set_input_embeddings(self, value):
263
+ self.model.embeddings = value
264
+
265
+ def get_output_embeddings(self):
266
+ return self.lm_head
267
+
268
+ def set_output_embeddings(self, new_embeddings):
269
+ self.lm_head = new_embeddings
270
+
271
+ def set_decoder(self, decoder):
272
+ self.model = decoder
273
+
274
+ def get_decoder(self):
275
+ return self.model
276
+
277
+ def generate(self, *args, **kwargs):
278
+ try:
279
+ return super().generate(*args, **kwargs)
280
+ except AttributeError as exception:
281
+ if 'past_key_values' in str(exception):
282
+ raise AttributeError(
283
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
284
+ f"which is not supported for {self.__class__.__name__}. "
285
+ f"Try another generation strategy instead. "
286
+ f"For the available generation strategies, check this doc: "
287
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
288
+ )
289
+ else:
290
+ raise exception
291
+
292
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
293
+ def forward(
294
+ self,
295
+ input_ids: torch.LongTensor = None,
296
+ attention_mask: Optional[torch.Tensor] = None,
297
+ inputs_embeds: Optional[torch.Tensor] = None,
298
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
299
+ labels: Optional[torch.LongTensor] = None,
300
+ use_cache: Optional[bool] = None,
301
+ output_attentions: Optional[bool] = None,
302
+ output_hidden_states: Optional[bool] = None,
303
+ return_dict: Optional[bool] = None,
304
+ logits_to_keep: Optional[int] = 0,
305
+ **kwargs: Unpack[Dict]
306
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
307
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
308
+ output_hidden_states = (
309
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
310
+ )
311
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
312
+
313
+ outputs = self.model(
314
+ input_ids=input_ids,
315
+ attention_mask=attention_mask,
316
+ inputs_embeds=inputs_embeds,
317
+ past_key_values=past_key_values,
318
+ use_cache=use_cache,
319
+ output_attentions=output_attentions,
320
+ output_hidden_states=output_hidden_states,
321
+ return_dict=return_dict,
322
+ **kwargs
323
+ )
324
+
325
+ hidden_states = outputs[0]
326
+
327
+ loss, logits = None, None
328
+ if not self.config.fuse_linear_cross_entropy or labels is None:
329
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
330
+ if labels is not None:
331
+ if getattr(self, 'criterion', None) is None:
332
+ if self.config.fuse_linear_cross_entropy:
333
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
334
+ elif self.config.fuse_cross_entropy:
335
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
336
+ else:
337
+ criterion = nn.CrossEntropyLoss()
338
+ else:
339
+ criterion = self.criterion
340
+ labels = labels.to(hidden_states.device)
341
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
342
+ if self.config.fuse_linear_cross_entropy:
343
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
344
+ else:
345
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
346
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
347
+
348
+ if not return_dict:
349
+ output = (logits,) + outputs[1:]
350
+ return (loss,) + output if loss is not None else output
351
+
352
+ return CausalLMOutputWithPast(
353
+ loss=loss,
354
+ logits=logits,
355
+ past_key_values=outputs.past_key_values,
356
+ hidden_states=outputs.hidden_states,
357
+ attentions=outputs.attentions,
358
+ )
models/mom/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.mom.configuration_mom import MomConfig
6
+ from fla.models.mom.modeling_mom import MomForCausalLM, MomModel
7
+
8
+ AutoConfig.register(MomConfig.model_type, MomConfig, exist_ok=True)
9
+ AutoModel.register(MomConfig, MomModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(MomConfig, MomForCausalLM, exist_ok=True)
11
+
12
+ __all__ = ['MomConfig', 'MomForCausalLM', 'MomModel']
models/mom/configuration_mom.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Dict, Optional
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+
8
+ class MomConfig(PretrainedConfig):
9
+ model_type = 'mom'
10
+ keys_to_ignore_at_inference = ['past_key_values']
11
+
12
+ def __init__(
13
+ self,
14
+ attn_mode: str = "chunk",
15
+ hidden_size: int = 2048,
16
+ conv_size: int = 4,
17
+ num_heads: int = 4,
18
+ head_dim: int = 256,
19
+ expand_v: float = 1.,
20
+ use_output_gate: bool = True,
21
+ use_short_conv: bool = True,
22
+ max_position_embeddings: int = 2048,
23
+ hidden_ratio: Optional[int] = 4,
24
+ intermediate_size: Optional[int] = None,
25
+ hidden_act: str = "swish",
26
+ num_hidden_layers: int = 24,
27
+ norm_eps: float = 1e-6,
28
+ attn: Optional[Dict] = None,
29
+ use_cache: bool = True,
30
+ pad_token_id: Optional[int] = None,
31
+ bos_token_id: int = 1,
32
+ eos_token_id: int = 2,
33
+ tie_word_embeddings: bool = False,
34
+ initializer_range: float = 0.02,
35
+ num_memories: int = 4,
36
+ topk: int = 2,
37
+ capacity: float = 1.0,
38
+ use_layer_wise_balance: bool = True,
39
+ aux_loss_scale: float = 0.01,
40
+ shared_mem: bool = True,
41
+ single_kv_proj: bool = False,
42
+ mom_backend: str = 'gated_deltanet',
43
+ fuse_norm: bool = True,
44
+ fuse_swiglu: bool = True,
45
+ fuse_cross_entropy: bool = True,
46
+ vocab_size: int = 32000,
47
+ **kwargs
48
+ ):
49
+ self.attn_mode = attn_mode
50
+ self.hidden_size = hidden_size
51
+ self.num_heads = num_heads
52
+ self.head_dim = head_dim
53
+ self.expand_v = expand_v
54
+ self.conv_size = conv_size
55
+ self.use_output_gate = use_output_gate
56
+ self.use_short_conv = use_short_conv
57
+ self.max_position_embeddings = max_position_embeddings
58
+
59
+ self.hidden_ratio = hidden_ratio
60
+ self.intermediate_size = intermediate_size
61
+ self.hidden_act = hidden_act
62
+ self.num_hidden_layers = num_hidden_layers
63
+ self.norm_eps = norm_eps
64
+ self.attn = attn
65
+ self.use_cache = use_cache
66
+ self.initializer_range = initializer_range
67
+
68
+ self.num_memories = num_memories
69
+ self.topk = topk
70
+ self.capacity = capacity
71
+ self.use_layer_wise_balance = use_layer_wise_balance
72
+ self.aux_loss_scale = aux_loss_scale
73
+ self.shared_mem = shared_mem
74
+ self.single_kv_proj = single_kv_proj
75
+ self.mom_backend = mom_backend
76
+
77
+ self.fuse_norm = fuse_norm
78
+ self.fuse_swiglu = fuse_swiglu
79
+ self.fuse_cross_entropy = fuse_cross_entropy
80
+ self.vocab_size = vocab_size
81
+
82
+ if self.mom_backend not in ['gated_deltanet']:
83
+ raise NotImplementedError(f"The MoM backend {mom_backend} is not currently supported.")
84
+
85
+ if attn is not None:
86
+ if not isinstance(attn, Dict):
87
+ raise ValueError("attn must be a dictionary")
88
+ if 'layers' not in attn:
89
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
90
+ if 'num_heads' not in attn:
91
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
92
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
93
+ attn['window_size'] = attn.get('window_size', None)
94
+
95
+ super().__init__(
96
+ pad_token_id=pad_token_id,
97
+ bos_token_id=bos_token_id,
98
+ eos_token_id=eos_token_id,
99
+ tie_word_embeddings=tie_word_embeddings,
100
+ **kwargs,
101
+ )
models/mom/modeling_mom.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from dataclasses import dataclass
8
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
+ from transformers.modeling_utils import PreTrainedModel
14
+ from transformers.utils import logging
15
+
16
+ from fla.layers import MomAttention
17
+ from fla.layers.attn import Attention
18
+ from fla.models.mom.configuration_mom import MomConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as MomMLP
22
+ from fla.modules import RMSNorm
23
+
24
+ if TYPE_CHECKING:
25
+ from transformers.processing_utils import Unpack
26
+
27
+
28
+ try:
29
+ from transformers.modeling_layers import GradientCheckpointingLayer
30
+ except ImportError:
31
+ from fla.models.modeling_layers import GradientCheckpointingLayer
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ def load_balancing_loss_func(
37
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
38
+ num_experts: Optional[int] = None,
39
+ top_k=2,
40
+ attention_mask: Optional[torch.Tensor] = None,
41
+ ) -> Union[torch.Tensor, int]:
42
+ r"""
43
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
44
+
45
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
46
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
47
+ experts is too unbalanced.
48
+
49
+ Args:
50
+ gate_logits:
51
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
52
+ shape [batch_size X sequence_length, num_experts].
53
+ num_experts:
54
+ Number of experts
55
+ top_k:
56
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
57
+ parameter.
58
+ attention_mask (`torch.Tensor`, *optional*):
59
+ The attention_mask used in forward function
60
+ shape [batch_size X sequence_length] if not None.
61
+
62
+ Returns:
63
+ The auxiliary loss.
64
+ """
65
+ if gate_logits is None or not isinstance(gate_logits, tuple):
66
+ return 0
67
+
68
+ if isinstance(gate_logits, tuple):
69
+ compute_device = gate_logits[0].device
70
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
71
+
72
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
73
+
74
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
75
+
76
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
77
+
78
+ if attention_mask is None:
79
+ # Compute the percentage of tokens routed to each experts
80
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
81
+
82
+ # Compute the average probability of routing to these experts
83
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
84
+ else:
85
+ batch_size, sequence_length = attention_mask.shape
86
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
87
+
88
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
89
+ expert_attention_mask = (
90
+ attention_mask[None, :, :, None, None]
91
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
92
+ .reshape(-1, top_k, num_experts)
93
+ .to(compute_device)
94
+ )
95
+
96
+ # Compute the percentage of tokens routed to each experts
97
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
98
+ expert_attention_mask, dim=0
99
+ )
100
+
101
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
102
+ router_per_expert_attention_mask = (
103
+ attention_mask[None, :, :, None]
104
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
105
+ .reshape(-1, num_experts)
106
+ .to(compute_device)
107
+ )
108
+
109
+ # Compute the average probability of routing to these experts
110
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
111
+ router_per_expert_attention_mask, dim=0
112
+ )
113
+
114
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
115
+ return overall_loss * num_experts
116
+
117
+
118
+ class MomBlock(GradientCheckpointingLayer):
119
+
120
+ def __init__(self, config: MomConfig, layer_idx: int):
121
+ super().__init__()
122
+ self.hidden_size = config.hidden_size
123
+
124
+ self.attn_norm = RMSNorm(hidden_size=config.hidden_size, eps=config.norm_eps)
125
+ if config.attn is not None and layer_idx in config.attn['layers']:
126
+ self.attn = Attention(
127
+ hidden_size=config.hidden_size,
128
+ num_heads=config.attn['num_heads'],
129
+ num_kv_heads=config.attn['num_kv_heads'],
130
+ window_size=config.attn['window_size'],
131
+ max_position_embeddings=config.max_position_embeddings,
132
+ layer_idx=layer_idx
133
+ )
134
+ else:
135
+ if config.mom_backend == 'gated_deltanet':
136
+ self.attn = MomAttention(
137
+ mode=config.attn_mode,
138
+ hidden_size=config.hidden_size,
139
+ expand_v=config.expand_v,
140
+ head_dim=config.head_dim,
141
+ num_heads=config.num_heads,
142
+ use_output_gate=config.use_output_gate,
143
+ use_short_conv=config.use_short_conv,
144
+ conv_size=config.conv_size,
145
+ norm_eps=config.norm_eps,
146
+ layer_idx=layer_idx,
147
+ num_memories=config.num_memories,
148
+ topk=config.topk,
149
+ capacity=config.capacity,
150
+ shared_mem=config.shared_mem,
151
+ single_kv_proj=config.single_kv_proj,
152
+ )
153
+ else:
154
+ raise NotImplementedError(f"The MoM backend {config.mom_backend} is not currently supported.")
155
+ self.mlp_norm = RMSNorm(hidden_size=config.hidden_size, eps=config.norm_eps)
156
+ self.mlp = MomMLP(
157
+ hidden_size=config.hidden_size,
158
+ hidden_ratio=config.hidden_ratio,
159
+ intermediate_size=config.intermediate_size,
160
+ hidden_act=config.hidden_act,
161
+ fuse_swiglu=config.fuse_swiglu
162
+ )
163
+
164
+ def forward(
165
+ self,
166
+ hidden_states: torch.Tensor,
167
+ attention_mask: Optional[torch.Tensor] = None,
168
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
169
+ use_cache: Optional[bool] = False,
170
+ output_attentions: Optional[bool] = False,
171
+ **kwargs: Unpack[Dict]
172
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
173
+ residual = hidden_states
174
+ if hasattr(self, 'attn_norm'):
175
+ hidden_states = self.attn_norm(hidden_states)
176
+ hidden_states, attentions, past_key_values, router_logits = self.attn(
177
+ hidden_states=hidden_states,
178
+ attention_mask=attention_mask,
179
+ past_key_values=past_key_values,
180
+ use_cache=use_cache,
181
+ output_attentions=output_attentions,
182
+ **kwargs
183
+ )
184
+ if hasattr(self, 'mlp_norm'):
185
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
186
+ else:
187
+ hidden_states = residual + hidden_states
188
+ residual = hidden_states
189
+ hidden_states = self.mlp(hidden_states, **kwargs)
190
+ hidden_states = residual + hidden_states
191
+
192
+ outputs = (hidden_states, attentions, past_key_values, router_logits)
193
+
194
+ return outputs
195
+
196
+
197
+ class MomPreTrainedModel(PreTrainedModel):
198
+
199
+ config_class = MomConfig
200
+ supports_gradient_checkpointing = True
201
+ _no_split_modules = ['MomBlock']
202
+
203
+ def __init__(self, *inputs, **kwargs):
204
+ super().__init__(*inputs, **kwargs)
205
+
206
+ def _init_weights(
207
+ self,
208
+ module: nn.Module,
209
+ rescale_prenorm_residual: bool = False,
210
+ num_residuals_per_layer: int = 2,
211
+ ):
212
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
213
+ # Slightly different from the TF version which uses truncated_normal for initialization
214
+ # cf https://github.com/pytorch/pytorch/pull/5617
215
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
216
+ if module.bias is not None:
217
+ nn.init.zeros_(module.bias)
218
+ elif isinstance(module, nn.Embedding):
219
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
220
+ if module.padding_idx is not None:
221
+ module.weight.data[module.padding_idx].zero_()
222
+ elif hasattr(module, 'reset_parameters'):
223
+ module.reset_parameters()
224
+
225
+ if rescale_prenorm_residual:
226
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
227
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
228
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
229
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
230
+ #
231
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
232
+ for name, p in module.named_parameters():
233
+ if name in ["o_proj.weight", "down_proj.weight"]:
234
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
235
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
236
+ # We need to reinit p since this code could be called multiple times
237
+ # Having just p *= scale would repeatedly scale it down
238
+ with torch.no_grad():
239
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
240
+
241
+
242
+ @dataclass
243
+ class MomOutputWithPast(BaseModelOutputWithPast):
244
+ router_logits: Optional[Tuple[torch.FloatTensor, ...]] = None
245
+
246
+
247
+ class MomModel(MomPreTrainedModel):
248
+
249
+ def __init__(self, config: MomConfig):
250
+ super().__init__(config)
251
+ self.padding_idx = config.pad_token_id
252
+ self.vocab_size = config.vocab_size
253
+
254
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
255
+ self.layers = nn.ModuleList([MomBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
256
+ self.norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
257
+
258
+ self.gradient_checkpointing = False
259
+
260
+ self.post_init()
261
+
262
+ def get_input_embeddings(self):
263
+ return self.embeddings
264
+
265
+ def set_input_embeddings(self, value):
266
+ self.embeddings = value
267
+
268
+ def forward(
269
+ self,
270
+ input_ids: Optional[torch.LongTensor] = None,
271
+ attention_mask: Optional[torch.Tensor] = None, # noqa
272
+ inputs_embeds: Optional[torch.FloatTensor] = None,
273
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
274
+ use_cache: Optional[bool] = None,
275
+ output_attentions: Optional[bool] = None,
276
+ output_hidden_states: Optional[bool] = None,
277
+ return_dict: Optional[bool] = None,
278
+ **kwargs: Unpack[Dict]
279
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
280
+ if output_attentions:
281
+ warnings.warn("`MomModel` does not `output_attentions` now, setting it to `False`.")
282
+ output_attentions = False
283
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
284
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
285
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
286
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
287
+
288
+ # retrieve input_ids and inputs_embeds
289
+ if input_ids is not None and inputs_embeds is not None:
290
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
291
+ if input_ids is None and inputs_embeds is None:
292
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
293
+
294
+ if inputs_embeds is None:
295
+ inputs_embeds = self.embeddings(input_ids)
296
+ hidden_states = inputs_embeds
297
+
298
+ if use_cache and not isinstance(past_key_values, Cache):
299
+ past_key_values = Cache.from_legacy_cache(past_key_values)
300
+
301
+ all_hidden_states = () if output_hidden_states else None
302
+ all_attns = () if output_attentions else None
303
+ all_router_logits = ()
304
+
305
+ for layer in self.layers:
306
+ if output_hidden_states:
307
+ all_hidden_states += (hidden_states,)
308
+
309
+ hidden_states, attentions, past_key_values, router_logits = layer(
310
+ hidden_states,
311
+ attention_mask=attention_mask,
312
+ past_key_values=past_key_values,
313
+ use_cache=use_cache,
314
+ output_attentions=output_attentions,
315
+ **kwargs
316
+ )
317
+
318
+ if output_attentions:
319
+ all_attns += (attentions,)
320
+ all_router_logits += (router_logits,)
321
+
322
+ hidden_states = self.norm(hidden_states)
323
+
324
+ # add hidden states from the last decoder layer
325
+ if output_hidden_states:
326
+ all_hidden_states += (hidden_states,)
327
+
328
+ if not return_dict:
329
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
330
+ return MomOutputWithPast(
331
+ last_hidden_state=hidden_states,
332
+ past_key_values=past_key_values,
333
+ hidden_states=all_hidden_states,
334
+ attentions=all_attns,
335
+ router_logits=all_router_logits
336
+ )
337
+
338
+
339
+ @dataclass
340
+ class MomCausalLMOutputWithPast(CausalLMOutputWithPast):
341
+ aux_loss: Optional[torch.FloatTensor] = None
342
+ router_logits: Optional[Tuple[torch.FloatTensor, ...]] = None
343
+
344
+
345
+ class MomForCausalLM(MomPreTrainedModel, FLAGenerationMixin):
346
+
347
+ _tied_weights_keys = ["lm_head.weight"]
348
+
349
+ def __init__(self, config):
350
+ super().__init__(config)
351
+ self.model = MomModel(config)
352
+ self.vocab_size = config.vocab_size
353
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
354
+ self.num_memories = config.num_memories
355
+ self.topk = config.topk
356
+ self.aux_loss_scale = config.aux_loss_scale
357
+
358
+ # Initialize weights and apply final processing
359
+ self.post_init()
360
+
361
+ def get_input_embeddings(self):
362
+ return self.model.embeddings
363
+
364
+ def set_input_embeddings(self, value):
365
+ self.model.embeddings = value
366
+
367
+ def get_output_embeddings(self):
368
+ return self.lm_head
369
+
370
+ def set_output_embeddings(self, new_embeddings):
371
+ self.lm_head = new_embeddings
372
+
373
+ def set_decoder(self, decoder):
374
+ self.model = decoder
375
+
376
+ def get_decoder(self):
377
+ return self.model
378
+
379
+ def generate(self, *args, **kwargs):
380
+ try:
381
+ return super().generate(*args, **kwargs)
382
+ except AttributeError as exception:
383
+ if 'past_key_values' in str(exception):
384
+ raise AttributeError(
385
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
386
+ f"which is not supported for {self.__class__.__name__}. "
387
+ f"Try another generation strategy instead. "
388
+ f"For the available generation strategies, check this doc: "
389
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
390
+ )
391
+ else:
392
+ raise exception
393
+
394
+ def forward(
395
+ self,
396
+ input_ids: torch.LongTensor = None,
397
+ attention_mask: Optional[torch.Tensor] = None,
398
+ inputs_embeds: Optional[torch.Tensor] = None,
399
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
400
+ labels: Optional[torch.LongTensor] = None,
401
+ use_cache: Optional[bool] = None,
402
+ output_attentions: Optional[bool] = None,
403
+ output_hidden_states: Optional[bool] = None,
404
+ return_dict: Optional[bool] = None,
405
+ num_logits_to_keep: Optional[int] = 0,
406
+ **kwargs: Unpack[Dict]
407
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
408
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
409
+ output_hidden_states = (
410
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
411
+ )
412
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
413
+
414
+ outputs = self.model(
415
+ input_ids=input_ids,
416
+ attention_mask=attention_mask,
417
+ inputs_embeds=inputs_embeds,
418
+ past_key_values=past_key_values,
419
+ use_cache=use_cache,
420
+ output_attentions=output_attentions,
421
+ output_hidden_states=output_hidden_states,
422
+ return_dict=return_dict,
423
+ **kwargs
424
+ )
425
+
426
+ hidden_states = outputs[0]
427
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training
428
+ logits = None if fuse_linear_and_cross_entropy else self.lm_head(hidden_states[:, -num_logits_to_keep:])
429
+
430
+ loss = None
431
+ aux_loss = None
432
+ if labels is not None:
433
+ if self.config.fuse_cross_entropy:
434
+ if fuse_linear_and_cross_entropy:
435
+ loss_fct = FusedLinearCrossEntropyLoss()
436
+ else:
437
+ loss_fct = FusedCrossEntropyLoss(inplace_backward=True)
438
+ else:
439
+ loss_fct = nn.CrossEntropyLoss()
440
+ # Enable model parallelism
441
+ labels = labels.to(hidden_states.device)
442
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], loss_fct.ignore_index)), 1)
443
+ if fuse_linear_and_cross_entropy:
444
+ loss = loss_fct(hidden_states.view(-1, self.config.hidden_size),
445
+ labels.view(-1),
446
+ self.lm_head.weight,
447
+ self.lm_head.bias)
448
+ else:
449
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
450
+
451
+ aux_loss = load_balancing_loss_func(
452
+ outputs.router_logits,
453
+ self.num_memories,
454
+ self.topk,
455
+ attention_mask,
456
+ )
457
+
458
+ # print(aux_loss)
459
+
460
+ loss += aux_loss.to(loss.device) * self.aux_loss_scale
461
+
462
+ if not return_dict:
463
+ output = (logits,) + outputs[1:]
464
+ return (loss,) + output if loss is not None else output
465
+
466
+ return MomCausalLMOutputWithPast(
467
+ loss=loss,
468
+ logits=logits,
469
+ past_key_values=outputs.past_key_values,
470
+ hidden_states=outputs.hidden_states,
471
+ attentions=outputs.attentions,
472
+ router_logits=outputs.router_logits,
473
+ aux_loss=aux_loss
474
+ )
models/nsa/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.nsa.configuration_nsa import NSAConfig
6
+ from fla.models.nsa.modeling_nsa import NSAForCausalLM, NSAModel
7
+
8
+ AutoConfig.register(NSAConfig.model_type, NSAConfig, exist_ok=True)
9
+ AutoModel.register(NSAConfig, NSAModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(NSAConfig, NSAForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = [
14
+ 'NSAConfig', 'NSAModel', 'NSAForCausalLM',
15
+ ]
models/nsa/configuration_nsa.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class NSAConfig(PretrainedConfig):
10
+
11
+ model_type = 'nsa'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ num_hidden_layers: int = 24,
18
+ num_heads: int = 64,
19
+ num_kv_heads: int = 4,
20
+ head_dim: int = 32,
21
+ qkv_bias: bool = False,
22
+ block_size: int = 64,
23
+ block_counts: Optional[int] = 16,
24
+ window_size: Optional[int] = 512,
25
+ rope_theta: Optional[float] = 10000.,
26
+ max_position_embeddings: int = 2048,
27
+ hidden_ratio: Optional[int] = 4,
28
+ intermediate_size: Optional[int] = None,
29
+ hidden_act: str = "swish",
30
+ initializer_range: float = 0.02,
31
+ elementwise_affine: Optional[bool] = True,
32
+ norm_eps: float = 1e-6,
33
+ use_cache: bool = True,
34
+ pad_token_id: Optional[int] = None,
35
+ bos_token_id: int = 1,
36
+ eos_token_id: int = 2,
37
+ tie_word_embeddings: bool = False,
38
+ fuse_norm: bool = True,
39
+ fuse_swiglu: bool = True,
40
+ fuse_cross_entropy: bool = True,
41
+ fuse_linear_cross_entropy: bool = False,
42
+ use_l2warp: bool = False,
43
+ vocab_size: int = 32000,
44
+ **kwargs,
45
+ ):
46
+ self.hidden_size = hidden_size
47
+ self.num_hidden_layers = num_hidden_layers
48
+ self.num_heads = num_heads
49
+ self.num_kv_heads = num_kv_heads
50
+ self.head_dim = head_dim
51
+ self.qkv_bias = qkv_bias
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
+
58
+ self.hidden_ratio = hidden_ratio
59
+ self.intermediate_size = intermediate_size
60
+ self.hidden_act = hidden_act
61
+
62
+ self.initializer_range = initializer_range
63
+ self.elementwise_affine = elementwise_affine
64
+ self.norm_eps = norm_eps
65
+ self.use_cache = use_cache
66
+
67
+ self.fuse_norm = fuse_norm
68
+ self.fuse_swiglu = fuse_swiglu
69
+ self.fuse_cross_entropy = fuse_cross_entropy
70
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
71
+ self.use_l2warp = use_l2warp
72
+ self.vocab_size = vocab_size
73
+
74
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
75
+ raise ValueError(
76
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
77
+ )
78
+ if fuse_linear_cross_entropy:
79
+ warnings.warn(
80
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
81
+ "at the potential cost of reduced precision. "
82
+ "If you observe issues like loss divergence, consider disabling this setting."
83
+ )
84
+
85
+ super().__init__(
86
+ pad_token_id=pad_token_id,
87
+ bos_token_id=bos_token_id,
88
+ eos_token_id=eos_token_id,
89
+ tie_word_embeddings=tie_word_embeddings,
90
+ **kwargs,
91
+ )
models/nsa/modeling_nsa.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.nsa import NativeSparseAttention
17
+ from fla.models.nsa.configuration_nsa import NSAConfig
18
+ from fla.models.utils import Cache, FLAGenerationMixin
19
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
20
+ from fla.modules import GatedMLP as NSAMLP
21
+ from fla.modules import RMSNorm
22
+ from fla.modules.l2warp import l2_warp
23
+
24
+ if TYPE_CHECKING:
25
+ from transformers.processing_utils import Unpack
26
+
27
+
28
+ try:
29
+ from transformers.modeling_layers import GradientCheckpointingLayer
30
+ except ImportError:
31
+ from fla.models.modeling_layers import GradientCheckpointingLayer
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class NSABlock(GradientCheckpointingLayer):
37
+
38
+ def __init__(self, config: NSAConfig, layer_idx: int):
39
+ super().__init__()
40
+
41
+ self.config = config
42
+ self.layer_idx = layer_idx
43
+
44
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
45
+ self.attn = NativeSparseAttention(
46
+ hidden_size=config.hidden_size,
47
+ num_heads=config.num_heads,
48
+ num_kv_heads=config.num_kv_heads,
49
+ qkv_bias=config.qkv_bias,
50
+ block_size=config.block_size,
51
+ block_counts=config.block_counts,
52
+ window_size=config.window_size,
53
+ rope_theta=config.rope_theta,
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
58
+ self.mlp = NSAMLP(
59
+ hidden_size=config.hidden_size,
60
+ hidden_ratio=config.hidden_ratio,
61
+ intermediate_size=config.intermediate_size,
62
+ hidden_act=config.hidden_act,
63
+ fuse_swiglu=config.fuse_swiglu
64
+ )
65
+
66
+ def forward(
67
+ self,
68
+ hidden_states: torch.Tensor,
69
+ attention_mask: Optional[torch.Tensor] = None,
70
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
71
+ use_cache: Optional[bool] = False,
72
+ output_attentions: Optional[bool] = False,
73
+ **kwargs: Unpack[Dict]
74
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
75
+ residual = hidden_states
76
+ hidden_states = self.attn_norm(hidden_states)
77
+ hidden_states, attentions, past_key_values = self.attn(
78
+ hidden_states=hidden_states,
79
+ attention_mask=attention_mask,
80
+ past_key_values=past_key_values,
81
+ use_cache=use_cache,
82
+ output_attentions=output_attentions,
83
+ **kwargs
84
+ )
85
+ if self.config.fuse_norm:
86
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
87
+ else:
88
+ hidden_states = residual + hidden_states
89
+ residual = hidden_states
90
+ hidden_states = self.mlp_norm(hidden_states)
91
+ hidden_states = self.mlp(hidden_states, **kwargs)
92
+ hidden_states = residual + hidden_states
93
+
94
+ outputs = (hidden_states, attentions, past_key_values)
95
+
96
+ return outputs
97
+
98
+
99
+ class NSAPreTrainedModel(PreTrainedModel):
100
+
101
+ config_class = NSAConfig
102
+ base_model_prefix = 'model'
103
+ supports_gradient_checkpointing = True
104
+ _no_split_modules = ['NSABlock']
105
+ _supports_cache_class = True
106
+
107
+ def __init__(self, *inputs, **kwargs):
108
+ super().__init__(*inputs, **kwargs)
109
+
110
+ def _init_weights(
111
+ self,
112
+ module: nn.Module,
113
+ prenorm_residual_strategy: Optional[str] = None,
114
+ num_residuals_per_layer: int = 2,
115
+ ):
116
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
117
+ # Slightly different from the TF version which uses truncated_normal for initialization
118
+ # cf https://github.com/pytorch/pytorch/pull/5617
119
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
120
+ if module.bias is not None:
121
+ nn.init.zeros_(module.bias)
122
+ elif isinstance(module, nn.Embedding):
123
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
124
+ elif hasattr(module, 'reset_parameters'):
125
+ module.reset_parameters()
126
+
127
+ if prenorm_residual_strategy is not None:
128
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
129
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
130
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
131
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
132
+ #
133
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
134
+ p = None
135
+ if hasattr(module, 'o_proj'):
136
+ p = module.o_proj.weight
137
+ elif hasattr(module, 'down_proj'):
138
+ p = module.down_proj.weight
139
+ if p is not None:
140
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
141
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
142
+ # We need to reinit p since this code could be called multiple times
143
+ # Having just p *= scale would repeatedly scale it down
144
+ if prenorm_residual_strategy == 'rescale':
145
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
146
+ with torch.no_grad():
147
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
148
+ elif prenorm_residual_strategy == 'zero':
149
+ nn.init.zeros_(p)
150
+ else:
151
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
152
+
153
+
154
+ class NSAModel(NSAPreTrainedModel):
155
+
156
+ def __init__(self, config: NSAConfig):
157
+ super().__init__(config)
158
+ self.padding_idx = config.pad_token_id
159
+ self.vocab_size = config.vocab_size
160
+
161
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
162
+ self.layers = nn.ModuleList([NSABlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
163
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
164
+
165
+ self.gradient_checkpointing = False
166
+
167
+ self.post_init()
168
+
169
+ def get_input_embeddings(self):
170
+ return self.embeddings
171
+
172
+ def set_input_embeddings(self, value):
173
+ self.embeddings = value
174
+
175
+ def forward(
176
+ self,
177
+ input_ids: Optional[torch.LongTensor] = None,
178
+ attention_mask: Optional[torch.Tensor] = None, # noqa
179
+ inputs_embeds: Optional[torch.FloatTensor] = None,
180
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
181
+ use_cache: Optional[bool] = None,
182
+ output_attentions: Optional[bool] = None,
183
+ output_hidden_states: Optional[bool] = None,
184
+ return_dict: Optional[bool] = None,
185
+ **kwargs: Unpack[Dict]
186
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
187
+ if output_attentions:
188
+ warnings.warn("`NSAModel` does not `output_attentions` now, setting it to `False`.")
189
+ output_attentions = False
190
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
191
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
192
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
193
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
194
+
195
+ # retrieve input_ids and inputs_embeds
196
+ if input_ids is not None and inputs_embeds is not None:
197
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
198
+ if input_ids is None and inputs_embeds is None:
199
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
200
+
201
+ if inputs_embeds is None:
202
+ inputs_embeds = self.embeddings(input_ids)
203
+ hidden_states = inputs_embeds
204
+
205
+ if use_cache and not isinstance(past_key_values, Cache):
206
+ past_key_values = Cache.from_legacy_cache(past_key_values)
207
+
208
+ all_hidden_states = () if output_hidden_states else None
209
+ all_attns = () if output_attentions else None
210
+ for layer in self.layers:
211
+ if output_hidden_states:
212
+ all_hidden_states += (hidden_states,)
213
+
214
+ hidden_states, attentions, past_key_values = layer(
215
+ hidden_states,
216
+ attention_mask=attention_mask,
217
+ past_key_values=past_key_values,
218
+ use_cache=use_cache,
219
+ output_attentions=output_attentions,
220
+ **kwargs
221
+ )
222
+
223
+ if output_attentions:
224
+ all_attns += (attentions,)
225
+
226
+ hidden_states = self.norm(hidden_states)
227
+
228
+ # add hidden states from the last decoder layer
229
+ if output_hidden_states:
230
+ all_hidden_states += (hidden_states,)
231
+
232
+ if not return_dict:
233
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
234
+ return BaseModelOutputWithPast(
235
+ last_hidden_state=hidden_states,
236
+ past_key_values=past_key_values,
237
+ hidden_states=all_hidden_states,
238
+ attentions=all_attns
239
+ )
240
+
241
+
242
+ class NSAForCausalLM(NSAPreTrainedModel, FLAGenerationMixin):
243
+
244
+ _tied_weights_keys = ["lm_head.weight"]
245
+
246
+ def __init__(self, config):
247
+ super().__init__(config)
248
+ self.model = NSAModel(config)
249
+ self.vocab_size = config.vocab_size
250
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
251
+ self.criterion = None
252
+
253
+ # Initialize weights and apply final processing
254
+ self.post_init()
255
+
256
+ def get_input_embeddings(self):
257
+ return self.model.embeddings
258
+
259
+ def set_input_embeddings(self, value):
260
+ self.model.embeddings = value
261
+
262
+ def get_output_embeddings(self):
263
+ return self.lm_head
264
+
265
+ def set_output_embeddings(self, new_embeddings):
266
+ self.lm_head = new_embeddings
267
+
268
+ def set_decoder(self, decoder):
269
+ self.model = decoder
270
+
271
+ def get_decoder(self):
272
+ return self.model
273
+
274
+ def generate(self, *args, **kwargs):
275
+ try:
276
+ return super().generate(*args, **kwargs)
277
+ except AttributeError as exception:
278
+ if 'past_key_values' in str(exception):
279
+ raise AttributeError(
280
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
281
+ f"which is not supported for {self.__class__.__name__}. "
282
+ f"Try another generation strategy instead. "
283
+ f"For the available generation strategies, check this doc: "
284
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
285
+ )
286
+ else:
287
+ raise exception
288
+
289
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
290
+ def forward(
291
+ self,
292
+ input_ids: torch.LongTensor = None,
293
+ attention_mask: Optional[torch.Tensor] = None,
294
+ inputs_embeds: Optional[torch.Tensor] = None,
295
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
296
+ labels: Optional[torch.LongTensor] = None,
297
+ use_cache: Optional[bool] = None,
298
+ output_attentions: Optional[bool] = None,
299
+ output_hidden_states: Optional[bool] = None,
300
+ return_dict: Optional[bool] = None,
301
+ logits_to_keep: Optional[int] = 0,
302
+ **kwargs: Unpack[Dict]
303
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
304
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
305
+ output_hidden_states = (
306
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
307
+ )
308
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
309
+
310
+ outputs = self.model(
311
+ input_ids=input_ids,
312
+ attention_mask=attention_mask,
313
+ inputs_embeds=inputs_embeds,
314
+ past_key_values=past_key_values,
315
+ use_cache=use_cache,
316
+ output_attentions=output_attentions,
317
+ output_hidden_states=output_hidden_states,
318
+ return_dict=return_dict,
319
+ **kwargs
320
+ )
321
+
322
+ hidden_states = outputs[0]
323
+
324
+ loss, logits = None, None
325
+ if not self.config.fuse_linear_cross_entropy or labels is None:
326
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
327
+ if labels is not None:
328
+ if getattr(self, 'criterion', None) is None:
329
+ if self.config.fuse_linear_cross_entropy:
330
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
331
+ elif self.config.fuse_cross_entropy:
332
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
333
+ else:
334
+ criterion = nn.CrossEntropyLoss()
335
+ else:
336
+ criterion = self.criterion
337
+ labels = labels.to(hidden_states.device)
338
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
339
+ if self.config.fuse_linear_cross_entropy:
340
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
341
+ else:
342
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
343
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
344
+
345
+ if not return_dict:
346
+ output = (logits,) + outputs[1:]
347
+ return (loss,) + output if loss is not None else output
348
+
349
+ return CausalLMOutputWithPast(
350
+ loss=loss,
351
+ logits=logits,
352
+ past_key_values=outputs.past_key_values,
353
+ hidden_states=outputs.hidden_states,
354
+ attentions=outputs.attentions,
355
+ )
models/past_gdn/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from .configuration_past_gdn import past_gdnConfig
6
+ from .modeling_past_gdn import past_gdnForCausalLM, past_gdnModel
7
+
8
+ AutoConfig.register(past_gdnConfig.model_type, past_gdnConfig)
9
+ AutoModel.register(past_gdnConfig, past_gdnModel)
10
+ AutoModelForCausalLM.register(past_gdnConfig, past_gdnForCausalLM)
11
+
12
+ __all__ = ['past_gdnConfig', 'past_gdnForCausalLM', 'past_gdnModel']
models/past_gdn/configuration_past_gdn.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Dict, Optional
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+
8
+
9
+ class past_gdnConfig(PretrainedConfig):
10
+ model_type = 'past_gdn'
11
+ keys_to_ignore_at_inference = ['past_key_values']
12
+ def __init__(
13
+ self,
14
+ attn_mode: str = "chunk",
15
+ hidden_size: int = 2048,
16
+ expand_k: int = 1,
17
+ expand_v: int = 1,
18
+ use_gate: bool = False,
19
+ use_short_conv: bool = True,
20
+ conv_size: int = 4,
21
+ use_beta: bool = True,
22
+ use_output_norm: bool = True,
23
+ num_heads: int = 16,
24
+ qk_norm: str = 'l2',
25
+ qk_activation: str = 'silu',
26
+ max_position_embeddings: int = 2048,
27
+ hidden_ratio: Optional[int] = 4,
28
+ intermediate_size: Optional[int] = None,
29
+ hidden_act: str = "swish",
30
+ num_hidden_layers: int = 24,
31
+ norm_eps: float = 1e-6,
32
+ attn: Optional[Dict] = None,
33
+ use_cache: bool = True,
34
+ pad_token_id: int = None,
35
+ bos_token_id: int = 1,
36
+ eos_token_id: int = 2,
37
+ tie_word_embeddings: bool = False,
38
+ initializer_range: float = 0.02,
39
+ fuse_norm: bool = True,
40
+ fuse_swiglu: bool = True,
41
+ fuse_cross_entropy: bool = True,
42
+ vocab_size: int = 32000,
43
+ aux_loss_scale:float = 0.01,
44
+ ratio : int = 2,
45
+ topk : int = 1,
46
+ **kwargs
47
+ ):
48
+ self.attn_mode = attn_mode
49
+ self.aux_loss_scale = aux_loss_scale
50
+ self.hidden_size = hidden_size
51
+ self.expand_k = expand_k
52
+ self.expand_v = expand_v
53
+ self.use_gate = use_gate
54
+ self.use_short_conv = use_short_conv
55
+ self.conv_size = conv_size
56
+ self.use_beta = use_beta
57
+ self.use_output_norm = use_output_norm
58
+ self.num_heads = num_heads
59
+ self.qk_norm = qk_norm
60
+ self.qk_activation = qk_activation
61
+ self.max_position_embeddings = max_position_embeddings
62
+
63
+ self.hidden_ratio = hidden_ratio
64
+ self.intermediate_size = intermediate_size
65
+ self.hidden_act = hidden_act
66
+ self.num_hidden_layers = num_hidden_layers
67
+ self.norm_eps = norm_eps
68
+ self.attn = attn
69
+ self.use_cache = use_cache
70
+ self.initializer_range = initializer_range
71
+ self.fuse_norm = fuse_norm
72
+ self.fuse_swiglu = fuse_swiglu
73
+ self.fuse_cross_entropy = fuse_cross_entropy
74
+ self.vocab_size = vocab_size
75
+ self.ratio = ratio
76
+ self.topk = topk
77
+
78
+ if attn is not None:
79
+ if not isinstance(attn, Dict):
80
+ raise ValueError("attn must be a dictionary")
81
+ if 'layers' not in attn:
82
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
83
+ if 'num_heads' not in attn:
84
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
85
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
86
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
87
+ attn['window_size'] = attn.get('window_size', None)
88
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
89
+
90
+ super().__init__(
91
+ pad_token_id=pad_token_id,
92
+ bos_token_id=bos_token_id,
93
+ eos_token_id=eos_token_id,
94
+ tie_word_embeddings=tie_word_embeddings,
95
+ **kwargs,
96
+ )
models/past_gdn/modeling_past_gdn.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union,Iterable
8
+ from einops import rearrange
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.utils.checkpoint
12
+ from transformers.generation import GenerationMixin
13
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.utils import logging
16
+ from transformers.utils.deprecation import deprecate_kwarg
17
+
18
+ from ...layers.attn import Attention
19
+ from ...layers.past_gdn import past_gdn
20
+ from ...models.past_gdn.configuration_past_gdn import past_gdnConfig
21
+ from fla.models.utils import Cache
22
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
23
+ from fla.modules import GatedMLP as past_gdnMLP
24
+ from ...modules import RMSNorm
25
+ from ...modules import RotaryEmbedding
26
+ logger = logging.get_logger(__name__)
27
+
28
+ if TYPE_CHECKING:
29
+ from transformers.processing_utils import Unpack
30
+
31
+
32
+ class past_gdnBlock(nn.Module):
33
+ def __init__(self, config: past_gdnConfig, layer_idx: int):
34
+ super().__init__()
35
+
36
+ self.config = config
37
+ self.layer_idx = layer_idx
38
+ print(config)
39
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
40
+ if config.attn is not None and layer_idx in config.attn['layers']:
41
+ self.attn = Attention(
42
+ hidden_size=config.hidden_size,
43
+ num_heads=config.attn['num_heads'],
44
+ num_kv_heads=config.attn['num_kv_heads'],
45
+ qkv_bias=config.attn['qkv_bias'],
46
+ window_size=config.attn['window_size'],
47
+ rope_theta=config.attn['rope_theta'],
48
+ max_position_embeddings=config.max_position_embeddings,
49
+ layer_idx=layer_idx
50
+ )
51
+ else:
52
+ self.attn = past_gdn(
53
+ mode=config.attn_mode,
54
+ hidden_size=config.hidden_size,
55
+ expand_k=config.expand_k,
56
+ expand_v=config.expand_v,
57
+ num_heads=config.num_heads,
58
+ use_gate=config.use_gate,
59
+ use_short_conv=config.use_short_conv,
60
+ use_output_norm=config.use_output_norm,
61
+ conv_size=config.conv_size,
62
+ norm_eps=config.norm_eps,
63
+ ratio = config.ratio,
64
+ topk = config.topk,
65
+ layer_idx=layer_idx
66
+ )
67
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
68
+ self.mlp = past_gdnMLP(
69
+ hidden_size=config.hidden_size,
70
+ hidden_ratio=config.hidden_ratio,
71
+ intermediate_size=config.intermediate_size,
72
+ hidden_act=config.hidden_act,
73
+ fuse_swiglu=config.fuse_swiglu
74
+ )
75
+
76
+ def forward(
77
+ self,
78
+ hidden_states: torch.Tensor,
79
+ attention_mask: Optional[torch.Tensor] = None,
80
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
81
+ use_cache: Optional[bool] = False,
82
+ output_attentions: Optional[bool] = False,
83
+ **kwargs: Unpack[Dict]
84
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
85
+ residual = hidden_states
86
+ hidden_states = self.attn_norm(hidden_states)
87
+ hidden_states, attentions, past_key_values,router_logits = self.attn(
88
+ hidden_states=hidden_states,
89
+ attention_mask=attention_mask,
90
+ past_key_values=past_key_values,
91
+ use_cache=use_cache,
92
+ output_attentions=output_attentions,
93
+ **kwargs
94
+ )
95
+ if self.config.fuse_norm:
96
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
97
+ else:
98
+ hidden_states = residual + hidden_states
99
+ residual = hidden_states
100
+ hidden_states = self.mlp_norm(hidden_states)
101
+ hidden_states = self.mlp(hidden_states, **kwargs)
102
+ hidden_states = residual + hidden_states
103
+
104
+ outputs = (hidden_states, attentions, past_key_values,router_logits)
105
+
106
+ return outputs
107
+
108
+
109
+ class past_gdnPreTrainedModel(PreTrainedModel):
110
+
111
+ config_class = past_gdnConfig
112
+ base_model_prefix = 'model'
113
+ supports_gradient_checkpointing = True
114
+ _no_split_modules = ['past_gdnBlock']
115
+ _supports_cache_class = True
116
+
117
+ def __init__(self, *inputs, **kwargs):
118
+ super().__init__(*inputs, **kwargs)
119
+
120
+ def _init_weights(
121
+ self,
122
+ module: nn.Module,
123
+ prenorm_residual_strategy: Optional[str] = 'rescale',
124
+ num_residuals_per_layer: int = 2,
125
+ ):
126
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
127
+ # Slightly different from the TF version which uses truncated_normal for initialization
128
+ # cf https://github.com/pytorch/pytorch/pull/5617
129
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
130
+ if module.bias is not None:
131
+ nn.init.zeros_(module.bias)
132
+ elif isinstance(module, nn.Embedding):
133
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
134
+ elif hasattr(module, 'reset_parameters'):
135
+ module.reset_parameters()
136
+
137
+ if prenorm_residual_strategy is not None:
138
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
139
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
140
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
141
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
142
+ #
143
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
144
+ p = None
145
+ if hasattr(module, 'o_proj'):
146
+ p = module.o_proj.weight
147
+ elif hasattr(module, 'down_proj'):
148
+ p = module.down_proj.weight
149
+ if p is not None:
150
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
151
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
152
+ # We need to reinit p since this code could be called multiple times
153
+ # Having just p *= scale would repeatedly scale it down
154
+ if prenorm_residual_strategy == 'rescale':
155
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
156
+ with torch.no_grad():
157
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
158
+ elif prenorm_residual_strategy == 'zero':
159
+ nn.init.zeros_(p)
160
+ else:
161
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
162
+
163
+
164
+ class past_gdnModel(past_gdnPreTrainedModel):
165
+
166
+ def __init__(self, config: past_gdnConfig):
167
+ super().__init__(config)
168
+ self.padding_idx = config.pad_token_id
169
+ self.vocab_size = config.vocab_size
170
+
171
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
172
+ self.layers = nn.ModuleList([past_gdnBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
173
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
174
+
175
+ self.gradient_checkpointing = False
176
+
177
+ self.post_init()
178
+
179
+ def get_input_embeddings(self):
180
+ return self.embeddings
181
+
182
+ def set_input_embeddings(self, value):
183
+ self.embeddings = value
184
+
185
+ def forward(
186
+ self,
187
+ input_ids: Optional[torch.LongTensor] = None,
188
+ attention_mask: Optional[torch.Tensor] = None, # noqa
189
+ inputs_embeds: Optional[torch.FloatTensor] = None,
190
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
191
+ use_cache: Optional[bool] = None,
192
+ output_attentions: Optional[bool] = None,
193
+ output_hidden_states: Optional[bool] = None,
194
+ return_dict: Optional[bool] = None,
195
+ **kwargs: Unpack[Dict]
196
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
197
+ if output_attentions:
198
+ warnings.warn("`past_gdnModel` does not `output_attentions` now, setting it to `False`.")
199
+ output_attentions = False
200
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
201
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
202
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
203
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
204
+
205
+ # retrieve input_ids and inputs_embeds
206
+ if input_ids is not None and inputs_embeds is not None:
207
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
208
+ if input_ids is None and inputs_embeds is None:
209
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
210
+
211
+ if inputs_embeds is None:
212
+ inputs_embeds = self.embeddings(input_ids)
213
+ hidden_states = inputs_embeds
214
+
215
+ if use_cache and not isinstance(past_key_values, Cache):
216
+ past_key_values = Cache.from_legacy_cache(past_key_values)
217
+
218
+ if self.gradient_checkpointing and self.training and use_cache:
219
+ logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
220
+ use_cache = False
221
+
222
+ all_hidden_states = () if output_hidden_states else None
223
+ all_attns = () if output_attentions else None
224
+ all_router_logits = ()
225
+ for layer in self.layers:
226
+ if output_hidden_states:
227
+ all_hidden_states += (hidden_states,)
228
+
229
+ if self.gradient_checkpointing and self.training:
230
+ hidden_states, attentions, past_key_values, router_logits = self._gradient_checkpointing_func(
231
+ layer.__call__,
232
+ hidden_states,
233
+ attention_mask,
234
+ past_key_values,
235
+ use_cache,
236
+ output_attentions,
237
+ **kwargs
238
+ )
239
+ else:
240
+ hidden_states, attentions, past_key_values, router_logits = layer(
241
+ hidden_states,
242
+ attention_mask=attention_mask,
243
+ past_key_values=past_key_values,
244
+ use_cache=use_cache,
245
+ output_attentions=output_attentions,
246
+ **kwargs
247
+ )
248
+
249
+ if output_attentions:
250
+ all_attns += (attentions,)
251
+ all_router_logits += (router_logits,)
252
+ hidden_states = self.norm(hidden_states)
253
+
254
+ # add hidden states from the last decoder layer
255
+ if output_hidden_states:
256
+ all_hidden_states += (hidden_states,)
257
+
258
+ if not return_dict:
259
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
260
+ # return BaseModelOutputWithPast(
261
+ # last_hidden_state=hidden_states,
262
+ # past_key_values=past_key_values,
263
+ # hidden_states=all_hidden_states,
264
+ # attentions=all_attns
265
+ # )
266
+ return past_gdnOutputWithPast(
267
+ last_hidden_state=hidden_states,
268
+ past_key_values=past_key_values,
269
+ hidden_states=all_hidden_states,
270
+ attentions=all_attns,
271
+ router_logits=all_router_logits
272
+ )
273
+
274
+
275
+ from dataclasses import dataclass
276
+ @dataclass
277
+ class past_gdnOutputWithPast(BaseModelOutputWithPast):
278
+ router_logits: Optional[Tuple[torch.FloatTensor, ...]] = None
279
+
280
+
281
+ @dataclass
282
+ class past_gdnCausalLMOutputWithPast(CausalLMOutputWithPast):
283
+ aux_loss: Optional[torch.FloatTensor] = None
284
+ router_logits: Optional[Tuple[torch.FloatTensor, ...]] = None
285
+
286
+ def load_balancing_loss_func(
287
+ gate_logits: Union[torch.Tensor, Tuple],
288
+ num_memories: torch.Tensor = None,
289
+ top_k=2,
290
+ use_layer_wise_balance=False,
291
+ ) -> torch.FloatTensor:
292
+ r"""
293
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
294
+
295
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
296
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
297
+ experts is too unbalanced.
298
+
299
+ Args:
300
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
301
+ Logits from the `gate`, should be a tuple of tensors. Shape: [batch_size, seqeunce_length, num_memories].
302
+ num_memories (`int`, *optional*):
303
+ Number of experts
304
+
305
+ Returns:
306
+ The auxiliary loss.
307
+ """
308
+ if gate_logits is None or (
309
+ isinstance(gate_logits, Iterable) and len(gate_logits) == 0
310
+ ):
311
+ return 0
312
+
313
+ # ✨ Here is the fix for balance loss in Mixtral.
314
+ # We should calculate the balance loss in a layer-wise manner otherwise it may lead to degenerated solutions.
315
+ if use_layer_wise_balance:
316
+ if not isinstance(gate_logits, Iterable):
317
+ gate_logits = (gate_logits,)
318
+ else:
319
+ if isinstance(gate_logits, Iterable):
320
+ gate_logits = (torch.cat(gate_logits, dim=0),)
321
+ else:
322
+ gate_logits = (gate_logits,)
323
+
324
+ all_balance_losses = []
325
+
326
+ for logits in gate_logits:
327
+ if logits.dim() == 4:
328
+ logits = rearrange(logits,'b h l r-> (b h) l r')
329
+ routing_weights, selected_experts = torch.topk(logits, top_k, dim=-1)
330
+ routing_weights = routing_weights.softmax(dim=-1).to(logits.dtype)
331
+ routing_weights_full = torch.zeros_like(logits).scatter(-1, selected_experts, routing_weights)
332
+
333
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
334
+ if selected_experts.dtype != torch.int64:
335
+ selected_experts = selected_experts.to(torch.int64)
336
+
337
+ if len(selected_experts.shape) == 2:
338
+ selected_experts = selected_experts.unsqueeze(2)
339
+
340
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_memories)
341
+
342
+ # For a given token, determine if it was routed to a given expert.
343
+ expert_mask = torch.max(expert_mask, axis=-2).values
344
+
345
+ # cast to float32 otherwise mean will fail
346
+ expert_mask = expert_mask.to(torch.float32)
347
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
348
+
349
+ router_prob_per_group_and_expert = torch.mean(routing_weights_full, axis=-2)
350
+
351
+ # ✨ balance loss for this layer
352
+ balance_loss = torch.mean(
353
+ tokens_per_group_and_expert * router_prob_per_group_and_expert
354
+ ) * (num_memories**2)
355
+ all_balance_losses.append(balance_loss.reshape(1))
356
+
357
+ all_balance_losses = torch.cat(all_balance_losses).mean() # ✨
358
+
359
+ return all_balance_losses
360
+
361
+
362
+ class past_gdnForCausalLM(past_gdnPreTrainedModel, GenerationMixin):
363
+
364
+ _tied_weights_keys = ["lm_head.weight"]
365
+
366
+ def __init__(self, config):
367
+ super().__init__(config)
368
+ self.model = past_gdnModel(config)
369
+ self.vocab_size = config.vocab_size
370
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
371
+ self.criterion = None
372
+
373
+ # Initialize weights and apply final processing
374
+ self.post_init()
375
+
376
+ def get_input_embeddings(self):
377
+ return self.model.embeddings
378
+
379
+ def set_input_embeddings(self, value):
380
+ self.model.embeddings = value
381
+
382
+ def get_output_embeddings(self):
383
+ return self.lm_head
384
+
385
+ def set_output_embeddings(self, new_embeddings):
386
+ self.lm_head = new_embeddings
387
+
388
+ def set_decoder(self, decoder):
389
+ self.model = decoder
390
+
391
+ def get_decoder(self):
392
+ return self.model
393
+
394
+ def generate(self, *args, **kwargs):
395
+ try:
396
+ return super().generate(*args, **kwargs)
397
+ except AttributeError as exception:
398
+ if 'past_key_values' in str(exception):
399
+ raise AttributeError(
400
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
401
+ f"which is not supported for {self.__class__.__name__}. "
402
+ f"Try another generation strategy instead. "
403
+ f"For the available generation strategies, check this doc: "
404
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
405
+ )
406
+ else:
407
+ raise exception
408
+
409
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
410
+ def prepare_inputs_for_generation(
411
+ self,
412
+ input_ids: torch.LongTensor = None,
413
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ inputs_embeds: Optional[torch.Tensor] = None,
416
+ use_cache: bool = True,
417
+ logits_to_keep: Optional[int] = None,
418
+ **kwargs
419
+ ):
420
+ # only last token for `inputs_ids` if the `past_key_values` is not empty.
421
+ if past_key_values is not None and len(past_key_values) > 0:
422
+ input_ids = input_ids[:, -1:]
423
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
424
+ if inputs_embeds is not None and len(past_key_values) == 0:
425
+ model_inputs = {'inputs_embeds': inputs_embeds}
426
+ else:
427
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
428
+ # recompiles graphs as the stride of the inputs is a guard.
429
+ # Ref: https://github.com/huggingface/transformers/pull/29114
430
+ # TODO: use `next_tokens` directly instead.
431
+ model_inputs = {'input_ids': input_ids.contiguous()}
432
+
433
+ if logits_to_keep is not None:
434
+ model_inputs['logits_to_keep'] = logits_to_keep
435
+
436
+ model_inputs.update({
437
+ 'past_key_values': past_key_values,
438
+ 'use_cache': use_cache,
439
+ 'attention_mask': attention_mask,
440
+ })
441
+ return model_inputs
442
+
443
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
444
+ def forward(
445
+ self,
446
+ input_ids: torch.LongTensor = None,
447
+ attention_mask: Optional[torch.Tensor] = None,
448
+ inputs_embeds: Optional[torch.Tensor] = None,
449
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
450
+ labels: Optional[torch.LongTensor] = None,
451
+ use_cache: Optional[bool] = None,
452
+ output_attentions: Optional[bool] = None,
453
+ output_hidden_states: Optional[bool] = None,
454
+ return_dict: Optional[bool] = None,
455
+ logits_to_keep: Optional[int] = 0,
456
+ **kwargs: Unpack[Dict]
457
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
458
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
459
+ output_hidden_states = (
460
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
461
+ )
462
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
463
+
464
+ outputs = self.model(
465
+ input_ids=input_ids,
466
+ attention_mask=attention_mask,
467
+ inputs_embeds=inputs_embeds,
468
+ past_key_values=past_key_values,
469
+ use_cache=use_cache,
470
+ output_attentions=output_attentions,
471
+ output_hidden_states=output_hidden_states,
472
+ return_dict=return_dict,
473
+ **kwargs
474
+ )
475
+
476
+ hidden_states = outputs[0]
477
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training
478
+
479
+ loss, logits = None, None
480
+ if not fuse_linear_and_cross_entropy or labels is None:
481
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
482
+ if labels is not None:
483
+ if getattr(self, 'criterion', None) is None:
484
+ if fuse_linear_and_cross_entropy:
485
+ criterion = FusedLinearCrossEntropyLoss()
486
+ elif self.config.fuse_cross_entropy:
487
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
488
+ else:
489
+ criterion = nn.CrossEntropyLoss()
490
+ else:
491
+ criterion = self.criterion
492
+ labels = labels.to(hidden_states.device)
493
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
494
+ if fuse_linear_and_cross_entropy:
495
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
496
+ else:
497
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
498
+
499
+ valid_router_logits = tuple(
500
+ logits
501
+ for logits in (outputs.router_logits if return_dict else outputs[-1])
502
+ if logits is not None
503
+ )
504
+ aux_loss = load_balancing_loss_func(
505
+ valid_router_logits,
506
+ self.config.ratio,
507
+ self.config.topk,
508
+ use_layer_wise_balance=True,
509
+ )
510
+ aux_loss *= self.config.aux_loss_scale
511
+ # print('aux_loss:',aux_loss)
512
+ if aux_loss:
513
+ loss += aux_loss
514
+
515
+ if not return_dict:
516
+ output = (logits,) + outputs[1:]
517
+ return (loss,) + output if loss is not None else output
518
+
519
+ # return CausalLMOutputWithPast(
520
+ # loss=loss,
521
+ # logits=logits,
522
+ # past_key_values=outputs.past_key_values,
523
+ # hidden_states=outputs.hidden_states,
524
+ # attentions=outputs.attentions,
525
+ # )
526
+
527
+ return past_gdnCausalLMOutputWithPast(
528
+ loss=loss,
529
+ logits=logits,
530
+ past_key_values=outputs.past_key_values,
531
+ hidden_states=outputs.hidden_states,
532
+ attentions=outputs.attentions,
533
+ router_logits=outputs.router_logits,
534
+ aux_loss=aux_loss
535
+ )
models/path_attn/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.path_attn.configuration_path_attention import PaTHAttentionConfig
6
+ from fla.models.path_attn.modeling_path_attention import PaTHAttentionForCausalLM, PaTHAttentionModel
7
+
8
+ AutoConfig.register(PaTHAttentionConfig.model_type, PaTHAttentionConfig, exist_ok=True)
9
+ AutoModel.register(PaTHAttentionConfig, PaTHAttentionModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(PaTHAttentionConfig, PaTHAttentionForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['PaTHAttentionConfig', 'PaTHAttentionForCausalLM', 'PaTHAttentionModel']
models/path_attn/configuration_path_attention.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class PaTHAttentionConfig(PretrainedConfig):
10
+
11
+ model_type = 'path_attn'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size: int = 2048,
17
+ num_hidden_layers: int = 24,
18
+ num_heads: int = 32,
19
+ num_kv_heads: Optional[int] = None,
20
+ hidden_ratio: Optional[int] = 4,
21
+ intermediate_size: Optional[int] = None,
22
+ hidden_act: str = "swish",
23
+ initializer_range: float = 0.02,
24
+ elementwise_affine: Optional[bool] = True,
25
+ norm_eps: float = 1e-6,
26
+ use_cache: bool = True,
27
+ pad_token_id: Optional[int] = None,
28
+ bos_token_id: int = 1,
29
+ eos_token_id: int = 2,
30
+ tie_word_embeddings: bool = False,
31
+ fuse_norm: bool = True,
32
+ fuse_swiglu: bool = True,
33
+ fuse_cross_entropy: bool = True,
34
+ fuse_linear_cross_entropy: bool = False,
35
+ use_l2warp: bool = False,
36
+ vocab_size: int = 32000,
37
+ use_forget_gate: bool = False,
38
+ use_w_shortconv: bool = True,
39
+ use_low_rank_w: bool = True,
40
+ **kwargs,
41
+ ):
42
+ self.hidden_size = hidden_size
43
+ self.num_hidden_layers = num_hidden_layers
44
+ self.num_heads = num_heads
45
+ self.num_kv_heads = num_kv_heads
46
+ self.hidden_ratio = hidden_ratio
47
+ self.intermediate_size = intermediate_size
48
+ self.hidden_act = hidden_act
49
+
50
+ self.initializer_range = initializer_range
51
+ self.elementwise_affine = elementwise_affine
52
+ self.norm_eps = norm_eps
53
+ self.use_cache = use_cache
54
+
55
+ self.fuse_norm = fuse_norm
56
+ self.fuse_swiglu = fuse_swiglu
57
+ self.fuse_cross_entropy = fuse_cross_entropy
58
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
59
+ self.use_l2warp = use_l2warp
60
+ self.vocab_size = vocab_size
61
+
62
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
63
+ raise ValueError(
64
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
65
+ )
66
+ if fuse_linear_cross_entropy:
67
+ warnings.warn(
68
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
69
+ "at the potential cost of reduced precision. "
70
+ "If you observe issues like loss divergence, consider disabling this setting."
71
+ )
72
+
73
+ self.use_forget_gate = use_forget_gate
74
+ self.use_w_shortconv = use_w_shortconv
75
+ self.use_low_rank_w = use_low_rank_w
76
+
77
+ super().__init__(
78
+ pad_token_id=pad_token_id,
79
+ bos_token_id=bos_token_id,
80
+ eos_token_id=eos_token_id,
81
+ tie_word_embeddings=tie_word_embeddings,
82
+ **kwargs,
83
+ )
models/path_attn/modeling_path_attention.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.path_attn import PaTHAttention
17
+ from fla.models.path_attn.configuration_path_attention import PaTHAttentionConfig
18
+ from fla.models.utils import Cache, FLAGenerationMixin
19
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
20
+ from fla.modules import GatedMLP as PaTHAttentionMLP
21
+ from fla.modules import RMSNorm
22
+ from fla.modules.l2warp import l2_warp
23
+
24
+ if TYPE_CHECKING:
25
+ from transformers.processing_utils import Unpack
26
+
27
+
28
+ try:
29
+ from transformers.modeling_layers import GradientCheckpointingLayer
30
+ except ImportError:
31
+ from fla.models.modeling_layers import GradientCheckpointingLayer
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class PaTHAttentionBlock(GradientCheckpointingLayer):
37
+
38
+ def __init__(self, config: PaTHAttentionConfig, layer_idx: int):
39
+ super().__init__()
40
+
41
+ self.config = config
42
+ self.layer_idx = layer_idx
43
+
44
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
45
+ self.attn = PaTHAttention(
46
+ hidden_size=config.hidden_size,
47
+ num_heads=config.num_heads,
48
+ num_kv_heads=config.num_kv_heads,
49
+ use_forget_gate=config.use_forget_gate,
50
+ use_w_shortconv=config.use_w_shortconv,
51
+ use_low_rank_w=config.use_low_rank_w,
52
+ layer_idx=layer_idx
53
+ )
54
+
55
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
56
+ self.mlp = PaTHAttentionMLP(
57
+ hidden_size=config.hidden_size,
58
+ hidden_ratio=config.hidden_ratio,
59
+ intermediate_size=config.intermediate_size,
60
+ hidden_act=config.hidden_act,
61
+ fuse_swiglu=config.fuse_swiglu
62
+ )
63
+
64
+ def forward(
65
+ self,
66
+ hidden_states: torch.Tensor,
67
+ attention_mask: Optional[torch.Tensor] = None,
68
+ past_key_values: Optional[Tuple[torch.Tensor]] = None,
69
+ output_attentions: Optional[bool] = False,
70
+ use_cache: Optional[bool] = False,
71
+ **kwargs: Unpack[Any]
72
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
73
+
74
+ residual = hidden_states
75
+ hidden_states = self.attn_norm(hidden_states)
76
+ hidden_states, attentions, past_key_values = self.attn(
77
+ hidden_states=hidden_states,
78
+ attention_mask=attention_mask,
79
+ past_key_values=past_key_values,
80
+ use_cache=use_cache,
81
+ output_attentions=output_attentions,
82
+ **kwargs
83
+ )
84
+ if self.config.fuse_norm:
85
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
86
+ else:
87
+ hidden_states = residual + hidden_states
88
+ residual = hidden_states
89
+ hidden_states = self.mlp_norm(hidden_states)
90
+ hidden_states = self.mlp(hidden_states, **kwargs)
91
+ hidden_states = residual + hidden_states
92
+
93
+ outputs = (hidden_states,)
94
+
95
+ if output_attentions:
96
+ outputs += (attentions,)
97
+
98
+ if use_cache:
99
+ outputs += (past_key_values,)
100
+
101
+ return outputs
102
+
103
+
104
+ class PaTHAttentionPreTrainedModel(PreTrainedModel):
105
+
106
+ config_class = PaTHAttentionConfig
107
+ base_model_prefix = 'model'
108
+ supports_gradient_checkpointing = True
109
+ _no_split_modules = ['PaTHAttentionBlock']
110
+ _supports_cache_class = True
111
+
112
+ def __init__(self, *inputs, **kwargs):
113
+ super().__init__(*inputs, **kwargs)
114
+
115
+ def _init_weights(
116
+ self,
117
+ module: nn.Module,
118
+ rescale_prenorm_residual: bool = False,
119
+ num_residuals_per_layer: int = 2,
120
+ ):
121
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
122
+ # Slightly different from the TF version which uses truncated_normal for initialization
123
+ # cf https://github.com/pytorch/pytorch/pull/5617
124
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
125
+ if module.bias is not None:
126
+ nn.init.zeros_(module.bias)
127
+ elif isinstance(module, nn.Embedding):
128
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
129
+ elif hasattr(module, 'reset_parameters'):
130
+ module.reset_parameters()
131
+
132
+ if rescale_prenorm_residual:
133
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
134
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
135
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
136
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
137
+ #
138
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
139
+ p = None
140
+ if hasattr(module, 'o_proj'):
141
+ p = module.o_proj.weight
142
+ elif hasattr(module, 'down_proj'):
143
+ p = module.down_proj.weight
144
+ if p is not None:
145
+ # Special Scaled Initialization --> There are 2 Layer Norms per PaTHAttention Block
146
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
147
+ # We need to reinit p since this code could be called multiple times
148
+ # Having just p *= scale would repeatedly scale it down
149
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
150
+ with torch.no_grad():
151
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
152
+
153
+
154
+ class PaTHAttentionModel(PaTHAttentionPreTrainedModel):
155
+
156
+ def __init__(
157
+ self,
158
+ config: PaTHAttentionConfig
159
+ ) -> PaTHAttentionModel:
160
+ super().__init__(config)
161
+ self.padding_idx = config.pad_token_id
162
+ self.vocab_size = config.vocab_size
163
+
164
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
165
+ self.layers = nn.ModuleList([
166
+ PaTHAttentionBlock(config, layer_idx)
167
+ for layer_idx in range(config.num_hidden_layers)
168
+ ])
169
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
170
+
171
+ self.gradient_checkpointing = False
172
+
173
+ self.post_init()
174
+
175
+ def get_input_embeddings(self):
176
+ return self.embeddings
177
+
178
+ def set_input_embeddings(self, value):
179
+ self.embeddings = value
180
+
181
+ def forward(
182
+ self,
183
+ input_ids: Optional[torch.LongTensor] = None,
184
+ attention_mask: Optional[torch.Tensor] = None,
185
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
186
+ inputs_embeds: Optional[torch.FloatTensor] = None,
187
+ use_cache: Optional[bool] = None,
188
+ output_attentions: Optional[bool] = None,
189
+ output_hidden_states: Optional[bool] = None,
190
+ return_dict: Optional[bool] = None,
191
+ **kwargs: Unpack[Any]
192
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
193
+ if output_attentions:
194
+ warnings.warn(
195
+ "`PaTHAttentionModel` does not support output attention weights now, "
196
+ "so `output_attentions` is set to `False`."
197
+ )
198
+ output_attentions = False
199
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
200
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
201
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
202
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
203
+
204
+ # retrieve input_ids and inputs_embeds
205
+ if input_ids is not None and inputs_embeds is not None:
206
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
207
+ elif input_ids is None and inputs_embeds is None:
208
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
209
+
210
+ if use_cache and not isinstance(past_key_values, Cache):
211
+ past_key_values = Cache.from_legacy_cache(past_key_values)
212
+
213
+ if inputs_embeds is None:
214
+ inputs_embeds = self.embeddings(input_ids)
215
+
216
+ # embed positions
217
+ hidden_states = inputs_embeds
218
+
219
+ all_hidden_states = () if output_hidden_states else None
220
+ all_attns = () if output_attentions else None
221
+ next_cache = None
222
+
223
+ for layer in self.layers:
224
+ if output_hidden_states:
225
+ all_hidden_states += (hidden_states,)
226
+
227
+ layer_outputs = layer(
228
+ hidden_states,
229
+ attention_mask=attention_mask,
230
+ past_key_values=past_key_values,
231
+ output_attentions=output_attentions,
232
+ use_cache=use_cache,
233
+ **kwargs
234
+ )
235
+
236
+ hidden_states = layer_outputs[0]
237
+
238
+ if use_cache:
239
+ next_cache = layer_outputs[2 if output_attentions else 1]
240
+
241
+ if output_attentions:
242
+ all_attns += (layer_outputs[1],)
243
+
244
+ hidden_states = self.norm(hidden_states)
245
+
246
+ # add hidden states from the last decoder layer
247
+ if output_hidden_states:
248
+ all_hidden_states += (hidden_states,)
249
+
250
+ if not return_dict:
251
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attns] if v is not None)
252
+
253
+ return BaseModelOutputWithPast(
254
+ last_hidden_state=hidden_states,
255
+ past_key_values=next_cache,
256
+ hidden_states=all_hidden_states,
257
+ attentions=all_attns
258
+ )
259
+
260
+
261
+ class PaTHAttentionForCausalLM(PaTHAttentionPreTrainedModel, FLAGenerationMixin):
262
+
263
+ _tied_weights_keys = ["lm_head.weight"]
264
+
265
+ def __init__(self, config):
266
+ super().__init__(config)
267
+ self.model = PaTHAttentionModel(config)
268
+ self.vocab_size = config.vocab_size
269
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
270
+ self.criterion = None
271
+
272
+ # Initialize weights and apply final processing
273
+ self.post_init()
274
+
275
+ def get_input_embeddings(self):
276
+ return self.model.embeddings
277
+
278
+ def set_input_embeddings(self, value):
279
+ self.model.embeddings = value
280
+
281
+ def get_output_embeddings(self):
282
+ return self.lm_head
283
+
284
+ def set_output_embeddings(self, new_embeddings):
285
+ self.lm_head = new_embeddings
286
+
287
+ def set_decoder(self, decoder):
288
+ self.model = decoder
289
+
290
+ def get_decoder(self):
291
+ return self.model
292
+
293
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
294
+ def forward(
295
+ self,
296
+ input_ids: torch.LongTensor = None,
297
+ attention_mask: Optional[torch.Tensor] = None,
298
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
299
+ inputs_embeds: Optional[torch.FloatTensor] = None,
300
+ labels: Optional[torch.LongTensor] = None,
301
+ use_cache: Optional[bool] = None,
302
+ output_attentions: Optional[bool] = None,
303
+ output_hidden_states: Optional[bool] = None,
304
+ return_dict: Optional[bool] = None,
305
+ logits_to_keep: Optional[int] = 0,
306
+ **kwargs: Unpack[Any]
307
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
308
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
309
+ output_hidden_states = (
310
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
311
+ )
312
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
313
+
314
+ outputs = self.model(
315
+ input_ids=input_ids,
316
+ attention_mask=attention_mask,
317
+ past_key_values=past_key_values,
318
+ inputs_embeds=inputs_embeds,
319
+ use_cache=use_cache,
320
+ output_attentions=output_attentions,
321
+ output_hidden_states=output_hidden_states,
322
+ return_dict=return_dict,
323
+ **kwargs
324
+ )
325
+
326
+ hidden_states = outputs[0]
327
+
328
+ logits = None if self.config.fuse_linear_cross_entropy else self.lm_head(hidden_states[:, -logits_to_keep:])
329
+
330
+ loss = None
331
+ if labels is not None:
332
+ if getattr(self, 'criterion', None) is None:
333
+ if self.config.fuse_linear_cross_entropy:
334
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
335
+ elif self.config.fuse_cross_entropy:
336
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
337
+ else:
338
+ criterion = nn.CrossEntropyLoss()
339
+ else:
340
+ criterion = self.criterion
341
+ # Enable model parallelism
342
+ labels = labels.to(hidden_states.device)
343
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
344
+ if self.config.fuse_linear_cross_entropy:
345
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
346
+ else:
347
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
348
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
349
+
350
+ if not return_dict:
351
+ output = (logits,) + outputs[1:]
352
+ return (loss,) + output if loss is not None else output
353
+
354
+ return CausalLMOutputWithPast(
355
+ loss=loss,
356
+ logits=logits,
357
+ past_key_values=outputs.past_key_values,
358
+ hidden_states=outputs.hidden_states,
359
+ attentions=outputs.attentions,
360
+ )
models/retnet/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.retnet.configuration_retnet import RetNetConfig
6
+ from fla.models.retnet.modeling_retnet import RetNetForCausalLM, RetNetModel
7
+
8
+ AutoConfig.register(RetNetConfig.model_type, RetNetConfig, exist_ok=True)
9
+ AutoModel.register(RetNetConfig, RetNetModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(RetNetConfig, RetNetForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['RetNetConfig', 'RetNetForCausalLM', 'RetNetModel']
models/retnet/configuration_retnet.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from typing import Dict, Optional
7
+
8
+ from transformers.configuration_utils import PretrainedConfig
9
+
10
+
11
+ class RetNetConfig(PretrainedConfig):
12
+
13
+ model_type = 'retnet'
14
+ keys_to_ignore_at_inference = ['past_key_values']
15
+
16
+ def __init__(
17
+ self,
18
+ attn_mode: str = "chunk",
19
+ hidden_size: int = 2048,
20
+ expand_k: float = 1.0,
21
+ expand_v: float = 2.0,
22
+ hidden_ratio: Optional[int] = 2,
23
+ intermediate_size: Optional[int] = None,
24
+ num_hidden_layers: int = 24,
25
+ num_heads: int = 8,
26
+ num_kv_heads: Optional[int] = None,
27
+ feature_map: Optional[str] = None,
28
+ hidden_act: str = "swish",
29
+ use_short_conv: bool = False,
30
+ conv_size: int = 4,
31
+ use_output_gate: bool = True,
32
+ max_position_embeddings: int = 2048,
33
+ elementwise_affine: Optional[bool] = True,
34
+ norm_eps: float = 1e-6,
35
+ attn: Optional[Dict] = None,
36
+ use_cache: bool = True,
37
+ pad_token_id: Optional[int] = None,
38
+ bos_token_id: int = 1,
39
+ eos_token_id: int = 2,
40
+ tie_word_embeddings: bool = False,
41
+ initializer_range: float = 0.02,
42
+ fuse_norm: bool = True,
43
+ fuse_swiglu: bool = True,
44
+ fuse_cross_entropy: bool = True,
45
+ fuse_linear_cross_entropy: bool = False,
46
+ use_l2warp: bool = False,
47
+ vocab_size: int = 32000,
48
+ **kwargs
49
+ ) -> RetNetConfig:
50
+ self.attn_mode = attn_mode
51
+ self.hidden_size = hidden_size
52
+ self.expand_k = expand_k
53
+ self.expand_v = expand_v
54
+ self.hidden_ratio = hidden_ratio
55
+ self.intermediate_size = intermediate_size
56
+ self.num_hidden_layers = num_hidden_layers
57
+ self.num_heads = num_heads
58
+ self.num_kv_heads = num_kv_heads
59
+ self.feature_map = feature_map
60
+ self.hidden_act = hidden_act
61
+ self.use_short_conv = use_short_conv
62
+ self.conv_size = conv_size
63
+ self.use_output_gate = use_output_gate
64
+ self.hidden_act = hidden_act
65
+ self.max_position_embeddings = max_position_embeddings
66
+ self.elementwise_affine = elementwise_affine
67
+ self.norm_eps = norm_eps
68
+ self.attn = attn
69
+ self.use_cache = use_cache
70
+ self.initializer_range = initializer_range
71
+
72
+ self.fuse_norm = fuse_norm
73
+ self.fuse_swiglu = fuse_swiglu
74
+ self.fuse_cross_entropy = fuse_cross_entropy
75
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
76
+ self.use_l2warp = use_l2warp
77
+ self.vocab_size = vocab_size
78
+
79
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
80
+ raise ValueError(
81
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
82
+ )
83
+ if fuse_linear_cross_entropy:
84
+ warnings.warn(
85
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
86
+ "at the potential cost of reduced precision. "
87
+ "If you observe issues like loss divergence, consider disabling this setting."
88
+ )
89
+
90
+ if attn is not None:
91
+ if not isinstance(attn, Dict):
92
+ raise ValueError("attn must be a dictionary")
93
+ if 'layers' not in attn:
94
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
95
+ if 'num_heads' not in attn:
96
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
97
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
98
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
99
+ attn['window_size'] = attn.get('window_size', None)
100
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
101
+
102
+ super().__init__(
103
+ pad_token_id=pad_token_id,
104
+ bos_token_id=bos_token_id,
105
+ eos_token_id=eos_token_id,
106
+ tie_word_embeddings=tie_word_embeddings,
107
+ **kwargs,
108
+ )
models/retnet/modeling_retnet.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.utils import logging
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from fla.layers.attn import Attention
17
+ from fla.layers.multiscale_retention import MultiScaleRetention
18
+ from fla.models.retnet.configuration_retnet import RetNetConfig
19
+ from fla.models.utils import Cache, FLAGenerationMixin
20
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
21
+ from fla.modules import GatedMLP as RetNetMLP
22
+ from fla.modules import RMSNorm
23
+ from fla.modules.l2warp import l2_warp
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+
29
+ try:
30
+ from transformers.modeling_layers import GradientCheckpointingLayer
31
+ except ImportError:
32
+ from fla.models.modeling_layers import GradientCheckpointingLayer
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class RetNetBlock(GradientCheckpointingLayer):
38
+
39
+ def __init__(self, config: RetNetConfig, layer_idx: int):
40
+ super().__init__()
41
+
42
+ self.config = config
43
+ self.layer_idx = layer_idx
44
+
45
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
46
+ if config.attn is not None and layer_idx in config.attn['layers']:
47
+ self.attn = Attention(
48
+ hidden_size=config.hidden_size,
49
+ num_heads=config.attn['num_heads'],
50
+ num_kv_heads=config.attn['num_kv_heads'],
51
+ qkv_bias=config.attn['qkv_bias'],
52
+ window_size=config.attn['window_size'],
53
+ rope_theta=config.attn['rope_theta'],
54
+ max_position_embeddings=config.max_position_embeddings,
55
+ layer_idx=layer_idx
56
+ )
57
+ else:
58
+ self.attn = MultiScaleRetention(
59
+ mode=config.attn_mode,
60
+ hidden_size=config.hidden_size,
61
+ expand_k=config.expand_k,
62
+ expand_v=config.expand_v,
63
+ num_heads=config.num_heads,
64
+ num_kv_heads=config.num_kv_heads,
65
+ feature_map=config.feature_map,
66
+ use_output_gate=config.use_output_gate,
67
+ gate_fn=config.hidden_act,
68
+ elementwise_affine=config.elementwise_affine,
69
+ norm_eps=config.norm_eps,
70
+ fuse_norm=config.fuse_norm,
71
+ layer_idx=layer_idx
72
+ )
73
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
74
+ self.mlp = RetNetMLP(
75
+ hidden_size=config.hidden_size,
76
+ hidden_ratio=config.hidden_ratio,
77
+ intermediate_size=config.intermediate_size,
78
+ hidden_act=config.hidden_act,
79
+ fuse_swiglu=config.fuse_swiglu
80
+ )
81
+
82
+ def forward(
83
+ self,
84
+ hidden_states: torch.Tensor,
85
+ attention_mask: Optional[torch.Tensor] = None,
86
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
87
+ use_cache: Optional[bool] = False,
88
+ output_attentions: Optional[bool] = False,
89
+ **kwargs: Unpack[Dict]
90
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
91
+
92
+ residual = hidden_states
93
+
94
+ hidden_states = self.attn_norm(hidden_states)
95
+ hidden_states, attentions, past_key_values = self.attn(
96
+ hidden_states=hidden_states,
97
+ attention_mask=attention_mask,
98
+ past_key_values=past_key_values,
99
+ use_cache=use_cache,
100
+ output_attentions=output_attentions,
101
+ **kwargs
102
+ )
103
+ if self.config.fuse_norm:
104
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
105
+ else:
106
+ hidden_states = residual + hidden_states
107
+ residual = hidden_states
108
+ hidden_states = self.mlp_norm(hidden_states)
109
+ hidden_states = self.mlp(hidden_states, **kwargs)
110
+ hidden_states = residual + hidden_states
111
+
112
+ outputs = (hidden_states, attentions, past_key_values)
113
+
114
+ return outputs
115
+
116
+
117
+ class RetNetPreTrainedModel(PreTrainedModel):
118
+
119
+ config_class = RetNetConfig
120
+ base_model_prefix = 'model'
121
+ supports_gradient_checkpointing = True
122
+ _no_split_modules = ['RetNetBlock']
123
+ _supports_cache_class = True
124
+
125
+ def __init__(self, *inputs, **kwargs):
126
+ super().__init__(*inputs, **kwargs)
127
+
128
+ def _init_weights(
129
+ self,
130
+ module: nn.Module,
131
+ prenorm_residual_strategy: Optional[str] = None,
132
+ num_residuals_per_layer: int = 2,
133
+ ):
134
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
135
+ # Slightly different from the TF version which uses truncated_normal for initialization
136
+ # cf https://github.com/pytorch/pytorch/pull/5617
137
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
138
+ if module.bias is not None:
139
+ nn.init.zeros_(module.bias)
140
+ elif isinstance(module, nn.Embedding):
141
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
142
+ elif hasattr(module, 'reset_parameters'):
143
+ module.reset_parameters()
144
+
145
+ if prenorm_residual_strategy is not None:
146
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
147
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
148
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
149
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
150
+ #
151
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
152
+ p = None
153
+ if hasattr(module, 'o_proj'):
154
+ p = module.o_proj.weight
155
+ elif hasattr(module, 'down_proj'):
156
+ p = module.down_proj.weight
157
+ if p is not None:
158
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
159
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
160
+ # We need to reinit p since this code could be called multiple times
161
+ # Having just p *= scale would repeatedly scale it down
162
+ if prenorm_residual_strategy == 'rescale':
163
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
164
+ with torch.no_grad():
165
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
166
+ elif prenorm_residual_strategy == 'zero':
167
+ nn.init.zeros_(p)
168
+ else:
169
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
170
+
171
+
172
+ class RetNetModel(RetNetPreTrainedModel):
173
+
174
+ def __init__(self, config: RetNetConfig):
175
+ super().__init__(config)
176
+ self.padding_idx = config.pad_token_id
177
+ self.vocab_size = config.vocab_size
178
+
179
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
180
+ self.layers = nn.ModuleList(
181
+ [RetNetBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
182
+ )
183
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
184
+
185
+ self.gradient_checkpointing = False
186
+
187
+ self.post_init()
188
+
189
+ def get_input_embeddings(self):
190
+ return self.embeddings
191
+
192
+ def set_input_embeddings(self, value):
193
+ self.embeddings = value
194
+
195
+ def forward(
196
+ self,
197
+ input_ids: Optional[torch.LongTensor] = None,
198
+ attention_mask: Optional[torch.Tensor] = None, # noqa
199
+ inputs_embeds: Optional[torch.FloatTensor] = None,
200
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
201
+ use_cache: Optional[bool] = None,
202
+ output_attentions: Optional[bool] = None,
203
+ output_hidden_states: Optional[bool] = None,
204
+ return_dict: Optional[bool] = None,
205
+ **kwargs: Unpack[Dict]
206
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
207
+ if output_attentions:
208
+ warnings.warn(
209
+ "`RetNetModel` does not support output attention weights now, so `output_attentions` is set to `False`."
210
+ )
211
+ output_attentions = False
212
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
213
+ output_hidden_states = (
214
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
215
+ )
216
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
217
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
218
+
219
+ # retrieve input_ids and inputs_embeds
220
+ if input_ids is not None and inputs_embeds is not None:
221
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
222
+ if input_ids is None and inputs_embeds is None:
223
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
224
+
225
+ if inputs_embeds is None:
226
+ inputs_embeds = self.embeddings(input_ids)
227
+ hidden_states = inputs_embeds
228
+
229
+ if use_cache and not isinstance(past_key_values, Cache):
230
+ past_key_values = Cache.from_legacy_cache(past_key_values)
231
+
232
+ all_hidden_states = () if output_hidden_states else None
233
+ all_attns = () if output_attentions else None
234
+ for layer in self.layers:
235
+ if output_hidden_states:
236
+ all_hidden_states += (hidden_states,)
237
+
238
+ hidden_states, attentions, past_key_values = layer(
239
+ hidden_states,
240
+ attention_mask=attention_mask,
241
+ past_key_values=past_key_values,
242
+ use_cache=use_cache,
243
+ output_attentions=output_attentions,
244
+ **kwargs
245
+ )
246
+
247
+ if output_attentions:
248
+ all_attns += (attentions,)
249
+
250
+ hidden_states = self.norm(hidden_states)
251
+
252
+ # add hidden states from the last decoder layer
253
+ if output_hidden_states:
254
+ all_hidden_states += (hidden_states,)
255
+
256
+ if not return_dict:
257
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
258
+ return BaseModelOutputWithPast(
259
+ last_hidden_state=hidden_states,
260
+ past_key_values=past_key_values,
261
+ hidden_states=all_hidden_states,
262
+ attentions=all_attns
263
+ )
264
+
265
+
266
+ class RetNetForCausalLM(RetNetPreTrainedModel, FLAGenerationMixin):
267
+
268
+ _tied_weights_keys = ["lm_head.weight"]
269
+
270
+ def __init__(self, config):
271
+ super().__init__(config)
272
+ self.model = RetNetModel(config)
273
+ self.vocab_size = config.vocab_size
274
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
275
+ self.criterion = None
276
+
277
+ # Initialize weights and apply final processing
278
+ self.post_init()
279
+
280
+ def get_input_embeddings(self):
281
+ return self.model.embeddings
282
+
283
+ def set_input_embeddings(self, value):
284
+ self.model.embeddings = value
285
+
286
+ def get_output_embeddings(self):
287
+ return self.lm_head
288
+
289
+ def set_output_embeddings(self, new_embeddings):
290
+ self.lm_head = new_embeddings
291
+
292
+ def set_decoder(self, decoder):
293
+ self.model = decoder
294
+
295
+ def get_decoder(self):
296
+ return self.model
297
+
298
+ def generate(self, *args, **kwargs):
299
+ try:
300
+ return super().generate(*args, **kwargs)
301
+ except AttributeError as exception:
302
+ # Expected exception: "AttributeError: '(object name)' object has no attribute 'past_key_values'"
303
+ if 'past_key_values' in str(exception):
304
+ raise AttributeError(
305
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
306
+ f"which is not supported for {self.__class__.__name__}. "
307
+ f"Try another generation strategy instead. "
308
+ f"For the available generation strategies, check this doc: "
309
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
310
+ )
311
+ else:
312
+ raise exception
313
+
314
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
315
+ def forward(
316
+ self,
317
+ input_ids: torch.LongTensor = None,
318
+ attention_mask: Optional[torch.Tensor] = None,
319
+ inputs_embeds: Optional[torch.FloatTensor] = None,
320
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
321
+ labels: Optional[torch.LongTensor] = None,
322
+ use_cache: Optional[bool] = None,
323
+ output_attentions: Optional[bool] = None,
324
+ output_hidden_states: Optional[bool] = None,
325
+ return_dict: Optional[bool] = None,
326
+ logits_to_keep: Optional[int] = 0,
327
+ **kwargs: Unpack[Dict]
328
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
329
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
330
+ output_hidden_states = (
331
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
332
+ )
333
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
334
+
335
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
336
+ outputs = self.model(
337
+ input_ids=input_ids,
338
+ attention_mask=attention_mask,
339
+ inputs_embeds=inputs_embeds,
340
+ past_key_values=past_key_values,
341
+ use_cache=use_cache,
342
+ output_attentions=output_attentions,
343
+ output_hidden_states=output_hidden_states,
344
+ return_dict=return_dict,
345
+ **kwargs
346
+ )
347
+
348
+ hidden_states = outputs[0]
349
+
350
+ loss, logits = None, None
351
+ if not self.config.fuse_linear_cross_entropy or labels is None:
352
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
353
+ if labels is not None:
354
+ if getattr(self, 'criterion', None) is None:
355
+ if self.config.fuse_linear_cross_entropy:
356
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
357
+ elif self.config.fuse_cross_entropy:
358
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
359
+ else:
360
+ criterion = nn.CrossEntropyLoss()
361
+ else:
362
+ criterion = self.criterion
363
+ labels = labels.to(hidden_states.device)
364
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
365
+ if self.config.fuse_linear_cross_entropy:
366
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
367
+ else:
368
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
369
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
370
+
371
+ if not return_dict:
372
+ output = (logits,) + outputs[1:]
373
+ return (loss,) + output if loss is not None else output
374
+
375
+ return CausalLMOutputWithPast(
376
+ loss=loss,
377
+ logits=logits,
378
+ past_key_values=outputs.past_key_values,
379
+ hidden_states=outputs.hidden_states,
380
+ attentions=outputs.attentions,
381
+ )
models/rodimus/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.rodimus.configuration_rodimus import RodimusConfig
6
+ from fla.models.rodimus.modeling_rodimus import RodimusForCausalLM, RodimusModel
7
+
8
+ AutoConfig.register(RodimusConfig.model_type, RodimusConfig, exist_ok=True)
9
+ AutoModel.register(RodimusConfig, RodimusModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(RodimusConfig, RodimusForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['RodimusConfig', 'RodimusForCausalLM', 'RodimusModel']
models/rodimus/configuration_rodimus.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional, Union
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class RodimusConfig(PretrainedConfig):
10
+
11
+ model_type = 'rodimus'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ block_type: str = 'rodimus_plus',
17
+ hidden_size: int = 2048,
18
+ num_hidden_layers: int = 24,
19
+ attn_mode: str = "chunk",
20
+ residual_in_fp32: bool = True,
21
+ block_residual_in_fp32: bool = False,
22
+ expand_ratio: Optional[int] = 64,
23
+ input_gate_low_rank: Optional[Union[float, str]] = 'auto',
24
+ use_short_conv: bool = True,
25
+ conv_size: int = 4,
26
+ hidden_ratio: Optional[float] = 4/3,
27
+ intermediate_size: Optional[int] = None,
28
+ hidden_act: str = "swish",
29
+ max_position_embeddings: int = 2048,
30
+ norm_eps: float = 1e-5,
31
+ k_norm_eps: Optional[float] = None,
32
+ attn: Optional[Dict] = None,
33
+ ska_attn: Optional[Dict] = None,
34
+ use_cache: bool = True,
35
+ pad_token_id: Optional[int] = None,
36
+ bos_token_id: int = 126080,
37
+ eos_token_id: int = 126081,
38
+ tie_word_embeddings: bool = True,
39
+ initializer_range: float = 0.02,
40
+ fuse_norm: bool = True,
41
+ fuse_swiglu: bool = True,
42
+ fuse_cross_entropy: bool = True,
43
+ fuse_linear_cross_entropy: bool = False,
44
+ use_l2warp: bool = False,
45
+ vocab_size: int = 126464,
46
+ **kwargs
47
+ ):
48
+ self.block_type = block_type
49
+ self.hidden_size = hidden_size
50
+ self.num_hidden_layers = num_hidden_layers
51
+ self.attn_mode = attn_mode
52
+ self.residual_in_fp32 = residual_in_fp32
53
+ self.block_residual_in_fp32 = block_residual_in_fp32
54
+ self.expand_ratio = expand_ratio
55
+ self.input_gate_low_rank = input_gate_low_rank
56
+
57
+ self.use_short_conv = use_short_conv
58
+ self.conv_size = conv_size
59
+ self.max_position_embeddings = max_position_embeddings
60
+ self.hidden_ratio = hidden_ratio
61
+ self.intermediate_size = intermediate_size
62
+ self.hidden_act = hidden_act
63
+ self.norm_eps = norm_eps
64
+ self.k_norm_eps = k_norm_eps
65
+
66
+ self.attn = attn
67
+ self.ska_attn = ska_attn
68
+ self.use_cache = use_cache
69
+ self.initializer_range = initializer_range
70
+
71
+ self.fuse_norm = fuse_norm
72
+ self.fuse_swiglu = fuse_swiglu
73
+ self.fuse_cross_entropy = fuse_cross_entropy
74
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
75
+ self.use_l2warp = use_l2warp
76
+ self.vocab_size = vocab_size
77
+
78
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
79
+ raise ValueError(
80
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
81
+ )
82
+ if fuse_linear_cross_entropy:
83
+ warnings.warn(
84
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
85
+ "at the potential cost of reduced precision. "
86
+ "If you observe issues like loss divergence, consider disabling this setting."
87
+ )
88
+
89
+ if attn is not None:
90
+ if not isinstance(attn, Dict):
91
+ raise ValueError("attn must be a dictionary")
92
+ if 'layers' not in attn:
93
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
94
+ if 'num_heads' not in attn:
95
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
96
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
97
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
98
+ attn['qk_norm'] = attn.get('qk_norm', False)
99
+ attn['window_size'] = attn.get('window_size', None)
100
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
101
+
102
+ if ska_attn is not None:
103
+ if not isinstance(ska_attn, Dict):
104
+ raise ValueError("attn must be a dictionary")
105
+ if 'num_heads' not in ska_attn:
106
+ raise ValueError("Number of heads must be provided to initialize shared-key attention layers")
107
+ ska_attn['qkv_bias'] = ska_attn.get('qkv_bias', False)
108
+ ska_attn['qk_norm'] = ska_attn.get('qk_norm', False)
109
+ ska_attn['window_size'] = ska_attn.get('window_size', 1024)
110
+ ska_attn['rope_theta'] = ska_attn.get('rope_theta', 10000.)
111
+
112
+ super().__init__(
113
+ pad_token_id=pad_token_id,
114
+ bos_token_id=bos_token_id,
115
+ eos_token_id=eos_token_id,
116
+ tie_word_embeddings=tie_word_embeddings,
117
+ **kwargs,
118
+ )
models/rodimus/modeling_rodimus.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from functools import partial
8
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
+ from transformers.modeling_utils import PreTrainedModel
14
+ from transformers.utils import logging
15
+ from transformers.utils.deprecation import deprecate_kwarg
16
+
17
+ from fla.layers.attn import Attention
18
+ from fla.layers.rodimus import RodimusAttention, SlidingWindowSharedKeyAttention, align_multiple
19
+ from fla.models.rodimus.configuration_rodimus import RodimusConfig
20
+ from fla.models.utils import Cache, FLAGenerationMixin
21
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
22
+ from fla.modules import GatedMLP as RodimusMLP
23
+ from fla.modules import RMSNorm
24
+ from fla.modules.l2warp import l2_warp
25
+
26
+ try:
27
+ from torch.distributed.tensor import DTensor
28
+ except (ImportError, AttributeError):
29
+ DTensor = None
30
+
31
+ if TYPE_CHECKING:
32
+ from transformers.processing_utils import Unpack
33
+
34
+
35
+ try:
36
+ from transformers.modeling_layers import GradientCheckpointingLayer
37
+ except ImportError:
38
+ from fla.models.modeling_layers import GradientCheckpointingLayer
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ class RodimusBlock(GradientCheckpointingLayer):
44
+
45
+ def __init__(self, config: RodimusConfig, layer_idx: int):
46
+ super().__init__()
47
+
48
+ self.config = config
49
+ self.layer_idx = layer_idx
50
+ self.block_type = config.block_type
51
+ self.block_residual_in_fp32 = config.residual_in_fp32
52
+ self.residual_in_fp32 = config.residual_in_fp32
53
+ self.fuse_norm = config.fuse_norm
54
+
55
+ self._is_ori_attn = False
56
+
57
+ if config.intermediate_size is None:
58
+ intermediate_size = align_multiple(int(config.hidden_ratio * config.hidden_size), 8)
59
+ else:
60
+ intermediate_size = config.intermediate_size
61
+
62
+ mlp_cls = partial(
63
+ RodimusMLP,
64
+ hidden_size=config.hidden_size,
65
+ hidden_ratio=None,
66
+ intermediate_size=intermediate_size,
67
+ hidden_act=config.hidden_act,
68
+ fuse_swiglu=config.fuse_swiglu
69
+ )
70
+ norm_cls = partial(
71
+ RMSNorm if self.fuse_norm else nn.RMSNorm,
72
+ config.hidden_size,
73
+ eps=config.norm_eps,
74
+ )
75
+
76
+ if config.attn is not None and layer_idx in config.attn['layers']:
77
+ self._is_ori_attn = True
78
+ self.attn_norm = norm_cls()
79
+ self.attn = Attention(
80
+ hidden_size=config.hidden_size,
81
+ num_heads=config.attn['num_heads'],
82
+ num_kv_heads=config.attn['num_kv_heads'],
83
+ qkv_bias=config.attn['qkv_bias'],
84
+ window_size=config.attn['window_size'],
85
+ rope_theta=config.attn['rope_theta'],
86
+ max_position_embeddings=config.max_position_embeddings,
87
+ layer_idx=layer_idx
88
+ )
89
+
90
+ self.mlp_norm = norm_cls()
91
+ self.mlp = mlp_cls()
92
+ else:
93
+ self.mixer_norm = norm_cls()
94
+ self.mixer = RodimusAttention(
95
+ block_type=config.block_type,
96
+ mode=config.attn_mode,
97
+ hidden_size=config.hidden_size,
98
+ input_gate_low_rank=config.input_gate_low_rank,
99
+ expand_ratio=config.expand_ratio,
100
+ use_short_conv=config.use_short_conv,
101
+ conv_size=config.conv_size,
102
+ norm_eps=config.norm_eps,
103
+ k_norm_eps=config.k_norm_eps,
104
+ residual_in_fp32=config.residual_in_fp32,
105
+ layer_idx=layer_idx
106
+ )
107
+
108
+ if self.block_type == "rodimus_plus":
109
+ self.ska_attn_norm = norm_cls()
110
+ self.ska_attn = SlidingWindowSharedKeyAttention(
111
+ hidden_size=config.hidden_size,
112
+ num_heads=config.ska_attn['num_heads'],
113
+ qkv_bias=config.ska_attn['qkv_bias'],
114
+ qk_norm=config.ska_attn['qk_norm'],
115
+ window_size=config.ska_attn['window_size'],
116
+ rope_theta=config.ska_attn['rope_theta'],
117
+ max_position_embeddings=config.max_position_embeddings,
118
+ layer_idx=layer_idx
119
+ )
120
+
121
+ self.mlp_norm = norm_cls()
122
+ self.mlp = mlp_cls()
123
+
124
+ def forward(
125
+ self,
126
+ hidden_states: torch.Tensor,
127
+ attention_mask: Optional[torch.Tensor] = None,
128
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
129
+ use_cache: Optional[bool] = False,
130
+ output_attentions: Optional[bool] = False,
131
+ residual: Optional[torch.Tensor] = None,
132
+ **kwargs: Unpack[Dict]
133
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
134
+
135
+ if self.block_residual_in_fp32 and self.layer_idx > 0:
136
+ assert residual is not None, 'Residual must be passed in when setting `block_residual_in_fp32=True`'
137
+
138
+ if self._is_ori_attn:
139
+ if self.block_residual_in_fp32:
140
+ hidden_states, residual = self.attn_norm(
141
+ hidden_states,
142
+ residual=residual,
143
+ prenorm=True,
144
+ residual_in_fp32=self.residual_in_fp32
145
+ )
146
+ else:
147
+ residual = hidden_states.float() if self.residual_in_fp32 else hidden_states
148
+ hidden_states = self.attn_norm(hidden_states)
149
+
150
+ hidden_states, attentions, past_key_values = self.attn(
151
+ hidden_states=hidden_states,
152
+ attention_mask=attention_mask,
153
+ past_key_values=past_key_values,
154
+ use_cache=use_cache,
155
+ output_attentions=output_attentions,
156
+ **kwargs
157
+ )
158
+ if self.fuse_norm:
159
+ hidden_states, residual = self.mlp_norm(
160
+ hidden_states,
161
+ residual,
162
+ prenorm=True,
163
+ residual_in_fp32=self.residual_in_fp32
164
+ )
165
+ else:
166
+ hidden_states = residual + hidden_states
167
+ residual = hidden_states.float() if self.residual_in_fp32 else hidden_states
168
+ hidden_states = self.mlp_norm(hidden_states.to(self.mlp_norm.weight.dtype))
169
+
170
+ hidden_states = self.mlp(hidden_states, **kwargs)
171
+ else:
172
+ if self.block_residual_in_fp32:
173
+ hidden_states, residual = self.mixer_norm(
174
+ hidden_states,
175
+ residual=residual,
176
+ prenorm=True,
177
+ residual_in_fp32=self.residual_in_fp32
178
+ )
179
+ else:
180
+ residual = hidden_states.float() if self.residual_in_fp32 else hidden_states
181
+ hidden_states = self.mixer_norm(hidden_states)
182
+
183
+ hidden_states, attentions, past_key_values = self.mixer(
184
+ hidden_states=hidden_states,
185
+ attention_mask=attention_mask,
186
+ past_key_values=past_key_values,
187
+ use_cache=use_cache,
188
+ output_attentions=output_attentions,
189
+ **kwargs
190
+ )
191
+
192
+ if self.block_type == "rodimus_plus":
193
+ past_key_values, rodimus_caches = past_key_values
194
+
195
+ if self.fuse_norm:
196
+ hidden_states, residual = self.ska_attn_norm(
197
+ hidden_states,
198
+ residual,
199
+ prenorm=True,
200
+ residual_in_fp32=self.residual_in_fp32
201
+ )
202
+ else:
203
+ hidden_states = residual + hidden_states
204
+ residual = hidden_states.float() if self.residual_in_fp32 else hidden_states
205
+ hidden_states = self.ska_attn_norm(hidden_states.to(dtype=self.ska_attn_norm.weight.dtype))
206
+
207
+ hidden_states, attentions, past_key_values = self.ska_attn(
208
+ hidden_states=hidden_states,
209
+ attention_mask=attention_mask,
210
+ past_key_values=past_key_values,
211
+ use_cache=use_cache,
212
+ output_attentions=output_attentions,
213
+ rodimus_caches=rodimus_caches,
214
+ **kwargs
215
+ )
216
+
217
+ if self.fuse_norm:
218
+ hidden_states = self.mlp_norm(
219
+ hidden_states,
220
+ residual=residual,
221
+ prenorm=False,
222
+ residual_in_fp32=self.residual_in_fp32
223
+ )
224
+ else:
225
+ hidden_states = residual + hidden_states
226
+ hidden_states = self.mlp_norm(hidden_states.to(dtype=self.mlp_norm.weight.dtype))
227
+
228
+ hidden_states = self.mlp(hidden_states, **kwargs)
229
+
230
+ if self.block_residual_in_fp32:
231
+ hidden_states = (hidden_states, residual)
232
+ else:
233
+ hidden_states = (residual + hidden_states).to(dtype=hidden_states.dtype)
234
+
235
+ outputs = (hidden_states, attentions, past_key_values)
236
+ return outputs
237
+
238
+
239
+ class RodimusPreTrainedModel(PreTrainedModel):
240
+
241
+ config_class = RodimusConfig
242
+ base_model_prefix = 'model'
243
+ supports_gradient_checkpointing = True
244
+ _no_split_modules = ['RodimusBlock']
245
+ _supports_cache_class = True
246
+
247
+ def __init__(self, *inputs, **kwargs):
248
+ super().__init__(*inputs, **kwargs)
249
+ if self.config.block_type == "rodimus":
250
+ self.num_residuals_per_layer = 1
251
+ elif self.config.block_type == "rodimus_plus":
252
+ self.num_residuals_per_layer = 3
253
+ else:
254
+ raise NotImplementedError()
255
+
256
+ def _init_weights(
257
+ self,
258
+ module: nn.Module,
259
+ prenorm_residual_strategy: Optional[str] = None,
260
+ ):
261
+ num_residuals_per_layer = self.num_residuals_per_layer
262
+
263
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
264
+ # Slightly different from the TF version which uses truncated_normal for initialization
265
+ # cf https://github.com/pytorch/pytorch/pull/5617
266
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
267
+ if module.bias is not None:
268
+ nn.init.zeros_(module.bias)
269
+ elif isinstance(module, nn.Embedding):
270
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
271
+ elif hasattr(module, 'reset_parameters'):
272
+ module.reset_parameters()
273
+
274
+ sigmoid_bias_max = 0.999
275
+ sigmoid_bias_min = 0.9
276
+ max_ = 1 - sigmoid_bias_min
277
+ min_ = 1 - sigmoid_bias_max
278
+ g_gate_bias = torch.exp(
279
+ torch.rand(self.config.expand_ratio) * (math.log(max_) - math.log(min_))
280
+ + math.log(min_)
281
+ ).clamp(min=1e-4)
282
+ g_gate_bias = g_gate_bias + torch.log(-torch.expm1(-g_gate_bias))
283
+ tau_gate_bias = torch.logit(torch.empty((self.config.expand_ratio, )).uniform_(1/16, 0.9))
284
+
285
+ if hasattr(module, 'i_gate_proj'):
286
+ nn.init.xavier_uniform_(module.i_gate_proj[0].weight, gain=2 ** -2.5)
287
+ nn.init.xavier_uniform_(module.i_gate_proj[1].weight, gain=2 ** -2.5)
288
+ nn.init.zeros_(module.i_gate_proj[1].bias)
289
+ if hasattr(module, 'g_gate_proj'):
290
+ nn.init.xavier_uniform_(module.g_gate_proj.weight, gain=2 ** -2.5)
291
+ with torch.no_grad():
292
+ if not isinstance(module.g_gate_proj.bias, DTensor):
293
+ module.g_gate_proj.bias.copy_(g_gate_bias)
294
+ else:
295
+ logger.warning_once("`g_gate_proj.bias` is a DTensor, skipping initialization")
296
+
297
+ if hasattr(module, 'tau_gate_proj'):
298
+ nn.init.xavier_uniform_(module.tau_gate_proj.weight, gain=2 ** -2.5)
299
+ with torch.no_grad():
300
+ if not isinstance(module.tau_gate_proj.bias, DTensor):
301
+ module.tau_gate_proj.bias.copy_(tau_gate_bias)
302
+ else:
303
+ logger.warning_once("`tau_gate_proj.bias` is a DTensor, skipping initialization")
304
+
305
+ if prenorm_residual_strategy is not None:
306
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
307
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
308
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
309
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
310
+ #
311
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
312
+ p = None
313
+ if hasattr(module, 'o_proj'):
314
+ p = module.o_proj.weight
315
+ elif hasattr(module, 'down_proj'):
316
+ p = module.down_proj.weight
317
+ if p is not None:
318
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
319
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
320
+ # We need to reinit p since this code could be called multiple times
321
+ # Having just p *= scale would repeatedly scale it down
322
+ if prenorm_residual_strategy == 'rescale':
323
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
324
+ with torch.no_grad():
325
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
326
+ elif prenorm_residual_strategy == 'zero':
327
+ nn.init.zeros_(p)
328
+ else:
329
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
330
+
331
+
332
+ class RodimusModel(RodimusPreTrainedModel):
333
+
334
+ def __init__(self, config: RodimusConfig):
335
+ super().__init__(config)
336
+ self.padding_idx = config.pad_token_id
337
+ self.vocab_size = config.vocab_size
338
+ self.block_residual_in_fp32 = config.block_residual_in_fp32
339
+
340
+ if config.block_residual_in_fp32:
341
+ if not config.residual_in_fp32:
342
+ warning_message = (
343
+ "`residual_in_fp32=False` is incompatible with `block_residual_in_fp32=True`. "
344
+ "Setting `residual_in_fp32=True`..."
345
+ )
346
+ logger.warning_once(warning_message)
347
+ config.residual_in_fp32 = True
348
+ if not config.fuse_norm:
349
+ logger.warning_once(
350
+ '`fuse_norm=False` is incompatible with `block_residual_in_fp32=True` Setting `fuse_norm=True`...')
351
+ config.fuse_norm = True
352
+
353
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
354
+ self.layers = nn.ModuleList([RodimusBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
355
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
356
+
357
+ self.gradient_checkpointing = False
358
+
359
+ self.post_init()
360
+
361
+ def get_input_embeddings(self):
362
+ return self.embeddings
363
+
364
+ def set_input_embeddings(self, value):
365
+ self.embeddings = value
366
+
367
+ def forward(
368
+ self,
369
+ input_ids: Optional[torch.LongTensor] = None,
370
+ attention_mask: Optional[torch.Tensor] = None, # noqa
371
+ inputs_embeds: Optional[torch.FloatTensor] = None,
372
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
373
+ use_cache: Optional[bool] = None,
374
+ output_attentions: Optional[bool] = None,
375
+ output_hidden_states: Optional[bool] = None,
376
+ return_dict: Optional[bool] = None,
377
+ **kwargs: Unpack[Dict]
378
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
379
+
380
+ if output_attentions:
381
+ warnings.warn("`RodimusModel` does not `output_attentions` now, setting it to `False`.")
382
+ output_attentions = False
383
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
384
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
385
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
386
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
387
+
388
+ # retrieve input_ids and inputs_embeds
389
+ if input_ids is not None and inputs_embeds is not None:
390
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
391
+ if input_ids is None and inputs_embeds is None:
392
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
393
+
394
+ if inputs_embeds is None:
395
+ inputs_embeds = self.embeddings(input_ids)
396
+ hidden_states = inputs_embeds
397
+
398
+ if use_cache and not isinstance(past_key_values, Cache):
399
+ past_key_values = Cache.from_legacy_cache(past_key_values)
400
+
401
+ all_hidden_states = () if output_hidden_states else None
402
+ all_attns = () if output_attentions else None
403
+ residual = None
404
+ for layer in self.layers:
405
+ if output_hidden_states:
406
+ all_hidden_states += (hidden_states,)
407
+
408
+ hidden_states, attentions, past_key_values = layer(
409
+ hidden_states,
410
+ attention_mask=attention_mask,
411
+ past_key_values=past_key_values,
412
+ use_cache=use_cache,
413
+ output_attentions=output_attentions,
414
+ residual=residual,
415
+ **kwargs
416
+ )
417
+
418
+ if self.block_residual_in_fp32:
419
+ hidden_states, residual = hidden_states
420
+ else:
421
+ residual = None
422
+
423
+ if output_attentions:
424
+ all_attns += (attentions,)
425
+
426
+ if self.block_residual_in_fp32:
427
+ hidden_states = self.norm(
428
+ hidden_states,
429
+ residual=residual,
430
+ prenorm=False,
431
+ residual_in_fp32=True,
432
+ )
433
+ else:
434
+ hidden_states = self.norm(hidden_states)
435
+
436
+ # add hidden states from the last decoder layer
437
+ if output_hidden_states:
438
+ all_hidden_states += (hidden_states,)
439
+
440
+ if not return_dict:
441
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
442
+ return BaseModelOutputWithPast(
443
+ last_hidden_state=hidden_states,
444
+ past_key_values=past_key_values,
445
+ hidden_states=all_hidden_states,
446
+ attentions=all_attns
447
+ )
448
+
449
+
450
+ class RodimusForCausalLM(RodimusPreTrainedModel, FLAGenerationMixin):
451
+
452
+ _tied_weights_keys = ["lm_head.weight"]
453
+
454
+ def __init__(self, config):
455
+ super().__init__(config)
456
+ self.model = RodimusModel(config)
457
+ self.vocab_size = config.vocab_size
458
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
459
+ self.criterion = None
460
+
461
+ # Initialize weights and apply final processing
462
+ self.post_init()
463
+
464
+ def get_input_embeddings(self):
465
+ return self.model.embeddings
466
+
467
+ def set_input_embeddings(self, value):
468
+ self.model.embeddings = value
469
+
470
+ def get_output_embeddings(self):
471
+ return self.lm_head
472
+
473
+ def set_output_embeddings(self, new_embeddings):
474
+ self.lm_head = new_embeddings
475
+
476
+ def set_decoder(self, decoder):
477
+ self.model = decoder
478
+
479
+ def get_decoder(self):
480
+ return self.model
481
+
482
+ def generate(self, *args, **kwargs):
483
+ try:
484
+ return super().generate(*args, **kwargs)
485
+ except AttributeError as exception:
486
+ if 'past_key_values' in str(exception):
487
+ raise AttributeError(
488
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
489
+ f"which is not supported for {self.__class__.__name__}. "
490
+ f"Try another generation strategy instead. "
491
+ f"For the available generation strategies, check this doc: "
492
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
493
+ )
494
+ else:
495
+ raise exception
496
+
497
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
498
+ def forward(
499
+ self,
500
+ input_ids: torch.LongTensor = None,
501
+ attention_mask: Optional[torch.Tensor] = None,
502
+ inputs_embeds: Optional[torch.Tensor] = None,
503
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
504
+ labels: Optional[torch.LongTensor] = None,
505
+ use_cache: Optional[bool] = None,
506
+ output_attentions: Optional[bool] = None,
507
+ output_hidden_states: Optional[bool] = None,
508
+ return_dict: Optional[bool] = None,
509
+ logits_to_keep: Optional[int] = 0,
510
+ **kwargs: Unpack[Dict]
511
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
512
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
513
+ output_hidden_states = (
514
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
515
+ )
516
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
517
+
518
+ outputs = self.model(
519
+ input_ids=input_ids,
520
+ attention_mask=attention_mask,
521
+ inputs_embeds=inputs_embeds,
522
+ past_key_values=past_key_values,
523
+ use_cache=use_cache,
524
+ output_attentions=output_attentions,
525
+ output_hidden_states=output_hidden_states,
526
+ return_dict=return_dict,
527
+ **kwargs
528
+ )
529
+
530
+ hidden_states = outputs[0]
531
+
532
+ loss, logits = None, None
533
+ if not self.config.fuse_linear_cross_entropy or labels is None:
534
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
535
+ if labels is not None:
536
+ if getattr(self, 'criterion', None) is None:
537
+ if self.config.fuse_linear_cross_entropy:
538
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
539
+ elif self.config.fuse_cross_entropy:
540
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
541
+ else:
542
+ criterion = nn.CrossEntropyLoss()
543
+ else:
544
+ criterion = self.criterion
545
+ labels = labels.to(hidden_states.device)
546
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
547
+ if self.config.fuse_linear_cross_entropy:
548
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
549
+ else:
550
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
551
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
552
+
553
+ if not return_dict:
554
+ output = (logits,) + outputs[1:]
555
+ return (loss,) + output if loss is not None else output
556
+
557
+ return CausalLMOutputWithPast(
558
+ loss=loss,
559
+ logits=logits,
560
+ past_key_values=outputs.past_key_values,
561
+ hidden_states=outputs.hidden_states,
562
+ attentions=outputs.attentions,
563
+ )
models/rwkv6/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.rwkv6.configuration_rwkv6 import RWKV6Config
6
+ from fla.models.rwkv6.modeling_rwkv6 import RWKV6ForCausalLM, RWKV6Model
7
+
8
+ AutoConfig.register(RWKV6Config.model_type, RWKV6Config, exist_ok=True)
9
+ AutoModel.register(RWKV6Config, RWKV6Model, exist_ok=True)
10
+ AutoModelForCausalLM.register(RWKV6Config, RWKV6ForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['RWKV6Config', 'RWKV6ForCausalLM', 'RWKV6Model']
models/rwkv6/configuration_rwkv6.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, Optional
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class RWKV6Config(PretrainedConfig):
10
+
11
+ model_type = 'rwkv6'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ attn_mode: str = "chunk",
17
+ hidden_size: int = 2048,
18
+ expand_k: float = 0.5,
19
+ expand_v: float = 1.0,
20
+ hidden_ratio: Optional[float] = 3.5,
21
+ intermediate_size: Optional[int] = None,
22
+ num_hidden_layers: int = 24,
23
+ num_heads: int = 4,
24
+ proj_low_rank_dim: int = 32,
25
+ gate_low_rank_dim: int = 64,
26
+ hidden_act: str = "sqrelu",
27
+ max_position_embeddings: int = 2048,
28
+ norm_first: bool = True,
29
+ norm_bias: bool = True,
30
+ norm_eps: float = 1e-5,
31
+ attn: Optional[Dict] = None,
32
+ use_cache: bool = True,
33
+ pad_token_id: Optional[int] = None,
34
+ bos_token_id: int = 1,
35
+ eos_token_id: int = 2,
36
+ tie_word_embeddings: bool = False,
37
+ initializer_range: float = 0.02,
38
+ fuse_norm: bool = True,
39
+ fuse_cross_entropy: bool = True,
40
+ fuse_linear_cross_entropy: bool = False,
41
+ use_l2warp: bool = False,
42
+ vocab_size: int = 32000,
43
+ **kwargs
44
+ ):
45
+ self.attn_mode = attn_mode
46
+ self.hidden_size = hidden_size
47
+ self.expand_k = expand_k
48
+ self.expand_v = expand_v
49
+ self.hidden_ratio = hidden_ratio
50
+ self.intermediate_size = intermediate_size
51
+ self.norm_first = norm_first
52
+ self.num_hidden_layers = num_hidden_layers
53
+ self.num_heads = num_heads
54
+ self.proj_low_rank_dim = proj_low_rank_dim
55
+ self.gate_low_rank_dim = gate_low_rank_dim
56
+ self.hidden_act = hidden_act
57
+ self.max_position_embeddings = max_position_embeddings
58
+ self.norm_bias = norm_bias
59
+ self.norm_eps = norm_eps
60
+ self.attn = attn
61
+ self.use_cache = use_cache
62
+ self.initializer_range = initializer_range
63
+ self.fuse_norm = fuse_norm
64
+ self.fuse_cross_entropy = fuse_cross_entropy
65
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
66
+ self.use_l2warp = use_l2warp
67
+ self.vocab_size = vocab_size
68
+
69
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
70
+ raise ValueError(
71
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
72
+ )
73
+ if fuse_linear_cross_entropy:
74
+ warnings.warn(
75
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
76
+ "at the potential cost of reduced precision. "
77
+ "If you observe issues like loss divergence, consider disabling this setting."
78
+ )
79
+
80
+ if attn is not None:
81
+ if not isinstance(attn, Dict):
82
+ raise ValueError("attn must be a dictionary")
83
+ if 'layers' not in attn:
84
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
85
+ if 'num_heads' not in attn:
86
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
87
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
88
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
89
+ attn['window_size'] = attn.get('window_size', None)
90
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
91
+
92
+ super().__init__(
93
+ pad_token_id=pad_token_id,
94
+ bos_token_id=bos_token_id,
95
+ eos_token_id=eos_token_id,
96
+ tie_word_embeddings=tie_word_embeddings,
97
+ **kwargs,
98
+ )
models/rwkv7/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from fla.models.rwkv7.configuration_rwkv7 import RWKV7Config
6
+ from fla.models.rwkv7.modeling_rwkv7 import RWKV7ForCausalLM, RWKV7Model
7
+
8
+ AutoConfig.register(RWKV7Config.model_type, RWKV7Config, exist_ok=True)
9
+ AutoModel.register(RWKV7Config, RWKV7Model, exist_ok=True)
10
+ AutoModelForCausalLM.register(RWKV7Config, RWKV7ForCausalLM, exist_ok=True)
11
+
12
+
13
+ __all__ = ['RWKV7Config', 'RWKV7ForCausalLM', 'RWKV7Model']
models/rwkv7/configuration_rwkv7.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import warnings
4
+ from typing import Dict, List, Optional, Union
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+
8
+
9
+ class RWKV7Config(PretrainedConfig):
10
+
11
+ model_type = 'rwkv7'
12
+ keys_to_ignore_at_inference = ['past_key_values']
13
+
14
+ def __init__(
15
+ self,
16
+ attn_mode: str = "chunk",
17
+ hidden_size: int = 2048,
18
+ hidden_ratio: Optional[int] = 4,
19
+ intermediate_size: Optional[int] = None,
20
+ num_hidden_layers: int = 24,
21
+ head_dim: Optional[int] = 64,
22
+ num_heads: Optional[int] = None,
23
+ decay_low_rank_dim: int = 64,
24
+ gate_low_rank_dim: int = 128,
25
+ a_low_rank_dim: int = 64,
26
+ v_low_rank_dim: int = 16,
27
+ hidden_act: str = "sqrelu",
28
+ max_position_embeddings: int = 2048,
29
+ norm_first: bool = True,
30
+ norm_bias: bool = True,
31
+ norm_eps: float = 1e-5,
32
+ attn: Optional[Dict] = None,
33
+ use_cache: bool = True,
34
+ pad_token_id: Optional[int] = None,
35
+ bos_token_id: int = 1,
36
+ eos_token_id: int = 2,
37
+ tie_word_embeddings: bool = False,
38
+ initializer_range: float = 0.02,
39
+ fuse_norm: bool = True,
40
+ fuse_cross_entropy: bool = True,
41
+ fuse_linear_cross_entropy: bool = False,
42
+ use_l2warp: bool = True,
43
+ vocab_size: int = 32000,
44
+ value_dim: Optional[Union[int, List[int]]] = None,
45
+ **kwargs
46
+ ):
47
+ self.attn_mode = attn_mode
48
+ self.hidden_size = hidden_size
49
+ self.hidden_ratio = hidden_ratio
50
+ self.intermediate_size = intermediate_size
51
+ self.norm_first = norm_first
52
+ self.num_hidden_layers = num_hidden_layers
53
+
54
+ if head_dim is None and num_heads is not None:
55
+ head_dim = int(hidden_size // num_heads)
56
+ elif head_dim is not None and num_heads is None:
57
+ num_heads = int(hidden_size // head_dim)
58
+
59
+ if value_dim is None:
60
+ value_dim = [hidden_size] * num_hidden_layers
61
+ elif isinstance(value_dim, int):
62
+ assert value_dim >= hidden_size, "value_dim must be greater than hidden_size"
63
+ assert value_dim % hidden_size == 0, "value_dim must be divisible by hidden_size"
64
+ value_dim = [value_dim] * num_hidden_layers
65
+ else:
66
+ assert len(value_dim) == num_hidden_layers, "value_dim must have the same length as num_hidden_layers"
67
+ for v in value_dim:
68
+ assert v >= hidden_size, "value_dim must be greater than hidden_size"
69
+ assert v % hidden_size == 0, "value_dim must be divisible by hidden_size"
70
+
71
+ self.head_dim = head_dim
72
+ self.num_heads = num_heads
73
+ self.value_dim = value_dim
74
+
75
+ self.decay_low_rank_dim = decay_low_rank_dim
76
+ self.gate_low_rank_dim = gate_low_rank_dim
77
+ self.a_low_rank_dim = a_low_rank_dim
78
+ self.v_low_rank_dim = v_low_rank_dim
79
+ self.hidden_act = hidden_act
80
+ self.max_position_embeddings = max_position_embeddings
81
+ self.norm_bias = norm_bias
82
+ self.norm_eps = norm_eps
83
+ self.attn = attn
84
+ self.use_cache = use_cache
85
+ self.initializer_range = initializer_range
86
+ self.fuse_norm = fuse_norm
87
+ self.fuse_cross_entropy = fuse_cross_entropy
88
+ self.fuse_linear_cross_entropy = fuse_linear_cross_entropy
89
+ self.use_l2warp = use_l2warp
90
+ self.vocab_size = vocab_size
91
+
92
+ if fuse_cross_entropy and fuse_linear_cross_entropy:
93
+ raise ValueError(
94
+ "`fuse_cross_entropy` and `fuse_linear_cross_entropy` cannot be True at the same time."
95
+ )
96
+ if fuse_linear_cross_entropy:
97
+ warnings.warn(
98
+ "`fuse_linear_cross_entropy` is enabled, which can improves memory efficiency "
99
+ "at the potential cost of reduced precision. "
100
+ "If you observe issues like loss divergence, consider disabling this setting."
101
+ )
102
+
103
+ if attn is not None:
104
+ if not isinstance(attn, Dict):
105
+ raise ValueError("attn must be a dictionary")
106
+ if 'layers' not in attn:
107
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
108
+ if 'num_heads' not in attn:
109
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
110
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
111
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
112
+ attn['window_size'] = attn.get('window_size', None)
113
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
114
+
115
+ super().__init__(
116
+ pad_token_id=pad_token_id,
117
+ bos_token_id=bos_token_id,
118
+ eos_token_id=eos_token_id,
119
+ tie_word_embeddings=tie_word_embeddings,
120
+ **kwargs,
121
+ )