modeling_olmoe.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. """PyTorch OLMoE model."""
  13. import math
  14. from typing import Optional, Union
  15. import torch
  16. import torch.nn.functional as F
  17. from torch import nn
  18. from ...activations import ACT2FN
  19. from ...cache_utils import Cache, DynamicCache, StaticCache
  20. from ...generation import GenerationMixin
  21. from ...modeling_attn_mask_utils import AttentionMaskConverter
  22. from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
  23. from ...modeling_layers import GradientCheckpointingLayer
  24. from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
  25. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  26. from ...modeling_utils import PreTrainedModel
  27. from ...utils import auto_docstring, logging
  28. from ...utils.deprecation import deprecate_kwarg
  29. from .configuration_olmoe import OlmoeConfig
  30. if is_flash_attn_available():
  31. from ...modeling_flash_attention_utils import _flash_attention_forward
  32. logger = logging.get_logger(__name__)
  33. # Copied from transformers.models.qwen2_moe.modeling_qwen2_moe.load_balancing_loss_func
  34. def load_balancing_loss_func(
  35. gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
  36. num_experts: Optional[int] = None,
  37. top_k=2,
  38. attention_mask: Optional[torch.Tensor] = None,
  39. ) -> Union[torch.Tensor, int]:
  40. r"""
  41. Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
  42. See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
  43. function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
  44. experts is too unbalanced.
  45. Args:
  46. gate_logits:
  47. Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
  48. shape [batch_size X sequence_length, num_experts].
  49. num_experts:
  50. Number of experts
  51. top_k:
  52. The number of experts to route per-token, can be also interpreted as the `top-k` routing
  53. parameter.
  54. attention_mask (`torch.Tensor`, *optional*):
  55. The attention_mask used in forward function
  56. shape [batch_size X sequence_length] if not None.
  57. Returns:
  58. The auxiliary loss.
  59. """
  60. if gate_logits is None or not isinstance(gate_logits, tuple):
  61. return 0
  62. if isinstance(gate_logits, tuple):
  63. compute_device = gate_logits[0].device
  64. concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
  65. routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
  66. _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
  67. expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
  68. if attention_mask is None:
  69. # Compute the percentage of tokens routed to each experts
  70. tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
  71. # Compute the average probability of routing to these experts
  72. router_prob_per_expert = torch.mean(routing_weights, dim=0)
  73. else:
  74. batch_size, sequence_length = attention_mask.shape
  75. num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
  76. # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
  77. expert_attention_mask = (
  78. attention_mask[None, :, :, None, None]
  79. .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
  80. .reshape(-1, top_k, num_experts)
  81. .to(compute_device)
  82. )
  83. # Compute the percentage of tokens routed to each experts
  84. tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
  85. expert_attention_mask, dim=0
  86. )
  87. # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
  88. router_per_expert_attention_mask = (
  89. attention_mask[None, :, :, None]
  90. .expand((num_hidden_layers, batch_size, sequence_length, routing_weights.shape[1]))
  91. .reshape(-1, routing_weights.shape[1])
  92. .to(compute_device)
  93. )
  94. # Compute the average probability of routing to these experts
  95. router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
  96. router_per_expert_attention_mask, dim=0
  97. )
  98. device_index = routing_weights.device.index if routing_weights.device.index is not None else 0
  99. rank = routing_weights.shape[1] * int(device_index)
  100. overall_loss = torch.sum(
  101. tokens_per_expert[:, rank : rank + routing_weights.shape[1]] * router_prob_per_expert.unsqueeze(0)
  102. )
  103. return overall_loss * num_experts
  104. class OlmoeRMSNorm(nn.Module):
  105. def __init__(self, hidden_size, eps=1e-5):
  106. """
  107. OlmoeRMSNorm is equivalent to T5LayerNorm
  108. """
  109. super().__init__()
  110. self.weight = nn.Parameter(torch.ones(hidden_size))
  111. self.variance_epsilon = eps
  112. def forward(self, hidden_states):
  113. input_dtype = hidden_states.dtype
  114. hidden_states = hidden_states.to(torch.float32)
  115. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  116. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  117. return self.weight * hidden_states.to(input_dtype)
  118. def extra_repr(self):
  119. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  120. # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Olmoe
  121. class OlmoeRotaryEmbedding(nn.Module):
  122. inv_freq: torch.Tensor # fix linting for `register_buffer`
  123. def __init__(self, config: OlmoeConfig, device=None):
  124. super().__init__()
  125. # BC: "rope_type" was originally "type"
  126. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  127. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  128. else:
  129. self.rope_type = "default"
  130. self.max_seq_len_cached = config.max_position_embeddings
  131. self.original_max_seq_len = config.max_position_embeddings
  132. self.config = config
  133. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  134. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  135. self.register_buffer("inv_freq", inv_freq, persistent=False)
  136. self.original_inv_freq = self.inv_freq
  137. @torch.no_grad()
  138. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  139. def forward(self, x, position_ids):
  140. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  141. position_ids_expanded = position_ids[:, None, :].float()
  142. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  143. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  144. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  145. emb = torch.cat((freqs, freqs), dim=-1)
  146. cos = emb.cos() * self.attention_scaling
  147. sin = emb.sin() * self.attention_scaling
  148. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  149. # Copied from transformers.models.llama.modeling_llama.rotate_half
  150. def rotate_half(x):
  151. """Rotates half the hidden dims of the input."""
  152. x1 = x[..., : x.shape[-1] // 2]
  153. x2 = x[..., x.shape[-1] // 2 :]
  154. return torch.cat((-x2, x1), dim=-1)
  155. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  156. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  157. """Applies Rotary Position Embedding to the query and key tensors.
  158. Args:
  159. q (`torch.Tensor`): The query tensor.
  160. k (`torch.Tensor`): The key tensor.
  161. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  162. sin (`torch.Tensor`): The sine part of the rotary embedding.
  163. position_ids (`torch.Tensor`, *optional*):
  164. Deprecated and unused.
  165. unsqueeze_dim (`int`, *optional*, defaults to 1):
  166. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  167. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  168. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  169. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  170. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  171. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  172. Returns:
  173. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  174. """
  175. cos = cos.unsqueeze(unsqueeze_dim)
  176. sin = sin.unsqueeze(unsqueeze_dim)
  177. q_embed = (q * cos) + (rotate_half(q) * sin)
  178. k_embed = (k * cos) + (rotate_half(k) * sin)
  179. return q_embed, k_embed
  180. # Copied from transformers.models.olmo.modeling_olmo.OlmoMLP with Olmo->Olmoe
  181. class OlmoeMLP(nn.Module):
  182. def __init__(self, config):
  183. super().__init__()
  184. self.config = config
  185. self.hidden_size = config.hidden_size
  186. self.intermediate_size = config.intermediate_size
  187. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  188. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  189. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
  190. self.act_fn = ACT2FN[config.hidden_act]
  191. def forward(self, x):
  192. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  193. return down_proj
  194. # Copied from transformers.models.llama.modeling_llama.repeat_kv
  195. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  196. """
  197. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  198. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  199. """
  200. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  201. if n_rep == 1:
  202. return hidden_states
  203. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  204. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  205. class OlmoeAttention(nn.Module):
  206. """Multi-headed attention from 'Attention Is All You Need' paper"""
  207. def __init__(self, config: OlmoeConfig, layer_idx: Optional[int] = None):
  208. super().__init__()
  209. self.config = config
  210. self.layer_idx = layer_idx
  211. if layer_idx is None:
  212. logger.warning_once(
  213. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  214. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  215. "when creating this class."
  216. )
  217. self.attention_dropout = config.attention_dropout
  218. self.hidden_size = config.hidden_size
  219. self.num_heads = config.num_attention_heads
  220. self.head_dim = self.hidden_size // self.num_heads
  221. self.num_key_value_heads = config.num_key_value_heads
  222. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  223. self.max_position_embeddings = config.max_position_embeddings
  224. self.rope_theta = config.rope_theta
  225. self.is_causal = True
  226. if (self.head_dim * self.num_heads) != self.hidden_size:
  227. raise ValueError(
  228. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  229. f" and `num_heads`: {self.num_heads})."
  230. )
  231. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
  232. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  233. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  234. self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
  235. self.q_norm = OlmoeRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
  236. self.k_norm = OlmoeRMSNorm(
  237. (self.hidden_size // self.num_heads) * self.num_key_value_heads, eps=config.rms_norm_eps
  238. )
  239. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  240. def forward(
  241. self,
  242. hidden_states: torch.Tensor,
  243. attention_mask: Optional[torch.Tensor] = None,
  244. position_ids: Optional[torch.LongTensor] = None,
  245. past_key_values: Optional[Cache] = None,
  246. output_attentions: bool = False,
  247. use_cache: bool = False,
  248. cache_position: Optional[torch.LongTensor] = None,
  249. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  250. **kwargs,
  251. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  252. bsz, q_len, _ = hidden_states.size()
  253. query_states = self.q_norm(self.q_proj(hidden_states))
  254. key_states = self.k_norm(self.k_proj(hidden_states))
  255. value_states = self.v_proj(hidden_states)
  256. if self.config.clip_qkv is not None:
  257. query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  258. key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  259. value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  260. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  261. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  262. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  263. cos, sin = position_embeddings
  264. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  265. if past_key_values is not None:
  266. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  267. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  268. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  269. key_states = repeat_kv(key_states, self.num_key_value_groups)
  270. value_states = repeat_kv(value_states, self.num_key_value_groups)
  271. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
  272. if attention_mask is not None: # no matter the length, we just slice it
  273. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  274. attn_weights = attn_weights + causal_mask
  275. # upcast attention to fp32
  276. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
  277. attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
  278. attn_output = torch.matmul(attn_weights, value_states)
  279. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  280. raise ValueError(
  281. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  282. f" {attn_output.size()}"
  283. )
  284. attn_output = attn_output.transpose(1, 2).contiguous()
  285. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  286. attn_output = self.o_proj(attn_output)
  287. if not output_attentions:
  288. attn_weights = None
  289. return attn_output, attn_weights
  290. class OlmoeFlashAttention2(OlmoeAttention):
  291. """
  292. OLMoE flash attention module. This module inherits from `OlmoeAttention` as the weights of the module stays
  293. untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
  294. flash attention and deal with padding tokens in case the input contains any of them.
  295. """
  296. def __init__(self, *args, **kwargs):
  297. super().__init__(*args, **kwargs)
  298. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  299. # 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.
  300. # 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).
  301. self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
  302. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  303. def forward(
  304. self,
  305. hidden_states: torch.Tensor,
  306. attention_mask: Optional[torch.LongTensor] = None,
  307. position_ids: Optional[torch.LongTensor] = None,
  308. past_key_values: Optional[Cache] = None,
  309. output_attentions: bool = False,
  310. use_cache: bool = False,
  311. cache_position: Optional[torch.LongTensor] = None,
  312. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  313. **kwargs,
  314. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  315. output_attentions = False
  316. bsz, q_len, _ = hidden_states.size()
  317. query_states = self.q_norm(self.q_proj(hidden_states))
  318. key_states = self.k_norm(self.k_proj(hidden_states))
  319. value_states = self.v_proj(hidden_states)
  320. if self.config.clip_qkv is not None:
  321. query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  322. key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  323. value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  324. # Flash attention requires the input to have the shape
  325. # batch_size x seq_length x head_dim x hidden_dim
  326. # therefore we just need to keep the original shape
  327. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  328. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  329. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  330. cos, sin = position_embeddings
  331. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  332. if past_key_values is not None:
  333. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  334. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  335. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  336. # 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
  337. # to be able to avoid many of these transpose/reshape/view.
  338. query_states = query_states.transpose(1, 2)
  339. key_states = key_states.transpose(1, 2)
  340. value_states = value_states.transpose(1, 2)
  341. dropout_rate = self.attention_dropout if self.training else 0.0
  342. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  343. # therefore the input hidden states gets silently casted in float32. Hence, we need
  344. # cast them back in the correct dtype just to be sure everything works as expected.
  345. # This might slowdown training & inference so it is recommended to not cast the LayerNorms
  346. # in fp32. (OlmoeRMSNorm handles it correctly)
  347. input_dtype = query_states.dtype
  348. device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
  349. if input_dtype == torch.float32:
  350. if torch.is_autocast_enabled():
  351. target_dtype = (
  352. torch.get_autocast_dtype(device_type)
  353. if hasattr(torch, "get_autocast_dtype")
  354. else torch.get_autocast_gpu_dtype()
  355. )
  356. # Handle the case where the model is quantized
  357. elif hasattr(self.config, "_pre_quantization_dtype"):
  358. target_dtype = self.config._pre_quantization_dtype
  359. else:
  360. target_dtype = self.q_proj.weight.dtype
  361. logger.warning_once(
  362. f"The input hidden states seems to be silently casted in float32, this might be related to"
  363. f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
  364. f" {target_dtype}."
  365. )
  366. query_states = query_states.to(target_dtype)
  367. key_states = key_states.to(target_dtype)
  368. value_states = value_states.to(target_dtype)
  369. attn_output = _flash_attention_forward(
  370. query_states,
  371. key_states,
  372. value_states,
  373. attention_mask,
  374. q_len,
  375. dropout=dropout_rate,
  376. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  377. is_causal=self.is_causal,
  378. )
  379. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
  380. attn_output = self.o_proj(attn_output)
  381. if not output_attentions:
  382. attn_weights = None
  383. return attn_output, attn_weights
  384. class OlmoeSdpaAttention(OlmoeAttention):
  385. """
  386. OLMoE attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
  387. `OlmoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
  388. SDPA API.
  389. """
  390. # Adapted from OlmoeAttention.forward
  391. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  392. def forward(
  393. self,
  394. hidden_states: torch.Tensor,
  395. attention_mask: Optional[torch.Tensor] = None,
  396. position_ids: Optional[torch.LongTensor] = None,
  397. past_key_values: Optional[Cache] = None,
  398. output_attentions: bool = False,
  399. use_cache: bool = False,
  400. cache_position: Optional[torch.LongTensor] = None,
  401. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  402. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  403. if output_attentions:
  404. # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
  405. logger.warning_once(
  406. "OlmoeModel is using OlmoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
  407. '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.'
  408. )
  409. return super().forward(
  410. hidden_states=hidden_states,
  411. attention_mask=attention_mask,
  412. position_ids=position_ids,
  413. past_key_values=past_key_values,
  414. output_attentions=output_attentions,
  415. use_cache=use_cache,
  416. cache_position=cache_position,
  417. position_embeddings=position_embeddings,
  418. )
  419. bsz, q_len, _ = hidden_states.size()
  420. query_states = self.q_norm(self.q_proj(hidden_states))
  421. key_states = self.k_norm(self.k_proj(hidden_states))
  422. value_states = self.v_proj(hidden_states)
  423. if self.config.clip_qkv is not None:
  424. query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  425. key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  426. value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
  427. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  428. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  429. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  430. cos, sin = position_embeddings
  431. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  432. if past_key_values is not None:
  433. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  434. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  435. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  436. key_states = repeat_kv(key_states, self.num_key_value_groups)
  437. value_states = repeat_kv(value_states, self.num_key_value_groups)
  438. causal_mask = attention_mask
  439. # if attention_mask is not None and cache_position is not None:
  440. if attention_mask is not None:
  441. causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
  442. # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
  443. # Reference: https://github.com/pytorch/pytorch/issues/112577.
  444. if query_states.device.type == "cuda" and causal_mask is not None:
  445. query_states = query_states.contiguous()
  446. key_states = key_states.contiguous()
  447. value_states = value_states.contiguous()
  448. # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
  449. # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
  450. is_causal = causal_mask is None and q_len > 1
  451. attn_output = torch.nn.functional.scaled_dot_product_attention(
  452. query_states,
  453. key_states,
  454. value_states,
  455. attn_mask=causal_mask,
  456. dropout_p=self.attention_dropout if self.training else 0.0,
  457. is_causal=is_causal,
  458. )
  459. attn_output = attn_output.transpose(1, 2).contiguous()
  460. attn_output = attn_output.view(bsz, q_len, self.hidden_size)
  461. attn_output = self.o_proj(attn_output)
  462. return attn_output, None
  463. OLMOE_ATTENTION_CLASSES = {
  464. "eager": OlmoeAttention,
  465. "flash_attention_2": OlmoeFlashAttention2,
  466. "sdpa": OlmoeSdpaAttention,
  467. }
  468. class OlmoeSparseMoeBlock(nn.Module):
  469. def __init__(self, config):
  470. super().__init__()
  471. self.num_experts = config.num_experts
  472. self.top_k = config.num_experts_per_tok
  473. self.norm_topk_prob = config.norm_topk_prob
  474. self.gate = nn.Linear(config.hidden_size, self.num_experts, bias=False)
  475. self.experts = nn.ModuleList([OlmoeMLP(config) for _ in range(self.num_experts)])
  476. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  477. batch_size, sequence_length, hidden_dim = hidden_states.shape
  478. hidden_states = hidden_states.view(-1, hidden_dim)
  479. # router_logits: (batch * sequence_length, n_experts)
  480. router_logits = self.gate(hidden_states)
  481. routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
  482. routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
  483. if self.norm_topk_prob:
  484. routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
  485. # we cast back to the input dtype
  486. routing_weights = routing_weights.to(hidden_states.dtype)
  487. final_hidden_states = torch.zeros(
  488. (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
  489. )
  490. # One hot encode the selected experts to create an expert mask
  491. # this will be used to easily index which expert is going to be selected
  492. expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
  493. # Loop over all available experts in the model and perform the computation on each expert
  494. for expert_idx in range(self.num_experts):
  495. expert_layer = self.experts[expert_idx]
  496. idx, top_x = torch.where(expert_mask[expert_idx])
  497. # Index the correct hidden states and compute the expert hidden state for
  498. # the current expert. We need to make sure to multiply the output hidden
  499. # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
  500. current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
  501. current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
  502. # However `index_add_` only support torch tensors for indexing so we'll use
  503. # the `top_x` tensor here.
  504. final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
  505. final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
  506. return final_hidden_states, router_logits
  507. class OlmoeDecoderLayer(GradientCheckpointingLayer):
  508. def __init__(self, config: OlmoeConfig, layer_idx: int):
  509. super().__init__()
  510. self.hidden_size = config.hidden_size
  511. self.self_attn = OLMOE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
  512. self.mlp = OlmoeSparseMoeBlock(config)
  513. self.input_layernorm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  514. self.post_attention_layernorm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  515. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  516. def forward(
  517. self,
  518. hidden_states: torch.Tensor,
  519. attention_mask: Optional[torch.Tensor] = None,
  520. position_ids: Optional[torch.LongTensor] = None,
  521. past_key_values: Optional[Cache] = None,
  522. output_attentions: Optional[bool] = False,
  523. output_router_logits: Optional[bool] = False,
  524. use_cache: Optional[bool] = False,
  525. cache_position: Optional[torch.LongTensor] = None,
  526. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  527. **kwargs,
  528. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  529. """
  530. Args:
  531. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  532. attention_mask (`torch.FloatTensor`, *optional*):
  533. attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
  534. query_sequence_length, key_sequence_length)` if default attention is used.
  535. output_attentions (`bool`, *optional*):
  536. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  537. returned tensors for more detail.
  538. output_router_logits (`bool`, *optional*):
  539. Whether or not to return the logits of all the routers. They are useful for computing the router loss,
  540. and should not be returned during inference.
  541. use_cache (`bool`, *optional*):
  542. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  543. (see `past_key_values`).
  544. past_key_values (`Cache`, *optional*): cached past key and value projection states
  545. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  546. Indices depicting the position of the input sequence tokens in the sequence
  547. position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  548. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  549. with `head_dim` being the embedding dimension of each attention head.
  550. kwargs (`dict`, *optional*):
  551. Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
  552. into the model
  553. """
  554. residual = hidden_states
  555. hidden_states = self.input_layernorm(hidden_states)
  556. # Self Attention
  557. hidden_states, self_attn_weights = self.self_attn(
  558. hidden_states=hidden_states,
  559. attention_mask=attention_mask,
  560. position_ids=position_ids,
  561. past_key_values=past_key_values,
  562. output_attentions=output_attentions,
  563. use_cache=use_cache,
  564. cache_position=cache_position,
  565. position_embeddings=position_embeddings,
  566. **kwargs,
  567. )
  568. hidden_states = residual + hidden_states
  569. # Fully Connected
  570. residual = hidden_states
  571. hidden_states = self.post_attention_layernorm(hidden_states)
  572. hidden_states, router_logits = self.mlp(hidden_states)
  573. hidden_states = residual + hidden_states
  574. outputs = (hidden_states,)
  575. if output_attentions:
  576. outputs += (self_attn_weights,)
  577. if output_router_logits:
  578. outputs += (router_logits,)
  579. return outputs
  580. @auto_docstring
  581. class OlmoePreTrainedModel(PreTrainedModel):
  582. config: OlmoeConfig
  583. base_model_prefix = "model"
  584. supports_gradient_checkpointing = True
  585. _no_split_modules = ["OlmoeDecoderLayer"]
  586. _skip_keys_device_placement = ["past_key_values"]
  587. _supports_flash_attn = True
  588. _supports_sdpa = True
  589. _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
  590. def _init_weights(self, module):
  591. std = self.config.initializer_range
  592. if isinstance(module, nn.Linear):
  593. module.weight.data.normal_(mean=0.0, std=std)
  594. if module.bias is not None:
  595. module.bias.data.zero_()
  596. elif isinstance(module, OlmoeRMSNorm):
  597. module.weight.data.fill_(1.0)
  598. elif isinstance(module, nn.Embedding):
  599. module.weight.data.normal_(mean=0.0, std=std)
  600. if module.padding_idx is not None:
  601. module.weight.data[module.padding_idx].zero_()
  602. @auto_docstring
  603. class OlmoeModel(OlmoePreTrainedModel):
  604. def __init__(self, config: OlmoeConfig):
  605. super().__init__(config)
  606. self.padding_idx = config.pad_token_id
  607. self.vocab_size = config.vocab_size
  608. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  609. self.layers = nn.ModuleList(
  610. [OlmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  611. )
  612. self.norm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  613. self.rotary_emb = OlmoeRotaryEmbedding(config=config)
  614. self.gradient_checkpointing = False
  615. # Initialize weights and apply final processing
  616. self.post_init()
  617. @auto_docstring
  618. def forward(
  619. self,
  620. input_ids: Optional[torch.LongTensor] = None,
  621. attention_mask: Optional[torch.Tensor] = None,
  622. position_ids: Optional[torch.LongTensor] = None,
  623. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  624. inputs_embeds: Optional[torch.FloatTensor] = None,
  625. use_cache: Optional[bool] = None,
  626. output_attentions: Optional[bool] = None,
  627. output_hidden_states: Optional[bool] = None,
  628. output_router_logits: Optional[bool] = None,
  629. return_dict: Optional[bool] = None,
  630. cache_position: Optional[torch.LongTensor] = None,
  631. ) -> Union[tuple, MoeModelOutputWithPast]:
  632. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  633. output_router_logits = (
  634. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  635. )
  636. output_hidden_states = (
  637. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  638. )
  639. use_cache = use_cache if use_cache is not None else self.config.use_cache
  640. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  641. if (input_ids is None) ^ (inputs_embeds is not None):
  642. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  643. if self.gradient_checkpointing and self.training and use_cache:
  644. logger.warning_once(
  645. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  646. )
  647. use_cache = False
  648. if inputs_embeds is None:
  649. inputs_embeds = self.embed_tokens(input_ids)
  650. if use_cache and past_key_values is None:
  651. past_key_values = DynamicCache(config=self.config)
  652. if cache_position is None:
  653. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  654. cache_position = torch.arange(
  655. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  656. )
  657. if position_ids is None:
  658. position_ids = cache_position.unsqueeze(0)
  659. causal_mask = self._update_causal_mask(
  660. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
  661. )
  662. # embed positions
  663. hidden_states = inputs_embeds
  664. # create position embeddings to be shared across the decoder layers
  665. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  666. # decoder layers
  667. all_hidden_states = () if output_hidden_states else None
  668. all_self_attns = () if output_attentions else None
  669. all_router_logits = () if output_router_logits else None
  670. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  671. if output_hidden_states:
  672. all_hidden_states += (hidden_states,)
  673. layer_outputs = decoder_layer(
  674. hidden_states,
  675. attention_mask=causal_mask,
  676. position_ids=position_ids,
  677. past_key_values=past_key_values,
  678. output_attentions=output_attentions,
  679. output_router_logits=output_router_logits,
  680. use_cache=use_cache,
  681. cache_position=cache_position,
  682. position_embeddings=position_embeddings,
  683. )
  684. hidden_states = layer_outputs[0]
  685. if output_attentions:
  686. all_self_attns += (layer_outputs[1],)
  687. if output_router_logits and layer_outputs[-1] is not None:
  688. all_router_logits += (layer_outputs[-1],)
  689. hidden_states = self.norm(hidden_states)
  690. # add hidden states from the last decoder layer
  691. if output_hidden_states:
  692. all_hidden_states += (hidden_states,)
  693. if not return_dict:
  694. return tuple(
  695. v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None
  696. )
  697. return MoeModelOutputWithPast(
  698. last_hidden_state=hidden_states,
  699. past_key_values=past_key_values,
  700. hidden_states=all_hidden_states,
  701. attentions=all_self_attns,
  702. router_logits=all_router_logits,
  703. )
  704. def _update_causal_mask(
  705. self,
  706. attention_mask: torch.Tensor,
  707. input_tensor: torch.Tensor,
  708. cache_position: torch.Tensor,
  709. past_key_values: Cache,
  710. output_attentions: bool,
  711. ):
  712. if self.config._attn_implementation == "flash_attention_2":
  713. if attention_mask is not None and 0.0 in attention_mask:
  714. return attention_mask
  715. return None
  716. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  717. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  718. # to infer the attention mask.
  719. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  720. using_static_cache = isinstance(past_key_values, StaticCache)
  721. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  722. if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
  723. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  724. attention_mask,
  725. inputs_embeds=input_tensor,
  726. past_key_values_length=past_seen_tokens,
  727. is_training=self.training,
  728. ):
  729. return None
  730. dtype, device = input_tensor.dtype, input_tensor.device
  731. sequence_length = input_tensor.shape[1]
  732. if using_static_cache:
  733. target_length = past_key_values.get_max_cache_shape()
  734. else:
  735. target_length = (
  736. attention_mask.shape[-1]
  737. if isinstance(attention_mask, torch.Tensor)
  738. else past_seen_tokens + sequence_length + 1
  739. )
  740. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  741. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  742. attention_mask,
  743. sequence_length=sequence_length,
  744. target_length=target_length,
  745. dtype=dtype,
  746. device=device,
  747. cache_position=cache_position,
  748. batch_size=input_tensor.shape[0],
  749. )
  750. if (
  751. self.config._attn_implementation == "sdpa"
  752. and attention_mask is not None
  753. and attention_mask.device.type in ["cuda", "xpu", "npu"]
  754. and not output_attentions
  755. ):
  756. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  757. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  758. # Details: https://github.com/pytorch/pytorch/issues/110213
  759. min_dtype = torch.finfo(dtype).min
  760. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  761. return causal_mask
  762. @staticmethod
  763. def _prepare_4d_causal_attention_mask_with_cache_position(
  764. attention_mask: torch.Tensor,
  765. sequence_length: int,
  766. target_length: int,
  767. dtype: torch.dtype,
  768. device: torch.device,
  769. cache_position: torch.Tensor,
  770. batch_size: int,
  771. **kwargs,
  772. ):
  773. """
  774. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  775. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  776. Args:
  777. attention_mask (`torch.Tensor`):
  778. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  779. `(batch_size, 1, query_length, key_value_length)`.
  780. sequence_length (`int`):
  781. The sequence length being processed.
  782. target_length (`int`):
  783. The target length: when generating with static cache, the mask should be as long as the static cache,
  784. to account for the 0 padding, the part of the cache that is not filled yet.
  785. dtype (`torch.dtype`):
  786. The dtype to use for the 4D attention mask.
  787. device (`torch.device`):
  788. The device to place the 4D attention mask on.
  789. cache_position (`torch.Tensor`):
  790. Indices depicting the position of the input sequence tokens in the sequence.
  791. batch_size (`torch.Tensor`):
  792. Batch size.
  793. """
  794. if attention_mask is not None and attention_mask.dim() == 4:
  795. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  796. causal_mask = attention_mask
  797. else:
  798. min_dtype = torch.finfo(dtype).min
  799. causal_mask = torch.full(
  800. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
  801. )
  802. if sequence_length != 1:
  803. causal_mask = torch.triu(causal_mask, diagonal=1)
  804. causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
  805. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  806. if attention_mask is not None:
  807. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  808. mask_length = attention_mask.shape[-1]
  809. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
  810. padding_mask = padding_mask == 0
  811. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  812. padding_mask, min_dtype
  813. )
  814. return causal_mask
  815. class OlmoeForCausalLM(OlmoePreTrainedModel, GenerationMixin):
  816. _tied_weights_keys = ["lm_head.weight"]
  817. def __init__(self, config):
  818. super().__init__(config)
  819. self.model = OlmoeModel(config)
  820. self.vocab_size = config.vocab_size
  821. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  822. self.router_aux_loss_coef = config.router_aux_loss_coef
  823. self.num_experts = config.num_experts
  824. self.num_experts_per_tok = config.num_experts_per_tok
  825. # Initialize weights and apply final processing
  826. self.post_init()
  827. @auto_docstring
  828. def forward(
  829. self,
  830. input_ids: Optional[torch.LongTensor] = None,
  831. attention_mask: Optional[torch.Tensor] = None,
  832. position_ids: Optional[torch.LongTensor] = None,
  833. past_key_values: Optional[Cache] = None,
  834. inputs_embeds: Optional[torch.FloatTensor] = None,
  835. labels: Optional[torch.LongTensor] = None,
  836. use_cache: Optional[bool] = None,
  837. output_attentions: Optional[bool] = None,
  838. output_hidden_states: Optional[bool] = None,
  839. output_router_logits: Optional[bool] = None,
  840. return_dict: Optional[bool] = None,
  841. cache_position: Optional[torch.LongTensor] = None,
  842. logits_to_keep: Union[int, torch.Tensor] = 0,
  843. **kwargs,
  844. ) -> Union[tuple, MoeCausalLMOutputWithPast]:
  845. r"""
  846. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  847. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  848. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  849. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  850. Example:
  851. ```python
  852. >>> from transformers import AutoTokenizer, OlmoeForCausalLM
  853. >>> model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924")
  854. >>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")
  855. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  856. >>> inputs = tokenizer(prompt, return_tensors="pt")
  857. >>> # Generate
  858. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  859. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  860. 'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
  861. ```
  862. """
  863. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  864. output_router_logits = (
  865. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  866. )
  867. output_hidden_states = (
  868. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  869. )
  870. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  871. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  872. outputs = self.model(
  873. input_ids=input_ids,
  874. attention_mask=attention_mask,
  875. position_ids=position_ids,
  876. past_key_values=past_key_values,
  877. inputs_embeds=inputs_embeds,
  878. use_cache=use_cache,
  879. output_attentions=output_attentions,
  880. output_hidden_states=output_hidden_states,
  881. output_router_logits=output_router_logits,
  882. return_dict=return_dict,
  883. cache_position=cache_position,
  884. )
  885. hidden_states = outputs[0]
  886. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  887. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  888. logits = self.lm_head(hidden_states[:, slice_indices, :])
  889. loss = None
  890. if labels is not None:
  891. loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
  892. aux_loss = None
  893. if output_router_logits:
  894. aux_loss = load_balancing_loss_func(
  895. outputs.router_logits if return_dict else outputs[-1],
  896. self.num_experts,
  897. self.num_experts_per_tok,
  898. attention_mask,
  899. )
  900. if labels is not None:
  901. loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
  902. if not return_dict:
  903. output = (logits,) + outputs[1:]
  904. if output_router_logits:
  905. output = (aux_loss,) + output
  906. return (loss,) + output if loss is not None else output
  907. return MoeCausalLMOutputWithPast(
  908. loss=loss,
  909. aux_loss=aux_loss,
  910. logits=logits,
  911. past_key_values=outputs.past_key_values,
  912. hidden_states=outputs.hidden_states,
  913. attentions=outputs.attentions,
  914. router_logits=outputs.router_logits,
  915. )
  916. __all__ = ["OlmoeForCausalLM", "OlmoeModel", "OlmoePreTrainedModel"]