modeling_minimax.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/minimax/modular_minimax.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_minimax.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2025 MiniMaxAI and HuggingFace Inc. teams. All rights reserved.
  8. #
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. from collections.abc import Callable
  22. from typing import Optional
  23. import torch
  24. import torch.nn.functional as F
  25. from torch import nn
  26. from ... import initialization as init
  27. from ...activations import ACT2FN
  28. from ...cache_utils import Cache, DynamicCache
  29. from ...generation import GenerationMixin
  30. from ...integrations import (
  31. use_experts_implementation,
  32. use_kernel_forward_from_hub,
  33. use_kernel_func_from_hub,
  34. use_kernelized_func,
  35. )
  36. from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
  37. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  38. from ...modeling_layers import (
  39. GenericForQuestionAnswering,
  40. GenericForSequenceClassification,
  41. GenericForTokenClassification,
  42. GradientCheckpointingLayer,
  43. )
  44. from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
  45. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  46. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  47. from ...processing_utils import Unpack
  48. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
  49. from ...utils.generic import maybe_autocast, merge_with_config_defaults
  50. from ...utils.output_capturing import OutputRecorder, capture_outputs
  51. from .configuration_minimax import MiniMaxConfig
  52. @use_kernel_forward_from_hub("RMSNorm")
  53. class MiniMaxRMSNorm(nn.Module):
  54. def __init__(self, hidden_size, eps: float = 1e-6) -> None:
  55. """
  56. MiniMaxRMSNorm is equivalent to T5LayerNorm
  57. """
  58. super().__init__()
  59. self.weight = nn.Parameter(torch.ones(hidden_size))
  60. self.variance_epsilon = eps
  61. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  62. input_dtype = hidden_states.dtype
  63. hidden_states = hidden_states.to(torch.float32)
  64. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  65. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  66. return self.weight * hidden_states.to(input_dtype)
  67. def extra_repr(self):
  68. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  69. class MiniMaxCache(DynamicCache):
  70. def __init__(self):
  71. super().__init__()
  72. self.linear_cache: list[torch.Tensor] = []
  73. def set_linear_cache(self, layer_idx, linear_cache):
  74. # There may be skipped layers, fill them with empty lists
  75. for _ in range(len(self.linear_cache), layer_idx + 1):
  76. self.linear_cache.append([])
  77. self.linear_cache[layer_idx] = linear_cache
  78. def get_linear_cache(self, layer_idx: int):
  79. if layer_idx < len(self):
  80. return self.linear_cache[layer_idx]
  81. return None
  82. def __len__(self):
  83. return max(super().__len__(), len(self.linear_cache))
  84. def batch_repeat_interleave(self, repeats: int):
  85. for layer_idx in range(len(self)):
  86. if self.linear_cache[layer_idx] != []:
  87. self.linear_cache[layer_idx] = self.linear_cache[layer_idx].repeat_interleave(repeats, dim=0)
  88. else:
  89. self.layers[layer_idx].batch_repeat_interleave(repeats)
  90. def batch_select_indices(self, indices: torch.Tensor):
  91. for layer_idx in range(len(self)):
  92. if self.linear_cache[layer_idx] != []:
  93. self.linear_cache[layer_idx] = self.linear_cache[layer_idx][indices, ...]
  94. else:
  95. self.layers[layer_idx].batch_select_indices(indices)
  96. def crop(self, max_length: int):
  97. raise RuntimeError("MiniMaxCache doesnot support `crop` method")
  98. class MiniMaxLightningAttention(nn.Module):
  99. def __init__(self, config: MiniMaxConfig, layer_idx: int):
  100. super().__init__()
  101. self.layer_idx = layer_idx
  102. self.head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
  103. self.num_attention_heads = config.num_attention_heads
  104. self.num_hidden_layers = config.num_hidden_layers
  105. self.block_size = config.block_size
  106. self.act_fn = ACT2FN[config.hidden_act]
  107. self.norm = MiniMaxRMSNorm(self.head_dim * self.num_attention_heads)
  108. self.qkv_proj = nn.Linear(config.hidden_size, self.num_attention_heads * self.head_dim * 3, bias=False)
  109. self.out_proj = nn.Linear(self.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
  110. self.output_gate = nn.Linear(config.hidden_size, self.num_attention_heads * self.head_dim, bias=False)
  111. slope_rate = self.get_slope_rate()
  112. query_decay, key_decay, diagonal_decay = self.decay_factors(slope_rate)
  113. self.register_buffer("slope_rate", slope_rate)
  114. self.register_buffer("query_decay", query_decay)
  115. self.register_buffer("key_decay", key_decay)
  116. self.register_buffer("diagonal_decay", diagonal_decay)
  117. def get_slope_rate(self):
  118. base = 1 / (2 ** (8 / self.num_attention_heads))
  119. exponent = torch.arange(self.num_attention_heads) + 1
  120. factor = 1 - self.layer_idx / (self.num_hidden_layers - 1 + 1e-5) + 1e-5
  121. rate = base**exponent
  122. rate = rate * factor
  123. rate = rate[:, None, None]
  124. return rate
  125. def decay_factors(self, slope_rate):
  126. block_size_range = torch.arange(self.block_size) + 1
  127. query_decay = torch.exp(-slope_rate * block_size_range[:, None])
  128. key_decay = torch.exp(-slope_rate * (self.block_size - block_size_range[:, None]))
  129. diagonal_decay = block_size_range[:, None] - block_size_range[None, :]
  130. diagonal_decay = diagonal_decay[None, None, :, :]
  131. diagonal_decay = slope_rate * diagonal_decay
  132. diagonal_decay = torch.where(diagonal_decay >= 0, -diagonal_decay, float("-inf"))
  133. diagonal_decay = torch.exp(diagonal_decay)
  134. return query_decay, key_decay, diagonal_decay
  135. def forward(
  136. self,
  137. hidden_states: torch.Tensor,
  138. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  139. attention_mask: torch.Tensor | None,
  140. past_key_values: Cache | None = None,
  141. **kwargs: Unpack[FlashAttentionKwargs],
  142. ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
  143. batch_size, seq_len, hidden_size = hidden_states.shape
  144. num_blocks = (seq_len + self.block_size - 1) // self.block_size
  145. qkv_states = self.act_fn(self.qkv_proj(hidden_states))
  146. qkv_states = qkv_states.reshape(batch_size, seq_len, self.num_attention_heads, 3 * self.head_dim)
  147. query_states, key_states, value_states = torch.split(qkv_states, self.head_dim, dim=3)
  148. query_states = query_states.transpose(1, 2)
  149. key_states = key_states.transpose(1, 2)
  150. value_states = value_states.transpose(1, 2)
  151. # calculated (K.T @ V) and saved as cache
  152. attn_weights_inter = None
  153. if past_key_values is not None:
  154. attn_weights_inter = past_key_values.get_linear_cache(self.layer_idx)
  155. if attn_weights_inter is None:
  156. attn_weights_inter = torch.zeros(batch_size, self.num_attention_heads, self.head_dim, self.head_dim).to(
  157. value_states
  158. )
  159. # apply attention_mask
  160. if attention_mask is not None:
  161. attention_mask = attention_mask.to(dtype=torch.bool) # Ensure it's a boolean tensor
  162. value_states = value_states.masked_fill(~attention_mask.unsqueeze(1).unsqueeze(-1), 0)
  163. attn_output = []
  164. for i in range(num_blocks):
  165. start_idx = i * self.block_size
  166. end_idx = min(start_idx + self.block_size, seq_len)
  167. current_block_size = end_idx - start_idx
  168. current_query_states = query_states[:, :, start_idx:end_idx]
  169. current_key_states = key_states[:, :, start_idx:end_idx]
  170. current_value_states = value_states[:, :, start_idx:end_idx]
  171. current_query_decay = self.query_decay[:, :current_block_size]
  172. current_key_decay = self.key_decay[:, -current_block_size:]
  173. current_diagonal_decay = self.diagonal_decay[:, :, :current_block_size, :current_block_size]
  174. block_decay = torch.exp(-self.slope_rate * current_block_size)
  175. # intra: ( Q @ K.T ) @ V -> QK * V
  176. attn_weights_intra = torch.matmul(current_query_states, current_key_states.transpose(-1, -2))
  177. attn_output_intra = torch.matmul(attn_weights_intra * current_diagonal_decay, current_value_states)
  178. # inter: Q @ ( K.T @ V ) -> Q * KV
  179. attn_output_inter = torch.matmul(current_query_states * current_query_decay, attn_weights_inter)
  180. # final attention output
  181. current_attn_output = attn_output_inter + attn_output_intra
  182. attn_output.append(current_attn_output)
  183. # calculate attn_weights_inter for next block or cache
  184. next_attn_weights_inter = torch.matmul(
  185. (current_key_states * current_key_decay).transpose(-1, -2), current_value_states
  186. )
  187. attn_weights_inter = attn_weights_inter * block_decay + next_attn_weights_inter
  188. else:
  189. ratio = torch.exp(-self.slope_rate)
  190. attn_output = []
  191. for i in range(seq_len):
  192. current_query_states = query_states[:, :, i : i + 1]
  193. current_key_states = key_states[:, :, i : i + 1]
  194. current_value_states = value_states[:, :, i : i + 1]
  195. current_attn_weights_inter = torch.matmul(current_key_states.transpose(-1, -2), current_value_states)
  196. attn_weights_inter = ratio * attn_weights_inter + current_attn_weights_inter
  197. current_attn_output = torch.matmul(current_query_states, attn_weights_inter)
  198. attn_output.append(current_attn_output)
  199. # concatenate attention outputs over all blocks
  200. attn_output = torch.cat(attn_output, dim=-2)
  201. # final output projection
  202. attn_output = attn_output.transpose(1, 2)
  203. attn_output = attn_output.reshape(batch_size, seq_len, self.num_attention_heads * self.head_dim)
  204. attn_output = self.norm(attn_output)
  205. attn_output = F.sigmoid(self.output_gate(hidden_states)) * attn_output
  206. attn_output = self.out_proj(attn_output)
  207. # update cache
  208. if past_key_values is not None:
  209. past_key_values.set_linear_cache(self.layer_idx, attn_weights_inter)
  210. return attn_output, attn_weights_inter
  211. class MiniMaxRotaryEmbedding(nn.Module):
  212. inv_freq: torch.Tensor # fix linting for `register_buffer`
  213. def __init__(self, config: MiniMaxConfig, device=None):
  214. super().__init__()
  215. self.max_seq_len_cached = config.max_position_embeddings
  216. self.original_max_seq_len = config.max_position_embeddings
  217. self.config = config
  218. self.rope_type = self.config.rope_parameters["rope_type"]
  219. rope_init_fn: Callable = self.compute_default_rope_parameters
  220. if self.rope_type != "default":
  221. rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  222. inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
  223. self.register_buffer("inv_freq", inv_freq, persistent=False)
  224. self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
  225. @staticmethod
  226. def compute_default_rope_parameters(
  227. config: MiniMaxConfig | None = None,
  228. device: Optional["torch.device"] = None,
  229. seq_len: int | None = None,
  230. ) -> tuple["torch.Tensor", float]:
  231. """
  232. Computes the inverse frequencies according to the original RoPE implementation
  233. Args:
  234. config ([`~transformers.PreTrainedConfig`]):
  235. The model configuration.
  236. device (`torch.device`):
  237. The device to use for initialization of the inverse frequencies.
  238. seq_len (`int`, *optional*):
  239. The current sequence length. Unused for this type of RoPE.
  240. Returns:
  241. Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
  242. post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
  243. """
  244. base = config.rope_parameters["rope_theta"]
  245. dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
  246. attention_factor = 1.0 # Unused in this type of RoPE
  247. # Compute the inverse frequencies
  248. inv_freq = 1.0 / (
  249. base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
  250. )
  251. return inv_freq, attention_factor
  252. @torch.no_grad()
  253. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  254. def forward(self, x, position_ids):
  255. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  256. position_ids_expanded = position_ids[:, None, :].float()
  257. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  258. with maybe_autocast(device_type=device_type, enabled=False): # Force float32
  259. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  260. emb = torch.cat((freqs, freqs), dim=-1)
  261. cos = emb.cos() * self.attention_scaling
  262. sin = emb.sin() * self.attention_scaling
  263. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  264. def rotate_half(x):
  265. """Rotates half the hidden dims of the input."""
  266. x1 = x[..., : x.shape[-1] // 2]
  267. x2 = x[..., x.shape[-1] // 2 :]
  268. return torch.cat((-x2, x1), dim=-1)
  269. @use_kernel_func_from_hub("rotary_pos_emb")
  270. def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
  271. """Applies Rotary Position Embedding to the query and key tensors.
  272. Args:
  273. q (`torch.Tensor`): The query tensor.
  274. k (`torch.Tensor`): The key tensor.
  275. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  276. sin (`torch.Tensor`): The sine part of the rotary embedding.
  277. unsqueeze_dim (`int`, *optional*, defaults to 1):
  278. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  279. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  280. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  281. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  282. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  283. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  284. Returns:
  285. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  286. """
  287. cos = cos.unsqueeze(unsqueeze_dim)
  288. sin = sin.unsqueeze(unsqueeze_dim)
  289. q_embed = (q * cos) + (rotate_half(q) * sin)
  290. k_embed = (k * cos) + (rotate_half(k) * sin)
  291. return q_embed, k_embed
  292. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  293. """
  294. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  295. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  296. """
  297. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  298. if n_rep == 1:
  299. return hidden_states
  300. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  301. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  302. def eager_attention_forward(
  303. module: nn.Module,
  304. query: torch.Tensor,
  305. key: torch.Tensor,
  306. value: torch.Tensor,
  307. attention_mask: torch.Tensor | None,
  308. scaling: float,
  309. dropout: float = 0.0,
  310. **kwargs: Unpack[TransformersKwargs],
  311. ):
  312. key_states = repeat_kv(key, module.num_key_value_groups)
  313. value_states = repeat_kv(value, module.num_key_value_groups)
  314. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  315. if attention_mask is not None:
  316. attn_weights = attn_weights + attention_mask
  317. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  318. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  319. attn_output = torch.matmul(attn_weights, value_states)
  320. attn_output = attn_output.transpose(1, 2).contiguous()
  321. return attn_output, attn_weights
  322. @use_kernelized_func(apply_rotary_pos_emb)
  323. class MiniMaxAttention(nn.Module):
  324. """Multi-headed attention from 'Attention Is All You Need' paper"""
  325. def __init__(self, config: MiniMaxConfig, layer_idx: int):
  326. super().__init__()
  327. self.config = config
  328. self.layer_idx = layer_idx
  329. self.head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
  330. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  331. self.scaling = self.head_dim**-0.5
  332. self.attention_dropout = config.attention_dropout
  333. self.is_causal = True
  334. self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
  335. self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
  336. self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
  337. self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
  338. def forward(
  339. self,
  340. hidden_states: torch.Tensor,
  341. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  342. attention_mask: torch.Tensor | None,
  343. past_key_values: Cache | None = None,
  344. **kwargs: Unpack[FlashAttentionKwargs],
  345. ) -> tuple[torch.Tensor, torch.Tensor | None]:
  346. input_shape = hidden_states.shape[:-1]
  347. hidden_shape = (*input_shape, -1, self.head_dim)
  348. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  349. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  350. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  351. cos, sin = position_embeddings
  352. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  353. if past_key_values is not None:
  354. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
  355. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  356. self.config._attn_implementation, eager_attention_forward
  357. )
  358. attn_output, attn_weights = attention_interface(
  359. self,
  360. query_states,
  361. key_states,
  362. value_states,
  363. attention_mask,
  364. dropout=0.0 if not self.training else self.attention_dropout,
  365. scaling=self.scaling,
  366. sliding_window=getattr(self.config, "sliding_window", None), # main diff with Llama
  367. **kwargs,
  368. )
  369. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  370. attn_output = self.o_proj(attn_output)
  371. return attn_output, attn_weights
  372. class MiniMaxTopKRouter(nn.Module):
  373. def __init__(self, config):
  374. super().__init__()
  375. self.top_k = config.num_experts_per_tok
  376. self.num_experts = config.num_local_experts
  377. self.hidden_dim = config.hidden_size
  378. self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim))
  379. def forward(self, hidden_states):
  380. hidden_states = hidden_states.reshape(-1, self.hidden_dim)
  381. router_logits = F.linear(hidden_states, self.weight) # (seq_len, num_experts)
  382. router_logits = torch.nn.functional.softmax(router_logits.float(), dim=-1)
  383. router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) # (seq_len, top_k)
  384. router_top_value /= router_top_value.sum(dim=-1, keepdim=True)
  385. router_scores = router_top_value
  386. return router_logits, router_scores, router_indices
  387. @use_experts_implementation
  388. class MiniMaxExperts(nn.Module):
  389. """Collection of expert weights stored as 3D tensors."""
  390. def __init__(self, config: MiniMaxConfig):
  391. super().__init__()
  392. self.num_experts = config.num_local_experts
  393. self.hidden_dim = config.hidden_size
  394. self.intermediate_dim = config.intermediate_size
  395. self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
  396. self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
  397. self.act_fn = ACT2FN[config.hidden_act]
  398. def forward(
  399. self,
  400. hidden_states: torch.Tensor,
  401. top_k_index: torch.Tensor,
  402. top_k_weights: torch.Tensor,
  403. ) -> torch.Tensor:
  404. final_hidden_states = torch.zeros_like(hidden_states)
  405. with torch.no_grad():
  406. expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
  407. expert_mask = expert_mask.permute(2, 1, 0)
  408. expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
  409. for expert_idx in expert_hit:
  410. expert_idx = expert_idx[0]
  411. if expert_idx == self.num_experts:
  412. continue
  413. top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
  414. current_state = hidden_states[token_idx]
  415. gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
  416. current_hidden_states = self.act_fn(gate) * up
  417. current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
  418. current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
  419. final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
  420. return final_hidden_states
  421. class MiniMaxSparseMoeBlock(nn.Module):
  422. def __init__(self, config):
  423. super().__init__()
  424. self.top_k = config.num_experts_per_tok
  425. self.jitter_noise = config.router_jitter_noise
  426. self.gate = MiniMaxTopKRouter(config)
  427. self.experts = MiniMaxExperts(config)
  428. def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
  429. batch_size, sequence_length, hidden_dim = hidden_states.shape
  430. if self.training and self.jitter_noise > 0:
  431. hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
  432. hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
  433. _, top_k_weights, top_k_index = self.gate(hidden_states)
  434. hidden_states = self.experts(hidden_states, top_k_index, top_k_weights)
  435. hidden_states = hidden_states.reshape(batch_size, sequence_length, hidden_dim)
  436. return hidden_states
  437. class MiniMaxDecoderLayer(GradientCheckpointingLayer):
  438. def __init__(self, config: MiniMaxConfig, layer_idx: int):
  439. super().__init__()
  440. self.hidden_size = config.hidden_size
  441. self.self_attn = MiniMaxAttention(config, layer_idx)
  442. self.input_layernorm = MiniMaxRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  443. self.post_attention_layernorm = MiniMaxRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  444. self.layer_idx = layer_idx
  445. self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
  446. self.mlp_alpha_factor = config.mlp_alpha_factor
  447. self.mlp_beta_factor = config.mlp_beta_factor
  448. self.mlp = MiniMaxSparseMoeBlock(config)
  449. if self.layer_type == "linear_attention":
  450. self.self_attn = MiniMaxLightningAttention(config, layer_idx)
  451. self.attn_alpha_factor = config.linear_attn_alpha_factor
  452. self.attn_beta_factor = config.linear_attn_beta_factor
  453. else:
  454. self.self_attn = MiniMaxAttention(config, layer_idx)
  455. self.attn_alpha_factor = config.full_attn_alpha_factor
  456. self.attn_beta_factor = config.full_attn_beta_factor
  457. def forward(
  458. self,
  459. hidden_states: torch.Tensor,
  460. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  461. attention_mask: torch.Tensor | None = None,
  462. position_ids: torch.LongTensor | None = None,
  463. past_key_values: Cache | None = None,
  464. use_cache: bool | None = False,
  465. **kwargs: Unpack[FlashAttentionKwargs],
  466. ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
  467. hidden_states = self.input_layernorm(hidden_states)
  468. residual = hidden_states
  469. hidden_states, _ = self.self_attn(
  470. hidden_states=hidden_states,
  471. position_embeddings=position_embeddings,
  472. attention_mask=attention_mask,
  473. position_ids=position_ids,
  474. past_key_values=past_key_values,
  475. use_cache=use_cache,
  476. **kwargs,
  477. )
  478. hidden_states = residual * self.attn_alpha_factor + hidden_states * self.attn_beta_factor
  479. hidden_states = self.post_attention_layernorm(hidden_states)
  480. residual = hidden_states
  481. hidden_states = self.mlp(hidden_states)
  482. hidden_states = residual * self.mlp_alpha_factor + hidden_states * self.mlp_beta_factor
  483. return hidden_states
  484. @auto_docstring
  485. class MiniMaxPreTrainedModel(PreTrainedModel):
  486. config: MiniMaxConfig
  487. base_model_prefix = "model"
  488. supports_gradient_checkpointing = True
  489. _no_split_modules = ["MiniMaxDecoderLayer"]
  490. _skip_keys_device_placement = ["past_key_values"]
  491. _supports_flash_attn = True
  492. _supports_sdpa = True
  493. _supports_flex_attn = True
  494. _can_compile_fullgraph = False # uses a non-compilable custom cache class MiniMaxCache
  495. _supports_attention_backend = True
  496. _can_record_outputs = {
  497. "router_logits": OutputRecorder(MiniMaxTopKRouter, layer_name="mlp.gate", index=0),
  498. "hidden_states": MiniMaxDecoderLayer,
  499. "attentions": [MiniMaxAttention, MiniMaxLightningAttention],
  500. }
  501. @torch.no_grad()
  502. def _init_weights(self, module):
  503. super()._init_weights(module)
  504. std = self.config.initializer_range
  505. if isinstance(module, MiniMaxExperts):
  506. init.normal_(module.gate_up_proj, mean=0.0, std=std)
  507. init.normal_(module.down_proj, mean=0.0, std=std)
  508. elif isinstance(module, MiniMaxTopKRouter):
  509. init.normal_(module.weight, mean=0.0, std=std)
  510. if isinstance(module, MiniMaxLightningAttention):
  511. slope_rate = module.get_slope_rate()
  512. query_decay, key_decay, diagonal_decay = module.decay_factors(slope_rate)
  513. init.copy_(module.slope_rate, slope_rate)
  514. init.copy_(module.query_decay, query_decay)
  515. init.copy_(module.key_decay, key_decay)
  516. init.copy_(module.diagonal_decay, diagonal_decay)
  517. @auto_docstring
  518. class MiniMaxModel(MiniMaxPreTrainedModel):
  519. def __init__(self, config: MiniMaxConfig):
  520. super().__init__(config)
  521. self.padding_idx = config.pad_token_id
  522. self.vocab_size = config.vocab_size
  523. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  524. self.layers = nn.ModuleList(
  525. [MiniMaxDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  526. )
  527. self.norm = MiniMaxRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  528. self.rotary_emb = MiniMaxRotaryEmbedding(config=config)
  529. self.gradient_checkpointing = False
  530. # Initialize weights and apply final processing
  531. self.post_init()
  532. @merge_with_config_defaults
  533. @capture_outputs
  534. def forward(
  535. self,
  536. input_ids: torch.LongTensor | None = None,
  537. attention_mask: torch.Tensor | None = None,
  538. position_ids: torch.LongTensor | None = None,
  539. past_key_values: MiniMaxCache | None = None,
  540. inputs_embeds: torch.FloatTensor | None = None,
  541. use_cache: bool | None = None,
  542. **kwargs: Unpack[TransformersKwargs],
  543. ) -> tuple | MoeModelOutputWithPast:
  544. if (input_ids is None) ^ (inputs_embeds is not None):
  545. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  546. if use_cache and past_key_values is None:
  547. past_key_values = MiniMaxCache()
  548. elif use_cache and not isinstance(past_key_values, MiniMaxCache):
  549. raise ValueError(
  550. f"MiniMax uses cache of its own and is not compatible with `past_key_values` of type {type(past_key_values)}."
  551. )
  552. if inputs_embeds is None:
  553. inputs_embeds = self.embed_tokens(input_ids)
  554. if position_ids is None:
  555. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  556. position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
  557. position_ids = position_ids.unsqueeze(0)
  558. mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
  559. causal_mask = mask_function(
  560. config=self.config,
  561. inputs_embeds=inputs_embeds,
  562. attention_mask=attention_mask,
  563. past_key_values=past_key_values,
  564. position_ids=position_ids,
  565. )
  566. hidden_states = inputs_embeds
  567. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  568. for i, decoder_layer in enumerate(self.layers):
  569. if self.config.layer_types[i] == "full_attention":
  570. input_attention_mask = causal_mask
  571. else:
  572. # lightning attention uses original attention_mask, and uses it only for the first step
  573. input_attention_mask = attention_mask
  574. hidden_states = decoder_layer(
  575. hidden_states,
  576. attention_mask=input_attention_mask,
  577. position_embeddings=position_embeddings,
  578. position_ids=position_ids,
  579. past_key_values=past_key_values,
  580. use_cache=use_cache,
  581. **kwargs,
  582. )
  583. hidden_states = self.norm(hidden_states)
  584. return MoeModelOutputWithPast(
  585. last_hidden_state=hidden_states,
  586. past_key_values=past_key_values,
  587. )
  588. def load_balancing_loss_func(
  589. gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
  590. num_experts: int | None = None,
  591. top_k=2,
  592. attention_mask: torch.Tensor | None = None,
  593. ) -> torch.Tensor | int:
  594. r"""
  595. Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
  596. See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
  597. function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
  598. experts is too unbalanced.
  599. Args:
  600. gate_logits:
  601. Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
  602. shape [batch_size X sequence_length, num_experts].
  603. num_experts:
  604. Number of experts
  605. top_k:
  606. The number of experts to route per-token, can be also interpreted as the `top-k` routing
  607. parameter.
  608. attention_mask (`torch.Tensor`, *optional*):
  609. The attention_mask used in forward function
  610. shape [batch_size X sequence_length] if not None.
  611. Returns:
  612. The auxiliary loss.
  613. """
  614. if gate_logits is None or not isinstance(gate_logits, tuple):
  615. return 0
  616. if isinstance(gate_logits, tuple):
  617. compute_device = gate_logits[0].device
  618. concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
  619. routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
  620. _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
  621. expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
  622. if attention_mask is None:
  623. # Compute the percentage of tokens routed to each experts
  624. tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
  625. # Compute the average probability of routing to these experts
  626. router_prob_per_expert = torch.mean(routing_weights, dim=0)
  627. else:
  628. batch_size, sequence_length = attention_mask.shape
  629. num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
  630. # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
  631. expert_attention_mask = (
  632. attention_mask[None, :, :, None, None]
  633. .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
  634. .reshape(-1, top_k, num_experts)
  635. .to(compute_device)
  636. )
  637. # Compute the percentage of tokens routed to each experts
  638. tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
  639. expert_attention_mask, dim=0
  640. )
  641. # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
  642. router_per_expert_attention_mask = (
  643. attention_mask[None, :, :, None]
  644. .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
  645. .reshape(-1, num_experts)
  646. .to(compute_device)
  647. )
  648. # Compute the average probability of routing to these experts
  649. router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
  650. router_per_expert_attention_mask, dim=0
  651. )
  652. overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
  653. return overall_loss * num_experts
  654. @auto_docstring
  655. class MiniMaxForCausalLM(MiniMaxPreTrainedModel, GenerationMixin):
  656. _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
  657. _tp_plan = {"lm_head": "colwise_gather_output"}
  658. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  659. def __init__(self, config):
  660. super().__init__(config)
  661. self.model = MiniMaxModel(config)
  662. self.vocab_size = config.vocab_size
  663. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  664. self.router_aux_loss_coef = config.router_aux_loss_coef
  665. self.num_experts = config.num_local_experts
  666. self.num_experts_per_tok = config.num_experts_per_tok
  667. # Initialize weights and apply final processing
  668. self.post_init()
  669. @can_return_tuple
  670. @auto_docstring
  671. def forward(
  672. self,
  673. input_ids: torch.LongTensor | None = None,
  674. attention_mask: torch.Tensor | None = None,
  675. position_ids: torch.LongTensor | None = None,
  676. past_key_values: Cache | None = None,
  677. inputs_embeds: torch.FloatTensor | None = None,
  678. labels: torch.LongTensor | None = None,
  679. use_cache: bool | None = None,
  680. output_router_logits: bool | None = None,
  681. logits_to_keep: int | torch.Tensor = 0,
  682. **kwargs: Unpack[TransformersKwargs],
  683. ) -> MoeCausalLMOutputWithPast:
  684. r"""
  685. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  686. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  687. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  688. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  689. Example:
  690. ```python
  691. >>> from transformers import AutoTokenizer, MiniMaxForCausalLM
  692. >>> model = MiniMaxForCausalLM.from_pretrained("MiniMaxAI/MiniMax-Text-01-hf")
  693. >>> tokenizer = AutoTokenizer.from_pretrained("MiniMaxAI/MiniMax-Text-01-hf")
  694. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  695. >>> inputs = tokenizer(prompt, return_tensors="pt")
  696. >>> # Generate
  697. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  698. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  699. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  700. ```"""
  701. output_router_logits = (
  702. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  703. )
  704. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  705. outputs: MoeModelOutputWithPast = self.model(
  706. input_ids=input_ids,
  707. attention_mask=attention_mask,
  708. position_ids=position_ids,
  709. past_key_values=past_key_values,
  710. inputs_embeds=inputs_embeds,
  711. use_cache=use_cache,
  712. output_router_logits=output_router_logits,
  713. **kwargs,
  714. )
  715. hidden_states = outputs.last_hidden_state
  716. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  717. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  718. logits = self.lm_head(hidden_states[:, slice_indices, :])
  719. loss = None
  720. if labels is not None:
  721. loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
  722. aux_loss = None
  723. if output_router_logits:
  724. aux_loss = load_balancing_loss_func(
  725. outputs.router_logits,
  726. self.num_experts,
  727. self.num_experts_per_tok,
  728. attention_mask,
  729. )
  730. if labels is not None:
  731. loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
  732. return MoeCausalLMOutputWithPast(
  733. loss=loss,
  734. aux_loss=aux_loss,
  735. logits=logits,
  736. past_key_values=outputs.past_key_values,
  737. hidden_states=outputs.hidden_states,
  738. attentions=outputs.attentions,
  739. router_logits=outputs.router_logits,
  740. )
  741. class MiniMaxForSequenceClassification(GenericForSequenceClassification, MiniMaxPreTrainedModel):
  742. pass
  743. class MiniMaxForTokenClassification(GenericForTokenClassification, MiniMaxPreTrainedModel):
  744. pass
  745. class MiniMaxForQuestionAnswering(GenericForQuestionAnswering, MiniMaxPreTrainedModel):
  746. pass
  747. __all__ = [
  748. "MiniMaxPreTrainedModel",
  749. "MiniMaxModel",
  750. "MiniMaxForCausalLM",
  751. "MiniMaxForSequenceClassification",
  752. "MiniMaxForTokenClassification",
  753. "MiniMaxForQuestionAnswering",
  754. ]