Spaces:
Runtime error
Runtime error
NewBreaker
commited on
Commit
•
23aa310
1
Parent(s):
2d83a06
first
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ptuning/README.md +248 -0
- ptuning/README_en.md +115 -0
- ptuning/arguments.py +224 -0
- ptuning/datasets/AdvertiseGen/dev.json +0 -0
- ptuning/datasets/AdvertiseGen/train.json +0 -0
- ptuning/datasets/Zettels/dev.json +21 -0
- ptuning/datasets/Zettels/train.json +140 -0
- ptuning/datasets/chat/dev.json +20 -0
- ptuning/datasets/chat/train.json +102 -0
- ptuning/deepspeed.json +21 -0
- ptuning/ds_train_finetune.sh +28 -0
- ptuning/evaluate.sh +22 -0
- ptuning/evaluate_finetune.sh +18 -0
- ptuning/main.py +445 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/all_results.json +8 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/config.json +32 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/configuration_chatglm.py +105 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/generation_config.json +7 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/ice_text.model +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/modeling_chatglm.py +1472 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/optimizer.pt +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/pytorch_model.bin +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/quantization.py +515 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/rng_state.pth +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/scheduler.pt +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/special_tokens_map.json +7 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/tokenization_chatglm.py +430 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/tokenizer_config.json +22 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/trainer_state.json +616 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/training_args.bin +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-38-54_LAPTOP-U8KCJD82/1682019627.5574055/events.out.tfevents.1682019627.LAPTOP-U8KCJD82.39620.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-38-54_LAPTOP-U8KCJD82/events.out.tfevents.1682019627.LAPTOP-U8KCJD82.39620.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-57-00_LAPTOP-U8KCJD82/1682020719.8067539/events.out.tfevents.1682020719.LAPTOP-U8KCJD82.34144.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-57-00_LAPTOP-U8KCJD82/events.out.tfevents.1682020719.LAPTOP-U8KCJD82.34144.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-03-18_LAPTOP-U8KCJD82/1682021099.0769536/events.out.tfevents.1682021099.LAPTOP-U8KCJD82.4528.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-03-18_LAPTOP-U8KCJD82/events.out.tfevents.1682021099.LAPTOP-U8KCJD82.4528.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-07-46_LAPTOP-U8KCJD82/1682021363.5070107/events.out.tfevents.1682021363.LAPTOP-U8KCJD82.34384.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-07-46_LAPTOP-U8KCJD82/events.out.tfevents.1682021363.LAPTOP-U8KCJD82.34384.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-45-46_LAPTOP-U8KCJD82/1682048840.1281629/events.out.tfevents.1682048840.LAPTOP-U8KCJD82.30268.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-45-46_LAPTOP-U8KCJD82/events.out.tfevents.1682048840.LAPTOP-U8KCJD82.30268.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-48-35_LAPTOP-U8KCJD82/events.out.tfevents.1682049010.LAPTOP-U8KCJD82.40476.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-53-35_LAPTOP-U8KCJD82/1682049309.5723379/events.out.tfevents.1682049309.LAPTOP-U8KCJD82.19992.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-53-35_LAPTOP-U8KCJD82/events.out.tfevents.1682049309.LAPTOP-U8KCJD82.19992.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-59-08_LAPTOP-U8KCJD82/1682049642.960882/events.out.tfevents.1682049642.LAPTOP-U8KCJD82.21296.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-59-08_LAPTOP-U8KCJD82/events.out.tfevents.1682049642.LAPTOP-U8KCJD82.21296.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_12-04-16_LAPTOP-U8KCJD82/1682049952.9553204/events.out.tfevents.1682049952.LAPTOP-U8KCJD82.3092.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_12-04-16_LAPTOP-U8KCJD82/events.out.tfevents.1682049952.LAPTOP-U8KCJD82.3092.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_15-57-52_LAPTOP-U8KCJD82/1682063879.4572506/events.out.tfevents.1682063879.LAPTOP-U8KCJD82.41476.1 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_15-57-52_LAPTOP-U8KCJD82/events.out.tfevents.1682063879.LAPTOP-U8KCJD82.41476.0 +3 -0
- ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_16-51-52_LAPTOP-U8KCJD82/1682067121.1639612/events.out.tfevents.1682067121.LAPTOP-U8KCJD82.14196.1 +3 -0
ptuning/README.md
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ChatGLM-6B-PT
|
2 |
+
本仓库实现了对于 ChatGLM-6B 模型基于 [P-Tuning v2](https://github.com/THUDM/P-tuning-v2) 的微调。P-Tuning v2 将需要微调的参数量减少到原来的 0.1%,再通过模型量化、Gradient Checkpoint 等方法,最低只需要 7GB 显存即可运行。
|
3 |
+
|
4 |
+
下面以 [ADGEN](https://aclanthology.org/D19-1321.pdf) (广告生成) 数据集为例介绍代码的使用方法。
|
5 |
+
|
6 |
+
*Read this in [English](README_en.md).*
|
7 |
+
|
8 |
+
## 软件依赖
|
9 |
+
运行微调需要4.27.1版本的`transformers`。除 ChatGLM-6B 的依赖之外,还需要安装以下依赖
|
10 |
+
```
|
11 |
+
pip install rouge_chinese nltk jieba datasets
|
12 |
+
```
|
13 |
+
## 使用方法
|
14 |
+
|
15 |
+
### 下载数据集
|
16 |
+
ADGEN 数据集任务为根据输入(content)生成一段广告词(summary)。
|
17 |
+
|
18 |
+
```json
|
19 |
+
{
|
20 |
+
"content": "类型#上衣*版型#宽松*版型#显瘦*图案#线条*衣样式#衬衫*衣袖型#泡泡袖*衣款式#抽绳",
|
21 |
+
"summary": "这件衬衫的款式非常的宽松,利落的线条可以很好的隐藏身材上的小缺点,穿在身上有着很好的显瘦效果。领口装饰了一个可爱的抽绳,漂亮的绳结展现出了十足的个性,配合时尚的泡泡袖型,尽显女性甜美可爱的气息。"
|
22 |
+
}
|
23 |
+
```
|
24 |
+
|
25 |
+
从 [Google Drive](https://drive.google.com/file/d/13_vf0xRTQsyneRKdD1bZIr93vBGOczrk/view?usp=sharing) 或者 [Tsinghua Cloud](https://cloud.tsinghua.edu.cn/f/b3f119a008264b1cabd1/?dl=1) 下载处理好的 ADGEN 数据集,将解压后的 `AdvertiseGen` 目录放到本目录下。
|
26 |
+
|
27 |
+
### 训练
|
28 |
+
|
29 |
+
#### P-tuning v2
|
30 |
+
|
31 |
+
运行以下指令进行训练:
|
32 |
+
```shell
|
33 |
+
bash train.sh
|
34 |
+
```
|
35 |
+
`train.sh` 中的 `PRE_SEQ_LEN` 和 `LR` 分别是 soft prompt 长度和训练的学习率,可以进行调节以取得最佳的效果。P-Tuning-v2 方法会冻结全部的模型参数,可通过调整 `quantization_bit` 来被原始模型的量化等级,不加此选项则为 FP16 精度加载。
|
36 |
+
|
37 |
+
在默认配置 `quantization_bit=4`、`per_device_train_batch_size=1`、`gradient_accumulation_steps=16` 下,INT4 的模型参数被冻结,一次训练迭代会以 1 的批处理大小进行 16 次累加的前后向传播,等效为 16 的总批处理大小,此时最低只需 6.7G 显存。若想在同等批处理大小下提升训练效率,可在二者乘积不变的情况下,加大 `per_device_train_batch_size` 的值,但也会带来更多的显存消耗,请根据实际情况酌情调整。
|
38 |
+
|
39 |
+
如果你想要[从本地加载模型](https://github.com/THUDM/ChatGLM-6B#%E4%BB%8E%E6%9C%AC%E5%9C%B0%E5%8A%A0%E8%BD%BD%E6%A8%A1%E5%9E%8B),可以将 `train.sh` 中的 `THUDM/chatglm-6b` 改为你本地的模型路径。
|
40 |
+
|
41 |
+
#### Finetune
|
42 |
+
|
43 |
+
如果需要进行全参数的 Finetune,需要安装 [Deepspeed](https://github.com/microsoft/DeepSpeed),然后运行以下指令:
|
44 |
+
|
45 |
+
```shell
|
46 |
+
bash ds_train_finetune.sh
|
47 |
+
```
|
48 |
+
|
49 |
+
### 推理
|
50 |
+
|
51 |
+
将 `evaluate.sh` 中的 `CHECKPOINT` 更改为训练时保存的 checkpoint 名称,运行以下指令进行模型推理和评测:
|
52 |
+
```shell
|
53 |
+
bash evaluate.sh
|
54 |
+
```
|
55 |
+
**[2023/04/10更新]** 在 P-tuning v2 训练时模型只保存 PrefixEncoder 部分的参数,所以在推理时需要同时加载原 ChatGLM-6B 模型以及 PrefixEncoder 的权重,因此需要指定参数(已更新 `evaluate.sh`) :
|
56 |
+
|
57 |
+
```shell
|
58 |
+
--model_name_or_path THUDM/chatglm-6b
|
59 |
+
--ptuning_checkpoint $CHECKPOINT_PATH
|
60 |
+
```
|
61 |
+
|
62 |
+
仍然兼容旧版全参保存的 Checkpoint,只需要跟之前一样设定 `model_name_or_path`:
|
63 |
+
|
64 |
+
```shell
|
65 |
+
--model_name_or_path $CHECKPOINT_PATH
|
66 |
+
```
|
67 |
+
|
68 |
+
评测指标为中文 Rouge score 和 BLEU-4。生成的结果保存在
|
69 |
+
`./output/adgen-chatglm-6b-pt-8-1e-2/generated_predictions.txt`。
|
70 |
+
|
71 |
+
### 例子
|
72 |
+
#### 示例1
|
73 |
+
* Input: 类型#上衣\*材质#牛仔布\*颜色#白色\*风格#简约\*图案#刺绣\*衣样式#外套\*衣款式#破洞
|
74 |
+
* Label: 简约而不简单的牛仔外套,白色的衣身十分百搭。衣身多处有做旧破洞设计,打破单调乏味,增加一丝造型看点。衣身后背处有趣味刺绣装饰,丰富层次感,彰显别样时尚。
|
75 |
+
* Output[微调前]: 这件上衣的材质是牛仔布,颜色是白色,风格是简约,图案是刺绣,衣样式是外套,衣款式是破洞。
|
76 |
+
* Output[微调后]: 这是一款简约的牛仔外套,破洞设计,将牛仔布破洞,带来一种随意与个性。破洞的牛仔外套,展现出时尚气息,带来一种休闲感。同时,刺绣图案,让整件外套更加立体。
|
77 |
+
|
78 |
+
#### 示例2
|
79 |
+
|
80 |
+
* Input: 类型#裙\*版型#显瘦\*风格#文艺\*风格#简约\*图案#印花\*图案#撞色\*裙下摆#压褶\*裙长#连衣裙\*裙领型#圆领
|
81 |
+
* Label: 文艺个性的印花连衣裙,藏青色底蕴,低调又大气,撞色太阳花分布整个裙身,绚丽而美好,带来时尚减龄的气质。基础款的舒适圆领,简约不失大方,勾勒精致脸庞。领后是一粒包布扣固定,穿脱十分方便。前片立体的打褶设计,搭配后片压褶的做工,增添层次和空间感,显瘦又有型。
|
82 |
+
* Output[微调前]: 类型#裙*版型#显瘦*风格#文艺*风格#简约*图案#印花*图案#撞色*裙下摆#压褶*裙长#连衣裙*裙领型#圆领 1\. 连衣裙:简约风格,裙长为膝盖以上,裙领型为圆领。2\. 裙下摆:压褶设计,使裙摆呈现出流畅的褶皱效果。3\. 裙领型:裙领型为圆领,使穿上连衣裙后更加有型。4\. 版型:采用显瘦设计,让连衣裙看起来更加苗条。5\. 风格:文艺风格,让连衣裙更加有内涵和品味。6\. 图案:印花设计,在连衣裙上印有独特的图案。7\. 撞色:采用撞色设计,让连衣裙在色彩上更加鲜明、富有层次感。
|
83 |
+
* Output[微调后]: 这是一款文艺范的连衣裙,以印花为元素,采用简约的印花,既能够突出文艺气质,又能够展现简约风。在印花的同时又有领子和裙摆的压褶设计,更加凸显文艺气质。简约而不会过于单调,搭配出街,穿着十分舒适。
|
84 |
+
|
85 |
+
### 评估结果
|
86 |
+
|
87 |
+
| | Finetune | P-tuning v2 | LoRA |
|
88 |
+
| ------------- | ----------- | ----- | ------------- |
|
89 |
+
| BLEU-4 | 8.01 | 8.10 | 7.62 |
|
90 |
+
| Rouge-1 | 31.23 | 31.12 | 30.60 |
|
91 |
+
| Rouge-2 | 7.36 | 7.11 | 6.96 |
|
92 |
+
| Rouge-l | 25.08 | 24.97 | 24.80 |
|
93 |
+
| Training Loss | 3.00 | 3.74 | 3.32 |
|
94 |
+
|
95 |
+
|
96 |
+
|
97 |
+
#### 实验设置
|
98 |
+
|
99 |
+
```
|
100 |
+
max_source_length=64
|
101 |
+
max_target_length=64
|
102 |
+
max_steps=3000
|
103 |
+
```
|
104 |
+
|
105 |
+
##### P-tuning v2
|
106 |
+
|
107 |
+
```
|
108 |
+
pre_seq_len=128
|
109 |
+
learning_rate=2e-2
|
110 |
+
quantization_bit=4
|
111 |
+
per_device_train_batch_size=16
|
112 |
+
gradient_accumulation_steps=1
|
113 |
+
```
|
114 |
+
|
115 |
+
##### Finetune
|
116 |
+
|
117 |
+
```
|
118 |
+
learning_rate=1e-4
|
119 |
+
fp16
|
120 |
+
num_gpus=4
|
121 |
+
per_device_train_batch_size=4
|
122 |
+
gradient_accumulation_steps=1
|
123 |
+
```
|
124 |
+
|
125 |
+
##### LoRA
|
126 |
+
|
127 |
+
实现采用的是 [simple_thu_chatglm6b](https://github.com/yuanzhoulvpi2017/zero_nlp/tree/main/simple_thu_chatglm6b)
|
128 |
+
|
129 |
+
```
|
130 |
+
learning_rate=5e-4
|
131 |
+
per_device_train_batch_size=16
|
132 |
+
gradient_accumulation_steps=1
|
133 |
+
```
|
134 |
+
|
135 |
+
|
136 |
+
|
137 |
+
## 模型部署
|
138 |
+
首先载入Tokenizer:
|
139 |
+
|
140 |
+
```python
|
141 |
+
import os
|
142 |
+
import torch
|
143 |
+
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
144 |
+
|
145 |
+
# 载入Tokenizer
|
146 |
+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
|
147 |
+
```
|
148 |
+
|
149 |
+
1. 如果需要加载的是新 Checkpoint(只包含 PrefixEncoder 参数):
|
150 |
+
|
151 |
+
```python
|
152 |
+
config = AutoConfig.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, pre_seq_len=128)
|
153 |
+
model = AutoModel.from_pretrained("THUDM/chatglm-6b", config=config, trust_remote_code=True)
|
154 |
+
prefix_state_dict = torch.load(os.path.join(CHECKPOINT_PATH, "pytorch_model.bin"))
|
155 |
+
new_prefix_state_dict = {}
|
156 |
+
for k, v in prefix_state_dict.items():
|
157 |
+
if k.startswith("transformer.prefix_encoder."):
|
158 |
+
new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
|
159 |
+
model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
|
160 |
+
```
|
161 |
+
注意你可能需要将 `pre_seq_len` 改成你训练时的实际值。如果你是[从本地加载模型](https://github.com/THUDM/ChatGLM-6B#%E4%BB%8E%E6%9C%AC%E5%9C%B0%E5%8A%A0%E8%BD%BD%E6%A8%A1%E5%9E%8B)的话,需要将 `THUDM/chatglm-6b` 改成本地的模型路径(注意不是checkpoint路径)。
|
162 |
+
|
163 |
+
2. 如果需要加载的是旧 Checkpoint(包含 ChatGLM-6B 以及 PrefixEncoder 参数),或者进行的是全参数微调,则直接加载整个 Checkpoint:
|
164 |
+
|
165 |
+
```python
|
166 |
+
model = AutoModel.from_pretrained(CHECKPOINT_PATH, trust_remote_code=True)
|
167 |
+
```
|
168 |
+
|
169 |
+
之后根据需求可以进行量化,也可以直接使用:
|
170 |
+
|
171 |
+
```python
|
172 |
+
# Comment out the following line if you don't use quantization
|
173 |
+
model = model.quantize(4)
|
174 |
+
model = model.half().cuda()
|
175 |
+
model.transformer.prefix_encoder.float()
|
176 |
+
model = model.eval()
|
177 |
+
|
178 |
+
response, history = model.chat(tokenizer, "你好", history=[])
|
179 |
+
```
|
180 |
+
|
181 |
+
## 使用自己的数据集
|
182 |
+
修改 `train.sh` 和 `evaluate.sh` 中的 `train_file`、`validation_file`和`test_file`为你自己的 JSON 格式数据集路径,并将 `prompt_column` 和 `response_column` 改为 JSON 文件中输入文本和输出文本对应的 KEY。可能还需要增大 `max_source_length` 和 `max_target_length` 来匹配你自己的数据集中的最大输入输出长度。
|
183 |
+
|
184 |
+
## 对话数据集
|
185 |
+
|
186 |
+
如需要使用多轮对话数据对模型进行微调,可以提供聊天历史,例如
|
187 |
+
|
188 |
+
```json
|
189 |
+
{
|
190 |
+
"prompt": "是的。上下水管都好的",
|
191 |
+
"response": "那就要检查线路了,一般风扇继电器是由电脑控制吸合的,如果电路存在断路,或者电脑坏了的话会出现继电器不吸合的情况!",
|
192 |
+
"history": [
|
193 |
+
[
|
194 |
+
"长城h3风扇不转。继电器好的。保险丝好的传感器新的风扇也新的这是为什么。就是继电器缺一个信号线",
|
195 |
+
"用电脑能读数据流吗?水温多少"
|
196 |
+
],
|
197 |
+
[
|
198 |
+
"95",
|
199 |
+
"上下水管温差怎么样啊?空气是不是都排干净了呢?"
|
200 |
+
]
|
201 |
+
]
|
202 |
+
}
|
203 |
+
```
|
204 |
+
|
205 |
+
训练时需要指定 `--history_column` 为数据中聊天历史的 key(在此例子中是 `history`),将自动把聊天历史拼接,例如:
|
206 |
+
|
207 |
+
- Input
|
208 |
+
|
209 |
+
```
|
210 |
+
[Round 0]
|
211 |
+
问:长城h3风扇不转。继电器好的。保险丝好的传感器新的风扇也新的这是为什么。就是继电器缺一个信号线
|
212 |
+
��:用电脑能读数据流吗?水温多少
|
213 |
+
[Round 1]
|
214 |
+
问:95
|
215 |
+
答:上下水管温差怎么样啊?空气是不是都排干净了呢?
|
216 |
+
[Round 2]
|
217 |
+
问:是的。上下水管都好的
|
218 |
+
答:
|
219 |
+
```
|
220 |
+
|
221 |
+
- Label
|
222 |
+
|
223 |
+
```
|
224 |
+
那就要检查线路了,一般风扇继电器是由电脑控制吸合的,如果电路存在断路,或者电脑坏了的话会出现继电器不吸合的情况!
|
225 |
+
```
|
226 |
+
|
227 |
+
要注意超过输入长度 `max_source_length` 的内容会被截。
|
228 |
+
|
229 |
+
可以参考以下指令:
|
230 |
+
|
231 |
+
```shell
|
232 |
+
bash train_chat.sh
|
233 |
+
```
|
234 |
+
|
235 |
+
## 引用
|
236 |
+
|
237 |
+
```
|
238 |
+
@inproceedings{liu2022p,
|
239 |
+
title={P-tuning: Prompt tuning can be comparable to fine-tuning across scales and tasks},
|
240 |
+
author={Liu, Xiao and Ji, Kaixuan and Fu, Yicheng and Tam, Weng and Du, Zhengxiao and Yang, Zhilin and Tang, Jie},
|
241 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers)},
|
242 |
+
pages={61--68},
|
243 |
+
year={2022}
|
244 |
+
}
|
245 |
+
```
|
246 |
+
|
247 |
+
|
248 |
+
|
ptuning/README_en.md
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ChatGLM-6B-PT
|
2 |
+
This repository implements tuning of the ChatGLM-6B model based on [P-Tuning v2](https://github.com/THUDM/P-tuning-v2). P-Tuning v2 reduces the amount of parameters that need to be optimized to 0.1% of the full fine-tuning, and then through model quantization, Gradient Checkpoint and other methods, it only needs a minimum of 7GB of video memory to run.
|
3 |
+
|
4 |
+
The following uses the [ADGEN](https://aclanthology.org/D19-1321.pdf) (advertising generation) dataset as an example to introduce how to use the code.
|
5 |
+
|
6 |
+
## Software dependencies
|
7 |
+
Running p-tuning requires version 4.27.1 of `transformers`. In addition to the dependencies of ChatGLM-6B, the following dependencies are required
|
8 |
+
```
|
9 |
+
pip install rouge_chinese nltk jieba datasets
|
10 |
+
```
|
11 |
+
## Instructions
|
12 |
+
|
13 |
+
### Download the dataset
|
14 |
+
The task of the ADGEN dataset is to generate an advertisement word (summary) based on the input (content).
|
15 |
+
|
16 |
+
```json
|
17 |
+
{
|
18 |
+
"content": "类型#上衣*版型#宽松*版型#显瘦*图案#线条*衣样式#衬衫*衣袖型#泡泡袖*衣款式#抽绳",
|
19 |
+
"summary": "这件衬衫的款式非常的宽松,利落的线条可以很好的隐藏身材上的小缺点,穿在身上有着很好的显瘦效果。领口装饰了一个可爱的抽绳,漂亮的绳结展现出了十足的个性,配合时尚的泡泡袖型,尽显女性甜美可爱的气息。"
|
20 |
+
}
|
21 |
+
```
|
22 |
+
|
23 |
+
From [Google Drive](https://drive.google.com/file/d/13_vf0xRTQsyneRKdD1bZIr93vBGOczrk/view?usp=sharing) or [Tsinghua Cloud](https://cloud.tsinghua.edu.cn/f/b3f119a008264b1cabd1/?dl=1) Download the processed ADGEN dataset, and put the decompressed `AdvertiseGen` directory into this directory.
|
24 |
+
|
25 |
+
### Training
|
26 |
+
Run the following commands for training:
|
27 |
+
```shell
|
28 |
+
bash train.sh
|
29 |
+
```
|
30 |
+
`PRE_SEQ_LEN` and `LR` in `train.sh` are soft prompt length and training learning rate respectively, which can be adjusted to achieve the best results. The P-Tuning-v2 method will freeze all model parameters, and the quantization level of the original model can be adjusted by adjusting `quantization_bit`. If this option is not added, it will be loaded with FP16 precision.
|
31 |
+
|
32 |
+
Under the default configuration of `per_device_train_batch_size=1`, `gradient_accumulation_steps=16`, the model parameters of INT4 are frozen, and a training iteration will perform 16 cumulative forward and backward propagations with a batch size of 1, which is equivalent to the total batch size of 16, and only 6.7G GPU memory is required at this time with `quantization_bit=4`. If you want to improve the training efficiency under the same batch size, you can increase the value of `per_device_train_batch_size` while keeping the product of the two unchanged, but it will also bring more GPU memory consumption, please adjust it according to the actual situation.
|
33 |
+
|
34 |
+
### Inference
|
35 |
+
|
36 |
+
Change `CHECKPOINT` in `evaluate.sh` to the checkpoint name saved during training, and run the following commands for model inference and evaluation:
|
37 |
+
```shell
|
38 |
+
bash evaluate.sh
|
39 |
+
```
|
40 |
+
|
41 |
+
The evaluation indicators are Chinese Rouge score and BLEU-4. The generated results are saved in
|
42 |
+
`./output/adgen-chatglm-6b-pt-8-1e-2/generated_predictions.txt`.
|
43 |
+
|
44 |
+
### Example
|
45 |
+
#### Example 1
|
46 |
+
* Input: 类型#上衣\*材质#牛仔布\*颜色#白色\*风格#简约\*图案#刺绣\*衣样式#外套\*衣款式#破洞
|
47 |
+
* Label: 简约而不简单的牛仔外套,白色的衣身十分百搭。衣身多处有做旧破洞设计,打破单调乏味,增加一丝造型看点。衣身后背处有趣味刺绣装饰,丰富层次感,彰显别样时尚。
|
48 |
+
* Output[微调前]: 这件上衣的材质是牛仔布,颜色是白色,风格是简约,图案是刺绣,衣样式是外套,衣款式是破洞。
|
49 |
+
* Output[微调后]: 这是一款简约的牛仔外套,破洞设计,将牛仔布破洞,带来一种随意与个性。破洞的牛仔外套,展现出时尚气息,带来一种休闲感。同时,刺绣图案,让整件外套更加立体。
|
50 |
+
|
51 |
+
#### Example 2
|
52 |
+
|
53 |
+
* Input: 类型#裙\*版型#显瘦\*风格#文艺\*风格#简约\*图案#印花\*图案#撞色\*裙下摆#压褶\*裙长#连衣裙\*裙领型#圆领
|
54 |
+
* Label: 文艺个性的印花连衣裙,藏青色底蕴,低调又大气,撞色太阳花分布整个裙身,绚丽而美好,带来时尚减龄的气质。基础款的舒适圆领,简约不失大方,勾勒精致脸庞。领后是一粒包布扣固定,穿脱十分方便。前片立体的打褶设计,搭配后片压褶的做工,增添层次和空间感,显瘦又有型。
|
55 |
+
* Output[微调前]: 类型#裙*版型#显瘦*风格#文艺*风格#简约*图案#印花*图案#撞色*裙下摆#压褶*裙长#连衣裙*裙领型#圆领 1\. 连衣裙:简约风格,裙长为膝盖以上,裙领型为圆领。2\. 裙下摆:压褶设计,使裙摆呈现出流畅的褶皱效果。3\. 裙领型:裙领型为圆领,使穿上连衣裙后更加有型。4\. 版型:采用显瘦设计,让连衣裙看起来更加苗条。5\. 风格:文艺风格,让连衣裙更加有内涵和品味。6\. 图案:印花设计,在连衣裙上印有独特的图案。7\. 撞色:采用撞色设计,让连衣裙在色彩上更加鲜明、���有层次感。
|
56 |
+
* Output[微调后]: 这是一款文艺范的连衣裙,以印花为元素,采用简约的印花,既能够突出文艺气质,又能够展现简约风。在印花的同时又有领子和裙摆的压褶设计,更加凸显文艺气质。简约而不会过于单调,搭配出街,穿着十分舒适。
|
57 |
+
|
58 |
+
### evaluation result
|
59 |
+
|
60 |
+
| | P-tuning v2 | LoRA |
|
61 |
+
| ------- | ----------- | ----- |
|
62 |
+
| BLEU-4 | 7.71 | 6.13 |
|
63 |
+
| Rouge-1 | 31.35 | 28.36 |
|
64 |
+
| Rouge-2 | 7.19 | 4.38 |
|
65 |
+
| Rouge-l | 25.17 | 17.54 |
|
66 |
+
|
67 |
+
#### Experiment Settings
|
68 |
+
|
69 |
+
```
|
70 |
+
max_source_length=64
|
71 |
+
max_target_length=64
|
72 |
+
per_device_train_batch_size=1
|
73 |
+
gradient_accumulation_steps=16
|
74 |
+
max_steps=3000
|
75 |
+
```
|
76 |
+
|
77 |
+
##### P-tuning v2
|
78 |
+
|
79 |
+
```
|
80 |
+
pre_seq_len=128
|
81 |
+
learning_rate=2e-2
|
82 |
+
quantization_bit=4
|
83 |
+
```
|
84 |
+
|
85 |
+
##### LoRA
|
86 |
+
|
87 |
+
```
|
88 |
+
learning_rate=5e-4
|
89 |
+
```
|
90 |
+
|
91 |
+
The implementation uses [simple_thu_chatglm6b](https://github.com/yuanzhoulvpi2017/zero_nlp/tree/main/simple_thu_chatglm6b)
|
92 |
+
|
93 |
+
|
94 |
+
|
95 |
+
## Model Deployment
|
96 |
+
Replace `THUDM/chatglm-6b` in the corresponding demo or code with the path of the checkpoint after P-Tuning(in the example, `./output/adgen-chatglm-6b-pt-8-1e-2/ checkpoint-3000`). Note that the current fine-tuning does not support multiple rounds of data, so only the responses from the first round of the conversation are fine-tuned.
|
97 |
+
|
98 |
+
## Use your own dataset
|
99 |
+
Modify `train_file`, `validation_file` and `test_file` in `train.sh` and `evaluate.sh` to your own JSON format dataset paths, and change `prompt_column` and `response_column` to the keys in the JSON file corresponding to input text and output text.
|
100 |
+
|
101 |
+
## TODO
|
102 |
+
* [ ] Support for chat data
|
103 |
+
* [ ] Support for full finetuning
|
104 |
+
|
105 |
+
## quoting
|
106 |
+
|
107 |
+
```
|
108 |
+
@inproceedings{liu2022p,
|
109 |
+
title={P-tuning: Prompt tuning can be comparable to fine-tuning across scales and tasks},
|
110 |
+
author={Liu, Xiao and Ji, Kaixuan and Fu, Yicheng and Tam, Weng and Du, Zhengxiao and Yang, Zhilin and Tang, Jie},
|
111 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers)},
|
112 |
+
pages={61--68},
|
113 |
+
year={2022}
|
114 |
+
}
|
115 |
+
```
|
ptuning/arguments.py
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass, field
|
2 |
+
from typing import Optional
|
3 |
+
|
4 |
+
|
5 |
+
@dataclass
|
6 |
+
class ModelArguments:
|
7 |
+
"""
|
8 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
9 |
+
"""
|
10 |
+
|
11 |
+
model_name_or_path: str = field(
|
12 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
13 |
+
)
|
14 |
+
ptuning_checkpoint: str = field(
|
15 |
+
default=None, metadata={"help": "Path to p-tuning v2 checkpoints"}
|
16 |
+
)
|
17 |
+
config_name: Optional[str] = field(
|
18 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
19 |
+
)
|
20 |
+
tokenizer_name: Optional[str] = field(
|
21 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
22 |
+
)
|
23 |
+
cache_dir: Optional[str] = field(
|
24 |
+
default=None,
|
25 |
+
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
|
26 |
+
)
|
27 |
+
use_fast_tokenizer: bool = field(
|
28 |
+
default=True,
|
29 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
30 |
+
)
|
31 |
+
model_revision: str = field(
|
32 |
+
default="main",
|
33 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
34 |
+
)
|
35 |
+
use_auth_token: bool = field(
|
36 |
+
default=False,
|
37 |
+
metadata={
|
38 |
+
"help": (
|
39 |
+
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
|
40 |
+
"with private models)."
|
41 |
+
)
|
42 |
+
},
|
43 |
+
)
|
44 |
+
resize_position_embeddings: Optional[bool] = field(
|
45 |
+
default=None,
|
46 |
+
metadata={
|
47 |
+
"help": (
|
48 |
+
"Whether to automatically resize the position embeddings if `max_source_length` exceeds "
|
49 |
+
"the model's position embeddings."
|
50 |
+
)
|
51 |
+
},
|
52 |
+
)
|
53 |
+
quantization_bit: Optional[int] = field(
|
54 |
+
default=None
|
55 |
+
)
|
56 |
+
pre_seq_len: Optional[int] = field(
|
57 |
+
default=None
|
58 |
+
)
|
59 |
+
prefix_projection: bool = field(
|
60 |
+
default=False
|
61 |
+
)
|
62 |
+
|
63 |
+
|
64 |
+
@dataclass
|
65 |
+
class DataTrainingArguments:
|
66 |
+
"""
|
67 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
68 |
+
"""
|
69 |
+
|
70 |
+
lang: Optional[str] = field(default=None, metadata={"help": "Language id for summarization."})
|
71 |
+
|
72 |
+
dataset_name: Optional[str] = field(
|
73 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
74 |
+
)
|
75 |
+
dataset_config_name: Optional[str] = field(
|
76 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
77 |
+
)
|
78 |
+
prompt_column: Optional[str] = field(
|
79 |
+
default=None,
|
80 |
+
metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
|
81 |
+
)
|
82 |
+
response_column: Optional[str] = field(
|
83 |
+
default=None,
|
84 |
+
metadata={"help": "The name of the column in the datasets containing the summaries (for summarization)."},
|
85 |
+
)
|
86 |
+
history_column: Optional[str] = field(
|
87 |
+
default=None,
|
88 |
+
metadata={"help": "The name of the column in the datasets containing the history of chat."},
|
89 |
+
)
|
90 |
+
train_file: Optional[str] = field(
|
91 |
+
default=None, metadata={"help": "The input training data file (a jsonlines or csv file)."}
|
92 |
+
)
|
93 |
+
validation_file: Optional[str] = field(
|
94 |
+
default=None,
|
95 |
+
metadata={
|
96 |
+
"help": (
|
97 |
+
"An optional input evaluation data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
|
98 |
+
)
|
99 |
+
},
|
100 |
+
)
|
101 |
+
test_file: Optional[str] = field(
|
102 |
+
default=None,
|
103 |
+
metadata={
|
104 |
+
"help": "An optional input test data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
|
105 |
+
},
|
106 |
+
)
|
107 |
+
overwrite_cache: bool = field(
|
108 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
109 |
+
)
|
110 |
+
preprocessing_num_workers: Optional[int] = field(
|
111 |
+
default=None,
|
112 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
113 |
+
)
|
114 |
+
max_source_length: Optional[int] = field(
|
115 |
+
default=1024,
|
116 |
+
metadata={
|
117 |
+
"help": (
|
118 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
119 |
+
"than this will be truncated, sequences shorter will be padded."
|
120 |
+
)
|
121 |
+
},
|
122 |
+
)
|
123 |
+
max_target_length: Optional[int] = field(
|
124 |
+
default=128,
|
125 |
+
metadata={
|
126 |
+
"help": (
|
127 |
+
"The maximum total sequence length for target text after tokenization. Sequences longer "
|
128 |
+
"than this will be truncated, sequences shorter will be padded."
|
129 |
+
)
|
130 |
+
},
|
131 |
+
)
|
132 |
+
val_max_target_length: Optional[int] = field(
|
133 |
+
default=None,
|
134 |
+
metadata={
|
135 |
+
"help": (
|
136 |
+
"The maximum total sequence length for validation target text after tokenization. Sequences longer "
|
137 |
+
"than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`."
|
138 |
+
"This argument is also used to override the ``max_length`` param of ``model.generate``, which is used "
|
139 |
+
"during ``evaluate`` and ``predict``."
|
140 |
+
)
|
141 |
+
},
|
142 |
+
)
|
143 |
+
pad_to_max_length: bool = field(
|
144 |
+
default=False,
|
145 |
+
metadata={
|
146 |
+
"help": (
|
147 |
+
"Whether to pad all samples to model maximum sentence length. "
|
148 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
|
149 |
+
"efficient on GPU but very bad for TPU."
|
150 |
+
)
|
151 |
+
},
|
152 |
+
)
|
153 |
+
max_train_samples: Optional[int] = field(
|
154 |
+
default=None,
|
155 |
+
metadata={
|
156 |
+
"help": (
|
157 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
158 |
+
"value if set."
|
159 |
+
)
|
160 |
+
},
|
161 |
+
)
|
162 |
+
max_eval_samples: Optional[int] = field(
|
163 |
+
default=None,
|
164 |
+
metadata={
|
165 |
+
"help": (
|
166 |
+
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
167 |
+
"value if set."
|
168 |
+
)
|
169 |
+
},
|
170 |
+
)
|
171 |
+
max_predict_samples: Optional[int] = field(
|
172 |
+
default=None,
|
173 |
+
metadata={
|
174 |
+
"help": (
|
175 |
+
"For debugging purposes or quicker training, truncate the number of prediction examples to this "
|
176 |
+
"value if set."
|
177 |
+
)
|
178 |
+
},
|
179 |
+
)
|
180 |
+
num_beams: Optional[int] = field(
|
181 |
+
default=None,
|
182 |
+
metadata={
|
183 |
+
"help": (
|
184 |
+
"Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
|
185 |
+
"which is used during ``evaluate`` and ``predict``."
|
186 |
+
)
|
187 |
+
},
|
188 |
+
)
|
189 |
+
ignore_pad_token_for_loss: bool = field(
|
190 |
+
default=True,
|
191 |
+
metadata={
|
192 |
+
"help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
|
193 |
+
},
|
194 |
+
)
|
195 |
+
source_prefix: Optional[str] = field(
|
196 |
+
default="", metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
|
197 |
+
)
|
198 |
+
|
199 |
+
forced_bos_token: Optional[str] = field(
|
200 |
+
default=None,
|
201 |
+
metadata={
|
202 |
+
"help": (
|
203 |
+
"The token to force as the first generated token after the decoder_start_token_id."
|
204 |
+
"Useful for multilingual models like mBART where the first generated token"
|
205 |
+
"needs to be the target language token (Usually it is the target language token)"
|
206 |
+
)
|
207 |
+
},
|
208 |
+
)
|
209 |
+
|
210 |
+
|
211 |
+
|
212 |
+
def __post_init__(self):
|
213 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None and self.test_file is None:
|
214 |
+
raise ValueError("Need either a dataset name or a training/validation/test file.")
|
215 |
+
else:
|
216 |
+
if self.train_file is not None:
|
217 |
+
extension = self.train_file.split(".")[-1]
|
218 |
+
assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
|
219 |
+
if self.validation_file is not None:
|
220 |
+
extension = self.validation_file.split(".")[-1]
|
221 |
+
assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
|
222 |
+
if self.val_max_target_length is None:
|
223 |
+
self.val_max_target_length = self.max_target_length
|
224 |
+
|
ptuning/datasets/AdvertiseGen/dev.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ptuning/datasets/AdvertiseGen/train.json
ADDED
Binary file (53.8 MB). View file
|
|
ptuning/datasets/Zettels/dev.json
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "可见光图像的成像过程受光照强度及环境影响,低照度环境下采集的可见光图像存在信噪比、对比度、分辨率均较低等特点,给进一步图像处理,图像识别、目标检测等任务带来更严峻的挑战."}
|
2 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "当前,人类在水下和低光环境中的活动越来越频繁,比如:目标检测、智能识别、水下探测等。因水下和低光图像具有很多的相似情况,因此,对于如何解决两者共同存在的问题成为了比较热门的话题"}
|
3 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "随着国家科技水平的发展和国民经济水平的提高,人们对于出行的要求也让汽车行业得以迅猛的发展.但是,汽车行业的迅猛发展,在方便人们的出行的同时,也导致了交通事故率的显著提高."}
|
4 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "在有雾的天气下,大气中存在着很多悬浮的小液滴,导致所获取图像的可视性显著下降,会出现场景细节模糊、图像色彩衰减等问题。随着社会的发展,机器视觉被广泛应用于安全监控、目标识别、遥感成像、图像分类等领域,机器视觉的有效性通常建立在具有较好可视性的输入图像之上。因此,消除有雾天气产生的不良视觉效果,获得可视性良好的图像具有重要的意义。"}
|
5 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "随着智能算法的发展,图像识别技术越来越受到人们的关注,科研人员在训练识别模型的时候也希望得到更准确、更稳定的识别模型。但是,图像数据库的图像质量可能会受到各种各样外在因素的影响,如光照不均、相对运动和色彩失真等。对图像进行增强处理,可提高图像品质,丰富图像的信息量,便于计算机进一步理解图像。因此,彩色图像的增强处理技术在交通智能化、军事国防和医学等方面能够发挥相当重要的作用。"}
|
6 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "日常生活中经常需要在低光条件下捕捉图像,例如在夜间或昏暗的室内房间。在此环境下拍摄的图像往往会出现能见度差、对比度低、噪声大等多种问题。虽然自动曝光机制(如ISO、快门、闪光灯等)可以增强图像亮度,但同时也会产生其他的影响(如模糊、过饱和度等)。"}
|
7 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "受光照强度的影响,在夜间和背光条件下采集的图像往往含有较低的对比度、大面积的暗区域和明显的噪声污染。这些降质图像往往导致人们无法正确地辨识场景内容,也常常给图像检索、多媒体信息安全等后续计算机视觉任务带来严峻的挑战。因此,低照度图像增强具有重要的理论价值和现实意义,受到学界广泛关注。"}
|
8 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "在光线昏暗的环境下,摄影师拍摄出正常成像非常困难。在更极端的黑暗情况下,如光照严重受限(月光)或短时间的曝光,成像就更为困难。低光下拍摄的图像和极低光下拍摄的图像对比如图1所示,明显看出极低光下拍摄的图像相比低光下拍摄的图像被隐藏的信息更多。"}
|
9 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "在图像采集过程中,所在场景的光照条件往往是影响图像质量的重要因素之一,在现代社会生产生活中,人们采集图像变的更为方便和快捷,由于光照条件不足产生的低照度图像识别度不高,导致缺乏可用性,并对后续的图像处理、目标识别、语义分割等仸务造成了困难"}
|
10 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "可见光图像的成像过程受光照强度及环境影响,低照度环境下采集的可见光图像存在信噪比、对比度、分辨率均较低等特点,给进一步图像处理,图像识别、目标检测等任务带来更严峻的挑战"}
|
11 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "在很多计算机视觉任务中,如目标检测、图像检索、图像分割等,都要求输入图像亮度合适、细节清晰。然而,在弱光照或者曝光不足的情况下,采集到的图像存在亮度低、色彩不饱和、细节模糊等缺点,这些缺点将影响到来操作来都不像像后续的计算机视觉任务。因此,研究弱光照图像的增强很有必要。"}
|
12 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "随着计算机视觉领域的収展,携带着丰富信息的高质量图像无论是在日常生活还是科学研究中都有着巨大的研究潜力。但是,由于不同的光照条件、周围的噪声等原因,图像质量高低不一,严重影响了人们判别图片中的信息,从而引起不必要的冲突和结果。尤其是在黑暗条件下,人们难以识别摄像头捕捉到的图像信息,而且智能系统很大程度上也依赖于高质量的输入图像,为了解决这个问题,本文就低照度图像问题迚行了研究。"}
|
13 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "在光线昏暗的环境下,摄影师拍摄出正常成像非常困难。在更极端的黑暗情况下,如光照严重受限(月光)或短时间的曝光,成像就更为困难。低光下拍摄的图像和极低光下拍摄的图像对比如图1所示,明显看出极低光下拍摄的图像相比低光下拍摄的图像被隐藏的信息更多。"}
|
14 |
+
{"content": "语料描述-为什么要进行低光增强?", "summary": "部分图像增强在计算机断层成像、工业产品质量检验、交通监控及卫星图像处理中有着广泛的应用。其中低照度图像是一种常见的图像种类,它的主要特点是微光、暗色区域占图像主要部分。造成图像低照度的原因有很多,例如光线不足,摄影设备性能有限以及设备配置不正确等,这类图像可见性偏低,不便于观察与分析,且会对相关应用产生负面影响,尤其是在图像的匹配、融合、分析、检测以及分割方面,给数字图像处理带来极大挑战。"}
|
15 |
+
{"content": "结论 ", "summary": "本文提出了一种可以对夜间的油茶果果实图像进行快速、精准识别的目标检测网络YOLON,(1)可以对夜间的油茶果果实目标进行进行检测,mAP可以达到98.17%,高于YOLO v4、EfficientNet、YOLOX等对比算法的mAP,表明YOLON可以较好地对夜间油茶果的进行检测。(2)对不同遮挡程度下的(3)但是YOLON对的运行速度尚有待提高,此外运行时对GPU的依赖程度较大,无法在CPU上完成快速推理,对于嵌入式设备的部署尚不理想,这也是本文未来重点的研究方向。"}
|
16 |
+
{"content": "单果、双果、多果、整树的识别效果 ", "summary": "结果表明,随着果实数量的增加,成功率呈下降趋势。在2个果实中,成功率为100%。三果、四果、五果串的成功率分别为91.6%、88.9%和85.3%。"}
|
17 |
+
{"content": "检测效果对比 ", "summary": "使用YOLON、YOLOR、和YOLO V4在COA数据集上进行了进一步的比较, 本文提出的YOLON其在COA数据集上的表现优于YOLO V4 和YOLOR。"}
|
18 |
+
{"content": "算法的运行时间 ", "summary": "随着不同分辨率的图像尺寸的增加,时间与mAP的变化,选取最适合的分辨率,可以花上去两个曲线,找两条曲线相交的那个点,类似于下面的效果"}
|
19 |
+
{"content": "结果 ", "summary": "为了验证该方法的有效性,对COA数据集中216张测试图像进行了测试,结果如表1所示,该方法的准备率和召回率分别为90.00%和90.00%,平均IOU和mAP分别为90.00%和90.00%,检测速度可达30f/s,能够满足油茶果采摘机器人对果实进行实时检测的需求,可以为算法部署在油茶果采摘机器人的开发上提供技术支持。"}
|
20 |
+
{"content": "本文要研究的重点问题 ", "summary": "夜间油茶果的果实目标识别"}
|
21 |
+
{"content": "本文提出的基于多分支结构和U-net结合的低照度图像增强算法有以下三点贡献: ", "summary": "1)本文提出了一种新颖的端到端的低照度图像增强网络,可以应用于多种场景,计算速度和准确率也都有所提升。此网络还结合了多分支网络和U-net迚行特征提取,取得了不错的结果。2)本文的方法在噪声抑制、对比度增强等方面有着较好的效果,能够有效地减少噪声的影响。3)本文使用大量的实验来证明所提出模型的有效性,且使用了很多优秀的方法来进行对比,并且从定性和定量的角度分析对比结果,取得了满意的效果。总体来说,本文提出的斱法在各方面都很大程度上优于现有的算法。"}
|
ptuning/datasets/Zettels/train.json
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{"content": "目前国内外常见的低照度图像增强方法主要分为四种: ", "summary": "(1)基于直方图增强法(HistogramEqualization,HE).该方法通过整体调整图像直方图分布来增强图像亮度和对比度,此类方法精简快捷,但常出现颜色失真、细节丢失等问题."}
|
2 |
+
{"content": "目前国内外常见的低照度图像增强方法主要分为四种: ", "summary": "(2)基于Retinex增强法.Land提出人眼视觉亮度与颜色感知由实际物体自身的反射率决定,与环境光强度无关.根据Retinex理论提出带色彩恢复的多尺度Retinex(multi-scaleRetinexwithcolorrestora-tion,MSRCR)和LIME等多种经典算法.此类方法容易出现颜色失真,虽然有学者增加颜色校正模块,但仍无法完全克服颜色失真问题."}
|
3 |
+
{"content": "目前国内外常见的低照度图像增强方法主要分为四种: ", "summary": "(3)基于伪雾图增强法.该方法利用低照度图像的反转图像通过去雾算法进行增强.如Dong等提出增强方法取得较好的照度增强效果,但在应对复杂场景增强时容易出现块效应和噪声."}
|
4 |
+
{"content": "目前国内外常见的低照度图像增强方法主要分为四种: ", "summary": "(4)基于神经网络的增强法.此类方法利用神经网络学习低照度图像到正常照度图像的映射,如刘超等提出利用卷积自编码网络从低照度图像训练集中学习图像特征.此类方法能够有效的对低照度图像进行照度增强,但增强的图像在细节及色彩方面有所欠缺."}
|
5 |
+
{"content": "单纯地增加曝光量的问题 ", "summary": "相机的动态范围有限,如果增加相机曝光度来揭示曝光不足区域的信息,那么曝光良好的区域可能会出现过度曝光甚至饱和的现象。"}
|
6 |
+
{"content": "单纯地增加曝光量的问题 ", "summary": "在图像拍摄过程中可以通过提高感光度(ISO)增加亮度,但不可避免地会放大噪音。采用缩放或直方图拉伸等一系列后期处理方法可以减弱噪音的影响,但并不能有效解决信噪比低 的问题。在拍摄过程中采用打开光圈、延长曝光时间、使用闪光灯等物理方法虽然能达到在低光环境下增加信噪比的效果,但图像会因为相机抖动或物体的移动而变得模糊。"}
|
7 |
+
{"content": "说明别人方法不好 ", "summary": "为了解决这一问题,研究人员提出了一些有效的图像增强技术。采用这些方法虽然可以获到良好的主观质量,却不能准确地反映场景图像的真实亮度和对比度。"}
|
8 |
+
{"content": "说明别人方法不好 ", "summary": "LIME虽整体图片偏亮,但是却与原色彩模式相比,存在失真的问题"}
|
9 |
+
{"content": "深度学习算法的好处 ", "summary": "深度学习方法具有较高的 能力,同时可以通过训练样本的控制来提供较多的先验知识 来降低低照度图像重建问题的病态程度,可以针对特定的低照度数据集实现较好的增强效果。"}
|
10 |
+
{"content": "油茶果描述 ", "summary": "油茶Camelliaoleifera是我国最主要的经济树种之一,与油棕、油橄榄和椰子并称为世界四大木本食用油料树种。因其良好的适应性,油茶适宜种植在我国南方广大的红壤丘陵地区,主要分布在湖南、江西、浙江、海南、广东、广西、重庆、四川、贵州、湖北、安徽、福建等地。其中湖南、江西和广西三省(区)合计栽培面积占全国总面积的75%以上,常年产茶油量占全国总产量的80%以上。据初步统计,截至2011年,全国已选育出的油茶新品种共有365个,其中通过国家审定的油茶良种有73个,省级油茶良种292个。品种繁多、良莠不齐,优良品种经过长期嫁接繁殖逐步退化等问题给油茶产业的发展带来了严重的消极影响。"}
|
11 |
+
{"content": "油茶果描述 ", "summary": "油茶林主要分布于我国南方地区,其油茶果实经加工后,可广泛用于食品、工业、医药等重要领域,是重要的经济林树种之一。油茶树树叶繁茂,枝桠交叠,油茶果成熟时呈球形或椭圆形,颜色呈淡黄色或暗红色、或呈绿色,与树叶颜色相近。油茶果目标与背景成多元信息叠加,且受光照、摇晃等不稳定因素的影响,以上因素致使快速、准确地识别油茶果极其困难。在对林果采摘机器人视觉识别技术的相关研究中,目前主要集中于对目标的颜色。形态、纹理、光谱等单特征识别。在多特征识别研究中,Hayashi等人提出了基于形态学特征及颜色特征的茄子图像分割法,并采用网格模板获取完整的茄子目标;Zhao等人利用纹理特征和颜色特征识别树上苹果;Blasco等人结合多光谱特征和形态学特征,利用贝叶斯分类器检测柑橘表面;王津京等人利用支持向量机算法对待识别的目标苹果的颜色和形状特征进行了综合分类。"}
|
12 |
+
{"content": "油茶果描述 ", "summary": "���积神经网络可以自动提取特征,并分类检测,精度高,实时性强,成为果蔬目标检测的主流框架。而Faster R-CNN 卷积神经网络经过RCNN、Fast-RCNN的不断改进,精度和检测效率都得到了进一步的提高。在卷积神经网络果蔬识别方面已经有大量的研究。西北农林科技大学冯亚利使用改进的DY3TNet模型实现了田间猕猴桃果实的检测。闫建伟等为了快速准确识别自然环境下刺梨果实,提出了一种基于改进的Faster-RCNN的刺梨果实识别方法。傅隆生等为了实现田间条件下快速、准确地识别多簇猕猴桃果实,提出了一种基于LeNet卷积神经网络的深度学习模型进行多簇猕猴桃果实图像的识别。程鸿芳等针对传统的基于内容的识别方法在特征提取方面存在的计算复杂、特征不可迁移等问题,对LeNet卷积神经网络结构进行改进,设计了一种基于改进LeNet卷积神经网络的苹果目标识别模型,并利用该模型对不同场景的苹果图像进行了识别与验证,综合识别率达到93.79%;与其他方法相比,该算法具有较强的抗干扰能力,图像识别速度快,识别率更高。中南林业科技大学张习之等提出了一种基于改进卷积自编码机神经网络的油茶果图像自动识别方法,该改进算法100次迭代所需时间为166s,平均识别准确率为90.4%。"}
|
13 |
+
{"content": "低光增强深度学习算法使用的数据集 ", "summary": "CHEN等在2018年首次采用SID(see in the dark)数据集,基于数据驱动方法训练一个端到端的网络,实现了极端低光情况下图像的增强,取得了良好的效果,但该方法设计的网络对物体细节的还原仍然有着很大的不足,增强之后的图像中物体的边缘存在模糊现象,且该方法只在其构建的数据集上表现良好。"}
|
14 |
+
{"content": "说明目前用的人很少 ", "summary": "目前在卷积神经网络识别油茶果方面的研究较少,尚无文献用Faster-RCNN卷积网络的方法识别油茶果。本文选用Faster-RCNN交替优化训练方法,并使用Faster-RCNN卷积神经网络对油茶果进行了识别。"}
|
15 |
+
{"content": "最后一段说明自己要干啥 ", "summary": "为了提高低照度图像的图像质量,本文利用生成对抗网络的学习能力,提出一种基于U-Net生成对抗网络的低照度图像增强方法.该方法利用U-Net结构和深度卷积结构构造生成对抗网络,实现利用低照度图像生成照度与正常照度图像拟合的增强图像.实验表明,该方法能够有效提高低照度图像的亮度、对比度."}
|
16 |
+
{"content": "低照度图像产生的硬件原因 ", "summary": "在低照度条件下拍摄的图像通常会出现不同程度的质量退化,虽然专业设备和先进的摄影技术可以在一定程度上缓解这些退化,但固有原因产生的噪声是不可避免的。由于没有足够的光,相机传感器的输出易受系统的固有噪声干扰,因此输出的图像可能会在曝光不足的区域丢失部分重要信息,从而加大了计算机视觉任务的难度。"}
|
17 |
+
{"content": "深度学习发展很快 ", "summary": "近年来,深度学习发展迅速,在高层次视觉任务中应用非常广泛,如图像识别、语义分割等。与此同时,也有一些研究人员尝试用深度学习算法去解决低层次图像领域问题,如图像去噪、图像去雾、图像超分辨率等,这些算法也取得了较好的成绩。相对于传统算法,深度学习算法具有不需要人工设计特征提取方法,可直接端到端地训练和输出结果等优势"}
|
18 |
+
{"content": "本文的贡献 ", "summary": "本文提出的基于多分支结构和U-net结合的低照度图像增强算法有以下三点贡献: ∑"}
|
19 |
+
{"content": "引出我们研究的问题 ", "summary": "针对低照度条件下的图像对比度不高、颜色失衡和存在噪声的问题,提出了一种基于卷积神经网络的低照度图像增强模型。"}
|
20 |
+
{"content": "引言中引出本研究的表述 ", "summary": "为了对低照度图像进行增强,本文利用卷积卷积神经网络的非线性映射能力,提出了一种基于U-Net网络的低照度图像增强方法。"}
|
21 |
+
{"content": "引言中引出本研究的表述 ", "summary": "利用数据驱动的方式,实现了对低照度的图像进行增强,实验表明,该方法能够有效提高低照度油茶果图像的亮度、对比度,且细节可以保持完整"}
|
22 |
+
{"content": "Dong的方法", "summary": "基于Dong的去雾算法增强。Dong等发现,低照度图像经过翻转后图像与雾天图像具有一定的相似性,因此可以采用图像去雾的思想对低照度图像进行增强,可以取得一定的增强效果。但由于Dong未考虑雾图中存在的白色区域所导致的暗通道理论失效的问题,在应对复杂场景增强时容易出现块效应和噪声等问题。基于伪雾图增强法。该方法利用低照度图像的反转图像通过��雾算法进行增强,如Dong等提出的增强方法取得了较好的照度增强效果,但在应对复杂场景增强时容易出现块效应和噪声等问题。"}
|
23 |
+
{"content": "将注意力机制引入CNN结构中有什么好处 ", "summary": "将注意力机制应用于UNet分割网络中,可以比较好的实现对显著性区域的关注,以及对无关背景区域的抑制。"}
|
24 |
+
{"content": "将注意力机制引入CNN结构中有什么好处 ", "summary": "注意力模型可以很好的嵌入到CNN框架中,而且不增加计算量的同时提高模型性能。"}
|
25 |
+
{"content": "将注意力机制引入CNN结构中有什么好处 ", "summary": "提出了Attention-U-Net算法,该算法将通道注意力及空间注意力机制加入低光增强网络之中"}
|
26 |
+
{"content": "CIL数据集的采集条件", "summary": "用于网络训练的低照度/正常图像对,于2020年10月25日-11月5日白天在湖南省天沃科技有限公司雷叔叔油茶果种植基地拍摄,拍摄的油茶果的品种为华顺203,205。图像采集设备为尼康D90数码相机,相机的光圈为F22,快门模式为M模式,ISO为200,拍摄设备如图1所示,尼康相机固定在三脚架上,三角架轴心到树干中心的距离为200cm,相机镜头到油茶树最外侧的距离为95cm,相机距离地面的高度为150cm;在对同一场景同一位置的油茶果采集不同曝光度的图像时,若采用手动按快门进行拍摄,会不可控地引起相机镜头的抖动,从而造成拍摄的不同曝光度的图像,无法达到像素级的对应,对后续网络的训练造成较大干扰,因此本研究在制作油茶果的低照度/正常光照图像的数据集CIL(Camellia oleifera Abel Image in low light)时,采用红外遥控的方式的进行图像的采集2021.01.25,其中红外遥控器的发射端由采集人员手持,红外遥控器的接收端置于单反相机的上方,两者通过热靴连接。"}
|
27 |
+
{"content": "注意力机制引入的区域 ", "summary": "attention模块用在了skip connection上,原始U-Net只是单纯的把同层的下采样层的特征直接concate到上采样层中,改进后的使用attention模块对下采样层同层和上采样层上一层的特征图进行处理后再和上采样后的特征图进行concate"}
|
28 |
+
{"content": "注意力机制引入的区域 ", "summary": "Attention coefficients(取值0~1)与feature map相乘,会让不相关的区域的值变小(抑制),target区域的值变大(Attention)。"}
|
29 |
+
{"content": "注意力机制引入的区域 ", "summary": "利用下采样层的结构化信息和当前层纹理信息的融合,利用sigmoid归一化,得到关联性强的区域,和当前层做乘积,从而强调本层的显著性区域的特征。"}
|
30 |
+
{"content": "注意力机制引入的区域 ", "summary": "在基础的UNet的基础上增加了attention 的机制,通过自动学习参数来调整激活值,attention的可视化效果还是主要部分,不像non-local的方式每一个像素点都要和其他像素点进行关联,可以视作一种隐式的注意力机制。"}
|
31 |
+
{"content": "我们的方法如何好 ", "summary": "通过大量的实验表明,运用深度残差网络和U-net,可以更好地进行特征提取,低照度图像增强的效果也更好,很大程度上优于现有的技术。提出的方法不仅在视觉上提高了亮度和对比度,色彩更真实,更加符合人眼视觉系统特性,而且PSNR、SSIM等七项客观图像质量指标在几种算法中都是最优的。"}
|
32 |
+
{"content": "我们的方法如何好 ", "summary": "3)本文使用大量的实验来证明所提出模型的有效性,且使用了很多"}
|
33 |
+
{"content": "我们的方法如何好 ", "summary": "其可对不同尺度的低照度图像进行增强"}
|
34 |
+
{"content": "我们的方法如何好 ", "summary": "通过在公开数据集(LOL,SID)上验证表明,RUNet方法在效果上有所改进,尤其是整体视觉效果。"}
|
35 |
+
{"content": "我们的方法如何好 ", "summary": "不仅在客观评价指标上的评分更高,PSNR、SSIM等七项客观图像质量指标在几种算法中都是最优的,而且在视觉上提高了亮度和对比度,色彩更真实,更符合人眼的视觉原理。"}
|
36 |
+
{"content": "合成数据集 ", "summary": "我们从RAISE收集了780张原始图像,700张用于生成训练对,80张用于网络的验证。使用Adobe Photoshop Lightroom调整对应的参数,包括曝光度、振动和对比度,具体参数为:曝光参数E设置为了[-5,0],振动参数V设置为[-100,0],对比度参数C设置为[-100,0]来合成低照度图像。为了防止颜色偏差的问题,在训练数据集中加入了700对灰度图像对。这些灰度图像对被转换为彩色图像对。为了使增强前后的黑白区域保持一致,我们添加了五对白-白训练对和五对黑-黑训练对。最后,将所有图像的大小调整为400x600,并转换为JPG格式。"}
|
37 |
+
{"content": "合成数据集 ", "summary": "通过伽玛校正来合成数据集,但对于伽玛校正,可能无法反映不同曝光级别之间的关系。"}
|
38 |
+
{"content": "CIL数据集的明细 ", "summary": "CIL数据集,分别拍摄了单果、多果、整树、花朵、花和果实、无果等多种油茶果图像场景的低照度/正常图像对,以确保算法对不同的场景的低照度图像的增强效果。CIL数据集用较短的快门时间拍摄的油茶果图像做为低照度图像,较长的快门时间拍摄的图像做为对应的参考图像,一共包含1200组不同曝光度的图像,各个场景下的具体图像数量如表1所示,曝光时间分别为1/1000s、1/500s、1/250s、1/60s、1/10s,其中做为低照度图像的曝光时间分别为1/1000s、1/500s、1/250s、1/60s,每组图像对应的参考图像的曝光时间为1/10s。"}
|
39 |
+
{"content": "为什么要使用U-Net", "summary": "在数据集规模较小的情况,使用U-Net进行烟尘分割。相比于其他语义分割网络,U-Net的优点在于能针对小型数据集进行端到端的快速、有效训练。"}
|
40 |
+
{"content": "存在的问题 ", "summary": "油茶果处于高山丘陵地区,因此山上多风,所以对在非同一时刻采集到的油茶果图像可能会存在轻微的晃动,"}
|
41 |
+
{"content": "U-Net的结构描述", "summary": "U-net网络结构因其对称结构与英文字母“U”相似而得此名,主要由下采样、上采样以及“桥”连接三部分组成,其网络结构见图2。左边称为下采样,也叫压缩路径或编码器(encoder),主要作用是提取图像的浅层特征,如图像的位置信息;右边称为上采样,也叫扩展路径或解码器(decoder),主要作用是提取图像的深层特征,如图像中像素的类别信息;中间的箭头表示“桥”连接,也叫跳跃连接(skipconnection,SC),主要作用是把下采样得到的特征图与上采样得到的特征图进行复制拼接,形成一个同时具有深层次和浅层次信息的特征图,实现更为有效的分割。除此之外,上、下采样和“桥”连接部分由卷积层、池化层、反卷积层以及激励层组成。其中卷积层用于提取甲状腺图像的特征;池化层用于下采样部分,其将获取的特征数据和参数进行压缩,减少模型过拟合;反卷积层用来还原特征图的尺寸大小,使得最后输出大小与原图大小一致;激励层是将卷积所得的输出进行一个非线性映射,来保证模型能够更好地拟合图像。本研究所使用的激活函数为ReLU,最后输出层使用Sigmoid函数对像素点进行分类"}
|
42 |
+
{"content": "对U-Net增强效果的描述", "summary": "对单通道的图像进行伪彩色处理,可以直观地看到,经过U-Net增强后的图像,其整体照度得到了增强,而且,各个通道的轮廓和细节信息也得到了增强,变得更为突出。例如R通道,增强前的树叶、树枝等信息耦合在一起,无法区分,而增强后,两者的边界则变得非常显著,有利于后续图像的进一步分析。"}
|
43 |
+
{"content": "对U-Net增强效果的描述", "summary": "自己的U-Net代码是对图像进行了端对端 的处理,不仅仅是可以对图像进行低照度增强,还进行去噪,"}
|
44 |
+
{"content": "我们提出的网络", "summary": "受SID算法的启发,本文验证了利用神经网络对低照度图像进行端到端的增强,并提出了一个有连续的自网络组成的新型网络RV-UNet。"}
|
45 |
+
{"content": "我们提出的网络", "summary": "通常原始输入图像的比编码-解码网络的输出包含更多细节,因为可以为恢复细节提供信息。采用级联代替跳跃连接,将上一个上采样块的特征映射与输入图像相结合,使原始信息和照明估计都能完全保留并传输到下一步。级联层之后是带有ReLU的三个激活层,它将输入的图像信息与估计的全局光照信息想结合,最终生成细节更好的增强效果。"}
|
46 |
+
{"content": "多级", "summary": "在训练过程中,首先针对不同曝光时间的图像乘上对应的放大系数进行粗增强,,该系数不参与网络训练,由研究人员指定;而在网络测试时,模型先由输入图像的直方图进行亮度模式判定,根据先验知识分别乘上对应的放大因子,对图像进行粗调整后,再输入到A-UNet网络中进行端到端处理 。"}
|
47 |
+
{"content": "油茶果图像的采集", "summary": "本研究采集油茶果的试验地点为湖南省永州市雷叔叔油茶果种植基地,拍摄时间为2020年10月28日-2020年11月6日的白天,,"}
|
48 |
+
{"content": "油茶果图像的采集", "summary": "江西省林业科学院国家油茶林基地。拍摄相机为索尼相机,像素为640×480。于2019年9月14~23日的晴天拍摄,采集了典青、赣兴46、赣抚20等34个品种的油茶果图像并保存成JPG的格式。图1为拍摄的部分油茶果图像。环境下的油茶果图像,将训练集图像数量扩充到3820张,使卷积神经网络学习到各种情况下油茶果图像的特征(若训练数据集中没有包含多样化的样本,则会导致机器学习不足,识别结果置信度降低)。"}
|
49 |
+
{"content": "试验环境", "summary": "本试验在Windows图形工作站计算机上进行,处理器为Intel-i5-9400F,内存为32GB,操作系统Windows10(64位)。考虑到GPU算力的需要,选用显卡为RTX 2080Ti,显存11GB。Python的版本是3.6.4,在pycharmIDE上编译。深度学习框架选择PyTorch。同时为了提高训练速度,采用GPU加速方法,cuda版本是8.1,cudnn版本为7.6.0。"}
|
50 |
+
{"content": "U-Net的优点", "summary": "由于U型网络可以较好地保留图像的细节,为了学习低光图像和正常光照图像之间的映射关系,本文采用U型结构的卷积神经网络。如图3所示,该网络由编码器、解码器和跳跃连接构成。"}
|
51 |
+
{"content": "实验结果的图表", "summary": "各个算法对应多个评价指标,使用多个图表"}
|
52 |
+
{"content": "实验结果的图表", "summary": "在一个图表上对应上所有的方法和评价指标"}
|
53 |
+
{"content": "说明本文的做法好", "summary": "以上数据表明本文算法在低照度图像的增强效果以及运行效率上均有一个较好的表现,为自然环境下油茶果的检测和识别提供了保障。"}
|
54 |
+
{"content": "说明本文的做法好", "summary": "大量的实验表明,该方法不仅可以获得视觉上令人满意的低光增强效果,而且能够很好地表示图像的分解过程"}
|
55 |
+
{"content": "说明本文的做法好", "summary": "我们进行了大量的实验,以证明我们设计算法的有效性及相对于常见低照度增强算法的优越性。此外,我们算法在2080Ti GPU上花费不高50ms来处理VGA分辨率的图像,这些特性使得我们的产品具有是有价值。"}
|
56 |
+
{"content": "针对于本文不利的指标进行申辩", "summary": "本文所提的增强算法,尽管在时间效率上低于LIME和HE等传统算法,但是增强效果上,则远远高于这些算法。表明本文算法具有良好的实时性和准确性,为后续的计算机视觉的准确识别,有助于提高油茶果采摘机器人采摘作业的准确性和效率。"}
|
57 |
+
{"content": "我们算法的增强效果", "summary": "实验结果表明,与传统的低照度增强算法相比,本文所以提出的模型,不仅可以最大程度地还原图像的真实亮度,而且能够有效提高图像的对比度、调整颜色失衡已经去除噪声,客观图像质量评价指标也高手同类算法。"}
|
58 |
+
{"content": "我们算法的增强效果", "summary": "实验结果表明,本文所提算法不仅在主客观评价上有较好的表现,而且利用增强后的图像训练出来的YOLO v4网络比未经过增强处理的图像训练出来的YOLO v4网络识别准确率更高。"}
|
59 |
+
{"content": "我们算法的增强效果", "summary": "该增强算法是利用神经网络进行端到端的训练,参数调整过程中没有任何人工参与,大大减少了人工设计的复杂性。"}
|
60 |
+
{"content": "我们算法的增强效果", "summary": "实验表明,本文算法,不仅在合成图像中表现出色,而且"}
|
61 |
+
{"content": "我们算法的增强效果", "summary": "本文分别从定性和定量的角度将RV-UNet与流行的低照度增强方法进行了比较,结果表明,本文算法不仅在各个增强指标上表现出了,而且也最符合人眼特性,xxx效果最好。"}
|
62 |
+
{"content": "我们算法的增强效果", "summary": "综上所述,RV-UNet的增强效果优于LIME等传统增强算法,而且与Retinex-Net等深度学习增强算法相比,图像的主客观增强效果均表现出色。但本文方法也存在一些问题,例如对一些区域进行处理时存在过度增强,从而引起亮斑问题。"}
|
63 |
+
{"content": "我们算法的增强效果", "summary": "与其他算法相比,本文提出的算法可以有更生动和自然的结果,由于RV-UNet对输入图像具有全局感知能力,并且可以按照语义信息对整个图像进行增强,因此可以避免在正常或者较亮区域的过度曝光或者在较暗区域的曝光不足。此外,低照度图像的细节了增强后仍然可以保持不变,得益于细节重构步骤。"}
|
64 |
+
{"content": "损失函数", "summary": "本文实验选择低照度增强公开基准数据集LOL进行训练的,该数据集包含1500组低光/亮光图像对。具体来说,有500对大小为400×600的真实场景图像和1000对大小为384×384的原始数据合成图像。本文使用1000对合成图像对和485对真实图像对进行训练,其余15对进行测试。由于LOL测试集的图像是在极弱光条件下拍摄的,图像的黑暗区域充满了强烈的噪声,因此通过这个数据集的结果可以很好地显示了本文算法在低光照条件下的增强性能。"}
|
65 |
+
{"content": "常见的图像去噪算法", "summary": "最流行的方法可以归纳为BM3D 和WNNM 。由于测试中优化过程的高度复杂性,以及参数需要人工进行精心设计,这些传统去噪算法���实际应用中往往表现不是很出色。"}
|
66 |
+
{"content": "人们对于图像去噪的态度", "summary": "在图像处理、多媒体、计算机视觉等领域,图像去噪一直是人们关注的热点,近几十年来提出了很多经典算法。"}
|
67 |
+
{"content": "数据驱动", "summary": "Retinex分解图像的方法是直接在输入图像上估计反射率和照度,但设计适合各种场景的适当约束函数并不容易。因此,尝试以数据驱动的方式解决此问题。DeNet每次都会获取成对的弱光/正常光图像,并在弱光和正常光图像的指导下学习弱光及其对应的正常光图像的分解。"}
|
68 |
+
{"content": "基于深度学习的去噪算法", "summary": "基于深度学习的去噪算法显示出了优越性,有代表性的工作,如使用堆叠稀疏去噪自动编码器的SSDA 、可训练非线性反应扩散的TNRD、具有残差学习和批处理归一化的DnCNN,由于"}
|
69 |
+
{"content": "编码-解码描述", "summary": "在编码-解码网络中,首先是由编码网络对图像进行编码,然后将图像的全部信息压缩为瓶颈层的细长向量,最后由解码网络解码进行解码。"}
|
70 |
+
{"content": "时间复杂度", "summary": "评价一个算法的优劣,一般主要从算法的执行时间(计算量)和所需要占用的存储空间(访问量)两方面进行衡量,但时间复杂度计算的不是程序具体运行的时间,而是算法执行语句的次数。"}
|
71 |
+
{"content": "评价增强效果", "summary": "客观评价方式是通过峰值信噪比、信息熵、标准差等参数对低照度图像的增强效果进行定量分析。"}
|
72 |
+
{"content": "评价增强效果", "summary": "使用PSNR评价指标,偶尔会出现评价结果与主观评价不一致的情况,这是由于该指标"}
|
73 |
+
{"content": "评价增强效果", "summary": "PSNR在对图像进行评价的时候,只是对图像的绝对质量进行数字打分,而忽略了人眼的主观感受,例如人眼对一个区域的感知结果会受到其周围邻近区域的影响,因此常常会出现PSNR分数与主观评价不一致的情况。"}
|
74 |
+
{"content": "评价增强效果", "summary": ",使用PSNR对图像进行评价,有时候会出现评价分数与主观评价不一致的情况,"}
|
75 |
+
{"content": "评价指标", "summary": "本文在测试数据集上对所提出的网络性能进行了评估,并分别将其与文献、文献和文献三种主流低照度图像增强的方法进行了定性和定量的比较。为了公平起见,本文应用了作者提供的带有推荐参数设置的代码。为了评价这些算法的性能,本文采用峰值信噪比(PSNR)、结构相似性指数(SSIM)和自然图像质量评估器(NIQE)来量化增强后图像的恢复质量。"}
|
76 |
+
{"content": "评价指标", "summary": "PSNR是一个绝对误差,使用像素相对于其最大可能值的均方误差来计算。在假设人类的视觉系统高度协调以提取结构信息的情况下,SSIM试图通过更紧密地与人类的感知保持一致来改进绝对误差度量。这两个客观评价指标的值越大,表明图像处理效果越好,而NIQE值越大说明与自然图像差距越大,质量越差。可以从表1中看出本文网络表现出最优的性能。"}
|
77 |
+
{"content": "空间复杂度", "summary": "空间复杂度是对一个算法在运行过程中临时占用存储空间大小的量度。在深度学习中,空间复杂度决定了模型的参数数量,模型的参数越多,训练模型所需的数据量就越大,而现实生活中的数据集通常不会太大,这会导致模型的训练容易过拟合"}
|
78 |
+
{"content": "使用Google Cloud Vision 进行检测", "summary": "这个东西相对来说会客观一点儿,大家都是认这个东西的"}
|
79 |
+
{"content": "使用Google Cloud Vision 进行检测", "summary": "图3为谷歌云识别低照度/正常光照图像对,原始图像来自于MEF数据集。由于光照较低,谷歌云视觉只能将图像标记为“天空”、“云”和“尖顶”,经过增强后,前景埃菲尔铁塔被成功地检测到,并用一个绿色的boundingbox精确地标记出来,表明了我们方法的有效性"}
|
80 |
+
{"content": "缺乏数据集", "summary": "由于在现实世界中,获取可以做到像素级匹配的低照度/正常图像对的难度较大,早期采用深度学习算法对低照度图像进行增强的研究中,多是采用人工合成过的低照度图像数据集。然而,这些低照度图像通常是由研究者们通过一些已知参数的具体算法,对正常光照条件下的图像进行随机变暗处理,以及增加随机噪声等方式获得。与真实场景下采集到低照度图像相比,这类人工合成的图像,往往过于简化,缺乏真实场景下的复杂的噪声与图像失真。"}
|
81 |
+
{"content": "基于深度学习的低光增强方法", "summary": "由于深度学习网络对非线性映射有较好的拟合作用,近年来研究者相继尝试了使用深度学习来对低照度图像进行增强的方式。"}
|
82 |
+
{"content": "基于深度学习的低光增强方法", "summary": "这类算法能够利用神经网络学习低照度图像到正常照度图像之间的非线性映射,例如Lore等人最早提出了将LLNet网络用于处理低照度图像的"}
|
83 |
+
{"content": "基于深度学习的低光增强方法", "summary": "基于伪雾图增强法。该方法利用低照度图像的反转图像通过去雾算法进行增强,如Dong等提出的增强方法取得了较好的照度增强效果,但在应对复杂场景增强时容易出现块效应和噪声等问题。"}
|
84 |
+
{"content": "基于深度学习的低光增强方法", "summary": "随着深度学习的出现,许多低级视觉任务都从中受益,例如[14]、[15]用于去噪,[16]用于超分辨率。"}
|
85 |
+
{"content": "基于深度学习的低光增强方法", "summary": "RetinexNet"}
|
86 |
+
{"content": "基于深度学习的低光增强方法", "summary": "最近出现的做法"}
|
87 |
+
{"content": "防止卷积后图像变小", "summary": "为了避免卷积时对图像边缘造成影响,丢失图像边缘,每个卷积层在进行卷积操作前都会对图像的边缘进行0填充,是的图像在卷积前与卷积后的大小可以保持一致。"}
|
88 |
+
{"content": "为什么不能直接对低照度图像进行亮度增强", "summary": "在低照度条件下拍摄的图像通常xxx质量很差,这是因为除了不理想的光照条件外,还存在着多种类型的图像退化,例如噪声和颜色失真,都一起被隐藏在图像中,因此仅仅提高低照度图像的亮度将不可避免地放到这些噪声,使图像产生伪影和失真。"}
|
89 |
+
{"content": "为什么不能直接对低照度图像进行亮度增强", "summary": "不同低照度区域具有不同程度的噪声,如果直接对低照度图像进行亮度增强的话,也会不可避免的放大这些噪声,使图像产生伪影和失真"}
|
90 |
+
{"content": "闪光灯", "summary": "闪光灯是点状光源,而自然光是平行光源,因此使用闪光灯辅助成像有可能会产生不自然的曝光,而且使用闪光灯可以在一定程度上使环境变得明亮,但也会了成像中引入高光和不平衡的照明,使图像在视觉上缺乏真实感。"}
|
91 |
+
{"content": "拍出低照度图像的场景", "summary": "由于油茶果生长环境的特殊性,油茶果采收机器人在作业时,视觉系统并不是在所有时刻和地点都可以获得良好的光照条件,例如黄昏、阴天、雾天等光照不足的情景下,甚至在晴天的一些背光处也会有欠曝光的现象。在这种光照条件下直接捕获的图像,往往具有较低的信噪比,容易对后续机器视觉的目标检测等工作造成较大干扰。"}
|
92 |
+
{"content": "拍出低照度图像的场景", "summary": "造成低照度图像的原因有很多,例如拍摄环境光照条件较差、摄影设备性能有限以及设备配置不当等。"}
|
93 |
+
{"content": "必要性", "summary": "油茶果采摘机器人的工作环境复杂,尤其是在阴天、傍晚,采集到的果实图像存在整体偏暗、模糊、对比度不高、细节不清晰、动态范围压缩有限等问题,给后续油茶果的自动化采收带来了较大困难。"}
|
94 |
+
{"content": "必要性", "summary": "从低光环境下采集的油茶果图像,经常存在对比度低、细节丢失、噪声污染严重等问题,不利于人眼的观察和计算机视觉的检测。"}
|
95 |
+
{"content": "必要性", "summary": "图像质量与很多计算机视觉相关的相关技术的效果息息相关,高质量的图像可以带来更多信息,方便后续的增强任务。油茶果机器人作业时的很多因素都会直接或者间接地影响图像质量,低光照便是其中之一。"}
|
96 |
+
{"content": "必要性", "summary": "低质量的图像会降低很多计算机视觉的性能,因为这些算法,通常是针对高质量输入图像设计的,因此对低照度图像进行增强,不仅可能图像的视觉效果,还可以提高相关视觉算法的作业效果。"}
|
97 |
+
{"content": "必要性", "summary": "在拍照成像中,光照不足,会非常明显的影响成像质量,使其对比度降低并且丢失细节信息,不仅影响视觉效果,而且会给后续为自然光照图像设计的计算机视觉系统的性能造成较大影响。为了使这些隐藏在低照度区域的细节清晰可见,提高计算机视觉系统的准确性,需要对低照度图像进行增强。"}
|
98 |
+
{"content": "延时摄影", "summary": "长时间曝光延长了拍摄时的曝光时间,可以让更多的光子到达成像设备的感光元件上,但是仅限于静态摄影,若是物体在拍摄过程中发生了位移,很可能导致成像结果模糊"}
|
99 |
+
{"content": "目的", "summary": "研究低照度增强的主要目的在于提升图像亮度的同时,降低图像噪声、减小色彩偏差、增强图像整体与局部的对比度,以增强图像的视觉效果与质量,例如锐化图像特征,使图像具有更高的视觉质量。低照度图像增强的目的是"}
|
100 |
+
{"content": "目的", "summary": "低照度图像增强的目的是改善低光照条件下的成像图像质量与视觉效果,同时减小对光照以及拍摄设备的依赖程度,具有广大的应用前景。"}
|
101 |
+
{"content": "发展水平", "summary": "国内外很多学者,对低照度图像增强技术进行了相关研究,取得了不错的效果,但大多是针对通用场景的增强,针对农业领域里面的低照度图像进行增强的研究相对较少。"}
|
102 |
+
{"content": "发展水平", "summary": "近年来,很多学者对低照度增强领域进行了研究,使低照度增强技术有了较大的发展,但是开发一种可以用于实际领域的低光增强策略仍然面临着较大挑战,因为常见的低光增强算法往往受限于特定的场景,增强效果只是限制在这个特定领域里面,换另外一个场景有可能就不再适用了。XXX"}
|
103 |
+
{"content": "目标", "summary": "理想的低照度图像增强算法,不仅应该可以对低照度图像进行增强,而且还可以有效地去除隐藏在暗区域中的图像,并且灵活地调整图像的增强等级。"}
|
104 |
+
{"content": "应用", "summary": "低照度图像增强的目的是改善低光照条件下的成像图像质量与视觉效果,同时减小对光照以及拍摄设备的依赖程度,具有广大的应用前景。"}
|
105 |
+
{"content": "应用", "summary": "RV-UNet主要应用场景为帮助提高其他计算机视觉任务的性能,比如物体检测和识别。由于大部分视觉识别模型都基于自然"}
|
106 |
+
{"content": "难度所在", "summary": "对于大部分低照度图像,对图像进行简单的调整,并不能同时提升图像的亮度与质量。xxxx(中间省略很多具体算法的做法)这些难以调和之处正是低照度增强算法的难点所在。"}
|
107 |
+
{"content": "难度所在", "summary": "很难确定精准的Ground Truth∑"}
|
108 |
+
{"content": "难度所在", "summary": "深度学习应用于低照度图像增强的难度所在∑"}
|
109 |
+
{"content": "深度学习应用于低照度图像增强的难度所在", "summary": "如何从单个图像中有效地估计出照明分量,并灵活地调整光照水平在对低照度区域进行增强后,如何消除之前隐藏在暗区域中的噪声和颜色失真等变换如何只通过少量的数据集训练一个没有Ground Truth的低照度增强网络?"}
|
110 |
+
{"content": "很难确定精准的Ground Truth", "summary": "从用户的角度考虑,不同的人、不同的需求场景可能需要不同的图像亮度值,对于研究人员而言,很难精准确定一个适用于所有人的Ground Truth。"}
|
111 |
+
{"content": "直方图均衡化 ", "summary": "在常规的图像增强任务中,直方图均衡化被广泛地应用到了各种图像增强任务中,通过对图像的直方图进行变换,得到从当前像素值。"}
|
112 |
+
{"content": "HSV颜色空间", "summary": "HSV色彩空间的H通道采用环形数据表示,在该通道上设计增强网络的损失函数难度较大,"}
|
113 |
+
{"content": "为什么要将低照度图像转换到不同的颜色空间中进行处理", "summary": "低光照图像与自然光照图像之间的主要区别为:图像的亮度和色彩的偏移,而亮度和色度则可以很好地反映出两者之间的差别。 因此将图像转换到YCbCr 颜色空间中,从而得到一个比在RGB颜色空间更适合改变图像亮度和色度的调整模型。"}
|
114 |
+
{"content": "YCbCr颜色空间", "summary": "图像在YCbCr颜色空间的数字矩阵,相比于在RGB颜色空间的数字矩阵,更适合进行低照度增强处理,可以帮助提升模型的性能。"}
|
115 |
+
{"content": "直方图的作用 ", "summary": "直方图可以统计数字图像中具有不同像素值的像素数量,图像直方图描绘了图像中像素值的分布情况。直方图被广泛应用于各种图像增强任务中,通过对图像的直方图进行变换,得到从当前像素值到新的像素值的直接映射。这类方法中最经典最常用的是直方图均衡化,但是直方图均衡化不会对图像的内容进行判断,只是在单纯地对所有的像素值进行计算映射,容易放大原始图像中的噪声。同时直方图均衡会使图像的平均亮度保持在像素值的动态范围中间,这会破坏一些场景的整体亮度。"}
|
116 |
+
{"content": "局部直方图 ", "summary": "一些方法使用局部直方图均衡来避免破坏图像整体的平均亮度,但容易导致一些边界问题,而使得图像出现Checkerboard效应 等伪像。"}
|
117 |
+
{"content": "传统算法", "summary": "LIME的色彩保持度较好,但是存在过度增强的问题,细节处会有损失。"}
|
118 |
+
{"content": "传统算法", "summary": "Wang等人提出了一种称为NPE的算法,这种算法可以在增强对比度的同时保持照度的自然性。"}
|
119 |
+
{"content": "传统算法", "summary": "FU等人提出了一种算法,该算法通过融合最初估计的光照图的多个导数来调整图像亮度,但这种方法往往会牺牲包含丰富纹理区域的真实感。"}
|
120 |
+
{"content": "传统算法", "summary": "Guo等考虑从最初的结构光照图估计结构光照图。这些方法通常假定图像无噪声和颜色失真,并且不明确考虑退化。"}
|
121 |
+
{"content": "SID ", "summary": "chen等人提出了一种可以用于处理低照度图像的算法,该算法是基于全卷积网络的端到端训练,可以同时处理噪声和颜色失真。但该算法受限于特定格式的数据集,如果修改网络以接收JPEG格式的数据(这个说法是原文自己说的),性能将会显著下降。"}
|
122 |
+
{"content": "伽马变换 ", "summary": "伽玛以非线性的方式对每个像素都进行非线性映射,虽然可以提高亮度,尤其是较暗区域的亮度,但是却没有考虑单个像素与其相邻像素之间的关系,因此增强效果往往会失真。"}
|
123 |
+
{"content": "Retinex", "summary": "Retinex理论的关键假设是图像可以分解为两个分量,即反射和照明。早期的算法包括单尺度的Retinex(SSR)和多尺度的Retinex(MSR),但是其结果通常看起来不自然,并且在某些地方存在过度增强。"}
|
124 |
+
{"content": "Retinex", "summary": "基于深度学习的算法∑"}
|
125 |
+
{"content": "基于深度学习的算法", "summary": "shen等人认为多尺度Retinex等价于具有不同高斯卷积核的前馈卷积神经网络,受此启发,他们构建了一个卷积神经网络(MSR网络)来学习低照度图像和正常光照图像之间的端到端映射。ΞWei等人设计了一个深度网络,称为RetinexNet,Retinex-NetΞKindling the Darkness"}
|
126 |
+
{"content": "传统Retinex算法的限制所在", "summary": "虽然这些算法在特定情况下会有较好的增强效果,但是对于不同场景的低照度图像增强,每个场景都需要进行人工进行精心的参数设计,费时费力,实际应用价值相对较弱。"}
|
127 |
+
{"content": "传统Retinex算法的限制所在", "summary": "现在大多数基于Retinex的方法都为这种高度不适定分解精心设计了约束和参数,而这些约束和参数在应用于其他场景时可能受到模型容量的限制,从而无法取得良好的效果。"}
|
128 |
+
{"content": "Retinex-Net", "summary": "在Retinex理论的指导下,我们设计了一个Deep Retinex-Net网络来一起完成反射/照明分解和弱光增强。网络由三个步骤组成:分解、调整和重建。在分解步骤中,Retinex网络通过Decom网络将输入图像分解为R和I。在训练阶段,同时将低光/正常光照图像输入到网络,而在测试阶段,则仅将低照度图像作为输入。在低/正常光图像具有相同反射率和照明平滑度的约束下,Decom网络通过数据驱动的方式,对反射图的分解参数进行学习,使得不同照明图像分解的反射图R保持一致。在调整步骤中,使用Enhance-Net来使照明变亮。Enhance-Net采用了编码-解码网络的总体框架。采用多尺度级联保持当对图像进行亮度调整时,使全局与局部之间保持语义上下文的连贯性。此外,如果需要,通常会将在弱光条件下产生的放大噪声从反射图中去除。然后,在重建阶段,我们将调整后的照明图和反射图通过元素的乘法结合起来,从而得到最终的低照度增强效果图。"}
|
129 |
+
{"content": "shen等人认为多尺度Retinex等价于具有不同高斯卷积核的前馈卷积神经网络,受此启发,他们构建了一个卷积神经网络(MSR网络)来学习低照度图像和正常光照图像之间的端到端映射。", "summary": "L. Shen, Z. Yue, F. Feng, Q. Chen, S. Liu, and J. Ma, “Msr-net:low-light image enhancement using deep convolutional network,”p. arXiv , 11 2017."}
|
130 |
+
{"content": "未来的研究方向", "summary": "本文未来的研究方向是:1.增加算法对不同场景的鲁棒性,将算法的应用场景扩展到雾天、雨天等背景中 2.对算法的增强效果进行合理化约束,避免对非低照度区域进行增强,从而导致增强效果过亮的问题。"}
|
131 |
+
{"content": "未来的研究方向", "summary": "反光部分,也会被放大"}
|
132 |
+
{"content": "批标准化", "summary": "当前实验实验使用的增强网络包含了6个卷积层,我们在其前5个卷积层的激活层后再加入批标准化层,使得目前的CNN结构由Conv-Relu变为Conv-Relu-BN结构。"}
|
133 |
+
{"content": "对网络图的描述", "summary": "图中的K表示卷积核的尺寸,K3即表示卷积核尺寸为3x3,Conv表示卷积层,Conv前的数字表示卷积层中卷积核的个数,"}
|
134 |
+
{"content": "低光照图像与正常光照图像的区别所在", "summary": "低光照图像与自然光照图像之间的主要区别为:图像的亮度和色彩的偏移,而亮度和色度则可以很好地反映出两者之间的差别。"}
|
135 |
+
{"content": "对颜色的影响", "summary": "在低光照条件下,亮度和色度受到的损耗程度是不同的,亮度通道相比于色度通道受到了更多的全局损耗。"}
|
136 |
+
{"content": "实验条件及参数设置", "summary": "本实验使用PyTorch 深度学习框架实现网络,在显存为11G的RTX 2080Ti上训练。使用的SID 数据集包含5094个原始的短曝光极低光图像,每个极低光图像均有对应的长曝光参考图像。长曝光参考图像I^{Hgt}高斯滤波 缩小4倍得到低分辨率图像I^{Lgt},图像宽度W和高度H均为512,每批次输入1张图片。预训练中,转换子网络T-1采用Adam 优化算法,beta1设为0.900,beta2设为0.999,训练总批次为4000,学习率为10^–4,在批次大于2000后,学习率为10^–5。转换子网络T-2采用Adam优化算法,beta1设为0.500,beta2设为0.999,损失函数中λr设为1.000,λp设为0.006,λg设为0.001。训练总批次为2104,学习率为10–4,在104批次后将学习率慢慢衰减至10–6。转换网络T采用Adam优化算法,beta1设为0.500,beta2设为0.999,损失函数中λr设为1.000,λp设为0.006,λg设为0.001。训练总批次为2104,学习率为10^–4,在前100个批次将学习率线性衰减到10^–5,在10^4批次内将学习率线性衰减到10–6,之后再以学习率10–6训练104次。"}
|
137 |
+
{"content": "实验结果与分析", "summary": "为了评估本方法的性能,与近期已有的几种方法包括多通道融合的方法(BIMEF)、带色彩恢复多尺度Retinex算法(MSRCR)、自然保留增强算法(NPE)、基于光照估计的方法(LIME)、多偏差融合方法(MF)、反射光照估计方法(SRIE)进行比较。本文在两个公共数据集(LIME数据和DICM数据)的低照度图像上对上述方法进行了性能评估。"}
|
138 |
+
{"content": "结论", "summary": "本文提出了一种面向低照度图像增强的双曝光融合处理算法。首先,利用照度估计技术得到用于图像融合的权重矩阵;然后,通过摄像机响应模型合成双曝光图像。鉴于不同曝光量下图像颜色基本相同,定义低亮度像素和亮度分量找到最佳曝光率,使合成图像在原始图像曝光不足的区域得到更好的曝光;最后,根据权重矩阵将输入图像与合成图像进行融合,得到增强结果。和已有算法相比,本文方法能够获得较小的亮度失真,且具有合理的时间开销。由于实际环境的复杂性,对过度曝光进行优化建模仍是一个充满挑战性的问题,未来将对此展开进一步研究。"}
|
139 |
+
{"content": "结论", "summary": "本文针对极端低光情况下的图像增强问题,提出一种新的增强模型,引入残差网络和感知损失重构图片的高频信息,更好地还原了图像的细节,得到了更好的视觉效果,在PSNR和SSIM这2个定量指标上也有所提升。"}
|
140 |
+
{"content": "结论", "summary": "另一方面目前亮度放大倍数为人为输入,未来可以根据极低光图像的信息估算出亮度放大倍数。如何在进一步地提升增强后图像视觉效果的同时提高PSNR和SSIM定量指标的值,以及如何估算光度放大倍数,将是未来研究的方向。"}
|
ptuning/datasets/chat/dev.json
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{"content": "101", "summary": "10201"}
|
2 |
+
{"content": "102", "summary": "10404"}
|
3 |
+
{"content": "103", "summary": "10609"}
|
4 |
+
{"content": "104", "summary": "10816"}
|
5 |
+
{"content": "105", "summary": "11025"}
|
6 |
+
{"content": "106", "summary": "11236"}
|
7 |
+
{"content": "107", "summary": "11449"}
|
8 |
+
{"content": "108", "summary": "11664"}
|
9 |
+
{"content": "109", "summary": "11881"}
|
10 |
+
{"content": "110", "summary": "12100"}
|
11 |
+
{"content": "111", "summary": "12321"}
|
12 |
+
{"content": "112", "summary": "12544"}
|
13 |
+
{"content": "113", "summary": "12769"}
|
14 |
+
{"content": "114", "summary": "12996"}
|
15 |
+
{"content": "115", "summary": "13225"}
|
16 |
+
{"content": "116", "summary": "13456"}
|
17 |
+
{"content": "117", "summary": "13689"}
|
18 |
+
{"content": "118", "summary": "13924"}
|
19 |
+
{"content": "119", "summary": "14161"}
|
20 |
+
{"content": "120", "summary": "14400"}
|
ptuning/datasets/chat/train.json
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{"content": "0", "summary": "0"}
|
2 |
+
{"content": "1", "summary": "1"}
|
3 |
+
{"content": "2", "summary": "4"}
|
4 |
+
{"content": "3", "summary": "9"}
|
5 |
+
{"content": "4", "summary": "16"}
|
6 |
+
{"content": "5", "summary": "25"}
|
7 |
+
{"content": "6", "summary": "36"}
|
8 |
+
{"content": "7", "summary": "49"}
|
9 |
+
{"content": "8", "summary": "64"}
|
10 |
+
{"content": "9", "summary": "81"}
|
11 |
+
{"content": "10", "summary": "100"}
|
12 |
+
{"content": "11", "summary": "121"}
|
13 |
+
{"content": "12", "summary": "144"}
|
14 |
+
{"content": "13", "summary": "169"}
|
15 |
+
{"content": "14", "summary": "196"}
|
16 |
+
{"content": "15", "summary": "225"}
|
17 |
+
{"content": "16", "summary": "256"}
|
18 |
+
{"content": "17", "summary": "289"}
|
19 |
+
{"content": "18", "summary": "324"}
|
20 |
+
{"content": "19", "summary": "361"}
|
21 |
+
{"content": "20", "summary": "400"}
|
22 |
+
{"content": "21", "summary": "441"}
|
23 |
+
{"content": "22", "summary": "484"}
|
24 |
+
{"content": "23", "summary": "529"}
|
25 |
+
{"content": "24", "summary": "576"}
|
26 |
+
{"content": "25", "summary": "625"}
|
27 |
+
{"content": "26", "summary": "676"}
|
28 |
+
{"content": "27", "summary": "729"}
|
29 |
+
{"content": "28", "summary": "784"}
|
30 |
+
{"content": "29", "summary": "841"}
|
31 |
+
{"content": "30", "summary": "900"}
|
32 |
+
{"content": "31", "summary": "961"}
|
33 |
+
{"content": "32", "summary": "1024"}
|
34 |
+
{"content": "33", "summary": "1089"}
|
35 |
+
{"content": "34", "summary": "1156"}
|
36 |
+
{"content": "35", "summary": "1225"}
|
37 |
+
{"content": "36", "summary": "1296"}
|
38 |
+
{"content": "37", "summary": "1369"}
|
39 |
+
{"content": "38", "summary": "1444"}
|
40 |
+
{"content": "39", "summary": "1521"}
|
41 |
+
{"content": "40", "summary": "1600"}
|
42 |
+
{"content": "41", "summary": "1681"}
|
43 |
+
{"content": "42", "summary": "1764"}
|
44 |
+
{"content": "43", "summary": "1849"}
|
45 |
+
{"content": "44", "summary": "1936"}
|
46 |
+
{"content": "45", "summary": "2025"}
|
47 |
+
{"content": "46", "summary": "2116"}
|
48 |
+
{"content": "47", "summary": "2209"}
|
49 |
+
{"content": "48", "summary": "2304"}
|
50 |
+
{"content": "49", "summary": "2401"}
|
51 |
+
{"content": "50", "summary": "2500"}
|
52 |
+
{"content": "51", "summary": "2601"}
|
53 |
+
{"content": "52", "summary": "2704"}
|
54 |
+
{"content": "53", "summary": "2809"}
|
55 |
+
{"content": "54", "summary": "2916"}
|
56 |
+
{"content": "55", "summary": "3025"}
|
57 |
+
{"content": "56", "summary": "3136"}
|
58 |
+
{"content": "57", "summary": "3249"}
|
59 |
+
{"content": "58", "summary": "3364"}
|
60 |
+
{"content": "59", "summary": "3481"}
|
61 |
+
{"content": "60", "summary": "3600"}
|
62 |
+
{"content": "61", "summary": "3721"}
|
63 |
+
{"content": "62", "summary": "3844"}
|
64 |
+
{"content": "63", "summary": "3969"}
|
65 |
+
{"content": "64", "summary": "4096"}
|
66 |
+
{"content": "65", "summary": "4225"}
|
67 |
+
{"content": "66", "summary": "4356"}
|
68 |
+
{"content": "67", "summary": "4489"}
|
69 |
+
{"content": "68", "summary": "4624"}
|
70 |
+
{"content": "69", "summary": "4761"}
|
71 |
+
{"content": "70", "summary": "4900"}
|
72 |
+
{"content": "71", "summary": "5041"}
|
73 |
+
{"content": "72", "summary": "5184"}
|
74 |
+
{"content": "73", "summary": "5329"}
|
75 |
+
{"content": "74", "summary": "5476"}
|
76 |
+
{"content": "75", "summary": "5625"}
|
77 |
+
{"content": "76", "summary": "5776"}
|
78 |
+
{"content": "77", "summary": "5929"}
|
79 |
+
{"content": "78", "summary": "6084"}
|
80 |
+
{"content": "79", "summary": "6241"}
|
81 |
+
{"content": "80", "summary": "6400"}
|
82 |
+
{"content": "81", "summary": "6561"}
|
83 |
+
{"content": "82", "summary": "6724"}
|
84 |
+
{"content": "83", "summary": "6889"}
|
85 |
+
{"content": "84", "summary": "7056"}
|
86 |
+
{"content": "85", "summary": "7225"}
|
87 |
+
{"content": "86", "summary": "7396"}
|
88 |
+
{"content": "87", "summary": "7569"}
|
89 |
+
{"content": "88", "summary": "7744"}
|
90 |
+
{"content": "89", "summary": "7921"}
|
91 |
+
{"content": "90", "summary": "8100"}
|
92 |
+
{"content": "91", "summary": "8281"}
|
93 |
+
{"content": "92", "summary": "8464"}
|
94 |
+
{"content": "93", "summary": "8649"}
|
95 |
+
{"content": "94", "summary": "8836"}
|
96 |
+
{"content": "95", "summary": "9025"}
|
97 |
+
{"content": "96", "summary": "9216"}
|
98 |
+
{"content": "97", "summary": "9409"}
|
99 |
+
{"content": "98", "summary": "9604"}
|
100 |
+
{"content": "99", "summary": "9801"}
|
101 |
+
{"content": "100", "summary": "10000"}
|
102 |
+
|
ptuning/deepspeed.json
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"train_micro_batch_size_per_gpu": "auto",
|
3 |
+
"zero_allow_untested_optimizer": true,
|
4 |
+
"fp16": {
|
5 |
+
"enabled": "auto",
|
6 |
+
"loss_scale": 0,
|
7 |
+
"initial_scale_power": 16,
|
8 |
+
"loss_scale_window": 1000,
|
9 |
+
"hysteresis": 2,
|
10 |
+
"min_loss_scale": 1
|
11 |
+
},
|
12 |
+
"zero_optimization": {
|
13 |
+
"stage": 2,
|
14 |
+
"allgather_partitions": true,
|
15 |
+
"allgather_bucket_size": 5e8,
|
16 |
+
"overlap_comm": false,
|
17 |
+
"reduce_scatter": true,
|
18 |
+
"reduce_bucket_size": 5e8,
|
19 |
+
"contiguous_gradients" : true
|
20 |
+
}
|
21 |
+
}
|
ptuning/ds_train_finetune.sh
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
LR=1e-4
|
3 |
+
|
4 |
+
MASTER_PORT=$(shuf -n 1 -i 10000-65535)
|
5 |
+
|
6 |
+
deepspeed --num_gpus=4 --master_port $MASTER_PORT main.py \
|
7 |
+
--deepspeed deepspeed.json \
|
8 |
+
--do_train \
|
9 |
+
--train_file AdvertiseGen/train.json \
|
10 |
+
--test_file AdvertiseGen/dev.json \
|
11 |
+
--prompt_column content \
|
12 |
+
--response_column summary \
|
13 |
+
--overwrite_cache \
|
14 |
+
--model_name_or_path THUDM/chatglm-6b \
|
15 |
+
--output_dir ./output/adgen-chatglm-6b-ft-$LR \
|
16 |
+
--overwrite_output_dir \
|
17 |
+
--max_source_length 64 \
|
18 |
+
--max_target_length 64 \
|
19 |
+
--per_device_train_batch_size 4 \
|
20 |
+
--per_device_eval_batch_size 1 \
|
21 |
+
--gradient_accumulation_steps 1 \
|
22 |
+
--predict_with_generate \
|
23 |
+
--max_steps 5000 \
|
24 |
+
--logging_steps 10 \
|
25 |
+
--save_steps 1000 \
|
26 |
+
--learning_rate $LR \
|
27 |
+
--fp16
|
28 |
+
|
ptuning/evaluate.sh
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
PRE_SEQ_LEN=128
|
2 |
+
CHECKPOINT=adgen-chatglm-6b-pt-128-2e-2
|
3 |
+
STEP=1000
|
4 |
+
|
5 |
+
CUDA_VISIBLE_DEVICES=0 python main.py \
|
6 |
+
--do_predict \
|
7 |
+
--train_file .\\datasets\\AdvertiseGen\\train.json \
|
8 |
+
--validation_file .\\datasets\\AdvertiseGen\\dev.json \
|
9 |
+
--test_file .\\datasets\\AdvertiseGen\\dev.json \
|
10 |
+
--overwrite_cache \
|
11 |
+
--prompt_column content \
|
12 |
+
--response_column summary \
|
13 |
+
--model_name_or_path ..\\models\\chatglm-6b-int4 \
|
14 |
+
--ptuning_checkpoint .\\output\\$CHECKPOINT\\checkpoint-$STEP \
|
15 |
+
--output_dir .\\output\\$CHECKPOINT \
|
16 |
+
--overwrite_output_dir \
|
17 |
+
--max_source_length 64 \
|
18 |
+
--max_target_length 64 \
|
19 |
+
--per_device_eval_batch_size 1 \
|
20 |
+
--predict_with_generate \
|
21 |
+
--pre_seq_len $PRE_SEQ_LEN \
|
22 |
+
--quantization_bit 4
|
ptuning/evaluate_finetune.sh
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CHECKPOINT=adgen-chatglm-6b-ft-1e-4
|
2 |
+
STEP=3000
|
3 |
+
|
4 |
+
CUDA_VISIBLE_DEVICES=0 python3 main.py \
|
5 |
+
--do_predict \
|
6 |
+
--validation_file AdvertiseGen/dev.json \
|
7 |
+
--test_file AdvertiseGen/dev.json \
|
8 |
+
--overwrite_cache \
|
9 |
+
--prompt_column content \
|
10 |
+
--response_column summary \
|
11 |
+
--model_name_or_path ./output/$CHECKPOINT/checkpoint-$STEP \
|
12 |
+
--output_dir ./output/$CHECKPOINT \
|
13 |
+
--overwrite_output_dir \
|
14 |
+
--max_source_length 256 \
|
15 |
+
--max_target_length 256 \
|
16 |
+
--per_device_eval_batch_size 1 \
|
17 |
+
--predict_with_generate \
|
18 |
+
--fp16_full_eval
|
ptuning/main.py
ADDED
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""
|
17 |
+
Fine-tuning the library models for sequence to sequence.
|
18 |
+
"""
|
19 |
+
# You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
|
20 |
+
|
21 |
+
import logging
|
22 |
+
import os
|
23 |
+
import sys
|
24 |
+
import json
|
25 |
+
|
26 |
+
import numpy as np
|
27 |
+
from datasets import load_dataset
|
28 |
+
import jieba
|
29 |
+
from rouge_chinese import Rouge
|
30 |
+
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
|
31 |
+
import torch
|
32 |
+
|
33 |
+
import transformers
|
34 |
+
from transformers import (
|
35 |
+
AutoConfig,
|
36 |
+
AutoModel,
|
37 |
+
AutoTokenizer,
|
38 |
+
AutoTokenizer,
|
39 |
+
DataCollatorForSeq2Seq,
|
40 |
+
HfArgumentParser,
|
41 |
+
Seq2SeqTrainingArguments,
|
42 |
+
set_seed,
|
43 |
+
)
|
44 |
+
from trainer_seq2seq import Seq2SeqTrainer
|
45 |
+
|
46 |
+
from arguments import ModelArguments, DataTrainingArguments
|
47 |
+
|
48 |
+
logger = logging.getLogger(__name__)
|
49 |
+
|
50 |
+
def main():
|
51 |
+
|
52 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
53 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
54 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
55 |
+
# let's parse it to get our arguments.
|
56 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
57 |
+
else:
|
58 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
59 |
+
|
60 |
+
# Setup logging
|
61 |
+
logging.basicConfig(
|
62 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
63 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
64 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
65 |
+
)
|
66 |
+
|
67 |
+
if training_args.should_log:
|
68 |
+
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
|
69 |
+
transformers.utils.logging.set_verbosity_info()
|
70 |
+
|
71 |
+
log_level = training_args.get_process_log_level()
|
72 |
+
logger.setLevel(log_level)
|
73 |
+
# datasets.utils.logging.set_verbosity(log_level)
|
74 |
+
transformers.utils.logging.set_verbosity(log_level)
|
75 |
+
transformers.utils.logging.enable_default_handler()
|
76 |
+
transformers.utils.logging.enable_explicit_format()
|
77 |
+
|
78 |
+
# Log on each process the small summary:
|
79 |
+
logger.warning(
|
80 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
81 |
+
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
82 |
+
)
|
83 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
84 |
+
|
85 |
+
# Set seed before initializing model.
|
86 |
+
set_seed(training_args.seed)
|
87 |
+
|
88 |
+
# Load dataset
|
89 |
+
data_files = {}
|
90 |
+
if data_args.train_file is not None:
|
91 |
+
data_files["train"] = data_args.train_file
|
92 |
+
extension = data_args.train_file.split(".")[-1]
|
93 |
+
if data_args.validation_file is not None:
|
94 |
+
data_files["validation"] = data_args.validation_file
|
95 |
+
extension = data_args.validation_file.split(".")[-1]
|
96 |
+
if data_args.test_file is not None:
|
97 |
+
data_files["test"] = data_args.test_file
|
98 |
+
extension = data_args.test_file.split(".")[-1]
|
99 |
+
|
100 |
+
raw_datasets = load_dataset(
|
101 |
+
extension,
|
102 |
+
data_files=data_files,
|
103 |
+
cache_dir=model_args.cache_dir,
|
104 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
105 |
+
)
|
106 |
+
print('---------------------------------------------------')
|
107 |
+
|
108 |
+
print("raw_datasets:", raw_datasets)
|
109 |
+
|
110 |
+
|
111 |
+
# Load pretrained model and tokenizer
|
112 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True)
|
113 |
+
config.pre_seq_len = model_args.pre_seq_len
|
114 |
+
config.prefix_projection = model_args.prefix_projection
|
115 |
+
|
116 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, trust_remote_code=True)
|
117 |
+
|
118 |
+
if model_args.ptuning_checkpoint is not None:
|
119 |
+
# Evaluation
|
120 |
+
# Loading extra state dict of prefix encoder
|
121 |
+
model = AutoModel.from_pretrained(model_args.model_name_or_path, config=config, trust_remote_code=True)
|
122 |
+
prefix_state_dict = torch.load(os.path.join(model_args.ptuning_checkpoint, "pytorch_model.bin"))
|
123 |
+
new_prefix_state_dict = {}
|
124 |
+
for k, v in prefix_state_dict.items():
|
125 |
+
if k.startswith("transformer.prefix_encoder."):
|
126 |
+
new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
|
127 |
+
model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
|
128 |
+
else:
|
129 |
+
model = AutoModel.from_pretrained(model_args.model_name_or_path, config=config, trust_remote_code=True)
|
130 |
+
|
131 |
+
if model_args.quantization_bit is not None:
|
132 |
+
print(f"Quantized to {model_args.quantization_bit} bit")
|
133 |
+
|
134 |
+
try:
|
135 |
+
# kernel_file = "{}\\quantization_kernels.so".format(model_args.model_name_or_path)
|
136 |
+
kernel_file = "{}/quantization_kernels.so".format(model_args.model_name_or_path)
|
137 |
+
model = model.quantize(bits=model_args.quantization_bit, kernel_file=kernel_file)
|
138 |
+
|
139 |
+
except:
|
140 |
+
model = model.quantize(bits=model_args.quantization_bit)
|
141 |
+
|
142 |
+
|
143 |
+
if model_args.pre_seq_len is not None:
|
144 |
+
# P-tuning v2
|
145 |
+
model = model.half()
|
146 |
+
model.transformer.prefix_encoder.float()
|
147 |
+
else:
|
148 |
+
# Finetune
|
149 |
+
model = model.float()
|
150 |
+
|
151 |
+
prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
|
152 |
+
|
153 |
+
# Preprocessing the datasets.
|
154 |
+
# We need to tokenize inputs and targets.
|
155 |
+
if training_args.do_train:
|
156 |
+
column_names = raw_datasets["train"].column_names
|
157 |
+
elif training_args.do_eval:
|
158 |
+
column_names = raw_datasets["validation"].column_names
|
159 |
+
elif training_args.do_predict:
|
160 |
+
column_names = raw_datasets["test"].column_names
|
161 |
+
|
162 |
+
else:
|
163 |
+
logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.")
|
164 |
+
return
|
165 |
+
|
166 |
+
# Get the column names for input/target.
|
167 |
+
prompt_column = data_args.prompt_column
|
168 |
+
response_column = data_args.response_column
|
169 |
+
history_column = data_args.history_column
|
170 |
+
|
171 |
+
# Temporarily set max_target_length for training.
|
172 |
+
max_target_length = data_args.max_target_length
|
173 |
+
|
174 |
+
def preprocess_function_eval(examples):
|
175 |
+
inputs, targets = [], []
|
176 |
+
for i in range(len(examples[prompt_column])):
|
177 |
+
if examples[prompt_column][i] and examples[response_column][i]:
|
178 |
+
query = examples[prompt_column][i]
|
179 |
+
if history_column is None or len(examples[history_column][i]) == 0:
|
180 |
+
prompt = query
|
181 |
+
else:
|
182 |
+
prompt = ""
|
183 |
+
history = examples[history_column][i]
|
184 |
+
for turn_idx, (old_query, response) in enumerate(history):
|
185 |
+
prompt += "[Round {}]\n问:{}\n答:{}\n".format(turn_idx, old_query, response)
|
186 |
+
prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
|
187 |
+
inputs.append(prompt)
|
188 |
+
targets.append(examples[response_column][i])
|
189 |
+
|
190 |
+
inputs = [prefix + inp for inp in inputs]
|
191 |
+
model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, truncation=True, padding=True)
|
192 |
+
labels = tokenizer(text_target=targets, max_length=max_target_length, truncation=True)
|
193 |
+
|
194 |
+
if data_args.ignore_pad_token_for_loss:
|
195 |
+
labels["input_ids"] = [
|
196 |
+
[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
|
197 |
+
]
|
198 |
+
model_inputs["labels"] = labels["input_ids"]
|
199 |
+
|
200 |
+
return model_inputs
|
201 |
+
|
202 |
+
def preprocess_function_train(examples):
|
203 |
+
max_seq_length = data_args.max_source_length + data_args.max_target_length
|
204 |
+
|
205 |
+
model_inputs = {
|
206 |
+
"input_ids": [],
|
207 |
+
"labels": [],
|
208 |
+
}
|
209 |
+
for i in range(len(examples[prompt_column])):
|
210 |
+
if examples[prompt_column][i] and examples[response_column][i]:
|
211 |
+
query, answer = examples[prompt_column][i], examples[response_column][i]
|
212 |
+
|
213 |
+
if history_column is None:
|
214 |
+
prompt = query
|
215 |
+
else:
|
216 |
+
prompt = ""
|
217 |
+
history = examples[history_column][i]
|
218 |
+
for turn_idx, (old_query, response) in enumerate(history):
|
219 |
+
prompt += "[Round {}]\n问:{}\n答:{}\n".format(turn_idx, old_query, response)
|
220 |
+
prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
|
221 |
+
|
222 |
+
prompt = prefix + prompt
|
223 |
+
a_ids = tokenizer.encode(text=prompt, add_special_tokens=False)
|
224 |
+
b_ids = tokenizer.encode(text=answer, add_special_tokens=False)
|
225 |
+
|
226 |
+
if len(a_ids) > data_args.max_source_length - 1:
|
227 |
+
a_ids = a_ids[: data_args.max_source_length - 1]
|
228 |
+
|
229 |
+
if len(b_ids) > data_args.max_target_length - 2:
|
230 |
+
b_ids = b_ids[: data_args.max_target_length - 2]
|
231 |
+
|
232 |
+
input_ids = tokenizer.build_inputs_with_special_tokens(a_ids, b_ids)
|
233 |
+
|
234 |
+
context_length = input_ids.index(tokenizer.bos_token_id)
|
235 |
+
mask_position = context_length - 1
|
236 |
+
labels = [-100] * context_length + input_ids[mask_position+1:]
|
237 |
+
|
238 |
+
pad_len = max_seq_length - len(input_ids)
|
239 |
+
input_ids = input_ids + [tokenizer.pad_token_id] * pad_len
|
240 |
+
labels = labels + [tokenizer.pad_token_id] * pad_len
|
241 |
+
if data_args.ignore_pad_token_for_loss:
|
242 |
+
labels = [(l if l != tokenizer.pad_token_id else -100) for l in labels]
|
243 |
+
|
244 |
+
model_inputs["input_ids"].append(input_ids)
|
245 |
+
model_inputs["labels"].append(labels)
|
246 |
+
|
247 |
+
return model_inputs
|
248 |
+
|
249 |
+
def print_dataset_example(example):
|
250 |
+
print("input_ids",example["input_ids"])
|
251 |
+
print("inputs", tokenizer.decode(example["input_ids"]))
|
252 |
+
print("label_ids", example["labels"])
|
253 |
+
print("labels", tokenizer.decode(example["labels"]))
|
254 |
+
|
255 |
+
if training_args.do_train:
|
256 |
+
if "train" not in raw_datasets:
|
257 |
+
raise ValueError("--do_train requires a train dataset")
|
258 |
+
train_dataset = raw_datasets["train"]
|
259 |
+
if data_args.max_train_samples is not None:
|
260 |
+
max_train_samples = min(len(train_dataset), data_args.max_train_samples)
|
261 |
+
train_dataset = train_dataset.select(range(max_train_samples))
|
262 |
+
with training_args.main_process_first(desc="train dataset map pre-processing"):
|
263 |
+
train_dataset = train_dataset.map(
|
264 |
+
preprocess_function_train,
|
265 |
+
batched=True,
|
266 |
+
num_proc=data_args.preprocessing_num_workers,
|
267 |
+
remove_columns=column_names,
|
268 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
269 |
+
desc="Running tokenizer on train dataset",
|
270 |
+
)
|
271 |
+
print_dataset_example(train_dataset[0])
|
272 |
+
|
273 |
+
if training_args.do_eval:
|
274 |
+
max_target_length = data_args.val_max_target_length
|
275 |
+
if "validation" not in raw_datasets:
|
276 |
+
raise ValueError("--do_eval requires a validation dataset")
|
277 |
+
eval_dataset = raw_datasets["validation"]
|
278 |
+
if data_args.max_eval_samples is not None:
|
279 |
+
max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
|
280 |
+
eval_dataset = eval_dataset.select(range(max_eval_samples))
|
281 |
+
with training_args.main_process_first(desc="validation dataset map pre-processing"):
|
282 |
+
eval_dataset = eval_dataset.map(
|
283 |
+
preprocess_function_eval,
|
284 |
+
batched=True,
|
285 |
+
num_proc=data_args.preprocessing_num_workers,
|
286 |
+
remove_columns=column_names,
|
287 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
288 |
+
desc="Running tokenizer on validation dataset",
|
289 |
+
)
|
290 |
+
print_dataset_example(eval_dataset[0])
|
291 |
+
|
292 |
+
if training_args.do_predict:
|
293 |
+
max_target_length = data_args.val_max_target_length
|
294 |
+
if "test" not in raw_datasets:
|
295 |
+
raise ValueError("--do_predict requires a test dataset")
|
296 |
+
predict_dataset = raw_datasets["test"]
|
297 |
+
if data_args.max_predict_samples is not None:
|
298 |
+
max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples)
|
299 |
+
predict_dataset = predict_dataset.select(range(max_predict_samples))
|
300 |
+
with training_args.main_process_first(desc="prediction dataset map pre-processing"):
|
301 |
+
predict_dataset = predict_dataset.map(
|
302 |
+
preprocess_function_eval,
|
303 |
+
batched=True,
|
304 |
+
num_proc=data_args.preprocessing_num_workers,
|
305 |
+
remove_columns=column_names,
|
306 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
307 |
+
desc="Running tokenizer on prediction dataset",
|
308 |
+
)
|
309 |
+
print_dataset_example(predict_dataset[0])
|
310 |
+
|
311 |
+
# Data collator
|
312 |
+
label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id
|
313 |
+
data_collator = DataCollatorForSeq2Seq(
|
314 |
+
tokenizer,
|
315 |
+
model=model,
|
316 |
+
label_pad_token_id=label_pad_token_id,
|
317 |
+
pad_to_multiple_of=None,
|
318 |
+
padding=False
|
319 |
+
)
|
320 |
+
|
321 |
+
# Metric
|
322 |
+
def compute_metrics(eval_preds):
|
323 |
+
preds, labels = eval_preds
|
324 |
+
if isinstance(preds, tuple):
|
325 |
+
preds = preds[0]
|
326 |
+
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
|
327 |
+
if data_args.ignore_pad_token_for_loss:
|
328 |
+
# Replace -100 in the labels as we can't decode them.
|
329 |
+
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
|
330 |
+
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
|
331 |
+
|
332 |
+
score_dict = {
|
333 |
+
"rouge-1": [],
|
334 |
+
"rouge-2": [],
|
335 |
+
"rouge-l": [],
|
336 |
+
"bleu-4": []
|
337 |
+
}
|
338 |
+
for pred, label in zip(decoded_preds, decoded_labels):
|
339 |
+
hypothesis = list(jieba.cut(pred))
|
340 |
+
reference = list(jieba.cut(label))
|
341 |
+
rouge = Rouge()
|
342 |
+
scores = rouge.get_scores(' '.join(hypothesis) , ' '.join(reference))
|
343 |
+
result = scores[0]
|
344 |
+
|
345 |
+
for k, v in result.items():
|
346 |
+
score_dict[k].append(round(v["f"] * 100, 4))
|
347 |
+
bleu_score = sentence_bleu([list(label)], list(pred), smoothing_function=SmoothingFunction().method3)
|
348 |
+
score_dict["bleu-4"].append(round(bleu_score * 100, 4))
|
349 |
+
|
350 |
+
for k, v in score_dict.items():
|
351 |
+
score_dict[k] = float(np.mean(v))
|
352 |
+
return score_dict
|
353 |
+
|
354 |
+
# Override the decoding parameters of Seq2SeqTrainer
|
355 |
+
training_args.generation_max_length = (
|
356 |
+
training_args.generation_max_length
|
357 |
+
if training_args.generation_max_length is not None
|
358 |
+
else data_args.val_max_target_length
|
359 |
+
)
|
360 |
+
training_args.generation_num_beams = (
|
361 |
+
data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams
|
362 |
+
)
|
363 |
+
# Initialize our Trainer
|
364 |
+
trainer = Seq2SeqTrainer(
|
365 |
+
model=model,
|
366 |
+
args=training_args,
|
367 |
+
train_dataset=train_dataset if training_args.do_train else None,
|
368 |
+
eval_dataset=eval_dataset if training_args.do_eval else None,
|
369 |
+
tokenizer=tokenizer,
|
370 |
+
data_collator=data_collator,
|
371 |
+
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
|
372 |
+
save_prefixencoder=model_args.pre_seq_len is not None
|
373 |
+
)
|
374 |
+
|
375 |
+
# Training
|
376 |
+
if training_args.do_train:
|
377 |
+
checkpoint = None
|
378 |
+
if training_args.resume_from_checkpoint is not None:
|
379 |
+
checkpoint = training_args.resume_from_checkpoint
|
380 |
+
# elif last_checkpoint is not None:
|
381 |
+
# checkpoint = last_checkpoint
|
382 |
+
model.gradient_checkpointing_enable()
|
383 |
+
model.enable_input_require_grads()
|
384 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
385 |
+
# trainer.save_model() # Saves the tokenizer too for easy upload
|
386 |
+
|
387 |
+
metrics = train_result.metrics
|
388 |
+
max_train_samples = (
|
389 |
+
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
|
390 |
+
)
|
391 |
+
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
|
392 |
+
|
393 |
+
trainer.log_metrics("train", metrics)
|
394 |
+
trainer.save_metrics("train", metrics)
|
395 |
+
trainer.save_state()
|
396 |
+
|
397 |
+
# Evaluation
|
398 |
+
results = {}
|
399 |
+
if training_args.do_eval:
|
400 |
+
logger.info("*** Evaluate ***")
|
401 |
+
metrics = trainer.evaluate(metric_key_prefix="eval", do_sample=True, top_p=0.7, max_length=512, temperature=0.95)
|
402 |
+
max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
|
403 |
+
metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
|
404 |
+
|
405 |
+
trainer.log_metrics("eval", metrics)
|
406 |
+
trainer.save_metrics("eval", metrics)
|
407 |
+
|
408 |
+
if training_args.do_predict:
|
409 |
+
logger.info("*** Predict ***")
|
410 |
+
|
411 |
+
predict_results = trainer.predict(predict_dataset, metric_key_prefix="predict", max_length=512, do_sample=True, top_p=0.7, temperature=0.95)
|
412 |
+
metrics = predict_results.metrics
|
413 |
+
max_predict_samples = (
|
414 |
+
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset)
|
415 |
+
)
|
416 |
+
metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset))
|
417 |
+
|
418 |
+
trainer.log_metrics("predict", metrics)
|
419 |
+
trainer.save_metrics("predict", metrics)
|
420 |
+
|
421 |
+
if trainer.is_world_process_zero():
|
422 |
+
if training_args.predict_with_generate:
|
423 |
+
predictions = tokenizer.batch_decode(
|
424 |
+
predict_results.predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True
|
425 |
+
)
|
426 |
+
predictions = [pred.strip() for pred in predictions]
|
427 |
+
labels = tokenizer.batch_decode(
|
428 |
+
predict_results.label_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
|
429 |
+
)
|
430 |
+
labels = [label.strip() for label in labels]
|
431 |
+
output_prediction_file = os.path.join(training_args.output_dir, "generated_predictions.txt")
|
432 |
+
with open(output_prediction_file, "w", encoding="utf-8") as writer:
|
433 |
+
for p, l in zip(predictions, labels):
|
434 |
+
res = json.dumps({"labels": l, "predict": p}, ensure_ascii=False)
|
435 |
+
writer.write(f"{res}\n")
|
436 |
+
return results
|
437 |
+
|
438 |
+
|
439 |
+
def _mp_fn(index):
|
440 |
+
# For xla_spawn (TPUs)
|
441 |
+
main()
|
442 |
+
|
443 |
+
|
444 |
+
if __name__ == "__main__":
|
445 |
+
main()
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/all_results.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"epoch": 114.29,
|
3 |
+
"train_loss": 0.2596614052057266,
|
4 |
+
"train_runtime": 12879.4173,
|
5 |
+
"train_samples": 140,
|
6 |
+
"train_samples_per_second": 1.242,
|
7 |
+
"train_steps_per_second": 0.078
|
8 |
+
}
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/config.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "..\\models\\chatglm-6b-int4",
|
3 |
+
"architectures": [
|
4 |
+
"ChatGLMForConditionalGeneration"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
8 |
+
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
9 |
+
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
|
10 |
+
},
|
11 |
+
"bos_token_id": 130004,
|
12 |
+
"eos_token_id": 130005,
|
13 |
+
"gmask_token_id": 130001,
|
14 |
+
"hidden_size": 4096,
|
15 |
+
"inner_hidden_size": 16384,
|
16 |
+
"layernorm_epsilon": 1e-05,
|
17 |
+
"mask_token_id": 130000,
|
18 |
+
"max_sequence_length": 2048,
|
19 |
+
"model_type": "chatglm",
|
20 |
+
"num_attention_heads": 32,
|
21 |
+
"num_layers": 28,
|
22 |
+
"pad_token_id": 3,
|
23 |
+
"position_encoding_2d": true,
|
24 |
+
"pre_seq_len": 128,
|
25 |
+
"prefix_projection": false,
|
26 |
+
"quantization_bit": 4,
|
27 |
+
"quantization_embeddings": false,
|
28 |
+
"torch_dtype": "float16",
|
29 |
+
"transformers_version": "4.27.1",
|
30 |
+
"use_cache": true,
|
31 |
+
"vocab_size": 130528
|
32 |
+
}
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/configuration_chatglm.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" ChatGLM model configuration """
|
2 |
+
|
3 |
+
from transformers.configuration_utils import PretrainedConfig
|
4 |
+
from transformers.utils import logging
|
5 |
+
|
6 |
+
logger = logging.get_logger(__name__)
|
7 |
+
|
8 |
+
|
9 |
+
class ChatGLMConfig(PretrainedConfig):
|
10 |
+
r"""
|
11 |
+
This is the configuration class to store the configuration of a [`~ChatGLMModel`].
|
12 |
+
It is used to instantiate an ChatGLM model according to the specified arguments, defining the model
|
13 |
+
architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
|
14 |
+
the ChatGLM-6B [THUDM/ChatGLM-6B](https://huggingface.co/THUDM/chatglm-6b) architecture.
|
15 |
+
|
16 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used
|
17 |
+
to control the model outputs. Read the documentation from [`PretrainedConfig`]
|
18 |
+
for more information.
|
19 |
+
|
20 |
+
|
21 |
+
Args:
|
22 |
+
vocab_size (`int`, *optional*, defaults to 150528):
|
23 |
+
Vocabulary size of the ChatGLM-6B model. Defines the number of different tokens that can be represented by the
|
24 |
+
`inputs_ids` passed when calling [`~ChatGLMModel`] or
|
25 |
+
[`~TFChatGLMModel`].
|
26 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
27 |
+
Dimension of the encoder layers and the pooler layer.
|
28 |
+
num_hidden_layers (`int`, *optional*, defaults to 28):
|
29 |
+
Number of hidden layers in the Transformer encoder.
|
30 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
31 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
32 |
+
inner_hidden_size (`int`, *optional*, defaults to 16384):
|
33 |
+
Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
34 |
+
max_sequence_length (`int`, *optional*, defaults to 512):
|
35 |
+
The maximum sequence length that this model might ever be used with.
|
36 |
+
Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
|
37 |
+
layernorm_epsilon (`float`, *optional*, defaults to 1e-5):
|
38 |
+
The epsilon used by the layer normalization layers.
|
39 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
40 |
+
Whether the model should return the last key/values attentions (not used by all models).
|
41 |
+
Example:
|
42 |
+
|
43 |
+
```python
|
44 |
+
>>> from configuration_chatglm import ChatGLMConfig
|
45 |
+
>>> from modeling_chatglm import ChatGLMModel
|
46 |
+
|
47 |
+
>>> # Initializing a ChatGLM-6B THUDM/ChatGLM-6B style configuration
|
48 |
+
>>> configuration = ChatGLMConfig()
|
49 |
+
|
50 |
+
>>> # Initializing a model from the THUDM/ChatGLM-6B style configuration
|
51 |
+
>>> model = ChatGLMModel(configuration)
|
52 |
+
|
53 |
+
>>> # Accessing the model configuration
|
54 |
+
>>> configuration = model.config
|
55 |
+
```
|
56 |
+
"""
|
57 |
+
model_type = "chatglm"
|
58 |
+
|
59 |
+
def __init__(
|
60 |
+
self,
|
61 |
+
vocab_size=150528,
|
62 |
+
hidden_size=4096,
|
63 |
+
num_layers=28,
|
64 |
+
num_attention_heads=32,
|
65 |
+
layernorm_epsilon=1e-5,
|
66 |
+
use_cache=False,
|
67 |
+
bos_token_id=150004,
|
68 |
+
eos_token_id=150005,
|
69 |
+
mask_token_id=150000,
|
70 |
+
gmask_token_id=150001,
|
71 |
+
pad_token_id=0,
|
72 |
+
max_sequence_length=2048,
|
73 |
+
inner_hidden_size=16384,
|
74 |
+
position_encoding_2d=True,
|
75 |
+
quantization_bit=0,
|
76 |
+
quantization_embeddings=False,
|
77 |
+
pre_seq_len=None,
|
78 |
+
prefix_projection=False,
|
79 |
+
**kwargs
|
80 |
+
):
|
81 |
+
self.num_layers = num_layers
|
82 |
+
self.vocab_size = vocab_size
|
83 |
+
self.hidden_size = hidden_size
|
84 |
+
self.num_attention_heads = num_attention_heads
|
85 |
+
self.max_sequence_length = max_sequence_length
|
86 |
+
self.layernorm_epsilon = layernorm_epsilon
|
87 |
+
self.inner_hidden_size = inner_hidden_size
|
88 |
+
self.use_cache = use_cache
|
89 |
+
self.bos_token_id = bos_token_id
|
90 |
+
self.eos_token_id = eos_token_id
|
91 |
+
self.pad_token_id = pad_token_id
|
92 |
+
self.mask_token_id = mask_token_id
|
93 |
+
self.gmask_token_id = gmask_token_id
|
94 |
+
self.position_encoding_2d = position_encoding_2d
|
95 |
+
self.quantization_bit = quantization_bit
|
96 |
+
self.quantization_embeddings = quantization_embeddings
|
97 |
+
self.pre_seq_len = pre_seq_len
|
98 |
+
self.prefix_projection = prefix_projection
|
99 |
+
|
100 |
+
super().__init__(
|
101 |
+
pad_token_id=pad_token_id,
|
102 |
+
bos_token_id=bos_token_id,
|
103 |
+
eos_token_id=eos_token_id,
|
104 |
+
**kwargs
|
105 |
+
)
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 130004,
|
4 |
+
"eos_token_id": 130005,
|
5 |
+
"pad_token_id": 3,
|
6 |
+
"transformers_version": "4.27.1"
|
7 |
+
}
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/ice_text.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5e974d9a69c242ce014c88c2b26089270f6198f3c0b700a887666cd3e816f17e
|
3 |
+
size 2706249
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/modeling_chatglm.py
ADDED
@@ -0,0 +1,1472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" PyTorch ChatGLM model. """
|
2 |
+
|
3 |
+
import math
|
4 |
+
import copy
|
5 |
+
import os
|
6 |
+
import warnings
|
7 |
+
import re
|
8 |
+
import sys
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.utils.checkpoint
|
12 |
+
import torch.nn.functional as F
|
13 |
+
from torch import nn
|
14 |
+
from torch.nn import CrossEntropyLoss, LayerNorm
|
15 |
+
from torch.nn.utils import skip_init
|
16 |
+
from typing import Optional, Tuple, Union, List, Callable, Dict, Any
|
17 |
+
|
18 |
+
from transformers.utils import (
|
19 |
+
add_code_sample_docstrings,
|
20 |
+
add_start_docstrings,
|
21 |
+
add_start_docstrings_to_model_forward,
|
22 |
+
)
|
23 |
+
from transformers.modeling_outputs import (
|
24 |
+
BaseModelOutputWithPast,
|
25 |
+
CausalLMOutputWithPast,
|
26 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
27 |
+
)
|
28 |
+
from transformers.modeling_utils import PreTrainedModel
|
29 |
+
from transformers.utils import logging
|
30 |
+
from transformers.generation.logits_process import LogitsProcessor
|
31 |
+
from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
|
32 |
+
|
33 |
+
from .configuration_chatglm import ChatGLMConfig
|
34 |
+
|
35 |
+
|
36 |
+
# flags required to enable jit fusion kernels
|
37 |
+
|
38 |
+
if sys.platform != 'darwin':
|
39 |
+
torch._C._jit_set_profiling_mode(False)
|
40 |
+
torch._C._jit_set_profiling_executor(False)
|
41 |
+
torch._C._jit_override_can_fuse_on_cpu(True)
|
42 |
+
torch._C._jit_override_can_fuse_on_gpu(True)
|
43 |
+
|
44 |
+
logger = logging.get_logger(__name__)
|
45 |
+
|
46 |
+
_CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
|
47 |
+
_CONFIG_FOR_DOC = "ChatGLM6BConfig"
|
48 |
+
|
49 |
+
CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
50 |
+
"THUDM/chatglm-6b",
|
51 |
+
# See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
|
52 |
+
]
|
53 |
+
|
54 |
+
|
55 |
+
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
56 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
57 |
+
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
58 |
+
scores.zero_()
|
59 |
+
scores[..., 5] = 5e4
|
60 |
+
return scores
|
61 |
+
|
62 |
+
|
63 |
+
def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
|
64 |
+
"""Load tf checkpoints in a pytorch model."""
|
65 |
+
try:
|
66 |
+
import re
|
67 |
+
|
68 |
+
import numpy as np
|
69 |
+
import tensorflow as tf
|
70 |
+
except ImportError:
|
71 |
+
logger.error(
|
72 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
73 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
74 |
+
)
|
75 |
+
raise
|
76 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
77 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
78 |
+
# Load weights from TF model
|
79 |
+
init_vars = tf.train.list_variables(tf_path)
|
80 |
+
names = []
|
81 |
+
arrays = []
|
82 |
+
for name, shape in init_vars:
|
83 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
84 |
+
array = tf.train.load_variable(tf_path, name)
|
85 |
+
names.append(name)
|
86 |
+
arrays.append(array)
|
87 |
+
|
88 |
+
for name, array in zip(names, arrays):
|
89 |
+
name = name.split("/")
|
90 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
91 |
+
# which are not required for using pretrained model
|
92 |
+
if any(
|
93 |
+
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
|
94 |
+
for n in name
|
95 |
+
):
|
96 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
97 |
+
continue
|
98 |
+
pointer = model
|
99 |
+
for m_name in name:
|
100 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
101 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
102 |
+
else:
|
103 |
+
scope_names = [m_name]
|
104 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
105 |
+
pointer = getattr(pointer, "weight")
|
106 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
107 |
+
pointer = getattr(pointer, "bias")
|
108 |
+
elif scope_names[0] == "output_weights":
|
109 |
+
pointer = getattr(pointer, "weight")
|
110 |
+
elif scope_names[0] == "squad":
|
111 |
+
pointer = getattr(pointer, "classifier")
|
112 |
+
else:
|
113 |
+
try:
|
114 |
+
pointer = getattr(pointer, scope_names[0])
|
115 |
+
except AttributeError:
|
116 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
117 |
+
continue
|
118 |
+
if len(scope_names) >= 2:
|
119 |
+
num = int(scope_names[1])
|
120 |
+
pointer = pointer[num]
|
121 |
+
if m_name[-11:] == "_embeddings":
|
122 |
+
pointer = getattr(pointer, "weight")
|
123 |
+
elif m_name == "kernel":
|
124 |
+
array = np.transpose(array)
|
125 |
+
try:
|
126 |
+
assert (
|
127 |
+
pointer.shape == array.shape
|
128 |
+
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
|
129 |
+
except AssertionError as e:
|
130 |
+
e.args += (pointer.shape, array.shape)
|
131 |
+
raise
|
132 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
133 |
+
pointer.data = torch.from_numpy(array)
|
134 |
+
return model
|
135 |
+
|
136 |
+
|
137 |
+
class PrefixEncoder(torch.nn.Module):
|
138 |
+
"""
|
139 |
+
The torch.nn model to encode the prefix
|
140 |
+
Input shape: (batch-size, prefix-length)
|
141 |
+
Output shape: (batch-size, prefix-length, 2*layers*hidden)
|
142 |
+
"""
|
143 |
+
|
144 |
+
def __init__(self, config):
|
145 |
+
super().__init__()
|
146 |
+
self.prefix_projection = config.prefix_projection
|
147 |
+
if self.prefix_projection:
|
148 |
+
# Use a two-layer MLP to encode the prefix
|
149 |
+
self.embedding = torch.nn.Embedding(config.pre_seq_len, config.hidden_size)
|
150 |
+
self.trans = torch.nn.Sequential(
|
151 |
+
torch.nn.Linear(config.hidden_size, config.hidden_size),
|
152 |
+
torch.nn.Tanh(),
|
153 |
+
torch.nn.Linear(config.hidden_size, config.num_layers * config.hidden_size * 2)
|
154 |
+
)
|
155 |
+
else:
|
156 |
+
self.embedding = torch.nn.Embedding(config.pre_seq_len, config.num_layers * config.hidden_size * 2)
|
157 |
+
|
158 |
+
def forward(self, prefix: torch.Tensor):
|
159 |
+
if self.prefix_projection:
|
160 |
+
prefix_tokens = self.embedding(prefix)
|
161 |
+
past_key_values = self.trans(prefix_tokens)
|
162 |
+
else:
|
163 |
+
past_key_values = self.embedding(prefix)
|
164 |
+
return past_key_values
|
165 |
+
|
166 |
+
|
167 |
+
@torch.jit.script
|
168 |
+
def gelu_impl(x):
|
169 |
+
"""OpenAI's gelu implementation."""
|
170 |
+
return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
|
171 |
+
(1.0 + 0.044715 * x * x)))
|
172 |
+
|
173 |
+
|
174 |
+
def gelu(x):
|
175 |
+
return gelu_impl(x)
|
176 |
+
|
177 |
+
|
178 |
+
class RotaryEmbedding(torch.nn.Module):
|
179 |
+
def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
|
180 |
+
super().__init__()
|
181 |
+
inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
|
182 |
+
inv_freq = inv_freq.half()
|
183 |
+
self.learnable = learnable
|
184 |
+
if learnable:
|
185 |
+
self.inv_freq = torch.nn.Parameter(inv_freq)
|
186 |
+
self.max_seq_len_cached = None
|
187 |
+
else:
|
188 |
+
self.register_buffer('inv_freq', inv_freq)
|
189 |
+
self.max_seq_len_cached = None
|
190 |
+
self.cos_cached = None
|
191 |
+
self.sin_cached = None
|
192 |
+
self.precision = precision
|
193 |
+
|
194 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
|
195 |
+
error_msgs):
|
196 |
+
pass
|
197 |
+
|
198 |
+
def forward(self, x, seq_dim=1, seq_len=None):
|
199 |
+
if seq_len is None:
|
200 |
+
seq_len = x.shape[seq_dim]
|
201 |
+
if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
|
202 |
+
self.max_seq_len_cached = None if self.learnable else seq_len
|
203 |
+
t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
|
204 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
205 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
206 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
207 |
+
if self.precision == torch.bfloat16:
|
208 |
+
emb = emb.float()
|
209 |
+
|
210 |
+
# [sx, 1 (b * np), hn]
|
211 |
+
cos_cached = emb.cos()[:, None, :]
|
212 |
+
sin_cached = emb.sin()[:, None, :]
|
213 |
+
if self.precision == torch.bfloat16:
|
214 |
+
cos_cached = cos_cached.bfloat16()
|
215 |
+
sin_cached = sin_cached.bfloat16()
|
216 |
+
if self.learnable:
|
217 |
+
return cos_cached, sin_cached
|
218 |
+
self.cos_cached, self.sin_cached = cos_cached, sin_cached
|
219 |
+
return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
|
220 |
+
|
221 |
+
def _apply(self, fn):
|
222 |
+
if self.cos_cached is not None:
|
223 |
+
self.cos_cached = fn(self.cos_cached)
|
224 |
+
if self.sin_cached is not None:
|
225 |
+
self.sin_cached = fn(self.sin_cached)
|
226 |
+
return super()._apply(fn)
|
227 |
+
|
228 |
+
def rotate_half(x):
|
229 |
+
x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
|
230 |
+
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
|
231 |
+
|
232 |
+
|
233 |
+
@torch.jit.script
|
234 |
+
def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
|
235 |
+
# position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
|
236 |
+
cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
|
237 |
+
F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
|
238 |
+
q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
|
239 |
+
return q, k
|
240 |
+
|
241 |
+
|
242 |
+
def attention_fn(
|
243 |
+
self,
|
244 |
+
query_layer,
|
245 |
+
key_layer,
|
246 |
+
value_layer,
|
247 |
+
attention_mask,
|
248 |
+
hidden_size_per_partition,
|
249 |
+
layer_id,
|
250 |
+
layer_past=None,
|
251 |
+
scaling_attention_score=True,
|
252 |
+
use_cache=False,
|
253 |
+
):
|
254 |
+
if layer_past is not None:
|
255 |
+
past_key, past_value = layer_past[0], layer_past[1]
|
256 |
+
key_layer = torch.cat((past_key, key_layer), dim=0)
|
257 |
+
value_layer = torch.cat((past_value, value_layer), dim=0)
|
258 |
+
|
259 |
+
# seqlen, batch, num_attention_heads, hidden_size_per_attention_head
|
260 |
+
seq_len, b, nh, hidden_size = key_layer.shape
|
261 |
+
|
262 |
+
if use_cache:
|
263 |
+
present = (key_layer, value_layer)
|
264 |
+
else:
|
265 |
+
present = None
|
266 |
+
|
267 |
+
query_key_layer_scaling_coeff = float(layer_id + 1)
|
268 |
+
if scaling_attention_score:
|
269 |
+
query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
|
270 |
+
|
271 |
+
# ===================================
|
272 |
+
# Raw attention scores. [b, np, s, s]
|
273 |
+
# ===================================
|
274 |
+
|
275 |
+
# [b, np, sq, sk]
|
276 |
+
output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
|
277 |
+
|
278 |
+
# [sq, b, np, hn] -> [sq, b * np, hn]
|
279 |
+
query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
|
280 |
+
# [sk, b, np, hn] -> [sk, b * np, hn]
|
281 |
+
key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
|
282 |
+
|
283 |
+
matmul_result = torch.zeros(
|
284 |
+
1, 1, 1,
|
285 |
+
dtype=query_layer.dtype,
|
286 |
+
device=query_layer.device,
|
287 |
+
)
|
288 |
+
|
289 |
+
matmul_result = torch.baddbmm(
|
290 |
+
matmul_result,
|
291 |
+
query_layer.transpose(0, 1), # [b * np, sq, hn]
|
292 |
+
key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
|
293 |
+
beta=0.0,
|
294 |
+
alpha=1.0,
|
295 |
+
)
|
296 |
+
|
297 |
+
# change view to [b, np, sq, sk]
|
298 |
+
attention_scores = matmul_result.view(*output_size)
|
299 |
+
|
300 |
+
if self.scale_mask_softmax:
|
301 |
+
self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
|
302 |
+
attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
|
303 |
+
else:
|
304 |
+
if not (attention_mask == 0).all():
|
305 |
+
# if auto-regressive, skip
|
306 |
+
attention_scores.masked_fill_(attention_mask, -10000.0)
|
307 |
+
dtype = attention_scores.dtype
|
308 |
+
attention_scores = attention_scores.float()
|
309 |
+
attention_scores = attention_scores * query_key_layer_scaling_coeff
|
310 |
+
|
311 |
+
attention_probs = F.softmax(attention_scores, dim=-1)
|
312 |
+
|
313 |
+
attention_probs = attention_probs.type(dtype)
|
314 |
+
|
315 |
+
# =========================
|
316 |
+
# Context layer. [sq, b, hp]
|
317 |
+
# =========================
|
318 |
+
|
319 |
+
# value_layer -> context layer.
|
320 |
+
# [sk, b, np, hn] --> [b, np, sq, hn]
|
321 |
+
|
322 |
+
# context layer shape: [b, np, sq, hn]
|
323 |
+
output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
|
324 |
+
|
325 |
+
# change view [sk, b * np, hn]
|
326 |
+
value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
|
327 |
+
|
328 |
+
# change view [b * np, sq, sk]
|
329 |
+
attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
|
330 |
+
|
331 |
+
# matmul: [b * np, sq, hn]
|
332 |
+
context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
|
333 |
+
|
334 |
+
# change view [b, np, sq, hn]
|
335 |
+
context_layer = context_layer.view(*output_size)
|
336 |
+
|
337 |
+
# [b, np, sq, hn] --> [sq, b, np, hn]
|
338 |
+
context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
|
339 |
+
|
340 |
+
# [sq, b, np, hn] --> [sq, b, hp]
|
341 |
+
new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
|
342 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
343 |
+
|
344 |
+
outputs = (context_layer, present, attention_probs)
|
345 |
+
|
346 |
+
return outputs
|
347 |
+
|
348 |
+
|
349 |
+
def default_init(cls, *args, **kwargs):
|
350 |
+
return cls(*args, **kwargs)
|
351 |
+
|
352 |
+
|
353 |
+
class SelfAttention(torch.nn.Module):
|
354 |
+
def __init__(self, hidden_size, num_attention_heads,
|
355 |
+
layer_id, hidden_size_per_attention_head=None, bias=True,
|
356 |
+
params_dtype=torch.float, position_encoding_2d=True, empty_init=True):
|
357 |
+
if empty_init:
|
358 |
+
init_method = skip_init
|
359 |
+
else:
|
360 |
+
init_method = default_init
|
361 |
+
super(SelfAttention, self).__init__()
|
362 |
+
|
363 |
+
self.layer_id = layer_id
|
364 |
+
self.hidden_size = hidden_size
|
365 |
+
self.hidden_size_per_partition = hidden_size
|
366 |
+
self.num_attention_heads = num_attention_heads
|
367 |
+
self.num_attention_heads_per_partition = num_attention_heads
|
368 |
+
self.position_encoding_2d = position_encoding_2d
|
369 |
+
self.rotary_emb = RotaryEmbedding(
|
370 |
+
self.hidden_size // (self.num_attention_heads * 2)
|
371 |
+
if position_encoding_2d
|
372 |
+
else self.hidden_size // self.num_attention_heads,
|
373 |
+
base=10000,
|
374 |
+
precision=torch.half,
|
375 |
+
learnable=False,
|
376 |
+
)
|
377 |
+
|
378 |
+
self.scale_mask_softmax = None
|
379 |
+
|
380 |
+
if hidden_size_per_attention_head is None:
|
381 |
+
self.hidden_size_per_attention_head = hidden_size // num_attention_heads
|
382 |
+
else:
|
383 |
+
self.hidden_size_per_attention_head = hidden_size_per_attention_head
|
384 |
+
|
385 |
+
self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
|
386 |
+
|
387 |
+
# Strided linear layer.
|
388 |
+
self.query_key_value = init_method(
|
389 |
+
torch.nn.Linear,
|
390 |
+
hidden_size,
|
391 |
+
3 * self.inner_hidden_size,
|
392 |
+
bias=bias,
|
393 |
+
dtype=params_dtype,
|
394 |
+
)
|
395 |
+
|
396 |
+
self.dense = init_method(
|
397 |
+
torch.nn.Linear,
|
398 |
+
self.inner_hidden_size,
|
399 |
+
hidden_size,
|
400 |
+
bias=bias,
|
401 |
+
dtype=params_dtype,
|
402 |
+
)
|
403 |
+
|
404 |
+
@staticmethod
|
405 |
+
def attention_mask_func(attention_scores, attention_mask):
|
406 |
+
attention_scores.masked_fill_(attention_mask, -10000.0)
|
407 |
+
return attention_scores
|
408 |
+
|
409 |
+
def split_tensor_along_last_dim(self, tensor, num_partitions,
|
410 |
+
contiguous_split_chunks=False):
|
411 |
+
"""Split a tensor along its last dimension.
|
412 |
+
Arguments:
|
413 |
+
tensor: input tensor.
|
414 |
+
num_partitions: number of partitions to split the tensor
|
415 |
+
contiguous_split_chunks: If True, make each chunk contiguous
|
416 |
+
in memory.
|
417 |
+
"""
|
418 |
+
# Get the size and dimension.
|
419 |
+
last_dim = tensor.dim() - 1
|
420 |
+
last_dim_size = tensor.size()[last_dim] // num_partitions
|
421 |
+
# Split.
|
422 |
+
tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
|
423 |
+
# Note: torch.split does not create contiguous tensors by default.
|
424 |
+
if contiguous_split_chunks:
|
425 |
+
return tuple(chunk.contiguous() for chunk in tensor_list)
|
426 |
+
|
427 |
+
return tensor_list
|
428 |
+
|
429 |
+
def forward(
|
430 |
+
self,
|
431 |
+
hidden_states: torch.Tensor,
|
432 |
+
position_ids,
|
433 |
+
attention_mask: torch.Tensor,
|
434 |
+
layer_id,
|
435 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
436 |
+
use_cache: bool = False,
|
437 |
+
output_attentions: bool = False,
|
438 |
+
):
|
439 |
+
"""
|
440 |
+
hidden_states: [seq_len, batch, hidden_size]
|
441 |
+
attention_mask: [(1, 1), seq_len, seq_len]
|
442 |
+
"""
|
443 |
+
|
444 |
+
# [seq_len, batch, 3 * hidden_size]
|
445 |
+
mixed_raw_layer = self.query_key_value(hidden_states)
|
446 |
+
|
447 |
+
# [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
|
448 |
+
new_tensor_shape = mixed_raw_layer.size()[:-1] + (
|
449 |
+
self.num_attention_heads_per_partition,
|
450 |
+
3 * self.hidden_size_per_attention_head,
|
451 |
+
)
|
452 |
+
mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
|
453 |
+
|
454 |
+
# [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
|
455 |
+
(query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
|
456 |
+
|
457 |
+
if self.position_encoding_2d:
|
458 |
+
q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
|
459 |
+
k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
|
460 |
+
cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
|
461 |
+
position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
|
462 |
+
position_ids[:, 1, :].transpose(0, 1).contiguous()
|
463 |
+
q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
|
464 |
+
q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
|
465 |
+
query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
|
466 |
+
key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
|
467 |
+
else:
|
468 |
+
position_ids = position_ids.transpose(0, 1)
|
469 |
+
cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
|
470 |
+
# [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
|
471 |
+
query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
|
472 |
+
|
473 |
+
# [seq_len, batch, hidden_size]
|
474 |
+
context_layer, present, attention_probs = attention_fn(
|
475 |
+
self=self,
|
476 |
+
query_layer=query_layer,
|
477 |
+
key_layer=key_layer,
|
478 |
+
value_layer=value_layer,
|
479 |
+
attention_mask=attention_mask,
|
480 |
+
hidden_size_per_partition=self.hidden_size_per_partition,
|
481 |
+
layer_id=layer_id,
|
482 |
+
layer_past=layer_past,
|
483 |
+
use_cache=use_cache
|
484 |
+
)
|
485 |
+
|
486 |
+
output = self.dense(context_layer)
|
487 |
+
|
488 |
+
outputs = (output, present)
|
489 |
+
|
490 |
+
if output_attentions:
|
491 |
+
outputs += (attention_probs,)
|
492 |
+
|
493 |
+
return outputs # output, present, attention_probs
|
494 |
+
|
495 |
+
|
496 |
+
class GEGLU(torch.nn.Module):
|
497 |
+
def __init__(self):
|
498 |
+
super().__init__()
|
499 |
+
self.activation_fn = F.gelu
|
500 |
+
|
501 |
+
def forward(self, x):
|
502 |
+
# dim=-1 breaks in jit for pt<1.10
|
503 |
+
x1, x2 = x.chunk(2, dim=(x.ndim - 1))
|
504 |
+
return x1 * self.activation_fn(x2)
|
505 |
+
|
506 |
+
|
507 |
+
class GLU(torch.nn.Module):
|
508 |
+
def __init__(self, hidden_size, inner_hidden_size=None,
|
509 |
+
layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float, empty_init=True):
|
510 |
+
super(GLU, self).__init__()
|
511 |
+
if empty_init:
|
512 |
+
init_method = skip_init
|
513 |
+
else:
|
514 |
+
init_method = default_init
|
515 |
+
self.layer_id = layer_id
|
516 |
+
self.activation_func = activation_func
|
517 |
+
|
518 |
+
# Project to 4h.
|
519 |
+
self.hidden_size = hidden_size
|
520 |
+
if inner_hidden_size is None:
|
521 |
+
inner_hidden_size = 4 * hidden_size
|
522 |
+
self.inner_hidden_size = inner_hidden_size
|
523 |
+
self.dense_h_to_4h = init_method(
|
524 |
+
torch.nn.Linear,
|
525 |
+
self.hidden_size,
|
526 |
+
self.inner_hidden_size,
|
527 |
+
bias=bias,
|
528 |
+
dtype=params_dtype,
|
529 |
+
)
|
530 |
+
# Project back to h.
|
531 |
+
self.dense_4h_to_h = init_method(
|
532 |
+
torch.nn.Linear,
|
533 |
+
self.inner_hidden_size,
|
534 |
+
self.hidden_size,
|
535 |
+
bias=bias,
|
536 |
+
dtype=params_dtype,
|
537 |
+
)
|
538 |
+
|
539 |
+
def forward(self, hidden_states):
|
540 |
+
"""
|
541 |
+
hidden_states: [seq_len, batch, hidden_size]
|
542 |
+
"""
|
543 |
+
|
544 |
+
# [seq_len, batch, inner_hidden_size]
|
545 |
+
intermediate_parallel = self.dense_h_to_4h(hidden_states)
|
546 |
+
|
547 |
+
intermediate_parallel = self.activation_func(intermediate_parallel)
|
548 |
+
|
549 |
+
output = self.dense_4h_to_h(intermediate_parallel)
|
550 |
+
|
551 |
+
return output
|
552 |
+
|
553 |
+
|
554 |
+
class GLMBlock(torch.nn.Module):
|
555 |
+
def __init__(
|
556 |
+
self,
|
557 |
+
hidden_size,
|
558 |
+
num_attention_heads,
|
559 |
+
layernorm_epsilon,
|
560 |
+
layer_id,
|
561 |
+
inner_hidden_size=None,
|
562 |
+
hidden_size_per_attention_head=None,
|
563 |
+
layernorm=LayerNorm,
|
564 |
+
use_bias=True,
|
565 |
+
params_dtype=torch.float,
|
566 |
+
num_layers=28,
|
567 |
+
position_encoding_2d=True,
|
568 |
+
empty_init=True
|
569 |
+
):
|
570 |
+
super(GLMBlock, self).__init__()
|
571 |
+
# Set output layer initialization if not provided.
|
572 |
+
|
573 |
+
self.layer_id = layer_id
|
574 |
+
|
575 |
+
# Layernorm on the input data.
|
576 |
+
self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
|
577 |
+
|
578 |
+
self.position_encoding_2d = position_encoding_2d
|
579 |
+
|
580 |
+
# Self attention.
|
581 |
+
self.attention = SelfAttention(
|
582 |
+
hidden_size,
|
583 |
+
num_attention_heads,
|
584 |
+
layer_id,
|
585 |
+
hidden_size_per_attention_head=hidden_size_per_attention_head,
|
586 |
+
bias=use_bias,
|
587 |
+
params_dtype=params_dtype,
|
588 |
+
position_encoding_2d=self.position_encoding_2d,
|
589 |
+
empty_init=empty_init
|
590 |
+
)
|
591 |
+
|
592 |
+
# Layernorm on the input data.
|
593 |
+
self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
|
594 |
+
|
595 |
+
self.num_layers = num_layers
|
596 |
+
|
597 |
+
# GLU
|
598 |
+
self.mlp = GLU(
|
599 |
+
hidden_size,
|
600 |
+
inner_hidden_size=inner_hidden_size,
|
601 |
+
bias=use_bias,
|
602 |
+
layer_id=layer_id,
|
603 |
+
params_dtype=params_dtype,
|
604 |
+
empty_init=empty_init
|
605 |
+
)
|
606 |
+
|
607 |
+
def forward(
|
608 |
+
self,
|
609 |
+
hidden_states: torch.Tensor,
|
610 |
+
position_ids,
|
611 |
+
attention_mask: torch.Tensor,
|
612 |
+
layer_id,
|
613 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
614 |
+
use_cache: bool = False,
|
615 |
+
output_attentions: bool = False,
|
616 |
+
):
|
617 |
+
"""
|
618 |
+
hidden_states: [seq_len, batch, hidden_size]
|
619 |
+
attention_mask: [(1, 1), seq_len, seq_len]
|
620 |
+
"""
|
621 |
+
|
622 |
+
# Layer norm at the begining of the transformer layer.
|
623 |
+
# [seq_len, batch, hidden_size]
|
624 |
+
attention_input = self.input_layernorm(hidden_states)
|
625 |
+
|
626 |
+
# Self attention.
|
627 |
+
attention_outputs = self.attention(
|
628 |
+
attention_input,
|
629 |
+
position_ids,
|
630 |
+
attention_mask=attention_mask,
|
631 |
+
layer_id=layer_id,
|
632 |
+
layer_past=layer_past,
|
633 |
+
use_cache=use_cache,
|
634 |
+
output_attentions=output_attentions
|
635 |
+
)
|
636 |
+
|
637 |
+
attention_output = attention_outputs[0]
|
638 |
+
|
639 |
+
outputs = attention_outputs[1:]
|
640 |
+
|
641 |
+
# Residual connection.
|
642 |
+
alpha = (2 * self.num_layers) ** 0.5
|
643 |
+
hidden_states = attention_input * alpha + attention_output
|
644 |
+
|
645 |
+
mlp_input = self.post_attention_layernorm(hidden_states)
|
646 |
+
|
647 |
+
# MLP.
|
648 |
+
mlp_output = self.mlp(mlp_input)
|
649 |
+
|
650 |
+
# Second residual connection.
|
651 |
+
output = mlp_input * alpha + mlp_output
|
652 |
+
|
653 |
+
if use_cache:
|
654 |
+
outputs = (output,) + outputs
|
655 |
+
else:
|
656 |
+
outputs = (output,) + outputs[1:]
|
657 |
+
|
658 |
+
return outputs # hidden_states, present, attentions
|
659 |
+
|
660 |
+
|
661 |
+
class ChatGLMPreTrainedModel(PreTrainedModel):
|
662 |
+
"""
|
663 |
+
An abstract class to handle weights initialization and
|
664 |
+
a simple interface for downloading and loading pretrained models.
|
665 |
+
"""
|
666 |
+
|
667 |
+
is_parallelizable = False
|
668 |
+
supports_gradient_checkpointing = True
|
669 |
+
config_class = ChatGLMConfig
|
670 |
+
base_model_prefix = "transformer"
|
671 |
+
_no_split_modules = ["GLMBlock"]
|
672 |
+
|
673 |
+
def __init__(self, *inputs, **kwargs):
|
674 |
+
super().__init__(*inputs, **kwargs)
|
675 |
+
|
676 |
+
def _init_weights(self, module: nn.Module):
|
677 |
+
"""Initialize the weights."""
|
678 |
+
return
|
679 |
+
|
680 |
+
def get_masks(self, input_ids, device):
|
681 |
+
batch_size, seq_length = input_ids.shape
|
682 |
+
context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
|
683 |
+
attention_mask = torch.ones((batch_size, seq_length, seq_length), device=device)
|
684 |
+
attention_mask.tril_()
|
685 |
+
for i, context_length in enumerate(context_lengths):
|
686 |
+
attention_mask[i, :, :context_length] = 1
|
687 |
+
attention_mask.unsqueeze_(1)
|
688 |
+
attention_mask = (attention_mask < 0.5).bool()
|
689 |
+
|
690 |
+
return attention_mask
|
691 |
+
|
692 |
+
def get_position_ids(self, input_ids, mask_positions, device, use_gmasks=None):
|
693 |
+
batch_size, seq_length = input_ids.shape
|
694 |
+
if use_gmasks is None:
|
695 |
+
use_gmasks = [False] * batch_size
|
696 |
+
context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
|
697 |
+
if self.position_encoding_2d:
|
698 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
|
699 |
+
for i, context_length in enumerate(context_lengths):
|
700 |
+
position_ids[i, context_length:] = mask_positions[i]
|
701 |
+
block_position_ids = [torch.cat((
|
702 |
+
torch.zeros(context_length, dtype=torch.long, device=device),
|
703 |
+
torch.arange(seq_length - context_length, dtype=torch.long, device=device) + 1
|
704 |
+
)) for context_length in context_lengths]
|
705 |
+
block_position_ids = torch.stack(block_position_ids, dim=0)
|
706 |
+
position_ids = torch.stack((position_ids, block_position_ids), dim=1)
|
707 |
+
else:
|
708 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
|
709 |
+
for i, context_length in enumerate(context_lengths):
|
710 |
+
if not use_gmasks[i]:
|
711 |
+
position_ids[context_length:] = mask_positions[i]
|
712 |
+
|
713 |
+
return position_ids
|
714 |
+
|
715 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
716 |
+
if isinstance(module, ChatGLMModel):
|
717 |
+
module.gradient_checkpointing = value
|
718 |
+
|
719 |
+
|
720 |
+
CHATGLM_6B_START_DOCSTRING = r"""
|
721 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
|
722 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
|
723 |
+
usage and behavior.
|
724 |
+
|
725 |
+
Parameters:
|
726 |
+
config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
|
727 |
+
Initializing with a config file does not load the weights associated with the model, only the configuration.
|
728 |
+
Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
729 |
+
"""
|
730 |
+
|
731 |
+
CHATGLM_6B_INPUTS_DOCSTRING = r"""
|
732 |
+
Args:
|
733 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
734 |
+
Indices of input sequence tokens in the vocabulary.
|
735 |
+
|
736 |
+
Indices can be obtained using [`ChatGLM6BTokenizer`].
|
737 |
+
See [`PreTrainedTokenizer.encode`] and
|
738 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
739 |
+
|
740 |
+
[What are input IDs?](../glossary#input-ids)
|
741 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
742 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
743 |
+
|
744 |
+
- 1 for tokens that are **not masked**,
|
745 |
+
- 0 for tokens that are **masked**.
|
746 |
+
|
747 |
+
[What are attention masks?](../glossary#attention-mask)
|
748 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
749 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
|
750 |
+
|
751 |
+
- 0 corresponds to a *sentence A* token,
|
752 |
+
- 1 corresponds to a *sentence B* token.
|
753 |
+
|
754 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
755 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
756 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
757 |
+
Selected in the range `[0, config.max_position_embeddings - 1]`.
|
758 |
+
|
759 |
+
[What are position IDs?](../glossary#position-ids)
|
760 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
761 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
762 |
+
|
763 |
+
- 1 indicates the head is **not masked**,
|
764 |
+
- 0 indicates the head is **masked**.
|
765 |
+
|
766 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
767 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
768 |
+
This is useful if you want more control over how to convert *input_ids* indices into associated vectors
|
769 |
+
than the model's internal embedding lookup matrix.
|
770 |
+
output_attentions (`bool`, *optional*):
|
771 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
772 |
+
tensors for more detail.
|
773 |
+
output_hidden_states (`bool`, *optional*):
|
774 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
775 |
+
more detail.
|
776 |
+
return_dict (`bool`, *optional*):
|
777 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
778 |
+
"""
|
779 |
+
|
780 |
+
|
781 |
+
@add_start_docstrings(
|
782 |
+
"The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
|
783 |
+
CHATGLM_6B_START_DOCSTRING,
|
784 |
+
)
|
785 |
+
class ChatGLMModel(ChatGLMPreTrainedModel):
|
786 |
+
"""
|
787 |
+
|
788 |
+
The model can behave as an encoder (with only self-attention) as well
|
789 |
+
as a decoder, in which case a layer of cross-attention is added between
|
790 |
+
the self-attention layers, following the architecture described in [Attention is
|
791 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
|
792 |
+
Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
793 |
+
|
794 |
+
To behave as an decoder the model needs to be initialized with the
|
795 |
+
`is_decoder` argument of the configuration set to `True`.
|
796 |
+
To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
|
797 |
+
argument and `add_cross_attention` set to `True`; an
|
798 |
+
`encoder_hidden_states` is then expected as an input to the forward pass.
|
799 |
+
"""
|
800 |
+
|
801 |
+
def __init__(self, config: ChatGLMConfig, empty_init=True):
|
802 |
+
super().__init__(config)
|
803 |
+
if empty_init:
|
804 |
+
init_method = skip_init
|
805 |
+
else:
|
806 |
+
init_method = default_init
|
807 |
+
# recording parameters
|
808 |
+
self.max_sequence_length = config.max_sequence_length
|
809 |
+
self.hidden_size = config.hidden_size
|
810 |
+
self.params_dtype = torch.half
|
811 |
+
self.num_attention_heads = config.num_attention_heads
|
812 |
+
self.vocab_size = config.vocab_size
|
813 |
+
self.num_layers = config.num_layers
|
814 |
+
self.layernorm_epsilon = config.layernorm_epsilon
|
815 |
+
self.inner_hidden_size = config.inner_hidden_size
|
816 |
+
self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
|
817 |
+
self.position_encoding_2d = config.position_encoding_2d
|
818 |
+
self.pre_seq_len = config.pre_seq_len
|
819 |
+
self.prefix_projection = config.prefix_projection
|
820 |
+
|
821 |
+
self.word_embeddings = init_method(
|
822 |
+
torch.nn.Embedding,
|
823 |
+
num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
|
824 |
+
dtype=self.params_dtype
|
825 |
+
)
|
826 |
+
self.gradient_checkpointing = False
|
827 |
+
|
828 |
+
def get_layer(layer_id):
|
829 |
+
return GLMBlock(
|
830 |
+
self.hidden_size,
|
831 |
+
self.num_attention_heads,
|
832 |
+
self.layernorm_epsilon,
|
833 |
+
layer_id,
|
834 |
+
inner_hidden_size=self.inner_hidden_size,
|
835 |
+
hidden_size_per_attention_head=self.hidden_size_per_attention_head,
|
836 |
+
layernorm=LayerNorm,
|
837 |
+
use_bias=True,
|
838 |
+
params_dtype=self.params_dtype,
|
839 |
+
position_encoding_2d=self.position_encoding_2d,
|
840 |
+
empty_init=empty_init
|
841 |
+
)
|
842 |
+
|
843 |
+
self.layers = torch.nn.ModuleList(
|
844 |
+
[get_layer(layer_id) for layer_id in range(self.num_layers)]
|
845 |
+
)
|
846 |
+
|
847 |
+
# Final layer norm before output.
|
848 |
+
self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
|
849 |
+
|
850 |
+
if self.pre_seq_len is not None:
|
851 |
+
for param in self.parameters():
|
852 |
+
param.requires_grad = False
|
853 |
+
self.prefix_tokens = torch.arange(self.pre_seq_len).long()
|
854 |
+
self.prefix_encoder = PrefixEncoder(config)
|
855 |
+
self.dropout = torch.nn.Dropout(0.1)
|
856 |
+
|
857 |
+
# total_params = sum(p.numel() for p in self.parameters())
|
858 |
+
# trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
|
859 |
+
# print("Using p-tuning v2: # trainable_params = {} / {}".format(trainable_params, total_params))
|
860 |
+
|
861 |
+
def get_input_embeddings(self):
|
862 |
+
return self.word_embeddings
|
863 |
+
|
864 |
+
def set_input_embeddings(self, new_embeddings: torch.Tensor):
|
865 |
+
self.word_embeddings = new_embeddings
|
866 |
+
|
867 |
+
def get_prompt(self, batch_size, device, dtype=torch.half):
|
868 |
+
prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
|
869 |
+
past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
|
870 |
+
past_key_values = past_key_values.view(
|
871 |
+
batch_size,
|
872 |
+
self.pre_seq_len,
|
873 |
+
self.num_layers * 2,
|
874 |
+
self.num_attention_heads,
|
875 |
+
self.hidden_size // self.num_attention_heads
|
876 |
+
)
|
877 |
+
# seq_len, b, nh, hidden_size
|
878 |
+
past_key_values = self.dropout(past_key_values)
|
879 |
+
past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
|
880 |
+
# past_key_values = [(v[0], v[1]) for v in past_key_values]
|
881 |
+
return past_key_values
|
882 |
+
|
883 |
+
@add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
884 |
+
@add_code_sample_docstrings(
|
885 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
886 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
887 |
+
config_class=_CONFIG_FOR_DOC,
|
888 |
+
)
|
889 |
+
def forward(
|
890 |
+
self,
|
891 |
+
input_ids: Optional[torch.LongTensor] = None,
|
892 |
+
position_ids: Optional[torch.LongTensor] = None,
|
893 |
+
attention_mask: Optional[torch.Tensor] = None,
|
894 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
895 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
896 |
+
use_cache: Optional[bool] = None,
|
897 |
+
output_attentions: Optional[bool] = None,
|
898 |
+
output_hidden_states: Optional[bool] = None,
|
899 |
+
return_dict: Optional[bool] = None,
|
900 |
+
) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
|
901 |
+
|
902 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
903 |
+
output_hidden_states = (
|
904 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
905 |
+
)
|
906 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
907 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
908 |
+
|
909 |
+
if self.gradient_checkpointing and self.training:
|
910 |
+
if use_cache:
|
911 |
+
logger.warning_once(
|
912 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
913 |
+
)
|
914 |
+
use_cache = False
|
915 |
+
|
916 |
+
if input_ids is not None and inputs_embeds is not None:
|
917 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
918 |
+
elif input_ids is not None:
|
919 |
+
batch_size, seq_length = input_ids.shape[:2]
|
920 |
+
elif inputs_embeds is not None:
|
921 |
+
batch_size, seq_length, _ = inputs_embeds.shape[:2]
|
922 |
+
else:
|
923 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
924 |
+
|
925 |
+
if inputs_embeds is None:
|
926 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
927 |
+
|
928 |
+
if past_key_values is None:
|
929 |
+
if self.pre_seq_len is not None:
|
930 |
+
past_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device,
|
931 |
+
dtype=inputs_embeds.dtype)
|
932 |
+
else:
|
933 |
+
past_key_values = tuple([None] * len(self.layers))
|
934 |
+
|
935 |
+
if attention_mask is None:
|
936 |
+
attention_mask = self.get_masks(
|
937 |
+
input_ids,
|
938 |
+
device=input_ids.device
|
939 |
+
)
|
940 |
+
|
941 |
+
|
942 |
+
if position_ids is None:
|
943 |
+
MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
|
944 |
+
seqs = input_ids.tolist()
|
945 |
+
|
946 |
+
mask_positions, use_gmasks = [], []
|
947 |
+
for seq in seqs:
|
948 |
+
mask_token = gMASK if gMASK in seq else MASK
|
949 |
+
use_gmask = mask_token == gMASK
|
950 |
+
mask_positions.append(seq.index(mask_token))
|
951 |
+
use_gmasks.append(use_gmask)
|
952 |
+
|
953 |
+
position_ids = self.get_position_ids(
|
954 |
+
input_ids,
|
955 |
+
mask_positions=mask_positions,
|
956 |
+
device=input_ids.device,
|
957 |
+
use_gmasks=use_gmasks
|
958 |
+
)
|
959 |
+
|
960 |
+
if self.pre_seq_len is not None and attention_mask is not None:
|
961 |
+
prefix_attention_mask = torch.ones(batch_size, 1, input_ids.size(-1), self.pre_seq_len).to(
|
962 |
+
attention_mask.device)
|
963 |
+
prefix_attention_mask = (prefix_attention_mask < 0.5).bool()
|
964 |
+
attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=3)
|
965 |
+
|
966 |
+
# [seq_len, batch, hidden_size]
|
967 |
+
hidden_states = inputs_embeds.transpose(0, 1)
|
968 |
+
|
969 |
+
presents = () if use_cache else None
|
970 |
+
all_self_attentions = () if output_attentions else None
|
971 |
+
all_hidden_states = () if output_hidden_states else None
|
972 |
+
|
973 |
+
if attention_mask is None:
|
974 |
+
attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
|
975 |
+
|
976 |
+
else:
|
977 |
+
attention_mask = attention_mask.to(input_ids.device)
|
978 |
+
|
979 |
+
for i, layer in enumerate(self.layers):
|
980 |
+
|
981 |
+
if output_hidden_states:
|
982 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
983 |
+
layer_past = past_key_values[i]
|
984 |
+
|
985 |
+
if self.gradient_checkpointing and self.training:
|
986 |
+
layer_ret = torch.utils.checkpoint.checkpoint(
|
987 |
+
layer,
|
988 |
+
hidden_states,
|
989 |
+
position_ids,
|
990 |
+
attention_mask,
|
991 |
+
torch.tensor(i),
|
992 |
+
layer_past,
|
993 |
+
use_cache,
|
994 |
+
output_attentions
|
995 |
+
)
|
996 |
+
else:
|
997 |
+
layer_ret = layer(
|
998 |
+
hidden_states,
|
999 |
+
position_ids=position_ids,
|
1000 |
+
attention_mask=attention_mask,
|
1001 |
+
layer_id=torch.tensor(i),
|
1002 |
+
layer_past=layer_past,
|
1003 |
+
use_cache=use_cache,
|
1004 |
+
output_attentions=output_attentions
|
1005 |
+
)
|
1006 |
+
|
1007 |
+
hidden_states = layer_ret[0]
|
1008 |
+
|
1009 |
+
if use_cache:
|
1010 |
+
presents = presents + (layer_ret[1],)
|
1011 |
+
|
1012 |
+
if output_attentions:
|
1013 |
+
all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
|
1014 |
+
|
1015 |
+
# Final layer norm.
|
1016 |
+
hidden_states = self.final_layernorm(hidden_states)
|
1017 |
+
|
1018 |
+
if output_hidden_states:
|
1019 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1020 |
+
|
1021 |
+
if not return_dict:
|
1022 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
1023 |
+
|
1024 |
+
return BaseModelOutputWithPast(
|
1025 |
+
last_hidden_state=hidden_states,
|
1026 |
+
past_key_values=presents,
|
1027 |
+
hidden_states=all_hidden_states,
|
1028 |
+
attentions=all_self_attentions,
|
1029 |
+
)
|
1030 |
+
|
1031 |
+
|
1032 |
+
class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
1033 |
+
def __init__(self, config: ChatGLMConfig, empty_init=True):
|
1034 |
+
super().__init__(config)
|
1035 |
+
if empty_init:
|
1036 |
+
init_method = skip_init
|
1037 |
+
else:
|
1038 |
+
init_method = default_init
|
1039 |
+
|
1040 |
+
# self.hidden_size = config.hidden_size
|
1041 |
+
# self.params_dtype = torch.half
|
1042 |
+
# self.vocab_size = config.vocab_size
|
1043 |
+
self.max_sequence_length = config.max_sequence_length
|
1044 |
+
|
1045 |
+
self.position_encoding_2d = config.position_encoding_2d
|
1046 |
+
|
1047 |
+
self.transformer = ChatGLMModel(config, empty_init=empty_init)
|
1048 |
+
|
1049 |
+
self.lm_head = init_method(
|
1050 |
+
nn.Linear,
|
1051 |
+
config.hidden_size,
|
1052 |
+
config.vocab_size,
|
1053 |
+
bias=False,
|
1054 |
+
dtype=torch.half
|
1055 |
+
)
|
1056 |
+
|
1057 |
+
self.config = config
|
1058 |
+
|
1059 |
+
self.quantized = False
|
1060 |
+
|
1061 |
+
if self.config.quantization_bit:
|
1062 |
+
self.quantize(self.config.quantization_bit, self.config.quantization_embeddings, use_quantization_cache=True, empty_init=True)
|
1063 |
+
|
1064 |
+
def get_output_embeddings(self):
|
1065 |
+
return self.lm_head
|
1066 |
+
|
1067 |
+
def set_output_embeddings(self, new_embeddings):
|
1068 |
+
self.lm_head = new_embeddings
|
1069 |
+
|
1070 |
+
def _update_model_kwargs_for_generation(
|
1071 |
+
self,
|
1072 |
+
outputs: ModelOutput,
|
1073 |
+
model_kwargs: Dict[str, Any],
|
1074 |
+
is_encoder_decoder: bool = False,
|
1075 |
+
standardize_cache_format: bool = False,
|
1076 |
+
) -> Dict[str, Any]:
|
1077 |
+
# update past_key_values
|
1078 |
+
model_kwargs["past_key_values"] = self._extract_past_from_model_output(
|
1079 |
+
outputs, standardize_cache_format=standardize_cache_format
|
1080 |
+
)
|
1081 |
+
|
1082 |
+
# update attention mask
|
1083 |
+
if "attention_mask" in model_kwargs:
|
1084 |
+
attention_mask = model_kwargs["attention_mask"]
|
1085 |
+
if attention_mask is not None and attention_mask.dtype == torch.bool:
|
1086 |
+
attention_mask = torch.cat(
|
1087 |
+
[attention_mask, attention_mask.new_ones((*attention_mask.shape[:3], 1))], dim=3)
|
1088 |
+
new_attention_mask = attention_mask[:, :, -1:].clone()
|
1089 |
+
new_attention_mask[..., -1] = False
|
1090 |
+
model_kwargs["attention_mask"] = torch.cat(
|
1091 |
+
[attention_mask, new_attention_mask], dim=2
|
1092 |
+
)
|
1093 |
+
|
1094 |
+
# update position ids
|
1095 |
+
if "position_ids" in model_kwargs:
|
1096 |
+
position_ids = model_kwargs["position_ids"]
|
1097 |
+
new_position_id = position_ids[..., -1:].clone()
|
1098 |
+
new_position_id[:, 1, :] += 1
|
1099 |
+
model_kwargs["position_ids"] = torch.cat(
|
1100 |
+
[position_ids, new_position_id], dim=-1
|
1101 |
+
)
|
1102 |
+
|
1103 |
+
return model_kwargs
|
1104 |
+
|
1105 |
+
def prepare_inputs_for_generation(
|
1106 |
+
self,
|
1107 |
+
input_ids: torch.LongTensor,
|
1108 |
+
past: Optional[torch.Tensor] = None,
|
1109 |
+
past_key_values: Optional[torch.Tensor] = None,
|
1110 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1111 |
+
position_ids: Optional[torch.Tensor] = None,
|
1112 |
+
**kwargs
|
1113 |
+
) -> dict:
|
1114 |
+
batch_size, seq_length = input_ids.shape
|
1115 |
+
MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
|
1116 |
+
seqs = input_ids.tolist()
|
1117 |
+
mask_positions, use_gmasks = [], []
|
1118 |
+
for seq in seqs:
|
1119 |
+
mask_token = gMASK if gMASK in seq else MASK
|
1120 |
+
use_gmask = mask_token == gMASK
|
1121 |
+
mask_positions.append(seq.index(mask_token))
|
1122 |
+
use_gmasks.append(use_gmask)
|
1123 |
+
|
1124 |
+
# only last token for input_ids if past is not None
|
1125 |
+
if past is not None or past_key_values is not None:
|
1126 |
+
last_token = input_ids[:, -1].unsqueeze(-1)
|
1127 |
+
if attention_mask is not None and attention_mask.dtype == torch.bool:
|
1128 |
+
attention_mask = attention_mask[:, :, -1:]
|
1129 |
+
else:
|
1130 |
+
attention_mask = None
|
1131 |
+
if position_ids is not None:
|
1132 |
+
position_ids = position_ids[..., -1:]
|
1133 |
+
else:
|
1134 |
+
context_lengths = [seq.index(self.config.bos_token_id) for seq in seqs]
|
1135 |
+
if self.position_encoding_2d:
|
1136 |
+
position_ids = torch.tensor(
|
1137 |
+
[[mask_position, seq_length - context_length] for mask_position, context_length in
|
1138 |
+
zip(mask_positions, context_lengths)], dtype=torch.long, device=input_ids.device).unsqueeze(-1)
|
1139 |
+
else:
|
1140 |
+
position_ids = torch.tensor([mask_position for mask_position in mask_positions], dtype=torch.long,
|
1141 |
+
device=input_ids.device).unsqueeze(-1)
|
1142 |
+
|
1143 |
+
if past is None:
|
1144 |
+
past = past_key_values
|
1145 |
+
return {
|
1146 |
+
"input_ids": last_token,
|
1147 |
+
"past_key_values": past,
|
1148 |
+
"position_ids": position_ids,
|
1149 |
+
"attention_mask": attention_mask
|
1150 |
+
}
|
1151 |
+
else:
|
1152 |
+
if attention_mask is not None and attention_mask.dtype != torch.bool:
|
1153 |
+
logger.warning_once(f"The dtype of attention mask ({attention_mask.dtype}) is not bool")
|
1154 |
+
attention_mask = None
|
1155 |
+
if attention_mask is None:
|
1156 |
+
attention_mask = self.get_masks(
|
1157 |
+
input_ids,
|
1158 |
+
device=input_ids.device
|
1159 |
+
)
|
1160 |
+
if position_ids is None:
|
1161 |
+
position_ids = self.get_position_ids(
|
1162 |
+
input_ids,
|
1163 |
+
device=input_ids.device,
|
1164 |
+
mask_positions=mask_positions,
|
1165 |
+
use_gmasks=use_gmasks
|
1166 |
+
)
|
1167 |
+
|
1168 |
+
return {
|
1169 |
+
"input_ids": input_ids,
|
1170 |
+
"past_key_values": past,
|
1171 |
+
"position_ids": position_ids,
|
1172 |
+
"attention_mask": attention_mask
|
1173 |
+
}
|
1174 |
+
|
1175 |
+
def forward(
|
1176 |
+
self,
|
1177 |
+
input_ids: Optional[torch.Tensor] = None,
|
1178 |
+
position_ids: Optional[torch.Tensor] = None,
|
1179 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1180 |
+
past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
|
1181 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1182 |
+
labels: Optional[torch.Tensor] = None,
|
1183 |
+
use_cache: Optional[bool] = None,
|
1184 |
+
output_attentions: Optional[bool] = None,
|
1185 |
+
output_hidden_states: Optional[bool] = None,
|
1186 |
+
return_dict: Optional[bool] = None,
|
1187 |
+
):
|
1188 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1189 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1190 |
+
|
1191 |
+
transformer_outputs = self.transformer(
|
1192 |
+
input_ids=input_ids,
|
1193 |
+
position_ids=position_ids,
|
1194 |
+
attention_mask=attention_mask,
|
1195 |
+
past_key_values=past_key_values,
|
1196 |
+
inputs_embeds=inputs_embeds,
|
1197 |
+
use_cache=use_cache,
|
1198 |
+
output_attentions=output_attentions,
|
1199 |
+
output_hidden_states=output_hidden_states,
|
1200 |
+
return_dict=return_dict,
|
1201 |
+
)
|
1202 |
+
|
1203 |
+
hidden_states = transformer_outputs[0]
|
1204 |
+
|
1205 |
+
lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
|
1206 |
+
|
1207 |
+
loss = None
|
1208 |
+
if labels is not None:
|
1209 |
+
lm_logits = lm_logits.to(torch.float32)
|
1210 |
+
|
1211 |
+
# Shift so that tokens < n predict n
|
1212 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1213 |
+
shift_labels = labels[..., 1:].contiguous()
|
1214 |
+
# Flatten the tokens
|
1215 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
1216 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
1217 |
+
|
1218 |
+
lm_logits = lm_logits.to(hidden_states.dtype)
|
1219 |
+
loss = loss.to(hidden_states.dtype)
|
1220 |
+
|
1221 |
+
if not return_dict:
|
1222 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
1223 |
+
return ((loss,) + output) if loss is not None else output
|
1224 |
+
|
1225 |
+
return CausalLMOutputWithPast(
|
1226 |
+
loss=loss,
|
1227 |
+
logits=lm_logits,
|
1228 |
+
past_key_values=transformer_outputs.past_key_values,
|
1229 |
+
hidden_states=transformer_outputs.hidden_states,
|
1230 |
+
attentions=transformer_outputs.attentions,
|
1231 |
+
)
|
1232 |
+
|
1233 |
+
@staticmethod
|
1234 |
+
def _reorder_cache(
|
1235 |
+
past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
|
1236 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
|
1237 |
+
"""
|
1238 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
1239 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
1240 |
+
beam_idx at every generation step.
|
1241 |
+
|
1242 |
+
Output shares the same memory storage as `past`.
|
1243 |
+
"""
|
1244 |
+
return tuple(
|
1245 |
+
(
|
1246 |
+
layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
|
1247 |
+
layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
|
1248 |
+
)
|
1249 |
+
for layer_past in past
|
1250 |
+
)
|
1251 |
+
|
1252 |
+
def process_response(self, response):
|
1253 |
+
response = response.strip()
|
1254 |
+
response = response.replace("[[训练时间]]", "2023年")
|
1255 |
+
punkts = [
|
1256 |
+
[",", ","],
|
1257 |
+
["!", "!"],
|
1258 |
+
[":", ":"],
|
1259 |
+
[";", ";"],
|
1260 |
+
["\?", "?"],
|
1261 |
+
]
|
1262 |
+
for item in punkts:
|
1263 |
+
response = re.sub(r"([\u4e00-\u9fff])%s" % item[0], r"\1%s" % item[1], response)
|
1264 |
+
response = re.sub(r"%s([\u4e00-\u9fff])" % item[0], r"%s\1" % item[1], response)
|
1265 |
+
return response
|
1266 |
+
|
1267 |
+
@torch.no_grad()
|
1268 |
+
def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
|
1269 |
+
do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
|
1270 |
+
if history is None:
|
1271 |
+
history = []
|
1272 |
+
if logits_processor is None:
|
1273 |
+
logits_processor = LogitsProcessorList()
|
1274 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1275 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
|
1276 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1277 |
+
if not history:
|
1278 |
+
prompt = query
|
1279 |
+
else:
|
1280 |
+
prompt = ""
|
1281 |
+
for i, (old_query, response) in enumerate(history):
|
1282 |
+
prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
|
1283 |
+
prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
|
1284 |
+
inputs = tokenizer([prompt], return_tensors="pt")
|
1285 |
+
inputs = inputs.to(self.device)
|
1286 |
+
outputs = self.generate(**inputs, **gen_kwargs)
|
1287 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
|
1288 |
+
response = tokenizer.decode(outputs)
|
1289 |
+
response = self.process_response(response)
|
1290 |
+
history = history + [(query, response)]
|
1291 |
+
return response, history
|
1292 |
+
|
1293 |
+
@torch.no_grad()
|
1294 |
+
def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,
|
1295 |
+
do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
|
1296 |
+
if history is None:
|
1297 |
+
history = []
|
1298 |
+
if logits_processor is None:
|
1299 |
+
logits_processor = LogitsProcessorList()
|
1300 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1301 |
+
gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
|
1302 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1303 |
+
if not history:
|
1304 |
+
prompt = query
|
1305 |
+
else:
|
1306 |
+
prompt = ""
|
1307 |
+
for i, (old_query, response) in enumerate(history):
|
1308 |
+
prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
|
1309 |
+
prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
|
1310 |
+
inputs = tokenizer([prompt], return_tensors="pt")
|
1311 |
+
inputs = inputs.to(self.device)
|
1312 |
+
for outputs in self.stream_generate(**inputs, **gen_kwargs):
|
1313 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
|
1314 |
+
response = tokenizer.decode(outputs)
|
1315 |
+
response = self.process_response(response)
|
1316 |
+
new_history = history + [(query, response)]
|
1317 |
+
yield response, new_history
|
1318 |
+
|
1319 |
+
@torch.no_grad()
|
1320 |
+
def stream_generate(
|
1321 |
+
self,
|
1322 |
+
input_ids,
|
1323 |
+
generation_config: Optional[GenerationConfig] = None,
|
1324 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
1325 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
1326 |
+
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
|
1327 |
+
**kwargs,
|
1328 |
+
):
|
1329 |
+
batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
|
1330 |
+
|
1331 |
+
if generation_config is None:
|
1332 |
+
generation_config = self.generation_config
|
1333 |
+
generation_config = copy.deepcopy(generation_config)
|
1334 |
+
model_kwargs = generation_config.update(**kwargs)
|
1335 |
+
bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
|
1336 |
+
|
1337 |
+
if isinstance(eos_token_id, int):
|
1338 |
+
eos_token_id = [eos_token_id]
|
1339 |
+
|
1340 |
+
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
|
1341 |
+
if has_default_max_length and generation_config.max_new_tokens is None:
|
1342 |
+
warnings.warn(
|
1343 |
+
f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
|
1344 |
+
"This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
|
1345 |
+
" recommend using `max_new_tokens` to control the maximum length of the generation.",
|
1346 |
+
UserWarning,
|
1347 |
+
)
|
1348 |
+
elif generation_config.max_new_tokens is not None:
|
1349 |
+
generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
|
1350 |
+
if not has_default_max_length:
|
1351 |
+
logger.warn(
|
1352 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
1353 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
1354 |
+
"Please refer to the documentation for more information. "
|
1355 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
|
1356 |
+
UserWarning,
|
1357 |
+
)
|
1358 |
+
|
1359 |
+
if input_ids_seq_length >= generation_config.max_length:
|
1360 |
+
input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
|
1361 |
+
logger.warning(
|
1362 |
+
f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
|
1363 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
1364 |
+
" increasing `max_new_tokens`."
|
1365 |
+
)
|
1366 |
+
|
1367 |
+
# 2. Set generation parameters if not already defined
|
1368 |
+
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
1369 |
+
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
1370 |
+
|
1371 |
+
logits_processor = self._get_logits_processor(
|
1372 |
+
generation_config=generation_config,
|
1373 |
+
input_ids_seq_length=input_ids_seq_length,
|
1374 |
+
encoder_input_ids=input_ids,
|
1375 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
1376 |
+
logits_processor=logits_processor,
|
1377 |
+
)
|
1378 |
+
|
1379 |
+
stopping_criteria = self._get_stopping_criteria(
|
1380 |
+
generation_config=generation_config, stopping_criteria=stopping_criteria
|
1381 |
+
)
|
1382 |
+
logits_warper = self._get_logits_warper(generation_config)
|
1383 |
+
|
1384 |
+
unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
|
1385 |
+
scores = None
|
1386 |
+
while True:
|
1387 |
+
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
1388 |
+
# forward pass to get next token
|
1389 |
+
outputs = self(
|
1390 |
+
**model_inputs,
|
1391 |
+
return_dict=True,
|
1392 |
+
output_attentions=False,
|
1393 |
+
output_hidden_states=False,
|
1394 |
+
)
|
1395 |
+
|
1396 |
+
next_token_logits = outputs.logits[:, -1, :]
|
1397 |
+
|
1398 |
+
# pre-process distribution
|
1399 |
+
next_token_scores = logits_processor(input_ids, next_token_logits)
|
1400 |
+
next_token_scores = logits_warper(input_ids, next_token_scores)
|
1401 |
+
|
1402 |
+
# sample
|
1403 |
+
probs = nn.functional.softmax(next_token_scores, dim=-1)
|
1404 |
+
if generation_config.do_sample:
|
1405 |
+
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
1406 |
+
else:
|
1407 |
+
next_tokens = torch.argmax(probs, dim=-1)
|
1408 |
+
|
1409 |
+
# update generated ids, model inputs, and length for next step
|
1410 |
+
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
1411 |
+
model_kwargs = self._update_model_kwargs_for_generation(
|
1412 |
+
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
|
1413 |
+
)
|
1414 |
+
unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
|
1415 |
+
|
1416 |
+
# stop when each sentence is finished, or if we exceed the maximum length
|
1417 |
+
if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
|
1418 |
+
break
|
1419 |
+
yield input_ids
|
1420 |
+
|
1421 |
+
def quantize(self, bits: int, quantize_embeddings=False, use_quantization_cache=False, empty_init=False, **kwargs):
|
1422 |
+
if bits == 0:
|
1423 |
+
return
|
1424 |
+
|
1425 |
+
from .quantization import quantize, QuantizedEmbedding, QuantizedLinear, load_cpu_kernel
|
1426 |
+
|
1427 |
+
if self.quantized:
|
1428 |
+
if self.device == torch.device("cpu"):
|
1429 |
+
logger.info("Already quantized, reloading cpu kernel.")
|
1430 |
+
load_cpu_kernel(**kwargs)
|
1431 |
+
else:
|
1432 |
+
logger.info("Already quantized.")
|
1433 |
+
return self
|
1434 |
+
|
1435 |
+
self.quantized = True
|
1436 |
+
|
1437 |
+
self.config.quantization_bit = bits
|
1438 |
+
self.config.quantization_embeddings = quantize_embeddings
|
1439 |
+
|
1440 |
+
self.transformer = quantize(self.transformer, bits, use_quantization_cache=use_quantization_cache, empty_init=empty_init, **kwargs)
|
1441 |
+
|
1442 |
+
if self.device == torch.device("cpu"):
|
1443 |
+
dtype = torch.float32
|
1444 |
+
else:
|
1445 |
+
dtype = torch.half
|
1446 |
+
|
1447 |
+
if quantize_embeddings:
|
1448 |
+
logger.info("Applying quantization to embeddings")
|
1449 |
+
self.transformer.word_embeddings = QuantizedEmbedding(
|
1450 |
+
weight_bit_width=bits,
|
1451 |
+
weight_tensor=self.transformer.word_embeddings.weight.to(self.device),
|
1452 |
+
num_embeddings=self.transformer.word_embeddings.num_embeddings,
|
1453 |
+
embedding_dim=self.transformer.word_embeddings.embedding_dim,
|
1454 |
+
dtype=dtype,
|
1455 |
+
empty_init=empty_init,
|
1456 |
+
device=self.transformer.word_embeddings.weight.device,
|
1457 |
+
)
|
1458 |
+
self.lm_head = QuantizedLinear(
|
1459 |
+
weight_bit_width=bits,
|
1460 |
+
weight_tensor=self.lm_head.weight.to(self.device),
|
1461 |
+
bias_tensor=None,
|
1462 |
+
in_features=self.lm_head.in_features,
|
1463 |
+
out_features=self.lm_head.out_features,
|
1464 |
+
bias=False,
|
1465 |
+
quantized_weight=self.transformer.word_embeddings.weight,
|
1466 |
+
quantized_weight_scale=self.transformer.word_embeddings.weight_scale,
|
1467 |
+
dtype=dtype,
|
1468 |
+
empty_init=empty_init,
|
1469 |
+
device=self.lm_head.weight.device,
|
1470 |
+
)
|
1471 |
+
|
1472 |
+
return self
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/optimizer.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0c1bae103ea1bfc1bd47213378dc044d55554c61d5da8d3771230013f4300f11
|
3 |
+
size 234882351
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4f00304c7adb89a5779f15a408af0d674fd60b3c341455bb7ca8d1d88b519dbe
|
3 |
+
size 117441341
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/quantization.py
ADDED
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch.nn import Linear, Embedding
|
2 |
+
from torch.nn.parameter import Parameter
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
import os
|
6 |
+
import bz2
|
7 |
+
import torch
|
8 |
+
import base64
|
9 |
+
import ctypes
|
10 |
+
from transformers.utils import logging
|
11 |
+
|
12 |
+
from typing import List
|
13 |
+
from functools import partial
|
14 |
+
|
15 |
+
logger = logging.get_logger(__name__)
|
16 |
+
|
17 |
+
try:
|
18 |
+
from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
|
19 |
+
|
20 |
+
class Kernel:
|
21 |
+
def __init__(self, code: bytes, function_names: List[str]):
|
22 |
+
self.code = code
|
23 |
+
self._function_names = function_names
|
24 |
+
self._cmodule = LazyKernelCModule(self.code)
|
25 |
+
|
26 |
+
for name in self._function_names:
|
27 |
+
setattr(self, name, KernelFunction(self._cmodule, name))
|
28 |
+
|
29 |
+
quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoG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uvebBudScjZ79g8cWJ8av0k+/bE5WKd5MdbFpbDVMxu1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
|
30 |
+
|
31 |
+
kernels = Kernel(
|
32 |
+
bz2.decompress(base64.b64decode(quantization_code)),
|
33 |
+
[
|
34 |
+
"int4WeightCompression",
|
35 |
+
"int4WeightExtractionFloat",
|
36 |
+
"int4WeightExtractionHalf",
|
37 |
+
"int8WeightExtractionFloat",
|
38 |
+
"int8WeightExtractionHalf",
|
39 |
+
],
|
40 |
+
)
|
41 |
+
except Exception as exception:
|
42 |
+
kernels = None
|
43 |
+
logger.warning("Failed to load cpm_kernels:", exception)
|
44 |
+
|
45 |
+
|
46 |
+
class W8A16Linear(torch.autograd.Function):
|
47 |
+
@staticmethod
|
48 |
+
def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
|
49 |
+
ctx.inp_shape = inp.size()
|
50 |
+
ctx.weight_bit_width = weight_bit_width
|
51 |
+
out_features = quant_w.size(0)
|
52 |
+
inp = inp.contiguous().view(-1, inp.size(-1))
|
53 |
+
weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
|
54 |
+
ctx.weight_shape = weight.size()
|
55 |
+
output = inp.mm(weight.t())
|
56 |
+
ctx.save_for_backward(inp, quant_w, scale_w)
|
57 |
+
return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
|
58 |
+
|
59 |
+
@staticmethod
|
60 |
+
def backward(ctx, grad_output: torch.Tensor):
|
61 |
+
inp, quant_w, scale_w = ctx.saved_tensors
|
62 |
+
weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
|
63 |
+
grad_output = grad_output.contiguous().view(-1, weight.size(0))
|
64 |
+
grad_input = grad_output.mm(weight)
|
65 |
+
grad_weight = grad_output.t().mm(inp)
|
66 |
+
return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
|
67 |
+
|
68 |
+
|
69 |
+
class W8A16LinearCPU(torch.autograd.Function):
|
70 |
+
@staticmethod
|
71 |
+
def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width, quantization_cache=None):
|
72 |
+
ctx.inp_shape = inp.size()
|
73 |
+
ctx.weight_bit_width = weight_bit_width
|
74 |
+
out_features = quant_w.size(0)
|
75 |
+
inp = inp.contiguous().view(-1, inp.size(-1))
|
76 |
+
weight = extract_weight_to_float(quant_w, scale_w, weight_bit_width, quantization_cache=quantization_cache)
|
77 |
+
ctx.weight_shape = weight.size()
|
78 |
+
output = inp.mm(weight.t())
|
79 |
+
ctx.save_for_backward(inp, quant_w, scale_w)
|
80 |
+
return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
|
81 |
+
|
82 |
+
@staticmethod
|
83 |
+
def backward(ctx, grad_output: torch.Tensor):
|
84 |
+
inp, quant_w, scale_w = ctx.saved_tensors
|
85 |
+
weight = extract_weight_to_float(quant_w, scale_w, ctx.weight_bit_width)
|
86 |
+
grad_output = grad_output.contiguous().view(-1, weight.size(0))
|
87 |
+
grad_input = grad_output.mm(weight)
|
88 |
+
grad_weight = grad_output.t().mm(inp)
|
89 |
+
return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
|
90 |
+
|
91 |
+
|
92 |
+
default_cpu_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels.c")
|
93 |
+
default_cpu_kernel_code = "QlpoOTFBWSZTWXLbSoQAAgzbgERwQXxmTwAAr/ff3kABt0Q2oRVT0hpo9RtEAAAAyBEiSQ9EGjQGQAAAwANGhowjJoNGmgMEUplMTNSMJ5TQaDJpsoMyRMj8P4mZzFSVVwqSXG8GG7MlVwiToYEQwVD7noBxMhNfkeZYtYFtbgOBUSIGtIQjhNHCEnPJsadhb3yBmRIOD3TeAtNLSaU5GgvKUBWSNuuOIHmVt0YhW6rsmDMDUjeUJGJ64R1Jm5lrh0Aa0tKjhFwPdWcGogxLDSXPWQUWTM8Sd3Qz1HMYNxx3HMeiNqNo4jeRDEfZ3gUSHIcU/heomq0vEzL1Msz5KKGxH8FrNOYw3KaxdqaEmNHYMxJFgQbR0DyRknL2L4kwUSxKRdhjRpEtUqilVfggFL1klaMS3PPRDfNqbBOPWO7m4JTVGhS9QTBDDJaEbLbrUQNB+IpJSKQbG5SZZ5gkwJEhJ3aYKJipZ/i7kinChIOW2lQg"
|
94 |
+
default_cpu_parallel_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels_parallel.c")
|
95 |
+
default_cpu_parallel_kernel_code = "QlpoOTFBWSZTWUzax5EAALXbgERwSX1mTwAAr/ff3kACNyXUbZYwBpoaNGIyAaADQwRSaVP9QoMg0A2oAPU0AEUkU9GaaKMaQB6gA09T1ARRKnpk0niaJkaaNDJ6g0DTIKVKfZ/g6v1Kem5LJLa0WmkukkuCIHUqWbtJGJMsCSQFiPEIYHgBIZDzR8R6REbYxIqD2Cu7lMkFoPu6LmHeOAy0GF83Tc40jgmTs4HnCe60QfJa2bDBZ0Y1lhgbiZjW8SNsAKCk42UOEdjWN3KoiCIYeQUCCKWIyHewhtSoInLKSG22l4jKM2ZDCVKtBm3OTYBl3jsVqMImtj7PQw7xKxLXQzwgJaPPgW1fRhrvPJICl4YFDYfNbkbBh5JDgrazFml50xEQQwQUjxNwE0IDSofLzSg7UNVKn+Rr1KErzBHUxBqdHRlXzqYsIa5K9Y0UuE2ugw3g5KYofm7AaGNTzJSMhcchhxdaU4JZ0F1UNgQ8XcGDguypqYza8yFaEoGgNRcLej+g2t0feGKFE5OY2PFluQ3q4HgycxlfvzHqo0KcM0JI8OKXtzayJFgsqC1NdUQVu8rChnA6FO3MFyGOoC9KO8ITPpYM5pRqTlczFkLES/4u5IpwoSCZtY8i"
|
96 |
+
|
97 |
+
cpu_kernels = None
|
98 |
+
|
99 |
+
|
100 |
+
class CPUKernel:
|
101 |
+
def __init__(self, kernel_file="", source_code=default_cpu_kernel_code_path, compile_parallel_kernel=None, parallel_num=None):
|
102 |
+
self.load =False
|
103 |
+
self.int8WeightExtractionFloat = None
|
104 |
+
self.int4WeightExtractionFloat = None
|
105 |
+
self.int4WeightCompression = None
|
106 |
+
self.SetNumThreads = lambda x: x
|
107 |
+
|
108 |
+
try:
|
109 |
+
if not os.path.exists(default_cpu_kernel_code_path):
|
110 |
+
with open(default_cpu_kernel_code_path, "w", encoding="utf-8") as file:
|
111 |
+
code = default_cpu_kernel_code
|
112 |
+
cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
|
113 |
+
file.write(cpu_quantization_code)
|
114 |
+
|
115 |
+
if not os.path.exists(default_cpu_parallel_kernel_code_path):
|
116 |
+
with open(default_cpu_parallel_kernel_code_path, "w", encoding="utf-8") as file:
|
117 |
+
code = default_cpu_parallel_kernel_code
|
118 |
+
cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
|
119 |
+
file.write(cpu_quantization_code)
|
120 |
+
|
121 |
+
except Exception as ex:
|
122 |
+
print("Error when generating default cpu kernel code(can be ignored when using custom kernels).")
|
123 |
+
|
124 |
+
if compile_parallel_kernel is None:
|
125 |
+
compile_parallel_kernel = bool(int(os.cpu_count()) >= 4)
|
126 |
+
|
127 |
+
if compile_parallel_kernel and source_code == default_cpu_kernel_code_path:
|
128 |
+
source_code = default_cpu_parallel_kernel_code_path
|
129 |
+
|
130 |
+
kernels = None
|
131 |
+
|
132 |
+
if (not kernel_file) or (not os.path.exists(kernel_file)):
|
133 |
+
print("No compiled kernel found.")
|
134 |
+
try:
|
135 |
+
if os.path.exists(source_code):
|
136 |
+
print("Compiling kernels :", source_code)
|
137 |
+
kernel_file = source_code[:-2] + ".so"
|
138 |
+
|
139 |
+
if compile_parallel_kernel:
|
140 |
+
compile_command = "gcc -O3 -fPIC -pthread -fopenmp -std=c99 {} -shared -o {}".format(source_code, kernel_file)
|
141 |
+
print("Compiling", compile_command)
|
142 |
+
exit_state = os.system(compile_command)
|
143 |
+
if not exit_state:
|
144 |
+
try:
|
145 |
+
kernels = ctypes.cdll.LoadLibrary(kernel_file)
|
146 |
+
print("Load kernel :", kernel_file)
|
147 |
+
except:
|
148 |
+
kernels = None
|
149 |
+
print("Load parallel cpu kernel failed, using default cpu kernel code:")
|
150 |
+
import traceback
|
151 |
+
exception = traceback.format_exc()
|
152 |
+
print(exception)
|
153 |
+
else:
|
154 |
+
print("Compile default cpu kernel failed, using default cpu kernel code.")
|
155 |
+
|
156 |
+
if kernels is None: # adjust config, use default cpu kernel
|
157 |
+
compile_parallel_kernel = False
|
158 |
+
source_code = default_cpu_kernel_code_path
|
159 |
+
kernel_file = source_code[:-2] + ".so"
|
160 |
+
|
161 |
+
if kernels is None:
|
162 |
+
compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file)
|
163 |
+
print("Compiling", compile_command)
|
164 |
+
exit_state = os.system(compile_command)
|
165 |
+
if not exit_state:
|
166 |
+
try:
|
167 |
+
kernels = ctypes.cdll.LoadLibrary(kernel_file)
|
168 |
+
print("Load kernel :", kernel_file)
|
169 |
+
except:
|
170 |
+
kernels = None
|
171 |
+
print("Load default cpu kernel failed:")
|
172 |
+
import traceback
|
173 |
+
exception = traceback.format_exc()
|
174 |
+
print(exception)
|
175 |
+
else:
|
176 |
+
print("Compile default cpu kernel failed.")
|
177 |
+
else:
|
178 |
+
print("Kernel source code not found.")
|
179 |
+
return
|
180 |
+
except:
|
181 |
+
print("Failed to build cpu kernel:")
|
182 |
+
import traceback
|
183 |
+
exception = traceback.format_exc()
|
184 |
+
print(exception)
|
185 |
+
return
|
186 |
+
else:
|
187 |
+
try:
|
188 |
+
kernels = ctypes.cdll.LoadLibrary(kernel_file)
|
189 |
+
print("Load kernel :", kernel_file)
|
190 |
+
except:
|
191 |
+
kernels = None
|
192 |
+
print("Load custom cpu kernel failed:")
|
193 |
+
import traceback
|
194 |
+
exception = traceback.format_exc()
|
195 |
+
print(exception)
|
196 |
+
|
197 |
+
if kernels is not None:
|
198 |
+
self.int8WeightExtractionFloat = kernels.extract_int8_weight_to_float
|
199 |
+
self.int4WeightExtractionFloat = kernels.extract_int4_weight_to_float
|
200 |
+
self.int4WeightCompression = kernels.compress_int4_weight
|
201 |
+
if compile_parallel_kernel:
|
202 |
+
try:
|
203 |
+
self.SetNumThreads = kernels.set_num_threads
|
204 |
+
except:
|
205 |
+
print("No set_num_threads() found in kernel.")
|
206 |
+
self.load = True
|
207 |
+
else:
|
208 |
+
print("Failed to load kernel.")
|
209 |
+
return
|
210 |
+
|
211 |
+
if compile_parallel_kernel:
|
212 |
+
if parallel_num is None:
|
213 |
+
parallel_num = max(os.cpu_count() // 2, 1)
|
214 |
+
print("Setting CPU quantization kernel threads to", parallel_num)
|
215 |
+
if parallel_num < 4:
|
216 |
+
print("Parallel kernel is not recommended when parallel num < 4.")
|
217 |
+
self.SetNumThreads(parallel_num)
|
218 |
+
|
219 |
+
self.parallel_num = parallel_num
|
220 |
+
|
221 |
+
|
222 |
+
def compress_int4_weight(weight: torch.Tensor): # (n, m)
|
223 |
+
"""compress weight on cpu or cuda to int4"""
|
224 |
+
if weight.device == torch.device("cpu"):
|
225 |
+
assert isinstance(cpu_kernels, CPUKernel)
|
226 |
+
n, m = weight.size(0), weight.size(1)
|
227 |
+
assert m % 2 == 0
|
228 |
+
m = m // 2
|
229 |
+
out = torch.empty(n, m, dtype=torch.int8, device="cpu")
|
230 |
+
cpu_kernels.int4WeightCompression(
|
231 |
+
ctypes.c_void_p(weight.data_ptr()),
|
232 |
+
ctypes.c_void_p(out.data_ptr()),
|
233 |
+
ctypes.c_int32(n),
|
234 |
+
ctypes.c_int32(m)
|
235 |
+
)
|
236 |
+
return out
|
237 |
+
else:
|
238 |
+
with torch.cuda.device(weight.device):
|
239 |
+
n, m = weight.size(0), weight.size(1)
|
240 |
+
assert m % 2 == 0
|
241 |
+
m = m // 2
|
242 |
+
out = torch.empty(n, m, dtype=torch.int8, device="cuda")
|
243 |
+
stream = torch.cuda.current_stream()
|
244 |
+
|
245 |
+
gridDim = (n, 1, 1)
|
246 |
+
blockDim = (min(round_up(m, 32), 1024), 1, 1)
|
247 |
+
|
248 |
+
kernels.int4WeightCompression(
|
249 |
+
gridDim,
|
250 |
+
blockDim,
|
251 |
+
0,
|
252 |
+
stream,
|
253 |
+
[ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
|
254 |
+
)
|
255 |
+
return out
|
256 |
+
|
257 |
+
|
258 |
+
def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
|
259 |
+
if source_bit_width == 8:
|
260 |
+
func = kernels.int8WeightExtractionHalf
|
261 |
+
elif source_bit_width == 4:
|
262 |
+
func = kernels.int4WeightExtractionHalf
|
263 |
+
else:
|
264 |
+
assert False, "Unsupported bit-width"
|
265 |
+
|
266 |
+
with torch.cuda.device(weight.device):
|
267 |
+
n, m = weight.size(0), weight.size(1)
|
268 |
+
out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
|
269 |
+
stream = torch.cuda.current_stream()
|
270 |
+
|
271 |
+
gridDim = (n, 1, 1)
|
272 |
+
blockDim = (min(round_up(m, 32), 1024), 1, 1)
|
273 |
+
|
274 |
+
func(
|
275 |
+
gridDim,
|
276 |
+
blockDim,
|
277 |
+
0,
|
278 |
+
stream,
|
279 |
+
[
|
280 |
+
ctypes.c_void_p(weight.data_ptr()),
|
281 |
+
ctypes.c_void_p(scale_list.data_ptr()),
|
282 |
+
ctypes.c_void_p(out.data_ptr()),
|
283 |
+
ctypes.c_int32(n),
|
284 |
+
ctypes.c_int32(m),
|
285 |
+
],
|
286 |
+
)
|
287 |
+
return out
|
288 |
+
|
289 |
+
|
290 |
+
def extract_weight_to_float(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int, quantization_cache=None):
|
291 |
+
"""extract weight on cpu to float32"""
|
292 |
+
if source_bit_width == 8:
|
293 |
+
func = cpu_kernels.int8WeightExtractionFloat
|
294 |
+
elif source_bit_width == 4:
|
295 |
+
func = cpu_kernels.int4WeightExtractionFloat
|
296 |
+
else:
|
297 |
+
assert False, "Unsupported bit-width"
|
298 |
+
|
299 |
+
n, m = weight.size(0), weight.size(1)
|
300 |
+
|
301 |
+
if quantization_cache is not None:
|
302 |
+
out = quantization_cache
|
303 |
+
func(
|
304 |
+
ctypes.c_void_p(weight.data_ptr()),
|
305 |
+
ctypes.c_void_p(scale_list.data_ptr()),
|
306 |
+
ctypes.c_void_p(out.data_ptr()),
|
307 |
+
ctypes.c_int32(n),
|
308 |
+
ctypes.c_int32(m)
|
309 |
+
)
|
310 |
+
return out.tensor
|
311 |
+
else:
|
312 |
+
out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.float, device="cpu")
|
313 |
+
func(
|
314 |
+
ctypes.c_void_p(weight.data_ptr()),
|
315 |
+
ctypes.c_void_p(scale_list.data_ptr()),
|
316 |
+
ctypes.c_void_p(out.data_ptr()),
|
317 |
+
ctypes.c_int32(n),
|
318 |
+
ctypes.c_int32(m)
|
319 |
+
)
|
320 |
+
return out
|
321 |
+
|
322 |
+
|
323 |
+
class CacheTensor():
|
324 |
+
def __init__(self, *args, **kwargs):
|
325 |
+
self.tensor = torch.empty(*args, **kwargs)
|
326 |
+
|
327 |
+
def to(self, *args, **kwargs):
|
328 |
+
self.tensor = self.tensor.to(*args, **kwargs)
|
329 |
+
|
330 |
+
def data_ptr(self):
|
331 |
+
return self.tensor.data_ptr()
|
332 |
+
|
333 |
+
|
334 |
+
class QuantizedLinear(Linear):
|
335 |
+
def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, quantized_weight=None, quantized_weight_scale=None, quantization_cache=None, empty_init=False, *args, **kwargs):
|
336 |
+
super(QuantizedLinear, self).__init__(*args, **kwargs)
|
337 |
+
self.weight_bit_width = weight_bit_width
|
338 |
+
self.quantization_cache = quantization_cache
|
339 |
+
|
340 |
+
if (quantized_weight is not None) and (quantized_weight_scale is not None):
|
341 |
+
del self.weight
|
342 |
+
self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
|
343 |
+
self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
|
344 |
+
else:
|
345 |
+
shape = self.weight.shape
|
346 |
+
del self.weight
|
347 |
+
|
348 |
+
if weight_tensor is None or empty_init:
|
349 |
+
self.weight = torch.empty(
|
350 |
+
shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
|
351 |
+
)
|
352 |
+
self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
|
353 |
+
else:
|
354 |
+
self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(kwargs["dtype"])
|
355 |
+
self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
|
356 |
+
if weight_bit_width == 4:
|
357 |
+
self.weight = compress_int4_weight(self.weight)
|
358 |
+
|
359 |
+
self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
|
360 |
+
self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
|
361 |
+
|
362 |
+
if bias_tensor is not None:
|
363 |
+
self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
|
364 |
+
else:
|
365 |
+
self.bias = None
|
366 |
+
|
367 |
+
def reset_parameters(self):
|
368 |
+
"""To accelerate initialization"""
|
369 |
+
pass
|
370 |
+
|
371 |
+
def forward(self, input):
|
372 |
+
if self.weight.device == torch.device("cpu"):
|
373 |
+
output = W8A16LinearCPU.apply(input, self.weight, self.weight_scale, self.weight_bit_width, self.quantization_cache)
|
374 |
+
else:
|
375 |
+
output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
|
376 |
+
if self.bias is not None:
|
377 |
+
output = output + self.bias
|
378 |
+
return output
|
379 |
+
|
380 |
+
def _apply(self, fn):
|
381 |
+
self_obj = super()._apply(fn)
|
382 |
+
if self.quantization_cache is not None:
|
383 |
+
self.quantization_cache.to(self_obj.weight.device)
|
384 |
+
self.quantization_cache.to(self_obj.weight_scale.dtype)
|
385 |
+
return self_obj
|
386 |
+
|
387 |
+
|
388 |
+
class QuantizedEmbedding(Embedding): # TODO: backward, check empty_init
|
389 |
+
def __init__(self, weight_bit_width: int, weight_tensor=None, quantized_weight=None, quantized_weight_scale=None, empty_init=False, *args, **kwargs):
|
390 |
+
super(QuantizedEmbedding, self).__init__(*args, **kwargs)
|
391 |
+
self.weight_bit_width = weight_bit_width
|
392 |
+
|
393 |
+
if (quantized_weight is not None) and (quantized_weight_scale is not None):
|
394 |
+
del self.weight
|
395 |
+
self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
|
396 |
+
self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
|
397 |
+
else:
|
398 |
+
shape = self.weight.shape
|
399 |
+
del self.weight
|
400 |
+
|
401 |
+
if weight_tensor is None or empty_init:
|
402 |
+
self.weight = torch.empty(
|
403 |
+
shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
|
404 |
+
)
|
405 |
+
self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
|
406 |
+
else:
|
407 |
+
self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).half()
|
408 |
+
self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
|
409 |
+
if weight_bit_width == 4:
|
410 |
+
self.weight = compress_int4_weight(self.weight)
|
411 |
+
|
412 |
+
self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
|
413 |
+
self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
|
414 |
+
|
415 |
+
def forward(self, input):
|
416 |
+
if self.weight.device == torch.device("cpu"):
|
417 |
+
original_weight = extract_weight_to_float(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width)
|
418 |
+
else:
|
419 |
+
original_weight = extract_weight_to_half(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width)
|
420 |
+
output = F.embedding(
|
421 |
+
input, original_weight, self.padding_idx, self.max_norm,
|
422 |
+
self.norm_type, self.scale_grad_by_freq, self.sparse
|
423 |
+
)
|
424 |
+
return output
|
425 |
+
|
426 |
+
|
427 |
+
def load_cpu_kernel(**kwargs):
|
428 |
+
global cpu_kernels
|
429 |
+
cpu_kernels = CPUKernel(**kwargs)
|
430 |
+
assert cpu_kernels.load
|
431 |
+
|
432 |
+
|
433 |
+
def quantize(model, weight_bit_width, use_quantization_cache=False, empty_init=False, **kwargs):
|
434 |
+
"""Replace fp16 linear with quantized linear"""
|
435 |
+
|
436 |
+
query_key_value_quantization_cache = None
|
437 |
+
dense_quantization_cache = None
|
438 |
+
dense_h_to_4h_quantization_cache = None
|
439 |
+
dense_4h_to_h_quantization_cache = None
|
440 |
+
|
441 |
+
try:
|
442 |
+
load_cpu_kernel(**kwargs)
|
443 |
+
except:
|
444 |
+
if kernels is None: # CUDA kernels failed
|
445 |
+
print("Cannot load cpu or cuda kernel, quantization failed:")
|
446 |
+
assert kernels is not None
|
447 |
+
print("Cannot load cpu kernel, don't use quantized model on cpu.")
|
448 |
+
|
449 |
+
current_device = model.device
|
450 |
+
|
451 |
+
if model.device == torch.device("cpu"):
|
452 |
+
dtype=torch.float32
|
453 |
+
else:
|
454 |
+
dtype = torch.half
|
455 |
+
|
456 |
+
QuantizedLinearWithPara = partial(
|
457 |
+
QuantizedLinear,
|
458 |
+
weight_bit_width=weight_bit_width,
|
459 |
+
bias=True,
|
460 |
+
dtype=dtype,
|
461 |
+
empty_init=empty_init
|
462 |
+
)
|
463 |
+
|
464 |
+
if use_quantization_cache:
|
465 |
+
print("Using quantization cache")
|
466 |
+
layer = model.layers[0]
|
467 |
+
weight = layer.attention.query_key_value.weight
|
468 |
+
n, m = weight.size(0), weight.size(1)
|
469 |
+
query_key_value_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
470 |
+
weight = layer.attention.dense.weight
|
471 |
+
n, m = weight.size(0), weight.size(1)
|
472 |
+
dense_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
473 |
+
weight = layer.mlp.dense_h_to_4h.weight
|
474 |
+
n, m = weight.size(0), weight.size(1)
|
475 |
+
dense_h_to_4h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
476 |
+
weight = layer.mlp.dense_4h_to_h.weight
|
477 |
+
n, m = weight.size(0), weight.size(1)
|
478 |
+
dense_4h_to_h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
479 |
+
|
480 |
+
print("Applying quantization to glm layers")
|
481 |
+
|
482 |
+
for layer in model.layers:
|
483 |
+
layer.attention.query_key_value = QuantizedLinearWithPara(
|
484 |
+
weight_tensor=layer.attention.query_key_value.weight.to(current_device),
|
485 |
+
bias_tensor=layer.attention.query_key_value.bias,
|
486 |
+
in_features=layer.attention.query_key_value.in_features,
|
487 |
+
out_features=layer.attention.query_key_value.out_features,
|
488 |
+
device=layer.attention.query_key_value.weight.device,
|
489 |
+
quantization_cache=query_key_value_quantization_cache
|
490 |
+
)
|
491 |
+
layer.attention.dense = QuantizedLinearWithPara(
|
492 |
+
weight_tensor=layer.attention.dense.weight.to(current_device),
|
493 |
+
bias_tensor=layer.attention.dense.bias,
|
494 |
+
in_features=layer.attention.dense.in_features,
|
495 |
+
out_features=layer.attention.dense.out_features,
|
496 |
+
device=layer.attention.dense.weight.device,
|
497 |
+
quantization_cache=dense_quantization_cache
|
498 |
+
)
|
499 |
+
layer.mlp.dense_h_to_4h = QuantizedLinearWithPara(
|
500 |
+
weight_tensor=layer.mlp.dense_h_to_4h.weight.to(current_device),
|
501 |
+
bias_tensor=layer.mlp.dense_h_to_4h.bias,
|
502 |
+
in_features=layer.mlp.dense_h_to_4h.in_features,
|
503 |
+
out_features=layer.mlp.dense_h_to_4h.out_features,
|
504 |
+
device=layer.mlp.dense_h_to_4h.weight.device,
|
505 |
+
quantization_cache=dense_h_to_4h_quantization_cache
|
506 |
+
)
|
507 |
+
layer.mlp.dense_4h_to_h = QuantizedLinearWithPara(
|
508 |
+
weight_tensor=layer.mlp.dense_4h_to_h.weight.to(current_device),
|
509 |
+
bias_tensor=layer.mlp.dense_4h_to_h.bias,
|
510 |
+
in_features=layer.mlp.dense_4h_to_h.in_features,
|
511 |
+
out_features=layer.mlp.dense_4h_to_h.out_features,
|
512 |
+
device=layer.mlp.dense_4h_to_h.weight.device,
|
513 |
+
quantization_cache=dense_4h_to_h_quantization_cache
|
514 |
+
)
|
515 |
+
return model
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/rng_state.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6ced23e0e417f2dfcf6eed7e0bfc1d56c4c6ed8e2c602d433d06066af88ab2e7
|
3 |
+
size 14575
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/scheduler.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ce21225b3a04f92b1556e137b9e4f00a59dda32eda3027243d8cfd9edab1acb7
|
3 |
+
size 627
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/special_tokens_map.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<sop>",
|
3 |
+
"eos_token": "<eop>",
|
4 |
+
"mask_token": "[MASK]",
|
5 |
+
"pad_token": "<pad>",
|
6 |
+
"unk_token": "<unk>"
|
7 |
+
}
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/tokenization_chatglm.py
ADDED
@@ -0,0 +1,430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tokenization classes for ChatGLM."""
|
2 |
+
from typing import List, Optional, Union
|
3 |
+
import os
|
4 |
+
|
5 |
+
from transformers.tokenization_utils import PreTrainedTokenizer
|
6 |
+
from transformers.utils import logging, PaddingStrategy
|
7 |
+
from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
|
8 |
+
from typing import Dict
|
9 |
+
import sentencepiece as spm
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
logger = logging.get_logger(__name__)
|
13 |
+
|
14 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
15 |
+
"THUDM/chatglm-6b": 2048,
|
16 |
+
}
|
17 |
+
|
18 |
+
|
19 |
+
class TextTokenizer:
|
20 |
+
def __init__(self, model_path):
|
21 |
+
self.sp = spm.SentencePieceProcessor()
|
22 |
+
self.sp.Load(model_path)
|
23 |
+
self.num_tokens = self.sp.vocab_size()
|
24 |
+
|
25 |
+
def encode(self, text):
|
26 |
+
return self.sp.EncodeAsIds(text)
|
27 |
+
|
28 |
+
def decode(self, ids: List[int]):
|
29 |
+
return self.sp.DecodeIds(ids)
|
30 |
+
|
31 |
+
def tokenize(self, text):
|
32 |
+
return self.sp.EncodeAsPieces(text)
|
33 |
+
|
34 |
+
def convert_tokens_to_ids(self, tokens):
|
35 |
+
return [self.sp.PieceToId(token) for token in tokens]
|
36 |
+
|
37 |
+
def convert_token_to_id(self, token):
|
38 |
+
return self.sp.PieceToId(token)
|
39 |
+
|
40 |
+
def convert_id_to_token(self, idx):
|
41 |
+
return self.sp.IdToPiece(idx)
|
42 |
+
|
43 |
+
def __len__(self):
|
44 |
+
return self.num_tokens
|
45 |
+
|
46 |
+
|
47 |
+
class SPTokenizer:
|
48 |
+
def __init__(
|
49 |
+
self,
|
50 |
+
vocab_file,
|
51 |
+
num_image_tokens=20000,
|
52 |
+
max_blank_length=80,
|
53 |
+
byte_fallback=True,
|
54 |
+
):
|
55 |
+
assert vocab_file is not None
|
56 |
+
self.vocab_file = vocab_file
|
57 |
+
self.num_image_tokens = num_image_tokens
|
58 |
+
self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
|
59 |
+
self.max_blank_length = max_blank_length
|
60 |
+
self.byte_fallback = byte_fallback
|
61 |
+
self.text_tokenizer = TextTokenizer(vocab_file)
|
62 |
+
|
63 |
+
def _get_text_tokenizer(self):
|
64 |
+
return self.text_tokenizer
|
65 |
+
|
66 |
+
@staticmethod
|
67 |
+
def get_blank_token(length: int):
|
68 |
+
assert length >= 2
|
69 |
+
return f"<|blank_{length}|>"
|
70 |
+
|
71 |
+
@staticmethod
|
72 |
+
def get_tab_token():
|
73 |
+
return f"<|tab|>"
|
74 |
+
|
75 |
+
@property
|
76 |
+
def num_text_tokens(self):
|
77 |
+
return self.text_tokenizer.num_tokens
|
78 |
+
|
79 |
+
@property
|
80 |
+
def num_tokens(self):
|
81 |
+
return self.num_image_tokens + self.num_text_tokens
|
82 |
+
|
83 |
+
@staticmethod
|
84 |
+
def _encode_whitespaces(text: str, max_len: int = 80):
|
85 |
+
text = text.replace("\t", SPTokenizer.get_tab_token())
|
86 |
+
for i in range(max_len, 1, -1):
|
87 |
+
text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
|
88 |
+
return text
|
89 |
+
|
90 |
+
def _preprocess(self, text: str, linebreak=True, whitespaces=True):
|
91 |
+
if linebreak:
|
92 |
+
text = text.replace("\n", "<n>")
|
93 |
+
if whitespaces:
|
94 |
+
text = self._encode_whitespaces(text, max_len=self.max_blank_length)
|
95 |
+
return text
|
96 |
+
|
97 |
+
def encode(
|
98 |
+
self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
|
99 |
+
) -> List[int]:
|
100 |
+
"""
|
101 |
+
@param text: Text to encode.
|
102 |
+
@param linebreak: Whether to encode newline (\n) in text.
|
103 |
+
@param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
|
104 |
+
@param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
|
105 |
+
@param add_dummy_prefix: Whether to add dummy blank space in the beginning.
|
106 |
+
"""
|
107 |
+
text = self._preprocess(text, linebreak, whitespaces)
|
108 |
+
if not add_dummy_prefix:
|
109 |
+
text = "<n>" + text
|
110 |
+
tmp = self._get_text_tokenizer().encode(text)
|
111 |
+
tokens = [x + self.num_image_tokens for x in tmp]
|
112 |
+
return tokens if add_dummy_prefix else tokens[2:]
|
113 |
+
|
114 |
+
def decode(self, text_ids: List[int]) -> str:
|
115 |
+
ids = [int(_id) - self.num_image_tokens for _id in text_ids]
|
116 |
+
ids = [_id for _id in ids if _id >= 0]
|
117 |
+
text = self._get_text_tokenizer().decode(ids)
|
118 |
+
text = text.replace("<n>", "\n")
|
119 |
+
text = text.replace(SPTokenizer.get_tab_token(), "\t")
|
120 |
+
for i in range(2, self.max_blank_length + 1):
|
121 |
+
text = text.replace(self.get_blank_token(i), " " * i)
|
122 |
+
return text
|
123 |
+
|
124 |
+
def tokenize(
|
125 |
+
self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
|
126 |
+
) -> List[str]:
|
127 |
+
"""
|
128 |
+
@param text: Text to encode.
|
129 |
+
@param linebreak: Whether to encode newline (\n) in text.
|
130 |
+
@param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
|
131 |
+
@param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
|
132 |
+
@param add_dummy_prefix: Whether to add dummy blank space in the beginning.
|
133 |
+
"""
|
134 |
+
text = self._preprocess(text, linebreak, whitespaces)
|
135 |
+
if not add_dummy_prefix:
|
136 |
+
text = "<n>" + text
|
137 |
+
tokens = self._get_text_tokenizer().tokenize(text)
|
138 |
+
return tokens if add_dummy_prefix else tokens[2:]
|
139 |
+
|
140 |
+
def __getitem__(self, x: Union[int, str]):
|
141 |
+
if isinstance(x, int):
|
142 |
+
if x < self.num_image_tokens:
|
143 |
+
return "<image_{}>".format(x)
|
144 |
+
else:
|
145 |
+
return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
|
146 |
+
elif isinstance(x, str):
|
147 |
+
if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
|
148 |
+
return int(x[7:-1])
|
149 |
+
else:
|
150 |
+
return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
|
151 |
+
else:
|
152 |
+
raise ValueError("The key should be str or int.")
|
153 |
+
|
154 |
+
|
155 |
+
class ChatGLMTokenizer(PreTrainedTokenizer):
|
156 |
+
"""
|
157 |
+
Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
|
158 |
+
|
159 |
+
Args:
|
160 |
+
vocab_file (`str`):
|
161 |
+
Path to the vocabulary file.
|
162 |
+
"""
|
163 |
+
|
164 |
+
vocab_files_names = {"vocab_file": "ice_text.model"}
|
165 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
166 |
+
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
167 |
+
|
168 |
+
def __init__(
|
169 |
+
self,
|
170 |
+
vocab_file,
|
171 |
+
do_lower_case=False,
|
172 |
+
remove_space=False,
|
173 |
+
bos_token='<sop>',
|
174 |
+
eos_token='<eop>',
|
175 |
+
end_token='</s>',
|
176 |
+
mask_token='[MASK]',
|
177 |
+
gmask_token='[gMASK]',
|
178 |
+
padding_side="left",
|
179 |
+
pad_token="<pad>",
|
180 |
+
unk_token="<unk>",
|
181 |
+
num_image_tokens=20000,
|
182 |
+
**kwargs
|
183 |
+
) -> None:
|
184 |
+
super().__init__(
|
185 |
+
do_lower_case=do_lower_case,
|
186 |
+
remove_space=remove_space,
|
187 |
+
padding_side=padding_side,
|
188 |
+
bos_token=bos_token,
|
189 |
+
eos_token=eos_token,
|
190 |
+
end_token=end_token,
|
191 |
+
mask_token=mask_token,
|
192 |
+
gmask_token=gmask_token,
|
193 |
+
pad_token=pad_token,
|
194 |
+
unk_token=unk_token,
|
195 |
+
num_image_tokens=num_image_tokens,
|
196 |
+
**kwargs
|
197 |
+
)
|
198 |
+
|
199 |
+
self.do_lower_case = do_lower_case
|
200 |
+
self.remove_space = remove_space
|
201 |
+
self.vocab_file = vocab_file
|
202 |
+
|
203 |
+
self.bos_token = bos_token
|
204 |
+
self.eos_token = eos_token
|
205 |
+
self.end_token = end_token
|
206 |
+
self.mask_token = mask_token
|
207 |
+
self.gmask_token = gmask_token
|
208 |
+
|
209 |
+
self.sp_tokenizer = SPTokenizer(vocab_file, num_image_tokens=num_image_tokens)
|
210 |
+
|
211 |
+
""" Initialisation """
|
212 |
+
|
213 |
+
@property
|
214 |
+
def gmask_token_id(self) -> Optional[int]:
|
215 |
+
if self.gmask_token is None:
|
216 |
+
return None
|
217 |
+
return self.convert_tokens_to_ids(self.gmask_token)
|
218 |
+
|
219 |
+
@property
|
220 |
+
def end_token_id(self) -> Optional[int]:
|
221 |
+
"""
|
222 |
+
`Optional[int]`: Id of the end of context token in the vocabulary. Returns `None` if the token has not been
|
223 |
+
set.
|
224 |
+
"""
|
225 |
+
if self.end_token is None:
|
226 |
+
return None
|
227 |
+
return self.convert_tokens_to_ids(self.end_token)
|
228 |
+
|
229 |
+
@property
|
230 |
+
def vocab_size(self):
|
231 |
+
""" Returns vocab size """
|
232 |
+
return self.sp_tokenizer.num_tokens
|
233 |
+
|
234 |
+
def get_vocab(self):
|
235 |
+
""" Returns vocab as a dict """
|
236 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
237 |
+
vocab.update(self.added_tokens_encoder)
|
238 |
+
return vocab
|
239 |
+
|
240 |
+
def preprocess_text(self, inputs):
|
241 |
+
if self.remove_space:
|
242 |
+
outputs = " ".join(inputs.strip().split())
|
243 |
+
else:
|
244 |
+
outputs = inputs
|
245 |
+
|
246 |
+
if self.do_lower_case:
|
247 |
+
outputs = outputs.lower()
|
248 |
+
|
249 |
+
return outputs
|
250 |
+
|
251 |
+
def _tokenize(self, text, **kwargs):
|
252 |
+
""" Returns a tokenized string. """
|
253 |
+
text = self.preprocess_text(text)
|
254 |
+
|
255 |
+
seq = self.sp_tokenizer.tokenize(text)
|
256 |
+
|
257 |
+
return seq
|
258 |
+
|
259 |
+
def _decode(
|
260 |
+
self,
|
261 |
+
token_ids: Union[int, List[int]],
|
262 |
+
skip_special_tokens: bool = False,
|
263 |
+
clean_up_tokenization_spaces: bool = True,
|
264 |
+
**kwargs
|
265 |
+
) -> str:
|
266 |
+
if isinstance(token_ids, int):
|
267 |
+
token_ids = [token_ids]
|
268 |
+
if len(token_ids) == 0:
|
269 |
+
return ""
|
270 |
+
if self.pad_token_id in token_ids: # remove pad
|
271 |
+
token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
|
272 |
+
return self.sp_tokenizer.decode(token_ids)
|
273 |
+
|
274 |
+
def _convert_token_to_id(self, token):
|
275 |
+
""" Converts a token (str) in an id using the vocab. """
|
276 |
+
return self.sp_tokenizer[token]
|
277 |
+
|
278 |
+
def _convert_id_to_token(self, index):
|
279 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
280 |
+
return self.sp_tokenizer[index]
|
281 |
+
|
282 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
283 |
+
"""
|
284 |
+
Save the vocabulary and special tokens file to a directory.
|
285 |
+
|
286 |
+
Args:
|
287 |
+
save_directory (`str`):
|
288 |
+
The directory in which to save the vocabulary.
|
289 |
+
filename_prefix (`str`, *optional*):
|
290 |
+
An optional prefix to add to the named of the saved files.
|
291 |
+
|
292 |
+
Returns:
|
293 |
+
`Tuple(str)`: Paths to the files saved.
|
294 |
+
"""
|
295 |
+
if os.path.isdir(save_directory):
|
296 |
+
vocab_file = os.path.join(
|
297 |
+
save_directory, self.vocab_files_names["vocab_file"]
|
298 |
+
)
|
299 |
+
else:
|
300 |
+
vocab_file = save_directory
|
301 |
+
|
302 |
+
with open(self.vocab_file, 'rb') as fin:
|
303 |
+
proto_str = fin.read()
|
304 |
+
|
305 |
+
with open(vocab_file, "wb") as writer:
|
306 |
+
writer.write(proto_str)
|
307 |
+
|
308 |
+
return (vocab_file,)
|
309 |
+
|
310 |
+
def build_inputs_with_special_tokens(
|
311 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
312 |
+
) -> List[int]:
|
313 |
+
"""
|
314 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
315 |
+
adding special tokens. A BERT sequence has the following format:
|
316 |
+
|
317 |
+
- single sequence: `[CLS] X [SEP]`
|
318 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
319 |
+
|
320 |
+
Args:
|
321 |
+
token_ids_0 (`List[int]`):
|
322 |
+
List of IDs to which the special tokens will be added.
|
323 |
+
token_ids_1 (`List[int]`, *optional*):
|
324 |
+
Optional second list of IDs for sequence pairs.
|
325 |
+
|
326 |
+
Returns:
|
327 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
328 |
+
"""
|
329 |
+
gmask_id = self.sp_tokenizer[self.gmask_token]
|
330 |
+
eos_id = self.sp_tokenizer[self.eos_token]
|
331 |
+
token_ids_0 = token_ids_0 + [gmask_id, self.sp_tokenizer[self.bos_token]]
|
332 |
+
if token_ids_1 is not None:
|
333 |
+
token_ids_0 = token_ids_0 + token_ids_1 + [eos_id]
|
334 |
+
return token_ids_0
|
335 |
+
|
336 |
+
def _pad(
|
337 |
+
self,
|
338 |
+
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
339 |
+
max_length: Optional[int] = None,
|
340 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
341 |
+
pad_to_multiple_of: Optional[int] = None,
|
342 |
+
return_attention_mask: Optional[bool] = None,
|
343 |
+
) -> dict:
|
344 |
+
"""
|
345 |
+
Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
|
346 |
+
|
347 |
+
Args:
|
348 |
+
encoded_inputs:
|
349 |
+
Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
|
350 |
+
max_length: maximum length of the returned list and optionally padding length (see below).
|
351 |
+
Will truncate by taking into account the special tokens.
|
352 |
+
padding_strategy: PaddingStrategy to use for padding.
|
353 |
+
|
354 |
+
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
|
355 |
+
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
|
356 |
+
- PaddingStrategy.DO_NOT_PAD: Do not pad
|
357 |
+
The tokenizer padding sides are defined in self.padding_side:
|
358 |
+
|
359 |
+
- 'left': pads on the left of the sequences
|
360 |
+
- 'right': pads on the right of the sequences
|
361 |
+
pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
|
362 |
+
This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
|
363 |
+
`>= 7.5` (Volta).
|
364 |
+
return_attention_mask:
|
365 |
+
(optional) Set to False to avoid returning attention mask (default: set to model specifics)
|
366 |
+
"""
|
367 |
+
# Load from model defaults
|
368 |
+
bos_token_id = self.sp_tokenizer[self.bos_token]
|
369 |
+
mask_token_id = self.sp_tokenizer[self.mask_token]
|
370 |
+
gmask_token_id = self.sp_tokenizer[self.gmask_token]
|
371 |
+
assert self.padding_side == "left"
|
372 |
+
|
373 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
374 |
+
seq_length = len(required_input)
|
375 |
+
|
376 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
377 |
+
max_length = len(required_input)
|
378 |
+
|
379 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
380 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
381 |
+
|
382 |
+
needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
|
383 |
+
|
384 |
+
# Initialize attention mask if not present.
|
385 |
+
if max_length is not None:
|
386 |
+
if "attention_mask" not in encoded_inputs:
|
387 |
+
if bos_token_id in required_input:
|
388 |
+
context_length = required_input.index(bos_token_id)
|
389 |
+
else:
|
390 |
+
context_length = seq_length
|
391 |
+
attention_mask = np.ones((1, seq_length, seq_length))
|
392 |
+
attention_mask = np.tril(attention_mask)
|
393 |
+
attention_mask[:, :, :context_length] = 1
|
394 |
+
attention_mask = np.bool_(attention_mask < 0.5)
|
395 |
+
encoded_inputs["attention_mask"] = attention_mask
|
396 |
+
|
397 |
+
if "position_ids" not in encoded_inputs:
|
398 |
+
if bos_token_id in required_input:
|
399 |
+
context_length = required_input.index(bos_token_id)
|
400 |
+
else:
|
401 |
+
context_length = seq_length
|
402 |
+
position_ids = np.arange(seq_length, dtype=np.int64)
|
403 |
+
mask_token = mask_token_id if mask_token_id in required_input else gmask_token_id
|
404 |
+
if mask_token in required_input:
|
405 |
+
mask_position = required_input.index(mask_token)
|
406 |
+
position_ids[context_length:] = mask_position
|
407 |
+
block_position_ids = np.concatenate(
|
408 |
+
[np.zeros(context_length, dtype=np.int64),
|
409 |
+
np.arange(1, seq_length - context_length + 1, dtype=np.int64)])
|
410 |
+
encoded_inputs["position_ids"] = np.stack([position_ids, block_position_ids], axis=0)
|
411 |
+
|
412 |
+
if needs_to_be_padded:
|
413 |
+
difference = max_length - len(required_input)
|
414 |
+
|
415 |
+
if "attention_mask" in encoded_inputs:
|
416 |
+
encoded_inputs["attention_mask"] = np.pad(encoded_inputs["attention_mask"],
|
417 |
+
pad_width=[(0, 0), (difference, 0), (difference, 0)],
|
418 |
+
mode='constant', constant_values=True)
|
419 |
+
if "token_type_ids" in encoded_inputs:
|
420 |
+
encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
|
421 |
+
"token_type_ids"
|
422 |
+
]
|
423 |
+
if "special_tokens_mask" in encoded_inputs:
|
424 |
+
encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
|
425 |
+
if "position_ids" in encoded_inputs:
|
426 |
+
encoded_inputs["position_ids"] = np.pad(encoded_inputs["position_ids"],
|
427 |
+
pad_width=[(0, 0), (difference, 0)])
|
428 |
+
encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
|
429 |
+
|
430 |
+
return encoded_inputs
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/tokenizer_config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_chatglm.ChatGLMTokenizer",
|
5 |
+
null
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"bos_token": "<sop>",
|
9 |
+
"do_lower_case": false,
|
10 |
+
"end_token": "</s>",
|
11 |
+
"eos_token": "<eop>",
|
12 |
+
"gmask_token": "[gMASK]",
|
13 |
+
"mask_token": "[MASK]",
|
14 |
+
"model_max_length": 1000000000000000019884624838656,
|
15 |
+
"num_image_tokens": 0,
|
16 |
+
"pad_token": "<pad>",
|
17 |
+
"padding_side": "left",
|
18 |
+
"remove_space": false,
|
19 |
+
"special_tokens_map_file": null,
|
20 |
+
"tokenizer_class": "ChatGLMTokenizer",
|
21 |
+
"unk_token": "<unk>"
|
22 |
+
}
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/trainer_state.json
ADDED
@@ -0,0 +1,616 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"best_metric": null,
|
3 |
+
"best_model_checkpoint": null,
|
4 |
+
"epoch": 114.28571428571429,
|
5 |
+
"global_step": 1000,
|
6 |
+
"is_hyper_param_search": false,
|
7 |
+
"is_local_process_zero": true,
|
8 |
+
"is_world_process_zero": true,
|
9 |
+
"log_history": [
|
10 |
+
{
|
11 |
+
"epoch": 1.14,
|
12 |
+
"learning_rate": 0.0198,
|
13 |
+
"loss": 4.7949,
|
14 |
+
"step": 10
|
15 |
+
},
|
16 |
+
{
|
17 |
+
"epoch": 2.29,
|
18 |
+
"learning_rate": 0.0196,
|
19 |
+
"loss": 3.7519,
|
20 |
+
"step": 20
|
21 |
+
},
|
22 |
+
{
|
23 |
+
"epoch": 3.43,
|
24 |
+
"learning_rate": 0.0194,
|
25 |
+
"loss": 3.3049,
|
26 |
+
"step": 30
|
27 |
+
},
|
28 |
+
{
|
29 |
+
"epoch": 4.57,
|
30 |
+
"learning_rate": 0.0192,
|
31 |
+
"loss": 2.8868,
|
32 |
+
"step": 40
|
33 |
+
},
|
34 |
+
{
|
35 |
+
"epoch": 5.71,
|
36 |
+
"learning_rate": 0.019,
|
37 |
+
"loss": 2.4806,
|
38 |
+
"step": 50
|
39 |
+
},
|
40 |
+
{
|
41 |
+
"epoch": 6.86,
|
42 |
+
"learning_rate": 0.0188,
|
43 |
+
"loss": 1.865,
|
44 |
+
"step": 60
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"epoch": 8.0,
|
48 |
+
"learning_rate": 0.018600000000000002,
|
49 |
+
"loss": 1.4186,
|
50 |
+
"step": 70
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"epoch": 9.14,
|
54 |
+
"learning_rate": 0.0184,
|
55 |
+
"loss": 0.9316,
|
56 |
+
"step": 80
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"epoch": 10.29,
|
60 |
+
"learning_rate": 0.0182,
|
61 |
+
"loss": 0.5643,
|
62 |
+
"step": 90
|
63 |
+
},
|
64 |
+
{
|
65 |
+
"epoch": 11.43,
|
66 |
+
"learning_rate": 0.018000000000000002,
|
67 |
+
"loss": 0.3509,
|
68 |
+
"step": 100
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"epoch": 12.57,
|
72 |
+
"learning_rate": 0.0178,
|
73 |
+
"loss": 0.2172,
|
74 |
+
"step": 110
|
75 |
+
},
|
76 |
+
{
|
77 |
+
"epoch": 13.71,
|
78 |
+
"learning_rate": 0.0176,
|
79 |
+
"loss": 0.1486,
|
80 |
+
"step": 120
|
81 |
+
},
|
82 |
+
{
|
83 |
+
"epoch": 14.86,
|
84 |
+
"learning_rate": 0.0174,
|
85 |
+
"loss": 0.1196,
|
86 |
+
"step": 130
|
87 |
+
},
|
88 |
+
{
|
89 |
+
"epoch": 16.0,
|
90 |
+
"learning_rate": 0.0172,
|
91 |
+
"loss": 0.0802,
|
92 |
+
"step": 140
|
93 |
+
},
|
94 |
+
{
|
95 |
+
"epoch": 17.14,
|
96 |
+
"learning_rate": 0.017,
|
97 |
+
"loss": 0.0739,
|
98 |
+
"step": 150
|
99 |
+
},
|
100 |
+
{
|
101 |
+
"epoch": 18.29,
|
102 |
+
"learning_rate": 0.0168,
|
103 |
+
"loss": 0.0619,
|
104 |
+
"step": 160
|
105 |
+
},
|
106 |
+
{
|
107 |
+
"epoch": 19.43,
|
108 |
+
"learning_rate": 0.0166,
|
109 |
+
"loss": 0.062,
|
110 |
+
"step": 170
|
111 |
+
},
|
112 |
+
{
|
113 |
+
"epoch": 20.57,
|
114 |
+
"learning_rate": 0.016399999999999998,
|
115 |
+
"loss": 0.0595,
|
116 |
+
"step": 180
|
117 |
+
},
|
118 |
+
{
|
119 |
+
"epoch": 21.71,
|
120 |
+
"learning_rate": 0.016200000000000003,
|
121 |
+
"loss": 0.0569,
|
122 |
+
"step": 190
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"epoch": 22.86,
|
126 |
+
"learning_rate": 0.016,
|
127 |
+
"loss": 0.0533,
|
128 |
+
"step": 200
|
129 |
+
},
|
130 |
+
{
|
131 |
+
"epoch": 24.0,
|
132 |
+
"learning_rate": 0.0158,
|
133 |
+
"loss": 0.052,
|
134 |
+
"step": 210
|
135 |
+
},
|
136 |
+
{
|
137 |
+
"epoch": 25.14,
|
138 |
+
"learning_rate": 0.015600000000000001,
|
139 |
+
"loss": 0.0471,
|
140 |
+
"step": 220
|
141 |
+
},
|
142 |
+
{
|
143 |
+
"epoch": 26.29,
|
144 |
+
"learning_rate": 0.0154,
|
145 |
+
"loss": 0.0478,
|
146 |
+
"step": 230
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"epoch": 27.43,
|
150 |
+
"learning_rate": 0.0152,
|
151 |
+
"loss": 0.0415,
|
152 |
+
"step": 240
|
153 |
+
},
|
154 |
+
{
|
155 |
+
"epoch": 28.57,
|
156 |
+
"learning_rate": 0.015,
|
157 |
+
"loss": 0.0462,
|
158 |
+
"step": 250
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"epoch": 29.71,
|
162 |
+
"learning_rate": 0.0148,
|
163 |
+
"loss": 0.0437,
|
164 |
+
"step": 260
|
165 |
+
},
|
166 |
+
{
|
167 |
+
"epoch": 30.86,
|
168 |
+
"learning_rate": 0.0146,
|
169 |
+
"loss": 0.0452,
|
170 |
+
"step": 270
|
171 |
+
},
|
172 |
+
{
|
173 |
+
"epoch": 32.0,
|
174 |
+
"learning_rate": 0.0144,
|
175 |
+
"loss": 0.041,
|
176 |
+
"step": 280
|
177 |
+
},
|
178 |
+
{
|
179 |
+
"epoch": 33.14,
|
180 |
+
"learning_rate": 0.014199999999999999,
|
181 |
+
"loss": 0.0418,
|
182 |
+
"step": 290
|
183 |
+
},
|
184 |
+
{
|
185 |
+
"epoch": 34.29,
|
186 |
+
"learning_rate": 0.013999999999999999,
|
187 |
+
"loss": 0.0469,
|
188 |
+
"step": 300
|
189 |
+
},
|
190 |
+
{
|
191 |
+
"epoch": 35.43,
|
192 |
+
"learning_rate": 0.0138,
|
193 |
+
"loss": 0.0394,
|
194 |
+
"step": 310
|
195 |
+
},
|
196 |
+
{
|
197 |
+
"epoch": 36.57,
|
198 |
+
"learning_rate": 0.013600000000000001,
|
199 |
+
"loss": 0.0444,
|
200 |
+
"step": 320
|
201 |
+
},
|
202 |
+
{
|
203 |
+
"epoch": 37.71,
|
204 |
+
"learning_rate": 0.0134,
|
205 |
+
"loss": 0.0393,
|
206 |
+
"step": 330
|
207 |
+
},
|
208 |
+
{
|
209 |
+
"epoch": 38.86,
|
210 |
+
"learning_rate": 0.013200000000000002,
|
211 |
+
"loss": 0.045,
|
212 |
+
"step": 340
|
213 |
+
},
|
214 |
+
{
|
215 |
+
"epoch": 40.0,
|
216 |
+
"learning_rate": 0.013000000000000001,
|
217 |
+
"loss": 0.0392,
|
218 |
+
"step": 350
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"epoch": 41.14,
|
222 |
+
"learning_rate": 0.0128,
|
223 |
+
"loss": 0.0351,
|
224 |
+
"step": 360
|
225 |
+
},
|
226 |
+
{
|
227 |
+
"epoch": 42.29,
|
228 |
+
"learning_rate": 0.0126,
|
229 |
+
"loss": 0.0389,
|
230 |
+
"step": 370
|
231 |
+
},
|
232 |
+
{
|
233 |
+
"epoch": 43.43,
|
234 |
+
"learning_rate": 0.0124,
|
235 |
+
"loss": 0.0374,
|
236 |
+
"step": 380
|
237 |
+
},
|
238 |
+
{
|
239 |
+
"epoch": 44.57,
|
240 |
+
"learning_rate": 0.0122,
|
241 |
+
"loss": 0.035,
|
242 |
+
"step": 390
|
243 |
+
},
|
244 |
+
{
|
245 |
+
"epoch": 45.71,
|
246 |
+
"learning_rate": 0.012,
|
247 |
+
"loss": 0.0349,
|
248 |
+
"step": 400
|
249 |
+
},
|
250 |
+
{
|
251 |
+
"epoch": 46.86,
|
252 |
+
"learning_rate": 0.0118,
|
253 |
+
"loss": 0.0361,
|
254 |
+
"step": 410
|
255 |
+
},
|
256 |
+
{
|
257 |
+
"epoch": 48.0,
|
258 |
+
"learning_rate": 0.0116,
|
259 |
+
"loss": 0.0368,
|
260 |
+
"step": 420
|
261 |
+
},
|
262 |
+
{
|
263 |
+
"epoch": 49.14,
|
264 |
+
"learning_rate": 0.011399999999999999,
|
265 |
+
"loss": 0.0352,
|
266 |
+
"step": 430
|
267 |
+
},
|
268 |
+
{
|
269 |
+
"epoch": 50.29,
|
270 |
+
"learning_rate": 0.011200000000000002,
|
271 |
+
"loss": 0.0353,
|
272 |
+
"step": 440
|
273 |
+
},
|
274 |
+
{
|
275 |
+
"epoch": 51.43,
|
276 |
+
"learning_rate": 0.011000000000000001,
|
277 |
+
"loss": 0.0337,
|
278 |
+
"step": 450
|
279 |
+
},
|
280 |
+
{
|
281 |
+
"epoch": 52.57,
|
282 |
+
"learning_rate": 0.0108,
|
283 |
+
"loss": 0.032,
|
284 |
+
"step": 460
|
285 |
+
},
|
286 |
+
{
|
287 |
+
"epoch": 53.71,
|
288 |
+
"learning_rate": 0.0106,
|
289 |
+
"loss": 0.0366,
|
290 |
+
"step": 470
|
291 |
+
},
|
292 |
+
{
|
293 |
+
"epoch": 54.86,
|
294 |
+
"learning_rate": 0.010400000000000001,
|
295 |
+
"loss": 0.0317,
|
296 |
+
"step": 480
|
297 |
+
},
|
298 |
+
{
|
299 |
+
"epoch": 56.0,
|
300 |
+
"learning_rate": 0.0102,
|
301 |
+
"loss": 0.0332,
|
302 |
+
"step": 490
|
303 |
+
},
|
304 |
+
{
|
305 |
+
"epoch": 57.14,
|
306 |
+
"learning_rate": 0.01,
|
307 |
+
"loss": 0.0328,
|
308 |
+
"step": 500
|
309 |
+
},
|
310 |
+
{
|
311 |
+
"epoch": 58.29,
|
312 |
+
"learning_rate": 0.0098,
|
313 |
+
"loss": 0.0325,
|
314 |
+
"step": 510
|
315 |
+
},
|
316 |
+
{
|
317 |
+
"epoch": 59.43,
|
318 |
+
"learning_rate": 0.0096,
|
319 |
+
"loss": 0.0327,
|
320 |
+
"step": 520
|
321 |
+
},
|
322 |
+
{
|
323 |
+
"epoch": 60.57,
|
324 |
+
"learning_rate": 0.0094,
|
325 |
+
"loss": 0.0344,
|
326 |
+
"step": 530
|
327 |
+
},
|
328 |
+
{
|
329 |
+
"epoch": 61.71,
|
330 |
+
"learning_rate": 0.0092,
|
331 |
+
"loss": 0.0351,
|
332 |
+
"step": 540
|
333 |
+
},
|
334 |
+
{
|
335 |
+
"epoch": 62.86,
|
336 |
+
"learning_rate": 0.009000000000000001,
|
337 |
+
"loss": 0.0325,
|
338 |
+
"step": 550
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"epoch": 64.0,
|
342 |
+
"learning_rate": 0.0088,
|
343 |
+
"loss": 0.0329,
|
344 |
+
"step": 560
|
345 |
+
},
|
346 |
+
{
|
347 |
+
"epoch": 65.14,
|
348 |
+
"learning_rate": 0.0086,
|
349 |
+
"loss": 0.031,
|
350 |
+
"step": 570
|
351 |
+
},
|
352 |
+
{
|
353 |
+
"epoch": 66.29,
|
354 |
+
"learning_rate": 0.0084,
|
355 |
+
"loss": 0.0326,
|
356 |
+
"step": 580
|
357 |
+
},
|
358 |
+
{
|
359 |
+
"epoch": 67.43,
|
360 |
+
"learning_rate": 0.008199999999999999,
|
361 |
+
"loss": 0.0311,
|
362 |
+
"step": 590
|
363 |
+
},
|
364 |
+
{
|
365 |
+
"epoch": 68.57,
|
366 |
+
"learning_rate": 0.008,
|
367 |
+
"loss": 0.033,
|
368 |
+
"step": 600
|
369 |
+
},
|
370 |
+
{
|
371 |
+
"epoch": 69.71,
|
372 |
+
"learning_rate": 0.0078000000000000005,
|
373 |
+
"loss": 0.0297,
|
374 |
+
"step": 610
|
375 |
+
},
|
376 |
+
{
|
377 |
+
"epoch": 70.86,
|
378 |
+
"learning_rate": 0.0076,
|
379 |
+
"loss": 0.0331,
|
380 |
+
"step": 620
|
381 |
+
},
|
382 |
+
{
|
383 |
+
"epoch": 72.0,
|
384 |
+
"learning_rate": 0.0074,
|
385 |
+
"loss": 0.0318,
|
386 |
+
"step": 630
|
387 |
+
},
|
388 |
+
{
|
389 |
+
"epoch": 73.14,
|
390 |
+
"learning_rate": 0.0072,
|
391 |
+
"loss": 0.0307,
|
392 |
+
"step": 640
|
393 |
+
},
|
394 |
+
{
|
395 |
+
"epoch": 74.29,
|
396 |
+
"learning_rate": 0.006999999999999999,
|
397 |
+
"loss": 0.03,
|
398 |
+
"step": 650
|
399 |
+
},
|
400 |
+
{
|
401 |
+
"epoch": 75.43,
|
402 |
+
"learning_rate": 0.0068000000000000005,
|
403 |
+
"loss": 0.0307,
|
404 |
+
"step": 660
|
405 |
+
},
|
406 |
+
{
|
407 |
+
"epoch": 76.57,
|
408 |
+
"learning_rate": 0.006600000000000001,
|
409 |
+
"loss": 0.0334,
|
410 |
+
"step": 670
|
411 |
+
},
|
412 |
+
{
|
413 |
+
"epoch": 77.71,
|
414 |
+
"learning_rate": 0.0064,
|
415 |
+
"loss": 0.0321,
|
416 |
+
"step": 680
|
417 |
+
},
|
418 |
+
{
|
419 |
+
"epoch": 78.86,
|
420 |
+
"learning_rate": 0.0062,
|
421 |
+
"loss": 0.029,
|
422 |
+
"step": 690
|
423 |
+
},
|
424 |
+
{
|
425 |
+
"epoch": 80.0,
|
426 |
+
"learning_rate": 0.006,
|
427 |
+
"loss": 0.0315,
|
428 |
+
"step": 700
|
429 |
+
},
|
430 |
+
{
|
431 |
+
"epoch": 81.14,
|
432 |
+
"learning_rate": 0.0058,
|
433 |
+
"loss": 0.0294,
|
434 |
+
"step": 710
|
435 |
+
},
|
436 |
+
{
|
437 |
+
"epoch": 82.29,
|
438 |
+
"learning_rate": 0.005600000000000001,
|
439 |
+
"loss": 0.0323,
|
440 |
+
"step": 720
|
441 |
+
},
|
442 |
+
{
|
443 |
+
"epoch": 83.43,
|
444 |
+
"learning_rate": 0.0054,
|
445 |
+
"loss": 0.0274,
|
446 |
+
"step": 730
|
447 |
+
},
|
448 |
+
{
|
449 |
+
"epoch": 84.57,
|
450 |
+
"learning_rate": 0.005200000000000001,
|
451 |
+
"loss": 0.0305,
|
452 |
+
"step": 740
|
453 |
+
},
|
454 |
+
{
|
455 |
+
"epoch": 85.71,
|
456 |
+
"learning_rate": 0.005,
|
457 |
+
"loss": 0.0316,
|
458 |
+
"step": 750
|
459 |
+
},
|
460 |
+
{
|
461 |
+
"epoch": 86.86,
|
462 |
+
"learning_rate": 0.0048,
|
463 |
+
"loss": 0.0262,
|
464 |
+
"step": 760
|
465 |
+
},
|
466 |
+
{
|
467 |
+
"epoch": 88.0,
|
468 |
+
"learning_rate": 0.0046,
|
469 |
+
"loss": 0.0305,
|
470 |
+
"step": 770
|
471 |
+
},
|
472 |
+
{
|
473 |
+
"epoch": 89.14,
|
474 |
+
"learning_rate": 0.0044,
|
475 |
+
"loss": 0.0294,
|
476 |
+
"step": 780
|
477 |
+
},
|
478 |
+
{
|
479 |
+
"epoch": 90.29,
|
480 |
+
"learning_rate": 0.0042,
|
481 |
+
"loss": 0.0291,
|
482 |
+
"step": 790
|
483 |
+
},
|
484 |
+
{
|
485 |
+
"epoch": 91.43,
|
486 |
+
"learning_rate": 0.004,
|
487 |
+
"loss": 0.0274,
|
488 |
+
"step": 800
|
489 |
+
},
|
490 |
+
{
|
491 |
+
"epoch": 92.57,
|
492 |
+
"learning_rate": 0.0038,
|
493 |
+
"loss": 0.032,
|
494 |
+
"step": 810
|
495 |
+
},
|
496 |
+
{
|
497 |
+
"epoch": 93.71,
|
498 |
+
"learning_rate": 0.0036,
|
499 |
+
"loss": 0.0262,
|
500 |
+
"step": 820
|
501 |
+
},
|
502 |
+
{
|
503 |
+
"epoch": 94.86,
|
504 |
+
"learning_rate": 0.0034000000000000002,
|
505 |
+
"loss": 0.0325,
|
506 |
+
"step": 830
|
507 |
+
},
|
508 |
+
{
|
509 |
+
"epoch": 96.0,
|
510 |
+
"learning_rate": 0.0032,
|
511 |
+
"loss": 0.0276,
|
512 |
+
"step": 840
|
513 |
+
},
|
514 |
+
{
|
515 |
+
"epoch": 97.14,
|
516 |
+
"learning_rate": 0.003,
|
517 |
+
"loss": 0.029,
|
518 |
+
"step": 850
|
519 |
+
},
|
520 |
+
{
|
521 |
+
"epoch": 98.29,
|
522 |
+
"learning_rate": 0.0028000000000000004,
|
523 |
+
"loss": 0.0256,
|
524 |
+
"step": 860
|
525 |
+
},
|
526 |
+
{
|
527 |
+
"epoch": 99.43,
|
528 |
+
"learning_rate": 0.0026000000000000003,
|
529 |
+
"loss": 0.0305,
|
530 |
+
"step": 870
|
531 |
+
},
|
532 |
+
{
|
533 |
+
"epoch": 100.57,
|
534 |
+
"learning_rate": 0.0024,
|
535 |
+
"loss": 0.0271,
|
536 |
+
"step": 880
|
537 |
+
},
|
538 |
+
{
|
539 |
+
"epoch": 101.71,
|
540 |
+
"learning_rate": 0.0022,
|
541 |
+
"loss": 0.0302,
|
542 |
+
"step": 890
|
543 |
+
},
|
544 |
+
{
|
545 |
+
"epoch": 102.86,
|
546 |
+
"learning_rate": 0.002,
|
547 |
+
"loss": 0.0288,
|
548 |
+
"step": 900
|
549 |
+
},
|
550 |
+
{
|
551 |
+
"epoch": 104.0,
|
552 |
+
"learning_rate": 0.0018,
|
553 |
+
"loss": 0.0261,
|
554 |
+
"step": 910
|
555 |
+
},
|
556 |
+
{
|
557 |
+
"epoch": 105.14,
|
558 |
+
"learning_rate": 0.0016,
|
559 |
+
"loss": 0.0272,
|
560 |
+
"step": 920
|
561 |
+
},
|
562 |
+
{
|
563 |
+
"epoch": 106.29,
|
564 |
+
"learning_rate": 0.0014000000000000002,
|
565 |
+
"loss": 0.0285,
|
566 |
+
"step": 930
|
567 |
+
},
|
568 |
+
{
|
569 |
+
"epoch": 107.43,
|
570 |
+
"learning_rate": 0.0012,
|
571 |
+
"loss": 0.0271,
|
572 |
+
"step": 940
|
573 |
+
},
|
574 |
+
{
|
575 |
+
"epoch": 108.57,
|
576 |
+
"learning_rate": 0.001,
|
577 |
+
"loss": 0.0289,
|
578 |
+
"step": 950
|
579 |
+
},
|
580 |
+
{
|
581 |
+
"epoch": 109.71,
|
582 |
+
"learning_rate": 0.0008,
|
583 |
+
"loss": 0.028,
|
584 |
+
"step": 960
|
585 |
+
},
|
586 |
+
{
|
587 |
+
"epoch": 110.86,
|
588 |
+
"learning_rate": 0.0006,
|
589 |
+
"loss": 0.0263,
|
590 |
+
"step": 970
|
591 |
+
},
|
592 |
+
{
|
593 |
+
"epoch": 112.0,
|
594 |
+
"learning_rate": 0.0004,
|
595 |
+
"loss": 0.0279,
|
596 |
+
"step": 980
|
597 |
+
},
|
598 |
+
{
|
599 |
+
"epoch": 113.14,
|
600 |
+
"learning_rate": 0.0002,
|
601 |
+
"loss": 0.0272,
|
602 |
+
"step": 990
|
603 |
+
},
|
604 |
+
{
|
605 |
+
"epoch": 114.29,
|
606 |
+
"learning_rate": 0.0,
|
607 |
+
"loss": 0.0285,
|
608 |
+
"step": 1000
|
609 |
+
}
|
610 |
+
],
|
611 |
+
"max_steps": 1000,
|
612 |
+
"num_train_epochs": 125,
|
613 |
+
"total_flos": 3.4665721233408e+16,
|
614 |
+
"trial_name": null,
|
615 |
+
"trial_params": null
|
616 |
+
}
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/checkpoint-1000/training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:800d88035249fde5c3f1ce80f96f4ccad529f4cf9101a6a495f31e43927109c4
|
3 |
+
size 3771
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-38-54_LAPTOP-U8KCJD82/1682019627.5574055/events.out.tfevents.1682019627.LAPTOP-U8KCJD82.39620.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9dbba98e909e8f3a837bb9936dd583c354d8b83d6864e2e8b01328489a808369
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-38-54_LAPTOP-U8KCJD82/events.out.tfevents.1682019627.LAPTOP-U8KCJD82.39620.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b561736c3552194be6ec935d7a465bfb336fbd58bb8ab1d68a78ac97eb833cd7
|
3 |
+
size 4497
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-57-00_LAPTOP-U8KCJD82/1682020719.8067539/events.out.tfevents.1682020719.LAPTOP-U8KCJD82.34144.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5bc26469b12b39eefbfb19bf9be5eac4ad0c68d6e1ddd33e905d3059a06eee64
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_03-57-00_LAPTOP-U8KCJD82/events.out.tfevents.1682020719.LAPTOP-U8KCJD82.34144.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:be50f347728891e15e260d563eb2c32822e3ad0a5ab4e4d5c88689d517c633db
|
3 |
+
size 4999
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-03-18_LAPTOP-U8KCJD82/1682021099.0769536/events.out.tfevents.1682021099.LAPTOP-U8KCJD82.4528.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3c09d6a7d9ba37d37dfae6a9fc383664b7b345ed5b19930da85a2da075a85c8e
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-03-18_LAPTOP-U8KCJD82/events.out.tfevents.1682021099.LAPTOP-U8KCJD82.4528.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:44de312738e1f73fdf252da896b82969f54b288a16abdec15d9bccf5ead2ec89
|
3 |
+
size 4497
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-07-46_LAPTOP-U8KCJD82/1682021363.5070107/events.out.tfevents.1682021363.LAPTOP-U8KCJD82.34384.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c47bc2a2092ec54c278c7f331de46b05c3da8951fc57b79b59353f46d92040cd
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_04-07-46_LAPTOP-U8KCJD82/events.out.tfevents.1682021363.LAPTOP-U8KCJD82.34384.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:95acacb51277b736cd043af6c3df8b0949d37c1932f8dd39775db731d552b037
|
3 |
+
size 20519
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-45-46_LAPTOP-U8KCJD82/1682048840.1281629/events.out.tfevents.1682048840.LAPTOP-U8KCJD82.30268.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f8ac8fe57b89689c202e9c8543749e69915e6670e59659f288602c5fc361779b
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-45-46_LAPTOP-U8KCJD82/events.out.tfevents.1682048840.LAPTOP-U8KCJD82.30268.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d4662640a42ea57ab2152db47ef3f50d721d5509c11c69b51651f99e19411e95
|
3 |
+
size 4501
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-48-35_LAPTOP-U8KCJD82/events.out.tfevents.1682049010.LAPTOP-U8KCJD82.40476.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:43ba45944f035296405454ac17ff21e2da2fdbc697e34273d7dc45c7eb310ff9
|
3 |
+
size 88
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-53-35_LAPTOP-U8KCJD82/1682049309.5723379/events.out.tfevents.1682049309.LAPTOP-U8KCJD82.19992.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c0d37ef4a5778b1a30ca92ff219aa6c92fb662e0df7d88cbf52f0c9d1787d81b
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-53-35_LAPTOP-U8KCJD82/events.out.tfevents.1682049309.LAPTOP-U8KCJD82.19992.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fff7d6993d790a4606be9bebec5478bd2bba7ee0b58fe9c3bfc89edb004c28c8
|
3 |
+
size 4501
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-59-08_LAPTOP-U8KCJD82/1682049642.960882/events.out.tfevents.1682049642.LAPTOP-U8KCJD82.21296.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e2f300310a299cfb4131842c1f4a0b0741d07142c5ad82c82086a08ffb1d0716
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_11-59-08_LAPTOP-U8KCJD82/events.out.tfevents.1682049642.LAPTOP-U8KCJD82.21296.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:adb237b2fa30205061e1d9ba3f2423f8f065aba5b3f0cdaad6908760cc69ff0c
|
3 |
+
size 4501
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_12-04-16_LAPTOP-U8KCJD82/1682049952.9553204/events.out.tfevents.1682049952.LAPTOP-U8KCJD82.3092.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:854624c3499913de971099060c16894b8ff3cc8fb8ba1f912148ac43a812330f
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_12-04-16_LAPTOP-U8KCJD82/events.out.tfevents.1682049952.LAPTOP-U8KCJD82.3092.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9d9e876c62e1fa37df30e6a2d151671f2370546fd7a5f0803bd120affdd0404c
|
3 |
+
size 4414
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_15-57-52_LAPTOP-U8KCJD82/1682063879.4572506/events.out.tfevents.1682063879.LAPTOP-U8KCJD82.41476.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a56b44c1ba6b2d18be7f70271867146e964eba79a175486dd6b55b702a82892b
|
3 |
+
size 6115
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_15-57-52_LAPTOP-U8KCJD82/events.out.tfevents.1682063879.LAPTOP-U8KCJD82.41476.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:17547f8ac5cc000b35a1116cf4b79eed7c52ef17447e1e0e6842c7a6bee5bb34
|
3 |
+
size 6262
|
ptuning/output/adgen-chatglm-6b-pt-128-2e-2/runs/Apr21_16-51-52_LAPTOP-U8KCJD82/1682067121.1639612/events.out.tfevents.1682067121.LAPTOP-U8KCJD82.14196.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2f9a4229035dff3bd94f3f4bd94f88c1db0bbd318e5d085a98addc2fe12e9084
|
3 |
+
size 6115
|