modeling_granitemoeshared.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/granitemoeshared/modular_granitemoeshared.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_granitemoeshared.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2024 IBM and the HuggingFace Inc. team. 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, TypedDict
  23. import torch
  24. from torch import nn
  25. from torch.nn import functional as F
  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 use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
  31. from ...masking_utils import create_causal_mask
  32. from ...modeling_layers import GradientCheckpointingLayer
  33. from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
  34. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  35. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  36. from ...processing_utils import Unpack
  37. from ...utils import TransformersKwargs, auto_docstring
  38. from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults
  39. from ...utils.output_capturing import capture_outputs
  40. from .configuration_granitemoeshared import GraniteMoeSharedConfig
  41. class GraniteFlashAttentionKwargs(TypedDict, total=False):
  42. """
  43. Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
  44. Use cases include padding-free training and fewer `torch.compile` graph breaks.
  45. cu_seq_lens_q (`torch.LongTensor`):
  46. Gets cumulative sequence length for query state.
  47. cu_seq_lens_k (`torch.LongTensor`):
  48. Gets cumulative sequence length for key state.
  49. max_length_q (`int`):
  50. Maximum sequence length for query state.
  51. max_length_k (`int`):
  52. Maximum sequence length for key state.
  53. seq_idx (`torch.IntTensor):
  54. Index of each packed sequence.
  55. """
  56. cu_seq_lens_q: torch.LongTensor
  57. cu_seq_lens_k: torch.LongTensor
  58. max_length_q: int
  59. max_length_k: int
  60. seq_idx: torch.IntTensor
  61. class GraniteMoeSharedMLP(nn.Module):
  62. """
  63. MLP layer for shared experts
  64. Args:
  65. config:
  66. Configuration object with model hyperparameters.
  67. """
  68. def __init__(self, config: GraniteMoeSharedConfig):
  69. super().__init__()
  70. self.input_size = config.hidden_size
  71. self.hidden_size = config.shared_intermediate_size
  72. self.activation = ACT2FN[config.hidden_act]
  73. self.input_linear = nn.Linear(self.input_size, self.hidden_size * 2, bias=False)
  74. self.output_linear = nn.Linear(self.hidden_size, self.input_size, bias=False)
  75. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  76. hidden_states = self.input_linear(hidden_states)
  77. chunked_hidden_states = hidden_states.chunk(2, dim=-1)
  78. hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
  79. hidden_states = self.output_linear(hidden_states)
  80. return hidden_states
  81. @use_kernel_forward_from_hub("RMSNorm")
  82. class GraniteMoeSharedRMSNorm(nn.Module):
  83. def __init__(self, hidden_size, eps: float = 1e-6) -> None:
  84. """
  85. GraniteMoeSharedRMSNorm is equivalent to T5LayerNorm
  86. """
  87. super().__init__()
  88. self.weight = nn.Parameter(torch.ones(hidden_size))
  89. self.variance_epsilon = eps
  90. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  91. input_dtype = hidden_states.dtype
  92. hidden_states = hidden_states.to(torch.float32)
  93. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  94. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  95. return self.weight * hidden_states.to(input_dtype)
  96. def extra_repr(self):
  97. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  98. class GraniteMoeSharedParallelExperts(nn.Module):
  99. def __init__(self, num_experts: int, input_size: int, output_size: int) -> None:
  100. """
  101. Initialize the GraniteMoeSharedParallelExperts module.
  102. The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
  103. many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
  104. [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
  105. [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
  106. used in vllm.
  107. Args:
  108. num_experts (int):
  109. Number of experts.
  110. input_size (int):
  111. Size of the input.
  112. output_size (int):
  113. Size of the output.
  114. """
  115. super().__init__()
  116. self.weight = nn.Parameter(torch.empty(num_experts, output_size, input_size))
  117. self.num_experts = num_experts
  118. self.input_size = input_size
  119. self.output_size = output_size
  120. def forward(self, inputs, expert_size):
  121. """
  122. Forward pass of the GraniteMoeSharedParallelExperts module.
  123. Args:
  124. inputs (Tensor):
  125. Input tensor.
  126. expert_size:
  127. Expert size information.
  128. Returns:
  129. Tensor: Output tensor.
  130. """
  131. input_list = inputs.split(expert_size, dim=0)
  132. output_list = []
  133. for i in range(self.num_experts):
  134. output_list.append(F.linear(input_list[i], self.weight[i]))
  135. results = torch.cat(output_list, dim=0)
  136. return results
  137. class GraniteMoeSharedTopKGating(nn.Module):
  138. def __init__(self, input_size: int, num_experts: int, top_k: int):
  139. """
  140. Initialize the top-k gating mechanism.
  141. Args:
  142. input_size (`int`):
  143. Size of the input.
  144. num_experts (`int`):
  145. Number of experts.
  146. top_k (`int`):
  147. Number of top experts to select.
  148. """
  149. super().__init__()
  150. self.num_experts = num_experts
  151. self.input_size = input_size
  152. self.top_k = top_k
  153. self.layer = nn.Linear(input_size, num_experts, bias=False)
  154. def forward(self, hidden_states):
  155. # compute the top_k routing decision
  156. logits = self.layer(hidden_states).float() # [batch_size x seq_len, num_experts]
  157. top_k_logits, top_k_indices = logits.topk(self.top_k, dim=1) # [num_tokens, top_k]
  158. top_k_gates = torch.softmax(top_k_logits, dim=1).type_as(hidden_states) # [num_tokens, top_k]
  159. # compute number of input given to each expert
  160. zeros = torch.zeros(
  161. [top_k_gates.size(0), self.num_experts], dtype=top_k_gates.dtype, device=top_k_gates.device
  162. ) # [num_tokens, num_experts]
  163. gates = zeros.scatter(1, top_k_indices, 1) # [num_tokens, num_experts]
  164. expert_size = gates.long().sum(0) # [num_experts,]
  165. # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: Backend compiler failed with a fake tensor exception at`)
  166. # (and `DataDependentOutputException`)
  167. expert_size = expert_size.tolist()
  168. # sort and group input tokens according to expert assignment
  169. top_k_experts = top_k_indices.flatten() # [num_tokens * top_k]
  170. _, index_sorted_experts = top_k_experts.sort(0) # [num_tokens * top_k]
  171. batch_index = index_sorted_experts.div(self.top_k, rounding_mode="trunc") # [num_tokens * top_k]
  172. # gather the gate values for grouped input tokens
  173. top_k_gates = top_k_gates.flatten() # [num_tokens * top_k]
  174. batch_gates = top_k_gates[index_sorted_experts] # [num_tokens * top_k]
  175. return index_sorted_experts, batch_index, batch_gates, expert_size, logits
  176. class GraniteMoeSharedMoE(nn.Module):
  177. """
  178. A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
  179. Args:
  180. config:
  181. Configuration object with model hyperparameters.
  182. """
  183. def __init__(self, config: GraniteMoeSharedConfig):
  184. super().__init__()
  185. self.input_size = config.hidden_size
  186. self.hidden_size = config.intermediate_size
  187. self.activation = ACT2FN[config.hidden_act]
  188. self.input_linear = GraniteMoeSharedParallelExperts(
  189. config.num_local_experts, self.input_size, self.hidden_size * 2
  190. )
  191. self.output_linear = GraniteMoeSharedParallelExperts(
  192. config.num_local_experts, self.hidden_size, self.input_size
  193. )
  194. self.router = GraniteMoeSharedTopKGating(
  195. input_size=self.input_size,
  196. num_experts=config.num_local_experts,
  197. top_k=config.num_experts_per_tok,
  198. )
  199. def forward(self, layer_input):
  200. bsz, length, emb_size = layer_input.size()
  201. layer_input = layer_input.reshape(-1, emb_size)
  202. _, batch_index, batch_gates, expert_size, _ = self.router(layer_input)
  203. expert_inputs = layer_input[batch_index]
  204. hidden_states = self.input_linear(expert_inputs, expert_size)
  205. chunked_hidden_states = hidden_states.chunk(2, dim=-1)
  206. hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
  207. expert_outputs = self.output_linear(hidden_states, expert_size)
  208. expert_outputs = expert_outputs * batch_gates[:, None]
  209. zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
  210. layer_output = zeros.index_add(0, batch_index, expert_outputs)
  211. layer_output = layer_output.view(bsz, length, self.input_size)
  212. return layer_output
  213. def rotate_half(x):
  214. """Rotates half the hidden dims of the input."""
  215. x1 = x[..., : x.shape[-1] // 2]
  216. x2 = x[..., x.shape[-1] // 2 :]
  217. return torch.cat((-x2, x1), dim=-1)
  218. @use_kernel_func_from_hub("rotary_pos_emb")
  219. def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
  220. """Applies Rotary Position Embedding to the query and key tensors.
  221. Args:
  222. q (`torch.Tensor`): The query tensor.
  223. k (`torch.Tensor`): The key tensor.
  224. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  225. sin (`torch.Tensor`): The sine part of the rotary embedding.
  226. unsqueeze_dim (`int`, *optional*, defaults to 1):
  227. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  228. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  229. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  230. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  231. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  232. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  233. Returns:
  234. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  235. """
  236. cos = cos.unsqueeze(unsqueeze_dim)
  237. sin = sin.unsqueeze(unsqueeze_dim)
  238. q_embed = (q * cos) + (rotate_half(q) * sin)
  239. k_embed = (k * cos) + (rotate_half(k) * sin)
  240. return q_embed, k_embed
  241. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  242. """
  243. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  244. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  245. """
  246. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  247. if n_rep == 1:
  248. return hidden_states
  249. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  250. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  251. def eager_attention_forward(
  252. module: nn.Module,
  253. query: torch.Tensor,
  254. key: torch.Tensor,
  255. value: torch.Tensor,
  256. attention_mask: torch.Tensor | None,
  257. scaling: float,
  258. dropout: float = 0.0,
  259. **kwargs: Unpack[TransformersKwargs],
  260. ):
  261. key_states = repeat_kv(key, module.num_key_value_groups)
  262. value_states = repeat_kv(value, module.num_key_value_groups)
  263. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  264. if attention_mask is not None:
  265. attn_weights = attn_weights + attention_mask
  266. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  267. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  268. attn_output = torch.matmul(attn_weights, value_states)
  269. attn_output = attn_output.transpose(1, 2).contiguous()
  270. return attn_output, attn_weights
  271. @use_kernelized_func(apply_rotary_pos_emb)
  272. class GraniteMoeSharedAttention(nn.Module):
  273. """Multi-headed attention from 'Attention Is All You Need' paper"""
  274. def __init__(self, config: GraniteMoeSharedConfig, layer_idx: int):
  275. super().__init__()
  276. self.config = config
  277. self.layer_idx = layer_idx
  278. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  279. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  280. self.scaling = config.attention_multiplier # Only diff with llama
  281. self.attention_dropout = config.attention_dropout
  282. self.is_causal = True
  283. self.q_proj = nn.Linear(
  284. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  285. )
  286. self.k_proj = nn.Linear(
  287. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  288. )
  289. self.v_proj = nn.Linear(
  290. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  291. )
  292. self.o_proj = nn.Linear(
  293. config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
  294. )
  295. def forward(
  296. self,
  297. hidden_states: torch.Tensor,
  298. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  299. attention_mask: torch.Tensor | None = None,
  300. past_key_values: Cache | None = None,
  301. **kwargs: Unpack[TransformersKwargs],
  302. ) -> tuple[torch.Tensor, torch.Tensor]:
  303. input_shape = hidden_states.shape[:-1]
  304. hidden_shape = (*input_shape, -1, self.head_dim)
  305. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  306. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  307. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  308. cos, sin = position_embeddings
  309. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  310. if past_key_values is not None:
  311. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
  312. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  313. self.config._attn_implementation, eager_attention_forward
  314. )
  315. attn_output, attn_weights = attention_interface(
  316. self,
  317. query_states,
  318. key_states,
  319. value_states,
  320. attention_mask,
  321. dropout=0.0 if not self.training else self.attention_dropout,
  322. scaling=self.scaling,
  323. **kwargs,
  324. )
  325. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  326. attn_output = self.o_proj(attn_output)
  327. return attn_output, attn_weights
  328. class GraniteMoeSharedDecoderLayer(GradientCheckpointingLayer):
  329. def __init__(self, config: GraniteMoeSharedConfig, layer_idx: int):
  330. super().__init__()
  331. self.hidden_size = config.hidden_size
  332. self.self_attn = GraniteMoeSharedAttention(config=config, layer_idx=layer_idx)
  333. self.input_layernorm = GraniteMoeSharedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  334. self.post_attention_layernorm = GraniteMoeSharedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  335. self.block_sparse_moe = GraniteMoeSharedMoE(config)
  336. self.residual_multiplier = config.residual_multiplier # Only diff with mixtral!
  337. self.shared_mlp = None if config.shared_intermediate_size == 0 else GraniteMoeSharedMLP(config)
  338. def forward(
  339. self,
  340. hidden_states: torch.Tensor,
  341. attention_mask: torch.Tensor | None = None,
  342. position_ids: torch.LongTensor | None = None,
  343. past_key_values: Cache | None = None,
  344. output_attentions: bool | None = False,
  345. use_cache: bool | None = False,
  346. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  347. **kwargs: Unpack[GraniteFlashAttentionKwargs],
  348. ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
  349. residual = hidden_states
  350. hidden_states = self.input_layernorm(hidden_states)
  351. # Self Attention
  352. hidden_states, _ = self.self_attn(
  353. hidden_states=hidden_states,
  354. attention_mask=attention_mask,
  355. position_ids=position_ids,
  356. past_key_values=past_key_values,
  357. output_attentions=output_attentions,
  358. use_cache=use_cache,
  359. position_embeddings=position_embeddings,
  360. **kwargs,
  361. )
  362. hidden_states = residual + hidden_states * self.residual_multiplier
  363. residual = hidden_states
  364. hidden_states = self.post_attention_layernorm(hidden_states)
  365. moe_hidden_states = self.block_sparse_moe(hidden_states)
  366. if self.shared_mlp is None:
  367. hidden_states = moe_hidden_states
  368. else:
  369. hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
  370. hidden_states = residual + hidden_states * self.residual_multiplier
  371. return hidden_states
  372. @auto_docstring
  373. class GraniteMoeSharedPreTrainedModel(PreTrainedModel):
  374. config: GraniteMoeSharedConfig
  375. base_model_prefix = "model"
  376. supports_gradient_checkpointing = True
  377. _no_split_modules = ["GraniteMoeSharedDecoderLayer"]
  378. _skip_keys_device_placement = ["past_key_values"]
  379. _supports_flash_attn = True
  380. _supports_sdpa = True
  381. _supports_flex_attn = True
  382. _can_compile_fullgraph = False # TopK gating fails fullgraph compilation at "expert_size = expert_size.tolist()"
  383. _supports_attention_backend = True
  384. _can_record_outputs = {
  385. "hidden_states": GraniteMoeSharedDecoderLayer,
  386. "attentions": GraniteMoeSharedAttention,
  387. }
  388. @torch.no_grad()
  389. def _init_weights(self, module):
  390. super()._init_weights(module)
  391. if isinstance(module, GraniteMoeSharedParallelExperts):
  392. init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
  393. class GraniteMoeSharedRotaryEmbedding(nn.Module):
  394. inv_freq: torch.Tensor # fix linting for `register_buffer`
  395. def __init__(self, config: GraniteMoeSharedConfig, device=None):
  396. super().__init__()
  397. self.max_seq_len_cached = config.max_position_embeddings
  398. self.original_max_seq_len = config.max_position_embeddings
  399. self.config = config
  400. self.rope_type = self.config.rope_parameters["rope_type"]
  401. rope_init_fn: Callable = self.compute_default_rope_parameters
  402. if self.rope_type != "default":
  403. rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  404. inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
  405. self.register_buffer("inv_freq", inv_freq, persistent=False)
  406. self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
  407. @staticmethod
  408. def compute_default_rope_parameters(
  409. config: GraniteMoeSharedConfig | None = None,
  410. device: Optional["torch.device"] = None,
  411. seq_len: int | None = None,
  412. ) -> tuple["torch.Tensor", float]:
  413. """
  414. Computes the inverse frequencies according to the original RoPE implementation
  415. Args:
  416. config ([`~transformers.PreTrainedConfig`]):
  417. The model configuration.
  418. device (`torch.device`):
  419. The device to use for initialization of the inverse frequencies.
  420. seq_len (`int`, *optional*):
  421. The current sequence length. Unused for this type of RoPE.
  422. Returns:
  423. Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
  424. post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
  425. """
  426. base = config.rope_parameters["rope_theta"]
  427. dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
  428. attention_factor = 1.0 # Unused in this type of RoPE
  429. # Compute the inverse frequencies
  430. inv_freq = 1.0 / (
  431. base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
  432. )
  433. return inv_freq, attention_factor
  434. @torch.no_grad()
  435. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  436. def forward(self, x, position_ids):
  437. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  438. position_ids_expanded = position_ids[:, None, :].float()
  439. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  440. with maybe_autocast(device_type=device_type, enabled=False): # Force float32
  441. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  442. emb = torch.cat((freqs, freqs), dim=-1)
  443. cos = emb.cos() * self.attention_scaling
  444. sin = emb.sin() * self.attention_scaling
  445. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  446. @auto_docstring
  447. class GraniteMoeSharedModel(GraniteMoeSharedPreTrainedModel):
  448. def __init__(self, config: GraniteMoeSharedConfig):
  449. super().__init__(config)
  450. self.padding_idx = config.pad_token_id
  451. self.vocab_size = config.vocab_size
  452. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  453. self.layers = nn.ModuleList(
  454. [GraniteMoeSharedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  455. )
  456. self.norm = GraniteMoeSharedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  457. self.rotary_emb = GraniteMoeSharedRotaryEmbedding(config=config)
  458. self.gradient_checkpointing = False
  459. self.embedding_multiplier = config.embedding_multiplier
  460. # Initialize weights and apply final processing
  461. self.post_init()
  462. @merge_with_config_defaults
  463. @capture_outputs
  464. @auto_docstring
  465. def forward(
  466. self,
  467. input_ids: torch.LongTensor | None = None,
  468. attention_mask: torch.Tensor | None = None,
  469. position_ids: torch.LongTensor | None = None,
  470. past_key_values: Cache | None = None,
  471. inputs_embeds: torch.FloatTensor | None = None,
  472. use_cache: bool | None = None,
  473. **kwargs: Unpack[TransformersKwargs],
  474. ) -> MoeModelOutputWithPast:
  475. if (input_ids is None) ^ (inputs_embeds is not None):
  476. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  477. if use_cache and past_key_values is None:
  478. past_key_values = DynamicCache(config=self.config)
  479. if inputs_embeds is None:
  480. inputs_embeds = self.embed_tokens(input_ids)
  481. if position_ids is None:
  482. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  483. position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
  484. position_ids = position_ids.unsqueeze(0)
  485. causal_mask = create_causal_mask( # ONLY DIFF WITH MIXTRAL: NO SLIDING
  486. config=self.config,
  487. inputs_embeds=inputs_embeds,
  488. attention_mask=attention_mask,
  489. past_key_values=past_key_values,
  490. position_ids=position_ids,
  491. )
  492. inputs_embeds = inputs_embeds * self.embedding_multiplier
  493. hidden_states = inputs_embeds
  494. # create position embeddings to be shared across the decoder layers
  495. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  496. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  497. hidden_states = decoder_layer(
  498. hidden_states,
  499. position_embeddings=position_embeddings,
  500. attention_mask=causal_mask,
  501. position_ids=position_ids,
  502. past_key_values=past_key_values,
  503. use_cache=use_cache,
  504. **kwargs,
  505. )
  506. hidden_states = self.norm(hidden_states)
  507. return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
  508. last_hidden_state=hidden_states,
  509. past_key_values=past_key_values,
  510. )
  511. def load_balancing_loss_func(
  512. gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
  513. num_experts: int | None = None,
  514. top_k=2,
  515. attention_mask: torch.Tensor | None = None,
  516. ) -> torch.Tensor | int:
  517. r"""
  518. Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
  519. See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
  520. function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
  521. experts is too unbalanced.
  522. Args:
  523. gate_logits:
  524. Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
  525. shape [batch_size X sequence_length, num_experts].
  526. num_experts:
  527. Number of experts
  528. top_k:
  529. The number of experts to route per-token, can be also interpreted as the `top-k` routing
  530. parameter.
  531. attention_mask (`torch.Tensor`, *optional*):
  532. The attention_mask used in forward function
  533. shape [batch_size X sequence_length] if not None.
  534. Returns:
  535. The auxiliary loss.
  536. """
  537. if gate_logits is None or not isinstance(gate_logits, tuple):
  538. return 0
  539. if isinstance(gate_logits, tuple):
  540. compute_device = gate_logits[0].device
  541. concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
  542. routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
  543. _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
  544. expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
  545. if attention_mask is None:
  546. # Compute the percentage of tokens routed to each experts
  547. tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
  548. # Compute the average probability of routing to these experts
  549. router_prob_per_expert = torch.mean(routing_weights, dim=0)
  550. else:
  551. batch_size, sequence_length = attention_mask.shape
  552. num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
  553. # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
  554. expert_attention_mask = (
  555. attention_mask[None, :, :, None, None]
  556. .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
  557. .reshape(-1, top_k, num_experts)
  558. .to(compute_device)
  559. )
  560. # Compute the percentage of tokens routed to each experts
  561. tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
  562. expert_attention_mask, dim=0
  563. )
  564. # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
  565. router_per_expert_attention_mask = (
  566. attention_mask[None, :, :, None]
  567. .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
  568. .reshape(-1, num_experts)
  569. .to(compute_device)
  570. )
  571. # Compute the average probability of routing to these experts
  572. router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
  573. router_per_expert_attention_mask, dim=0
  574. )
  575. overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
  576. return overall_loss * num_experts
  577. @auto_docstring
  578. class GraniteMoeSharedForCausalLM(GraniteMoeSharedPreTrainedModel, GenerationMixin):
  579. _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
  580. _tp_plan = {"lm_head": "colwise_gather_output"}
  581. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  582. def __init__(self, config: GraniteMoeSharedConfig):
  583. super().__init__(config)
  584. self.model = GraniteMoeSharedModel(config)
  585. self.vocab_size = config.vocab_size
  586. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  587. self.router_aux_loss_coef = config.router_aux_loss_coef
  588. self.num_experts = config.num_local_experts
  589. self.num_experts_per_tok = config.num_experts_per_tok
  590. self.logits_scaling = config.logits_scaling
  591. # Initialize weights and apply final processing
  592. self.post_init()
  593. @auto_docstring
  594. @can_return_tuple
  595. def forward(
  596. self,
  597. input_ids: torch.LongTensor | None = None,
  598. attention_mask: torch.Tensor | None = None,
  599. position_ids: torch.LongTensor | None = None,
  600. past_key_values: Cache | None = None,
  601. inputs_embeds: torch.FloatTensor | None = None,
  602. labels: torch.LongTensor | None = None,
  603. output_router_logits: bool | None = None,
  604. logits_to_keep: int | torch.Tensor = 0,
  605. **kwargs,
  606. ) -> tuple | MoeCausalLMOutputWithPast:
  607. r"""
  608. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  609. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  610. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  611. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  612. Example:
  613. ```python
  614. >>> from transformers import AutoTokenizer, GraniteMoeSharedForCausalLM
  615. >>> model = GraniteMoeSharedForCausalLM.from_pretrained("ibm/PowerMoE-3b")
  616. >>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")
  617. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  618. >>> inputs = tokenizer(prompt, return_tensors="pt")
  619. >>> # Generate
  620. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  621. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  622. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  623. ```"""
  624. output_router_logits = (
  625. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  626. )
  627. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  628. outputs = self.model(
  629. input_ids=input_ids,
  630. attention_mask=attention_mask,
  631. position_ids=position_ids,
  632. past_key_values=past_key_values,
  633. inputs_embeds=inputs_embeds,
  634. **kwargs,
  635. )
  636. # Only compute necessary logits
  637. hidden_states = outputs.last_hidden_state
  638. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  639. logits = self.lm_head(hidden_states[:, slice_indices, :])
  640. logits = logits / self.config.logits_scaling
  641. loss = None
  642. if labels is not None:
  643. # Flatten the tokens
  644. loss = self.loss_function(
  645. logits,
  646. labels,
  647. vocab_size=self.config.vocab_size,
  648. **kwargs,
  649. )
  650. aux_loss = None
  651. if output_router_logits:
  652. aux_loss = load_balancing_loss_func(
  653. outputs.router_logits,
  654. self.num_experts,
  655. self.num_experts_per_tok,
  656. attention_mask,
  657. )
  658. if labels is not None:
  659. loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
  660. return MoeCausalLMOutputWithPast(
  661. loss=loss,
  662. aux_loss=aux_loss,
  663. logits=logits,
  664. past_key_values=outputs.past_key_values,
  665. hidden_states=outputs.hidden_states,
  666. attentions=outputs.attentions,
  667. router_logits=outputs.router_logits,
  668. )
  669. __all__ = ["GraniteMoeSharedForCausalLM", "GraniteMoeSharedModel", "GraniteMoeSharedPreTrainedModel"]