ZihanWang314 commited on
Commit
e0522c3
·
verified ·
1 Parent(s): 7786569

Upload folder using huggingface_hub

Browse files
all_punct.txt ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ !
2
+ "
3
+ #
4
+ $
5
+ %
6
+ &
7
+ '
8
+ (
9
+ )
10
+ *
11
+ +
12
+ ,
13
+ -
14
+ .
15
+ /
16
+ :
17
+ ;
18
+ <
19
+ =
20
+ >
21
+ ?
22
+ @
23
+ [
24
+ \
25
+ ]
26
+ ^
27
+ _
28
+ `
29
+ {
30
+ |
31
+ }
32
+ ~
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+ _
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+  
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+ ·
110
+
111
+
112
+
113
+
byteVocab.txt ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 0 数
2
+ 1 学
3
+ 2 是
4
+ 3 利
5
+ 4 用
6
+ 5 符
7
+ 6 号
8
+ 7 语
9
+ 8 言
10
+ 9 研
11
+ 10 究
12
+ 11 數
13
+ 12 量
14
+ 13 结
15
+ 14 构
16
+ 15 变
17
+ 16 化
18
+ 17 以
19
+ 18 及
20
+ 19 空
21
+ 20 间
22
+ 21 等
23
+ 22 概
24
+ 23 念
25
+ 24 的
26
+ 25 一
27
+ 26 門
28
+ 27 科
29
+ 28 从
30
+ 29 某
31
+ 30 种
32
+ 31 角
33
+ 32 度
34
+ 33 看
35
+ 34 屬
36
+ 35 於
37
+ 36 形
38
+ 37 式
39
+ 38 學
40
+ 39 種
41
+ 40 透
42
+ 41 過
43
+ 42 抽
44
+ 43 象
45
+ 44 和
46
+ 45 邏
47
+ 46 輯
48
+ 47 推
49
+ 48 理
50
+ 49 使
51
+ 50 由
52
+ 51 計
53
+ 52 算
54
+ 53 對
55
+ 54 物
56
+ 55 體
57
+ 56 狀
58
+ 57 運
59
+ 58 動
60
+ 59 觀
61
+ 60 察
62
+ 61 而
63
+ 62 產
64
+ 63 生
65
+ 64 家
66
+ 65 們
67
+ 66 拓
68
+ 67 展
69
+ 68 這
70
+ 69 些
71
+ 70 為
72
+ 71 了
73
+ 72 公
74
+ 73 新
75
+ 74 猜
76
+ 75 想
77
+ 76 從
78
+ 77 選
79
+ 78 定
80
+ 79 義
81
+ 80 中
82
+ 81 建
83
+ 82 立
84
+ 83 起
85
+ 84 嚴
86
+ 85 謹
87
+ 86 導
88
+ 87 出
89
+ 88 基
90
+ 89 礎
91
+ 90 知
92
+ 91 識
93
+ 92 與
94
+ 93 總
95
+ 94 個
96
+ 95 人
97
+ 96 團
98
+ 97 活
99
+ 98 不
100
+ 99 可
101
+ 100 或
102
+ 101 缺
103
+ 102 環
104
+ 103 本
105
+ 104 完
106
+ 105 善
107
+ 106 早
108
+ 107 在
109
+ 108 古
110
+ 109 埃
111
+ 110 美
112
+ 111 索
113
+ 112 達
114
+ 113 米
115
+ 114 亞
116
+ 115 印
117
+ 116 內
118
+ 117 代
119
+ 118 文
120
+ 119 便
121
+ 120 見
122
+ 121 希
123
+ 122 臘
124
+ 123 那
125
+ 124 裡
126
+ 125 有
127
+ 126 更
128
+ 127 處
129
+ 128 時
130
+ 129 開
131
+ 130 始
132
+ 131 發
133
+ 132 持
134
+ 133 續
135
+ 134 斷
136
+ 135 地
137
+ 136 小
138
+ 137 幅
139
+ 138 進
140
+ 139 至
141
+ 140 世
142
+ 141 紀
143
+ 142 藝
144
+ 143 復
145
+ 144 興
146
+ 145 期
147
+ 146 因
148
+ 147 为
149
+ 148 現
150
+ 149 革
151
+ 150 兩
152
+ 151 者
153
+ 152 交
154
+ 153 互
155
+ 154 致
156
+ 155 加
157
+ 156 速
158
+ 157 发
159
+ 158 直
160
+ 159 今
161
+ 160 日
162
+ 161 并
163
+ 162 成
164
+ 163 許
165
+ 164 多
166
+ 165 國
167
+ 166 區
168
+ 167 教
169
+ 168 育
170
+ 169 範
171
+ 170 疇
172
+ 171 部
173
+ 172 分
174
+ 173 同
175
+ 174 領
176
+ 175 域
177
+ 176 包
178
+ 177 括
179
+ 178 工
180
+ 179 程
181
+ 180 醫
182
+ 181 經
183
+ 182 濟
184
+ 183 金
185
+ 184 融
186
+ 185 應
187
+ 186 通
188
+ 187 常
189
+ 188 被
190
+ 189 稱
191
+ 190 亦
192
+ 191 會
193
+ 192 激
194
+ 193 並
195
+ 194 全
196
+ 195 例
197
+ 196 如
198
+ 197 实
199
+ 198 质
200
+ 199 性
201
+ 200 论
202
+ 201 对
203
+ 202 于
204
+ 203 问
205
+ 204 题
206
+ 205 思
207
+ 206 考
208
+ 207 也
209
+ 208 純
210
+ 209 就
211
+ 210 身
212
+ 211 容
213
+ 212 任
214
+ 213 何
215
+ 214 實
216
+ 215 際
217
+ 216 目
218
+ 217 標
219
+ 218 雖
220
+ 219 然
221
+ 220 但
222
+ 221 其
223
+ 222 过
224
+ 223 之
225
+ 224 处
226
+ 225 詞
227
+ 226 源
228
+ 227 西
229
+ 228 方
230
+ 229 自
231
+ 230 語
232
+ 231 習
233
+ 232 問
234
+ 233 另
235
+ 234 外
236
+ 235 還
237
+ 236 較
238
+ 237 狹
239
+ 238 且
240
+ 239 技
241
+ 240 術
242
+ 241 意
243
+ 242 即
244
+ 243 關
245
+ 244 功
246
+ 245 來
247
+ 246 指
248
+ 247 英
249
+ 248 表
250
+ 249 面
251
+ 250 上
252
+ 251 複
253
+ 252 法
254
+ 253 溯
255
+ 254 拉
256
+ 255 丁
257
+ 256 塞
258
+ 257 罗
259
+ 258 譯
260
+ 259 此
261
+ 260 亚
262
+ 261 里
263
+ 262 士
264
+ 263 德
265
+ 264 拿
266
+ 265 萬
267
+ 266 皆
268
+ 267 汉
269
+ 268 字
270
+ 269 示
271
+ 270 大
272
+ 271 約
273
+ 272 产
274
+ 273 国
275
+ 274 宋
276
+ 275 元
277
+ 276 含
278
+ 277 天
279
+ 278 秦
280
+ 279 九
281
+ 280 韶
282
+ 281 章
283
+ 282 永
284
+ 283 樂
285
+ 284 典
286
+ 285 記
287
+ 286 書
288
+ 287 周
289
+ 288 密
290
+ 289 所
291
+ 290 著
292
+ 291 癸
293
+ 292 辛
294
+ 293 雜
295
+ 294 爲
296
+ 295 略
297
+ 296 軌
298
+ 297 明
299
+ 298 柯
300
+ 299 尚
301
+ 300 遷
302
+ 301 钥
303
+ 302 清
304
+ 303 杜
305
+ 304 耕
306
+ 305 拾
307
+ 306 遺
308
+ 307 取
309
+ 308 忠
310
+ 309 撰
311
+ 310 到
312
+ 311 年
313
+ 312 名
314
+ 313 審
315
+ 314 查
316
+ 315 委
317
+ 316 員
318
+ 317 況
319
+ 318 後
320
+ 319 確
321
+ 320 認
322
+ 321 历
323
+ 322 史
324
+ 323 着
325
+ 324 久
326
+ 325 遠
327
+ 326 歷
328
+ 327 它
329
+ 328 類
330
+ 329 六
331
+ 330 艺
332
+ 331 腊
333
+ 332 础
334
+ 333 识
335
+ 334 前
336
+ 335 已
337
+ 336 嘗
338
+ 337 試
339
+ 338 則
340
+ 339 衡
341
+ 340 質
342
+ 341 少
343
+ 342 間
344
+ 343 長
345
+ 344 短
346
+ 345 係
347
+ 346 比
348
+ 347 时
349
+ 348 单
350
+ 349 位
351
+ 350 季
352
+ 351 節
353
+ 352 減
354
+ 353 乘
355
+ 354 除
356
+ 355 石
357
+ 356 碑
358
+ 357 泥
359
+ 358 版
360
+ 359 證
361
+ 360 當
362
+ 361 幾
363
+ 362 步
364
+ 363 需
365
+ 364 要
366
+ 365 寫
367
+ 366 作
368
+ 367 他
369
+ 368 錄
370
+ 369 系
371
+ 370 統
372
+ 371 木
373
+ 372 帝
374
+ 373 儲
375
+ 374 存
376
+ 375 據
377
+ 376 奇
378
+ 377 普
379
+ 378 曾
380
+ 379 最
381
+ 380 初
382
+ 381 候
383
+ 382 主
384
+ 383 原
385
+ 384 做
386
+ 385 稅
387
+ 386 務
388
+ 387 貿
389
+ 388 易
390
+ 389 相
391
+ 390 解
392
+ 391 測
393
+ 392 土
394
+ 393 預
395
+ 394 事
396
+ 395 件
397
+ 396 这
398
+ 397 简
399
+ 398 纪
400
+ 399 术
401
+ 400 三
402
+ 401 体
403
+ 402 备
404
+ 403 们
405
+ 404 开
406
+ 405 与
407
+ 406 关
408
+ 407 图
409
+ 408 换
410
+ 409 微
411
+ 410 积
412
+ 411 随
413
+ 412 轉
414
+ 413 向
415
+ 414 集
416
+ 415 合
417
+ 416 逻
418
+ 417 辑
419
+ 418 重
420
+ 419 心
421
+ 420 求
422
+ 421 际
423
+ 422 转
424
+ 423 般
425
+ 424 延
426
+ 425 豐
427
+ 426 富
428
+ 427 都
429
+ 428 受
430
+ 429 惠
431
+ 430 彼
432
+ 431 月
433
+ 432 刊
434
+ 433 說
435
+ 434 放
436
+ 435 評
437
+ 436 論
438
+ 437 資
439
+ 438 料
440
+ 439 庫
441
+ 440 籍
442
+ 441 創
443
+ 442 份
444
+ 443 超
445
+ 444 百
446
+ 445 十
447
+ 446 每
448
+ 447 增
449
+ 448 七
450
+ 449 五
451
+ 450 千
452
+ 451 海
453
+ 452 絕
454
+ 453 涉
455
+ 454 結
456
+ 455 構
457
+ 456 變
458
+ 457 困
459
+ 458 難
460
+ 459 題
461
+ 460 具
462
+ 461 去
463
+ 462 決
464
+ 463 往
465
+ 464 值
466
+ 465 得
467
+ 466 給
468
+ 467 牛
469
+ 468 頓
470
+ 469 莱
471
+ 470 布
472
+ 471 尼
473
+ 472 兹
474
+ 473 積
475
+ 474 費
476
+ 475 曼
477
+ 476 路
478
+ 477 徑
479
+ 478 洞
480
+ 479 二
481
+ 480 弦
482
+ 481 引
483
+ 482 申
484
+ 483 只
485
+ 484 答
486
+ 485 途
487
+ 486 非
488
+ 487 尋
489
+ 488 諾
490
+ 489 貝
491
+ 490 爾
492
+ 491 獎
493
+ 492 維
494
+ 493 格
495
+ 494 納
496
+ 495 像
497
+ 496 效
498
+ 497 爆
499
+ 498 專
500
+ 499 業
501
+ 500 歧
502
+ 501 又
503
+ 502 電
504
+ 503 腦
505
+ 504 談
506
+ 505 優
507
+ 506 簡
508
+ 507 單
509
+ 508 巧
510
+ 509 妙
511
+ 510 歐
512
+ 511 無
config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DeepseekV2ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_deepseek.DeepseekV2Config",
9
+ "AutoModel": "modeling_deepseek.DeepseekV2Model",
10
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV2ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.001,
13
+ "bos_token_id": 100000,
14
+ "eos_token_id": 100001,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 1,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 2048,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 10944,
21
+ "kv_lora_rank": 512,
22
+ "max_position_embeddings": 4096,
23
+ "model_type": "deepseek_v2",
24
+ "moe_intermediate_size": 1408,
25
+ "moe_layer_freq": 1,
26
+ "n_group": 1,
27
+ "n_routed_experts": 64,
28
+ "n_shared_experts": 2,
29
+ "norm_topk_prob": false,
30
+ "num_attention_heads": 16,
31
+ "num_experts_per_tok": 6,
32
+ "num_hidden_layers": 27,
33
+ "num_key_value_heads": 16,
34
+ "pretraining_tp": 1,
35
+ "q_lora_rank": null,
36
+ "qk_nope_head_dim": 128,
37
+ "qk_rope_head_dim": 64,
38
+ "rms_norm_eps": 1e-06,
39
+ "rope_scaling": null,
40
+ "rope_theta": 10000,
41
+ "routed_scaling_factor": 1.0,
42
+ "scoring_func": "softmax",
43
+ "seq_aux": true,
44
+ "tie_word_embeddings": false,
45
+ "topk_group": 1,
46
+ "topk_method": "greedy",
47
+ "torch_dtype": "bfloat16",
48
+ "transformers_version": "4.33.1",
49
+ "use_cache": true,
50
+ "v_head_dim": 128,
51
+ "vocab_size": 102400
52
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
7
+ class DeepseekV2Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V2.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 102400):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV2Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_attention_heads (`int`, *optional*, defaults to 32):
30
+ Number of attention heads for each attention layer in the Transformer decoder.
31
+ n_shared_experts (`int`, *optional*, defaults to None):
32
+ Number of shared experts, None means dense model.
33
+ n_routed_experts (`int`, *optional*, defaults to None):
34
+ Number of routed experts, None means dense model.
35
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
36
+ Scaling factor or routed experts.
37
+ topk_method (`str`, *optional*, defaults to `gready`):
38
+ Topk method used in routed gate.
39
+ n_group (`int`, *optional*, defaults to None):
40
+ Number of groups for routed experts.
41
+ topk_group (`int`, *optional*, defaults to None):
42
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
43
+ num_experts_per_tok (`int`, *optional*, defaults to None):
44
+ Number of selected experts, None means dense model.
45
+ moe_layer_freq (`int`, *optional*, defaults to 1):
46
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
47
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
48
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
49
+ \--k dense layers--/
50
+ norm_topk_prob (`bool`, *optional*, defaults to False):
51
+ Whether to normalize the weights of the routed experts.
52
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
53
+ Method of computing expert weights.
54
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
55
+ Auxiliary loss weight coefficient.
56
+ seq_aux = (`bool`, *optional*, defaults to True):
57
+ Whether to compute the auxiliary loss for each individual sample.
58
+ num_key_value_heads (`int`, *optional*):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
62
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
63
+ by meanpooling all the original heads within that group. For more details checkout [this
64
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
65
+ `num_attention_heads`.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
73
+ The epsilon used by the rms normalization layers.
74
+ use_cache (`bool`, *optional*, defaults to `True`):
75
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
76
+ relevant if `config.is_decoder=True`.
77
+ pad_token_id (`int`, *optional*):
78
+ Padding token id.
79
+ bos_token_id (`int`, *optional*, defaults to 1):
80
+ Beginning of stream token id.
81
+ eos_token_id (`int`, *optional*, defaults to 2):
82
+ End of stream token id.
83
+ pretraining_tp (`int`, *optional*, defaults to 1):
84
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
85
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
86
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
87
+ issue](https://github.com/pytorch/pytorch/issues/76232).
88
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
89
+ Whether to tie weight embeddings
90
+ rope_theta (`float`, *optional*, defaults to 10000.0):
91
+ The base period of the RoPE embeddings.
92
+ rope_scaling (`Dict`, *optional*):
93
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
94
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
95
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
96
+ `max_position_embeddings` to the expected new maximum.
97
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
98
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
99
+ attention_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for the attention probabilities.
101
+
102
+ ```python
103
+ >>> from transformers import DeepseekV2Model, DeepseekV2Config
104
+
105
+ >>> # Initializing a Deepseek-V2 style configuration
106
+ >>> configuration = DeepseekV2Config()
107
+
108
+ >>> # Accessing the model configuration
109
+ >>> configuration = model.config
110
+ ```"""
111
+
112
+ model_type = "deepseek_v2"
113
+ keys_to_ignore_at_inference = ["past_key_values"]
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=102400,
118
+ hidden_size=4096,
119
+ intermediate_size=11008,
120
+ moe_intermediate_size = 1407,
121
+ num_hidden_layers=30,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=32,
124
+ n_shared_experts = None,
125
+ n_routed_experts = None,
126
+ ep_size = 1,
127
+ routed_scaling_factor = 1.0,
128
+ kv_lora_rank = 512,
129
+ q_lora_rank = 1536,
130
+ qk_rope_head_dim = 64,
131
+ v_head_dim = 128,
132
+ qk_nope_head_dim = 128,
133
+ topk_method = 'gready',
134
+ n_group = None,
135
+ topk_group = None,
136
+ num_experts_per_tok = None,
137
+ moe_layer_freq = 1,
138
+ first_k_dense_replace = 0,
139
+ norm_topk_prob = False,
140
+ scoring_func = 'softmax',
141
+ aux_loss_alpha = 0.001,
142
+ seq_aux = True,
143
+ hidden_act="silu",
144
+ max_position_embeddings=2048,
145
+ initializer_range=0.02,
146
+ rms_norm_eps=1e-6,
147
+ use_cache=True,
148
+ pad_token_id=None,
149
+ bos_token_id=100000,
150
+ eos_token_id=100001,
151
+ pretraining_tp=1,
152
+ tie_word_embeddings=False,
153
+ rope_theta=10000.0,
154
+ rope_scaling=None,
155
+ attention_bias=False,
156
+ attention_dropout=0.0,
157
+ **kwargs,
158
+ ):
159
+ self.vocab_size = vocab_size
160
+ self.max_position_embeddings = max_position_embeddings
161
+ self.hidden_size = hidden_size
162
+ self.intermediate_size = intermediate_size
163
+ self.moe_intermediate_size = moe_intermediate_size
164
+ self.num_hidden_layers = num_hidden_layers
165
+ self.num_attention_heads = num_attention_heads
166
+ self.n_shared_experts = n_shared_experts
167
+ self.n_routed_experts = n_routed_experts
168
+ self.ep_size = ep_size
169
+ self.routed_scaling_factor = routed_scaling_factor
170
+ self.kv_lora_rank = kv_lora_rank
171
+ self.q_lora_rank = q_lora_rank
172
+ self.qk_rope_head_dim = qk_rope_head_dim
173
+ self.v_head_dim = v_head_dim
174
+ self.qk_nope_head_dim = qk_nope_head_dim
175
+ self.topk_method = topk_method
176
+ self.n_group = n_group
177
+ self.topk_group = topk_group
178
+ self.num_experts_per_tok = num_experts_per_tok
179
+ self.moe_layer_freq = moe_layer_freq
180
+ self.first_k_dense_replace = first_k_dense_replace
181
+ self.norm_topk_prob = norm_topk_prob
182
+ self.scoring_func = scoring_func
183
+ self.aux_loss_alpha = aux_loss_alpha
184
+ self.seq_aux = seq_aux
185
+ # for backward compatibility
186
+ if num_key_value_heads is None:
187
+ num_key_value_heads = num_attention_heads
188
+
189
+ self.num_key_value_heads = num_key_value_heads
190
+ self.hidden_act = hidden_act
191
+ self.initializer_range = initializer_range
192
+ self.rms_norm_eps = rms_norm_eps
193
+ self.pretraining_tp = pretraining_tp
194
+ self.use_cache = use_cache
195
+ self.rope_theta = rope_theta
196
+ self.rope_scaling = rope_scaling
197
+ self.attention_bias = attention_bias
198
+ self.attention_dropout = attention_dropout
199
+
200
+ super().__init__(
201
+ pad_token_id=pad_token_id,
202
+ bos_token_id=bos_token_id,
203
+ eos_token_id=eos_token_id,
204
+ tie_word_embeddings=tie_word_embeddings,
205
+ **kwargs,
206
+ )
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100000,
4
+ "eos_token_id": 100001,
5
+ "do_sample": true,
6
+ "temperature": 0.3,
7
+ "top_p": 0.95,
8
+ "transformers_version": "4.39.3"
9
+ }
model-00001-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9918de0d7b98d0313f6aa7ee52b5b4c1995237ac811b18e9eaaf9b248a75363
3
+ size 8594887408
model-00002-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ffee204b4162ab7fbb732d5e6f156079d14410115b357527667caa4b68a6044
3
+ size 8591757448
model-00003-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0a93987f8dcd969e03512ed99b1373028a35fb66f3217e2e63b2a47291db726
3
+ size 8590718520
model-00004-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e491207f17337f7c3da8c6bd60c0b2244d6f2e72388ee086f3db89acb521b730
3
+ size 5636263200
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_deepseek.py ADDED
@@ -0,0 +1,1936 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch DeepSeek model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+ from collections import Counter
25
+ import os
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+
33
+ from transformers.activations import ACT2FN
34
+ from transformers.cache_utils import Cache, DynamicCache
35
+ from transformers.modeling_attn_mask_utils import (
36
+ AttentionMaskConverter,
37
+ _prepare_4d_attention_mask,
38
+ _prepare_4d_causal_attention_mask,
39
+ )
40
+ from transformers.modeling_outputs import (
41
+ BaseModelOutputWithPast,
42
+ CausalLMOutputWithPast,
43
+ SequenceClassifierOutputWithPast,
44
+ )
45
+ from transformers.modeling_utils import PreTrainedModel
46
+ from transformers.pytorch_utils import (
47
+ ALL_LAYERNORM_LAYERS,
48
+ is_torch_greater_or_equal_than_1_13,
49
+ )
50
+ from transformers.utils import (
51
+ add_start_docstrings,
52
+ add_start_docstrings_to_model_forward,
53
+ is_flash_attn_2_available,
54
+ is_flash_attn_greater_or_equal_2_10,
55
+ logging,
56
+ replace_return_docstrings,
57
+ )
58
+ from transformers.utils.import_utils import is_torch_fx_available
59
+ from .configuration_deepseek import DeepseekV2Config
60
+ import torch.distributed as dist
61
+ import numpy as np
62
+
63
+ if is_flash_attn_2_available():
64
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
65
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
66
+
67
+
68
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
69
+ # It means that the function will not be traced through and simply appear as a node in the graph.
70
+ if is_torch_fx_available():
71
+ if not is_torch_greater_or_equal_than_1_13:
72
+ import torch.fx
73
+
74
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
75
+
76
+
77
+ logger = logging.get_logger(__name__)
78
+
79
+ _CONFIG_FOR_DOC = "DeepseekV2Config"
80
+
81
+
82
+ def _get_unpad_data(attention_mask):
83
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
84
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
85
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
86
+ cu_seqlens = F.pad(
87
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
88
+ )
89
+ return (
90
+ indices,
91
+ cu_seqlens,
92
+ max_seqlen_in_batch,
93
+ )
94
+
95
+
96
+ class DeepseekV2RMSNorm(nn.Module):
97
+ def __init__(self, hidden_size, eps=1e-6):
98
+ """
99
+ DeepseekV2RMSNorm is equivalent to T5LayerNorm
100
+ """
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ input_dtype = hidden_states.dtype
107
+ hidden_states = hidden_states.to(torch.float32)
108
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
109
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
110
+ return self.weight * hidden_states.to(input_dtype)
111
+
112
+
113
+ ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
114
+
115
+
116
+ class DeepseekV2RotaryEmbedding(nn.Module):
117
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
118
+ super().__init__()
119
+
120
+ self.dim = dim
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.base = base
123
+ inv_freq = 1.0 / (
124
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
125
+ )
126
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
127
+
128
+ # Build here to make `torch.jit.trace` work.
129
+ self._set_cos_sin_cache(
130
+ seq_len=max_position_embeddings,
131
+ device=self.inv_freq.device,
132
+ dtype=torch.get_default_dtype(),
133
+ )
134
+ self.max_seq_len_cached = None
135
+
136
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
137
+ self.max_seq_len_cached = seq_len
138
+ t = torch.arange(
139
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
140
+ )
141
+
142
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
143
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
146
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
147
+
148
+ def forward(self, x, seq_len=None):
149
+ # x: [bs, num_attention_heads, seq_len, head_size]
150
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
151
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
152
+
153
+ return (
154
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
155
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
156
+ )
157
+
158
+
159
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
160
+ class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
161
+ """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
162
+
163
+ def __init__(
164
+ self,
165
+ dim,
166
+ max_position_embeddings=2048,
167
+ base=10000,
168
+ device=None,
169
+ scaling_factor=1.0,
170
+ ):
171
+ self.scaling_factor = scaling_factor
172
+ super().__init__(dim, max_position_embeddings, base, device)
173
+
174
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
175
+ self.max_seq_len_cached = seq_len
176
+ t = torch.arange(
177
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
178
+ )
179
+ t = t / self.scaling_factor
180
+
181
+ freqs = torch.outer(t, self.inv_freq)
182
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
183
+ emb = torch.cat((freqs, freqs), dim=-1)
184
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
185
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
186
+
187
+
188
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
189
+ class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
190
+ """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
191
+
192
+ def __init__(
193
+ self,
194
+ dim,
195
+ max_position_embeddings=2048,
196
+ base=10000,
197
+ device=None,
198
+ scaling_factor=1.0,
199
+ ):
200
+ self.scaling_factor = scaling_factor
201
+ super().__init__(dim, max_position_embeddings, base, device)
202
+
203
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
204
+ self.max_seq_len_cached = seq_len
205
+
206
+ if seq_len > self.max_position_embeddings:
207
+ base = self.base * (
208
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
209
+ - (self.scaling_factor - 1)
210
+ ) ** (self.dim / (self.dim - 2))
211
+ inv_freq = 1.0 / (
212
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
213
+ )
214
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
215
+
216
+ t = torch.arange(
217
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
218
+ )
219
+
220
+ freqs = torch.outer(t, self.inv_freq)
221
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
222
+ emb = torch.cat((freqs, freqs), dim=-1)
223
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
224
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
225
+
226
+
227
+ # Inverse dim formula to find dim based on number of rotations
228
+ def yarn_find_correction_dim(
229
+ num_rotations, dim, base=10000, max_position_embeddings=2048
230
+ ):
231
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
232
+ 2 * math.log(base)
233
+ )
234
+
235
+
236
+ # Find dim range bounds based on rotations
237
+ def yarn_find_correction_range(
238
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
239
+ ):
240
+ low = math.floor(
241
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
242
+ )
243
+ high = math.ceil(
244
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
245
+ )
246
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
247
+
248
+
249
+ def yarn_get_mscale(scale=1, mscale=1):
250
+ if scale <= 1:
251
+ return 1.0
252
+ return 0.1 * mscale * math.log(scale) + 1.0
253
+
254
+
255
+ def yarn_linear_ramp_mask(min, max, dim):
256
+ if min == max:
257
+ max += 0.001 # Prevent singularity
258
+
259
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
260
+ ramp_func = torch.clamp(linear_func, 0, 1)
261
+ return ramp_func
262
+
263
+
264
+ class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
265
+
266
+ def __init__(
267
+ self,
268
+ dim,
269
+ max_position_embeddings=2048,
270
+ base=10000,
271
+ device=None,
272
+ scaling_factor=1.0,
273
+ original_max_position_embeddings=4096,
274
+ beta_fast=32,
275
+ beta_slow=1,
276
+ mscale=1,
277
+ mscale_all_dim=0,
278
+ ):
279
+ self.scaling_factor = scaling_factor
280
+ self.original_max_position_embeddings = original_max_position_embeddings
281
+ self.beta_fast = beta_fast
282
+ self.beta_slow = beta_slow
283
+ self.mscale = mscale
284
+ self.mscale_all_dim = mscale_all_dim
285
+ super().__init__(dim, max_position_embeddings, base, device)
286
+
287
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
288
+ self.max_seq_len_cached = seq_len
289
+ dim = self.dim
290
+
291
+ freq_extra = 1.0 / (
292
+ self.base
293
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
294
+ )
295
+ freq_inter = 1.0 / (
296
+ self.scaling_factor
297
+ * self.base
298
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
299
+ )
300
+
301
+ low, high = yarn_find_correction_range(
302
+ self.beta_fast,
303
+ self.beta_slow,
304
+ dim,
305
+ self.base,
306
+ self.original_max_position_embeddings,
307
+ )
308
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
309
+ device=device, dtype=torch.float32
310
+ )
311
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
312
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
313
+
314
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
315
+
316
+ freqs = torch.outer(t, inv_freq)
317
+
318
+ _mscale = float(
319
+ yarn_get_mscale(self.scaling_factor, self.mscale)
320
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
321
+ )
322
+
323
+ emb = torch.cat((freqs, freqs), dim=-1)
324
+ self.register_buffer(
325
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
326
+ )
327
+ self.register_buffer(
328
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
329
+ )
330
+
331
+
332
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
333
+ def rotate_half(x):
334
+ """Rotates half the hidden dims of the input."""
335
+ x1 = x[..., : x.shape[-1] // 2]
336
+ x2 = x[..., x.shape[-1] // 2 :]
337
+ return torch.cat((-x2, x1), dim=-1)
338
+
339
+
340
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
341
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
342
+ """Applies Rotary Position Embedding to the query and key tensors.
343
+
344
+ Args:
345
+ q (`torch.Tensor`): The query tensor.
346
+ k (`torch.Tensor`): The key tensor.
347
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
348
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
349
+ position_ids (`torch.Tensor`):
350
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
351
+ used to pass offsetted position ids when working with a KV-cache.
352
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
353
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
354
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
355
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
356
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
357
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
358
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
359
+ Returns:
360
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
361
+ """
362
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
363
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
364
+
365
+ b, h, s, d = q.shape
366
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
367
+
368
+ b, h, s, d = k.shape
369
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
370
+
371
+ q_embed = (q * cos) + (rotate_half(q) * sin)
372
+ k_embed = (k * cos) + (rotate_half(k) * sin)
373
+ return q_embed, k_embed
374
+
375
+
376
+ class DeepseekV2MLP(nn.Module):
377
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
378
+ super().__init__()
379
+ self.config = config
380
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
381
+ self.intermediate_size = (
382
+ config.intermediate_size if intermediate_size is None else intermediate_size
383
+ )
384
+
385
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
386
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
387
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
388
+ self.act_fn = ACT2FN[config.hidden_act]
389
+
390
+ def forward(self, x):
391
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
392
+ return down_proj
393
+
394
+
395
+ class MoEGate(nn.Module):
396
+ def __init__(self, config):
397
+ super().__init__()
398
+ self.config = config
399
+ self.top_k = config.num_experts_per_tok
400
+ self.n_routed_experts = config.n_routed_experts
401
+ self.routed_scaling_factor = config.routed_scaling_factor
402
+ self.scoring_func = config.scoring_func
403
+ self.alpha = config.aux_loss_alpha
404
+ self.seq_aux = config.seq_aux
405
+ self.topk_method = config.topk_method
406
+ self.n_group = config.n_group
407
+ self.topk_group = config.topk_group
408
+
409
+ # topk selection algorithm
410
+ self.norm_topk_prob = config.norm_topk_prob
411
+ self.gating_dim = config.hidden_size
412
+ self.weight = nn.Parameter(
413
+ torch.empty((self.n_routed_experts, self.gating_dim))
414
+ )
415
+ self.reset_parameters()
416
+
417
+ def reset_parameters(self) -> None:
418
+ import torch.nn.init as init
419
+
420
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
421
+
422
+ def forward(self, hidden_states):
423
+ bsz, seq_len, h = hidden_states.shape
424
+ ### compute gating score
425
+ hidden_states = hidden_states.view(-1, h)
426
+ logits = F.linear(
427
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
428
+ )
429
+ if self.scoring_func == "softmax":
430
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
431
+ else:
432
+ raise NotImplementedError(
433
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
434
+ )
435
+
436
+ ### select top-k experts
437
+ if self.topk_method == "greedy":
438
+ topk_weight, topk_idx = torch.topk(
439
+ scores, k=self.top_k, dim=-1, sorted=False
440
+ )
441
+ elif self.topk_method == "group_limited_greedy":
442
+ group_scores = (
443
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
444
+ ) # [n, n_group]
445
+ group_idx = torch.topk(
446
+ group_scores, k=self.topk_group, dim=-1, sorted=False
447
+ )[
448
+ 1
449
+ ] # [n, top_k_group]
450
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
451
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
452
+ score_mask = (
453
+ group_mask.unsqueeze(-1)
454
+ .expand(
455
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
456
+ )
457
+ .reshape(bsz * seq_len, -1)
458
+ ) # [n, e]
459
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
460
+ topk_weight, topk_idx = torch.topk(
461
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
462
+ )
463
+
464
+ ### norm gate to sum 1
465
+ if self.top_k > 1 and self.norm_topk_prob:
466
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
467
+ topk_weight = topk_weight / denominator
468
+ else:
469
+ topk_weight = topk_weight * self.routed_scaling_factor
470
+ ### expert-level computation auxiliary loss
471
+ if self.training and self.alpha > 0.0:
472
+ scores_for_aux = scores
473
+ aux_topk = self.top_k
474
+ # always compute aux loss based on the naive greedy topk method
475
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
476
+ if self.seq_aux:
477
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
478
+ ce = torch.zeros(
479
+ bsz, self.n_routed_experts, device=hidden_states.device
480
+ )
481
+ ce.scatter_add_(
482
+ 1,
483
+ topk_idx_for_aux_loss,
484
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
485
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
486
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
487
+ dim=1
488
+ ).mean() * self.alpha
489
+ else:
490
+ mask_ce = F.one_hot(
491
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
492
+ )
493
+ ce = mask_ce.float().mean(0)
494
+ Pi = scores_for_aux.mean(0)
495
+ fi = ce * self.n_routed_experts
496
+ aux_loss = (Pi * fi).sum() * self.alpha
497
+ else:
498
+ aux_loss = None
499
+ return topk_idx, topk_weight, aux_loss
500
+
501
+
502
+ class AddAuxiliaryLoss(torch.autograd.Function):
503
+ """
504
+ The trick function of adding auxiliary (aux) loss,
505
+ which includes the gradient of the aux loss during backpropagation.
506
+ """
507
+
508
+ @staticmethod
509
+ def forward(ctx, x, loss):
510
+ assert loss.numel() == 1
511
+ ctx.dtype = loss.dtype
512
+ ctx.required_aux_loss = loss.requires_grad
513
+ return x
514
+
515
+ @staticmethod
516
+ def backward(ctx, grad_output):
517
+ grad_loss = None
518
+ if ctx.required_aux_loss:
519
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
520
+ return grad_output, grad_loss
521
+
522
+
523
+ class DeepseekV2MoE(nn.Module):
524
+ """
525
+ A mixed expert module containing shared experts.
526
+ """
527
+
528
+ def __init__(self, config, layer_idx):
529
+ super().__init__()
530
+ self.config = config
531
+ self.layer_idx = layer_idx
532
+ self.num_experts_per_tok = config.num_experts_per_tok
533
+
534
+ if hasattr(config, "ep_size") and config.ep_size > 1:
535
+ assert config.ep_size == dist.get_world_size()
536
+ self.ep_size = config.ep_size
537
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
538
+ self.ep_rank = dist.get_rank()
539
+ self.experts = nn.ModuleList(
540
+ [
541
+ (
542
+ DeepseekV2MLP(
543
+ config, intermediate_size=config.moe_intermediate_size
544
+ )
545
+ if i >= self.ep_rank * self.experts_per_rank
546
+ and i < (self.ep_rank + 1) * self.experts_per_rank
547
+ else None
548
+ )
549
+ for i in range(config.n_routed_experts)
550
+ ]
551
+ )
552
+ else:
553
+ self.ep_size = 1
554
+ self.experts_per_rank = config.n_routed_experts
555
+ self.ep_rank = 0
556
+ self.experts = nn.ModuleList(
557
+ [
558
+ DeepseekV2MLP(
559
+ config, intermediate_size=config.moe_intermediate_size
560
+ )
561
+ for i in range(config.n_routed_experts)
562
+ ]
563
+ )
564
+ self.gate = MoEGate(config)
565
+ if config.n_shared_experts is not None:
566
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
567
+ self.shared_experts = DeepseekV2MLP(
568
+ config=config, intermediate_size=intermediate_size
569
+ )
570
+
571
+ def forward(self, hidden_states):
572
+ identity = hidden_states
573
+ orig_shape = hidden_states.shape
574
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
575
+ if hasattr(self.config, 'log_expert_weights') and self.config.log_expert_weights:
576
+ assert hasattr(self.config, 'expert_log_dir'), "Please specify expert_log_dir in the config to log the expert weights"
577
+ log_dir = self.config.expert_log_dir
578
+ file_path = os.path.join(log_dir, f"expert_weights_{self.layer_idx}.txt")
579
+ with open(file_path, "a") as f:
580
+ tk_idx_list = topk_idx.view(-1).tolist()
581
+ tk_weight_list = topk_weight.view(-1).tolist()
582
+ f.write("\t".join([str(i) for i in tk_idx_list]) + "\t\t" + "\t".join([str(round(i, 4)) for i in tk_weight_list]) + "\n")
583
+
584
+
585
+
586
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
587
+ flat_topk_idx = topk_idx.view(-1)
588
+ if self.training:
589
+ hidden_states = hidden_states.repeat_interleave(
590
+ self.num_experts_per_tok, dim=0
591
+ )
592
+ y = torch.empty_like(hidden_states)
593
+ for i, expert in enumerate(self.experts):
594
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
595
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
596
+ y = y.to(hidden_states.dtype).view(*orig_shape)
597
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
598
+ else:
599
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
600
+ if self.config.n_shared_experts is not None:
601
+ y = y + self.shared_experts(identity)
602
+ return y
603
+
604
+ @torch.no_grad()
605
+ def moe_infer(self, x, topk_ids, topk_weight):
606
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
607
+ cnts.scatter_(1, topk_ids, 1)
608
+ tokens_per_expert = cnts.sum(dim=0)
609
+ idxs = topk_ids.view(-1).argsort()
610
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
611
+ sorted_tokens_shape = sorted_tokens.shape
612
+ if self.ep_size > 1:
613
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
614
+ tokens_per_expert_group = tokens_per_expert.new_empty(
615
+ tokens_per_expert.shape[0]
616
+ )
617
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
618
+ output_splits = (
619
+ tokens_per_expert_group.view(self.ep_size, -1)
620
+ .sum(1)
621
+ .cpu()
622
+ .numpy()
623
+ .tolist()
624
+ )
625
+ gathered_tokens = sorted_tokens.new_empty(
626
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
627
+ )
628
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
629
+ dist.all_to_all(
630
+ list(gathered_tokens.split(output_splits)),
631
+ list(sorted_tokens.split(input_split_sizes)),
632
+ )
633
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
634
+ self.ep_size, self.experts_per_rank
635
+ ).sum(dim=0)
636
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
637
+ s = 0
638
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
639
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
640
+ s += k
641
+ gatherd_idxs = gatherd_idxs.argsort()
642
+ sorted_tokens = gathered_tokens[gatherd_idxs]
643
+ tokens_per_expert = tokens_per_expert_post_gather
644
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
645
+
646
+ outputs = []
647
+ start_idx = 0
648
+ for i, num_tokens in enumerate(tokens_per_expert):
649
+ end_idx = start_idx + num_tokens
650
+ if num_tokens == 0:
651
+ continue
652
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
653
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
654
+ expert_out = expert(tokens_for_this_expert)
655
+ outputs.append(expert_out)
656
+ start_idx = end_idx
657
+
658
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
659
+ if self.ep_size > 1:
660
+ new_x = torch.empty_like(outs)
661
+ new_x[gatherd_idxs] = outs
662
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
663
+ dist.all_to_all(
664
+ list(gathered_tokens.split(input_split_sizes)),
665
+ list(new_x.split(output_splits)),
666
+ )
667
+ outs = gathered_tokens
668
+
669
+ new_x = torch.empty_like(outs)
670
+ new_x[idxs] = outs
671
+ final_out = (
672
+ new_x.view(*topk_ids.shape, -1)
673
+ .type(topk_weight.dtype)
674
+ .mul_(topk_weight.unsqueeze(dim=-1))
675
+ .sum(dim=1)
676
+ .type(new_x.dtype)
677
+ )
678
+ return final_out
679
+
680
+
681
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
682
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
683
+ """
684
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
685
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
686
+ """
687
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
688
+ if n_rep == 1:
689
+ return hidden_states
690
+ hidden_states = hidden_states[:, :, None, :, :].expand(
691
+ batch, num_key_value_heads, n_rep, slen, head_dim
692
+ )
693
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
694
+
695
+
696
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
697
+ class DeepseekV2Attention(nn.Module):
698
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
699
+
700
+ def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
701
+ super().__init__()
702
+ self.config = config
703
+ self.layer_idx = layer_idx
704
+ if layer_idx is None:
705
+ logger.warning_once(
706
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
707
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
708
+ "when creating this class."
709
+ )
710
+
711
+ self.attention_dropout = config.attention_dropout
712
+ self.hidden_size = config.hidden_size
713
+ self.num_heads = config.num_attention_heads
714
+
715
+ self.max_position_embeddings = config.max_position_embeddings
716
+ self.rope_theta = config.rope_theta
717
+ self.q_lora_rank = config.q_lora_rank
718
+ self.qk_rope_head_dim = config.qk_rope_head_dim
719
+ self.kv_lora_rank = config.kv_lora_rank
720
+ self.v_head_dim = config.v_head_dim
721
+ self.qk_nope_head_dim = config.qk_nope_head_dim
722
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
723
+
724
+ self.is_causal = True
725
+
726
+ if self.q_lora_rank is None:
727
+ self.q_proj = nn.Linear(
728
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
729
+ )
730
+ else:
731
+ self.q_a_proj = nn.Linear(
732
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
733
+ )
734
+ self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
735
+ self.q_b_proj = nn.Linear(
736
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
737
+ )
738
+
739
+ self.kv_a_proj_with_mqa = nn.Linear(
740
+ self.hidden_size,
741
+ config.kv_lora_rank + config.qk_rope_head_dim,
742
+ bias=config.attention_bias,
743
+ )
744
+ self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
745
+ self.kv_b_proj = nn.Linear(
746
+ config.kv_lora_rank,
747
+ self.num_heads
748
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
749
+ bias=False,
750
+ )
751
+
752
+ self.o_proj = nn.Linear(
753
+ self.num_heads * self.v_head_dim,
754
+ self.hidden_size,
755
+ bias=config.attention_bias,
756
+ )
757
+ self._init_rope()
758
+
759
+ self.softmax_scale = self.q_head_dim ** (-0.5)
760
+ if self.config.rope_scaling is not None:
761
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
762
+ scaling_factor = self.config.rope_scaling["factor"]
763
+ if mscale_all_dim:
764
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
765
+ self.softmax_scale = self.softmax_scale * mscale * mscale
766
+
767
+ def _init_rope(self):
768
+ if self.config.rope_scaling is None:
769
+ self.rotary_emb = DeepseekV2RotaryEmbedding(
770
+ self.qk_rope_head_dim,
771
+ max_position_embeddings=self.max_position_embeddings,
772
+ base=self.rope_theta,
773
+ )
774
+ else:
775
+ scaling_type = self.config.rope_scaling["type"]
776
+ scaling_factor = self.config.rope_scaling["factor"]
777
+ if scaling_type == "linear":
778
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
779
+ self.qk_rope_head_dim,
780
+ max_position_embeddings=self.max_position_embeddings,
781
+ scaling_factor=scaling_factor,
782
+ base=self.rope_theta,
783
+ )
784
+ elif scaling_type == "dynamic":
785
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
786
+ self.qk_rope_head_dim,
787
+ max_position_embeddings=self.max_position_embeddings,
788
+ scaling_factor=scaling_factor,
789
+ base=self.rope_theta,
790
+ )
791
+ elif scaling_type == "yarn":
792
+ kwargs = {
793
+ key: self.config.rope_scaling[key]
794
+ for key in [
795
+ "original_max_position_embeddings",
796
+ "beta_fast",
797
+ "beta_slow",
798
+ "mscale",
799
+ "mscale_all_dim",
800
+ ]
801
+ if key in self.config.rope_scaling
802
+ }
803
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
804
+ self.qk_rope_head_dim,
805
+ max_position_embeddings=self.max_position_embeddings,
806
+ scaling_factor=scaling_factor,
807
+ base=self.rope_theta,
808
+ **kwargs,
809
+ )
810
+ else:
811
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
812
+
813
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
814
+ return (
815
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
816
+ .transpose(1, 2)
817
+ .contiguous()
818
+ )
819
+
820
+ def forward(
821
+ self,
822
+ hidden_states: torch.Tensor,
823
+ attention_mask: Optional[torch.Tensor] = None,
824
+ position_ids: Optional[torch.LongTensor] = None,
825
+ past_key_value: Optional[Cache] = None,
826
+ output_attentions: bool = False,
827
+ use_cache: bool = False,
828
+ **kwargs,
829
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
830
+ if "padding_mask" in kwargs:
831
+ warnings.warn(
832
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
833
+ )
834
+ bsz, q_len, _ = hidden_states.size()
835
+
836
+ if self.q_lora_rank is None:
837
+ q = self.q_proj(hidden_states)
838
+ else:
839
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
840
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
841
+ q_nope, q_pe = torch.split(
842
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
843
+ )
844
+
845
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
846
+ compressed_kv, k_pe = torch.split(
847
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
848
+ )
849
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
850
+ kv = (
851
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
852
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
853
+ .transpose(1, 2)
854
+ )
855
+
856
+ k_nope, value_states = torch.split(
857
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
858
+ )
859
+ kv_seq_len = value_states.shape[-2]
860
+ if past_key_value is not None:
861
+ if self.layer_idx is None:
862
+ raise ValueError(
863
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
864
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
865
+ "with a layer index."
866
+ )
867
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
868
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
869
+
870
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
871
+
872
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
873
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
874
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
875
+
876
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
877
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
878
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
879
+ if past_key_value is not None:
880
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
881
+ key_states, value_states = past_key_value.update(
882
+ key_states, value_states, self.layer_idx, cache_kwargs
883
+ )
884
+
885
+ attn_weights = (
886
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
887
+ )
888
+
889
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
890
+ raise ValueError(
891
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
892
+ f" {attn_weights.size()}"
893
+ )
894
+ assert attention_mask is not None
895
+ if attention_mask is not None:
896
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
897
+ raise ValueError(
898
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
899
+ )
900
+ attn_weights = attn_weights + attention_mask
901
+
902
+ # upcast attention to fp32
903
+ attn_weights = nn.functional.softmax(
904
+ attn_weights, dim=-1, dtype=torch.float32
905
+ ).to(query_states.dtype)
906
+ attn_weights = nn.functional.dropout(
907
+ attn_weights, p=self.attention_dropout, training=self.training
908
+ )
909
+ attn_output = torch.matmul(attn_weights, value_states)
910
+
911
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
912
+ raise ValueError(
913
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
914
+ f" {attn_output.size()}"
915
+ )
916
+
917
+ attn_output = attn_output.transpose(1, 2).contiguous()
918
+
919
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
920
+
921
+ attn_output = self.o_proj(attn_output)
922
+
923
+ if not output_attentions:
924
+ attn_weights = None
925
+
926
+ return attn_output, attn_weights, past_key_value
927
+
928
+
929
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
930
+ class DeepseekV2FlashAttention2(DeepseekV2Attention):
931
+ """
932
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
933
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
934
+ flash attention and deal with padding tokens in case the input contains any of them.
935
+ """
936
+
937
+ def __init__(self, *args, **kwargs):
938
+ super().__init__(*args, **kwargs)
939
+
940
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
941
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
942
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
943
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
944
+
945
+ def forward(
946
+ self,
947
+ hidden_states: torch.Tensor,
948
+ attention_mask: Optional[torch.LongTensor] = None,
949
+ position_ids: Optional[torch.LongTensor] = None,
950
+ past_key_value: Optional[Cache] = None,
951
+ output_attentions: bool = False,
952
+ use_cache: bool = False,
953
+ **kwargs,
954
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
955
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
956
+ if "padding_mask" in kwargs:
957
+ warnings.warn(
958
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
959
+ )
960
+
961
+ # overwrite attention_mask with padding_mask
962
+ attention_mask = kwargs.pop("padding_mask")
963
+
964
+ output_attentions = False
965
+
966
+ bsz, q_len, _ = hidden_states.size()
967
+
968
+ if self.q_lora_rank is None:
969
+ q = self.q_proj(hidden_states)
970
+ else:
971
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
972
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
973
+ q_nope, q_pe = torch.split(
974
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
975
+ )
976
+
977
+ # Flash attention requires the input to have the shape
978
+ # batch_size x seq_length x head_dim x hidden_dim
979
+ # therefore we just need to keep the original shape
980
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
981
+ compressed_kv, k_pe = torch.split(
982
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
983
+ )
984
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
985
+ kv = (
986
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
987
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
988
+ .transpose(1, 2)
989
+ )
990
+
991
+ k_nope, value_states = torch.split(
992
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
993
+ )
994
+ kv_seq_len = value_states.shape[-2]
995
+
996
+ kv_seq_len = value_states.shape[-2]
997
+ if past_key_value is not None:
998
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
999
+
1000
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1001
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1002
+
1003
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1004
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1005
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1006
+
1007
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1008
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1009
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1010
+
1011
+ if self.q_head_dim != self.v_head_dim:
1012
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1013
+
1014
+ if past_key_value is not None:
1015
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1016
+ key_states, value_states = past_key_value.update(
1017
+ key_states, value_states, self.layer_idx, cache_kwargs
1018
+ )
1019
+
1020
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
1021
+ # to be able to avoid many of these transpose/reshape/view.
1022
+ query_states = query_states.transpose(1, 2)
1023
+ key_states = key_states.transpose(1, 2)
1024
+ value_states = value_states.transpose(1, 2)
1025
+
1026
+ dropout_rate = self.attention_dropout if self.training else 0.0
1027
+
1028
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1029
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1030
+ # cast them back in the correct dtype just to be sure everything works as expected.
1031
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1032
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
1033
+
1034
+ input_dtype = query_states.dtype
1035
+ if input_dtype == torch.float32:
1036
+ # Handle the case where the model is quantized
1037
+ if hasattr(self.config, "_pre_quantization_dtype"):
1038
+ target_dtype = self.config._pre_quantization_dtype
1039
+ elif torch.is_autocast_enabled():
1040
+ target_dtype = torch.get_autocast_gpu_dtype()
1041
+ else:
1042
+ target_dtype = (
1043
+ self.q_proj.weight.dtype
1044
+ if self.q_lora_rank is None
1045
+ else self.q_a_proj.weight.dtype
1046
+ )
1047
+
1048
+ logger.warning_once(
1049
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1050
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1051
+ f" {target_dtype}."
1052
+ )
1053
+
1054
+ query_states = query_states.to(target_dtype)
1055
+ key_states = key_states.to(target_dtype)
1056
+ value_states = value_states.to(target_dtype)
1057
+
1058
+ attn_output = self._flash_attention_forward(
1059
+ query_states,
1060
+ key_states,
1061
+ value_states,
1062
+ attention_mask,
1063
+ q_len,
1064
+ dropout=dropout_rate,
1065
+ softmax_scale=self.softmax_scale,
1066
+ )
1067
+ if self.q_head_dim != self.v_head_dim:
1068
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1069
+
1070
+ attn_output = attn_output.reshape(
1071
+ bsz, q_len, self.num_heads * self.v_head_dim
1072
+ ).contiguous()
1073
+ attn_output = self.o_proj(attn_output)
1074
+
1075
+ if not output_attentions:
1076
+ attn_weights = None
1077
+
1078
+ return attn_output, attn_weights, past_key_value
1079
+
1080
+ def _flash_attention_forward(
1081
+ self,
1082
+ query_states,
1083
+ key_states,
1084
+ value_states,
1085
+ attention_mask,
1086
+ query_length,
1087
+ dropout=0.0,
1088
+ softmax_scale=None,
1089
+ ):
1090
+ """
1091
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1092
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1093
+
1094
+ Args:
1095
+ query_states (`torch.Tensor`):
1096
+ Input query states to be passed to Flash Attention API
1097
+ key_states (`torch.Tensor`):
1098
+ Input key states to be passed to Flash Attention API
1099
+ value_states (`torch.Tensor`):
1100
+ Input value states to be passed to Flash Attention API
1101
+ attention_mask (`torch.Tensor`):
1102
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1103
+ position of padding tokens and 1 for the position of non-padding tokens.
1104
+ dropout (`int`, *optional*):
1105
+ Attention dropout
1106
+ softmax_scale (`float`, *optional*):
1107
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1108
+ """
1109
+ if not self._flash_attn_uses_top_left_mask:
1110
+ causal = self.is_causal
1111
+ else:
1112
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
1113
+ causal = self.is_causal and query_length != 1
1114
+
1115
+ # Contains at least one padding token in the sequence
1116
+ if attention_mask is not None:
1117
+ batch_size = query_states.shape[0]
1118
+ (
1119
+ query_states,
1120
+ key_states,
1121
+ value_states,
1122
+ indices_q,
1123
+ cu_seq_lens,
1124
+ max_seq_lens,
1125
+ ) = self._upad_input(
1126
+ query_states, key_states, value_states, attention_mask, query_length
1127
+ )
1128
+
1129
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1130
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1131
+
1132
+ attn_output_unpad = flash_attn_varlen_func(
1133
+ query_states,
1134
+ key_states,
1135
+ value_states,
1136
+ cu_seqlens_q=cu_seqlens_q,
1137
+ cu_seqlens_k=cu_seqlens_k,
1138
+ max_seqlen_q=max_seqlen_in_batch_q,
1139
+ max_seqlen_k=max_seqlen_in_batch_k,
1140
+ dropout_p=dropout,
1141
+ softmax_scale=softmax_scale,
1142
+ causal=causal,
1143
+ )
1144
+
1145
+ attn_output = pad_input(
1146
+ attn_output_unpad, indices_q, batch_size, query_length
1147
+ )
1148
+ else:
1149
+ attn_output = flash_attn_func(
1150
+ query_states,
1151
+ key_states,
1152
+ value_states,
1153
+ dropout,
1154
+ softmax_scale=softmax_scale,
1155
+ causal=causal,
1156
+ )
1157
+
1158
+ return attn_output
1159
+
1160
+ def _upad_input(
1161
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1162
+ ):
1163
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1164
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1165
+
1166
+ key_layer = index_first_axis(
1167
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1168
+ indices_k,
1169
+ )
1170
+ value_layer = index_first_axis(
1171
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1172
+ indices_k,
1173
+ )
1174
+ if query_length == kv_seq_len:
1175
+ query_layer = index_first_axis(
1176
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1177
+ indices_k,
1178
+ )
1179
+ cu_seqlens_q = cu_seqlens_k
1180
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1181
+ indices_q = indices_k
1182
+ elif query_length == 1:
1183
+ max_seqlen_in_batch_q = 1
1184
+ cu_seqlens_q = torch.arange(
1185
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1186
+ ) # There is a memcpy here, that is very bad.
1187
+ indices_q = cu_seqlens_q[:-1]
1188
+ query_layer = query_layer.squeeze(1)
1189
+ else:
1190
+ # The -q_len: slice assumes left padding.
1191
+ attention_mask = attention_mask[:, -query_length:]
1192
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1193
+ query_layer, attention_mask
1194
+ )
1195
+
1196
+ return (
1197
+ query_layer,
1198
+ key_layer,
1199
+ value_layer,
1200
+ indices_q,
1201
+ (cu_seqlens_q, cu_seqlens_k),
1202
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1203
+ )
1204
+
1205
+
1206
+ ATTENTION_CLASSES = {
1207
+ "eager": DeepseekV2Attention,
1208
+ "flash_attention_2": DeepseekV2FlashAttention2,
1209
+ }
1210
+
1211
+
1212
+ class DeepseekV2DecoderLayer(nn.Module):
1213
+ def __init__(self, config: DeepseekV2Config, layer_idx: int):
1214
+ super().__init__()
1215
+ self.hidden_size = config.hidden_size
1216
+
1217
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1218
+ config=config, layer_idx=layer_idx
1219
+ )
1220
+
1221
+ self.mlp = (
1222
+ DeepseekV2MoE(config, layer_idx)
1223
+ if (
1224
+ config.n_routed_experts is not None
1225
+ and layer_idx >= config.first_k_dense_replace
1226
+ and layer_idx % config.moe_layer_freq == 0
1227
+ )
1228
+ else DeepseekV2MLP(config)
1229
+ )
1230
+ self.input_layernorm = DeepseekV2RMSNorm(
1231
+ config.hidden_size, eps=config.rms_norm_eps
1232
+ )
1233
+ self.post_attention_layernorm = DeepseekV2RMSNorm(
1234
+ config.hidden_size, eps=config.rms_norm_eps
1235
+ )
1236
+
1237
+ def forward(
1238
+ self,
1239
+ hidden_states: torch.Tensor,
1240
+ attention_mask: Optional[torch.Tensor] = None,
1241
+ position_ids: Optional[torch.LongTensor] = None,
1242
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1243
+ output_attentions: Optional[bool] = False,
1244
+ use_cache: Optional[bool] = False,
1245
+ **kwargs,
1246
+ ) -> Tuple[
1247
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1248
+ ]:
1249
+ """
1250
+ Args:
1251
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1252
+ attention_mask (`torch.FloatTensor`, *optional*):
1253
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1254
+ query_sequence_length, key_sequence_length)` if default attention is used.
1255
+ output_attentions (`bool`, *optional*):
1256
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1257
+ returned tensors for more detail.
1258
+ use_cache (`bool`, *optional*):
1259
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1260
+ (see `past_key_values`).
1261
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1262
+ """
1263
+ if "padding_mask" in kwargs:
1264
+ warnings.warn(
1265
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1266
+ )
1267
+ residual = hidden_states
1268
+
1269
+ hidden_states = self.input_layernorm(hidden_states)
1270
+
1271
+ # Self Attention
1272
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1273
+ hidden_states=hidden_states,
1274
+ attention_mask=attention_mask,
1275
+ position_ids=position_ids,
1276
+ past_key_value=past_key_value,
1277
+ output_attentions=output_attentions,
1278
+ use_cache=use_cache,
1279
+ **kwargs,
1280
+ )
1281
+ hidden_states = residual + hidden_states
1282
+
1283
+ # Fully Connected
1284
+ residual = hidden_states
1285
+ hidden_states = self.post_attention_layernorm(hidden_states)
1286
+ hidden_states = self.mlp(hidden_states)
1287
+ hidden_states = residual + hidden_states
1288
+
1289
+ outputs = (hidden_states,)
1290
+
1291
+ if output_attentions:
1292
+ outputs += (self_attn_weights,)
1293
+
1294
+ if use_cache:
1295
+ outputs += (present_key_value,)
1296
+
1297
+ return outputs
1298
+
1299
+
1300
+ DeepseekV2_START_DOCSTRING = r"""
1301
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1302
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1303
+ etc.)
1304
+
1305
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1306
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1307
+ and behavior.
1308
+
1309
+ Parameters:
1310
+ config ([`DeepseekV2Config`]):
1311
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1312
+ load the weights associated with the model, only the configuration. Check out the
1313
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1314
+ """
1315
+
1316
+
1317
+ @add_start_docstrings(
1318
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1319
+ DeepseekV2_START_DOCSTRING,
1320
+ )
1321
+ class DeepseekV2PreTrainedModel(PreTrainedModel):
1322
+ config_class = DeepseekV2Config
1323
+ base_model_prefix = "model"
1324
+ supports_gradient_checkpointing = True
1325
+ _no_split_modules = ["DeepseekV2DecoderLayer"]
1326
+ _skip_keys_device_placement = "past_key_values"
1327
+ _supports_flash_attn_2 = True
1328
+ _supports_cache_class = True
1329
+
1330
+ def _init_weights(self, module):
1331
+ std = self.config.initializer_range
1332
+ if isinstance(module, nn.Linear):
1333
+ module.weight.data.normal_(mean=0.0, std=std)
1334
+ if module.bias is not None:
1335
+ module.bias.data.zero_()
1336
+ elif isinstance(module, nn.Embedding):
1337
+ module.weight.data.normal_(mean=0.0, std=std)
1338
+ if module.padding_idx is not None:
1339
+ module.weight.data[module.padding_idx].zero_()
1340
+
1341
+
1342
+ DeepseekV2_INPUTS_DOCSTRING = r"""
1343
+ Args:
1344
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1345
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1346
+ it.
1347
+
1348
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1349
+ [`PreTrainedTokenizer.__call__`] for details.
1350
+
1351
+ [What are input IDs?](../glossary#input-ids)
1352
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1353
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1354
+
1355
+ - 1 for tokens that are **not masked**,
1356
+ - 0 for tokens that are **masked**.
1357
+
1358
+ [What are attention masks?](../glossary#attention-mask)
1359
+
1360
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1361
+ [`PreTrainedTokenizer.__call__`] for details.
1362
+
1363
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1364
+ `past_key_values`).
1365
+
1366
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1367
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1368
+ information on the default strategy.
1369
+
1370
+ - 1 indicates the head is **not masked**,
1371
+ - 0 indicates the head is **masked**.
1372
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1373
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1374
+ config.n_positions - 1]`.
1375
+
1376
+ [What are position IDs?](../glossary#position-ids)
1377
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1378
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1379
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1380
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1381
+
1382
+ Two formats are allowed:
1383
+ - a [`~cache_utils.Cache`] instance;
1384
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1385
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1386
+ cache format.
1387
+
1388
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1389
+ legacy cache format will be returned.
1390
+
1391
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1392
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1393
+ of shape `(batch_size, sequence_length)`.
1394
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1395
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1396
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1397
+ model's internal embedding lookup matrix.
1398
+ use_cache (`bool`, *optional*):
1399
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1400
+ `past_key_values`).
1401
+ output_attentions (`bool`, *optional*):
1402
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1403
+ tensors for more detail.
1404
+ output_hidden_states (`bool`, *optional*):
1405
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1406
+ more detail.
1407
+ return_dict (`bool`, *optional*):
1408
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1409
+ """
1410
+
1411
+
1412
+ @add_start_docstrings(
1413
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1414
+ DeepseekV2_START_DOCSTRING,
1415
+ )
1416
+ class DeepseekV2Model(DeepseekV2PreTrainedModel):
1417
+ """
1418
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1419
+
1420
+ Args:
1421
+ config: DeepseekV2Config
1422
+ """
1423
+
1424
+ def __init__(self, config: DeepseekV2Config):
1425
+ super().__init__(config)
1426
+ self.padding_idx = config.pad_token_id
1427
+ self.vocab_size = config.vocab_size
1428
+
1429
+ self.embed_tokens = nn.Embedding(
1430
+ config.vocab_size, config.hidden_size, self.padding_idx
1431
+ )
1432
+ self.layers = nn.ModuleList(
1433
+ [
1434
+ DeepseekV2DecoderLayer(config, layer_idx)
1435
+ for layer_idx in range(config.num_hidden_layers)
1436
+ ]
1437
+ )
1438
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1439
+ self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1440
+
1441
+ self.gradient_checkpointing = False
1442
+ # Initialize weights and apply final processing
1443
+ self.post_init()
1444
+
1445
+ def get_input_embeddings(self):
1446
+ return self.embed_tokens
1447
+
1448
+ def set_input_embeddings(self, value):
1449
+ self.embed_tokens = value
1450
+
1451
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1452
+ def forward(
1453
+ self,
1454
+ input_ids: torch.LongTensor = None,
1455
+ attention_mask: Optional[torch.Tensor] = None,
1456
+ position_ids: Optional[torch.LongTensor] = None,
1457
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1458
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1459
+ use_cache: Optional[bool] = None,
1460
+ output_attentions: Optional[bool] = None,
1461
+ output_hidden_states: Optional[bool] = None,
1462
+ return_dict: Optional[bool] = None,
1463
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1464
+ output_attentions = (
1465
+ output_attentions
1466
+ if output_attentions is not None
1467
+ else self.config.output_attentions
1468
+ )
1469
+ output_hidden_states = (
1470
+ output_hidden_states
1471
+ if output_hidden_states is not None
1472
+ else self.config.output_hidden_states
1473
+ )
1474
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1475
+
1476
+ return_dict = (
1477
+ return_dict if return_dict is not None else self.config.use_return_dict
1478
+ )
1479
+
1480
+ # retrieve input_ids and inputs_embeds
1481
+ if input_ids is not None and inputs_embeds is not None:
1482
+ raise ValueError(
1483
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1484
+ )
1485
+ elif input_ids is not None:
1486
+ batch_size, seq_length = input_ids.shape[:2]
1487
+ elif inputs_embeds is not None:
1488
+ batch_size, seq_length = inputs_embeds.shape[:2]
1489
+ else:
1490
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1491
+
1492
+ if self.gradient_checkpointing and self.training:
1493
+ if use_cache:
1494
+ logger.warning_once(
1495
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1496
+ )
1497
+ use_cache = False
1498
+
1499
+ past_key_values_length = 0
1500
+ if use_cache:
1501
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1502
+ if use_legacy_cache:
1503
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1504
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1505
+
1506
+ if position_ids is None:
1507
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1508
+ position_ids = torch.arange(
1509
+ past_key_values_length,
1510
+ seq_length + past_key_values_length,
1511
+ dtype=torch.long,
1512
+ device=device,
1513
+ )
1514
+ position_ids = position_ids.unsqueeze(0)
1515
+
1516
+ if inputs_embeds is None:
1517
+ inputs_embeds = self.embed_tokens(input_ids)
1518
+
1519
+ if self._use_flash_attention_2:
1520
+ # 2d mask is passed through the layers
1521
+ attention_mask = (
1522
+ attention_mask
1523
+ if (attention_mask is not None and 0 in attention_mask)
1524
+ else None
1525
+ )
1526
+ else:
1527
+ # 4d mask is passed through the layers
1528
+ attention_mask = _prepare_4d_causal_attention_mask(
1529
+ attention_mask,
1530
+ (batch_size, seq_length),
1531
+ inputs_embeds,
1532
+ past_key_values_length,
1533
+ )
1534
+
1535
+ # embed positions
1536
+ hidden_states = inputs_embeds
1537
+
1538
+ # decoder layers
1539
+ all_hidden_states = () if output_hidden_states else None
1540
+ all_self_attns = () if output_attentions else None
1541
+ next_decoder_cache = None
1542
+
1543
+ for decoder_layer in self.layers:
1544
+ if output_hidden_states:
1545
+ all_hidden_states += (hidden_states,)
1546
+
1547
+ if self.gradient_checkpointing and self.training:
1548
+ layer_outputs = self._gradient_checkpointing_func(
1549
+ decoder_layer.__call__,
1550
+ hidden_states,
1551
+ attention_mask,
1552
+ position_ids,
1553
+ past_key_values,
1554
+ output_attentions,
1555
+ use_cache,
1556
+ )
1557
+ else:
1558
+ layer_outputs = decoder_layer(
1559
+ hidden_states,
1560
+ attention_mask=attention_mask,
1561
+ position_ids=position_ids,
1562
+ past_key_value=past_key_values,
1563
+ output_attentions=output_attentions,
1564
+ use_cache=use_cache,
1565
+ )
1566
+
1567
+ hidden_states = layer_outputs[0]
1568
+
1569
+ if use_cache:
1570
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1571
+
1572
+ if output_attentions:
1573
+ all_self_attns += (layer_outputs[1],)
1574
+
1575
+ hidden_states = self.norm(hidden_states)
1576
+
1577
+ # add hidden states from the last decoder layer
1578
+ if output_hidden_states:
1579
+ all_hidden_states += (hidden_states,)
1580
+
1581
+ next_cache = None
1582
+ if use_cache:
1583
+ next_cache = (
1584
+ next_decoder_cache.to_legacy_cache()
1585
+ if use_legacy_cache
1586
+ else next_decoder_cache
1587
+ )
1588
+ if not return_dict:
1589
+ return tuple(
1590
+ v
1591
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1592
+ if v is not None
1593
+ )
1594
+ return BaseModelOutputWithPast(
1595
+ last_hidden_state=hidden_states,
1596
+ past_key_values=next_cache,
1597
+ hidden_states=all_hidden_states,
1598
+ attentions=all_self_attns,
1599
+ )
1600
+
1601
+
1602
+ class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1603
+ _tied_weights_keys = ["lm_head.weight"]
1604
+
1605
+ def __init__(self, config):
1606
+ super().__init__(config)
1607
+ self.model = DeepseekV2Model(config)
1608
+ self.vocab_size = config.vocab_size
1609
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1610
+
1611
+ # Initialize weights and apply final processing
1612
+ self.post_init()
1613
+
1614
+ def get_input_embeddings(self):
1615
+ return self.model.embed_tokens
1616
+
1617
+ def set_input_embeddings(self, value):
1618
+ self.model.embed_tokens = value
1619
+
1620
+ def get_output_embeddings(self):
1621
+ return self.lm_head
1622
+
1623
+ def set_output_embeddings(self, new_embeddings):
1624
+ self.lm_head = new_embeddings
1625
+
1626
+ def set_decoder(self, decoder):
1627
+ self.model = decoder
1628
+
1629
+ def get_decoder(self):
1630
+ return self.model
1631
+
1632
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1633
+ @replace_return_docstrings(
1634
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1635
+ )
1636
+ def forward(
1637
+ self,
1638
+ input_ids: torch.LongTensor = None,
1639
+ attention_mask: Optional[torch.Tensor] = None,
1640
+ position_ids: Optional[torch.LongTensor] = None,
1641
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1642
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1643
+ labels: Optional[torch.LongTensor] = None,
1644
+ use_cache: Optional[bool] = None,
1645
+ output_attentions: Optional[bool] = None,
1646
+ output_hidden_states: Optional[bool] = None,
1647
+ return_dict: Optional[bool] = None,
1648
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1649
+ r"""
1650
+ Args:
1651
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1652
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1653
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1654
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1655
+
1656
+ Returns:
1657
+
1658
+ Example:
1659
+
1660
+ ```python
1661
+ >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1662
+
1663
+ >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1664
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1665
+
1666
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1667
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1668
+
1669
+ >>> # Generate
1670
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1671
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1672
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1673
+ ```"""
1674
+ output_attentions = (
1675
+ output_attentions
1676
+ if output_attentions is not None
1677
+ else self.config.output_attentions
1678
+ )
1679
+ output_hidden_states = (
1680
+ output_hidden_states
1681
+ if output_hidden_states is not None
1682
+ else self.config.output_hidden_states
1683
+ )
1684
+ return_dict = (
1685
+ return_dict if return_dict is not None else self.config.use_return_dict
1686
+ )
1687
+
1688
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1689
+ outputs = self.model(
1690
+ input_ids=input_ids,
1691
+ attention_mask=attention_mask,
1692
+ position_ids=position_ids,
1693
+ past_key_values=past_key_values,
1694
+ inputs_embeds=inputs_embeds,
1695
+ use_cache=use_cache,
1696
+ output_attentions=output_attentions,
1697
+ output_hidden_states=output_hidden_states,
1698
+ return_dict=return_dict,
1699
+ )
1700
+
1701
+ hidden_states = outputs[0]
1702
+ logits = self.lm_head(hidden_states)
1703
+ logits = logits.float()
1704
+
1705
+ loss = None
1706
+ if labels is not None:
1707
+ # Shift so that tokens < n predict n
1708
+ shift_logits = logits[..., :-1, :].contiguous()
1709
+ shift_labels = labels[..., 1:].contiguous()
1710
+ # Flatten the tokens
1711
+ loss_fct = CrossEntropyLoss()
1712
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1713
+ shift_labels = shift_labels.view(-1)
1714
+ # Enable model parallelism
1715
+ shift_labels = shift_labels.to(shift_logits.device)
1716
+ loss = loss_fct(shift_logits, shift_labels)
1717
+
1718
+ if not return_dict:
1719
+ output = (logits,) + outputs[1:]
1720
+ return (loss,) + output if loss is not None else output
1721
+
1722
+ return CausalLMOutputWithPast(
1723
+ loss=loss,
1724
+ logits=logits,
1725
+ past_key_values=outputs.past_key_values,
1726
+ hidden_states=outputs.hidden_states,
1727
+ attentions=outputs.attentions,
1728
+ )
1729
+
1730
+ def prepare_inputs_for_generation(
1731
+ self,
1732
+ input_ids,
1733
+ past_key_values=None,
1734
+ attention_mask=None,
1735
+ inputs_embeds=None,
1736
+ **kwargs,
1737
+ ):
1738
+ if past_key_values is not None:
1739
+ if isinstance(past_key_values, Cache):
1740
+ cache_length = past_key_values.get_seq_length()
1741
+ past_length = past_key_values.seen_tokens
1742
+ max_cache_length = past_key_values.get_max_length()
1743
+ else:
1744
+ cache_length = past_length = past_key_values[0][0].shape[2]
1745
+ max_cache_length = None
1746
+
1747
+ # Keep only the unprocessed tokens:
1748
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1749
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1750
+ # input)
1751
+ if (
1752
+ attention_mask is not None
1753
+ and attention_mask.shape[1] > input_ids.shape[1]
1754
+ ):
1755
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1756
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1757
+ # input_ids based on the past_length.
1758
+ elif past_length < input_ids.shape[1]:
1759
+ input_ids = input_ids[:, past_length:]
1760
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1761
+
1762
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1763
+ if (
1764
+ max_cache_length is not None
1765
+ and attention_mask is not None
1766
+ and cache_length + input_ids.shape[1] > max_cache_length
1767
+ ):
1768
+ attention_mask = attention_mask[:, -max_cache_length:]
1769
+
1770
+ position_ids = kwargs.get("position_ids", None)
1771
+ if attention_mask is not None and position_ids is None:
1772
+ # create position_ids on the fly for batch generation
1773
+ position_ids = attention_mask.long().cumsum(-1) - 1
1774
+ position_ids.masked_fill_(attention_mask == 0, 1)
1775
+ if past_key_values:
1776
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1777
+
1778
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1779
+ if inputs_embeds is not None and past_key_values is None:
1780
+ model_inputs = {"inputs_embeds": inputs_embeds}
1781
+ else:
1782
+ model_inputs = {"input_ids": input_ids}
1783
+
1784
+ model_inputs.update(
1785
+ {
1786
+ "position_ids": position_ids,
1787
+ "past_key_values": past_key_values,
1788
+ "use_cache": kwargs.get("use_cache"),
1789
+ "attention_mask": attention_mask,
1790
+ }
1791
+ )
1792
+ return model_inputs
1793
+
1794
+ @staticmethod
1795
+ def _reorder_cache(past_key_values, beam_idx):
1796
+ reordered_past = ()
1797
+ for layer_past in past_key_values:
1798
+ reordered_past += (
1799
+ tuple(
1800
+ past_state.index_select(0, beam_idx.to(past_state.device))
1801
+ for past_state in layer_past
1802
+ ),
1803
+ )
1804
+ return reordered_past
1805
+
1806
+
1807
+ @add_start_docstrings(
1808
+ """
1809
+ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
1810
+
1811
+ [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1812
+ (e.g. GPT-2) do.
1813
+
1814
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1815
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1816
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1817
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1818
+ each row of the batch).
1819
+ """,
1820
+ DeepseekV2_START_DOCSTRING,
1821
+ )
1822
+ class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
1823
+ def __init__(self, config):
1824
+ super().__init__(config)
1825
+ self.num_labels = config.num_labels
1826
+ self.model = DeepseekV2Model(config)
1827
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1828
+
1829
+ # Initialize weights and apply final processing
1830
+ self.post_init()
1831
+
1832
+ def get_input_embeddings(self):
1833
+ return self.model.embed_tokens
1834
+
1835
+ def set_input_embeddings(self, value):
1836
+ self.model.embed_tokens = value
1837
+
1838
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1839
+ def forward(
1840
+ self,
1841
+ input_ids: torch.LongTensor = None,
1842
+ attention_mask: Optional[torch.Tensor] = None,
1843
+ position_ids: Optional[torch.LongTensor] = None,
1844
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1845
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1846
+ labels: Optional[torch.LongTensor] = None,
1847
+ use_cache: Optional[bool] = None,
1848
+ output_attentions: Optional[bool] = None,
1849
+ output_hidden_states: Optional[bool] = None,
1850
+ return_dict: Optional[bool] = None,
1851
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1852
+ r"""
1853
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1854
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1855
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1856
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1857
+ """
1858
+ return_dict = (
1859
+ return_dict if return_dict is not None else self.config.use_return_dict
1860
+ )
1861
+
1862
+ transformer_outputs = self.model(
1863
+ input_ids,
1864
+ attention_mask=attention_mask,
1865
+ position_ids=position_ids,
1866
+ past_key_values=past_key_values,
1867
+ inputs_embeds=inputs_embeds,
1868
+ use_cache=use_cache,
1869
+ output_attentions=output_attentions,
1870
+ output_hidden_states=output_hidden_states,
1871
+ return_dict=return_dict,
1872
+ )
1873
+ hidden_states = transformer_outputs[0]
1874
+ logits = self.score(hidden_states)
1875
+
1876
+ if input_ids is not None:
1877
+ batch_size = input_ids.shape[0]
1878
+ else:
1879
+ batch_size = inputs_embeds.shape[0]
1880
+
1881
+ if self.config.pad_token_id is None and batch_size != 1:
1882
+ raise ValueError(
1883
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1884
+ )
1885
+ if self.config.pad_token_id is None:
1886
+ sequence_lengths = -1
1887
+ else:
1888
+ if input_ids is not None:
1889
+ sequence_lengths = (
1890
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1891
+ ).to(logits.device)
1892
+ else:
1893
+ sequence_lengths = -1
1894
+
1895
+ pooled_logits = logits[
1896
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1897
+ ]
1898
+
1899
+ loss = None
1900
+ if labels is not None:
1901
+ labels = labels.to(logits.device)
1902
+ if self.config.problem_type is None:
1903
+ if self.num_labels == 1:
1904
+ self.config.problem_type = "regression"
1905
+ elif self.num_labels > 1 and (
1906
+ labels.dtype == torch.long or labels.dtype == torch.int
1907
+ ):
1908
+ self.config.problem_type = "single_label_classification"
1909
+ else:
1910
+ self.config.problem_type = "multi_label_classification"
1911
+
1912
+ if self.config.problem_type == "regression":
1913
+ loss_fct = MSELoss()
1914
+ if self.num_labels == 1:
1915
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1916
+ else:
1917
+ loss = loss_fct(pooled_logits, labels)
1918
+ elif self.config.problem_type == "single_label_classification":
1919
+ loss_fct = CrossEntropyLoss()
1920
+ loss = loss_fct(
1921
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1922
+ )
1923
+ elif self.config.problem_type == "multi_label_classification":
1924
+ loss_fct = BCEWithLogitsLoss()
1925
+ loss = loss_fct(pooled_logits, labels)
1926
+ if not return_dict:
1927
+ output = (pooled_logits,) + transformer_outputs[1:]
1928
+ return ((loss,) + output) if loss is not None else output
1929
+
1930
+ return SequenceClassifierOutputWithPast(
1931
+ loss=loss,
1932
+ logits=pooled_logits,
1933
+ past_key_values=transformer_outputs.past_key_values,
1934
+ hidden_states=transformer_outputs.hidden_states,
1935
+ attentions=transformer_outputs.attentions,
1936
+ )
tokenization_deepseek.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Forked from the file src/transformers/models/bert_generation/tokenization_bert_generation.py from the HuggingFace Transformers library.
17
+ Permalink: https://github.com/huggingface/transformers/blob/04ab5605fbb4ef207b10bf2772d88c53fc242e83/src/transformers/models/bert_generation/tokenization_bert_generation.py
18
+ Tokenizer class for ReplitLM
19
+ Class is modified for compatibility with custom vocabulary and to achieve desired encode/decode behavior for Replit Code V1 3B model.
20
+ """
21
+ import os
22
+ import sentencepiece as spm
23
+ from sentencepiece import SentencePieceProcessor
24
+ from shutil import copyfile
25
+ from transformers import PreTrainedTokenizer
26
+ from typing import Any, Dict, List, Optional, Tuple
27
+ import base64
28
+
29
+ VOCAB_FILES_NAMES = {'vocab_file': 'spiece.model'}
30
+
31
+ class Tokenizer:
32
+ def __init__(self, model_path="/weka-jd/prod/deepseek/permanent/shared/mingchuan/llama_data/tokenizer.model"):
33
+ # reload tokenizer
34
+ assert os.path.isfile(model_path), model_path
35
+ self.sp_model = SentencePieceProcessor(model_file=model_path)
36
+
37
+ # # ? print spm for debugging
38
+ # spm_proto = sp_pb2_model.ModelProto()
39
+ # spm_proto.ParseFromString(self.sp_model.serialized_model_proto())
40
+ # print(dir(spm_proto))
41
+ # attrs = ['denormalizer_spec', 'normalizer_spec', 'trainer_spec']
42
+ # print('=======' * 5)
43
+ # for attr in attrs:
44
+ # print('=======', attr, '=======')
45
+ # print(getattr(spm_proto, attr))
46
+
47
+ # BOS / EOS token IDs
48
+ self.n_words: int = self.sp_model.vocab_size()
49
+ self.bos_id: int = self.sp_model.bos_id()
50
+ self.eos_id: int = self.sp_model.eos_id()
51
+ self.pad_id: int = self.sp_model.pad_id()
52
+ assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
53
+
54
+ def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
55
+ assert type(s) is str
56
+ t = self.sp_model.encode(s)
57
+ if bos:
58
+ t = [self.bos_id] + t
59
+ if eos:
60
+ t = t + [self.eos_id]
61
+ return t
62
+
63
+ def decode(self, t: List[int]) -> str:
64
+ return self.sp_model.decode(t)
65
+
66
+ class LineBBPETokenizer(Tokenizer):
67
+ def __init__(self,
68
+ model_path="/3fs-jd/prod/deepseek/shared/daidamai/data/bbpe/spm_0717_final/100000/bbpe_full_bytes.model",
69
+ ignore_decode_err=False, attachfile_path=None):
70
+ super().__init__(model_path=model_path)
71
+ self.ignore_decode_err = ignore_decode_err
72
+ Bvocab_path = attachfile_path + "/byteVocab.txt"
73
+ #'/3fs-jd/prod/deepseek/shared/daidamai/data/bbpe/byteVocab.txt'
74
+ punct_path = attachfile_path + "/all_punct.txt"
75
+ #punct_path = '/3fs-jd/prod/deepseek/shared/daidamai/data/bbpe/all_punct.txt'
76
+ Bvocab = open(Bvocab_path, 'r', encoding = 'utf-8')
77
+ self.punct = []
78
+ with open(punct_path, 'r', encoding='utf-8') as f:
79
+ lines = f.readlines()
80
+ for line in lines:
81
+ line = line.strip()
82
+ if line:
83
+ self.punct.append(line)
84
+
85
+ self.numchars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
86
+ self.white_space = [' ']
87
+ self.special_chars = set(self.numchars) | set(self.punct) | set(self.white_space)
88
+
89
+ # ! remove chars that will be encoded to 0 (unk_id)
90
+ unk_ch = set()
91
+ for ch in self.special_chars:
92
+ ids = self.sp_model.encode(ch)
93
+ if 0 in ids:
94
+ unk_ch.update(ch)
95
+ self.special_chars = self.special_chars - unk_ch
96
+
97
+ self.byte2ch = [-1] * 256
98
+ self.ch2byte = {}
99
+ for line in list(Bvocab.readlines())[:256]:
100
+ tokens = line.strip().split('\t')
101
+ self.byte2ch[int(tokens[0])] = tokens[1]
102
+ self.ch2byte[tokens[1]] = int(tokens[0])
103
+ self.b16_dec = {}
104
+ self.b16_enc = ['x'] * 16
105
+ for i in range(10):
106
+ self.b16_dec[str(i)] = i
107
+ self.b16_enc[i] = str(i)
108
+ self.b16_dec['A'] = 10
109
+ self.b16_dec['B'] = 11
110
+ self.b16_dec['C'] = 12
111
+ self.b16_dec['D'] = 13
112
+ self.b16_dec['E'] = 14
113
+ self.b16_dec['F'] = 15
114
+ self.b16_enc[10] = 'A'
115
+ self.b16_enc[11] = 'B'
116
+ self.b16_enc[12] = 'C'
117
+ self.b16_enc[13] = 'D'
118
+ self.b16_enc[14] = 'E'
119
+ self.b16_enc[15] = 'F'
120
+
121
+ self.new_line_id = self.sp_model.encode(self.mapping_raw_to_256ch('\n'))[-1]
122
+
123
+ def base16encode(self, n):
124
+ return self.b16_enc[n // 16] + self.b16_enc[n % 16]
125
+
126
+ def base16decode(self, s):
127
+ return self.b16_dec[s[0]] * 16 + self.b16_dec[s[1]]
128
+
129
+ def mapping_raw_to_256ch(self, s: str) -> str:
130
+ mapped_s = []
131
+ for token in s:
132
+ if token in self.special_chars:
133
+ mapped_s.append(token)
134
+ continue
135
+ tk = str(base64.b16encode(token.encode("utf-8")))[2:-1]
136
+ num = len(tk) // 2
137
+ for i in range(num):
138
+ mapped_s.append(self.byte2ch[(self.base16decode(tk[2*i:2*i+2]))])
139
+ return ''.join(mapped_s)
140
+
141
+ def mapping_256ch_to_raw(self, s: str) -> str:
142
+ mapped_s = ''
143
+ for token in s:
144
+ if token in self.ch2byte:
145
+ mapped_s += self.base16encode(self.ch2byte[token])
146
+ else:
147
+ mapped_s += str(base64.b16encode(token.encode("utf-8")))[2:-1]
148
+ # decode utf-8 string to text string
149
+ byte_s = bytes.fromhex(mapped_s)
150
+ if self.ignore_decode_err:
151
+ try:
152
+ mapped_s = byte_s.decode('utf-8')
153
+ except UnicodeDecodeError:
154
+ mapped_s = ''
155
+ else:
156
+ mapped_s = byte_s.decode('utf-8')
157
+ return mapped_s
158
+
159
+ def encode_line(self, s):
160
+ if s == '\n':
161
+ return [self.new_line_id]
162
+ ss = self.mapping_raw_to_256ch(s)
163
+ t = self.sp_model.encode(ss)
164
+ return t
165
+
166
+ def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
167
+ assert type(s) is str
168
+ t = []
169
+ lines = s.split('\n')
170
+ n_lines = len(lines)
171
+ for i in range(n_lines):
172
+ if i != n_lines - 1:
173
+ line = lines[i] + '\n'
174
+ else:
175
+ line = lines[i]
176
+ tt = self.encode_line(line)
177
+ t += tt
178
+ if bos:
179
+ t = [self.bos_id] + t
180
+ if eos:
181
+ t = t + [self.eos_id]
182
+ return t
183
+
184
+ def get_restored_white_space(self, t):
185
+ t = t[:3]
186
+ if t[0] == self.bos_id:
187
+ t = t[1:]
188
+ decoded = self.sp_model.decode(t)
189
+ encoded = self.sp_model.encode(decoded)
190
+ if len(encoded) < len(t):
191
+ return ' '
192
+ else:
193
+ return ''
194
+
195
+ def decode_line(self, t):
196
+ if len(t) == 1 and t[0] == self.new_line_id:
197
+ return '\n'
198
+ # ? special bug fixing for a single whitespace in the line beginning, sentencepiece will consume it, we restore it
199
+ restored_white_space = self.get_restored_white_space(t)
200
+ ss = self.sp_model.decode(t)
201
+ s = restored_white_space + self.mapping_256ch_to_raw(ss)
202
+ return s
203
+
204
+ def decode(self, t: List[int]) -> str:
205
+ s = ''
206
+ new_line_indices = [index for index, value in enumerate(t) if value == self.new_line_id]
207
+ last_idx = 0
208
+ for i in range(len(new_line_indices)):
209
+ line_id = t[last_idx:new_line_indices[i] + 1]
210
+ ss = self.decode_line(line_id)
211
+ s += ss
212
+ last_idx = new_line_indices[i] + 1
213
+ if last_idx < len(t):
214
+ line_id = t[last_idx:]
215
+ ss = self.decode_line(line_id)
216
+ s += ss
217
+ return s
218
+
219
+ def add_special(self, special_tokens):
220
+ '''
221
+ add special tokens to the tokenizer
222
+ '''
223
+ spm_proto = sp_pb2_model.ModelProto()
224
+ spm_proto.ParseFromString(self.sp_model.serialized_model_proto())
225
+ for special_token in special_tokens:
226
+ new_p = sp_pb2_model.ModelProto().SentencePiece()
227
+ new_p.piece = self.mapping_raw_to_256ch(special_token)
228
+ new_p.score = 0.0
229
+ new_p.type = 4
230
+ spm_proto.pieces.append(new_p)
231
+ print(f'special token added: {special_token}')
232
+ self.sp_model.LoadFromSerializedProto(spm_proto.SerializeToString())
233
+
234
+ class DeepSeekTokenizer(PreTrainedTokenizer):
235
+ """
236
+ Construct a ReplitLMTokenizer tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
237
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods.
238
+ Args:
239
+ vocab_file (`str`):
240
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
241
+ contains the vocabulary necessary to instantiate a tokenizer.
242
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
243
+ The end of sequence token.
244
+ bos_token (`str`, *optional*, defaults to `None`):
245
+ The begin of sequence token.
246
+ unk_token (`str`, *optional*, defaults to `"<|unk|>"`):
247
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
248
+ token instead.
249
+ pad_token (`str`, *optional*, defaults to `"<|pad|>"`):
250
+ The token used for padding, for example when batching sequences of different lengths.
251
+ sp_model_kwargs (`dict`, *optional*):
252
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
253
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
254
+ to set:
255
+ - `enable_sampling`: Enable subword regularization.
256
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
257
+ - `nbest_size = {0,1}`: No sampling is performed.
258
+ - `nbest_size > 1`: samples from the nbest_size results.
259
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
260
+ using forward-filtering-and-backward-sampling algorithm.
261
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
262
+ BPE-dropout.
263
+ """
264
+ vocab_files_names = VOCAB_FILES_NAMES
265
+ prefix_tokens: List[int] = []
266
+ model_input_names = ['input_ids', 'attention_mask']
267
+
268
+ def __init__(self, vocab_file, bos_token="<s>", eos_token='</s>', unk_token=None, pad_token=None, sep_token='</s>', sp_model_kwargs: Optional[Dict[str, Any]]=None, name_or_path=None, **kwargs) -> None:
269
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
270
+ super().__init__(bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, pad_token=pad_token, sep_token=sep_token, sp_model_kwargs=self.sp_model_kwargs, **kwargs)
271
+ #obtain the current directory of py
272
+ vocab_path = name_or_path
273
+ print("vocab_path: ", vocab_path)
274
+ self.vocab_path = vocab_path
275
+ self.vocab_file = vocab_path + '/tokenizer.model'
276
+ self.token = LineBBPETokenizer(model_path=self.vocab_file, attachfile_path=vocab_path, ignore_decode_err=True)
277
+
278
+ @property
279
+ def vocab_size(self):
280
+ return self.token.sp_model.get_piece_size()
281
+
282
+ def get_vocab(self):
283
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
284
+ vocab.update(self.added_tokens_encoder)
285
+ return vocab
286
+
287
+ def __getstate__(self):
288
+ state = self.__dict__.copy()
289
+ state['token'] = None
290
+ return state
291
+
292
+ def __setstate__(self, d):
293
+ self.__dict__ = d
294
+ if not hasattr(self, 'sp_model_kwargs'):
295
+ self.sp_model_kwargs = {}
296
+ self.token = LineBBPETokenizer(model_path=self.vocab_file, attachfile_path=self.vocab_path)
297
+
298
+ def _tokenize(self, text: str) -> List[str]:
299
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
300
+ token_ids = self.token.encode(text, bos=True, eos=False)
301
+ string_tokens = [self._convert_id_to_token(token_id) for token_id in token_ids]
302
+ return string_tokens
303
+
304
+ def _convert_token_to_id(self, token):
305
+ """Converts a token (str) in an id using the vocab."""
306
+ return self.token.sp_model.piece_to_id(token)
307
+
308
+ def _convert_id_to_token(self, index):
309
+ """Converts an index (integer) in a token (str) using the vocab."""
310
+ token = self.token.sp_model.id_to_piece(index)
311
+ return token
312
+
313
+ def convert_tokens_to_string(self, tokens):
314
+ """Converts a sequence of tokens (string) in a single string."""
315
+ ids = [self._convert_token_to_id(token) for token in tokens]
316
+ return self.token.decode(ids)
317
+
318
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str]=None) -> Tuple[str]:
319
+ if not os.path.isdir(save_directory):
320
+ raise ValueError(f'Vocabulary path ({save_directory}) should be a directory')
321
+ out_vocab_file = os.path.join(save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])
322
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
323
+ copyfile(self.vocab_file, out_vocab_file)
324
+ elif not os.path.isfile(self.vocab_file):
325
+ with open(out_vocab_file, 'wb') as fi:
326
+ content_spiece_model = self.sp_model.serialized_model_proto()
327
+ fi.write(content_spiece_model)
328
+ return (out_vocab_file,)
tokenization_deepseek_fast.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Union
2
+
3
+
4
+ from transformers.models.llama import LlamaTokenizerFast
5
+
6
+
7
+ class DeepseekTokenizerFast(LlamaTokenizerFast):
8
+
9
+ def convert_ids_to_tokens(
10
+ self, ids: Union[int, List[int]], skip_special_tokens: bool = False
11
+ ) -> Union[str, List[str]]:
12
+ """
13
+ Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
14
+ added tokens.
15
+
16
+ Args:
17
+ ids (`int` or `List[int]`):
18
+ The token id (or token ids) to convert to tokens.
19
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
20
+ Whether or not to remove special tokens in the decoding.
21
+
22
+ Returns:
23
+ `str` or `List[str]`: The decoded token(s).
24
+ """
25
+ if isinstance(ids, int):
26
+ return self._convert_id_to_token(ids)
27
+ tokens = []
28
+ for index in ids:
29
+ index = int(index)
30
+ if skip_special_tokens and index in self.all_special_ids:
31
+ continue
32
+ token = self._tokenizer.id_to_token(index)
33
+ tokens.append(token if token is not None else "")
34
+ return tokens
35
+
36
+ def _convert_id_to_token(self, index: int) -> Optional[str]:
37
+ token = self._tokenizer.id_to_token(int(index))
38
+ return token if token is not None else ""
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|begin▁of▁sentence|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 16384,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<|end▁of▁sentence|>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "unk_token": null,
33
+ "tokenizer_class": "LlamaTokenizerFast",
34
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{{ bos_token }}{% for message in messages %}{% if message['role'] == 'user' %}{{ 'User: ' + message['content'] + '\n\n' }}{% elif message['role'] == 'assistant' %}{{ 'Assistant: ' + message['content'] + eos_token }}{% elif message['role'] == 'system' %}{{ message['content'] + '\n\n' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}"
35
+ }