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