BAAI
/

A-PolarBear commited on
Commit
9420d40
·
verified ·
1 Parent(s): 4a06694

Upload modeling_deepseek.py

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