modeling_qwen3.py 23 KB

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