OsakanaTeishoku commited on
Commit
218a819
1 Parent(s): acef7b3

Upload modeling_deepseek.py

Browse files
Files changed (1) hide show
  1. modeling_deepseek.py +1560 -0
modeling_deepseek.py ADDED
@@ -0,0 +1,1560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_deepseek import DeepseekConfig
52
+
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+
59
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
60
+ # It means that the function will not be traced through and simply appear as a node in the graph.
61
+ if is_torch_fx_available():
62
+ if not is_torch_greater_or_equal_than_1_13:
63
+ import torch.fx
64
+
65
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
66
+
67
+
68
+ logger = logging.get_logger(__name__)
69
+
70
+ _CONFIG_FOR_DOC = "DeepseekConfig"
71
+
72
+
73
+ def _get_unpad_data(attention_mask):
74
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
75
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
76
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
77
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
78
+ return (
79
+ indices,
80
+ cu_seqlens,
81
+ max_seqlen_in_batch,
82
+ )
83
+
84
+
85
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
86
+ warnings.warn(
87
+ "Calling `transformers.models.Deepseek.modeling_Deepseek._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
88
+ )
89
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
90
+
91
+
92
+ def _make_causal_mask(
93
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
94
+ ):
95
+ warnings.warn(
96
+ "Calling `transformers.models.Deepseek.modeling_Deepseek._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.Deepseek.modeling_Deepseek.AttentionMaskConverter._make_causal_mask"
97
+ )
98
+ return AttentionMaskConverter._make_causal_mask(
99
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
100
+ )
101
+
102
+
103
+ class DeepseekRMSNorm(nn.Module):
104
+ def __init__(self, hidden_size, eps=1e-6):
105
+ """
106
+ DeepseekRMSNorm is equivalent to T5LayerNorm
107
+ """
108
+ super().__init__()
109
+ self.weight = nn.Parameter(torch.ones(hidden_size))
110
+ self.variance_epsilon = eps
111
+
112
+ def forward(self, hidden_states):
113
+ input_dtype = hidden_states.dtype
114
+ hidden_states = hidden_states.to(torch.float32)
115
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
116
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
117
+ return self.weight * hidden_states.to(input_dtype)
118
+
119
+
120
+ ALL_LAYERNORM_LAYERS.append(DeepseekRMSNorm)
121
+
122
+
123
+ class DeepseekRotaryEmbedding(nn.Module):
124
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
125
+ super().__init__()
126
+
127
+ self.dim = dim
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.base = base
130
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
131
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
132
+
133
+ # Build here to make `torch.jit.trace` work.
134
+ self._set_cos_sin_cache(
135
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
136
+ )
137
+ self.max_seq_len_cached = None
138
+
139
+
140
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
141
+ self.max_seq_len_cached = seq_len
142
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
143
+
144
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
145
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
146
+ emb = torch.cat((freqs, freqs), dim=-1)
147
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
148
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
149
+
150
+ def forward(self, x, seq_len=None):
151
+ # x: [bs, num_attention_heads, seq_len, head_size]
152
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
153
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
154
+
155
+ return (
156
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
157
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
158
+ )
159
+
160
+
161
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Deepseek
162
+ class DeepseekLinearScalingRotaryEmbedding(DeepseekRotaryEmbedding):
163
+ """DeepseekRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
164
+
165
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
166
+ self.scaling_factor = scaling_factor
167
+ super().__init__(dim, max_position_embeddings, base, device)
168
+
169
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
170
+ self.max_seq_len_cached = seq_len
171
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
172
+ t = t / self.scaling_factor
173
+
174
+ freqs = torch.outer(t, self.inv_freq)
175
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
176
+ emb = torch.cat((freqs, freqs), dim=-1)
177
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
178
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
179
+
180
+
181
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Deepseek
182
+ class DeepseekDynamicNTKScalingRotaryEmbedding(DeepseekRotaryEmbedding):
183
+ """DeepseekRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
184
+
185
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
186
+ self.scaling_factor = scaling_factor
187
+ super().__init__(dim, max_position_embeddings, base, device)
188
+
189
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
190
+ self.max_seq_len_cached = seq_len
191
+
192
+ if seq_len > self.max_position_embeddings:
193
+ base = self.base * (
194
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
195
+ ) ** (self.dim / (self.dim - 2))
196
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
197
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
198
+
199
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
200
+
201
+ freqs = torch.outer(t, self.inv_freq)
202
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
203
+ emb = torch.cat((freqs, freqs), dim=-1)
204
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
205
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
206
+
207
+
208
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
209
+ def rotate_half(x):
210
+ """Rotates half the hidden dims of the input."""
211
+ x1 = x[..., : x.shape[-1] // 2]
212
+ x2 = x[..., x.shape[-1] // 2 :]
213
+ return torch.cat((-x2, x1), dim=-1)
214
+
215
+
216
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
217
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
218
+ """Applies Rotary Position Embedding to the query and key tensors.
219
+
220
+ Args:
221
+ q (`torch.Tensor`): The query tensor.
222
+ k (`torch.Tensor`): The key tensor.
223
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
224
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
225
+ position_ids (`torch.Tensor`):
226
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
227
+ used to pass offsetted position ids when working with a KV-cache.
228
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
229
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
230
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
231
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
232
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
233
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
234
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
235
+ Returns:
236
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
237
+ """
238
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
239
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
240
+ q_embed = (q * cos) + (rotate_half(q) * sin)
241
+ k_embed = (k * cos) + (rotate_half(k) * sin)
242
+ return q_embed, k_embed
243
+
244
+
245
+ class DeepseekMLP(nn.Module):
246
+ def __init__(self, config, hidden_size = None, intermediate_size = None):
247
+ super().__init__()
248
+ self.config = config
249
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
250
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
251
+
252
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
253
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
254
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
255
+ self.act_fn = ACT2FN[config.hidden_act]
256
+
257
+ def forward(self, x):
258
+ if self.config.pretraining_tp > 1:
259
+ slice = self.intermediate_size // self.config.pretraining_tp
260
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
261
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
262
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
263
+
264
+ gate_proj = torch.cat(
265
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
266
+ )
267
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
268
+
269
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
270
+ down_proj = [
271
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
272
+ ]
273
+ down_proj = sum(down_proj)
274
+ else:
275
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
276
+
277
+ return down_proj
278
+
279
+
280
+ class MoEGate(nn.Module):
281
+ def __init__(self, config):
282
+ super().__init__()
283
+ self.config = config
284
+ self.top_k = config.num_experts_per_tok
285
+ self.n_routed_experts = config.n_routed_experts
286
+
287
+ self.scoring_func = config.scoring_func
288
+ self.alpha = config.aux_loss_alpha
289
+ self.seq_aux = config.seq_aux
290
+
291
+ # topk selection algorithm
292
+ self.norm_topk_prob = config.norm_topk_prob
293
+ self.gating_dim = config.hidden_size
294
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
295
+ self.reset_parameters()
296
+
297
+ def reset_parameters(self) -> None:
298
+ import torch.nn.init as init
299
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
300
+
301
+ def forward(self, hidden_states):
302
+ bsz, seq_len, h = hidden_states.shape
303
+ ### compute gating score
304
+ hidden_states = hidden_states.view(-1, h)
305
+ logits = F.linear(hidden_states, self.weight, None)
306
+ if self.scoring_func == 'softmax':
307
+ scores = logits.softmax(dim=-1)
308
+ else:
309
+ raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
310
+
311
+ ### select top-k experts
312
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
313
+
314
+ ### norm gate to sum 1
315
+ if self.top_k > 1 and self.norm_topk_prob:
316
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
317
+ topk_weight = topk_weight / denominator
318
+
319
+ ### expert-level computation auxiliary loss
320
+ if self.training and self.alpha > 0.0:
321
+ scores_for_aux = scores
322
+ aux_topk = self.top_k
323
+ # always compute aux loss based on the naive greedy topk method
324
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
325
+ if self.seq_aux:
326
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
327
+ ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
328
+ ce.scatter_add_(1, topk_idx_for_aux_loss, torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(seq_len * aux_topk / self.n_routed_experts)
329
+ aux_loss = (ce * scores_for_seq_aux.mean(dim = 1)).sum(dim = 1).mean() * self.alpha
330
+ else:
331
+ mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
332
+ ce = mask_ce.float().mean(0)
333
+ Pi = scores_for_aux.mean(0)
334
+ fi = ce * self.n_routed_experts
335
+ aux_loss = (Pi * fi).sum() * self.alpha
336
+ else:
337
+ aux_loss = None
338
+ return topk_idx, topk_weight, aux_loss
339
+
340
+
341
+ class AddAuxiliaryLoss(torch.autograd.Function):
342
+ """
343
+ The trick function of adding auxiliary (aux) loss,
344
+ which includes the gradient of the aux loss during backpropagation.
345
+ """
346
+ @staticmethod
347
+ def forward(ctx, x, loss):
348
+ assert loss.numel() == 1
349
+ ctx.dtype = loss.dtype
350
+ ctx.required_aux_loss = loss.requires_grad
351
+ return x
352
+
353
+ @staticmethod
354
+ def backward(ctx, grad_output):
355
+ grad_loss = None
356
+ if ctx.required_aux_loss:
357
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
358
+ return grad_output, grad_loss
359
+
360
+
361
+ class DeepseekMoE(nn.Module):
362
+ """
363
+ A mixed expert module containing shared experts.
364
+ """
365
+ def __init__(self, config):
366
+ super().__init__()
367
+ self.config = config
368
+ self.num_experts_per_tok = config.num_experts_per_tok
369
+ self.experts = nn.ModuleList([DeepseekMLP(config, intermediate_size = config.moe_intermediate_size) for i in range(config.n_routed_experts)])
370
+ self.gate = MoEGate(config)
371
+ if config.n_shared_experts is not None:
372
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
373
+ self.shared_experts = DeepseekMLP(config=config, intermediate_size = intermediate_size)
374
+
375
+ def forward(self, hidden_states):
376
+ identity = hidden_states
377
+ orig_shape = hidden_states.shape
378
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
379
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
380
+ flat_topk_idx = topk_idx.view(-1)
381
+ if self.training:
382
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
383
+ y = torch.empty_like(hidden_states)
384
+ for i, expert in enumerate(self.experts):
385
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
386
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
387
+ y = y.view(*orig_shape)
388
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
389
+ else:
390
+ y = self.moe_infer(hidden_states, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
391
+ if self.config.n_shared_experts is not None:
392
+ y = y + self.shared_experts(identity)
393
+ return y
394
+
395
+ @torch.no_grad()
396
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
397
+ expert_cache = torch.zeros_like(x)
398
+ idxs = flat_expert_indices.argsort()
399
+ tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
400
+ token_idxs = idxs // self.num_experts_per_tok
401
+ for i, end_idx in enumerate(tokens_per_expert):
402
+ start_idx = 0 if i == 0 else tokens_per_expert[i-1]
403
+ if start_idx == end_idx:
404
+ continue
405
+ expert = self.experts[i]
406
+ exp_token_idx = token_idxs[start_idx:end_idx]
407
+ expert_tokens = x[exp_token_idx]
408
+ expert_out = expert(expert_tokens)
409
+ expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
410
+ expert_cache.scatter_reduce_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out, reduce='sum')
411
+ return expert_cache
412
+
413
+
414
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
415
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
416
+ """
417
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
418
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
419
+ """
420
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
421
+ if n_rep == 1:
422
+ return hidden_states
423
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
424
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
425
+
426
+
427
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->Deepseek
428
+ class DeepseekAttention(nn.Module):
429
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
430
+
431
+ def __init__(self, config: DeepseekConfig, layer_idx: Optional[int] = None):
432
+ super().__init__()
433
+ self.config = config
434
+ self.layer_idx = layer_idx
435
+ if layer_idx is None:
436
+ logger.warning_once(
437
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
438
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
439
+ "when creating this class."
440
+ )
441
+
442
+ self.attention_dropout = config.attention_dropout
443
+ self.hidden_size = config.hidden_size
444
+ self.num_heads = config.num_attention_heads
445
+ self.head_dim = self.hidden_size // self.num_heads
446
+ self.num_key_value_heads = config.num_key_value_heads
447
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
448
+ self.max_position_embeddings = config.max_position_embeddings
449
+ self.rope_theta = config.rope_theta
450
+ self.is_causal = True
451
+
452
+ if (self.head_dim * self.num_heads) != self.hidden_size:
453
+ raise ValueError(
454
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
455
+ f" and `num_heads`: {self.num_heads})."
456
+ )
457
+
458
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
459
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
460
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
461
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
462
+ self._init_rope()
463
+
464
+ def _init_rope(self):
465
+ if self.config.rope_scaling is None:
466
+ self.rotary_emb = DeepseekRotaryEmbedding(
467
+ self.head_dim,
468
+ max_position_embeddings=self.max_position_embeddings,
469
+ base=self.rope_theta,
470
+ )
471
+ else:
472
+ scaling_type = self.config.rope_scaling["type"]
473
+ scaling_factor = self.config.rope_scaling["factor"]
474
+ if scaling_type == "linear":
475
+ self.rotary_emb = DeepseekLinearScalingRotaryEmbedding(
476
+ self.head_dim,
477
+ max_position_embeddings=self.max_position_embeddings,
478
+ scaling_factor=scaling_factor,
479
+ base=self.rope_theta,
480
+ )
481
+ elif scaling_type == "dynamic":
482
+ self.rotary_emb = DeepseekDynamicNTKScalingRotaryEmbedding(
483
+ self.head_dim,
484
+ max_position_embeddings=self.max_position_embeddings,
485
+ scaling_factor=scaling_factor,
486
+ base=self.rope_theta,
487
+ )
488
+ else:
489
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
490
+
491
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
492
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
493
+
494
+ def forward(
495
+ self,
496
+ hidden_states: torch.Tensor,
497
+ attention_mask: Optional[torch.Tensor] = None,
498
+ position_ids: Optional[torch.LongTensor] = None,
499
+ past_key_value: Optional[Cache] = None,
500
+ output_attentions: bool = False,
501
+ use_cache: bool = False,
502
+ **kwargs,
503
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
504
+ if "padding_mask" in kwargs:
505
+ warnings.warn(
506
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
507
+ )
508
+
509
+ bsz, q_len, _ = hidden_states.size()
510
+
511
+ if self.config.pretraining_tp > 1:
512
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
513
+ query_slices = self.q_proj.weight.split(
514
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
515
+ )
516
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
517
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
518
+
519
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
520
+ query_states = torch.cat(query_states, dim=-1)
521
+
522
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
523
+ key_states = torch.cat(key_states, dim=-1)
524
+
525
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
526
+ value_states = torch.cat(value_states, dim=-1)
527
+
528
+ else:
529
+ query_states = self.q_proj(hidden_states)
530
+ key_states = self.k_proj(hidden_states)
531
+ value_states = self.v_proj(hidden_states)
532
+
533
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
534
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
535
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
536
+
537
+ kv_seq_len = key_states.shape[-2]
538
+ if past_key_value is not None:
539
+ if self.layer_idx is None:
540
+ raise ValueError(
541
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
542
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
543
+ "with a layer index."
544
+ )
545
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
546
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
547
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
548
+
549
+ if past_key_value is not None:
550
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
551
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
552
+
553
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
554
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
555
+
556
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
557
+
558
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
559
+ raise ValueError(
560
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
561
+ f" {attn_weights.size()}"
562
+ )
563
+
564
+ if attention_mask is not None:
565
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
566
+ raise ValueError(
567
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
568
+ )
569
+ attn_weights = attn_weights + attention_mask
570
+
571
+ # upcast attention to fp32
572
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
573
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
574
+ attn_output = torch.matmul(attn_weights, value_states)
575
+
576
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
577
+ raise ValueError(
578
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
579
+ f" {attn_output.size()}"
580
+ )
581
+
582
+ attn_output = attn_output.transpose(1, 2).contiguous()
583
+
584
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
585
+
586
+ if self.config.pretraining_tp > 1:
587
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
588
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
589
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
590
+ else:
591
+ attn_output = self.o_proj(attn_output)
592
+
593
+ if not output_attentions:
594
+ attn_weights = None
595
+
596
+ return attn_output, attn_weights, past_key_value
597
+
598
+
599
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Deepseek
600
+ class DeepseekFlashAttention2(DeepseekAttention):
601
+ """
602
+ Deepseek flash attention module. This module inherits from `DeepseekAttention` as the weights of the module stays
603
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
604
+ flash attention and deal with padding tokens in case the input contains any of them.
605
+ """
606
+
607
+ def __init__(self, *args, **kwargs):
608
+ super().__init__(*args, **kwargs)
609
+
610
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
611
+ # 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.
612
+ # 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).
613
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
614
+
615
+ def forward(
616
+ self,
617
+ hidden_states: torch.Tensor,
618
+ attention_mask: Optional[torch.LongTensor] = None,
619
+ position_ids: Optional[torch.LongTensor] = None,
620
+ past_key_value: Optional[Cache] = None,
621
+ output_attentions: bool = False,
622
+ use_cache: bool = False,
623
+ **kwargs,
624
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
625
+ # DeepseekFlashAttention2 attention does not support output_attentions
626
+ if "padding_mask" in kwargs:
627
+ warnings.warn(
628
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
629
+ )
630
+
631
+ # overwrite attention_mask with padding_mask
632
+ attention_mask = kwargs.pop("padding_mask")
633
+
634
+ output_attentions = False
635
+
636
+ bsz, q_len, _ = hidden_states.size()
637
+
638
+ query_states = self.q_proj(hidden_states)
639
+ key_states = self.k_proj(hidden_states)
640
+ value_states = self.v_proj(hidden_states)
641
+
642
+ # Flash attention requires the input to have the shape
643
+ # batch_size x seq_length x head_dim x hidden_dim
644
+ # therefore we just need to keep the original shape
645
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
646
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
647
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
648
+
649
+ kv_seq_len = key_states.shape[-2]
650
+ if past_key_value is not None:
651
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
652
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
653
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
654
+
655
+ if past_key_value is not None:
656
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
657
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
658
+
659
+ # 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
660
+ # to be able to avoid many of these transpose/reshape/view.
661
+ query_states = query_states.transpose(1, 2)
662
+ key_states = key_states.transpose(1, 2)
663
+ value_states = value_states.transpose(1, 2)
664
+
665
+ dropout_rate = self.attention_dropout if self.training else 0.0
666
+
667
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
668
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
669
+ # cast them back in the correct dtype just to be sure everything works as expected.
670
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
671
+ # in fp32. (DeepseekRMSNorm handles it correctly)
672
+
673
+ input_dtype = query_states.dtype
674
+ if input_dtype == torch.float32:
675
+ # Handle the case where the model is quantized
676
+ if hasattr(self.config, "_pre_quantization_dtype"):
677
+ target_dtype = self.config._pre_quantization_dtype
678
+ elif torch.is_autocast_enabled():
679
+ target_dtype = torch.get_autocast_gpu_dtype()
680
+ else:
681
+ target_dtype = self.q_proj.weight.dtype
682
+
683
+ logger.warning_once(
684
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
685
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
686
+ f" {target_dtype}."
687
+ )
688
+
689
+ query_states = query_states.to(target_dtype)
690
+ key_states = key_states.to(target_dtype)
691
+ value_states = value_states.to(target_dtype)
692
+
693
+ attn_output = self._flash_attention_forward(
694
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
695
+ )
696
+
697
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
698
+ attn_output = self.o_proj(attn_output)
699
+
700
+ if not output_attentions:
701
+ attn_weights = None
702
+
703
+ return attn_output, attn_weights, past_key_value
704
+
705
+ def _flash_attention_forward(
706
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
707
+ ):
708
+ """
709
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
710
+ first unpad the input, then computes the attention scores and pad the final attention scores.
711
+
712
+ Args:
713
+ query_states (`torch.Tensor`):
714
+ Input query states to be passed to Flash Attention API
715
+ key_states (`torch.Tensor`):
716
+ Input key states to be passed to Flash Attention API
717
+ value_states (`torch.Tensor`):
718
+ Input value states to be passed to Flash Attention API
719
+ attention_mask (`torch.Tensor`):
720
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
721
+ position of padding tokens and 1 for the position of non-padding tokens.
722
+ dropout (`int`, *optional*):
723
+ Attention dropout
724
+ softmax_scale (`float`, *optional*):
725
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
726
+ """
727
+ if not self._flash_attn_uses_top_left_mask:
728
+ causal = self.is_causal
729
+ else:
730
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekFlashAttention2 __init__.
731
+ causal = self.is_causal and query_length != 1
732
+
733
+ # Contains at least one padding token in the sequence
734
+ if attention_mask is not None:
735
+ batch_size = query_states.shape[0]
736
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
737
+ query_states, key_states, value_states, attention_mask, query_length
738
+ )
739
+
740
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
741
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
742
+
743
+ attn_output_unpad = flash_attn_varlen_func(
744
+ query_states,
745
+ key_states,
746
+ value_states,
747
+ cu_seqlens_q=cu_seqlens_q,
748
+ cu_seqlens_k=cu_seqlens_k,
749
+ max_seqlen_q=max_seqlen_in_batch_q,
750
+ max_seqlen_k=max_seqlen_in_batch_k,
751
+ dropout_p=dropout,
752
+ softmax_scale=softmax_scale,
753
+ causal=causal,
754
+ )
755
+
756
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
757
+ else:
758
+ attn_output = flash_attn_func(
759
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
760
+ )
761
+
762
+ return attn_output
763
+
764
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
765
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
766
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
767
+
768
+ key_layer = index_first_axis(
769
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
770
+ )
771
+ value_layer = index_first_axis(
772
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
773
+ )
774
+ if query_length == kv_seq_len:
775
+ query_layer = index_first_axis(
776
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
777
+ )
778
+ cu_seqlens_q = cu_seqlens_k
779
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
780
+ indices_q = indices_k
781
+ elif query_length == 1:
782
+ max_seqlen_in_batch_q = 1
783
+ cu_seqlens_q = torch.arange(
784
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
785
+ ) # There is a memcpy here, that is very bad.
786
+ indices_q = cu_seqlens_q[:-1]
787
+ query_layer = query_layer.squeeze(1)
788
+ else:
789
+ # The -q_len: slice assumes left padding.
790
+ attention_mask = attention_mask[:, -query_length:]
791
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
792
+
793
+ return (
794
+ query_layer,
795
+ key_layer,
796
+ value_layer,
797
+ indices_q,
798
+ (cu_seqlens_q, cu_seqlens_k),
799
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
800
+ )
801
+
802
+
803
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Deepseek
804
+ class DeepseekSdpaAttention(DeepseekAttention):
805
+ """
806
+ Deepseek attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
807
+ `DeepseekAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
808
+ SDPA API.
809
+ """
810
+
811
+ # Adapted from DeepseekAttention.forward
812
+ def forward(
813
+ self,
814
+ hidden_states: torch.Tensor,
815
+ attention_mask: Optional[torch.Tensor] = None,
816
+ position_ids: Optional[torch.LongTensor] = None,
817
+ past_key_value: Optional[Cache] = None,
818
+ output_attentions: bool = False,
819
+ use_cache: bool = False,
820
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
821
+ if output_attentions:
822
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
823
+ logger.warning_once(
824
+ "DeepseekModel is using DeepseekSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
825
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
826
+ )
827
+ return super().forward(
828
+ hidden_states=hidden_states,
829
+ attention_mask=attention_mask,
830
+ position_ids=position_ids,
831
+ past_key_value=past_key_value,
832
+ output_attentions=output_attentions,
833
+ use_cache=use_cache,
834
+ )
835
+
836
+ bsz, q_len, _ = hidden_states.size()
837
+
838
+ query_states = self.q_proj(hidden_states)
839
+ key_states = self.k_proj(hidden_states)
840
+ value_states = self.v_proj(hidden_states)
841
+
842
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
843
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
844
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
845
+
846
+ kv_seq_len = key_states.shape[-2]
847
+ if past_key_value is not None:
848
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
849
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
850
+
851
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
852
+
853
+ if past_key_value is not None:
854
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
855
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
856
+
857
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
858
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
859
+
860
+ if attention_mask is not None:
861
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
862
+ raise ValueError(
863
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
864
+ )
865
+
866
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
867
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
868
+ if query_states.device.type == "cuda" and attention_mask is not None:
869
+ query_states = query_states.contiguous()
870
+ key_states = key_states.contiguous()
871
+ value_states = value_states.contiguous()
872
+
873
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
874
+ query_states,
875
+ key_states,
876
+ value_states,
877
+ attn_mask=attention_mask,
878
+ dropout_p=self.attention_dropout if self.training else 0.0,
879
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
880
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
881
+ )
882
+
883
+ attn_output = attn_output.transpose(1, 2).contiguous()
884
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
885
+
886
+ attn_output = self.o_proj(attn_output)
887
+
888
+ return attn_output, None, past_key_value
889
+
890
+
891
+ Deepseek_ATTENTION_CLASSES = {
892
+ "eager": DeepseekAttention,
893
+ "flash_attention_2": DeepseekFlashAttention2,
894
+ "sdpa": DeepseekSdpaAttention,
895
+ }
896
+
897
+
898
+ class DeepseekDecoderLayer(nn.Module):
899
+ def __init__(self, config: DeepseekConfig, layer_idx: int):
900
+ super().__init__()
901
+ self.hidden_size = config.hidden_size
902
+
903
+ self.self_attn = Deepseek_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
904
+
905
+ self.mlp = DeepseekMoE(config) if (config.n_routed_experts is not None and \
906
+ layer_idx >= config.first_k_dense_replace and layer_idx % config.moe_layer_freq == 0) \
907
+ else DeepseekMLP(config)
908
+ self.input_layernorm = DeepseekRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
909
+ self.post_attention_layernorm = DeepseekRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
910
+
911
+ def forward(
912
+ self,
913
+ hidden_states: torch.Tensor,
914
+ attention_mask: Optional[torch.Tensor] = None,
915
+ position_ids: Optional[torch.LongTensor] = None,
916
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
917
+ output_attentions: Optional[bool] = False,
918
+ use_cache: Optional[bool] = False,
919
+ **kwargs,
920
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
921
+ """
922
+ Args:
923
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
924
+ attention_mask (`torch.FloatTensor`, *optional*):
925
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
926
+ query_sequence_length, key_sequence_length)` if default attention is used.
927
+ output_attentions (`bool`, *optional*):
928
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
929
+ returned tensors for more detail.
930
+ use_cache (`bool`, *optional*):
931
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
932
+ (see `past_key_values`).
933
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
934
+ """
935
+ if "padding_mask" in kwargs:
936
+ warnings.warn(
937
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
938
+ )
939
+ residual = hidden_states
940
+
941
+ hidden_states = self.input_layernorm(hidden_states)
942
+
943
+ # Self Attention
944
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
945
+ hidden_states=hidden_states,
946
+ attention_mask=attention_mask,
947
+ position_ids=position_ids,
948
+ past_key_value=past_key_value,
949
+ output_attentions=output_attentions,
950
+ use_cache=use_cache,
951
+ **kwargs,
952
+ )
953
+ hidden_states = residual + hidden_states
954
+
955
+ # Fully Connected
956
+ residual = hidden_states
957
+ hidden_states = self.post_attention_layernorm(hidden_states)
958
+ hidden_states = self.mlp(hidden_states)
959
+ hidden_states = residual + hidden_states
960
+
961
+ outputs = (hidden_states,)
962
+
963
+ if output_attentions:
964
+ outputs += (self_attn_weights,)
965
+
966
+ if use_cache:
967
+ outputs += (present_key_value,)
968
+
969
+ return outputs
970
+
971
+
972
+ Deepseek_START_DOCSTRING = r"""
973
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
974
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
975
+ etc.)
976
+
977
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
978
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
979
+ and behavior.
980
+
981
+ Parameters:
982
+ config ([`DeepseekConfig`]):
983
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
984
+ load the weights associated with the model, only the configuration. Check out the
985
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
986
+ """
987
+
988
+
989
+ @add_start_docstrings(
990
+ "The bare Deepseek Model outputting raw hidden-states without any specific head on top.",
991
+ Deepseek_START_DOCSTRING,
992
+ )
993
+ class DeepseekPreTrainedModel(PreTrainedModel):
994
+ config_class = DeepseekConfig
995
+ base_model_prefix = "model"
996
+ supports_gradient_checkpointing = True
997
+ _no_split_modules = ["DeepseekDecoderLayer"]
998
+ _skip_keys_device_placement = "past_key_values"
999
+ _supports_flash_attn_2 = True
1000
+ _supports_sdpa = True
1001
+ _supports_cache_class = True
1002
+
1003
+ def _init_weights(self, module):
1004
+ std = self.config.initializer_range
1005
+ if isinstance(module, nn.Linear):
1006
+ module.weight.data.normal_(mean=0.0, std=std)
1007
+ if module.bias is not None:
1008
+ module.bias.data.zero_()
1009
+ elif isinstance(module, nn.Embedding):
1010
+ module.weight.data.normal_(mean=0.0, std=std)
1011
+ if module.padding_idx is not None:
1012
+ module.weight.data[module.padding_idx].zero_()
1013
+
1014
+
1015
+ Deepseek_INPUTS_DOCSTRING = r"""
1016
+ Args:
1017
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1018
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1019
+ it.
1020
+
1021
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1022
+ [`PreTrainedTokenizer.__call__`] for details.
1023
+
1024
+ [What are input IDs?](../glossary#input-ids)
1025
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1026
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1027
+
1028
+ - 1 for tokens that are **not masked**,
1029
+ - 0 for tokens that are **masked**.
1030
+
1031
+ [What are attention masks?](../glossary#attention-mask)
1032
+
1033
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1034
+ [`PreTrainedTokenizer.__call__`] for details.
1035
+
1036
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1037
+ `past_key_values`).
1038
+
1039
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1040
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1041
+ information on the default strategy.
1042
+
1043
+ - 1 indicates the head is **not masked**,
1044
+ - 0 indicates the head is **masked**.
1045
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1046
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1047
+ config.n_positions - 1]`.
1048
+
1049
+ [What are position IDs?](../glossary#position-ids)
1050
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1051
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1052
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1053
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1054
+
1055
+ Two formats are allowed:
1056
+ - a [`~cache_utils.Cache`] instance;
1057
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1058
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1059
+ cache format.
1060
+
1061
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1062
+ legacy cache format will be returned.
1063
+
1064
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1065
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1066
+ of shape `(batch_size, sequence_length)`.
1067
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1068
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1069
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1070
+ model's internal embedding lookup matrix.
1071
+ use_cache (`bool`, *optional*):
1072
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1073
+ `past_key_values`).
1074
+ output_attentions (`bool`, *optional*):
1075
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1076
+ tensors for more detail.
1077
+ output_hidden_states (`bool`, *optional*):
1078
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1079
+ more detail.
1080
+ return_dict (`bool`, *optional*):
1081
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1082
+ """
1083
+
1084
+
1085
+ @add_start_docstrings(
1086
+ "The bare Deepseek Model outputting raw hidden-states without any specific head on top.",
1087
+ Deepseek_START_DOCSTRING,
1088
+ )
1089
+ class DeepseekModel(DeepseekPreTrainedModel):
1090
+ """
1091
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekDecoderLayer`]
1092
+
1093
+ Args:
1094
+ config: DeepseekConfig
1095
+ """
1096
+
1097
+ def __init__(self, config: DeepseekConfig):
1098
+ super().__init__(config)
1099
+ self.padding_idx = config.pad_token_id
1100
+ self.vocab_size = config.vocab_size
1101
+
1102
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1103
+ self.layers = nn.ModuleList(
1104
+ [DeepseekDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1105
+ )
1106
+ self._use_sdpa = config._attn_implementation == "sdpa"
1107
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1108
+ self.norm = DeepseekRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1109
+
1110
+ self.gradient_checkpointing = False
1111
+ # Initialize weights and apply final processing
1112
+ self.post_init()
1113
+
1114
+ def get_input_embeddings(self):
1115
+ return self.embed_tokens
1116
+
1117
+ def set_input_embeddings(self, value):
1118
+ self.embed_tokens = value
1119
+
1120
+ @add_start_docstrings_to_model_forward(Deepseek_INPUTS_DOCSTRING)
1121
+ def forward(
1122
+ self,
1123
+ input_ids: torch.LongTensor = None,
1124
+ attention_mask: Optional[torch.Tensor] = None,
1125
+ position_ids: Optional[torch.LongTensor] = None,
1126
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1127
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1128
+ use_cache: Optional[bool] = None,
1129
+ output_attentions: Optional[bool] = None,
1130
+ output_hidden_states: Optional[bool] = None,
1131
+ return_dict: Optional[bool] = None,
1132
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1133
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1134
+ output_hidden_states = (
1135
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1136
+ )
1137
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1138
+
1139
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1140
+
1141
+ # retrieve input_ids and inputs_embeds
1142
+ if input_ids is not None and inputs_embeds is not None:
1143
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1144
+ elif input_ids is not None:
1145
+ batch_size, seq_length = input_ids.shape[:2]
1146
+ elif inputs_embeds is not None:
1147
+ batch_size, seq_length = inputs_embeds.shape[:2]
1148
+ else:
1149
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1150
+
1151
+ if self.gradient_checkpointing and self.training:
1152
+ if use_cache:
1153
+ logger.warning_once(
1154
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1155
+ )
1156
+ use_cache = False
1157
+
1158
+ past_key_values_length = 0
1159
+ if use_cache:
1160
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1161
+ if use_legacy_cache:
1162
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1163
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1164
+
1165
+ if position_ids is None:
1166
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1167
+ position_ids = torch.arange(
1168
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1169
+ )
1170
+ position_ids = position_ids.unsqueeze(0)
1171
+
1172
+ if inputs_embeds is None:
1173
+ inputs_embeds = self.embed_tokens(input_ids)
1174
+
1175
+ if self._use_flash_attention_2:
1176
+ # 2d mask is passed through the layers
1177
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1178
+ elif self._use_sdpa and not output_attentions:
1179
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1180
+ # the manual implementation that requires a 4D causal mask in all cases.
1181
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1182
+ attention_mask,
1183
+ (batch_size, seq_length),
1184
+ inputs_embeds,
1185
+ past_key_values_length,
1186
+ )
1187
+ else:
1188
+ # 4d mask is passed through the layers
1189
+ attention_mask = _prepare_4d_causal_attention_mask(
1190
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1191
+ )
1192
+
1193
+ # embed positions
1194
+ hidden_states = inputs_embeds
1195
+
1196
+ # decoder layers
1197
+ all_hidden_states = () if output_hidden_states else None
1198
+ all_self_attns = () if output_attentions else None
1199
+ next_decoder_cache = None
1200
+
1201
+ for decoder_layer in self.layers:
1202
+ if output_hidden_states:
1203
+ all_hidden_states += (hidden_states,)
1204
+
1205
+ if self.gradient_checkpointing and self.training:
1206
+ layer_outputs = self._gradient_checkpointing_func(
1207
+ decoder_layer.__call__,
1208
+ hidden_states,
1209
+ attention_mask,
1210
+ position_ids,
1211
+ past_key_values,
1212
+ output_attentions,
1213
+ use_cache,
1214
+ )
1215
+ else:
1216
+ layer_outputs = decoder_layer(
1217
+ hidden_states,
1218
+ attention_mask=attention_mask,
1219
+ position_ids=position_ids,
1220
+ past_key_value=past_key_values,
1221
+ output_attentions=output_attentions,
1222
+ use_cache=use_cache,
1223
+ )
1224
+
1225
+ hidden_states = layer_outputs[0]
1226
+
1227
+ if use_cache:
1228
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1229
+
1230
+ if output_attentions:
1231
+ all_self_attns += (layer_outputs[1],)
1232
+
1233
+ hidden_states = self.norm(hidden_states)
1234
+
1235
+ # add hidden states from the last decoder layer
1236
+ if output_hidden_states:
1237
+ all_hidden_states += (hidden_states,)
1238
+
1239
+ next_cache = None
1240
+ if use_cache:
1241
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1242
+ if not return_dict:
1243
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1244
+ return BaseModelOutputWithPast(
1245
+ last_hidden_state=hidden_states,
1246
+ past_key_values=next_cache,
1247
+ hidden_states=all_hidden_states,
1248
+ attentions=all_self_attns,
1249
+ )
1250
+
1251
+
1252
+ class DeepseekForCausalLM(DeepseekPreTrainedModel):
1253
+ _tied_weights_keys = ["lm_head.weight"]
1254
+
1255
+ def __init__(self, config):
1256
+ super().__init__(config)
1257
+ self.model = DeepseekModel(config)
1258
+ self.vocab_size = config.vocab_size
1259
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1260
+
1261
+ # Initialize weights and apply final processing
1262
+ self.post_init()
1263
+
1264
+ def get_input_embeddings(self):
1265
+ return self.model.embed_tokens
1266
+
1267
+ def set_input_embeddings(self, value):
1268
+ self.model.embed_tokens = value
1269
+
1270
+ def get_output_embeddings(self):
1271
+ return self.lm_head
1272
+
1273
+ def set_output_embeddings(self, new_embeddings):
1274
+ self.lm_head = new_embeddings
1275
+
1276
+ def set_decoder(self, decoder):
1277
+ self.model = decoder
1278
+
1279
+ def get_decoder(self):
1280
+ return self.model
1281
+
1282
+ @add_start_docstrings_to_model_forward(Deepseek_INPUTS_DOCSTRING)
1283
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1284
+ def forward(
1285
+ self,
1286
+ input_ids: torch.LongTensor = None,
1287
+ attention_mask: Optional[torch.Tensor] = None,
1288
+ position_ids: Optional[torch.LongTensor] = None,
1289
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1290
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1291
+ labels: Optional[torch.LongTensor] = None,
1292
+ use_cache: Optional[bool] = None,
1293
+ output_attentions: Optional[bool] = None,
1294
+ output_hidden_states: Optional[bool] = None,
1295
+ return_dict: Optional[bool] = None,
1296
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1297
+ r"""
1298
+ Args:
1299
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1300
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1301
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1302
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1303
+
1304
+ Returns:
1305
+
1306
+ Example:
1307
+
1308
+ ```python
1309
+ >>> from transformers import AutoTokenizer, DeepseekForCausalLM
1310
+
1311
+ >>> model = DeepseekForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1312
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1313
+
1314
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1315
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1316
+
1317
+ >>> # Generate
1318
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1319
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1320
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1321
+ ```"""
1322
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1323
+ output_hidden_states = (
1324
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1325
+ )
1326
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1327
+
1328
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1329
+ outputs = self.model(
1330
+ input_ids=input_ids,
1331
+ attention_mask=attention_mask,
1332
+ position_ids=position_ids,
1333
+ past_key_values=past_key_values,
1334
+ inputs_embeds=inputs_embeds,
1335
+ use_cache=use_cache,
1336
+ output_attentions=output_attentions,
1337
+ output_hidden_states=output_hidden_states,
1338
+ return_dict=return_dict,
1339
+ )
1340
+
1341
+ hidden_states = outputs[0]
1342
+ if self.config.pretraining_tp > 1:
1343
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1344
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1345
+ logits = torch.cat(logits, dim=-1)
1346
+ else:
1347
+ logits = self.lm_head(hidden_states)
1348
+ logits = logits.float()
1349
+
1350
+ loss = None
1351
+ if labels is not None:
1352
+ # Shift so that tokens < n predict n
1353
+ shift_logits = logits[..., :-1, :].contiguous()
1354
+ shift_labels = labels[..., 1:].contiguous()
1355
+ # Flatten the tokens
1356
+ loss_fct = CrossEntropyLoss()
1357
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1358
+ shift_labels = shift_labels.view(-1)
1359
+ # Enable model parallelism
1360
+ shift_labels = shift_labels.to(shift_logits.device)
1361
+ loss = loss_fct(shift_logits, shift_labels)
1362
+
1363
+ if not return_dict:
1364
+ output = (logits,) + outputs[1:]
1365
+ return (loss,) + output if loss is not None else output
1366
+
1367
+ return CausalLMOutputWithPast(
1368
+ loss=loss,
1369
+ logits=logits,
1370
+ past_key_values=outputs.past_key_values,
1371
+ hidden_states=outputs.hidden_states,
1372
+ attentions=outputs.attentions,
1373
+ )
1374
+
1375
+ def prepare_inputs_for_generation(
1376
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1377
+ ):
1378
+ if past_key_values is not None:
1379
+ if isinstance(past_key_values, Cache):
1380
+ cache_length = past_key_values.get_seq_length()
1381
+ past_length = past_key_values.seen_tokens
1382
+ max_cache_length = past_key_values.get_max_length()
1383
+ else:
1384
+ cache_length = past_length = past_key_values[0][0].shape[2]
1385
+ max_cache_length = None
1386
+
1387
+ # Keep only the unprocessed tokens:
1388
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1389
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1390
+ # input)
1391
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1392
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1393
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1394
+ # input_ids based on the past_length.
1395
+ elif past_length < input_ids.shape[1]:
1396
+ input_ids = input_ids[:, past_length:]
1397
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1398
+
1399
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1400
+ if (
1401
+ max_cache_length is not None
1402
+ and attention_mask is not None
1403
+ and cache_length + input_ids.shape[1] > max_cache_length
1404
+ ):
1405
+ attention_mask = attention_mask[:, -max_cache_length:]
1406
+
1407
+ position_ids = kwargs.get("position_ids", None)
1408
+ if attention_mask is not None and position_ids is None:
1409
+ # create position_ids on the fly for batch generation
1410
+ position_ids = attention_mask.long().cumsum(-1) - 1
1411
+ position_ids.masked_fill_(attention_mask == 0, 1)
1412
+ if past_key_values:
1413
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1414
+
1415
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1416
+ if inputs_embeds is not None and past_key_values is None:
1417
+ model_inputs = {"inputs_embeds": inputs_embeds}
1418
+ else:
1419
+ model_inputs = {"input_ids": input_ids}
1420
+
1421
+ model_inputs.update(
1422
+ {
1423
+ "position_ids": position_ids,
1424
+ "past_key_values": past_key_values,
1425
+ "use_cache": kwargs.get("use_cache"),
1426
+ "attention_mask": attention_mask,
1427
+ }
1428
+ )
1429
+ return model_inputs
1430
+
1431
+ @staticmethod
1432
+ def _reorder_cache(past_key_values, beam_idx):
1433
+ reordered_past = ()
1434
+ for layer_past in past_key_values:
1435
+ reordered_past += (
1436
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1437
+ )
1438
+ return reordered_past
1439
+
1440
+
1441
+ @add_start_docstrings(
1442
+ """
1443
+ The Deepseek Model transformer with a sequence classification head on top (linear layer).
1444
+
1445
+ [`DeepseekForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1446
+ (e.g. GPT-2) do.
1447
+
1448
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1449
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1450
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1451
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1452
+ each row of the batch).
1453
+ """,
1454
+ Deepseek_START_DOCSTRING,
1455
+ )
1456
+ class DeepseekForSequenceClassification(DeepseekPreTrainedModel):
1457
+ def __init__(self, config):
1458
+ super().__init__(config)
1459
+ self.num_labels = config.num_labels
1460
+ self.model = DeepseekModel(config)
1461
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1462
+
1463
+ # Initialize weights and apply final processing
1464
+ self.post_init()
1465
+
1466
+ def get_input_embeddings(self):
1467
+ return self.model.embed_tokens
1468
+
1469
+ def set_input_embeddings(self, value):
1470
+ self.model.embed_tokens = value
1471
+
1472
+ @add_start_docstrings_to_model_forward(Deepseek_INPUTS_DOCSTRING)
1473
+ def forward(
1474
+ self,
1475
+ input_ids: torch.LongTensor = None,
1476
+ attention_mask: Optional[torch.Tensor] = None,
1477
+ position_ids: Optional[torch.LongTensor] = None,
1478
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1479
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1480
+ labels: Optional[torch.LongTensor] = None,
1481
+ use_cache: Optional[bool] = None,
1482
+ output_attentions: Optional[bool] = None,
1483
+ output_hidden_states: Optional[bool] = None,
1484
+ return_dict: Optional[bool] = None,
1485
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1486
+ r"""
1487
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1488
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1489
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1490
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1491
+ """
1492
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1493
+
1494
+ transformer_outputs = self.model(
1495
+ input_ids,
1496
+ attention_mask=attention_mask,
1497
+ position_ids=position_ids,
1498
+ past_key_values=past_key_values,
1499
+ inputs_embeds=inputs_embeds,
1500
+ use_cache=use_cache,
1501
+ output_attentions=output_attentions,
1502
+ output_hidden_states=output_hidden_states,
1503
+ return_dict=return_dict,
1504
+ )
1505
+ hidden_states = transformer_outputs[0]
1506
+ logits = self.score(hidden_states)
1507
+
1508
+ if input_ids is not None:
1509
+ batch_size = input_ids.shape[0]
1510
+ else:
1511
+ batch_size = inputs_embeds.shape[0]
1512
+
1513
+ if self.config.pad_token_id is None and batch_size != 1:
1514
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1515
+ if self.config.pad_token_id is None:
1516
+ sequence_lengths = -1
1517
+ else:
1518
+ if input_ids is not None:
1519
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1520
+ logits.device
1521
+ )
1522
+ else:
1523
+ sequence_lengths = -1
1524
+
1525
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1526
+
1527
+ loss = None
1528
+ if labels is not None:
1529
+ labels = labels.to(logits.device)
1530
+ if self.config.problem_type is None:
1531
+ if self.num_labels == 1:
1532
+ self.config.problem_type = "regression"
1533
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1534
+ self.config.problem_type = "single_label_classification"
1535
+ else:
1536
+ self.config.problem_type = "multi_label_classification"
1537
+
1538
+ if self.config.problem_type == "regression":
1539
+ loss_fct = MSELoss()
1540
+ if self.num_labels == 1:
1541
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1542
+ else:
1543
+ loss = loss_fct(pooled_logits, labels)
1544
+ elif self.config.problem_type == "single_label_classification":
1545
+ loss_fct = CrossEntropyLoss()
1546
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1547
+ elif self.config.problem_type == "multi_label_classification":
1548
+ loss_fct = BCEWithLogitsLoss()
1549
+ loss = loss_fct(pooled_logits, labels)
1550
+ if not return_dict:
1551
+ output = (pooled_logits,) + transformer_outputs[1:]
1552
+ return ((loss,) + output) if loss is not None else output
1553
+
1554
+ return SequenceClassifierOutputWithPast(
1555
+ loss=loss,
1556
+ logits=pooled_logits,
1557
+ past_key_values=transformer_outputs.past_key_values,
1558
+ hidden_states=transformer_outputs.hidden_states,
1559
+ attentions=transformer_outputs.attentions,
1560
+ )