bb1975/MiMo-V2.5-Pro
1378
1# coding=utf-8
2#
3# Copyright 2026 Xiaomi Corporation.
4# Copyright 2026 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
18from copy import copy
19from typing import Callable, Optional, Union
20
21import torch
22import torch.nn as nn
23import torch.nn.functional as F
24
25from transformers.activations import ACT2FN
26from transformers.cache_utils import Cache, DynamicCache
27from transformers.generation import GenerationMixin
28from transformers.integrations import use_kernel_forward_from_hub
29from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
30from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
31from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
32from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
33from transformers.processing_utils import Unpack
34from transformers.utils import TransformersKwargs, can_return_tuple, logging
35
36from .configuration_mimo_v2 import MiMoV2Config
37
38
39logger = logging.get_logger(__name__)
40
41
42def rotate_half(x):
43 """Rotates half the hidden dims of the input."""
44 x1 = x[..., : x.shape[-1] // 2]
45 x2 = x[..., x.shape[-1] // 2 :]
46 return torch.cat((-x2, x1), dim=-1)
47
48
49def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
50 """Applies rotary position embedding to query and key tensors."""
51 cos = cos.unsqueeze(unsqueeze_dim)
52 sin = sin.unsqueeze(unsqueeze_dim)
53 q_embed = (q * cos) + (rotate_half(q) * sin)
54 k_embed = (k * cos) + (rotate_half(k) * sin)
55 return q_embed, k_embed
56
57
58def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
59 batch, num_key_value_heads, slen, head_dim = hidden_states.shape
60 if n_rep == 1:
61 return hidden_states
62 hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
63 return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
64
65
66def eager_attention_forward(
67 module: nn.Module,
68 query: torch.Tensor,
69 key: torch.Tensor,
70 value: torch.Tensor,
71 attention_mask: Optional[torch.Tensor],
72 scaling: float,
73 dropout: float = 0.0,
74 sinks: Optional[torch.Tensor] = None,
75 **kwargs,
76):
77 key_states = repeat_kv(key, module.num_key_value_groups)
78 value_states = repeat_kv(value, module.num_key_value_groups)
79 attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
80 if attention_mask is not None:
81 causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
82 attn_weights = attn_weights + causal_mask
83
84 if sinks is not None:
85 sinks = module.attention_sink_bias.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
86 attn_weights = torch.cat([attn_weights, sinks], dim=-1)
87
88 attn_weights = attn_weights - attn_weights.max(dim=-1, keepdim=True).values
89 probs = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
90
91 if sinks is not None:
92 probs = probs[..., :-1]
93
94 attn_weights = nn.functional.dropout(probs, p=dropout, training=module.training)
95 attn_output = torch.matmul(attn_weights, value_states)
96 attn_output = attn_output.transpose(1, 2).contiguous()
97 return attn_output, attn_weights
98
99
100@use_kernel_forward_from_hub("RMSNorm")
101class MiMoV2RMSNorm(nn.Module):
102 def __init__(self, hidden_size, eps=1e-6):
103 super().__init__()
104 self.weight = nn.Parameter(torch.ones(hidden_size))
105 self.variance_epsilon = eps
106
107 def forward(self, hidden_states):
108 input_dtype = hidden_states.dtype
109 hidden_states = hidden_states.to(torch.float32)
110 variance = hidden_states.pow(2).mean(-1, keepdim=True)
111 hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
112 return self.weight * hidden_states.to(input_dtype)
113
114
115class MiMoV2MLP(nn.Module):
116 def __init__(self, config, intermediate_size=None):
117 super().__init__()
118 self.config = config
119 self.hidden_size = config.hidden_size
120 self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
121 self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
122 self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
123 self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
124 self.act_fn = ACT2FN[config.hidden_act]
125
126 def forward(self, hidden_states):
127 return self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
128
129
130class MiMoV2MoEGate(nn.Module):
131 def __init__(self, config):
132 super().__init__()
133 self.config = config
134 self.top_k = config.num_experts_per_tok
135 self.n_routed_experts = config.n_routed_experts
136 self.routed_scaling_factor = config.routed_scaling_factor if config.routed_scaling_factor is not None else 1.0
137 self.scoring_func = config.scoring_func
138 self.topk_method = config.topk_method
139 self.n_group = config.n_group
140 self.topk_group = config.topk_group
141 self.norm_topk_prob = config.norm_topk_prob
142 self.gating_dim = config.hidden_size
143 self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
144 if self.topk_method == "noaux_tc":
145 self.e_score_correction_bias = nn.Parameter(torch.empty((self.n_routed_experts)))
146
147 def forward(self, hidden_states):
148 bsz, seq_len, h = hidden_states.shape
149 hidden_states = hidden_states.view(-1, h)
150 logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32), None)
151 if self.scoring_func == "sigmoid":
152 scores = logits.sigmoid()
153 else:
154 raise NotImplementedError(f"Unsupported scoring function for MoE gating: {self.scoring_func}")
155
156 if self.topk_method == "noaux_tc":
157 if self.training:
158 raise ValueError("MiMoV2 noaux_tc routing is only implemented for inference.")
159 scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
160 group_scores = scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
161 group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
162 group_mask = torch.zeros_like(group_scores)
163 group_mask.scatter_(1, group_idx, 1)
164 score_mask = (
165 group_mask.unsqueeze(-1)
166 .expand(bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group)
167 .reshape(bsz * seq_len, -1)
168 )
169 tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
170 _, topk_idx = torch.topk(tmp_scores, k=self.top_k, dim=-1, sorted=False)
171 topk_weight = scores.gather(1, topk_idx)
172 else:
173 raise NotImplementedError(f"Unsupported TopK function for MoE gating: {self.topk_method}")
174
175 if self.top_k > 1 and self.norm_topk_prob:
176 denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
177 topk_weight = topk_weight / denominator
178 topk_weight = topk_weight * self.routed_scaling_factor
179 return topk_idx, topk_weight
180
181
182class MiMoV2MoE(nn.Module):
183 def __init__(self, config):
184 super().__init__()
185 self.config = config
186 self.experts = nn.ModuleList(
187 [MiMoV2MLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.n_routed_experts)]
188 )
189 self.gate = MiMoV2MoEGate(config)
190
191 def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
192 final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
193 expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
194 expert_mask = expert_mask.permute(2, 0, 1)
195
196 for expert_idx, expert in enumerate(self.experts):
197 mask = expert_mask[expert_idx]
198 token_indices, weight_indices = torch.where(mask)
199 if token_indices.numel() > 0:
200 expert_weights = topk_weights[token_indices, weight_indices]
201 expert_input = hidden_states[token_indices]
202 expert_output = expert(expert_input)
203 final_hidden_states.index_add_(0, token_indices, expert_output * expert_weights.unsqueeze(-1))
204
205 return final_hidden_states.type(hidden_states.dtype)
206
207 def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
208 orig_shape = hidden_states.shape
209 topk_indices, topk_weights = self.gate(hidden_states)
210 hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
211 hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
212 return hidden_states
213
214
215class MiMoV2Attention(nn.Module):
216 """MiMoV2 attention.
217
218 `projection_layout` only controls how checkpoint weights are named and
219 stored: Flash uses separate q/k/v projections, while Pro uses fused qkv.
220 The attention computation after projection is shared.
221 """
222
223 def __init__(self, config, is_swa: bool, layer_idx: int, projection_layout: str = "split"):
224 super().__init__()
225 if projection_layout not in {"split", "fused_qkv"}:
226 raise ValueError(f"Unsupported MiMoV2 attention projection layout: {projection_layout}")
227
228 self.config = config
229 self.layer_idx = layer_idx
230 self.is_swa = is_swa
231 self.is_causal = True
232 self.projection_layout = projection_layout
233
234 default_head_dim = config.hidden_size // config.num_attention_heads
235 default_v_head_dim = getattr(config, "v_head_dim", default_head_dim)
236
237 if is_swa:
238 self.head_dim = getattr(config, "swa_head_dim", getattr(config, "head_dim", default_head_dim))
239 self.v_head_dim = getattr(config, "swa_v_head_dim", default_v_head_dim)
240 self.num_attention_heads = getattr(config, "swa_num_attention_heads", config.num_attention_heads)
241 self.num_key_value_heads = getattr(config, "swa_num_key_value_heads", config.num_key_value_heads)
242 else:
243 self.head_dim = getattr(config, "head_dim", default_head_dim)
244 self.v_head_dim = getattr(config, "v_head_dim", self.head_dim)
245 self.num_attention_heads = config.num_attention_heads
246 self.num_key_value_heads = config.num_key_value_heads
247
248 self.rope_dim = int(self.head_dim * getattr(config, "partial_rotary_factor", 1.0))
249 if self.rope_dim % 2 != 0:
250 raise ValueError(
251 f"MiMoV2 rotary dimension must be even, got {self.rope_dim} from "
252 f"head_dim={self.head_dim} and partial_rotary_factor={getattr(config, 'partial_rotary_factor', 1.0)}"
253 )
254 self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
255 self.attention_dropout = getattr(config, "attention_dropout", 0.0)
256 self.scaling = self.head_dim**-0.5
257 self.sliding_window = getattr(config, "sliding_window", None) if is_swa else None
258 self.q_size = self.num_attention_heads * self.head_dim
259 self.k_size = self.num_key_value_heads * self.head_dim
260 self.v_size = self.num_key_value_heads * self.v_head_dim
261 self.o_hidden_size = self.num_attention_heads * self.v_head_dim
262 self.v_scale = getattr(config, "attention_value_scale", None)
263 self.attention_sink_bias = (
264 nn.Parameter(torch.empty(self.num_attention_heads), requires_grad=False)
265 if (
266 (getattr(config, "add_full_attention_sink_bias", False) and not is_swa)
267 or (getattr(config, "add_swa_attention_sink_bias", False) and is_swa)
268 )
269 else None
270 )
271
272 attention_bias = getattr(config, "attention_bias", False)
273 if self.projection_layout == "fused_qkv":
274 self.qkv_proj = nn.Linear(
275 config.hidden_size,
276 self.q_size + self.k_size + self.v_size,
277 bias=attention_bias,
278 )
279 else:
280 self.q_proj = nn.Linear(config.hidden_size, self.q_size, bias=attention_bias)
281 self.k_proj = nn.Linear(config.hidden_size, self.k_size, bias=attention_bias)
282 self.v_proj = nn.Linear(config.hidden_size, self.v_size, bias=attention_bias)
283 self.o_proj = nn.Linear(self.o_hidden_size, config.hidden_size, bias=False)
284
285 def _forward_attention(
286 self,
287 query_states: torch.Tensor,
288 key_states: torch.Tensor,
289 value_states: torch.Tensor,
290 input_shape: torch.Size,
291 position_embeddings: tuple[torch.Tensor, torch.Tensor],
292 attention_mask: Optional[torch.Tensor],
293 past_key_values: Optional[Cache] = None,
294 cache_position: Optional[torch.LongTensor] = None,
295 position_ids: Optional[torch.LongTensor] = None,
296 ) -> tuple[torch.Tensor, torch.Tensor]:
297 if self.v_scale is not None:
298 value_states = value_states * self.v_scale
299
300 cos, sin = position_embeddings
301 query_rope, query_nope = query_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
302 key_rope, key_nope = key_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
303 query_rope, key_rope = apply_rotary_pos_emb(query_rope, key_rope, cos, sin)
304 query_states = torch.cat([query_rope, query_nope], dim=-1)
305 key_states = torch.cat([key_rope, key_nope], dim=-1)
306
307 if past_key_values is not None:
308 cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
309 key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
310
311 attn_implementation = self.config._attn_implementation
312 if attn_implementation is not None and attn_implementation.startswith("paged|"):
313 raise ValueError(
314 "MiMoV2 remote code does not support paged attention cache. "
315 "Please use eager, sdpa, flex_attention, or flash_attention_2."
316 )
317
318 attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
319 attn_implementation, eager_attention_forward
320 )
321 if self.attention_sink_bias is not None and attn_implementation == "sdpa":
322 logger.warning_once(
323 "MiMoV2 attention sink bias is not supported by SDPA; falling back to eager attention for correctness."
324 )
325 attention_interface = eager_attention_forward
326
327 attention_kwargs = {
328 "dropout": 0.0 if not self.training else self.attention_dropout,
329 "scaling": self.scaling,
330 "position_ids": position_ids,
331 "is_causal": self.is_causal,
332 }
333 if attention_interface is eager_attention_forward:
334 attention_kwargs["sinks"] = self.attention_sink_bias
335 else:
336 if self.attention_sink_bias is not None:
337 attention_kwargs["s_aux"] = self.attention_sink_bias
338 if self.sliding_window is not None:
339 attention_kwargs["sliding_window"] = self.sliding_window
340
341 attn_output, attn_weights = attention_interface(
342 self,
343 query_states,
344 key_states,
345 value_states,
346 attention_mask,
347 **attention_kwargs,
348 )
349 attn_output = attn_output.reshape(*input_shape, -1).contiguous()
350 attn_output = self.o_proj(attn_output)
351 return attn_output, attn_weights
352
353 def forward(
354 self,
355 hidden_states: torch.Tensor,
356 position_embeddings: tuple[torch.Tensor, torch.Tensor],
357 attention_mask: Optional[torch.Tensor],
358 past_key_values: Optional[Cache] = None,
359 cache_position: Optional[torch.LongTensor] = None,
360 position_ids: Optional[torch.LongTensor] = None,
361 **kwargs: Unpack[TransformersKwargs],
362 ) -> tuple[torch.Tensor, torch.Tensor]:
363 input_shape = hidden_states.shape[:-1]
364
365 if self.projection_layout == "fused_qkv":
366 qkv_states = self.qkv_proj(hidden_states)
367 query_states, key_states, value_states = qkv_states.split([self.q_size, self.k_size, self.v_size], dim=-1)
368 else:
369 query_states = self.q_proj(hidden_states)
370 key_states = self.k_proj(hidden_states)
371 value_states = self.v_proj(hidden_states)
372
373 query_states = query_states.view(*input_shape, self.num_attention_heads, self.head_dim).transpose(1, 2)
374 key_states = key_states.view(*input_shape, self.num_key_value_heads, self.head_dim).transpose(1, 2)
375 value_states = value_states.view(*input_shape, self.num_key_value_heads, self.v_head_dim).transpose(1, 2)
376 return self._forward_attention(
377 query_states,
378 key_states,
379 value_states,
380 input_shape,
381 position_embeddings,
382 attention_mask,
383 past_key_values=past_key_values,
384 cache_position=cache_position,
385 position_ids=position_ids,
386 )
387
388
389class MiMoV2DecoderLayer(nn.Module):
390 attention_projection_layout = "split"
391
392 def __init__(self, config, layer_idx: int, attention_projection_layout: Optional[str] = None):
393 super().__init__()
394 attention_projection_layout = attention_projection_layout or self.attention_projection_layout
395 is_swa_layer = config.hybrid_layer_pattern[layer_idx] == 1
396 self.attention_type = "sliding_window_attention" if is_swa_layer else "full_attention"
397 self.self_attn = MiMoV2Attention(
398 config, is_swa_layer, layer_idx, projection_layout=attention_projection_layout
399 )
400 self.mlp = (
401 MiMoV2MoE(config)
402 if getattr(config, "n_routed_experts", None) is not None and config.moe_layer_freq[layer_idx]
403 else MiMoV2MLP(config)
404 )
405 self.input_layernorm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
406 self.post_attention_layernorm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
407
408 def forward(
409 self,
410 hidden_states: torch.Tensor,
411 attention_mask: Optional[torch.Tensor] = None,
412 position_ids: Optional[torch.LongTensor] = None,
413 past_key_values: Optional[Cache] = None,
414 use_cache: Optional[bool] = False,
415 cache_position: Optional[torch.LongTensor] = None,
416 position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
417 **kwargs: Unpack[TransformersKwargs],
418 ) -> torch.Tensor:
419 residual = hidden_states
420 hidden_states = self.input_layernorm(hidden_states)
421 hidden_states, _ = self.self_attn(
422 hidden_states=hidden_states,
423 attention_mask=attention_mask,
424 position_ids=position_ids,
425 past_key_values=past_key_values,
426 use_cache=use_cache,
427 cache_position=cache_position,
428 position_embeddings=position_embeddings,
429 **kwargs,
430 )
431 hidden_states = residual + hidden_states
432
433 residual = hidden_states
434 hidden_states = self.post_attention_layernorm(hidden_states)
435 hidden_states = self.mlp(hidden_states)
436 hidden_states = residual + hidden_states
437 return hidden_states
438
439
440class MiMoV2RotaryEmbedding(nn.Module):
441 inv_freq: torch.Tensor
442
443 def __init__(self, config, is_swa: bool, device=None):
444 super().__init__()
445 if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
446 self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type", "default"))
447 else:
448 self.rope_type = "default"
449 self.max_seq_len_cached = config.max_position_embeddings
450 self.original_max_seq_len = config.max_position_embeddings
451
452 self.config = copy(config)
453 self.config.rope_parameters = copy(getattr(config, "rope_parameters", None) or {})
454 if is_swa:
455 self.config.rope_theta = getattr(config, "swa_rope_theta", config.rope_theta)
456 self.config.head_dim = getattr(config, "swa_head_dim", getattr(config, "head_dim", None))
457 if self.config.rope_parameters:
458 self.config.rope_parameters["rope_theta"] = self.config.rope_theta
459 self.rope_init_fn = (
460 self.compute_default_rope_parameters
461 if self.rope_type == "default"
462 else ROPE_INIT_FUNCTIONS[self.rope_type]
463 )
464
465 inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
466 self.register_buffer("inv_freq", inv_freq, persistent=False)
467 self.original_inv_freq = self.inv_freq
468
469 @staticmethod
470 def compute_default_rope_parameters(config, device=None, seq_len=None, layer_type=None):
471 config.standardize_rope_params()
472 rope_parameters = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters
473 base = rope_parameters["rope_theta"]
474 partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
475 head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
476 dim = int(head_dim * partial_rotary_factor)
477 if dim % 2 != 0:
478 raise ValueError(
479 f"MiMoV2 rotary dimension must be even, got {dim} from "
480 f"head_dim={head_dim} and partial_rotary_factor={partial_rotary_factor}"
481 )
482 inv_freq = 1.0 / (
483 base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
484 )
485 return inv_freq, 1.0
486
487 @torch.no_grad()
488 @dynamic_rope_update
489 def forward(self, x, position_ids):
490 inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
491 position_ids_expanded = position_ids[:, None, :].float()
492
493 device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
494 with torch.autocast(device_type=device_type, enabled=False):
495 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
496 emb = torch.cat((freqs, freqs), dim=-1)
497 cos = emb.cos() * self.attention_scaling
498 sin = emb.sin() * self.attention_scaling
499
500 return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
501
502
503class MiMoV2Model(PreTrainedModel):
504 config_class = MiMoV2Config
505 attention_projection_layout = "split"
506
507 def __init__(self, config):
508 super().__init__(config)
509 self.attention_projection_layout = getattr(
510 config, "attention_projection_layout", self.attention_projection_layout
511 )
512 self.vocab_size = config.vocab_size
513 self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
514 self.layers = nn.ModuleList(
515 [
516 MiMoV2DecoderLayer(
517 config,
518 layer_idx,
519 attention_projection_layout=self.attention_projection_layout,
520 )
521 for layer_idx in range(config.num_hidden_layers)
522 ]
523 )
524 self.norm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
525 self.rotary_emb = MiMoV2RotaryEmbedding(config=config, is_swa=False)
526 self.swa_rotary_emb = MiMoV2RotaryEmbedding(config=config, is_swa=True)
527 self.has_sliding_layers = any(pattern == 1 for pattern in config.hybrid_layer_pattern)
528 self.config.layer_types = [
529 "sliding_attention" if config.hybrid_layer_pattern[i] == 1 else "full_attention"
530 for i in range(config.num_hidden_layers)
531 ]
532 self.post_init()
533
534 def get_input_embeddings(self):
535 return self.embed_tokens
536
537 def set_input_embeddings(self, value):
538 self.embed_tokens = value
539
540 def forward(
541 self,
542 input_ids: Optional[torch.LongTensor] = None,
543 attention_mask: Optional[torch.Tensor] = None,
544 position_ids: Optional[torch.LongTensor] = None,
545 past_key_values: Optional[Cache] = None,
546 inputs_embeds: Optional[torch.FloatTensor] = None,
547 use_cache: Optional[bool] = None,
548 cache_position: Optional[torch.LongTensor] = None,
549 **kwargs: Unpack[TransformersKwargs],
550 ) -> BaseModelOutputWithPast:
551 if (input_ids is None) ^ (inputs_embeds is not None):
552 raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
553
554 use_cache = use_cache if use_cache is not None else self.config.use_cache
555
556 if inputs_embeds is None:
557 inputs_embeds = self.embed_tokens(input_ids)
558
559 if use_cache and past_key_values is None:
560 past_key_values = DynamicCache(config=self.config)
561
562 if cache_position is None:
563 past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
564 cache_position = torch.arange(
565 past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
566 )
567
568 if position_ids is None:
569 position_ids = cache_position.unsqueeze(0)
570
571 if not isinstance(causal_mask_mapping := attention_mask, dict):
572 mask_kwargs = {
573 "config": self.config,
574 "input_embeds": inputs_embeds,
575 "attention_mask": attention_mask,
576 "cache_position": cache_position,
577 "past_key_values": past_key_values,
578 "position_ids": position_ids,
579 }
580 causal_mask_mapping = {
581 "full_attention": create_causal_mask(**mask_kwargs),
582 }
583 if self.has_sliding_layers:
584 if getattr(self.config, "sliding_window", None) is None:
585 raise ValueError("MiMoV2 config `sliding_window` must be set when hybrid_layer_pattern uses SWA.")
586 causal_mask_mapping["sliding_window_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
587
588 hidden_states = inputs_embeds
589 position_embeddings = self.rotary_emb(hidden_states, position_ids)
590 swa_position_embeddings = self.swa_rotary_emb(hidden_states, position_ids)
591
592 for decoder_layer in self.layers[: self.config.num_hidden_layers]:
593 hidden_states = decoder_layer(
594 hidden_states,
595 attention_mask=causal_mask_mapping[decoder_layer.attention_type],
596 position_embeddings=position_embeddings
597 if decoder_layer.attention_type == "full_attention"
598 else swa_position_embeddings,
599 position_ids=position_ids,
600 past_key_values=past_key_values,
601 use_cache=use_cache,
602 cache_position=cache_position,
603 **kwargs,
604 )
605
606 hidden_states = self.norm(hidden_states)
607 return BaseModelOutputWithPast(
608 last_hidden_state=hidden_states,
609 past_key_values=past_key_values if use_cache else None,
610 )
611
612
613class MiMoV2ForCausalLM(PreTrainedModel, GenerationMixin):
614 config_class = MiMoV2Config
615 model_class = MiMoV2Model
616 _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
617 _tp_plan = {"lm_head": "colwise_rep"}
618 _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
619 _keys_to_ignore_on_load_unexpected = [
620 r"model\.(swa_)?rotary_emb\.inv_freq",
621 r"model\.layers\.\d+\.self_attn\.rotary_emb\.inv_freq",
622 r"model\.layers\.\d+\.self_attn\.rotary_emb\.(cos_cached|sin_cached)",
623 r"model\.mtp\..*",
624 ]
625
626 def __init__(self, config):
627 super().__init__(config)
628 self.model = self.model_class(config)
629 self.vocab_size = config.vocab_size
630 self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
631 self.post_init()
632
633 def get_input_embeddings(self):
634 return self.model.embed_tokens
635
636 def set_input_embeddings(self, value):
637 self.model.embed_tokens = value
638
639 def get_output_embeddings(self):
640 return self.lm_head
641
642 def set_output_embeddings(self, new_embeddings):
643 self.lm_head = new_embeddings
644
645 @can_return_tuple
646 def forward(
647 self,
648 input_ids: Optional[torch.LongTensor] = None,
649 attention_mask: Optional[torch.Tensor] = None,
650 position_ids: Optional[torch.LongTensor] = None,
651 past_key_values: Optional[Cache] = None,
652 inputs_embeds: Optional[torch.FloatTensor] = None,
653 labels: Optional[torch.LongTensor] = None,
654 use_cache: Optional[bool] = None,
655 cache_position: Optional[torch.LongTensor] = None,
656 logits_to_keep: Union[int, torch.Tensor] = 0,
657 **kwargs: Unpack[TransformersKwargs],
658 ) -> CausalLMOutputWithPast:
659 outputs: BaseModelOutputWithPast = self.model(
660 input_ids=input_ids,
661 attention_mask=attention_mask,
662 position_ids=position_ids,
663 past_key_values=past_key_values,
664 inputs_embeds=inputs_embeds,
665 use_cache=use_cache,
666 cache_position=cache_position,
667 **kwargs,
668 )
669
670 hidden_states = outputs.last_hidden_state
671 slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
672 logits = self.lm_head(hidden_states[:, slice_indices, :])
673
674 loss = None
675 if labels is not None:
676 loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
677
678 return CausalLMOutputWithPast(
679 loss=loss,
680 logits=logits,
681 past_key_values=outputs.past_key_values,
682 hidden_states=outputs.hidden_states,
683 attentions=outputs.attentions,
684 )
685
686
687__all__ = [
688 "MiMoV2Attention",
689 "MiMoV2DecoderLayer",
690 "MiMoV2ForCausalLM",
691 "MiMoV2MLP",
692 "MiMoV2MoE",
693 "MiMoV2MoEGate",
694 "MiMoV2Model",
695 "MiMoV2RMSNorm",
696 "MiMoV2RotaryEmbedding",
697]
698 