modeling_granitemoe.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. # coding=utf-8
  2. # Copyright 2024 IBM and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from typing import Callable, Optional, Union
  17. import torch
  18. import torch.nn.functional as F
  19. from torch import nn
  20. from ...activations import ACT2FN
  21. from ...cache_utils import Cache, DynamicCache
  22. from ...generation import GenerationMixin
  23. from ...modeling_attn_mask_utils import AttentionMaskConverter
  24. from ...modeling_layers import GradientCheckpointingLayer
  25. from ...modeling_outputs import BaseModelOutputWithPast, MoeCausalLMOutputWithPast, MoeModelOutputWithPast
  26. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  27. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  28. from ...utils import auto_docstring, is_torch_flex_attn_available, logging
  29. from ...utils.deprecation import deprecate_kwarg
  30. from .configuration_granitemoe import GraniteMoeConfig
  31. if is_torch_flex_attn_available():
  32. from torch.nn.attention.flex_attention import BlockMask
  33. from ...integrations.flex_attention import make_flex_block_causal_mask
  34. logger = logging.get_logger(__name__)
  35. # Copied from transformers.models.qwen2_moe.modeling_qwen2_moe.load_balancing_loss_func
  36. def load_balancing_loss_func(
  37. gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
  38. num_experts: Optional[int] = None,
  39. top_k=2,
  40. attention_mask: Optional[torch.Tensor] = None,
  41. ) -> Union[torch.Tensor, int]:
  42. r"""
  43. Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
  44. See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
  45. function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
  46. experts is too unbalanced.
  47. Args:
  48. gate_logits:
  49. Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
  50. shape [batch_size X sequence_length, num_experts].
  51. num_experts:
  52. Number of experts
  53. top_k:
  54. The number of experts to route per-token, can be also interpreted as the `top-k` routing
  55. parameter.
  56. attention_mask (`torch.Tensor`, *optional*):
  57. The attention_mask used in forward function
  58. shape [batch_size X sequence_length] if not None.
  59. Returns:
  60. The auxiliary loss.
  61. """
  62. if gate_logits is None or not isinstance(gate_logits, tuple):
  63. return 0
  64. if isinstance(gate_logits, tuple):
  65. compute_device = gate_logits[0].device
  66. concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
  67. routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
  68. _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
  69. expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
  70. if attention_mask is None:
  71. # Compute the percentage of tokens routed to each experts
  72. tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
  73. # Compute the average probability of routing to these experts
  74. router_prob_per_expert = torch.mean(routing_weights, dim=0)
  75. else:
  76. batch_size, sequence_length = attention_mask.shape
  77. num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
  78. # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
  79. expert_attention_mask = (
  80. attention_mask[None, :, :, None, None]
  81. .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
  82. .reshape(-1, top_k, num_experts)
  83. .to(compute_device)
  84. )
  85. # Compute the percentage of tokens routed to each experts
  86. tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
  87. expert_attention_mask, dim=0
  88. )
  89. # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
  90. router_per_expert_attention_mask = (
  91. attention_mask[None, :, :, None]
  92. .expand((num_hidden_layers, batch_size, sequence_length, routing_weights.shape[1]))
  93. .reshape(-1, routing_weights.shape[1])
  94. .to(compute_device)
  95. )
  96. # Compute the average probability of routing to these experts
  97. router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
  98. router_per_expert_attention_mask, dim=0
  99. )
  100. device_index = routing_weights.device.index if routing_weights.device.index is not None else 0
  101. rank = routing_weights.shape[1] * int(device_index)
  102. overall_loss = torch.sum(
  103. tokens_per_expert[:, rank : rank + routing_weights.shape[1]] * router_prob_per_expert.unsqueeze(0)
  104. )
  105. return overall_loss * num_experts
  106. # Copied from transformers.models.granite.modeling_granite.GraniteRMSNorm with Granite->GraniteMoe
  107. class GraniteMoeRMSNorm(nn.Module):
  108. def __init__(self, hidden_size, eps=1e-6):
  109. """
  110. GraniteMoeRMSNorm is equivalent to T5LayerNorm
  111. """
  112. super().__init__()
  113. self.weight = nn.Parameter(torch.ones(hidden_size))
  114. self.variance_epsilon = eps
  115. def forward(self, hidden_states):
  116. input_dtype = hidden_states.dtype
  117. hidden_states = hidden_states.to(torch.float32)
  118. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  119. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  120. return self.weight * hidden_states.to(input_dtype)
  121. def extra_repr(self):
  122. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  123. # Copied from transformers.models.granite.modeling_granite.GraniteRotaryEmbedding with Granite->GraniteMoe
  124. class GraniteMoeRotaryEmbedding(nn.Module):
  125. inv_freq: torch.Tensor # fix linting for `register_buffer`
  126. def __init__(self, config: GraniteMoeConfig, device=None):
  127. super().__init__()
  128. # BC: "rope_type" was originally "type"
  129. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  130. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  131. else:
  132. self.rope_type = "default"
  133. self.max_seq_len_cached = config.max_position_embeddings
  134. self.original_max_seq_len = config.max_position_embeddings
  135. self.config = config
  136. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  137. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  138. self.register_buffer("inv_freq", inv_freq, persistent=False)
  139. self.original_inv_freq = self.inv_freq
  140. @torch.no_grad()
  141. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  142. def forward(self, x, position_ids):
  143. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  144. position_ids_expanded = position_ids[:, None, :].float()
  145. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  146. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  147. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  148. emb = torch.cat((freqs, freqs), dim=-1)
  149. cos = emb.cos() * self.attention_scaling
  150. sin = emb.sin() * self.attention_scaling
  151. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  152. # Copied from transformers.models.granite.modeling_granite.rotate_half with Granite->GraniteMoe
  153. def rotate_half(x):
  154. """Rotates half the hidden dims of the input."""
  155. x1 = x[..., : x.shape[-1] // 2]
  156. x2 = x[..., x.shape[-1] // 2 :]
  157. return torch.cat((-x2, x1), dim=-1)
  158. # Copied from transformers.models.granite.modeling_granite.apply_rotary_pos_emb with Granite->GraniteMoe
  159. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  160. """Applies Rotary Position Embedding to the query and key tensors.
  161. Args:
  162. q (`torch.Tensor`): The query tensor.
  163. k (`torch.Tensor`): The key tensor.
  164. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  165. sin (`torch.Tensor`): The sine part of the rotary embedding.
  166. position_ids (`torch.Tensor`, *optional*):
  167. Deprecated and unused.
  168. unsqueeze_dim (`int`, *optional*, defaults to 1):
  169. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  170. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  171. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  172. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  173. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  174. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  175. Returns:
  176. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  177. """
  178. cos = cos.unsqueeze(unsqueeze_dim)
  179. sin = sin.unsqueeze(unsqueeze_dim)
  180. q_embed = (q * cos) + (rotate_half(q) * sin)
  181. k_embed = (k * cos) + (rotate_half(k) * sin)
  182. return q_embed, k_embed
  183. # Copied from transformers.models.jetmoe.modeling_jetmoe.JetMoeParallelExperts with JetMoe->GraniteMoe
  184. class GraniteMoeParallelExperts(nn.Module):
  185. def __init__(self, num_experts: int, input_size: int, output_size: int) -> None:
  186. """
  187. Initialize the GraniteMoeParallelExperts module.
  188. The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
  189. many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
  190. [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
  191. [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
  192. used in vllm.
  193. Args:
  194. num_experts (int):
  195. Number of experts.
  196. input_size (int):
  197. Size of the input.
  198. output_size (int):
  199. Size of the output.
  200. """
  201. super().__init__()
  202. self.weight = nn.Parameter(torch.empty(num_experts, output_size, input_size))
  203. self.num_experts = num_experts
  204. self.input_size = input_size
  205. self.output_size = output_size
  206. def forward(self, inputs, expert_size):
  207. """
  208. Forward pass of the GraniteMoeParallelExperts module.
  209. Args:
  210. inputs (Tensor):
  211. Input tensor.
  212. expert_size:
  213. Expert size information.
  214. Returns:
  215. Tensor: Output tensor.
  216. """
  217. input_list = inputs.split(expert_size, dim=0)
  218. output_list = []
  219. for i in range(self.num_experts):
  220. output_list.append(F.linear(input_list[i], self.weight[i]))
  221. results = torch.cat(output_list, dim=0)
  222. return results
  223. # Copied from transformers.models.jetmoe.modeling_jetmoe.JetMoeTopKGating with JetMoe->GraniteMoe
  224. class GraniteMoeTopKGating(nn.Module):
  225. def __init__(self, input_size: int, num_experts: int, top_k: int):
  226. """
  227. Initialize the top-k gating mechanism.
  228. Args:
  229. input_size (`int`):
  230. Size of the input.
  231. num_experts (`int`):
  232. Number of experts.
  233. top_k (`int`):
  234. Number of top experts to select.
  235. """
  236. super().__init__()
  237. self.num_experts = num_experts
  238. self.input_size = input_size
  239. self.top_k = top_k
  240. self.layer = nn.Linear(input_size, num_experts, bias=False)
  241. def forward(self, hidden_states):
  242. # compute the top_k routing decision
  243. logits = self.layer(hidden_states).float() # [batch_size x seq_len, num_experts]
  244. top_k_logits, top_k_indices = logits.topk(self.top_k, dim=1) # [num_tokens, top_k]
  245. top_k_gates = torch.softmax(top_k_logits, dim=1).type_as(hidden_states) # [num_tokens, top_k]
  246. # compute number of input given to each expert
  247. zeros = torch.zeros(
  248. [top_k_gates.size(0), self.num_experts], dtype=top_k_gates.dtype, device=top_k_gates.device
  249. ) # [num_tokens, num_experts]
  250. gates = zeros.scatter(1, top_k_indices, 1) # [num_tokens, num_experts]
  251. expert_size = gates.long().sum(0) # [num_experts,]
  252. # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: Backend compiler failed with a fake tensor exception at`)
  253. # (and `DataDependentOutputException`)
  254. expert_size = expert_size.tolist()
  255. # sort and group input tokens according to expert assignment
  256. top_k_experts = top_k_indices.flatten() # [num_tokens * top_k]
  257. _, index_sorted_experts = top_k_experts.sort(0) # [num_tokens * top_k]
  258. batch_index = index_sorted_experts.div(self.top_k, rounding_mode="trunc") # [num_tokens * top_k]
  259. # gather the gate values for grouped input tokens
  260. top_k_gates = top_k_gates.flatten() # [num_tokens * top_k]
  261. batch_gates = top_k_gates[index_sorted_experts] # [num_tokens * top_k]
  262. return index_sorted_experts, batch_index, batch_gates, expert_size, logits
  263. class GraniteMoeMoE(nn.Module):
  264. """
  265. A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
  266. Args:
  267. config:
  268. Configuration object with model hyperparameters.
  269. """
  270. def __init__(self, config: GraniteMoeConfig):
  271. super().__init__()
  272. self.input_size = config.hidden_size
  273. self.hidden_size = config.intermediate_size
  274. self.activation = ACT2FN[config.hidden_act]
  275. self.input_linear = GraniteMoeParallelExperts(config.num_local_experts, self.input_size, self.hidden_size * 2)
  276. self.output_linear = GraniteMoeParallelExperts(config.num_local_experts, self.hidden_size, self.input_size)
  277. self.router = GraniteMoeTopKGating(
  278. input_size=self.input_size,
  279. num_experts=config.num_local_experts,
  280. top_k=config.num_experts_per_tok,
  281. )
  282. def forward(self, layer_input):
  283. """
  284. Forward pass of the mixture of experts layer.
  285. Args:
  286. layer_input (Tensor):
  287. Input tensor.
  288. Returns:
  289. Tensor:
  290. Output tensor.
  291. Tensor:
  292. Router logits.
  293. """
  294. bsz, length, emb_size = layer_input.size()
  295. layer_input = layer_input.reshape(-1, emb_size)
  296. _, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
  297. expert_inputs = layer_input[batch_index]
  298. hidden_states = self.input_linear(expert_inputs, expert_size)
  299. chunked_hidden_states = hidden_states.chunk(2, dim=-1)
  300. hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
  301. expert_outputs = self.output_linear(hidden_states, expert_size)
  302. expert_outputs = expert_outputs * batch_gates[:, None]
  303. zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
  304. layer_output = zeros.index_add(0, batch_index, expert_outputs)
  305. layer_output = layer_output.view(bsz, length, self.input_size)
  306. return layer_output, router_logits
  307. # Copied from transformers.models.granite.modeling_granite.repeat_kv with Granite->GraniteMoe
  308. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  309. """
  310. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  311. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  312. """
  313. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  314. if n_rep == 1:
  315. return hidden_states
  316. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  317. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  318. # copied from transformers.models.granite.modeling_granite.GraniteAttention with Granite->GraniteMoe
  319. # no longer copied after attention refactors
  320. class GraniteMoeAttention(nn.Module):
  321. """Multi-headed attention from 'Attention Is All You Need' paper"""
  322. def __init__(self, config: GraniteMoeConfig, layer_idx: Optional[int] = None):
  323. super().__init__()
  324. self.config = config
  325. self.layer_idx = layer_idx
  326. if layer_idx is None:
  327. logger.warning_once(
  328. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  329. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  330. "when creating this class."
  331. )
  332. self.attention_dropout = config.attention_dropout
  333. self.hidden_size = config.hidden_size
  334. self.num_heads = config.num_attention_heads
  335. self.head_dim = self.hidden_size // self.num_heads
  336. self.num_key_value_heads = config.num_key_value_heads
  337. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  338. self.is_causal = True
  339. self.scaling = config.attention_multiplier
  340. if (self.head_dim * self.num_heads) != self.hidden_size:
  341. raise ValueError(
  342. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  343. f" and `num_heads`: {self.num_heads})."
  344. )
  345. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
  346. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  347. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  348. self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
  349. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  350. def forward(
  351. self,
  352. hidden_states: torch.Tensor,
  353. attention_mask: Optional[torch.Tensor] = None,
  354. position_ids: Optional[torch.LongTensor] = None,
  355. past_key_values: Optional[Cache] = None,
  356. use_cache: bool = False,
  357. cache_position: Optional[torch.LongTensor] = None,
  358. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # None or rope embeddings
  359. **kwargs,
  360. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  361. bsz, q_len, _ = hidden_states.size()
  362. query_states = self.q_proj(hidden_states)
  363. key_states = self.k_proj(hidden_states)
  364. value_states = self.v_proj(hidden_states)
  365. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  366. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  367. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  368. cos, sin = position_embeddings if position_embeddings is not None else (None, None)
  369. if position_embeddings is not None:
  370. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  371. if past_key_values is not None:
  372. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  373. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  374. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  375. attention_interface: Callable = eager_attention_forward
  376. if self.config._attn_implementation != "eager":
  377. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  378. attn_output, attn_weights = attention_interface(
  379. self,
  380. query_states,
  381. key_states,
  382. value_states,
  383. attention_mask,
  384. dropout=0.0 if not self.training else self.attention_dropout,
  385. scaling=self.scaling,
  386. **kwargs,
  387. )
  388. attn_output = attn_output.view(bsz, q_len, -1)
  389. attn_output = self.o_proj(attn_output)
  390. return attn_output, attn_weights
  391. def eager_attention_forward(
  392. module: nn.Module,
  393. query: torch.Tensor,
  394. key: torch.Tensor,
  395. value: torch.Tensor,
  396. attention_mask: Optional[torch.Tensor],
  397. scaling: float,
  398. dropout: float = 0.0,
  399. **kwargs,
  400. ):
  401. key_states = repeat_kv(key, module.num_key_value_groups)
  402. value_states = repeat_kv(value, module.num_key_value_groups)
  403. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  404. if attention_mask is not None:
  405. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  406. attn_weights = attn_weights + causal_mask
  407. # upcast attention to fp32
  408. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  409. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  410. attn_output = torch.matmul(attn_weights, value_states)
  411. attn_output = attn_output.transpose(1, 2).contiguous()
  412. return attn_output, attn_weights
  413. class GraniteMoeDecoderLayer(GradientCheckpointingLayer):
  414. def __init__(self, config: GraniteMoeConfig, layer_idx: int):
  415. super().__init__()
  416. self.hidden_size = config.hidden_size
  417. self.self_attn = GraniteMoeAttention(config=config, layer_idx=layer_idx)
  418. if config.num_local_experts > 0:
  419. self.block_sparse_moe = GraniteMoeMoE(config)
  420. self.input_layernorm = GraniteMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  421. self.post_attention_layernorm = GraniteMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  422. self.residual_multiplier = config.residual_multiplier
  423. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  424. def forward(
  425. self,
  426. hidden_states: torch.Tensor,
  427. attention_mask: Optional[torch.Tensor] = None,
  428. position_ids: Optional[torch.LongTensor] = None,
  429. past_key_values: Optional[Cache] = None,
  430. output_attentions: Optional[bool] = False,
  431. use_cache: Optional[bool] = False,
  432. cache_position: Optional[torch.LongTensor] = None,
  433. output_router_logits: Optional[bool] = False,
  434. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  435. **kwargs,
  436. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  437. """
  438. Args:
  439. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  440. attention_mask (`torch.FloatTensor`, *optional*):
  441. attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
  442. query_sequence_length, key_sequence_length)` if default attention is used.
  443. output_attentions (`bool`, *optional*):
  444. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  445. returned tensors for more detail.
  446. use_cache (`bool`, *optional*):
  447. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  448. (see `past_key_values`).
  449. past_key_values (`Cache`, *optional*): cached past key and value projection states
  450. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  451. Indices depicting the position of the input sequence tokens in the sequence
  452. output_router_logits (`bool`, *optional*):
  453. Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
  454. should not be returned during inference.
  455. position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  456. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  457. with `head_dim` being the embedding dimension of each attention head.
  458. kwargs (`dict`, *optional*):
  459. Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
  460. into the model
  461. """
  462. residual = hidden_states
  463. hidden_states = self.input_layernorm(hidden_states)
  464. # Self Attention
  465. hidden_states, self_attn_weights = self.self_attn(
  466. hidden_states=hidden_states,
  467. attention_mask=attention_mask,
  468. position_ids=position_ids,
  469. past_key_values=past_key_values,
  470. output_attentions=output_attentions,
  471. use_cache=use_cache,
  472. cache_position=cache_position,
  473. position_embeddings=position_embeddings,
  474. **kwargs,
  475. )
  476. hidden_states = residual + hidden_states * self.residual_multiplier
  477. # Fully Connected
  478. residual = hidden_states
  479. hidden_states = self.post_attention_layernorm(hidden_states)
  480. hidden_states, router_logits = self.block_sparse_moe(hidden_states)
  481. hidden_states = residual + hidden_states * self.residual_multiplier
  482. outputs = (hidden_states,)
  483. if output_attentions:
  484. outputs += (self_attn_weights,)
  485. if output_router_logits:
  486. outputs += (router_logits,)
  487. return outputs
  488. @auto_docstring
  489. class GraniteMoePreTrainedModel(PreTrainedModel):
  490. config: GraniteMoeConfig
  491. base_model_prefix = "model"
  492. supports_gradient_checkpointing = True
  493. _no_split_modules = ["GraniteMoeDecoderLayer"]
  494. _skip_keys_device_placement = ["past_key_values"]
  495. _supports_flash_attn = True
  496. _supports_sdpa = True
  497. _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
  498. def _init_weights(self, module):
  499. super()._init_weights(module)
  500. if isinstance(module, GraniteMoeParallelExperts):
  501. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  502. @auto_docstring
  503. class GraniteMoeModel(GraniteMoePreTrainedModel):
  504. def __init__(self, config: GraniteMoeConfig):
  505. super().__init__(config)
  506. self.padding_idx = config.pad_token_id
  507. self.vocab_size = config.vocab_size
  508. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  509. self.layers = nn.ModuleList(
  510. [GraniteMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  511. )
  512. self.norm = GraniteMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  513. self.gradient_checkpointing = False
  514. self.embedding_multiplier = config.embedding_multiplier
  515. self.hidden_size = config.hidden_size
  516. self.num_heads = config.num_attention_heads
  517. self.head_dim = self.hidden_size // self.num_heads
  518. self.max_position_embeddings = config.max_position_embeddings
  519. self.rope_theta = config.rope_theta
  520. self.position_embedding_type = config.position_embedding_type
  521. self.rotary_emb = GraniteMoeRotaryEmbedding(config) if self.position_embedding_type == "rope" else None
  522. # Initialize weights and apply final processing
  523. self.post_init()
  524. @auto_docstring
  525. def forward(
  526. self,
  527. input_ids: Optional[torch.LongTensor] = None,
  528. attention_mask: Optional[torch.Tensor] = None,
  529. position_ids: Optional[torch.LongTensor] = None,
  530. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  531. inputs_embeds: Optional[torch.FloatTensor] = None,
  532. use_cache: Optional[bool] = None,
  533. output_attentions: Optional[bool] = None,
  534. output_hidden_states: Optional[bool] = None,
  535. output_router_logits: Optional[bool] = None,
  536. return_dict: Optional[bool] = None,
  537. cache_position: Optional[torch.LongTensor] = None,
  538. **kwargs,
  539. ) -> Union[tuple, BaseModelOutputWithPast]:
  540. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  541. output_hidden_states = (
  542. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  543. )
  544. use_cache = use_cache if use_cache is not None else self.config.use_cache
  545. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  546. if (input_ids is None) ^ (inputs_embeds is not None):
  547. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  548. if self.gradient_checkpointing and self.training and use_cache:
  549. logger.warning_once(
  550. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  551. )
  552. use_cache = False
  553. if inputs_embeds is None:
  554. inputs_embeds = self.embed_tokens(input_ids)
  555. inputs_embeds = inputs_embeds * self.embedding_multiplier
  556. if use_cache and past_key_values is None:
  557. past_key_values = DynamicCache(config=self.config)
  558. if cache_position is None:
  559. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  560. cache_position = torch.arange(
  561. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  562. )
  563. if position_ids is None:
  564. position_ids = cache_position.unsqueeze(0)
  565. causal_mask = self._update_causal_mask(
  566. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
  567. )
  568. # embed positions
  569. hidden_states = inputs_embeds
  570. position_embeddings = None
  571. # create position embeddings to be shared across the decoder layers
  572. if self.rotary_emb is not None:
  573. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  574. # decoder layers
  575. all_hidden_states = () if output_hidden_states else None
  576. all_self_attns = () if output_attentions else None
  577. all_router_logits = () if output_router_logits else None
  578. for decoder_layer in self.layers:
  579. if output_hidden_states:
  580. all_hidden_states += (hidden_states,)
  581. layer_outputs = decoder_layer(
  582. hidden_states,
  583. attention_mask=causal_mask,
  584. position_ids=position_ids,
  585. past_key_values=past_key_values,
  586. output_attentions=output_attentions,
  587. use_cache=use_cache,
  588. cache_position=cache_position,
  589. output_router_logits=output_router_logits,
  590. position_embeddings=position_embeddings,
  591. )
  592. hidden_states = layer_outputs[0]
  593. if output_attentions:
  594. all_self_attns += (layer_outputs[1],)
  595. if output_router_logits:
  596. all_router_logits += (layer_outputs[-1],)
  597. hidden_states = self.norm(hidden_states)
  598. # add hidden states from the last decoder layer
  599. if output_hidden_states:
  600. all_hidden_states += (hidden_states,)
  601. if not return_dict:
  602. return tuple(
  603. v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None
  604. )
  605. return MoeModelOutputWithPast(
  606. last_hidden_state=hidden_states,
  607. past_key_values=past_key_values,
  608. hidden_states=all_hidden_states,
  609. attentions=all_self_attns,
  610. router_logits=all_router_logits,
  611. )
  612. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._update_causal_mask
  613. def _update_causal_mask(
  614. self,
  615. attention_mask: Union[torch.Tensor, "BlockMask"],
  616. input_tensor: torch.Tensor,
  617. cache_position: torch.Tensor,
  618. past_key_values: Cache,
  619. output_attentions: bool = False,
  620. ):
  621. if self.config._attn_implementation == "flash_attention_2":
  622. if attention_mask is not None and (attention_mask == 0.0).any():
  623. return attention_mask
  624. return None
  625. if self.config._attn_implementation == "flex_attention":
  626. if isinstance(attention_mask, torch.Tensor):
  627. attention_mask = make_flex_block_causal_mask(attention_mask)
  628. return attention_mask
  629. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  630. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  631. # to infer the attention mask.
  632. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  633. using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
  634. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  635. if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
  636. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  637. attention_mask,
  638. inputs_embeds=input_tensor,
  639. past_key_values_length=past_seen_tokens,
  640. is_training=self.training,
  641. ):
  642. return None
  643. dtype = input_tensor.dtype
  644. sequence_length = input_tensor.shape[1]
  645. if using_compilable_cache:
  646. target_length = past_key_values.get_max_cache_shape()
  647. else:
  648. target_length = (
  649. attention_mask.shape[-1]
  650. if isinstance(attention_mask, torch.Tensor)
  651. else past_seen_tokens + sequence_length + 1
  652. )
  653. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  654. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  655. attention_mask,
  656. sequence_length=sequence_length,
  657. target_length=target_length,
  658. dtype=dtype,
  659. cache_position=cache_position,
  660. batch_size=input_tensor.shape[0],
  661. )
  662. if (
  663. self.config._attn_implementation == "sdpa"
  664. and attention_mask is not None
  665. and attention_mask.device.type in ["cuda", "xpu", "npu"]
  666. and not output_attentions
  667. ):
  668. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  669. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  670. # Details: https://github.com/pytorch/pytorch/issues/110213
  671. min_dtype = torch.finfo(dtype).min
  672. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  673. return causal_mask
  674. @staticmethod
  675. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
  676. def _prepare_4d_causal_attention_mask_with_cache_position(
  677. attention_mask: torch.Tensor,
  678. sequence_length: int,
  679. target_length: int,
  680. dtype: torch.dtype,
  681. cache_position: torch.Tensor,
  682. batch_size: int,
  683. **kwargs,
  684. ):
  685. """
  686. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  687. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  688. Args:
  689. attention_mask (`torch.Tensor`):
  690. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  691. `(batch_size, 1, query_length, key_value_length)`.
  692. sequence_length (`int`):
  693. The sequence length being processed.
  694. target_length (`int`):
  695. The target length: when generating with static cache, the mask should be as long as the static cache,
  696. to account for the 0 padding, the part of the cache that is not filled yet.
  697. dtype (`torch.dtype`):
  698. The dtype to use for the 4D attention mask.
  699. cache_position (`torch.Tensor`):
  700. Indices depicting the position of the input sequence tokens in the sequence.
  701. batch_size (`torch.Tensor`):
  702. Batch size.
  703. """
  704. if attention_mask is not None and attention_mask.dim() == 4:
  705. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  706. causal_mask = attention_mask
  707. else:
  708. min_dtype = torch.finfo(dtype).min
  709. causal_mask = torch.full(
  710. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
  711. )
  712. if sequence_length != 1:
  713. causal_mask = torch.triu(causal_mask, diagonal=1)
  714. causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
  715. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  716. if attention_mask is not None:
  717. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  718. mask_length = attention_mask.shape[-1]
  719. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
  720. causal_mask.device
  721. )
  722. padding_mask = padding_mask == 0
  723. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  724. padding_mask, min_dtype
  725. )
  726. return causal_mask
  727. class GraniteMoeForCausalLM(GraniteMoePreTrainedModel, GenerationMixin):
  728. _tied_weights_keys = ["lm_head.weight"]
  729. def __init__(self, config: GraniteMoeConfig):
  730. super().__init__(config)
  731. self.model = GraniteMoeModel(config)
  732. self.vocab_size = config.vocab_size
  733. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  734. self.router_aux_loss_coef = config.router_aux_loss_coef
  735. self.num_experts = config.num_local_experts
  736. self.num_experts_per_tok = config.num_experts_per_tok
  737. # Initialize weights and apply final processing
  738. self.post_init()
  739. @auto_docstring
  740. def forward(
  741. self,
  742. input_ids: Optional[torch.LongTensor] = None,
  743. attention_mask: Optional[torch.Tensor] = None,
  744. position_ids: Optional[torch.LongTensor] = None,
  745. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  746. inputs_embeds: Optional[torch.FloatTensor] = None,
  747. labels: Optional[torch.LongTensor] = None,
  748. use_cache: Optional[bool] = None,
  749. output_attentions: Optional[bool] = None,
  750. output_hidden_states: Optional[bool] = None,
  751. output_router_logits: Optional[bool] = None,
  752. return_dict: Optional[bool] = None,
  753. cache_position: Optional[torch.LongTensor] = None,
  754. logits_to_keep: Union[int, torch.Tensor] = 0,
  755. **kwargs,
  756. ) -> Union[tuple, MoeCausalLMOutputWithPast]:
  757. r"""
  758. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  759. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  760. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  761. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  762. Example:
  763. ```python
  764. >>> from transformers import AutoTokenizer, GraniteMoeForCausalLM
  765. >>> model = GraniteMoeForCausalLM.from_pretrained("ibm/PowerMoE-3b")
  766. >>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")
  767. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  768. >>> inputs = tokenizer(prompt, return_tensors="pt")
  769. >>> # Generate
  770. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  771. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  772. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  773. ```"""
  774. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  775. output_router_logits = (
  776. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  777. )
  778. output_hidden_states = (
  779. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  780. )
  781. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  782. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  783. outputs = self.model(
  784. input_ids=input_ids,
  785. attention_mask=attention_mask,
  786. position_ids=position_ids,
  787. past_key_values=past_key_values,
  788. inputs_embeds=inputs_embeds,
  789. use_cache=use_cache,
  790. output_attentions=output_attentions,
  791. output_hidden_states=output_hidden_states,
  792. output_router_logits=output_router_logits,
  793. return_dict=return_dict,
  794. cache_position=cache_position,
  795. **kwargs,
  796. )
  797. # Only compute necessary logits
  798. hidden_states = outputs[0]
  799. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  800. logits = self.lm_head(hidden_states[:, slice_indices, :])
  801. logits = logits / self.config.logits_scaling
  802. loss = None
  803. if labels is not None:
  804. # Upcast to float if we need to compute the loss to avoid potential precision issues
  805. logits = logits.float()
  806. # Flatten the tokens
  807. loss = self.loss_function(
  808. logits,
  809. labels,
  810. vocab_size=self.config.vocab_size,
  811. **kwargs,
  812. )
  813. aux_loss = None
  814. if output_router_logits:
  815. aux_loss = load_balancing_loss_func(
  816. outputs.router_logits if return_dict else outputs[-1],
  817. self.num_experts,
  818. self.num_experts_per_tok,
  819. attention_mask,
  820. )
  821. if labels is not None:
  822. loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
  823. if not return_dict:
  824. output = (logits,) + outputs[1:]
  825. if output_router_logits:
  826. output = (aux_loss,) + output
  827. return (loss,) + output if loss is not None else output
  828. return MoeCausalLMOutputWithPast(
  829. loss=loss,
  830. aux_loss=aux_loss,
  831. logits=logits,
  832. past_key_values=outputs.past_key_values,
  833. hidden_states=outputs.hidden_states,
  834. attentions=outputs.attentions,
  835. router_logits=outputs.router_logits,
  836. )
  837. __all__ = ["GraniteMoeForCausalLM", "GraniteMoeModel", "GraniteMoePreTrainedModel"]