edwko commited on
Commit
7eba6c9
1 Parent(s): 38bb2fc

Upload 9 files

Browse files
config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "A_initializer_range": [
3
+ 1,
4
+ 16
5
+ ],
6
+ "_name_or_path": "OuteAI/Lite-Oute-2-Mamba2Attn-Base",
7
+ "architectures": [
8
+ "Mamba2ForCausalLM"
9
+ ],
10
+ "attention_conv_kernel": 4,
11
+ "attention_head_dim": 128,
12
+ "attention_layers_idx": [
13
+ 6,
14
+ 12,
15
+ 18,
16
+ 24
17
+ ],
18
+ "auto_map": {
19
+ "AutoConfig": "configuration_mamba2attn.Mamba2Config",
20
+ "AutoModelForCausalLM": "modeling_mamba2attn.Mamba2ForCausalLM"
21
+ },
22
+ "bos_token_id": 1,
23
+ "chunk_size": 256,
24
+ "classifier_dropout": 0.1,
25
+ "conv_initializer_range": null,
26
+ "emb_initializer_range": 0.02,
27
+ "eos_token_id": 2,
28
+ "expand": 2,
29
+ "hidden_act": "silu",
30
+ "hidden_size": 1024,
31
+ "intermediate_size": 2048,
32
+ "layer_norm_epsilon": 1e-05,
33
+ "mamba2_conv_kernel": 4,
34
+ "mamba2_head_dim": 64,
35
+ "mamba2_num_heads": 32,
36
+ "max_position_embeddings": 8192,
37
+ "mlp_intermediate_size": 0,
38
+ "mlp_padding_size": 128,
39
+ "model_type": "mamba2",
40
+ "num_attention_heads": 16,
41
+ "num_hidden_layers": 32,
42
+ "num_key_value_heads": 16,
43
+ "pad_token_id": 0,
44
+ "rescale_prenorm_residual": false,
45
+ "residual_in_fp32": true,
46
+ "rope_emb_dim": 64,
47
+ "rope_scaling": null,
48
+ "rope_theta": 10000.0,
49
+ "state_size": 128,
50
+ "tie_embedding_weights": true,
51
+ "time_step_floor": 0.0001,
52
+ "time_step_limit": [
53
+ 0.0,
54
+ Infinity
55
+ ],
56
+ "time_step_max": 0.1,
57
+ "time_step_min": 0.001,
58
+ "torch_dtype": "float32",
59
+ "transformers_version": "4.44.2",
60
+ "use_attention_out_bias": false,
61
+ "use_attention_qkv_bias": false,
62
+ "use_cache": true,
63
+ "use_conv_bias": true,
64
+ "use_mamba2_bias": false,
65
+ "use_mlp_bias": false,
66
+ "vocab_size": 32768
67
+ }
configuration_mamba2attn.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Implementation from: https://github.com/huggingface/transformers/pull/32027
17
+
18
+ """MAMBA2 configuration"""
19
+
20
+ from typing import List
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class Mamba2Config(PretrainedConfig):
30
+ """
31
+ This is the configuration class to store the configuration of a [`Mamba2Model`]. It is used to instantiate a MAMBA2
32
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
33
+ defaults will yield a similar configuration to that of the MAMBA2
34
+ [state-spaces/mamba2-130m](https://huggingface.co/state-spaces/mamba2-130m) architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 50280):
42
+ Vocabulary size of the MAMBA2 model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`Mamba2Model`].
44
+ pad_token_id (`int`, *optional*, defaults to 0):
45
+ Padding token id.
46
+ bos_token_id (`int`, *optional*, defaults to 0):
47
+ The id of the beginning of sentence token in the vocabulary.
48
+ eos_token_id (`int`, *optional*, defaults to 0):
49
+ The id of the end of sentence token in the vocabulary.
50
+ hidden_size (`int`, *optional*, defaults to 768):
51
+ Dimensionality of the embeddings and hidden states.
52
+ state_size (`int`, *optional*, defaults to 128):
53
+ Shape of the state space latents.
54
+ expand (`int`, *optional*, defaults to 2):
55
+ Expanding factor used to determine the intermediate size.
56
+ chunk_size (`int`, *optional*, defaults to 256):
57
+ Block / Chunk size for the HW-efficient algorithm which parallelizes on intra- and inter-chunk calculations.
58
+ mamba2_conv_kernel (`int`, *optional*, defaults to 4):
59
+ Size of the convolution kernel in the mamba2 mixer.
60
+ attention_conv_kernel (`int`, *optional*, defaults to 4):
61
+ Size of the convolution kernel in the attention block.
62
+ mlp_intermediate_size (`int`, *optional*, defaults to 0):
63
+ Dimensionality of up-projections within the MLP blocks. If set to <=0, then MLP blocks are disabled.
64
+ mlp_padding_size (`int`, *optional*, defaults to 128):
65
+ Padding `mlp_intermediate_size` to a multiple of this.
66
+ mamba2_head_dim (`int`, *optional*, defaults to 64):
67
+ Multi-input SSM head dimension.
68
+ attention_head_dim (`int`, *optional*, defaults to 128):
69
+ Multi-head attention's head dimension.
70
+ num_attention_heads (`int`, *optional*, defaults to 30):
71
+ The number of heads in multi-head attention.
72
+ num_key_value_heads (`int`, *optional*, defaults to 30):
73
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
74
+ `attention_num_key_value_heads=attention_num_heads`, the model will use Multi Head Attention (MHA), if
75
+ `attention_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
76
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
77
+ by meanpooling all the original heads within that group. For more details checkout [this
78
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `attention_num_heads`.
79
+ num_hidden_layers (`int`, *optional*, defaults to 24):
80
+ Number of hidden layers in the model.
81
+ attention_layers_idx (`List[int]`, *optional*, defaults to `[]`):
82
+ The specific layers that exchange the mamba2 mixer block with the attention equivalent.
83
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
84
+ The epsilon to use in the layer normalization layers.
85
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
86
+ Whether or not to use bias in the convolution layer of the mixer block.
87
+ use_mlp_bias (`bool`, *optional*, defaults to `False`):
88
+ Whether or not to use a bias in the up- and downprojections of the MLP block.
89
+ use_mamba2_bias (`bool`, *optional*, defaults to `False`):
90
+ Whether or not to use bias in ["in_proj", "out_proj"] of the mamba2 mixer block.
91
+ use_attention_qkv_bias (`bool`, *optional*, defaults to `False`):
92
+ Whether or not to use bias in the qkv projection of the attention block.
93
+ use_attention_out_bias (`bool`, *optional*, defaults to `False`):
94
+ Whether or not to use bias in the out projection of the attention block.
95
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
96
+ The non-linear activation function (function or string) in the decoder.
97
+ emb_initializer_range (`float`, *optional*, defaults to 0.02):
98
+ The standard deviation of the truncated_normal_initializer for initializing the embedding weight matrix.
99
+ conv_initializer_range (`float`, *optional*):
100
+ The range for uniformly initializing the convolution weights.
101
+ A_initializer_range (`List[int]`, *optional*, defaults to `[1, 16]`):
102
+ The range for uniformly initializing the 1-SS(a) scalar.
103
+ time_step_min (`float`, *optional*, defaults to 0.001):
104
+ Minimum `time_step` used to bound `dt_proj.bias`.
105
+ time_step_max (`float`, *optional*, defaults to 0.1):
106
+ Maximum `time_step` used to bound `dt_proj.bias`.
107
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
108
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
109
+ time_step_limit (`List[float]`, *optional*, defaults to `[0.0, inf]`):
110
+ Clapping values for the dt weights.
111
+ residual_in_fp32 (`bool`, *optional*, defaults to `True`):
112
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model
113
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `False`):
114
+ Whether or not to rescale `out_proj` weights when initializing.
115
+ rope_emb_dim (`int`, *optional*, defaults to 64):
116
+ Embedding dimension of the RoPE embeddings.
117
+ rope_theta (`float`, *optional*, defaults to 10000.0):
118
+ The base period of the RoPE embeddings.
119
+ rope_scaling (`Dict`, *optional*):
120
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
121
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
122
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
123
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
124
+ these scaling strategies behave:
125
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
126
+ experimental feature, subject to breaking API changes in future versions.
127
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
128
+ The maximum sequence length that this model might ever be used with. This is based on the context length the
129
+ Mamba2 models have been trained on. Also necessary when using any sort of RoPE embeddings.
130
+ tie_embedding_weights (`bool`, *optional*, defaults to `True`):
131
+ Whether or not to tie the lm head to the input embeddings.
132
+ use_cache (`bool`, *optional*, defaults to `True`):
133
+ Whether or not the cache should be used.
134
+ classifier_dropout (`float`, *optional*, defaults to 0.1):
135
+ The dropout ratio for the classification head in [`Mamba2ForSequenceClassification`] model.
136
+
137
+ Example:
138
+
139
+ ```python
140
+ >>> from transformers import Mamba2Config, Mamba2Model
141
+
142
+ >>> # Initializing a Mamba2 configuration
143
+ >>> configuration = Mamba2Config()
144
+
145
+ >>> # Initializing a model (with random weights) from the configuration
146
+ >>> model = Mamba2Model(configuration)
147
+
148
+ >>> # Accessing the model configuration
149
+ >>> configuration = model.config
150
+ ```
151
+ """
152
+
153
+ model_type = "mamba2"
154
+ keys_to_ignore_at_inference = ["past_key_values"]
155
+
156
+ def __init__(
157
+ self,
158
+ vocab_size=50280,
159
+ pad_token_id=0,
160
+ bos_token_id=0,
161
+ eos_token_id=0,
162
+ hidden_size=768,
163
+ state_size=128,
164
+ expand=2,
165
+ chunk_size=256,
166
+ mamba2_conv_kernel=4,
167
+ attention_conv_kernel=4,
168
+ mlp_intermediate_size=0,
169
+ mlp_padding_size=128,
170
+ mamba2_head_dim=64,
171
+ attention_head_dim=128,
172
+ num_attention_heads=30,
173
+ num_key_value_heads=30,
174
+ num_hidden_layers=24,
175
+ attention_layers_idx=None,
176
+ layer_norm_epsilon=1e-5,
177
+ use_conv_bias=True,
178
+ use_mlp_bias=False,
179
+ use_mamba2_bias=False,
180
+ use_attention_qkv_bias=False,
181
+ use_attention_out_bias=False,
182
+ hidden_act="silu",
183
+ emb_initializer_range=0.02,
184
+ conv_initializer_range=None,
185
+ A_initializer_range=None,
186
+ time_step_min=0.001,
187
+ time_step_max=0.1,
188
+ time_step_floor=1e-4,
189
+ time_step_limit=None,
190
+ residual_in_fp32=True,
191
+ rescale_prenorm_residual=False,
192
+ rope_emb_dim=64,
193
+ rope_theta=10000.0,
194
+ rope_scaling=None,
195
+ max_position_embeddings=2048,
196
+ tie_embedding_weights=True,
197
+ use_cache=True,
198
+ classifier_dropout=0.1,
199
+ **kwargs,
200
+ ):
201
+ # Avoid mutable default args
202
+ attention_layers_idx = [] if attention_layers_idx is None else attention_layers_idx
203
+ A_initializer_range = [1, 16] if A_initializer_range is None else A_initializer_range
204
+ time_step_limit = [0.0, float("inf")] if time_step_limit is None else time_step_limit
205
+
206
+ self.vocab_size = vocab_size
207
+ self.pad_token_id = pad_token_id
208
+ self.bos_token_id = bos_token_id
209
+ self.eos_token_id = eos_token_id
210
+ self.hidden_size = hidden_size
211
+ self.state_size = state_size
212
+ self.expand = expand
213
+ self.intermediate_size = int(expand * self.hidden_size)
214
+ self.chunk_size = chunk_size
215
+ self.mamba2_conv_kernel = mamba2_conv_kernel
216
+ self.attention_conv_kernel = attention_conv_kernel
217
+ self.mlp_padding_size = mlp_padding_size
218
+ self.mlp_intermediate_size = mlp_intermediate_size
219
+ self.mamba2_head_dim = mamba2_head_dim
220
+ self.mamba2_num_heads = self.intermediate_size // self.mamba2_head_dim
221
+ self.attention_head_dim = attention_head_dim
222
+ self.num_attention_heads = num_attention_heads
223
+ self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
224
+ self.num_hidden_layers = num_hidden_layers
225
+ self.attention_layers_idx = attention_layers_idx
226
+ self._attention_layers_idx_validation()
227
+ self.layer_norm_epsilon = layer_norm_epsilon
228
+ self.use_conv_bias = use_conv_bias
229
+ self.use_mlp_bias = use_mlp_bias
230
+ self.use_mamba2_bias = use_mamba2_bias
231
+ self.use_attention_qkv_bias = use_attention_qkv_bias
232
+ self.use_attention_out_bias = use_attention_out_bias
233
+ self.hidden_act = hidden_act
234
+ self.emb_initializer_range = emb_initializer_range
235
+ self.conv_initializer_range = conv_initializer_range
236
+ self.A_initializer_range = A_initializer_range
237
+ self.time_step_min = time_step_min
238
+ self.time_step_max = time_step_max
239
+ self.time_step_floor = time_step_floor
240
+ self.time_step_limit = time_step_limit
241
+ self.residual_in_fp32 = residual_in_fp32
242
+ self.rescale_prenorm_residual = rescale_prenorm_residual
243
+ self.rope_emb_dim = rope_emb_dim
244
+ self.rope_theta = rope_theta
245
+ self.rope_scaling = rope_scaling
246
+ if self.rope_emb_dim > 0:
247
+ self._rope_scaling_validation()
248
+ self.max_position_embeddings = max_position_embeddings
249
+ self.tie_embedding_weights = tie_embedding_weights
250
+ self.use_cache = use_cache
251
+ self.classifier_dropout = classifier_dropout
252
+
253
+ super().__init__(
254
+ bos_token_id=bos_token_id,
255
+ eos_token_id=eos_token_id,
256
+ pad_token_id=pad_token_id,
257
+ tie_embedding_weights=tie_embedding_weights,
258
+ **kwargs,
259
+ )
260
+
261
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
262
+ def _rope_scaling_validation(self):
263
+ """
264
+ Validate the `rope_scaling` configuration.
265
+ """
266
+ if self.rope_scaling is None:
267
+ return
268
+
269
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
270
+ raise ValueError(
271
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
272
+ )
273
+ rope_scaling_type = self.rope_scaling.get("type", None)
274
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
275
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
276
+ raise ValueError(
277
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
278
+ )
279
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
280
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
281
+
282
+ def _attention_layers_idx_validation(self):
283
+ """
284
+ Validate the `attention_layers_idx` configuration.
285
+ """
286
+ if isinstance(self.attention_layers_idx, list) and len(self.attention_layers_idx) == 0:
287
+ return
288
+
289
+ if not isinstance(self.attention_layers_idx, List) and all(
290
+ isinstance(x, int) for x in self.attention_layers_idx
291
+ ):
292
+ raise ValueError(
293
+ "`attention_layers_idx` must be a list of integers indicating the attention layers, "
294
+ f"got {self.attention_layers_idx}"
295
+ )
296
+
297
+ if min(self.attention_layers_idx) < 0 or max(self.attention_layers_idx) >= self.num_hidden_layers:
298
+ raise ValueError(
299
+ "`attention_layers_idx` has out-of-range indices, "
300
+ f"got {self.attention_layers_idx}, but expected indices in {list(range(self.num_hidden_layers))}"
301
+ )
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.44.2"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f180a1f218b19ad4a3986698893de8b773c11a7d3065d7a4b7adaf26e4babb3
3
+ size 1008294800
modeling_mamba2attn.py ADDED
@@ -0,0 +1,2020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 state-spaces/mamba org and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Implementation from: https://github.com/huggingface/transformers/pull/32027
17
+
18
+ """PyTorch MAMBA2 model."""
19
+
20
+ import math
21
+ from typing import Any, Dict, List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from packaging import version
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ SequenceClassifierOutputWithPast,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from transformers.utils.import_utils import (
47
+ get_torch_version,
48
+ is_causal_conv1d_available,
49
+ is_flash_attn_2_available,
50
+ is_flash_attn_greater_or_equal_2_10,
51
+ )
52
+ from .configuration_mamba2attn import Mamba2Config
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ if is_flash_attn_2_available():
58
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
59
+
60
+ try:
61
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
62
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
63
+ except:
64
+ selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined = None, None, None
65
+
66
+ try:
67
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
68
+ except:
69
+ causal_conv1d_update, causal_conv1d_fn = None, None
70
+
71
+ is_fast_path_available = all(
72
+ (
73
+ selective_state_update,
74
+ mamba_chunk_scan_combined,
75
+ mamba_split_conv1d_scan_combined,
76
+ causal_conv1d_fn,
77
+ causal_conv1d_update,
78
+ )
79
+ )
80
+
81
+
82
+ _CONFIG_FOR_DOC = "MambaConfig"
83
+
84
+
85
+ # Adapted from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache with Mamba->Mamba2
86
+ class HybridMamba2AttentionDynamicCache(DynamicCache):
87
+ """
88
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba2 cache
89
+ (which has a constant shape regardless of seq_len).
90
+
91
+ This cache has two sets of lists of tensors: `key_cache`, `value_cache`, and 'conv_states' for attention cache and
92
+ `conv_states` and `ssm_states` for mamba2 cache. Each of these lists has `num_layers` tensors.
93
+
94
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_key_value_heads, seq_len, attention_head_dim)`,
95
+ while `conv_states` has a shape of `(batch_size, attention_head_dim * (num_attention_heads + 2 * num_key_value_heads), attention_conv_kernel)`
96
+ or `(batch_size, 0)` (empty tensors) and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
97
+
98
+ For mamba2 layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
99
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, intermediate_size + 2 * state_size, mamba2_conv_kernel)`,
100
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, mamba2_num_heads, mamba2_head_dim, state_size)`.
101
+ """
102
+
103
+ def __init__(self, config, batch_size, dtype=torch.float16, device=None):
104
+ self.dtype = dtype
105
+ self.has_previous_state = False
106
+
107
+ in_channels = config.intermediate_size + 2 * config.state_size
108
+ ssm_state_size = config.state_size
109
+ mamba2_conv_kernel_size = config.mamba2_conv_kernel
110
+ attention_conv_kernel_size = config.attention_conv_kernel
111
+ mamba2_num_heads = config.mamba2_num_heads
112
+ mamba2_head_dim = config.mamba2_head_dim
113
+ attention_head_dim = config.attention_head_dim
114
+ attention_num_heads = config.num_attention_heads
115
+ attention_num_heads_kv = config.num_key_value_heads
116
+ attention_qkv_dim = attention_head_dim * (attention_num_heads + 2 * attention_num_heads_kv)
117
+
118
+ self.conv_states = []
119
+ self.ssm_states = []
120
+ self.transformer_layers = []
121
+ for i in range(config.num_hidden_layers):
122
+ if i not in config.attention_layers_idx:
123
+ self.conv_states += [
124
+ torch.zeros(batch_size, in_channels, mamba2_conv_kernel_size, device=device, dtype=dtype)
125
+ ]
126
+ self.ssm_states += [
127
+ torch.zeros(
128
+ batch_size, mamba2_num_heads, mamba2_head_dim, ssm_state_size, device=device, dtype=dtype
129
+ )
130
+ ]
131
+ else:
132
+ # Conv1d is optional for the attention layer
133
+ if attention_conv_kernel_size > 0:
134
+ self.conv_states += [
135
+ torch.zeros(
136
+ batch_size, attention_qkv_dim, attention_conv_kernel_size, device=device, dtype=dtype
137
+ )
138
+ ]
139
+ else:
140
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
141
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
142
+ self.transformer_layers.append(i)
143
+
144
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
145
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
146
+
147
+ # Copied from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.update
148
+ def update(
149
+ self,
150
+ key_states: torch.Tensor,
151
+ value_states: torch.Tensor,
152
+ layer_idx: int,
153
+ cache_kwargs: Optional[Dict[str, Any]] = None,
154
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
155
+ # Update the cache
156
+ if self.key_cache[layer_idx].shape[-1] == 0:
157
+ self.key_cache[layer_idx] = key_states
158
+ self.value_cache[layer_idx] = value_states
159
+ else:
160
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
161
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
162
+
163
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
164
+
165
+ # Copied from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.reorder_cache
166
+ def reorder_cache(self, beam_idx: torch.LongTensor):
167
+ """Reorders the cache for beam search, given the selected beam indices."""
168
+ for layer_idx in range(len(self.key_cache)):
169
+ device = self.key_cache[layer_idx].device
170
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
171
+ device = self.value_cache[layer_idx].device
172
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
173
+
174
+ device = self.conv_states[layer_idx].device
175
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
176
+ device = self.ssm_states[layer_idx].device
177
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
178
+
179
+ # Adapted from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.get_seq_length
180
+ # Fixes issues when accessing on empty cache and allow mamba2 pure architectures
181
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
182
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
183
+ # Mamba2 layers don't need the seq_len either way
184
+ if len(self.transformer_layers) == 0:
185
+ return 0
186
+
187
+ # Take any layer that contains cache and not empty tensor
188
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
189
+ if len(self.key_cache) <= layer_idx:
190
+ return 0
191
+
192
+ # We also allow seq_len checks on empty tensors
193
+ size_idx = -2 if len(self.key_cache[layer_idx].shape) > 2 else -1
194
+
195
+ return self.key_cache[layer_idx].shape[size_idx]
196
+
197
+ # Copied from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.to_legacy_cache with Mamba->Mamba2
198
+ def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
199
+ raise NotImplementedError("HybridMamba2AttentionDynamicCache does not have a legacy cache equivalent.")
200
+
201
+ @classmethod
202
+ # Copied from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.from_legacy_cache with Mamba->Mamba2
203
+ def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None) -> "DynamicCache":
204
+ raise NotImplementedError("HybridMamba2AttentionDynamicCache does not have a legacy cache equivalent.")
205
+
206
+
207
+ class Mamba2MLP(nn.Module):
208
+ def __init__(self, config: Mamba2Config, layer_idx):
209
+ super().__init__()
210
+ self.layer_idx = layer_idx
211
+
212
+ self.hidden_size = config.hidden_size
213
+ self.original_intermediate_size = config.mlp_intermediate_size
214
+ self.mlp_padding_size = config.mlp_padding_size
215
+
216
+ self.intermediate_size = (
217
+ (self.original_intermediate_size + self.mlp_padding_size - 1)
218
+ // self.mlp_padding_size
219
+ * self.mlp_padding_size
220
+ )
221
+
222
+ self.fc1 = nn.Linear(self.hidden_size, 2 * self.intermediate_size, bias=config.use_mlp_bias)
223
+ self.activation = config.hidden_act
224
+ self.act = ACT2FN[config.hidden_act]
225
+ self.fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_mlp_bias)
226
+
227
+ def forward(self, x):
228
+ y = self.fc1(x)
229
+ y, z = y.chunk(2, dim=-1)
230
+ y = y * self.act(z)
231
+ y = self.fc2(y)
232
+ return y
233
+
234
+
235
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mamba2
236
+ class Mamba2RotaryEmbedding(nn.Module):
237
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
238
+ super().__init__()
239
+ self.scaling_factor = scaling_factor
240
+ self.dim = dim
241
+ self.max_position_embeddings = max_position_embeddings
242
+ self.base = base
243
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
244
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
245
+ # For BC we register cos and sin cached
246
+ self.max_seq_len_cached = max_position_embeddings
247
+
248
+ @torch.no_grad()
249
+ def forward(self, x, position_ids):
250
+ # x: [bs, num_attention_heads, seq_len, head_size]
251
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
252
+ position_ids_expanded = position_ids[:, None, :].float()
253
+ # Force float32 since bfloat16 loses precision on long contexts
254
+ # See https://github.com/huggingface/transformers/pull/29285
255
+ device_type = x.device.type
256
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
257
+ with torch.autocast(device_type=device_type, enabled=False):
258
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
259
+ emb = torch.cat((freqs, freqs), dim=-1)
260
+ cos = emb.cos()
261
+ sin = emb.sin()
262
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
263
+
264
+
265
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Mamba2
266
+ class Mamba2LinearScalingRotaryEmbedding(Mamba2RotaryEmbedding):
267
+ """Mamba2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
268
+
269
+ def forward(self, x, position_ids):
270
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
271
+ position_ids = position_ids.float() / self.scaling_factor
272
+ cos, sin = super().forward(x, position_ids)
273
+ return cos, sin
274
+
275
+
276
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Mamba2
277
+ class Mamba2DynamicNTKScalingRotaryEmbedding(Mamba2RotaryEmbedding):
278
+ """Mamba2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
279
+
280
+ def forward(self, x, position_ids):
281
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
282
+ seq_len = torch.max(position_ids) + 1
283
+ if seq_len > self.max_position_embeddings:
284
+ base = self.base * (
285
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
286
+ ) ** (self.dim / (self.dim - 2))
287
+ inv_freq = 1.0 / (
288
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
289
+ )
290
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
291
+
292
+ cos, sin = super().forward(x, position_ids)
293
+ return cos, sin
294
+
295
+
296
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
297
+ def rotate_half(x):
298
+ """Rotates half the hidden dims of the input."""
299
+ x1 = x[..., : x.shape[-1] // 2]
300
+ x2 = x[..., x.shape[-1] // 2 :]
301
+ return torch.cat((-x2, x1), dim=-1)
302
+
303
+
304
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
305
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
306
+ """Applies Rotary Position Embedding to the query and key tensors.
307
+
308
+ Args:
309
+ q (`torch.Tensor`): The query tensor.
310
+ k (`torch.Tensor`): The key tensor.
311
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
312
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
313
+ position_ids (`torch.Tensor`, *optional*):
314
+ Deprecated and unused.
315
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
316
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
317
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
318
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
319
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
320
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
321
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
322
+ Returns:
323
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
324
+ """
325
+ cos = cos.unsqueeze(unsqueeze_dim)
326
+ sin = sin.unsqueeze(unsqueeze_dim)
327
+ q_embed = (q * cos) + (rotate_half(q) * sin)
328
+ k_embed = (k * cos) + (rotate_half(k) * sin)
329
+ return q_embed, k_embed
330
+
331
+
332
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
333
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
334
+ """
335
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
336
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
337
+ """
338
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
339
+ if n_rep == 1:
340
+ return hidden_states
341
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
342
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
343
+
344
+
345
+ # Adapted from transformers.models.llama.modeling_llama.LlamaAttention with Llama->Mamba2
346
+ class Mamba2Attention(nn.Module):
347
+ """
348
+ Multi-headed attention from 'Attention Is All You Need' paper. Possible switch to MQA when num_heads_kv < num_heads_q.
349
+ """
350
+
351
+ def __init__(self, config: Mamba2Config, layer_idx: int):
352
+ super().__init__()
353
+ self.config = config
354
+
355
+ self.hidden_size = config.hidden_size
356
+ self.conv_kernel_size = config.attention_conv_kernel
357
+ self.head_dim = config.attention_head_dim
358
+ self.num_heads = config.num_attention_heads
359
+ self.num_heads_kv = config.num_key_value_heads
360
+ self.num_groups_kv = self.num_heads // self.num_heads_kv
361
+ # See https://github.com/state-spaces/mamba/issues/457#issuecomment-2221116217
362
+ # hidden_size % num_heads == 0 is not necessary due to this custom head projection dim
363
+ self.qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv)
364
+ self.out_dim = self.head_dim * self.num_heads
365
+
366
+ # Optional RoPE
367
+ self.rotary_emb_dim = config.rope_emb_dim
368
+ self.rope_theta = config.rope_theta
369
+ self._init_rope()
370
+
371
+ self.in_proj = nn.Linear(self.hidden_size, self.qkv_dim, bias=config.use_attention_qkv_bias)
372
+ # Optional conv1d
373
+ self._init_conv1d()
374
+ self.out_proj = nn.Linear(self.out_dim, self.hidden_size, bias=config.use_attention_out_bias)
375
+
376
+ self.is_causal = True
377
+ self.layer_idx = layer_idx
378
+
379
+ # We throw a similar fast path warning, in case no mamba2 block is used
380
+ if config.num_hidden_layers == len(config.attention_layers_idx):
381
+ if not is_causal_conv1d_available():
382
+ logger.warning_once(
383
+ "Convolution implementation in Mamba2 attention is falling back to naive implementation because `(causal_conv1d_fn, causal_conv1d_update)`"
384
+ "is None. To install follow https://github.com/Dao-AILab/causal-conv1d."
385
+ )
386
+
387
+ # Adapted from transformers.models.llama.modeling_llama.LlamaAttention._init_rope
388
+ # Rope is optional and can be ignored if rope_emb_dim <= 0
389
+ def _init_rope(self):
390
+ # RoPE is optional
391
+ if self.rotary_emb_dim < 1:
392
+ return
393
+
394
+ if self.config.rope_scaling is None:
395
+ self.rotary_emb = Mamba2RotaryEmbedding(
396
+ self.rotary_emb_dim,
397
+ max_position_embeddings=self.config.max_position_embeddings,
398
+ base=self.rope_theta,
399
+ )
400
+ else:
401
+ scaling_type = self.config.rope_scaling["type"]
402
+ scaling_factor = self.config.rope_scaling["factor"]
403
+ if scaling_type == "linear":
404
+ self.rotary_emb = Mamba2LinearScalingRotaryEmbedding(
405
+ self.rotary_emb_dim,
406
+ max_position_embeddings=self.config.max_position_embeddings,
407
+ scaling_factor=scaling_factor,
408
+ base=self.rope_theta,
409
+ )
410
+ elif scaling_type == "dynamic":
411
+ self.rotary_emb = Mamba2DynamicNTKScalingRotaryEmbedding(
412
+ self.rotary_emb_dim,
413
+ max_position_embeddings=self.config.max_position_embeddings,
414
+ scaling_factor=scaling_factor,
415
+ base=self.rope_theta,
416
+ )
417
+ else:
418
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
419
+
420
+ def _init_conv1d(self):
421
+ # Conv1d is optional
422
+ if self.conv_kernel_size < 1:
423
+ return
424
+
425
+ self.conv1d = nn.Conv1d(
426
+ self.qkv_dim,
427
+ self.qkv_dim,
428
+ kernel_size=self.conv_kernel_size,
429
+ padding=self.conv_kernel_size - 1,
430
+ groups=self.qkv_dim,
431
+ )
432
+
433
+ # Adapted from transformers.models.llama.modeling_llama.LlamaAttention.forward
434
+ # Custom projections involving optional causal-conv-1d and optional (partial) RoPE
435
+ def forward(
436
+ self,
437
+ hidden_states: torch.FloatTensor,
438
+ attention_mask: torch.FloatTensor,
439
+ position_ids: torch.LongTensor,
440
+ cache: Optional[HybridMamba2AttentionDynamicCache] = None,
441
+ output_attentions: Optional[bool] = False,
442
+ use_cache: Optional[bool] = False,
443
+ ):
444
+ bsz, q_len, _ = hidden_states.shape
445
+
446
+ # Apply attention-conv1d-specific projections and rope
447
+ query, key, value = self._attn_conv1d_projections_and_rope(
448
+ hidden_states=hidden_states, position_ids=position_ids, cache=cache, use_cache=use_cache
449
+ )
450
+
451
+ # Repeat k/v heads if n_kv_heads < n_heads
452
+ key = repeat_kv(key, self.num_groups_kv)
453
+ value = repeat_kv(value, self.num_groups_kv)
454
+
455
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) / math.sqrt(self.head_dim)
456
+
457
+ if attention_mask is not None: # no matter the length, we just slice it
458
+ causal_mask = attention_mask[:, :, :, : key.shape[-2]]
459
+ attn_weights = attn_weights + causal_mask
460
+
461
+ # upcast attention to fp32
462
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
463
+ attn_weights = nn.functional.dropout(attn_weights, p=0.0, training=self.training)
464
+ attn_output = torch.matmul(attn_weights, value)
465
+
466
+ # Reshape output
467
+ attn_output = attn_output.transpose(1, 2).contiguous()
468
+ attn_output = attn_output.reshape(bsz, q_len, -1)
469
+
470
+ # Final projection
471
+ attn_output = self.out_proj(attn_output)
472
+
473
+ if not output_attentions:
474
+ attn_weights = None
475
+
476
+ return attn_output, attn_weights
477
+
478
+ def _conv1d(self, qkv, seq_len, cache, cached_start, cached_forward):
479
+ # Init cache with first "real" values
480
+ if cached_start:
481
+ qkv_t = qkv.transpose(1, 2)
482
+ cache.conv_states[self.layer_idx].copy_(
483
+ nn.functional.pad(qkv_t, (self.conv_kernel_size - qkv_t.shape[-1], 0))
484
+ )
485
+
486
+ if is_causal_conv1d_available():
487
+ if cached_forward:
488
+ qkv = causal_conv1d_update(
489
+ x=qkv.squeeze(1),
490
+ conv_state=cache.conv_states[self.layer_idx],
491
+ weight=self.conv1d.weight.squeeze(1),
492
+ bias=self.conv1d.bias,
493
+ ).unsqueeze(1)
494
+ else:
495
+ qkv = causal_conv1d_fn(
496
+ x=qkv.transpose(1, 2),
497
+ weight=self.conv1d.weight.squeeze(1),
498
+ bias=self.conv1d.bias,
499
+ ).transpose(1, 2)
500
+ else:
501
+ if cached_forward:
502
+ cache.conv_states[self.layer_idx].copy_(
503
+ torch.roll(cache.conv_states[self.layer_idx], shifts=-1, dims=-1)
504
+ )
505
+ cache.conv_states[self.layer_idx][:, :, -1] = qkv.squeeze(1)
506
+ qkv = torch.sum(cache.conv_states[self.layer_idx] * self.conv1d.weight.squeeze(1), dim=-1)
507
+ if self.conv1d.bias is not None:
508
+ qkv = qkv + self.conv1d.bias
509
+ qkv = qkv.unsqueeze(1)
510
+ else:
511
+ qkv = self.conv1d(qkv.transpose(1, 2))[..., :seq_len].transpose(1, 2).contiguous()
512
+
513
+ return qkv
514
+
515
+ # Moved to a separate function since it's optional
516
+ # Mixture of transformers.models.gpt_neox.modeling_gpt_neox.GPTNeoXAttention._attn_projections_and_rope and
517
+ # transformers.models.llama.modeling_llama.LlamaAttention.forward RoPE parts
518
+ # GPTNeoX for the partial (on dim) RoPE application, Llama for the general RoPE embeddings
519
+ def _apply_rope(
520
+ self,
521
+ query: torch.FloatTensor,
522
+ key: torch.FloatTensor,
523
+ value: torch.FloatTensor,
524
+ position_ids: torch.LongTensor,
525
+ ):
526
+ # Compute rotary embeddings on rotary_emb_dim
527
+ query_rot = query[..., : self.rotary_emb_dim]
528
+ query_pass = query[..., self.rotary_emb_dim :]
529
+ key_rot = key[..., : self.rotary_emb_dim]
530
+ key_pass = key[..., self.rotary_emb_dim :]
531
+
532
+ # Compute RoPE and stitch it back together
533
+ cos, sin = self.rotary_emb(value, position_ids)
534
+ query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
535
+ query = torch.cat((query, query_pass), dim=-1)
536
+ key = torch.cat((key, key_pass), dim=-1)
537
+
538
+ return query, key
539
+
540
+ def _attn_conv1d_projections_and_rope(
541
+ self,
542
+ hidden_states: torch.FloatTensor,
543
+ position_ids: torch.LongTensor,
544
+ cache: Optional[HybridMamba2AttentionDynamicCache] = None,
545
+ use_cache: Optional[bool] = False,
546
+ ):
547
+ bsz, q_len, _ = hidden_states.shape
548
+
549
+ # Managing cache state
550
+ has_layer_past = cache is not None
551
+ if has_layer_past:
552
+ cached_start = not cache.has_previous_state
553
+ cached_forward = not cached_start
554
+ else:
555
+ cached_start = False
556
+ cached_forward = False
557
+
558
+ # Compute QKV
559
+ # Attention heads [batch, seq_len, hidden_size]
560
+ # --> [batch, seq_len, (head_dim * (num_heads(_q) + 2 * num_heads_kv)]
561
+ qkv = self.in_proj(hidden_states)
562
+
563
+ # (Optional) Apply Conv1d, caching is applied in-place
564
+ if self.conv_kernel_size > 0:
565
+ qkv = self._conv1d(
566
+ qkv, seq_len=qkv.shape[1], cache=cache, cached_start=cached_start, cached_forward=cached_forward
567
+ )
568
+
569
+ # Get the respective matrices from the parallel projection back
570
+ q, k, v = qkv.split(
571
+ [self.num_heads * self.head_dim, self.num_heads_kv * self.head_dim, self.num_heads_kv * self.head_dim],
572
+ dim=-1,
573
+ )
574
+
575
+ # Split combined hidden dims back into respective attention heads
576
+ # [batch, seq_len, hidden_size] --> [batch, seq_len, num_heads, head_dim]
577
+ query = q.reshape(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
578
+ key = k.reshape(bsz, q_len, self.num_heads_kv, self.head_dim).transpose(1, 2)
579
+ value = v.reshape(bsz, q_len, self.num_heads_kv, self.head_dim).transpose(1, 2)
580
+
581
+ # (Optional) RoPE
582
+ if self.rotary_emb_dim > 0:
583
+ # TODO do we need to cache sin and cos for RoPE, llama doesn't seem to cache it (except when using sink cache)?
584
+ query, key = self._apply_rope(query, key, value, position_ids)
585
+
586
+ # Cache KV values
587
+ if has_layer_past:
588
+ key, value = cache.update(key, value, self.layer_idx)
589
+
590
+ return query, key, value
591
+
592
+
593
+ # Adapted from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Mamba2
594
+ class Mamba2FlashAttention2(Mamba2Attention):
595
+ """
596
+ Mamba2 flash attention module. This module inherits from `Mamba2Attention` as the weights of the module stays
597
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
598
+ flash attention and deal with padding tokens in case the input contains any of them.
599
+ """
600
+
601
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
602
+ def __init__(self, *args, **kwargs):
603
+ super().__init__(*args, **kwargs)
604
+
605
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
606
+ # 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.
607
+ # 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).
608
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
609
+
610
+ # Adapted from transformers.models.llama.modeling_llama.LlamaFlashAttention2.forward
611
+ # Custom projections involving optional causal-conv-1d and optional (partial) RoPE
612
+ def forward(
613
+ self,
614
+ hidden_states: torch.FloatTensor,
615
+ attention_mask: torch.FloatTensor,
616
+ position_ids: torch.LongTensor,
617
+ cache: Optional[HybridMamba2AttentionDynamicCache] = None,
618
+ output_attentions: Optional[bool] = False,
619
+ use_cache: Optional[bool] = False,
620
+ ):
621
+ bsz, q_len, _ = hidden_states.shape
622
+
623
+ # Apply attention-conv1d-specific projections and rope
624
+ query, key, value = self._attn_conv1d_projections_and_rope(
625
+ hidden_states=hidden_states, position_ids=position_ids, cache=cache, use_cache=use_cache
626
+ )
627
+
628
+ # Repeat k/v heads if n_kv_heads < n_heads
629
+ key = repeat_kv(key, self.num_groups_kv)
630
+ value = repeat_kv(value, self.num_groups_kv)
631
+
632
+ # Permute to get the expected shape for Flash Attention
633
+ query = query.transpose(1, 2)
634
+ key = key.transpose(1, 2)
635
+ value = value.transpose(1, 2)
636
+
637
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
638
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
639
+ # cast them back in float16 / bfloat16 just to be sure everything works as expected.
640
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
641
+ input_dtype = query.dtype
642
+ if input_dtype == torch.float32:
643
+ if torch.is_autocast_enabled():
644
+ target_dtype = torch.get_autocast_gpu_dtype()
645
+ # Handle the case where the model is quantized
646
+ elif hasattr(self.config, "_pre_quantization_dtype"):
647
+ target_dtype = self.config._pre_quantization_dtype
648
+ else:
649
+ target_dtype = self.in_proj.weight.dtype
650
+
651
+ logger.warning_once(
652
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
653
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
654
+ f" {target_dtype}."
655
+ )
656
+
657
+ query = query.to(target_dtype)
658
+ key = key.to(target_dtype)
659
+ value = value.to(target_dtype)
660
+
661
+ # Compute attention
662
+ attn_weights = _flash_attention_forward(
663
+ query,
664
+ key,
665
+ value,
666
+ attention_mask,
667
+ q_len,
668
+ dropout=0.0,
669
+ softmax_scale=None,
670
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
671
+ is_causal=self.is_causal,
672
+ )
673
+
674
+ # Reshape outputs
675
+ attn_output = attn_weights.reshape(bsz, q_len, -1).contiguous()
676
+ attn_output = self.out_proj(attn_output)
677
+
678
+ if not output_attentions:
679
+ attn_weights = None
680
+
681
+ return attn_output, attn_weights
682
+
683
+
684
+ # Adapted from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Mamba2
685
+ class Mamba2SdpaAttention(Mamba2Attention):
686
+ """
687
+ Mamba2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
688
+ `Mamba2Attention` as the weights of the module stays untouched. The only changes are on the forward pass
689
+ to adapt to the SDPA API.
690
+ """
691
+
692
+ def __init__(self, *args, **kwargs):
693
+ super().__init__(*args, **kwargs)
694
+
695
+ # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
696
+ # attn_mask, so we need to call `.contiguous()`. This was fixed in torch==2.2.0.
697
+ # Reference: https://github.com/pytorch/pytorch/issues/112577
698
+ self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
699
+
700
+ # Adapted from transformers.models.llama.modeling_llama.LlamaSdpaAttention.forward
701
+ # Custom projections involving optional causal-conv-1d and optional (partial) RoPE
702
+ def forward(
703
+ self,
704
+ hidden_states: torch.FloatTensor,
705
+ attention_mask: torch.FloatTensor,
706
+ position_ids: torch.LongTensor,
707
+ cache: Optional[HybridMamba2AttentionDynamicCache] = None,
708
+ output_attentions: Optional[bool] = False,
709
+ use_cache: Optional[bool] = False,
710
+ ):
711
+ if output_attentions:
712
+ logger.warning_once(
713
+ "`Mamba2SdpaAttention` is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
714
+ "`output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual "
715
+ "implementation will be required from Transformers version v5.0.0 onwards. "
716
+ 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
717
+ )
718
+ return super().forward(
719
+ hidden_states=hidden_states,
720
+ attention_mask=attention_mask,
721
+ position_ids=position_ids,
722
+ output_attentions=output_attentions,
723
+ cache=cache,
724
+ use_cache=use_cache,
725
+ )
726
+
727
+ bsz, q_len, _ = hidden_states.size()
728
+
729
+ # Apply attention-conv1d-specific projections and rope
730
+ query, key, value = self._attn_conv1d_projections_and_rope(
731
+ hidden_states=hidden_states, position_ids=position_ids, cache=cache, use_cache=use_cache
732
+ )
733
+
734
+ # Repeat k/v heads if n_kv_heads < n_heads
735
+ key = repeat_kv(key, self.num_groups_kv)
736
+ value = repeat_kv(value, self.num_groups_kv)
737
+
738
+ causal_mask = attention_mask
739
+ if attention_mask is not None:
740
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
741
+
742
+ # Avoid torch==2.1.2 specific bug for the memory-efficient backend in SDPA
743
+ if self.require_contiguous_qkv and query.device.type == "cuda" and attention_mask is not None:
744
+ query = query.contiguous()
745
+ key = key.contiguous()
746
+ value = value.contiguous()
747
+
748
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
749
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
750
+ is_causal = True if attention_mask is None and q_len > 1 else False
751
+
752
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
753
+ query=query,
754
+ key=key,
755
+ value=value,
756
+ attn_mask=causal_mask,
757
+ dropout_p=0.0,
758
+ is_causal=is_causal,
759
+ )
760
+
761
+ # Reshape outputs
762
+ attn_output = attn_output.transpose(1, 2).contiguous()
763
+ attn_output = attn_output.view(bsz, q_len, -1)
764
+
765
+ attn_output = self.out_proj(attn_output)
766
+
767
+ return attn_output, None
768
+
769
+
770
+ MAMBA2_ATTENTION_CLASSES = {
771
+ "eager": Mamba2Attention,
772
+ "flash_attention_2": Mamba2FlashAttention2,
773
+ "sdpa": Mamba2SdpaAttention,
774
+ }
775
+
776
+
777
+ class Mamba2Mixer(nn.Module):
778
+ """
779
+ Using the found relation to the attention mechanism under certain conditions (State-Space-Duality SSD),
780
+ we use the Multi-input SSM which can be seen as a counterpart to the Multi-value Attention with analogues:
781
+ - X ~= V
782
+ - B ~= Q
783
+ - C ~= K
784
+ - A (1-SS(a)) ~= Attention Mask
785
+
786
+ For an overview, see the mamba2 paper, section 6, figure 4.
787
+ """
788
+
789
+ def __init__(self, config: Mamba2Config, layer_idx: int):
790
+ super().__init__()
791
+ self.hidden_size = config.hidden_size
792
+ self.ssm_state_size = config.state_size
793
+ self.conv_kernel_size = config.mamba2_conv_kernel
794
+ self.intermediate_size = config.intermediate_size
795
+ self.head_dim = config.mamba2_head_dim
796
+ self.num_heads = config.mamba2_num_heads
797
+ self.chunk_size = config.chunk_size
798
+ self.dt_min = config.time_step_limit[0]
799
+ self.dt_max = config.time_step_limit[1]
800
+ self.layer_idx = layer_idx
801
+ self.use_bias = config.use_mamba2_bias
802
+ self.use_conv_bias = config.use_conv_bias
803
+
804
+ # Parallel projection of the input hidden states
805
+ self.in_proj = nn.Linear(
806
+ in_features=self.hidden_size,
807
+ out_features=2 * (self.intermediate_size + self.ssm_state_size) + self.num_heads,
808
+ bias=self.use_bias,
809
+ )
810
+
811
+ conv1d_dim = self.intermediate_size + 2 * self.ssm_state_size
812
+ self.conv1d = nn.Conv1d(
813
+ in_channels=conv1d_dim,
814
+ out_channels=conv1d_dim,
815
+ bias=config.use_conv_bias,
816
+ kernel_size=config.mamba2_conv_kernel,
817
+ groups=conv1d_dim,
818
+ padding=config.mamba2_conv_kernel - 1,
819
+ )
820
+
821
+ self.activation = config.hidden_act
822
+ self.act = ACT2FN[config.hidden_act]
823
+
824
+ # We only use a bias as parameter
825
+ self.dt_bias = nn.Parameter(torch.rand(size=(self.num_heads,)))
826
+
827
+ # Scalar initialization of A, i.e. 1-Semi-Separable Matrix of A (== 1-SS(a))
828
+ A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(*config.A_initializer_range)
829
+ self.A_log = nn.Parameter(torch.log(A))
830
+
831
+ # As D is a skip connection with A, it is also a scalar of the same shape as A
832
+ self.D = nn.Parameter(torch.ones(self.num_heads))
833
+
834
+ # Residual normalization introduced for instability, see section 7 of the paper
835
+ self.norm = Mamba2RMSNorm(self.intermediate_size, eps=1e-5)
836
+
837
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
838
+
839
+ if not is_fast_path_available:
840
+ logger.warning_once(
841
+ "The fast path is not available because on of "
842
+ "`(selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, causal_conv1d_fn, causal_conv1d_update)`"
843
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
844
+ " https://github.com/Dao-AILab/causal-conv1d"
845
+ )
846
+
847
+ def triton_kernels_forward(self, hidden_states, cache):
848
+ # Managing cache state
849
+ if cache is not None:
850
+ cached_start = not cache.has_previous_state
851
+ cached_forward = not cached_start
852
+ else:
853
+ cached_start = False
854
+ cached_forward = False
855
+
856
+ # 1. Parallel projection for the input
857
+ zxbcdt = self.in_proj(hidden_states)
858
+
859
+ # 2-5. Training combined into one triton kernel
860
+ if self.training and cache is None:
861
+ y = mamba_split_conv1d_scan_combined(
862
+ zxbcdt=zxbcdt,
863
+ conv1d_weight=self.conv1d.weight.squeeze(1),
864
+ conv1d_bias=self.conv1d.bias,
865
+ dt_bias=self.dt_bias,
866
+ A=-torch.exp(self.A_log),
867
+ D=self.D,
868
+ chunk_size=self.chunk_size,
869
+ seq_idx=None,
870
+ activation=self.activation,
871
+ rmsnorm_weight=self.norm.weight,
872
+ rmsnorm_eps=self.norm.eps,
873
+ outproj_weight=self.out_proj.weight,
874
+ outproj_bias=self.out_proj.bias,
875
+ headdim=self.head_dim,
876
+ ngroups=1,
877
+ norm_before_gate=False,
878
+ dt_limit=(self.dt_min, self.dt_max),
879
+ initial_states=None,
880
+ return_final_states=False,
881
+ )
882
+ return y
883
+
884
+ # Reconstructing the necessary vars
885
+ d_mlp = (zxbcdt.shape[-1] - 2 * self.intermediate_size - 2 * self.ssm_state_size - self.num_heads) // 2
886
+ z0, x0, z, xBC, dt = torch.split(
887
+ zxbcdt,
888
+ [d_mlp, d_mlp, self.intermediate_size, self.intermediate_size + 2 * self.ssm_state_size, self.num_heads],
889
+ dim=-1,
890
+ )
891
+
892
+ # 2. Causal convolution for partial set of variables ("input" (x), B, C)
893
+ # Init cache with first "real" values
894
+ if cached_start:
895
+ xBC_t = xBC.transpose(1, 2)
896
+ cache.conv_states[self.layer_idx].copy_(F.pad(xBC_t, (self.conv_kernel_size - xBC_t.shape[-1], 0)))
897
+
898
+ if cached_forward:
899
+ xBC = causal_conv1d_update(
900
+ x=xBC.squeeze(1),
901
+ conv_state=cache.conv_states[self.layer_idx],
902
+ weight=self.conv1d.weight.squeeze(1),
903
+ bias=self.conv1d.bias,
904
+ activation=self.activation,
905
+ )
906
+ else:
907
+ xBC = causal_conv1d_fn(
908
+ x=xBC.transpose(1, 2),
909
+ weight=self.conv1d.weight.squeeze(1),
910
+ bias=self.conv1d.bias,
911
+ activation=self.activation,
912
+ ).transpose(1, 2)
913
+
914
+ # Reconstruct causal convolution vars
915
+ x, B, C = torch.split(xBC, [self.intermediate_size, self.ssm_state_size, self.ssm_state_size], dim=-1)
916
+
917
+ # 3. State Space Duality (SSD)
918
+ # Discretize 1-SS(a)
919
+ A = -torch.exp(self.A_log.float()) # .float() to avoid infs/nans
920
+
921
+ if not cached_forward:
922
+ y = mamba_chunk_scan_combined(
923
+ x=x.reshape(x.shape[0], x.shape[1], -1, self.head_dim),
924
+ dt=dt,
925
+ A=A,
926
+ B=B.unsqueeze(-2),
927
+ C=C.unsqueeze(-2),
928
+ chunk_size=self.chunk_size,
929
+ D=self.D,
930
+ z=None,
931
+ initial_states=None,
932
+ dt_bias=self.dt_bias,
933
+ dt_softplus=True,
934
+ seq_idx=None,
935
+ dt_limit=(self.dt_min, self.dt_max),
936
+ return_final_states=cached_start,
937
+ )
938
+
939
+ if cached_start:
940
+ y, last_state = y
941
+ if cached_start:
942
+ cache.ssm_states[self.layer_idx].copy_(last_state)
943
+
944
+ # [bsz, seq_len, num_heads, head_dim] -> [bsz, seq_len, intermediate size]
945
+ y = y.reshape(y.shape[0], y.shape[1], -1)
946
+ else:
947
+ # Preparing values for single step
948
+ # [num_heads] -> [num_heads, head_dim, state_size]
949
+ A = (
950
+ A.unsqueeze(-1)
951
+ .unsqueeze(-1)
952
+ .expand(A.shape[0], self.head_dim, self.ssm_state_size)
953
+ .to(dtype=torch.float32)
954
+ )
955
+ # [bsz, 1, num_heads] -> [bsz, num_heads, head_dim]
956
+ dt = dt.transpose(1, 2).expand(dt.shape[0], dt.shape[-1], self.head_dim)
957
+ # [num_heads] -> [num_heads, head_dim]
958
+ dt_bias = self.dt_bias.unsqueeze(-1).expand(self.dt_bias.shape[0], self.head_dim)
959
+ # [num_heads] -> [num_heads, head_dim]
960
+ D = self.D.unsqueeze(-1).expand(self.D.shape[0], self.head_dim)
961
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
962
+ x_reshaped = x.reshape(x.shape[0], -1, self.head_dim)
963
+
964
+ # Triton kernel for updating states in-place and returning the hidden state
965
+ y = selective_state_update(
966
+ state=cache.ssm_states[self.layer_idx],
967
+ x=x_reshaped,
968
+ dt=dt,
969
+ A=A,
970
+ B=B,
971
+ C=C,
972
+ D=D,
973
+ z=None,
974
+ dt_bias=dt_bias,
975
+ dt_softplus=True,
976
+ )
977
+
978
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
979
+ y = y.reshape(y.shape[0], -1).unsqueeze(1)
980
+
981
+ # 4. Gate normalization introduced for instability, see section 7 of the paper
982
+ y = self.norm(y, residual=z)
983
+ if d_mlp > 0:
984
+ y = torch.cat([self.act(z0) * x0, y], dim=-1)
985
+
986
+ # 5. Out projecting
987
+ y = self.out_proj(y)
988
+
989
+ return y
990
+
991
+ @classmethod
992
+ def _ssd_naive(
993
+ cls, x, dt, A, B, C, D, chunk_size, dt_bias, dt_min, dt_max, initial_states=None, return_final_states=False
994
+ ):
995
+ """
996
+ Arguments:
997
+ x: (batch_size, seq_len, num_heads, head_dim)
998
+ dt: (batch_size, seq_len, num_heads)
999
+ A: (num_heads)
1000
+ B: (batch_size, seq_len, num_heads, ssm_state_size)
1001
+ C: (batch_size, seq_len, num_heads, ssm_state_size)
1002
+ D: (num_heads)
1003
+ dt_bias: (num_heads)
1004
+ Return:
1005
+ y: (batch_size, seq_len, num_heads, head_dim)
1006
+ """
1007
+
1008
+ def pad_by_size(x, pad_size):
1009
+ """
1010
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
1011
+
1012
+ Assumes that we only have tensors of either size 4 or 3
1013
+ """
1014
+ assert 2 < len(x.shape) < 5
1015
+
1016
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(x.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
1017
+
1018
+ return F.pad(x, pad_shape, mode="constant", value=0)
1019
+
1020
+ def reshape_into_chunks(x, pad_size, chunk_size):
1021
+ """
1022
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1) and
1023
+ simultaneously splitting it into chunk sequences.
1024
+
1025
+ Assumes that we only have tensors of either size 4 or 3
1026
+ """
1027
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
1028
+ x = pad_by_size(x, pad_size)
1029
+
1030
+ if len(x.shape) == 3:
1031
+ # b (l c) h -> b l c h with c=chunk_size
1032
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
1033
+ return x.reshape(x.shape[0], -1, chunk_size, x.shape[2])
1034
+ else:
1035
+ # b (l c) h p -> b l c h p with c=chunk_size
1036
+ # [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]
1037
+ return x.reshape(x.shape[0], -1, chunk_size, x.shape[2], x.shape[3])
1038
+
1039
+ def segsum(x):
1040
+ """
1041
+ More stable segment sum calculation
1042
+ """
1043
+ T = x.size(-1)
1044
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
1045
+ x = x.unsqueeze(-1).expand(*x.size(), T)
1046
+ mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=-1)
1047
+ x = x.masked_fill(~mask, 0)
1048
+ x_segsum = torch.cumsum(x, dim=-2)
1049
+ mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=0)
1050
+ x_segsum = x_segsum.masked_fill(~mask, -torch.inf)
1051
+ return x_segsum
1052
+
1053
+ # Since it is parallelized by chunks they have to be of the same size which we ensure by padding
1054
+ seq_len = x.shape[1]
1055
+ pad_size = chunk_size - (seq_len % chunk_size)
1056
+
1057
+ # dt softplus and clamping
1058
+ dt = F.softplus(dt + dt_bias)
1059
+ dt = torch.clamp(dt, dt_min, dt_max)
1060
+
1061
+ D_residual = D.unsqueeze(-1) * pad_by_size(x, pad_size)
1062
+
1063
+ # Discretize x and A
1064
+ x = x * dt.unsqueeze(-1)
1065
+ A = A.to(x.dtype) * dt
1066
+
1067
+ # Rearrange into blocks/chunks
1068
+ x, A, B, C = [reshape_into_chunks(t, pad_size, chunk_size) for t in (x, A, B, C)]
1069
+
1070
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
1071
+ A = A.permute(0, 3, 1, 2)
1072
+ A_cumsum = torch.cumsum(A, dim=-1)
1073
+
1074
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
1075
+ L = torch.exp(segsum(A))
1076
+ Y_diag = torch.einsum("bclhn,bcshn,bhcls,bcshp->bclhp", C, B, L, x)
1077
+
1078
+ # 2. Compute the state for each intra-chunk
1079
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
1080
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
1081
+ states = torch.einsum("bclhn,bhcl,bclhp->bchpn", B, decay_states, x)
1082
+
1083
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
1084
+ # (middle term of factorization of off-diag blocks; A terms)
1085
+ if initial_states is None:
1086
+ initial_states = torch.zeros_like(states[:, :1])
1087
+ states = torch.cat([initial_states, states], dim=1)
1088
+ decay_chunk = torch.exp(segsum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
1089
+ new_states = torch.einsum("bhzc,bchpn->bzhpn", decay_chunk, states)
1090
+ states, final_state = new_states[:, :-1], new_states[:, -1]
1091
+
1092
+ # 4. Compute state -> output conversion per chunk
1093
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
1094
+ state_decay_out = torch.exp(A_cumsum)
1095
+ Y_off = torch.einsum("bclhn,bchpn,bhcl->bclhp", C, states, state_decay_out)
1096
+
1097
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
1098
+ y = Y_diag + Y_off
1099
+ # [bsz, -1, chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
1100
+ y = y.reshape(y.shape[0], -1, y.shape[-2], y.shape[-1])
1101
+
1102
+ # Add D residual to final output
1103
+ y = y + D_residual
1104
+
1105
+ # Cutting off padded chunks
1106
+ if pad_size > 0:
1107
+ y = y[:, :seq_len, :, :]
1108
+
1109
+ if not return_final_states:
1110
+ return y
1111
+ else:
1112
+ return y, final_state
1113
+
1114
+ def slow_forward(self, hidden_states, cache):
1115
+ seq_len = hidden_states.shape[1]
1116
+
1117
+ # Managing cache state
1118
+ if cache is not None:
1119
+ cached_start = not cache.has_previous_state
1120
+ cached_forward = not cached_start
1121
+ else:
1122
+ cached_start = False
1123
+ cached_forward = False
1124
+
1125
+ # 1. Parallel projection for the input
1126
+ zxbcdt = self.in_proj(hidden_states)
1127
+
1128
+ # Reconstructing the necessary vars
1129
+ d_mlp = (zxbcdt.shape[-1] - 2 * self.intermediate_size - 2 * self.ssm_state_size - self.num_heads) // 2
1130
+ z0, x0, z, xBC, dt = torch.split(
1131
+ zxbcdt,
1132
+ [d_mlp, d_mlp, self.intermediate_size, self.intermediate_size + 2 * self.ssm_state_size, self.num_heads],
1133
+ dim=-1,
1134
+ )
1135
+
1136
+ # 2. Causal convolution for partial set of variables ("input" (x), B, C)
1137
+ # Init cache with first "real" values
1138
+ if cached_start:
1139
+ xBC_t = xBC.transpose(1, 2)
1140
+ cache.conv_states[self.layer_idx].copy_(F.pad(xBC_t, (self.conv_kernel_size - xBC_t.shape[-1], 0)))
1141
+
1142
+ if cached_forward:
1143
+ cache.conv_states[self.layer_idx].copy_(torch.roll(cache.conv_states[self.layer_idx], shifts=-1, dims=-1))
1144
+ cache.conv_states[self.layer_idx][:, :, -1] = xBC.squeeze(1)
1145
+ xBC = torch.sum(cache.conv_states[self.layer_idx] * self.conv1d.weight.squeeze(1), dim=-1)
1146
+ if self.conv1d.bias is not None:
1147
+ xBC = xBC + self.conv1d.bias
1148
+ xBC = self.act(xBC)
1149
+ else:
1150
+ xBC = self.act(self.conv1d(xBC.transpose(1, 2))[..., :seq_len].transpose(1, 2))
1151
+
1152
+ # Reconstruct causal convolution vars
1153
+ x, B, C = torch.split(xBC, [self.intermediate_size, self.ssm_state_size, self.ssm_state_size], dim=-1)
1154
+
1155
+ # 3. State Space Duality (SSD)
1156
+ # Discretize 1-SS(a)
1157
+ A = -torch.exp(self.A_log.float()) # .float() to avoid infs/nans
1158
+
1159
+ if not cached_forward:
1160
+ y = self._ssd_naive(
1161
+ # [bsz, seq_len, intermediate_size] -> [bsz, seq_len, num_heads, head_dim]
1162
+ x=x.reshape(x.shape[0], x.shape[1], -1, self.head_dim),
1163
+ dt=dt,
1164
+ A=A,
1165
+ # [bsz, seq_len, state_size] -> [bsz, seq_len, num_groups=1, state_size]
1166
+ B=B.unsqueeze(-2),
1167
+ # [bsz, seq_len, state_size] -> [bsz, seq_len, num_groups=1, state_size]
1168
+ C=C.unsqueeze(-2),
1169
+ chunk_size=self.chunk_size,
1170
+ D=self.D,
1171
+ initial_states=None,
1172
+ dt_bias=self.dt_bias,
1173
+ dt_min=self.dt_min,
1174
+ dt_max=self.dt_max,
1175
+ return_final_states=cached_start,
1176
+ )
1177
+
1178
+ if cached_start:
1179
+ y, last_state = y
1180
+ if cached_start:
1181
+ cache.ssm_states[self.layer_idx].copy_(last_state)
1182
+
1183
+ # [bsz, seq_len, num_heads, head_dim] -> [bsz, seq_len, intermediate_size]
1184
+ y = y.reshape(y.shape[0], y.shape[1], -1)
1185
+ else:
1186
+ # Get time step with softplus and bias
1187
+ dt = F.softplus(dt + self.dt_bias.to(dtype=dt.dtype))
1188
+ dt = dt.squeeze(1)
1189
+
1190
+ # Discretize A
1191
+ dA = torch.exp(dt * A)
1192
+
1193
+ # Discretize B and x
1194
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
1195
+ x = x.reshape(x.shape[0], -1, self.head_dim)
1196
+ dBx = torch.einsum("bh,bn,bhp->bhpn", dt, B, x)
1197
+
1198
+ # State calculation
1199
+ cache.ssm_states[self.layer_idx].copy_(
1200
+ cache.ssm_states[self.layer_idx] * dA.unsqueeze(-1).unsqueeze(-1) + dBx
1201
+ )
1202
+
1203
+ # Subsequent output
1204
+ y = torch.einsum("bhpn,bn->bhp", cache.ssm_states[self.layer_idx].to(C.dtype), C)
1205
+
1206
+ # D skip connection
1207
+ y = y + self.D.unsqueeze(-1) * x
1208
+
1209
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
1210
+ y = y.reshape(y.shape[0], -1).unsqueeze(1)
1211
+
1212
+ # 4. Gate normalization introduced for instability, see section 7 of the paper
1213
+ y = self.norm(y, residual=z)
1214
+ if d_mlp > 0:
1215
+ y = torch.cat([self.act(z0) * x0, y], dim=-1)
1216
+
1217
+ # 5. Out projecting
1218
+ y = self.out_proj(y)
1219
+
1220
+ return y
1221
+
1222
+ def forward(self, hidden_states, cache: Optional[HybridMamba2AttentionDynamicCache] = None):
1223
+ # TODO: check version for AMD support?
1224
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
1225
+ return self.triton_kernels_forward(hidden_states, cache)
1226
+ return self.slow_forward(hidden_states, cache)
1227
+
1228
+
1229
+ # Adapted from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mamba2
1230
+ # An optional residual normalization has been integrated
1231
+ class Mamba2RMSNorm(nn.Module):
1232
+ def __init__(self, hidden_size, eps=1e-6):
1233
+ """
1234
+ Mamba2RMSNorm is equivalent to LlamaRMSNorm but with optional residual normalizing
1235
+ """
1236
+ super().__init__()
1237
+ self.weight = nn.Parameter(torch.ones(hidden_size))
1238
+ self.eps = eps
1239
+
1240
+ def forward(self, hidden_states, residual=None):
1241
+ input_dtype = hidden_states.dtype
1242
+ hidden_states = hidden_states.to(torch.float32)
1243
+
1244
+ # Residual normalization introduced for instability, see section 7 of the paper
1245
+ if residual is not None:
1246
+ hidden_states = hidden_states * F.silu(residual.to(torch.float32))
1247
+
1248
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
1249
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
1250
+
1251
+ return self.weight * hidden_states.to(input_dtype)
1252
+
1253
+
1254
+ # Adapted from transformers.models.mamba.modeling_mamba.MambaBlock
1255
+ # Allows attention instead of mamba2 and an optional MLP layer afterward
1256
+ class Mamba2Block(nn.Module):
1257
+ def __init__(self, config, layer_idx):
1258
+ super().__init__()
1259
+ self.config = config
1260
+ self.layer_idx = layer_idx
1261
+ self.attention_layer = layer_idx in config.attention_layers_idx
1262
+ self.mlp_layer = config.mlp_intermediate_size > 0
1263
+ self.residual_in_fp32 = config.residual_in_fp32
1264
+ self.norm = Mamba2RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1265
+
1266
+ # Mixer is either attention layer or mamba2 layer
1267
+ if self.attention_layer:
1268
+ self.mixer = MAMBA2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
1269
+ else:
1270
+ self.mixer = Mamba2Mixer(config, layer_idx=layer_idx)
1271
+
1272
+ # Following mlp layer is optional
1273
+ if self.mlp_layer:
1274
+ self.norm2 = Mamba2RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1275
+ self.mlp = Mamba2MLP(config, layer_idx=layer_idx)
1276
+ else:
1277
+ self.norm2 = None
1278
+ self.mlp = None
1279
+
1280
+ def forward(
1281
+ self,
1282
+ hidden_states: torch.FloatTensor,
1283
+ attention_mask: torch.FloatTensor,
1284
+ position_ids: torch.LongTensor,
1285
+ cache: Optional[HybridMamba2AttentionDynamicCache] = None,
1286
+ output_attentions: Optional[bool] = False,
1287
+ use_cache: Optional[bool] = False,
1288
+ ):
1289
+ dtype = hidden_states.dtype
1290
+
1291
+ residual = hidden_states
1292
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
1293
+ if self.residual_in_fp32:
1294
+ residual = residual.to(torch.float32)
1295
+
1296
+ # Mamba2 path
1297
+ if not self.attention_layer:
1298
+ hidden_states = self.mixer(hidden_states, cache=cache)
1299
+ attn_weights = None
1300
+ # Attention path
1301
+ else:
1302
+ hidden_states, attn_weights = self.mixer(
1303
+ hidden_states=hidden_states,
1304
+ attention_mask=attention_mask,
1305
+ position_ids=position_ids,
1306
+ cache=cache,
1307
+ output_attentions=output_attentions,
1308
+ use_cache=use_cache,
1309
+ )
1310
+ hidden_states = (residual + hidden_states).to(dtype)
1311
+
1312
+ if self.mlp_layer:
1313
+ residual = hidden_states
1314
+ hidden_states = self.norm2(hidden_states.to(dtype=self.norm2.weight.dtype))
1315
+ if self.residual_in_fp32:
1316
+ residual = residual.to(torch.float32)
1317
+
1318
+ hidden_states = self.mlp(hidden_states)
1319
+ hidden_states = (hidden_states + residual).to(dtype)
1320
+
1321
+ return hidden_states, attn_weights
1322
+
1323
+
1324
+ class Mamba2PreTrainedModel(PreTrainedModel):
1325
+ """
1326
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1327
+ models.
1328
+ """
1329
+
1330
+ config_class = Mamba2Config
1331
+ base_model_prefix = "backbone"
1332
+ _no_split_modules = ["Mamba2Block"]
1333
+ supports_gradient_checkpointing = True
1334
+ _skip_keys_device_placement = "past_key_values"
1335
+ _supports_flash_attn_2 = True
1336
+ _supports_sdpa = True
1337
+ _supports_cache_class = True # Note: only supports HybridMamba2AttentionDynamicCache
1338
+ _is_stateful = True
1339
+
1340
+ # Adapted from transformers.models.mamba.modeling_mamba.MambaPreTrainedModel._init_weights
1341
+ # Only using dt bias and rescale_prenorm_residual is expanded when using the additional MLP layer
1342
+ def _init_weights(self, module):
1343
+ """Initialize the weights."""
1344
+ if isinstance(module, Mamba2Mixer):
1345
+ module.A_log._no_weight_decay = True
1346
+ module.D._no_weight_decay = True
1347
+
1348
+ dt = torch.exp(
1349
+ torch.rand(self.config.mamba2_num_heads)
1350
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
1351
+ + math.log(self.config.time_step_min)
1352
+ ).clamp(min=self.config.time_step_floor)
1353
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
1354
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
1355
+ with torch.no_grad():
1356
+ module.dt_bias.copy_(inv_dt)
1357
+ module.dt_bias._no_reinit = True
1358
+ module.dt_bias._no_weight_decay = True
1359
+
1360
+ if isinstance(module, nn.Linear):
1361
+ if module.bias is not None:
1362
+ if not getattr(module.bias, "_no_reinit", False):
1363
+ nn.init.zeros_(module.bias)
1364
+ elif isinstance(module, nn.Embedding):
1365
+ nn.init.normal_(module.weight, std=self.config.emb_initializer_range)
1366
+ elif isinstance(module, nn.Conv1d):
1367
+ if self.config.conv_initializer_range is not None:
1368
+ nn.init.uniform_(
1369
+ module.weight, -self.config.conv_initializer_range, self.config.conv_initializer_range
1370
+ )
1371
+
1372
+ if self.config.rescale_prenorm_residual:
1373
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
1374
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
1375
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
1376
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
1377
+ #
1378
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
1379
+ for name, p in module.named_parameters():
1380
+ if name in ["out_proj.weight", "fc2.weight"]:
1381
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
1382
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
1383
+ # We need to reinit p since this code could be called multiple times
1384
+ # Having just p *= scale would repeatedly scale it down
1385
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
1386
+
1387
+ # mlp layer is considered as an additional overhead
1388
+ n_residuals = 2 if self.config.mlp_intermediate_size > 0 else 1
1389
+ with torch.no_grad():
1390
+ p /= math.sqrt(n_residuals * self.config.num_hidden_layers)
1391
+
1392
+
1393
+ MAMBA2_START_DOCSTRING = r"""
1394
+
1395
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1396
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1397
+ etc.)
1398
+
1399
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1400
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1401
+ and behavior.
1402
+
1403
+ Parameters:
1404
+ config ([`Mamba2Config`]): Model configuration class with all the parameters of the model.
1405
+ Initializing with a config file does not load the weights associated with the model, only the
1406
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1407
+ """
1408
+
1409
+ MAMBA2_INPUTS_DOCSTRING = r"""
1410
+ Args:
1411
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1412
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1413
+ it.
1414
+
1415
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1416
+ [`PreTrainedTokenizer.__call__`] for details.
1417
+
1418
+ [What are input IDs?](../glossary#input-ids)
1419
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1420
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1421
+
1422
+ - 1 for tokens that are **not masked**,
1423
+ - 0 for tokens that are **masked**.
1424
+
1425
+ [What are attention masks?](../glossary#attention-mask)
1426
+
1427
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1428
+ [`PreTrainedTokenizer.__call__`] for details.
1429
+
1430
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1431
+ `past_key_values`).
1432
+
1433
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1434
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1435
+ information on the default strategy.
1436
+
1437
+ - 1 indicates the head is **not masked**,
1438
+ - 0 indicates the head is **masked**.
1439
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1440
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1441
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1442
+ model's internal embedding lookup matrix.
1443
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1444
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1445
+ config.n_positions - 1]`.
1446
+
1447
+ [What are position IDs?](../glossary#position-ids)
1448
+ past_key_values (`HybridMamba2AttentionDynamicCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1449
+ A HybridMamba2AttentionDynamicCache object containing pre-computed hidden-states (keys, values, and, if used, the convolution in the
1450
+ self-attention blocks and convolution and ssm states in the mamba2 blocks) that can be used (see `past_key_values` input)
1451
+ to speed up sequential decoding.
1452
+ Key and value cache tensors have shape `(batch_size, num_key_value_heads, seq_len, attention_head_dim)`.
1453
+ Convolution and ssm states tensors have shape `(batch_size, intermediate_size + 2 * state_size, mamba2_conv_kernel)` if used in the mamba2 block
1454
+ else it has shape `(batch_size, attention_head_dim * (num_attention_heads + 2 * num_key_value_heads), attention_conv_kernel)`
1455
+ and `(batch_size, mamba2_num_heads, mamba2_head_dim, state_size)` respectively.
1456
+ See the `HybridMamba2AttentionDynamicCache` class for more details.
1457
+
1458
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that
1459
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1460
+ `input_ids` of shape `(batch_size, sequence_length)`.
1461
+ use_cache (`bool`, *optional*):
1462
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1463
+ `past_key_values`).
1464
+ output_attentions (`bool`, *optional*):
1465
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1466
+ tensors for more detail.
1467
+ output_hidden_states (`bool`, *optional*):
1468
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1469
+ more detail.
1470
+ return_dict (`bool`, *optional*):
1471
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1472
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1473
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1474
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1475
+ the complete sequence length.
1476
+ """
1477
+
1478
+
1479
+ @add_start_docstrings(
1480
+ "The bare MAMBA2 Model outputting raw hidden-states without any specific head on top.",
1481
+ MAMBA2_START_DOCSTRING,
1482
+ )
1483
+ class Mamba2Model(Mamba2PreTrainedModel):
1484
+ # Adapted from transformers.models.mamba.modeling_mamba.MambaModel.__init__ with Mamba->Mamba2
1485
+ # Additional information about possible attention layers
1486
+ def __init__(self, config):
1487
+ super().__init__(config)
1488
+
1489
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
1490
+ self.layers = nn.ModuleList([Mamba2Block(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
1491
+
1492
+ self._attn_implementation = config._attn_implementation
1493
+ self._uses_attention_layers = len(config.attention_layers_idx) > 0
1494
+
1495
+ self.gradient_checkpointing = False
1496
+ self.norm_f = Mamba2RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1497
+ # Initialize weights and apply final processing
1498
+ self._register_load_state_dict_pre_hook(self.load_hook)
1499
+ self.post_init()
1500
+
1501
+ # Copied from transformers.models.mamba.modeling_mamba.MambaModel.load_hook
1502
+ def load_hook(self, state_dict, prefix, *args):
1503
+ for k in state_dict:
1504
+ if "embedding." in k:
1505
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
1506
+ break
1507
+
1508
+ def get_input_embeddings(self):
1509
+ return self.embeddings
1510
+
1511
+ def set_input_embeddings(self, new_embeddings):
1512
+ self.embeddings = new_embeddings
1513
+
1514
+ @add_start_docstrings_to_model_forward(MAMBA2_INPUTS_DOCSTRING)
1515
+ @add_code_sample_docstrings(
1516
+ output_type=BaseModelOutputWithPast,
1517
+ config_class=_CONFIG_FOR_DOC,
1518
+ )
1519
+ # Adapted from transformers.models.jamba.modeling_jamba.JambaModel.forward
1520
+ # No MoE logic, inits cache itself like Mamba does, and handles position_ids like Llama
1521
+ def forward(
1522
+ self,
1523
+ input_ids: Optional[torch.LongTensor] = None,
1524
+ attention_mask: Optional[torch.Tensor] = None,
1525
+ inputs_embeds: Optional[torch.LongTensor] = None,
1526
+ position_ids: Optional[torch.LongTensor] = None,
1527
+ past_key_values: Optional[HybridMamba2AttentionDynamicCache] = None,
1528
+ use_cache: Optional[bool] = None,
1529
+ output_attentions: Optional[bool] = None,
1530
+ output_hidden_states: Optional[bool] = None,
1531
+ return_dict: Optional[bool] = None,
1532
+ cache_position: Optional[torch.LongTensor] = None,
1533
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1534
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1535
+ output_hidden_states = (
1536
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1537
+ )
1538
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
1539
+
1540
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1541
+
1542
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
1543
+ raise ValueError(
1544
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1545
+ )
1546
+
1547
+ if self.gradient_checkpointing and self.training and use_cache:
1548
+ logger.warning_once(
1549
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1550
+ )
1551
+ use_cache = False
1552
+
1553
+ if inputs_embeds is None:
1554
+ inputs_embeds = self.embeddings(input_ids)
1555
+ hidden_states = inputs_embeds
1556
+
1557
+ # We allow empty caches on initial forward
1558
+ if past_key_values is None and use_cache:
1559
+ past_key_values = HybridMamba2AttentionDynamicCache(
1560
+ config=self.config,
1561
+ batch_size=inputs_embeds.shape[0],
1562
+ device=inputs_embeds.device,
1563
+ dtype=inputs_embeds.dtype,
1564
+ )
1565
+
1566
+ # LLama based positions
1567
+ if cache_position is None:
1568
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1569
+ cache_position = torch.arange(
1570
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1571
+ )
1572
+ if position_ids is None:
1573
+ position_ids = cache_position.unsqueeze(0)
1574
+
1575
+ causal_mask = self._update_causal_mask(
1576
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1577
+ )
1578
+
1579
+ all_hidden_states = () if output_hidden_states else None
1580
+ all_self_attns = () if output_attentions else None
1581
+
1582
+ for mixer_block in self.layers:
1583
+ if output_hidden_states:
1584
+ all_hidden_states += (hidden_states,)
1585
+
1586
+ if self.gradient_checkpointing and self.training:
1587
+ out = self._gradient_checkpointing_func(
1588
+ mixer_block.__call__,
1589
+ hidden_states,
1590
+ causal_mask,
1591
+ position_ids,
1592
+ past_key_values,
1593
+ output_attentions,
1594
+ use_cache,
1595
+ )
1596
+ else:
1597
+ out = mixer_block(
1598
+ hidden_states=hidden_states,
1599
+ attention_mask=causal_mask,
1600
+ position_ids=position_ids,
1601
+ cache=past_key_values,
1602
+ output_attentions=output_attentions,
1603
+ use_cache=use_cache,
1604
+ )
1605
+
1606
+ hidden_states = out[0]
1607
+
1608
+ if output_attentions:
1609
+ if out[1] is not None:
1610
+ # Append attentions only of attention layers. Mamba2 layers return `None` as the attention weights
1611
+ all_self_attns += (out[1],)
1612
+
1613
+ hidden_states = self.norm_f(hidden_states)
1614
+
1615
+ # Add hidden states from the last block
1616
+ if output_hidden_states:
1617
+ all_hidden_states += (hidden_states,)
1618
+
1619
+ if past_key_values and not past_key_values.has_previous_state:
1620
+ past_key_values.has_previous_state = True
1621
+
1622
+ next_cache = None if not use_cache else past_key_values
1623
+
1624
+ if not return_dict:
1625
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1626
+
1627
+ return BaseModelOutputWithPast(
1628
+ last_hidden_state=hidden_states,
1629
+ past_key_values=next_cache,
1630
+ hidden_states=all_hidden_states,
1631
+ attentions=all_self_attns,
1632
+ )
1633
+
1634
+ # Adapted from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1635
+ # Custom hybrid cache instead
1636
+ def _update_causal_mask(
1637
+ self,
1638
+ attention_mask: torch.Tensor,
1639
+ input_tensor: torch.Tensor,
1640
+ cache_position: torch.Tensor,
1641
+ past_key_values: HybridMamba2AttentionDynamicCache,
1642
+ output_attentions: bool,
1643
+ ):
1644
+ if not self._uses_attention_layers:
1645
+ return None
1646
+
1647
+ if self._attn_implementation == "flash_attention_2":
1648
+ if attention_mask is not None and 0.0 in attention_mask:
1649
+ return attention_mask
1650
+ return None
1651
+
1652
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1653
+ # order to dispatch on Flash Attention 2.
1654
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1655
+
1656
+ # TODO: check if this is compatible with this custom cache format
1657
+ if self._attn_implementation == "sdpa" and not output_attentions:
1658
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1659
+ attention_mask,
1660
+ inputs_embeds=input_tensor,
1661
+ past_key_values_length=past_seen_tokens,
1662
+ is_training=self.training,
1663
+ ):
1664
+ return None
1665
+
1666
+ dtype, device = input_tensor.dtype, input_tensor.device
1667
+ min_dtype = torch.finfo(dtype).min
1668
+ sequence_length = input_tensor.shape[1]
1669
+ target_length = (
1670
+ attention_mask.shape[-1]
1671
+ if isinstance(attention_mask, torch.Tensor)
1672
+ else past_seen_tokens + sequence_length
1673
+ )
1674
+
1675
+ if attention_mask is not None and attention_mask.dim() == 4:
1676
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1677
+ if attention_mask.max() != 0:
1678
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1679
+ causal_mask = attention_mask
1680
+ else:
1681
+ causal_mask = torch.full(
1682
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1683
+ )
1684
+ if sequence_length != 1:
1685
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1686
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1687
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1688
+ if attention_mask is not None:
1689
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1690
+ mask_length = attention_mask.shape[-1]
1691
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1692
+ padding_mask = padding_mask == 0
1693
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1694
+ padding_mask, min_dtype
1695
+ )
1696
+ if (
1697
+ self._attn_implementation == "sdpa"
1698
+ and attention_mask is not None
1699
+ and attention_mask.device.type == "cuda"
1700
+ and not output_attentions
1701
+ ):
1702
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1703
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1704
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1705
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1706
+
1707
+ return causal_mask
1708
+
1709
+
1710
+ @add_start_docstrings(
1711
+ """
1712
+ The MAMBA2 Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
1713
+ """,
1714
+ MAMBA2_START_DOCSTRING,
1715
+ )
1716
+ class Mamba2ForCausalLM(Mamba2PreTrainedModel):
1717
+ _tied_weights_keys = ["lm_head.weight"]
1718
+
1719
+ def __init__(self, config):
1720
+ super().__init__(config)
1721
+ self.backbone = Mamba2Model(config)
1722
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1723
+
1724
+ # Initialize weights and apply final processing
1725
+ self.post_init()
1726
+
1727
+ def get_output_embeddings(self):
1728
+ return self.lm_head
1729
+
1730
+ def set_output_embeddings(self, new_embeddings):
1731
+ self.lm_head = new_embeddings
1732
+
1733
+ def get_input_embeddings(self):
1734
+ return self.backbone.get_input_embeddings()
1735
+
1736
+ def set_input_embeddings(self, new_embeddings):
1737
+ return self.backbone.set_input_embeddings(new_embeddings)
1738
+
1739
+ # Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM.prepare_inputs_for_generation
1740
+ # We omit some args Mamba2 doesn't use such as output_router_logits and num_logits_to_keep; additional optional reinit of the cache
1741
+ def prepare_inputs_for_generation(
1742
+ self,
1743
+ input_ids,
1744
+ past_key_values=None,
1745
+ attention_mask=None,
1746
+ inputs_embeds=None,
1747
+ cache_position=None,
1748
+ position_ids=None,
1749
+ use_cache=True,
1750
+ **kwargs,
1751
+ ):
1752
+ empty_past_kv = past_key_values is None
1753
+
1754
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1755
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1756
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1757
+ if not empty_past_kv:
1758
+ if inputs_embeds is not None: # Exception 1
1759
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1760
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1761
+ input_ids = input_ids[:, cache_position]
1762
+
1763
+ # Initialize cache, if necessary
1764
+ if empty_past_kv:
1765
+ past_key_values = HybridMamba2AttentionDynamicCache(
1766
+ config=self.config,
1767
+ batch_size=input_ids.shape[0],
1768
+ device=self.device,
1769
+ dtype=self.dtype,
1770
+ )
1771
+
1772
+ if attention_mask is not None and position_ids is None:
1773
+ # create position_ids on the fly for batch generation
1774
+ position_ids = attention_mask.long().cumsum(-1) - 1
1775
+ position_ids.masked_fill_(attention_mask == 0, 1)
1776
+ if not empty_past_kv:
1777
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1778
+
1779
+ # If `inputs_embeds` are passed, we only want to use them in the 1st generation step
1780
+ if inputs_embeds is not None and empty_past_kv:
1781
+ model_inputs = {"inputs_embeds": inputs_embeds}
1782
+ else:
1783
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1784
+
1785
+ model_inputs.update(
1786
+ {
1787
+ "position_ids": position_ids,
1788
+ "past_key_values": past_key_values,
1789
+ "use_cache": use_cache,
1790
+ "attention_mask": attention_mask,
1791
+ "cache_position": cache_position,
1792
+ }
1793
+ )
1794
+ return model_inputs
1795
+
1796
+ @add_start_docstrings_to_model_forward(MAMBA2_INPUTS_DOCSTRING)
1797
+ @add_code_sample_docstrings(
1798
+ output_type=CausalLMOutputWithPast,
1799
+ config_class=_CONFIG_FOR_DOC,
1800
+ )
1801
+ def forward(
1802
+ self,
1803
+ input_ids: Optional[torch.LongTensor] = None,
1804
+ attention_mask: Optional[torch.Tensor] = None,
1805
+ inputs_embeds: Optional[torch.LongTensor] = None,
1806
+ position_ids: Optional[torch.LongTensor] = None,
1807
+ past_key_values: Optional[HybridMamba2AttentionDynamicCache] = None,
1808
+ labels: Optional[torch.LongTensor] = None,
1809
+ use_cache: Optional[bool] = None,
1810
+ output_attentions: Optional[bool] = None,
1811
+ output_hidden_states: Optional[bool] = None,
1812
+ return_dict: Optional[bool] = None,
1813
+ cache_position: Optional[torch.LongTensor] = None,
1814
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1815
+ r"""
1816
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1817
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1818
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1819
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1820
+ """
1821
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1822
+
1823
+ outputs = self.backbone(
1824
+ input_ids=input_ids,
1825
+ attention_mask=attention_mask,
1826
+ inputs_embeds=inputs_embeds,
1827
+ position_ids=position_ids,
1828
+ past_key_values=past_key_values,
1829
+ use_cache=use_cache,
1830
+ output_attentions=output_attentions,
1831
+ output_hidden_states=output_hidden_states,
1832
+ return_dict=return_dict,
1833
+ cache_position=cache_position,
1834
+ )
1835
+
1836
+ hidden_states = outputs[0]
1837
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1838
+
1839
+ loss = None
1840
+ if labels is not None:
1841
+ # Move labels to correct device to enable model parallelism
1842
+ labels = labels.to(logits.device)
1843
+ # Shift so that tokens < n predict n
1844
+ shift_logits = logits[..., :-1, :].contiguous()
1845
+ shift_labels = labels[..., 1:].contiguous()
1846
+ # Flatten the tokens
1847
+ loss_fct = CrossEntropyLoss()
1848
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1849
+
1850
+ if not return_dict:
1851
+ output = (logits,) + outputs[1:]
1852
+ return ((loss,) + output) if loss is not None else output
1853
+
1854
+ return CausalLMOutputWithPast(
1855
+ loss=loss,
1856
+ logits=logits,
1857
+ past_key_values=outputs.past_key_values,
1858
+ hidden_states=outputs.hidden_states,
1859
+ attentions=outputs.attentions,
1860
+ )
1861
+
1862
+
1863
+ # Copied from transformers.models.bart.modeling_bart.BartClassificationHead with Bart->Mamba2, torch.tanh->F.silu
1864
+ class Mamba2ClassificationHead(nn.Module):
1865
+ """Head for sentence-level classification tasks."""
1866
+
1867
+ def __init__(
1868
+ self,
1869
+ input_dim: int,
1870
+ inner_dim: int,
1871
+ num_classes: int,
1872
+ pooler_dropout: float,
1873
+ ):
1874
+ super().__init__()
1875
+ self.dense = nn.Linear(input_dim, inner_dim)
1876
+ self.dropout = nn.Dropout(p=pooler_dropout)
1877
+ self.out_proj = nn.Linear(inner_dim, num_classes)
1878
+
1879
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1880
+ hidden_states = self.dropout(hidden_states)
1881
+ hidden_states = self.dense(hidden_states)
1882
+ hidden_states = F.silu(hidden_states)
1883
+ hidden_states = self.dropout(hidden_states)
1884
+ hidden_states = self.out_proj(hidden_states)
1885
+ return hidden_states
1886
+
1887
+
1888
+ @add_start_docstrings(
1889
+ """
1890
+ Mamba2 Model backbone with a sequence classification/regression head on top
1891
+ (a linear layer on top of the pooled output) e.g. for GLUE tasks.
1892
+
1893
+ [`Mamba2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1894
+ (e.g. GPT-2) do.
1895
+
1896
+ Since it does classification on the last token, it requires to know the position of the last token.
1897
+ If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row.
1898
+ If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1899
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1900
+ each row of the batch).
1901
+ """,
1902
+ MAMBA2_START_DOCSTRING,
1903
+ )
1904
+ class Mamba2ForSequenceClassification(Mamba2PreTrainedModel):
1905
+ # Copied from transformers.models.bart.modeling_bart.BartForSequenceClassification.__init__ with Bart->Mamba2,d_model->hidden_size,model->backbone
1906
+ def __init__(self, config: Mamba2Config, **kwargs):
1907
+ super().__init__(config, **kwargs)
1908
+ self.backbone = Mamba2Model(config)
1909
+ self.classification_head = Mamba2ClassificationHead(
1910
+ config.hidden_size,
1911
+ config.hidden_size,
1912
+ config.num_labels,
1913
+ config.classifier_dropout,
1914
+ )
1915
+
1916
+ # Initialize weights and apply final processing
1917
+ self.post_init()
1918
+
1919
+ def get_input_embeddings(self):
1920
+ return self.backbone.embeddings
1921
+
1922
+ def set_input_embeddings(self, value):
1923
+ self.backbone.embeddings = value
1924
+
1925
+ @add_start_docstrings_to_model_forward(MAMBA2_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1926
+ @replace_return_docstrings(output_type=SequenceClassifierOutputWithPast, config_class=_CONFIG_FOR_DOC)
1927
+ @add_code_sample_docstrings(
1928
+ output_type=SequenceClassifierOutputWithPast,
1929
+ config_class=_CONFIG_FOR_DOC,
1930
+ )
1931
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralForSequenceClassification.forward with self.num_labels->self.config.num_labels,self.score->self.classification_head,self.model->self.backbone
1932
+ def forward(
1933
+ self,
1934
+ input_ids: torch.LongTensor = None,
1935
+ attention_mask: Optional[torch.Tensor] = None,
1936
+ position_ids: Optional[torch.LongTensor] = None,
1937
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1938
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1939
+ labels: Optional[torch.LongTensor] = None,
1940
+ use_cache: Optional[bool] = None,
1941
+ output_attentions: Optional[bool] = None,
1942
+ output_hidden_states: Optional[bool] = None,
1943
+ return_dict: Optional[bool] = None,
1944
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1945
+ r"""
1946
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1947
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1948
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1949
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1950
+ """
1951
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1952
+
1953
+ transformer_outputs = self.backbone(
1954
+ input_ids,
1955
+ attention_mask=attention_mask,
1956
+ position_ids=position_ids,
1957
+ past_key_values=past_key_values,
1958
+ inputs_embeds=inputs_embeds,
1959
+ use_cache=use_cache,
1960
+ output_attentions=output_attentions,
1961
+ output_hidden_states=output_hidden_states,
1962
+ return_dict=return_dict,
1963
+ )
1964
+ hidden_states = transformer_outputs[0]
1965
+ logits = self.classification_head(hidden_states)
1966
+
1967
+ if input_ids is not None:
1968
+ batch_size = input_ids.shape[0]
1969
+ else:
1970
+ batch_size = inputs_embeds.shape[0]
1971
+
1972
+ if self.config.pad_token_id is None and batch_size != 1:
1973
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1974
+ if self.config.pad_token_id is None:
1975
+ sequence_lengths = -1
1976
+ else:
1977
+ if input_ids is not None:
1978
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1979
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1980
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1981
+ sequence_lengths = sequence_lengths.to(logits.device)
1982
+ else:
1983
+ sequence_lengths = -1
1984
+
1985
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1986
+
1987
+ loss = None
1988
+ if labels is not None:
1989
+ labels = labels.to(logits.device)
1990
+ if self.config.problem_type is None:
1991
+ if self.config.num_labels == 1:
1992
+ self.config.problem_type = "regression"
1993
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1994
+ self.config.problem_type = "single_label_classification"
1995
+ else:
1996
+ self.config.problem_type = "multi_label_classification"
1997
+
1998
+ if self.config.problem_type == "regression":
1999
+ loss_fct = MSELoss()
2000
+ if self.config.num_labels == 1:
2001
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2002
+ else:
2003
+ loss = loss_fct(pooled_logits, labels)
2004
+ elif self.config.problem_type == "single_label_classification":
2005
+ loss_fct = CrossEntropyLoss()
2006
+ loss = loss_fct(pooled_logits.view(-1, self.config.num_labels), labels.view(-1))
2007
+ elif self.config.problem_type == "multi_label_classification":
2008
+ loss_fct = BCEWithLogitsLoss()
2009
+ loss = loss_fct(pooled_logits, labels)
2010
+ if not return_dict:
2011
+ output = (pooled_logits,) + transformer_outputs[1:]
2012
+ return ((loss,) + output) if loss is not None else output
2013
+
2014
+ return SequenceClassifierOutputWithPast(
2015
+ loss=loss,
2016
+ logits=pooled_logits,
2017
+ past_key_values=transformer_outputs.past_key_values,
2018
+ hidden_states=transformer_outputs.hidden_states,
2019
+ attentions=transformer_outputs.attentions,
2020
+ )
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
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dadfd56d766715c61d2ef780a525ab43b8e6da4de6865bda3d95fdef5e134055
3
+ size 493443
tokenizer_config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "bos_token": "<s>",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "</s>",
34
+ "legacy": true,
35
+ "model_max_length": 1000000000000000019884624838656,
36
+ "pad_token": null,
37
+ "sp_model_kwargs": {},
38
+ "spaces_between_special_tokens": false,
39
+ "tokenizer_class": "LlamaTokenizer",
40
+ "unk_token": "<unk>",
41
+ "use_default_system_prompt": false
42
+ }