modeling_dbrx.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. # coding=utf-8
  2. # Copyright 2024 Databricks Mosaic Research 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 DBRX model."""
  16. import math
  17. from typing import Any, Optional, Union
  18. import torch
  19. from torch import nn
  20. from ...activations import ACT2FN
  21. from ...cache_utils import Cache, DynamicCache, StaticCache
  22. from ...generation import GenerationMixin
  23. from ...modeling_attn_mask_utils import AttentionMaskConverter
  24. from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
  25. from ...modeling_layers import GradientCheckpointingLayer
  26. from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
  27. from ...modeling_utils import PreTrainedModel
  28. from ...utils import auto_docstring, is_torch_flex_attn_available, logging
  29. from ...utils.deprecation import deprecate_kwarg
  30. from .configuration_dbrx import DbrxConfig
  31. if is_torch_flex_attn_available():
  32. from torch.nn.attention.flex_attention import BlockMask
  33. from ...integrations.flex_attention import make_flex_block_causal_mask
  34. if is_flash_attn_available():
  35. from ...modeling_flash_attention_utils import _flash_attention_forward
  36. logger = logging.get_logger(__name__)
  37. class DbrxRotaryEmbedding(nn.Module):
  38. inv_freq: torch.Tensor # fix linting for `register_buffer`
  39. def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
  40. super().__init__()
  41. self.dim = dim
  42. self.max_position_embeddings = max_position_embeddings
  43. self.base = base
  44. inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
  45. self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
  46. @torch.no_grad()
  47. def forward(self, x, position_ids, seq_len=None):
  48. # x: [bs, num_attention_heads, seq_len, head_size]
  49. self.inv_freq.to(x.device)
  50. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
  51. position_ids_expanded = position_ids[:, None, :].float()
  52. # Force float32 since bfloat16 loses precision on long contexts
  53. # See https://github.com/huggingface/transformers/pull/29285
  54. device_type = x.device.type
  55. device_type = device_type if device_type != "mps" else "cpu"
  56. with torch.autocast(device_type=device_type, enabled=False):
  57. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  58. emb = torch.cat((freqs, freqs), dim=-1)
  59. cos = emb.cos()
  60. sin = emb.sin()
  61. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  62. # Copied from transformers.models.llama.modeling_llama.rotate_half
  63. def rotate_half(x):
  64. """Rotates half the hidden dims of the input."""
  65. x1 = x[..., : x.shape[-1] // 2]
  66. x2 = x[..., x.shape[-1] // 2 :]
  67. return torch.cat((-x2, x1), dim=-1)
  68. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  69. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  70. """Applies Rotary Position Embedding to the query and key tensors.
  71. Args:
  72. q (`torch.Tensor`): The query tensor.
  73. k (`torch.Tensor`): The key tensor.
  74. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  75. sin (`torch.Tensor`): The sine part of the rotary embedding.
  76. position_ids (`torch.Tensor`, *optional*):
  77. Deprecated and unused.
  78. unsqueeze_dim (`int`, *optional*, defaults to 1):
  79. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  80. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  81. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  82. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  83. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  84. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  85. Returns:
  86. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  87. """
  88. cos = cos.unsqueeze(unsqueeze_dim)
  89. sin = sin.unsqueeze(unsqueeze_dim)
  90. q_embed = (q * cos) + (rotate_half(q) * sin)
  91. k_embed = (k * cos) + (rotate_half(k) * sin)
  92. return q_embed, k_embed
  93. # Copied from transformers.models.llama.modeling_llama.repeat_kv
  94. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  95. """
  96. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  97. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  98. """
  99. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  100. if n_rep == 1:
  101. return hidden_states
  102. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  103. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  104. def load_balancing_loss_func(
  105. gate_probabilities: torch.Tensor,
  106. num_experts: int,
  107. top_k: int,
  108. attention_mask: Optional[torch.Tensor],
  109. ) -> torch.Tensor:
  110. r"""Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
  111. See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
  112. function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
  113. experts is too unbalanced.
  114. Args:
  115. gate_logits (Union[`torch.Tensor`, tuple[torch.Tensor]):
  116. Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
  117. shape [batch_size X sequence_length, num_experts].
  118. num_experts (`int`):
  119. Number of experts.
  120. top_k (`int`):
  121. The number of experts each token is routed to.
  122. attention_mask (`torch.Tensor`, *optional*):
  123. The attention_mask used in forward function
  124. shape [batch_size X sequence_length] if not None.
  125. Returns:
  126. The auxiliary loss.
  127. """
  128. if gate_probabilities is None or not isinstance(gate_probabilities, tuple):
  129. return torch.tensor(0.0)
  130. if isinstance(gate_probabilities, tuple):
  131. compute_device = gate_probabilities[0].device
  132. routing_weights = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_probabilities], dim=0)
  133. _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
  134. expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
  135. if attention_mask is None:
  136. # Compute the percentage of tokens routed to each experts
  137. tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
  138. # Compute the average probability of routing to these experts
  139. router_prob_per_expert = torch.mean(routing_weights, dim=0)
  140. else:
  141. batch_size, sequence_length = attention_mask.shape
  142. num_hidden_layers = routing_weights.shape[0] // (batch_size * sequence_length)
  143. # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
  144. expert_attention_mask = (
  145. attention_mask[None, :, :, None, None]
  146. .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
  147. .reshape(-1, top_k, num_experts)
  148. .to(compute_device)
  149. )
  150. # Compute the percentage of tokens routed to each experts
  151. tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
  152. expert_attention_mask, dim=0
  153. )
  154. # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
  155. router_per_expert_attention_mask = (
  156. attention_mask[None, :, :, None]
  157. .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
  158. .reshape(-1, num_experts)
  159. .to(compute_device)
  160. )
  161. # Compute the average probability of routing to these experts
  162. router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
  163. router_per_expert_attention_mask, dim=0
  164. )
  165. overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
  166. return overall_loss * num_experts
  167. class DbrxAttention(nn.Module):
  168. """Multi-head self attention."""
  169. def __init__(self, config: DbrxConfig, block_idx: Optional[int] = None):
  170. super().__init__()
  171. self.config = config
  172. self.hidden_size = config.d_model
  173. self.num_heads = config.n_heads
  174. self.head_dim = self.hidden_size // self.num_heads
  175. self.max_position_embeddings = config.max_seq_len
  176. self.block_idx = block_idx
  177. if block_idx is None:
  178. logger.warning_once(
  179. f"Instantiating {self.__class__.__name__} without passing a `block_idx` is not recommended and will "
  180. + "lead to errors during the forward call if caching is used. Please make sure to provide a `block_idx` "
  181. + "when creating this class."
  182. )
  183. attn_config = config.attn_config
  184. self.attn_pdrop = attn_config.attn_pdrop
  185. self.clip_qkv = attn_config.clip_qkv
  186. self.num_key_value_heads = attn_config.kv_n_heads
  187. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  188. self.rope_theta = attn_config.rope_theta
  189. self.is_causal = True
  190. self.Wqkv = nn.Linear(
  191. self.hidden_size, self.hidden_size + 2 * self.num_key_value_heads * self.head_dim, bias=False
  192. )
  193. self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
  194. self.rotary_emb = DbrxRotaryEmbedding(
  195. self.head_dim,
  196. max_position_embeddings=self.max_position_embeddings,
  197. base=self.rope_theta,
  198. )
  199. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  200. def forward(
  201. self,
  202. hidden_states: torch.Tensor,
  203. position_ids: torch.LongTensor,
  204. attention_mask: Optional[torch.Tensor] = None,
  205. past_key_values: Optional[Cache] = None,
  206. output_attentions: bool = False,
  207. use_cache: bool = False,
  208. cache_position: Optional[torch.LongTensor] = None,
  209. **kwargs: Any,
  210. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
  211. bsz, q_len, _ = hidden_states.size()
  212. qkv_states = self.Wqkv(hidden_states)
  213. min_val = -self.clip_qkv if self.clip_qkv is not None else None
  214. max_val = self.clip_qkv
  215. qkv_states = qkv_states.clamp(min=min_val, max=max_val)
  216. query_states, key_states, value_states = qkv_states.split(
  217. [
  218. self.hidden_size,
  219. self.num_key_value_heads * self.head_dim,
  220. self.num_key_value_heads * self.head_dim,
  221. ],
  222. dim=2,
  223. )
  224. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  225. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  226. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  227. cos, sin = self.rotary_emb(value_states, position_ids)
  228. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  229. if past_key_values is not None:
  230. # sin and cos are specific to RoPE models; position_ids needed for the static cache
  231. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  232. key_states, value_states = past_key_values.update(key_states, value_states, self.block_idx, cache_kwargs)
  233. key_states = repeat_kv(key_states, self.num_key_value_groups)
  234. value_states = repeat_kv(value_states, self.num_key_value_groups)
  235. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
  236. if attention_mask is not None: # no matter the length, we just slice it
  237. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  238. attn_weights = attn_weights + causal_mask
  239. # upcast attention to fp32
  240. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
  241. attn_weights = nn.functional.dropout(attn_weights, p=self.attn_pdrop, training=self.training)
  242. attn_output = torch.matmul(attn_weights, value_states)
  243. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  244. raise ValueError(
  245. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  246. + f" {attn_output.size()}"
  247. )
  248. attn_output = attn_output.transpose(1, 2).contiguous()
  249. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  250. attn_output = self.out_proj(attn_output)
  251. if not output_attentions:
  252. attn_weights = None
  253. return attn_output, attn_weights
  254. class DbrxFlashAttention2(DbrxAttention):
  255. """Dbrx flash attention module.
  256. This module inherits from `DbrxAttention` as the weights of the module stays
  257. untouched. The only required change would be on the forward pass where it
  258. calls the public API of flash attention.
  259. """
  260. def __init__(self, *args, **kwargs):
  261. super().__init__(*args, **kwargs)
  262. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  263. # 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.
  264. # 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).
  265. self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
  266. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  267. def forward(
  268. self,
  269. hidden_states: torch.Tensor,
  270. attention_mask: Optional[torch.LongTensor] = None,
  271. position_ids: Optional[torch.LongTensor] = None,
  272. past_key_values: Optional[Cache] = None,
  273. output_attentions: bool = False,
  274. use_cache: bool = False,
  275. cache_position: Optional[torch.LongTensor] = None,
  276. **kwargs: Any,
  277. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  278. if isinstance(past_key_values, StaticCache):
  279. raise ValueError(
  280. "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
  281. "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
  282. )
  283. logger.info("Implicitly setting `output_attentions` to False as it is not supported in Flash Attention.")
  284. output_attentions = False
  285. bsz, q_len, _ = hidden_states.size()
  286. qkv_states = self.Wqkv(hidden_states)
  287. if self.clip_qkv is not None:
  288. qkv_states = qkv_states.clamp(min=-self.clip_qkv, max=self.clip_qkv)
  289. query_states, key_states, value_states = qkv_states.split(
  290. [
  291. self.hidden_size,
  292. self.num_key_value_heads * self.head_dim,
  293. self.num_key_value_heads * self.head_dim,
  294. ],
  295. dim=2,
  296. )
  297. # Flash attention requires the input to have the shape
  298. # batch_size x seq_length x head_dim x hidden_dim
  299. # therefore we just need to keep the original shape
  300. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  301. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  302. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  303. cos, sin = self.rotary_emb(value_states, position_ids)
  304. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  305. if past_key_values is not None:
  306. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  307. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  308. key_states, value_states = past_key_values.update(key_states, value_states, self.block_idx, cache_kwargs)
  309. # TODO: These transpose are quite inefficient but Flash Attention requires the layout
  310. # [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
  311. # to be able to avoid many of these transpose/reshape/view.
  312. query_states = query_states.transpose(1, 2)
  313. key_states = key_states.transpose(1, 2)
  314. value_states = value_states.transpose(1, 2)
  315. dropout_rate = self.attn_pdrop if self.training else 0.0
  316. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  317. # therefore the input hidden states gets silently casted in float32. Hence, we need
  318. # cast them back in the correct dtype just to be sure everything works as expected.
  319. # This might slowdown training & inference so it is recommended to not cast the LayerNorms
  320. # in fp32. (LlamaRMSNorm handles it correctly)
  321. input_dtype = query_states.dtype
  322. device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
  323. if input_dtype == torch.float32:
  324. if torch.is_autocast_enabled():
  325. target_dtype = (
  326. torch.get_autocast_dtype(device_type)
  327. if hasattr(torch, "get_autocast_dtype")
  328. else torch.get_autocast_gpu_dtype()
  329. )
  330. # Handle the case where the model is quantized
  331. elif hasattr(self.config, "_pre_quantization_dtype"):
  332. target_dtype = self.config._pre_quantization_dtype
  333. else:
  334. target_dtype = query_states.dtype
  335. logger.warning_once(
  336. "The input hidden states seems to be silently casted in float32, this might be "
  337. + "related to the fact you have upcasted embedding or layer norm layers in "
  338. + f"float32. We will cast back the input in {target_dtype}."
  339. )
  340. query_states = query_states.to(target_dtype)
  341. key_states = key_states.to(target_dtype)
  342. value_states = value_states.to(target_dtype)
  343. attn_output = _flash_attention_forward(
  344. query_states,
  345. key_states,
  346. value_states,
  347. attention_mask,
  348. q_len,
  349. position_ids=position_ids,
  350. dropout=dropout_rate,
  351. is_causal=self.is_causal,
  352. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  353. )
  354. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
  355. attn_output = self.out_proj(attn_output)
  356. if not output_attentions:
  357. attn_weights = None
  358. return attn_output, attn_weights
  359. class DbrxSdpaAttention(DbrxAttention):
  360. """
  361. Dbrx attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
  362. `DbrxAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
  363. SDPA API.
  364. """
  365. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  366. def forward(
  367. self,
  368. hidden_states: torch.Tensor,
  369. attention_mask: Optional[torch.Tensor] = None,
  370. position_ids: Optional[torch.LongTensor] = None,
  371. past_key_values: Optional[Cache] = None,
  372. output_attentions: bool = False,
  373. use_cache: bool = False,
  374. cache_position: Optional[torch.LongTensor] = None,
  375. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  376. if output_attentions:
  377. # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
  378. logger.warning_once(
  379. "DbrxModel is using DbrxSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
  380. '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.'
  381. )
  382. return super().forward(
  383. hidden_states=hidden_states,
  384. attention_mask=attention_mask,
  385. position_ids=position_ids,
  386. past_key_values=past_key_values,
  387. output_attentions=output_attentions,
  388. use_cache=use_cache,
  389. cache_position=cache_position,
  390. )
  391. bsz, q_len, _ = hidden_states.size()
  392. qkv_states = self.Wqkv(hidden_states)
  393. if self.clip_qkv is not None:
  394. qkv_states = qkv_states.clamp(min=-self.clip_qkv, max=self.clip_qkv)
  395. query_states, key_states, value_states = qkv_states.split(
  396. [
  397. self.hidden_size,
  398. self.num_key_value_heads * self.head_dim,
  399. self.num_key_value_heads * self.head_dim,
  400. ],
  401. dim=2,
  402. )
  403. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  404. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  405. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  406. cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
  407. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
  408. if past_key_values is not None:
  409. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  410. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  411. key_states, value_states = past_key_values.update(key_states, value_states, self.block_idx, cache_kwargs)
  412. key_states = repeat_kv(key_states, self.num_key_value_groups)
  413. value_states = repeat_kv(value_states, self.num_key_value_groups)
  414. causal_mask = attention_mask
  415. if attention_mask is not None:
  416. causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
  417. # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
  418. # Reference: https://github.com/pytorch/pytorch/issues/112577.
  419. if query_states.device.type == "cuda" and causal_mask is not None:
  420. query_states = query_states.contiguous()
  421. key_states = key_states.contiguous()
  422. value_states = value_states.contiguous()
  423. # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
  424. # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
  425. is_causal = causal_mask is None and q_len > 1
  426. attn_output = torch.nn.functional.scaled_dot_product_attention(
  427. query_states,
  428. key_states,
  429. value_states,
  430. attn_mask=causal_mask,
  431. dropout_p=self.attn_pdrop if self.training else 0.0,
  432. is_causal=is_causal,
  433. )
  434. attn_output = attn_output.transpose(1, 2).contiguous()
  435. attn_output = attn_output.view(bsz, q_len, -1)
  436. attn_output = self.out_proj(attn_output)
  437. return attn_output, None
  438. DBRX_ATTENTION_CLASSES = {
  439. "eager": DbrxAttention,
  440. "flash_attention_2": DbrxFlashAttention2,
  441. "sdpa": DbrxSdpaAttention,
  442. }
  443. class DbrxNormAttentionNorm(nn.Module):
  444. def __init__(self, config: DbrxConfig, block_idx: Optional[int] = None):
  445. super().__init__()
  446. self.block_idx = block_idx
  447. self.resid_pdrop = config.resid_pdrop
  448. self.norm_1 = nn.LayerNorm(config.d_model, bias=False)
  449. self.attn = DBRX_ATTENTION_CLASSES[config._attn_implementation](
  450. config=config,
  451. block_idx=block_idx,
  452. )
  453. self.norm_2 = nn.LayerNorm(config.d_model, bias=False)
  454. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  455. def forward(
  456. self,
  457. hidden_states: torch.Tensor,
  458. position_ids: torch.LongTensor,
  459. attention_mask: Optional[torch.Tensor] = None,
  460. past_key_values: Optional[Cache] = None,
  461. output_attentions: bool = False,
  462. use_cache: bool = False,
  463. cache_position: Optional[torch.LongTensor] = None,
  464. **kwargs: Any,
  465. ) -> tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
  466. residual_states = hidden_states
  467. hidden_states = self.norm_1(hidden_states).to(hidden_states.dtype)
  468. hidden_states, attn_weights = self.attn(
  469. hidden_states=hidden_states,
  470. attention_mask=attention_mask,
  471. position_ids=position_ids,
  472. past_key_values=past_key_values,
  473. output_attentions=output_attentions,
  474. use_cache=use_cache,
  475. cache_position=cache_position,
  476. **kwargs,
  477. )
  478. hidden_states = nn.functional.dropout(hidden_states, p=self.resid_pdrop, training=self.training)
  479. hidden_states = hidden_states + residual_states
  480. residual_states = hidden_states
  481. hidden_states = self.norm_2(hidden_states).to(hidden_states.dtype)
  482. return residual_states, hidden_states, attn_weights
  483. class DbrxRouter(nn.Module):
  484. def __init__(
  485. self,
  486. hidden_size: int,
  487. moe_num_experts: int,
  488. moe_top_k: int,
  489. moe_jitter_eps: Optional[float],
  490. moe_normalize_expert_weights: Optional[float],
  491. ):
  492. super().__init__()
  493. self.hidden_size = hidden_size
  494. self.moe_num_experts = moe_num_experts
  495. self.moe_top_k = moe_top_k
  496. self.moe_jitter_eps = moe_jitter_eps
  497. self.moe_normalize_expert_weights = moe_normalize_expert_weights
  498. self.layer = nn.Linear(self.hidden_size, self.moe_num_experts, bias=False)
  499. def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.LongTensor]:
  500. if self.training and self.moe_jitter_eps is not None:
  501. hidden_states *= torch.empty_like(hidden_states).uniform_(
  502. 1.0 - self.moe_jitter_eps, 1.0 + self.moe_jitter_eps
  503. )
  504. hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
  505. weights = self.layer(hidden_states).softmax(dim=-1, dtype=torch.float32)
  506. top_weights, top_experts = torch.topk(weights, self.moe_top_k, dim=-1)
  507. top_weights_scale = (
  508. torch.norm(top_weights, p=self.moe_normalize_expert_weights, dim=-1, keepdim=True)
  509. if self.moe_normalize_expert_weights is not None
  510. else 1.0
  511. )
  512. top_weights = top_weights / top_weights_scale
  513. weights = weights.to(hidden_states.dtype)
  514. top_weights = top_weights.to(hidden_states.dtype)
  515. return weights, top_weights, top_experts
  516. class DbrxExpertGLU(nn.Module):
  517. def __init__(self, hidden_size: int, ffn_hidden_size: int, moe_num_experts: int, ffn_act_fn: dict):
  518. super().__init__()
  519. self.hidden_size = hidden_size
  520. self.ffn_hidden_size = ffn_hidden_size
  521. self.moe_num_experts = moe_num_experts
  522. self.w1 = nn.Parameter(torch.empty(moe_num_experts * ffn_hidden_size, hidden_size))
  523. self.v1 = nn.Parameter(torch.empty(moe_num_experts * ffn_hidden_size, hidden_size))
  524. self.w2 = nn.Parameter(torch.empty(moe_num_experts * ffn_hidden_size, hidden_size))
  525. act_fn_name = ffn_act_fn.get("name", "silu")
  526. self.activation_fn = ACT2FN[act_fn_name]
  527. def forward(
  528. self, x: torch.Tensor, expert_w1: torch.Tensor, expert_v1: torch.Tensor, expert_w2: torch.Tensor
  529. ) -> torch.Tensor:
  530. gate_proj = x.matmul(expert_w1.t())
  531. up_proj = x.matmul(expert_v1.t())
  532. gate_proj = self.activation_fn(gate_proj)
  533. intermediate_states = gate_proj * up_proj
  534. down_proj = intermediate_states.matmul(expert_w2)
  535. return down_proj
  536. class DbrxExperts(nn.Module):
  537. def __init__(self, hidden_size: int, ffn_hidden_size: int, moe_num_experts: int, ffn_act_fn: dict):
  538. super().__init__()
  539. self.moe_num_experts = moe_num_experts
  540. self.mlp = DbrxExpertGLU(
  541. hidden_size=hidden_size,
  542. ffn_hidden_size=ffn_hidden_size,
  543. moe_num_experts=moe_num_experts,
  544. ffn_act_fn=ffn_act_fn,
  545. )
  546. def forward(
  547. self, x: torch.Tensor, weights: torch.Tensor, top_weights: torch.Tensor, top_experts: torch.LongTensor
  548. ) -> torch.Tensor:
  549. bsz, q_len, hidden_size = x.shape
  550. x = x.view(-1, hidden_size)
  551. out = torch.zeros_like(x)
  552. expert_mask = nn.functional.one_hot(top_experts, num_classes=self.moe_num_experts).permute(2, 1, 0)
  553. # Chunk experts at once to avoid storing full parameter multiple times in autograd
  554. w1_chunked = self.mlp.w1.view(self.mlp.moe_num_experts, self.mlp.ffn_hidden_size, self.mlp.hidden_size).chunk(
  555. self.moe_num_experts, dim=0
  556. )
  557. v1_chunked = self.mlp.v1.view(self.mlp.moe_num_experts, self.mlp.ffn_hidden_size, self.mlp.hidden_size).chunk(
  558. self.moe_num_experts, dim=0
  559. )
  560. w2_chunked = self.mlp.w2.view(self.mlp.moe_num_experts, self.mlp.ffn_hidden_size, self.mlp.hidden_size).chunk(
  561. self.moe_num_experts, dim=0
  562. )
  563. w1_chunked = [w1.squeeze(dim=0) for w1 in w1_chunked]
  564. v1_chunked = [v1.squeeze(dim=0) for v1 in v1_chunked]
  565. w2_chunked = [w2.squeeze(dim=0) for w2 in w2_chunked]
  566. for expert_idx in range(0, self.moe_num_experts):
  567. # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: dynamic shape operator: aten.nonzero.default`)
  568. # (set torch._dynamo.config.capture_dynamic_output_shape_ops = True may help but not tested)
  569. topk_idx, token_idx = torch.where(expert_mask[expert_idx])
  570. if token_idx.shape[0] == 0:
  571. continue
  572. token_list = token_idx
  573. topk_list = topk_idx
  574. expert_tokens = x[None, token_list].reshape(-1, hidden_size)
  575. expert_out = (
  576. self.mlp(expert_tokens, w1_chunked[expert_idx], v1_chunked[expert_idx], w2_chunked[expert_idx])
  577. * top_weights[token_list, topk_list, None]
  578. )
  579. out.index_add_(0, token_idx, expert_out)
  580. out = out.reshape(bsz, q_len, hidden_size)
  581. return out
  582. class DbrxFFN(nn.Module):
  583. def __init__(self, config: DbrxConfig):
  584. super().__init__()
  585. ffn_config = config.ffn_config
  586. self.router = DbrxRouter(
  587. hidden_size=config.d_model,
  588. moe_num_experts=ffn_config.moe_num_experts,
  589. moe_top_k=ffn_config.moe_top_k,
  590. moe_jitter_eps=ffn_config.moe_jitter_eps,
  591. moe_normalize_expert_weights=ffn_config.moe_normalize_expert_weights,
  592. )
  593. self.experts = DbrxExperts(
  594. hidden_size=config.d_model,
  595. ffn_hidden_size=ffn_config.ffn_hidden_size,
  596. moe_num_experts=ffn_config.moe_num_experts,
  597. ffn_act_fn=ffn_config.ffn_act_fn,
  598. )
  599. def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
  600. weights, top_weights, top_experts = self.router(x)
  601. out = self.experts(x, weights, top_weights, top_experts)
  602. return out, weights
  603. class DbrxBlock(GradientCheckpointingLayer):
  604. def __init__(self, config: DbrxConfig, block_idx: int):
  605. super().__init__()
  606. self.hidden_size = config.d_model
  607. self.resid_pdrop = config.resid_pdrop
  608. self.block_idx = block_idx
  609. self.norm_attn_norm = DbrxNormAttentionNorm(
  610. config=config,
  611. block_idx=block_idx,
  612. )
  613. self.ffn = DbrxFFN(config=config)
  614. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  615. def forward(
  616. self,
  617. hidden_states: torch.Tensor,
  618. attention_mask: Optional[torch.Tensor] = None,
  619. position_ids: Optional[torch.LongTensor] = None,
  620. past_key_values: Optional[Cache] = None,
  621. output_attentions: Optional[bool] = False,
  622. output_router_logits: Optional[bool] = False,
  623. use_cache: Optional[bool] = False,
  624. cache_position: Optional[torch.LongTensor] = None,
  625. **kwargs: Any,
  626. ) -> Union[
  627. tuple[torch.Tensor],
  628. tuple[torch.Tensor, Optional[torch.Tensor]],
  629. tuple[torch.Tensor, Optional[Cache]],
  630. tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]],
  631. tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]],
  632. tuple[torch.Tensor, Optional[Cache], Optional[torch.Tensor]],
  633. tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache], Optional[torch.Tensor]],
  634. ]:
  635. """Forward function for DbrxBlock.
  636. Args:
  637. hidden_states (`torch.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  638. position_ids (`torch.LongTensor`): position ids of shape `(batch, seq_len)`
  639. attention_mask (`torch.Tensor`, *optional*): attention mask of size (batch_size, sequence_length)
  640. if flash attention is used or (batch_size, 1, query_sequence_length, key_sequence_length)
  641. if default attention is used.
  642. past_key_values (`Cache`, *optional*): cached past key and value projection states
  643. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all
  644. attention layers. See `attentions` under returned tensors for more detail.
  645. output_router_logits (`bool`, *optional*): Whether or not to return the router logits.
  646. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are
  647. returned and can be used to speed up decoding (see `past_key_values`).
  648. cache_position (`torch.LongTensor`, *optional*): position ids of the cache
  649. """
  650. # Norm + Attention + Norm
  651. resid_states, hidden_states, self_attn_weights = self.norm_attn_norm(
  652. hidden_states=hidden_states,
  653. attention_mask=attention_mask,
  654. position_ids=position_ids,
  655. past_key_values=past_key_values,
  656. output_attentions=output_attentions,
  657. use_cache=use_cache,
  658. cache_position=cache_position,
  659. **kwargs,
  660. )
  661. # Fully Connected
  662. hidden_states, router_logits = self.ffn(hidden_states)
  663. hidden_states = nn.functional.dropout(hidden_states, p=self.resid_pdrop, training=self.training)
  664. hidden_states = resid_states + hidden_states
  665. outputs = (hidden_states,)
  666. if output_attentions:
  667. outputs += (self_attn_weights,)
  668. if output_router_logits:
  669. outputs += (router_logits,)
  670. return outputs
  671. @auto_docstring
  672. class DbrxPreTrainedModel(PreTrainedModel):
  673. config: DbrxConfig
  674. base_model_prefix = "transformer"
  675. supports_gradient_checkpointing = True
  676. _no_split_modules = ["DbrxBlock"]
  677. _skip_keys_device_placement = ["past_key_values"]
  678. _supports_flash_attn = True
  679. _supports_sdpa = True
  680. _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
  681. def _init_weights(self, module: nn.Module):
  682. std = self.config.initializer_range
  683. if isinstance(module, nn.Linear):
  684. module.weight.data.normal_(mean=0.0, std=std)
  685. if module.bias is not None:
  686. module.bias.data.zero_()
  687. elif isinstance(module, nn.Embedding):
  688. module.weight.data.normal_(mean=0.0, std=std)
  689. if module.padding_idx is not None:
  690. module.weight.data[module.padding_idx].zero_()
  691. elif isinstance(module, nn.LayerNorm):
  692. module.weight.data.fill_(1.0)
  693. if module.bias is not None:
  694. module.bias.data.zero_()
  695. elif isinstance(module, DbrxExpertGLU):
  696. module.w1.data.normal_(mean=0.0, std=std)
  697. module.v1.data.normal_(mean=0.0, std=std)
  698. module.w2.data.normal_(mean=0.0, std=std)
  699. @auto_docstring
  700. class DbrxModel(DbrxPreTrainedModel):
  701. """Transformer decoder consisting of *config.num_hidden_layers*. Each layer is a [`DbrxBlock`] layer.
  702. Args:
  703. config ([`DbrxConfig`]): Model configuration class with all parameters of the model.
  704. Initializing with a config file does not load the weights associated with the model, only the
  705. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  706. """
  707. def __init__(self, config: DbrxConfig):
  708. super().__init__(config)
  709. self.padding_idx = config.pad_token_id
  710. self.vocab_size = config.vocab_size
  711. self.emb_pdrop = config.emb_pdrop
  712. self.wte = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
  713. self.blocks = nn.ModuleList([DbrxBlock(config, block_idx) for block_idx in range(config.n_layers)])
  714. self.norm_f = nn.LayerNorm(config.d_model, bias=False)
  715. self.gradient_checkpointing = False
  716. # Initialize weights and apply final processing
  717. self.post_init()
  718. def get_input_embeddings(self) -> nn.Embedding:
  719. return self.wte
  720. def set_input_embeddings(self, value: nn.Embedding):
  721. self.wte = value
  722. @auto_docstring
  723. def forward(
  724. self,
  725. input_ids: Optional[torch.LongTensor] = None,
  726. attention_mask: Optional[torch.Tensor] = None,
  727. position_ids: Optional[torch.LongTensor] = None,
  728. past_key_values: Optional[Cache] = None,
  729. inputs_embeds: Optional[torch.Tensor] = None,
  730. use_cache: Optional[bool] = None,
  731. output_attentions: Optional[bool] = None,
  732. output_hidden_states: Optional[bool] = None,
  733. output_router_logits: Optional[bool] = None,
  734. return_dict: Optional[bool] = None,
  735. cache_position: Optional[torch.LongTensor] = None,
  736. **kwargs, # NOOP kwargs, for now
  737. ) -> Union[tuple, MoeModelOutputWithPast]:
  738. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  739. output_hidden_states = (
  740. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  741. )
  742. output_router_logits = (
  743. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  744. )
  745. use_cache = use_cache if use_cache is not None else self.config.use_cache
  746. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  747. if (input_ids is None) ^ (inputs_embeds is not None):
  748. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  749. if self.gradient_checkpointing and self.training and use_cache:
  750. logger.warning_once(
  751. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  752. )
  753. use_cache = False
  754. if inputs_embeds is None:
  755. inputs_embeds = self.wte(input_ids)
  756. inputs_embeds = nn.functional.dropout(inputs_embeds, p=self.emb_pdrop, training=self.training)
  757. if use_cache and past_key_values is None:
  758. past_key_values = DynamicCache(config=self.config)
  759. if cache_position is None:
  760. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  761. cache_position = torch.arange(
  762. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  763. )
  764. if position_ids is None:
  765. position_ids = cache_position.unsqueeze(0)
  766. causal_mask = self._update_causal_mask(
  767. attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
  768. )
  769. # embed positions
  770. hidden_states = inputs_embeds
  771. # decoder layers
  772. all_hidden_states = () if output_hidden_states else None
  773. all_self_attns = () if output_attentions else None
  774. all_router_logits = () if output_router_logits else None
  775. for block in self.blocks:
  776. if output_hidden_states:
  777. all_hidden_states += (hidden_states,)
  778. block_outputs = block(
  779. hidden_states,
  780. attention_mask=causal_mask,
  781. position_ids=position_ids,
  782. past_key_values=past_key_values,
  783. output_attentions=output_attentions,
  784. output_router_logits=output_router_logits,
  785. use_cache=use_cache,
  786. cache_position=cache_position,
  787. )
  788. hidden_states = block_outputs[0]
  789. if output_attentions:
  790. all_self_attns += (block_outputs[1],)
  791. if output_router_logits:
  792. all_router_logits += (block_outputs[-1],)
  793. hidden_states = self.norm_f(hidden_states)
  794. # add hidden states from the last decoder layer
  795. if output_hidden_states:
  796. all_hidden_states += (hidden_states,)
  797. if not return_dict:
  798. return tuple(
  799. v
  800. for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_router_logits]
  801. if v is not None
  802. )
  803. return MoeModelOutputWithPast(
  804. last_hidden_state=hidden_states,
  805. past_key_values=past_key_values,
  806. hidden_states=all_hidden_states,
  807. attentions=all_self_attns,
  808. router_logits=all_router_logits,
  809. )
  810. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._update_causal_mask
  811. def _update_causal_mask(
  812. self,
  813. attention_mask: Union[torch.Tensor, "BlockMask"],
  814. input_tensor: torch.Tensor,
  815. cache_position: torch.Tensor,
  816. past_key_values: Cache,
  817. output_attentions: bool = False,
  818. ):
  819. if self.config._attn_implementation == "flash_attention_2":
  820. if attention_mask is not None and (attention_mask == 0.0).any():
  821. return attention_mask
  822. return None
  823. if self.config._attn_implementation == "flex_attention":
  824. if isinstance(attention_mask, torch.Tensor):
  825. attention_mask = make_flex_block_causal_mask(attention_mask)
  826. return attention_mask
  827. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  828. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  829. # to infer the attention mask.
  830. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  831. using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
  832. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  833. if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
  834. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  835. attention_mask,
  836. inputs_embeds=input_tensor,
  837. past_key_values_length=past_seen_tokens,
  838. is_training=self.training,
  839. ):
  840. return None
  841. dtype = input_tensor.dtype
  842. sequence_length = input_tensor.shape[1]
  843. if using_compilable_cache:
  844. target_length = past_key_values.get_max_cache_shape()
  845. else:
  846. target_length = (
  847. attention_mask.shape[-1]
  848. if isinstance(attention_mask, torch.Tensor)
  849. else past_seen_tokens + sequence_length + 1
  850. )
  851. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  852. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  853. attention_mask,
  854. sequence_length=sequence_length,
  855. target_length=target_length,
  856. dtype=dtype,
  857. cache_position=cache_position,
  858. batch_size=input_tensor.shape[0],
  859. )
  860. if (
  861. self.config._attn_implementation == "sdpa"
  862. and attention_mask is not None
  863. and attention_mask.device.type in ["cuda", "xpu", "npu"]
  864. and not output_attentions
  865. ):
  866. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  867. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  868. # Details: https://github.com/pytorch/pytorch/issues/110213
  869. min_dtype = torch.finfo(dtype).min
  870. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  871. return causal_mask
  872. @staticmethod
  873. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
  874. def _prepare_4d_causal_attention_mask_with_cache_position(
  875. attention_mask: torch.Tensor,
  876. sequence_length: int,
  877. target_length: int,
  878. dtype: torch.dtype,
  879. cache_position: torch.Tensor,
  880. batch_size: int,
  881. **kwargs,
  882. ):
  883. """
  884. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  885. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  886. Args:
  887. attention_mask (`torch.Tensor`):
  888. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  889. `(batch_size, 1, query_length, key_value_length)`.
  890. sequence_length (`int`):
  891. The sequence length being processed.
  892. target_length (`int`):
  893. The target length: when generating with static cache, the mask should be as long as the static cache,
  894. to account for the 0 padding, the part of the cache that is not filled yet.
  895. dtype (`torch.dtype`):
  896. The dtype to use for the 4D attention mask.
  897. cache_position (`torch.Tensor`):
  898. Indices depicting the position of the input sequence tokens in the sequence.
  899. batch_size (`torch.Tensor`):
  900. Batch size.
  901. """
  902. if attention_mask is not None and attention_mask.dim() == 4:
  903. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  904. causal_mask = attention_mask
  905. else:
  906. min_dtype = torch.finfo(dtype).min
  907. causal_mask = torch.full(
  908. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
  909. )
  910. if sequence_length != 1:
  911. causal_mask = torch.triu(causal_mask, diagonal=1)
  912. causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
  913. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  914. if attention_mask is not None:
  915. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  916. mask_length = attention_mask.shape[-1]
  917. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
  918. causal_mask.device
  919. )
  920. padding_mask = padding_mask == 0
  921. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  922. padding_mask, min_dtype
  923. )
  924. return causal_mask
  925. @auto_docstring(
  926. custom_intro="""
  927. The DBRX Model transformer for causal language modeling.
  928. """
  929. )
  930. class DbrxForCausalLM(DbrxPreTrainedModel, GenerationMixin):
  931. def __init__(self, config: DbrxConfig):
  932. super().__init__(config)
  933. self.transformer = DbrxModel(config)
  934. self.vocab_size = config.vocab_size
  935. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  936. self.moe_loss_weight = config.ffn_config.moe_loss_weight
  937. self.num_experts = config.ffn_config.moe_num_experts
  938. self.num_experts_per_tok = config.ffn_config.moe_top_k
  939. # Initialize weights and apply final processing
  940. self.post_init()
  941. def get_input_embeddings(self) -> nn.Embedding:
  942. return self.transformer.get_input_embeddings()
  943. def set_input_embeddings(self, value: nn.Embedding):
  944. self.transformer.set_input_embeddings(value)
  945. def get_output_embeddings(self) -> nn.Linear:
  946. return self.lm_head
  947. def set_output_embeddings(self, new_embeddings: nn.Linear):
  948. self.lm_head = new_embeddings
  949. def set_decoder(self, decoder: DbrxModel):
  950. self.transformer = decoder
  951. def get_decoder(self) -> DbrxModel:
  952. return self.transformer
  953. @auto_docstring
  954. def forward(
  955. self,
  956. input_ids: Optional[torch.LongTensor] = None,
  957. attention_mask: Optional[torch.Tensor] = None,
  958. position_ids: Optional[torch.LongTensor] = None,
  959. past_key_values: Optional[Cache] = None,
  960. inputs_embeds: Optional[torch.Tensor] = None,
  961. labels: Optional[torch.LongTensor] = None,
  962. use_cache: Optional[bool] = None,
  963. output_attentions: Optional[bool] = None,
  964. output_hidden_states: Optional[bool] = None,
  965. output_router_logits: Optional[bool] = None,
  966. return_dict: Optional[bool] = None,
  967. cache_position: Optional[torch.LongTensor] = None,
  968. logits_to_keep: Union[int, torch.Tensor] = 0,
  969. **kwargs,
  970. ) -> Union[tuple, MoeCausalLMOutputWithPast]:
  971. r"""
  972. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  973. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  974. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  975. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  976. Example:
  977. ```python
  978. >> from transformers import AutoTokenizer, DbrxForCausalLM
  979. >> model = DbrxForCausalLM.from_pretrained("databricks/dbrx-instruct")
  980. >> tokenizer = AutoTokenizer.from_pretrained("databricks/dbrx-instruct")
  981. >> prompt = "Hey, are you conscious? Can you talk to me?"
  982. >> inputs = tokenizer(prompt, return_tensors="pt")
  983. >> # Generate
  984. >> generate_ids = model.generate(inputs.input_ids, max_length=30)
  985. >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  986. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  987. ```
  988. """
  989. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  990. output_hidden_states = (
  991. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  992. )
  993. output_router_logits = (
  994. output_router_logits if output_router_logits is not None else self.config.output_router_logits
  995. )
  996. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  997. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  998. outputs = self.transformer(
  999. input_ids=input_ids,
  1000. attention_mask=attention_mask,
  1001. position_ids=position_ids,
  1002. past_key_values=past_key_values,
  1003. inputs_embeds=inputs_embeds,
  1004. use_cache=use_cache,
  1005. output_attentions=output_attentions,
  1006. output_hidden_states=output_hidden_states,
  1007. output_router_logits=output_router_logits,
  1008. return_dict=return_dict,
  1009. cache_position=cache_position,
  1010. )
  1011. hidden_states = outputs[0]
  1012. # No upscaling to float was ever done for Dbrx
  1013. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1014. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1015. loss = None
  1016. if labels is not None:
  1017. loss = self.loss_function(
  1018. logits,
  1019. labels,
  1020. vocab_size=self.config.vocab_size,
  1021. **kwargs,
  1022. )
  1023. aux_loss = None
  1024. if output_router_logits:
  1025. aux_loss = load_balancing_loss_func(
  1026. outputs.router_logits if return_dict else outputs[-1],
  1027. self.num_experts,
  1028. self.num_experts_per_tok,
  1029. attention_mask,
  1030. )
  1031. if labels is not None and loss is not None:
  1032. loss += self.moe_loss_weight * aux_loss.to(loss.device) # make sure to reside in the same device
  1033. if not return_dict:
  1034. output = (logits,) + outputs[1:]
  1035. if output_router_logits:
  1036. output = (aux_loss,) + output
  1037. return (loss,) + output if loss is not None else output
  1038. return MoeCausalLMOutputWithPast(
  1039. loss=loss,
  1040. aux_loss=aux_loss,
  1041. logits=logits,
  1042. past_key_values=outputs.past_key_values,
  1043. hidden_states=outputs.hidden_states,
  1044. attentions=outputs.attentions,
  1045. router_logits=outputs.router_logits,
  1046. )
  1047. __all__ = ["DbrxForCausalLM", "DbrxModel", "DbrxPreTrainedModel"]