YongganFu commited on
Commit
8c7caf4
·
verified ·
1 Parent(s): 095ee38

Upload model

Browse files
Files changed (2) hide show
  1. modeling_nvrdiff.py +3 -2
  2. modeling_qwen3.py +1229 -0
modeling_nvrdiff.py CHANGED
@@ -7,7 +7,8 @@ import torch.nn.functional as F
7
  from torch import nn
8
  from transformers.modeling_outputs import CausalLMOutputWithPast
9
 
10
- from torchtitan.models.qwen3.modeling_qwen3 import Qwen3Config, Qwen3Model, Qwen3PreTrainedModel, Qwen3Attention, apply_rotary_pos_emb, repeat_kv
 
11
 
12
  from torch.nn.attention.flex_attention import flex_attention, create_block_mask
13
 
@@ -246,7 +247,7 @@ class DiffEncoderModel(Qwen3PreTrainedModel, GenerationMixin):
246
  - a causal decoder + LM head over B, conditioned on F_A
247
  """
248
 
249
- def __init__(self, config: Qwen3Config):
250
  super().__init__(config)
251
 
252
  self.mask_token_id = config.mask_token_id
 
7
  from torch import nn
8
  from transformers.modeling_outputs import CausalLMOutputWithPast
9
 
10
+ from .modeling_qwen3 import Qwen3Model, Qwen3PreTrainedModel, Qwen3Attention, apply_rotary_pos_emb, repeat_kv
11
+ from .configuration_nvrdiff import NVRDiffConfig
12
 
13
  from torch.nn.attention.flex_attention import flex_attention, create_block_mask
14
 
 
247
  - a causal decoder + LM head over B, conditioned on F_A
248
  """
249
 
250
+ def __init__(self, config: NVRDiffConfig):
251
  super().__init__(config)
252
 
253
  self.mask_token_id = config.mask_token_id
modeling_qwen3.py ADDED
@@ -0,0 +1,1229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from typing import Callable, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from transformers.activations import ACT2FN
22
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
23
+ from transformers.generation import GenerationMixin
24
+ from transformers.integrations import use_kernel_forward_from_hub
25
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
26
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
27
+ from transformers.modeling_layers import GradientCheckpointingLayer
28
+ from transformers.modeling_outputs import (
29
+ BaseModelOutputWithPast,
30
+ CausalLMOutputWithPast,
31
+ QuestionAnsweringModelOutput,
32
+ SequenceClassifierOutputWithPast,
33
+ TokenClassifierOutput,
34
+ )
35
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from transformers.processing_utils import Unpack
38
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
39
+ from .configuration_nvrdiff import NVRDiffConfig
40
+
41
+
42
+ if is_torch_flex_attn_available():
43
+ from torch.nn.attention.flex_attention import BlockMask
44
+
45
+ from transformers.integrations.flex_attention import make_flex_block_causal_mask
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ @use_kernel_forward_from_hub("RMSNorm")
52
+ class Qwen3RMSNorm(nn.Module):
53
+ def __init__(self, hidden_size, eps=1e-6):
54
+ """
55
+ Qwen3RMSNorm is equivalent to T5LayerNorm
56
+ """
57
+ super().__init__()
58
+ self.weight = nn.Parameter(torch.ones(hidden_size))
59
+ self.variance_epsilon = eps
60
+
61
+ def forward(self, hidden_states):
62
+ input_dtype = hidden_states.dtype
63
+ hidden_states = hidden_states.to(torch.float32)
64
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
65
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
66
+ return self.weight * hidden_states.to(input_dtype)
67
+
68
+ def extra_repr(self):
69
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
70
+
71
+
72
+ class Qwen3MLP(nn.Module):
73
+ def __init__(self, config):
74
+ super().__init__()
75
+ self.config = config
76
+ self.hidden_size = config.hidden_size
77
+ self.intermediate_size = config.intermediate_size
78
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
79
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
80
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
81
+ self.act_fn = ACT2FN[config.hidden_act]
82
+
83
+ def forward(self, x):
84
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
85
+ return down_proj
86
+
87
+
88
+ def rotate_half(x):
89
+ """Rotates half the hidden dims of the input."""
90
+ x1 = x[..., : x.shape[-1] // 2]
91
+ x2 = x[..., x.shape[-1] // 2 :]
92
+ return torch.cat((-x2, x1), dim=-1)
93
+
94
+
95
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
96
+ """Applies Rotary Position Embedding to the query and key tensors.
97
+
98
+ Args:
99
+ q (`torch.Tensor`): The query tensor.
100
+ k (`torch.Tensor`): The key tensor.
101
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
102
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
103
+ position_ids (`torch.Tensor`, *optional*):
104
+ Deprecated and unused.
105
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
106
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
107
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
108
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
109
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
110
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
111
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
112
+ Returns:
113
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
114
+ """
115
+ cos = cos.unsqueeze(unsqueeze_dim)
116
+ sin = sin.unsqueeze(unsqueeze_dim)
117
+ q_embed = (q * cos) + (rotate_half(q) * sin)
118
+ k_embed = (k * cos) + (rotate_half(k) * sin)
119
+ return q_embed, k_embed
120
+
121
+
122
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
123
+ """
124
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
125
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
126
+ """
127
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
128
+ if n_rep == 1:
129
+ return hidden_states
130
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
131
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
132
+
133
+
134
+ def eager_attention_forward(
135
+ module: nn.Module,
136
+ query: torch.Tensor,
137
+ key: torch.Tensor,
138
+ value: torch.Tensor,
139
+ attention_mask: Optional[torch.Tensor],
140
+ scaling: float,
141
+ dropout: float = 0.0,
142
+ **kwargs,
143
+ ):
144
+ key_states = repeat_kv(key, module.num_key_value_groups)
145
+ value_states = repeat_kv(value, module.num_key_value_groups)
146
+
147
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
148
+ if attention_mask is not None:
149
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
150
+ attn_weights = attn_weights + causal_mask
151
+
152
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
153
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
154
+ attn_output = torch.matmul(attn_weights, value_states)
155
+ attn_output = attn_output.transpose(1, 2).contiguous()
156
+
157
+ return attn_output, attn_weights
158
+
159
+
160
+ class Qwen3Attention(nn.Module):
161
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
162
+
163
+ def __init__(self, config: NVRDiffConfig, layer_idx: int):
164
+ super().__init__()
165
+ self.config = config
166
+
167
+ self.layer_idx = layer_idx
168
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
169
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
170
+ self.scaling = self.head_dim**-0.5
171
+ self.attention_dropout = config.attention_dropout
172
+
173
+ self.diffusion_lm = config.diffusion_lm
174
+
175
+ self.is_causal = None if not self.diffusion_lm else False
176
+
177
+ self.q_proj = nn.Linear(
178
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
179
+ )
180
+ self.k_proj = nn.Linear(
181
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
182
+ )
183
+ self.v_proj = nn.Linear(
184
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
185
+ )
186
+ self.o_proj = nn.Linear(
187
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=False # config.attention_bias
188
+ )
189
+
190
+ if not config.disable_qk_norm:
191
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
192
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
193
+ else:
194
+ self.q_norm = nn.Identity()
195
+ self.k_norm = nn.Identity()
196
+
197
+ self.sliding_window = config.sliding_window
198
+ if not (
199
+ self.config.use_sliding_window
200
+ and getattr(self.config, "sliding_window", None) is not None
201
+ and self.layer_idx >= self.config.max_window_layers
202
+ ):
203
+ self.sliding_window = None
204
+
205
+ def forward(
206
+ self,
207
+ hidden_states: torch.Tensor,
208
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
209
+ attention_mask: Optional[torch.Tensor],
210
+ past_key_value: Optional[Cache] = None,
211
+ cache_position: Optional[torch.LongTensor] = None,
212
+ replace_position: Optional[torch.Tensor] = None,
213
+ is_training: bool = True,
214
+ use_cache: bool = False,
215
+ **kwargs: Unpack[FlashAttentionKwargs],
216
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
217
+ input_shape = hidden_states.shape[:-1]
218
+ hidden_shape = (*input_shape, -1, self.head_dim)
219
+
220
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
221
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
222
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
223
+
224
+ cos, sin = position_embeddings
225
+
226
+ if replace_position is not None:
227
+ # Get the indices that need to be replaced
228
+ replace_indices = replace_position.nonzero(as_tuple=True)[1] # [selected_length]
229
+ block_end_index = replace_indices.max() + 1 if len(replace_indices) > 0 else query_states.shape[-2]
230
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids=None, unsqueeze_dim=1)
231
+ else:
232
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
233
+
234
+ if past_key_value is not None:
235
+ if replace_position is None:
236
+ # Normal cache behavior - append new keys/values
237
+ if use_cache:
238
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
239
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
240
+ else: ## if use_cache == False, do not update cache
241
+ old_k, old_v = past_key_value[self.layer_idx]
242
+ key_states = torch.cat([old_k, key_states], dim=-2)
243
+ value_states = torch.cat([old_v, value_states], dim=-2)
244
+ else:
245
+ # Replace specific positions in the cache
246
+ # Extract past keys and values from cache
247
+ if hasattr(past_key_value, 'key_cache') and hasattr(past_key_value, 'value_cache'):
248
+ # Get past keys and values for this layer
249
+ past_key = past_key_value.key_cache[self.layer_idx] # Shape: [B, n_kv_h, L, hs]
250
+ past_value = past_key_value.value_cache[self.layer_idx] # Shape: [B, n_kv_h, L, hs]
251
+
252
+ # Get the indices that need to be replaced in the full sequence
253
+ replace_indices = replace_position.nonzero(as_tuple=True)[1] # [selected_length]
254
+
255
+ # key_states and value_states are only for the current block (selected_length)
256
+ # We need to replace the positions indicated by replace_indices with these new values
257
+ if len(replace_indices) == key_states.shape[-2]:
258
+ # Replace selected positions in past_key with new key_states
259
+ past_key = past_key.clone() # Make a copy to avoid in-place modification
260
+ past_value = past_value.clone()
261
+ past_key[:, :, replace_indices] = key_states
262
+ past_value[:, :, replace_indices] = value_states
263
+
264
+ # Update the cache with modified keys/values
265
+ past_key_value.key_cache[self.layer_idx] = past_key
266
+ past_key_value.value_cache[self.layer_idx] = past_value
267
+
268
+ key_states = past_key
269
+ value_states = past_value
270
+ else:
271
+ print("length mismatch")
272
+ # Fallback - length mismatch, use normal cache update
273
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
274
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
275
+ else:
276
+ # Fallback to normal behavior if cache structure is unexpected
277
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
278
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
279
+
280
+ attention_interface: Callable = eager_attention_forward
281
+ if self.config._attn_implementation != "eager":
282
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
283
+ logger.warning_once(
284
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
285
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
286
+ )
287
+ else:
288
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
289
+
290
+ attn_output, attn_weights = attention_interface(
291
+ self,
292
+ query_states,
293
+ key_states,
294
+ value_states,
295
+ attention_mask if not self.diffusion_lm else None,
296
+ dropout=0.0 if not self.training else self.attention_dropout,
297
+ scaling=self.scaling,
298
+ sliding_window=self.sliding_window, # diff with Llama
299
+ is_causal=self.is_causal,
300
+ **kwargs,
301
+ )
302
+
303
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
304
+ attn_output = self.o_proj(attn_output)
305
+ return attn_output, attn_weights
306
+
307
+
308
+ class Qwen3DecoderLayer(GradientCheckpointingLayer):
309
+ def __init__(self, config: NVRDiffConfig, layer_idx: int):
310
+ super().__init__()
311
+ self.hidden_size = config.hidden_size
312
+ if hasattr(config, 'attn_class'):
313
+ attn_class = config.attn_class
314
+ else:
315
+ attn_class = Qwen3Attention
316
+
317
+ self.layer_idx = layer_idx
318
+
319
+ self.self_attn = attn_class(config=config, layer_idx=layer_idx)
320
+ self.mlp = Qwen3MLP(config)
321
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
322
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
323
+ if (
324
+ config.sliding_window and config._attn_implementation != "flash_attention_2"
325
+ ): # diff with Llama is this warning
326
+ logger.warning_once(
327
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
328
+ "unexpected results may be encountered."
329
+ )
330
+
331
+
332
+ def forward(
333
+ self,
334
+ hidden_states: torch.Tensor,
335
+ attention_mask: Optional[torch.Tensor] = None,
336
+ position_ids: Optional[torch.LongTensor] = None,
337
+ past_key_value: Optional[Cache] = None,
338
+ output_attentions: Optional[bool] = False,
339
+ use_cache: Optional[bool] = False,
340
+ cache_position: Optional[torch.LongTensor] = None,
341
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
342
+ replace_position: Optional[torch.Tensor] = None,
343
+ is_training: bool = True,
344
+ **kwargs: Unpack[FlashAttentionKwargs],
345
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
346
+ residual = hidden_states
347
+ hidden_states = self.input_layernorm(hidden_states)
348
+
349
+ # Self Attention
350
+ hidden_states, self_attn_weights = self.self_attn(
351
+ hidden_states=hidden_states,
352
+ attention_mask=attention_mask,
353
+ position_ids=position_ids,
354
+ past_key_value=past_key_value,
355
+ output_attentions=output_attentions,
356
+ use_cache=use_cache,
357
+ cache_position=cache_position,
358
+ position_embeddings=position_embeddings,
359
+ replace_position=replace_position,
360
+ is_training=is_training,
361
+ **kwargs,
362
+ )
363
+ hidden_states = residual + hidden_states
364
+
365
+ # Fully Connected
366
+ residual = hidden_states
367
+ hidden_states = self.post_attention_layernorm(hidden_states)
368
+ hidden_states = self.mlp(hidden_states)
369
+ hidden_states = residual + hidden_states
370
+
371
+ outputs = (hidden_states,)
372
+ if output_attentions:
373
+ outputs += (self_attn_weights,)
374
+
375
+ return outputs
376
+
377
+
378
+ @auto_docstring
379
+ class Qwen3PreTrainedModel(PreTrainedModel):
380
+ config_class = NVRDiffConfig
381
+ base_model_prefix = "model"
382
+ supports_gradient_checkpointing = True
383
+ _no_split_modules = ["Qwen3DecoderLayer"]
384
+ _skip_keys_device_placement = ["past_key_values"]
385
+ _supports_flash_attn_2 = True
386
+ _supports_sdpa = True
387
+ _supports_flex_attn = True
388
+ _supports_cache_class = True
389
+ _supports_quantized_cache = True
390
+ _supports_static_cache = True
391
+ _supports_attention_backend = True
392
+
393
+ def _init_weights(self, module):
394
+ std = self.config.initializer_range
395
+ if isinstance(module, nn.Linear):
396
+ module.weight.data.normal_(mean=0.0, std=std)
397
+ if module.bias is not None:
398
+ module.bias.data.zero_()
399
+ elif isinstance(module, nn.Embedding):
400
+ module.weight.data.normal_(mean=0.0, std=std)
401
+ if module.padding_idx is not None:
402
+ module.weight.data[module.padding_idx].zero_()
403
+ elif isinstance(module, Qwen3RMSNorm):
404
+ module.weight.data.fill_(1.0)
405
+
406
+
407
+ class Qwen3RotaryEmbedding(nn.Module):
408
+ def __init__(self, config: NVRDiffConfig, device=None):
409
+ super().__init__()
410
+ # BC: "rope_type" was originally "type"
411
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
412
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
413
+ else:
414
+ self.rope_type = "default"
415
+ self.max_seq_len_cached = config.max_position_embeddings
416
+ self.original_max_seq_len = config.max_position_embeddings
417
+
418
+ self.config = config
419
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
420
+
421
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
422
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
423
+ self.original_inv_freq = self.inv_freq
424
+
425
+ @torch.no_grad()
426
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
427
+ def forward(self, x, position_ids):
428
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
429
+ position_ids_expanded = position_ids[:, None, :].float()
430
+
431
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
432
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
433
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
434
+ emb = torch.cat((freqs, freqs), dim=-1)
435
+ cos = emb.cos() * self.attention_scaling
436
+ sin = emb.sin() * self.attention_scaling
437
+
438
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
439
+
440
+
441
+ @auto_docstring
442
+ class Qwen3Model(Qwen3PreTrainedModel):
443
+ def __init__(self, config: NVRDiffConfig):
444
+ super().__init__(config)
445
+ self.config = config
446
+
447
+ self.padding_idx = config.pad_token_id
448
+ self.vocab_size = config.vocab_size
449
+
450
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
451
+ self.layers = nn.ModuleList(
452
+ [Qwen3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
453
+ )
454
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
455
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
456
+ self.gradient_checkpointing = False
457
+
458
+ # Initialize weights and apply final processing
459
+ self.post_init()
460
+
461
+ def get_input_embeddings(self):
462
+ return self.embed_tokens
463
+
464
+ def set_input_embeddings(self, value):
465
+ self.embed_tokens = value
466
+
467
+ @can_return_tuple
468
+ @auto_docstring
469
+ def forward(
470
+ self,
471
+ input_ids: Optional[torch.LongTensor] = None,
472
+ attention_mask: Optional[torch.Tensor] = None,
473
+ position_ids: Optional[torch.LongTensor] = None,
474
+ past_key_values: Optional[Cache] = None,
475
+ inputs_embeds: Optional[torch.FloatTensor] = None,
476
+ use_cache: Optional[bool] = None,
477
+ output_attentions: Optional[bool] = None,
478
+ output_hidden_states: Optional[bool] = None,
479
+ cache_position: Optional[torch.LongTensor] = None,
480
+ replace_position: Optional[torch.Tensor] = None,
481
+ is_training: bool = True,
482
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
483
+ ) -> BaseModelOutputWithPast:
484
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
485
+ output_hidden_states = (
486
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
487
+ )
488
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
489
+
490
+ if (input_ids is None) ^ (inputs_embeds is not None):
491
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
492
+
493
+ if self.gradient_checkpointing and self.training and use_cache:
494
+ logger.warning_once(
495
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
496
+ )
497
+ use_cache = False
498
+
499
+ # Allow both Cache objects and legacy tuple format for compatibility
500
+ if past_key_values is not None and not isinstance(past_key_values, Cache):
501
+ # Convert legacy tuple format to DynamicCache if needed
502
+ if isinstance(past_key_values, (list, tuple)):
503
+ # This is likely a legacy format - convert to DynamicCache
504
+ legacy_cache = past_key_values
505
+ past_key_values = DynamicCache()
506
+ for layer_idx, layer_cache in enumerate(legacy_cache):
507
+ if isinstance(layer_cache, (list, tuple)) and len(layer_cache) == 2:
508
+ key_cache, value_cache = layer_cache
509
+ past_key_values.update(key_cache, value_cache, layer_idx)
510
+ else:
511
+ raise ValueError("The `past_key_values` should be either a `Cache` object, list/tuple of layer caches, or `None`.")
512
+
513
+ # # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
514
+ # if not isinstance(past_key_values, (type(None), Cache)):
515
+ # raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
516
+
517
+ if inputs_embeds is None:
518
+ inputs_embeds = self.embed_tokens(input_ids)
519
+
520
+ if use_cache and past_key_values is None:
521
+ past_key_values = DynamicCache()
522
+
523
+ if cache_position is None:
524
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
525
+ cache_position = torch.arange(
526
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
527
+ )
528
+
529
+ if position_ids is None:
530
+ position_ids = cache_position.unsqueeze(0)
531
+
532
+ causal_mask = self._update_causal_mask(
533
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
534
+ )
535
+
536
+ hidden_states = inputs_embeds
537
+
538
+ # create position embeddings to be shared across the decoder layers
539
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
540
+
541
+ # decoder layers
542
+ all_hidden_states = () if output_hidden_states else None
543
+ all_self_attns = () if output_attentions else None
544
+
545
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
546
+ if output_hidden_states:
547
+ all_hidden_states += (hidden_states,)
548
+
549
+ layer_outputs = decoder_layer(
550
+ hidden_states,
551
+ attention_mask=causal_mask,
552
+ position_ids=position_ids,
553
+ past_key_value=past_key_values,
554
+ output_attentions=output_attentions,
555
+ use_cache=use_cache,
556
+ cache_position=cache_position,
557
+ position_embeddings=position_embeddings,
558
+ replace_position=replace_position,
559
+ is_training=is_training,
560
+ **flash_attn_kwargs,
561
+ )
562
+
563
+ hidden_states = layer_outputs[0]
564
+
565
+ if output_attentions:
566
+ all_self_attns += (layer_outputs[1],)
567
+
568
+ hidden_states = self.norm(hidden_states)
569
+
570
+ # add hidden states from the last decoder layer
571
+ if output_hidden_states:
572
+ all_hidden_states += (hidden_states,)
573
+
574
+ past_key_values_output = None
575
+ if use_cache and past_key_values is not None:
576
+ if isinstance(past_key_values, Cache):
577
+ # Convert Cache to list of tuples format: [(key, value), (key, value), ...]
578
+ past_key_values_output = []
579
+ if hasattr(past_key_values, 'key_cache') and hasattr(past_key_values, 'value_cache'):
580
+ # DynamicCache format
581
+ for layer_idx in range(len(past_key_values.key_cache)):
582
+ past_key_values_output.append((
583
+ past_key_values.key_cache[layer_idx],
584
+ past_key_values.value_cache[layer_idx]
585
+ ))
586
+ else:
587
+ # Fallback - return as is
588
+ past_key_values_output = past_key_values
589
+ else:
590
+ past_key_values_output = past_key_values
591
+
592
+ return BaseModelOutputWithPast(
593
+ last_hidden_state=hidden_states,
594
+ past_key_values=past_key_values_output,
595
+ hidden_states=all_hidden_states,
596
+ attentions=all_self_attns,
597
+ )
598
+
599
+ def _update_causal_mask(
600
+ self,
601
+ attention_mask: Union[torch.Tensor, "BlockMask"],
602
+ input_tensor: torch.Tensor,
603
+ cache_position: torch.Tensor,
604
+ past_key_values: Cache,
605
+ output_attentions: bool = False,
606
+ ):
607
+ if self.config._attn_implementation == "flash_attention_2":
608
+ if attention_mask is not None and past_key_values is not None:
609
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
610
+ if is_padding_right:
611
+ raise ValueError(
612
+ "You are attempting to perform batched generation with padding_side='right'"
613
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3. Make sure to "
614
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
615
+ )
616
+ if attention_mask is not None and 0.0 in attention_mask:
617
+ return attention_mask
618
+ return None
619
+ if self.config._attn_implementation == "flex_attention":
620
+ if isinstance(attention_mask, torch.Tensor):
621
+ attention_mask = make_flex_block_causal_mask(attention_mask)
622
+ return attention_mask
623
+
624
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
625
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
626
+ # to infer the attention mask.
627
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
628
+ using_static_cache = isinstance(past_key_values, StaticCache)
629
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
630
+
631
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
632
+ if (
633
+ self.config._attn_implementation == "sdpa"
634
+ and not (using_static_cache or using_sliding_window_cache)
635
+ and not output_attentions
636
+ ):
637
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
638
+ attention_mask,
639
+ inputs_embeds=input_tensor,
640
+ past_key_values_length=past_seen_tokens,
641
+ sliding_window=self.config.sliding_window,
642
+ is_training=self.training,
643
+ ):
644
+ return None
645
+
646
+ dtype = input_tensor.dtype
647
+ min_dtype = torch.finfo(dtype).min
648
+ sequence_length = input_tensor.shape[1]
649
+ # SlidingWindowCache or StaticCache
650
+ if using_sliding_window_cache or using_static_cache:
651
+ target_length = past_key_values.get_max_cache_shape()
652
+ # DynamicCache or no cache
653
+ else:
654
+ target_length = (
655
+ attention_mask.shape[-1]
656
+ if isinstance(attention_mask, torch.Tensor)
657
+ else past_seen_tokens + sequence_length + 1
658
+ )
659
+
660
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
661
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
662
+ attention_mask,
663
+ sequence_length=sequence_length,
664
+ target_length=target_length,
665
+ dtype=dtype,
666
+ cache_position=cache_position,
667
+ batch_size=input_tensor.shape[0],
668
+ config=self.config,
669
+ past_key_values=past_key_values,
670
+ )
671
+
672
+ if (
673
+ self.config._attn_implementation == "sdpa"
674
+ and attention_mask is not None
675
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
676
+ and not output_attentions
677
+ ):
678
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
679
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
680
+ # Details: https://github.com/pytorch/pytorch/issues/110213
681
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
682
+
683
+ return causal_mask
684
+
685
+ @staticmethod
686
+ def _prepare_4d_causal_attention_mask_with_cache_position(
687
+ attention_mask: torch.Tensor,
688
+ sequence_length: int,
689
+ target_length: int,
690
+ dtype: torch.dtype,
691
+ cache_position: torch.Tensor,
692
+ batch_size: int,
693
+ config: NVRDiffConfig,
694
+ past_key_values: Cache,
695
+ ):
696
+ """
697
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
698
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
699
+
700
+ Args:
701
+ attention_mask (`torch.Tensor`):
702
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
703
+ sequence_length (`int`):
704
+ The sequence length being processed.
705
+ target_length (`int`):
706
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
707
+ dtype (`torch.dtype`):
708
+ The dtype to use for the 4D attention mask.
709
+ cache_position (`torch.Tensor`):
710
+ Indices depicting the position of the input sequence tokens in the sequence.
711
+ batch_size (`torch.Tensor`):
712
+ Batch size.
713
+ config (`NVRDiffConfig`):
714
+ The model's configuration class
715
+ past_key_values (`Cache`):
716
+ The cache class that is being used currently to generate
717
+ """
718
+ if attention_mask is not None and attention_mask.dim() == 4:
719
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
720
+ causal_mask = attention_mask
721
+ else:
722
+ min_dtype = torch.finfo(dtype).min
723
+ causal_mask = torch.full(
724
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
725
+ )
726
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
727
+ -1, 1
728
+ )
729
+ text_config = config.get_text_config()
730
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
731
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
732
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
733
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
734
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
735
+ cache_position.reshape(-1, 1) - text_config.sliding_window
736
+ )
737
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
738
+ causal_mask *= diagonal_attend_mask
739
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
740
+ if attention_mask is not None:
741
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
742
+ if attention_mask.shape[-1] > target_length:
743
+ attention_mask = attention_mask[:, :target_length]
744
+ mask_length = attention_mask.shape[-1]
745
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
746
+ causal_mask.device
747
+ )
748
+ padding_mask = padding_mask == 0
749
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
750
+ padding_mask, min_dtype
751
+ )
752
+ return causal_mask
753
+
754
+
755
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
756
+
757
+
758
+ @auto_docstring
759
+ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
760
+ _tied_weights_keys = ["lm_head.weight"]
761
+ _tp_plan = {"lm_head": "colwise_rep"}
762
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
763
+
764
+ def __init__(self, config):
765
+ super().__init__(config)
766
+
767
+ config._attn_implementation = config.attn_implementation
768
+
769
+ self.model = Qwen3Model(config)
770
+ self.vocab_size = config.vocab_size
771
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
772
+
773
+ # Initialize weights and apply final processing
774
+ self.post_init()
775
+
776
+ def get_input_embeddings(self):
777
+ return self.model.embed_tokens
778
+
779
+ def set_input_embeddings(self, value):
780
+ self.model.embed_tokens = value
781
+
782
+ def get_output_embeddings(self):
783
+ return self.lm_head
784
+
785
+ def set_output_embeddings(self, new_embeddings):
786
+ self.lm_head = new_embeddings
787
+
788
+ def set_decoder(self, decoder):
789
+ self.model = decoder
790
+
791
+ def get_decoder(self):
792
+ return self.model
793
+
794
+ @can_return_tuple
795
+ @auto_docstring
796
+ def forward(
797
+ self,
798
+ input_ids: Optional[torch.LongTensor] = None,
799
+ attention_mask: Optional[torch.Tensor] = None,
800
+ position_ids: Optional[torch.LongTensor] = None,
801
+ past_key_values: Optional[Cache] = None,
802
+ inputs_embeds: Optional[torch.FloatTensor] = None,
803
+ labels: Optional[torch.LongTensor] = None,
804
+ use_cache: Optional[bool] = None,
805
+ output_attentions: Optional[bool] = None,
806
+ output_hidden_states: Optional[bool] = None,
807
+ cache_position: Optional[torch.LongTensor] = None,
808
+ logits_to_keep: Union[int, torch.Tensor] = 0,
809
+ replace_position: Optional[torch.Tensor] = None,
810
+ **kwargs: Unpack[KwargsForCausalLM],
811
+ ) -> CausalLMOutputWithPast:
812
+ r"""
813
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
814
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
815
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
816
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
817
+
818
+ Example:
819
+
820
+ ```python
821
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
822
+
823
+ >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
824
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
825
+
826
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
827
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
828
+
829
+ >>> # Generate
830
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
831
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
832
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
833
+ ```"""
834
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
835
+ output_hidden_states = (
836
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
837
+ )
838
+
839
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
840
+ outputs: BaseModelOutputWithPast = self.model(
841
+ input_ids=input_ids,
842
+ attention_mask=attention_mask,
843
+ position_ids=position_ids,
844
+ past_key_values=past_key_values,
845
+ inputs_embeds=inputs_embeds,
846
+ use_cache=use_cache,
847
+ output_attentions=output_attentions,
848
+ output_hidden_states=output_hidden_states,
849
+ cache_position=cache_position,
850
+ replace_position=replace_position,
851
+ **kwargs,
852
+ )
853
+
854
+ hidden_states = outputs.last_hidden_state
855
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
856
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
857
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
858
+
859
+ loss = None
860
+ if labels is not None:
861
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
862
+
863
+ return CausalLMOutputWithPast(
864
+ loss=loss,
865
+ logits=logits,
866
+ past_key_values=outputs.past_key_values,
867
+ hidden_states=outputs.hidden_states,
868
+ attentions=outputs.attentions,
869
+ )
870
+
871
+
872
+ @auto_docstring(
873
+ custom_intro="""
874
+ The Qwen3 Model transformer with a sequence classification head on top (linear layer).
875
+
876
+ [`Qwen3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
877
+ (e.g. GPT-2) do.
878
+
879
+ Since it does classification on the last token, it requires to know the position of the last token. If a
880
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
881
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
882
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
883
+ each row of the batch).
884
+ """
885
+ )
886
+ class Qwen3ForSequenceClassification(Qwen3PreTrainedModel):
887
+ def __init__(self, config):
888
+ super().__init__(config)
889
+ self.num_labels = config.num_labels
890
+ self.model = Qwen3Model(config)
891
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
892
+
893
+ # Initialize weights and apply final processing
894
+ self.post_init()
895
+
896
+ def get_input_embeddings(self):
897
+ return self.model.embed_tokens
898
+
899
+ def set_input_embeddings(self, value):
900
+ self.model.embed_tokens = value
901
+
902
+ @can_return_tuple
903
+ @auto_docstring
904
+ def forward(
905
+ self,
906
+ input_ids: Optional[torch.LongTensor] = None,
907
+ attention_mask: Optional[torch.Tensor] = None,
908
+ position_ids: Optional[torch.LongTensor] = None,
909
+ past_key_values: Optional[Cache] = None,
910
+ inputs_embeds: Optional[torch.FloatTensor] = None,
911
+ labels: Optional[torch.LongTensor] = None,
912
+ use_cache: Optional[bool] = None,
913
+ output_attentions: Optional[bool] = None,
914
+ output_hidden_states: Optional[bool] = None,
915
+ ) -> SequenceClassifierOutputWithPast:
916
+ r"""
917
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
918
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
919
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
920
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
921
+ """
922
+
923
+ transformer_outputs: BaseModelOutputWithPast = self.model(
924
+ input_ids,
925
+ attention_mask=attention_mask,
926
+ position_ids=position_ids,
927
+ past_key_values=past_key_values,
928
+ inputs_embeds=inputs_embeds,
929
+ use_cache=use_cache,
930
+ output_attentions=output_attentions,
931
+ output_hidden_states=output_hidden_states,
932
+ )
933
+ hidden_states = transformer_outputs.last_hidden_state
934
+ logits = self.score(hidden_states)
935
+
936
+ if input_ids is not None:
937
+ batch_size = input_ids.shape[0]
938
+ else:
939
+ batch_size = inputs_embeds.shape[0]
940
+
941
+ if self.config.pad_token_id is None and batch_size != 1:
942
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
943
+ if self.config.pad_token_id is None:
944
+ last_non_pad_token = -1
945
+ elif input_ids is not None:
946
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
947
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
948
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
949
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
950
+ else:
951
+ last_non_pad_token = -1
952
+ logger.warning_once(
953
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
954
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
955
+ )
956
+
957
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
958
+
959
+ loss = None
960
+ if labels is not None:
961
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
962
+
963
+ return SequenceClassifierOutputWithPast(
964
+ loss=loss,
965
+ logits=pooled_logits,
966
+ past_key_values=transformer_outputs.past_key_values,
967
+ hidden_states=transformer_outputs.hidden_states,
968
+ attentions=transformer_outputs.attentions,
969
+ )
970
+
971
+
972
+ @auto_docstring
973
+ class Qwen3ForTokenClassification(Qwen3PreTrainedModel):
974
+ def __init__(self, config):
975
+ super().__init__(config)
976
+ self.num_labels = config.num_labels
977
+ self.model = Qwen3Model(config)
978
+ if getattr(config, "classifier_dropout", None) is not None:
979
+ classifier_dropout = config.classifier_dropout
980
+ elif getattr(config, "hidden_dropout", None) is not None:
981
+ classifier_dropout = config.hidden_dropout
982
+ else:
983
+ classifier_dropout = 0.1
984
+ self.dropout = nn.Dropout(classifier_dropout)
985
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
986
+
987
+ # Initialize weights and apply final processing
988
+ self.post_init()
989
+
990
+ def get_input_embeddings(self):
991
+ return self.model.embed_tokens
992
+
993
+ def set_input_embeddings(self, value):
994
+ self.model.embed_tokens = value
995
+
996
+ @can_return_tuple
997
+ @auto_docstring
998
+ def forward(
999
+ self,
1000
+ input_ids: Optional[torch.LongTensor] = None,
1001
+ attention_mask: Optional[torch.Tensor] = None,
1002
+ position_ids: Optional[torch.LongTensor] = None,
1003
+ past_key_values: Optional[Cache] = None,
1004
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1005
+ labels: Optional[torch.LongTensor] = None,
1006
+ use_cache: Optional[bool] = None,
1007
+ output_attentions: Optional[bool] = None,
1008
+ output_hidden_states: Optional[bool] = None,
1009
+ ) -> TokenClassifierOutput:
1010
+ r"""
1011
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1012
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1013
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1014
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1015
+ """
1016
+
1017
+ outputs: BaseModelOutputWithPast = self.model(
1018
+ input_ids,
1019
+ attention_mask=attention_mask,
1020
+ position_ids=position_ids,
1021
+ past_key_values=past_key_values,
1022
+ inputs_embeds=inputs_embeds,
1023
+ use_cache=use_cache,
1024
+ output_attentions=output_attentions,
1025
+ output_hidden_states=output_hidden_states,
1026
+ )
1027
+ sequence_output = outputs.last_hidden_state
1028
+ sequence_output = self.dropout(sequence_output)
1029
+ logits = self.score(sequence_output)
1030
+
1031
+ loss = None
1032
+ if labels is not None:
1033
+ loss = self.loss_function(logits, labels, self.config)
1034
+
1035
+ return TokenClassifierOutput(
1036
+ loss=loss,
1037
+ logits=logits,
1038
+ hidden_states=outputs.hidden_states,
1039
+ attentions=outputs.attentions,
1040
+ )
1041
+
1042
+
1043
+ @auto_docstring
1044
+ class Qwen3ForQuestionAnswering(Qwen3PreTrainedModel):
1045
+ base_model_prefix = "transformer"
1046
+
1047
+ def __init__(self, config):
1048
+ super().__init__(config)
1049
+ self.transformer = Qwen3Model(config)
1050
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1051
+
1052
+ # Initialize weights and apply final processing
1053
+ self.post_init()
1054
+
1055
+ def get_input_embeddings(self):
1056
+ return self.transformer.embed_tokens
1057
+
1058
+ def set_input_embeddings(self, value):
1059
+ self.transformer.embed_tokens = value
1060
+
1061
+ @can_return_tuple
1062
+ @auto_docstring
1063
+ def forward(
1064
+ self,
1065
+ input_ids: Optional[torch.LongTensor] = None,
1066
+ attention_mask: Optional[torch.Tensor] = None,
1067
+ position_ids: Optional[torch.LongTensor] = None,
1068
+ past_key_values: Optional[Cache] = None,
1069
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1070
+ start_positions: Optional[torch.LongTensor] = None,
1071
+ end_positions: Optional[torch.LongTensor] = None,
1072
+ output_attentions: Optional[bool] = None,
1073
+ output_hidden_states: Optional[bool] = None,
1074
+ **kwargs,
1075
+ ) -> QuestionAnsweringModelOutput:
1076
+ outputs: BaseModelOutputWithPast = self.transformer(
1077
+ input_ids,
1078
+ attention_mask=attention_mask,
1079
+ position_ids=position_ids,
1080
+ past_key_values=past_key_values,
1081
+ inputs_embeds=inputs_embeds,
1082
+ output_attentions=output_attentions,
1083
+ output_hidden_states=output_hidden_states,
1084
+ )
1085
+
1086
+ sequence_output = outputs.last_hidden_state
1087
+
1088
+ logits = self.qa_outputs(sequence_output)
1089
+ start_logits, end_logits = logits.split(1, dim=-1)
1090
+ start_logits = start_logits.squeeze(-1).contiguous()
1091
+ end_logits = end_logits.squeeze(-1).contiguous()
1092
+
1093
+ loss = None
1094
+ if start_positions is not None and end_positions is not None:
1095
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1096
+
1097
+ return QuestionAnsweringModelOutput(
1098
+ loss=loss,
1099
+ start_logits=start_logits,
1100
+ end_logits=end_logits,
1101
+ hidden_states=outputs.hidden_states,
1102
+ attentions=outputs.attentions,
1103
+ )
1104
+
1105
+
1106
+ class Qwen3DiffusionLM(Qwen3ForCausalLM):
1107
+ def __init__(self, config):
1108
+ super().__init__(config)
1109
+ self.mask_token_id = 151662 # [MASK] token ID
1110
+
1111
+ def forward_process(self, input_ids, eps=1e-3):
1112
+ b, l = input_ids.shape
1113
+ t = torch.rand(b, device=input_ids.device)
1114
+ p_mask = (1 - eps) * t + eps
1115
+ p_mask = p_mask[:, None].repeat(1, l)
1116
+
1117
+ # Generate masked indices
1118
+ masked_indices = torch.rand((b, l), device=input_ids.device) < p_mask
1119
+
1120
+ noisy_batch = torch.where(masked_indices, self.mask_token_id, input_ids)
1121
+
1122
+ return noisy_batch, masked_indices, p_mask
1123
+
1124
+ @can_return_tuple
1125
+ @auto_docstring
1126
+ def forward(
1127
+ self,
1128
+ input_ids: Optional[torch.LongTensor] = None,
1129
+ attention_mask: Optional[torch.Tensor] = None,
1130
+ position_ids: Optional[torch.LongTensor] = None,
1131
+ past_key_values: Optional[Cache] = None,
1132
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1133
+ labels: Optional[torch.LongTensor] = None,
1134
+ use_cache: Optional[bool] = None,
1135
+ output_attentions: Optional[bool] = None,
1136
+ output_hidden_states: Optional[bool] = None,
1137
+ cache_position: Optional[torch.LongTensor] = None,
1138
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1139
+ replace_position: Optional[torch.Tensor] = None,
1140
+ eps: float = 1e-3,
1141
+ **kwargs: Unpack[KwargsForCausalLM],
1142
+ ) -> CausalLMOutputWithPast:
1143
+ # Apply random length truncation with 1% probability
1144
+ # if torch.rand(1) < 0.01:
1145
+ # random_length = torch.randint(1, input_ids.shape[1] + 1, (1,))
1146
+ # input_ids = input_ids[:, :random_length]
1147
+ # if attention_mask is not None:
1148
+ # attention_mask = attention_mask[:, :random_length]
1149
+
1150
+ # Apply forward process for diffusion with shifted masking
1151
+
1152
+ if labels is not None:
1153
+ if self.config.random_length_prob is not None:
1154
+ if torch.rand(1) < self.config.random_length_prob:
1155
+ random_length = torch.randint(2, input_ids.shape[1] + 1, (1,))
1156
+ input_ids = input_ids[:, :random_length]
1157
+ labels = labels[:, :random_length]
1158
+
1159
+ if attention_mask is not None:
1160
+ attention_mask = attention_mask[:, :random_length]
1161
+ if position_ids is not None:
1162
+ position_ids = position_ids[:, :random_length]
1163
+
1164
+ noisy_batch, masked_indices, p_mask = self.forward_process(input_ids, eps)
1165
+ else:
1166
+ noisy_batch = input_ids
1167
+ masked_indices = None
1168
+ p_mask = None
1169
+
1170
+ # Get model outputs
1171
+ outputs: BaseModelOutputWithPast = self.model(
1172
+ input_ids=noisy_batch,
1173
+ attention_mask=attention_mask,
1174
+ position_ids=position_ids,
1175
+ past_key_values=past_key_values,
1176
+ inputs_embeds=inputs_embeds,
1177
+ use_cache=use_cache,
1178
+ output_attentions=output_attentions,
1179
+ output_hidden_states=output_hidden_states,
1180
+ cache_position=cache_position,
1181
+ replace_position=replace_position,
1182
+ **kwargs,
1183
+ )
1184
+
1185
+ hidden_states = outputs.last_hidden_state
1186
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1187
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1188
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1189
+
1190
+ loss = None
1191
+ if labels is not None:
1192
+ if self.config.dlm_type == 'dream':
1193
+ logits = logits[..., :-1, :].contiguous()
1194
+ labels = labels[..., 1:].contiguous()
1195
+ masked_indices = masked_indices[:, 1:]
1196
+ p_mask = p_mask[:, 1:]
1197
+
1198
+ # Calculate token-wise cross entropy loss for masked positions
1199
+ token_loss = torch.nn.functional.cross_entropy(
1200
+ logits[masked_indices],
1201
+ labels[masked_indices],
1202
+ reduction='none'
1203
+ ) / p_mask[masked_indices]
1204
+
1205
+ # Average loss over masked tokens only
1206
+ loss = token_loss.sum() / masked_indices.sum()
1207
+
1208
+ # loss = None
1209
+ # if labels is not None:
1210
+ # loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1211
+
1212
+ return CausalLMOutputWithPast(
1213
+ loss=loss,
1214
+ logits=logits,
1215
+ past_key_values=outputs.past_key_values,
1216
+ hidden_states=outputs.hidden_states,
1217
+ attentions=outputs.attentions,
1218
+ )
1219
+
1220
+
1221
+ __all__ = [
1222
+ "Qwen3ForCausalLM",
1223
+ "Qwen3ForQuestionAnswering",
1224
+ "Qwen3Model",
1225
+ "Qwen3PreTrainedModel",
1226
+ "Qwen3ForSequenceClassification",
1227
+ "Qwen3ForTokenClassification",
1228
+ "Qwen3DiffusionLM",
1229
+ ]