Upload folder using huggingface_hub
Browse files- README.md +160 -3
- README_ZH.md +156 -0
- logo.png +0 -0
- pretrain/added_tokens.json +3 -0
- pretrain/all_results.json +15 -0
- pretrain/config.json +30 -0
- pretrain/configuration_baichuan.py +69 -0
- pretrain/eval_results.json +10 -0
- pretrain/generation_config.json +14 -0
- pretrain/generation_utils.py +83 -0
- pretrain/modeling_baichuan.py +784 -0
- pretrain/pytorch_model-00001-of-00002.bin +3 -0
- pretrain/pytorch_model-00002-of-00002.bin +3 -0
- pretrain/pytorch_model.bin.index.json +234 -0
- pretrain/quantizer.py +210 -0
- pretrain/special_tokens_map.json +30 -0
- pretrain/tokenization_baichuan.py +251 -0
- pretrain/tokenizer.model +3 -0
- pretrain/tokenizer_config.json +47 -0
- pretrain/train_results.json +8 -0
- pretrain/trainer_state.json +475 -0
- pretrain/training_args.bin +3 -0
- sft/added_tokens.json +3 -0
- sft/config.json +30 -0
- sft/configuration_baichuan.py +69 -0
- sft/generation_config.json +14 -0
- sft/generation_utils.py +83 -0
- sft/modeling_baichuan.py +784 -0
- sft/pytorch_model-00001-of-00002.bin +3 -0
- sft/pytorch_model-00002-of-00002.bin +3 -0
- sft/pytorch_model.bin.index.json +234 -0
- sft/quantizer.py +210 -0
- sft/special_tokens_map.json +30 -0
- sft/tokenization_baichuan.py +251 -0
- sft/tokenizer.model +3 -0
- sft/tokenizer_config.json +47 -0
- sft/trainer_state.json +0 -0
- sft/training_args.bin +3 -0
README.md
CHANGED
@@ -1,3 +1,160 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[**中文**](./README_ZH.md) | [**English**](./README.md)
|
2 |
+
|
3 |
+
<p align="center" width="100%">
|
4 |
+
<a href="https://github.com/daiyizheng/TCMChat" target="_blank"><img src="./logo.png" alt="TCMChat" style="width: 25%; min-width: 300px; display: block; margin: auto;"></a>
|
5 |
+
</p>
|
6 |
+
|
7 |
+
# TCMChat: A Generative Large Language Model for Traditional Chinese Medicine
|
8 |
+
|
9 |
+
[![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](https://github.com/SCIR-HI/Huatuo-Llama-Med-Chinese/blob/main/LICENSE) [![Python 3.10.12](https://img.shields.io/badge/python-3.10.12-blue.svg)](https://www.python.org/downloads/release/python-390/)
|
10 |
+
|
11 |
+
## News
|
12 |
+
|
13 |
+
[2024-5-17] Open source model weight on HuggingFace.
|
14 |
+
|
15 |
+
## Application
|
16 |
+
|
17 |
+
### Install
|
18 |
+
|
19 |
+
```
|
20 |
+
git clone https://github.com/daiyizheng/TCMChat
|
21 |
+
cd TCMChat
|
22 |
+
```
|
23 |
+
First install the dependency package. python environment 3.10+ is recommended.
|
24 |
+
|
25 |
+
```
|
26 |
+
pip install -r requirements.txt
|
27 |
+
```
|
28 |
+
|
29 |
+
### Weights download
|
30 |
+
|
31 |
+
- [TCMChat](https://huggingface.co/daiyizheng/TCMChat): QA and recommendation of TCM knowledge based on baichuan2-7B-Chat.
|
32 |
+
|
33 |
+
### Inference
|
34 |
+
|
35 |
+
#### Command line
|
36 |
+
|
37 |
+
```
|
38 |
+
python cli_infer.py \
|
39 |
+
--model_name_or_path /your/model/path \
|
40 |
+
--model_type chat
|
41 |
+
```
|
42 |
+
|
43 |
+
#### Web demo
|
44 |
+
|
45 |
+
```
|
46 |
+
python gradio_demo.py
|
47 |
+
```
|
48 |
+
|
49 |
+
We provide an online tool:[https://xomics.com.cn/tcmchat](https://xomics.com.cn/tcmchat)
|
50 |
+
|
51 |
+
|
52 |
+
### Retrain
|
53 |
+
|
54 |
+
#### Dataset Download
|
55 |
+
|
56 |
+
- [Pretrain dataset](https://github.com/ZJUFanLab/TCMChat/tree/master/data/pretrain)
|
57 |
+
- [SFT dataset](https://github.com/ZJUFanLab/TCMChat/tree/master/data/sft)
|
58 |
+
- [Benchmark dataset](https://github.com/ZJUFanLab/TCMChat/tree/master/data/evaluate)
|
59 |
+
|
60 |
+
> Note: Currently only sample data is provided. In the near future, we will fully open source the original data.
|
61 |
+
|
62 |
+
|
63 |
+
#### Pre-training
|
64 |
+
|
65 |
+
```shell
|
66 |
+
train_type="pretrain"
|
67 |
+
train_file="data/pretrain/train"
|
68 |
+
validation_file="data/pretrain/test"
|
69 |
+
block_size="1024"
|
70 |
+
deepspeed_dir="data/resources/deepspeed_zero_stage2_config.yml"
|
71 |
+
num_train_epochs="2"
|
72 |
+
export WANDB_PROJECT="TCM-${train_type}"
|
73 |
+
date_time=$(date +"%Y%m%d%H%M%S")
|
74 |
+
run_name="${date_time}_${block_size}"
|
75 |
+
model_name_or_path="your/path/Baichuan2-7B-Chat"
|
76 |
+
output_dir="output/${train_type}/${date_time}_${block_size}"
|
77 |
+
|
78 |
+
|
79 |
+
accelerate launch --config_file ${deepspeed_dir} src/pretraining.py \
|
80 |
+
--model_name_or_path ${model_name_or_path} \
|
81 |
+
--train_file ${train_file} \
|
82 |
+
--validation_file ${validation_file} \
|
83 |
+
--preprocessing_num_workers 20 \
|
84 |
+
--cache_dir ./cache \
|
85 |
+
--block_size ${block_size} \
|
86 |
+
--seed 42 \
|
87 |
+
--do_train \
|
88 |
+
--do_eval \
|
89 |
+
--per_device_train_batch_size 32 \
|
90 |
+
--per_device_eval_batch_size 32 \
|
91 |
+
--num_train_epochs ${num_train_epochs} \
|
92 |
+
--low_cpu_mem_usage True \
|
93 |
+
--torch_dtype bfloat16 \
|
94 |
+
--bf16 \
|
95 |
+
--ddp_find_unused_parameters False \
|
96 |
+
--gradient_checkpointing True \
|
97 |
+
--learning_rate 2e-4 \
|
98 |
+
--warmup_ratio 0.05 \
|
99 |
+
--weight_decay 0.01 \
|
100 |
+
--report_to wandb \
|
101 |
+
--run_name ${run_name} \
|
102 |
+
--logging_dir logs \
|
103 |
+
--logging_strategy steps \
|
104 |
+
--logging_steps 10 \
|
105 |
+
--eval_steps 50 \
|
106 |
+
--evaluation_strategy steps \
|
107 |
+
--save_steps 100 \
|
108 |
+
--save_strategy steps \
|
109 |
+
--save_total_limit 13 \
|
110 |
+
--output_dir ${output_dir} \
|
111 |
+
--overwrite_output_dir
|
112 |
+
```
|
113 |
+
|
114 |
+
#### Fine-tuning
|
115 |
+
|
116 |
+
```shell
|
117 |
+
train_type="SFT"
|
118 |
+
model_max_length="1024"
|
119 |
+
date_time=$(date +"%Y%m%d%H%M%S")
|
120 |
+
data_path="data/sft/sample_train_baichuan_data.json"
|
121 |
+
model_name_or_path="your/path/pretrain"
|
122 |
+
deepspeed_dir="data/resources/deepspeed_zero_stage2_confi_baichuan2.json"
|
123 |
+
export WANDB_PROJECT="TCM-${train_type}"
|
124 |
+
run_name="${train_type}_${date_time}"
|
125 |
+
output_dir="output/${train_type}/${date_time}_${model_max_length}"
|
126 |
+
|
127 |
+
|
128 |
+
deepspeed --hostfile="" src/fine-tune.py \
|
129 |
+
--report_to "wandb" \
|
130 |
+
--run_name ${run_name} \
|
131 |
+
--data_path ${data_path} \
|
132 |
+
--model_name_or_path ${model_name_or_path} \
|
133 |
+
--output_dir ${output_dir} \
|
134 |
+
--model_max_length ${model_max_length} \
|
135 |
+
--num_train_epochs 4 \
|
136 |
+
--per_device_train_batch_size 16 \
|
137 |
+
--gradient_accumulation_steps 1 \
|
138 |
+
--save_strategy epoch \
|
139 |
+
--learning_rate 2e-5 \
|
140 |
+
--lr_scheduler_type constant \
|
141 |
+
--adam_beta1 0.9 \
|
142 |
+
--adam_beta2 0.98 \
|
143 |
+
--adam_epsilon 1e-8 \
|
144 |
+
--max_grad_norm 1.0 \
|
145 |
+
--weight_decay 1e-4 \
|
146 |
+
--warmup_ratio 0.0 \
|
147 |
+
--logging_steps 1 \
|
148 |
+
--gradient_checkpointing True \
|
149 |
+
--deepspeed ${deepspeed_dir} \
|
150 |
+
--bf16 True \
|
151 |
+
--tf32 True
|
152 |
+
```
|
153 |
+
|
154 |
+
### Training details
|
155 |
+
|
156 |
+
Please refer to the experimental section of the paper for instructions.
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
|
README_ZH.md
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[**中文**](./README_ZH.md) | [**English**](./README.md)
|
2 |
+
|
3 |
+
<p align="center" width="100%">
|
4 |
+
<a href="https://github.com/daiyizheng/TCMChat" target="_blank"><img src="./logo.png" alt="TCMChat" style="width: 25%; min-width: 300px; display: block; margin: auto;"></a>
|
5 |
+
</p>
|
6 |
+
|
7 |
+
# TCMChat: Traditional Chinese Medicine Recommendation System based on Large Language Model
|
8 |
+
|
9 |
+
[![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](https://github.com/SCIR-HI/Huatuo-Llama-Med-Chinese/blob/main/LICENSE) [![Python 3.10.12](https://img.shields.io/badge/python-3.10.12-blue.svg)](https://www.python.org/downloads/release/python-390/)
|
10 |
+
|
11 |
+
## 新闻
|
12 |
+
|
13 |
+
[2024-5-17] huggingface 开源模型权重
|
14 |
+
|
15 |
+
## 应用
|
16 |
+
|
17 |
+
### 安装
|
18 |
+
|
19 |
+
```
|
20 |
+
git clone https://github.com/daiyizheng/TCMChat
|
21 |
+
cd TCMChat
|
22 |
+
```
|
23 |
+
|
24 |
+
首先安装依赖包,python环境建议3.10+
|
25 |
+
|
26 |
+
```
|
27 |
+
pip install -r requirements.txt
|
28 |
+
```
|
29 |
+
|
30 |
+
### 权重下载
|
31 |
+
|
32 |
+
- [TCMChat](https://huggingface.co/daiyizheng/TCMChat): 基于baichuan2-7B-Chat的中药、方剂知识问答与推荐。
|
33 |
+
|
34 |
+
### 推理
|
35 |
+
|
36 |
+
#### 命令行测试
|
37 |
+
|
38 |
+
```
|
39 |
+
python cli_infer.py \
|
40 |
+
--model_name_or_path /your/model/path \
|
41 |
+
--model_type chat
|
42 |
+
```
|
43 |
+
|
44 |
+
#### Web页面测试
|
45 |
+
|
46 |
+
```
|
47 |
+
python gradio_demo.py
|
48 |
+
```
|
49 |
+
|
50 |
+
我们提供了一个在线的体验工具:[https://xomics.com.cn/tcmchat](https://xomics.com.cn/tcmchat)
|
51 |
+
|
52 |
+
|
53 |
+
### 重新训练
|
54 |
+
#### 数据集下载
|
55 |
+
|
56 |
+
- [预训练数据](https://github.com/ZJUFanLab/TCMChat/tree/master/data/pretrain)
|
57 |
+
- [微调数据](https://github.com/ZJUFanLab/TCMChat/tree/master/data/sft)
|
58 |
+
- [基准评测数据](https://github.com/ZJUFanLab/TCMChat/tree/master/data/evaluate)
|
59 |
+
|
60 |
+
> 注意:目前只提供样例数据,不久将来,我们将完全开源原始数据
|
61 |
+
|
62 |
+
|
63 |
+
#### 预训练
|
64 |
+
|
65 |
+
```shell
|
66 |
+
train_type="pretrain"
|
67 |
+
train_file="data/pretrain/train"
|
68 |
+
validation_file="data/pretrain/test"
|
69 |
+
block_size="1024"
|
70 |
+
deepspeed_dir="data/resources/deepspeed_zero_stage2_config.yml"
|
71 |
+
num_train_epochs="2"
|
72 |
+
export WANDB_PROJECT="TCM-${train_type}"
|
73 |
+
date_time=$(date +"%Y%m%d%H%M%S")
|
74 |
+
run_name="${date_time}_${block_size}"
|
75 |
+
model_name_or_path="your/path/Baichuan2-7B-Chat"
|
76 |
+
output_dir="output/${train_type}/${date_time}_${block_size}"
|
77 |
+
|
78 |
+
|
79 |
+
accelerate launch --config_file ${deepspeed_dir} src/pretraining.py \
|
80 |
+
--model_name_or_path ${model_name_or_path} \
|
81 |
+
--train_file ${train_file} \
|
82 |
+
--validation_file ${validation_file} \
|
83 |
+
--preprocessing_num_workers 20 \
|
84 |
+
--cache_dir ./cache \
|
85 |
+
--block_size ${block_size} \
|
86 |
+
--seed 42 \
|
87 |
+
--do_train \
|
88 |
+
--do_eval \
|
89 |
+
--per_device_train_batch_size 32 \
|
90 |
+
--per_device_eval_batch_size 32 \
|
91 |
+
--num_train_epochs ${num_train_epochs} \
|
92 |
+
--low_cpu_mem_usage True \
|
93 |
+
--torch_dtype bfloat16 \
|
94 |
+
--bf16 \
|
95 |
+
--ddp_find_unused_parameters False \
|
96 |
+
--gradient_checkpointing True \
|
97 |
+
--learning_rate 2e-4 \
|
98 |
+
--warmup_ratio 0.05 \
|
99 |
+
--weight_decay 0.01 \
|
100 |
+
--report_to wandb \
|
101 |
+
--run_name ${run_name} \
|
102 |
+
--logging_dir logs \
|
103 |
+
--logging_strategy steps \
|
104 |
+
--logging_steps 10 \
|
105 |
+
--eval_steps 50 \
|
106 |
+
--evaluation_strategy steps \
|
107 |
+
--save_steps 100 \
|
108 |
+
--save_strategy steps \
|
109 |
+
--save_total_limit 13 \
|
110 |
+
--output_dir ${output_dir} \
|
111 |
+
--overwrite_output_dir
|
112 |
+
```
|
113 |
+
|
114 |
+
#### 微调
|
115 |
+
```shell
|
116 |
+
train_type="SFT"
|
117 |
+
model_max_length="1024"
|
118 |
+
date_time=$(date +"%Y%m%d%H%M%S")
|
119 |
+
data_path="data/sft/sample_train_baichuan_data.json"
|
120 |
+
model_name_or_path="your/path/pretrain"
|
121 |
+
deepspeed_dir="data/resources/deepspeed_zero_stage2_confi_baichuan2.json"
|
122 |
+
export WANDB_PROJECT="TCM-${train_type}"
|
123 |
+
run_name="${train_type}_${date_time}"
|
124 |
+
output_dir="output/${train_type}/${date_time}_${model_max_length}"
|
125 |
+
|
126 |
+
|
127 |
+
deepspeed --hostfile="" src/fine-tune.py \
|
128 |
+
--report_to "wandb" \
|
129 |
+
--run_name ${run_name} \
|
130 |
+
--data_path ${data_path} \
|
131 |
+
--model_name_or_path ${model_name_or_path} \
|
132 |
+
--output_dir ${output_dir} \
|
133 |
+
--model_max_length ${model_max_length} \
|
134 |
+
--num_train_epochs 4 \
|
135 |
+
--per_device_train_batch_size 16 \
|
136 |
+
--gradient_accumulation_steps 1 \
|
137 |
+
--save_strategy epoch \
|
138 |
+
--learning_rate 2e-5 \
|
139 |
+
--lr_scheduler_type constant \
|
140 |
+
--adam_beta1 0.9 \
|
141 |
+
--adam_beta2 0.98 \
|
142 |
+
--adam_epsilon 1e-8 \
|
143 |
+
--max_grad_norm 1.0 \
|
144 |
+
--weight_decay 1e-4 \
|
145 |
+
--warmup_ratio 0.0 \
|
146 |
+
--logging_steps 1 \
|
147 |
+
--gradient_checkpointing True \
|
148 |
+
--deepspeed ${deepspeed_dir} \
|
149 |
+
--bf16 True \
|
150 |
+
--tf32 True
|
151 |
+
```
|
152 |
+
|
153 |
+
### 训练细节
|
154 |
+
|
155 |
+
请参考论文实验部分说明。
|
156 |
+
|
logo.png
ADDED
pretrain/added_tokens.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<pad>": 125696
|
3 |
+
}
|
pretrain/all_results.json
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"epoch": 0.5,
|
3 |
+
"eval_accuracy": 0.5588218971620847,
|
4 |
+
"eval_loss": 3.2893426418304443,
|
5 |
+
"eval_runtime": 31.972,
|
6 |
+
"eval_samples": 2008,
|
7 |
+
"eval_samples_per_second": 62.805,
|
8 |
+
"eval_steps_per_second": 0.25,
|
9 |
+
"perplexity": 26.825224078575424,
|
10 |
+
"train_loss": 1.8579450334821428,
|
11 |
+
"train_runtime": 7071.4809,
|
12 |
+
"train_samples": 300760,
|
13 |
+
"train_samples_per_second": 21.266,
|
14 |
+
"train_steps_per_second": 0.083
|
15 |
+
}
|
pretrain/config.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"_name_or_path": "/slurm/home/yrd/shaolab/daiyizheng/resources/hf_weights/baichuan/Baichuan2-7B-Chat",
|
4 |
+
"architectures": [
|
5 |
+
"BaichuanForCausalLM"
|
6 |
+
],
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_baichuan.BaichuanConfig",
|
9 |
+
"AutoModelForCausalLM": "modeling_baichuan.BaichuanForCausalLM"
|
10 |
+
},
|
11 |
+
"bos_token_id": 1,
|
12 |
+
"eos_token_id": 2,
|
13 |
+
"hidden_act": "silu",
|
14 |
+
"hidden_size": 4096,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 11008,
|
17 |
+
"max_position_embeddings": 4096,
|
18 |
+
"model_max_length": 4096,
|
19 |
+
"model_type": "baichuan",
|
20 |
+
"num_attention_heads": 32,
|
21 |
+
"num_hidden_layers": 32,
|
22 |
+
"pad_token_id": 0,
|
23 |
+
"rms_norm_eps": 1e-06,
|
24 |
+
"tie_word_embeddings": false,
|
25 |
+
"torch_dtype": "bfloat16",
|
26 |
+
"transformers_version": "4.33.1",
|
27 |
+
"use_cache": false,
|
28 |
+
"vocab_size": 125696,
|
29 |
+
"z_loss_weight": 0
|
30 |
+
}
|
pretrain/configuration_baichuan.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
2 |
+
|
3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
+
# and OPT implementations in this library. It has been modified from its
|
7 |
+
# original forms to accommodate minor architectural differences compared
|
8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
+
#
|
10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
+
# you may not use this file except in compliance with the License.
|
12 |
+
# You may obtain a copy of the License at
|
13 |
+
#
|
14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
+
#
|
16 |
+
# Unless required by applicable law or agreed to in writing, software
|
17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
+
# See the License for the specific language governing permissions and
|
20 |
+
# limitations under the License.
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.utils import logging
|
24 |
+
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__)
|
27 |
+
|
28 |
+
|
29 |
+
class BaichuanConfig(PretrainedConfig):
|
30 |
+
model_type = "baichuan"
|
31 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
32 |
+
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
vocab_size=125696,
|
36 |
+
hidden_size=4096,
|
37 |
+
intermediate_size=11008,
|
38 |
+
num_hidden_layers=32,
|
39 |
+
num_attention_heads=32,
|
40 |
+
hidden_act="silu",
|
41 |
+
max_position_embeddings=4096,
|
42 |
+
initializer_range=0.02,
|
43 |
+
rms_norm_eps=1e-6,
|
44 |
+
use_cache=True,
|
45 |
+
pad_token_id=0,
|
46 |
+
bos_token_id=1,
|
47 |
+
eos_token_id=2,
|
48 |
+
tie_word_embeddings=False,
|
49 |
+
z_loss_weight=0,
|
50 |
+
**kwargs,
|
51 |
+
):
|
52 |
+
self.vocab_size = vocab_size
|
53 |
+
self.max_position_embeddings = max_position_embeddings
|
54 |
+
self.hidden_size = hidden_size
|
55 |
+
self.intermediate_size = intermediate_size
|
56 |
+
self.num_hidden_layers = num_hidden_layers
|
57 |
+
self.num_attention_heads = num_attention_heads
|
58 |
+
self.hidden_act = hidden_act
|
59 |
+
self.initializer_range = initializer_range
|
60 |
+
self.rms_norm_eps = rms_norm_eps
|
61 |
+
self.use_cache = use_cache
|
62 |
+
self.z_loss_weight = z_loss_weight
|
63 |
+
super().__init__(
|
64 |
+
pad_token_id=pad_token_id,
|
65 |
+
bos_token_id=bos_token_id,
|
66 |
+
eos_token_id=eos_token_id,
|
67 |
+
tie_word_embeddings=tie_word_embeddings,
|
68 |
+
**kwargs,
|
69 |
+
)
|
pretrain/eval_results.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"epoch": 0.5,
|
3 |
+
"eval_accuracy": 0.5588218971620847,
|
4 |
+
"eval_loss": 3.2893426418304443,
|
5 |
+
"eval_runtime": 31.972,
|
6 |
+
"eval_samples": 2008,
|
7 |
+
"eval_samples_per_second": 62.805,
|
8 |
+
"eval_steps_per_second": 0.25,
|
9 |
+
"perplexity": 26.825224078575424
|
10 |
+
}
|
pretrain/generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"assistant_token_id": 196,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"do_sample": true,
|
5 |
+
"eos_token_id": 2,
|
6 |
+
"max_new_tokens": 2048,
|
7 |
+
"pad_token_id": 0,
|
8 |
+
"repetition_penalty": 1.05,
|
9 |
+
"temperature": 0.3,
|
10 |
+
"top_k": 5,
|
11 |
+
"top_p": 0.85,
|
12 |
+
"transformers_version": "4.33.1",
|
13 |
+
"user_token_id": 195
|
14 |
+
}
|
pretrain/generation_utils.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List
|
2 |
+
from queue import Queue
|
3 |
+
|
4 |
+
import torch
|
5 |
+
|
6 |
+
|
7 |
+
def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
|
8 |
+
def _parse_messages(messages, split_role="user"):
|
9 |
+
system, rounds = "", []
|
10 |
+
round = []
|
11 |
+
for i, message in enumerate(messages):
|
12 |
+
if message["role"] == "system":
|
13 |
+
assert i == 0
|
14 |
+
system = message["content"]
|
15 |
+
continue
|
16 |
+
if message["role"] == split_role and round:
|
17 |
+
rounds.append(round)
|
18 |
+
round = []
|
19 |
+
round.append(message)
|
20 |
+
if round:
|
21 |
+
rounds.append(round)
|
22 |
+
return system, rounds
|
23 |
+
|
24 |
+
max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
|
25 |
+
max_input_tokens = model.config.model_max_length - max_new_tokens
|
26 |
+
system, rounds = _parse_messages(messages, split_role="user")
|
27 |
+
system_tokens = tokenizer.encode(system)
|
28 |
+
max_history_tokens = max_input_tokens - len(system_tokens)
|
29 |
+
|
30 |
+
history_tokens = []
|
31 |
+
for round in rounds[::-1]:
|
32 |
+
round_tokens = []
|
33 |
+
for message in round:
|
34 |
+
if message["role"] == "user":
|
35 |
+
round_tokens.append(model.generation_config.user_token_id)
|
36 |
+
else:
|
37 |
+
round_tokens.append(model.generation_config.assistant_token_id)
|
38 |
+
round_tokens.extend(tokenizer.encode(message["content"]))
|
39 |
+
if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:
|
40 |
+
history_tokens = round_tokens + history_tokens # concat left
|
41 |
+
if len(history_tokens) < max_history_tokens:
|
42 |
+
continue
|
43 |
+
break
|
44 |
+
|
45 |
+
input_tokens = system_tokens + history_tokens
|
46 |
+
if messages[-1]["role"] != "assistant":
|
47 |
+
input_tokens.append(model.generation_config.assistant_token_id)
|
48 |
+
input_tokens = input_tokens[-max_input_tokens:] # truncate left
|
49 |
+
return torch.LongTensor([input_tokens]).to(model.device)
|
50 |
+
|
51 |
+
|
52 |
+
class TextIterStreamer:
|
53 |
+
def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):
|
54 |
+
self.tokenizer = tokenizer
|
55 |
+
self.skip_prompt = skip_prompt
|
56 |
+
self.skip_special_tokens = skip_special_tokens
|
57 |
+
self.tokens = []
|
58 |
+
self.text_queue = Queue()
|
59 |
+
self.next_tokens_are_prompt = True
|
60 |
+
|
61 |
+
def put(self, value):
|
62 |
+
if self.skip_prompt and self.next_tokens_are_prompt:
|
63 |
+
self.next_tokens_are_prompt = False
|
64 |
+
else:
|
65 |
+
if len(value.shape) > 1:
|
66 |
+
value = value[0]
|
67 |
+
self.tokens.extend(value.tolist())
|
68 |
+
self.text_queue.put(
|
69 |
+
self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))
|
70 |
+
|
71 |
+
def end(self):
|
72 |
+
self.text_queue.put(None)
|
73 |
+
|
74 |
+
def __iter__(self):
|
75 |
+
return self
|
76 |
+
|
77 |
+
def __next__(self):
|
78 |
+
value = self.text_queue.get()
|
79 |
+
if value is None:
|
80 |
+
raise StopIteration()
|
81 |
+
else:
|
82 |
+
return value
|
83 |
+
|
pretrain/modeling_baichuan.py
ADDED
@@ -0,0 +1,784 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
2 |
+
|
3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
+
# and OPT implementations in this library. It has been modified from its
|
7 |
+
# original forms to accommodate minor architectural differences compared
|
8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
+
#
|
10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
+
# you may not use this file except in compliance with the License.
|
12 |
+
# You may obtain a copy of the License at
|
13 |
+
#
|
14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
+
#
|
16 |
+
# Unless required by applicable law or agreed to in writing, software
|
17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
+
# See the License for the specific language governing permissions and
|
20 |
+
# limitations under the License.
|
21 |
+
|
22 |
+
|
23 |
+
from .configuration_baichuan import BaichuanConfig
|
24 |
+
from .generation_utils import build_chat_input, TextIterStreamer
|
25 |
+
|
26 |
+
import math
|
27 |
+
from typing import List, Optional, Tuple, Union
|
28 |
+
from threading import Thread
|
29 |
+
|
30 |
+
import torch
|
31 |
+
import torch.utils.checkpoint
|
32 |
+
from torch import nn
|
33 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
34 |
+
from torch.nn import functional as F
|
35 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
36 |
+
from transformers.activations import ACT2FN
|
37 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
38 |
+
from transformers.generation.utils import GenerationConfig
|
39 |
+
from transformers.utils import logging, ContextManagers
|
40 |
+
|
41 |
+
import os
|
42 |
+
from contextlib import contextmanager
|
43 |
+
logger = logging.get_logger(__name__)
|
44 |
+
|
45 |
+
try:
|
46 |
+
from xformers import ops as xops
|
47 |
+
except ImportError:
|
48 |
+
xops = None
|
49 |
+
logger.warning(
|
50 |
+
"Xformers is not installed correctly. If you want to use memory_efficient_attention to accelerate training use the following command to install Xformers\npip install xformers."
|
51 |
+
)
|
52 |
+
|
53 |
+
|
54 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
55 |
+
def _make_causal_mask(
|
56 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
57 |
+
):
|
58 |
+
"""
|
59 |
+
Make causal mask used for bi-directional self-attention.
|
60 |
+
"""
|
61 |
+
bsz, tgt_len = input_ids_shape
|
62 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
63 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
64 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
65 |
+
mask = mask.to(dtype)
|
66 |
+
|
67 |
+
if past_key_values_length > 0:
|
68 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
69 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
70 |
+
|
71 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
72 |
+
"""
|
73 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
74 |
+
"""
|
75 |
+
if len(mask.size()) == 3:
|
76 |
+
bsz, src_len, _ = mask.size()
|
77 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
78 |
+
expanded_mask = mask[:,None,:,:].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
79 |
+
else:
|
80 |
+
bsz, src_len = mask.size()
|
81 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
82 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
83 |
+
|
84 |
+
inverted_mask = 1.0 - expanded_mask
|
85 |
+
|
86 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
87 |
+
|
88 |
+
|
89 |
+
class RMSNorm(nn.Module):
|
90 |
+
def __init__(self, hidden_size, eps=1e-6):
|
91 |
+
"""
|
92 |
+
RMSNorm is equivalent to T5LayerNorm
|
93 |
+
"""
|
94 |
+
super().__init__()
|
95 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
96 |
+
self.variance_epsilon = eps
|
97 |
+
|
98 |
+
def forward(self, hidden_states):
|
99 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
100 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
101 |
+
|
102 |
+
# convert into half-precision if necessary
|
103 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
104 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
105 |
+
|
106 |
+
return self.weight * hidden_states
|
107 |
+
|
108 |
+
|
109 |
+
class RotaryEmbedding(torch.nn.Module):
|
110 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
111 |
+
super().__init__()
|
112 |
+
self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
113 |
+
self.max_seq_len_cached = max_position_embeddings
|
114 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
115 |
+
freqs = torch.outer(t, self.inv_freq)
|
116 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
117 |
+
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32)
|
118 |
+
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32)
|
119 |
+
def forward(self, x, seq_len=None):
|
120 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
121 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
122 |
+
if seq_len > self.max_seq_len_cached:
|
123 |
+
self.max_seq_len_cached = seq_len
|
124 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
125 |
+
freqs = torch.outer(t, self.inv_freq)
|
126 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
127 |
+
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32).to(x.device)
|
128 |
+
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32).to(x.device)
|
129 |
+
elif self.cos_cached.device != x.device:
|
130 |
+
self.cos_cached = self.cos_cached.to(x.device)
|
131 |
+
self.sin_cached = self.sin_cached.to(x.device)
|
132 |
+
return (
|
133 |
+
self.cos_cached[:, :, :seq_len, ...],
|
134 |
+
self.sin_cached[:, :, :seq_len, ...],
|
135 |
+
)
|
136 |
+
|
137 |
+
|
138 |
+
def rotate_half(x):
|
139 |
+
"""Rotates half the hidden dims of the input."""
|
140 |
+
x1 = x[..., : x.shape[-1] // 2]
|
141 |
+
x2 = x[..., x.shape[-1] // 2:]
|
142 |
+
return torch.cat((-x2, x1), dim=-1)
|
143 |
+
|
144 |
+
|
145 |
+
def apply_rotary_pos_emb(q, k, cos_, sin_, position_ids):
|
146 |
+
cos = cos_.squeeze(1).squeeze(0) # [seq_len, dim]
|
147 |
+
sin = sin_.squeeze(1).squeeze(0) # [seq_len, dim]
|
148 |
+
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
149 |
+
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
150 |
+
q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
|
151 |
+
k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
|
152 |
+
return q_embed.to(q.dtype), k_embed.to(k.dtype)
|
153 |
+
|
154 |
+
|
155 |
+
class MLP(nn.Module):
|
156 |
+
def __init__(
|
157 |
+
self,
|
158 |
+
hidden_size: int,
|
159 |
+
intermediate_size: int,
|
160 |
+
hidden_act: str,
|
161 |
+
):
|
162 |
+
super().__init__()
|
163 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
164 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
165 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
166 |
+
self.act_fn = ACT2FN[hidden_act]
|
167 |
+
|
168 |
+
def forward(self, x):
|
169 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
170 |
+
|
171 |
+
|
172 |
+
class Attention(nn.Module):
|
173 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
174 |
+
def __init__(self, config: BaichuanConfig):
|
175 |
+
super().__init__()
|
176 |
+
self.config = config
|
177 |
+
self.hidden_size = config.hidden_size
|
178 |
+
self.num_heads = config.num_attention_heads
|
179 |
+
self.head_dim = self.hidden_size // self.num_heads
|
180 |
+
self.max_position_embeddings = config.max_position_embeddings
|
181 |
+
|
182 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
183 |
+
raise ValueError(
|
184 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
185 |
+
f" and `num_heads`: {self.num_heads})."
|
186 |
+
)
|
187 |
+
self.W_pack = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
|
188 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
189 |
+
self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
190 |
+
|
191 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
192 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
193 |
+
|
194 |
+
def forward(
|
195 |
+
self,
|
196 |
+
hidden_states: torch.Tensor,
|
197 |
+
attention_mask: Optional[torch.Tensor] = None,
|
198 |
+
position_ids: Optional[torch.LongTensor] = None,
|
199 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
200 |
+
output_attentions: bool = False,
|
201 |
+
use_cache: bool = False,
|
202 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
203 |
+
bsz, q_len, _ = hidden_states.size()
|
204 |
+
|
205 |
+
proj = self.W_pack(hidden_states)
|
206 |
+
proj = proj.unflatten(-1, (3, self.hidden_size)).unsqueeze(0).transpose(0, -2).squeeze(-2)
|
207 |
+
query_states = proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
208 |
+
key_states = proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
209 |
+
value_states = proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
210 |
+
|
211 |
+
kv_seq_len = key_states.shape[-2]
|
212 |
+
if past_key_value is not None:
|
213 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
214 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
215 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
216 |
+
# [bsz, nh, t, hd]
|
217 |
+
|
218 |
+
if past_key_value is not None:
|
219 |
+
# reuse k, v, self_attention
|
220 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
221 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
222 |
+
|
223 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
224 |
+
if xops is not None and self.training:
|
225 |
+
attn_weights = None
|
226 |
+
query_states = query_states.transpose(1, 2)
|
227 |
+
key_states = key_states.transpose(1, 2)
|
228 |
+
value_states = value_states.transpose(1, 2)
|
229 |
+
attn_output = xops.memory_efficient_attention(
|
230 |
+
query_states, key_states, value_states, attn_bias=xops.LowerTriangularMask()
|
231 |
+
)
|
232 |
+
else:
|
233 |
+
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
|
234 |
+
attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
|
235 |
+
attn_output = attn_output.transpose(1, 2)
|
236 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
237 |
+
attn_output = self.o_proj(attn_output)
|
238 |
+
|
239 |
+
if not output_attentions:
|
240 |
+
attn_weights = None
|
241 |
+
|
242 |
+
return attn_output, attn_weights, past_key_value
|
243 |
+
|
244 |
+
|
245 |
+
class DecoderLayer(nn.Module):
|
246 |
+
def __init__(self, config: BaichuanConfig):
|
247 |
+
super().__init__()
|
248 |
+
self.hidden_size = config.hidden_size
|
249 |
+
self.self_attn = Attention(config=config)
|
250 |
+
self.mlp = MLP(
|
251 |
+
hidden_size=self.hidden_size,
|
252 |
+
intermediate_size=config.intermediate_size,
|
253 |
+
hidden_act=config.hidden_act,
|
254 |
+
)
|
255 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
256 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
257 |
+
|
258 |
+
def forward(
|
259 |
+
self,
|
260 |
+
hidden_states: torch.Tensor,
|
261 |
+
attention_mask: Optional[torch.Tensor] = None,
|
262 |
+
position_ids: Optional[torch.LongTensor] = None,
|
263 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
264 |
+
output_attentions: Optional[bool] = False,
|
265 |
+
use_cache: Optional[bool] = False,
|
266 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
267 |
+
|
268 |
+
residual = hidden_states
|
269 |
+
|
270 |
+
hidden_states = self.input_layernorm(hidden_states)
|
271 |
+
|
272 |
+
# Self Attention
|
273 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
274 |
+
hidden_states=hidden_states,
|
275 |
+
attention_mask=attention_mask,
|
276 |
+
position_ids=position_ids,
|
277 |
+
past_key_value=past_key_value,
|
278 |
+
output_attentions=output_attentions,
|
279 |
+
use_cache=use_cache,
|
280 |
+
)
|
281 |
+
hidden_states = residual + hidden_states
|
282 |
+
|
283 |
+
# Fully Connected
|
284 |
+
residual = hidden_states
|
285 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
286 |
+
hidden_states = self.mlp(hidden_states)
|
287 |
+
hidden_states = residual + hidden_states
|
288 |
+
|
289 |
+
outputs = (hidden_states,)
|
290 |
+
|
291 |
+
if output_attentions:
|
292 |
+
outputs += (self_attn_weights,)
|
293 |
+
|
294 |
+
if use_cache:
|
295 |
+
outputs += (present_key_value,)
|
296 |
+
|
297 |
+
return outputs
|
298 |
+
|
299 |
+
|
300 |
+
class BaichuanPreTrainedModel(PreTrainedModel):
|
301 |
+
config_class = BaichuanConfig
|
302 |
+
base_model_prefix = "model"
|
303 |
+
supports_gradient_checkpointing = True
|
304 |
+
_no_split_modules = ["DecoderLayer"]
|
305 |
+
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
306 |
+
|
307 |
+
def _init_weights(self, module):
|
308 |
+
std = self.config.initializer_range
|
309 |
+
if isinstance(module, nn.Linear):
|
310 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
311 |
+
if module.bias is not None:
|
312 |
+
module.bias.data.zero_()
|
313 |
+
elif isinstance(module, nn.Embedding):
|
314 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
315 |
+
if module.padding_idx is not None:
|
316 |
+
module.weight.data[module.padding_idx].zero_()
|
317 |
+
|
318 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
319 |
+
if isinstance(module, BaichuanModel):
|
320 |
+
module.gradient_checkpointing = value
|
321 |
+
|
322 |
+
|
323 |
+
class BaichuanModel(BaichuanPreTrainedModel):
|
324 |
+
def __init__(self, config: BaichuanConfig):
|
325 |
+
super().__init__(config)
|
326 |
+
self.padding_idx = config.pad_token_id
|
327 |
+
self.vocab_size = config.vocab_size
|
328 |
+
|
329 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
330 |
+
self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
331 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
332 |
+
|
333 |
+
self.gradient_checkpointing = False
|
334 |
+
# Initialize weights and apply final processing
|
335 |
+
self.post_init()
|
336 |
+
|
337 |
+
def get_input_embeddings(self):
|
338 |
+
return self.embed_tokens
|
339 |
+
|
340 |
+
def set_input_embeddings(self, value):
|
341 |
+
self.embed_tokens = value
|
342 |
+
|
343 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
344 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
345 |
+
# create causal mask
|
346 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
347 |
+
combined_attention_mask = None
|
348 |
+
if input_shape[-1] > 1:
|
349 |
+
combined_attention_mask = _make_causal_mask(
|
350 |
+
input_shape,
|
351 |
+
inputs_embeds.dtype,
|
352 |
+
device=inputs_embeds.device,
|
353 |
+
past_key_values_length=past_key_values_length,
|
354 |
+
)
|
355 |
+
|
356 |
+
if attention_mask is not None:
|
357 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
358 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
359 |
+
inputs_embeds.device
|
360 |
+
)
|
361 |
+
combined_attention_mask = (
|
362 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
363 |
+
)
|
364 |
+
|
365 |
+
return combined_attention_mask
|
366 |
+
|
367 |
+
def forward(
|
368 |
+
self,
|
369 |
+
input_ids: torch.LongTensor = None,
|
370 |
+
attention_mask: Optional[torch.Tensor] = None,
|
371 |
+
position_ids: Optional[torch.LongTensor] = None,
|
372 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
373 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
374 |
+
use_cache: Optional[bool] = None,
|
375 |
+
output_attentions: Optional[bool] = None,
|
376 |
+
output_hidden_states: Optional[bool] = None,
|
377 |
+
return_dict: Optional[bool] = None,
|
378 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
379 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
380 |
+
output_hidden_states = (
|
381 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
382 |
+
)
|
383 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
384 |
+
|
385 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
386 |
+
|
387 |
+
# retrieve input_ids and inputs_embeds
|
388 |
+
if input_ids is not None and inputs_embeds is not None:
|
389 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
390 |
+
elif input_ids is not None:
|
391 |
+
batch_size, seq_length = input_ids.shape
|
392 |
+
elif inputs_embeds is not None:
|
393 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
394 |
+
else:
|
395 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
396 |
+
|
397 |
+
seq_length_with_past = seq_length
|
398 |
+
past_key_values_length = 0
|
399 |
+
|
400 |
+
if past_key_values is not None:
|
401 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
402 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
403 |
+
|
404 |
+
if position_ids is None:
|
405 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
406 |
+
position_ids = torch.arange(
|
407 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
408 |
+
)
|
409 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
410 |
+
else:
|
411 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
412 |
+
|
413 |
+
if inputs_embeds is None:
|
414 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
415 |
+
# embed positions
|
416 |
+
if attention_mask is None:
|
417 |
+
attention_mask = torch.ones(
|
418 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
419 |
+
)
|
420 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
421 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
422 |
+
)
|
423 |
+
|
424 |
+
hidden_states = inputs_embeds
|
425 |
+
|
426 |
+
if self.gradient_checkpointing and self.training:
|
427 |
+
if use_cache:
|
428 |
+
logger.warning_once(
|
429 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
430 |
+
)
|
431 |
+
use_cache = False
|
432 |
+
|
433 |
+
# decoder layers
|
434 |
+
all_hidden_states = () if output_hidden_states else None
|
435 |
+
all_self_attns = () if output_attentions else None
|
436 |
+
next_decoder_cache = () if use_cache else None
|
437 |
+
|
438 |
+
for idx, decoder_layer in enumerate(self.layers):
|
439 |
+
if output_hidden_states:
|
440 |
+
all_hidden_states += (hidden_states,)
|
441 |
+
|
442 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
443 |
+
|
444 |
+
if self.gradient_checkpointing and self.training:
|
445 |
+
|
446 |
+
def create_custom_forward(module):
|
447 |
+
def custom_forward(*inputs):
|
448 |
+
# None for past_key_value
|
449 |
+
return module(*inputs, output_attentions, None)
|
450 |
+
|
451 |
+
return custom_forward
|
452 |
+
|
453 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
454 |
+
create_custom_forward(decoder_layer),
|
455 |
+
hidden_states,
|
456 |
+
attention_mask,
|
457 |
+
position_ids,
|
458 |
+
None,
|
459 |
+
)
|
460 |
+
else:
|
461 |
+
layer_outputs = decoder_layer(
|
462 |
+
hidden_states,
|
463 |
+
attention_mask=attention_mask,
|
464 |
+
position_ids=position_ids,
|
465 |
+
past_key_value=past_key_value,
|
466 |
+
output_attentions=output_attentions,
|
467 |
+
use_cache=use_cache,
|
468 |
+
)
|
469 |
+
|
470 |
+
hidden_states = layer_outputs[0]
|
471 |
+
|
472 |
+
if use_cache:
|
473 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
474 |
+
|
475 |
+
if output_attentions:
|
476 |
+
all_self_attns += (layer_outputs[1],)
|
477 |
+
|
478 |
+
hidden_states = self.norm(hidden_states)
|
479 |
+
|
480 |
+
# add hidden states from the last decoder layer
|
481 |
+
if output_hidden_states:
|
482 |
+
all_hidden_states += (hidden_states,)
|
483 |
+
|
484 |
+
next_cache = next_decoder_cache if use_cache else None
|
485 |
+
if not return_dict:
|
486 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
487 |
+
return BaseModelOutputWithPast(
|
488 |
+
last_hidden_state=hidden_states,
|
489 |
+
past_key_values=next_cache,
|
490 |
+
hidden_states=all_hidden_states,
|
491 |
+
attentions=all_self_attns,
|
492 |
+
)
|
493 |
+
|
494 |
+
|
495 |
+
class NormHead(nn.Module):
|
496 |
+
def __init__(self, hidden_size, vocab_size, bias=False):
|
497 |
+
super().__init__()
|
498 |
+
self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
|
499 |
+
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
500 |
+
self.first_flag = True
|
501 |
+
|
502 |
+
def forward(self, hidden_states):
|
503 |
+
if self.training:
|
504 |
+
norm_weight = nn.functional.normalize(self.weight)
|
505 |
+
elif self.first_flag:
|
506 |
+
self.first_flag = False
|
507 |
+
self.weight.data = nn.functional.normalize(self.weight)
|
508 |
+
norm_weight = self.weight
|
509 |
+
else:
|
510 |
+
norm_weight = self.weight
|
511 |
+
return nn.functional.linear(hidden_states, norm_weight)
|
512 |
+
|
513 |
+
_init_weights = True
|
514 |
+
@contextmanager
|
515 |
+
def no_init_weights(_enable=True):
|
516 |
+
global _init_weights
|
517 |
+
old_init_weights = _init_weights
|
518 |
+
if _enable:
|
519 |
+
_init_weights = False
|
520 |
+
try:
|
521 |
+
yield
|
522 |
+
finally:
|
523 |
+
_init_weights = old_init_weights
|
524 |
+
|
525 |
+
class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
526 |
+
def __init__(self, config, *model_args, **model_kwargs):
|
527 |
+
super().__init__(config, *model_args, **model_kwargs)
|
528 |
+
self.model = BaichuanModel(config)
|
529 |
+
|
530 |
+
self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
|
531 |
+
if hasattr(config, "quantization_config") and isinstance(config.quantization_config, dict) and config.quantization_config.get('load_in_4bit', False):
|
532 |
+
try:
|
533 |
+
from .quantizer import quantize_offline, init_model_weight_int4
|
534 |
+
except ImportError:
|
535 |
+
raise ImportError(f"Needs QLinear to run quantize.")
|
536 |
+
quantize_offline(self, 4)
|
537 |
+
# Initialize weights and apply final processing
|
538 |
+
self.post_init()
|
539 |
+
|
540 |
+
def get_input_embeddings(self):
|
541 |
+
return self.model.embed_tokens
|
542 |
+
|
543 |
+
def set_input_embeddings(self, value):
|
544 |
+
self.model.embed_tokens = value
|
545 |
+
|
546 |
+
def get_output_embeddings(self):
|
547 |
+
return self.lm_head
|
548 |
+
|
549 |
+
def set_output_embeddings(self, new_embeddings):
|
550 |
+
self.lm_head = new_embeddings
|
551 |
+
|
552 |
+
def set_decoder(self, decoder):
|
553 |
+
self.model = decoder
|
554 |
+
|
555 |
+
def get_decoder(self):
|
556 |
+
return self.model
|
557 |
+
|
558 |
+
@classmethod
|
559 |
+
def from_pretrained(
|
560 |
+
cls,
|
561 |
+
pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
|
562 |
+
*model_args,
|
563 |
+
config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
|
564 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
565 |
+
ignore_mismatched_sizes: bool = False,
|
566 |
+
force_download: bool = False,
|
567 |
+
local_files_only: bool = False,
|
568 |
+
token: Optional[Union[str, bool]] = None,
|
569 |
+
revision: str = "main",
|
570 |
+
use_safetensors: bool = None,
|
571 |
+
**kwargs,
|
572 |
+
):
|
573 |
+
# Load config if we don't provide a configuration
|
574 |
+
if not isinstance(config, PretrainedConfig):
|
575 |
+
config_path = config if config is not None else pretrained_model_name_or_path
|
576 |
+
config, model_kwargs = cls.config_class.from_pretrained(
|
577 |
+
config_path,
|
578 |
+
cache_dir=cache_dir,
|
579 |
+
return_unused_kwargs=True,
|
580 |
+
force_download=force_download,
|
581 |
+
resume_download=False,
|
582 |
+
proxies=None,
|
583 |
+
local_files_only=local_files_only,
|
584 |
+
token=token,
|
585 |
+
revision=revision,
|
586 |
+
subfolder="",
|
587 |
+
_from_auto=False,
|
588 |
+
_from_pipeline=None,
|
589 |
+
**kwargs,
|
590 |
+
)
|
591 |
+
else:
|
592 |
+
model_kwargs = kwargs
|
593 |
+
|
594 |
+
if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
|
595 |
+
try:
|
596 |
+
from .quantizer import init_model_weight_int4
|
597 |
+
from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map
|
598 |
+
from accelerate.utils import CustomDtype
|
599 |
+
from accelerate.utils import get_balanced_memory
|
600 |
+
except ImportError:
|
601 |
+
raise ImportError(f"Needs import model weight init func to run quantize.")
|
602 |
+
# Instantiate model.
|
603 |
+
init_contexts = [no_init_weights(_enable=True)]
|
604 |
+
init_contexts.append(init_empty_weights())
|
605 |
+
with ContextManagers(init_contexts):
|
606 |
+
model = cls(config)
|
607 |
+
|
608 |
+
model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin')
|
609 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
610 |
+
model.is_quantized = True
|
611 |
+
|
612 |
+
device_map = kwargs.pop("device_map", None)
|
613 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
614 |
+
|
615 |
+
if device_map is not None:
|
616 |
+
kwargs = {"no_split_module_classes": model._no_split_modules}
|
617 |
+
target_dtype = CustomDtype.INT4
|
618 |
+
max_memory = get_balanced_memory(
|
619 |
+
model,
|
620 |
+
dtype=target_dtype,
|
621 |
+
low_zero=(device_map == "balanced_low_0"),
|
622 |
+
max_memory=None,
|
623 |
+
**kwargs,
|
624 |
+
)
|
625 |
+
kwargs["max_memory"] = max_memory
|
626 |
+
device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs)
|
627 |
+
|
628 |
+
model = init_model_weight_int4(config, model, state_dict)
|
629 |
+
|
630 |
+
# Set model in evaluation mode to deactivate DropOut modules by default
|
631 |
+
model.eval()
|
632 |
+
# If it is a model with generation capabilities, attempt to load the generation config
|
633 |
+
if model.can_generate():
|
634 |
+
try:
|
635 |
+
model.generation_config = GenerationConfig.from_pretrained(
|
636 |
+
pretrained_model_name_or_path,
|
637 |
+
cache_dir=cache_dir,
|
638 |
+
force_download=force_download,
|
639 |
+
resume_download=False,
|
640 |
+
proxies=None,
|
641 |
+
local_files_only=local_files_only,
|
642 |
+
token=token,
|
643 |
+
revision=revision,
|
644 |
+
subfolder="",
|
645 |
+
_from_auto=False,
|
646 |
+
_from_pipeline=None,
|
647 |
+
**kwargs,
|
648 |
+
)
|
649 |
+
except (OSError, TypeError):
|
650 |
+
logger.info(
|
651 |
+
"Generation config file not found, using a generation config created from the model config."
|
652 |
+
)
|
653 |
+
pass
|
654 |
+
|
655 |
+
if device_map is not None:
|
656 |
+
dispatch_model(model, device_map=device_map)
|
657 |
+
|
658 |
+
return model
|
659 |
+
return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
|
660 |
+
config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
|
661 |
+
force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
|
662 |
+
use_safetensors=use_safetensors, **kwargs)
|
663 |
+
|
664 |
+
def forward(
|
665 |
+
self,
|
666 |
+
input_ids: torch.LongTensor = None,
|
667 |
+
attention_mask: Optional[torch.Tensor] = None,
|
668 |
+
position_ids: Optional[torch.LongTensor] = None,
|
669 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
670 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
671 |
+
labels: Optional[torch.LongTensor] = None,
|
672 |
+
use_cache: Optional[bool] = None,
|
673 |
+
output_attentions: Optional[bool] = None,
|
674 |
+
output_hidden_states: Optional[bool] = None,
|
675 |
+
return_dict: Optional[bool] = None,
|
676 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
677 |
+
|
678 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
679 |
+
output_hidden_states = (
|
680 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
681 |
+
)
|
682 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
683 |
+
|
684 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
685 |
+
outputs = self.model(
|
686 |
+
input_ids=input_ids,
|
687 |
+
attention_mask=attention_mask,
|
688 |
+
position_ids=position_ids,
|
689 |
+
past_key_values=past_key_values,
|
690 |
+
inputs_embeds=inputs_embeds,
|
691 |
+
use_cache=use_cache,
|
692 |
+
output_attentions=output_attentions,
|
693 |
+
output_hidden_states=output_hidden_states,
|
694 |
+
return_dict=return_dict,
|
695 |
+
)
|
696 |
+
|
697 |
+
hidden_states = outputs[0]
|
698 |
+
logits = self.lm_head(hidden_states)
|
699 |
+
loss = None
|
700 |
+
if labels is not None:
|
701 |
+
# Shift so that tokens < n predict n
|
702 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
703 |
+
shift_labels = labels[..., 1:].contiguous()
|
704 |
+
# Flatten the tokens
|
705 |
+
loss_fct = CrossEntropyLoss()
|
706 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
707 |
+
shift_labels = shift_labels.view(-1)
|
708 |
+
softmax_normalizer = shift_logits.max(-1).values ** 2
|
709 |
+
z_loss = self.config.z_loss_weight * softmax_normalizer.mean()
|
710 |
+
# Enable model parallelism
|
711 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
712 |
+
loss = loss_fct(shift_logits, shift_labels) + z_loss
|
713 |
+
|
714 |
+
if not return_dict:
|
715 |
+
output = (logits,) + outputs[1:]
|
716 |
+
return (loss,) + output if loss is not None else output
|
717 |
+
|
718 |
+
return CausalLMOutputWithPast(
|
719 |
+
loss=loss,
|
720 |
+
logits=logits,
|
721 |
+
past_key_values=outputs.past_key_values,
|
722 |
+
hidden_states=outputs.hidden_states,
|
723 |
+
attentions=outputs.attentions,
|
724 |
+
)
|
725 |
+
|
726 |
+
def prepare_inputs_for_generation(
|
727 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
728 |
+
):
|
729 |
+
if past_key_values:
|
730 |
+
input_ids = input_ids[:, -1:]
|
731 |
+
|
732 |
+
position_ids = kwargs.get("position_ids", None)
|
733 |
+
if attention_mask is not None and position_ids is None:
|
734 |
+
# create position_ids on the fly for batch generation
|
735 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
736 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
737 |
+
if past_key_values:
|
738 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
739 |
+
|
740 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
741 |
+
if inputs_embeds is not None and past_key_values is None:
|
742 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
743 |
+
else:
|
744 |
+
model_inputs = {"input_ids": input_ids}
|
745 |
+
|
746 |
+
model_inputs.update(
|
747 |
+
{
|
748 |
+
"position_ids": position_ids,
|
749 |
+
"past_key_values": past_key_values,
|
750 |
+
"use_cache": kwargs.get("use_cache"),
|
751 |
+
"attention_mask": attention_mask,
|
752 |
+
}
|
753 |
+
)
|
754 |
+
return model_inputs
|
755 |
+
|
756 |
+
@staticmethod
|
757 |
+
def _reorder_cache(past_key_values, beam_idx):
|
758 |
+
reordered_past = ()
|
759 |
+
for layer_past in past_key_values:
|
760 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
761 |
+
return reordered_past
|
762 |
+
|
763 |
+
def quantize(self, bits: int):
|
764 |
+
try:
|
765 |
+
from .quantizer import quantize_online
|
766 |
+
except ImportError:
|
767 |
+
raise ImportError(f"Needs QLinear to run quantize.")
|
768 |
+
return quantize_online(self, bits)
|
769 |
+
|
770 |
+
def chat(self, tokenizer, messages: List[dict], stream=False,
|
771 |
+
generation_config: Optional[GenerationConfig]=None):
|
772 |
+
generation_config = generation_config or self.generation_config
|
773 |
+
input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
|
774 |
+
if stream:
|
775 |
+
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
776 |
+
Thread(target=self.generate, kwargs=dict(
|
777 |
+
inputs=input_ids, streamer=streamer,
|
778 |
+
generation_config=generation_config,
|
779 |
+
)).start()
|
780 |
+
return streamer
|
781 |
+
else:
|
782 |
+
outputs = self.generate(input_ids, generation_config=generation_config)
|
783 |
+
response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
|
784 |
+
return response
|
pretrain/pytorch_model-00001-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0ff57093326944eb7e3b89a7a94206d3fd0f05275cf76dc612bfce961c41f1c4
|
3 |
+
size 9934622796
|
pretrain/pytorch_model-00002-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ef5f0d262552b1db85d243254f1fb1f20884421d4754e9c0fb7a26142d5ca195
|
3 |
+
size 5077401163
|
pretrain/pytorch_model.bin.index.json
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 15011946496
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "pytorch_model-00002-of-00002.bin",
|
7 |
+
"model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
|
8 |
+
"model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
13 |
+
"model.layers.0.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
14 |
+
"model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
15 |
+
"model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
16 |
+
"model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
17 |
+
"model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
18 |
+
"model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
19 |
+
"model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
20 |
+
"model.layers.1.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
21 |
+
"model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
22 |
+
"model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
23 |
+
"model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
24 |
+
"model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
25 |
+
"model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
26 |
+
"model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
27 |
+
"model.layers.10.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
28 |
+
"model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
29 |
+
"model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
30 |
+
"model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
31 |
+
"model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
32 |
+
"model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
33 |
+
"model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
34 |
+
"model.layers.11.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
35 |
+
"model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
36 |
+
"model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
37 |
+
"model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
38 |
+
"model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
39 |
+
"model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
40 |
+
"model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
41 |
+
"model.layers.12.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
42 |
+
"model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
43 |
+
"model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
44 |
+
"model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
45 |
+
"model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
46 |
+
"model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
47 |
+
"model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
48 |
+
"model.layers.13.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
49 |
+
"model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
50 |
+
"model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
51 |
+
"model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
52 |
+
"model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
53 |
+
"model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
54 |
+
"model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
55 |
+
"model.layers.14.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
56 |
+
"model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
57 |
+
"model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
58 |
+
"model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
59 |
+
"model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
60 |
+
"model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
61 |
+
"model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
62 |
+
"model.layers.15.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
63 |
+
"model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
64 |
+
"model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
65 |
+
"model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
66 |
+
"model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
67 |
+
"model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
68 |
+
"model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
69 |
+
"model.layers.16.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
70 |
+
"model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
71 |
+
"model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
72 |
+
"model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
73 |
+
"model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
74 |
+
"model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
75 |
+
"model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
76 |
+
"model.layers.17.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
77 |
+
"model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
78 |
+
"model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
79 |
+
"model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
80 |
+
"model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
81 |
+
"model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
82 |
+
"model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
83 |
+
"model.layers.18.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
84 |
+
"model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
85 |
+
"model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
86 |
+
"model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
87 |
+
"model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
88 |
+
"model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
89 |
+
"model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
90 |
+
"model.layers.19.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
91 |
+
"model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
92 |
+
"model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
93 |
+
"model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
94 |
+
"model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
95 |
+
"model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
96 |
+
"model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
97 |
+
"model.layers.2.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
98 |
+
"model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
99 |
+
"model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
100 |
+
"model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
101 |
+
"model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
102 |
+
"model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
103 |
+
"model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
104 |
+
"model.layers.20.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
105 |
+
"model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
106 |
+
"model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
107 |
+
"model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
108 |
+
"model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
109 |
+
"model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
110 |
+
"model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
111 |
+
"model.layers.21.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
112 |
+
"model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
113 |
+
"model.layers.22.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
114 |
+
"model.layers.22.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
115 |
+
"model.layers.22.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
116 |
+
"model.layers.22.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
117 |
+
"model.layers.22.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
118 |
+
"model.layers.22.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
119 |
+
"model.layers.22.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
120 |
+
"model.layers.23.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
121 |
+
"model.layers.23.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
122 |
+
"model.layers.23.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
123 |
+
"model.layers.23.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
124 |
+
"model.layers.23.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
125 |
+
"model.layers.23.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
126 |
+
"model.layers.23.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
127 |
+
"model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
128 |
+
"model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
129 |
+
"model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
130 |
+
"model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
131 |
+
"model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
132 |
+
"model.layers.24.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
133 |
+
"model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
134 |
+
"model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
135 |
+
"model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
136 |
+
"model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
137 |
+
"model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
138 |
+
"model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
139 |
+
"model.layers.25.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
140 |
+
"model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
141 |
+
"model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
142 |
+
"model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
143 |
+
"model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
144 |
+
"model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
145 |
+
"model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
146 |
+
"model.layers.26.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
147 |
+
"model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
148 |
+
"model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
149 |
+
"model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
150 |
+
"model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
151 |
+
"model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
152 |
+
"model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
153 |
+
"model.layers.27.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
154 |
+
"model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
155 |
+
"model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
156 |
+
"model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
157 |
+
"model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
158 |
+
"model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
159 |
+
"model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
160 |
+
"model.layers.28.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
161 |
+
"model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
162 |
+
"model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
163 |
+
"model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
164 |
+
"model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
165 |
+
"model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
166 |
+
"model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
167 |
+
"model.layers.29.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
168 |
+
"model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
169 |
+
"model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
170 |
+
"model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
171 |
+
"model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
172 |
+
"model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
173 |
+
"model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
174 |
+
"model.layers.3.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
175 |
+
"model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
176 |
+
"model.layers.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
177 |
+
"model.layers.30.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
178 |
+
"model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
179 |
+
"model.layers.30.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
180 |
+
"model.layers.30.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
181 |
+
"model.layers.30.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
182 |
+
"model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
183 |
+
"model.layers.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
184 |
+
"model.layers.31.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
185 |
+
"model.layers.31.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
186 |
+
"model.layers.31.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
187 |
+
"model.layers.31.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
188 |
+
"model.layers.31.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
189 |
+
"model.layers.31.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
190 |
+
"model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
191 |
+
"model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
192 |
+
"model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
193 |
+
"model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
194 |
+
"model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
195 |
+
"model.layers.4.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
196 |
+
"model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
197 |
+
"model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
198 |
+
"model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
199 |
+
"model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
200 |
+
"model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
201 |
+
"model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
202 |
+
"model.layers.5.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
203 |
+
"model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
204 |
+
"model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
205 |
+
"model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
206 |
+
"model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
207 |
+
"model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
208 |
+
"model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
209 |
+
"model.layers.6.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
210 |
+
"model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
211 |
+
"model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
212 |
+
"model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
213 |
+
"model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
214 |
+
"model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
215 |
+
"model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
216 |
+
"model.layers.7.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
217 |
+
"model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
218 |
+
"model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
219 |
+
"model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
220 |
+
"model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
221 |
+
"model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
222 |
+
"model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
223 |
+
"model.layers.8.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
224 |
+
"model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
225 |
+
"model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
226 |
+
"model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
227 |
+
"model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
228 |
+
"model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
229 |
+
"model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
230 |
+
"model.layers.9.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
231 |
+
"model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
232 |
+
"model.norm.weight": "pytorch_model-00002-of-00002.bin"
|
233 |
+
}
|
234 |
+
}
|
pretrain/quantizer.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import bitsandbytes as bnb
|
2 |
+
from bitsandbytes.nn.modules import Params4bit, Int8Params
|
3 |
+
import torch
|
4 |
+
|
5 |
+
def Params4bitCuda(self, device):
|
6 |
+
self.data = self.data.cuda(device)
|
7 |
+
self.quant_state[0] = self.quant_state[0].cuda(device)
|
8 |
+
self.quant_state[4][0] = self.quant_state[4][0].cuda(device)
|
9 |
+
self.quant_state[4][1][0] = self.quant_state[4][1][0].cuda(device)
|
10 |
+
self.quant_state[4][1][1] = self.quant_state[4][1][1].cuda(device)
|
11 |
+
|
12 |
+
self.quant_state[6] = self.quant_state[6].cuda(device)
|
13 |
+
return self
|
14 |
+
|
15 |
+
class Linear4bitOnline(torch.nn.Module):
|
16 |
+
def __init__(self, weight, bias, quant_type):
|
17 |
+
super().__init__()
|
18 |
+
self.weight = Params4bit(
|
19 |
+
weight.data, requires_grad=False, compress_statistics=True, quant_type=quant_type
|
20 |
+
)
|
21 |
+
self.compute_dtype = None
|
22 |
+
#self.weight.cuda(weight.device)
|
23 |
+
self.bias = bias
|
24 |
+
|
25 |
+
def forward(self, x: torch.Tensor):
|
26 |
+
# weights are cast automatically as Int8Params, but the bias has to be cast manually
|
27 |
+
if self.bias is not None and self.bias.dtype != x.dtype:
|
28 |
+
self.bias.data = self.bias.data.to(x.dtype)
|
29 |
+
|
30 |
+
if getattr(self.weight, "quant_state", None) is None:
|
31 |
+
print(
|
32 |
+
"FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first."
|
33 |
+
)
|
34 |
+
inp_dtype = x.dtype
|
35 |
+
if self.compute_dtype is not None:
|
36 |
+
x = x.to(self.compute_dtype)
|
37 |
+
|
38 |
+
bias = None if self.bias is None else self.bias.to(self.compute_dtype)
|
39 |
+
out = bnb.matmul_4bit(
|
40 |
+
x, self.weight.t(), bias=bias, quant_state=self.weight.quant_state
|
41 |
+
)
|
42 |
+
|
43 |
+
out = out.to(inp_dtype)
|
44 |
+
|
45 |
+
return out
|
46 |
+
|
47 |
+
class Linear8bitLtOnline(torch.nn.Module):
|
48 |
+
def __init__(
|
49 |
+
self,
|
50 |
+
weight,
|
51 |
+
bias,
|
52 |
+
has_fp16_weights=True,
|
53 |
+
memory_efficient_backward=False,
|
54 |
+
threshold=0.0,
|
55 |
+
index=None,
|
56 |
+
):
|
57 |
+
super().__init__()
|
58 |
+
assert (
|
59 |
+
not memory_efficient_backward
|
60 |
+
), "memory_efficient_backward is no longer required and the argument is deprecated in 0.37.0 and will be removed in 0.39.0"
|
61 |
+
self.state = bnb.MatmulLtState()
|
62 |
+
self.index = index
|
63 |
+
|
64 |
+
# Necessary for stacked layers
|
65 |
+
self.state.threshold = threshold
|
66 |
+
self.state.has_fp16_weights = has_fp16_weights
|
67 |
+
self.state.memory_efficient_backward = memory_efficient_backward
|
68 |
+
if threshold > 0.0 and not has_fp16_weights:
|
69 |
+
self.state.use_pool = True
|
70 |
+
|
71 |
+
self.weight = Int8Params(
|
72 |
+
weight.data,
|
73 |
+
has_fp16_weights=has_fp16_weights,
|
74 |
+
requires_grad=has_fp16_weights,
|
75 |
+
)
|
76 |
+
self.bias = bias
|
77 |
+
|
78 |
+
def init_8bit_state(self):
|
79 |
+
self.state.CB = self.weight.CB
|
80 |
+
self.state.SCB = self.weight.SCB
|
81 |
+
self.weight.CB = None
|
82 |
+
self.weight.SCB = None
|
83 |
+
|
84 |
+
def forward(self, x: torch.Tensor):
|
85 |
+
self.state.is_training = self.training
|
86 |
+
if self.weight.CB is not None:
|
87 |
+
self.init_8bit_state()
|
88 |
+
|
89 |
+
# weights are cast automatically as Int8Params, but the bias has to be cast manually
|
90 |
+
if self.bias is not None and self.bias.dtype != x.dtype:
|
91 |
+
self.bias.data = self.bias.data.to(x.dtype)
|
92 |
+
|
93 |
+
out = bnb.matmul(x, self.weight, bias=self.bias, state=self.state)
|
94 |
+
|
95 |
+
if not self.state.has_fp16_weights:
|
96 |
+
if self.state.CB is not None and self.state.CxB is not None:
|
97 |
+
# we converted 8-bit row major to turing/ampere format in the first inference pass
|
98 |
+
# we no longer need the row-major weight
|
99 |
+
del self.state.CB
|
100 |
+
self.weight.data = self.state.CxB
|
101 |
+
return out
|
102 |
+
|
103 |
+
def quantize_offline(model, bits: int):
|
104 |
+
assert (bits == 4), f'bits: {bits} is not supported'
|
105 |
+
|
106 |
+
for i, layer in enumerate(model.model.layers):
|
107 |
+
layer.self_attn.W_pack = bnb.nn.Linear4bit(
|
108 |
+
layer.self_attn.W_pack.weight.shape[1],
|
109 |
+
layer.self_attn.W_pack.weight.shape[0],
|
110 |
+
False,
|
111 |
+
torch.float16,
|
112 |
+
compress_statistics=True,
|
113 |
+
quant_type="nf4",
|
114 |
+
)
|
115 |
+
layer.self_attn.o_proj = bnb.nn.Linear4bit(
|
116 |
+
layer.self_attn.o_proj.weight.shape[1],
|
117 |
+
layer.self_attn.o_proj.weight.shape[0],
|
118 |
+
False,
|
119 |
+
torch.float16,
|
120 |
+
compress_statistics=True,
|
121 |
+
quant_type="nf4",
|
122 |
+
)
|
123 |
+
|
124 |
+
layer.mlp.gate_proj = bnb.nn.Linear4bit(
|
125 |
+
layer.mlp.gate_proj.weight.shape[1],
|
126 |
+
layer.mlp.gate_proj.weight.shape[0],
|
127 |
+
False,
|
128 |
+
torch.float16,
|
129 |
+
compress_statistics=True,
|
130 |
+
quant_type="nf4",
|
131 |
+
)
|
132 |
+
layer.mlp.down_proj = bnb.nn.Linear4bit(
|
133 |
+
layer.mlp.down_proj.weight.shape[1],
|
134 |
+
layer.mlp.down_proj.weight.shape[0],
|
135 |
+
False,
|
136 |
+
torch.float16,
|
137 |
+
compress_statistics=True,
|
138 |
+
quant_type="nf4",
|
139 |
+
)
|
140 |
+
layer.mlp.up_proj = bnb.nn.Linear4bit(
|
141 |
+
layer.mlp.up_proj.weight.shape[1],
|
142 |
+
layer.mlp.up_proj.weight.shape[0],
|
143 |
+
False,
|
144 |
+
torch.float16,
|
145 |
+
compress_statistics=True,
|
146 |
+
quant_type="nf4",
|
147 |
+
)
|
148 |
+
return model
|
149 |
+
|
150 |
+
def quantize_online(model, bits: int):
|
151 |
+
def quant(weight, bias=None):
|
152 |
+
if bits == 8:
|
153 |
+
linear = Linear8bitLtOnline(
|
154 |
+
weight,
|
155 |
+
bias,
|
156 |
+
has_fp16_weights=False,
|
157 |
+
threshold=6.0,
|
158 |
+
)
|
159 |
+
if bias is not None:
|
160 |
+
linear.bias = torch.nn.Parameter(bias)
|
161 |
+
elif bits == 4:
|
162 |
+
linear = Linear4bitOnline(
|
163 |
+
weight,
|
164 |
+
bias,
|
165 |
+
quant_type="nf4", #fp4/nf4
|
166 |
+
)
|
167 |
+
else:
|
168 |
+
raise ValueError("quantize only support 4/8 bit")
|
169 |
+
return linear
|
170 |
+
|
171 |
+
for i, layer in enumerate(model.model.layers):
|
172 |
+
layer.self_attn.W_pack = quant(layer.self_attn.W_pack.weight)
|
173 |
+
layer.self_attn.o_proj = quant(layer.self_attn.o_proj.weight)
|
174 |
+
layer.mlp.gate_proj = quant(layer.mlp.gate_proj.weight)
|
175 |
+
layer.mlp.down_proj = quant(layer.mlp.down_proj.weight)
|
176 |
+
layer.mlp.up_proj = quant(layer.mlp.up_proj.weight)
|
177 |
+
return model
|
178 |
+
|
179 |
+
def init_model_weight_int4(config, model, state_dict):
|
180 |
+
#replace Params4bit.cuda with Params4bitCuda
|
181 |
+
Params4bit.cuda = Params4bitCuda
|
182 |
+
|
183 |
+
for i in range(config.num_hidden_layers):
|
184 |
+
weight_data = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.data']
|
185 |
+
weight_quant_state = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.quant_state']
|
186 |
+
model.model.layers[i].self_attn.W_pack.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
187 |
+
|
188 |
+
weight_data = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.data']
|
189 |
+
weight_quant_state = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.quant_state']
|
190 |
+
model.model.layers[i].self_attn.o_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
191 |
+
|
192 |
+
weight_data = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.data']
|
193 |
+
weight_quant_state = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.quant_state']
|
194 |
+
model.model.layers[i].mlp.gate_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
195 |
+
|
196 |
+
weight_data = state_dict[f'model.layers.{i}.mlp.up_proj.weight.data']
|
197 |
+
weight_quant_state = state_dict[f'model.layers.{i}.mlp.up_proj.weight.quant_state']
|
198 |
+
model.model.layers[i].mlp.up_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
199 |
+
|
200 |
+
weight_data = state_dict[f'model.layers.{i}.mlp.down_proj.weight.data']
|
201 |
+
weight_quant_state = state_dict[f'model.layers.{i}.mlp.down_proj.weight.quant_state']
|
202 |
+
model.model.layers[i].mlp.down_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
203 |
+
|
204 |
+
model.model.layers[i].input_layernorm.weight = state_dict[f'model.layers.{i}.input_layernorm.weight']
|
205 |
+
model.model.layers[i].post_attention_layernorm.weight = state_dict[f'model.layers.{i}.post_attention_layernorm.weight']
|
206 |
+
|
207 |
+
model.model.embed_tokens.weight = state_dict['model.embed_tokens.weight']
|
208 |
+
model.model.norm.weight = state_dict['model.norm.weight']
|
209 |
+
model.lm_head.weight = state_dict['lm_head.weight']
|
210 |
+
return model
|
pretrain/special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<unk>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": true,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<unk>",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": true,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
}
|
30 |
+
}
|
pretrain/tokenization_baichuan.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
2 |
+
|
3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
+
# and OPT implementations in this library. It has been modified from its
|
7 |
+
# original forms to accommodate minor architectural differences compared
|
8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
+
#
|
10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
+
# you may not use this file except in compliance with the License.
|
12 |
+
# You may obtain a copy of the License at
|
13 |
+
#
|
14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
+
#
|
16 |
+
# Unless required by applicable law or agreed to in writing, software
|
17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
+
# See the License for the specific language governing permissions and
|
20 |
+
# limitations under the License.
|
21 |
+
|
22 |
+
import os
|
23 |
+
from shutil import copyfile
|
24 |
+
from typing import Any, Dict, List, Optional, Tuple
|
25 |
+
|
26 |
+
import sentencepiece as spm
|
27 |
+
|
28 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
29 |
+
from transformers.utils import logging
|
30 |
+
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
35 |
+
|
36 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
37 |
+
"vocab_file": {},
|
38 |
+
"tokenizer_file": {},
|
39 |
+
}
|
40 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
|
41 |
+
|
42 |
+
|
43 |
+
class BaichuanTokenizer(PreTrainedTokenizer):
|
44 |
+
"""
|
45 |
+
Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
|
46 |
+
|
47 |
+
Args:
|
48 |
+
vocab_file (`str`):
|
49 |
+
Path to the vocabulary file.
|
50 |
+
"""
|
51 |
+
|
52 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
53 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
54 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
55 |
+
model_input_names = ["input_ids", "attention_mask"]
|
56 |
+
|
57 |
+
def __init__(
|
58 |
+
self,
|
59 |
+
vocab_file,
|
60 |
+
unk_token="<unk>",
|
61 |
+
bos_token="<s>",
|
62 |
+
eos_token="</s>",
|
63 |
+
pad_token=None,
|
64 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
65 |
+
add_bos_token=True,
|
66 |
+
add_eos_token=False,
|
67 |
+
clean_up_tokenization_spaces=False,
|
68 |
+
**kwargs,
|
69 |
+
):
|
70 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
71 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
72 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
73 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
74 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
75 |
+
super().__init__(
|
76 |
+
bos_token=bos_token,
|
77 |
+
eos_token=eos_token,
|
78 |
+
unk_token=unk_token,
|
79 |
+
pad_token=pad_token,
|
80 |
+
add_bos_token=add_bos_token,
|
81 |
+
add_eos_token=add_eos_token,
|
82 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
83 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
84 |
+
**kwargs,
|
85 |
+
)
|
86 |
+
self.vocab_file = vocab_file
|
87 |
+
self.add_bos_token = add_bos_token
|
88 |
+
self.add_eos_token = add_eos_token
|
89 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
90 |
+
self.sp_model.Load(vocab_file)
|
91 |
+
|
92 |
+
def __getstate__(self):
|
93 |
+
state = self.__dict__.copy()
|
94 |
+
state["sp_model"] = None
|
95 |
+
return state
|
96 |
+
|
97 |
+
def __setstate__(self, d):
|
98 |
+
self.__dict__ = d
|
99 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
100 |
+
self.sp_model.Load(self.vocab_file)
|
101 |
+
|
102 |
+
@property
|
103 |
+
def vocab_size(self):
|
104 |
+
"""Returns vocab size"""
|
105 |
+
return self.sp_model.get_piece_size()
|
106 |
+
|
107 |
+
def get_vocab(self):
|
108 |
+
"""Returns vocab as a dict"""
|
109 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
110 |
+
vocab.update(self.added_tokens_encoder)
|
111 |
+
return vocab
|
112 |
+
|
113 |
+
def _tokenize(self, text):
|
114 |
+
"""Returns a tokenized string."""
|
115 |
+
return self.sp_model.encode(text, out_type=str)
|
116 |
+
|
117 |
+
def _convert_token_to_id(self, token):
|
118 |
+
"""Converts a token (str) in an id using the vocab."""
|
119 |
+
return self.sp_model.piece_to_id(token)
|
120 |
+
|
121 |
+
def _convert_id_to_token(self, index):
|
122 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
123 |
+
token = self.sp_model.IdToPiece(index)
|
124 |
+
return token
|
125 |
+
|
126 |
+
def convert_tokens_to_string(self, tokens):
|
127 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
128 |
+
current_sub_tokens = []
|
129 |
+
out_string = ""
|
130 |
+
prev_is_special = False
|
131 |
+
for i, token in enumerate(tokens):
|
132 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
133 |
+
if token in self.all_special_tokens:
|
134 |
+
if not prev_is_special and i != 0:
|
135 |
+
out_string += " "
|
136 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
137 |
+
prev_is_special = True
|
138 |
+
current_sub_tokens = []
|
139 |
+
else:
|
140 |
+
current_sub_tokens.append(token)
|
141 |
+
prev_is_special = False
|
142 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
143 |
+
return out_string
|
144 |
+
|
145 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
146 |
+
"""
|
147 |
+
Save the vocabulary and special tokens file to a directory.
|
148 |
+
|
149 |
+
Args:
|
150 |
+
save_directory (`str`):
|
151 |
+
The directory in which to save the vocabulary.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
`Tuple(str)`: Paths to the files saved.
|
155 |
+
"""
|
156 |
+
if not os.path.isdir(save_directory):
|
157 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
158 |
+
return
|
159 |
+
out_vocab_file = os.path.join(
|
160 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
161 |
+
)
|
162 |
+
|
163 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
164 |
+
copyfile(self.vocab_file, out_vocab_file)
|
165 |
+
elif not os.path.isfile(self.vocab_file):
|
166 |
+
with open(out_vocab_file, "wb") as fi:
|
167 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
168 |
+
fi.write(content_spiece_model)
|
169 |
+
|
170 |
+
return (out_vocab_file,)
|
171 |
+
|
172 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
173 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
174 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
175 |
+
|
176 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
177 |
+
|
178 |
+
if token_ids_1 is not None:
|
179 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
180 |
+
|
181 |
+
return output
|
182 |
+
|
183 |
+
def get_special_tokens_mask(
|
184 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
185 |
+
) -> List[int]:
|
186 |
+
"""
|
187 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
188 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
189 |
+
|
190 |
+
Args:
|
191 |
+
token_ids_0 (`List[int]`):
|
192 |
+
List of IDs.
|
193 |
+
token_ids_1 (`List[int]`, *optional*):
|
194 |
+
Optional second list of IDs for sequence pairs.
|
195 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
196 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
197 |
+
|
198 |
+
Returns:
|
199 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
200 |
+
"""
|
201 |
+
if already_has_special_tokens:
|
202 |
+
return super().get_special_tokens_mask(
|
203 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
204 |
+
)
|
205 |
+
|
206 |
+
bos_token_id = [1] if self.add_bos_token else []
|
207 |
+
eos_token_id = [1] if self.add_eos_token else []
|
208 |
+
|
209 |
+
if token_ids_1 is None:
|
210 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
211 |
+
return (
|
212 |
+
bos_token_id
|
213 |
+
+ ([0] * len(token_ids_0))
|
214 |
+
+ eos_token_id
|
215 |
+
+ bos_token_id
|
216 |
+
+ ([0] * len(token_ids_1))
|
217 |
+
+ eos_token_id
|
218 |
+
)
|
219 |
+
|
220 |
+
def create_token_type_ids_from_sequences(
|
221 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
222 |
+
) -> List[int]:
|
223 |
+
"""
|
224 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
225 |
+
sequence pair mask has the following format:
|
226 |
+
|
227 |
+
```
|
228 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
229 |
+
| first sequence | second sequence |
|
230 |
+
```
|
231 |
+
|
232 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
233 |
+
|
234 |
+
Args:
|
235 |
+
token_ids_0 (`List[int]`):
|
236 |
+
List of ids.
|
237 |
+
token_ids_1 (`List[int]`, *optional*):
|
238 |
+
Optional second list of IDs for sequence pairs.
|
239 |
+
|
240 |
+
Returns:
|
241 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
242 |
+
"""
|
243 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
244 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
245 |
+
|
246 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
247 |
+
|
248 |
+
if token_ids_1 is not None:
|
249 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
250 |
+
|
251 |
+
return output
|
pretrain/tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:79452955be6b419a65984273a9f08af86042e1c2a75ee3ba989cbf620a133cc2
|
3 |
+
size 2001107
|
pretrain/tokenizer_config.json
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"auto_map": {
|
5 |
+
"AutoTokenizer": [
|
6 |
+
"tokenization_baichuan.BaichuanTokenizer",
|
7 |
+
null
|
8 |
+
]
|
9 |
+
},
|
10 |
+
"bos_token": {
|
11 |
+
"__type": "AddedToken",
|
12 |
+
"content": "<s>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": true,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false
|
17 |
+
},
|
18 |
+
"clean_up_tokenization_spaces": false,
|
19 |
+
"eos_token": {
|
20 |
+
"__type": "AddedToken",
|
21 |
+
"content": "</s>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": true,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": true
|
26 |
+
},
|
27 |
+
"model_max_length": 4096,
|
28 |
+
"pad_token": {
|
29 |
+
"__type": "AddedToken",
|
30 |
+
"content": "<unk>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": true,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": true
|
35 |
+
},
|
36 |
+
"sp_model_kwargs": {},
|
37 |
+
"tokenizer_class": "BaichuanTokenizer",
|
38 |
+
"unk_token": {
|
39 |
+
"__type": "AddedToken",
|
40 |
+
"content": "<unk>",
|
41 |
+
"lstrip": false,
|
42 |
+
"normalized": true,
|
43 |
+
"rstrip": false,
|
44 |
+
"single_word": true
|
45 |
+
},
|
46 |
+
"use_fast": false
|
47 |
+
}
|
pretrain/train_results.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"epoch": 0.5,
|
3 |
+
"train_loss": 1.8579450334821428,
|
4 |
+
"train_runtime": 7071.4809,
|
5 |
+
"train_samples": 300760,
|
6 |
+
"train_samples_per_second": 21.266,
|
7 |
+
"train_steps_per_second": 0.083
|
8 |
+
}
|
pretrain/trainer_state.json
ADDED
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"best_metric": null,
|
3 |
+
"best_model_checkpoint": null,
|
4 |
+
"epoch": 0.5004255319148936,
|
5 |
+
"eval_steps": 50,
|
6 |
+
"global_step": 588,
|
7 |
+
"is_hyper_param_search": false,
|
8 |
+
"is_local_process_zero": true,
|
9 |
+
"is_world_process_zero": true,
|
10 |
+
"log_history": [
|
11 |
+
{
|
12 |
+
"epoch": 0.01,
|
13 |
+
"learning_rate": 0.00013539849850576911,
|
14 |
+
"loss": 4.8195,
|
15 |
+
"step": 10
|
16 |
+
},
|
17 |
+
{
|
18 |
+
"epoch": 0.02,
|
19 |
+
"learning_rate": 0.00017615750792387034,
|
20 |
+
"loss": 2.2427,
|
21 |
+
"step": 20
|
22 |
+
},
|
23 |
+
{
|
24 |
+
"epoch": 0.03,
|
25 |
+
"learning_rate": 0.0002,
|
26 |
+
"loss": 2.0574,
|
27 |
+
"step": 30
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"epoch": 0.03,
|
31 |
+
"learning_rate": 0.0001967741935483871,
|
32 |
+
"loss": 2.0078,
|
33 |
+
"step": 40
|
34 |
+
},
|
35 |
+
{
|
36 |
+
"epoch": 0.04,
|
37 |
+
"learning_rate": 0.0001931899641577061,
|
38 |
+
"loss": 1.9905,
|
39 |
+
"step": 50
|
40 |
+
},
|
41 |
+
{
|
42 |
+
"epoch": 0.04,
|
43 |
+
"eval_accuracy": 0.6544462424008755,
|
44 |
+
"eval_loss": 1.5293824672698975,
|
45 |
+
"eval_runtime": 32.8926,
|
46 |
+
"eval_samples_per_second": 61.047,
|
47 |
+
"eval_steps_per_second": 0.243,
|
48 |
+
"step": 50
|
49 |
+
},
|
50 |
+
{
|
51 |
+
"epoch": 0.05,
|
52 |
+
"learning_rate": 0.0001896057347670251,
|
53 |
+
"loss": 1.9798,
|
54 |
+
"step": 60
|
55 |
+
},
|
56 |
+
{
|
57 |
+
"epoch": 0.06,
|
58 |
+
"learning_rate": 0.00018602150537634407,
|
59 |
+
"loss": 1.9546,
|
60 |
+
"step": 70
|
61 |
+
},
|
62 |
+
{
|
63 |
+
"epoch": 0.07,
|
64 |
+
"learning_rate": 0.0001824372759856631,
|
65 |
+
"loss": 1.9234,
|
66 |
+
"step": 80
|
67 |
+
},
|
68 |
+
{
|
69 |
+
"epoch": 0.08,
|
70 |
+
"learning_rate": 0.00017885304659498208,
|
71 |
+
"loss": 1.929,
|
72 |
+
"step": 90
|
73 |
+
},
|
74 |
+
{
|
75 |
+
"epoch": 0.09,
|
76 |
+
"learning_rate": 0.00017526881720430107,
|
77 |
+
"loss": 1.907,
|
78 |
+
"step": 100
|
79 |
+
},
|
80 |
+
{
|
81 |
+
"epoch": 0.09,
|
82 |
+
"eval_accuracy": 0.5062341056107924,
|
83 |
+
"eval_loss": 3.5476841926574707,
|
84 |
+
"eval_runtime": 32.158,
|
85 |
+
"eval_samples_per_second": 62.442,
|
86 |
+
"eval_steps_per_second": 0.249,
|
87 |
+
"step": 100
|
88 |
+
},
|
89 |
+
{
|
90 |
+
"epoch": 0.09,
|
91 |
+
"learning_rate": 0.0001716845878136201,
|
92 |
+
"loss": 1.8956,
|
93 |
+
"step": 110
|
94 |
+
},
|
95 |
+
{
|
96 |
+
"epoch": 0.1,
|
97 |
+
"learning_rate": 0.00016810035842293908,
|
98 |
+
"loss": 1.8982,
|
99 |
+
"step": 120
|
100 |
+
},
|
101 |
+
{
|
102 |
+
"epoch": 0.11,
|
103 |
+
"learning_rate": 0.00016451612903225807,
|
104 |
+
"loss": 1.8738,
|
105 |
+
"step": 130
|
106 |
+
},
|
107 |
+
{
|
108 |
+
"epoch": 0.12,
|
109 |
+
"learning_rate": 0.00016093189964157706,
|
110 |
+
"loss": 1.8788,
|
111 |
+
"step": 140
|
112 |
+
},
|
113 |
+
{
|
114 |
+
"epoch": 0.13,
|
115 |
+
"learning_rate": 0.00015734767025089608,
|
116 |
+
"loss": 1.8675,
|
117 |
+
"step": 150
|
118 |
+
},
|
119 |
+
{
|
120 |
+
"epoch": 0.13,
|
121 |
+
"eval_accuracy": 0.5123508896963466,
|
122 |
+
"eval_loss": 3.6367032527923584,
|
123 |
+
"eval_runtime": 33.3455,
|
124 |
+
"eval_samples_per_second": 60.218,
|
125 |
+
"eval_steps_per_second": 0.24,
|
126 |
+
"step": 150
|
127 |
+
},
|
128 |
+
{
|
129 |
+
"epoch": 0.14,
|
130 |
+
"learning_rate": 0.00015376344086021504,
|
131 |
+
"loss": 1.8457,
|
132 |
+
"step": 160
|
133 |
+
},
|
134 |
+
{
|
135 |
+
"epoch": 0.14,
|
136 |
+
"learning_rate": 0.00015017921146953406,
|
137 |
+
"loss": 1.8669,
|
138 |
+
"step": 170
|
139 |
+
},
|
140 |
+
{
|
141 |
+
"epoch": 0.15,
|
142 |
+
"learning_rate": 0.00014659498207885305,
|
143 |
+
"loss": 1.8484,
|
144 |
+
"step": 180
|
145 |
+
},
|
146 |
+
{
|
147 |
+
"epoch": 0.16,
|
148 |
+
"learning_rate": 0.00014301075268817205,
|
149 |
+
"loss": 1.8312,
|
150 |
+
"step": 190
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"epoch": 0.17,
|
154 |
+
"learning_rate": 0.00013942652329749104,
|
155 |
+
"loss": 1.8359,
|
156 |
+
"step": 200
|
157 |
+
},
|
158 |
+
{
|
159 |
+
"epoch": 0.17,
|
160 |
+
"eval_accuracy": 0.514210995704377,
|
161 |
+
"eval_loss": 3.6230080127716064,
|
162 |
+
"eval_runtime": 33.3113,
|
163 |
+
"eval_samples_per_second": 60.28,
|
164 |
+
"eval_steps_per_second": 0.24,
|
165 |
+
"step": 200
|
166 |
+
},
|
167 |
+
{
|
168 |
+
"epoch": 0.18,
|
169 |
+
"learning_rate": 0.00013584229390681005,
|
170 |
+
"loss": 1.8261,
|
171 |
+
"step": 210
|
172 |
+
},
|
173 |
+
{
|
174 |
+
"epoch": 0.19,
|
175 |
+
"learning_rate": 0.00013225806451612905,
|
176 |
+
"loss": 1.8447,
|
177 |
+
"step": 220
|
178 |
+
},
|
179 |
+
{
|
180 |
+
"epoch": 0.2,
|
181 |
+
"learning_rate": 0.00012867383512544804,
|
182 |
+
"loss": 1.836,
|
183 |
+
"step": 230
|
184 |
+
},
|
185 |
+
{
|
186 |
+
"epoch": 0.2,
|
187 |
+
"learning_rate": 0.00012508960573476703,
|
188 |
+
"loss": 1.8209,
|
189 |
+
"step": 240
|
190 |
+
},
|
191 |
+
{
|
192 |
+
"epoch": 0.21,
|
193 |
+
"learning_rate": 0.00012150537634408603,
|
194 |
+
"loss": 1.8103,
|
195 |
+
"step": 250
|
196 |
+
},
|
197 |
+
{
|
198 |
+
"epoch": 0.21,
|
199 |
+
"eval_accuracy": 0.5280159907778466,
|
200 |
+
"eval_loss": 3.4809513092041016,
|
201 |
+
"eval_runtime": 33.3217,
|
202 |
+
"eval_samples_per_second": 60.261,
|
203 |
+
"eval_steps_per_second": 0.24,
|
204 |
+
"step": 250
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"epoch": 0.22,
|
208 |
+
"learning_rate": 0.00011792114695340501,
|
209 |
+
"loss": 1.8104,
|
210 |
+
"step": 260
|
211 |
+
},
|
212 |
+
{
|
213 |
+
"epoch": 0.23,
|
214 |
+
"learning_rate": 0.00011433691756272403,
|
215 |
+
"loss": 1.8002,
|
216 |
+
"step": 270
|
217 |
+
},
|
218 |
+
{
|
219 |
+
"epoch": 0.24,
|
220 |
+
"learning_rate": 0.000110752688172043,
|
221 |
+
"loss": 1.7979,
|
222 |
+
"step": 280
|
223 |
+
},
|
224 |
+
{
|
225 |
+
"epoch": 0.25,
|
226 |
+
"learning_rate": 0.00010716845878136201,
|
227 |
+
"loss": 1.7871,
|
228 |
+
"step": 290
|
229 |
+
},
|
230 |
+
{
|
231 |
+
"epoch": 0.26,
|
232 |
+
"learning_rate": 0.000103584229390681,
|
233 |
+
"loss": 1.7905,
|
234 |
+
"step": 300
|
235 |
+
},
|
236 |
+
{
|
237 |
+
"epoch": 0.26,
|
238 |
+
"eval_accuracy": 0.5359403052501626,
|
239 |
+
"eval_loss": 3.469621419906616,
|
240 |
+
"eval_runtime": 33.3288,
|
241 |
+
"eval_samples_per_second": 60.248,
|
242 |
+
"eval_steps_per_second": 0.24,
|
243 |
+
"step": 300
|
244 |
+
},
|
245 |
+
{
|
246 |
+
"epoch": 0.26,
|
247 |
+
"learning_rate": 0.0001,
|
248 |
+
"loss": 1.7734,
|
249 |
+
"step": 310
|
250 |
+
},
|
251 |
+
{
|
252 |
+
"epoch": 0.27,
|
253 |
+
"learning_rate": 9.6415770609319e-05,
|
254 |
+
"loss": 1.7913,
|
255 |
+
"step": 320
|
256 |
+
},
|
257 |
+
{
|
258 |
+
"epoch": 0.28,
|
259 |
+
"learning_rate": 9.2831541218638e-05,
|
260 |
+
"loss": 1.76,
|
261 |
+
"step": 330
|
262 |
+
},
|
263 |
+
{
|
264 |
+
"epoch": 0.29,
|
265 |
+
"learning_rate": 8.924731182795699e-05,
|
266 |
+
"loss": 1.7728,
|
267 |
+
"step": 340
|
268 |
+
},
|
269 |
+
{
|
270 |
+
"epoch": 0.3,
|
271 |
+
"learning_rate": 8.566308243727598e-05,
|
272 |
+
"loss": 1.7578,
|
273 |
+
"step": 350
|
274 |
+
},
|
275 |
+
{
|
276 |
+
"epoch": 0.3,
|
277 |
+
"eval_accuracy": 0.5407767755955649,
|
278 |
+
"eval_loss": 3.409736156463623,
|
279 |
+
"eval_runtime": 32.2132,
|
280 |
+
"eval_samples_per_second": 62.335,
|
281 |
+
"eval_steps_per_second": 0.248,
|
282 |
+
"step": 350
|
283 |
+
},
|
284 |
+
{
|
285 |
+
"epoch": 0.31,
|
286 |
+
"learning_rate": 8.207885304659499e-05,
|
287 |
+
"loss": 1.7371,
|
288 |
+
"step": 360
|
289 |
+
},
|
290 |
+
{
|
291 |
+
"epoch": 0.31,
|
292 |
+
"learning_rate": 7.849462365591398e-05,
|
293 |
+
"loss": 1.7593,
|
294 |
+
"step": 370
|
295 |
+
},
|
296 |
+
{
|
297 |
+
"epoch": 0.32,
|
298 |
+
"learning_rate": 7.491039426523297e-05,
|
299 |
+
"loss": 1.7437,
|
300 |
+
"step": 380
|
301 |
+
},
|
302 |
+
{
|
303 |
+
"epoch": 0.33,
|
304 |
+
"learning_rate": 7.132616487455197e-05,
|
305 |
+
"loss": 1.7414,
|
306 |
+
"step": 390
|
307 |
+
},
|
308 |
+
{
|
309 |
+
"epoch": 0.34,
|
310 |
+
"learning_rate": 6.774193548387096e-05,
|
311 |
+
"loss": 1.729,
|
312 |
+
"step": 400
|
313 |
+
},
|
314 |
+
{
|
315 |
+
"epoch": 0.34,
|
316 |
+
"eval_accuracy": 0.5427147714128822,
|
317 |
+
"eval_loss": 3.4043824672698975,
|
318 |
+
"eval_runtime": 33.2117,
|
319 |
+
"eval_samples_per_second": 60.461,
|
320 |
+
"eval_steps_per_second": 0.241,
|
321 |
+
"step": 400
|
322 |
+
},
|
323 |
+
{
|
324 |
+
"epoch": 0.35,
|
325 |
+
"learning_rate": 6.415770609318996e-05,
|
326 |
+
"loss": 1.7609,
|
327 |
+
"step": 410
|
328 |
+
},
|
329 |
+
{
|
330 |
+
"epoch": 0.36,
|
331 |
+
"learning_rate": 6.057347670250897e-05,
|
332 |
+
"loss": 1.7368,
|
333 |
+
"step": 420
|
334 |
+
},
|
335 |
+
{
|
336 |
+
"epoch": 0.37,
|
337 |
+
"learning_rate": 5.6989247311827965e-05,
|
338 |
+
"loss": 1.7354,
|
339 |
+
"step": 430
|
340 |
+
},
|
341 |
+
{
|
342 |
+
"epoch": 0.37,
|
343 |
+
"learning_rate": 5.340501792114696e-05,
|
344 |
+
"loss": 1.7269,
|
345 |
+
"step": 440
|
346 |
+
},
|
347 |
+
{
|
348 |
+
"epoch": 0.38,
|
349 |
+
"learning_rate": 4.982078853046595e-05,
|
350 |
+
"loss": 1.7308,
|
351 |
+
"step": 450
|
352 |
+
},
|
353 |
+
{
|
354 |
+
"epoch": 0.38,
|
355 |
+
"eval_accuracy": 0.5484289625466852,
|
356 |
+
"eval_loss": 3.3802289962768555,
|
357 |
+
"eval_runtime": 32.0517,
|
358 |
+
"eval_samples_per_second": 62.649,
|
359 |
+
"eval_steps_per_second": 0.25,
|
360 |
+
"step": 450
|
361 |
+
},
|
362 |
+
{
|
363 |
+
"epoch": 0.39,
|
364 |
+
"learning_rate": 4.6236559139784944e-05,
|
365 |
+
"loss": 1.7006,
|
366 |
+
"step": 460
|
367 |
+
},
|
368 |
+
{
|
369 |
+
"epoch": 0.4,
|
370 |
+
"learning_rate": 4.265232974910394e-05,
|
371 |
+
"loss": 1.7124,
|
372 |
+
"step": 470
|
373 |
+
},
|
374 |
+
{
|
375 |
+
"epoch": 0.41,
|
376 |
+
"learning_rate": 3.906810035842295e-05,
|
377 |
+
"loss": 1.7225,
|
378 |
+
"step": 480
|
379 |
+
},
|
380 |
+
{
|
381 |
+
"epoch": 0.42,
|
382 |
+
"learning_rate": 3.548387096774194e-05,
|
383 |
+
"loss": 1.7029,
|
384 |
+
"step": 490
|
385 |
+
},
|
386 |
+
{
|
387 |
+
"epoch": 0.43,
|
388 |
+
"learning_rate": 3.1899641577060935e-05,
|
389 |
+
"loss": 1.6896,
|
390 |
+
"step": 500
|
391 |
+
},
|
392 |
+
{
|
393 |
+
"epoch": 0.43,
|
394 |
+
"eval_accuracy": 0.5529602022019449,
|
395 |
+
"eval_loss": 3.345804214477539,
|
396 |
+
"eval_runtime": 32.1251,
|
397 |
+
"eval_samples_per_second": 62.506,
|
398 |
+
"eval_steps_per_second": 0.249,
|
399 |
+
"step": 500
|
400 |
+
},
|
401 |
+
{
|
402 |
+
"epoch": 0.43,
|
403 |
+
"learning_rate": 2.831541218637993e-05,
|
404 |
+
"loss": 1.7141,
|
405 |
+
"step": 510
|
406 |
+
},
|
407 |
+
{
|
408 |
+
"epoch": 0.44,
|
409 |
+
"learning_rate": 2.4731182795698928e-05,
|
410 |
+
"loss": 1.6969,
|
411 |
+
"step": 520
|
412 |
+
},
|
413 |
+
{
|
414 |
+
"epoch": 0.45,
|
415 |
+
"learning_rate": 2.1146953405017922e-05,
|
416 |
+
"loss": 1.7087,
|
417 |
+
"step": 530
|
418 |
+
},
|
419 |
+
{
|
420 |
+
"epoch": 0.46,
|
421 |
+
"learning_rate": 1.7562724014336916e-05,
|
422 |
+
"loss": 1.6779,
|
423 |
+
"step": 540
|
424 |
+
},
|
425 |
+
{
|
426 |
+
"epoch": 0.47,
|
427 |
+
"learning_rate": 1.3978494623655914e-05,
|
428 |
+
"loss": 1.6721,
|
429 |
+
"step": 550
|
430 |
+
},
|
431 |
+
{
|
432 |
+
"epoch": 0.47,
|
433 |
+
"eval_accuracy": 0.5576710752298722,
|
434 |
+
"eval_loss": 3.291583776473999,
|
435 |
+
"eval_runtime": 32.0142,
|
436 |
+
"eval_samples_per_second": 62.722,
|
437 |
+
"eval_steps_per_second": 0.25,
|
438 |
+
"step": 550
|
439 |
+
},
|
440 |
+
{
|
441 |
+
"epoch": 0.48,
|
442 |
+
"learning_rate": 1.039426523297491e-05,
|
443 |
+
"loss": 1.6997,
|
444 |
+
"step": 560
|
445 |
+
},
|
446 |
+
{
|
447 |
+
"epoch": 0.49,
|
448 |
+
"learning_rate": 6.810035842293908e-06,
|
449 |
+
"loss": 1.6679,
|
450 |
+
"step": 570
|
451 |
+
},
|
452 |
+
{
|
453 |
+
"epoch": 0.49,
|
454 |
+
"learning_rate": 3.225806451612903e-06,
|
455 |
+
"loss": 1.6949,
|
456 |
+
"step": 580
|
457 |
+
},
|
458 |
+
{
|
459 |
+
"epoch": 0.5,
|
460 |
+
"step": 588,
|
461 |
+
"total_flos": 6.465698107324629e+18,
|
462 |
+
"train_loss": 1.8579450334821428,
|
463 |
+
"train_runtime": 7071.4809,
|
464 |
+
"train_samples_per_second": 21.266,
|
465 |
+
"train_steps_per_second": 0.083
|
466 |
+
}
|
467 |
+
],
|
468 |
+
"logging_steps": 10,
|
469 |
+
"max_steps": 588,
|
470 |
+
"num_train_epochs": 1,
|
471 |
+
"save_steps": 100,
|
472 |
+
"total_flos": 6.465698107324629e+18,
|
473 |
+
"trial_name": null,
|
474 |
+
"trial_params": null
|
475 |
+
}
|
pretrain/training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cb8db4955aec5080dc0e92d2bf35d69a5bb9242f782e743647aac17c682e4c4b
|
3 |
+
size 5435
|
sft/added_tokens.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<pad>": 125696
|
3 |
+
}
|
sft/config.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"_name_or_path": "output/pretrain/pretrain_epoch05_1651461_20240330223713_1024",
|
4 |
+
"architectures": [
|
5 |
+
"BaichuanForCausalLM"
|
6 |
+
],
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_baichuan.BaichuanConfig",
|
9 |
+
"AutoModelForCausalLM": "modeling_baichuan.BaichuanForCausalLM"
|
10 |
+
},
|
11 |
+
"bos_token_id": 1,
|
12 |
+
"eos_token_id": 2,
|
13 |
+
"hidden_act": "silu",
|
14 |
+
"hidden_size": 4096,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 11008,
|
17 |
+
"max_position_embeddings": 4096,
|
18 |
+
"model_max_length": 4096,
|
19 |
+
"model_type": "baichuan",
|
20 |
+
"num_attention_heads": 32,
|
21 |
+
"num_hidden_layers": 32,
|
22 |
+
"pad_token_id": 0,
|
23 |
+
"rms_norm_eps": 1e-06,
|
24 |
+
"tie_word_embeddings": false,
|
25 |
+
"torch_dtype": "bfloat16",
|
26 |
+
"transformers_version": "4.33.1",
|
27 |
+
"use_cache": false,
|
28 |
+
"vocab_size": 125696,
|
29 |
+
"z_loss_weight": 0
|
30 |
+
}
|
sft/configuration_baichuan.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
2 |
+
|
3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
+
# and OPT implementations in this library. It has been modified from its
|
7 |
+
# original forms to accommodate minor architectural differences compared
|
8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
+
#
|
10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
+
# you may not use this file except in compliance with the License.
|
12 |
+
# You may obtain a copy of the License at
|
13 |
+
#
|
14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
+
#
|
16 |
+
# Unless required by applicable law or agreed to in writing, software
|
17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
+
# See the License for the specific language governing permissions and
|
20 |
+
# limitations under the License.
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.utils import logging
|
24 |
+
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__)
|
27 |
+
|
28 |
+
|
29 |
+
class BaichuanConfig(PretrainedConfig):
|
30 |
+
model_type = "baichuan"
|
31 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
32 |
+
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
vocab_size=125696,
|
36 |
+
hidden_size=4096,
|
37 |
+
intermediate_size=11008,
|
38 |
+
num_hidden_layers=32,
|
39 |
+
num_attention_heads=32,
|
40 |
+
hidden_act="silu",
|
41 |
+
max_position_embeddings=4096,
|
42 |
+
initializer_range=0.02,
|
43 |
+
rms_norm_eps=1e-6,
|
44 |
+
use_cache=True,
|
45 |
+
pad_token_id=0,
|
46 |
+
bos_token_id=1,
|
47 |
+
eos_token_id=2,
|
48 |
+
tie_word_embeddings=False,
|
49 |
+
z_loss_weight=0,
|
50 |
+
**kwargs,
|
51 |
+
):
|
52 |
+
self.vocab_size = vocab_size
|
53 |
+
self.max_position_embeddings = max_position_embeddings
|
54 |
+
self.hidden_size = hidden_size
|
55 |
+
self.intermediate_size = intermediate_size
|
56 |
+
self.num_hidden_layers = num_hidden_layers
|
57 |
+
self.num_attention_heads = num_attention_heads
|
58 |
+
self.hidden_act = hidden_act
|
59 |
+
self.initializer_range = initializer_range
|
60 |
+
self.rms_norm_eps = rms_norm_eps
|
61 |
+
self.use_cache = use_cache
|
62 |
+
self.z_loss_weight = z_loss_weight
|
63 |
+
super().__init__(
|
64 |
+
pad_token_id=pad_token_id,
|
65 |
+
bos_token_id=bos_token_id,
|
66 |
+
eos_token_id=eos_token_id,
|
67 |
+
tie_word_embeddings=tie_word_embeddings,
|
68 |
+
**kwargs,
|
69 |
+
)
|
sft/generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"assistant_token_id": 196,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"do_sample": true,
|
5 |
+
"eos_token_id": 2,
|
6 |
+
"max_new_tokens": 2048,
|
7 |
+
"pad_token_id": 0,
|
8 |
+
"repetition_penalty": 1.05,
|
9 |
+
"temperature": 0.3,
|
10 |
+
"top_k": 5,
|
11 |
+
"top_p": 0.85,
|
12 |
+
"transformers_version": "4.33.1",
|
13 |
+
"user_token_id": 195
|
14 |
+
}
|
sft/generation_utils.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List
|
2 |
+
from queue import Queue
|
3 |
+
|
4 |
+
import torch
|
5 |
+
|
6 |
+
|
7 |
+
def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
|
8 |
+
def _parse_messages(messages, split_role="user"):
|
9 |
+
system, rounds = "", []
|
10 |
+
round = []
|
11 |
+
for i, message in enumerate(messages):
|
12 |
+
if message["role"] == "system":
|
13 |
+
assert i == 0
|
14 |
+
system = message["content"]
|
15 |
+
continue
|
16 |
+
if message["role"] == split_role and round:
|
17 |
+
rounds.append(round)
|
18 |
+
round = []
|
19 |
+
round.append(message)
|
20 |
+
if round:
|
21 |
+
rounds.append(round)
|
22 |
+
return system, rounds
|
23 |
+
|
24 |
+
max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
|
25 |
+
max_input_tokens = model.config.model_max_length - max_new_tokens
|
26 |
+
system, rounds = _parse_messages(messages, split_role="user")
|
27 |
+
system_tokens = tokenizer.encode(system)
|
28 |
+
max_history_tokens = max_input_tokens - len(system_tokens)
|
29 |
+
|
30 |
+
history_tokens = []
|
31 |
+
for round in rounds[::-1]:
|
32 |
+
round_tokens = []
|
33 |
+
for message in round:
|
34 |
+
if message["role"] == "user":
|
35 |
+
round_tokens.append(model.generation_config.user_token_id)
|
36 |
+
else:
|
37 |
+
round_tokens.append(model.generation_config.assistant_token_id)
|
38 |
+
round_tokens.extend(tokenizer.encode(message["content"]))
|
39 |
+
if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:
|
40 |
+
history_tokens = round_tokens + history_tokens # concat left
|
41 |
+
if len(history_tokens) < max_history_tokens:
|
42 |
+
continue
|
43 |
+
break
|
44 |
+
|
45 |
+
input_tokens = system_tokens + history_tokens
|
46 |
+
if messages[-1]["role"] != "assistant":
|
47 |
+
input_tokens.append(model.generation_config.assistant_token_id)
|
48 |
+
input_tokens = input_tokens[-max_input_tokens:] # truncate left
|
49 |
+
return torch.LongTensor([input_tokens]).to(model.device)
|
50 |
+
|
51 |
+
|
52 |
+
class TextIterStreamer:
|
53 |
+
def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):
|
54 |
+
self.tokenizer = tokenizer
|
55 |
+
self.skip_prompt = skip_prompt
|
56 |
+
self.skip_special_tokens = skip_special_tokens
|
57 |
+
self.tokens = []
|
58 |
+
self.text_queue = Queue()
|
59 |
+
self.next_tokens_are_prompt = True
|
60 |
+
|
61 |
+
def put(self, value):
|
62 |
+
if self.skip_prompt and self.next_tokens_are_prompt:
|
63 |
+
self.next_tokens_are_prompt = False
|
64 |
+
else:
|
65 |
+
if len(value.shape) > 1:
|
66 |
+
value = value[0]
|
67 |
+
self.tokens.extend(value.tolist())
|
68 |
+
self.text_queue.put(
|
69 |
+
self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))
|
70 |
+
|
71 |
+
def end(self):
|
72 |
+
self.text_queue.put(None)
|
73 |
+
|
74 |
+
def __iter__(self):
|
75 |
+
return self
|
76 |
+
|
77 |
+
def __next__(self):
|
78 |
+
value = self.text_queue.get()
|
79 |
+
if value is None:
|
80 |
+
raise StopIteration()
|
81 |
+
else:
|
82 |
+
return value
|
83 |
+
|
sft/modeling_baichuan.py
ADDED
@@ -0,0 +1,784 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
2 |
+
|
3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
+
# and OPT implementations in this library. It has been modified from its
|
7 |
+
# original forms to accommodate minor architectural differences compared
|
8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
+
#
|
10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
+
# you may not use this file except in compliance with the License.
|
12 |
+
# You may obtain a copy of the License at
|
13 |
+
#
|
14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
+
#
|
16 |
+
# Unless required by applicable law or agreed to in writing, software
|
17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
+
# See the License for the specific language governing permissions and
|
20 |
+
# limitations under the License.
|
21 |
+
|
22 |
+
|
23 |
+
from .configuration_baichuan import BaichuanConfig
|
24 |
+
from .generation_utils import build_chat_input, TextIterStreamer
|
25 |
+
|
26 |
+
import math
|
27 |
+
from typing import List, Optional, Tuple, Union
|
28 |
+
from threading import Thread
|
29 |
+
|
30 |
+
import torch
|
31 |
+
import torch.utils.checkpoint
|
32 |
+
from torch import nn
|
33 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
34 |
+
from torch.nn import functional as F
|
35 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
36 |
+
from transformers.activations import ACT2FN
|
37 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
38 |
+
from transformers.generation.utils import GenerationConfig
|
39 |
+
from transformers.utils import logging, ContextManagers
|
40 |
+
|
41 |
+
import os
|
42 |
+
from contextlib import contextmanager
|
43 |
+
logger = logging.get_logger(__name__)
|
44 |
+
|
45 |
+
try:
|
46 |
+
from xformers import ops as xops
|
47 |
+
except ImportError:
|
48 |
+
xops = None
|
49 |
+
logger.warning(
|
50 |
+
"Xformers is not installed correctly. If you want to use memory_efficient_attention to accelerate training use the following command to install Xformers\npip install xformers."
|
51 |
+
)
|
52 |
+
|
53 |
+
|
54 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
55 |
+
def _make_causal_mask(
|
56 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
57 |
+
):
|
58 |
+
"""
|
59 |
+
Make causal mask used for bi-directional self-attention.
|
60 |
+
"""
|
61 |
+
bsz, tgt_len = input_ids_shape
|
62 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
63 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
64 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
65 |
+
mask = mask.to(dtype)
|
66 |
+
|
67 |
+
if past_key_values_length > 0:
|
68 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
69 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
70 |
+
|
71 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
72 |
+
"""
|
73 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
74 |
+
"""
|
75 |
+
if len(mask.size()) == 3:
|
76 |
+
bsz, src_len, _ = mask.size()
|
77 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
78 |
+
expanded_mask = mask[:,None,:,:].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
79 |
+
else:
|
80 |
+
bsz, src_len = mask.size()
|
81 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
82 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
83 |
+
|
84 |
+
inverted_mask = 1.0 - expanded_mask
|
85 |
+
|
86 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
87 |
+
|
88 |
+
|
89 |
+
class RMSNorm(nn.Module):
|
90 |
+
def __init__(self, hidden_size, eps=1e-6):
|
91 |
+
"""
|
92 |
+
RMSNorm is equivalent to T5LayerNorm
|
93 |
+
"""
|
94 |
+
super().__init__()
|
95 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
96 |
+
self.variance_epsilon = eps
|
97 |
+
|
98 |
+
def forward(self, hidden_states):
|
99 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
100 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
101 |
+
|
102 |
+
# convert into half-precision if necessary
|
103 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
104 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
105 |
+
|
106 |
+
return self.weight * hidden_states
|
107 |
+
|
108 |
+
|
109 |
+
class RotaryEmbedding(torch.nn.Module):
|
110 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
111 |
+
super().__init__()
|
112 |
+
self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
113 |
+
self.max_seq_len_cached = max_position_embeddings
|
114 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
115 |
+
freqs = torch.outer(t, self.inv_freq)
|
116 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
117 |
+
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32)
|
118 |
+
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32)
|
119 |
+
def forward(self, x, seq_len=None):
|
120 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
121 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
122 |
+
if seq_len > self.max_seq_len_cached:
|
123 |
+
self.max_seq_len_cached = seq_len
|
124 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
125 |
+
freqs = torch.outer(t, self.inv_freq)
|
126 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
127 |
+
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32).to(x.device)
|
128 |
+
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32).to(x.device)
|
129 |
+
elif self.cos_cached.device != x.device:
|
130 |
+
self.cos_cached = self.cos_cached.to(x.device)
|
131 |
+
self.sin_cached = self.sin_cached.to(x.device)
|
132 |
+
return (
|
133 |
+
self.cos_cached[:, :, :seq_len, ...],
|
134 |
+
self.sin_cached[:, :, :seq_len, ...],
|
135 |
+
)
|
136 |
+
|
137 |
+
|
138 |
+
def rotate_half(x):
|
139 |
+
"""Rotates half the hidden dims of the input."""
|
140 |
+
x1 = x[..., : x.shape[-1] // 2]
|
141 |
+
x2 = x[..., x.shape[-1] // 2:]
|
142 |
+
return torch.cat((-x2, x1), dim=-1)
|
143 |
+
|
144 |
+
|
145 |
+
def apply_rotary_pos_emb(q, k, cos_, sin_, position_ids):
|
146 |
+
cos = cos_.squeeze(1).squeeze(0) # [seq_len, dim]
|
147 |
+
sin = sin_.squeeze(1).squeeze(0) # [seq_len, dim]
|
148 |
+
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
149 |
+
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
150 |
+
q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
|
151 |
+
k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
|
152 |
+
return q_embed.to(q.dtype), k_embed.to(k.dtype)
|
153 |
+
|
154 |
+
|
155 |
+
class MLP(nn.Module):
|
156 |
+
def __init__(
|
157 |
+
self,
|
158 |
+
hidden_size: int,
|
159 |
+
intermediate_size: int,
|
160 |
+
hidden_act: str,
|
161 |
+
):
|
162 |
+
super().__init__()
|
163 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
164 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
165 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
166 |
+
self.act_fn = ACT2FN[hidden_act]
|
167 |
+
|
168 |
+
def forward(self, x):
|
169 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
170 |
+
|
171 |
+
|
172 |
+
class Attention(nn.Module):
|
173 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
174 |
+
def __init__(self, config: BaichuanConfig):
|
175 |
+
super().__init__()
|
176 |
+
self.config = config
|
177 |
+
self.hidden_size = config.hidden_size
|
178 |
+
self.num_heads = config.num_attention_heads
|
179 |
+
self.head_dim = self.hidden_size // self.num_heads
|
180 |
+
self.max_position_embeddings = config.max_position_embeddings
|
181 |
+
|
182 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
183 |
+
raise ValueError(
|
184 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
185 |
+
f" and `num_heads`: {self.num_heads})."
|
186 |
+
)
|
187 |
+
self.W_pack = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
|
188 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
189 |
+
self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
190 |
+
|
191 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
192 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
193 |
+
|
194 |
+
def forward(
|
195 |
+
self,
|
196 |
+
hidden_states: torch.Tensor,
|
197 |
+
attention_mask: Optional[torch.Tensor] = None,
|
198 |
+
position_ids: Optional[torch.LongTensor] = None,
|
199 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
200 |
+
output_attentions: bool = False,
|
201 |
+
use_cache: bool = False,
|
202 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
203 |
+
bsz, q_len, _ = hidden_states.size()
|
204 |
+
|
205 |
+
proj = self.W_pack(hidden_states)
|
206 |
+
proj = proj.unflatten(-1, (3, self.hidden_size)).unsqueeze(0).transpose(0, -2).squeeze(-2)
|
207 |
+
query_states = proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
208 |
+
key_states = proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
209 |
+
value_states = proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
210 |
+
|
211 |
+
kv_seq_len = key_states.shape[-2]
|
212 |
+
if past_key_value is not None:
|
213 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
214 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
215 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
216 |
+
# [bsz, nh, t, hd]
|
217 |
+
|
218 |
+
if past_key_value is not None:
|
219 |
+
# reuse k, v, self_attention
|
220 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
221 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
222 |
+
|
223 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
224 |
+
if xops is not None and self.training:
|
225 |
+
attn_weights = None
|
226 |
+
query_states = query_states.transpose(1, 2)
|
227 |
+
key_states = key_states.transpose(1, 2)
|
228 |
+
value_states = value_states.transpose(1, 2)
|
229 |
+
attn_output = xops.memory_efficient_attention(
|
230 |
+
query_states, key_states, value_states, attn_bias=xops.LowerTriangularMask()
|
231 |
+
)
|
232 |
+
else:
|
233 |
+
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
|
234 |
+
attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
|
235 |
+
attn_output = attn_output.transpose(1, 2)
|
236 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
237 |
+
attn_output = self.o_proj(attn_output)
|
238 |
+
|
239 |
+
if not output_attentions:
|
240 |
+
attn_weights = None
|
241 |
+
|
242 |
+
return attn_output, attn_weights, past_key_value
|
243 |
+
|
244 |
+
|
245 |
+
class DecoderLayer(nn.Module):
|
246 |
+
def __init__(self, config: BaichuanConfig):
|
247 |
+
super().__init__()
|
248 |
+
self.hidden_size = config.hidden_size
|
249 |
+
self.self_attn = Attention(config=config)
|
250 |
+
self.mlp = MLP(
|
251 |
+
hidden_size=self.hidden_size,
|
252 |
+
intermediate_size=config.intermediate_size,
|
253 |
+
hidden_act=config.hidden_act,
|
254 |
+
)
|
255 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
256 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
257 |
+
|
258 |
+
def forward(
|
259 |
+
self,
|
260 |
+
hidden_states: torch.Tensor,
|
261 |
+
attention_mask: Optional[torch.Tensor] = None,
|
262 |
+
position_ids: Optional[torch.LongTensor] = None,
|
263 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
264 |
+
output_attentions: Optional[bool] = False,
|
265 |
+
use_cache: Optional[bool] = False,
|
266 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
267 |
+
|
268 |
+
residual = hidden_states
|
269 |
+
|
270 |
+
hidden_states = self.input_layernorm(hidden_states)
|
271 |
+
|
272 |
+
# Self Attention
|
273 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
274 |
+
hidden_states=hidden_states,
|
275 |
+
attention_mask=attention_mask,
|
276 |
+
position_ids=position_ids,
|
277 |
+
past_key_value=past_key_value,
|
278 |
+
output_attentions=output_attentions,
|
279 |
+
use_cache=use_cache,
|
280 |
+
)
|
281 |
+
hidden_states = residual + hidden_states
|
282 |
+
|
283 |
+
# Fully Connected
|
284 |
+
residual = hidden_states
|
285 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
286 |
+
hidden_states = self.mlp(hidden_states)
|
287 |
+
hidden_states = residual + hidden_states
|
288 |
+
|
289 |
+
outputs = (hidden_states,)
|
290 |
+
|
291 |
+
if output_attentions:
|
292 |
+
outputs += (self_attn_weights,)
|
293 |
+
|
294 |
+
if use_cache:
|
295 |
+
outputs += (present_key_value,)
|
296 |
+
|
297 |
+
return outputs
|
298 |
+
|
299 |
+
|
300 |
+
class BaichuanPreTrainedModel(PreTrainedModel):
|
301 |
+
config_class = BaichuanConfig
|
302 |
+
base_model_prefix = "model"
|
303 |
+
supports_gradient_checkpointing = True
|
304 |
+
_no_split_modules = ["DecoderLayer"]
|
305 |
+
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
306 |
+
|
307 |
+
def _init_weights(self, module):
|
308 |
+
std = self.config.initializer_range
|
309 |
+
if isinstance(module, nn.Linear):
|
310 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
311 |
+
if module.bias is not None:
|
312 |
+
module.bias.data.zero_()
|
313 |
+
elif isinstance(module, nn.Embedding):
|
314 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
315 |
+
if module.padding_idx is not None:
|
316 |
+
module.weight.data[module.padding_idx].zero_()
|
317 |
+
|
318 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
319 |
+
if isinstance(module, BaichuanModel):
|
320 |
+
module.gradient_checkpointing = value
|
321 |
+
|
322 |
+
|
323 |
+
class BaichuanModel(BaichuanPreTrainedModel):
|
324 |
+
def __init__(self, config: BaichuanConfig):
|
325 |
+
super().__init__(config)
|
326 |
+
self.padding_idx = config.pad_token_id
|
327 |
+
self.vocab_size = config.vocab_size
|
328 |
+
|
329 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
330 |
+
self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
331 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
332 |
+
|
333 |
+
self.gradient_checkpointing = False
|
334 |
+
# Initialize weights and apply final processing
|
335 |
+
self.post_init()
|
336 |
+
|
337 |
+
def get_input_embeddings(self):
|
338 |
+
return self.embed_tokens
|
339 |
+
|
340 |
+
def set_input_embeddings(self, value):
|
341 |
+
self.embed_tokens = value
|
342 |
+
|
343 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
344 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
345 |
+
# create causal mask
|
346 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
347 |
+
combined_attention_mask = None
|
348 |
+
if input_shape[-1] > 1:
|
349 |
+
combined_attention_mask = _make_causal_mask(
|
350 |
+
input_shape,
|
351 |
+
inputs_embeds.dtype,
|
352 |
+
device=inputs_embeds.device,
|
353 |
+
past_key_values_length=past_key_values_length,
|
354 |
+
)
|
355 |
+
|
356 |
+
if attention_mask is not None:
|
357 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
358 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
359 |
+
inputs_embeds.device
|
360 |
+
)
|
361 |
+
combined_attention_mask = (
|
362 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
363 |
+
)
|
364 |
+
|
365 |
+
return combined_attention_mask
|
366 |
+
|
367 |
+
def forward(
|
368 |
+
self,
|
369 |
+
input_ids: torch.LongTensor = None,
|
370 |
+
attention_mask: Optional[torch.Tensor] = None,
|
371 |
+
position_ids: Optional[torch.LongTensor] = None,
|
372 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
373 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
374 |
+
use_cache: Optional[bool] = None,
|
375 |
+
output_attentions: Optional[bool] = None,
|
376 |
+
output_hidden_states: Optional[bool] = None,
|
377 |
+
return_dict: Optional[bool] = None,
|
378 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
379 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
380 |
+
output_hidden_states = (
|
381 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
382 |
+
)
|
383 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
384 |
+
|
385 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
386 |
+
|
387 |
+
# retrieve input_ids and inputs_embeds
|
388 |
+
if input_ids is not None and inputs_embeds is not None:
|
389 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
390 |
+
elif input_ids is not None:
|
391 |
+
batch_size, seq_length = input_ids.shape
|
392 |
+
elif inputs_embeds is not None:
|
393 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
394 |
+
else:
|
395 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
396 |
+
|
397 |
+
seq_length_with_past = seq_length
|
398 |
+
past_key_values_length = 0
|
399 |
+
|
400 |
+
if past_key_values is not None:
|
401 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
402 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
403 |
+
|
404 |
+
if position_ids is None:
|
405 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
406 |
+
position_ids = torch.arange(
|
407 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
408 |
+
)
|
409 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
410 |
+
else:
|
411 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
412 |
+
|
413 |
+
if inputs_embeds is None:
|
414 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
415 |
+
# embed positions
|
416 |
+
if attention_mask is None:
|
417 |
+
attention_mask = torch.ones(
|
418 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
419 |
+
)
|
420 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
421 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
422 |
+
)
|
423 |
+
|
424 |
+
hidden_states = inputs_embeds
|
425 |
+
|
426 |
+
if self.gradient_checkpointing and self.training:
|
427 |
+
if use_cache:
|
428 |
+
logger.warning_once(
|
429 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
430 |
+
)
|
431 |
+
use_cache = False
|
432 |
+
|
433 |
+
# decoder layers
|
434 |
+
all_hidden_states = () if output_hidden_states else None
|
435 |
+
all_self_attns = () if output_attentions else None
|
436 |
+
next_decoder_cache = () if use_cache else None
|
437 |
+
|
438 |
+
for idx, decoder_layer in enumerate(self.layers):
|
439 |
+
if output_hidden_states:
|
440 |
+
all_hidden_states += (hidden_states,)
|
441 |
+
|
442 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
443 |
+
|
444 |
+
if self.gradient_checkpointing and self.training:
|
445 |
+
|
446 |
+
def create_custom_forward(module):
|
447 |
+
def custom_forward(*inputs):
|
448 |
+
# None for past_key_value
|
449 |
+
return module(*inputs, output_attentions, None)
|
450 |
+
|
451 |
+
return custom_forward
|
452 |
+
|
453 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
454 |
+
create_custom_forward(decoder_layer),
|
455 |
+
hidden_states,
|
456 |
+
attention_mask,
|
457 |
+
position_ids,
|
458 |
+
None,
|
459 |
+
)
|
460 |
+
else:
|
461 |
+
layer_outputs = decoder_layer(
|
462 |
+
hidden_states,
|
463 |
+
attention_mask=attention_mask,
|
464 |
+
position_ids=position_ids,
|
465 |
+
past_key_value=past_key_value,
|
466 |
+
output_attentions=output_attentions,
|
467 |
+
use_cache=use_cache,
|
468 |
+
)
|
469 |
+
|
470 |
+
hidden_states = layer_outputs[0]
|
471 |
+
|
472 |
+
if use_cache:
|
473 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
474 |
+
|
475 |
+
if output_attentions:
|
476 |
+
all_self_attns += (layer_outputs[1],)
|
477 |
+
|
478 |
+
hidden_states = self.norm(hidden_states)
|
479 |
+
|
480 |
+
# add hidden states from the last decoder layer
|
481 |
+
if output_hidden_states:
|
482 |
+
all_hidden_states += (hidden_states,)
|
483 |
+
|
484 |
+
next_cache = next_decoder_cache if use_cache else None
|
485 |
+
if not return_dict:
|
486 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
487 |
+
return BaseModelOutputWithPast(
|
488 |
+
last_hidden_state=hidden_states,
|
489 |
+
past_key_values=next_cache,
|
490 |
+
hidden_states=all_hidden_states,
|
491 |
+
attentions=all_self_attns,
|
492 |
+
)
|
493 |
+
|
494 |
+
|
495 |
+
class NormHead(nn.Module):
|
496 |
+
def __init__(self, hidden_size, vocab_size, bias=False):
|
497 |
+
super().__init__()
|
498 |
+
self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
|
499 |
+
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
500 |
+
self.first_flag = True
|
501 |
+
|
502 |
+
def forward(self, hidden_states):
|
503 |
+
if self.training:
|
504 |
+
norm_weight = nn.functional.normalize(self.weight)
|
505 |
+
elif self.first_flag:
|
506 |
+
self.first_flag = False
|
507 |
+
self.weight.data = nn.functional.normalize(self.weight)
|
508 |
+
norm_weight = self.weight
|
509 |
+
else:
|
510 |
+
norm_weight = self.weight
|
511 |
+
return nn.functional.linear(hidden_states, norm_weight)
|
512 |
+
|
513 |
+
_init_weights = True
|
514 |
+
@contextmanager
|
515 |
+
def no_init_weights(_enable=True):
|
516 |
+
global _init_weights
|
517 |
+
old_init_weights = _init_weights
|
518 |
+
if _enable:
|
519 |
+
_init_weights = False
|
520 |
+
try:
|
521 |
+
yield
|
522 |
+
finally:
|
523 |
+
_init_weights = old_init_weights
|
524 |
+
|
525 |
+
class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
526 |
+
def __init__(self, config, *model_args, **model_kwargs):
|
527 |
+
super().__init__(config, *model_args, **model_kwargs)
|
528 |
+
self.model = BaichuanModel(config)
|
529 |
+
|
530 |
+
self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
|
531 |
+
if hasattr(config, "quantization_config") and isinstance(config.quantization_config, dict) and config.quantization_config.get('load_in_4bit', False):
|
532 |
+
try:
|
533 |
+
from .quantizer import quantize_offline, init_model_weight_int4
|
534 |
+
except ImportError:
|
535 |
+
raise ImportError(f"Needs QLinear to run quantize.")
|
536 |
+
quantize_offline(self, 4)
|
537 |
+
# Initialize weights and apply final processing
|
538 |
+
self.post_init()
|
539 |
+
|
540 |
+
def get_input_embeddings(self):
|
541 |
+
return self.model.embed_tokens
|
542 |
+
|
543 |
+
def set_input_embeddings(self, value):
|
544 |
+
self.model.embed_tokens = value
|
545 |
+
|
546 |
+
def get_output_embeddings(self):
|
547 |
+
return self.lm_head
|
548 |
+
|
549 |
+
def set_output_embeddings(self, new_embeddings):
|
550 |
+
self.lm_head = new_embeddings
|
551 |
+
|
552 |
+
def set_decoder(self, decoder):
|
553 |
+
self.model = decoder
|
554 |
+
|
555 |
+
def get_decoder(self):
|
556 |
+
return self.model
|
557 |
+
|
558 |
+
@classmethod
|
559 |
+
def from_pretrained(
|
560 |
+
cls,
|
561 |
+
pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
|
562 |
+
*model_args,
|
563 |
+
config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
|
564 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
565 |
+
ignore_mismatched_sizes: bool = False,
|
566 |
+
force_download: bool = False,
|
567 |
+
local_files_only: bool = False,
|
568 |
+
token: Optional[Union[str, bool]] = None,
|
569 |
+
revision: str = "main",
|
570 |
+
use_safetensors: bool = None,
|
571 |
+
**kwargs,
|
572 |
+
):
|
573 |
+
# Load config if we don't provide a configuration
|
574 |
+
if not isinstance(config, PretrainedConfig):
|
575 |
+
config_path = config if config is not None else pretrained_model_name_or_path
|
576 |
+
config, model_kwargs = cls.config_class.from_pretrained(
|
577 |
+
config_path,
|
578 |
+
cache_dir=cache_dir,
|
579 |
+
return_unused_kwargs=True,
|
580 |
+
force_download=force_download,
|
581 |
+
resume_download=False,
|
582 |
+
proxies=None,
|
583 |
+
local_files_only=local_files_only,
|
584 |
+
token=token,
|
585 |
+
revision=revision,
|
586 |
+
subfolder="",
|
587 |
+
_from_auto=False,
|
588 |
+
_from_pipeline=None,
|
589 |
+
**kwargs,
|
590 |
+
)
|
591 |
+
else:
|
592 |
+
model_kwargs = kwargs
|
593 |
+
|
594 |
+
if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
|
595 |
+
try:
|
596 |
+
from .quantizer import init_model_weight_int4
|
597 |
+
from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map
|
598 |
+
from accelerate.utils import CustomDtype
|
599 |
+
from accelerate.utils import get_balanced_memory
|
600 |
+
except ImportError:
|
601 |
+
raise ImportError(f"Needs import model weight init func to run quantize.")
|
602 |
+
# Instantiate model.
|
603 |
+
init_contexts = [no_init_weights(_enable=True)]
|
604 |
+
init_contexts.append(init_empty_weights())
|
605 |
+
with ContextManagers(init_contexts):
|
606 |
+
model = cls(config)
|
607 |
+
|
608 |
+
model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin')
|
609 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
610 |
+
model.is_quantized = True
|
611 |
+
|
612 |
+
device_map = kwargs.pop("device_map", None)
|
613 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
614 |
+
|
615 |
+
if device_map is not None:
|
616 |
+
kwargs = {"no_split_module_classes": model._no_split_modules}
|
617 |
+
target_dtype = CustomDtype.INT4
|
618 |
+
max_memory = get_balanced_memory(
|
619 |
+
model,
|
620 |
+
dtype=target_dtype,
|
621 |
+
low_zero=(device_map == "balanced_low_0"),
|
622 |
+
max_memory=None,
|
623 |
+
**kwargs,
|
624 |
+
)
|
625 |
+
kwargs["max_memory"] = max_memory
|
626 |
+
device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs)
|
627 |
+
|
628 |
+
model = init_model_weight_int4(config, model, state_dict)
|
629 |
+
|
630 |
+
# Set model in evaluation mode to deactivate DropOut modules by default
|
631 |
+
model.eval()
|
632 |
+
# If it is a model with generation capabilities, attempt to load the generation config
|
633 |
+
if model.can_generate():
|
634 |
+
try:
|
635 |
+
model.generation_config = GenerationConfig.from_pretrained(
|
636 |
+
pretrained_model_name_or_path,
|
637 |
+
cache_dir=cache_dir,
|
638 |
+
force_download=force_download,
|
639 |
+
resume_download=False,
|
640 |
+
proxies=None,
|
641 |
+
local_files_only=local_files_only,
|
642 |
+
token=token,
|
643 |
+
revision=revision,
|
644 |
+
subfolder="",
|
645 |
+
_from_auto=False,
|
646 |
+
_from_pipeline=None,
|
647 |
+
**kwargs,
|
648 |
+
)
|
649 |
+
except (OSError, TypeError):
|
650 |
+
logger.info(
|
651 |
+
"Generation config file not found, using a generation config created from the model config."
|
652 |
+
)
|
653 |
+
pass
|
654 |
+
|
655 |
+
if device_map is not None:
|
656 |
+
dispatch_model(model, device_map=device_map)
|
657 |
+
|
658 |
+
return model
|
659 |
+
return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
|
660 |
+
config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
|
661 |
+
force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
|
662 |
+
use_safetensors=use_safetensors, **kwargs)
|
663 |
+
|
664 |
+
def forward(
|
665 |
+
self,
|
666 |
+
input_ids: torch.LongTensor = None,
|
667 |
+
attention_mask: Optional[torch.Tensor] = None,
|
668 |
+
position_ids: Optional[torch.LongTensor] = None,
|
669 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
670 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
671 |
+
labels: Optional[torch.LongTensor] = None,
|
672 |
+
use_cache: Optional[bool] = None,
|
673 |
+
output_attentions: Optional[bool] = None,
|
674 |
+
output_hidden_states: Optional[bool] = None,
|
675 |
+
return_dict: Optional[bool] = None,
|
676 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
677 |
+
|
678 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
679 |
+
output_hidden_states = (
|
680 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
681 |
+
)
|
682 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
683 |
+
|
684 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
685 |
+
outputs = self.model(
|
686 |
+
input_ids=input_ids,
|
687 |
+
attention_mask=attention_mask,
|
688 |
+
position_ids=position_ids,
|
689 |
+
past_key_values=past_key_values,
|
690 |
+
inputs_embeds=inputs_embeds,
|
691 |
+
use_cache=use_cache,
|
692 |
+
output_attentions=output_attentions,
|
693 |
+
output_hidden_states=output_hidden_states,
|
694 |
+
return_dict=return_dict,
|
695 |
+
)
|
696 |
+
|
697 |
+
hidden_states = outputs[0]
|
698 |
+
logits = self.lm_head(hidden_states)
|
699 |
+
loss = None
|
700 |
+
if labels is not None:
|
701 |
+
# Shift so that tokens < n predict n
|
702 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
703 |
+
shift_labels = labels[..., 1:].contiguous()
|
704 |
+
# Flatten the tokens
|
705 |
+
loss_fct = CrossEntropyLoss()
|
706 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
707 |
+
shift_labels = shift_labels.view(-1)
|
708 |
+
softmax_normalizer = shift_logits.max(-1).values ** 2
|
709 |
+
z_loss = self.config.z_loss_weight * softmax_normalizer.mean()
|
710 |
+
# Enable model parallelism
|
711 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
712 |
+
loss = loss_fct(shift_logits, shift_labels) + z_loss
|
713 |
+
|
714 |
+
if not return_dict:
|
715 |
+
output = (logits,) + outputs[1:]
|
716 |
+
return (loss,) + output if loss is not None else output
|
717 |
+
|
718 |
+
return CausalLMOutputWithPast(
|
719 |
+
loss=loss,
|
720 |
+
logits=logits,
|
721 |
+
past_key_values=outputs.past_key_values,
|
722 |
+
hidden_states=outputs.hidden_states,
|
723 |
+
attentions=outputs.attentions,
|
724 |
+
)
|
725 |
+
|
726 |
+
def prepare_inputs_for_generation(
|
727 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
728 |
+
):
|
729 |
+
if past_key_values:
|
730 |
+
input_ids = input_ids[:, -1:]
|
731 |
+
|
732 |
+
position_ids = kwargs.get("position_ids", None)
|
733 |
+
if attention_mask is not None and position_ids is None:
|
734 |
+
# create position_ids on the fly for batch generation
|
735 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
736 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
737 |
+
if past_key_values:
|
738 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
739 |
+
|
740 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
741 |
+
if inputs_embeds is not None and past_key_values is None:
|
742 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
743 |
+
else:
|
744 |
+
model_inputs = {"input_ids": input_ids}
|
745 |
+
|
746 |
+
model_inputs.update(
|
747 |
+
{
|
748 |
+
"position_ids": position_ids,
|
749 |
+
"past_key_values": past_key_values,
|
750 |
+
"use_cache": kwargs.get("use_cache"),
|
751 |
+
"attention_mask": attention_mask,
|
752 |
+
}
|
753 |
+
)
|
754 |
+
return model_inputs
|
755 |
+
|
756 |
+
@staticmethod
|
757 |
+
def _reorder_cache(past_key_values, beam_idx):
|
758 |
+
reordered_past = ()
|
759 |
+
for layer_past in past_key_values:
|
760 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
761 |
+
return reordered_past
|
762 |
+
|
763 |
+
def quantize(self, bits: int):
|
764 |
+
try:
|
765 |
+
from .quantizer import quantize_online
|
766 |
+
except ImportError:
|
767 |
+
raise ImportError(f"Needs QLinear to run quantize.")
|
768 |
+
return quantize_online(self, bits)
|
769 |
+
|
770 |
+
def chat(self, tokenizer, messages: List[dict], stream=False,
|
771 |
+
generation_config: Optional[GenerationConfig]=None):
|
772 |
+
generation_config = generation_config or self.generation_config
|
773 |
+
input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
|
774 |
+
if stream:
|
775 |
+
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
776 |
+
Thread(target=self.generate, kwargs=dict(
|
777 |
+
inputs=input_ids, streamer=streamer,
|
778 |
+
generation_config=generation_config,
|
779 |
+
)).start()
|
780 |
+
return streamer
|
781 |
+
else:
|
782 |
+
outputs = self.generate(input_ids, generation_config=generation_config)
|
783 |
+
response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
|
784 |
+
return response
|
sft/pytorch_model-00001-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:66ef7c47e443ac4a0ed7a4bd33d4071ccaf0c96cdfc13b0c85be60b01099bbc8
|
3 |
+
size 9934622796
|
sft/pytorch_model-00002-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1604a6b25e02c17e37d913e9d3e14e9a76826aef2dd07d0b6e8471cab29423fa
|
3 |
+
size 5077401163
|
sft/pytorch_model.bin.index.json
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 15011946496
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "pytorch_model-00002-of-00002.bin",
|
7 |
+
"model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
|
8 |
+
"model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
13 |
+
"model.layers.0.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
14 |
+
"model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
15 |
+
"model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
16 |
+
"model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
17 |
+
"model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
18 |
+
"model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
19 |
+
"model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
20 |
+
"model.layers.1.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
21 |
+
"model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
22 |
+
"model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
23 |
+
"model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
24 |
+
"model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
25 |
+
"model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
26 |
+
"model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
27 |
+
"model.layers.10.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
28 |
+
"model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
29 |
+
"model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
30 |
+
"model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
31 |
+
"model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
32 |
+
"model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
33 |
+
"model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
34 |
+
"model.layers.11.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
35 |
+
"model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
36 |
+
"model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
37 |
+
"model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
38 |
+
"model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
39 |
+
"model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
40 |
+
"model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
41 |
+
"model.layers.12.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
42 |
+
"model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
43 |
+
"model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
44 |
+
"model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
45 |
+
"model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
46 |
+
"model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
47 |
+
"model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
48 |
+
"model.layers.13.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
49 |
+
"model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
50 |
+
"model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
51 |
+
"model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
52 |
+
"model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
53 |
+
"model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
54 |
+
"model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
55 |
+
"model.layers.14.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
56 |
+
"model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
57 |
+
"model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
58 |
+
"model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
59 |
+
"model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
60 |
+
"model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
61 |
+
"model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
62 |
+
"model.layers.15.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
63 |
+
"model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
64 |
+
"model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
65 |
+
"model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
66 |
+
"model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
67 |
+
"model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
68 |
+
"model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
69 |
+
"model.layers.16.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
70 |
+
"model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
71 |
+
"model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
72 |
+
"model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
73 |
+
"model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
74 |
+
"model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
75 |
+
"model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
76 |
+
"model.layers.17.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
77 |
+
"model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
78 |
+
"model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
79 |
+
"model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
80 |
+
"model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
81 |
+
"model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
82 |
+
"model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
83 |
+
"model.layers.18.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
84 |
+
"model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
85 |
+
"model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
86 |
+
"model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
87 |
+
"model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
88 |
+
"model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
89 |
+
"model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
90 |
+
"model.layers.19.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
91 |
+
"model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
92 |
+
"model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
93 |
+
"model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
94 |
+
"model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
95 |
+
"model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
96 |
+
"model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
97 |
+
"model.layers.2.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
98 |
+
"model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
99 |
+
"model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
100 |
+
"model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
101 |
+
"model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
102 |
+
"model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
103 |
+
"model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
104 |
+
"model.layers.20.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
105 |
+
"model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
106 |
+
"model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
107 |
+
"model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
108 |
+
"model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
109 |
+
"model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
110 |
+
"model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
111 |
+
"model.layers.21.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
112 |
+
"model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
113 |
+
"model.layers.22.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
114 |
+
"model.layers.22.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
115 |
+
"model.layers.22.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
116 |
+
"model.layers.22.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
117 |
+
"model.layers.22.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
118 |
+
"model.layers.22.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
119 |
+
"model.layers.22.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
120 |
+
"model.layers.23.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
121 |
+
"model.layers.23.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
122 |
+
"model.layers.23.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
123 |
+
"model.layers.23.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
124 |
+
"model.layers.23.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
125 |
+
"model.layers.23.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
126 |
+
"model.layers.23.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
127 |
+
"model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
128 |
+
"model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
129 |
+
"model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
130 |
+
"model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
131 |
+
"model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
132 |
+
"model.layers.24.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
133 |
+
"model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
134 |
+
"model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
135 |
+
"model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
136 |
+
"model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
137 |
+
"model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
138 |
+
"model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
139 |
+
"model.layers.25.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
140 |
+
"model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
141 |
+
"model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
142 |
+
"model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
143 |
+
"model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
144 |
+
"model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
145 |
+
"model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
146 |
+
"model.layers.26.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
147 |
+
"model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
148 |
+
"model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
149 |
+
"model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
150 |
+
"model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
151 |
+
"model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
152 |
+
"model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
153 |
+
"model.layers.27.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
154 |
+
"model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
155 |
+
"model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
156 |
+
"model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
157 |
+
"model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
158 |
+
"model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
159 |
+
"model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
160 |
+
"model.layers.28.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
161 |
+
"model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
162 |
+
"model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
163 |
+
"model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
164 |
+
"model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
165 |
+
"model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
166 |
+
"model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
167 |
+
"model.layers.29.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
168 |
+
"model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
169 |
+
"model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
170 |
+
"model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
171 |
+
"model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
172 |
+
"model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
173 |
+
"model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
174 |
+
"model.layers.3.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
175 |
+
"model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
176 |
+
"model.layers.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
177 |
+
"model.layers.30.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
178 |
+
"model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
179 |
+
"model.layers.30.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
180 |
+
"model.layers.30.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
181 |
+
"model.layers.30.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
182 |
+
"model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
183 |
+
"model.layers.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
184 |
+
"model.layers.31.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
185 |
+
"model.layers.31.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
186 |
+
"model.layers.31.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
187 |
+
"model.layers.31.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
188 |
+
"model.layers.31.self_attn.W_pack.weight": "pytorch_model-00002-of-00002.bin",
|
189 |
+
"model.layers.31.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
190 |
+
"model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
191 |
+
"model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
192 |
+
"model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
193 |
+
"model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
194 |
+
"model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
195 |
+
"model.layers.4.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
196 |
+
"model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
197 |
+
"model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
198 |
+
"model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
199 |
+
"model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
200 |
+
"model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
201 |
+
"model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
202 |
+
"model.layers.5.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
203 |
+
"model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
204 |
+
"model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
205 |
+
"model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
206 |
+
"model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
207 |
+
"model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
208 |
+
"model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
209 |
+
"model.layers.6.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
210 |
+
"model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
211 |
+
"model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
212 |
+
"model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
213 |
+
"model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
214 |
+
"model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
215 |
+
"model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
216 |
+
"model.layers.7.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
217 |
+
"model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
218 |
+
"model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
219 |
+
"model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
220 |
+
"model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
221 |
+
"model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
222 |
+
"model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
223 |
+
"model.layers.8.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
224 |
+
"model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
225 |
+
"model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
226 |
+
"model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
227 |
+
"model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
228 |
+
"model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
229 |
+
"model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
230 |
+
"model.layers.9.self_attn.W_pack.weight": "pytorch_model-00001-of-00002.bin",
|
231 |
+
"model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
232 |
+
"model.norm.weight": "pytorch_model-00002-of-00002.bin"
|
233 |
+
}
|
234 |
+
}
|
sft/quantizer.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import bitsandbytes as bnb
|
2 |
+
from bitsandbytes.nn.modules import Params4bit, Int8Params
|
3 |
+
import torch
|
4 |
+
|
5 |
+
def Params4bitCuda(self, device):
|
6 |
+
self.data = self.data.cuda(device)
|
7 |
+
self.quant_state[0] = self.quant_state[0].cuda(device)
|
8 |
+
self.quant_state[4][0] = self.quant_state[4][0].cuda(device)
|
9 |
+
self.quant_state[4][1][0] = self.quant_state[4][1][0].cuda(device)
|
10 |
+
self.quant_state[4][1][1] = self.quant_state[4][1][1].cuda(device)
|
11 |
+
|
12 |
+
self.quant_state[6] = self.quant_state[6].cuda(device)
|
13 |
+
return self
|
14 |
+
|
15 |
+
class Linear4bitOnline(torch.nn.Module):
|
16 |
+
def __init__(self, weight, bias, quant_type):
|
17 |
+
super().__init__()
|
18 |
+
self.weight = Params4bit(
|
19 |
+
weight.data, requires_grad=False, compress_statistics=True, quant_type=quant_type
|
20 |
+
)
|
21 |
+
self.compute_dtype = None
|
22 |
+
#self.weight.cuda(weight.device)
|
23 |
+
self.bias = bias
|
24 |
+
|
25 |
+
def forward(self, x: torch.Tensor):
|
26 |
+
# weights are cast automatically as Int8Params, but the bias has to be cast manually
|
27 |
+
if self.bias is not None and self.bias.dtype != x.dtype:
|
28 |
+
self.bias.data = self.bias.data.to(x.dtype)
|
29 |
+
|
30 |
+
if getattr(self.weight, "quant_state", None) is None:
|
31 |
+
print(
|
32 |
+
"FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first."
|
33 |
+
)
|
34 |
+
inp_dtype = x.dtype
|
35 |
+
if self.compute_dtype is not None:
|
36 |
+
x = x.to(self.compute_dtype)
|
37 |
+
|
38 |
+
bias = None if self.bias is None else self.bias.to(self.compute_dtype)
|
39 |
+
out = bnb.matmul_4bit(
|
40 |
+
x, self.weight.t(), bias=bias, quant_state=self.weight.quant_state
|
41 |
+
)
|
42 |
+
|
43 |
+
out = out.to(inp_dtype)
|
44 |
+
|
45 |
+
return out
|
46 |
+
|
47 |
+
class Linear8bitLtOnline(torch.nn.Module):
|
48 |
+
def __init__(
|
49 |
+
self,
|
50 |
+
weight,
|
51 |
+
bias,
|
52 |
+
has_fp16_weights=True,
|
53 |
+
memory_efficient_backward=False,
|
54 |
+
threshold=0.0,
|
55 |
+
index=None,
|
56 |
+
):
|
57 |
+
super().__init__()
|
58 |
+
assert (
|
59 |
+
not memory_efficient_backward
|
60 |
+
), "memory_efficient_backward is no longer required and the argument is deprecated in 0.37.0 and will be removed in 0.39.0"
|
61 |
+
self.state = bnb.MatmulLtState()
|
62 |
+
self.index = index
|
63 |
+
|
64 |
+
# Necessary for stacked layers
|
65 |
+
self.state.threshold = threshold
|
66 |
+
self.state.has_fp16_weights = has_fp16_weights
|
67 |
+
self.state.memory_efficient_backward = memory_efficient_backward
|
68 |
+
if threshold > 0.0 and not has_fp16_weights:
|
69 |
+
self.state.use_pool = True
|
70 |
+
|
71 |
+
self.weight = Int8Params(
|
72 |
+
weight.data,
|
73 |
+
has_fp16_weights=has_fp16_weights,
|
74 |
+
requires_grad=has_fp16_weights,
|
75 |
+
)
|
76 |
+
self.bias = bias
|
77 |
+
|
78 |
+
def init_8bit_state(self):
|
79 |
+
self.state.CB = self.weight.CB
|
80 |
+
self.state.SCB = self.weight.SCB
|
81 |
+
self.weight.CB = None
|
82 |
+
self.weight.SCB = None
|
83 |
+
|
84 |
+
def forward(self, x: torch.Tensor):
|
85 |
+
self.state.is_training = self.training
|
86 |
+
if self.weight.CB is not None:
|
87 |
+
self.init_8bit_state()
|
88 |
+
|
89 |
+
# weights are cast automatically as Int8Params, but the bias has to be cast manually
|
90 |
+
if self.bias is not None and self.bias.dtype != x.dtype:
|
91 |
+
self.bias.data = self.bias.data.to(x.dtype)
|
92 |
+
|
93 |
+
out = bnb.matmul(x, self.weight, bias=self.bias, state=self.state)
|
94 |
+
|
95 |
+
if not self.state.has_fp16_weights:
|
96 |
+
if self.state.CB is not None and self.state.CxB is not None:
|
97 |
+
# we converted 8-bit row major to turing/ampere format in the first inference pass
|
98 |
+
# we no longer need the row-major weight
|
99 |
+
del self.state.CB
|
100 |
+
self.weight.data = self.state.CxB
|
101 |
+
return out
|
102 |
+
|
103 |
+
def quantize_offline(model, bits: int):
|
104 |
+
assert (bits == 4), f'bits: {bits} is not supported'
|
105 |
+
|
106 |
+
for i, layer in enumerate(model.model.layers):
|
107 |
+
layer.self_attn.W_pack = bnb.nn.Linear4bit(
|
108 |
+
layer.self_attn.W_pack.weight.shape[1],
|
109 |
+
layer.self_attn.W_pack.weight.shape[0],
|
110 |
+
False,
|
111 |
+
torch.float16,
|
112 |
+
compress_statistics=True,
|
113 |
+
quant_type="nf4",
|
114 |
+
)
|
115 |
+
layer.self_attn.o_proj = bnb.nn.Linear4bit(
|
116 |
+
layer.self_attn.o_proj.weight.shape[1],
|
117 |
+
layer.self_attn.o_proj.weight.shape[0],
|
118 |
+
False,
|
119 |
+
torch.float16,
|
120 |
+
compress_statistics=True,
|
121 |
+
quant_type="nf4",
|
122 |
+
)
|
123 |
+
|
124 |
+
layer.mlp.gate_proj = bnb.nn.Linear4bit(
|
125 |
+
layer.mlp.gate_proj.weight.shape[1],
|
126 |
+
layer.mlp.gate_proj.weight.shape[0],
|
127 |
+
False,
|
128 |
+
torch.float16,
|
129 |
+
compress_statistics=True,
|
130 |
+
quant_type="nf4",
|
131 |
+
)
|
132 |
+
layer.mlp.down_proj = bnb.nn.Linear4bit(
|
133 |
+
layer.mlp.down_proj.weight.shape[1],
|
134 |
+
layer.mlp.down_proj.weight.shape[0],
|
135 |
+
False,
|
136 |
+
torch.float16,
|
137 |
+
compress_statistics=True,
|
138 |
+
quant_type="nf4",
|
139 |
+
)
|
140 |
+
layer.mlp.up_proj = bnb.nn.Linear4bit(
|
141 |
+
layer.mlp.up_proj.weight.shape[1],
|
142 |
+
layer.mlp.up_proj.weight.shape[0],
|
143 |
+
False,
|
144 |
+
torch.float16,
|
145 |
+
compress_statistics=True,
|
146 |
+
quant_type="nf4",
|
147 |
+
)
|
148 |
+
return model
|
149 |
+
|
150 |
+
def quantize_online(model, bits: int):
|
151 |
+
def quant(weight, bias=None):
|
152 |
+
if bits == 8:
|
153 |
+
linear = Linear8bitLtOnline(
|
154 |
+
weight,
|
155 |
+
bias,
|
156 |
+
has_fp16_weights=False,
|
157 |
+
threshold=6.0,
|
158 |
+
)
|
159 |
+
if bias is not None:
|
160 |
+
linear.bias = torch.nn.Parameter(bias)
|
161 |
+
elif bits == 4:
|
162 |
+
linear = Linear4bitOnline(
|
163 |
+
weight,
|
164 |
+
bias,
|
165 |
+
quant_type="nf4", #fp4/nf4
|
166 |
+
)
|
167 |
+
else:
|
168 |
+
raise ValueError("quantize only support 4/8 bit")
|
169 |
+
return linear
|
170 |
+
|
171 |
+
for i, layer in enumerate(model.model.layers):
|
172 |
+
layer.self_attn.W_pack = quant(layer.self_attn.W_pack.weight)
|
173 |
+
layer.self_attn.o_proj = quant(layer.self_attn.o_proj.weight)
|
174 |
+
layer.mlp.gate_proj = quant(layer.mlp.gate_proj.weight)
|
175 |
+
layer.mlp.down_proj = quant(layer.mlp.down_proj.weight)
|
176 |
+
layer.mlp.up_proj = quant(layer.mlp.up_proj.weight)
|
177 |
+
return model
|
178 |
+
|
179 |
+
def init_model_weight_int4(config, model, state_dict):
|
180 |
+
#replace Params4bit.cuda with Params4bitCuda
|
181 |
+
Params4bit.cuda = Params4bitCuda
|
182 |
+
|
183 |
+
for i in range(config.num_hidden_layers):
|
184 |
+
weight_data = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.data']
|
185 |
+
weight_quant_state = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.quant_state']
|
186 |
+
model.model.layers[i].self_attn.W_pack.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
187 |
+
|
188 |
+
weight_data = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.data']
|
189 |
+
weight_quant_state = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.quant_state']
|
190 |
+
model.model.layers[i].self_attn.o_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
191 |
+
|
192 |
+
weight_data = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.data']
|
193 |
+
weight_quant_state = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.quant_state']
|
194 |
+
model.model.layers[i].mlp.gate_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
195 |
+
|
196 |
+
weight_data = state_dict[f'model.layers.{i}.mlp.up_proj.weight.data']
|
197 |
+
weight_quant_state = state_dict[f'model.layers.{i}.mlp.up_proj.weight.quant_state']
|
198 |
+
model.model.layers[i].mlp.up_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
199 |
+
|
200 |
+
weight_data = state_dict[f'model.layers.{i}.mlp.down_proj.weight.data']
|
201 |
+
weight_quant_state = state_dict[f'model.layers.{i}.mlp.down_proj.weight.quant_state']
|
202 |
+
model.model.layers[i].mlp.down_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
203 |
+
|
204 |
+
model.model.layers[i].input_layernorm.weight = state_dict[f'model.layers.{i}.input_layernorm.weight']
|
205 |
+
model.model.layers[i].post_attention_layernorm.weight = state_dict[f'model.layers.{i}.post_attention_layernorm.weight']
|
206 |
+
|
207 |
+
model.model.embed_tokens.weight = state_dict['model.embed_tokens.weight']
|
208 |
+
model.model.norm.weight = state_dict['model.norm.weight']
|
209 |
+
model.lm_head.weight = state_dict['lm_head.weight']
|
210 |
+
return model
|
sft/special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<unk>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": true,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<unk>",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": true,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
}
|
30 |
+
}
|
sft/tokenization_baichuan.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
2 |
+
|
3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
+
# and OPT implementations in this library. It has been modified from its
|
7 |
+
# original forms to accommodate minor architectural differences compared
|
8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
+
#
|
10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
+
# you may not use this file except in compliance with the License.
|
12 |
+
# You may obtain a copy of the License at
|
13 |
+
#
|
14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
+
#
|
16 |
+
# Unless required by applicable law or agreed to in writing, software
|
17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
+
# See the License for the specific language governing permissions and
|
20 |
+
# limitations under the License.
|
21 |
+
|
22 |
+
import os
|
23 |
+
from shutil import copyfile
|
24 |
+
from typing import Any, Dict, List, Optional, Tuple
|
25 |
+
|
26 |
+
import sentencepiece as spm
|
27 |
+
|
28 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
29 |
+
from transformers.utils import logging
|
30 |
+
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
35 |
+
|
36 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
37 |
+
"vocab_file": {},
|
38 |
+
"tokenizer_file": {},
|
39 |
+
}
|
40 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
|
41 |
+
|
42 |
+
|
43 |
+
class BaichuanTokenizer(PreTrainedTokenizer):
|
44 |
+
"""
|
45 |
+
Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
|
46 |
+
|
47 |
+
Args:
|
48 |
+
vocab_file (`str`):
|
49 |
+
Path to the vocabulary file.
|
50 |
+
"""
|
51 |
+
|
52 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
53 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
54 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
55 |
+
model_input_names = ["input_ids", "attention_mask"]
|
56 |
+
|
57 |
+
def __init__(
|
58 |
+
self,
|
59 |
+
vocab_file,
|
60 |
+
unk_token="<unk>",
|
61 |
+
bos_token="<s>",
|
62 |
+
eos_token="</s>",
|
63 |
+
pad_token=None,
|
64 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
65 |
+
add_bos_token=True,
|
66 |
+
add_eos_token=False,
|
67 |
+
clean_up_tokenization_spaces=False,
|
68 |
+
**kwargs,
|
69 |
+
):
|
70 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
71 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
72 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
73 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
74 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
75 |
+
super().__init__(
|
76 |
+
bos_token=bos_token,
|
77 |
+
eos_token=eos_token,
|
78 |
+
unk_token=unk_token,
|
79 |
+
pad_token=pad_token,
|
80 |
+
add_bos_token=add_bos_token,
|
81 |
+
add_eos_token=add_eos_token,
|
82 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
83 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
84 |
+
**kwargs,
|
85 |
+
)
|
86 |
+
self.vocab_file = vocab_file
|
87 |
+
self.add_bos_token = add_bos_token
|
88 |
+
self.add_eos_token = add_eos_token
|
89 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
90 |
+
self.sp_model.Load(vocab_file)
|
91 |
+
|
92 |
+
def __getstate__(self):
|
93 |
+
state = self.__dict__.copy()
|
94 |
+
state["sp_model"] = None
|
95 |
+
return state
|
96 |
+
|
97 |
+
def __setstate__(self, d):
|
98 |
+
self.__dict__ = d
|
99 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
100 |
+
self.sp_model.Load(self.vocab_file)
|
101 |
+
|
102 |
+
@property
|
103 |
+
def vocab_size(self):
|
104 |
+
"""Returns vocab size"""
|
105 |
+
return self.sp_model.get_piece_size()
|
106 |
+
|
107 |
+
def get_vocab(self):
|
108 |
+
"""Returns vocab as a dict"""
|
109 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
110 |
+
vocab.update(self.added_tokens_encoder)
|
111 |
+
return vocab
|
112 |
+
|
113 |
+
def _tokenize(self, text):
|
114 |
+
"""Returns a tokenized string."""
|
115 |
+
return self.sp_model.encode(text, out_type=str)
|
116 |
+
|
117 |
+
def _convert_token_to_id(self, token):
|
118 |
+
"""Converts a token (str) in an id using the vocab."""
|
119 |
+
return self.sp_model.piece_to_id(token)
|
120 |
+
|
121 |
+
def _convert_id_to_token(self, index):
|
122 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
123 |
+
token = self.sp_model.IdToPiece(index)
|
124 |
+
return token
|
125 |
+
|
126 |
+
def convert_tokens_to_string(self, tokens):
|
127 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
128 |
+
current_sub_tokens = []
|
129 |
+
out_string = ""
|
130 |
+
prev_is_special = False
|
131 |
+
for i, token in enumerate(tokens):
|
132 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
133 |
+
if token in self.all_special_tokens:
|
134 |
+
if not prev_is_special and i != 0:
|
135 |
+
out_string += " "
|
136 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
137 |
+
prev_is_special = True
|
138 |
+
current_sub_tokens = []
|
139 |
+
else:
|
140 |
+
current_sub_tokens.append(token)
|
141 |
+
prev_is_special = False
|
142 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
143 |
+
return out_string
|
144 |
+
|
145 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
146 |
+
"""
|
147 |
+
Save the vocabulary and special tokens file to a directory.
|
148 |
+
|
149 |
+
Args:
|
150 |
+
save_directory (`str`):
|
151 |
+
The directory in which to save the vocabulary.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
`Tuple(str)`: Paths to the files saved.
|
155 |
+
"""
|
156 |
+
if not os.path.isdir(save_directory):
|
157 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
158 |
+
return
|
159 |
+
out_vocab_file = os.path.join(
|
160 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
161 |
+
)
|
162 |
+
|
163 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
164 |
+
copyfile(self.vocab_file, out_vocab_file)
|
165 |
+
elif not os.path.isfile(self.vocab_file):
|
166 |
+
with open(out_vocab_file, "wb") as fi:
|
167 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
168 |
+
fi.write(content_spiece_model)
|
169 |
+
|
170 |
+
return (out_vocab_file,)
|
171 |
+
|
172 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
173 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
174 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
175 |
+
|
176 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
177 |
+
|
178 |
+
if token_ids_1 is not None:
|
179 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
180 |
+
|
181 |
+
return output
|
182 |
+
|
183 |
+
def get_special_tokens_mask(
|
184 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
185 |
+
) -> List[int]:
|
186 |
+
"""
|
187 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
188 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
189 |
+
|
190 |
+
Args:
|
191 |
+
token_ids_0 (`List[int]`):
|
192 |
+
List of IDs.
|
193 |
+
token_ids_1 (`List[int]`, *optional*):
|
194 |
+
Optional second list of IDs for sequence pairs.
|
195 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
196 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
197 |
+
|
198 |
+
Returns:
|
199 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
200 |
+
"""
|
201 |
+
if already_has_special_tokens:
|
202 |
+
return super().get_special_tokens_mask(
|
203 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
204 |
+
)
|
205 |
+
|
206 |
+
bos_token_id = [1] if self.add_bos_token else []
|
207 |
+
eos_token_id = [1] if self.add_eos_token else []
|
208 |
+
|
209 |
+
if token_ids_1 is None:
|
210 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
211 |
+
return (
|
212 |
+
bos_token_id
|
213 |
+
+ ([0] * len(token_ids_0))
|
214 |
+
+ eos_token_id
|
215 |
+
+ bos_token_id
|
216 |
+
+ ([0] * len(token_ids_1))
|
217 |
+
+ eos_token_id
|
218 |
+
)
|
219 |
+
|
220 |
+
def create_token_type_ids_from_sequences(
|
221 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
222 |
+
) -> List[int]:
|
223 |
+
"""
|
224 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
225 |
+
sequence pair mask has the following format:
|
226 |
+
|
227 |
+
```
|
228 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
229 |
+
| first sequence | second sequence |
|
230 |
+
```
|
231 |
+
|
232 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
233 |
+
|
234 |
+
Args:
|
235 |
+
token_ids_0 (`List[int]`):
|
236 |
+
List of ids.
|
237 |
+
token_ids_1 (`List[int]`, *optional*):
|
238 |
+
Optional second list of IDs for sequence pairs.
|
239 |
+
|
240 |
+
Returns:
|
241 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
242 |
+
"""
|
243 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
244 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
245 |
+
|
246 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
247 |
+
|
248 |
+
if token_ids_1 is not None:
|
249 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
250 |
+
|
251 |
+
return output
|
sft/tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:79452955be6b419a65984273a9f08af86042e1c2a75ee3ba989cbf620a133cc2
|
3 |
+
size 2001107
|
sft/tokenizer_config.json
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"auto_map": {
|
5 |
+
"AutoTokenizer": [
|
6 |
+
"tokenization_baichuan.BaichuanTokenizer",
|
7 |
+
null
|
8 |
+
]
|
9 |
+
},
|
10 |
+
"bos_token": {
|
11 |
+
"__type": "AddedToken",
|
12 |
+
"content": "<s>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": true,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false
|
17 |
+
},
|
18 |
+
"clean_up_tokenization_spaces": false,
|
19 |
+
"eos_token": {
|
20 |
+
"__type": "AddedToken",
|
21 |
+
"content": "</s>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": true,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": true
|
26 |
+
},
|
27 |
+
"model_max_length": 1024,
|
28 |
+
"pad_token": {
|
29 |
+
"__type": "AddedToken",
|
30 |
+
"content": "<unk>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": true,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": true
|
35 |
+
},
|
36 |
+
"sp_model_kwargs": {},
|
37 |
+
"tokenizer_class": "BaichuanTokenizer",
|
38 |
+
"unk_token": {
|
39 |
+
"__type": "AddedToken",
|
40 |
+
"content": "<unk>",
|
41 |
+
"lstrip": false,
|
42 |
+
"normalized": true,
|
43 |
+
"rstrip": false,
|
44 |
+
"single_word": true
|
45 |
+
},
|
46 |
+
"use_fast": false
|
47 |
+
}
|
sft/trainer_state.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
sft/training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d0505f4ab35544577ab949653eb814ecf657a661ebf42dfc4604bdd7b2e8375a
|
3 |
+
size 5627
|