YuPeng0214 commited on
Commit
9b2eccf
·
verified ·
1 Parent(s): 9a6e6ae

Upload modeling_qzhou_v2.py

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