vltnmmdv commited on
Commit
3cb0445
1 Parent(s): 465ab5b

Upload DeepseekFixedForCausalLM

Browse files
config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "deepseek-ai/deepseek-moe-16b-base",
3
+ "architectures": [
4
+ "DeepseekFixedForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_deepseek_fixed.DeepseekFixedConfig",
10
+ "AutoModel": "deepseek-ai/deepseek-moe-16b-base--modeling_deepseek.DeepseekModel",
11
+ "AutoModelForCausalLM": "modelling_deepseek_fixed.DeepseekFixedForCausalLM"
12
+ },
13
+ "aux_loss_alpha": 0.001,
14
+ "bos_token_id": 100000,
15
+ "eos_token_id": 100001,
16
+ "first_k_dense_replace": 1,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 2048,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 10944,
21
+ "max_position_embeddings": 4096,
22
+ "model_type": "deepseek_with_concentration",
23
+ "moe_implementation": "eager",
24
+ "moe_intermediate_size": 1408,
25
+ "moe_layer_freq": 1,
26
+ "n_routed_experts": 64,
27
+ "n_shared_experts": 2,
28
+ "norm_topk_prob": false,
29
+ "num_attention_heads": 16,
30
+ "num_experts_per_tok": 6,
31
+ "num_hidden_layers": 28,
32
+ "num_key_value_heads": 16,
33
+ "pretraining_tp": 1,
34
+ "rms_norm_eps": 1e-06,
35
+ "rope_scaling": null,
36
+ "rope_theta": 10000,
37
+ "scoring_func": "softmax",
38
+ "seq_aux": true,
39
+ "tie_word_embeddings": false,
40
+ "torch_dtype": "float32",
41
+ "transformers_version": "4.36.0",
42
+ "use_cache": true,
43
+ "vocab_size": 102400
44
+ }
configuration_deepseek_fixed.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+ DEEPSEEK_FIXES_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
9
+ class DeepseekFixedConfig(PretrainedConfig):
10
+ r"""
11
+ This is the configuration class to store the configuration of a DeepseekWithConcentrationekModel`]. It is used to instantiate an DeepSeek
12
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
13
+ defaults will yield a similar configuration to that of the DeepseekWithConcentration-7B.
14
+
15
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
16
+ documentation from [`PretrainedConfig`] for more information.
17
+
18
+
19
+ Args:
20
+ vocab_size (`int`, *optional*, defaults to 102400):
21
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
22
+ `inputs_ids` passed when calling [`DeepseekWithConcentrationModel`]
23
+ hidden_size (`int`, *optional*, defaults to 4096):
24
+ Dimension of the hidden representations.
25
+ intermediate_size (`int`, *optional*, defaults to 11008):
26
+ Dimension of the MLP representations.
27
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
28
+ Dimension of the MoE representations.
29
+ num_hidden_layers (`int`, *optional*, defaults to 32):
30
+ Number of hidden layers in the Transformer decoder.
31
+ num_attention_heads (`int`, *optional*, defaults to 32):
32
+ Number of attention heads for each attention layer in the Transformer decoder.
33
+ n_shared_experts (`int`, *optional*, defaults to None):
34
+ Number of shared experts, None means dense model.
35
+ n_routed_experts (`int`, *optional*, defaults to None):
36
+ Number of routed experts, None means dense model.
37
+ num_experts_per_tok (`int`, *optional*, defaults to None):
38
+ Number of selected experts, None means dense model.
39
+ moe_layer_freq (`int`, *optional*, defaults to 1):
40
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
41
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
42
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
43
+ \--k dense layers--/
44
+ norm_topk_prob (`bool`, *optional*, defaults to False):
45
+ Whether to normalize the weights of the routed experts.
46
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
47
+ Method of computing expert weights.
48
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
49
+ Auxiliary loss weight coefficient.
50
+ seq_aux = (`bool`, *optional*, defaults to True):
51
+ Whether to compute the auxiliary loss for each individual sample.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
63
+ The maximum sequence length that this model might ever be used with.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
67
+ The epsilon used by the rms normalization layers.
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
70
+ relevant if `config.is_decoder=True`.
71
+ pad_token_id (`int`, *optional*):
72
+ Padding token id.
73
+ bos_token_id (`int`, *optional*, defaults to 1):
74
+ Beginning of stream token id.
75
+ eos_token_id (`int`, *optional*, defaults to 2):
76
+ End of stream token id.
77
+ pretraining_tp (`int`, *optional*, defaults to 1):
78
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
79
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
80
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
81
+ issue](https://github.com/pytorch/pytorch/issues/76232).
82
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
83
+ Whether to tie weight embeddings
84
+ rope_theta (`float`, *optional*, defaults to 10000.0):
85
+ The base period of the RoPE embeddings.
86
+ rope_scaling (`Dict`, *optional*):
87
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
88
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
89
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
90
+ `max_position_embeddings` to the expected new maximum.
91
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
92
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
93
+ attention_dropout (`float`, *optional*, defaults to 0.0):
94
+ The dropout ratio for the attention probabilities.
95
+
96
+ ```python
97
+ >>> from transformers import DeepseekWithConcentrationModel, DeepseekWithConcentrationConfig
98
+
99
+ >>> # Initializing a DeepseekWithConcentration DeepseekWithConcentration-7b style configuration
100
+ >>> configuration = DeepseekWithConcentrationConfig()
101
+
102
+ >>> # Accessing the model configuration
103
+ >>> configuration = model.config
104
+ ```"""
105
+
106
+ model_type = "deepseek_with_concentration"
107
+ keys_to_ignore_at_inference = ["past_key_values"]
108
+
109
+ def __init__(
110
+ self,
111
+ vocab_size=102400,
112
+ hidden_size=4096,
113
+ intermediate_size=11008,
114
+ moe_intermediate_size = 1407,
115
+ num_hidden_layers=30,
116
+ num_attention_heads=32,
117
+ num_key_value_heads=32,
118
+ n_shared_experts = None,
119
+ n_routed_experts = None,
120
+ num_experts_per_tok = None,
121
+ moe_layer_freq = 1,
122
+ first_k_dense_replace = 0,
123
+ norm_topk_prob = False,
124
+ scoring_func = 'softmax',
125
+ aux_loss_alpha = 0.001,
126
+ seq_aux = True,
127
+ hidden_act="silu",
128
+ max_position_embeddings=2048,
129
+ initializer_range=0.02,
130
+ rms_norm_eps=1e-6,
131
+ use_cache=True,
132
+ pad_token_id=None,
133
+ bos_token_id=100000,
134
+ eos_token_id=100001,
135
+ pretraining_tp=1,
136
+ tie_word_embeddings=False,
137
+ rope_theta=10000.0,
138
+ rope_scaling=None,
139
+ attention_bias=False,
140
+ attention_dropout=0.0,
141
+ moe_implementation="eager",
142
+ **kwargs,
143
+ ):
144
+ self.vocab_size = vocab_size
145
+ self.max_position_embeddings = max_position_embeddings
146
+ self.hidden_size = hidden_size
147
+ self.intermediate_size = intermediate_size
148
+ self.moe_intermediate_size = moe_intermediate_size
149
+ self.num_hidden_layers = num_hidden_layers
150
+ self.num_attention_heads = num_attention_heads
151
+ self.n_shared_experts = n_shared_experts
152
+ self.n_routed_experts = n_routed_experts
153
+ self.num_experts_per_tok = num_experts_per_tok
154
+ self.moe_layer_freq = moe_layer_freq
155
+ self.first_k_dense_replace = first_k_dense_replace
156
+ self.norm_topk_prob = norm_topk_prob
157
+ self.scoring_func = scoring_func
158
+ self.aux_loss_alpha = aux_loss_alpha
159
+ self.seq_aux = seq_aux
160
+
161
+ # for backward compatibility
162
+ if num_key_value_heads is None:
163
+ num_key_value_heads = num_attention_heads
164
+
165
+ self.num_key_value_heads = num_key_value_heads
166
+ self.hidden_act = hidden_act
167
+ self.initializer_range = initializer_range
168
+ self.rms_norm_eps = rms_norm_eps
169
+ self.pretraining_tp = pretraining_tp
170
+ self.use_cache = use_cache
171
+ self.rope_theta = rope_theta
172
+ self.rope_scaling = rope_scaling
173
+ self._rope_scaling_validation()
174
+ self.attention_bias = attention_bias
175
+ self.attention_dropout = attention_dropout
176
+ self.moe_implementation = moe_implementation
177
+
178
+ super().__init__(
179
+ pad_token_id=pad_token_id,
180
+ bos_token_id=bos_token_id,
181
+ eos_token_id=eos_token_id,
182
+ tie_word_embeddings=tie_word_embeddings,
183
+ **kwargs,
184
+ )
185
+
186
+ def _rope_scaling_validation(self):
187
+ """
188
+ Validate the `rope_scaling` configuration.
189
+ """
190
+ if self.rope_scaling is None:
191
+ return
192
+
193
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
194
+ raise ValueError(
195
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
196
+ f"got {self.rope_scaling}"
197
+ )
198
+ rope_scaling_type = self.rope_scaling.get("type", None)
199
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
200
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
201
+ raise ValueError(
202
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
203
+ )
204
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
205
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100000,
4
+ "eos_token_id": 100001,
5
+ "transformers_version": "4.36.0"
6
+ }
model-00001-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:223c6cb1bbcaa99661a20f0353e6f5f8054d9ae2e7786825548a17db20f28ea4
3
+ size 4989198728
model-00002-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4cb7290dfc3b98773263b7bb7e4a5f203b119e175ab2ecab284d5c1379f9018
3
+ size 4991307104
model-00003-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b260f65b66ced9b6ed6d58349a8ff45e04d138483196484abb2c9c35d9c2c9e
3
+ size 4991307112
model-00004-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bfdc4b782e0ea9b6b26780b4774b886722a2a2b8df4a52651461532867d40722
3
+ size 4991831264
model-00005-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1596d16d20610bc5959d08c20c7dcb8491632f3fa2372d73d2b7e34a7a1243ef
3
+ size 4989226376
model-00006-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce69a8b43513aa93c8afca718e792025ec7212f372df997f4b096662e1c4d075
3
+ size 4991307528
model-00007-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a8b448b97424a2271acad334e8411cbb40815a3ce84fe9b982d115790a54b0a
3
+ size 4991307536
model-00008-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80c7ba17de2b368a9037f969e857a479881d09eb9fc61b256c0117053c531da3
3
+ size 4991307536
model-00009-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:129a260e81b94652461d1c7a0db072f3191807074a679e5d914be903b2f30ba8
3
+ size 4991307536
model-00010-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c1cb281e57d0522adbded78527a0d08a2a468566b7cc474b3d4b7462a30a3af6
3
+ size 4991307536
model-00011-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ac664d16488a5d1ff54d4165904e792c2909ed57aedf38599799f8207d37e67
3
+ size 4991307536
model-00012-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa1de409dae31109848475db4ef1a4c172c3cd8d29c9b4657a5f2fb3b0df0102
3
+ size 4991831936
model-00013-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cb1978de28008a8b30a8f08bb014165819a3450cc481bbe439cd572c4a0d597
3
+ size 4772177328
model-00014-of-00014.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4bec88932328406a408286ebefcb0ca139c250f12201fee763125bcb82a753a2
3
+ size 838860928
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modelling_deepseek_fixed.py ADDED
@@ -0,0 +1,1787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 DeepseekFixed model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import numpy as np
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
+ _prepare_4d_causal_attention_mask_for_sdpa,
39
+ )
40
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
41
+ SequenceClassifierOutputWithPast
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
44
+ from transformers.utils import (
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ is_flash_attn_2_available,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from transformers.utils.import_utils import is_torch_fx_available
52
+ from .configuration_deepseek_fixed import DeepseekFixedConfig
53
+
54
+ if is_flash_attn_2_available():
55
+ from transformers.utils import is_flash_attn_greater_or_equal_2_10
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
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
+ logger = logging.get_logger(__name__)
68
+
69
+ _CONFIG_FOR_DOC = "DeepseekFixedConfig"
70
+
71
+
72
+ def _get_unpad_data(attention_mask):
73
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
74
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
75
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
76
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
77
+ return (
78
+ indices,
79
+ cu_seqlens,
80
+ max_seqlen_in_batch,
81
+ )
82
+
83
+
84
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
85
+ warnings.warn(
86
+ "Calling `transformers.models.DeepseekFixed.modelling_deepseek_fixed._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
87
+ )
88
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
89
+
90
+
91
+ def _make_causal_mask(
92
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
93
+ ):
94
+ warnings.warn(
95
+ "Calling `transformers.models.DeepseekFixed.modeling_deepseek_fixed._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.Deepseek.modeling_Deepseek.AttentionMaskConverter._make_causal_mask"
96
+ )
97
+ return AttentionMaskConverter._make_causal_mask(
98
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
99
+ )
100
+
101
+
102
+ class DeepseekFixedRMSNorm(nn.Module):
103
+ def __init__(self, hidden_size, eps=1e-6):
104
+ """
105
+ DeepseekFixedRMSNorm is equivalent to T5LayerNorm
106
+ """
107
+ super().__init__()
108
+ self.weight = nn.Parameter(torch.ones(hidden_size))
109
+ self.variance_epsilon = eps
110
+
111
+ def forward(self, hidden_states):
112
+ input_dtype = hidden_states.dtype
113
+ hidden_states = hidden_states.to(torch.float32)
114
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
115
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
116
+ return self.weight * hidden_states.to(input_dtype)
117
+
118
+
119
+ ALL_LAYERNORM_LAYERS.append(DeepseekFixedRMSNorm)
120
+
121
+
122
+ class DeepseekFixedRotaryEmbedding(nn.Module):
123
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
124
+ super().__init__()
125
+ self.scaling_factor = scaling_factor
126
+ self.dim = dim
127
+ self.max_position_embeddings = max_position_embeddings
128
+ self.base = base
129
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
130
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
131
+ # For BC we register cos and sin cached
132
+ self.max_seq_len_cached = max_position_embeddings
133
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
134
+ t = t / self.scaling_factor
135
+ freqs = torch.outer(t, self.inv_freq)
136
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+ self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
139
+ self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
140
+
141
+ @property
142
+ def sin_cached(self):
143
+ logger.warning_once(
144
+ "The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
145
+ "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class"
146
+ )
147
+ return self._sin_cached
148
+
149
+ @property
150
+ def cos_cached(self):
151
+ logger.warning_once(
152
+ "The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
153
+ "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class"
154
+ )
155
+ return self._cos_cached
156
+
157
+ @torch.no_grad()
158
+ def forward(self, x, position_ids):
159
+ # x: [bs, num_attention_heads, seq_len, head_size]
160
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
161
+ position_ids_expanded = position_ids[:, None, :].float()
162
+ # Force float32 since bfloat16 loses precision on long contexts
163
+ # See https://github.com/huggingface/transformers/pull/29285
164
+ device_type = x.device.type
165
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
166
+ with torch.autocast(device_type=device_type, enabled=False):
167
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
168
+ emb = torch.cat((freqs, freqs), dim=-1)
169
+ cos = emb.cos()
170
+ sin = emb.sin()
171
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
172
+
173
+
174
+ class DeepseekFixedLinearScalingRotaryEmbedding(DeepseekFixedRotaryEmbedding):
175
+ """DeepseekFixedRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
176
+
177
+ def forward(self, x, position_ids):
178
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
179
+ position_ids = position_ids.float() / self.scaling_factor
180
+ cos, sin = super().forward(x, position_ids)
181
+ return cos, sin
182
+
183
+
184
+ class DeepseekFixedDynamicNTKScalingRotaryEmbedding(DeepseekFixedRotaryEmbedding):
185
+ """DeepseekFixedRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
186
+
187
+ def forward(self, x, position_ids):
188
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
189
+ seq_len = torch.max(position_ids) + 1
190
+ if seq_len > self.max_position_embeddings:
191
+ base = self.base * (
192
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
193
+ ) ** (self.dim / (self.dim - 2))
194
+ inv_freq = 1.0 / (
195
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
196
+ )
197
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
198
+
199
+ cos, sin = super().forward(x, position_ids)
200
+ return cos, sin
201
+
202
+
203
+ def rotate_half(x):
204
+ """Rotates half the hidden dims of the input."""
205
+ x1 = x[..., : x.shape[-1] // 2]
206
+ x2 = x[..., x.shape[-1] // 2:]
207
+ return torch.cat((-x2, x1), dim=-1)
208
+
209
+
210
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
211
+ """Applies Rotary Position Embedding to the query and key tensors.
212
+
213
+ Args:
214
+ q (`torch.Tensor`): The query tensor.
215
+ k (`torch.Tensor`): The key tensor.
216
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
217
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
218
+ position_ids (`torch.Tensor`, *optional*):
219
+ Deprecated and unused.
220
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
221
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
222
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
223
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
224
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
225
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
226
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
227
+ Returns:
228
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
229
+ """
230
+ cos = cos.unsqueeze(unsqueeze_dim)
231
+ sin = sin.unsqueeze(unsqueeze_dim)
232
+ q_embed = (q * cos) + (rotate_half(q) * sin)
233
+ k_embed = (k * cos) + (rotate_half(k) * sin)
234
+ return q_embed, k_embed
235
+
236
+
237
+ class DeepseekFixedMLP(nn.Module):
238
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
239
+ super().__init__()
240
+ self.config = config
241
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
242
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
243
+
244
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
245
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
246
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
247
+ self.act_fn = ACT2FN[config.hidden_act]
248
+
249
+ def forward(self, x, **kwargs):
250
+ if self.config.pretraining_tp > 1:
251
+ slice = self.intermediate_size // self.config.pretraining_tp
252
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
253
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
254
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
255
+
256
+ gate_proj = torch.cat(
257
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
258
+ )
259
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
260
+
261
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
262
+ down_proj = [
263
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
264
+ ]
265
+ down_proj = sum(down_proj)
266
+ else:
267
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
268
+
269
+ return down_proj
270
+
271
+
272
+ class MoEGate(nn.Module):
273
+ def __init__(self, config):
274
+ super().__init__()
275
+ self.config = config
276
+ self.top_k = config.num_experts_per_tok
277
+ self.n_routed_experts = config.n_routed_experts
278
+
279
+ self.scoring_func = config.scoring_func
280
+ self.alpha = config.aux_loss_alpha
281
+ self.seq_aux = config.seq_aux
282
+
283
+ # topk selection algorithm
284
+ self.norm_topk_prob = config.norm_topk_prob
285
+ self.gating_dim = config.hidden_size
286
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
287
+
288
+ self.reset_parameters()
289
+
290
+ def reset_parameters(self) -> None:
291
+ import torch.nn.init as init
292
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
293
+
294
+ def forward(self, hidden_states):
295
+ bsz, seq_len, h = hidden_states.shape
296
+ ### compute gating score
297
+ hidden_states = hidden_states.view(-1, h)
298
+ logits = F.linear(hidden_states, self.weight, None)
299
+ if self.scoring_func == 'softmax':
300
+ scores = logits.to(torch.float32).softmax(dim=-1)
301
+ else:
302
+ raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
303
+
304
+ ### select top-k experts
305
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
306
+
307
+ ### norm gate to sum 1
308
+ if self.top_k > 1 and self.norm_topk_prob:
309
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
310
+ topk_weight = topk_weight / denominator
311
+
312
+ ### expert-level computation auxiliary loss
313
+ if self.training and self.alpha > 0.0:
314
+ scores_for_aux = scores
315
+ aux_topk = self.top_k
316
+ # always compute aux loss based on the naive greedy topk method
317
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
318
+ if self.seq_aux:
319
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
320
+ ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device, dtype=torch.float32)
321
+ ce.scatter_add_(
322
+ 1,
323
+ topk_idx_for_aux_loss,
324
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device, dtype=torch.float32),
325
+ )
326
+ ce.div_(seq_len * aux_topk / self.n_routed_experts)
327
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
328
+ else:
329
+ mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
330
+ ce = mask_ce.float().mean(0)
331
+ Pi = scores_for_aux.mean(0)
332
+ fi = ce * self.n_routed_experts
333
+ aux_loss = (Pi * fi).sum() * self.alpha
334
+ else:
335
+ aux_loss = None
336
+ return topk_idx, topk_weight, aux_loss
337
+
338
+
339
+ class AddAuxiliaryLoss(torch.autograd.Function):
340
+ """
341
+ The trick function of adding auxiliary (aux) loss,
342
+ which includes the gradient of the aux loss during backpropagation.
343
+ """
344
+
345
+ @staticmethod
346
+ def forward(ctx, x, loss):
347
+ assert loss.numel() == 1
348
+ ctx.dtype = loss.dtype
349
+ ctx.required_aux_loss = loss.requires_grad
350
+ return x
351
+
352
+ @staticmethod
353
+ def backward(ctx, grad_output):
354
+ grad_loss = None
355
+ if ctx.required_aux_loss:
356
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
357
+ return grad_output, grad_loss
358
+
359
+
360
+ class DeepseekFixedMoE(nn.Module):
361
+ """
362
+ A mixed expert module containing shared experts.
363
+ """
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(
370
+ [DeepseekFixedMLP(config, intermediate_size=config.moe_intermediate_size) for i in
371
+ range(config.n_routed_experts)])
372
+ self.gate = MoEGate(config)
373
+ if config.n_shared_experts is not None:
374
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
375
+ self.shared_experts = DeepseekFixedMLP(config=config, intermediate_size=intermediate_size)
376
+
377
+ def forward(self, hidden_states):
378
+ identity = hidden_states
379
+ orig_shape = hidden_states.shape
380
+ topk_idx, topk_weight, aux_loss = self.gate(
381
+ hidden_states,
382
+ )
383
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
384
+ flat_topk_idx = topk_idx.view(-1)
385
+ if self.training:
386
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
387
+ y = torch.empty_like(hidden_states)
388
+ for i, expert in enumerate(self.experts):
389
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
390
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
391
+ y = y.view(*orig_shape)
392
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
393
+ else:
394
+ y = self.moe_infer(hidden_states, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
395
+ if self.config.n_shared_experts is not None:
396
+ y = y + self.shared_experts(identity)
397
+ return y
398
+
399
+ @torch.no_grad()
400
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
401
+ expert_cache = torch.zeros_like(x)
402
+ idxs = flat_expert_indices.argsort()
403
+ tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
404
+ token_idxs = idxs // self.num_experts_per_tok
405
+ for i, end_idx in enumerate(tokens_per_expert):
406
+ start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
407
+ if start_idx == end_idx:
408
+ continue
409
+ expert = self.experts[i]
410
+ exp_token_idx = token_idxs[start_idx:end_idx]
411
+ expert_tokens = x[exp_token_idx]
412
+ expert_out = expert(expert_tokens)
413
+ expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
414
+ expert_cache.scatter_reduce_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out, reduce='sum')
415
+ return expert_cache
416
+
417
+
418
+ DeepseekFixed_MOE_CLASSES = {
419
+ 'eager': DeepseekFixedMoE,
420
+ }
421
+ try:
422
+ from megablocks.layers import common
423
+ from megablocks.layers import moe
424
+ from megablocks.layers import dmlp_registry
425
+ from megablocks.layers import mpu
426
+ from megablocks.layers import router
427
+ from megablocks.layers.arguments import Arguments
428
+ import megablocks.ops as ops
429
+ import numpy as np
430
+ import stk
431
+
432
+
433
+ def promote_scalar(x):
434
+ return x.view(1) if not len(x.size()) else x
435
+
436
+ class DeepseekFixedMegablocksMoE(DeepseekFixedMoE):
437
+ def __init__(self, config: DeepseekFixedConfig):
438
+ super().__init__(config)
439
+ self.sort_end_bit = max(int(np.ceil(np.log2(self.config.n_routed_experts))), 1)
440
+ self.blocking = 128
441
+ self.quantize_scatter_num_bits = -1
442
+ max_column_index = (self.config.moe_intermediate_size * self.config.n_routed_experts) // self.blocking
443
+ self.transpose_sort_end_bit = max(int(np.ceil(np.log2(max_column_index))), 1)
444
+
445
+ # From https://github.com/stanford-futuredata/megablocks/blob/7c25169ce87c32c31e8845ef34785d3095b1a2cb/megablocks/layers/dmoe.py#L31
446
+ def sparse_transpose(self, size, row_indices, column_indices):
447
+ block_columns = size[1] // self.blocking
448
+
449
+ # Sort row indices by column indices to get the transposed matrix's
450
+ # column indices.
451
+ #
452
+ # NOTE: Our sort operation uses the same width indices as the input values.
453
+ # To avoid overflow when we have large activation matrices we cast to
454
+ # 32-bit before sorting.
455
+ _, gather_indices = ops.sort(column_indices.int(), self.transpose_sort_end_bit)
456
+
457
+ # There are a constant number of blocks in every row of the sparse matrix.
458
+ # A blocks offset is:
459
+ #
460
+ # row_index * blocks_per_row + column_index % blocks_per_row
461
+ #
462
+ # Once we have the block offsets ordered for transposition we can divide
463
+ # by blocks_per_row to get the transposed column indices.
464
+ column_indices_t = row_indices.gather(0, gather_indices.long())
465
+ block_offsets_t = gather_indices.int()
466
+
467
+ zero = torch.zeros((1,), dtype=torch.int32, device=row_indices.device)
468
+ nnz_per_column = ops.histogram(column_indices, block_columns)
469
+ nnz_per_column = ops.inclusive_cumsum(nnz_per_column, 0)
470
+ offsets_t = torch.cat([zero, nnz_per_column])
471
+ return column_indices_t, offsets_t, block_offsets_t
472
+
473
+ # From https://github.com/stanford-futuredata/megablocks/blob/7c25169ce87c32c31e8845ef34785d3095b1a2cb/megablocks/layers/dmoe.py#L59
474
+ def topology(self, x: torch.Tensor, padded_bins: torch.Tensor):
475
+ padded_tokens, _ = x.size()
476
+ assert padded_tokens % self.blocking == 0
477
+ assert self.config.moe_intermediate_size % self.blocking == 0
478
+
479
+ # Offsets for the sparse matrix. All rows have the
480
+ # same number of nonzero blocks dictated by the
481
+ # dimensionality of a single expert.
482
+ block_rows = padded_tokens // self.blocking
483
+ blocks_per_row = self.config.moe_intermediate_size // self.blocking
484
+ offsets = torch.arange(
485
+ 0,
486
+ block_rows * blocks_per_row + 1,
487
+ blocks_per_row,
488
+ dtype=torch.int32,
489
+ device=x.device,
490
+ )
491
+
492
+ # Indices for the sparse matrix. The indices for
493
+ # the intermediate matrix are dynamic depending
494
+ # on the mapping of tokens to experts.
495
+ column_indices = ops.topology(
496
+ padded_bins, self.blocking, block_rows, blocks_per_row
497
+ )
498
+
499
+ # TODO(tgale): This is unused. Remove the need for this in stk.
500
+ # For now, use meta init to save the device memory.
501
+ data = torch.empty(
502
+ column_indices.numel(),
503
+ self.blocking,
504
+ self.blocking,
505
+ dtype=x.dtype,
506
+ device="meta",
507
+ )
508
+ shape = (padded_tokens, self.config.moe_intermediate_size * self.config.n_routed_experts)
509
+ row_indices = stk.ops.row_indices(shape, data, offsets, column_indices)
510
+ column_indices_t, offsets_t, block_offsets_t = self.sparse_transpose(
511
+ shape, row_indices, column_indices
512
+ )
513
+ return stk.Matrix(
514
+ shape,
515
+ data,
516
+ row_indices,
517
+ column_indices,
518
+ offsets,
519
+ column_indices_t,
520
+ offsets_t,
521
+ block_offsets_t,
522
+ )
523
+
524
+ # From https://github.com/stanford-futuredata/megablocks/blob/7c25169ce87c32c31e8845ef34785d3095b1a2cb/megablocks/layers/dmoe.py#L103
525
+ def indices_and_padded_bins(self, top_experts: torch.Tensor):
526
+ # Sort the expert ids to produce the scatter/gather
527
+ # indices for the permutation.
528
+ top_experts = top_experts.int()
529
+ bin_ids, indices = ops.sort(top_experts, self.sort_end_bit)
530
+
531
+ # Histogram the expert ids to identify the number of
532
+ # tokens routed to each expert.
533
+ tokens_per_expert = ops.histogram(top_experts, self.config.n_routed_experts)
534
+
535
+ # Round the token counts up to the block size used in
536
+ # the matrix muliplications. Caculate the starting
537
+ # position of each bin.
538
+ padded_tokens_per_expert = ops.round_up(tokens_per_expert, self.blocking)
539
+ padded_bins = ops.inclusive_cumsum(padded_tokens_per_expert, 0)
540
+ padded_bins = promote_scalar(padded_bins)
541
+
542
+ # Calculate the bin bounds for the sorted tokens.
543
+ bins = ops.inclusive_cumsum(tokens_per_expert, 0)
544
+ bins = promote_scalar(bins)
545
+ return indices, bin_ids, bins, padded_bins, tokens_per_expert
546
+
547
+ # From https://github.com/stanford-futuredata/megablocks/blob/7c25169ce87c32c31e8845ef34785d3095b1a2cb/megablocks/layers/dmoe.py#L126
548
+ def sparse_forward(
549
+ self,
550
+ hidden_states: torch.Tensor,
551
+ expert_weights: torch.Tensor,
552
+ top_experts: torch.Tensor,
553
+ ):
554
+ # x: [sl, bs, hs]
555
+ # expert_weights: [sl * bs, top-k]
556
+ # top_experts: [sl * bs, top-k]
557
+ expert_weights = expert_weights.flatten().to(hidden_states.dtype)
558
+ top_experts = top_experts.flatten()
559
+
560
+ with torch.no_grad():
561
+ (
562
+ indices,
563
+ bin_ids,
564
+ bins,
565
+ padded_bins,
566
+ _,
567
+ ) = self.indices_and_padded_bins(top_experts)
568
+
569
+ # Permute tokens and pad to prepare expert computation
570
+ # (top_k * sequence_length padding, model_dim)
571
+ # Route the tokens for MoE computation.
572
+ hidden_states = ops.padded_gather(
573
+ hidden_states, indices, bin_ids, bins, padded_bins, self.num_experts_per_tok
574
+ )
575
+
576
+ # Create the sparse matrix topology
577
+ with torch.no_grad():
578
+ topo = self.topology(hidden_states, padded_bins)
579
+
580
+ w1 = torch.cat([expert.gate_proj.weight.T for expert in self.experts], dim=1)
581
+ w2 = torch.cat([expert.down_proj.weight for expert in self.experts], dim=1).T
582
+ w3 = torch.cat([expert.up_proj.weight.T for expert in self.experts], dim=1)
583
+
584
+ # Perform the expert computation
585
+ hidden_states = stk.Matrix( # type: ignore
586
+ topo.size(),
587
+ F.silu(stk.ops.sdd(hidden_states, w1, topo).data)
588
+ * stk.ops.sdd(hidden_states, w3, topo).data,
589
+ topo.row_indices,
590
+ topo.column_indices,
591
+ topo.offsets,
592
+ topo.column_indices_t,
593
+ topo.offsets_t,
594
+ topo.block_offsets_t,
595
+ )
596
+ hidden_states = stk.ops.dsd(hidden_states, w2)
597
+
598
+ # Permute back and remove padding
599
+ # (top_k * sequence_length, model_dim)
600
+ hidden_states: torch.Tensor = ops.padded_scatter( # type: ignore
601
+ hidden_states,
602
+ indices,
603
+ bin_ids,
604
+ expert_weights,
605
+ bins,
606
+ padded_bins,
607
+ self.num_experts_per_tok,
608
+ self.quantize_scatter_num_bits,
609
+ )
610
+ return hidden_states
611
+
612
+ @torch.no_grad()
613
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
614
+ orig_shape = x.shape
615
+ x = self.sparse_forward(
616
+ x, flat_expert_weights, flat_expert_indices
617
+ )
618
+ return x.view(*orig_shape)
619
+
620
+ warnings.warn("Megablocks MoE is LOADED")
621
+
622
+ DeepseekFixed_MOE_CLASSES['megablocks'] = DeepseekFixedMegablocksMoE
623
+ except ImportError:
624
+ warnings.warn("Megablocks MoE is UNAVAILABLE")
625
+ pass
626
+
627
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
628
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
629
+ """
630
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
631
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
632
+ """
633
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
634
+ if n_rep == 1:
635
+ return hidden_states
636
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
637
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
638
+
639
+
640
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekFixed
641
+ class DeepseekFixedAttention(nn.Module):
642
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
643
+
644
+ def __init__(self, config: DeepseekFixedConfig, layer_idx: Optional[int] = None):
645
+ super().__init__()
646
+ self.config = config
647
+ self.layer_idx = layer_idx
648
+ if layer_idx is None:
649
+ logger.warning_once(
650
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
651
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
652
+ "when creating this class."
653
+ )
654
+
655
+ self.attention_dropout = config.attention_dropout
656
+ self.hidden_size = config.hidden_size
657
+ self.num_heads = config.num_attention_heads
658
+ self.head_dim = self.hidden_size // self.num_heads
659
+ self.num_key_value_heads = config.num_key_value_heads
660
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
661
+ self.max_position_embeddings = config.max_position_embeddings
662
+ self.rope_theta = config.rope_theta
663
+ self.is_causal = True
664
+
665
+ if (self.head_dim * self.num_heads) != self.hidden_size:
666
+ raise ValueError(
667
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
668
+ f" and `num_heads`: {self.num_heads})."
669
+ )
670
+
671
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
672
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
673
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
674
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
675
+ self._init_rope()
676
+
677
+ def _init_rope(self):
678
+ if self.config.rope_scaling is None:
679
+ self.rotary_emb = DeepseekFixedRotaryEmbedding(
680
+ self.head_dim,
681
+ max_position_embeddings=self.max_position_embeddings,
682
+ base=self.rope_theta,
683
+ )
684
+ else:
685
+ scaling_type = self.config.rope_scaling["type"]
686
+ scaling_factor = self.config.rope_scaling["factor"]
687
+ if scaling_type == "linear":
688
+ self.rotary_emb = DeepseekFixedLinearScalingRotaryEmbedding(
689
+ self.head_dim,
690
+ max_position_embeddings=self.max_position_embeddings,
691
+ scaling_factor=scaling_factor,
692
+ base=self.rope_theta,
693
+ )
694
+ elif scaling_type == "dynamic":
695
+ self.rotary_emb = DeepseekFixedDynamicNTKScalingRotaryEmbedding(
696
+ self.head_dim,
697
+ max_position_embeddings=self.max_position_embeddings,
698
+ scaling_factor=scaling_factor,
699
+ base=self.rope_theta,
700
+ )
701
+ else:
702
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
703
+
704
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
705
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
706
+
707
+ def forward(
708
+ self,
709
+ hidden_states: torch.Tensor,
710
+ attention_mask: Optional[torch.Tensor] = None,
711
+ position_ids: Optional[torch.LongTensor] = None,
712
+ past_key_value: Optional[Cache] = None,
713
+ output_attentions: bool = False,
714
+ use_cache: bool = False,
715
+ **kwargs,
716
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
717
+ if "padding_mask" in kwargs:
718
+ warnings.warn(
719
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
720
+ )
721
+
722
+ bsz, q_len, _ = hidden_states.size()
723
+
724
+ if self.config.pretraining_tp > 1:
725
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
726
+ query_slices = self.q_proj.weight.split(
727
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
728
+ )
729
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
730
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
731
+
732
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
733
+ query_states = torch.cat(query_states, dim=-1)
734
+
735
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
736
+ key_states = torch.cat(key_states, dim=-1)
737
+
738
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
739
+ value_states = torch.cat(value_states, dim=-1)
740
+
741
+ else:
742
+ query_states = self.q_proj(hidden_states)
743
+ key_states = self.k_proj(hidden_states)
744
+ value_states = self.v_proj(hidden_states)
745
+
746
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
747
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
748
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
749
+
750
+ kv_seq_len = key_states.shape[-2]
751
+ if past_key_value is not None:
752
+ if self.layer_idx is None:
753
+ raise ValueError(
754
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
755
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
756
+ "with a layer index."
757
+ )
758
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
759
+ cos, sin = self.rotary_emb(value_states, position_ids)
760
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
761
+
762
+ if past_key_value is not None:
763
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
764
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
765
+
766
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
767
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
768
+
769
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
770
+
771
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
772
+ raise ValueError(
773
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
774
+ f" {attn_weights.size()}"
775
+ )
776
+
777
+ if attention_mask is not None:
778
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
779
+ raise ValueError(
780
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
781
+ )
782
+ attn_weights = attn_weights + attention_mask
783
+
784
+ # upcast attention to fp32
785
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
786
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
787
+ attn_output = torch.matmul(attn_weights, value_states)
788
+
789
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
790
+ raise ValueError(
791
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
792
+ f" {attn_output.size()}"
793
+ )
794
+
795
+ attn_output = attn_output.transpose(1, 2).contiguous()
796
+
797
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
798
+
799
+ if self.config.pretraining_tp > 1:
800
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
801
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
802
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
803
+ else:
804
+ attn_output = self.o_proj(attn_output)
805
+
806
+ if not output_attentions:
807
+ attn_weights = None
808
+
809
+ return attn_output, attn_weights, past_key_value
810
+
811
+
812
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekFixed
813
+ class DeepseekFixedFlashAttention2(DeepseekFixedAttention):
814
+ """
815
+ DeepseekFixed flash attention module. This module inherits from `DeepseekFixedAttention` as the weights of the module stays
816
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
817
+ flash attention and deal with padding tokens in case the input contains any of them.
818
+ """
819
+
820
+ def __init__(self, *args, **kwargs):
821
+ super().__init__(*args, **kwargs)
822
+
823
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
824
+ # 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.
825
+ # 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).
826
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
827
+
828
+ def forward(
829
+ self,
830
+ hidden_states: torch.Tensor,
831
+ attention_mask: Optional[torch.LongTensor] = None,
832
+ position_ids: Optional[torch.LongTensor] = None,
833
+ past_key_value: Optional[Cache] = None,
834
+ output_attentions: bool = False,
835
+ use_cache: bool = False,
836
+ **kwargs,
837
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
838
+ # DeepseekFixedFlashAttention2 attention does not support output_attentions
839
+ if "padding_mask" in kwargs:
840
+ warnings.warn(
841
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
842
+ )
843
+
844
+ # overwrite attention_mask with padding_mask
845
+ attention_mask = kwargs.pop("padding_mask")
846
+
847
+ output_attentions = False
848
+
849
+ bsz, q_len, _ = hidden_states.size()
850
+
851
+ query_states = self.q_proj(hidden_states)
852
+ key_states = self.k_proj(hidden_states)
853
+ value_states = self.v_proj(hidden_states)
854
+
855
+ # Flash attention requires the input to have the shape
856
+ # batch_size x seq_length x head_dim x hidden_dim
857
+ # therefore we just need to keep the original shape
858
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
859
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
860
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
861
+
862
+ kv_seq_len = key_states.shape[-2]
863
+ if past_key_value is not None:
864
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
865
+ cos, sin = self.rotary_emb(value_states, position_ids)
866
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
867
+
868
+ if past_key_value is not None:
869
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
870
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
871
+
872
+ # 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
873
+ # to be able to avoid many of these transpose/reshape/view.
874
+ query_states = query_states.transpose(1, 2)
875
+ key_states = key_states.transpose(1, 2)
876
+ value_states = value_states.transpose(1, 2)
877
+
878
+ dropout_rate = self.attention_dropout if self.training else 0.0
879
+
880
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
881
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
882
+ # cast them back in the correct dtype just to be sure everything works as expected.
883
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
884
+ # in fp32. (DeepseekFixedRMSNorm handles it correctly)
885
+
886
+ input_dtype = query_states.dtype
887
+ if input_dtype == torch.float32:
888
+ # Handle the case where the model is quantized
889
+ if hasattr(self.config, "_pre_quantization_dtype"):
890
+ target_dtype = self.config._pre_quantization_dtype
891
+ elif torch.is_autocast_enabled():
892
+ target_dtype = torch.get_autocast_gpu_dtype()
893
+ else:
894
+ target_dtype = self.q_proj.weight.dtype
895
+
896
+ logger.warning_once(
897
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
898
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
899
+ f" {target_dtype}."
900
+ )
901
+
902
+ query_states = query_states.to(target_dtype)
903
+ key_states = key_states.to(target_dtype)
904
+ value_states = value_states.to(target_dtype)
905
+
906
+ attn_output = self._flash_attention_forward(
907
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
908
+ )
909
+
910
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
911
+ attn_output = self.o_proj(attn_output)
912
+
913
+ if not output_attentions:
914
+ attn_weights = None
915
+
916
+ return attn_output, attn_weights, past_key_value
917
+
918
+ def _flash_attention_forward(
919
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
920
+ ):
921
+ """
922
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
923
+ first unpad the input, then computes the attention scores and pad the final attention scores.
924
+
925
+ Args:
926
+ query_states (`torch.Tensor`):
927
+ Input query states to be passed to Flash Attention API
928
+ key_states (`torch.Tensor`):
929
+ Input key states to be passed to Flash Attention API
930
+ value_states (`torch.Tensor`):
931
+ Input value states to be passed to Flash Attention API
932
+ attention_mask (`torch.Tensor`):
933
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
934
+ position of padding tokens and 1 for the position of non-padding tokens.
935
+ dropout (`int`, *optional*):
936
+ Attention dropout
937
+ softmax_scale (`float`, *optional*):
938
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
939
+ """
940
+ if not self._flash_attn_uses_top_left_mask:
941
+ causal = self.is_causal
942
+ else:
943
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekFixedFlashAttention2 __init__.
944
+ causal = self.is_causal and query_length != 1
945
+
946
+ # Contains at least one padding token in the sequence
947
+ if attention_mask is not None:
948
+ batch_size = query_states.shape[0]
949
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
950
+ query_states, key_states, value_states, attention_mask, query_length
951
+ )
952
+
953
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
954
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
955
+
956
+ attn_output_unpad = flash_attn_varlen_func(
957
+ query_states,
958
+ key_states,
959
+ value_states,
960
+ cu_seqlens_q=cu_seqlens_q,
961
+ cu_seqlens_k=cu_seqlens_k,
962
+ max_seqlen_q=max_seqlen_in_batch_q,
963
+ max_seqlen_k=max_seqlen_in_batch_k,
964
+ dropout_p=dropout,
965
+ softmax_scale=softmax_scale,
966
+ causal=causal,
967
+ )
968
+
969
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
970
+ else:
971
+ attn_output = flash_attn_func(
972
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
973
+ )
974
+
975
+ return attn_output
976
+
977
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
978
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
979
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
980
+
981
+ key_layer = index_first_axis(
982
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
983
+ )
984
+ value_layer = index_first_axis(
985
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
986
+ )
987
+ if query_length == kv_seq_len:
988
+ query_layer = index_first_axis(
989
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
990
+ )
991
+ cu_seqlens_q = cu_seqlens_k
992
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
993
+ indices_q = indices_k
994
+ elif query_length == 1:
995
+ max_seqlen_in_batch_q = 1
996
+ cu_seqlens_q = torch.arange(
997
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
998
+ ) # There is a memcpy here, that is very bad.
999
+ indices_q = cu_seqlens_q[:-1]
1000
+ query_layer = query_layer.squeeze(1)
1001
+ else:
1002
+ # The -q_len: slice assumes left padding.
1003
+ attention_mask = attention_mask[:, -query_length:]
1004
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
1005
+
1006
+ return (
1007
+ query_layer,
1008
+ key_layer,
1009
+ value_layer,
1010
+ indices_q,
1011
+ (cu_seqlens_q, cu_seqlens_k),
1012
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1013
+ )
1014
+
1015
+
1016
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->DeepseekFixed
1017
+ class DeepseekFixedSdpaAttention(DeepseekFixedAttention):
1018
+ """
1019
+ DeepseekFixed attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1020
+ `DeepseekFixedAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1021
+ SDPA API.
1022
+ """
1023
+
1024
+ # Adapted from DeepseekFixedAttention.forward
1025
+ def forward(
1026
+ self,
1027
+ hidden_states: torch.Tensor,
1028
+ attention_mask: Optional[torch.Tensor] = None,
1029
+ position_ids: Optional[torch.LongTensor] = None,
1030
+ past_key_value: Optional[Cache] = None,
1031
+ output_attentions: bool = False,
1032
+ use_cache: bool = False,
1033
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1034
+ if output_attentions:
1035
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1036
+ logger.warning_once(
1037
+ "DeepseekFixedModel is using DeepseekFixedSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1038
+ '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.'
1039
+ )
1040
+ return super().forward(
1041
+ hidden_states=hidden_states,
1042
+ attention_mask=attention_mask,
1043
+ position_ids=position_ids,
1044
+ past_key_value=past_key_value,
1045
+ output_attentions=output_attentions,
1046
+ use_cache=use_cache,
1047
+ )
1048
+
1049
+ bsz, q_len, _ = hidden_states.size()
1050
+
1051
+ query_states = self.q_proj(hidden_states)
1052
+ key_states = self.k_proj(hidden_states)
1053
+ value_states = self.v_proj(hidden_states)
1054
+
1055
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1056
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1057
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1058
+
1059
+ kv_seq_len = key_states.shape[-2]
1060
+ if past_key_value is not None:
1061
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1062
+ cos, sin = self.rotary_emb(value_states, position_ids)
1063
+
1064
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1065
+
1066
+ if past_key_value is not None:
1067
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1068
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1069
+
1070
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1071
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1072
+
1073
+ if attention_mask is not None:
1074
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1075
+ raise ValueError(
1076
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1077
+ )
1078
+
1079
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1080
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1081
+ if query_states.device.type == "cuda" and attention_mask is not None:
1082
+ query_states = query_states.contiguous()
1083
+ key_states = key_states.contiguous()
1084
+ value_states = value_states.contiguous()
1085
+
1086
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1087
+ query_states,
1088
+ key_states,
1089
+ value_states,
1090
+ attn_mask=attention_mask,
1091
+ dropout_p=self.attention_dropout if self.training else 0.0,
1092
+ # 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.
1093
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1094
+ )
1095
+
1096
+ attn_output = attn_output.transpose(1, 2).contiguous()
1097
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
1098
+
1099
+ attn_output = self.o_proj(attn_output)
1100
+
1101
+ return attn_output, None, past_key_value
1102
+
1103
+
1104
+ DeepseekFixed_ATTENTION_CLASSES = {
1105
+ "eager": DeepseekFixedAttention,
1106
+ "flash_attention_2": DeepseekFixedFlashAttention2,
1107
+ "sdpa": DeepseekFixedSdpaAttention,
1108
+ }
1109
+
1110
+
1111
+ class DeepseekFixedDecoderLayer(nn.Module):
1112
+ def __init__(self, config: DeepseekFixedConfig, layer_idx: int):
1113
+ super().__init__()
1114
+ self.hidden_size = config.hidden_size
1115
+
1116
+ self.self_attn = DeepseekFixed_ATTENTION_CLASSES[config._attn_implementation](config=config,
1117
+ layer_idx=layer_idx)
1118
+
1119
+ self.mlp = DeepseekFixed_MOE_CLASSES[config.moe_implementation](config) if (config.n_routed_experts is not None and \
1120
+ layer_idx >= config.first_k_dense_replace and layer_idx % config.moe_layer_freq == 0) \
1121
+ else DeepseekFixedMLP(config)
1122
+ self.input_layernorm = DeepseekFixedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1123
+ self.post_attention_layernorm = DeepseekFixedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1124
+
1125
+ def forward(
1126
+ self,
1127
+ hidden_states: torch.Tensor,
1128
+ attention_mask: Optional[torch.Tensor] = None,
1129
+ position_ids: Optional[torch.LongTensor] = None,
1130
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1131
+ output_attentions: Optional[bool] = False,
1132
+ use_cache: Optional[bool] = False,
1133
+ **kwargs,
1134
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1135
+ """
1136
+ Args:
1137
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1138
+ attention_mask (`torch.FloatTensor`, *optional*):
1139
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1140
+ query_sequence_length, key_sequence_length)` if default attention is used.
1141
+ output_attentions (`bool`, *optional*):
1142
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1143
+ returned tensors for more detail.
1144
+ use_cache (`bool`, *optional*):
1145
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1146
+ (see `past_key_values`).
1147
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1148
+ """
1149
+ if "padding_mask" in kwargs:
1150
+ warnings.warn(
1151
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1152
+ )
1153
+ residual = hidden_states
1154
+
1155
+ hidden_states = self.input_layernorm(hidden_states)
1156
+
1157
+ # Self Attention
1158
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1159
+ hidden_states=hidden_states,
1160
+ attention_mask=attention_mask,
1161
+ position_ids=position_ids,
1162
+ past_key_value=past_key_value,
1163
+ output_attentions=output_attentions,
1164
+ use_cache=use_cache,
1165
+ **kwargs,
1166
+ )
1167
+ hidden_states = residual + hidden_states
1168
+
1169
+ # Fully Connected
1170
+ residual = hidden_states
1171
+ hidden_states = self.post_attention_layernorm(hidden_states)
1172
+ hidden_states = self.mlp(
1173
+ hidden_states,
1174
+ )
1175
+ hidden_states = residual + hidden_states
1176
+
1177
+ outputs = (hidden_states,)
1178
+
1179
+ if output_attentions:
1180
+ outputs += (self_attn_weights,)
1181
+
1182
+ if use_cache:
1183
+ outputs += (present_key_value,)
1184
+
1185
+ return outputs
1186
+
1187
+
1188
+ DeepseekFixed_START_DOCSTRING = r"""
1189
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1190
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1191
+ etc.)
1192
+
1193
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1194
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1195
+ and behavior.
1196
+
1197
+ Parameters:
1198
+ config ([`DeepseekFixedConfig`]):
1199
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1200
+ load the weights associated with the model, only the configuration. Check out the
1201
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1202
+ """
1203
+
1204
+
1205
+ @add_start_docstrings(
1206
+ "The bare DeepseekFixed Model outputting raw hidden-states without any specific head on top.",
1207
+ DeepseekFixed_START_DOCSTRING,
1208
+ )
1209
+ class DeepseekFixedPreTrainedModel(PreTrainedModel):
1210
+ config_class = DeepseekFixedConfig
1211
+ base_model_prefix = "model"
1212
+ supports_gradient_checkpointing = True
1213
+ _no_split_modules = ["DeepseekFixedDecoderLayer"]
1214
+ _skip_keys_device_placement = "past_key_values"
1215
+ _supports_flash_attn_2 = True
1216
+ _supports_sdpa = True
1217
+ _supports_cache_class = True
1218
+
1219
+ def _init_weights(self, module):
1220
+ std = self.config.initializer_range
1221
+ if isinstance(module, nn.Linear):
1222
+ module.weight.data.normal_(mean=0.0, std=std)
1223
+ if module.bias is not None:
1224
+ module.bias.data.zero_()
1225
+ elif isinstance(module, nn.Embedding):
1226
+ module.weight.data.normal_(mean=0.0, std=std)
1227
+ if module.padding_idx is not None:
1228
+ module.weight.data[module.padding_idx].zero_()
1229
+
1230
+
1231
+ DeepseekFixed_INPUTS_DOCSTRING = r"""
1232
+ Args:
1233
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1234
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1235
+ it.
1236
+
1237
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1238
+ [`PreTrainedTokenizer.__call__`] for details.
1239
+
1240
+ [What are input IDs?](../glossary#input-ids)
1241
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1242
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1243
+
1244
+ - 1 for tokens that are **not masked**,
1245
+ - 0 for tokens that are **masked**.
1246
+
1247
+ [What are attention masks?](../glossary#attention-mask)
1248
+
1249
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1250
+ [`PreTrainedTokenizer.__call__`] for details.
1251
+
1252
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1253
+ `past_key_values`).
1254
+
1255
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1256
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1257
+ information on the default strategy.
1258
+
1259
+ - 1 indicates the head is **not masked**,
1260
+ - 0 indicates the head is **masked**.
1261
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1262
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1263
+ config.n_positions - 1]`.
1264
+
1265
+ [What are position IDs?](../glossary#position-ids)
1266
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1267
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1268
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1269
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1270
+
1271
+ Two formats are allowed:
1272
+ - a [`~cache_utils.Cache`] instance;
1273
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1274
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1275
+ cache format.
1276
+
1277
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1278
+ legacy cache format will be returned.
1279
+
1280
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1281
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1282
+ of shape `(batch_size, sequence_length)`.
1283
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1284
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1285
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1286
+ model's internal embedding lookup matrix.
1287
+ use_cache (`bool`, *optional*):
1288
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1289
+ `past_key_values`).
1290
+ output_attentions (`bool`, *optional*):
1291
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1292
+ tensors for more detail.
1293
+ output_hidden_states (`bool`, *optional*):
1294
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1295
+ more detail.
1296
+ return_dict (`bool`, *optional*):
1297
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1298
+ """
1299
+
1300
+
1301
+ @add_start_docstrings(
1302
+ "The bare DeepseekFixed Model outputting raw hidden-states without any specific head on top.",
1303
+ DeepseekFixed_START_DOCSTRING,
1304
+ )
1305
+ class DeepseekFixedModel(DeepseekFixedPreTrainedModel):
1306
+ """
1307
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekFixedDecoderLayer`]
1308
+
1309
+ Args:
1310
+ config: DeepseekFixedConfig
1311
+ """
1312
+
1313
+ def __init__(self, config: DeepseekFixedConfig):
1314
+ super().__init__(config)
1315
+ self.padding_idx = config.pad_token_id
1316
+ self.vocab_size = config.vocab_size
1317
+
1318
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1319
+ self.layers = nn.ModuleList(
1320
+ [DeepseekFixedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1321
+ )
1322
+ self._use_sdpa = config._attn_implementation == "sdpa"
1323
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1324
+ self.norm = DeepseekFixedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1325
+
1326
+ self.gradient_checkpointing = False
1327
+ # Initialize weights and apply final processing
1328
+ self.post_init()
1329
+
1330
+ def _gate_func_call_by_name(self, func_name, *args, **kwargs):
1331
+ res = {}
1332
+ for i in range(self.config.num_hidden_layers):
1333
+ mlp_layer = self.layers[i].mlp
1334
+ if not hasattr(mlp_layer, "gate"):
1335
+ continue
1336
+ func = getattr(mlp_layer.gate, func_name)
1337
+ r = func(*args, **kwargs)
1338
+ res[i] = r
1339
+ return res
1340
+
1341
+ def get_input_embeddings(self):
1342
+ return self.embed_tokens
1343
+
1344
+ def set_input_embeddings(self, value):
1345
+ self.embed_tokens = value
1346
+
1347
+ @add_start_docstrings_to_model_forward(DeepseekFixed_INPUTS_DOCSTRING)
1348
+ def forward(
1349
+ self,
1350
+ input_ids: torch.LongTensor = None,
1351
+ attention_mask: Optional[torch.Tensor] = None,
1352
+ position_ids: Optional[torch.LongTensor] = None,
1353
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1354
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1355
+ use_cache: Optional[bool] = None,
1356
+ output_attentions: Optional[bool] = None,
1357
+ output_hidden_states: Optional[bool] = None,
1358
+ return_dict: Optional[bool] = None,
1359
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1360
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1361
+ output_hidden_states = (
1362
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1363
+ )
1364
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1365
+
1366
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1367
+
1368
+ # retrieve input_ids and inputs_embeds
1369
+ if input_ids is not None and inputs_embeds is not None:
1370
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1371
+ elif input_ids is not None:
1372
+ batch_size, seq_length = input_ids.shape[:2]
1373
+ elif inputs_embeds is not None:
1374
+ batch_size, seq_length = inputs_embeds.shape[:2]
1375
+ else:
1376
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1377
+
1378
+ if self.gradient_checkpointing and self.training:
1379
+ if use_cache:
1380
+ logger.warning_once(
1381
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1382
+ )
1383
+ use_cache = False
1384
+
1385
+ past_key_values_length = 0
1386
+ if use_cache:
1387
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1388
+ if use_legacy_cache:
1389
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1390
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1391
+
1392
+ if position_ids is None:
1393
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1394
+ position_ids = torch.arange(
1395
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1396
+ )
1397
+ position_ids = position_ids.unsqueeze(0)
1398
+
1399
+ if inputs_embeds is None:
1400
+ inputs_embeds = self.embed_tokens(input_ids)
1401
+
1402
+ if self._use_flash_attention_2:
1403
+ # 2d mask is passed through the layers
1404
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1405
+ elif self._use_sdpa and not output_attentions:
1406
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1407
+ # the manual implementation that requires a 4D causal mask in all cases.
1408
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1409
+ attention_mask,
1410
+ (batch_size, seq_length),
1411
+ inputs_embeds,
1412
+ past_key_values_length,
1413
+ )
1414
+ else:
1415
+ # 4d mask is passed through the layers
1416
+ attention_mask = _prepare_4d_causal_attention_mask(
1417
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1418
+ )
1419
+
1420
+ # embed positions
1421
+ hidden_states = inputs_embeds
1422
+
1423
+ # decoder layers
1424
+ all_hidden_states = () if output_hidden_states else None
1425
+ all_self_attns = () if output_attentions else None
1426
+ next_decoder_cache = None
1427
+
1428
+ for decoder_layer in self.layers:
1429
+ if output_hidden_states:
1430
+ all_hidden_states += (hidden_states,)
1431
+
1432
+ if self.gradient_checkpointing and self.training:
1433
+ layer_outputs = self._gradient_checkpointing_func(
1434
+ decoder_layer.__call__,
1435
+ hidden_states,
1436
+ attention_mask,
1437
+ position_ids,
1438
+ past_key_values,
1439
+ output_attentions,
1440
+ use_cache,
1441
+ )
1442
+ else:
1443
+ layer_outputs = decoder_layer(
1444
+ hidden_states,
1445
+ attention_mask=attention_mask,
1446
+ position_ids=position_ids,
1447
+ past_key_value=past_key_values,
1448
+ output_attentions=output_attentions,
1449
+ use_cache=use_cache,
1450
+ )
1451
+
1452
+ hidden_states = layer_outputs[0]
1453
+
1454
+ if use_cache:
1455
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1456
+
1457
+ if output_attentions:
1458
+ all_self_attns += (layer_outputs[1],)
1459
+
1460
+ hidden_states = self.norm(hidden_states)
1461
+
1462
+ # add hidden states from the last decoder layer
1463
+ if output_hidden_states:
1464
+ all_hidden_states += (hidden_states,)
1465
+
1466
+ next_cache = None
1467
+ if use_cache:
1468
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1469
+ if not return_dict:
1470
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1471
+ return BaseModelOutputWithPast(
1472
+ last_hidden_state=hidden_states,
1473
+ past_key_values=next_cache,
1474
+ hidden_states=all_hidden_states,
1475
+ attentions=all_self_attns,
1476
+ )
1477
+
1478
+
1479
+ class DeepseekFixedForCausalLM(DeepseekFixedPreTrainedModel):
1480
+ _tied_weights_keys = ["lm_head.weight"]
1481
+
1482
+ def __init__(self, config):
1483
+ super().__init__(config)
1484
+ self.model = DeepseekFixedModel(config)
1485
+ self.vocab_size = config.vocab_size
1486
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1487
+
1488
+ # Initialize weights and apply final processing
1489
+ self.post_init()
1490
+
1491
+ def get_input_embeddings(self):
1492
+ return self.model.embed_tokens
1493
+
1494
+ def set_input_embeddings(self, value):
1495
+ self.model.embed_tokens = value
1496
+
1497
+ def get_output_embeddings(self):
1498
+ return self.lm_head
1499
+
1500
+ def set_output_embeddings(self, new_embeddings):
1501
+ self.lm_head = new_embeddings
1502
+
1503
+ def set_decoder(self, decoder):
1504
+ self.model = decoder
1505
+
1506
+ def get_decoder(self):
1507
+ return self.model
1508
+
1509
+ @add_start_docstrings_to_model_forward(DeepseekFixed_INPUTS_DOCSTRING)
1510
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1511
+ def forward(
1512
+ self,
1513
+ input_ids: torch.LongTensor = None,
1514
+ attention_mask: Optional[torch.Tensor] = None,
1515
+ position_ids: Optional[torch.LongTensor] = None,
1516
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1517
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1518
+ labels: Optional[torch.LongTensor] = None,
1519
+ use_cache: Optional[bool] = None,
1520
+ output_attentions: Optional[bool] = None,
1521
+ output_hidden_states: Optional[bool] = None,
1522
+ return_dict: Optional[bool] = None,
1523
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1524
+ r"""
1525
+ Args:
1526
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1527
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1528
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1529
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1530
+
1531
+ Returns:
1532
+
1533
+ Example:
1534
+
1535
+ ```python
1536
+ >>> from transformers import AutoTokenizer
1537
+
1538
+ >>> model = DeepseekFixedForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1539
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1540
+
1541
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1542
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1543
+
1544
+ >>> # Generate
1545
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1546
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1547
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1548
+ ```"""
1549
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1550
+ output_hidden_states = (
1551
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1552
+ )
1553
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1554
+
1555
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1556
+ outputs = self.model(
1557
+ input_ids=input_ids,
1558
+ attention_mask=attention_mask,
1559
+ position_ids=position_ids,
1560
+ past_key_values=past_key_values,
1561
+ inputs_embeds=inputs_embeds,
1562
+ use_cache=use_cache,
1563
+ output_attentions=output_attentions,
1564
+ output_hidden_states=output_hidden_states,
1565
+ return_dict=return_dict,
1566
+ )
1567
+
1568
+ hidden_states = outputs[0]
1569
+ if self.config.pretraining_tp > 1:
1570
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1571
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1572
+ logits = torch.cat(logits, dim=-1)
1573
+ else:
1574
+ logits = self.lm_head(hidden_states)
1575
+ logits = logits.float()
1576
+
1577
+ loss = None
1578
+ if labels is not None:
1579
+ # Shift so that tokens < n predict n
1580
+ shift_logits = logits[..., :-1, :].contiguous()
1581
+ shift_labels = labels[..., 1:].contiguous()
1582
+ # Flatten the tokens
1583
+ loss_fct = CrossEntropyLoss()
1584
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1585
+ shift_labels = shift_labels.view(-1)
1586
+ # Enable model parallelism
1587
+ shift_labels = shift_labels.to(shift_logits.device)
1588
+ loss = loss_fct(shift_logits, shift_labels)
1589
+
1590
+ if not return_dict:
1591
+ output = (logits,) + outputs[1:]
1592
+ return (loss,) + output if loss is not None else output
1593
+
1594
+ return CausalLMOutputWithPast(
1595
+ loss=loss,
1596
+ logits=logits,
1597
+ past_key_values=outputs.past_key_values,
1598
+ hidden_states=outputs.hidden_states,
1599
+ attentions=outputs.attentions,
1600
+ )
1601
+
1602
+ def prepare_inputs_for_generation(
1603
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1604
+ ):
1605
+ if past_key_values is not None:
1606
+ if isinstance(past_key_values, Cache):
1607
+ cache_length = past_key_values.get_seq_length()
1608
+ past_length = past_key_values.seen_tokens
1609
+ max_cache_length = past_key_values.get_max_length()
1610
+ else:
1611
+ cache_length = past_length = past_key_values[0][0].shape[2]
1612
+ max_cache_length = None
1613
+
1614
+ # Keep only the unprocessed tokens:
1615
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1616
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1617
+ # input)
1618
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1619
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1620
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1621
+ # input_ids based on the past_length.
1622
+ elif past_length < input_ids.shape[1]:
1623
+ input_ids = input_ids[:, past_length:]
1624
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1625
+
1626
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1627
+ if (
1628
+ max_cache_length is not None
1629
+ and attention_mask is not None
1630
+ and cache_length + input_ids.shape[1] > max_cache_length
1631
+ ):
1632
+ attention_mask = attention_mask[:, -max_cache_length:]
1633
+
1634
+ position_ids = kwargs.get("position_ids", None)
1635
+ if attention_mask is not None and position_ids is None:
1636
+ # create position_ids on the fly for batch generation
1637
+ position_ids = attention_mask.long().cumsum(-1) - 1
1638
+ position_ids.masked_fill_(attention_mask == 0, 1)
1639
+ if past_key_values:
1640
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1641
+
1642
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1643
+ if inputs_embeds is not None and past_key_values is None:
1644
+ model_inputs = {"inputs_embeds": inputs_embeds}
1645
+ else:
1646
+ model_inputs = {"input_ids": input_ids}
1647
+
1648
+ model_inputs.update(
1649
+ {
1650
+ "position_ids": position_ids,
1651
+ "past_key_values": past_key_values,
1652
+ "use_cache": kwargs.get("use_cache"),
1653
+ "attention_mask": attention_mask,
1654
+ }
1655
+ )
1656
+ return model_inputs
1657
+
1658
+ @staticmethod
1659
+ def _reorder_cache(past_key_values, beam_idx):
1660
+ reordered_past = ()
1661
+ for layer_past in past_key_values:
1662
+ reordered_past += (
1663
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1664
+ )
1665
+ return reordered_past
1666
+
1667
+
1668
+ @add_start_docstrings(
1669
+ """
1670
+ The DeepseekFixed Model transformer with a sequence classification head on top (linear layer).
1671
+
1672
+ [`DeepseekFixedForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1673
+ (e.g. GPT-2) do.
1674
+
1675
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1676
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1677
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1678
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1679
+ each row of the batch).
1680
+ """,
1681
+ DeepseekFixed_START_DOCSTRING,
1682
+ )
1683
+ class DeepseekFixedForSequenceClassification(DeepseekFixedPreTrainedModel):
1684
+ def __init__(self, config):
1685
+ super().__init__(config)
1686
+ self.num_labels = config.num_labels
1687
+ self.model = DeepseekFixedModel(config)
1688
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1689
+
1690
+ # Initialize weights and apply final processing
1691
+ self.post_init()
1692
+
1693
+ def get_input_embeddings(self):
1694
+ return self.model.embed_tokens
1695
+
1696
+ def set_input_embeddings(self, value):
1697
+ self.model.embed_tokens = value
1698
+
1699
+ @add_start_docstrings_to_model_forward(DeepseekFixed_INPUTS_DOCSTRING)
1700
+ def forward(
1701
+ self,
1702
+ input_ids: torch.LongTensor = None,
1703
+ attention_mask: Optional[torch.Tensor] = None,
1704
+ position_ids: Optional[torch.LongTensor] = None,
1705
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1706
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1707
+ labels: Optional[torch.LongTensor] = None,
1708
+ use_cache: Optional[bool] = None,
1709
+ output_attentions: Optional[bool] = None,
1710
+ output_hidden_states: Optional[bool] = None,
1711
+ return_dict: Optional[bool] = None,
1712
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1713
+ r"""
1714
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1715
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1716
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1717
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1718
+ """
1719
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1720
+
1721
+ transformer_outputs = self.model(
1722
+ input_ids,
1723
+ attention_mask=attention_mask,
1724
+ position_ids=position_ids,
1725
+ past_key_values=past_key_values,
1726
+ inputs_embeds=inputs_embeds,
1727
+ use_cache=use_cache,
1728
+ output_attentions=output_attentions,
1729
+ output_hidden_states=output_hidden_states,
1730
+ return_dict=return_dict,
1731
+ )
1732
+ hidden_states = transformer_outputs[0]
1733
+ logits = self.score(hidden_states)
1734
+
1735
+ if input_ids is not None:
1736
+ batch_size = input_ids.shape[0]
1737
+ else:
1738
+ batch_size = inputs_embeds.shape[0]
1739
+
1740
+ if self.config.pad_token_id is None and batch_size != 1:
1741
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1742
+ if self.config.pad_token_id is None:
1743
+ sequence_lengths = -1
1744
+ else:
1745
+ if input_ids is not None:
1746
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1747
+ logits.device
1748
+ )
1749
+ else:
1750
+ sequence_lengths = -1
1751
+
1752
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1753
+
1754
+ loss = None
1755
+ if labels is not None:
1756
+ labels = labels.to(logits.device)
1757
+ if self.config.problem_type is None:
1758
+ if self.num_labels == 1:
1759
+ self.config.problem_type = "regression"
1760
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1761
+ self.config.problem_type = "single_label_classification"
1762
+ else:
1763
+ self.config.problem_type = "multi_label_classification"
1764
+
1765
+ if self.config.problem_type == "regression":
1766
+ loss_fct = MSELoss()
1767
+ if self.num_labels == 1:
1768
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1769
+ else:
1770
+ loss = loss_fct(pooled_logits, labels)
1771
+ elif self.config.problem_type == "single_label_classification":
1772
+ loss_fct = CrossEntropyLoss()
1773
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1774
+ elif self.config.problem_type == "multi_label_classification":
1775
+ loss_fct = BCEWithLogitsLoss()
1776
+ loss = loss_fct(pooled_logits, labels)
1777
+ if not return_dict:
1778
+ output = (pooled_logits,) + transformer_outputs[1:]
1779
+ return ((loss,) + output) if loss is not None else output
1780
+
1781
+ return SequenceClassifierOutputWithPast(
1782
+ loss=loss,
1783
+ logits=pooled_logits,
1784
+ past_key_values=transformer_outputs.past_key_values,
1785
+ hidden_states=transformer_outputs.hidden_states,
1786
+ attentions=transformer_outputs.attentions,
1787
+ )