yizaochen commited on
Commit
99a7cd2
·
verified ·
1 Parent(s): 46632b0

Add modeling_deepseekv2.py with multi-image support

Browse files
Files changed (1) hide show
  1. modeling_deepseekv2.py +1996 -0
modeling_deepseekv2.py ADDED
@@ -0,0 +1,1996 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI 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 DeepSeek model and compatible with both DeepSeekV2 and DeepSeekV3"""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+ import numpy as np
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ import torch.distributed as dist
30
+ from einops import repeat
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 _prepare_4d_causal_attention_mask
37
+ try:
38
+ from transformers.models.llama.modeling_llama import LlamaAttention
39
+ except:
40
+ LlamaAttention = None
41
+ try:
42
+ from transformers.models.llama.modeling_llama import LlamaFlashAttention2
43
+ except:
44
+ LlamaFlashAttention2 = None
45
+ from transformers.modeling_outputs import (
46
+ BaseModelOutputWithPast,
47
+ CausalLMOutputWithPast,
48
+ SequenceClassifierOutputWithPast,
49
+ )
50
+ from transformers.modeling_utils import PreTrainedModel
51
+ from transformers.pytorch_utils import (
52
+ ALL_LAYERNORM_LAYERS,
53
+ is_torch_greater_or_equal_than_1_13,
54
+ )
55
+ from transformers.utils import (
56
+ add_start_docstrings,
57
+ add_start_docstrings_to_model_forward,
58
+ is_flash_attn_2_available,
59
+ is_flash_attn_greater_or_equal_2_10,
60
+ logging,
61
+ replace_return_docstrings,
62
+ )
63
+ from transformers.utils.import_utils import is_torch_fx_available
64
+
65
+ from .configuration_deepseek_v2 import DeepseekV2Config
66
+
67
+ if is_flash_attn_2_available():
68
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
69
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
70
+
71
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
72
+ # It means that the function will not be traced through and simply appear as a node in the graph.
73
+ if is_torch_fx_available():
74
+ if not is_torch_greater_or_equal_than_1_13:
75
+ import torch.fx
76
+
77
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
78
+
79
+ logger = logging.get_logger(__name__)
80
+
81
+ _CONFIG_FOR_DOC = "DeepseekV2Config"
82
+
83
+
84
+ def _get_unpad_data(attention_mask):
85
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
86
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
87
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
88
+ cu_seqlens = F.pad(
89
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
90
+ )
91
+ return (
92
+ indices,
93
+ cu_seqlens,
94
+ max_seqlen_in_batch,
95
+ )
96
+
97
+
98
+ class DeepseekV2RMSNorm(nn.Module):
99
+ def __init__(self, hidden_size, eps=1e-6):
100
+ """
101
+ DeepseekV2RMSNorm is equivalent to T5LayerNorm
102
+ """
103
+ super().__init__()
104
+ self.weight = nn.Parameter(torch.ones(hidden_size))
105
+ self.variance_epsilon = eps
106
+
107
+ def forward(self, hidden_states):
108
+ input_dtype = hidden_states.dtype
109
+ hidden_states = hidden_states.to(torch.float32)
110
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
111
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
112
+ return self.weight * hidden_states.to(input_dtype)
113
+
114
+
115
+ ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
116
+
117
+
118
+
119
+
120
+ class DeepseekV2RotaryEmbedding(nn.Module):
121
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
122
+ super().__init__()
123
+
124
+ self.dim = dim
125
+ self.max_position_embeddings = max_position_embeddings
126
+ self.base = base
127
+ inv_freq = 1.0 / (
128
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
129
+ )
130
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
131
+
132
+ # Build here to make `torch.jit.trace` work.
133
+ self._set_cos_sin_cache(
134
+ seq_len=max_position_embeddings,
135
+ device=self.inv_freq.device,
136
+ dtype=torch.get_default_dtype(),
137
+ )
138
+ self.max_seq_len_cached = None
139
+
140
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
141
+ self.max_seq_len_cached = seq_len
142
+ t = torch.arange(
143
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
144
+ )
145
+
146
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
150
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
151
+
152
+ def forward(self, x, seq_len=None):
153
+ # x: [bs, num_attention_heads, seq_len, head_size]
154
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
155
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
156
+
157
+ return (
158
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
159
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
160
+ )
161
+
162
+
163
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
164
+ class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
165
+ """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
166
+
167
+ def __init__(
168
+ self,
169
+ dim,
170
+ max_position_embeddings=2048,
171
+ base=10000,
172
+ device=None,
173
+ scaling_factor=1.0,
174
+ ):
175
+ self.scaling_factor = scaling_factor
176
+ super().__init__(dim, max_position_embeddings, base, device)
177
+
178
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
179
+ self.max_seq_len_cached = seq_len
180
+ t = torch.arange(
181
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
182
+ )
183
+ t = t / self.scaling_factor
184
+
185
+ freqs = torch.outer(t, self.inv_freq)
186
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
187
+ emb = torch.cat((freqs, freqs), dim=-1)
188
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
189
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
190
+
191
+
192
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
193
+ class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
194
+ """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
195
+
196
+ def __init__(
197
+ self,
198
+ dim,
199
+ max_position_embeddings=2048,
200
+ base=10000,
201
+ device=None,
202
+ scaling_factor=1.0,
203
+ ):
204
+ self.scaling_factor = scaling_factor
205
+ super().__init__(dim, max_position_embeddings, base, device)
206
+
207
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
208
+ self.max_seq_len_cached = seq_len
209
+
210
+ if seq_len > self.max_position_embeddings:
211
+ base = self.base * (
212
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
213
+ - (self.scaling_factor - 1)
214
+ ) ** (self.dim / (self.dim - 2))
215
+ inv_freq = 1.0 / (
216
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
217
+ )
218
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
219
+
220
+ t = torch.arange(
221
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
222
+ )
223
+
224
+ freqs = torch.outer(t, self.inv_freq)
225
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
226
+ emb = torch.cat((freqs, freqs), dim=-1)
227
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
228
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
229
+
230
+
231
+ # Inverse dim formula to find dim based on number of rotations
232
+ def yarn_find_correction_dim(
233
+ num_rotations, dim, base=10000, max_position_embeddings=2048
234
+ ):
235
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
236
+ 2 * math.log(base)
237
+ )
238
+
239
+
240
+ # Find dim range bounds based on rotations
241
+ def yarn_find_correction_range(
242
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
243
+ ):
244
+ low = math.floor(
245
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
246
+ )
247
+ high = math.ceil(
248
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
249
+ )
250
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
251
+
252
+
253
+ def yarn_get_mscale(scale=1, mscale=1):
254
+ if scale <= 1:
255
+ return 1.0
256
+ return 0.1 * mscale * math.log(scale) + 1.0
257
+
258
+
259
+ def yarn_linear_ramp_mask(min, max, dim):
260
+ if min == max:
261
+ max += 0.001 # Prevent singularity
262
+
263
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
264
+ ramp_func = torch.clamp(linear_func, 0, 1)
265
+ return ramp_func
266
+
267
+
268
+ class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
269
+
270
+ def __init__(
271
+ self,
272
+ dim,
273
+ max_position_embeddings=2048,
274
+ base=10000,
275
+ device=None,
276
+ scaling_factor=1.0,
277
+ original_max_position_embeddings=4096,
278
+ beta_fast=32,
279
+ beta_slow=1,
280
+ mscale=1,
281
+ mscale_all_dim=0,
282
+ ):
283
+ self.scaling_factor = scaling_factor
284
+ self.original_max_position_embeddings = original_max_position_embeddings
285
+ self.beta_fast = beta_fast
286
+ self.beta_slow = beta_slow
287
+ self.mscale = mscale
288
+ self.mscale_all_dim = mscale_all_dim
289
+ super().__init__(dim, max_position_embeddings, base, device)
290
+
291
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
292
+ self.max_seq_len_cached = seq_len
293
+ dim = self.dim
294
+
295
+ freq_extra = 1.0 / (
296
+ self.base
297
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
298
+ )
299
+ freq_inter = 1.0 / (
300
+ self.scaling_factor
301
+ * self.base
302
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
303
+ )
304
+
305
+ low, high = yarn_find_correction_range(
306
+ self.beta_fast,
307
+ self.beta_slow,
308
+ dim,
309
+ self.base,
310
+ self.original_max_position_embeddings,
311
+ )
312
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
313
+ device=device, dtype=torch.float32
314
+ )
315
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
316
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
317
+
318
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
319
+
320
+ freqs = torch.outer(t, inv_freq)
321
+
322
+ _mscale = float(
323
+ yarn_get_mscale(self.scaling_factor, self.mscale)
324
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
325
+ )
326
+
327
+ emb = torch.cat((freqs, freqs), dim=-1)
328
+ self.register_buffer(
329
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
330
+ )
331
+ self.register_buffer(
332
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
333
+ )
334
+
335
+
336
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
337
+ def rotate_half(x):
338
+ """Rotates half the hidden dims of the input."""
339
+ x1 = x[..., : x.shape[-1] // 2]
340
+ x2 = x[..., x.shape[-1] // 2 :]
341
+ return torch.cat((-x2, x1), dim=-1)
342
+
343
+
344
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
345
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
346
+ """Applies Rotary Position Embedding to the query and key tensors.
347
+
348
+ Args:
349
+ q (`torch.Tensor`): The query tensor.
350
+ k (`torch.Tensor`): The key tensor.
351
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
352
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
353
+ position_ids (`torch.Tensor`):
354
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
355
+ used to pass offsetted position ids when working with a KV-cache.
356
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
357
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
358
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
359
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
360
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
361
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
362
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
363
+ Returns:
364
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
365
+ """
366
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
367
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
368
+
369
+
370
+ # print()
371
+
372
+ b, h, s, d = q.shape
373
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
374
+
375
+ b, h, s, d = k.shape
376
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
377
+
378
+ q_embed = (q * cos) + (rotate_half(q) * sin)
379
+ k_embed = (k * cos) + (rotate_half(k) * sin)
380
+
381
+
382
+ return q_embed, k_embed
383
+
384
+
385
+ class DeepseekV2MLP(nn.Module):
386
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
387
+ super().__init__()
388
+ self.config = config
389
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
390
+ self.intermediate_size = (
391
+ config.intermediate_size if intermediate_size is None else intermediate_size
392
+ )
393
+
394
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
395
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
396
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
397
+ self.act_fn = ACT2FN[config.hidden_act]
398
+
399
+ def forward(self, x):
400
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
401
+ return down_proj
402
+
403
+
404
+ class MoEGate(nn.Module):
405
+ def __init__(self, config):
406
+ super().__init__()
407
+ self.config = config
408
+ self.top_k = config.num_experts_per_tok
409
+ self.n_routed_experts = config.n_routed_experts
410
+ self.routed_scaling_factor = config.routed_scaling_factor
411
+ self.scoring_func = config.scoring_func
412
+ self.alpha = config.aux_loss_alpha
413
+ self.seq_aux = config.seq_aux
414
+ self.topk_method = config.topk_method
415
+ self.n_group = config.n_group
416
+ self.topk_group = config.topk_group
417
+
418
+ # topk selection algorithm
419
+ self.norm_topk_prob = config.norm_topk_prob
420
+ self.gating_dim = config.hidden_size
421
+ self.weight = nn.Parameter(
422
+ torch.empty((self.n_routed_experts, self.gating_dim))
423
+ )
424
+ if self.topk_method == "noaux_tc":
425
+ self.e_score_correction_bias = nn.Parameter(
426
+ torch.empty((self.n_routed_experts))
427
+ )
428
+ self.reset_parameters()
429
+
430
+ def reset_parameters(self) -> None:
431
+ import torch.nn.init as init
432
+
433
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
434
+
435
+ def forward(self, hidden_states):
436
+ bsz, seq_len, h = hidden_states.shape
437
+ ### compute gating score
438
+ hidden_states = hidden_states.view(-1, h)
439
+ logits = F.linear(
440
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
441
+ )
442
+ if self.scoring_func == "softmax":
443
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
444
+ elif self.scoring_func == "sigmoid":
445
+ scores = logits.sigmoid()
446
+ else:
447
+ raise NotImplementedError(
448
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
449
+ )
450
+
451
+ ### select top-k experts
452
+ if self.topk_method == "greedy":
453
+ topk_weight, topk_idx = torch.topk(
454
+ scores, k=self.top_k, dim=-1, sorted=False
455
+ )
456
+ elif self.topk_method == "group_limited_greedy":
457
+ group_scores = (
458
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
459
+ ) # [n, n_group]
460
+ group_idx = torch.topk(
461
+ group_scores, k=self.topk_group, dim=-1, sorted=False
462
+ )[
463
+ 1
464
+ ] # [n, top_k_group]
465
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
466
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
467
+ score_mask = (
468
+ group_mask.unsqueeze(-1)
469
+ .expand(
470
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
471
+ )
472
+ .reshape(bsz * seq_len, -1)
473
+ ) # [n, e]
474
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
475
+ topk_weight, topk_idx = torch.topk(
476
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
477
+ )
478
+ elif self.topk_method == "noaux_tc":
479
+ assert not self.training
480
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
481
+ group_scores = (
482
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
483
+ ) # [n, n_group]
484
+ group_idx = torch.topk(
485
+ group_scores, k=self.topk_group, dim=-1, sorted=False
486
+ )[
487
+ 1
488
+ ] # [n, top_k_group]
489
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
490
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
491
+ score_mask = (
492
+ group_mask.unsqueeze(-1)
493
+ .expand(
494
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
495
+ )
496
+ .reshape(bsz * seq_len, -1)
497
+ ) # [n, e]
498
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
499
+ _, topk_idx = torch.topk(
500
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
501
+ )
502
+ topk_weight = scores.gather(1, topk_idx)
503
+
504
+ ### norm gate to sum 1
505
+ if self.top_k > 1 and self.norm_topk_prob:
506
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
507
+ topk_weight = topk_weight / denominator * self.routed_scaling_factor
508
+ else:
509
+ topk_weight = topk_weight * self.routed_scaling_factor
510
+ ### expert-level computation auxiliary loss
511
+ if self.training and self.alpha > 0.0:
512
+ scores_for_aux = scores
513
+ aux_topk = self.top_k
514
+ # always compute aux loss based on the naive greedy topk method
515
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
516
+ if self.seq_aux:
517
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
518
+ ce = torch.zeros(
519
+ bsz, self.n_routed_experts, device=hidden_states.device
520
+ )
521
+ ce.scatter_add_(
522
+ 1,
523
+ topk_idx_for_aux_loss,
524
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
525
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
526
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
527
+ dim=1
528
+ ).mean() * self.alpha
529
+ else:
530
+ mask_ce = F.one_hot(
531
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
532
+ )
533
+ ce = mask_ce.float().mean(0)
534
+ Pi = scores_for_aux.mean(0)
535
+ fi = ce * self.n_routed_experts
536
+ aux_loss = (Pi * fi).sum() * self.alpha
537
+ else:
538
+ aux_loss = None
539
+ return topk_idx, topk_weight, aux_loss
540
+
541
+
542
+ class AddAuxiliaryLoss(torch.autograd.Function):
543
+ """
544
+ The trick function of adding auxiliary (aux) loss,
545
+ which includes the gradient of the aux loss during backpropagation.
546
+ """
547
+
548
+ @staticmethod
549
+ def forward(ctx, x, loss):
550
+ assert loss.numel() == 1
551
+ ctx.dtype = loss.dtype
552
+ ctx.required_aux_loss = loss.requires_grad
553
+ return x
554
+
555
+ @staticmethod
556
+ def backward(ctx, grad_output):
557
+ grad_loss = None
558
+ if ctx.required_aux_loss:
559
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
560
+ return grad_output, grad_loss
561
+
562
+
563
+ class DeepseekV2MoE(nn.Module):
564
+ """
565
+ A mixed expert module containing shared experts.
566
+ """
567
+
568
+ def __init__(self, config):
569
+ super().__init__()
570
+ self.config = config
571
+ self.num_experts_per_tok = config.num_experts_per_tok
572
+
573
+ if hasattr(config, "ep_size") and config.ep_size > 1:
574
+ assert config.ep_size == dist.get_world_size()
575
+ self.ep_size = config.ep_size
576
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
577
+ self.ep_rank = dist.get_rank()
578
+ self.experts = nn.ModuleList(
579
+ [
580
+ (
581
+ DeepseekV2MLP(
582
+ config, intermediate_size=config.moe_intermediate_size
583
+ )
584
+ if i >= self.ep_rank * self.experts_per_rank
585
+ and i < (self.ep_rank + 1) * self.experts_per_rank
586
+ else None
587
+ )
588
+ for i in range(config.n_routed_experts)
589
+ ]
590
+ )
591
+ else:
592
+ self.ep_size = 1
593
+ self.experts_per_rank = config.n_routed_experts
594
+ self.ep_rank = 0
595
+ self.experts = nn.ModuleList(
596
+ [
597
+ DeepseekV2MLP(
598
+ config, intermediate_size=config.moe_intermediate_size
599
+ )
600
+ for i in range(config.n_routed_experts)
601
+ ]
602
+ )
603
+ self.gate = MoEGate(config)
604
+ if config.n_shared_experts is not None:
605
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
606
+ self.shared_experts = DeepseekV2MLP(
607
+ config=config, intermediate_size=intermediate_size
608
+ )
609
+
610
+ def forward(self, hidden_states):
611
+ identity = hidden_states
612
+ orig_shape = hidden_states.shape
613
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
614
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
615
+ flat_topk_idx = topk_idx.view(-1)
616
+ if self.training:
617
+ hidden_states = hidden_states.repeat_interleave(
618
+ self.num_experts_per_tok, dim=0
619
+ )
620
+ y = torch.empty_like(hidden_states)
621
+ for i, expert in enumerate(self.experts):
622
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
623
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
624
+ y = y.to(hidden_states.dtype).view(*orig_shape)
625
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
626
+ else:
627
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
628
+ if self.config.n_shared_experts is not None:
629
+ y = y + self.shared_experts(identity)
630
+ return y
631
+
632
+ @torch.no_grad()
633
+ def moe_infer(self, x, topk_ids, topk_weight):
634
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
635
+ cnts.scatter_(1, topk_ids, 1)
636
+ tokens_per_expert = cnts.sum(dim=0)
637
+ idxs = topk_ids.view(-1).argsort()
638
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
639
+ sorted_tokens_shape = sorted_tokens.shape
640
+ if self.ep_size > 1:
641
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
642
+ tokens_per_expert_group = tokens_per_expert.new_empty(
643
+ tokens_per_expert.shape[0]
644
+ )
645
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
646
+ output_splits = (
647
+ tokens_per_expert_group.view(self.ep_size, -1)
648
+ .sum(1)
649
+ .cpu()
650
+ .numpy()
651
+ .tolist()
652
+ )
653
+ gathered_tokens = sorted_tokens.new_empty(
654
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
655
+ )
656
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
657
+ dist.all_to_all(
658
+ list(gathered_tokens.split(output_splits)),
659
+ list(sorted_tokens.split(input_split_sizes)),
660
+ )
661
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
662
+ self.ep_size, self.experts_per_rank
663
+ ).sum(dim=0)
664
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
665
+ s = 0
666
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
667
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
668
+ s += k
669
+ gatherd_idxs = gatherd_idxs.argsort()
670
+ sorted_tokens = gathered_tokens[gatherd_idxs]
671
+ tokens_per_expert = tokens_per_expert_post_gather
672
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
673
+
674
+ outputs = []
675
+ start_idx = 0
676
+ for i, num_tokens in enumerate(tokens_per_expert):
677
+ end_idx = start_idx + num_tokens
678
+ if num_tokens == 0:
679
+ continue
680
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
681
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
682
+ expert_out = expert(tokens_for_this_expert)
683
+ outputs.append(expert_out)
684
+ start_idx = end_idx
685
+
686
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
687
+ if self.ep_size > 1:
688
+ new_x = torch.empty_like(outs)
689
+ new_x[gatherd_idxs] = outs
690
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
691
+ dist.all_to_all(
692
+ list(gathered_tokens.split(input_split_sizes)),
693
+ list(new_x.split(output_splits)),
694
+ )
695
+ outs = gathered_tokens
696
+
697
+ new_x = torch.empty_like(outs)
698
+ new_x[idxs] = outs
699
+ final_out = (
700
+ new_x.view(*topk_ids.shape, -1)
701
+ .type(topk_weight.dtype)
702
+ .mul_(topk_weight.unsqueeze(dim=-1))
703
+ .sum(dim=1)
704
+ .type(new_x.dtype)
705
+ )
706
+ return final_out
707
+
708
+
709
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
710
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
711
+ """
712
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
713
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
714
+ """
715
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
716
+ if n_rep == 1:
717
+ return hidden_states
718
+ hidden_states = hidden_states[:, :, None, :, :].expand(
719
+ batch, num_key_value_heads, n_rep, slen, head_dim
720
+ )
721
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
722
+
723
+
724
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
725
+ class DeepseekV2Attention(nn.Module):
726
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
727
+
728
+ def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
729
+ super().__init__()
730
+ self.config = config
731
+ self.layer_idx = layer_idx
732
+ if layer_idx is None:
733
+ logger.warning_once(
734
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
735
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
736
+ "when creating this class."
737
+ )
738
+
739
+ self.attention_dropout = config.attention_dropout
740
+ self.hidden_size = config.hidden_size
741
+ self.num_heads = config.num_attention_heads
742
+
743
+ self.max_position_embeddings = config.max_position_embeddings
744
+ self.rope_theta = config.rope_theta
745
+ self.q_lora_rank = config.q_lora_rank
746
+ self.qk_rope_head_dim = config.qk_rope_head_dim
747
+ self.kv_lora_rank = config.kv_lora_rank
748
+ self.v_head_dim = config.v_head_dim
749
+ self.qk_nope_head_dim = config.qk_nope_head_dim
750
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
751
+
752
+ self.is_causal = True
753
+
754
+ if self.q_lora_rank is None:
755
+ self.q_proj = nn.Linear(
756
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
757
+ )
758
+ else:
759
+ self.q_a_proj = nn.Linear(
760
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
761
+ )
762
+ self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
763
+ self.q_b_proj = nn.Linear(
764
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
765
+ )
766
+ # config.kv_lora_rank + config.qk_rope_head_dim,
767
+ self.kv_a_proj_with_mqa = nn.Linear(
768
+ self.hidden_size,
769
+ config.kv_lora_rank + config.qk_rope_head_dim,
770
+ bias=config.attention_bias,
771
+ )
772
+ self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
773
+ self.kv_b_proj = nn.Linear(
774
+ config.kv_lora_rank,
775
+ self.num_heads
776
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
777
+ bias=False,
778
+ )
779
+
780
+ self.o_proj = nn.Linear(
781
+ self.num_heads * self.v_head_dim,
782
+ self.hidden_size,
783
+ bias=config.attention_bias,
784
+ )
785
+ self._init_rope()
786
+
787
+ self.softmax_scale = self.q_head_dim ** (-0.5)
788
+ if self.config.rope_scaling is not None:
789
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
790
+ scaling_factor = self.config.rope_scaling["factor"]
791
+ if mscale_all_dim:
792
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
793
+ self.softmax_scale = self.softmax_scale * mscale * mscale
794
+
795
+ def _init_rope(self):
796
+ if self.config.rope_scaling is None:
797
+ self.rotary_emb = DeepseekV2RotaryEmbedding(
798
+ self.qk_rope_head_dim,
799
+ max_position_embeddings=self.max_position_embeddings,
800
+ base=self.rope_theta,
801
+ )
802
+ # self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
803
+ # self.qk_rope_head_dim,
804
+ # max_position_embeddings=self.max_position_embeddings,
805
+ # scaling_factor=scaling_factor,
806
+ # base=self.rope_theta,
807
+ # )
808
+ else:
809
+ scaling_type = self.config.rope_scaling["type"]
810
+ scaling_factor = self.config.rope_scaling["factor"]
811
+ if scaling_type == "linear":
812
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
813
+ self.qk_rope_head_dim,
814
+ max_position_embeddings=self.max_position_embeddings,
815
+ scaling_factor=scaling_factor,
816
+ base=self.rope_theta,
817
+ )
818
+ elif scaling_type == "dynamic":
819
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
820
+ self.qk_rope_head_dim,
821
+ max_position_embeddings=self.max_position_embeddings,
822
+ scaling_factor=scaling_factor,
823
+ base=self.rope_theta,
824
+ )
825
+ elif scaling_type == "yarn":
826
+ kwargs = {
827
+ key: self.config.rope_scaling[key]
828
+ for key in [
829
+ "original_max_position_embeddings",
830
+ "beta_fast",
831
+ "beta_slow",
832
+ "mscale",
833
+ "mscale_all_dim",
834
+ ]
835
+ if key in self.config.rope_scaling
836
+ }
837
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
838
+ self.qk_rope_head_dim,
839
+ max_position_embeddings=self.max_position_embeddings,
840
+ scaling_factor=scaling_factor,
841
+ base=self.rope_theta,
842
+ **kwargs,
843
+ )
844
+ else:
845
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
846
+
847
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
848
+ return (
849
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
850
+ .transpose(1, 2)
851
+ .contiguous()
852
+ )
853
+
854
+ def forward(
855
+ self,
856
+ hidden_states: torch.Tensor,
857
+ attention_mask: Optional[torch.Tensor] = None,
858
+ position_ids: Optional[torch.LongTensor] = None,
859
+ past_key_value: Optional[Cache] = None,
860
+ output_attentions: bool = False,
861
+ use_cache: bool = False,
862
+ **kwargs,
863
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
864
+ if "padding_mask" in kwargs:
865
+ warnings.warn(
866
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
867
+ )
868
+ bsz, q_len, _ = hidden_states.size()
869
+
870
+ if self.q_lora_rank is None:
871
+ q = self.q_proj(hidden_states)
872
+ else:
873
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
874
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
875
+
876
+
877
+ q_nope, q_pe = torch.split(
878
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
879
+ )
880
+
881
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
882
+ compressed_kv, k_pe = torch.split(
883
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
884
+ )
885
+ compressed_kv = self.kv_a_layernorm(compressed_kv)
886
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
887
+
888
+ kv_seq_len = k_pe.shape[-2]
889
+ if past_key_value is not None:
890
+ if self.layer_idx is None:
891
+ raise ValueError(
892
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
893
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
894
+ "with a layer index."
895
+ )
896
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
897
+
898
+ cos, sin = self.rotary_emb(q_pe, seq_len=kv_seq_len)
899
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
900
+
901
+ if past_key_value is not None:
902
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
903
+ compressed_kv = compressed_kv.unsqueeze(1)
904
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
905
+ compressed_kv = compressed_kv.squeeze(1)
906
+
907
+ kv_b_proj = self.kv_b_proj.weight.view(self.num_heads, -1, self.kv_lora_rank)
908
+ q_absorb = kv_b_proj[:, :self.qk_nope_head_dim, :]
909
+ out_absorb = kv_b_proj[:, self.qk_nope_head_dim:, :]
910
+
911
+ q_nope = torch.matmul(q_nope, q_absorb)
912
+ attn_weights = (torch.matmul(q_pe, k_pe.mT) +
913
+ torch.matmul(q_nope, compressed_kv.unsqueeze(-3).mT)) * self.softmax_scale
914
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
915
+ raise ValueError(
916
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
917
+ f" {attn_weights.size()}"
918
+ )
919
+ assert attention_mask is not None
920
+ if attention_mask is not None:
921
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
922
+ raise ValueError(
923
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
924
+ )
925
+ attn_weights = attn_weights + attention_mask
926
+
927
+ # upcast attention to fp32
928
+ attn_weights = nn.functional.softmax(
929
+ attn_weights, dim=-1, dtype=torch.float32
930
+ ).to(q_pe.dtype)
931
+ attn_weights = nn.functional.dropout(
932
+ attn_weights, p=self.attention_dropout, training=self.training
933
+ )
934
+ attn_output = torch.einsum('bhql,blc->bhqc', attn_weights, compressed_kv)
935
+
936
+ attn_output = torch.matmul(attn_output, out_absorb.mT)
937
+
938
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
939
+ raise ValueError(
940
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
941
+ f" {attn_output.size()}"
942
+ )
943
+
944
+ attn_output = attn_output.transpose(1, 2).contiguous()
945
+
946
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
947
+
948
+ attn_output = self.o_proj(attn_output)
949
+
950
+ if not output_attentions:
951
+ attn_weights = None
952
+
953
+ return attn_output, attn_weights, past_key_value
954
+
955
+
956
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
957
+ class DeepseekV2FlashAttention2(DeepseekV2Attention):
958
+ """
959
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
960
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
961
+ flash attention and deal with padding tokens in case the input contains any of them.
962
+ """
963
+
964
+ def __init__(self, *args, **kwargs):
965
+ super().__init__(*args, **kwargs)
966
+
967
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
968
+ # 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.
969
+ # 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).
970
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
971
+
972
+ def forward(
973
+ self,
974
+ hidden_states: torch.Tensor,
975
+ attention_mask: Optional[torch.LongTensor] = None,
976
+ position_ids: Optional[torch.LongTensor] = None,
977
+ past_key_value: Optional[Cache] = None,
978
+ output_attentions: bool = False,
979
+ use_cache: bool = False,
980
+ **kwargs,
981
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
982
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
983
+ if "padding_mask" in kwargs:
984
+ warnings.warn(
985
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
986
+ )
987
+
988
+ # overwrite attention_mask with padding_mask
989
+ attention_mask = kwargs.pop("padding_mask")
990
+
991
+ output_attentions = False
992
+
993
+ bsz, q_len, _ = hidden_states.size()
994
+
995
+ if self.q_lora_rank is None:
996
+ q = self.q_proj(hidden_states)
997
+ else:
998
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
999
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1000
+ q_nope, q_pe = torch.split(
1001
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1002
+ )
1003
+
1004
+ # Flash attention requires the input to have the shape
1005
+ # batch_size x seq_length x head_dim x hidden_dim
1006
+ # therefore we just need to keep the original shape
1007
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1008
+ compressed_kv, k_pe = torch.split(
1009
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1010
+ )
1011
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1012
+ kv = (
1013
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1014
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1015
+ .transpose(1, 2)
1016
+ )
1017
+
1018
+ k_nope, value_states = torch.split(
1019
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1020
+ )
1021
+ kv_seq_len = value_states.shape[-2]
1022
+
1023
+ kv_seq_len = value_states.shape[-2]
1024
+ if past_key_value is not None:
1025
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1026
+
1027
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1028
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1029
+
1030
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1031
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1032
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1033
+
1034
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1035
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1036
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1037
+
1038
+ if self.q_head_dim != self.v_head_dim:
1039
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1040
+
1041
+ # TODO: support compressed_kv for kv_cache (instead of key_states, value_states) in flash_attention version
1042
+ if past_key_value is not None:
1043
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1044
+ key_states, value_states = past_key_value.update(
1045
+ key_states, value_states, self.layer_idx, cache_kwargs
1046
+ )
1047
+
1048
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
1049
+ # to be able to avoid many of these transpose/reshape/view.
1050
+ query_states = query_states.transpose(1, 2)
1051
+ key_states = key_states.transpose(1, 2)
1052
+ value_states = value_states.transpose(1, 2)
1053
+
1054
+ dropout_rate = self.attention_dropout if self.training else 0.0
1055
+
1056
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1057
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1058
+ # cast them back in the correct dtype just to be sure everything works as expected.
1059
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1060
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
1061
+
1062
+ input_dtype = query_states.dtype
1063
+ if input_dtype == torch.float32:
1064
+ # Handle the case where the model is quantized
1065
+ if hasattr(self.config, "_pre_quantization_dtype"):
1066
+ target_dtype = self.config._pre_quantization_dtype
1067
+ elif torch.is_autocast_enabled():
1068
+ target_dtype = torch.get_autocast_gpu_dtype()
1069
+ else:
1070
+ target_dtype = (
1071
+ self.q_proj.weight.dtype
1072
+ if self.q_lora_rank is None
1073
+ else self.q_a_proj.weight.dtype
1074
+ )
1075
+
1076
+ logger.warning_once(
1077
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1078
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1079
+ f" {target_dtype}."
1080
+ )
1081
+
1082
+ query_states = query_states.to(target_dtype)
1083
+ key_states = key_states.to(target_dtype)
1084
+ value_states = value_states.to(target_dtype)
1085
+
1086
+ attn_output = self._flash_attention_forward(
1087
+ query_states,
1088
+ key_states,
1089
+ value_states,
1090
+ attention_mask,
1091
+ q_len,
1092
+ dropout=dropout_rate,
1093
+ softmax_scale=self.softmax_scale,
1094
+ )
1095
+ if self.q_head_dim != self.v_head_dim:
1096
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1097
+
1098
+ attn_output = attn_output.reshape(
1099
+ bsz, q_len, self.num_heads * self.v_head_dim
1100
+ ).contiguous()
1101
+ attn_output = self.o_proj(attn_output)
1102
+
1103
+ if not output_attentions:
1104
+ attn_weights = None
1105
+
1106
+ return attn_output, attn_weights, past_key_value
1107
+
1108
+ def _flash_attention_forward(
1109
+ self,
1110
+ query_states,
1111
+ key_states,
1112
+ value_states,
1113
+ attention_mask,
1114
+ query_length,
1115
+ dropout=0.0,
1116
+ softmax_scale=None,
1117
+ ):
1118
+ """
1119
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1120
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1121
+
1122
+ Args:
1123
+ query_states (`torch.Tensor`):
1124
+ Input query states to be passed to Flash Attention API
1125
+ key_states (`torch.Tensor`):
1126
+ Input key states to be passed to Flash Attention API
1127
+ value_states (`torch.Tensor`):
1128
+ Input value states to be passed to Flash Attention API
1129
+ attention_mask (`torch.Tensor`):
1130
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1131
+ position of padding tokens and 1 for the position of non-padding tokens.
1132
+ dropout (`int`, *optional*):
1133
+ Attention dropout
1134
+ softmax_scale (`float`, *optional*):
1135
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1136
+ """
1137
+ if not self._flash_attn_uses_top_left_mask:
1138
+ causal = self.is_causal
1139
+ else:
1140
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
1141
+ causal = self.is_causal and query_length != 1
1142
+
1143
+ # Contains at least one padding token in the sequence
1144
+ if attention_mask is not None:
1145
+ batch_size = query_states.shape[0]
1146
+ (
1147
+ query_states,
1148
+ key_states,
1149
+ value_states,
1150
+ indices_q,
1151
+ cu_seq_lens,
1152
+ max_seq_lens,
1153
+ ) = self._upad_input(
1154
+ query_states, key_states, value_states, attention_mask, query_length
1155
+ )
1156
+
1157
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1158
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1159
+
1160
+ attn_output_unpad = flash_attn_varlen_func(
1161
+ query_states,
1162
+ key_states,
1163
+ value_states,
1164
+ cu_seqlens_q=cu_seqlens_q,
1165
+ cu_seqlens_k=cu_seqlens_k,
1166
+ max_seqlen_q=max_seqlen_in_batch_q,
1167
+ max_seqlen_k=max_seqlen_in_batch_k,
1168
+ dropout_p=dropout,
1169
+ softmax_scale=softmax_scale,
1170
+ causal=causal,
1171
+ )
1172
+
1173
+ attn_output = pad_input(
1174
+ attn_output_unpad, indices_q, batch_size, query_length
1175
+ )
1176
+ else:
1177
+ attn_output = flash_attn_func(
1178
+ query_states,
1179
+ key_states,
1180
+ value_states,
1181
+ dropout,
1182
+ softmax_scale=softmax_scale,
1183
+ causal=causal,
1184
+ )
1185
+
1186
+ return attn_output
1187
+
1188
+ def _upad_input(
1189
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1190
+ ):
1191
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1192
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1193
+
1194
+ key_layer = index_first_axis(
1195
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1196
+ indices_k,
1197
+ )
1198
+ value_layer = index_first_axis(
1199
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1200
+ indices_k,
1201
+ )
1202
+ if query_length == kv_seq_len:
1203
+ query_layer = index_first_axis(
1204
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1205
+ indices_k,
1206
+ )
1207
+ cu_seqlens_q = cu_seqlens_k
1208
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1209
+ indices_q = indices_k
1210
+ elif query_length == 1:
1211
+ max_seqlen_in_batch_q = 1
1212
+ cu_seqlens_q = torch.arange(
1213
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1214
+ ) # There is a memcpy here, that is very bad.
1215
+ indices_q = cu_seqlens_q[:-1]
1216
+ query_layer = query_layer.squeeze(1)
1217
+ else:
1218
+ # The -q_len: slice assumes left padding.
1219
+ attention_mask = attention_mask[:, -query_length:]
1220
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1221
+ query_layer, attention_mask
1222
+ )
1223
+
1224
+ return (
1225
+ query_layer,
1226
+ key_layer,
1227
+ value_layer,
1228
+ indices_q,
1229
+ (cu_seqlens_q, cu_seqlens_k),
1230
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1231
+ )
1232
+
1233
+
1234
+ ATTENTION_CLASSES = {
1235
+ "eager": DeepseekV2Attention,
1236
+ "flash_attention_2": DeepseekV2FlashAttention2,
1237
+
1238
+ "mla_eager": DeepseekV2Attention,
1239
+ "mla_flash_attention_2": DeepseekV2FlashAttention2,
1240
+
1241
+ "mha_eager": LlamaAttention,
1242
+ "mha_flash_attention_2": LlamaFlashAttention2
1243
+ }
1244
+
1245
+
1246
+ class DeepseekV2DecoderLayer(nn.Module):
1247
+ def __init__(self, config: DeepseekV2Config, layer_idx: int):
1248
+ super().__init__()
1249
+ self.hidden_size = config.hidden_size
1250
+
1251
+
1252
+ if config.use_mla:
1253
+ attn_implementation = "mla_" + config._attn_implementation
1254
+ else:
1255
+ attn_implementation = "mha_" + config._attn_implementation
1256
+
1257
+ self.self_attn = ATTENTION_CLASSES[attn_implementation](
1258
+ config=config, layer_idx=layer_idx
1259
+ )
1260
+
1261
+ self.mlp = (
1262
+ DeepseekV2MoE(config)
1263
+ if (
1264
+ config.n_routed_experts is not None
1265
+ and layer_idx >= config.first_k_dense_replace
1266
+ and layer_idx % config.moe_layer_freq == 0
1267
+ )
1268
+ else DeepseekV2MLP(config)
1269
+ )
1270
+ self.input_layernorm = DeepseekV2RMSNorm(
1271
+ config.hidden_size, eps=config.rms_norm_eps
1272
+ )
1273
+ self.post_attention_layernorm = DeepseekV2RMSNorm(
1274
+ config.hidden_size, eps=config.rms_norm_eps
1275
+ )
1276
+
1277
+ def forward(
1278
+ self,
1279
+ hidden_states: torch.Tensor,
1280
+ attention_mask: Optional[torch.Tensor] = None,
1281
+ position_ids: Optional[torch.LongTensor] = None,
1282
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1283
+ output_attentions: Optional[bool] = False,
1284
+ use_cache: Optional[bool] = False,
1285
+ **kwargs,
1286
+ ) -> Tuple[
1287
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1288
+ ]:
1289
+ """
1290
+ Args:
1291
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1292
+ attention_mask (`torch.FloatTensor`, *optional*):
1293
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1294
+ query_sequence_length, key_sequence_length)` if default attention is used.
1295
+ output_attentions (`bool`, *optional*):
1296
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1297
+ returned tensors for more detail.
1298
+ use_cache (`bool`, *optional*):
1299
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1300
+ (see `past_key_values`).
1301
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1302
+ """
1303
+ if "padding_mask" in kwargs:
1304
+ warnings.warn(
1305
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1306
+ )
1307
+ residual = hidden_states
1308
+
1309
+ hidden_states = self.input_layernorm(hidden_states)
1310
+
1311
+ # Self Attention
1312
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1313
+ hidden_states=hidden_states,
1314
+ attention_mask=attention_mask,
1315
+ position_ids=position_ids,
1316
+ past_key_value=past_key_value,
1317
+ output_attentions=output_attentions,
1318
+ use_cache=use_cache,
1319
+ **kwargs,
1320
+ )
1321
+ hidden_states = residual + hidden_states
1322
+
1323
+ # Fully Connected
1324
+ residual = hidden_states
1325
+ hidden_states = self.post_attention_layernorm(hidden_states)
1326
+ hidden_states = self.mlp(hidden_states)
1327
+ hidden_states = residual + hidden_states
1328
+
1329
+ outputs = (hidden_states,)
1330
+
1331
+ if output_attentions:
1332
+ outputs += (self_attn_weights,)
1333
+
1334
+ if use_cache:
1335
+ outputs += (present_key_value,)
1336
+
1337
+ return outputs
1338
+
1339
+
1340
+ DeepseekV2_START_DOCSTRING = r"""
1341
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1342
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1343
+ etc.)
1344
+
1345
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1346
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1347
+ and behavior.
1348
+
1349
+ Parameters:
1350
+ config ([`DeepseekV2Config`]):
1351
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1352
+ load the weights associated with the model, only the configuration. Check out the
1353
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1354
+ """
1355
+
1356
+
1357
+ @add_start_docstrings(
1358
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1359
+ DeepseekV2_START_DOCSTRING,
1360
+ )
1361
+ class DeepseekV2PreTrainedModel(PreTrainedModel):
1362
+ config_class = DeepseekV2Config
1363
+ base_model_prefix = "model"
1364
+ supports_gradient_checkpointing = True
1365
+ _no_split_modules = ["DeepseekV2DecoderLayer"]
1366
+ _skip_keys_device_placement = "past_key_values"
1367
+ _supports_flash_attn_2 = True
1368
+ _supports_cache_class = True
1369
+
1370
+ def _init_weights(self, module):
1371
+ std = self.config.initializer_range
1372
+ if isinstance(module, nn.Linear):
1373
+ module.weight.data.normal_(mean=0.0, std=std)
1374
+ if module.bias is not None:
1375
+ module.bias.data.zero_()
1376
+ elif isinstance(module, nn.Embedding):
1377
+ module.weight.data.normal_(mean=0.0, std=std)
1378
+ if module.padding_idx is not None:
1379
+ module.weight.data[module.padding_idx].zero_()
1380
+
1381
+
1382
+ DeepseekV2_INPUTS_DOCSTRING = r"""
1383
+ Args:
1384
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1385
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1386
+ it.
1387
+
1388
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1389
+ [`PreTrainedTokenizer.__call__`] for details.
1390
+
1391
+ [What are input IDs?](../glossary#input-ids)
1392
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1393
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1394
+
1395
+ - 1 for tokens that are **not masked**,
1396
+ - 0 for tokens that are **masked**.
1397
+
1398
+ [What are attention masks?](../glossary#attention-mask)
1399
+
1400
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1401
+ [`PreTrainedTokenizer.__call__`] for details.
1402
+
1403
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1404
+ `past_key_values`).
1405
+
1406
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1407
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1408
+ information on the default strategy.
1409
+
1410
+ - 1 indicates the head is **not masked**,
1411
+ - 0 indicates the head is **masked**.
1412
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1413
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1414
+ config.n_positions - 1]`.
1415
+
1416
+ [What are position IDs?](../glossary#position-ids)
1417
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1418
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1419
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1420
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1421
+
1422
+ Two formats are allowed:
1423
+ - a [`~cache_utils.Cache`] instance;
1424
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1425
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1426
+ cache format.
1427
+
1428
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1429
+ legacy cache format will be returned.
1430
+
1431
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1432
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1433
+ of shape `(batch_size, sequence_length)`.
1434
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1435
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1436
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1437
+ model's internal embedding lookup matrix.
1438
+ use_cache (`bool`, *optional*):
1439
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1440
+ `past_key_values`).
1441
+ output_attentions (`bool`, *optional*):
1442
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1443
+ tensors for more detail.
1444
+ output_hidden_states (`bool`, *optional*):
1445
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1446
+ more detail.
1447
+ return_dict (`bool`, *optional*):
1448
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1449
+ """
1450
+
1451
+
1452
+ @add_start_docstrings(
1453
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1454
+ DeepseekV2_START_DOCSTRING,
1455
+ )
1456
+ class DeepseekV2Model(DeepseekV2PreTrainedModel):
1457
+ """
1458
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1459
+
1460
+ Args:
1461
+ config: DeepseekV2Config
1462
+ """
1463
+
1464
+ def __init__(self, config: DeepseekV2Config):
1465
+ super().__init__(config)
1466
+ self.padding_idx = config.pad_token_id
1467
+ self.vocab_size = config.vocab_size
1468
+
1469
+ self.embed_tokens = nn.Embedding(
1470
+ config.vocab_size, config.hidden_size, self.padding_idx
1471
+ )
1472
+ self.layers = nn.ModuleList(
1473
+ [
1474
+ DeepseekV2DecoderLayer(config, layer_idx)
1475
+ for layer_idx in range(config.num_hidden_layers)
1476
+ ]
1477
+ )
1478
+ # print(config._attn_implementation)
1479
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1480
+ self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1481
+
1482
+ self.gradient_checkpointing = False
1483
+ # Initialize weights and apply final processing
1484
+ self.post_init()
1485
+
1486
+ def get_input_embeddings(self):
1487
+ return self.embed_tokens
1488
+
1489
+ def set_input_embeddings(self, value):
1490
+ self.embed_tokens = value
1491
+
1492
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1493
+ def forward(
1494
+ self,
1495
+ input_ids: torch.LongTensor = None,
1496
+ attention_mask: Optional[torch.Tensor] = None,
1497
+ position_ids: Optional[torch.LongTensor] = None,
1498
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1499
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1500
+ use_cache: Optional[bool] = None,
1501
+ output_attentions: Optional[bool] = None,
1502
+ output_hidden_states: Optional[bool] = None,
1503
+ return_dict: Optional[bool] = None,
1504
+ cache_position: Optional[torch.LongTensor] = None
1505
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1506
+ output_attentions = (
1507
+ output_attentions
1508
+ if output_attentions is not None
1509
+ else self.config.output_attentions
1510
+ )
1511
+ output_hidden_states = (
1512
+ output_hidden_states
1513
+ if output_hidden_states is not None
1514
+ else self.config.output_hidden_states
1515
+ )
1516
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1517
+
1518
+ return_dict = (
1519
+ return_dict if return_dict is not None else self.config.use_return_dict
1520
+ )
1521
+
1522
+ # retrieve input_ids and inputs_embeds
1523
+ if input_ids is not None and inputs_embeds is not None:
1524
+ raise ValueError(
1525
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1526
+ )
1527
+ elif input_ids is not None:
1528
+ batch_size, seq_length = input_ids.shape[:2]
1529
+ elif inputs_embeds is not None:
1530
+ batch_size, seq_length = inputs_embeds.shape[:2]
1531
+ else:
1532
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1533
+
1534
+ if self.gradient_checkpointing and self.training:
1535
+ if use_cache:
1536
+ logger.warning_once(
1537
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1538
+ )
1539
+ use_cache = False
1540
+
1541
+ past_key_values_length = 0
1542
+ if use_cache:
1543
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1544
+ if use_legacy_cache:
1545
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1546
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1547
+
1548
+ if position_ids is None:
1549
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1550
+ position_ids = torch.arange(
1551
+ past_key_values_length,
1552
+ seq_length + past_key_values_length,
1553
+ dtype=torch.long,
1554
+ device=device,
1555
+ )
1556
+ position_ids = position_ids.unsqueeze(0)
1557
+
1558
+ if inputs_embeds is None:
1559
+ inputs_embeds = self.embed_tokens(input_ids)
1560
+
1561
+ if self._use_flash_attention_2:
1562
+ # 2d mask is passed through the layers
1563
+ attention_mask = (
1564
+ attention_mask
1565
+ if (attention_mask is not None and 0 in attention_mask)
1566
+ else None
1567
+ )
1568
+ else:
1569
+ # 4d mask is passed through the layers
1570
+ attention_mask = _prepare_4d_causal_attention_mask(
1571
+ attention_mask,
1572
+ (batch_size, seq_length),
1573
+ inputs_embeds,
1574
+ past_key_values_length,
1575
+ )
1576
+
1577
+ # embed positions
1578
+ hidden_states = inputs_embeds
1579
+
1580
+ # decoder layers
1581
+ all_hidden_states = () if output_hidden_states else None
1582
+ all_self_attns = () if output_attentions else None
1583
+ next_decoder_cache = None
1584
+
1585
+ for decoder_layer in self.layers:
1586
+ if output_hidden_states:
1587
+ all_hidden_states += (hidden_states,)
1588
+
1589
+ if self.gradient_checkpointing and self.training:
1590
+ layer_outputs = self._gradient_checkpointing_func(
1591
+ decoder_layer.__call__,
1592
+ hidden_states,
1593
+ attention_mask,
1594
+ position_ids,
1595
+ past_key_values,
1596
+ output_attentions,
1597
+ use_cache,
1598
+ )
1599
+ else:
1600
+ layer_outputs = decoder_layer(
1601
+ hidden_states,
1602
+ attention_mask=attention_mask,
1603
+ position_ids=position_ids,
1604
+ past_key_value=past_key_values,
1605
+ output_attentions=output_attentions,
1606
+ use_cache=use_cache,
1607
+ )
1608
+
1609
+ hidden_states = layer_outputs[0]
1610
+
1611
+ if use_cache:
1612
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1613
+
1614
+ if output_attentions:
1615
+ all_self_attns += (layer_outputs[1],)
1616
+
1617
+ hidden_states = self.norm(hidden_states)
1618
+
1619
+ # add hidden states from the last decoder layer
1620
+ if output_hidden_states:
1621
+ all_hidden_states += (hidden_states,)
1622
+
1623
+ next_cache = None
1624
+ if use_cache:
1625
+ next_cache = (
1626
+ next_decoder_cache.to_legacy_cache()
1627
+ if use_legacy_cache
1628
+ else next_decoder_cache
1629
+ )
1630
+ if not return_dict:
1631
+ return tuple(
1632
+ v
1633
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1634
+ if v is not None
1635
+ )
1636
+ return BaseModelOutputWithPast(
1637
+ last_hidden_state=hidden_states,
1638
+ past_key_values=next_cache,
1639
+ hidden_states=all_hidden_states,
1640
+ attentions=all_self_attns,
1641
+ )
1642
+
1643
+
1644
+ class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1645
+ _tied_weights_keys = ["lm_head.weight"]
1646
+
1647
+ def __init__(self, config):
1648
+ super().__init__(config)
1649
+ self.model = DeepseekV2Model(config)
1650
+ self.vocab_size = config.vocab_size
1651
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1652
+
1653
+ # Initialize weights and apply final processing
1654
+ self.post_init()
1655
+
1656
+ def get_input_embeddings(self):
1657
+ return self.model.embed_tokens
1658
+
1659
+ def set_input_embeddings(self, value):
1660
+ self.model.embed_tokens = value
1661
+
1662
+ def get_output_embeddings(self):
1663
+ return self.lm_head
1664
+
1665
+ def set_output_embeddings(self, new_embeddings):
1666
+ self.lm_head = new_embeddings
1667
+
1668
+ def set_decoder(self, decoder):
1669
+ self.model = decoder
1670
+
1671
+ def get_decoder(self):
1672
+ return self.model
1673
+
1674
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1675
+ @replace_return_docstrings(
1676
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1677
+ )
1678
+ def forward(
1679
+ self,
1680
+ input_ids: torch.LongTensor = None,
1681
+ attention_mask: Optional[torch.Tensor] = None,
1682
+ position_ids: Optional[torch.LongTensor] = None,
1683
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1684
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1685
+ labels: Optional[torch.LongTensor] = None,
1686
+ use_cache: Optional[bool] = None,
1687
+ output_attentions: Optional[bool] = None,
1688
+ output_hidden_states: Optional[bool] = None,
1689
+ return_dict: Optional[bool] = None,
1690
+ cache_position: Optional[torch.LongTensor] = None
1691
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1692
+ r"""
1693
+ Args:
1694
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1695
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1696
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1697
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1698
+
1699
+ Returns:
1700
+
1701
+ Example:
1702
+
1703
+ ```python
1704
+ >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1705
+
1706
+ >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1707
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1708
+
1709
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1710
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1711
+
1712
+ >>> # Generate
1713
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1714
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1715
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1716
+ ```"""
1717
+ output_attentions = (
1718
+ output_attentions
1719
+ if output_attentions is not None
1720
+ else self.config.output_attentions
1721
+ )
1722
+ output_hidden_states = (
1723
+ output_hidden_states
1724
+ if output_hidden_states is not None
1725
+ else self.config.output_hidden_states
1726
+ )
1727
+ return_dict = (
1728
+ return_dict if return_dict is not None else self.config.use_return_dict
1729
+ )
1730
+
1731
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1732
+ outputs = self.model(
1733
+ input_ids=input_ids,
1734
+ attention_mask=attention_mask,
1735
+ position_ids=position_ids,
1736
+ past_key_values=past_key_values,
1737
+ inputs_embeds=inputs_embeds,
1738
+ use_cache=use_cache,
1739
+ output_attentions=output_attentions,
1740
+ output_hidden_states=output_hidden_states,
1741
+ return_dict=return_dict,
1742
+ cache_position=cache_position
1743
+ )
1744
+
1745
+ hidden_states = outputs[0]
1746
+ logits = self.lm_head(hidden_states)
1747
+ logits = logits.float()
1748
+
1749
+ loss = None
1750
+ if labels is not None:
1751
+ # Shift so that tokens < n predict n
1752
+ shift_logits = logits[..., :-1, :].contiguous()
1753
+ shift_labels = labels[..., 1:].contiguous()
1754
+ # Flatten the tokens
1755
+ loss_fct = CrossEntropyLoss()
1756
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1757
+ shift_labels = shift_labels.view(-1)
1758
+ # Enable model parallelism
1759
+ shift_labels = shift_labels.to(shift_logits.device)
1760
+ loss = loss_fct(shift_logits, shift_labels)
1761
+
1762
+ if not return_dict:
1763
+ output = (logits,) + outputs[1:]
1764
+ return (loss,) + output if loss is not None else output
1765
+
1766
+ return CausalLMOutputWithPast(
1767
+ loss=loss,
1768
+ logits=logits,
1769
+ past_key_values=outputs.past_key_values,
1770
+ hidden_states=outputs.hidden_states,
1771
+ attentions=outputs.attentions,
1772
+ )
1773
+
1774
+ def prepare_inputs_for_generation(
1775
+ self,
1776
+ input_ids,
1777
+ past_key_values=None,
1778
+ attention_mask=None,
1779
+ inputs_embeds=None,
1780
+ **kwargs,
1781
+ ):
1782
+ past_length = 0
1783
+ if past_key_values is not None:
1784
+ if isinstance(past_key_values, Cache):
1785
+ cache_length = past_key_values.get_seq_length()
1786
+ past_length = past_key_values.seen_tokens
1787
+ max_cache_length = past_key_values.get_max_length()
1788
+ else:
1789
+ cache_length = past_length = past_key_values[0][0].shape[2]
1790
+ max_cache_length = None
1791
+
1792
+ # Keep only the unprocessed tokens:
1793
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1794
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1795
+ # input)
1796
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1797
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1798
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1799
+ # input_ids based on the past_length.
1800
+ elif past_length < input_ids.shape[1]:
1801
+ input_ids = input_ids[:, past_length:]
1802
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1803
+
1804
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1805
+ if (
1806
+ max_cache_length is not None
1807
+ and attention_mask is not None
1808
+ and cache_length + input_ids.shape[1] > max_cache_length
1809
+ ):
1810
+ attention_mask = attention_mask[:, -max_cache_length:]
1811
+
1812
+ position_ids = kwargs.get("position_ids", None)
1813
+ if attention_mask is not None and position_ids is None:
1814
+ # create position_ids on the fly for batch generation
1815
+ position_ids = attention_mask.long().cumsum(-1) - 1
1816
+ position_ids.masked_fill_(attention_mask == 0, 1)
1817
+ if past_key_values:
1818
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1819
+
1820
+ if self.generation_config.cache_implementation == "static":
1821
+ # generation with static cache
1822
+ cache_position = kwargs.get("cache_position", None)
1823
+ if cache_position is None:
1824
+ past_length = 0
1825
+ else:
1826
+ past_length = cache_position[-1] + 1
1827
+ input_ids = input_ids[:, past_length:]
1828
+ position_ids = position_ids[:, past_length:]
1829
+
1830
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
1831
+ # same goes for position ids. Could also help with continued generation.
1832
+ cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
1833
+
1834
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1835
+ if inputs_embeds is not None and past_key_values is None:
1836
+ model_inputs = {"inputs_embeds": inputs_embeds}
1837
+ else:
1838
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1839
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1840
+ # TODO: use `next_tokens` directly instead.
1841
+ model_inputs = {"input_ids": input_ids.contiguous()}
1842
+
1843
+ model_inputs.update(
1844
+ {
1845
+ "position_ids": position_ids.contiguous(),
1846
+ "cache_position": cache_position,
1847
+ "past_key_values": past_key_values,
1848
+ "use_cache": kwargs.get("use_cache"),
1849
+ "attention_mask": attention_mask,
1850
+ }
1851
+ )
1852
+ return model_inputs
1853
+
1854
+ @staticmethod
1855
+ def _reorder_cache(past_key_values, beam_idx):
1856
+ reordered_past = ()
1857
+ for layer_past in past_key_values:
1858
+ reordered_past += (
1859
+ tuple(
1860
+ past_state.index_select(0, beam_idx.to(past_state.device))
1861
+ for past_state in layer_past
1862
+ ),
1863
+ )
1864
+ return reordered_past
1865
+
1866
+
1867
+ @add_start_docstrings(
1868
+ """
1869
+ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
1870
+
1871
+ [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1872
+ (e.g. GPT-2) do.
1873
+
1874
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1875
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1876
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1877
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1878
+ each row of the batch).
1879
+ """,
1880
+ DeepseekV2_START_DOCSTRING,
1881
+ )
1882
+ class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
1883
+ def __init__(self, config):
1884
+ super().__init__(config)
1885
+ self.num_labels = config.num_labels
1886
+ self.model = DeepseekV2Model(config)
1887
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1888
+
1889
+ # Initialize weights and apply final processing
1890
+ self.post_init()
1891
+
1892
+ def get_input_embeddings(self):
1893
+ return self.model.embed_tokens
1894
+
1895
+ def set_input_embeddings(self, value):
1896
+ self.model.embed_tokens = value
1897
+
1898
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1899
+ def forward(
1900
+ self,
1901
+ input_ids: torch.LongTensor = None,
1902
+ attention_mask: Optional[torch.Tensor] = None,
1903
+ position_ids: Optional[torch.LongTensor] = None,
1904
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1905
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1906
+ labels: Optional[torch.LongTensor] = None,
1907
+ use_cache: Optional[bool] = None,
1908
+ output_attentions: Optional[bool] = None,
1909
+ output_hidden_states: Optional[bool] = None,
1910
+ return_dict: Optional[bool] = None,
1911
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1912
+ r"""
1913
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1914
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1915
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1916
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1917
+ """
1918
+ return_dict = (
1919
+ return_dict if return_dict is not None else self.config.use_return_dict
1920
+ )
1921
+
1922
+ transformer_outputs = self.model(
1923
+ input_ids,
1924
+ attention_mask=attention_mask,
1925
+ position_ids=position_ids,
1926
+ past_key_values=past_key_values,
1927
+ inputs_embeds=inputs_embeds,
1928
+ use_cache=use_cache,
1929
+ output_attentions=output_attentions,
1930
+ output_hidden_states=output_hidden_states,
1931
+ return_dict=return_dict,
1932
+ )
1933
+ hidden_states = transformer_outputs[0]
1934
+ logits = self.score(hidden_states)
1935
+
1936
+ if input_ids is not None:
1937
+ batch_size = input_ids.shape[0]
1938
+ else:
1939
+ batch_size = inputs_embeds.shape[0]
1940
+
1941
+ if self.config.pad_token_id is None and batch_size != 1:
1942
+ raise ValueError(
1943
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1944
+ )
1945
+ if self.config.pad_token_id is None:
1946
+ sequence_lengths = -1
1947
+ else:
1948
+ if input_ids is not None:
1949
+ sequence_lengths = (
1950
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1951
+ ).to(logits.device)
1952
+ else:
1953
+ sequence_lengths = -1
1954
+
1955
+ pooled_logits = logits[
1956
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1957
+ ]
1958
+
1959
+ loss = None
1960
+ if labels is not None:
1961
+ labels = labels.to(logits.device)
1962
+ if self.config.problem_type is None:
1963
+ if self.num_labels == 1:
1964
+ self.config.problem_type = "regression"
1965
+ elif self.num_labels > 1 and (
1966
+ labels.dtype == torch.long or labels.dtype == torch.int
1967
+ ):
1968
+ self.config.problem_type = "single_label_classification"
1969
+ else:
1970
+ self.config.problem_type = "multi_label_classification"
1971
+
1972
+ if self.config.problem_type == "regression":
1973
+ loss_fct = MSELoss()
1974
+ if self.num_labels == 1:
1975
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1976
+ else:
1977
+ loss = loss_fct(pooled_logits, labels)
1978
+ elif self.config.problem_type == "single_label_classification":
1979
+ loss_fct = CrossEntropyLoss()
1980
+ loss = loss_fct(
1981
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1982
+ )
1983
+ elif self.config.problem_type == "multi_label_classification":
1984
+ loss_fct = BCEWithLogitsLoss()
1985
+ loss = loss_fct(pooled_logits, labels)
1986
+ if not return_dict:
1987
+ output = (pooled_logits,) + transformer_outputs[1:]
1988
+ return ((loss,) + output) if loss is not None else output
1989
+
1990
+ return SequenceClassifierOutputWithPast(
1991
+ loss=loss,
1992
+ logits=pooled_logits,
1993
+ past_key_values=transformer_outputs.past_key_values,
1994
+ hidden_states=transformer_outputs.hidden_states,
1995
+ attentions=transformer_outputs.attentions,
1996
+ )