zd56 commited on
Commit
86dfe9e
·
verified ·
1 Parent(s): d5f7f99

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
chat_template.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {{'<SPECIAL_10>System'}}{% for message in messages %}{% if message['role'] == 'system' %}{{'
2
+ ' + message['content'].strip()}}{% endif %}{% endfor %}{{'
3
+ '}}{% for message in messages %}{% if message['role'] == 'user' %}{{ '
4
+ <SPECIAL_11>User
5
+ ' + message['content'].strip() + '
6
+ <SPECIAL_11>Assistant
7
+ ' }}{% elif message['role'] == 'assistant' %}{{ message['content'].strip() }}{% endif %}{% endfor %}
config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SwimbaIForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attention_head_dim": 128,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_swimba.SwimbaIConfig",
10
+ "AutoModelForCausalLM": "modeling_swimbaII_v1.SwimbaIForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "chunk_size": 128,
14
+ "conv_kernel": 4,
15
+ "eos_token_id": 2,
16
+ "expand": 2,
17
+ "hidden_dropout": 0.0,
18
+ "hidden_size": 4096,
19
+ "hybrid_override_pattern": "M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 21504,
22
+ "layer_norm_epsilon": 1e-05,
23
+ "mamba_head_dim": 64,
24
+ "mamba_hidden_act": "silu",
25
+ "mamba_num_heads": 128,
26
+ "mamba_proj_bias": false,
27
+ "max_position_embeddings": 8192,
28
+ "mlp_bias": false,
29
+ "mlp_hidden_act": "relu2",
30
+ "model_type": "swimba_i",
31
+ "n_groups": 8,
32
+ "num_attention_heads": 32,
33
+ "num_experts": 4,
34
+ "num_experts_per_tok": 2,
35
+ "num_hidden_layers": 52,
36
+ "num_key_value_heads": 8,
37
+ "num_logits_to_keep": 1,
38
+ "output_router_logits": true,
39
+ "pad_token_id": 0,
40
+ "rescale_prenorm_residual": true,
41
+ "residual_in_fp32": false,
42
+ "rms_norm_eps": 1e-05,
43
+ "router_aux_loss_coef": 0.001,
44
+ "sliding_window": null,
45
+ "ssm_state_size": 128,
46
+ "tie_word_embeddings": false,
47
+ "time_step_floor": 0.0001,
48
+ "time_step_limit": [
49
+ 0.0,
50
+ Infinity
51
+ ],
52
+ "time_step_max": 0.1,
53
+ "time_step_min": 0.001,
54
+ "time_step_rank": 256,
55
+ "torch_dtype": "bfloat16",
56
+ "transformers_version": "4.53.2",
57
+ "use_bias": false,
58
+ "use_cache": true,
59
+ "use_conv_bias": true,
60
+ "use_mamba_kernels": true,
61
+ "vocab_size": 131072
62
+ }
configuration_swimba.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 AI21 Labs Ltd. and the HuggingFace Inc. team. All rights reserved.
3
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """SwimbaI model configuration"""
17
+
18
+ import re
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class SwimbaIConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`SwimbaIModel`]. It is used to instantiate a
30
+ SwimbaI model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of the SwimbaI-v0.1 model.
32
+
33
+ [todo](todo)
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 131072):
41
+ Vocabulary size of the SwimbaI model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`SwimbaIModel`]
43
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
44
+ Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
45
+ model has a output word embedding layer.
46
+ hidden_size (`int`, *optional*, defaults to 4096):
47
+ Dimension of the hidden representations.
48
+ intermediate_size (`int`, *optional*, defaults to 21504):
49
+ Dimension of the MLP representations.
50
+ num_hidden_layers (`int`, *optional*, defaults to 52):
51
+ Number of hidden layers in the Transformer encoder.
52
+ hybrid_override_pattern (`str`, *optional*, defaults to `"M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"`):
53
+ The pattern of the hybrid model. The pattern is a string of characters where each character represents M: Mamba2, *: Attention, -: MLP
54
+ num_attention_heads (`int`, *optional*, defaults to 32):
55
+ Number of attention heads for each attention layer in the Transformer encoder.
56
+ attention_head_dim (`int`, *optional*, defaults to 128):
57
+ Dimension of each attention head.
58
+ num_key_value_heads (`int`, *optional*, defaults to 8):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
62
+ mlp_hidden_act (`str`, *optional*, defaults to "relu2"):
63
+ The non-linear activation function in the MLP layers.
64
+ attention_bias (`bool`, *optional*, defaults to `False`):
65
+ Whether to use bias in attention layers.
66
+ mlp_bias (`bool`, *optional*, defaults to `False`):
67
+ Whether to use bias in MLP layers.
68
+ use_bias (`bool`, *optional*, defaults to `False`):
69
+ Whether to use bias in the model.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
73
+ The epsilon used by the layer normalization layers.
74
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
75
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
80
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
81
+ integer value, only last `num_logits_to_keep` logits will be calculated.
82
+ pad_token_id (`int`, *optional*, defaults to 0):
83
+ The id of the padding token.
84
+ bos_token_id (`int`, *optional*, defaults to 1):
85
+ The id of the "beginning-of-sequence" token.
86
+ eos_token_id (`int`, *optional*, defaults to 2):
87
+ The id of the "end-of-sequence" token.
88
+ sliding_window (`int`, *optional*, defaults to None):
89
+ Sliding window attention window size.
90
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
91
+ The maximum sequence length that this model might ever be used with.
92
+ attention_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio for the attention probabilities.
94
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
95
+ The dropout ratio for the hidden states.
96
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
97
+ Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
98
+ `causal-conv1d` are installed, and the mamba modules are running on a CUDA device.
99
+ ssm_state_size (`int`, *optional*, defaults to 128):
100
+ The dimension of the mamba state space latents.
101
+ mamba_num_heads (`int`, *optional*, defaults to 128):
102
+ Number of heads in Mamba layers.
103
+ mamba_n_groups (`int`, *optional*, defaults to 8):
104
+ Number of groups in Mamba layers.
105
+ mamba_head_dim (`int`, *optional*, defaults to 64):
106
+ Dimension of each Mamba head.
107
+ mamba_d_conv (`int`, *optional*, defaults to 4):
108
+ The size of the mamba convolution kernel.
109
+ mamba_expand (`int`, *optional*, defaults to 2):
110
+ Expanding factor used to determine the mamba intermediate size.
111
+ mamba_hidden_act (`str`, *optional*, defaults to "silu"):
112
+ The non-linear activation function in the Mamba layers.
113
+ mamba_dt_min (`float`, *optional*, defaults to 0.001):
114
+ Minimum value for the time step in Mamba.
115
+ mamba_dt_max (`float`, *optional*, defaults to 0.1):
116
+ Maximum value for the time step in Mamba.
117
+ mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))):
118
+ Limits for the time step in Mamba.
119
+ mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4):
120
+ Floor value for time step initialization in Mamba.
121
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
122
+ Whether to use bias in the convolution layer of the mamba mixer block.
123
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
124
+ Whether to use bias in the input and output projections of the mamba mixer block.
125
+ mamba_chunk_size (`int`, *optional*, defaults to 256):
126
+ Size of chunks for Mamba processing.
127
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
128
+ Whether to rescale the pre-normalization residual connections.
129
+ """
130
+
131
+ model_type = "swimba_i"
132
+ keys_to_ignore_at_inference = ["past_key_values"]
133
+
134
+ def __init__(
135
+ self,
136
+ vocab_size=131072,
137
+ tie_word_embeddings=False,
138
+ hidden_size=4096,
139
+ intermediate_size=21504,
140
+ num_hidden_layers=52,
141
+ hybrid_override_pattern="M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
142
+ num_attention_heads=32,
143
+ attention_head_dim=128,
144
+ num_key_value_heads=8, # nemo: num_query_groups
145
+ mlp_hidden_act="relu2",
146
+ attention_bias=False,
147
+ mlp_bias=False,
148
+ use_bias=False,
149
+ initializer_range=0.02, # nemo: init_method_std
150
+ layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon
151
+ residual_in_fp32=False, # Megatron Core default value
152
+ use_cache=True,
153
+ num_logits_to_keep=1,
154
+ pad_token_id=0,
155
+ bos_token_id=1,
156
+ eos_token_id=2,
157
+ sliding_window=None,
158
+ max_position_embeddings=8192,
159
+ attention_dropout=0.0,
160
+ hidden_dropout=0.0, # * ADDED
161
+ use_mamba_kernels=True,
162
+ ssm_state_size=128, # mamba_state_size
163
+ mamba_num_heads=128,
164
+ mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads
165
+ mamba_head_dim=64,
166
+ mamba_d_conv=4,
167
+ mamba_expand=2,
168
+ mamba_hidden_act="silu",
169
+ mamba_dt_min=0.001,
170
+ mamba_dt_max=0.1,
171
+ mamba_dt_limit=(0.0, float("inf")),
172
+ mamba_dt_init_floor=1e-4,
173
+ mamba_conv_bias=True,
174
+ mamba_proj_bias=False,
175
+ mamba_chunk_size=256,
176
+ num_experts=4, # Number of experts in MoE layers
177
+ num_experts_per_tok=2, # Number of experts per token in MoE layers
178
+ router_aux_loss_coef=0.001, # Coefficient for the router auxiliary loss
179
+ rescale_prenorm_residual=True,
180
+ output_router_logits=True,
181
+ **kwargs,
182
+ ):
183
+ self.vocab_size = vocab_size
184
+ self.tie_word_embeddings = tie_word_embeddings
185
+ self.hidden_size = hidden_size
186
+ self.intermediate_size = intermediate_size
187
+ self.num_hidden_layers = num_hidden_layers
188
+ self.hybrid_override_pattern = hybrid_override_pattern
189
+ self.num_attention_heads = num_attention_heads
190
+ self.attention_head_dim = attention_head_dim
191
+ self.sliding_window = sliding_window
192
+ self.max_position_embeddings = max_position_embeddings
193
+ self.attention_dropout = attention_dropout
194
+ self.hidden_dropout = hidden_dropout
195
+ self.num_experts = num_experts
196
+ self.num_experts_per_tok = num_experts_per_tok
197
+ self.router_aux_loss_coef = router_aux_loss_coef
198
+ self.output_router_logits = output_router_logits
199
+
200
+
201
+ # Validate hybrid_override_pattern
202
+ # M: Mamba2, *: Attention, -: MLP
203
+ assert len(self.hybrid_override_pattern) == self.num_hidden_layers, "hybrid_override_pattern must have the same length as num_hidden_layers"
204
+ assert re.match(r"^[*-M]+$", self.hybrid_override_pattern), "hybrid_override_pattern must only contain characters 'M', '*', or '-'"
205
+
206
+ # for backward compatibility
207
+ if num_key_value_heads is None:
208
+ num_key_value_heads = num_attention_heads
209
+
210
+ self.num_key_value_heads = num_key_value_heads
211
+ self.mlp_hidden_act = mlp_hidden_act
212
+ self.attention_bias = attention_bias
213
+ self.mlp_bias = mlp_bias
214
+ self.use_bias = use_bias
215
+ self.initializer_range = initializer_range
216
+ self.layer_norm_epsilon = layer_norm_epsilon
217
+ self.residual_in_fp32 = residual_in_fp32
218
+
219
+ self.use_cache = use_cache
220
+ self.num_logits_to_keep = num_logits_to_keep
221
+
222
+ self.use_mamba_kernels = use_mamba_kernels
223
+ self.n_groups = mamba_n_groups
224
+ self.mamba_head_dim = mamba_head_dim
225
+ self.ssm_state_size = ssm_state_size
226
+ self.mamba_num_heads = mamba_num_heads
227
+ self.conv_kernel = mamba_d_conv
228
+ self.expand = mamba_expand
229
+ self.mamba_hidden_act = mamba_hidden_act
230
+ self.time_step_min = mamba_dt_min
231
+ self.time_step_max = mamba_dt_max
232
+ self.time_step_limit = mamba_dt_limit
233
+ self.time_step_floor = mamba_dt_init_floor
234
+ self.use_conv_bias = mamba_conv_bias
235
+ self.mamba_proj_bias = mamba_proj_bias
236
+ self.chunk_size = mamba_chunk_size
237
+ self.rescale_prenorm_residual = rescale_prenorm_residual
238
+
239
+ super().__init__(
240
+ pad_token_id=pad_token_id,
241
+ bos_token_id=bos_token_id,
242
+ eos_token_id=eos_token_id,
243
+ tie_word_embeddings=tie_word_embeddings,
244
+ **kwargs,
245
+ )
246
+
247
+ @property
248
+ def layers_block_type(self):
249
+ return [
250
+ "mamba" if self.hybrid_override_pattern[i] == "M" else
251
+ "attention" if self.hybrid_override_pattern[i] == "*" else "mlp"
252
+ for i in range(self.num_hidden_layers)]
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.53.2"
7
+ }
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:723a1bb71666361991d76087002059b5fd59433f69ef784db977b1677dfaaeea
3
+ size 4916414936
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fcdb5db8570b70997003dd42c67372fff11947b6e891380a5b3991a9d29875d1
3
+ size 4917145352
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27556d2c72d95fb373b29adc71744b4c20e21e40047a51daa601a6068cd03d03
3
+ size 4919594912
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9810f3195d4877ccb52780c26ea3e0a9fd0e78cbec46b7bb2516f6e17d42f81b
3
+ size 4876327400
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb6af248ce2bb75cce859285be9f36b817ad47b62fa43b1174780e6ff5e43153
3
+ size 4918682504
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d499af9942ba7a12dff2c61da2c94ba045e79b7d1c0a03ccd83e7b2ae577e27e
3
+ size 1426072008
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4053ea57a6003d4baf42437ce0d14aa1de8934a0df5c8ac753c382bb052c2732
3
+ size 4894523000
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2dd75046e2cf2e6ceec5fb9e74c06175a65239ea1918d7362764c6051134f42c
3
+ size 4979491632
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2cd7bbfd4bec8489bf9416d29f18a6fca2a2133b27af0207e940c9f287e8ff8
3
+ size 2520964264
model.safetensors.index.json ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_parameters": 13574812672,
4
+ "total_size": 27149625344
5
+ },
6
+ "weight_map": {
7
+ "backbone.embeddings.weight": "model-00001-of-00006.safetensors",
8
+ "backbone.layers.0.mixer.A_log": "model-00001-of-00006.safetensors",
9
+ "backbone.layers.0.mixer.D": "model-00001-of-00006.safetensors",
10
+ "backbone.layers.0.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
11
+ "backbone.layers.0.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
12
+ "backbone.layers.0.mixer.dt_bias": "model-00001-of-00006.safetensors",
13
+ "backbone.layers.0.mixer.experts.0.weight": "model-00001-of-00006.safetensors",
14
+ "backbone.layers.0.mixer.experts.1.weight": "model-00001-of-00006.safetensors",
15
+ "backbone.layers.0.mixer.experts.2.weight": "model-00001-of-00006.safetensors",
16
+ "backbone.layers.0.mixer.experts.3.weight": "model-00001-of-00006.safetensors",
17
+ "backbone.layers.0.mixer.gate.weight": "model-00001-of-00006.safetensors",
18
+ "backbone.layers.0.mixer.norm.weight": "model-00001-of-00006.safetensors",
19
+ "backbone.layers.0.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
20
+ "backbone.layers.0.norm.weight": "model-00001-of-00006.safetensors",
21
+ "backbone.layers.1.mixer.down_proj.weight": "model-00001-of-00006.safetensors",
22
+ "backbone.layers.1.mixer.up_proj.weight": "model-00001-of-00006.safetensors",
23
+ "backbone.layers.1.norm.weight": "model-00001-of-00006.safetensors",
24
+ "backbone.layers.10.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
25
+ "backbone.layers.10.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
26
+ "backbone.layers.10.norm.weight": "model-00002-of-00006.safetensors",
27
+ "backbone.layers.11.mixer.A_log": "model-00002-of-00006.safetensors",
28
+ "backbone.layers.11.mixer.D": "model-00002-of-00006.safetensors",
29
+ "backbone.layers.11.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
30
+ "backbone.layers.11.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
31
+ "backbone.layers.11.mixer.dt_bias": "model-00002-of-00006.safetensors",
32
+ "backbone.layers.11.mixer.experts.0.weight": "model-00002-of-00006.safetensors",
33
+ "backbone.layers.11.mixer.experts.1.weight": "model-00002-of-00006.safetensors",
34
+ "backbone.layers.11.mixer.experts.2.weight": "model-00002-of-00006.safetensors",
35
+ "backbone.layers.11.mixer.experts.3.weight": "model-00002-of-00006.safetensors",
36
+ "backbone.layers.11.mixer.gate.weight": "model-00002-of-00006.safetensors",
37
+ "backbone.layers.11.mixer.norm.weight": "model-00002-of-00006.safetensors",
38
+ "backbone.layers.11.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
39
+ "backbone.layers.11.norm.weight": "model-00002-of-00006.safetensors",
40
+ "backbone.layers.12.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
41
+ "backbone.layers.12.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
42
+ "backbone.layers.12.norm.weight": "model-00002-of-00006.safetensors",
43
+ "backbone.layers.13.mixer.A_log": "model-00002-of-00006.safetensors",
44
+ "backbone.layers.13.mixer.D": "model-00002-of-00006.safetensors",
45
+ "backbone.layers.13.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
46
+ "backbone.layers.13.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
47
+ "backbone.layers.13.mixer.dt_bias": "model-00002-of-00006.safetensors",
48
+ "backbone.layers.13.mixer.experts.0.weight": "model-00002-of-00006.safetensors",
49
+ "backbone.layers.13.mixer.experts.1.weight": "model-00002-of-00006.safetensors",
50
+ "backbone.layers.13.mixer.experts.2.weight": "model-00002-of-00006.safetensors",
51
+ "backbone.layers.13.mixer.experts.3.weight": "model-00002-of-00006.safetensors",
52
+ "backbone.layers.13.mixer.gate.weight": "model-00002-of-00006.safetensors",
53
+ "backbone.layers.13.mixer.norm.weight": "model-00002-of-00006.safetensors",
54
+ "backbone.layers.13.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
55
+ "backbone.layers.13.norm.weight": "model-00002-of-00006.safetensors",
56
+ "backbone.layers.14.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
57
+ "backbone.layers.14.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
58
+ "backbone.layers.14.norm.weight": "model-00002-of-00006.safetensors",
59
+ "backbone.layers.15.mixer.A_log": "model-00002-of-00006.safetensors",
60
+ "backbone.layers.15.mixer.D": "model-00002-of-00006.safetensors",
61
+ "backbone.layers.15.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
62
+ "backbone.layers.15.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
63
+ "backbone.layers.15.mixer.dt_bias": "model-00002-of-00006.safetensors",
64
+ "backbone.layers.15.mixer.experts.0.weight": "model-00002-of-00006.safetensors",
65
+ "backbone.layers.15.mixer.experts.1.weight": "model-00002-of-00006.safetensors",
66
+ "backbone.layers.15.mixer.experts.2.weight": "model-00002-of-00006.safetensors",
67
+ "backbone.layers.15.mixer.experts.3.weight": "model-00002-of-00006.safetensors",
68
+ "backbone.layers.15.mixer.gate.weight": "model-00002-of-00006.safetensors",
69
+ "backbone.layers.15.mixer.norm.weight": "model-00002-of-00006.safetensors",
70
+ "backbone.layers.15.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
71
+ "backbone.layers.15.norm.weight": "model-00002-of-00006.safetensors",
72
+ "backbone.layers.16.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
73
+ "backbone.layers.16.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
74
+ "backbone.layers.16.norm.weight": "model-00002-of-00006.safetensors",
75
+ "backbone.layers.17.mixer.A_log": "model-00002-of-00006.safetensors",
76
+ "backbone.layers.17.mixer.D": "model-00002-of-00006.safetensors",
77
+ "backbone.layers.17.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
78
+ "backbone.layers.17.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
79
+ "backbone.layers.17.mixer.dt_bias": "model-00002-of-00006.safetensors",
80
+ "backbone.layers.17.mixer.experts.0.weight": "model-00002-of-00006.safetensors",
81
+ "backbone.layers.17.mixer.experts.1.weight": "model-00002-of-00006.safetensors",
82
+ "backbone.layers.17.mixer.experts.2.weight": "model-00002-of-00006.safetensors",
83
+ "backbone.layers.17.mixer.experts.3.weight": "model-00003-of-00006.safetensors",
84
+ "backbone.layers.17.mixer.gate.weight": "model-00002-of-00006.safetensors",
85
+ "backbone.layers.17.mixer.norm.weight": "model-00003-of-00006.safetensors",
86
+ "backbone.layers.17.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
87
+ "backbone.layers.17.norm.weight": "model-00002-of-00006.safetensors",
88
+ "backbone.layers.18.mixer.k_proj.weight": "model-00003-of-00006.safetensors",
89
+ "backbone.layers.18.mixer.o_proj.weight": "model-00003-of-00006.safetensors",
90
+ "backbone.layers.18.mixer.q_proj.weight": "model-00003-of-00006.safetensors",
91
+ "backbone.layers.18.mixer.v_proj.weight": "model-00003-of-00006.safetensors",
92
+ "backbone.layers.18.norm.weight": "model-00003-of-00006.safetensors",
93
+ "backbone.layers.19.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
94
+ "backbone.layers.19.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
95
+ "backbone.layers.19.norm.weight": "model-00003-of-00006.safetensors",
96
+ "backbone.layers.2.mixer.A_log": "model-00001-of-00006.safetensors",
97
+ "backbone.layers.2.mixer.D": "model-00001-of-00006.safetensors",
98
+ "backbone.layers.2.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
99
+ "backbone.layers.2.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
100
+ "backbone.layers.2.mixer.dt_bias": "model-00001-of-00006.safetensors",
101
+ "backbone.layers.2.mixer.experts.0.weight": "model-00001-of-00006.safetensors",
102
+ "backbone.layers.2.mixer.experts.1.weight": "model-00001-of-00006.safetensors",
103
+ "backbone.layers.2.mixer.experts.2.weight": "model-00001-of-00006.safetensors",
104
+ "backbone.layers.2.mixer.experts.3.weight": "model-00001-of-00006.safetensors",
105
+ "backbone.layers.2.mixer.gate.weight": "model-00001-of-00006.safetensors",
106
+ "backbone.layers.2.mixer.norm.weight": "model-00001-of-00006.safetensors",
107
+ "backbone.layers.2.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
108
+ "backbone.layers.2.norm.weight": "model-00001-of-00006.safetensors",
109
+ "backbone.layers.20.mixer.A_log": "model-00003-of-00006.safetensors",
110
+ "backbone.layers.20.mixer.D": "model-00003-of-00006.safetensors",
111
+ "backbone.layers.20.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
112
+ "backbone.layers.20.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
113
+ "backbone.layers.20.mixer.dt_bias": "model-00003-of-00006.safetensors",
114
+ "backbone.layers.20.mixer.experts.0.weight": "model-00003-of-00006.safetensors",
115
+ "backbone.layers.20.mixer.experts.1.weight": "model-00003-of-00006.safetensors",
116
+ "backbone.layers.20.mixer.experts.2.weight": "model-00003-of-00006.safetensors",
117
+ "backbone.layers.20.mixer.experts.3.weight": "model-00003-of-00006.safetensors",
118
+ "backbone.layers.20.mixer.gate.weight": "model-00003-of-00006.safetensors",
119
+ "backbone.layers.20.mixer.norm.weight": "model-00003-of-00006.safetensors",
120
+ "backbone.layers.20.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
121
+ "backbone.layers.20.norm.weight": "model-00003-of-00006.safetensors",
122
+ "backbone.layers.21.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
123
+ "backbone.layers.21.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
124
+ "backbone.layers.21.norm.weight": "model-00003-of-00006.safetensors",
125
+ "backbone.layers.22.mixer.A_log": "model-00003-of-00006.safetensors",
126
+ "backbone.layers.22.mixer.D": "model-00003-of-00006.safetensors",
127
+ "backbone.layers.22.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
128
+ "backbone.layers.22.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
129
+ "backbone.layers.22.mixer.dt_bias": "model-00003-of-00006.safetensors",
130
+ "backbone.layers.22.mixer.experts.0.weight": "model-00003-of-00006.safetensors",
131
+ "backbone.layers.22.mixer.experts.1.weight": "model-00003-of-00006.safetensors",
132
+ "backbone.layers.22.mixer.experts.2.weight": "model-00003-of-00006.safetensors",
133
+ "backbone.layers.22.mixer.experts.3.weight": "model-00003-of-00006.safetensors",
134
+ "backbone.layers.22.mixer.gate.weight": "model-00003-of-00006.safetensors",
135
+ "backbone.layers.22.mixer.norm.weight": "model-00003-of-00006.safetensors",
136
+ "backbone.layers.22.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
137
+ "backbone.layers.22.norm.weight": "model-00003-of-00006.safetensors",
138
+ "backbone.layers.23.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
139
+ "backbone.layers.23.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
140
+ "backbone.layers.23.norm.weight": "model-00003-of-00006.safetensors",
141
+ "backbone.layers.24.mixer.A_log": "model-00003-of-00006.safetensors",
142
+ "backbone.layers.24.mixer.D": "model-00003-of-00006.safetensors",
143
+ "backbone.layers.24.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
144
+ "backbone.layers.24.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
145
+ "backbone.layers.24.mixer.dt_bias": "model-00003-of-00006.safetensors",
146
+ "backbone.layers.24.mixer.experts.0.weight": "model-00003-of-00006.safetensors",
147
+ "backbone.layers.24.mixer.experts.1.weight": "model-00003-of-00006.safetensors",
148
+ "backbone.layers.24.mixer.experts.2.weight": "model-00003-of-00006.safetensors",
149
+ "backbone.layers.24.mixer.experts.3.weight": "model-00003-of-00006.safetensors",
150
+ "backbone.layers.24.mixer.gate.weight": "model-00003-of-00006.safetensors",
151
+ "backbone.layers.24.mixer.norm.weight": "model-00003-of-00006.safetensors",
152
+ "backbone.layers.24.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
153
+ "backbone.layers.24.norm.weight": "model-00003-of-00006.safetensors",
154
+ "backbone.layers.25.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
155
+ "backbone.layers.25.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
156
+ "backbone.layers.25.norm.weight": "model-00003-of-00006.safetensors",
157
+ "backbone.layers.26.mixer.A_log": "model-00003-of-00006.safetensors",
158
+ "backbone.layers.26.mixer.D": "model-00003-of-00006.safetensors",
159
+ "backbone.layers.26.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
160
+ "backbone.layers.26.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
161
+ "backbone.layers.26.mixer.dt_bias": "model-00003-of-00006.safetensors",
162
+ "backbone.layers.26.mixer.experts.0.weight": "model-00003-of-00006.safetensors",
163
+ "backbone.layers.26.mixer.experts.1.weight": "model-00003-of-00006.safetensors",
164
+ "backbone.layers.26.mixer.experts.2.weight": "model-00003-of-00006.safetensors",
165
+ "backbone.layers.26.mixer.experts.3.weight": "model-00003-of-00006.safetensors",
166
+ "backbone.layers.26.mixer.gate.weight": "model-00003-of-00006.safetensors",
167
+ "backbone.layers.26.mixer.norm.weight": "model-00003-of-00006.safetensors",
168
+ "backbone.layers.26.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
169
+ "backbone.layers.26.norm.weight": "model-00003-of-00006.safetensors",
170
+ "backbone.layers.27.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
171
+ "backbone.layers.27.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
172
+ "backbone.layers.27.norm.weight": "model-00003-of-00006.safetensors",
173
+ "backbone.layers.28.mixer.A_log": "model-00003-of-00006.safetensors",
174
+ "backbone.layers.28.mixer.D": "model-00003-of-00006.safetensors",
175
+ "backbone.layers.28.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
176
+ "backbone.layers.28.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
177
+ "backbone.layers.28.mixer.dt_bias": "model-00003-of-00006.safetensors",
178
+ "backbone.layers.28.mixer.experts.0.weight": "model-00003-of-00006.safetensors",
179
+ "backbone.layers.28.mixer.experts.1.weight": "model-00004-of-00006.safetensors",
180
+ "backbone.layers.28.mixer.experts.2.weight": "model-00004-of-00006.safetensors",
181
+ "backbone.layers.28.mixer.experts.3.weight": "model-00004-of-00006.safetensors",
182
+ "backbone.layers.28.mixer.gate.weight": "model-00003-of-00006.safetensors",
183
+ "backbone.layers.28.mixer.norm.weight": "model-00004-of-00006.safetensors",
184
+ "backbone.layers.28.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
185
+ "backbone.layers.28.norm.weight": "model-00003-of-00006.safetensors",
186
+ "backbone.layers.29.mixer.k_proj.weight": "model-00004-of-00006.safetensors",
187
+ "backbone.layers.29.mixer.o_proj.weight": "model-00004-of-00006.safetensors",
188
+ "backbone.layers.29.mixer.q_proj.weight": "model-00004-of-00006.safetensors",
189
+ "backbone.layers.29.mixer.v_proj.weight": "model-00004-of-00006.safetensors",
190
+ "backbone.layers.29.norm.weight": "model-00004-of-00006.safetensors",
191
+ "backbone.layers.3.mixer.down_proj.weight": "model-00001-of-00006.safetensors",
192
+ "backbone.layers.3.mixer.up_proj.weight": "model-00001-of-00006.safetensors",
193
+ "backbone.layers.3.norm.weight": "model-00001-of-00006.safetensors",
194
+ "backbone.layers.30.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
195
+ "backbone.layers.30.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
196
+ "backbone.layers.30.norm.weight": "model-00004-of-00006.safetensors",
197
+ "backbone.layers.31.mixer.A_log": "model-00004-of-00006.safetensors",
198
+ "backbone.layers.31.mixer.D": "model-00004-of-00006.safetensors",
199
+ "backbone.layers.31.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
200
+ "backbone.layers.31.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
201
+ "backbone.layers.31.mixer.dt_bias": "model-00004-of-00006.safetensors",
202
+ "backbone.layers.31.mixer.experts.0.weight": "model-00004-of-00006.safetensors",
203
+ "backbone.layers.31.mixer.experts.1.weight": "model-00004-of-00006.safetensors",
204
+ "backbone.layers.31.mixer.experts.2.weight": "model-00004-of-00006.safetensors",
205
+ "backbone.layers.31.mixer.experts.3.weight": "model-00004-of-00006.safetensors",
206
+ "backbone.layers.31.mixer.gate.weight": "model-00004-of-00006.safetensors",
207
+ "backbone.layers.31.mixer.norm.weight": "model-00004-of-00006.safetensors",
208
+ "backbone.layers.31.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
209
+ "backbone.layers.31.norm.weight": "model-00004-of-00006.safetensors",
210
+ "backbone.layers.32.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
211
+ "backbone.layers.32.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
212
+ "backbone.layers.32.norm.weight": "model-00004-of-00006.safetensors",
213
+ "backbone.layers.33.mixer.A_log": "model-00004-of-00006.safetensors",
214
+ "backbone.layers.33.mixer.D": "model-00004-of-00006.safetensors",
215
+ "backbone.layers.33.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
216
+ "backbone.layers.33.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
217
+ "backbone.layers.33.mixer.dt_bias": "model-00004-of-00006.safetensors",
218
+ "backbone.layers.33.mixer.experts.0.weight": "model-00004-of-00006.safetensors",
219
+ "backbone.layers.33.mixer.experts.1.weight": "model-00004-of-00006.safetensors",
220
+ "backbone.layers.33.mixer.experts.2.weight": "model-00004-of-00006.safetensors",
221
+ "backbone.layers.33.mixer.experts.3.weight": "model-00004-of-00006.safetensors",
222
+ "backbone.layers.33.mixer.gate.weight": "model-00004-of-00006.safetensors",
223
+ "backbone.layers.33.mixer.norm.weight": "model-00004-of-00006.safetensors",
224
+ "backbone.layers.33.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
225
+ "backbone.layers.33.norm.weight": "model-00004-of-00006.safetensors",
226
+ "backbone.layers.34.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
227
+ "backbone.layers.34.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
228
+ "backbone.layers.34.norm.weight": "model-00004-of-00006.safetensors",
229
+ "backbone.layers.35.mixer.A_log": "model-00004-of-00006.safetensors",
230
+ "backbone.layers.35.mixer.D": "model-00004-of-00006.safetensors",
231
+ "backbone.layers.35.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
232
+ "backbone.layers.35.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
233
+ "backbone.layers.35.mixer.dt_bias": "model-00004-of-00006.safetensors",
234
+ "backbone.layers.35.mixer.experts.0.weight": "model-00004-of-00006.safetensors",
235
+ "backbone.layers.35.mixer.experts.1.weight": "model-00004-of-00006.safetensors",
236
+ "backbone.layers.35.mixer.experts.2.weight": "model-00004-of-00006.safetensors",
237
+ "backbone.layers.35.mixer.experts.3.weight": "model-00004-of-00006.safetensors",
238
+ "backbone.layers.35.mixer.gate.weight": "model-00004-of-00006.safetensors",
239
+ "backbone.layers.35.mixer.norm.weight": "model-00004-of-00006.safetensors",
240
+ "backbone.layers.35.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
241
+ "backbone.layers.35.norm.weight": "model-00004-of-00006.safetensors",
242
+ "backbone.layers.36.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
243
+ "backbone.layers.36.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
244
+ "backbone.layers.36.norm.weight": "model-00004-of-00006.safetensors",
245
+ "backbone.layers.37.mixer.A_log": "model-00004-of-00006.safetensors",
246
+ "backbone.layers.37.mixer.D": "model-00004-of-00006.safetensors",
247
+ "backbone.layers.37.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
248
+ "backbone.layers.37.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
249
+ "backbone.layers.37.mixer.dt_bias": "model-00004-of-00006.safetensors",
250
+ "backbone.layers.37.mixer.experts.0.weight": "model-00004-of-00006.safetensors",
251
+ "backbone.layers.37.mixer.experts.1.weight": "model-00004-of-00006.safetensors",
252
+ "backbone.layers.37.mixer.experts.2.weight": "model-00004-of-00006.safetensors",
253
+ "backbone.layers.37.mixer.experts.3.weight": "model-00004-of-00006.safetensors",
254
+ "backbone.layers.37.mixer.gate.weight": "model-00004-of-00006.safetensors",
255
+ "backbone.layers.37.mixer.norm.weight": "model-00004-of-00006.safetensors",
256
+ "backbone.layers.37.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
257
+ "backbone.layers.37.norm.weight": "model-00004-of-00006.safetensors",
258
+ "backbone.layers.38.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
259
+ "backbone.layers.38.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
260
+ "backbone.layers.38.norm.weight": "model-00004-of-00006.safetensors",
261
+ "backbone.layers.39.mixer.A_log": "model-00005-of-00006.safetensors",
262
+ "backbone.layers.39.mixer.D": "model-00005-of-00006.safetensors",
263
+ "backbone.layers.39.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
264
+ "backbone.layers.39.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
265
+ "backbone.layers.39.mixer.dt_bias": "model-00005-of-00006.safetensors",
266
+ "backbone.layers.39.mixer.experts.0.weight": "model-00005-of-00006.safetensors",
267
+ "backbone.layers.39.mixer.experts.1.weight": "model-00005-of-00006.safetensors",
268
+ "backbone.layers.39.mixer.experts.2.weight": "model-00005-of-00006.safetensors",
269
+ "backbone.layers.39.mixer.experts.3.weight": "model-00005-of-00006.safetensors",
270
+ "backbone.layers.39.mixer.gate.weight": "model-00005-of-00006.safetensors",
271
+ "backbone.layers.39.mixer.norm.weight": "model-00005-of-00006.safetensors",
272
+ "backbone.layers.39.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
273
+ "backbone.layers.39.norm.weight": "model-00005-of-00006.safetensors",
274
+ "backbone.layers.4.mixer.A_log": "model-00001-of-00006.safetensors",
275
+ "backbone.layers.4.mixer.D": "model-00001-of-00006.safetensors",
276
+ "backbone.layers.4.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
277
+ "backbone.layers.4.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
278
+ "backbone.layers.4.mixer.dt_bias": "model-00001-of-00006.safetensors",
279
+ "backbone.layers.4.mixer.experts.0.weight": "model-00001-of-00006.safetensors",
280
+ "backbone.layers.4.mixer.experts.1.weight": "model-00001-of-00006.safetensors",
281
+ "backbone.layers.4.mixer.experts.2.weight": "model-00001-of-00006.safetensors",
282
+ "backbone.layers.4.mixer.experts.3.weight": "model-00001-of-00006.safetensors",
283
+ "backbone.layers.4.mixer.gate.weight": "model-00001-of-00006.safetensors",
284
+ "backbone.layers.4.mixer.norm.weight": "model-00001-of-00006.safetensors",
285
+ "backbone.layers.4.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
286
+ "backbone.layers.4.norm.weight": "model-00001-of-00006.safetensors",
287
+ "backbone.layers.40.mixer.k_proj.weight": "model-00005-of-00006.safetensors",
288
+ "backbone.layers.40.mixer.o_proj.weight": "model-00005-of-00006.safetensors",
289
+ "backbone.layers.40.mixer.q_proj.weight": "model-00005-of-00006.safetensors",
290
+ "backbone.layers.40.mixer.v_proj.weight": "model-00005-of-00006.safetensors",
291
+ "backbone.layers.40.norm.weight": "model-00005-of-00006.safetensors",
292
+ "backbone.layers.41.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
293
+ "backbone.layers.41.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
294
+ "backbone.layers.41.norm.weight": "model-00005-of-00006.safetensors",
295
+ "backbone.layers.42.mixer.A_log": "model-00005-of-00006.safetensors",
296
+ "backbone.layers.42.mixer.D": "model-00005-of-00006.safetensors",
297
+ "backbone.layers.42.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
298
+ "backbone.layers.42.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
299
+ "backbone.layers.42.mixer.dt_bias": "model-00005-of-00006.safetensors",
300
+ "backbone.layers.42.mixer.experts.0.weight": "model-00005-of-00006.safetensors",
301
+ "backbone.layers.42.mixer.experts.1.weight": "model-00005-of-00006.safetensors",
302
+ "backbone.layers.42.mixer.experts.2.weight": "model-00005-of-00006.safetensors",
303
+ "backbone.layers.42.mixer.experts.3.weight": "model-00005-of-00006.safetensors",
304
+ "backbone.layers.42.mixer.gate.weight": "model-00005-of-00006.safetensors",
305
+ "backbone.layers.42.mixer.norm.weight": "model-00005-of-00006.safetensors",
306
+ "backbone.layers.42.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
307
+ "backbone.layers.42.norm.weight": "model-00005-of-00006.safetensors",
308
+ "backbone.layers.43.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
309
+ "backbone.layers.43.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
310
+ "backbone.layers.43.norm.weight": "model-00005-of-00006.safetensors",
311
+ "backbone.layers.44.mixer.A_log": "model-00005-of-00006.safetensors",
312
+ "backbone.layers.44.mixer.D": "model-00005-of-00006.safetensors",
313
+ "backbone.layers.44.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
314
+ "backbone.layers.44.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
315
+ "backbone.layers.44.mixer.dt_bias": "model-00005-of-00006.safetensors",
316
+ "backbone.layers.44.mixer.experts.0.weight": "model-00005-of-00006.safetensors",
317
+ "backbone.layers.44.mixer.experts.1.weight": "model-00005-of-00006.safetensors",
318
+ "backbone.layers.44.mixer.experts.2.weight": "model-00005-of-00006.safetensors",
319
+ "backbone.layers.44.mixer.experts.3.weight": "model-00005-of-00006.safetensors",
320
+ "backbone.layers.44.mixer.gate.weight": "model-00005-of-00006.safetensors",
321
+ "backbone.layers.44.mixer.norm.weight": "model-00005-of-00006.safetensors",
322
+ "backbone.layers.44.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
323
+ "backbone.layers.44.norm.weight": "model-00005-of-00006.safetensors",
324
+ "backbone.layers.45.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
325
+ "backbone.layers.45.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
326
+ "backbone.layers.45.norm.weight": "model-00005-of-00006.safetensors",
327
+ "backbone.layers.46.mixer.A_log": "model-00005-of-00006.safetensors",
328
+ "backbone.layers.46.mixer.D": "model-00005-of-00006.safetensors",
329
+ "backbone.layers.46.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
330
+ "backbone.layers.46.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
331
+ "backbone.layers.46.mixer.dt_bias": "model-00005-of-00006.safetensors",
332
+ "backbone.layers.46.mixer.experts.0.weight": "model-00005-of-00006.safetensors",
333
+ "backbone.layers.46.mixer.experts.1.weight": "model-00005-of-00006.safetensors",
334
+ "backbone.layers.46.mixer.experts.2.weight": "model-00005-of-00006.safetensors",
335
+ "backbone.layers.46.mixer.experts.3.weight": "model-00005-of-00006.safetensors",
336
+ "backbone.layers.46.mixer.gate.weight": "model-00005-of-00006.safetensors",
337
+ "backbone.layers.46.mixer.norm.weight": "model-00005-of-00006.safetensors",
338
+ "backbone.layers.46.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
339
+ "backbone.layers.46.norm.weight": "model-00005-of-00006.safetensors",
340
+ "backbone.layers.47.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
341
+ "backbone.layers.47.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
342
+ "backbone.layers.47.norm.weight": "model-00005-of-00006.safetensors",
343
+ "backbone.layers.48.mixer.A_log": "model-00005-of-00006.safetensors",
344
+ "backbone.layers.48.mixer.D": "model-00005-of-00006.safetensors",
345
+ "backbone.layers.48.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
346
+ "backbone.layers.48.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
347
+ "backbone.layers.48.mixer.dt_bias": "model-00005-of-00006.safetensors",
348
+ "backbone.layers.48.mixer.experts.0.weight": "model-00005-of-00006.safetensors",
349
+ "backbone.layers.48.mixer.experts.1.weight": "model-00005-of-00006.safetensors",
350
+ "backbone.layers.48.mixer.experts.2.weight": "model-00005-of-00006.safetensors",
351
+ "backbone.layers.48.mixer.experts.3.weight": "model-00005-of-00006.safetensors",
352
+ "backbone.layers.48.mixer.gate.weight": "model-00005-of-00006.safetensors",
353
+ "backbone.layers.48.mixer.norm.weight": "model-00005-of-00006.safetensors",
354
+ "backbone.layers.48.mixer.out_proj.weight": "model-00006-of-00006.safetensors",
355
+ "backbone.layers.48.norm.weight": "model-00005-of-00006.safetensors",
356
+ "backbone.layers.49.mixer.down_proj.weight": "model-00006-of-00006.safetensors",
357
+ "backbone.layers.49.mixer.up_proj.weight": "model-00006-of-00006.safetensors",
358
+ "backbone.layers.49.norm.weight": "model-00006-of-00006.safetensors",
359
+ "backbone.layers.5.mixer.down_proj.weight": "model-00001-of-00006.safetensors",
360
+ "backbone.layers.5.mixer.up_proj.weight": "model-00001-of-00006.safetensors",
361
+ "backbone.layers.5.norm.weight": "model-00001-of-00006.safetensors",
362
+ "backbone.layers.50.mixer.A_log": "model-00006-of-00006.safetensors",
363
+ "backbone.layers.50.mixer.D": "model-00006-of-00006.safetensors",
364
+ "backbone.layers.50.mixer.conv1d.bias": "model-00006-of-00006.safetensors",
365
+ "backbone.layers.50.mixer.conv1d.weight": "model-00006-of-00006.safetensors",
366
+ "backbone.layers.50.mixer.dt_bias": "model-00006-of-00006.safetensors",
367
+ "backbone.layers.50.mixer.experts.0.weight": "model-00006-of-00006.safetensors",
368
+ "backbone.layers.50.mixer.experts.1.weight": "model-00006-of-00006.safetensors",
369
+ "backbone.layers.50.mixer.experts.2.weight": "model-00006-of-00006.safetensors",
370
+ "backbone.layers.50.mixer.experts.3.weight": "model-00006-of-00006.safetensors",
371
+ "backbone.layers.50.mixer.gate.weight": "model-00006-of-00006.safetensors",
372
+ "backbone.layers.50.mixer.norm.weight": "model-00006-of-00006.safetensors",
373
+ "backbone.layers.50.mixer.out_proj.weight": "model-00006-of-00006.safetensors",
374
+ "backbone.layers.50.norm.weight": "model-00006-of-00006.safetensors",
375
+ "backbone.layers.51.mixer.down_proj.weight": "model-00006-of-00006.safetensors",
376
+ "backbone.layers.51.mixer.up_proj.weight": "model-00006-of-00006.safetensors",
377
+ "backbone.layers.51.norm.weight": "model-00006-of-00006.safetensors",
378
+ "backbone.layers.6.mixer.A_log": "model-00001-of-00006.safetensors",
379
+ "backbone.layers.6.mixer.D": "model-00001-of-00006.safetensors",
380
+ "backbone.layers.6.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
381
+ "backbone.layers.6.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
382
+ "backbone.layers.6.mixer.dt_bias": "model-00001-of-00006.safetensors",
383
+ "backbone.layers.6.mixer.experts.0.weight": "model-00001-of-00006.safetensors",
384
+ "backbone.layers.6.mixer.experts.1.weight": "model-00001-of-00006.safetensors",
385
+ "backbone.layers.6.mixer.experts.2.weight": "model-00001-of-00006.safetensors",
386
+ "backbone.layers.6.mixer.experts.3.weight": "model-00001-of-00006.safetensors",
387
+ "backbone.layers.6.mixer.gate.weight": "model-00001-of-00006.safetensors",
388
+ "backbone.layers.6.mixer.norm.weight": "model-00001-of-00006.safetensors",
389
+ "backbone.layers.6.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
390
+ "backbone.layers.6.norm.weight": "model-00001-of-00006.safetensors",
391
+ "backbone.layers.7.mixer.k_proj.weight": "model-00001-of-00006.safetensors",
392
+ "backbone.layers.7.mixer.o_proj.weight": "model-00001-of-00006.safetensors",
393
+ "backbone.layers.7.mixer.q_proj.weight": "model-00001-of-00006.safetensors",
394
+ "backbone.layers.7.mixer.v_proj.weight": "model-00001-of-00006.safetensors",
395
+ "backbone.layers.7.norm.weight": "model-00001-of-00006.safetensors",
396
+ "backbone.layers.8.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
397
+ "backbone.layers.8.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
398
+ "backbone.layers.8.norm.weight": "model-00001-of-00006.safetensors",
399
+ "backbone.layers.9.mixer.A_log": "model-00002-of-00006.safetensors",
400
+ "backbone.layers.9.mixer.D": "model-00002-of-00006.safetensors",
401
+ "backbone.layers.9.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
402
+ "backbone.layers.9.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
403
+ "backbone.layers.9.mixer.dt_bias": "model-00002-of-00006.safetensors",
404
+ "backbone.layers.9.mixer.experts.0.weight": "model-00002-of-00006.safetensors",
405
+ "backbone.layers.9.mixer.experts.1.weight": "model-00002-of-00006.safetensors",
406
+ "backbone.layers.9.mixer.experts.2.weight": "model-00002-of-00006.safetensors",
407
+ "backbone.layers.9.mixer.experts.3.weight": "model-00002-of-00006.safetensors",
408
+ "backbone.layers.9.mixer.gate.weight": "model-00002-of-00006.safetensors",
409
+ "backbone.layers.9.mixer.norm.weight": "model-00002-of-00006.safetensors",
410
+ "backbone.layers.9.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
411
+ "backbone.layers.9.norm.weight": "model-00002-of-00006.safetensors",
412
+ "backbone.norm_f.weight": "model-00006-of-00006.safetensors",
413
+ "lm_head.weight": "model-00006-of-00006.safetensors"
414
+ }
415
+ }
modeling_swimbaII_v1.py ADDED
@@ -0,0 +1,1673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc. team.
3
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch SwimbaI model."""
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, Dict, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import CrossEntropyLoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import DynamicCache # we need __iter__ and __len__ of pkv
30
+ from transformers.generation import GenerationMixin
31
+ from transformers.modeling_attn_mask_utils import (
32
+ AttentionMaskConverter,
33
+ )
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.utils import (
36
+ ModelOutput,
37
+ add_code_sample_docstrings,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ logging,
41
+ )
42
+ from transformers.utils.import_utils import (
43
+ is_causal_conv1d_available,
44
+ is_flash_attn_2_available,
45
+ is_flash_attn_greater_or_equal_2_10,
46
+ is_mamba_2_ssm_available,
47
+ )
48
+ from configuration_swimba import SwimbaIConfig
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+
54
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
55
+ def load_balancing_loss_func(
56
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
57
+ num_experts: Optional[int] = None,
58
+ top_k=2,
59
+ attention_mask: Optional[torch.Tensor] = None,
60
+ ) -> Union[torch.Tensor, int]:
61
+ r"""
62
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
63
+
64
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
65
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
66
+ experts is too unbalanced.
67
+
68
+ Args:
69
+ gate_logits:
70
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
71
+ shape [batch_size X sequence_length, num_experts].
72
+ num_experts:
73
+ Number of experts
74
+ top_k:
75
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
76
+ parameter.
77
+ attention_mask (`torch.Tensor`, *optional*):
78
+ The attention_mask used in forward function
79
+ shape [batch_size X sequence_length] if not None.
80
+
81
+ Returns:
82
+ The auxiliary loss.
83
+ """
84
+ if gate_logits is None or not isinstance(gate_logits, tuple):
85
+ return 0
86
+
87
+ if isinstance(gate_logits, tuple):
88
+ if len(gate_logits) == 0:
89
+ return 0
90
+ compute_device = gate_logits[0].device
91
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
92
+
93
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
94
+
95
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
96
+
97
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
98
+
99
+ if attention_mask is None:
100
+ # Compute the percentage of tokens routed to each experts
101
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
102
+
103
+ # Compute the average probability of routing to these experts
104
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
105
+ else:
106
+ batch_size, sequence_length = attention_mask.shape
107
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
108
+
109
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
110
+ expert_attention_mask = (
111
+ attention_mask[None, :, :, None, None]
112
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
113
+ .reshape(-1, top_k, num_experts)
114
+ .to(compute_device)
115
+ )
116
+
117
+ # Compute the percentage of tokens routed to each experts
118
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
119
+ expert_attention_mask, dim=0
120
+ )
121
+
122
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
123
+ router_per_expert_attention_mask = (
124
+ attention_mask[None, :, :, None]
125
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
126
+ .reshape(-1, num_experts)
127
+ .to(compute_device)
128
+ )
129
+
130
+ # Compute the average probability of routing to these experts
131
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
132
+ router_per_expert_attention_mask, dim=0
133
+ )
134
+
135
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
136
+ return overall_loss * num_experts
137
+
138
+
139
+ # Copied from transformers.models.mamba.modeling_mamba2.modeling_mamba2.py with MAMBA2->NEMOTRONH,Mamba2->SwimbaI
140
+ # For Mamba2 components Mamba2->SwimbaIMamba2
141
+ if is_mamba_2_ssm_available():
142
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
143
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
144
+ else:
145
+ mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, selective_state_update = None, None, None
146
+
147
+ try:
148
+ #from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated
149
+ from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn
150
+ except ImportError:
151
+ raise ImportError("mamba-ssm is required by the Mamba model but cannot be imported")
152
+
153
+ if is_causal_conv1d_available():
154
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
155
+ else:
156
+ causal_conv1d_update, causal_conv1d_fn = None, None
157
+
158
+ if is_flash_attn_2_available():
159
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
160
+
161
+ is_fast_path_available = all(
162
+ (
163
+ selective_state_update,
164
+ mamba_chunk_scan_combined,
165
+ mamba_split_conv1d_scan_combined,
166
+ causal_conv1d_fn,
167
+ causal_conv1d_update,
168
+ )
169
+ )
170
+
171
+
172
+ _CHECKPOINT_FOR_DOC = "nvidia/SwimbaI-56B-Base-8K"
173
+ _CONFIG_FOR_DOC = "SwimbaIConfig"
174
+
175
+
176
+ # Helper methods for segment sum computation
177
+
178
+
179
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
180
+ """
181
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
182
+
183
+ Assumes that we only have tensors of either size 4 or 3
184
+ """
185
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
186
+
187
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
188
+
189
+
190
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
191
+ """
192
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
193
+ simultaneously splitting it into chunk sequences.
194
+
195
+ Assumes that we only have tensors of either size 4 or 3
196
+ """
197
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
198
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
199
+
200
+ if len(input_tensor.shape) == 3:
201
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
202
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
203
+ else:
204
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
205
+ return input_tensor.reshape(
206
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
207
+ )
208
+
209
+
210
+ def segment_sum(input_tensor):
211
+ """
212
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
213
+ """
214
+ chunk_size = input_tensor.size(-1)
215
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
216
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
217
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
218
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
219
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
220
+ input_tensor = input_tensor.masked_fill(~mask, 0)
221
+ # 3. compute actual cumsum
222
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
223
+
224
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
225
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
226
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
227
+ return tensor_segsum
228
+
229
+
230
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
231
+ """
232
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
233
+ """
234
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
235
+ dtype = hidden_states.dtype
236
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
237
+
238
+ return hidden_states
239
+
240
+ # Copied from NemotronH
241
+ # Copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
242
+ class HybridMambaAttentionDynamicCache(DynamicCache):
243
+ """
244
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
245
+ (which has a constant shape regardless of seq_len).
246
+
247
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
248
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
249
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
250
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
251
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
252
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
253
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
254
+ """
255
+
256
+ def __init__(self, config, batch_size, dtype=torch.float16, device=None):
257
+ super().__init__()
258
+ self.dtype = dtype
259
+ self.hybrid_override_pattern = config.hybrid_override_pattern
260
+ self.has_previous_state = False # only used by mamba
261
+ intermediate_size = config.expand * config.hidden_size
262
+ ssm_state_size = config.ssm_state_size
263
+ conv_kernel_size = config.conv_kernel
264
+ self.conv_states = []
265
+ self.ssm_states = []
266
+ self.transformer_layers = []
267
+ for i in range(config.num_hidden_layers):
268
+ if self.hybrid_override_pattern[i] == "M":
269
+ # Mamba layer
270
+ self.conv_states += [
271
+ torch.zeros(batch_size, intermediate_size, conv_kernel_size, device=device, dtype=dtype)
272
+ ]
273
+ self.ssm_states += [
274
+ torch.zeros(batch_size, intermediate_size, ssm_state_size, device=device, dtype=dtype)
275
+ ]
276
+ else:
277
+ # Attention or MLP layer
278
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
279
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
280
+ self.transformer_layers.append(i)
281
+
282
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
283
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
284
+
285
+ def update(
286
+ self,
287
+ key_states: torch.Tensor,
288
+ value_states: torch.Tensor,
289
+ layer_idx: int,
290
+ cache_kwargs: Optional[Dict[str, Any]] = None,
291
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
292
+ # Update the cache
293
+ if self.key_cache[layer_idx].shape[-1] == 0:
294
+ self.key_cache[layer_idx] = key_states
295
+ self.value_cache[layer_idx] = value_states
296
+ else:
297
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
298
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
299
+
300
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
301
+
302
+ def reorder_cache(self, beam_idx: torch.LongTensor):
303
+ """Reorders the cache for beam search, given the selected beam indices."""
304
+ for layer_idx in range(len(self.key_cache)):
305
+ device = self.key_cache[layer_idx].device
306
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
307
+ device = self.value_cache[layer_idx].device
308
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
309
+
310
+ device = self.conv_states[layer_idx].device
311
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
312
+ device = self.ssm_states[layer_idx].device
313
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
314
+
315
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
316
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
317
+ # take any layer that contains cache and not empty tensor
318
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
319
+ if len(self.key_cache) <= layer_idx:
320
+ return 0
321
+ return self.key_cache[layer_idx].shape[-2]
322
+
323
+ def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
324
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
325
+
326
+ @classmethod
327
+ def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None) -> "DynamicCache":
328
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
329
+
330
+ # Copied from modeling_mamba2.py
331
+ def update_conv_state(
332
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
333
+ ) -> torch.Tensor:
334
+ if cache_init:
335
+ self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
336
+ else:
337
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
338
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
339
+ return self.conv_states[layer_idx]
340
+
341
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
342
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
343
+ return self.ssm_states[layer_idx]
344
+
345
+ def reset(self):
346
+ self.conv_states.zero_()
347
+ self.ssm_states.zero_()
348
+
349
+ # Copied from NemotronH
350
+ class MambaRMSNormGated(torch.nn.Module):
351
+ def __init__(self, hidden_size, group_size, eps=1e-5):
352
+ super().__init__()
353
+ self.weight = nn.Parameter(torch.ones(hidden_size))
354
+ self.variance_epsilon = eps
355
+ self.group_size = group_size
356
+
357
+ # jan28b version
358
+ def forward(self, hidden_states, gate=None):
359
+ return rmsnorm_fn(x=hidden_states,
360
+ weight=self.weight,
361
+ bias=None, # No bias
362
+ z=gate,
363
+ eps=self.variance_epsilon,
364
+ group_size=self.group_size,
365
+ norm_before_gate=False
366
+ )
367
+
368
+ class SwimbaISparseMoEMamba2Mixer(nn.Module):
369
+ """
370
+ A modified Mamba2 mixer that incorporates MoE for the input projection.
371
+ """
372
+
373
+ def __init__(self, config: SwimbaIConfig, layer_idx: int):
374
+ super().__init__()
375
+ self.num_heads = config.mamba_num_heads
376
+ self.hidden_size = config.hidden_size
377
+ self.ssm_state_size = config.ssm_state_size
378
+ self.conv_kernel_size = config.conv_kernel
379
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
380
+ self.layer_idx = layer_idx
381
+ self.use_conv_bias = config.use_conv_bias
382
+ self.activation = config.mamba_hidden_act
383
+ self.act = ACT2FN[config.mamba_hidden_act]
384
+ self.layer_norm_epsilon = config.layer_norm_epsilon
385
+ self.n_groups = config.n_groups
386
+ self.head_dim = config.mamba_head_dim
387
+ self.chunk_size = config.chunk_size
388
+ self.time_step_limit = config.time_step_limit
389
+ self.time_step_min = config.time_step_min
390
+ self.time_step_max = config.time_step_max
391
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
392
+ self.use_bias = config.use_bias
393
+
394
+ # MoE specific attributes
395
+ self.num_experts = config.num_experts
396
+ self.top_k = config.num_experts_per_tok
397
+ self.norm_topk_prob = getattr(config, "norm_topk_prob", False)
398
+ self.gate = nn.Linear(self.hidden_size, self.num_experts, bias=False)
399
+ self.projection_size = self.intermediate_size + self.conv_dim + self.num_heads
400
+ self.experts = nn.ModuleList(
401
+ [nn.Linear(self.hidden_size, self.projection_size, bias=self.use_bias) for _ in range(self.num_experts)]
402
+ )
403
+
404
+ self.conv1d = nn.Conv1d(
405
+ in_channels=self.conv_dim,
406
+ out_channels=self.conv_dim,
407
+ bias=config.use_conv_bias,
408
+ kernel_size=config.conv_kernel,
409
+ groups=self.conv_dim,
410
+ padding=config.conv_kernel - 1,
411
+ )
412
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
413
+ A = torch.arange(1, self.num_heads + 1)
414
+ self.A_log = nn.Parameter(torch.log(A))
415
+ self.A_log._no_weight_decay = True
416
+ self.norm = MambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon, group_size=self.intermediate_size // self.n_groups)
417
+ self.D = nn.Parameter(torch.ones(self.num_heads))
418
+ self.D._no_weight_decay = True
419
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
420
+
421
+ # Copied from OLMoE
422
+ def _moe_forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
423
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
424
+ hidden_states = hidden_states.view(-1, hidden_dim)
425
+ # router_logits: (batch * sequence_length, n_experts)
426
+ router_logits = self.gate(hidden_states)
427
+
428
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
429
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
430
+ if self.norm_topk_prob:
431
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
432
+ # we cast back to the input dtype
433
+ routing_weights = routing_weights.to(hidden_states.dtype)
434
+
435
+ final_hidden_states = torch.zeros(
436
+ (batch_size * sequence_length, self.projection_size), dtype=hidden_states.dtype, device=hidden_states.device
437
+ )
438
+
439
+ # One hot encode the selected experts to create an expert mask
440
+ # this will be used to easily index which expert is going to be selected
441
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
442
+
443
+ # Loop over all available experts in the model and perform the computation on each expert
444
+ for expert_idx in range(self.num_experts):
445
+ expert_layer = self.experts[expert_idx]
446
+ idx, top_x = torch.where(expert_mask[expert_idx])
447
+
448
+ # Index the correct hidden states and compute the expert hidden state for
449
+ # the current expert. We need to make sure to multiply the output hidden
450
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
451
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
452
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
453
+
454
+ # However `index_add_` only support torch tensors for indexing so we'll use
455
+ # the `top_x` tensor here.
456
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
457
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, self.projection_size)
458
+ return final_hidden_states, router_logits
459
+
460
+ def cuda_kernels_forward(
461
+ self,
462
+ hidden_states: torch.Tensor,
463
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
464
+ cache_position: Optional[torch.LongTensor] = None,
465
+ attention_mask: Optional[torch.Tensor] = None,
466
+ ):
467
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
468
+ projected_states, router_logits = self._moe_forward(hidden_states)
469
+
470
+ batch_size, seq_len, _ = hidden_states.shape
471
+ groups_time_state_size = self.n_groups * self.ssm_state_size
472
+ d_mlp = (
473
+ projected_states.shape[-1]
474
+ - 2 * self.intermediate_size
475
+ - 2 * self.n_groups * self.ssm_state_size
476
+ - self.num_heads
477
+ ) // 2
478
+
479
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
480
+ _, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
481
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
482
+ )
483
+ hidden_states_B_C = causal_conv1d_update(
484
+ hidden_states_B_C,
485
+ cache_params.conv_states[self.layer_idx],
486
+ self.conv1d.weight.squeeze(1),
487
+ self.conv1d.bias,
488
+ self.activation,
489
+ )
490
+ hidden_states, B, C = torch.split(
491
+ hidden_states_B_C,
492
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
493
+ dim=-1,
494
+ )
495
+ A = -torch.exp(self.A_log.float())
496
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
497
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
498
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
499
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
500
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
501
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
502
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
503
+ hidden_states = selective_state_update(
504
+ cache_params.ssm_states[self.layer_idx],
505
+ hidden_states_reshaped,
506
+ dt,
507
+ A,
508
+ B,
509
+ C,
510
+ D,
511
+ z=None,
512
+ dt_bias=dt_bias,
513
+ dt_softplus=True,
514
+ )
515
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
516
+ hidden_states = self.norm(hidden_states, gate)
517
+ out = self.out_proj(hidden_states)[:, None, ...]
518
+ else:
519
+ A = -torch.exp(self.A_log.float())
520
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
521
+ if self.training and cache_params is None:
522
+ out = mamba_split_conv1d_scan_combined(
523
+ projected_states,
524
+ self.conv1d.weight.squeeze(1),
525
+ self.conv1d.bias,
526
+ self.dt_bias,
527
+ A,
528
+ D=self.D,
529
+ chunk_size=self.chunk_size,
530
+ seq_idx=None,
531
+ activation=self.activation,
532
+ rmsnorm_weight=self.norm.weight,
533
+ rmsnorm_eps=self.norm.variance_epsilon,
534
+ outproj_weight=self.out_proj.weight,
535
+ outproj_bias=self.out_proj.bias,
536
+ headdim=self.head_dim,
537
+ ngroups=self.n_groups,
538
+ norm_before_gate=False,
539
+ return_final_states=False,
540
+ **dt_limit_kwargs,
541
+ )
542
+ else:
543
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
544
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
545
+ )
546
+ if cache_params is not None:
547
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
548
+ conv_states = nn.functional.pad(
549
+ hidden_states_B_C_transposed,
550
+ (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
551
+ )
552
+ cache_params.update_conv_state(
553
+ layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
554
+ )
555
+ if self.activation not in ["silu", "swish"]:
556
+ hidden_states_B_C = self.act(
557
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
558
+ )
559
+ else:
560
+ hidden_states_B_C = causal_conv1d_fn(
561
+ x=hidden_states_B_C.transpose(1, 2),
562
+ weight=self.conv1d.weight.squeeze(1),
563
+ bias=self.conv1d.bias,
564
+ activation=self.activation,
565
+ ).transpose(1, 2)
566
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
567
+ hidden_states, B, C = torch.split(
568
+ hidden_states_B_C,
569
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
570
+ dim=-1,
571
+ )
572
+ scan_output, ssm_state = mamba_chunk_scan_combined(
573
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
574
+ dt,
575
+ A,
576
+ B.view(batch_size, seq_len, self.n_groups, -1),
577
+ C.view(batch_size, seq_len, self.n_groups, -1),
578
+ chunk_size=self.chunk_size,
579
+ D=self.D,
580
+ z=None,
581
+ seq_idx=None,
582
+ return_final_states=True,
583
+ dt_bias=self.dt_bias,
584
+ dt_softplus=True,
585
+ **dt_limit_kwargs,
586
+ )
587
+ if ssm_state is not None and cache_params is not None:
588
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
589
+ scan_output = scan_output.view(batch_size, seq_len, -1)
590
+ scan_output = self.norm(scan_output, gate)
591
+ out = self.out_proj(scan_output)
592
+ return out, router_logits
593
+
594
+ def torch_forward(self, hidden_states, cache_params: Optional[HybridMambaAttentionDynamicCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None):
595
+ batch_size, seq_len, _ = hidden_states.shape
596
+ dtype = hidden_states.dtype
597
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
598
+ projected_states, router_logits = self._moe_forward(hidden_states)
599
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size-self.num_heads) // 2
600
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
601
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
602
+ )
603
+
604
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
605
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
606
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
607
+ hidden_states_B_C = torch.sum(
608
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
609
+ )
610
+ if self.use_conv_bias:
611
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
612
+ hidden_states_B_C = self.act(hidden_states_B_C)
613
+ else:
614
+ if cache_params is not None:
615
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
616
+ conv_states = nn.functional.pad(
617
+ hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
618
+ )
619
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
620
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
621
+
622
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
623
+ hidden_states, B, C = torch.split(
624
+ hidden_states_B_C,
625
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
626
+ dim=-1
627
+ )
628
+ A = -torch.exp(self.A_log.float())
629
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
630
+ cache_device = cache_params.ssm_states.device
631
+ dt = dt[:, 0, :][:, None, ...]
632
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
633
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
634
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
635
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
636
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
637
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
638
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
639
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
640
+ B = B.reshape(batch_size, -1, B.shape[-1])
641
+ dB = dt[..., None] * B[..., None, :]
642
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
643
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
644
+ cache_params.update_ssm_state(
645
+ layer_idx=self.layer_idx,
646
+ new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
647
+ )
648
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
649
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
650
+ C = C.reshape(batch_size, -1, C.shape[-1])
651
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype)
652
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size)
653
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1)
654
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
655
+ y = y.view(batch_size, self.num_heads, self.head_dim)
656
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
657
+ y = (y + hidden_states * D).to(y.dtype)
658
+ y = y.reshape(batch_size, -1)[:, None, ...]
659
+ else:
660
+ dt = nn.functional.softplus(dt + self.dt_bias)
661
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
662
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
663
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
664
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
665
+ B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
666
+ C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
667
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
668
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
669
+ hidden_states = hidden_states * dt[..., None]
670
+ A = A.to(hidden_states.dtype) * dt
671
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
672
+ A = A.permute(0, 3, 1, 2)
673
+ A_cumsum = torch.cumsum(A, dim=-1)
674
+ L = torch.exp(segment_sum(A))
675
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :]
676
+ G = G_intermediate.sum(dim=-1)
677
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
678
+ M = M_intermediate.sum(dim=-1)
679
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
680
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
681
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
682
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
683
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
684
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
685
+ else:
686
+ previous_states = torch.zeros_like(states[:, :1])
687
+ states = torch.cat([previous_states, states], dim=1)
688
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
689
+ decay_chunk = decay_chunk.transpose(1, 3)
690
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
691
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
692
+ state_decay_out = torch.exp(A_cumsum)
693
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
694
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
695
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
696
+ y = Y_diag + Y_off
697
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
698
+ y = y + D_residual
699
+ if pad_size > 0:
700
+ y = y[:, :seq_len, :, :]
701
+ y = y.reshape(batch_size, seq_len, -1)
702
+ if ssm_state is not None and cache_params is not None:
703
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
704
+ scan_output = self.norm(y, gate)
705
+ contextualized_states = self.out_proj(scan_output.to(dtype))
706
+ return contextualized_states, router_logits
707
+
708
+ def forward(
709
+ self,
710
+ hidden_states,
711
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
712
+ cache_position: Optional[torch.LongTensor] = None,
713
+ attention_mask: Optional[torch.Tensor] = None,
714
+ ):
715
+ if is_fast_path_available and "cuda" in self.gate.weight.device.type:
716
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
717
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
718
+
719
+
720
+ # Copied from NemotronH
721
+ class SwimbaIRMSNorm(nn.Module):
722
+ def __init__(self, hidden_size, eps=1e-6):
723
+ """
724
+ SwimbaIRMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
725
+ """
726
+ super().__init__()
727
+ self.weight = nn.Parameter(torch.ones(hidden_size))
728
+ self.variance_epsilon = eps
729
+
730
+ def forward(self, hidden_states):
731
+ input_dtype = hidden_states.dtype
732
+ hidden_states = hidden_states.to(torch.float32)
733
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
734
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
735
+ # Weights are in float32
736
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
737
+
738
+
739
+ # Copied from transformers.models.nemotron.modeling_nemotron Nemotron->SwimbaI
740
+ # Copied from NemotronH
741
+ class SwimbaIMLP(nn.Module):
742
+ def __init__(self, config, layer_idx: Optional[int] = None):
743
+ super().__init__()
744
+ self.config = config
745
+ self.layer_idx = layer_idx
746
+ if layer_idx is None:
747
+ logger.warning_once(
748
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
749
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
750
+ "when creating this class."
751
+ )
752
+ self.hidden_size = config.hidden_size
753
+ self.intermediate_size = config.intermediate_size
754
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
755
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
756
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
757
+
758
+ def forward(self, x):
759
+ return self.down_proj(self.act_fn(self.up_proj(x)))
760
+
761
+ # Copied from NemotronH
762
+ class SwimbaIBlock(nn.Module):
763
+ def __init__(self, config, layer_idx):
764
+ super().__init__()
765
+ self.config = config
766
+ self.layer_idx = layer_idx
767
+ self.residual_in_fp32 = config.residual_in_fp32
768
+ self.norm = SwimbaIRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
769
+
770
+ # M: Mamba2, *: Attention, -: MLP
771
+ self.block_type = config.layers_block_type[layer_idx]
772
+ if self.block_type == "mamba":
773
+ self.mixer = SwimbaISparseMoEMamba2Mixer(config, layer_idx=layer_idx)
774
+ elif self.block_type == "attention":
775
+ self.mixer = SWIMBAI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
776
+ elif self.block_type == "mlp":
777
+ self.mixer = SwimbaIMLP(config)
778
+ else:
779
+ raise ValueError(f"Invalid layer pattern {config.hybrid_override_pattern[layer_idx]}")
780
+
781
+ def forward(
782
+ self,
783
+ hidden_states,
784
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
785
+ cache_position: Optional[torch.LongTensor] = None,
786
+ attention_mask: Optional[torch.Tensor] = None,
787
+ output_router_logits: bool = False,
788
+ use_cache: bool = False,
789
+ ):
790
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
791
+ # * Use torch.cuda.stream() to avoid NaN issues when using multiple GPUs
792
+ residual = hidden_states
793
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
794
+ if self.residual_in_fp32:
795
+ residual = residual.to(torch.float32)
796
+
797
+ router_logits = None
798
+ if self.block_type == "mamba":
799
+ hidden_states, router_logits = self.mixer(
800
+ hidden_states, cache_params=cache_params, cache_position=cache_position
801
+ )
802
+ elif self.block_type == "attention":
803
+ hidden_states, _, _ = self.mixer(
804
+ hidden_states, cache_position=cache_position
805
+ )
806
+ elif self.block_type == "mlp":
807
+ hidden_states = self.mixer(
808
+ hidden_states
809
+ )
810
+ else:
811
+ raise ValueError(f"Invalid block_type: {self.block_type}")
812
+
813
+ hidden_states = residual + hidden_states
814
+
815
+ outputs = (hidden_states,)
816
+ if output_router_logits:
817
+ outputs += (router_logits,)
818
+ return outputs
819
+
820
+
821
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
822
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
823
+ """
824
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
825
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
826
+ """
827
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
828
+ if n_rep == 1:
829
+ return hidden_states
830
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
831
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
832
+
833
+
834
+ # Copied from NemotronH
835
+ class SwimbaIAttention(nn.Module):
836
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
837
+
838
+ def __init__(self, config: SwimbaIConfig, layer_idx: Optional[int] = None):
839
+ super().__init__()
840
+ self.config = config
841
+ self.layer_idx = layer_idx
842
+ if layer_idx is None:
843
+ logger.warning_once(
844
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
845
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
846
+ "when creating this class."
847
+ )
848
+
849
+ self.attention_dropout = config.attention_dropout
850
+ self.hidden_size = config.hidden_size
851
+ self.num_heads = config.num_attention_heads
852
+ if config.attention_head_dim is not None:
853
+ self.head_dim = config.attention_head_dim
854
+ else:
855
+ self.head_dim = config.hidden_size // config.num_attention_heads
856
+ self.num_key_value_heads = config.num_key_value_heads
857
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
858
+ self.max_position_embeddings = config.max_position_embeddings
859
+ self.is_causal = True
860
+
861
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
862
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
863
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
864
+ self.o_proj = nn.Linear(self.head_dim * self.num_heads, self.hidden_size, bias=config.attention_bias)
865
+
866
+ def forward(
867
+ self,
868
+ hidden_states: torch.Tensor,
869
+ # position_embeddings: Tuple[torch.Tensor, torch.Tensor], #TODO
870
+ attention_mask: Optional[torch.Tensor] = None,
871
+ position_ids: Optional[torch.LongTensor] = None,
872
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
873
+ output_attentions: bool = False,
874
+ use_cache: bool = False,
875
+ cache_position: Optional[torch.LongTensor] = None,
876
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
877
+ bsz, q_len, _ = hidden_states.size()
878
+
879
+ query_states = self.q_proj(hidden_states)
880
+ key_states = self.k_proj(hidden_states)
881
+ value_states = self.v_proj(hidden_states)
882
+
883
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
884
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
885
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
886
+
887
+ if past_key_value is not None:
888
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
889
+
890
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
891
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
892
+
893
+ causal_mask = attention_mask
894
+ if attention_mask is not None: # no matter the length, we just slice it
895
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
896
+
897
+ if query_states.device.type == "cuda" and attention_mask is not None:
898
+ query_states = query_states.contiguous()
899
+ key_states = key_states.contiguous()
900
+ value_states = value_states.contiguous()
901
+
902
+ is_causal = True if causal_mask is None and q_len > 1 else False
903
+
904
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
905
+ query_states,
906
+ key_states,
907
+ value_states,
908
+ attn_mask=causal_mask,
909
+ dropout_p=self.attention_dropout if self.training else 0.0,
910
+ is_causal=is_causal,
911
+ )
912
+ attn_output = attn_output.transpose(1, 2).contiguous()
913
+ #attn_output = attn_output.view(bsz, q_len, self.hidden_size)
914
+ attn_output = attn_output.view(bsz, q_len, self.num_heads * self.head_dim)
915
+
916
+ attn_output = self.o_proj(attn_output)
917
+
918
+ return attn_output, None, past_key_value
919
+
920
+
921
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Jamba
922
+ #class JambaFlashAttention2(JambaAttention):
923
+ # Copied from NemotronH
924
+ class SwimbaIFlashAttention2(SwimbaIAttention):
925
+ """
926
+ Jamba flash attention module. This module inherits from `JambaAttention` as the weights of the module stays
927
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
928
+ flash attention and deal with padding tokens in case the input contains any of them.
929
+ """
930
+ def __init__(self, *args, **kwargs):
931
+ super().__init__(*args, **kwargs)
932
+
933
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
934
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
935
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
936
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
937
+
938
+ def forward(
939
+ self,
940
+ hidden_states: torch.Tensor,
941
+ attention_mask: Optional[torch.Tensor] = None,
942
+ position_ids: Optional[torch.LongTensor] = None,
943
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
944
+ output_attentions: bool = False,
945
+ use_cache: bool = False,
946
+ cache_position: Optional[torch.LongTensor] = None,
947
+ **kwargs,
948
+ ):
949
+ bsz, q_len, _ = hidden_states.size()
950
+
951
+ query_states = self.q_proj(hidden_states)
952
+ key_states = self.k_proj(hidden_states)
953
+ value_states = self.v_proj(hidden_states)
954
+
955
+ # Flash attention requires the input to have the shape
956
+ # batch_size x seq_length x head_dim x hidden_dim
957
+ # therefore we just need to keep the original shape
958
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
959
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
960
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
961
+
962
+ if past_key_value is not None:
963
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
964
+
965
+ # repeat k/v heads if n_kv_heads < n_heads
966
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
967
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
968
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
969
+
970
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
971
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
972
+ # cast them back in float16 just to be sure everything works as expected.
973
+ input_dtype = query_states.dtype
974
+ if input_dtype == torch.float32:
975
+ if torch.is_autocast_enabled():
976
+ target_dtype = torch.get_autocast_gpu_dtype()
977
+ # Handle the case where the model is quantized
978
+ elif hasattr(self.config, "_pre_quantization_dtype"):
979
+ target_dtype = self.config._pre_quantization_dtype
980
+ else:
981
+ target_dtype = self.q_proj.weight.dtype
982
+
983
+ logger.warning_once(
984
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
985
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
986
+ f" {target_dtype}."
987
+ )
988
+
989
+ query_states = query_states.to(target_dtype)
990
+ key_states = key_states.to(target_dtype)
991
+ value_states = value_states.to(target_dtype)
992
+
993
+ # Reashape to the expected shape for Flash Attention
994
+ key_states = key_states.transpose(1, 2)
995
+ value_states = value_states.transpose(1, 2)
996
+
997
+ attn_output = _flash_attention_forward(
998
+ query_states,
999
+ key_states,
1000
+ value_states,
1001
+ attention_mask,
1002
+ q_len,
1003
+ dropout=dropout_rate,
1004
+ sliding_window=getattr(self.config, "sliding_window", None),
1005
+ is_causal=self.is_causal,
1006
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
1007
+ )
1008
+
1009
+ #attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
1010
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim).contiguous()
1011
+ attn_output = self.o_proj(attn_output)
1012
+
1013
+ if not output_attentions:
1014
+ attn_weights = None
1015
+
1016
+ return attn_output, attn_weights, past_key_value
1017
+
1018
+
1019
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Jamba
1020
+ #class JambaSdpaAttention(JambaAttention):
1021
+ # Copied from NemotronH
1022
+ class SwimbaISdpaAttention(SwimbaIAttention):
1023
+ """
1024
+ Jamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1025
+ `JambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1026
+ SDPA API.
1027
+ """
1028
+
1029
+ # Adapted from SwimbaIAttention.forward
1030
+ def forward(
1031
+ self,
1032
+ hidden_states: torch.Tensor,
1033
+ attention_mask: Optional[torch.Tensor] = None,
1034
+ position_ids: Optional[torch.LongTensor] = None,
1035
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
1036
+ output_attentions: bool = False,
1037
+ use_cache: bool = False,
1038
+ cache_position: Optional[torch.LongTensor] = None,
1039
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1040
+ if output_attentions:
1041
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1042
+ logger.warning_once(
1043
+ "SwimbaIModel is using SwimbaISdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1044
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
1045
+ )
1046
+ return super().forward(
1047
+ hidden_states=hidden_states,
1048
+ attention_mask=attention_mask,
1049
+ position_ids=position_ids,
1050
+ past_key_value=past_key_value,
1051
+ output_attentions=output_attentions,
1052
+ use_cache=use_cache,
1053
+ )
1054
+
1055
+ bsz, q_len, _ = hidden_states.size()
1056
+
1057
+ query_states = self.q_proj(hidden_states)
1058
+ key_states = self.k_proj(hidden_states)
1059
+ value_states = self.v_proj(hidden_states)
1060
+
1061
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1062
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1063
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1064
+
1065
+ if past_key_value is not None:
1066
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
1067
+
1068
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1069
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1070
+
1071
+ causal_mask = attention_mask
1072
+ if attention_mask is not None:
1073
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
1074
+
1075
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1076
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1077
+ if query_states.device.type == "cuda" and attention_mask is not None:
1078
+ query_states = query_states.contiguous()
1079
+ key_states = key_states.contiguous()
1080
+ value_states = value_states.contiguous()
1081
+
1082
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
1083
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
1084
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
1085
+ is_causal = True if self.is_causal and causal_mask is None and q_len > 1 else False
1086
+
1087
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1088
+ query_states,
1089
+ key_states,
1090
+ value_states,
1091
+ attn_mask=causal_mask,
1092
+ dropout_p=self.attention_dropout if self.training else 0.0,
1093
+ is_causal=is_causal,
1094
+ )
1095
+
1096
+ attn_output = attn_output.transpose(1, 2).contiguous()
1097
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1098
+
1099
+ attn_output = self.o_proj(attn_output)
1100
+
1101
+ return attn_output, None, past_key_value
1102
+
1103
+
1104
+ SWIMBAI_ATTENTION_CLASSES = {
1105
+ "eager": SwimbaIAttention,
1106
+ "flash_attention_2": SwimbaIFlashAttention2,
1107
+ "sdpa": SwimbaISdpaAttention,
1108
+ }
1109
+
1110
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2PreTrainedModel
1111
+ # Copied from NemotronH
1112
+ class SwimbaIPreTrainedModel(PreTrainedModel):
1113
+ """
1114
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1115
+ models.
1116
+ """
1117
+
1118
+ config_class = SwimbaIConfig
1119
+ base_model_prefix = "backbone"
1120
+ _no_split_modules = ["SwimbaIBlock"]
1121
+ supports_gradient_checkpointing = True
1122
+ _is_stateful = True
1123
+
1124
+ def _init_weights(self, module):
1125
+ """Initialize the weights."""
1126
+ if isinstance(module, SwimbaISparseMoEMamba2Mixer):
1127
+ module.A_log._no_weight_decay = True
1128
+ module.D._no_weight_decay = True
1129
+
1130
+ dt = torch.exp(
1131
+ torch.rand(self.config.mamba_num_heads)
1132
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
1133
+ + math.log(self.config.time_step_min)
1134
+ ).clamp(min=self.config.time_step_floor)
1135
+
1136
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
1137
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
1138
+ with torch.no_grad():
1139
+ module.dt_bias.copy_(inv_dt)
1140
+ module.dt_bias._no_reinit = True
1141
+
1142
+ if isinstance(module, nn.Linear):
1143
+ if module.bias is not None:
1144
+ if not getattr(module.bias, "_no_reinit", False):
1145
+ nn.init.zeros_(module.bias)
1146
+ elif isinstance(module, nn.Embedding):
1147
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
1148
+
1149
+ # TODO: Check
1150
+ if self.config.rescale_prenorm_residual:
1151
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
1152
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
1153
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
1154
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
1155
+ #
1156
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
1157
+ for name, p in module.named_parameters():
1158
+ if name in ["out_proj.weight"]:
1159
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
1160
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
1161
+ # We need to reinit p since this code could be called multiple times
1162
+ # Having just p *= scale would repeatedly scale it down
1163
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
1164
+ with torch.no_grad():
1165
+ p /= math.sqrt(self.config.num_hidden_layers)
1166
+
1167
+
1168
+ @dataclass
1169
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2Output with MAMBA2->SwimbaI,Mamba2->SwimbaI
1170
+ # Copied from NemotronH
1171
+ class SwimbaIOutput(ModelOutput):
1172
+ """
1173
+ Class for the SwimbaI model outputs.
1174
+
1175
+ Args:
1176
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1177
+ Sequence of hidden-states at the output of the last layer of the model.
1178
+ cache_params (`HybridMambaAttentionDynamicCache`):
1179
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1180
+ avoid providing the old `input_ids`.
1181
+
1182
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1183
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1184
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1185
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1186
+
1187
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1188
+ """
1189
+
1190
+ last_hidden_state: Optional[torch.FloatTensor] = None
1191
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1192
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1193
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1194
+ router_logits: Optional[Tuple[torch.FloatTensor]] = None
1195
+
1196
+
1197
+ @dataclass
1198
+ # Copied from transformers.models.mamba2.modeling_mamba2.MambaCausalLMOutput with Mamba2->SwimbaI
1199
+ # Copied from NemotronH
1200
+ class SwimbaICausalLMOutput(ModelOutput):
1201
+ """
1202
+ Base class for causal language model (or autoregressive) outputs.
1203
+
1204
+ Args:
1205
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1206
+ Language modeling loss (for next-token prediction).
1207
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1208
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1209
+ cache_params (`HybridMambaAttentionDynamicCache`):
1210
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1211
+ avoid providing the old `input_ids`.
1212
+
1213
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1214
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1215
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1216
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1217
+
1218
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1219
+ """
1220
+
1221
+ loss: Optional[torch.FloatTensor] = None
1222
+ logits: Optional[torch.FloatTensor] = None
1223
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1224
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1225
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1226
+ aux_loss: Optional[torch.FloatTensor] = None
1227
+ router_logits: Optional[Tuple[torch.FloatTensor]] = None
1228
+
1229
+
1230
+ SWIMBAI_START_DOCSTRING = r"""
1231
+
1232
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1233
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1234
+ etc.)
1235
+
1236
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1237
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1238
+ and behavior.
1239
+
1240
+ Parameters:
1241
+ config ([`SwimbaIConfig`]): Model configuration class with all the parameters of the model.
1242
+ Initializing with a config file does not load the weights associated with the model, only the
1243
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1244
+ """
1245
+
1246
+ SWIMBAI_INPUTS_DOCSTRING = r"""
1247
+ Args:
1248
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
1249
+ Indices of input sequence tokens in the vocabulary.
1250
+
1251
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
1252
+ `input_ids`.
1253
+
1254
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1255
+ [`PreTrainedTokenizer.__call__`] for details.
1256
+
1257
+ [What are input IDs?](../glossary#input-ids)
1258
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1259
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1260
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1261
+ model's internal embedding lookup matrix.
1262
+ position_ids (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1263
+ Indices of positions of each input sequence tokens in the position embeddings.
1264
+ cache_params (`HybridMambaAttentionDynamicCache`, *optional*):
1265
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
1266
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
1267
+ use_cache (`bool`, *optional*):
1268
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
1269
+ output_attentions (`bool`, *optional*):
1270
+ Whether or not to return the attentions tensors of all attention layers.
1271
+ output_hidden_states (`bool`, *optional*):
1272
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1273
+ more detail.
1274
+ return_dict (`bool`, *optional*):
1275
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1276
+ cache_position (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1277
+ The position of the current input in the cache. This is used to ensure that the cache is correctly updated.
1278
+ If `cache_params` is passed, `cache_position` should also be passed.
1279
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1280
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1281
+
1282
+ - 1 for tokens that are **not masked**,
1283
+ - 0 for tokens that are **masked**.
1284
+
1285
+ [What are attention masks?](../glossary#attention-mask)
1286
+ """
1287
+
1288
+
1289
+ @add_start_docstrings(
1290
+ "The bare SwimbaI Model transformer outputting raw hidden-states without any specific head on top.",
1291
+ SWIMBAI_START_DOCSTRING,
1292
+ )
1293
+ # Copied from NemotronH
1294
+ class SwimbaIModel(SwimbaIPreTrainedModel):
1295
+ def __init__(self, config):
1296
+ super().__init__(config)
1297
+
1298
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
1299
+ self.layers = nn.ModuleList([SwimbaIBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
1300
+
1301
+ self.gradient_checkpointing = False
1302
+ self.norm_f = SwimbaIRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1303
+ # Initialize weights and apply final processing
1304
+ self._register_load_state_dict_pre_hook(self.load_hook)
1305
+ self.post_init()
1306
+
1307
+ def load_hook(self, state_dict, prefix, *args):
1308
+ for k in state_dict:
1309
+ if "embedding." in k:
1310
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
1311
+ break
1312
+
1313
+ def get_input_embeddings(self):
1314
+ return self.embeddings
1315
+
1316
+ def set_input_embeddings(self, new_embeddings):
1317
+ self.embeddings = new_embeddings
1318
+
1319
+ @add_start_docstrings_to_model_forward(SWIMBAI_INPUTS_DOCSTRING)
1320
+ @add_code_sample_docstrings(
1321
+ checkpoint=_CHECKPOINT_FOR_DOC,
1322
+ output_type=SwimbaIOutput,
1323
+ config_class=_CONFIG_FOR_DOC,
1324
+ )
1325
+ def forward(
1326
+ self,
1327
+ input_ids: Optional[torch.LongTensor] = None,
1328
+ inputs_embeds: Optional[torch.LongTensor] = None,
1329
+ position_ids: Optional[torch.LongTensor] = None,
1330
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1331
+ use_cache: Optional[bool] = None,
1332
+ output_attentions: Optional[bool] = None,
1333
+ output_hidden_states: Optional[bool] = None,
1334
+ output_router_logits: Optional[bool] = None,
1335
+ return_dict: Optional[bool] = None,
1336
+ cache_position: Optional[torch.LongTensor] = None,
1337
+ attention_mask: Optional[torch.Tensor] = None,
1338
+ **kwargs,
1339
+ ) -> Union[Tuple, SwimbaIOutput]:
1340
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1341
+ output_hidden_states = (
1342
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1343
+ )
1344
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
1345
+ output_router_logits = (
1346
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1347
+ )
1348
+
1349
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1350
+
1351
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
1352
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1353
+
1354
+ if inputs_embeds is None:
1355
+ inputs_embeds = self.embeddings(input_ids)
1356
+
1357
+ if self.gradient_checkpointing and self.training and use_cache:
1358
+ logger.warning_once(
1359
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1360
+ )
1361
+ use_cache = False
1362
+
1363
+ # From zamba_modeling.py
1364
+ if use_cache and cache_params is None:
1365
+ logger.warning_once(
1366
+ "SwimbaI requires an initialized `SwimbaIHybridDynamicCache` to return a cache. None was "
1367
+ "provided, so no cache will be returned."
1368
+ )
1369
+
1370
+ hidden_states = inputs_embeds
1371
+
1372
+ if cache_position is None:
1373
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
1374
+ if position_ids is None:
1375
+ position_ids = cache_position.unsqueeze(0)
1376
+
1377
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
1378
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
1379
+
1380
+ all_hidden_states = () if output_hidden_states else None
1381
+ all_self_attns = () if output_attentions else None
1382
+ all_router_logits = () if output_router_logits else None
1383
+
1384
+ for layer_idx, mixer_block in enumerate(self.layers):
1385
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
1386
+ if mixer_block.block_type == "mamba":
1387
+ layer_mask = mamba_mask
1388
+ elif mixer_block.block_type == "attention":
1389
+ layer_mask = causal_mask
1390
+ elif mixer_block.block_type == "mlp":
1391
+ layer_mask = None
1392
+ else:
1393
+ raise ValueError(f"Invalid block_type: {self.block_type}")
1394
+
1395
+ if output_hidden_states:
1396
+ all_hidden_states += (hidden_states,)
1397
+
1398
+ if self.gradient_checkpointing and self.training:
1399
+ layer_outputs = self._gradient_checkpointing_func(
1400
+ mixer_block.__call__, hidden_states, cache_params, cache_position, layer_mask, output_router_logits, use_cache
1401
+ )
1402
+ else:
1403
+ layer_outputs = mixer_block(
1404
+ hidden_states,
1405
+ cache_params=cache_params,
1406
+ cache_position=cache_position,
1407
+ attention_mask=layer_mask,
1408
+ output_router_logits=output_router_logits,
1409
+ use_cache=use_cache,
1410
+ )
1411
+
1412
+ hidden_states = layer_outputs[0]
1413
+ if output_router_logits and layer_outputs[1] is not None:
1414
+ all_router_logits += (layer_outputs[1],)
1415
+
1416
+ hidden_states = self.norm_f(hidden_states)
1417
+
1418
+ if output_hidden_states:
1419
+ all_hidden_states = all_hidden_states + (hidden_states,)
1420
+
1421
+ if not return_dict:
1422
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states, all_self_attns, all_router_logits] if v is not None)
1423
+
1424
+ return SwimbaIOutput(
1425
+ last_hidden_state=hidden_states,
1426
+ cache_params=cache_params if use_cache else None,
1427
+ hidden_states=all_hidden_states,
1428
+ attentions=all_self_attns,
1429
+ router_logits=all_router_logits,
1430
+ )
1431
+
1432
+ # Copied from transformers.models.jamba.modeling_jamba.JambaModel._update_causal_mask
1433
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
1434
+ if self.config._attn_implementation == "flash_attention_2":
1435
+ if attention_mask is not None and 0.0 in attention_mask:
1436
+ return attention_mask
1437
+ return None
1438
+
1439
+ dtype, device = input_tensor.dtype, input_tensor.device
1440
+ min_dtype = torch.finfo(dtype).min
1441
+ sequence_length = input_tensor.shape[1]
1442
+ target_length = cache_position[-1] + 1
1443
+
1444
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1445
+ if sequence_length != 1:
1446
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1447
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1448
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1449
+ if attention_mask is not None:
1450
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1451
+ if attention_mask.dim() == 2:
1452
+ mask_length = attention_mask.shape[-1]
1453
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1454
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1455
+
1456
+ if (
1457
+ self.config._attn_implementation == "sdpa"
1458
+ and attention_mask is not None
1459
+ and attention_mask.device.type == "cuda"
1460
+ ):
1461
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1462
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1463
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1464
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1465
+
1466
+ return causal_mask
1467
+
1468
+ def _update_mamba_mask(self, attention_mask, cache_position):
1469
+ """
1470
+ No need for zeroing states when
1471
+ 1. Cached forward
1472
+ 2. Attending to all inputs
1473
+ """
1474
+ mamba_mask = attention_mask
1475
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1476
+ mamba_mask = None
1477
+ return mamba_mask
1478
+
1479
+
1480
+ @add_start_docstrings(
1481
+ """
1482
+ The SWIMBAI Model transformer with a language modeling head on top (linear layer with weights not tied to the input
1483
+ embeddings).
1484
+ """,
1485
+ SWIMBAI_START_DOCSTRING,
1486
+ )
1487
+ # Copied from NemotronH
1488
+ class SwimbaIForCausalLM(SwimbaIPreTrainedModel, GenerationMixin):
1489
+ _tied_weights_keys = ["lm_head.weight"]
1490
+
1491
+ def __init__(self, config):
1492
+ super().__init__(config)
1493
+ self.backbone = SwimbaIModel(config)
1494
+ self.vocab_size = config.vocab_size
1495
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1496
+
1497
+ # MoE config
1498
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1499
+ self.num_experts = config.num_experts
1500
+ self.num_experts_per_tok = config.num_experts_per_tok
1501
+
1502
+ # Initialize weights and apply final processing
1503
+ self.post_init()
1504
+
1505
+ def get_input_embeddings(self):
1506
+ return self.backbone.get_input_embeddings()
1507
+
1508
+ def set_input_embeddings(self, new_embeddings):
1509
+ return self.backbone.set_input_embeddings(new_embeddings)
1510
+
1511
+ def get_output_embeddings(self):
1512
+ return self.lm_head
1513
+
1514
+ def set_output_embeddings(self, new_embeddings):
1515
+ self.lm_head = new_embeddings
1516
+
1517
+ def get_decoder(self):
1518
+ return self.model
1519
+
1520
+ def set_decoder(self, decoder):
1521
+ self.model = decoder
1522
+
1523
+ def prepare_inputs_for_generation(
1524
+ self,
1525
+ input_ids,
1526
+ past_key_values=None,
1527
+ attention_mask=None,
1528
+ inputs_embeds=None,
1529
+ cache_position=None,
1530
+ position_ids=None,
1531
+ use_cache=True,
1532
+ **kwargs,
1533
+ ):
1534
+ # Copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
1535
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
1536
+ empty_past_kv = past_key_values is None
1537
+
1538
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1539
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1540
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1541
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
1542
+ # (we can't check exception 3 while compiling)
1543
+ if not empty_past_kv:
1544
+ if (
1545
+ inputs_embeds is not None # Exception 1
1546
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
1547
+ ):
1548
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1549
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1550
+ input_ids = input_ids[:, cache_position]
1551
+ else:
1552
+ past_key_values = HybridMambaAttentionDynamicCache(
1553
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1554
+ )
1555
+
1556
+ if attention_mask is not None and position_ids is None:
1557
+ # create position_ids on the fly for batch generation
1558
+ position_ids = attention_mask.long().cumsum(-1) - 1
1559
+ position_ids.masked_fill_(attention_mask == 0, 1)
1560
+ if not empty_past_kv:
1561
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1562
+
1563
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1564
+ if inputs_embeds is not None and empty_past_kv:
1565
+ model_inputs = {"inputs_embeds": inputs_embeds}
1566
+ else:
1567
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1568
+
1569
+ model_inputs.update(
1570
+ {
1571
+ "position_ids": position_ids,
1572
+ "past_key_values": past_key_values,
1573
+ "use_cache": use_cache,
1574
+ "attention_mask": attention_mask,
1575
+ "logits_to_keep": self.config.num_logits_to_keep,
1576
+ "cache_position": cache_position,
1577
+ }
1578
+ )
1579
+ return model_inputs
1580
+
1581
+ @add_start_docstrings_to_model_forward(SWIMBAI_INPUTS_DOCSTRING)
1582
+ @add_code_sample_docstrings(
1583
+ checkpoint=_CHECKPOINT_FOR_DOC,
1584
+ output_type=SwimbaICausalLMOutput,
1585
+ config_class=_CONFIG_FOR_DOC,
1586
+ )
1587
+ def forward(
1588
+ self,
1589
+ input_ids: Optional[torch.LongTensor] = None,
1590
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1591
+ position_ids: Optional[torch.LongTensor] = None,
1592
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1593
+ labels: Optional[torch.LongTensor] = None,
1594
+ output_attentions: Optional[bool] = None,
1595
+ output_hidden_states: Optional[bool] = None,
1596
+ output_router_logits: Optional[bool] = None,
1597
+ return_dict: Optional[bool] = None,
1598
+ use_cache: Optional[bool] = None,
1599
+ cache_position: Optional[torch.Tensor] = None,
1600
+ attention_mask: Optional[torch.Tensor] = None,
1601
+ **kwargs, # for now we need this for generation
1602
+ ) -> Union[Tuple, SwimbaICausalLMOutput]:
1603
+ r"""
1604
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1605
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1606
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1607
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1608
+ """
1609
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1610
+ output_router_logits = (
1611
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1612
+ )
1613
+ output_hidden_states = (
1614
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1615
+ )
1616
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1617
+
1618
+ swimba_i_outputs = self.backbone(
1619
+ input_ids,
1620
+ cache_params=cache_params,
1621
+ inputs_embeds=inputs_embeds,
1622
+ output_attentions=output_attentions,
1623
+ output_hidden_states=output_hidden_states,
1624
+ output_router_logits=output_router_logits,
1625
+ return_dict=return_dict,
1626
+ use_cache=use_cache,
1627
+ cache_position=cache_position,
1628
+ attention_mask=attention_mask,
1629
+ )
1630
+ hidden_states = swimba_i_outputs[0]
1631
+
1632
+ # TODO: Check zamba_modeling.py: https://github.com/huggingface/transformers/blob/d7188ba600e36d3fd191b12e19f1b3bb81a8404f/src/transformers/models/zamba/modeling_zamba.py#L1284C1-L1286C2
1633
+ #logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1634
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1635
+
1636
+ loss = None
1637
+ if labels is not None:
1638
+ # move labels to correct device to enable model parallelism
1639
+ labels = labels.to(logits.device)
1640
+ # Shift so that tokens < n predict n
1641
+ shift_logits = logits[..., :-1, :].contiguous()
1642
+ shift_labels = labels[..., 1:].contiguous()
1643
+ # Flatten the tokens
1644
+ loss_fct = CrossEntropyLoss()
1645
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1646
+
1647
+ aux_loss = None
1648
+ if output_router_logits:
1649
+ # Copied from Olmoe
1650
+ aux_loss = load_balancing_loss_func(
1651
+ swimba_i_outputs.router_logits if return_dict else swimba_i_outputs[-1],
1652
+ self.num_experts,
1653
+ self.num_experts_per_tok,
1654
+ attention_mask,
1655
+ )
1656
+ if labels is not None:
1657
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device)
1658
+
1659
+ if not return_dict:
1660
+ output = (logits,) + swimba_i_outputs[1:]
1661
+ if output_router_logits:
1662
+ output = (aux_loss,) + output
1663
+ return (loss,) + output if loss is not None else output
1664
+
1665
+ return SwimbaICausalLMOutput(
1666
+ loss=loss,
1667
+ logits=logits,
1668
+ cache_params=swimba_i_outputs.cache_params,
1669
+ hidden_states=swimba_i_outputs.hidden_states,
1670
+ attentions=swimba_i_outputs.attentions,
1671
+ aux_loss=aux_loss,
1672
+ router_logits=swimba_i_outputs.router_logits,
1673
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3277c00fe5fb3963b3cb7c07b7f183722d2af4d775a4aea7cfb3684d7cccbc2f
3
+ size 17078330
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff