update model and config
Browse files- .gitattributes +6 -0
- README.md +334 -0
- config.json +26 -26
- configuration_skywork.py +27 -14
- generation_config.json +1 -1
- modeling_skywork.py +79 -279
- pytorch_model-00032-of-00053.bin +2 -2
- requirements.txt +1 -2
- tokenization_skywork.py +2 -19
.gitattributes
CHANGED
@@ -86,4 +86,10 @@ pytorch_model-00042-of-00053.bin filter=lfs diff=lfs merge=lfs -text
|
|
86 |
pytorch_model-00015-of-00053.bin filter=lfs diff=lfs merge=lfs -text
|
87 |
pytorch_model-00007-of-00053.bin filter=lfs diff=lfs merge=lfs -text
|
88 |
pytorch_model-00018-of-00053.bin filter=lfs diff=lfs merge=lfs -text
|
|
|
89 |
misc/*.gif filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
86 |
pytorch_model-00015-of-00053.bin filter=lfs diff=lfs merge=lfs -text
|
87 |
pytorch_model-00007-of-00053.bin filter=lfs diff=lfs merge=lfs -text
|
88 |
pytorch_model-00018-of-00053.bin filter=lfs diff=lfs merge=lfs -text
|
89 |
+
<<<<<<< HEAD
|
90 |
misc/*.gif filter=lfs diff=lfs merge=lfs -text
|
91 |
+
=======
|
92 |
+
misc/chat_demo_1.gif filter=lfs diff=lfs merge=lfs -text
|
93 |
+
misc/chat_demo_2.gif filter=lfs diff=lfs merge=lfs -text
|
94 |
+
misc/chat_demo_3.gif filter=lfs diff=lfs merge=lfs -text
|
95 |
+
>>>>>>> ad2bb36861f3dd52100257b3f53c094f008caa16
|
README.md
CHANGED
@@ -4,3 +4,337 @@ license_name: license
|
|
4 |
license_link: >-
|
5 |
https://github.com/SkyworkAI/Skywork/blob/main/Skywork%20Community%20License.pdf
|
6 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
license_link: >-
|
5 |
https://github.com/SkyworkAI/Skywork/blob/main/Skywork%20Community%20License.pdf
|
6 |
---
|
7 |
+
|
8 |
+
<!-- <div align="center">
|
9 |
+
<h1>
|
10 |
+
✨Skywork
|
11 |
+
</h1>
|
12 |
+
</div> -->
|
13 |
+
<div align="center"><img src="misc/skywork_logo.jpeg" width="550"/></div>
|
14 |
+
|
15 |
+
<p align="center">
|
16 |
+
🤗 <a href="https://huggingface.co/Skywork" target="_blank">Hugging Face</a> • 🤖 <a href="https://modelscope.cn/organization/Skywork" target="_blank">ModelScope</a> • 💬 <a href="https://github.com/SkyworkAI/Skywork/blob/main/misc/wechat.png?raw=true" target="_blank">WeChat</a>• 📜<a href="https://arxiv.org/" target="_blank">Tech Report</a>• 🧮<a href="https://arxiv.org/" target="_blank">Skymath Paper</a>
|
17 |
+
</p>
|
18 |
+
|
19 |
+
|
20 |
+
<div align="center">
|
21 |
+
|
22 |
+
|
23 |
+
[🎉天工在线对话平台已正式向公众开放](https://sso.tiangong.cn/?redirect=https://model-platform.tiangong.cn/overview&client_id=200005)
|
24 |
+
|
25 |
+
</div>
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
<div align="center">
|
30 |
+
|
31 |
+
|
32 |
+
[![GitHub Stars](https://img.shields.io/github/stars/SkyworkAI/Skywork)](https://github.com/SkyworkAI/Skywork/stargazers)
|
33 |
+
[![GitHub Forks](https://img.shields.io/github/forks/SkyworkAI/Skywork)](https://github.com/SkyworkAI/Skywork/fork)
|
34 |
+
</div>
|
35 |
+
|
36 |
+
|
37 |
+
|
38 |
+
# 模型介绍(Introduction)
|
39 |
+
**Skywork-13B-Base**模型在高质量清洗过滤的3.2万亿个多语言(主要是中文和英文)和代码数据上进行预训练,它在多种评测和各种基准测试上都展现了同等规模模型的最佳效果。
|
40 |
+
|
41 |
+
**Skywork-13B-Base**: The model was trained on a high-quality cleaned dataset consisting of 3.2 trillion multilingual data (mainly Chinese and English) and code. It has demonstrated the best performance among models of similar scale in various evaluations and benchmark tests.
|
42 |
+
|
43 |
+
如果您希望了解更多的信息,如训练方案,评估方法,请参考我们的[技术报告](https://arxiv.org/skywork-tech-report)和[Skywork-Math](https://arxiv.org/skywork-tech-report)论文。
|
44 |
+
|
45 |
+
If you are interested in more training and evaluation details, please refer to our [technical report](https://arxiv.org/skywork-tech-report) and [Skywork-Math]((https://arxiv.org/skywork-tech-report)) paper.
|
46 |
+
|
47 |
+
|
48 |
+
## 训练数据(Training Data)
|
49 |
+
我们精心搭建了数据清洗流程对文本中的低质量数据、有害信息、敏感信息进行清洗过滤。我们的Skywork-13B-Base模型是在清洗后的3.2TB高质量中、英、代码数据上进行训练,其中英文占比52.2%,中文占比39.6%,代码占比8%,在兼顾中文和英文上的表现的同时,代码能力也能有保证。
|
50 |
+
|
51 |
+
We have developed a data cleaning pipeline with great care to effectively clean and filter low-quality data and eliminate harmful information from text data. Our Skywork-13B-Base model is trained on a dataset with 3.2TB tokens that consists of high-quality Chinese, English, and code data, all of which have been thoroughly cleaned. The English data comprises 52.2% of the dataset, the Chinese data accounts for 39.6%, and the code data makes up 8%. This comprehensive approach ensures optimal performance for both Chinese and English while also maintaining the ability to handle code.
|
52 |
+
|
53 |
+
| | Category | Percentage |
|
54 |
+
|-------------|------------------|------------|
|
55 |
+
| **English** | Webpages | 39.8% |
|
56 |
+
| | Books | 3.6% |
|
57 |
+
| | Academic Papers | 3.0% |
|
58 |
+
| | Encyclopedia | 0.5% |
|
59 |
+
| | Miscellany | 2.9% |
|
60 |
+
| **Chinese** | Webpages | 30.4% |
|
61 |
+
| | Social Media | 5.5% |
|
62 |
+
| | Encyclopedia | 0.8% |
|
63 |
+
| | Miscellany | 3.1% |
|
64 |
+
| **Other Lang.** | Encyclopedia | 2.4% |
|
65 |
+
| **Code** | Github | 8.0% |
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
|
71 |
+
## 模型结构(Model Structure)
|
72 |
+
与Llama-2-13B模型对比,天工Skywork-13B模型采用相对更加瘦长的网络结构,层数为52层,同时将FFN Dim和Hidden Dim缩小到12288和4608,从而保证模型参数量和原始Llama-2-13B模型相当。根据我们前期实验对比,相对瘦长的网络结构在大Batch Size训练下可以取得更好的泛化效果。Skywork-13B和Llama-2-13B模型的对比如下:
|
73 |
+
|
74 |
+
Compared to the Llama2-13B model, the Skywork-13B model adopts a relatively thinner and deeper network structure with 52 layers. At the same time, the FFN Dim and Hidden Dim are reduced to 12288 and 4608, respectively, to ensure that the model has a similar number of parameters as the original Llama-13B model. Based on our preliminary experimental results, a relatively thinner and deeper network structure can achieve better generalization performance under large batch size training. The detailed comparison between the Skywork-13B and Llama-2-13B models is as follows:
|
75 |
+
|
76 |
+
| Model Structure | Llama2-13B | Skywork-13B |
|
77 |
+
|----------------------|:----:|:-----------:|
|
78 |
+
| Vocab. Size | 32,000 | 65,536 |
|
79 |
+
| Hidden Dim. | 5,120 | 4,608 |
|
80 |
+
| FFN Dim. | 13,696 | 12,288 |
|
81 |
+
| Head Dim. | 128 | 128 |
|
82 |
+
| Num. Heads | 40 | 36 |
|
83 |
+
| Num. Layers | 40 | 52 |
|
84 |
+
| Seq. Len. | 4,096 | 4,096 |
|
85 |
+
| Positional Embedding | RoPE | RoPE |
|
86 |
+
|
87 |
+
|
88 |
+
## 分词器(Tokenizer)
|
89 |
+
我们使用Byte-Pair Encoding(BPE)对数据进行分词,词表大小为65536,其中拉丁字符和子词为32000个,汉字和Unicode符号8000个,汉语词语25519个,剩下的17个为保留字。
|
90 |
+
|
91 |
+
We use Byte-Pair Encoding (BPE) to tokenize the data, with a vocabulary size of 65536. Among them, there are 32000 Latin characters and subwords, 8000 Chinese characters and Unicode symbols, 25519 Chinese words, and the remaining 17 are reserved words.
|
92 |
+
|
93 |
+
|
94 |
+
| Category | Size |
|
95 |
+
|---------------------------------|--------|
|
96 |
+
| Latin based words & subwords | 32000 |
|
97 |
+
| Chinese characters & Unicode symbols | 8000 |
|
98 |
+
| Chinese words | 25519 |
|
99 |
+
| Reserved symbols | 17 |
|
100 |
+
| **Total** | **65536** |
|
101 |
+
|
102 |
+
|
103 |
+
# 模型评估(Evaluation)
|
104 |
+
## 领域数据困惑度评估(Perplexity Evaluaiton)
|
105 |
+
语言模型训练的本质上是让预测下一个词更准确。基于这个认知,我们认为评估基础大模型一个重要的方式是评估在各大领域上语言模型生成文章的概率。在模型训练中预测下一个词的概率一般使用Cross Entropy损失函数,整体的损失函数为每个位置预测真实词损失的平均,则有:
|
106 |
+
|
107 |
+
$$loss = \sum^{n}_{i=1} log(p_i) / n = log( \prod_{i=1}^n p_i) / n$$
|
108 |
+
|
109 |
+
其中$n$是文档的长度,即token数,$p_i$是位置i上真实词的概率,我们知道文档中每一个位置上真实词的概率的联乘则为生成该文档的概率,如此我们就将loss和生成文章的概率联系在了一起。而不同模型因为使用的分词器不同,具有不同的token数,因此对损失函数乘以token数目$n$,这样就仅考虑生成文章的概率部分,不同模型也可以进行比较。我们将标准化后loss取指数转换成perplexity,使得模型的差异更加可读。为了阅读方便后续提到的loss和ppl为模型标准化后的loss和perplexity。
|
110 |
+
|
111 |
+
基于上述分析,我们对对多个领域筛选出2023年10月份新发布的几百到上千篇高质量文章,并人工进行了核对。保证所有的测试数据不在天工模型以及其他所有模型的训练集中,并且测试数据的来源也足够广泛,质量也高。我们可以选取当前最新的文章评测不同模型的ppl,模型很难作弊。
|
112 |
+
下图列出了不同开源模型,天工Skywork-13B-Base取得最优效果,证明了我们的Base模型的基础能力处于国内开源模型中文最强水平。
|
113 |
+
|
114 |
+
We have chosen several hundred to thousands of high-quality articles that were published in October 2023 across various fields. We have manually verified these articles to ensure their quality. It is important to note that none of the test data used in evaluating the Skywork model or any other models is included in their training set. Furthermore, the test data is diverse and of high quality, making it challenging for the models to gain an unfair advantage.
|
115 |
+
|
116 |
+
The figure below displays the performance of different open source models. Skywork-13B-Base achieves the best results.
|
117 |
+
|
118 |
+
| | Tech | Movie | Gov. | Game | Finance | General | Average |
|
119 |
+
|------------------|-------|-------|-------|-------|---------|---------|---------|
|
120 |
+
| MOSS-7B | 20.83 | 39.66 | 11.08 | 31.24 | 10.59 | 13.25 | 18.50 |
|
121 |
+
| InternLM-7B | 13.43 | 24.90 | 5.88 | 19.78 | 6.17 | 8.10 | 11.17 |
|
122 |
+
| Qwen-7B | 13.39 | 25.16 | 5.55 | 19.26 | 5.76 | 7.78 | 10.83 |
|
123 |
+
| Baichuan2-7B | 12.89 | 23.26 | 5.34 | 18.36 | 5.68 | 7.62 | 10.41 |
|
124 |
+
| LLaMA2-13B | 23.26 | 50.66 | 18.09 | 32.52 | 14.85 | 16.55 | 23.54 |
|
125 |
+
| Xverse-13B | 12.55 | 23.49 | 5.20 | 17.69 | 5.54 | 7.46 | 10.19 |
|
126 |
+
| Baichuan-13B | 12.38 | 22.46 | 5.21 | 17.59 | 5.42 | 7.37 | 10.03 |
|
127 |
+
| Baichuan2-13B | 12.14 | 21.85 | 5.05 | 17.15 | 5.35 | 7.24 | 9.81 |
|
128 |
+
| Qwen-14B | 11.90 | 22.43 | 4.89 | **16.94** | 5.24 | 7.03 | 9.67 |
|
129 |
+
| InternLM-20B | 12.34 | 22.06 | 5.75 | 17.45 | 5.73 | 7.78 | 10.34 |
|
130 |
+
| Aquila2-34B | 14.62 | 29.09 | 5.72 | 21.78 | 5.83 | 8.45 | 11.73 |
|
131 |
+
| Skywork-13B-Base | **11.58** | **21.84** | **4.76** | 17.28 | **4.92** | **6.82** | **9.42** |
|
132 |
+
|
133 |
+
### 评测数据和评测脚本(Loss Evaluation)
|
134 |
+
我们将评测数据和评测脚本也进行了开源,下载github上的代码运行下面命令则可以复现我们的结果。
|
135 |
+
|
136 |
+
We have also open-sourced the data and evaluation scripts. You can reproduce our results by running the following command.
|
137 |
+
|
138 |
+
```
|
139 |
+
bash bash_scripts/skywork_eval_loss.sh
|
140 |
+
```
|
141 |
+
|
142 |
+
## Benchmark评估(Benchmark Results)
|
143 |
+
我们评估了各大权威评测benchmark上的结果作为参考,包括C-Eval,MMLU,CMMLU,GSM8K。遵循之前的评估流程,C-Eval��MMLU、CMMLU测试5-shot结果,GSM8K测试8-shot结果。可以看到Skywork-13B-Base模型在中文开源模型中处于前列,在同等参数规模下为最优水平。
|
144 |
+
|
145 |
+
We evaluated Skywork-13B-Base on several popular benchmarks, including C-Eval, MMLU, CMMLU, and GSM8K. Following the previous evaluation process, we tested the 5-shot results of C-Eval, MMLU, and CMMLU, and the 8-shot results of GSM8K. It can be seen that the Skywork-13B-Base model is among the top models in the Chinese open source model community, performing at an optimal level with the same parameter scale.
|
146 |
+
|
147 |
+
| Model | C-Eval | CMMLU | MMLU | GSM8K |
|
148 |
+
|-------------------------|:-----:|:---------------:|:----------:|:-------:|
|
149 |
+
| LLaMA-1-13B-Base | 35.5 | 31.2 | 46.9 | 17.8 |
|
150 |
+
| Open-LLaMA-13B | 27.1 | 26.7 | 42.7 | 12.4 |
|
151 |
+
| LLaMA-2-13B-Base | 36.5 | 36.6 | 54.8 | 28.7 |
|
152 |
+
| InternLM-20B | 58.8 | - | 62.0 | 52.6 |
|
153 |
+
| Qwen-14B-Base | 72.1 | 71.0 | 66.3 | 61.3 |
|
154 |
+
| Aquila2-34B-Base | 63.1 | 71.4 | 64.2 | 58.4 |
|
155 |
+
| XVERSE-13B-Base | 54.7 | - | 55.1 | - |
|
156 |
+
| Baichuan-13B-Base | 52.4 | 55.3 | 51.6 | 26.6 |
|
157 |
+
| Baichuan-2-13B-Base | 58.1 | 62.0 | 59.2 | 52.3 |
|
158 |
+
| Skywork-13B-Base (ours) | 59.5 | 61.6 | 61.6 | 55.8 |
|
159 |
+
|
160 |
+
## Benchmark评估详细结果
|
161 |
+
我们给出**Skywork-13B-Base**模型在C-Eval,CMMLU,MMLU上模型的详细结果。
|
162 |
+
|
163 |
+
We provide detailed results of the Skywork-13B-Base model on C-EVAL, CMMLU, and MMLU.
|
164 |
+
|
165 |
+
| Benchmark | **STEM** | **Humanities** | **Social Science** | **Other** | **China Specific** | **Hard** | **Average** |
|
166 |
+
|:-----:|:---------:|:--------:|:-------------:|:--------:|:--------:|:--------:|:--------:|
|
167 |
+
| **C-EVAL** | 51.5 | 65.1 | 73.9 | 55.1 | - | 39.9 | 59.5 |
|
168 |
+
| **CMMLU** | 49.8 | 68.9 | 65.6 | 62.8 | 63.7 | - | 61.6 |
|
169 |
+
| **MMLU** | 50.6 | 57.8 | 71.9 | 68.3 | - | - | 61.6 |
|
170 |
+
|
171 |
+
|
172 |
+
# 快速开始(Quickstart)
|
173 |
+
我们将模型参数、配置文件、tokenizer等在huggingface和modelscope上进行了开源。
|
174 |
+
|
175 |
+
We have open-sourced the model parameters, configuration files, tokenizer, and more on Huggingface and Modelscope.
|
176 |
+
|
177 |
+
## 依赖安装(Requirements)
|
178 |
+
- Python 3.8及以上版本
|
179 |
+
- Pytorch 2.0及以上版本
|
180 |
+
- CUDA建议使用11.4以上版本。
|
181 |
+
|
182 |
+
Skywork-13B-Base模型,Skywork-13B-Chat模型和Skywork-13B-Math模型运行下面的脚本进行Python依赖安装。
|
183 |
+
|
184 |
+
- Python 3.8 and above
|
185 |
+
- Pytorch 2.0 and above
|
186 |
+
- CUDA 11.4 and above are recommended.
|
187 |
+
|
188 |
+
Skywork-13B-Base model, Skywork-13B-Chat model, and Skywork-13B-Math model run the following script for Python dependency installation:
|
189 |
+
|
190 |
+
```shell
|
191 |
+
pip install -r requirements.txt
|
192 |
+
```
|
193 |
+
## Huggingface模型测试(Demonstration)
|
194 |
+
|
195 |
+
|
196 |
+
### Base 模型推理(Base Model Inference)
|
197 |
+
|
198 |
+
```python
|
199 |
+
|
200 |
+
>>> from transformers import AutoModelForCausalLM, AutoTokenizer
|
201 |
+
>>> from transformers.generation import GenerationConfig
|
202 |
+
>>> import torch
|
203 |
+
|
204 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("SkyworkAI/Skywork-13B-Base", trust_remote_code=True)
|
205 |
+
>>> model = AutoModelForCausalLM.from_pretrained("SkyworkAI/Skywork-13B-Base", device_map="auto", trust_remote_code=True).eval()
|
206 |
+
|
207 |
+
>>> inputs = tokenizer('陕西的省会是西安', return_tensors='pt').to(model.device)
|
208 |
+
>>> response = model.generate(inputs.input_ids, max_length=128)
|
209 |
+
>>> print(tokenizer.decode(response.cpu()[0], skip_special_tokens=True))
|
210 |
+
陕西的省会是西安,西安是我国著名的古都,在历史上有十三个朝代在此建都,所以西安又被称为“十三朝古都”。西安是我国著名的旅游城市,每年都有大量的游客来到西安旅游,西安的旅游资源非常丰富,有很多著名的旅游景点,比如秦始皇兵马俑、大雁塔、华清池、大唐芙蓉园、西安城墙、大明宫国家遗址公园、西安碑林博物馆、西安钟楼、西安鼓楼、西安半坡博物馆、西安大兴善寺、西安小雁塔
|
211 |
+
|
212 |
+
|
213 |
+
>>> inputs = tokenizer('陕西的省会是西安,甘肃的省会是兰州,河南的省会是郑州', return_tensors='pt').to(model.device)
|
214 |
+
>>> response = model.generate(inputs.input_ids, max_length=128)
|
215 |
+
>>> print(tokenizer.decode(response.cpu()[0], skip_special_tokens=True))
|
216 |
+
陕西的省会是西安,甘肃的省会是兰州,河南的省会是郑州,湖北的省会是武汉,湖南的省会是长沙,江西的省会是南昌,安徽的省会是合肥,江苏的省会是南京,浙江的省会是杭州,福建的省会是福州,广东的省会是广州,广西的省会是南宁,海南的省会是海口,四川的省会是成都,贵州的省会是贵阳,云南的省会是昆明,西藏的省会是拉萨,青海的省会是西宁,宁夏的省会是银川,新疆的省会是乌鲁木齐。
|
217 |
+
|
218 |
+
|
219 |
+
```
|
220 |
+
|
221 |
+
# 模型微调(Fine-tuning)
|
222 |
+
## 全量微调(Full-parameter Fine-tuning)
|
223 |
+
使用Skywork-13B-Base模型进行预训练微调
|
224 |
+
```bash
|
225 |
+
## preprocess continue pretraining data
|
226 |
+
## Because pre-training data is usually large, we use a script to process the training data separately.
|
227 |
+
python train/pt_data_preprocess.py \
|
228 |
+
-t $MODEL_PATH \
|
229 |
+
-i data/pt_train.jsonl \
|
230 |
+
-o data_cache/pt_train_demo
|
231 |
+
|
232 |
+
## launch training
|
233 |
+
export WANDB_API_KEY=YOUR_WANDB_KEY
|
234 |
+
export WANDB_ENTITY=skywork
|
235 |
+
export WANDB_PROJECT=skywork-13b-opensource
|
236 |
+
|
237 |
+
export MODEL_PATH=skywork-13b-models/skywork-13b-base
|
238 |
+
export DATA_CACHE_DIR=data_cache/pt_train_demo/pt_train
|
239 |
+
bash bash_scripts/skywork_13b_pt.sh
|
240 |
+
|
241 |
+
```
|
242 |
+
使用Skywork-13B-Base模型进行有监督微调(SFT, Supevise Fine-tuning)
|
243 |
+
|
244 |
+
```bash
|
245 |
+
## preprocess data and launch training
|
246 |
+
export WANDB_API_KEY=YOUR_WANDB_KEY
|
247 |
+
export WANDB_ENTITY=skywork
|
248 |
+
export WANDB_PROJECT=skywork-13b-opensource
|
249 |
+
|
250 |
+
export SFT_DATA_DIR=data/sft_data
|
251 |
+
export DATA_CACHE_DIR=data_cache/sft_train_demo
|
252 |
+
bash bash_scripts/skywork_13b_sft.sh
|
253 |
+
|
254 |
+
|
255 |
+
```
|
256 |
+
|
257 |
+
## LoRA微调(PEFT)
|
258 |
+
使用Skywork-13B-Base模型以及LoRA进行预训练微调
|
259 |
+
```bash
|
260 |
+
## preprocess continue pretraining data
|
261 |
+
## Because pre-training data is usually large, we use a script to process the training data separately.
|
262 |
+
python train/pt_data_preprocess.py \
|
263 |
+
-t $MODEL_PATH \
|
264 |
+
-i data/pt_train.jsonl \
|
265 |
+
-o data_cache/pt_train_demo
|
266 |
+
|
267 |
+
|
268 |
+
export WANDB_API_KEY=YOUR_WANDB_KEY
|
269 |
+
export WANDB_ENTITY=skywork
|
270 |
+
export WANDB_PROJECT=skywork-13b-opensource
|
271 |
+
|
272 |
+
export MODEL_PATH=skywork-13b-models/skywork-13b-base
|
273 |
+
export DATA_CACHE_DIR=data_cache/pt_train_demo/pt_train
|
274 |
+
bash bash_scripts/skywork_13b_pt_lora.sh
|
275 |
+
|
276 |
+
```
|
277 |
+
|
278 |
+
使用Skywork-13B-Base模型以及LoRA进行有监督微调(SFT, Supevise Fine-tuning)
|
279 |
+
|
280 |
+
```bash
|
281 |
+
|
282 |
+
|
283 |
+
export WANDB_API_KEY=YOUR_WANDB_KEY
|
284 |
+
export WANDB_ENTITY=skywork
|
285 |
+
export WANDB_PROJECT=skywork-13b-opensource
|
286 |
+
|
287 |
+
export SFT_DATA_DIR=data/sft_data
|
288 |
+
export DATA_CACHE_DIR=data_cache/sft_train_demo
|
289 |
+
bash bash_scripts/skywork_13b_sft_lora.sh
|
290 |
+
|
291 |
+
```
|
292 |
+
# 声明和协议(Declaration and License Aggrement)
|
293 |
+
|
294 |
+
|
295 |
+
## 声明(Declaration)
|
296 |
+
|
297 |
+
我们在此声明,不要利用Skywork模型进行任何危害国家社会安全或违法的活动。另外,我们也要求使用者不要将 Skywork 模型用于未经适当安全审查和备案的互联网服务。我们希望所有的使用者都能遵守这个原则,确保科技的发展能在规范和合法的环境下进行。
|
298 |
+
|
299 |
+
我们已经尽我们所能,来确保模型训练过程中使用的数据的合规性。然而,尽管我们已经做出了巨大的努力,但由于模型和数据的复杂性,仍有可能存在一些无法预见的问题。因此,如果由于使用skywork开源模型而导致的任何问题,包括但不限于数据安全问题、公共舆论风险,或模型被误导、滥用、传播或不当利用所带来的任何风险和问题,我们将不承担任何责任。
|
300 |
+
|
301 |
+
We hereby declare that the Skywork model should not be used for any activities that pose a threat to national or societal security or engage in unlawful actions. Additionally, we request users not to deploy the Skywork model for internet services without appropriate security reviews and records. We hope that all users will adhere to this principle to ensure that technological advancements occur in a regulated and lawful environment.
|
302 |
+
|
303 |
+
We have done our utmost to ensure the compliance of the data used during the model's training process. However, despite our extensive efforts, due to the complexity of the model and data, there may still be unpredictable risks and issues. Therefore, if any problems arise as a result of using the Skywork open-source model, including but not limited to data security issues, public opinion risks, or any risks and problems arising from the model being misled, abused, disseminated, or improperly utilized, we will not assume any responsibility.
|
304 |
+
|
305 |
+
## 协议(License Aggrement)
|
306 |
+
|
307 |
+
社区使用Skywork模型需要遵循[《Skywork 模型社区许可协议》](https://github.com/SkyworkAI/Skywork/blob/main/Skywork%20模型社区许可协议.pdf)。Skywork模型支持商业用途,如果您计划将Skywork模型或其衍生品用于商业目的,无需再次申请, 但请您仔细阅读[《Skywork 模型社区许可协议》](https://github.com/SkyworkAI/Skywork/blob/main/Skywork%20模型社区许可协议.pdf)并严格遵守相关条款。
|
308 |
+
|
309 |
+
|
310 |
+
The community usage of Skywork model requires [Skywork Community License](https://github.com/SkyworkAI/Skywork/blob/main/Skywork%20Community%20License.pdf). The Skywork model supports commercial use. If you plan to use the Skywork model or its derivatives for commercial purposes, you must abide by terms and conditions within [Skywork Community License](https://github.com/SkyworkAI/Skywork/blob/main/Skywork%20Community%20License.pdf).
|
311 |
+
|
312 |
+
|
313 |
+
|
314 |
+
[《Skywork 模型社区许可协议》》]:https://github.com/SkyworkAI/Skywork/blob/main/Skywork%20模型社区许可协议.pdf
|
315 |
+
|
316 |
+
|
317 |
+
[[email protected]]: mailto:[email protected]
|
318 |
+
|
319 |
+
# 引用和联系我们(Contact Us and Citation)
|
320 |
+
如果您觉得我们的工作对您有帮助,欢迎引用我们的论文~
|
321 |
+
|
322 |
+
If you find our work helpful, please feel free to cite our paper~
|
323 |
+
```
|
324 |
+
@article{skyworktechreport,
|
325 |
+
title={},
|
326 |
+
author={},
|
327 |
+
journal={arXiv preprint arXiv:},
|
328 |
+
year={2023}
|
329 |
+
}
|
330 |
+
```
|
331 |
+
|
332 |
+
```
|
333 |
+
@article{skyworkmath,
|
334 |
+
title={},
|
335 |
+
author={},
|
336 |
+
journal={arXiv preprint arXiv:},
|
337 |
+
year={2023}
|
338 |
+
}
|
339 |
+
```
|
340 |
+
|
config.json
CHANGED
@@ -1,27 +1,27 @@
|
|
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 |
-
}
|
|
|
1 |
{
|
2 |
+
"architectures": [
|
3 |
+
"SkyworkForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_skywork.SkyworkConfig",
|
7 |
+
"AutoModelForCausalLM": "modeling_skywork.SkyworkForCausalLM"
|
8 |
+
},
|
9 |
+
"bos_token_id": 1,
|
10 |
+
"eos_token_id": 2,
|
11 |
+
"pad_token_id": 0,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 4608,
|
14 |
+
"initializer_range": 0.01,
|
15 |
+
"intermediate_size": 12288,
|
16 |
+
"max_position_embeddings": 131072,
|
17 |
+
"model_type": "skywork",
|
18 |
+
"num_attention_heads": 36,
|
19 |
+
"num_hidden_layers": 52,
|
20 |
+
"num_key_value_heads": 36,
|
21 |
+
"rms_norm_eps": 1e-06,
|
22 |
+
"tie_word_embeddings": false,
|
23 |
+
"torch_dtype": "bfloat16",
|
24 |
+
"transformers_version": "4.33.1",
|
25 |
+
"use_cache": true,
|
26 |
+
"vocab_size": 65519
|
27 |
+
}
|
configuration_skywork.py
CHANGED
@@ -1,13 +1,14 @@
|
|
1 |
# Copyright (c) SkyworkAI and the HuggingFace Inc. team. All rights reserved.
|
2 |
# This code is built upon Huggingface's transformers repository.
|
3 |
|
|
|
4 |
from transformers.configuration_utils import PretrainedConfig
|
5 |
from transformers.utils import logging
|
6 |
|
7 |
|
8 |
logger = logging.get_logger(__name__)
|
9 |
|
10 |
-
|
11 |
|
12 |
|
13 |
class SkyworkConfig(PretrainedConfig):
|
@@ -28,15 +29,13 @@ class SkyworkConfig(PretrainedConfig):
|
|
28 |
initializer_range=0.02,
|
29 |
rms_norm_eps=1e-6,
|
30 |
use_cache=True,
|
31 |
-
pad_token_id=
|
32 |
bos_token_id=1,
|
33 |
eos_token_id=2,
|
34 |
pretraining_tp=1,
|
35 |
tie_word_embeddings=False,
|
36 |
-
rope_scaling=None,
|
37 |
rope_theta=10000.0,
|
38 |
-
|
39 |
-
use_flash_attention=False,
|
40 |
**kwargs,
|
41 |
):
|
42 |
self.vocab_size = vocab_size
|
@@ -56,16 +55,9 @@ class SkyworkConfig(PretrainedConfig):
|
|
56 |
self.rms_norm_eps = rms_norm_eps
|
57 |
self.pretraining_tp = pretraining_tp
|
58 |
self.use_cache = use_cache
|
59 |
-
self.rope_scaling = rope_scaling
|
60 |
self.rope_theta = rope_theta
|
61 |
-
self.
|
62 |
-
self.
|
63 |
-
if self.use_flash_attention:
|
64 |
-
try:
|
65 |
-
from flash_attn.flash_attn_interface import flash_attn_varlen_func
|
66 |
-
from einops import rearrange
|
67 |
-
except:
|
68 |
-
raise ValueError("`use_flash_attention` requires Flash Attention 2+ and einops.\nTry `pip install einops` and installing Flash Attention from from https://github.com/Dao-AILab/flash-attention")
|
69 |
|
70 |
super().__init__(
|
71 |
pad_token_id=pad_token_id,
|
@@ -74,3 +66,24 @@ class SkyworkConfig(PretrainedConfig):
|
|
74 |
tie_word_embeddings=tie_word_embeddings,
|
75 |
**kwargs,
|
76 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# Copyright (c) SkyworkAI and the HuggingFace Inc. team. All rights reserved.
|
2 |
# This code is built upon Huggingface's transformers repository.
|
3 |
|
4 |
+
|
5 |
from transformers.configuration_utils import PretrainedConfig
|
6 |
from transformers.utils import logging
|
7 |
|
8 |
|
9 |
logger = logging.get_logger(__name__)
|
10 |
|
11 |
+
LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
12 |
|
13 |
|
14 |
class SkyworkConfig(PretrainedConfig):
|
|
|
29 |
initializer_range=0.02,
|
30 |
rms_norm_eps=1e-6,
|
31 |
use_cache=True,
|
32 |
+
pad_token_id=None,
|
33 |
bos_token_id=1,
|
34 |
eos_token_id=2,
|
35 |
pretraining_tp=1,
|
36 |
tie_word_embeddings=False,
|
|
|
37 |
rope_theta=10000.0,
|
38 |
+
rope_scaling=None,
|
|
|
39 |
**kwargs,
|
40 |
):
|
41 |
self.vocab_size = vocab_size
|
|
|
55 |
self.rms_norm_eps = rms_norm_eps
|
56 |
self.pretraining_tp = pretraining_tp
|
57 |
self.use_cache = use_cache
|
|
|
58 |
self.rope_theta = rope_theta
|
59 |
+
self.rope_scaling = rope_scaling
|
60 |
+
self._rope_scaling_validation()
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
super().__init__(
|
63 |
pad_token_id=pad_token_id,
|
|
|
66 |
tie_word_embeddings=tie_word_embeddings,
|
67 |
**kwargs,
|
68 |
)
|
69 |
+
|
70 |
+
def _rope_scaling_validation(self):
|
71 |
+
"""
|
72 |
+
Validate the `rope_scaling` configuration.
|
73 |
+
"""
|
74 |
+
if self.rope_scaling is None:
|
75 |
+
return
|
76 |
+
|
77 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
78 |
+
raise ValueError(
|
79 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
80 |
+
f"got {self.rope_scaling}"
|
81 |
+
)
|
82 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
83 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
84 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic", "ntk"]:
|
85 |
+
raise ValueError(
|
86 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
87 |
+
)
|
88 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
89 |
+
raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
|
generation_config.json
CHANGED
@@ -6,5 +6,5 @@
|
|
6 |
"pad_token_id": 0,
|
7 |
"temperature": 0.6,
|
8 |
"top_p": 0.9,
|
9 |
-
"transformers_version": "4.
|
10 |
}
|
|
|
6 |
"pad_token_id": 0,
|
7 |
"temperature": 0.6,
|
8 |
"top_p": 0.9,
|
9 |
+
"transformers_version": "4.33.1"
|
10 |
}
|
modeling_skywork.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
# Copyright (c) SkyworkAI and the HuggingFace Inc. team. All rights reserved.
|
2 |
# This code is built upon Huggingface's transformers repository.
|
|
|
3 |
import math
|
4 |
from typing import List, Optional, Tuple, Union
|
5 |
|
@@ -12,39 +13,15 @@ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
|
12 |
from transformers.activations import ACT2FN
|
13 |
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
14 |
from transformers.modeling_utils import PreTrainedModel
|
15 |
-
from transformers.
|
16 |
-
from transformers.utils import (
|
17 |
-
add_start_docstrings,
|
18 |
-
add_start_docstrings_to_model_forward,
|
19 |
-
is_flash_attn_available,
|
20 |
-
logging,
|
21 |
-
replace_return_docstrings,
|
22 |
-
)
|
23 |
from .configuration_skywork import SkyworkConfig
|
24 |
|
25 |
|
26 |
-
if is_flash_attn_available():
|
27 |
-
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
28 |
-
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
29 |
-
|
30 |
-
|
31 |
logger = logging.get_logger(__name__)
|
32 |
|
33 |
_CONFIG_FOR_DOC = "SkyworkConfig"
|
34 |
|
35 |
|
36 |
-
def _get_unpad_data(padding_mask):
|
37 |
-
seqlens_in_batch = padding_mask.sum(dim=-1, dtype=torch.int32)
|
38 |
-
indices = torch.nonzero(padding_mask.flatten(), as_tuple=False).flatten()
|
39 |
-
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
40 |
-
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
41 |
-
return (
|
42 |
-
indices,
|
43 |
-
cu_seqlens,
|
44 |
-
max_seqlen_in_batch,
|
45 |
-
)
|
46 |
-
|
47 |
-
|
48 |
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
49 |
def _make_causal_mask(
|
50 |
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
@@ -95,10 +72,7 @@ class SkyworkRMSNorm(nn.Module):
|
|
95 |
return self.weight * hidden_states.to(input_dtype)
|
96 |
|
97 |
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
class SkyworkRotaryEmbedding(nn.Module):
|
102 |
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
103 |
super().__init__()
|
104 |
|
@@ -120,8 +94,8 @@ class SkyworkRotaryEmbedding(nn.Module):
|
|
120 |
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
121 |
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
122 |
emb = torch.cat((freqs, freqs), dim=-1)
|
123 |
-
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
124 |
-
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
125 |
|
126 |
def forward(self, x, seq_len=None):
|
127 |
# x: [bs, num_attention_heads, seq_len, head_size]
|
@@ -129,8 +103,8 @@ class SkyworkRotaryEmbedding(nn.Module):
|
|
129 |
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
130 |
|
131 |
return (
|
132 |
-
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
133 |
-
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
134 |
)
|
135 |
|
136 |
|
@@ -149,8 +123,8 @@ class SkyworkLinearScalingRotaryEmbedding(SkyworkRotaryEmbedding):
|
|
149 |
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
150 |
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
151 |
emb = torch.cat((freqs, freqs), dim=-1)
|
152 |
-
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
153 |
-
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
154 |
|
155 |
|
156 |
class SkyworkDynamicNTKScalingRotaryEmbedding(SkyworkRotaryEmbedding):
|
@@ -175,9 +149,42 @@ class SkyworkDynamicNTKScalingRotaryEmbedding(SkyworkRotaryEmbedding):
|
|
175 |
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
176 |
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
177 |
emb = torch.cat((freqs, freqs), dim=-1)
|
178 |
-
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
179 |
-
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
180 |
|
|
|
|
|
|
|
|
|
181 |
|
182 |
def rotate_half(x):
|
183 |
"""Rotates half the hidden dims of the input."""
|
@@ -186,10 +193,12 @@ def rotate_half(x):
|
|
186 |
return torch.cat((-x2, x1), dim=-1)
|
187 |
|
188 |
|
189 |
-
# Copied from transformers.models.gpt_neox.modeling_gpt_neox.apply_rotary_pos_emb
|
190 |
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
191 |
-
|
192 |
-
|
|
|
|
|
|
|
193 |
q_embed = (q * cos) + (rotate_half(q) * sin)
|
194 |
k_embed = (k * cos) + (rotate_half(k) * sin)
|
195 |
return q_embed, k_embed
|
@@ -260,10 +269,10 @@ class SkyworkAttention(nn.Module):
|
|
260 |
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
261 |
f" and `num_heads`: {self.num_heads})."
|
262 |
)
|
263 |
-
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=
|
264 |
-
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=
|
265 |
-
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=
|
266 |
-
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=
|
267 |
self._init_rope()
|
268 |
|
269 |
def _init_rope(self):
|
@@ -290,9 +299,18 @@ class SkyworkAttention(nn.Module):
|
|
290 |
scaling_factor=scaling_factor,
|
291 |
base=self.rope_theta,
|
292 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
293 |
else:
|
294 |
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
295 |
-
|
|
|
|
|
296 |
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
297 |
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
298 |
|
@@ -304,7 +322,6 @@ class SkyworkAttention(nn.Module):
|
|
304 |
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
305 |
output_attentions: bool = False,
|
306 |
use_cache: bool = False,
|
307 |
-
padding_mask: Optional[torch.LongTensor] = None,
|
308 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
309 |
bsz, q_len, _ = hidden_states.size()
|
310 |
|
@@ -347,6 +364,7 @@ class SkyworkAttention(nn.Module):
|
|
347 |
|
348 |
past_key_value = (key_states, value_states) if use_cache else None
|
349 |
|
|
|
350 |
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
351 |
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
352 |
|
@@ -376,7 +394,6 @@ class SkyworkAttention(nn.Module):
|
|
376 |
)
|
377 |
|
378 |
attn_output = attn_output.transpose(1, 2).contiguous()
|
379 |
-
|
380 |
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
381 |
|
382 |
if self.config.pretraining_tp > 1:
|
@@ -392,193 +409,11 @@ class SkyworkAttention(nn.Module):
|
|
392 |
return attn_output, attn_weights, past_key_value
|
393 |
|
394 |
|
395 |
-
class SkyworkFlashAttention2(SkyworkAttention):
|
396 |
-
"""
|
397 |
-
Skywork flash attention module. This module inherits from `SkyworkAttention` as the weights of the module stays
|
398 |
-
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
399 |
-
flash attention and deal with padding tokens in case the input contains any of them.
|
400 |
-
"""
|
401 |
-
|
402 |
-
def forward(
|
403 |
-
self,
|
404 |
-
hidden_states: torch.Tensor,
|
405 |
-
attention_mask: Optional[torch.Tensor] = None,
|
406 |
-
position_ids: Optional[torch.LongTensor] = None,
|
407 |
-
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
408 |
-
output_attentions: bool = False,
|
409 |
-
use_cache: bool = False,
|
410 |
-
padding_mask: Optional[torch.LongTensor] = None,
|
411 |
-
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
412 |
-
# SkyworkFlashAttention2 attention does not support output_attentions
|
413 |
-
output_attentions = False
|
414 |
-
|
415 |
-
bsz, q_len, _ = hidden_states.size()
|
416 |
-
|
417 |
-
query_states = self.q_proj(hidden_states)
|
418 |
-
key_states = self.k_proj(hidden_states)
|
419 |
-
value_states = self.v_proj(hidden_states)
|
420 |
-
|
421 |
-
# Flash attention requires the input to have the shape
|
422 |
-
# batch_size x seq_length x head_dime x hidden_dim
|
423 |
-
# therefore we just need to keep the original shape
|
424 |
-
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
425 |
-
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
426 |
-
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
427 |
-
|
428 |
-
kv_seq_len = key_states.shape[-2]
|
429 |
-
if past_key_value is not None:
|
430 |
-
kv_seq_len += past_key_value[0].shape[-2]
|
431 |
-
|
432 |
-
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
433 |
-
|
434 |
-
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
435 |
-
|
436 |
-
if past_key_value is not None:
|
437 |
-
# reuse k, v, self_attention
|
438 |
-
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
439 |
-
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
440 |
-
|
441 |
-
past_key_value = (key_states, value_states) if use_cache else None
|
442 |
-
|
443 |
-
query_states = query_states.transpose(1, 2)
|
444 |
-
key_states = key_states.transpose(1, 2)
|
445 |
-
value_states = value_states.transpose(1, 2)
|
446 |
-
|
447 |
-
# TODO: skywork does not have dropout in the config??
|
448 |
-
# It is recommended to use dropout with FA according to the docs
|
449 |
-
# when training.
|
450 |
-
dropout_rate = 0.0 # if not self.training else self.attn_dropout
|
451 |
-
|
452 |
-
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
453 |
-
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
454 |
-
# cast them back in float16 just to be sure everything works as expected.
|
455 |
-
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
456 |
-
# in fp32. (SkyworkRMSNorm handles it correctly)
|
457 |
-
input_dtype = query_states.dtype
|
458 |
-
if input_dtype == torch.float32:
|
459 |
-
logger.warning_once(
|
460 |
-
"The input hidden states seems to be silently casted in float32, this might be related to"
|
461 |
-
" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
462 |
-
" float16."
|
463 |
-
)
|
464 |
-
|
465 |
-
query_states = query_states.to(torch.float16)
|
466 |
-
key_states = key_states.to(torch.float16)
|
467 |
-
value_states = value_states.to(torch.float16)
|
468 |
-
|
469 |
-
attn_output = self._flash_attention_forward(
|
470 |
-
query_states, key_states, value_states, padding_mask, q_len, dropout=dropout_rate
|
471 |
-
)
|
472 |
-
|
473 |
-
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
474 |
-
attn_output = self.o_proj(attn_output)
|
475 |
-
|
476 |
-
if not output_attentions:
|
477 |
-
attn_weights = None
|
478 |
-
|
479 |
-
return attn_output, attn_weights, past_key_value
|
480 |
-
|
481 |
-
def _flash_attention_forward(
|
482 |
-
self, query_states, key_states, value_states, padding_mask, query_length, dropout=0.0, softmax_scale=None
|
483 |
-
):
|
484 |
-
"""
|
485 |
-
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
486 |
-
first unpad the input, then computes the attention scores and pad the final attention scores.
|
487 |
-
|
488 |
-
Args:
|
489 |
-
query_states (`torch.Tensor`):
|
490 |
-
Input query states to be passed to Flash Attention API
|
491 |
-
key_states (`torch.Tensor`):
|
492 |
-
Input key states to be passed to Flash Attention API
|
493 |
-
value_states (`torch.Tensor`):
|
494 |
-
Input value states to be passed to Flash Attention API
|
495 |
-
padding_mask (`torch.Tensor`):
|
496 |
-
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
497 |
-
position of padding tokens and 1 for the position of non-padding tokens.
|
498 |
-
dropout (`int`, *optional*):
|
499 |
-
Attention dropout
|
500 |
-
softmax_scale (`float`, *optional*):
|
501 |
-
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
502 |
-
"""
|
503 |
-
# Contains at least one padding token in the sequence
|
504 |
-
if padding_mask is not None:
|
505 |
-
batch_size = query_states.shape[0]
|
506 |
-
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
507 |
-
query_states, key_states, value_states, padding_mask, query_length
|
508 |
-
)
|
509 |
-
|
510 |
-
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
511 |
-
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
512 |
-
|
513 |
-
attn_output_unpad = flash_attn_varlen_func(
|
514 |
-
query_states,
|
515 |
-
key_states,
|
516 |
-
value_states,
|
517 |
-
cu_seqlens_q=cu_seqlens_q,
|
518 |
-
cu_seqlens_k=cu_seqlens_k,
|
519 |
-
max_seqlen_q=max_seqlen_in_batch_q,
|
520 |
-
max_seqlen_k=max_seqlen_in_batch_k,
|
521 |
-
dropout_p=dropout,
|
522 |
-
softmax_scale=softmax_scale,
|
523 |
-
causal=True,
|
524 |
-
)
|
525 |
-
|
526 |
-
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
527 |
-
else:
|
528 |
-
attn_output = flash_attn_func(
|
529 |
-
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=True
|
530 |
-
)
|
531 |
-
|
532 |
-
return attn_output
|
533 |
-
|
534 |
-
def _upad_input(self, query_layer, key_layer, value_layer, padding_mask, query_length):
|
535 |
-
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(padding_mask)
|
536 |
-
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
537 |
-
|
538 |
-
key_layer = index_first_axis(
|
539 |
-
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
540 |
-
)
|
541 |
-
value_layer = index_first_axis(
|
542 |
-
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
543 |
-
)
|
544 |
-
if query_length == kv_seq_len:
|
545 |
-
query_layer = index_first_axis(
|
546 |
-
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
547 |
-
)
|
548 |
-
cu_seqlens_q = cu_seqlens_k
|
549 |
-
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
550 |
-
indices_q = indices_k
|
551 |
-
elif query_length == 1:
|
552 |
-
max_seqlen_in_batch_q = 1
|
553 |
-
cu_seqlens_q = torch.arange(
|
554 |
-
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
555 |
-
) # There is a memcpy here, that is very bad.
|
556 |
-
indices_q = cu_seqlens_q[:-1]
|
557 |
-
query_layer = query_layer.squeeze(1)
|
558 |
-
else:
|
559 |
-
# The -q_len: slice assumes left padding.
|
560 |
-
padding_mask = padding_mask[:, -query_length:]
|
561 |
-
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, padding_mask)
|
562 |
-
|
563 |
-
return (
|
564 |
-
query_layer,
|
565 |
-
key_layer,
|
566 |
-
value_layer,
|
567 |
-
indices_q,
|
568 |
-
(cu_seqlens_q, cu_seqlens_k),
|
569 |
-
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
570 |
-
)
|
571 |
-
|
572 |
-
|
573 |
class SkyworkDecoderLayer(nn.Module):
|
574 |
def __init__(self, config: SkyworkConfig):
|
575 |
super().__init__()
|
576 |
self.hidden_size = config.hidden_size
|
577 |
-
self.self_attn = (
|
578 |
-
SkyworkAttention(config=config)
|
579 |
-
if not getattr(config, "_flash_attn_2_enabled", False)
|
580 |
-
else SkyworkFlashAttention2(config=config)
|
581 |
-
)
|
582 |
self.mlp = SkyworkMLP(config)
|
583 |
self.input_layernorm = SkyworkRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
584 |
self.post_attention_layernorm = SkyworkRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
@@ -591,7 +426,6 @@ class SkyworkDecoderLayer(nn.Module):
|
|
591 |
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
592 |
output_attentions: Optional[bool] = False,
|
593 |
use_cache: Optional[bool] = False,
|
594 |
-
padding_mask: Optional[torch.LongTensor] = None,
|
595 |
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
596 |
"""
|
597 |
Args:
|
@@ -619,7 +453,6 @@ class SkyworkDecoderLayer(nn.Module):
|
|
619 |
past_key_value=past_key_value,
|
620 |
output_attentions=output_attentions,
|
621 |
use_cache=use_cache,
|
622 |
-
padding_mask=padding_mask,
|
623 |
)
|
624 |
hidden_states = residual + hidden_states
|
625 |
|
@@ -645,7 +478,6 @@ class SkyworkPreTrainedModel(PreTrainedModel):
|
|
645 |
supports_gradient_checkpointing = True
|
646 |
_no_split_modules = ["SkyworkDecoderLayer"]
|
647 |
_skip_keys_device_placement = "past_key_values"
|
648 |
-
_supports_flash_attn_2 = True
|
649 |
|
650 |
def _init_weights(self, module):
|
651 |
std = self.config.initializer_range
|
@@ -735,13 +567,13 @@ class SkyworkModel(SkyworkPreTrainedModel):
|
|
735 |
|
736 |
# retrieve input_ids and inputs_embeds
|
737 |
if input_ids is not None and inputs_embeds is not None:
|
738 |
-
raise ValueError("You cannot specify both
|
739 |
elif input_ids is not None:
|
740 |
batch_size, seq_length = input_ids.shape
|
741 |
elif inputs_embeds is not None:
|
742 |
batch_size, seq_length, _ = inputs_embeds.shape
|
743 |
else:
|
744 |
-
raise ValueError("You have to specify either
|
745 |
|
746 |
seq_length_with_past = seq_length
|
747 |
past_key_values_length = 0
|
@@ -755,7 +587,9 @@ class SkyworkModel(SkyworkPreTrainedModel):
|
|
755 |
position_ids = torch.arange(
|
756 |
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
757 |
)
|
758 |
-
position_ids = position_ids.unsqueeze(0)
|
|
|
|
|
759 |
|
760 |
if inputs_embeds is None:
|
761 |
inputs_embeds = self.embed_tokens(input_ids)
|
@@ -764,13 +598,6 @@ class SkyworkModel(SkyworkPreTrainedModel):
|
|
764 |
attention_mask = torch.ones(
|
765 |
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
766 |
)
|
767 |
-
padding_mask = None
|
768 |
-
else:
|
769 |
-
if 0 in attention_mask:
|
770 |
-
padding_mask = attention_mask
|
771 |
-
else:
|
772 |
-
padding_mask = None
|
773 |
-
|
774 |
attention_mask = self._prepare_decoder_attention_mask(
|
775 |
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
776 |
)
|
@@ -800,12 +627,15 @@ class SkyworkModel(SkyworkPreTrainedModel):
|
|
800 |
def create_custom_forward(module):
|
801 |
def custom_forward(*inputs):
|
802 |
# None for past_key_value
|
803 |
-
return module(*inputs, past_key_value, output_attentions
|
804 |
|
805 |
return custom_forward
|
806 |
|
807 |
layer_outputs = torch.utils.checkpoint.checkpoint(
|
808 |
-
create_custom_forward(decoder_layer),
|
|
|
|
|
|
|
809 |
)
|
810 |
else:
|
811 |
layer_outputs = decoder_layer(
|
@@ -815,7 +645,6 @@ class SkyworkModel(SkyworkPreTrainedModel):
|
|
815 |
past_key_value=past_key_value,
|
816 |
output_attentions=output_attentions,
|
817 |
use_cache=use_cache,
|
818 |
-
padding_mask=padding_mask,
|
819 |
)
|
820 |
|
821 |
hidden_states = layer_outputs[0]
|
@@ -873,7 +702,6 @@ class SkyworkForCausalLM(SkyworkPreTrainedModel):
|
|
873 |
def get_decoder(self):
|
874 |
return self.model
|
875 |
|
876 |
-
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
877 |
def forward(
|
878 |
self,
|
879 |
input_ids: torch.LongTensor = None,
|
@@ -887,31 +715,6 @@ class SkyworkForCausalLM(SkyworkPreTrainedModel):
|
|
887 |
output_hidden_states: Optional[bool] = None,
|
888 |
return_dict: Optional[bool] = None,
|
889 |
) -> Union[Tuple, CausalLMOutputWithPast]:
|
890 |
-
r"""
|
891 |
-
Args:
|
892 |
-
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
893 |
-
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
894 |
-
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
895 |
-
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
896 |
-
|
897 |
-
Returns:
|
898 |
-
|
899 |
-
Example:
|
900 |
-
|
901 |
-
```python
|
902 |
-
>>> from transformers import AutoTokenizer, SkyworkForCausalLM
|
903 |
-
|
904 |
-
>>> model = SkyworkForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
905 |
-
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
906 |
-
|
907 |
-
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
908 |
-
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
909 |
-
|
910 |
-
>>> # Generate
|
911 |
-
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
912 |
-
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
913 |
-
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
914 |
-
```"""
|
915 |
|
916 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
917 |
output_hidden_states = (
|
@@ -1005,6 +808,7 @@ class SkyworkForCausalLM(SkyworkPreTrainedModel):
|
|
1005 |
)
|
1006 |
return reordered_past
|
1007 |
|
|
|
1008 |
class SkyworkForSequenceClassification(SkyworkPreTrainedModel):
|
1009 |
def __init__(self, config):
|
1010 |
super().__init__(config)
|
@@ -1034,12 +838,8 @@ class SkyworkForSequenceClassification(SkyworkPreTrainedModel):
|
|
1034 |
output_hidden_states: Optional[bool] = None,
|
1035 |
return_dict: Optional[bool] = None,
|
1036 |
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1037 |
-
|
1038 |
-
|
1039 |
-
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1040 |
-
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1041 |
-
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1042 |
-
"""
|
1043 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1044 |
|
1045 |
transformer_outputs = self.model(
|
@@ -1108,4 +908,4 @@ class SkyworkForSequenceClassification(SkyworkPreTrainedModel):
|
|
1108 |
past_key_values=transformer_outputs.past_key_values,
|
1109 |
hidden_states=transformer_outputs.hidden_states,
|
1110 |
attentions=transformer_outputs.attentions,
|
1111 |
-
)
|
|
|
1 |
# Copyright (c) SkyworkAI and the HuggingFace Inc. team. All rights reserved.
|
2 |
# This code is built upon Huggingface's transformers repository.
|
3 |
+
|
4 |
import math
|
5 |
from typing import List, Optional, Tuple, Union
|
6 |
|
|
|
13 |
from transformers.activations import ACT2FN
|
14 |
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
15 |
from transformers.modeling_utils import PreTrainedModel
|
16 |
+
from transformers.utils import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
from .configuration_skywork import SkyworkConfig
|
18 |
|
19 |
|
|
|
|
|
|
|
|
|
|
|
20 |
logger = logging.get_logger(__name__)
|
21 |
|
22 |
_CONFIG_FOR_DOC = "SkyworkConfig"
|
23 |
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
26 |
def _make_causal_mask(
|
27 |
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
|
|
72 |
return self.weight * hidden_states.to(input_dtype)
|
73 |
|
74 |
|
75 |
+
class SkyworkRotaryEmbedding(torch.nn.Module):
|
|
|
|
|
|
|
76 |
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
77 |
super().__init__()
|
78 |
|
|
|
94 |
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
95 |
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
96 |
emb = torch.cat((freqs, freqs), dim=-1)
|
97 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
98 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
99 |
|
100 |
def forward(self, x, seq_len=None):
|
101 |
# x: [bs, num_attention_heads, seq_len, head_size]
|
|
|
103 |
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
104 |
|
105 |
return (
|
106 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
107 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
108 |
)
|
109 |
|
110 |
|
|
|
123 |
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
124 |
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
125 |
emb = torch.cat((freqs, freqs), dim=-1)
|
126 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
127 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
128 |
|
129 |
|
130 |
class SkyworkDynamicNTKScalingRotaryEmbedding(SkyworkRotaryEmbedding):
|
|
|
149 |
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
150 |
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
151 |
emb = torch.cat((freqs, freqs), dim=-1)
|
152 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
153 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
class SkyworkNTKScalingRotaryEmbedding(torch.nn.Module):
|
158 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=100, device=None):
|
159 |
+
super().__init__()
|
160 |
+
|
161 |
+
self.dim = dim
|
162 |
+
self.max_position_embeddings = max_position_embeddings
|
163 |
+
self.base = base * scaling_factor
|
164 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
165 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
166 |
+
|
167 |
+
# Build here to make `torch.jit.trace` work.
|
168 |
+
self._set_cos_sin_cache(
|
169 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
170 |
+
)
|
171 |
+
|
172 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
173 |
+
self.max_seq_len_cached = seq_len
|
174 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
175 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
176 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
177 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
178 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
179 |
+
|
180 |
+
def forward(self, x, seq_len=None):
|
181 |
+
if seq_len > self.max_seq_len_cached:
|
182 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
183 |
|
184 |
+
return (
|
185 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
186 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
187 |
+
)
|
188 |
|
189 |
def rotate_half(x):
|
190 |
"""Rotates half the hidden dims of the input."""
|
|
|
193 |
return torch.cat((-x2, x1), dim=-1)
|
194 |
|
195 |
|
|
|
196 |
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
197 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
198 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
199 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
200 |
+
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
201 |
+
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
202 |
q_embed = (q * cos) + (rotate_half(q) * sin)
|
203 |
k_embed = (k * cos) + (rotate_half(k) * sin)
|
204 |
return q_embed, k_embed
|
|
|
269 |
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
270 |
f" and `num_heads`: {self.num_heads})."
|
271 |
)
|
272 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
273 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
274 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
275 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
276 |
self._init_rope()
|
277 |
|
278 |
def _init_rope(self):
|
|
|
299 |
scaling_factor=scaling_factor,
|
300 |
base=self.rope_theta,
|
301 |
)
|
302 |
+
elif scaling_type == "ntk":
|
303 |
+
self.rotary_emb = SkyworkNTKScalingRotaryEmbedding(
|
304 |
+
self.head_dim,
|
305 |
+
max_position_embeddings=self.max_position_embeddings,
|
306 |
+
scaling_factor=scaling_factor,
|
307 |
+
base=self.rope_theta,
|
308 |
+
)
|
309 |
else:
|
310 |
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
311 |
+
print('-'*80)
|
312 |
+
print(f"USING COSTOM MODELING, scaling_type is {scaling_type}, scaling_factor is {scaling_factor}")
|
313 |
+
|
314 |
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
315 |
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
316 |
|
|
|
322 |
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
323 |
output_attentions: bool = False,
|
324 |
use_cache: bool = False,
|
|
|
325 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
326 |
bsz, q_len, _ = hidden_states.size()
|
327 |
|
|
|
364 |
|
365 |
past_key_value = (key_states, value_states) if use_cache else None
|
366 |
|
367 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
368 |
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
369 |
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
370 |
|
|
|
394 |
)
|
395 |
|
396 |
attn_output = attn_output.transpose(1, 2).contiguous()
|
|
|
397 |
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
398 |
|
399 |
if self.config.pretraining_tp > 1:
|
|
|
409 |
return attn_output, attn_weights, past_key_value
|
410 |
|
411 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
412 |
class SkyworkDecoderLayer(nn.Module):
|
413 |
def __init__(self, config: SkyworkConfig):
|
414 |
super().__init__()
|
415 |
self.hidden_size = config.hidden_size
|
416 |
+
self.self_attn = SkyworkAttention(config=config)
|
|
|
|
|
|
|
|
|
417 |
self.mlp = SkyworkMLP(config)
|
418 |
self.input_layernorm = SkyworkRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
419 |
self.post_attention_layernorm = SkyworkRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
|
426 |
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
427 |
output_attentions: Optional[bool] = False,
|
428 |
use_cache: Optional[bool] = False,
|
|
|
429 |
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
430 |
"""
|
431 |
Args:
|
|
|
453 |
past_key_value=past_key_value,
|
454 |
output_attentions=output_attentions,
|
455 |
use_cache=use_cache,
|
|
|
456 |
)
|
457 |
hidden_states = residual + hidden_states
|
458 |
|
|
|
478 |
supports_gradient_checkpointing = True
|
479 |
_no_split_modules = ["SkyworkDecoderLayer"]
|
480 |
_skip_keys_device_placement = "past_key_values"
|
|
|
481 |
|
482 |
def _init_weights(self, module):
|
483 |
std = self.config.initializer_range
|
|
|
567 |
|
568 |
# retrieve input_ids and inputs_embeds
|
569 |
if input_ids is not None and inputs_embeds is not None:
|
570 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
571 |
elif input_ids is not None:
|
572 |
batch_size, seq_length = input_ids.shape
|
573 |
elif inputs_embeds is not None:
|
574 |
batch_size, seq_length, _ = inputs_embeds.shape
|
575 |
else:
|
576 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
577 |
|
578 |
seq_length_with_past = seq_length
|
579 |
past_key_values_length = 0
|
|
|
587 |
position_ids = torch.arange(
|
588 |
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
589 |
)
|
590 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
591 |
+
else:
|
592 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
593 |
|
594 |
if inputs_embeds is None:
|
595 |
inputs_embeds = self.embed_tokens(input_ids)
|
|
|
598 |
attention_mask = torch.ones(
|
599 |
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
600 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
601 |
attention_mask = self._prepare_decoder_attention_mask(
|
602 |
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
603 |
)
|
|
|
627 |
def create_custom_forward(module):
|
628 |
def custom_forward(*inputs):
|
629 |
# None for past_key_value
|
630 |
+
return module(*inputs, past_key_value, output_attentions)
|
631 |
|
632 |
return custom_forward
|
633 |
|
634 |
layer_outputs = torch.utils.checkpoint.checkpoint(
|
635 |
+
create_custom_forward(decoder_layer),
|
636 |
+
hidden_states,
|
637 |
+
attention_mask,
|
638 |
+
position_ids,
|
639 |
)
|
640 |
else:
|
641 |
layer_outputs = decoder_layer(
|
|
|
645 |
past_key_value=past_key_value,
|
646 |
output_attentions=output_attentions,
|
647 |
use_cache=use_cache,
|
|
|
648 |
)
|
649 |
|
650 |
hidden_states = layer_outputs[0]
|
|
|
702 |
def get_decoder(self):
|
703 |
return self.model
|
704 |
|
|
|
705 |
def forward(
|
706 |
self,
|
707 |
input_ids: torch.LongTensor = None,
|
|
|
715 |
output_hidden_states: Optional[bool] = None,
|
716 |
return_dict: Optional[bool] = None,
|
717 |
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
718 |
|
719 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
720 |
output_hidden_states = (
|
|
|
808 |
)
|
809 |
return reordered_past
|
810 |
|
811 |
+
|
812 |
class SkyworkForSequenceClassification(SkyworkPreTrainedModel):
|
813 |
def __init__(self, config):
|
814 |
super().__init__(config)
|
|
|
838 |
output_hidden_states: Optional[bool] = None,
|
839 |
return_dict: Optional[bool] = None,
|
840 |
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
841 |
+
|
842 |
+
|
|
|
|
|
|
|
|
|
843 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
844 |
|
845 |
transformer_outputs = self.model(
|
|
|
908 |
past_key_values=transformer_outputs.past_key_values,
|
909 |
hidden_states=transformer_outputs.hidden_states,
|
910 |
attentions=transformer_outputs.attentions,
|
911 |
+
)
|
pytorch_model-00032-of-00053.bin
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:94d2a7a13be4bb785cdf29f0654109ff58604608141b126a4c3fd2dc40c60188
|
3 |
+
size 301957120
|
requirements.txt
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
tokenizers==0.14.0
|
2 |
transformers==4.34.0
|
3 |
-
flash_attn==2.0.4
|
4 |
torch==2.1.0
|
5 |
peft==0.5.0
|
6 |
-
|
|
|
1 |
tokenizers==0.14.0
|
2 |
transformers==4.34.0
|
|
|
3 |
torch==2.1.0
|
4 |
peft==0.5.0
|
5 |
+
datasets==2.14.1
|
tokenization_skywork.py
CHANGED
@@ -1,22 +1,5 @@
|
|
1 |
-
#
|
2 |
-
#
|
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 |
|
21 |
"""Tokenization classes for Skywork."""
|
22 |
import os
|
|
|
1 |
+
# Copyright (c) SkyworkAI and the HuggingFace Inc. team. All rights reserved.
|
2 |
+
# This code is built upon Huggingface's transformers repository.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
"""Tokenization classes for Skywork."""
|
5 |
import os
|