mzbac commited on
Commit
28d16e0
·
verified ·
1 Parent(s): bc94e9e

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. configuration_qwen2.py +148 -0
  2. modeling_qwen2.py +1475 -0
configuration_qwen2.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ """ Qwen2 model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "Qwen/Qwen2-7B-beta": "https://huggingface.co/Qwen/Qwen2-7B-beta/resolve/main/config.json",
25
+ }
26
+
27
+
28
+ class Qwen2Config(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
31
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
32
+ with the defaults will yield a similar configuration to that of
33
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 151936):
41
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`Qwen2Model`]
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 22016):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ num_key_value_heads (`int`, *optional*, defaults to 32):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
61
+ The maximum sequence length that this model might ever be used with.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
70
+ Whether the model's input and output word embeddings should be tied.
71
+ rope_theta (`float`, *optional*, defaults to 10000.0):
72
+ The base period of the RoPE embeddings.
73
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
74
+ Whether to use sliding window attention.
75
+ sliding_window (`int`, *optional*, defaults to 4096):
76
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
77
+ max_window_layers (`int`, *optional*, defaults to 28):
78
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
79
+ attention_dropout (`float`, *optional*, defaults to 0.0):
80
+ The dropout ratio for the attention probabilities.
81
+
82
+ ```python
83
+ >>> from transformers import Qwen2Model, Qwen2Config
84
+
85
+ >>> # Initializing a Qwen2 style configuration
86
+ >>> configuration = Qwen2Config()
87
+
88
+ >>> # Initializing a model from the Qwen2-7B style configuration
89
+ >>> model = Qwen2Model(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+ ```"""
94
+
95
+ model_type = "qwen2moe"
96
+ keys_to_ignore_at_inference = ["past_key_values"]
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=151936,
101
+ hidden_size=4096,
102
+ intermediate_size=22016,
103
+ num_hidden_layers=32,
104
+ num_attention_heads=32,
105
+ num_key_value_heads=32,
106
+ hidden_act="silu",
107
+ max_position_embeddings=32768,
108
+ initializer_range=0.02,
109
+ rms_norm_eps=1e-6,
110
+ use_cache=True,
111
+ tie_word_embeddings=False,
112
+ rope_theta=10000.0,
113
+ use_sliding_window=False,
114
+ sliding_window=4096,
115
+ max_window_layers=28,
116
+ attention_dropout=0.0,
117
+ num_local_experts= 3,
118
+ num_experts_per_tok= 2,
119
+ **kwargs,
120
+ ):
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.use_sliding_window = use_sliding_window
128
+ self.sliding_window = sliding_window
129
+ self.max_window_layers = max_window_layers
130
+
131
+ # for backward compatibility
132
+ if num_key_value_heads is None:
133
+ num_key_value_heads = num_attention_heads
134
+
135
+ self.num_key_value_heads = num_key_value_heads
136
+ self.hidden_act = hidden_act
137
+ self.initializer_range = initializer_range
138
+ self.rms_norm_eps = rms_norm_eps
139
+ self.use_cache = use_cache
140
+ self.rope_theta = rope_theta
141
+ self.attention_dropout = attention_dropout
142
+ self.num_local_experts =num_local_experts
143
+ self.num_experts_per_tok = num_experts_per_tok
144
+
145
+ super().__init__(
146
+ tie_word_embeddings=tie_word_embeddings,
147
+ **kwargs,
148
+ )
modeling_qwen2.py ADDED
@@ -0,0 +1,1475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Qwen2 model."""
21
+ import inspect
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from .configuration_qwen2 import Qwen2Config
46
+
47
+
48
+ if is_flash_attn_2_available():
49
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
50
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
51
+
52
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
59
+ _CONFIG_FOR_DOC = "Qwen2Config"
60
+
61
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
62
+ "Qwen/Qwen2-7B-beta",
63
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
64
+ ]
65
+
66
+
67
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
68
+ def _get_unpad_data(attention_mask):
69
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
70
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
71
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
72
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
73
+ return (
74
+ indices,
75
+ cu_seqlens,
76
+ max_seqlen_in_batch,
77
+ )
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
81
+ class Qwen2RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Qwen2RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
99
+ class Qwen2RotaryEmbedding(nn.Module):
100
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
101
+ super().__init__()
102
+
103
+ self.dim = dim
104
+ self.max_position_embeddings = max_position_embeddings
105
+ self.base = base
106
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
107
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
108
+
109
+ # Build here to make `torch.jit.trace` work.
110
+ self._set_cos_sin_cache(
111
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
112
+ )
113
+
114
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
115
+ self.max_seq_len_cached = seq_len
116
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
117
+
118
+ freqs = torch.outer(t, self.inv_freq)
119
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
120
+ emb = torch.cat((freqs, freqs), dim=-1)
121
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
122
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
123
+
124
+ def forward(self, x, seq_len=None):
125
+ # x: [bs, num_attention_heads, seq_len, head_size]
126
+ if seq_len > self.max_seq_len_cached:
127
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
128
+
129
+ return (
130
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
131
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
132
+ )
133
+
134
+
135
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
136
+ def rotate_half(x):
137
+ """Rotates half the hidden dims of the input."""
138
+ x1 = x[..., : x.shape[-1] // 2]
139
+ x2 = x[..., x.shape[-1] // 2 :]
140
+ return torch.cat((-x2, x1), dim=-1)
141
+
142
+
143
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
144
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
145
+ """Applies Rotary Position Embedding to the query and key tensors.
146
+
147
+ Args:
148
+ q (`torch.Tensor`): The query tensor.
149
+ k (`torch.Tensor`): The key tensor.
150
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
151
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
152
+ position_ids (`torch.Tensor`):
153
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
154
+ used to pass offsetted position ids when working with a KV-cache.
155
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
156
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
157
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
158
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
159
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
160
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
161
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
162
+ Returns:
163
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
164
+ """
165
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
166
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
167
+ q_embed = (q * cos) + (rotate_half(q) * sin)
168
+ k_embed = (k * cos) + (rotate_half(k) * sin)
169
+ return q_embed, k_embed
170
+
171
+
172
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
173
+ class Qwen2MLP(nn.Module):
174
+ def __init__(self, config):
175
+ super().__init__()
176
+ self.config = config
177
+ self.hidden_size = config.hidden_size
178
+ self.intermediate_size = config.intermediate_size
179
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
180
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
181
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
182
+ self.act_fn = ACT2FN[config.hidden_act]
183
+
184
+ def forward(self, x):
185
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
186
+
187
+
188
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
189
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
190
+ """
191
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
192
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
193
+ """
194
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
195
+ if n_rep == 1:
196
+ return hidden_states
197
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
198
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
199
+
200
+
201
+ class Qwen2Attention(nn.Module):
202
+ """
203
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
204
+ and "Generating Long Sequences with Sparse Transformers".
205
+ """
206
+
207
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
208
+ super().__init__()
209
+ self.config = config
210
+ self.layer_idx = layer_idx
211
+ if layer_idx is None:
212
+ logger.warning_once(
213
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
214
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
215
+ "when creating this class."
216
+ )
217
+
218
+ self.hidden_size = config.hidden_size
219
+ self.num_heads = config.num_attention_heads
220
+ self.head_dim = self.hidden_size // self.num_heads
221
+ self.num_key_value_heads = config.num_key_value_heads
222
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
223
+ self.max_position_embeddings = config.max_position_embeddings
224
+ self.rope_theta = config.rope_theta
225
+ self.is_causal = True
226
+ self.attention_dropout = config.attention_dropout
227
+
228
+ if (self.head_dim * self.num_heads) != self.hidden_size:
229
+ raise ValueError(
230
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
231
+ f" and `num_heads`: {self.num_heads})."
232
+ )
233
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
234
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
235
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
236
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
237
+
238
+ self.rotary_emb = Qwen2RotaryEmbedding(
239
+ self.head_dim,
240
+ max_position_embeddings=self.max_position_embeddings,
241
+ base=self.rope_theta,
242
+ )
243
+
244
+ def forward(
245
+ self,
246
+ hidden_states: torch.Tensor,
247
+ attention_mask: Optional[torch.Tensor] = None,
248
+ position_ids: Optional[torch.LongTensor] = None,
249
+ past_key_value: Optional[Cache] = None,
250
+ output_attentions: bool = False,
251
+ use_cache: bool = False,
252
+ **kwargs,
253
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
254
+ if "padding_mask" in kwargs:
255
+ warnings.warn(
256
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
257
+ )
258
+ bsz, q_len, _ = hidden_states.size()
259
+
260
+ query_states = self.q_proj(hidden_states)
261
+ key_states = self.k_proj(hidden_states)
262
+ value_states = self.v_proj(hidden_states)
263
+
264
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
265
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
266
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
267
+
268
+ kv_seq_len = key_states.shape[-2]
269
+ if past_key_value is not None:
270
+ if self.layer_idx is None:
271
+ raise ValueError(
272
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
273
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
274
+ "with a layer index."
275
+ )
276
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
277
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
278
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
279
+
280
+ if past_key_value is not None:
281
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
282
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
283
+
284
+ # repeat k/v heads if n_kv_heads < n_heads
285
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
286
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
287
+
288
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
289
+
290
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
291
+ raise ValueError(
292
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
293
+ f" {attn_weights.size()}"
294
+ )
295
+
296
+ if attention_mask is not None:
297
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
298
+ raise ValueError(
299
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
300
+ )
301
+
302
+ attn_weights = attn_weights + attention_mask
303
+
304
+ # upcast attention to fp32
305
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
306
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
307
+ attn_output = torch.matmul(attn_weights, value_states)
308
+
309
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
310
+ raise ValueError(
311
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
312
+ f" {attn_output.size()}"
313
+ )
314
+
315
+ attn_output = attn_output.transpose(1, 2).contiguous()
316
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
317
+
318
+ attn_output = self.o_proj(attn_output)
319
+
320
+ if not output_attentions:
321
+ attn_weights = None
322
+
323
+ return attn_output, attn_weights, past_key_value
324
+
325
+
326
+ class Qwen2FlashAttention2(Qwen2Attention):
327
+ """
328
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
329
+ as the weights of the module stays untouched. The only required change would be on the forward pass
330
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
331
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
332
+ config.max_window_layers layers.
333
+ """
334
+
335
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
336
+ def __init__(self, *args, **kwargs):
337
+ super().__init__(*args, **kwargs)
338
+
339
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
340
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
341
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
342
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ past_key_value: Optional[Cache] = None,
350
+ output_attentions: bool = False,
351
+ use_cache: bool = False,
352
+ **kwargs,
353
+ ):
354
+ if "padding_mask" in kwargs:
355
+ warnings.warn(
356
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
357
+ )
358
+
359
+ # overwrite attention_mask with padding_mask
360
+ attention_mask = kwargs.pop("padding_mask")
361
+ bsz, q_len, _ = hidden_states.size()
362
+
363
+ query_states = self.q_proj(hidden_states)
364
+ key_states = self.k_proj(hidden_states)
365
+ value_states = self.v_proj(hidden_states)
366
+
367
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
368
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
369
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
370
+
371
+ kv_seq_len = key_states.shape[-2]
372
+ if past_key_value is not None:
373
+ if self.layer_idx is None:
374
+ raise ValueError(
375
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
376
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
377
+ "with a layer index."
378
+ )
379
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
380
+
381
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
382
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
383
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
384
+
385
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
386
+
387
+ use_sliding_windows = (
388
+ _flash_supports_window_size
389
+ and getattr(self.config, "sliding_window", None) is not None
390
+ and kv_seq_len > self.config.sliding_window
391
+ and self.config.use_sliding_window
392
+ )
393
+
394
+ if not _flash_supports_window_size:
395
+ logger.warning_once(
396
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
397
+ " make sure to upgrade flash-attn library."
398
+ )
399
+
400
+ if past_key_value is not None:
401
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
402
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
403
+ if (
404
+ getattr(self.config, "sliding_window", None) is not None
405
+ and kv_seq_len > self.config.sliding_window
406
+ and cache_has_contents
407
+ ):
408
+ slicing_tokens = 1 - self.config.sliding_window
409
+
410
+ past_key = past_key_value[self.layer_idx][0]
411
+ past_value = past_key_value[self.layer_idx][1]
412
+
413
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
414
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
415
+
416
+ if past_key.shape[-2] != self.config.sliding_window - 1:
417
+ raise ValueError(
418
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
419
+ f" {past_key.shape}"
420
+ )
421
+
422
+ if attention_mask is not None:
423
+ attention_mask = attention_mask[:, slicing_tokens:]
424
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
425
+
426
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
427
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
428
+
429
+ # repeat k/v heads if n_kv_heads < n_heads
430
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
431
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
432
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
433
+
434
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
435
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
436
+ # cast them back in float16 just to be sure everything works as expected.
437
+ input_dtype = query_states.dtype
438
+ if input_dtype == torch.float32:
439
+ if torch.is_autocast_enabled():
440
+ target_dtype = torch.get_autocast_gpu_dtype()
441
+ # Handle the case where the model is quantized
442
+ elif hasattr(self.config, "_pre_quantization_dtype"):
443
+ target_dtype = self.config._pre_quantization_dtype
444
+ else:
445
+ target_dtype = self.q_proj.weight.dtype
446
+
447
+ logger.warning_once(
448
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
449
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
450
+ f" {target_dtype}."
451
+ )
452
+
453
+ query_states = query_states.to(target_dtype)
454
+ key_states = key_states.to(target_dtype)
455
+ value_states = value_states.to(target_dtype)
456
+
457
+ # Reashape to the expected shape for Flash Attention
458
+ query_states = query_states.transpose(1, 2)
459
+ key_states = key_states.transpose(1, 2)
460
+ value_states = value_states.transpose(1, 2)
461
+
462
+ attn_output = self._flash_attention_forward(
463
+ query_states,
464
+ key_states,
465
+ value_states,
466
+ attention_mask,
467
+ q_len,
468
+ dropout=dropout_rate,
469
+ use_sliding_windows=use_sliding_windows,
470
+ )
471
+
472
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
473
+ attn_output = self.o_proj(attn_output)
474
+
475
+ if not output_attentions:
476
+ attn_weights = None
477
+
478
+ return attn_output, attn_weights, past_key_value
479
+
480
+ def _flash_attention_forward(
481
+ self,
482
+ query_states,
483
+ key_states,
484
+ value_states,
485
+ attention_mask,
486
+ query_length,
487
+ dropout=0.0,
488
+ softmax_scale=None,
489
+ use_sliding_windows=False,
490
+ ):
491
+ """
492
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
493
+ first unpad the input, then computes the attention scores and pad the final attention scores.
494
+
495
+ Args:
496
+ query_states (`torch.Tensor`):
497
+ Input query states to be passed to Flash Attention API
498
+ key_states (`torch.Tensor`):
499
+ Input key states to be passed to Flash Attention API
500
+ value_states (`torch.Tensor`):
501
+ Input value states to be passed to Flash Attention API
502
+ attention_mask (`torch.Tensor`):
503
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
504
+ position of padding tokens and 1 for the position of non-padding tokens.
505
+ dropout (`int`, *optional*):
506
+ Attention dropout
507
+ softmax_scale (`float`, *optional*):
508
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
509
+ use_sliding_windows (`bool`, *optional*):
510
+ Whether to activate sliding window attention.
511
+ """
512
+ if not self._flash_attn_uses_top_left_mask:
513
+ causal = self.is_causal
514
+ else:
515
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
516
+ causal = self.is_causal and query_length != 1
517
+
518
+ # Decide whether to use SWA or not by layer index.
519
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
520
+ use_sliding_windows = False
521
+
522
+ # Contains at least one padding token in the sequence
523
+ if attention_mask is not None:
524
+ batch_size = query_states.shape[0]
525
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
526
+ query_states, key_states, value_states, attention_mask, query_length
527
+ )
528
+
529
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
530
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
531
+
532
+ if not use_sliding_windows:
533
+ attn_output_unpad = flash_attn_varlen_func(
534
+ query_states,
535
+ key_states,
536
+ value_states,
537
+ cu_seqlens_q=cu_seqlens_q,
538
+ cu_seqlens_k=cu_seqlens_k,
539
+ max_seqlen_q=max_seqlen_in_batch_q,
540
+ max_seqlen_k=max_seqlen_in_batch_k,
541
+ dropout_p=dropout,
542
+ softmax_scale=softmax_scale,
543
+ causal=causal,
544
+ )
545
+ else:
546
+ attn_output_unpad = flash_attn_varlen_func(
547
+ query_states,
548
+ key_states,
549
+ value_states,
550
+ cu_seqlens_q=cu_seqlens_q,
551
+ cu_seqlens_k=cu_seqlens_k,
552
+ max_seqlen_q=max_seqlen_in_batch_q,
553
+ max_seqlen_k=max_seqlen_in_batch_k,
554
+ dropout_p=dropout,
555
+ softmax_scale=softmax_scale,
556
+ causal=causal,
557
+ window_size=(self.config.sliding_window, self.config.sliding_window),
558
+ )
559
+
560
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
561
+ else:
562
+ if not use_sliding_windows:
563
+ attn_output = flash_attn_func(
564
+ query_states,
565
+ key_states,
566
+ value_states,
567
+ dropout,
568
+ softmax_scale=softmax_scale,
569
+ causal=causal,
570
+ )
571
+ else:
572
+ attn_output = flash_attn_func(
573
+ query_states,
574
+ key_states,
575
+ value_states,
576
+ dropout,
577
+ softmax_scale=softmax_scale,
578
+ causal=causal,
579
+ window_size=(self.config.sliding_window, self.config.sliding_window),
580
+ )
581
+
582
+ return attn_output
583
+
584
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
585
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
586
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
587
+
588
+ # On the first iteration we need to properly re-create the padding mask
589
+ # by slicing it on the proper place
590
+ if kv_seq_len != attention_mask.shape[-1]:
591
+ attention_mask_num_tokens = attention_mask.shape[-1]
592
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
593
+
594
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
595
+
596
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
597
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
598
+
599
+ if query_length == kv_seq_len:
600
+ query_layer = index_first_axis(
601
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
602
+ )
603
+ cu_seqlens_q = cu_seqlens_k
604
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
605
+ indices_q = indices_k
606
+ elif query_length == 1:
607
+ max_seqlen_in_batch_q = 1
608
+ cu_seqlens_q = torch.arange(
609
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
610
+ ) # There is a memcpy here, that is very bad.
611
+ indices_q = cu_seqlens_q[:-1]
612
+ query_layer = query_layer.squeeze(1)
613
+ else:
614
+ # The -q_len: slice assumes left padding.
615
+ attention_mask = attention_mask[:, -query_length:]
616
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
617
+
618
+ return (
619
+ query_layer,
620
+ key_layer,
621
+ value_layer,
622
+ indices_q,
623
+ (cu_seqlens_q, cu_seqlens_k),
624
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
625
+ )
626
+
627
+
628
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
629
+ class Qwen2SdpaAttention(Qwen2Attention):
630
+ """
631
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
632
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
633
+ SDPA API.
634
+ """
635
+
636
+ # Adapted from Qwen2Attention.forward
637
+ def forward(
638
+ self,
639
+ hidden_states: torch.Tensor,
640
+ attention_mask: Optional[torch.Tensor] = None,
641
+ position_ids: Optional[torch.LongTensor] = None,
642
+ past_key_value: Optional[Cache] = None,
643
+ output_attentions: bool = False,
644
+ use_cache: bool = False,
645
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
646
+ if output_attentions:
647
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
648
+ logger.warning_once(
649
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
650
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
651
+ )
652
+ return super().forward(
653
+ hidden_states=hidden_states,
654
+ attention_mask=attention_mask,
655
+ position_ids=position_ids,
656
+ past_key_value=past_key_value,
657
+ output_attentions=output_attentions,
658
+ use_cache=use_cache,
659
+ )
660
+
661
+ bsz, q_len, _ = hidden_states.size()
662
+
663
+ query_states = self.q_proj(hidden_states)
664
+ key_states = self.k_proj(hidden_states)
665
+ value_states = self.v_proj(hidden_states)
666
+
667
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
668
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
669
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
670
+
671
+ kv_seq_len = key_states.shape[-2]
672
+ past_key_value = getattr(self, "past_key_value", past_key_value)
673
+ if past_key_value is not None:
674
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) # add what was seen
675
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
676
+
677
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
678
+
679
+ past_seen_tokens = kv_seq_len - key_states.shape[-2]
680
+ new_cache_positions = torch.arange(past_seen_tokens, past_seen_tokens + q_len, device=key_states.device)
681
+ if past_key_value is not None:
682
+ cache_kwargs = {"sin": sin, "cos": cos, "position_ids": new_cache_positions} # Specific to RoPE models
683
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
684
+
685
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
686
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
687
+
688
+ if (
689
+ attention_mask is not None and not torch.all(attention_mask[..., 0] == 1) and q_len != 1
690
+ ): # user defined causal mask
691
+ causal_mask = attention_mask[:, :, past_seen_tokens : past_seen_tokens + q_len, : key_states.shape[-2]]
692
+ # this one liner is equivalent to the pad_unpad function
693
+ causal_mask.mul_(~torch.eq(causal_mask, causal_mask.min()).all(dim=-1)[..., None])
694
+ else:
695
+ causal_mask = None
696
+
697
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
698
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
699
+ if query_states.device.type == "cuda" and causal_mask is not None:
700
+ query_states = query_states.contiguous()
701
+ key_states = key_states.contiguous()
702
+ value_states = value_states.contiguous()
703
+
704
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
705
+ query_states,
706
+ key_states,
707
+ value_states,
708
+ attn_mask=causal_mask,
709
+ dropout_p=self.attention_dropout if self.training else 0.0,
710
+ is_causal=causal_mask is None and q_len > 1,
711
+ )
712
+
713
+ attn_output = attn_output.transpose(1, 2).contiguous()
714
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
715
+
716
+ attn_output = self.o_proj(attn_output)
717
+
718
+ return attn_output, None, past_key_value
719
+
720
+
721
+ QWEN2_ATTENTION_CLASSES = {
722
+ "eager": Qwen2Attention,
723
+ "flash_attention_2": Qwen2FlashAttention2,
724
+ "sdpa": Qwen2SdpaAttention,
725
+ }
726
+
727
+ class SparseMoeBlock(nn.Module):
728
+ """
729
+ This implementation is
730
+ strictly equivalent to standard MoE with full capacity (no
731
+ dropped tokens). It's faster since it formulates MoE operations
732
+ in terms of block-sparse operations to accomodate imbalanced
733
+ assignments of tokens to experts, whereas standard MoE either
734
+ (1) drop tokens at the cost of reduced performance or (2) set
735
+ capacity factor to number of experts and thus waste computation
736
+ and memory on padding.
737
+ """
738
+
739
+ def __init__(self, config):
740
+ super().__init__()
741
+ self.hidden_dim = config.hidden_size
742
+ self.ffn_dim = config.intermediate_size
743
+ self.num_experts = config.num_local_experts
744
+ self.top_k = config.num_experts_per_tok
745
+
746
+ # gating
747
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
748
+
749
+ self.experts = nn.ModuleList([Qwen2MLP(config) for _ in range(self.num_experts)])
750
+
751
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
752
+ """ """
753
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
754
+ hidden_states = hidden_states.view(-1, hidden_dim)
755
+ # router_logits: (batch * sequence_length, n_experts)
756
+ router_logits = self.gate(hidden_states)
757
+
758
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
759
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
760
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
761
+ # we cast back to the input dtype
762
+ routing_weights = routing_weights.to(hidden_states.dtype)
763
+
764
+ final_hidden_states = torch.zeros(
765
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
766
+ )
767
+
768
+ # One hot encode the selected experts to create an expert mask
769
+ # this will be used to easily index which expert is going to be sollicitated
770
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
771
+
772
+ # Loop over all available experts in the model and perform the computation on each expert
773
+ for expert_idx in range(self.num_experts):
774
+ expert_layer = self.experts[expert_idx]
775
+ idx, top_x = torch.where(expert_mask[expert_idx])
776
+
777
+ if top_x.shape[0] == 0:
778
+ continue
779
+
780
+ # in torch it is faster to index using lists than torch tensors
781
+ top_x_list = top_x.tolist()
782
+ idx_list = idx.tolist()
783
+
784
+ # Index the correct hidden states and compute the expert hidden state for
785
+ # the current expert. We need to make sure to multiply the output hidden
786
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
787
+ current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim)
788
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None]
789
+
790
+ # However `index_add_` only support torch tensors for indexing so we'll use
791
+ # the `top_x` tensor here.
792
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
793
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
794
+ return final_hidden_states, router_logits
795
+
796
+ class Qwen2DecoderLayer(nn.Module):
797
+ def __init__(self, config: Qwen2Config, layer_idx: int):
798
+ super().__init__()
799
+ self.hidden_size = config.hidden_size
800
+
801
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
802
+ logger.warning_once(
803
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
804
+ "unexpected results may be encountered."
805
+ )
806
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
807
+
808
+ self.block_sparse_moe = SparseMoeBlock(config)
809
+
810
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
811
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
812
+
813
+ def forward(
814
+ self,
815
+ hidden_states: torch.Tensor,
816
+ attention_mask: Optional[torch.Tensor] = None,
817
+ position_ids: Optional[torch.LongTensor] = None,
818
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
819
+ output_attentions: Optional[bool] = False,
820
+ use_cache: Optional[bool] = False,
821
+ **kwargs,
822
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
823
+ if "padding_mask" in kwargs:
824
+ warnings.warn(
825
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
826
+ "Please make sure use `attention_mask` instead.`"
827
+ )
828
+ """
829
+ Args:
830
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
831
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
832
+ `(batch, sequence_length)` where padding elements are indicated by 0.
833
+ output_attentions (`bool`, *optional*):
834
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
835
+ returned tensors for more detail.
836
+ use_cache (`bool`, *optional*):
837
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
838
+ (see `past_key_values`).
839
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
840
+ """
841
+
842
+ residual = hidden_states
843
+
844
+ hidden_states = self.input_layernorm(hidden_states)
845
+
846
+ # Self Attention
847
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
848
+ hidden_states=hidden_states,
849
+ attention_mask=attention_mask,
850
+ position_ids=position_ids,
851
+ past_key_value=past_key_value,
852
+ output_attentions=output_attentions,
853
+ use_cache=use_cache,
854
+ )
855
+ hidden_states = residual + hidden_states
856
+
857
+ # Fully Connected
858
+ residual = hidden_states
859
+ hidden_states = self.post_attention_layernorm(hidden_states)
860
+ hidden_states,_ = self.block_sparse_moe(hidden_states)
861
+ hidden_states = residual + hidden_states
862
+
863
+ outputs = (hidden_states,)
864
+
865
+ if output_attentions:
866
+ outputs += (self_attn_weights,)
867
+
868
+ if use_cache:
869
+ outputs += (present_key_value,)
870
+
871
+ return outputs
872
+
873
+
874
+ QWEN2_START_DOCSTRING = r"""
875
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
876
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
877
+ etc.)
878
+
879
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
880
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
881
+ and behavior.
882
+
883
+ Parameters:
884
+ config ([`Qwen2Config`]):
885
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
886
+ load the weights associated with the model, only the configuration. Check out the
887
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
888
+ """
889
+
890
+
891
+ @add_start_docstrings(
892
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
893
+ QWEN2_START_DOCSTRING,
894
+ )
895
+ class Qwen2PreTrainedModel(PreTrainedModel):
896
+ config_class = Qwen2Config
897
+ base_model_prefix = "model"
898
+ supports_gradient_checkpointing = True
899
+ _no_split_modules = ["Qwen2DecoderLayer"]
900
+ _skip_keys_device_placement = "past_key_values"
901
+ _supports_flash_attn_2 = True
902
+ _supports_sdpa = True
903
+ _supports_cache_class = True
904
+
905
+ def _init_weights(self, module):
906
+ std = self.config.initializer_range
907
+ if isinstance(module, nn.Linear):
908
+ module.weight.data.normal_(mean=0.0, std=std)
909
+ if module.bias is not None:
910
+ module.bias.data.zero_()
911
+ elif isinstance(module, nn.Embedding):
912
+ module.weight.data.normal_(mean=0.0, std=std)
913
+ if module.padding_idx is not None:
914
+ module.weight.data[module.padding_idx].zero_()
915
+
916
+
917
+ QWEN2_INPUTS_DOCSTRING = r"""
918
+ Args:
919
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
920
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
921
+ it.
922
+
923
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
924
+ [`PreTrainedTokenizer.__call__`] for details.
925
+
926
+ [What are input IDs?](../glossary#input-ids)
927
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
928
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
929
+
930
+ - 1 for tokens that are **not masked**,
931
+ - 0 for tokens that are **masked**.
932
+
933
+ [What are attention masks?](../glossary#attention-mask)
934
+
935
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
936
+ [`PreTrainedTokenizer.__call__`] for details.
937
+
938
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
939
+ `past_key_values`).
940
+
941
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
942
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
943
+ information on the default strategy.
944
+
945
+ - 1 indicates the head is **not masked**,
946
+ - 0 indicates the head is **masked**.
947
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
948
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
949
+ config.n_positions - 1]`.
950
+
951
+ [What are position IDs?](../glossary#position-ids)
952
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
953
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
954
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
955
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
956
+
957
+ Two formats are allowed:
958
+ - a [`~cache_utils.Cache`] instance;
959
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
960
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
961
+ cache format.
962
+
963
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
964
+ legacy cache format will be returned.
965
+
966
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
967
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
968
+ of shape `(batch_size, sequence_length)`.
969
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
970
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
971
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
972
+ model's internal embedding lookup matrix.
973
+ use_cache (`bool`, *optional*):
974
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
975
+ `past_key_values`).
976
+ output_attentions (`bool`, *optional*):
977
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
978
+ tensors for more detail.
979
+ output_hidden_states (`bool`, *optional*):
980
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
981
+ more detail.
982
+ return_dict (`bool`, *optional*):
983
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
984
+ """
985
+
986
+
987
+ @add_start_docstrings(
988
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
989
+ QWEN2_START_DOCSTRING,
990
+ )
991
+ class Qwen2Model(Qwen2PreTrainedModel):
992
+ """
993
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
994
+
995
+ Args:
996
+ config: Qwen2Config
997
+ """
998
+
999
+ def __init__(self, config: Qwen2Config):
1000
+ super().__init__(config)
1001
+ self.padding_idx = config.pad_token_id
1002
+ self.vocab_size = config.vocab_size
1003
+
1004
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1005
+ self.layers = nn.ModuleList(
1006
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1007
+ )
1008
+ self._attn_implementation = config._attn_implementation
1009
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1010
+
1011
+ self.gradient_checkpointing = False
1012
+ # Initialize weights and apply final processing
1013
+ self.post_init()
1014
+
1015
+ def get_input_embeddings(self):
1016
+ return self.embed_tokens
1017
+
1018
+ def set_input_embeddings(self, value):
1019
+ self.embed_tokens = value
1020
+
1021
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1022
+ def forward(
1023
+ self,
1024
+ input_ids: torch.LongTensor = None,
1025
+ attention_mask: Optional[torch.Tensor] = None,
1026
+ position_ids: Optional[torch.LongTensor] = None,
1027
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1028
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1029
+ use_cache: Optional[bool] = None,
1030
+ output_attentions: Optional[bool] = None,
1031
+ output_hidden_states: Optional[bool] = None,
1032
+ return_dict: Optional[bool] = None,
1033
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1034
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1035
+ output_hidden_states = (
1036
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1037
+ )
1038
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1039
+
1040
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1041
+
1042
+ # retrieve input_ids and inputs_embeds
1043
+ if input_ids is not None and inputs_embeds is not None:
1044
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1045
+ elif input_ids is not None:
1046
+ batch_size, seq_length = input_ids.shape
1047
+ elif inputs_embeds is not None:
1048
+ batch_size, seq_length, _ = inputs_embeds.shape
1049
+ else:
1050
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1051
+
1052
+ if self.gradient_checkpointing and self.training:
1053
+ if use_cache:
1054
+ logger.warning_once(
1055
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1056
+ )
1057
+ use_cache = False
1058
+
1059
+ past_key_values_length = 0
1060
+
1061
+ if use_cache:
1062
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1063
+ if use_legacy_cache:
1064
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1065
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1066
+
1067
+ if position_ids is None:
1068
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1069
+ position_ids = torch.arange(
1070
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1071
+ )
1072
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1073
+ else:
1074
+ position_ids = position_ids.view(-1, seq_length).long()
1075
+
1076
+ if inputs_embeds is None:
1077
+ inputs_embeds = self.embed_tokens(input_ids)
1078
+
1079
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1080
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1081
+ if is_padding_right:
1082
+ raise ValueError(
1083
+ "You are attempting to perform batched generation with padding_side='right'"
1084
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1085
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1086
+ )
1087
+
1088
+ if self._attn_implementation == "flash_attention_2":
1089
+ # 2d mask is passed through the layers
1090
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1091
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1092
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1093
+ # the manual implementation that requires a 4D causal mask in all cases.
1094
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1095
+ attention_mask,
1096
+ (batch_size, seq_length),
1097
+ inputs_embeds,
1098
+ past_key_values_length,
1099
+ )
1100
+ else:
1101
+ # 4d mask is passed through the layers
1102
+ attention_mask = _prepare_4d_causal_attention_mask(
1103
+ attention_mask,
1104
+ (batch_size, seq_length),
1105
+ inputs_embeds,
1106
+ past_key_values_length,
1107
+ sliding_window=self.config.sliding_window,
1108
+ )
1109
+
1110
+ hidden_states = inputs_embeds
1111
+
1112
+ # decoder layers
1113
+ all_hidden_states = () if output_hidden_states else None
1114
+ all_self_attns = () if output_attentions else None
1115
+ next_decoder_cache = None
1116
+
1117
+ for decoder_layer in self.layers:
1118
+ if output_hidden_states:
1119
+ all_hidden_states += (hidden_states,)
1120
+
1121
+ if self.gradient_checkpointing and self.training:
1122
+ layer_outputs = self._gradient_checkpointing_func(
1123
+ decoder_layer.__call__,
1124
+ hidden_states,
1125
+ attention_mask,
1126
+ position_ids,
1127
+ past_key_values,
1128
+ output_attentions,
1129
+ use_cache,
1130
+ )
1131
+ else:
1132
+ layer_outputs = decoder_layer(
1133
+ hidden_states,
1134
+ attention_mask=attention_mask,
1135
+ position_ids=position_ids,
1136
+ past_key_value=past_key_values,
1137
+ output_attentions=output_attentions,
1138
+ use_cache=use_cache,
1139
+ )
1140
+
1141
+ hidden_states = layer_outputs[0]
1142
+
1143
+ if use_cache:
1144
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1145
+
1146
+ if output_attentions:
1147
+ all_self_attns += (layer_outputs[1],)
1148
+
1149
+ hidden_states = self.norm(hidden_states)
1150
+
1151
+ # add hidden states from the last decoder layer
1152
+ if output_hidden_states:
1153
+ all_hidden_states += (hidden_states,)
1154
+
1155
+ next_cache = None
1156
+ if use_cache:
1157
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1158
+
1159
+ if not return_dict:
1160
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1161
+ return BaseModelOutputWithPast(
1162
+ last_hidden_state=hidden_states,
1163
+ past_key_values=next_cache,
1164
+ hidden_states=all_hidden_states,
1165
+ attentions=all_self_attns,
1166
+ )
1167
+
1168
+
1169
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1170
+ _tied_weights_keys = ["lm_head.weight"]
1171
+
1172
+ def __init__(self, config):
1173
+ super().__init__(config)
1174
+ self.model = Qwen2Model(config)
1175
+ self.vocab_size = config.vocab_size
1176
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1177
+
1178
+ # Initialize weights and apply final processing
1179
+ self.post_init()
1180
+
1181
+ def get_input_embeddings(self):
1182
+ return self.model.embed_tokens
1183
+
1184
+ def set_input_embeddings(self, value):
1185
+ self.model.embed_tokens = value
1186
+
1187
+ def get_output_embeddings(self):
1188
+ return self.lm_head
1189
+
1190
+ def set_output_embeddings(self, new_embeddings):
1191
+ self.lm_head = new_embeddings
1192
+
1193
+ def set_decoder(self, decoder):
1194
+ self.model = decoder
1195
+
1196
+ def get_decoder(self):
1197
+ return self.model
1198
+
1199
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1200
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1201
+ def forward(
1202
+ self,
1203
+ input_ids: torch.LongTensor = None,
1204
+ attention_mask: Optional[torch.Tensor] = None,
1205
+ position_ids: Optional[torch.LongTensor] = None,
1206
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1207
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1208
+ labels: Optional[torch.LongTensor] = None,
1209
+ use_cache: Optional[bool] = None,
1210
+ output_attentions: Optional[bool] = None,
1211
+ output_hidden_states: Optional[bool] = None,
1212
+ return_dict: Optional[bool] = None,
1213
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1214
+ r"""
1215
+ Args:
1216
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1217
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1218
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1219
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1220
+
1221
+ Returns:
1222
+
1223
+ Example:
1224
+
1225
+ ```python
1226
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1227
+
1228
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1229
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1230
+
1231
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1232
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1233
+
1234
+ >>> # Generate
1235
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1236
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1237
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1238
+ ```"""
1239
+
1240
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1241
+ output_hidden_states = (
1242
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1243
+ )
1244
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1245
+
1246
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1247
+ outputs = self.model(
1248
+ input_ids=input_ids,
1249
+ attention_mask=attention_mask,
1250
+ position_ids=position_ids,
1251
+ past_key_values=past_key_values,
1252
+ inputs_embeds=inputs_embeds,
1253
+ use_cache=use_cache,
1254
+ output_attentions=output_attentions,
1255
+ output_hidden_states=output_hidden_states,
1256
+ return_dict=return_dict,
1257
+ )
1258
+
1259
+ hidden_states = outputs[0]
1260
+ logits = self.lm_head(hidden_states)
1261
+ logits = logits.float()
1262
+
1263
+ loss = None
1264
+ if labels is not None:
1265
+ # Shift so that tokens < n predict n
1266
+ shift_logits = logits[..., :-1, :].contiguous()
1267
+ shift_labels = labels[..., 1:].contiguous()
1268
+ # Flatten the tokens
1269
+ loss_fct = CrossEntropyLoss()
1270
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1271
+ shift_labels = shift_labels.view(-1)
1272
+ # Enable model parallelism
1273
+ shift_labels = shift_labels.to(shift_logits.device)
1274
+ loss = loss_fct(shift_logits, shift_labels)
1275
+
1276
+ if not return_dict:
1277
+ output = (logits,) + outputs[1:]
1278
+ return (loss,) + output if loss is not None else output
1279
+
1280
+ return CausalLMOutputWithPast(
1281
+ loss=loss,
1282
+ logits=logits,
1283
+ past_key_values=outputs.past_key_values,
1284
+ hidden_states=outputs.hidden_states,
1285
+ attentions=outputs.attentions,
1286
+ )
1287
+
1288
+ def prepare_inputs_for_generation(
1289
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1290
+ ):
1291
+ # Omit tokens covered by past_key_values
1292
+ if past_key_values is not None:
1293
+ if isinstance(past_key_values, Cache):
1294
+ cache_length = past_key_values.get_seq_length()
1295
+ past_length = past_key_values.seen_tokens
1296
+ max_cache_length = past_key_values.get_max_length()
1297
+ else:
1298
+ cache_length = past_length = past_key_values[0][0].shape[2]
1299
+ max_cache_length = None
1300
+
1301
+ # Keep only the unprocessed tokens:
1302
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1303
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1304
+ # input)
1305
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1306
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1307
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1308
+ # input_ids based on the past_length.
1309
+ elif past_length < input_ids.shape[1]:
1310
+ input_ids = input_ids[:, past_length:]
1311
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1312
+
1313
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1314
+ if (
1315
+ max_cache_length is not None
1316
+ and attention_mask is not None
1317
+ and cache_length + input_ids.shape[1] > max_cache_length
1318
+ ):
1319
+ attention_mask = attention_mask[:, -max_cache_length:]
1320
+
1321
+ position_ids = kwargs.get("position_ids", None)
1322
+ if attention_mask is not None and position_ids is None:
1323
+ # create position_ids on the fly for batch generation
1324
+ position_ids = attention_mask.long().cumsum(-1) - 1
1325
+ position_ids.masked_fill_(attention_mask == 0, 1)
1326
+ if past_key_values:
1327
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1328
+
1329
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1330
+ if inputs_embeds is not None and past_key_values is None:
1331
+ model_inputs = {"inputs_embeds": inputs_embeds}
1332
+ else:
1333
+ model_inputs = {"input_ids": input_ids}
1334
+
1335
+ model_inputs.update(
1336
+ {
1337
+ "position_ids": position_ids,
1338
+ "past_key_values": past_key_values,
1339
+ "use_cache": kwargs.get("use_cache"),
1340
+ "attention_mask": attention_mask,
1341
+ }
1342
+ )
1343
+ return model_inputs
1344
+
1345
+ @staticmethod
1346
+ def _reorder_cache(past_key_values, beam_idx):
1347
+ reordered_past = ()
1348
+ for layer_past in past_key_values:
1349
+ reordered_past += (
1350
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1351
+ )
1352
+ return reordered_past
1353
+
1354
+
1355
+ @add_start_docstrings(
1356
+ """
1357
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1358
+
1359
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1360
+ (e.g. GPT-2) do.
1361
+
1362
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1363
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1364
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1365
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1366
+ each row of the batch).
1367
+ """,
1368
+ QWEN2_START_DOCSTRING,
1369
+ )
1370
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1371
+ def __init__(self, config):
1372
+ super().__init__(config)
1373
+ self.num_labels = config.num_labels
1374
+ self.model = Qwen2Model(config)
1375
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1376
+
1377
+ # Initialize weights and apply final processing
1378
+ self.post_init()
1379
+
1380
+ def get_input_embeddings(self):
1381
+ return self.model.embed_tokens
1382
+
1383
+ def set_input_embeddings(self, value):
1384
+ self.model.embed_tokens = value
1385
+
1386
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1387
+ def forward(
1388
+ self,
1389
+ input_ids: torch.LongTensor = None,
1390
+ attention_mask: Optional[torch.Tensor] = None,
1391
+ position_ids: Optional[torch.LongTensor] = None,
1392
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1393
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1394
+ labels: Optional[torch.LongTensor] = None,
1395
+ use_cache: Optional[bool] = None,
1396
+ output_attentions: Optional[bool] = None,
1397
+ output_hidden_states: Optional[bool] = None,
1398
+ return_dict: Optional[bool] = None,
1399
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1400
+ r"""
1401
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1402
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1403
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1404
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1405
+ """
1406
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1407
+
1408
+ transformer_outputs = self.model(
1409
+ input_ids,
1410
+ attention_mask=attention_mask,
1411
+ position_ids=position_ids,
1412
+ past_key_values=past_key_values,
1413
+ inputs_embeds=inputs_embeds,
1414
+ use_cache=use_cache,
1415
+ output_attentions=output_attentions,
1416
+ output_hidden_states=output_hidden_states,
1417
+ return_dict=return_dict,
1418
+ )
1419
+ hidden_states = transformer_outputs[0]
1420
+ logits = self.score(hidden_states)
1421
+
1422
+ if input_ids is not None:
1423
+ batch_size = input_ids.shape[0]
1424
+ else:
1425
+ batch_size = inputs_embeds.shape[0]
1426
+
1427
+ if self.config.pad_token_id is None and batch_size != 1:
1428
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1429
+ if self.config.pad_token_id is None:
1430
+ sequence_lengths = -1
1431
+ else:
1432
+ if input_ids is not None:
1433
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1434
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1435
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1436
+ sequence_lengths = sequence_lengths.to(logits.device)
1437
+ else:
1438
+ sequence_lengths = -1
1439
+
1440
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1441
+
1442
+ loss = None
1443
+ if labels is not None:
1444
+ labels = labels.to(logits.device)
1445
+ if self.config.problem_type is None:
1446
+ if self.num_labels == 1:
1447
+ self.config.problem_type = "regression"
1448
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1449
+ self.config.problem_type = "single_label_classification"
1450
+ else:
1451
+ self.config.problem_type = "multi_label_classification"
1452
+
1453
+ if self.config.problem_type == "regression":
1454
+ loss_fct = MSELoss()
1455
+ if self.num_labels == 1:
1456
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1457
+ else:
1458
+ loss = loss_fct(pooled_logits, labels)
1459
+ elif self.config.problem_type == "single_label_classification":
1460
+ loss_fct = CrossEntropyLoss()
1461
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1462
+ elif self.config.problem_type == "multi_label_classification":
1463
+ loss_fct = BCEWithLogitsLoss()
1464
+ loss = loss_fct(pooled_logits, labels)
1465
+ if not return_dict:
1466
+ output = (pooled_logits,) + transformer_outputs[1:]
1467
+ return ((loss,) + output) if loss is not None else output
1468
+
1469
+ return SequenceClassifierOutputWithPast(
1470
+ loss=loss,
1471
+ logits=pooled_logits,
1472
+ past_key_values=transformer_outputs.past_key_values,
1473
+ hidden_states=transformer_outputs.hidden_states,
1474
+ attentions=transformer_outputs.attentions,
1475
+ )