modeling_qwen2.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/qwen2/modular_qwen2.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_qwen2.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. from typing import Callable, Optional, Union
  8. import torch
  9. from torch import nn
  10. from ...activations import ACT2FN
  11. from ...cache_utils import Cache, DynamicCache
  12. from ...generation import GenerationMixin
  13. from ...integrations import use_kernel_forward_from_hub
  14. from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
  15. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  16. from ...modeling_layers import (
  17. GenericForQuestionAnswering,
  18. GenericForSequenceClassification,
  19. GenericForTokenClassification,
  20. GradientCheckpointingLayer,
  21. )
  22. from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
  23. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  24. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  25. from ...processing_utils import Unpack
  26. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
  27. from ...utils.deprecation import deprecate_kwarg
  28. from ...utils.generic import check_model_inputs
  29. from .configuration_qwen2 import Qwen2Config
  30. class Qwen2MLP(nn.Module):
  31. def __init__(self, config):
  32. super().__init__()
  33. self.config = config
  34. self.hidden_size = config.hidden_size
  35. self.intermediate_size = config.intermediate_size
  36. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  37. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  38. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
  39. self.act_fn = ACT2FN[config.hidden_act]
  40. def forward(self, x):
  41. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  42. return down_proj
  43. def rotate_half(x):
  44. """Rotates half the hidden dims of the input."""
  45. x1 = x[..., : x.shape[-1] // 2]
  46. x2 = x[..., x.shape[-1] // 2 :]
  47. return torch.cat((-x2, x1), dim=-1)
  48. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  49. """Applies Rotary Position Embedding to the query and key tensors.
  50. Args:
  51. q (`torch.Tensor`): The query tensor.
  52. k (`torch.Tensor`): The key tensor.
  53. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  54. sin (`torch.Tensor`): The sine part of the rotary embedding.
  55. position_ids (`torch.Tensor`, *optional*):
  56. Deprecated and unused.
  57. unsqueeze_dim (`int`, *optional*, defaults to 1):
  58. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  59. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  60. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  61. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  62. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  63. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  64. Returns:
  65. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  66. """
  67. cos = cos.unsqueeze(unsqueeze_dim)
  68. sin = sin.unsqueeze(unsqueeze_dim)
  69. q_embed = (q * cos) + (rotate_half(q) * sin)
  70. k_embed = (k * cos) + (rotate_half(k) * sin)
  71. return q_embed, k_embed
  72. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  73. """
  74. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  75. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  76. """
  77. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  78. if n_rep == 1:
  79. return hidden_states
  80. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  81. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  82. def eager_attention_forward(
  83. module: nn.Module,
  84. query: torch.Tensor,
  85. key: torch.Tensor,
  86. value: torch.Tensor,
  87. attention_mask: Optional[torch.Tensor],
  88. scaling: float,
  89. dropout: float = 0.0,
  90. **kwargs: Unpack[TransformersKwargs],
  91. ):
  92. key_states = repeat_kv(key, module.num_key_value_groups)
  93. value_states = repeat_kv(value, module.num_key_value_groups)
  94. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  95. if attention_mask is not None:
  96. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  97. attn_weights = attn_weights + causal_mask
  98. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  99. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  100. attn_output = torch.matmul(attn_weights, value_states)
  101. attn_output = attn_output.transpose(1, 2).contiguous()
  102. return attn_output, attn_weights
  103. class Qwen2Attention(nn.Module):
  104. """Multi-headed attention from 'Attention Is All You Need' paper"""
  105. def __init__(self, config: Qwen2Config, layer_idx: int):
  106. super().__init__()
  107. self.config = config
  108. self.layer_idx = layer_idx
  109. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  110. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  111. self.scaling = self.head_dim**-0.5
  112. self.attention_dropout = config.attention_dropout
  113. self.is_causal = True
  114. self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
  115. self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
  116. self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
  117. self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
  118. self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
  119. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  120. def forward(
  121. self,
  122. hidden_states: torch.Tensor,
  123. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  124. attention_mask: Optional[torch.Tensor],
  125. past_key_values: Optional[Cache] = None,
  126. cache_position: Optional[torch.LongTensor] = None,
  127. **kwargs: Unpack[FlashAttentionKwargs],
  128. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  129. input_shape = hidden_states.shape[:-1]
  130. hidden_shape = (*input_shape, -1, self.head_dim)
  131. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  132. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  133. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  134. cos, sin = position_embeddings
  135. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  136. if past_key_values is not None:
  137. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  138. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  139. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  140. attention_interface: Callable = eager_attention_forward
  141. if self.config._attn_implementation != "eager":
  142. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  143. attn_output, attn_weights = attention_interface(
  144. self,
  145. query_states,
  146. key_states,
  147. value_states,
  148. attention_mask,
  149. dropout=0.0 if not self.training else self.attention_dropout,
  150. scaling=self.scaling,
  151. sliding_window=self.sliding_window, # main diff with Llama
  152. **kwargs,
  153. )
  154. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  155. attn_output = self.o_proj(attn_output)
  156. return attn_output, attn_weights
  157. @use_kernel_forward_from_hub("RMSNorm")
  158. class Qwen2RMSNorm(nn.Module):
  159. def __init__(self, hidden_size, eps: float = 1e-6) -> None:
  160. """
  161. Qwen2RMSNorm is equivalent to T5LayerNorm
  162. """
  163. super().__init__()
  164. self.weight = nn.Parameter(torch.ones(hidden_size))
  165. self.variance_epsilon = eps
  166. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  167. input_dtype = hidden_states.dtype
  168. hidden_states = hidden_states.to(torch.float32)
  169. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  170. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  171. return self.weight * hidden_states.to(input_dtype)
  172. def extra_repr(self):
  173. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  174. class Qwen2DecoderLayer(GradientCheckpointingLayer):
  175. def __init__(self, config: Qwen2Config, layer_idx: int):
  176. super().__init__()
  177. self.hidden_size = config.hidden_size
  178. self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
  179. self.mlp = Qwen2MLP(config)
  180. self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  181. self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  182. self.attention_type = config.layer_types[layer_idx]
  183. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  184. def forward(
  185. self,
  186. hidden_states: torch.Tensor,
  187. attention_mask: Optional[torch.Tensor] = None,
  188. position_ids: Optional[torch.LongTensor] = None,
  189. past_key_values: Optional[Cache] = None,
  190. use_cache: Optional[bool] = False,
  191. cache_position: Optional[torch.LongTensor] = None,
  192. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  193. **kwargs: Unpack[TransformersKwargs],
  194. ) -> torch.Tensor:
  195. residual = hidden_states
  196. hidden_states = self.input_layernorm(hidden_states)
  197. # Self Attention
  198. hidden_states, _ = self.self_attn(
  199. hidden_states=hidden_states,
  200. attention_mask=attention_mask,
  201. position_ids=position_ids,
  202. past_key_values=past_key_values,
  203. use_cache=use_cache,
  204. cache_position=cache_position,
  205. position_embeddings=position_embeddings,
  206. **kwargs,
  207. )
  208. hidden_states = residual + hidden_states
  209. # Fully Connected
  210. residual = hidden_states
  211. hidden_states = self.post_attention_layernorm(hidden_states)
  212. hidden_states = self.mlp(hidden_states)
  213. hidden_states = residual + hidden_states
  214. return hidden_states
  215. @auto_docstring
  216. class Qwen2PreTrainedModel(PreTrainedModel):
  217. config: Qwen2Config
  218. base_model_prefix = "model"
  219. supports_gradient_checkpointing = True
  220. _no_split_modules = ["Qwen2DecoderLayer"]
  221. _skip_keys_device_placement = ["past_key_values"]
  222. _supports_flash_attn = True
  223. _supports_sdpa = True
  224. _supports_flex_attn = True
  225. _can_compile_fullgraph = True
  226. _supports_attention_backend = True
  227. _can_record_outputs = {
  228. "hidden_states": Qwen2DecoderLayer,
  229. "attentions": Qwen2Attention,
  230. }
  231. class Qwen2RotaryEmbedding(nn.Module):
  232. inv_freq: torch.Tensor # fix linting for `register_buffer`
  233. def __init__(self, config: Qwen2Config, device=None):
  234. super().__init__()
  235. # BC: "rope_type" was originally "type"
  236. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  237. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  238. else:
  239. self.rope_type = "default"
  240. self.max_seq_len_cached = config.max_position_embeddings
  241. self.original_max_seq_len = config.max_position_embeddings
  242. self.config = config
  243. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  244. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  245. self.register_buffer("inv_freq", inv_freq, persistent=False)
  246. self.original_inv_freq = self.inv_freq
  247. @torch.no_grad()
  248. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  249. def forward(self, x, position_ids):
  250. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  251. position_ids_expanded = position_ids[:, None, :].float()
  252. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  253. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  254. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  255. emb = torch.cat((freqs, freqs), dim=-1)
  256. cos = emb.cos() * self.attention_scaling
  257. sin = emb.sin() * self.attention_scaling
  258. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  259. @auto_docstring
  260. class Qwen2Model(Qwen2PreTrainedModel):
  261. def __init__(self, config: Qwen2Config):
  262. super().__init__(config)
  263. self.padding_idx = config.pad_token_id
  264. self.vocab_size = config.vocab_size
  265. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  266. self.layers = nn.ModuleList(
  267. [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  268. )
  269. self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  270. self.rotary_emb = Qwen2RotaryEmbedding(config=config)
  271. self.gradient_checkpointing = False
  272. self.has_sliding_layers = "sliding_attention" in self.config.layer_types
  273. # Initialize weights and apply final processing
  274. self.post_init()
  275. @check_model_inputs()
  276. @auto_docstring
  277. def forward(
  278. self,
  279. input_ids: Optional[torch.LongTensor] = None,
  280. attention_mask: Optional[torch.Tensor] = None,
  281. position_ids: Optional[torch.LongTensor] = None,
  282. past_key_values: Optional[Cache] = None,
  283. inputs_embeds: Optional[torch.FloatTensor] = None,
  284. use_cache: Optional[bool] = None,
  285. cache_position: Optional[torch.LongTensor] = None,
  286. **kwargs: Unpack[TransformersKwargs],
  287. ) -> BaseModelOutputWithPast:
  288. if (input_ids is None) ^ (inputs_embeds is not None):
  289. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  290. if inputs_embeds is None:
  291. inputs_embeds = self.embed_tokens(input_ids)
  292. if use_cache and past_key_values is None:
  293. past_key_values = DynamicCache(config=self.config)
  294. if cache_position is None:
  295. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  296. cache_position = torch.arange(
  297. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  298. )
  299. if position_ids is None:
  300. position_ids = cache_position.unsqueeze(0)
  301. # It may already have been prepared by e.g. `generate`
  302. if not isinstance(causal_mask_mapping := attention_mask, dict):
  303. # Prepare mask arguments
  304. mask_kwargs = {
  305. "config": self.config,
  306. "input_embeds": inputs_embeds,
  307. "attention_mask": attention_mask,
  308. "cache_position": cache_position,
  309. "past_key_values": past_key_values,
  310. "position_ids": position_ids,
  311. }
  312. # Create the masks
  313. causal_mask_mapping = {
  314. "full_attention": create_causal_mask(**mask_kwargs),
  315. }
  316. # The sliding window alternating layers are not always activated depending on the config
  317. if self.has_sliding_layers:
  318. causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
  319. hidden_states = inputs_embeds
  320. # create position embeddings to be shared across the decoder layers
  321. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  322. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  323. hidden_states = decoder_layer(
  324. hidden_states,
  325. attention_mask=causal_mask_mapping[decoder_layer.attention_type],
  326. position_ids=position_ids,
  327. past_key_values=past_key_values,
  328. use_cache=use_cache,
  329. cache_position=cache_position,
  330. position_embeddings=position_embeddings,
  331. **kwargs,
  332. )
  333. hidden_states = self.norm(hidden_states)
  334. return BaseModelOutputWithPast(
  335. last_hidden_state=hidden_states,
  336. past_key_values=past_key_values if use_cache else None,
  337. )
  338. @auto_docstring
  339. class Qwen2ForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
  340. _tied_weights_keys = ["lm_head.weight"]
  341. _tp_plan = {"lm_head": "colwise_rep"}
  342. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  343. def __init__(self, config):
  344. super().__init__(config)
  345. self.model = Qwen2Model(config)
  346. self.vocab_size = config.vocab_size
  347. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  348. # Initialize weights and apply final processing
  349. self.post_init()
  350. @can_return_tuple
  351. @auto_docstring
  352. def forward(
  353. self,
  354. input_ids: Optional[torch.LongTensor] = None,
  355. attention_mask: Optional[torch.Tensor] = None,
  356. position_ids: Optional[torch.LongTensor] = None,
  357. past_key_values: Optional[Cache] = None,
  358. inputs_embeds: Optional[torch.FloatTensor] = None,
  359. labels: Optional[torch.LongTensor] = None,
  360. use_cache: Optional[bool] = None,
  361. cache_position: Optional[torch.LongTensor] = None,
  362. logits_to_keep: Union[int, torch.Tensor] = 0,
  363. **kwargs: Unpack[TransformersKwargs],
  364. ) -> CausalLMOutputWithPast:
  365. r"""
  366. Example:
  367. ```python
  368. >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
  369. >>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
  370. >>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
  371. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  372. >>> inputs = tokenizer(prompt, return_tensors="pt")
  373. >>> # Generate
  374. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  375. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  376. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  377. ```"""
  378. outputs: BaseModelOutputWithPast = self.model(
  379. input_ids=input_ids,
  380. attention_mask=attention_mask,
  381. position_ids=position_ids,
  382. past_key_values=past_key_values,
  383. inputs_embeds=inputs_embeds,
  384. use_cache=use_cache,
  385. cache_position=cache_position,
  386. **kwargs,
  387. )
  388. hidden_states = outputs.last_hidden_state
  389. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  390. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  391. logits = self.lm_head(hidden_states[:, slice_indices, :])
  392. loss = None
  393. if labels is not None:
  394. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
  395. return CausalLMOutputWithPast(
  396. loss=loss,
  397. logits=logits,
  398. past_key_values=outputs.past_key_values,
  399. hidden_states=outputs.hidden_states,
  400. attentions=outputs.attentions,
  401. )
  402. class Qwen2ForSequenceClassification(GenericForSequenceClassification, Qwen2PreTrainedModel):
  403. pass
  404. class Qwen2ForTokenClassification(GenericForTokenClassification, Qwen2PreTrainedModel):
  405. pass
  406. class Qwen2ForQuestionAnswering(GenericForQuestionAnswering, Qwen2PreTrainedModel):
  407. base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
  408. __all__ = [
  409. "Qwen2PreTrainedModel",
  410. "Qwen2Model",
  411. "Qwen2ForCausalLM",
  412. "Qwen2RMSNorm",
  413. "Qwen2ForSequenceClassification",
  414. "Qwen2ForTokenClassification",
  415. "Qwen2ForQuestionAnswering",
  416. ]