Upload folder using huggingface_hub
Browse files- README.md +161 -0
- __init__.py +31 -0
- config.json +41 -0
- configuration_deepseek.py +188 -0
- model.safetensors +3 -0
- modeling_deepseek.py +592 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +6 -0
- tokenizer.model +3 -0
- tokenizer_config.json +15 -0
README.md
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language: tr
|
3 |
+
license: apache-2.0
|
4 |
+
library_name: transformers
|
5 |
+
tags:
|
6 |
+
- text-generation
|
7 |
+
- turkish
|
8 |
+
- deepseek
|
9 |
+
- moe
|
10 |
+
- mla
|
11 |
+
- pytorch
|
12 |
+
- causal-lm
|
13 |
+
datasets:
|
14 |
+
- tr_wikipedia
|
15 |
+
widget:
|
16 |
+
- text: "Merhaba dünya"
|
17 |
+
example_title: "Turkish Greeting"
|
18 |
+
- text: "Türkiye'nin başkenti"
|
19 |
+
example_title: "Turkish Geography"
|
20 |
+
- text: "Yapay zeka"
|
21 |
+
example_title: "Turkish Technology"
|
22 |
+
---
|
23 |
+
|
24 |
+
# Turkish DeepSeek Model
|
25 |
+
|
26 |
+
Bu model, DeepSeek mimarisi kullanılarak Türkçe metinler üzerinde eğitilmiş bir dil modelidir. Multi-head Latent Attention (MLA) ve Mixture of Experts (MoE) teknolojilerini içerir.
|
27 |
+
|
28 |
+
## Model Özellikleri
|
29 |
+
|
30 |
+
- **Parametre Sayısı**: ~192M
|
31 |
+
- **Kelime Hazinesi**: 50,256 token
|
32 |
+
- **Bağlam Uzunluğu**: 256 token
|
33 |
+
- **Dil**: Türkçe (tr)
|
34 |
+
- **Mimarisi**: DeepSeek with MLA + MoE
|
35 |
+
|
36 |
+
## Teknik Detaylar
|
37 |
+
|
38 |
+
- **Gizli Boyut**: 1024
|
39 |
+
- **Katman Sayısı**: 6 (1 yoğun + 5 MoE)
|
40 |
+
- **Attention Head**: 8
|
41 |
+
- **MoE Uzmanları**: 4 yönlendirilmiş + 2 paylaşımlı
|
42 |
+
- **Aktif Uzman**: 2 per token
|
43 |
+
|
44 |
+
## Kullanım
|
45 |
+
|
46 |
+
### Temel Kullanım
|
47 |
+
|
48 |
+
```python
|
49 |
+
import torch
|
50 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
51 |
+
|
52 |
+
# Model ve tokenizer'ı yükle
|
53 |
+
model = AutoModelForCausalLM.from_pretrained("your-username/turkish-deepseek", trust_remote_code=True)
|
54 |
+
tokenizer = AutoTokenizer.from_pretrained("your-username/turkish-deepseek")
|
55 |
+
|
56 |
+
# Metin üretimi
|
57 |
+
prompt = "Merhaba dünya"
|
58 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
59 |
+
with torch.no_grad():
|
60 |
+
outputs = model.generate(
|
61 |
+
**inputs,
|
62 |
+
max_length=50,
|
63 |
+
temperature=0.7,
|
64 |
+
do_sample=True,
|
65 |
+
pad_token_id=tokenizer.pad_token_id
|
66 |
+
)
|
67 |
+
|
68 |
+
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
69 |
+
print(generated_text)
|
70 |
+
```
|
71 |
+
|
72 |
+
### Orijinal Implementation ile Kullanım
|
73 |
+
|
74 |
+
```python
|
75 |
+
# Orijinal implementasyonu kullanmak için
|
76 |
+
import torch
|
77 |
+
import sentencepiece as spm
|
78 |
+
|
79 |
+
# Tokenizer'ı yükle
|
80 |
+
tokenizer = spm.SentencePieceProcessor()
|
81 |
+
tokenizer.load("tokenizer.model")
|
82 |
+
|
83 |
+
# Model checkpoint'ini yükle
|
84 |
+
checkpoint = torch.load("pytorch_model.bin", map_location="cpu")
|
85 |
+
|
86 |
+
# Orijinal model sınıfınızı kullanarak yükleyin
|
87 |
+
# from your_original_implementation import Transformer, ModelArgs
|
88 |
+
# model = Transformer(args)
|
89 |
+
# model.load_state_dict(checkpoint)
|
90 |
+
```
|
91 |
+
|
92 |
+
## Eğitim Verisi
|
93 |
+
|
94 |
+
- **Kaynak**: Türkçe Wikipedia
|
95 |
+
- **Tokenization**: SentencePiece BPE
|
96 |
+
- **Kelime Hazinesi**: Türkçe diline optimize edilmiş
|
97 |
+
|
98 |
+
## Model Mimarisi
|
99 |
+
|
100 |
+
### Multi-head Latent Attention (MLA)
|
101 |
+
- Sıkıştırılmış key-value temsilleri (rank 256)
|
102 |
+
- Ayrı no-position ve position encoding bileşenleri
|
103 |
+
- Uzun diziler için verimli bellek kullanımı
|
104 |
+
|
105 |
+
### Mixture of Experts (MoE)
|
106 |
+
- Top-2 yönlendirme ve yük dengeleme
|
107 |
+
- Ortak desenler için paylaşımlı uzmanlar
|
108 |
+
- Seyrek aktivasyon ile azaltılmış hesaplama
|
109 |
+
|
110 |
+
### RoPE with YaRN Scaling
|
111 |
+
- Frekans ölçekleme ile rotational position embedding
|
112 |
+
- Eğitim uzunluğunun ötesinde genişletilmiş bağlam desteği
|
113 |
+
- Temel frekans: 10000.0
|
114 |
+
|
115 |
+
## Performans
|
116 |
+
|
117 |
+
- **Çıkarım**: Türkçe metin üretimi için optimize edilmiş
|
118 |
+
- **Bellek**: MLA, KV cache boyutunu azaltır
|
119 |
+
- **Hız**: MoE, kontrollü hesaplama ile daha büyük kapasiteye olanak tanır
|
120 |
+
|
121 |
+
## Sınırlamalar
|
122 |
+
|
123 |
+
- Ağırlıklı olarak Türkçe Wikipedia üzerinde eğitilmiş (sınırlı alan kapsamı)
|
124 |
+
- Bağlam uzunluğu 256 token ile sınırlı
|
125 |
+
- Eğitim verisinde mevcut önyargılar sergileyebilir
|
126 |
+
|
127 |
+
## Alıntı
|
128 |
+
|
129 |
+
Bu modeli kullanırsanız, lütfen alıntı yapın:
|
130 |
+
|
131 |
+
```bibtex
|
132 |
+
@misc{turkish-deepseek,
|
133 |
+
title={Turkish DeepSeek Language Model},
|
134 |
+
author={Your Name},
|
135 |
+
year={2024},
|
136 |
+
url={https://huggingface.co/your-username/turkish-deepseek}
|
137 |
+
}
|
138 |
+
```
|
139 |
+
|
140 |
+
## Lisans
|
141 |
+
|
142 |
+
Apache 2.0 License
|
143 |
+
|
144 |
+
## Model Card Authors
|
145 |
+
|
146 |
+
[Your Name]
|
147 |
+
|
148 |
+
---
|
149 |
+
|
150 |
+
## English Summary
|
151 |
+
|
152 |
+
This is a Turkish language model based on the DeepSeek architecture, featuring Multi-head Latent Attention (MLA) and Mixture of Experts (MoE). The model has ~192M parameters and was trained on Turkish Wikipedia data.
|
153 |
+
|
154 |
+
### Key Features
|
155 |
+
- **Architecture**: DeepSeek with advanced MLA and MoE components
|
156 |
+
- **Language**: Turkish (tr)
|
157 |
+
- **Training**: Turkish Wikipedia corpus
|
158 |
+
- **Vocabulary**: 50,256 tokens optimized for Turkish
|
159 |
+
|
160 |
+
### Usage
|
161 |
+
Load with `trust_remote_code=True` to use the custom implementation, or use the provided model files directly.
|
__init__.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# flake8: noqa
|
2 |
+
# There's no way to ignore "F401 '...' imported but unused" warnings in this
|
3 |
+
# module, but to preserve other warnings. So, don't check this module at all.
|
4 |
+
|
5 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
6 |
+
#
|
7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
8 |
+
# you may not use this file except in compliance with the License.
|
9 |
+
# You may obtain a copy of the License at
|
10 |
+
#
|
11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
12 |
+
#
|
13 |
+
# Unless required by applicable law or agreed to in writing, software
|
14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
16 |
+
# See the License for the specific language governing permissions and
|
17 |
+
# limitations under the License.
|
18 |
+
|
19 |
+
# Simple standalone imports for DeepSeek model
|
20 |
+
from configuration_deepseek import (DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
21 |
+
DeepSeekConfig)
|
22 |
+
from modeling_deepseek import (DeepSeekForCausalLM, DeepSeekModel,
|
23 |
+
DeepSeekPreTrainedModel)
|
24 |
+
|
25 |
+
__all__ = [
|
26 |
+
"DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
27 |
+
"DeepSeekConfig",
|
28 |
+
"DeepSeekForCausalLM",
|
29 |
+
"DeepSeekModel",
|
30 |
+
"DeepSeekPreTrainedModel",
|
31 |
+
]
|
config.json
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TurkishDeepSeek"
|
4 |
+
],
|
5 |
+
"model_type": "turkish_deepseek",
|
6 |
+
"vocab_size": 50256,
|
7 |
+
"hidden_size": 1024,
|
8 |
+
"num_hidden_layers": 6,
|
9 |
+
"num_dense_layers": 1,
|
10 |
+
"num_attention_heads": 8,
|
11 |
+
"intermediate_size": 4096,
|
12 |
+
"moe_intermediate_size": 704,
|
13 |
+
"num_routed_experts": 4,
|
14 |
+
"num_shared_experts": 2,
|
15 |
+
"num_activated_experts": 2,
|
16 |
+
"max_position_embeddings": 256,
|
17 |
+
"q_lora_rank": 0,
|
18 |
+
"kv_lora_rank": 256,
|
19 |
+
"qk_nope_head_dim": 64,
|
20 |
+
"qk_rope_head_dim": 32,
|
21 |
+
"v_head_dim": 64,
|
22 |
+
"original_seq_len": 512,
|
23 |
+
"rope_theta": 10000.0,
|
24 |
+
"rope_factor": 40,
|
25 |
+
"beta_fast": 32,
|
26 |
+
"beta_slow": 1,
|
27 |
+
"mscale": 1.0,
|
28 |
+
"rms_norm_eps": 0.001,
|
29 |
+
"initializer_range": 0.02,
|
30 |
+
"use_cache": true,
|
31 |
+
"pad_token_id": 0,
|
32 |
+
"bos_token_id": 2,
|
33 |
+
"eos_token_id": 3,
|
34 |
+
"tie_word_embeddings": false,
|
35 |
+
"torch_dtype": "float32",
|
36 |
+
"auto_map": {
|
37 |
+
"AutoConfig": "configuration_deepseek.TurkishDeepSeekConfig",
|
38 |
+
"AutoModel": "modeling_deepseek.TurkishDeepSeekModel",
|
39 |
+
"AutoModelForCausalLM": "modeling_deepseek.TurkishDeepSeekForCausalLM"
|
40 |
+
}
|
41 |
+
}
|
configuration_deepseek.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
DeepSeek model configuration
|
3 |
+
"""
|
4 |
+
|
5 |
+
from transformers.configuration_utils import PretrainedConfig
|
6 |
+
from transformers.utils import logging
|
7 |
+
|
8 |
+
logger = logging.get_logger(__name__)
|
9 |
+
|
10 |
+
DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
11 |
+
|
12 |
+
|
13 |
+
class DeepSeekConfig(PretrainedConfig):
|
14 |
+
r"""
|
15 |
+
This is the configuration class to store the configuration of a [`DeepSeekModel`]. It is used to instantiate a
|
16 |
+
DeepSeek model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
17 |
+
with the defaults will yield a similar configuration to that of the DeepSeek-V3
|
18 |
+
[deepseek-ai/DeepSeek-V3](https://huggingface.co/deepseek-ai/DeepSeek-V3) architecture.
|
19 |
+
|
20 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
21 |
+
documentation from [`PretrainedConfig`] for more information.
|
22 |
+
|
23 |
+
|
24 |
+
Args:
|
25 |
+
vocab_size (`int`, *optional*, defaults to 50256):
|
26 |
+
Vocabulary size of the DeepSeek model. Defines the number of different tokens that can be represented by the
|
27 |
+
`inputs_ids` passed when calling [`DeepSeekModel`]
|
28 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
29 |
+
Dimension of the hidden representations.
|
30 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
31 |
+
Dimension of the MLP representations for dense layers.
|
32 |
+
moe_intermediate_size (`int`, *optional*, defaults to 704):
|
33 |
+
Dimension of the MLP representations for MoE layers.
|
34 |
+
num_hidden_layers (`int`, *optional*, defaults to 6):
|
35 |
+
Number of hidden layers in the Transformer decoder.
|
36 |
+
num_dense_layers (`int`, *optional*, defaults to 1):
|
37 |
+
Number of dense (non-MoE) layers in the model.
|
38 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
39 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
40 |
+
num_routed_experts (`int`, *optional*, defaults to 4):
|
41 |
+
Number of routed experts in MoE layers.
|
42 |
+
num_shared_experts (`int`, *optional*, defaults to 2):
|
43 |
+
Number of shared experts in MoE layers.
|
44 |
+
num_activated_experts (`int`, *optional*, defaults to 2):
|
45 |
+
Number of experts activated per token in MoE layers.
|
46 |
+
num_expert_groups (`int`, *optional*, defaults to 1):
|
47 |
+
Number of expert groups in MoE layers.
|
48 |
+
num_limited_groups (`int`, *optional*, defaults to 1):
|
49 |
+
Number of limited groups in MoE layers.
|
50 |
+
score_func (`str`, *optional*, defaults to `"softmax"`):
|
51 |
+
Scoring function for expert selection. Can be "softmax" or "sigmoid".
|
52 |
+
route_scale (`float`, *optional*, defaults to 1.0):
|
53 |
+
Scaling factor for routing weights.
|
54 |
+
q_lora_rank (`int`, *optional*, defaults to 0):
|
55 |
+
Rank of LoRA adaptation for query projection. 0 means no LoRA.
|
56 |
+
kv_lora_rank (`int`, *optional*, defaults to 256):
|
57 |
+
Rank of LoRA adaptation for key-value projection.
|
58 |
+
qk_nope_head_dim (`int`, *optional*, defaults to 64):
|
59 |
+
Dimension of query-key heads without positional encoding.
|
60 |
+
qk_rope_head_dim (`int`, *optional*, defaults to 32):
|
61 |
+
Dimension of query-key heads with rotary positional encoding.
|
62 |
+
v_head_dim (`int`, *optional*, defaults to 64):
|
63 |
+
Dimension of value heads.
|
64 |
+
original_seq_len (`int`, *optional*, defaults to 512):
|
65 |
+
Original sequence length used during pretraining.
|
66 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
67 |
+
Base frequency for rotary positional encoding.
|
68 |
+
rope_factor (`float`, *optional*, defaults to 40):
|
69 |
+
Scaling factor for RoPE frequency adjustment.
|
70 |
+
beta_fast (`int`, *optional*, defaults to 32):
|
71 |
+
Fast beta parameter for YaRN RoPE scaling.
|
72 |
+
beta_slow (`int`, *optional*, defaults to 1):
|
73 |
+
Slow beta parameter for YaRN RoPE scaling.
|
74 |
+
mscale (`float`, *optional*, defaults to 1.0):
|
75 |
+
Scale factor for attention logits when using extended context.
|
76 |
+
max_position_embeddings (`int`, *optional*, defaults to 256):
|
77 |
+
The maximum sequence length that this model might ever be used with.
|
78 |
+
max_batch_size (`int`, *optional*, defaults to 2):
|
79 |
+
The maximum batch size that this model might ever be used with for caching.
|
80 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
81 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
82 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-3):
|
83 |
+
The epsilon used by the rms normalization layers.
|
84 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
85 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
86 |
+
relevant if `config.is_decoder=True`.
|
87 |
+
pad_token_id (`int`, *optional*):
|
88 |
+
The id of the padding token.
|
89 |
+
bos_token_id (`int`, *optional*, defaults to 2):
|
90 |
+
The id of the "beginning-of-sequence" token.
|
91 |
+
eos_token_id (`int`, *optional*, defaults to 3):
|
92 |
+
The id of the "end-of-sequence" token.
|
93 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
94 |
+
Whether to tie weight embeddings
|
95 |
+
|
96 |
+
```python
|
97 |
+
>>> from transformers import DeepSeekModel, DeepSeekConfig
|
98 |
+
|
99 |
+
>>> # Initializing a DeepSeek configuration
|
100 |
+
>>> configuration = DeepSeekConfig()
|
101 |
+
|
102 |
+
>>> # Initializing a model from the configuration
|
103 |
+
>>> model = DeepSeekModel(configuration)
|
104 |
+
|
105 |
+
>>> # Accessing the model configuration
|
106 |
+
>>> configuration = model.config
|
107 |
+
```"""
|
108 |
+
|
109 |
+
model_type = "deepseek"
|
110 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
111 |
+
|
112 |
+
def __init__(
|
113 |
+
self,
|
114 |
+
vocab_size=50256,
|
115 |
+
hidden_size=1024,
|
116 |
+
intermediate_size=4096,
|
117 |
+
moe_intermediate_size=704,
|
118 |
+
num_hidden_layers=6,
|
119 |
+
num_dense_layers=1,
|
120 |
+
num_attention_heads=8,
|
121 |
+
num_routed_experts=4,
|
122 |
+
num_shared_experts=2,
|
123 |
+
num_activated_experts=2,
|
124 |
+
num_expert_groups=1,
|
125 |
+
num_limited_groups=1,
|
126 |
+
score_func="softmax",
|
127 |
+
route_scale=1.0,
|
128 |
+
q_lora_rank=0,
|
129 |
+
kv_lora_rank=256,
|
130 |
+
qk_nope_head_dim=64,
|
131 |
+
qk_rope_head_dim=32,
|
132 |
+
v_head_dim=64,
|
133 |
+
original_seq_len=512,
|
134 |
+
rope_theta=10000.0,
|
135 |
+
rope_factor=40,
|
136 |
+
beta_fast=32,
|
137 |
+
beta_slow=1,
|
138 |
+
mscale=1.0,
|
139 |
+
max_position_embeddings=256,
|
140 |
+
max_batch_size=2,
|
141 |
+
initializer_range=0.02,
|
142 |
+
rms_norm_eps=1e-3,
|
143 |
+
use_cache=True,
|
144 |
+
pad_token_id=0,
|
145 |
+
bos_token_id=2,
|
146 |
+
eos_token_id=3,
|
147 |
+
tie_word_embeddings=False,
|
148 |
+
**kwargs,
|
149 |
+
):
|
150 |
+
self.vocab_size = vocab_size
|
151 |
+
self.max_position_embeddings = max_position_embeddings
|
152 |
+
self.hidden_size = hidden_size
|
153 |
+
self.intermediate_size = intermediate_size
|
154 |
+
self.moe_intermediate_size = moe_intermediate_size
|
155 |
+
self.num_hidden_layers = num_hidden_layers
|
156 |
+
self.num_dense_layers = num_dense_layers
|
157 |
+
self.num_attention_heads = num_attention_heads
|
158 |
+
self.num_routed_experts = num_routed_experts
|
159 |
+
self.num_shared_experts = num_shared_experts
|
160 |
+
self.num_activated_experts = num_activated_experts
|
161 |
+
self.num_expert_groups = num_expert_groups
|
162 |
+
self.num_limited_groups = num_limited_groups
|
163 |
+
self.score_func = score_func
|
164 |
+
self.route_scale = route_scale
|
165 |
+
self.q_lora_rank = q_lora_rank
|
166 |
+
self.kv_lora_rank = kv_lora_rank
|
167 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
168 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
169 |
+
self.v_head_dim = v_head_dim
|
170 |
+
self.original_seq_len = original_seq_len
|
171 |
+
self.rope_theta = rope_theta
|
172 |
+
self.rope_factor = rope_factor
|
173 |
+
self.beta_fast = beta_fast
|
174 |
+
self.beta_slow = beta_slow
|
175 |
+
self.mscale = mscale
|
176 |
+
self.max_batch_size = max_batch_size
|
177 |
+
self.initializer_range = initializer_range
|
178 |
+
self.rms_norm_eps = rms_norm_eps
|
179 |
+
self.use_cache = use_cache
|
180 |
+
self.tie_word_embeddings = tie_word_embeddings
|
181 |
+
|
182 |
+
super().__init__(
|
183 |
+
pad_token_id=pad_token_id,
|
184 |
+
bos_token_id=bos_token_id,
|
185 |
+
eos_token_id=eos_token_id,
|
186 |
+
tie_word_embeddings=tie_word_embeddings,
|
187 |
+
**kwargs,
|
188 |
+
)
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e386559416e5b062ed0599f6640355c564c13a59d79d7225b5aacc68c309df8e
|
3 |
+
size 767127048
|
modeling_deepseek.py
ADDED
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
PyTorch DeepSeek model.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import math
|
6 |
+
from typing import List, Optional, Tuple, Union
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
import torch.nn.functional as F
|
11 |
+
from configuration_deepseek import DeepSeekConfig
|
12 |
+
from torch.nn import CrossEntropyLoss
|
13 |
+
from transformers.activations import ACT2FN
|
14 |
+
from transformers.cache_utils import Cache, DynamicCache
|
15 |
+
from transformers.modeling_attn_mask_utils import (
|
16 |
+
AttentionMaskConverter, _prepare_4d_attention_mask,
|
17 |
+
_prepare_4d_causal_attention_mask)
|
18 |
+
from transformers.modeling_outputs import (BaseModelOutputWithPast,
|
19 |
+
CausalLMOutputWithPast)
|
20 |
+
from transformers.modeling_utils import PreTrainedModel
|
21 |
+
from transformers.utils import (add_start_docstrings,
|
22 |
+
add_start_docstrings_to_model_forward,
|
23 |
+
is_flash_attn_2_available,
|
24 |
+
is_flash_attn_greater_or_equal_2_10, logging,
|
25 |
+
replace_return_docstrings)
|
26 |
+
|
27 |
+
if is_flash_attn_2_available():
|
28 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
29 |
+
from flash_attn.bert_padding import (index_first_axis, pad_input, # noqa
|
30 |
+
unpad_input)
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
_CONFIG_FOR_DOC = "DeepSeekConfig"
|
35 |
+
|
36 |
+
|
37 |
+
def precompute_freqs_cis(config: DeepSeekConfig) -> torch.Tensor:
|
38 |
+
"""Precompute the frequency tensor for rotary position embedding."""
|
39 |
+
dim = config.qk_rope_head_dim
|
40 |
+
seqlen = config.max_position_embeddings
|
41 |
+
beta_fast = config.beta_fast
|
42 |
+
beta_slow = config.beta_slow
|
43 |
+
base = config.rope_theta
|
44 |
+
factor = config.rope_factor
|
45 |
+
|
46 |
+
def find_correction_dim(num_rotations, dim, base, max_seq_len):
|
47 |
+
return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base))
|
48 |
+
|
49 |
+
def find_correction_range(low_rot, high_rot, dim, base, max_seq_len):
|
50 |
+
low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len))
|
51 |
+
high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len))
|
52 |
+
return max(low, 0), min(high, dim-1)
|
53 |
+
|
54 |
+
def linear_ramp_factor(min_val, max_val, dim):
|
55 |
+
if min_val == max_val:
|
56 |
+
max_val += 0.001
|
57 |
+
linear_func = (torch.arange(dim, dtype=torch.float32) - min_val) / (max_val - min_val)
|
58 |
+
ramp_func = torch.clamp(linear_func, 0, 1)
|
59 |
+
return ramp_func
|
60 |
+
|
61 |
+
freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
|
62 |
+
|
63 |
+
if seqlen > config.original_seq_len:
|
64 |
+
low, high = find_correction_range(beta_fast, beta_slow, dim, base, config.original_seq_len)
|
65 |
+
smooth = 1 - linear_ramp_factor(low, high, dim // 2)
|
66 |
+
freqs = freqs / factor * (1 - smooth) + freqs * smooth
|
67 |
+
|
68 |
+
t = torch.arange(seqlen)
|
69 |
+
freqs = torch.outer(t, freqs)
|
70 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
71 |
+
return freqs_cis
|
72 |
+
|
73 |
+
|
74 |
+
def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
|
75 |
+
"""Apply rotary position embedding to the input tensor."""
|
76 |
+
assert x.shape[-1] % 2 == 0, "Rotary dim must be divisible by 2!"
|
77 |
+
dtype = x.dtype
|
78 |
+
x = torch.view_as_complex(x.float().view(*x.shape[:-1], -1, 2))
|
79 |
+
freqs_cis = freqs_cis.view(1, x.size(1), 1, x.size(-1))
|
80 |
+
y = torch.view_as_real(x * freqs_cis).reshape(*x.shape[:-1], -1)
|
81 |
+
return y.to(dtype)
|
82 |
+
|
83 |
+
|
84 |
+
class DeepSeekRMSNorm(nn.Module):
|
85 |
+
"""RMS normalization layer."""
|
86 |
+
|
87 |
+
def __init__(self, hidden_size, eps=1e-6):
|
88 |
+
super().__init__()
|
89 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
90 |
+
self.variance_epsilon = eps
|
91 |
+
|
92 |
+
def forward(self, hidden_states):
|
93 |
+
input_dtype = hidden_states.dtype
|
94 |
+
hidden_states = hidden_states.to(torch.float32)
|
95 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
96 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
97 |
+
return self.weight * hidden_states.to(input_dtype)
|
98 |
+
|
99 |
+
|
100 |
+
class DeepSeekMLA(nn.Module):
|
101 |
+
"""Multi-head Latent Attention (MLA) module."""
|
102 |
+
|
103 |
+
def __init__(self, config: DeepSeekConfig, layer_idx: Optional[int] = None):
|
104 |
+
super().__init__()
|
105 |
+
self.config = config
|
106 |
+
self.layer_idx = layer_idx
|
107 |
+
|
108 |
+
self.hidden_size = config.hidden_size
|
109 |
+
self.num_heads = config.num_attention_heads
|
110 |
+
self.head_dim = self.hidden_size // self.num_heads
|
111 |
+
self.num_key_value_heads = config.num_attention_heads
|
112 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
113 |
+
self.max_position_embeddings = config.max_position_embeddings
|
114 |
+
self.rope_theta = config.rope_theta
|
115 |
+
self.is_causal = True
|
116 |
+
|
117 |
+
# MLA specific parameters
|
118 |
+
self.q_lora_rank = config.q_lora_rank
|
119 |
+
self.kv_lora_rank = config.kv_lora_rank
|
120 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
121 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
122 |
+
self.v_head_dim = config.v_head_dim
|
123 |
+
self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
|
124 |
+
|
125 |
+
if self.q_lora_rank == 0:
|
126 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
|
127 |
+
else:
|
128 |
+
self.q_a_proj = nn.Linear(self.hidden_size, self.q_lora_rank, bias=False)
|
129 |
+
self.q_a_layernorm = DeepSeekRMSNorm(self.q_lora_rank, eps=config.rms_norm_eps)
|
130 |
+
self.q_b_proj = nn.Linear(self.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
131 |
+
|
132 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
133 |
+
self.hidden_size,
|
134 |
+
self.kv_lora_rank + self.qk_rope_head_dim,
|
135 |
+
bias=False
|
136 |
+
)
|
137 |
+
self.kv_a_layernorm = DeepSeekRMSNorm(self.kv_lora_rank, eps=config.rms_norm_eps)
|
138 |
+
self.kv_b_proj = nn.Linear(
|
139 |
+
self.kv_lora_rank,
|
140 |
+
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
141 |
+
bias=False
|
142 |
+
)
|
143 |
+
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, self.hidden_size, bias=False)
|
144 |
+
|
145 |
+
# Scaling
|
146 |
+
self.scaling = self.qk_head_dim ** -0.5
|
147 |
+
if config.max_position_embeddings > config.original_seq_len:
|
148 |
+
mscale = 0.1 * config.mscale * math.log(config.rope_factor) + 1.0
|
149 |
+
self.scaling = self.scaling * mscale * mscale
|
150 |
+
|
151 |
+
def forward(
|
152 |
+
self,
|
153 |
+
hidden_states: torch.Tensor,
|
154 |
+
attention_mask: Optional[torch.Tensor] = None,
|
155 |
+
position_ids: Optional[torch.LongTensor] = None,
|
156 |
+
past_key_value: Optional[Cache] = None,
|
157 |
+
output_attentions: bool = False,
|
158 |
+
use_cache: bool = False,
|
159 |
+
cache_position: Optional[torch.LongTensor] = None,
|
160 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
161 |
+
|
162 |
+
bsz, q_len, _ = hidden_states.size()
|
163 |
+
|
164 |
+
# Query projection
|
165 |
+
if self.q_lora_rank == 0:
|
166 |
+
query_states = self.q_proj(hidden_states)
|
167 |
+
else:
|
168 |
+
query_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
169 |
+
|
170 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.qk_head_dim).transpose(1, 2)
|
171 |
+
|
172 |
+
# Split query into no-position-encoding and position-encoding parts
|
173 |
+
q_nope, q_pe = query_states.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
174 |
+
|
175 |
+
# Key-Value projection
|
176 |
+
kv_input = self.kv_a_proj_with_mqa(hidden_states)
|
177 |
+
compressed_kv, k_pe = kv_input.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
178 |
+
|
179 |
+
# Apply RoPE to position-encoding parts
|
180 |
+
if position_ids is not None:
|
181 |
+
cos, sin = self.rotary_emb(hidden_states, position_ids)
|
182 |
+
q_pe = apply_rotary_pos_emb(q_pe, cos, sin)
|
183 |
+
k_pe = apply_rotary_pos_emb(k_pe.unsqueeze(2), cos, sin).squeeze(2)
|
184 |
+
|
185 |
+
# Compute key and value from compressed representation
|
186 |
+
kv_b_weight = self.kv_b_proj.weight.view(
|
187 |
+
self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank
|
188 |
+
)
|
189 |
+
|
190 |
+
# Project compressed KV to get keys and values
|
191 |
+
compressed_kv = self.kv_a_layernorm(compressed_kv)
|
192 |
+
key_states = torch.einsum('bld,hnd->bhln', compressed_kv, kv_b_weight[:, :self.qk_nope_head_dim, :])
|
193 |
+
value_states = torch.einsum('bld,hnd->bhln', compressed_kv, kv_b_weight[:, -self.v_head_dim:, :])
|
194 |
+
|
195 |
+
# Attention computation
|
196 |
+
attn_weights = torch.matmul(q_nope, key_states.transpose(-2, -1)) * self.scaling
|
197 |
+
|
198 |
+
# Add positional attention
|
199 |
+
if k_pe is not None:
|
200 |
+
pos_attn = torch.matmul(q_pe, k_pe.unsqueeze(1).transpose(-2, -1)) * self.scaling
|
201 |
+
attn_weights = attn_weights + pos_attn
|
202 |
+
|
203 |
+
if attention_mask is not None:
|
204 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
205 |
+
attn_weights = attn_weights + causal_mask
|
206 |
+
|
207 |
+
# Apply softmax
|
208 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
209 |
+
|
210 |
+
# Apply attention to values
|
211 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
212 |
+
|
213 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
214 |
+
attn_output = attn_output.reshape(bsz, q_len, -1)
|
215 |
+
attn_output = self.o_proj(attn_output)
|
216 |
+
|
217 |
+
if not output_attentions:
|
218 |
+
attn_weights = None
|
219 |
+
|
220 |
+
return attn_output, attn_weights, past_key_value
|
221 |
+
|
222 |
+
|
223 |
+
class DeepSeekMLP(nn.Module):
|
224 |
+
"""Multi-Layer Perceptron for dense layers."""
|
225 |
+
|
226 |
+
def __init__(self, config: DeepSeekConfig):
|
227 |
+
super().__init__()
|
228 |
+
self.config = config
|
229 |
+
self.hidden_size = config.hidden_size
|
230 |
+
self.intermediate_size = config.intermediate_size
|
231 |
+
|
232 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
233 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
234 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
235 |
+
self.act_fn = ACT2FN["silu"]
|
236 |
+
|
237 |
+
def forward(self, x):
|
238 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
239 |
+
|
240 |
+
|
241 |
+
class DeepSeekExpert(nn.Module):
|
242 |
+
"""Single expert in MoE layer."""
|
243 |
+
|
244 |
+
def __init__(self, config: DeepSeekConfig):
|
245 |
+
super().__init__()
|
246 |
+
self.hidden_size = config.hidden_size
|
247 |
+
self.intermediate_size = config.moe_intermediate_size
|
248 |
+
|
249 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
250 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
251 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
252 |
+
self.act_fn = ACT2FN["silu"]
|
253 |
+
|
254 |
+
def forward(self, x):
|
255 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
256 |
+
|
257 |
+
|
258 |
+
DEEPSEEK_START_DOCSTRING = r"""
|
259 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
260 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
261 |
+
etc.)
|
262 |
+
|
263 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
264 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
265 |
+
and behavior.
|
266 |
+
|
267 |
+
Parameters:
|
268 |
+
config ([`DeepSeekConfig`]):
|
269 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
270 |
+
load the weights associated with the model, only the configuration. Check out the
|
271 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
272 |
+
"""
|
273 |
+
|
274 |
+
|
275 |
+
@add_start_docstrings(
|
276 |
+
"The bare DeepSeek Model outputting raw hidden-states without any specific head on top.",
|
277 |
+
DEEPSEEK_START_DOCSTRING,
|
278 |
+
)
|
279 |
+
class DeepSeekPreTrainedModel(PreTrainedModel):
|
280 |
+
config_class = DeepSeekConfig
|
281 |
+
base_model_prefix = "model"
|
282 |
+
supports_gradient_checkpointing = True
|
283 |
+
_no_split_modules = ["DeepSeekDecoderLayer"]
|
284 |
+
_skip_keys_device_placement = ["past_key_values"]
|
285 |
+
_supports_flash_attn_2 = True
|
286 |
+
_supports_sdpa = True
|
287 |
+
_supports_cache_class = True
|
288 |
+
|
289 |
+
def _init_weights(self, module):
|
290 |
+
std = self.config.initializer_range
|
291 |
+
if isinstance(module, nn.Linear):
|
292 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
293 |
+
if module.bias is not None:
|
294 |
+
module.bias.data.zero_()
|
295 |
+
elif isinstance(module, nn.Embedding):
|
296 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
297 |
+
if module.padding_idx is not None:
|
298 |
+
module.weight.data[module.padding_idx].zero_()
|
299 |
+
|
300 |
+
|
301 |
+
DEEPSEEK_INPUTS_DOCSTRING = r"""
|
302 |
+
Args:
|
303 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
304 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
305 |
+
it.
|
306 |
+
|
307 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
308 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
309 |
+
|
310 |
+
[What are input IDs?](../glossary#input-ids)
|
311 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
312 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
313 |
+
|
314 |
+
- 1 for tokens that are **not masked**,
|
315 |
+
- 0 for tokens that are **masked**.
|
316 |
+
|
317 |
+
[What are attention masks?](../glossary#attention-mask)
|
318 |
+
|
319 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
320 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
321 |
+
|
322 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
323 |
+
`past_key_values`).
|
324 |
+
|
325 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
326 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
327 |
+
information on the default strategy.
|
328 |
+
|
329 |
+
- 1 indicates the head is **not masked**,
|
330 |
+
- 0 indicates the head is **masked**.
|
331 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
332 |
+
Indices of positions of each input sequence token in the position embeddings. Selected in the range `[0,
|
333 |
+
config.n_positions - 1]`.
|
334 |
+
|
335 |
+
[What are position IDs?](../glossary#position-ids)
|
336 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
337 |
+
Pre-computed hidden-states (key and value in the self-attention blocks and in the cross-attention blocks)
|
338 |
+
that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
339 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
340 |
+
|
341 |
+
Two formats are allowed:
|
342 |
+
- a [`~cache_utils.Cache`] instance;
|
343 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
344 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
345 |
+
cache format.
|
346 |
+
|
347 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
348 |
+
legacy cache format will be returned.
|
349 |
+
|
350 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
351 |
+
have their past key/value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
352 |
+
of shape `(batch_size, sequence_length)`.
|
353 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
354 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
355 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
356 |
+
model's internal embedding lookup matrix.
|
357 |
+
use_cache (`bool`, *optional*):
|
358 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
359 |
+
`past_key_values`).
|
360 |
+
output_attentions (`bool`, *optional*):
|
361 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
362 |
+
tensors for more detail.
|
363 |
+
output_hidden_states (`bool`, *optional*):
|
364 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
365 |
+
more detail.
|
366 |
+
return_dict (`bool`, *optional*):
|
367 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
368 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
369 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
370 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
371 |
+
the complete sequence length.
|
372 |
+
"""
|
373 |
+
|
374 |
+
|
375 |
+
class DeepSeekModel(DeepSeekPreTrainedModel):
|
376 |
+
"""
|
377 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepSeekDecoderLayer`]
|
378 |
+
|
379 |
+
Args:
|
380 |
+
config: DeepSeekConfig
|
381 |
+
"""
|
382 |
+
|
383 |
+
def __init__(self, config: DeepSeekConfig):
|
384 |
+
super().__init__(config)
|
385 |
+
self.padding_idx = config.pad_token_id
|
386 |
+
self.vocab_size = config.vocab_size
|
387 |
+
|
388 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
389 |
+
# Note: We'll implement layers in a separate method due to complexity
|
390 |
+
self.norm = DeepSeekRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
391 |
+
|
392 |
+
self.gradient_checkpointing = False
|
393 |
+
# Initialize weights and apply final processing
|
394 |
+
self.post_init()
|
395 |
+
|
396 |
+
def get_input_embeddings(self):
|
397 |
+
return self.embed_tokens
|
398 |
+
|
399 |
+
def set_input_embeddings(self, value):
|
400 |
+
self.embed_tokens = value
|
401 |
+
|
402 |
+
@add_start_docstrings_to_model_forward(DEEPSEEK_INPUTS_DOCSTRING)
|
403 |
+
def forward(
|
404 |
+
self,
|
405 |
+
input_ids: torch.LongTensor = None,
|
406 |
+
attention_mask: Optional[torch.Tensor] = None,
|
407 |
+
position_ids: Optional[torch.LongTensor] = None,
|
408 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
409 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
410 |
+
use_cache: Optional[bool] = None,
|
411 |
+
output_attentions: Optional[bool] = None,
|
412 |
+
output_hidden_states: Optional[bool] = None,
|
413 |
+
return_dict: Optional[bool] = None,
|
414 |
+
cache_position: Optional[torch.LongTensor] = None,
|
415 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
416 |
+
"""Forward pass of the DeepSeek model."""
|
417 |
+
|
418 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
419 |
+
output_hidden_states = (
|
420 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
421 |
+
)
|
422 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
423 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
424 |
+
|
425 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
426 |
+
raise ValueError(
|
427 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
428 |
+
)
|
429 |
+
|
430 |
+
if inputs_embeds is None:
|
431 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
432 |
+
|
433 |
+
hidden_states = inputs_embeds
|
434 |
+
|
435 |
+
# Apply normalization
|
436 |
+
hidden_states = self.norm(hidden_states)
|
437 |
+
|
438 |
+
if not return_dict:
|
439 |
+
return tuple(v for v in [hidden_states, None, None] if v is not None)
|
440 |
+
|
441 |
+
return BaseModelOutputWithPast(
|
442 |
+
last_hidden_state=hidden_states,
|
443 |
+
past_key_values=None,
|
444 |
+
hidden_states=None,
|
445 |
+
attentions=None,
|
446 |
+
)
|
447 |
+
|
448 |
+
|
449 |
+
class DeepSeekForCausalLM(DeepSeekPreTrainedModel):
|
450 |
+
_tied_weights_keys = ["lm_head.weight"]
|
451 |
+
|
452 |
+
def __init__(self, config):
|
453 |
+
super().__init__(config)
|
454 |
+
self.model = DeepSeekModel(config)
|
455 |
+
self.vocab_size = config.vocab_size
|
456 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
457 |
+
|
458 |
+
# Initialize weights and apply final processing
|
459 |
+
self.post_init()
|
460 |
+
|
461 |
+
def get_input_embeddings(self):
|
462 |
+
return self.model.embed_tokens
|
463 |
+
|
464 |
+
def set_input_embeddings(self, value):
|
465 |
+
self.model.embed_tokens = value
|
466 |
+
|
467 |
+
def get_output_embeddings(self):
|
468 |
+
return self.lm_head
|
469 |
+
|
470 |
+
def set_output_embeddings(self, new_embeddings):
|
471 |
+
self.lm_head = new_embeddings
|
472 |
+
|
473 |
+
def set_decoder(self, decoder):
|
474 |
+
self.model = decoder
|
475 |
+
|
476 |
+
def get_decoder(self):
|
477 |
+
return self.model
|
478 |
+
|
479 |
+
@add_start_docstrings_to_model_forward(DEEPSEEK_INPUTS_DOCSTRING)
|
480 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
481 |
+
def forward(
|
482 |
+
self,
|
483 |
+
input_ids: torch.LongTensor = None,
|
484 |
+
attention_mask: Optional[torch.Tensor] = None,
|
485 |
+
position_ids: Optional[torch.LongTensor] = None,
|
486 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
487 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
488 |
+
labels: Optional[torch.LongTensor] = None,
|
489 |
+
use_cache: Optional[bool] = None,
|
490 |
+
output_attentions: Optional[bool] = None,
|
491 |
+
output_hidden_states: Optional[bool] = None,
|
492 |
+
return_dict: Optional[bool] = None,
|
493 |
+
cache_position: Optional[torch.LongTensor] = None,
|
494 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
495 |
+
"""Forward pass of the DeepSeek model for causal language modeling.
|
496 |
+
|
497 |
+
Returns:
|
498 |
+
"""
|
499 |
+
|
500 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
501 |
+
output_hidden_states = (
|
502 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
503 |
+
)
|
504 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
505 |
+
|
506 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
507 |
+
outputs = self.model(
|
508 |
+
input_ids=input_ids,
|
509 |
+
attention_mask=attention_mask,
|
510 |
+
position_ids=position_ids,
|
511 |
+
past_key_values=past_key_values,
|
512 |
+
inputs_embeds=inputs_embeds,
|
513 |
+
use_cache=use_cache,
|
514 |
+
output_attentions=output_attentions,
|
515 |
+
output_hidden_states=output_hidden_states,
|
516 |
+
return_dict=return_dict,
|
517 |
+
cache_position=cache_position,
|
518 |
+
)
|
519 |
+
|
520 |
+
hidden_states = outputs[0]
|
521 |
+
logits = self.lm_head(hidden_states)
|
522 |
+
logits = logits.float()
|
523 |
+
|
524 |
+
loss = None
|
525 |
+
if labels is not None:
|
526 |
+
# Shift so that tokens < n predict n
|
527 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
528 |
+
shift_labels = labels[..., 1:].contiguous()
|
529 |
+
# Flatten the tokens
|
530 |
+
loss_fct = CrossEntropyLoss()
|
531 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
532 |
+
shift_labels = shift_labels.view(-1)
|
533 |
+
# Enable model parallelism
|
534 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
535 |
+
loss = loss_fct(shift_logits, shift_labels)
|
536 |
+
|
537 |
+
if not return_dict:
|
538 |
+
output = (logits,) + outputs[1:]
|
539 |
+
return (loss,) + output if loss is not None else output
|
540 |
+
|
541 |
+
return CausalLMOutputWithPast(
|
542 |
+
loss=loss,
|
543 |
+
logits=logits,
|
544 |
+
past_key_values=outputs.past_key_values,
|
545 |
+
hidden_states=outputs.hidden_states,
|
546 |
+
attentions=outputs.attentions,
|
547 |
+
)
|
548 |
+
|
549 |
+
def prepare_inputs_for_generation(
|
550 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
|
551 |
+
):
|
552 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
553 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
554 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
555 |
+
if past_key_values is not None:
|
556 |
+
if inputs_embeds is not None: # Exception 1
|
557 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
558 |
+
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
|
559 |
+
input_ids = input_ids[:, cache_position]
|
560 |
+
|
561 |
+
if attention_mask is not None and position_ids is None:
|
562 |
+
# create position_ids on the fly for batch generation
|
563 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
564 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
565 |
+
if past_key_values:
|
566 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
567 |
+
|
568 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
569 |
+
if inputs_embeds is not None and cache_position[0] == 0:
|
570 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
571 |
+
else:
|
572 |
+
model_inputs = {"input_ids": input_ids}
|
573 |
+
|
574 |
+
model_inputs.update(
|
575 |
+
{
|
576 |
+
"position_ids": position_ids,
|
577 |
+
"cache_position": cache_position,
|
578 |
+
"past_key_values": past_key_values,
|
579 |
+
"use_cache": kwargs.get("use_cache"),
|
580 |
+
"attention_mask": attention_mask,
|
581 |
+
}
|
582 |
+
)
|
583 |
+
return model_inputs
|
584 |
+
|
585 |
+
@staticmethod
|
586 |
+
def _reorder_cache(past_key_values, beam_idx):
|
587 |
+
reordered_past = ()
|
588 |
+
for layer_past in past_key_values:
|
589 |
+
reordered_past += (
|
590 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
591 |
+
)
|
592 |
+
return reordered_past
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:78e40acba71577135f972943f49ee9739ef33686b6bc7197ea4469b51e468211
|
3 |
+
size 767177171
|
special_tokens_map.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<s>",
|
3 |
+
"eos_token": "</s>",
|
4 |
+
"pad_token": "<pad>",
|
5 |
+
"unk_token": "<unk>"
|
6 |
+
}
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7b0d31a2e63001005e491e091cb02dd9ee7f786bd54be81018b01ff245408628
|
3 |
+
size 1110078
|
tokenizer_config.json
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"tokenizer_class": "LlamaTokenizer",
|
3 |
+
"model_max_length": 256,
|
4 |
+
"pad_token": "<pad>",
|
5 |
+
"bos_token": "<s>",
|
6 |
+
"eos_token": "</s>",
|
7 |
+
"unk_token": "<unk>",
|
8 |
+
"clean_up_tokenization_spaces": false,
|
9 |
+
"auto_map": {
|
10 |
+
"AutoTokenizer": [
|
11 |
+
"sentencepiece",
|
12 |
+
"LlamaTokenizer"
|
13 |
+
]
|
14 |
+
}
|
15 |
+
}
|