modeling_jetmoe.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. # coding=utf-8
  2. # Copyright 2024 JetMoe AI and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch JetMoe model."""
  16. import math
  17. from typing import Optional, Union
  18. import torch
  19. from torch import nn
  20. from torch.nn import functional as F
  21. from ...activations import ACT2FN
  22. from ...cache_utils import Cache, DynamicCache
  23. from ...generation import GenerationMixin
  24. from ...modeling_attn_mask_utils import AttentionMaskConverter
  25. from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
  26. from ...modeling_layers import (
  27. GenericForSequenceClassification,
  28. GradientCheckpointingLayer,
  29. )
  30. from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
  31. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  32. from ...modeling_utils import PreTrainedModel
  33. from ...utils import auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
  34. from ...utils.deprecation import deprecate_kwarg
  35. from .configuration_jetmoe import JetMoeConfig
  36. if is_torch_flex_attn_available():
  37. from torch.nn.attention.flex_attention import BlockMask
  38. from ...integrations.flex_attention import make_flex_block_causal_mask
  39. if is_flash_attn_available():
  40. from ...modeling_flash_attention_utils import _flash_attention_forward
  41. logger = logging.get_logger(__name__)
  42. # Copied from transformers.models.qwen2_moe.modeling_qwen2_moe.load_balancing_loss_func
  43. def load_balancing_loss_func(
  44. gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
  45. num_experts: Optional[int] = None,
  46. top_k=2,
  47. attention_mask: Optional[torch.Tensor] = None,
  48. ) -> Union[torch.Tensor, int]:
  49. r"""
  50. Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
  51. See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
  52. function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
  53. experts is too unbalanced.
  54. Args:
  55. gate_logits:
  56. Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
  57. shape [batch_size X sequence_length, num_experts].
  58. num_experts:
  59. Number of experts
  60. top_k:
  61. The number of experts to route per-token, can be also interpreted as the `top-k` routing
  62. parameter.
  63. attention_mask (`torch.Tensor`, *optional*):
  64. The attention_mask used in forward function
  65. shape [batch_size X sequence_length] if not None.
  66. Returns:
  67. The auxiliary loss.
  68. """
  69. if gate_logits is None or not isinstance(gate_logits, tuple):
  70. return 0
  71. if isinstance(gate_logits, tuple):
  72. compute_device = gate_logits[0].device
  73. concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
  74. routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
  75. _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
  76. expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
  77. if attention_mask is None:
  78. # Compute the percentage of tokens routed to each experts
  79. tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
  80. # Compute the average probability of routing to these experts
  81. router_prob_per_expert = torch.mean(routing_weights, dim=0)
  82. else:
  83. batch_size, sequence_length = attention_mask.shape
  84. num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
  85. # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
  86. expert_attention_mask = (
  87. attention_mask[None, :, :, None, None]
  88. .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
  89. .reshape(-1, top_k, num_experts)
  90. .to(compute_device)
  91. )
  92. # Compute the percentage of tokens routed to each experts
  93. tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
  94. expert_attention_mask, dim=0
  95. )
  96. # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
  97. router_per_expert_attention_mask = (
  98. attention_mask[None, :, :, None]
  99. .expand((num_hidden_layers, batch_size, sequence_length, routing_weights.shape[1]))
  100. .reshape(-1, routing_weights.shape[1])
  101. .to(compute_device)
  102. )
  103. # Compute the average probability of routing to these experts
  104. router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
  105. router_per_expert_attention_mask, dim=0
  106. )
  107. device_index = routing_weights.device.index if routing_weights.device.index is not None else 0
  108. rank = routing_weights.shape[1] * int(device_index)
  109. overall_loss = torch.sum(
  110. tokens_per_expert[:, rank : rank + routing_weights.shape[1]] * router_prob_per_expert.unsqueeze(0)
  111. )
  112. return overall_loss * num_experts
  113. class JetMoeParallelExperts(nn.Module):
  114. def __init__(self, num_experts: int, input_size: int, output_size: int) -> None:
  115. """
  116. Initialize the JetMoeParallelExperts module.
  117. The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
  118. many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
  119. [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
  120. [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
  121. used in vllm.
  122. Args:
  123. num_experts (int):
  124. Number of experts.
  125. input_size (int):
  126. Size of the input.
  127. output_size (int):
  128. Size of the output.
  129. """
  130. super().__init__()
  131. self.weight = nn.Parameter(torch.empty(num_experts, output_size, input_size))
  132. self.num_experts = num_experts
  133. self.input_size = input_size
  134. self.output_size = output_size
  135. def forward(self, inputs, expert_size):
  136. """
  137. Forward pass of the JetMoeParallelExperts module.
  138. Args:
  139. inputs (Tensor):
  140. Input tensor.
  141. expert_size:
  142. Expert size information.
  143. Returns:
  144. Tensor: Output tensor.
  145. """
  146. input_list = inputs.split(expert_size, dim=0)
  147. output_list = []
  148. for i in range(self.num_experts):
  149. output_list.append(F.linear(input_list[i], self.weight[i]))
  150. results = torch.cat(output_list, dim=0)
  151. return results
  152. class JetMoeTopKGating(nn.Module):
  153. def __init__(self, input_size: int, num_experts: int, top_k: int):
  154. """
  155. Initialize the top-k gating mechanism.
  156. Args:
  157. input_size (`int`):
  158. Size of the input.
  159. num_experts (`int`):
  160. Number of experts.
  161. top_k (`int`):
  162. Number of top experts to select.
  163. """
  164. super().__init__()
  165. self.num_experts = num_experts
  166. self.input_size = input_size
  167. self.top_k = top_k
  168. self.layer = nn.Linear(input_size, num_experts, bias=False)
  169. def forward(self, hidden_states):
  170. # compute the top_k routing decision
  171. logits = self.layer(hidden_states).float() # [batch_size x seq_len, num_experts]
  172. top_k_logits, top_k_indices = logits.topk(self.top_k, dim=1) # [num_tokens, top_k]
  173. top_k_gates = torch.softmax(top_k_logits, dim=1).type_as(hidden_states) # [num_tokens, top_k]
  174. # compute number of input given to each expert
  175. zeros = torch.zeros(
  176. [top_k_gates.size(0), self.num_experts], dtype=top_k_gates.dtype, device=top_k_gates.device
  177. ) # [num_tokens, num_experts]
  178. gates = zeros.scatter(1, top_k_indices, 1) # [num_tokens, num_experts]
  179. expert_size = gates.long().sum(0) # [num_experts,]
  180. # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: Backend compiler failed with a fake tensor exception at`)
  181. # (and `DataDependentOutputException`)
  182. expert_size = expert_size.tolist()
  183. # sort and group input tokens according to expert assignment
  184. top_k_experts = top_k_indices.flatten() # [num_tokens * top_k]
  185. _, index_sorted_experts = top_k_experts.sort(0) # [num_tokens * top_k]
  186. batch_index = index_sorted_experts.div(self.top_k, rounding_mode="trunc") # [num_tokens * top_k]
  187. # gather the gate values for grouped input tokens
  188. top_k_gates = top_k_gates.flatten() # [num_tokens * top_k]
  189. batch_gates = top_k_gates[index_sorted_experts] # [num_tokens * top_k]
  190. return index_sorted_experts, batch_index, batch_gates, expert_size, logits
  191. class JetMoeMoE(nn.Module):
  192. """
  193. A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
  194. Args:
  195. config:
  196. Configuration object with model hyperparameters.
  197. """
  198. def __init__(self, config: JetMoeConfig):
  199. super().__init__()
  200. self.input_size = config.hidden_size
  201. self.hidden_size = config.intermediate_size
  202. self.activation = ACT2FN[config.activation_function]
  203. self.bias = torch.nn.Parameter(torch.empty(self.input_size))
  204. self.input_linear = JetMoeParallelExperts(config.num_local_experts, self.input_size, self.hidden_size * 2)
  205. self.output_linear = JetMoeParallelExperts(config.num_local_experts, self.hidden_size, self.input_size)
  206. self.router = JetMoeTopKGating(
  207. input_size=self.input_size,
  208. num_experts=config.num_local_experts,
  209. top_k=config.num_experts_per_tok,
  210. )
  211. def forward(self, layer_input):
  212. """
  213. Forward pass of the mixture of experts layer.
  214. Args:
  215. layer_input (Tensor):
  216. Input tensor.
  217. Returns:
  218. Tensor:
  219. Output tensor.
  220. Tensor:
  221. Router logits.
  222. """
  223. bsz, length, emb_size = layer_input.size()
  224. layer_input = layer_input.reshape(-1, emb_size)
  225. _, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
  226. expert_inputs = layer_input[batch_index]
  227. hidden_states = self.input_linear(expert_inputs, expert_size)
  228. chunked_hidden_states = hidden_states.chunk(2, dim=-1)
  229. hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
  230. expert_outputs = self.output_linear(hidden_states, expert_size)
  231. expert_outputs = expert_outputs * batch_gates[:, None]
  232. zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
  233. layer_output = zeros.index_add(0, batch_index, expert_outputs)
  234. layer_output = layer_output.view(bsz, length, self.input_size)
  235. layer_output = layer_output + self.bias
  236. return layer_output, router_logits
  237. class JetMoeMoA(nn.Module):
  238. """
  239. A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts.
  240. Args:
  241. config:
  242. Configuration object with model hyperparameters.
  243. """
  244. def __init__(self, config: JetMoeConfig):
  245. super().__init__()
  246. self.num_experts = config.num_local_experts
  247. self.input_size = config.hidden_size
  248. self.hidden_size = config.kv_channels * config.num_key_value_heads
  249. self.top_k = config.num_experts_per_tok
  250. self.bias = torch.nn.Parameter(torch.empty(self.input_size))
  251. self.input_linear = JetMoeParallelExperts(self.num_experts, self.input_size, self.hidden_size)
  252. self.output_linear = JetMoeParallelExperts(self.num_experts, self.hidden_size, self.input_size)
  253. self.router = JetMoeTopKGating(
  254. input_size=self.input_size,
  255. num_experts=self.num_experts,
  256. top_k=self.top_k,
  257. )
  258. def map(self, layer_input):
  259. """
  260. Map inputs to attention experts according to routing decision and compute query projection inside each experts.
  261. """
  262. # Compute gating topology
  263. bsz, length, emb_size = layer_input.size()
  264. layer_input = layer_input.reshape(-1, emb_size) # [bsz * length, emb_size]
  265. index_sorted_experts, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
  266. topo_info = (index_sorted_experts, batch_index, batch_gates, expert_size)
  267. # Group inputs according to topology and compute query projection
  268. expert_inputs = layer_input[batch_index] # [bsz * length * top_k, emb_size]
  269. expert_outputs = self.input_linear(expert_inputs, expert_size) # [bsz * length * top_k, hidden_size]
  270. # Ungroup queries back to original order
  271. zeros = torch.zeros(
  272. (bsz * length * self.top_k, self.hidden_size), dtype=expert_outputs.dtype, device=expert_outputs.device
  273. )
  274. layer_output = zeros.index_add(0, index_sorted_experts, expert_outputs)
  275. layer_output = layer_output.view(bsz, length, self.top_k, -1) # [bsz, length, top_k, hidden_size]
  276. return layer_output, router_logits, topo_info
  277. def reduce(self, layer_input, topo_info):
  278. """
  279. Compute output projection inside each attention experts and merge the outputs of different experts.
  280. """
  281. bsz, length, k, hidden_size = layer_input.size()
  282. layer_input = layer_input.reshape(-1, hidden_size) # [bsz * length * k, hidden_size]
  283. index_sorted_experts, batch_index, batch_gates, expert_size = topo_info
  284. # Group inputs according to topology and compute output projection
  285. expert_inputs = layer_input[index_sorted_experts] # [bsz * length * top_k, hidden_size]
  286. expert_outputs = self.output_linear(expert_inputs, expert_size) # [bsz * length * top_k, emb_size]
  287. # Apply gates to attention expert outputs
  288. expert_outputs = expert_outputs * batch_gates[:, None]
  289. # Ungroup and merge outputs to original order
  290. zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
  291. layer_output = zeros.index_add(0, batch_index, expert_outputs)
  292. layer_output = layer_output.view(bsz, length, self.input_size)
  293. layer_output = layer_output + self.bias
  294. return layer_output
  295. def forward(self, layer_input):
  296. raise NotImplementedError("This module doesn't support call and forward.")
  297. # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->JetMoe
  298. class JetMoeRMSNorm(nn.Module):
  299. def __init__(self, hidden_size, eps=1e-6):
  300. """
  301. JetMoeRMSNorm is equivalent to T5LayerNorm
  302. """
  303. super().__init__()
  304. self.weight = nn.Parameter(torch.ones(hidden_size))
  305. self.variance_epsilon = eps
  306. def forward(self, hidden_states):
  307. input_dtype = hidden_states.dtype
  308. hidden_states = hidden_states.to(torch.float32)
  309. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  310. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  311. return self.weight * hidden_states.to(input_dtype)
  312. def extra_repr(self):
  313. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  314. # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with Gemma->JetMoe
  315. class JetMoeRotaryEmbedding(nn.Module):
  316. inv_freq: torch.Tensor # fix linting for `register_buffer`
  317. def __init__(self, config: JetMoeConfig, device=None):
  318. super().__init__()
  319. # BC: "rope_type" was originally "type"
  320. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  321. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  322. else:
  323. self.rope_type = "default"
  324. self.max_seq_len_cached = config.max_position_embeddings
  325. self.original_max_seq_len = config.max_position_embeddings
  326. self.config = config
  327. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  328. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  329. self.register_buffer("inv_freq", inv_freq, persistent=False)
  330. self.original_inv_freq = self.inv_freq
  331. @torch.no_grad()
  332. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  333. def forward(self, x, position_ids):
  334. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  335. position_ids_expanded = position_ids[:, None, :].float()
  336. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  337. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  338. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  339. emb = torch.cat((freqs, freqs), dim=-1)
  340. cos = emb.cos() * self.attention_scaling
  341. sin = emb.sin() * self.attention_scaling
  342. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  343. # Copied from transformers.models.llama.modeling_llama.rotate_half
  344. def rotate_half(x):
  345. """Rotates half the hidden dims of the input."""
  346. x1 = x[..., : x.shape[-1] // 2]
  347. x2 = x[..., x.shape[-1] // 2 :]
  348. return torch.cat((-x2, x1), dim=-1)
  349. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  350. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  351. """Applies Rotary Position Embedding to the query and key tensors.
  352. Args:
  353. q (`torch.Tensor`): The query tensor.
  354. k (`torch.Tensor`): The key tensor.
  355. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  356. sin (`torch.Tensor`): The sine part of the rotary embedding.
  357. position_ids (`torch.Tensor`, *optional*):
  358. Deprecated and unused.
  359. unsqueeze_dim (`int`, *optional*, defaults to 1):
  360. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  361. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  362. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  363. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  364. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  365. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  366. Returns:
  367. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  368. """
  369. cos = cos.unsqueeze(unsqueeze_dim)
  370. sin = sin.unsqueeze(unsqueeze_dim)
  371. q_embed = (q * cos) + (rotate_half(q) * sin)
  372. k_embed = (k * cos) + (rotate_half(k) * sin)
  373. return q_embed, k_embed
  374. class JetMoeAttention(nn.Module):
  375. """
  376. Multi-headed attention from 'Attention Is All You Need' paper.
  377. """
  378. def __init__(self, config: JetMoeConfig, layer_idx: Optional[int] = None):
  379. """
  380. Initialize the JetMoeAttention module.
  381. Args:
  382. config:
  383. Configuration object with model hyperparameters.
  384. layer_idx:
  385. Index of the layer in the model.
  386. """
  387. super().__init__()
  388. self.config = config
  389. self.layer_idx = layer_idx
  390. self.is_causal = True
  391. if layer_idx is None:
  392. logger.warning_once(
  393. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  394. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  395. "when creating this class."
  396. )
  397. self.top_k = config.num_experts_per_tok
  398. self.attention_dropout = config.attention_dropout
  399. self.kv_projection_size = config.kv_channels * config.num_key_value_heads
  400. self.num_key_value_heads = config.num_key_value_heads
  401. self.num_heads = config.num_attention_heads
  402. self.head_dim = config.kv_channels
  403. self.experts = JetMoeMoA(config)
  404. self.kv_proj = torch.nn.Linear(config.hidden_size, self.kv_projection_size * 2, bias=False)
  405. self.rotary_emb = JetMoeRotaryEmbedding(config)
  406. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  407. def forward(
  408. self,
  409. hidden_states: torch.Tensor,
  410. attention_mask: Optional[torch.Tensor] = None,
  411. position_ids: Optional[torch.LongTensor] = None,
  412. past_key_values: Optional[Cache] = None,
  413. output_attentions: bool = False,
  414. use_cache: bool = False,
  415. cache_position: Optional[torch.LongTensor] = None,
  416. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  417. bsz, q_len, _ = hidden_states.size()
  418. query_states, router_logits, topo_info = self.experts.map(hidden_states)
  419. key_states, value_states = self.kv_proj(hidden_states).chunk(2, dim=-1)
  420. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  421. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  422. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  423. cos, sin = self.rotary_emb(value_states, position_ids)
  424. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  425. if past_key_values is not None:
  426. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  427. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  428. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  429. # repeat k/v heads for top-k attention experts
  430. key_states = key_states.repeat(1, self.top_k, 1, 1)
  431. value_states = value_states.repeat(1, self.top_k, 1, 1)
  432. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
  433. if attention_mask is not None: # no matter the length, we just slice it
  434. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  435. attn_weights = attn_weights + causal_mask
  436. # upcast attention to fp32
  437. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
  438. attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
  439. attn_output = torch.matmul(attn_weights, value_states)
  440. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  441. raise ValueError(
  442. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  443. f" {attn_output.size()}"
  444. )
  445. attn_output = attn_output.transpose(1, 2).contiguous()
  446. attn_output = attn_output.reshape(bsz, q_len, self.top_k, self.kv_projection_size)
  447. attn_output = self.experts.reduce(attn_output, topo_info)
  448. attn_output = attn_output.view(bsz, q_len, -1)
  449. if not output_attentions:
  450. attn_weights = None
  451. return attn_output, attn_weights, router_logits
  452. class JetMoeSdpaAttention(JetMoeAttention):
  453. """
  454. JetMoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
  455. `JetMoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
  456. SDPA API.
  457. """
  458. # Adapted from JetMoeAttention.forward
  459. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  460. def forward(
  461. self,
  462. hidden_states: torch.Tensor,
  463. attention_mask: Optional[torch.Tensor] = None,
  464. position_ids: Optional[torch.LongTensor] = None,
  465. past_key_values: Optional[Cache] = None,
  466. output_attentions: bool = False,
  467. use_cache: bool = False,
  468. cache_position: Optional[torch.LongTensor] = None,
  469. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]], Optional[torch.Tensor]]:
  470. if output_attentions:
  471. # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
  472. logger.warning_once(
  473. "JetMoeModel is using JetMoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
  474. 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
  475. )
  476. return super().forward(
  477. hidden_states=hidden_states,
  478. attention_mask=attention_mask,
  479. position_ids=position_ids,
  480. past_key_values=past_key_values,
  481. output_attentions=output_attentions,
  482. use_cache=use_cache,
  483. cache_position=cache_position,
  484. )
  485. bsz, q_len, _ = hidden_states.size()
  486. query_states, router_logits, topo_info = self.experts.map(hidden_states)
  487. key_states, value_states = self.kv_proj(hidden_states).chunk(2, dim=-1)
  488. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  489. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  490. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  491. cos, sin = self.rotary_emb(value_states, position_ids)
  492. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  493. if past_key_values is not None:
  494. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  495. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  496. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  497. # repeat k/v heads for top-k attention experts
  498. key_states = key_states.repeat(1, self.top_k, 1, 1)
  499. value_states = value_states.repeat(1, self.top_k, 1, 1)
  500. causal_mask = attention_mask
  501. if attention_mask is not None:
  502. causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
  503. # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
  504. # Reference: https://github.com/pytorch/pytorch/issues/112577.
  505. if query_states.device.type == "cuda" and causal_mask is not None:
  506. query_states = query_states.contiguous()
  507. key_states = key_states.contiguous()
  508. value_states = value_states.contiguous()
  509. # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
  510. # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
  511. is_causal = causal_mask is None and q_len > 1
  512. attn_output = torch.nn.functional.scaled_dot_product_attention(
  513. query_states,
  514. key_states,
  515. value_states,
  516. attn_mask=causal_mask,
  517. dropout_p=self.attention_dropout if self.training else 0.0,
  518. is_causal=is_causal,
  519. )
  520. attn_output = attn_output.transpose(1, 2).contiguous()
  521. attn_output = attn_output.reshape(bsz, q_len, self.top_k, self.kv_projection_size)
  522. attn_output = self.experts.reduce(attn_output, topo_info)
  523. attn_output = attn_output.view(bsz, q_len, -1)
  524. return attn_output, None, router_logits
  525. class JetMoeFlashAttention2(JetMoeAttention):
  526. def __init__(self, *args, **kwargs):
  527. super().__init__(*args, **kwargs)
  528. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  529. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
  530. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
  531. self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
  532. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  533. def forward(
  534. self,
  535. hidden_states: Optional[torch.FloatTensor],
  536. attention_mask: Optional[torch.FloatTensor] = None,
  537. position_ids: Optional[torch.LongTensor] = None,
  538. past_key_values: Optional[Cache] = None,
  539. use_cache: Optional[bool] = False,
  540. output_attentions: Optional[bool] = False,
  541. cache_position: Optional[torch.LongTensor] = None,
  542. ) -> Union[
  543. tuple[torch.Tensor, tuple[torch.Tensor]],
  544. Optional[tuple[torch.Tensor, tuple[torch.Tensor], tuple[torch.Tensor, ...]]],
  545. ]:
  546. """
  547. Forward pass of the JetMoeAttention module.
  548. Args:
  549. hidden_states (Optional[torch.FloatTensor]): Input hidden states.
  550. attention_mask (Optional[torch.FloatTensor]): Attention mask.
  551. layer_past (Optional[tuple[torch.Tensor]]): Past layer state.
  552. use_cache (Optional[bool]): Whether to use cached states.
  553. output_attentions (Optional[bool]): Whether to output attention weights.
  554. cache_position (Optional[torch.LongTensor]): Position of the cache.
  555. Returns:
  556. Union[tuple[torch.Tensor, tuple[torch.Tensor]], Optional[tuple[...]]]: Tuple containing outputs.
  557. """
  558. output_attentions = False
  559. bsz, q_len, hidden_size = hidden_states.size()
  560. # calculate query, key, values
  561. query_states, router_logits, topo_info = self.experts.map(hidden_states)
  562. key_states, value_states = self.kv_proj(hidden_states).chunk(2, dim=-1)
  563. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  564. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  565. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  566. cos, sin = self.rotary_emb(value_states, position_ids)
  567. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  568. if past_key_values is not None:
  569. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  570. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  571. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  572. # repeat k/v heads for top-k attention experts
  573. key_states = key_states.repeat(1, self.top_k, 1, 1)
  574. value_states = value_states.repeat(1, self.top_k, 1, 1)
  575. # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
  576. # to be able to avoid many of these transpose/reshape/view.
  577. query_states = query_states.transpose(1, 2)
  578. key_states = key_states.transpose(1, 2)
  579. value_states = value_states.transpose(1, 2)
  580. dropout_rate = self.attention_dropout if self.training else 0.0
  581. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  582. # therefore the input hidden states gets silently casted in float32. Hence, we need
  583. # cast them back in the correct dtype just to be sure everything works as expected.
  584. # This might slowdown training & inference so it is recommended to not cast the LayerNorms
  585. # in fp32. (LlamaRMSNorm handles it correctly)
  586. input_dtype = query_states.dtype
  587. device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
  588. if input_dtype == torch.float32:
  589. if torch.is_autocast_enabled():
  590. target_dtype = (
  591. torch.get_autocast_dtype(device_type)
  592. if hasattr(torch, "get_autocast_dtype")
  593. else torch.get_autocast_gpu_dtype()
  594. )
  595. # Handle the case where the model is quantized
  596. elif hasattr(self.config, "_pre_quantization_dtype"):
  597. target_dtype = self.config._pre_quantization_dtype
  598. else:
  599. target_dtype = self.kv_proj.weight.dtype
  600. logger.warning_once(
  601. f"The input hidden states seems to be silently casted in float32, this might be related to"
  602. f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
  603. f" {target_dtype}."
  604. )
  605. query_states = query_states.to(target_dtype)
  606. key_states = key_states.to(target_dtype)
  607. value_states = value_states.to(target_dtype)
  608. attn_output = _flash_attention_forward(
  609. query_states,
  610. key_states,
  611. value_states,
  612. attention_mask,
  613. q_len,
  614. dropout=dropout_rate,
  615. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  616. is_causal=self.is_causal,
  617. ).to(input_dtype)
  618. # output projection
  619. attn_output = attn_output.reshape(bsz, q_len, self.top_k, self.kv_projection_size)
  620. attn_output = self.experts.reduce(attn_output, topo_info)
  621. attn_output = attn_output.view(bsz, q_len, hidden_size) # re-assemble all head outputs side by side
  622. if not output_attentions:
  623. attn_weights = None
  624. return attn_output, attn_weights, router_logits
  625. JETMOE_ATTENTION_CLASSES = {
  626. "eager": JetMoeAttention,
  627. "flash_attention_2": JetMoeFlashAttention2,
  628. "sdpa": JetMoeSdpaAttention,
  629. }
  630. class JetMoeBlock(GradientCheckpointingLayer):
  631. def __init__(self, config: JetMoeConfig, layer_idx: Optional[int] = None):
  632. """
  633. Initialize the JetMoeBlock module.
  634. Args:
  635. config:
  636. Configuration object with model hyperparameters.
  637. """
  638. super().__init__()
  639. self.input_layernorm = JetMoeRMSNorm(config.hidden_size)
  640. self.self_attention = JETMOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
  641. self.post_attention_layernorm = JetMoeRMSNorm(config.hidden_size)
  642. self.mlp = JetMoeMoE(config)
  643. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  644. def forward(
  645. self,
  646. hidden_states: Optional[torch.FloatTensor],
  647. position_ids: Optional[torch.LongTensor] = None,
  648. past_key_values: Optional[Cache] = None,
  649. attention_mask: Optional[torch.FloatTensor] = None,
  650. output_attentions: Optional[bool] = False,
  651. output_router_logits: Optional[bool] = False,
  652. use_cache: Optional[bool] = False,
  653. cache_position: Optional[torch.LongTensor] = None,
  654. ) -> Union[tuple[torch.Tensor], Optional[tuple[torch.Tensor, tuple[torch.FloatTensor, ...]]]]:
  655. # Self Attention
  656. attn_output, self_attn_weights, attn_router_logits = self.self_attention(
  657. hidden_states=self.input_layernorm(hidden_states),
  658. attention_mask=attention_mask,
  659. position_ids=position_ids,
  660. past_key_values=past_key_values,
  661. output_attentions=output_attentions,
  662. use_cache=use_cache,
  663. cache_position=cache_position,
  664. )
  665. hidden_states = hidden_states + attn_output
  666. x_mlp, mlp_router_logits = self.mlp(self.post_attention_layernorm(hidden_states))
  667. hidden_states = hidden_states + x_mlp
  668. outputs = (hidden_states,)
  669. if output_attentions:
  670. outputs += (self_attn_weights,)
  671. if output_router_logits:
  672. outputs += attn_router_logits, mlp_router_logits
  673. return outputs
  674. @auto_docstring
  675. class JetMoePreTrainedModel(PreTrainedModel):
  676. config: JetMoeConfig
  677. base_model_prefix = "transformer"
  678. supports_gradient_checkpointing = False
  679. _no_split_modules = ["JetMoeBlock"]
  680. _skip_keys_device_placement = ["past_key_values"]
  681. _supports_flash_attn = True
  682. _supports_sdpa = True
  683. def _init_weights(self, module):
  684. """Initialize the weights."""
  685. if isinstance(module, (nn.Linear,)):
  686. # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
  687. # cf https://github.com/pytorch/pytorch/pull/5617
  688. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  689. if module.bias is not None:
  690. module.bias.data.zero_()
  691. elif isinstance(module, nn.Embedding):
  692. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  693. if module.padding_idx is not None:
  694. module.weight.data[module.padding_idx].zero_()
  695. elif isinstance(module, JetMoeRMSNorm):
  696. module.weight.data.fill_(1.0)
  697. elif isinstance(module, JetMoeParallelExperts):
  698. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  699. elif isinstance(module, (JetMoeMoA, JetMoeMoE)):
  700. module.bias.data.zero_()
  701. @auto_docstring
  702. class JetMoeModel(JetMoePreTrainedModel):
  703. """
  704. Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`JetMoeBlock`]
  705. Args:
  706. config:
  707. JetMoeConfig
  708. """
  709. def __init__(self, config: JetMoeConfig):
  710. super().__init__(config)
  711. self.padding_idx = config.pad_token_id
  712. self.vocab_size = config.vocab_size
  713. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  714. self.layers = nn.ModuleList([JetMoeBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
  715. self._attn_implementation = config._attn_implementation
  716. self.norm = JetMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  717. self.gradient_checkpointing = False
  718. # Initialize weights and apply final processing
  719. self.post_init()
  720. @can_return_tuple
  721. @auto_docstring
  722. def forward(
  723. self,
  724. input_ids: Optional[torch.LongTensor] = None,
  725. attention_mask: Optional[torch.Tensor] = None,
  726. position_ids: Optional[torch.LongTensor] = None,
  727. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  728. inputs_embeds: Optional[torch.FloatTensor] = None,
  729. use_cache: Optional[bool] = None,
  730. output_attentions: Optional[bool] = None,
  731. output_hidden_states: Optional[bool] = None,
  732. output_router_logits: Optional[bool] = None,
  733. cache_position: Optional[torch.LongTensor] = None,
  734. ) -> MoeModelOutputWithPast:
  735. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  736. output_hidden_states = (
  737. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  738. )
  739. output_router_logits = (
  740. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  741. )
  742. use_cache = use_cache if use_cache is not None else self.config.use_cache
  743. if (input_ids is None) ^ (inputs_embeds is not None):
  744. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  745. if self.gradient_checkpointing and self.training and use_cache:
  746. logger.warning_once(
  747. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  748. )
  749. use_cache = False
  750. if inputs_embeds is None:
  751. inputs_embeds = self.embed_tokens(input_ids)
  752. if use_cache and past_key_values is None:
  753. past_key_values = DynamicCache(config=self.config)
  754. if cache_position is None:
  755. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  756. cache_position = torch.arange(
  757. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  758. )
  759. if position_ids is None:
  760. position_ids = cache_position.unsqueeze(0)
  761. causal_mask = self._update_causal_mask(
  762. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
  763. )
  764. hidden_states = inputs_embeds
  765. # decoder layers
  766. all_hidden_states = () if output_hidden_states else None
  767. all_self_attns = () if output_attentions else None
  768. all_router_logits = () if output_router_logits else None
  769. for decoder_layer in self.layers:
  770. if output_hidden_states:
  771. all_hidden_states += (hidden_states,)
  772. layer_outputs = decoder_layer(
  773. hidden_states,
  774. attention_mask=causal_mask,
  775. position_ids=position_ids,
  776. past_key_values=past_key_values,
  777. output_attentions=output_attentions,
  778. output_router_logits=output_router_logits,
  779. use_cache=use_cache,
  780. )
  781. hidden_states = layer_outputs[0]
  782. if output_attentions:
  783. all_self_attns += (layer_outputs[1],)
  784. if output_router_logits:
  785. all_router_logits += (layer_outputs[-2], layer_outputs[-1])
  786. hidden_states = self.norm(hidden_states)
  787. # add hidden states from the last decoder layer
  788. if output_hidden_states:
  789. all_hidden_states += (hidden_states,)
  790. return MoeModelOutputWithPast(
  791. last_hidden_state=hidden_states,
  792. past_key_values=past_key_values,
  793. hidden_states=all_hidden_states,
  794. attentions=all_self_attns,
  795. router_logits=all_router_logits,
  796. )
  797. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._update_causal_mask
  798. def _update_causal_mask(
  799. self,
  800. attention_mask: Union[torch.Tensor, "BlockMask"],
  801. input_tensor: torch.Tensor,
  802. cache_position: torch.Tensor,
  803. past_key_values: Cache,
  804. output_attentions: bool = False,
  805. ):
  806. if self.config._attn_implementation == "flash_attention_2":
  807. if attention_mask is not None and (attention_mask == 0.0).any():
  808. return attention_mask
  809. return None
  810. if self.config._attn_implementation == "flex_attention":
  811. if isinstance(attention_mask, torch.Tensor):
  812. attention_mask = make_flex_block_causal_mask(attention_mask)
  813. return attention_mask
  814. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  815. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  816. # to infer the attention mask.
  817. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  818. using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
  819. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  820. if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
  821. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  822. attention_mask,
  823. inputs_embeds=input_tensor,
  824. past_key_values_length=past_seen_tokens,
  825. is_training=self.training,
  826. ):
  827. return None
  828. dtype = input_tensor.dtype
  829. sequence_length = input_tensor.shape[1]
  830. if using_compilable_cache:
  831. target_length = past_key_values.get_max_cache_shape()
  832. else:
  833. target_length = (
  834. attention_mask.shape[-1]
  835. if isinstance(attention_mask, torch.Tensor)
  836. else past_seen_tokens + sequence_length + 1
  837. )
  838. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  839. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  840. attention_mask,
  841. sequence_length=sequence_length,
  842. target_length=target_length,
  843. dtype=dtype,
  844. cache_position=cache_position,
  845. batch_size=input_tensor.shape[0],
  846. )
  847. if (
  848. self.config._attn_implementation == "sdpa"
  849. and attention_mask is not None
  850. and attention_mask.device.type in ["cuda", "xpu", "npu"]
  851. and not output_attentions
  852. ):
  853. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  854. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  855. # Details: https://github.com/pytorch/pytorch/issues/110213
  856. min_dtype = torch.finfo(dtype).min
  857. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  858. return causal_mask
  859. @staticmethod
  860. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
  861. def _prepare_4d_causal_attention_mask_with_cache_position(
  862. attention_mask: torch.Tensor,
  863. sequence_length: int,
  864. target_length: int,
  865. dtype: torch.dtype,
  866. cache_position: torch.Tensor,
  867. batch_size: int,
  868. **kwargs,
  869. ):
  870. """
  871. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  872. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  873. Args:
  874. attention_mask (`torch.Tensor`):
  875. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  876. `(batch_size, 1, query_length, key_value_length)`.
  877. sequence_length (`int`):
  878. The sequence length being processed.
  879. target_length (`int`):
  880. The target length: when generating with static cache, the mask should be as long as the static cache,
  881. to account for the 0 padding, the part of the cache that is not filled yet.
  882. dtype (`torch.dtype`):
  883. The dtype to use for the 4D attention mask.
  884. cache_position (`torch.Tensor`):
  885. Indices depicting the position of the input sequence tokens in the sequence.
  886. batch_size (`torch.Tensor`):
  887. Batch size.
  888. """
  889. if attention_mask is not None and attention_mask.dim() == 4:
  890. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  891. causal_mask = attention_mask
  892. else:
  893. min_dtype = torch.finfo(dtype).min
  894. causal_mask = torch.full(
  895. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
  896. )
  897. if sequence_length != 1:
  898. causal_mask = torch.triu(causal_mask, diagonal=1)
  899. causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
  900. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  901. if attention_mask is not None:
  902. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  903. mask_length = attention_mask.shape[-1]
  904. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
  905. causal_mask.device
  906. )
  907. padding_mask = padding_mask == 0
  908. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  909. padding_mask, min_dtype
  910. )
  911. return causal_mask
  912. class JetMoeForCausalLM(JetMoePreTrainedModel, GenerationMixin):
  913. _tied_weights_keys = ["lm_head.weight"]
  914. def __init__(self, config):
  915. super().__init__(config)
  916. self.model = JetMoeModel(config)
  917. self.vocab_size = config.vocab_size
  918. self.aux_loss_coef = config.aux_loss_coef
  919. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  920. self.tie_word_embeddings = config.tie_word_embeddings
  921. # Initialize weights and apply final processing
  922. self.post_init()
  923. @can_return_tuple
  924. @auto_docstring
  925. def forward(
  926. self,
  927. input_ids: Optional[torch.LongTensor] = None,
  928. attention_mask: Optional[torch.Tensor] = None,
  929. position_ids: Optional[torch.LongTensor] = None,
  930. past_key_values: Optional[Cache] = None,
  931. inputs_embeds: Optional[torch.FloatTensor] = None,
  932. labels: Optional[torch.LongTensor] = None,
  933. use_cache: Optional[bool] = None,
  934. output_attentions: Optional[bool] = None,
  935. output_hidden_states: Optional[bool] = None,
  936. output_router_logits: Optional[bool] = None,
  937. cache_position: Optional[torch.LongTensor] = None,
  938. logits_to_keep: Union[int, torch.Tensor] = 0,
  939. **kwargs,
  940. ) -> MoeCausalLMOutputWithPast:
  941. r"""
  942. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  943. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  944. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  945. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  946. """
  947. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  948. output_hidden_states = (
  949. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  950. )
  951. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  952. outputs: MoeModelOutputWithPast = self.model(
  953. input_ids=input_ids,
  954. attention_mask=attention_mask,
  955. position_ids=position_ids,
  956. past_key_values=past_key_values,
  957. inputs_embeds=inputs_embeds,
  958. use_cache=use_cache,
  959. output_attentions=output_attentions,
  960. output_hidden_states=output_hidden_states,
  961. cache_position=cache_position,
  962. )
  963. hidden_states = outputs.last_hidden_state
  964. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  965. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  966. logits = self.lm_head(hidden_states[:, slice_indices, :])
  967. loss = None
  968. if labels is not None:
  969. loss = self.loss_function(
  970. logits,
  971. labels,
  972. vocab_size=self.config.vocab_size,
  973. **kwargs,
  974. )
  975. aux_loss = None
  976. if output_router_logits:
  977. aux_loss = load_balancing_loss_func(
  978. outputs.router_logits,
  979. self.num_experts,
  980. self.num_experts_per_tok,
  981. attention_mask,
  982. )
  983. if labels is not None:
  984. loss += self.aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
  985. return MoeCausalLMOutputWithPast(
  986. loss=loss,
  987. aux_loss=aux_loss,
  988. logits=logits,
  989. past_key_values=outputs.past_key_values,
  990. hidden_states=outputs.hidden_states,
  991. attentions=outputs.attentions,
  992. router_logits=outputs.router_logits,
  993. )
  994. class JetMoeForSequenceClassification(GenericForSequenceClassification, JetMoePreTrainedModel): ...
  995. __all__ = ["JetMoeForCausalLM", "JetMoeModel", "JetMoePreTrainedModel", "JetMoeForSequenceClassification"]