seungbo7747 commited on
Commit
15201ee
·
verified ·
1 Parent(s): fc568d2

Upload modeling_deepseek.py

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