modular_qwen3.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # coding=utf-8
  2. # Copyright 2025 The Qwen team, Alibaba Group 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 Qwen3 model."""
  16. from typing import Callable, Optional
  17. import torch
  18. from ...cache_utils import Cache
  19. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  20. from ...modeling_outputs import CausalLMOutputWithPast
  21. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
  22. from ...processing_utils import Unpack
  23. from ...utils import TransformersKwargs, logging
  24. from ...utils.deprecation import deprecate_kwarg
  25. from ..gemma.modeling_gemma import GemmaMLP
  26. from ..llama.modeling_llama import (
  27. LlamaAttention,
  28. )
  29. from ..qwen2.modeling_qwen2 import (
  30. Qwen2DecoderLayer,
  31. Qwen2ForCausalLM,
  32. Qwen2ForQuestionAnswering,
  33. Qwen2ForSequenceClassification,
  34. Qwen2ForTokenClassification,
  35. Qwen2Model,
  36. Qwen2PreTrainedModel,
  37. Qwen2RMSNorm,
  38. apply_rotary_pos_emb,
  39. eager_attention_forward,
  40. )
  41. from .configuration_qwen3 import Qwen3Config
  42. logger = logging.get_logger(__name__)
  43. _CHECKPOINT_FOR_DOC = "Qwen/Qwen3-8B"
  44. class Qwen3RMSNorm(Qwen2RMSNorm):
  45. pass
  46. class Qwen3MLP(GemmaMLP):
  47. pass
  48. class Qwen3Attention(LlamaAttention):
  49. def __init__(self, config: Qwen3Config, layer_idx: int):
  50. super().__init__(config, layer_idx)
  51. self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
  52. self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
  53. self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
  54. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  55. def forward(
  56. self,
  57. hidden_states: torch.Tensor,
  58. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  59. attention_mask: Optional[torch.Tensor],
  60. past_key_values: Optional[Cache] = None,
  61. cache_position: Optional[torch.LongTensor] = None,
  62. **kwargs: Unpack[FlashAttentionKwargs],
  63. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  64. input_shape = hidden_states.shape[:-1]
  65. hidden_shape = (*input_shape, -1, self.head_dim)
  66. query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
  67. key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
  68. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  69. cos, sin = position_embeddings
  70. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  71. if past_key_values is not None:
  72. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  73. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  74. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  75. attention_interface: Callable = eager_attention_forward
  76. if self.config._attn_implementation != "eager":
  77. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  78. attn_output, attn_weights = attention_interface(
  79. self,
  80. query_states,
  81. key_states,
  82. value_states,
  83. attention_mask,
  84. dropout=0.0 if not self.training else self.attention_dropout,
  85. scaling=self.scaling,
  86. sliding_window=self.sliding_window, # diff with Llama
  87. **kwargs,
  88. )
  89. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  90. attn_output = self.o_proj(attn_output)
  91. return attn_output, attn_weights
  92. class Qwen3DecoderLayer(Qwen2DecoderLayer):
  93. pass
  94. class Qwen3PreTrainedModel(Qwen2PreTrainedModel):
  95. pass
  96. class Qwen3Model(Qwen2Model):
  97. pass
  98. class Qwen3ForCausalLM(Qwen2ForCausalLM):
  99. def forward(
  100. self,
  101. **super_kwargs: Unpack[TransformersKwargs],
  102. ) -> CausalLMOutputWithPast:
  103. r"""
  104. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  105. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  106. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  107. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  108. Example:
  109. ```python
  110. >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
  111. >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
  112. >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
  113. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  114. >>> inputs = tokenizer(prompt, return_tensors="pt")
  115. >>> # Generate
  116. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  117. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  118. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  119. ```"""
  120. return super().forward(**super_kwargs)
  121. class Qwen3ForSequenceClassification(Qwen2ForSequenceClassification):
  122. pass
  123. class Qwen3ForTokenClassification(Qwen2ForTokenClassification):
  124. pass
  125. class Qwen3ForQuestionAnswering(Qwen2ForQuestionAnswering):
  126. pass
  127. __all__ = [
  128. "Qwen3ForCausalLM",
  129. "Qwen3ForQuestionAnswering",
  130. "Qwen3PreTrainedModel",
  131. "Qwen3Model",
  132. "Qwen3ForSequenceClassification",
  133. "Qwen3ForTokenClassification",
  134. ]