jburtoft commited on
Commit
3a8165a
·
verified ·
1 Parent(s): 64c478c

Upload modeling_mimo_v2_flash.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_mimo_v2_flash.py +669 -0
modeling_mimo_v2_flash.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Copyright 2025 Xiaomi Corporation.
4
+ # Copyright 2025 The HuggingFace Inc. team.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ from typing import Callable, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.generation import GenerationMixin
25
+ from transformers.activations import ACT2FN
26
+ from transformers.cache_utils import Cache, DynamicCache
27
+ from transformers.integrations import use_kernel_forward_from_hub
28
+
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+
34
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
35
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from transformers.processing_utils import Unpack
38
+ from transformers.utils import (
39
+ logging,
40
+ )
41
+
42
+ from transformers.modeling_outputs import MoeModelOutputWithPast
43
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
44
+ from .configuration_mimo_v2_flash import MiMoV2FlashConfig
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ def rotate_half(x):
50
+ """Rotates half the hidden dims of the input."""
51
+ x1 = x[..., : x.shape[-1] // 2]
52
+ x2 = x[..., x.shape[-1] // 2:]
53
+ return torch.cat((-x2, x1), dim=-1)
54
+
55
+
56
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
57
+ """Applies Rotary Position Embedding to the query and key tensors.
58
+
59
+ Args:
60
+ q (`torch.Tensor`): The query tensor.
61
+ k (`torch.Tensor`): The key tensor.
62
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
63
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
64
+ position_ids (`torch.Tensor`, *optional*):
65
+ Deprecated and unused.
66
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
67
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
68
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
69
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
70
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
71
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
72
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
73
+ Returns:
74
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
75
+ """
76
+ cos = cos.unsqueeze(unsqueeze_dim)
77
+ sin = sin.unsqueeze(unsqueeze_dim)
78
+ q_embed = (q * cos) + (rotate_half(q) * sin)
79
+ k_embed = (k * cos) + (rotate_half(k) * sin)
80
+ return q_embed, k_embed
81
+
82
+
83
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
84
+ """
85
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
86
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
87
+ """
88
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
89
+ if n_rep == 1:
90
+ return hidden_states
91
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
92
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
93
+
94
+
95
+ def eager_attention_forward(
96
+ module: nn.Module,
97
+ query: torch.Tensor,
98
+ key: torch.Tensor,
99
+ value: torch.Tensor,
100
+ attention_mask: Optional[torch.Tensor],
101
+ scaling: float,
102
+ dropout: float = 0.0,
103
+ sinks: Optional[torch.Tensor] = None,
104
+ ):
105
+ key_states = repeat_kv(key, module.num_key_value_groups)
106
+ value_states = repeat_kv(value, module.num_key_value_groups)
107
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
108
+ if attention_mask is not None:
109
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
110
+ attn_weights = attn_weights + causal_mask
111
+
112
+ if sinks is not None:
113
+ sinks = module.attention_sink_bias.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
114
+ attn_weights = torch.cat([attn_weights, sinks], dim=-1)
115
+
116
+ attn_weights = attn_weights - attn_weights.max(dim=-1, keepdim=True).values
117
+ probs = F.softmax(attn_weights, dim=-1, dtype=attn_weights.dtype)
118
+
119
+ if sinks is not None:
120
+ probs = probs[..., :-1] # we drop the sink here
121
+
122
+ attn_weights = nn.functional.dropout(probs, p=dropout, training=module.training)
123
+ attn_output = torch.matmul(attn_weights, value_states)
124
+ attn_output = attn_output.transpose(1, 2).contiguous()
125
+ return attn_output, attn_weights
126
+
127
+
128
+ @use_kernel_forward_from_hub("RMSNorm")
129
+ class MiMoV2RMSNorm(nn.Module):
130
+ def __init__(self, hidden_size, eps=1e-6):
131
+ """
132
+ MiMoV2RMSNorm is equivalent to T5LayerNorm
133
+ """
134
+ super().__init__()
135
+ self.weight = nn.Parameter(torch.ones(hidden_size))
136
+ self.variance_epsilon = eps
137
+
138
+ def forward(self, hidden_states):
139
+ input_dtype = hidden_states.dtype
140
+ hidden_states = hidden_states.to(torch.float32)
141
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
142
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
143
+ return self.weight * hidden_states.to(input_dtype)
144
+
145
+
146
+ class MiMoV2MLP(nn.Module):
147
+ """MiMoV2MLP matching the gate, up, and down projection layers."""
148
+
149
+ def __init__(self, config: MiMoV2FlashConfig, intermediate_size=None):
150
+ super().__init__()
151
+ self.config = config
152
+ self.hidden_size = config.hidden_size
153
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
154
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
155
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
156
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
157
+ self.act_fn = ACT2FN[config.hidden_act]
158
+
159
+ def forward(self, hidden_states):
160
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
161
+ return down_proj
162
+
163
+
164
+ class MiMoV2MoEGate(nn.Module):
165
+ def __init__(self, config):
166
+ super().__init__()
167
+ self.config = config
168
+ self.top_k = config.num_experts_per_tok
169
+ self.n_routed_experts = config.n_routed_experts
170
+ self.routed_scaling_factor = (
171
+ config.routed_scaling_factor
172
+ if config.routed_scaling_factor is not None
173
+ else 1.0
174
+ )
175
+ self.scoring_func = config.scoring_func
176
+ self.topk_method = config.topk_method
177
+ self.n_group = config.n_group
178
+ self.topk_group = config.topk_group
179
+
180
+ # topk selection algorithm
181
+ self.norm_topk_prob = config.norm_topk_prob
182
+ self.gating_dim = config.hidden_size
183
+ self.weight = nn.Parameter(
184
+ torch.empty((self.n_routed_experts, self.gating_dim))
185
+ )
186
+ if self.topk_method == "noaux_tc":
187
+ self.e_score_correction_bias = nn.Parameter(
188
+ torch.empty((self.n_routed_experts))
189
+ )
190
+
191
+ def forward(self, hidden_states):
192
+ bsz, seq_len, h = hidden_states.shape
193
+ ### compute gating score
194
+ hidden_states = hidden_states.view(-1, h)
195
+ logits = F.linear(
196
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
197
+ )
198
+ if self.scoring_func == "sigmoid":
199
+ scores = logits.sigmoid()
200
+ else:
201
+ raise NotImplementedError(
202
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
203
+ )
204
+
205
+ ### select top-k experts
206
+ if self.topk_method == "noaux_tc":
207
+ assert not self.training
208
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
209
+ group_scores = (
210
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
211
+ ) # [n, n_group]
212
+ group_idx = torch.topk(
213
+ group_scores, k=self.topk_group, dim=-1, sorted=False
214
+ )[
215
+ 1
216
+ ] # [n, top_k_group]
217
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
218
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
219
+ score_mask = (
220
+ group_mask.unsqueeze(-1)
221
+ .expand(
222
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
223
+ )
224
+ .reshape(bsz * seq_len, -1)
225
+ ) # [n, e]
226
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) # [n, e]
227
+ _, topk_idx = torch.topk(
228
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
229
+ )
230
+ topk_weight = scores.gather(1, topk_idx)
231
+ else:
232
+ raise NotImplementedError(
233
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
234
+ )
235
+
236
+ ### norm gate to sum 1
237
+ if self.top_k > 1 and self.norm_topk_prob:
238
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
239
+ topk_weight = topk_weight / denominator
240
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
241
+
242
+ return topk_idx, topk_weight
243
+
244
+
245
+ class MiMoV2MoE(nn.Module):
246
+ """
247
+ A mixed expert module containing shared experts.
248
+ """
249
+
250
+ def __init__(self, config):
251
+ super().__init__()
252
+ self.config = config
253
+ self.experts = nn.ModuleList(
254
+ [
255
+ MiMoV2MLP(config, intermediate_size=config.moe_intermediate_size)
256
+ for _ in range(config.n_routed_experts)
257
+ ]
258
+ )
259
+ self.gate = MiMoV2MoEGate(config)
260
+
261
+ def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
262
+ r"""
263
+ CALL FOR CONTRIBUTION! I don't have time to optimise this right now, but expert weights need to be fused
264
+ to not have to do a loop here (deepseek has 256 experts soooo yeah).
265
+ """
266
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
267
+ expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
268
+ expert_mask = expert_mask.permute(2, 0, 1)
269
+
270
+ for expert_idx in range(len(self.experts)):
271
+ expert = self.experts[expert_idx]
272
+ mask = expert_mask[expert_idx]
273
+ token_indices, weight_indices = torch.where(mask)
274
+
275
+ if token_indices.numel() > 0:
276
+ expert_weights = topk_weights[token_indices, weight_indices]
277
+ expert_input = hidden_states[token_indices]
278
+ expert_output = expert(expert_input)
279
+ weighted_output = expert_output * expert_weights.unsqueeze(-1)
280
+ final_hidden_states.index_add_(0, token_indices, weighted_output)
281
+
282
+ # in original deepseek, the output of the experts are gathered once we leave this module
283
+ # thus the moe module is itelsf an IsolatedParallel module
284
+ # and all expert are "local" meaning we shard but we don't gather
285
+ return final_hidden_states.type(hidden_states.dtype)
286
+
287
+
288
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
289
+ orig_shape = hidden_states.shape
290
+ topk_indices, topk_weights = self.gate(hidden_states)
291
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
292
+ hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
293
+
294
+ return hidden_states
295
+
296
+
297
+ class MiMoV2Attention(nn.Module):
298
+ """MiMoV2 Global Attention (pattern == 0) and Sliding Window Attention (pattern == 1)."""
299
+
300
+ def __init__(self, config: MiMoV2FlashConfig, is_swa: bool, layer_idx: int):
301
+ super().__init__()
302
+ self.config = config
303
+ self.layer_idx = layer_idx
304
+
305
+ if is_swa:
306
+ self.head_dim = config.swa_head_dim
307
+ self.v_head_dim = config.swa_v_head_dim
308
+ self.num_attention_heads = config.swa_num_attention_heads
309
+ self.num_key_value_heads = config.swa_num_key_value_heads
310
+ else:
311
+ self.head_dim = config.head_dim
312
+ self.v_head_dim = config.v_head_dim
313
+ self.num_attention_heads = config.num_attention_heads
314
+ self.num_key_value_heads = config.num_key_value_heads
315
+
316
+ self.rope_dim = int(self.head_dim * config.partial_rotary_factor)
317
+ self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
318
+ self.attention_bias = config.attention_bias
319
+ self.attention_dropout: float = config.attention_dropout
320
+ self.scaling = self.head_dim ** -0.5
321
+
322
+ # These dimensions are for the attention layers
323
+ q_hidden_size = self.num_attention_heads * self.head_dim
324
+ k_hidden_size = self.num_key_value_heads * self.head_dim
325
+ v_hidden_size = self.num_key_value_heads * self.v_head_dim
326
+ o_hidden_size = self.num_attention_heads * self.v_head_dim
327
+
328
+ self.q_proj = nn.Linear(config.hidden_size, q_hidden_size, bias=self.attention_bias)
329
+ self.k_proj = nn.Linear(config.hidden_size, k_hidden_size, bias=self.attention_bias)
330
+ self.v_proj = nn.Linear(config.hidden_size, v_hidden_size, bias=self.attention_bias)
331
+ self.o_proj = nn.Linear(o_hidden_size, config.hidden_size, bias=False)
332
+
333
+ self.v_scale = getattr(config, "attention_value_scale", None)
334
+
335
+ self.attention_sink_bias = (
336
+ torch.nn.Parameter(torch.empty(config.num_attention_heads), requires_grad=False)
337
+ if (config.add_full_attention_sink_bias and not is_swa) or (config.add_swa_attention_sink_bias and is_swa)
338
+ else None
339
+ )
340
+
341
+ def forward(
342
+ self,
343
+ hidden_states: torch.Tensor,
344
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
345
+ attention_mask: Optional[torch.Tensor],
346
+ past_key_values: Optional[Cache] = None,
347
+ cache_position: Optional[torch.LongTensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ **kwargs: Unpack[TransformersKwargs],
350
+ ) -> tuple[torch.Tensor, torch.Tensor]:
351
+ input_shape = hidden_states.shape[:-1]
352
+ qk_hidden_shape = (*input_shape, -1, self.head_dim)
353
+ v_hidden_shape = (*input_shape, -1, self.v_head_dim)
354
+
355
+ query_states = self.q_proj(hidden_states).view(qk_hidden_shape).transpose(1, 2)
356
+ key_states = self.k_proj(hidden_states).view(qk_hidden_shape).transpose(1, 2)
357
+ value_states = self.v_proj(hidden_states).view(v_hidden_shape).transpose(1, 2)
358
+
359
+ if self.v_scale is not None:
360
+ value_states = value_states * self.v_scale
361
+
362
+ cos, sin = position_embeddings
363
+
364
+ query_rope, query_nope = query_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
365
+ key_rope, key_nope = key_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
366
+
367
+ query_rope, key_rope = apply_rotary_pos_emb(query_rope, key_rope, cos, sin)
368
+
369
+ query_states = torch.cat([query_rope, query_nope], dim=-1)
370
+ key_states = torch.cat([key_rope, key_nope], dim=-1)
371
+
372
+ if past_key_values is not None:
373
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
374
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
375
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
376
+
377
+ attention_interface: Callable = eager_attention_forward
378
+ if self.config._attn_implementation != "eager":
379
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
380
+
381
+ attn_output, attn_weights = attention_interface(
382
+ self,
383
+ query_states,
384
+ key_states,
385
+ value_states,
386
+ attention_mask,
387
+ dropout=0.0 if not self.training else self.attention_dropout,
388
+ scaling=self.scaling,
389
+ position_ids=position_ids,
390
+ sinks=self.attention_sink_bias,
391
+ )
392
+
393
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
394
+ attn_output = self.o_proj(attn_output)
395
+ return attn_output, attn_weights
396
+
397
+
398
+ class MiMoV2DecoderLayer(nn.Module):
399
+ """
400
+ MiMoV2 Decoder Layer. It dynamically chooses the correct attention
401
+ module based on the layer index and the `hybrid_layer_pattern`.
402
+ """
403
+
404
+ def __init__(self, config: MiMoV2FlashConfig, layer_idx: int):
405
+ super().__init__()
406
+
407
+ # This is the key logic: choose the module based on the pattern
408
+ is_swa_layer = config.hybrid_layer_pattern[layer_idx] == 1
409
+ if is_swa_layer:
410
+ self.attention_type = "sliding_window_attention"
411
+ self.self_attn = MiMoV2Attention(config, True, layer_idx)
412
+ else:
413
+ self.attention_type = "full_attention"
414
+ self.self_attn = MiMoV2Attention(config, False, layer_idx)
415
+
416
+ self.mlp = (
417
+ MiMoV2MoE(config)
418
+ if (
419
+ getattr(config, 'n_routed_experts', None) is not None
420
+ and config.moe_layer_freq[layer_idx]
421
+ )
422
+ else MiMoV2MLP(config)
423
+ )
424
+
425
+ self.input_layernorm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
426
+ self.post_attention_layernorm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
427
+ self.hidden_size = config.hidden_size
428
+
429
+ def forward(
430
+ self,
431
+ hidden_states: torch.Tensor,
432
+ attention_mask: Optional[torch.Tensor] = None,
433
+ position_ids: Optional[torch.LongTensor] = None,
434
+ past_key_values: Optional[Cache] = None,
435
+ use_cache: Optional[bool] = False,
436
+ cache_position: Optional[torch.LongTensor] = None,
437
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
438
+ **kwargs: Unpack[TransformersKwargs],
439
+ ) -> torch.Tensor:
440
+ residual = hidden_states
441
+ hidden_states = self.input_layernorm(hidden_states)
442
+ # Self Attention
443
+ hidden_states, _ = self.self_attn(
444
+ hidden_states=hidden_states,
445
+ attention_mask=attention_mask,
446
+ position_ids=position_ids,
447
+ past_key_values=past_key_values,
448
+ use_cache=use_cache,
449
+ cache_position=cache_position,
450
+ position_embeddings=position_embeddings,
451
+ **kwargs,
452
+ )
453
+ hidden_states = residual + hidden_states
454
+
455
+ # MLP or MOE
456
+ residual = hidden_states
457
+ hidden_states = self.post_attention_layernorm(hidden_states)
458
+ hidden_states = self.mlp(hidden_states)
459
+ hidden_states = residual + hidden_states
460
+ return hidden_states
461
+
462
+ class MiMoV2FlashRotaryEmbedding(nn.Module):
463
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
464
+
465
+ def __init__(self, config: MiMoV2FlashConfig, is_swa, device=None):
466
+ super().__init__()
467
+ # BC: "rope_type" was originally "type"
468
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
469
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
470
+ else:
471
+ self.rope_type = "default"
472
+ self.max_seq_len_cached = config.max_position_embeddings
473
+ self.original_max_seq_len = config.max_position_embeddings
474
+
475
+ self.config = config
476
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
477
+
478
+ if is_swa:
479
+ self.config.rope_theta = config.swa_rope_theta
480
+ self.config.head_dim = config.swa_head_dim
481
+
482
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
483
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
484
+ self.original_inv_freq = self.inv_freq
485
+
486
+ @torch.no_grad()
487
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
488
+ def forward(self, x, position_ids):
489
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
490
+ position_ids_expanded = position_ids[:, None, :].float()
491
+
492
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
493
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
494
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
495
+ emb = torch.cat((freqs, freqs), dim=-1)
496
+ cos = emb.cos() * self.attention_scaling
497
+ sin = emb.sin() * self.attention_scaling
498
+
499
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
500
+
501
+
502
+ @auto_docstring
503
+ class MiMoV2Model(PreTrainedModel):
504
+ """The main 'model' block, corresponding to `model.` in the weight map."""
505
+ config_class = MiMoV2FlashConfig
506
+
507
+ def __init__(self, config: MiMoV2FlashConfig):
508
+ super().__init__(config)
509
+ self.vocab_size = config.vocab_size
510
+
511
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
512
+ self.layers = nn.ModuleList(
513
+ [MiMoV2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
514
+ )
515
+ self.norm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
516
+ self.rotary_emb = MiMoV2FlashRotaryEmbedding(config=config, is_swa=False)
517
+ self.swa_rotary_emb = MiMoV2FlashRotaryEmbedding(config=config, is_swa=True)
518
+
519
+ self.has_sliding_layers = any(
520
+ pattern == 1 for pattern in config.hybrid_layer_pattern
521
+ )
522
+
523
+ # For Huggingface DynamicCache compatibility
524
+ self.config.layer_types = [
525
+ "sliding_attention" if config.hybrid_layer_pattern[i] == 1 else "full_attention"
526
+ for i in range(config.num_hidden_layers)
527
+ ]
528
+
529
+ @auto_docstring
530
+ def forward(
531
+ self,
532
+ input_ids: Optional[torch.LongTensor] = None,
533
+ attention_mask: Optional[torch.Tensor] = None,
534
+ position_ids: Optional[torch.LongTensor] = None,
535
+ past_key_values: Optional[Cache] = None,
536
+ inputs_embeds: Optional[torch.FloatTensor] = None,
537
+ use_cache: Optional[bool] = None,
538
+ cache_position: Optional[torch.LongTensor] = None,
539
+ **kwargs: Unpack[TransformersKwargs],
540
+ ) -> MoeModelOutputWithPast:
541
+ if (input_ids is None) ^ (inputs_embeds is not None):
542
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
543
+
544
+ if inputs_embeds is None:
545
+ inputs_embeds = self.embed_tokens(input_ids)
546
+
547
+ if use_cache and past_key_values is None:
548
+ past_key_values = DynamicCache(config=self.config)
549
+
550
+ if cache_position is None:
551
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
552
+ cache_position = torch.arange(
553
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
554
+ )
555
+
556
+ if position_ids is None:
557
+ position_ids = cache_position.unsqueeze(0)
558
+
559
+ # It may already have been prepared by e.g. `generate`
560
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
561
+ # Prepare mask arguments
562
+ mask_kwargs = {
563
+ "config": self.config,
564
+ "input_embeds": inputs_embeds,
565
+ "attention_mask": attention_mask,
566
+ "cache_position": cache_position,
567
+ "past_key_values": past_key_values,
568
+ "position_ids": position_ids,
569
+ }
570
+ # Create the masks
571
+ causal_mask_mapping = {
572
+ "full_attention": create_causal_mask(**mask_kwargs),
573
+ }
574
+ # The sliding window alternating layers are not always activated depending on the config
575
+ if self.has_sliding_layers:
576
+ causal_mask_mapping["sliding_window_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
577
+
578
+ hidden_states = inputs_embeds
579
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
580
+ swa_position_embeddings = self.swa_rotary_emb(hidden_states, position_ids)
581
+
582
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
583
+ hidden_states = decoder_layer(
584
+ hidden_states,
585
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
586
+ position_embeddings=(
587
+ position_embeddings
588
+ if decoder_layer.attention_type == "full_attention"
589
+ else swa_position_embeddings
590
+ ),
591
+ position_ids=position_ids,
592
+ past_key_values=past_key_values,
593
+ use_cache=use_cache,
594
+ cache_position=cache_position,
595
+ **kwargs,
596
+ )
597
+
598
+ hidden_states = self.norm(hidden_states)
599
+ return BaseModelOutputWithPast(
600
+ last_hidden_state=hidden_states,
601
+ past_key_values=past_key_values if use_cache else None,
602
+ )
603
+
604
+
605
+ @auto_docstring
606
+ class MiMoV2FlashForCausalLM(PreTrainedModel,GenerationMixin):
607
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
608
+ _tp_plan = {"lm_head": "colwise_rep"}
609
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
610
+
611
+ config_class = MiMoV2FlashConfig
612
+ _keys_to_ignore_on_load_unexpected = [r"model.layers\.\d+\.self_attn\.rotary_emb\.inv_freq"]
613
+
614
+ def __init__(self, config: MiMoV2FlashConfig):
615
+ super().__init__(config)
616
+ self.model = MiMoV2Model(config)
617
+ self.vocab_size = config.vocab_size
618
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
619
+
620
+ # Initialize weights and apply final processing
621
+ self.post_init()
622
+
623
+ @can_return_tuple
624
+ @auto_docstring
625
+ def forward(
626
+ self,
627
+ input_ids: Optional[torch.LongTensor] = None,
628
+ attention_mask: Optional[torch.Tensor] = None,
629
+ position_ids: Optional[torch.LongTensor] = None,
630
+ past_key_values: Optional[Cache] = None,
631
+ inputs_embeds: Optional[torch.FloatTensor] = None,
632
+ labels: Optional[torch.LongTensor] = None,
633
+ use_cache: Optional[bool] = None,
634
+ cache_position: Optional[torch.LongTensor] = None,
635
+ logits_to_keep: Union[int, torch.Tensor] = 0,
636
+ **kwargs: Unpack[TransformersKwargs],
637
+ ) -> CausalLMOutputWithPast:
638
+
639
+ outputs: BaseModelOutputWithPast = self.model(
640
+ input_ids=input_ids,
641
+ attention_mask=attention_mask,
642
+ position_ids=position_ids,
643
+ past_key_values=past_key_values,
644
+ inputs_embeds=inputs_embeds,
645
+ use_cache=use_cache,
646
+ cache_position=cache_position,
647
+ **kwargs,
648
+ )
649
+
650
+ hidden_states = outputs.last_hidden_state
651
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
652
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
653
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
654
+
655
+ loss = None
656
+ if labels is not None:
657
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
658
+
659
+ return CausalLMOutputWithPast(
660
+ loss=loss,
661
+ logits=logits,
662
+ past_key_values=outputs.past_key_values,
663
+ hidden_states=outputs.hidden_states,
664
+ attentions=outputs.attentions,
665
+ )
666
+
667
+ __all__ = [
668
+ "MiMoV2FlashForCausalLM"
669
+ ]