Commit
·
ff9681e
1
Parent(s):
24f558b
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +3 -0
- .github/ISSUE_TEMPLATE/bug_report.yaml +63 -0
- .github/ISSUE_TEMPLATE/config.yml +1 -0
- .github/ISSUE_TEMPLATE/feature_request.yml +26 -0
- .ipynb_checkpoints/Untitled-checkpoint.ipynb +6 -0
- .ipynb_checkpoints/web_demo-checkpoint.py +117 -0
- FAQ.md +15 -0
- MODEL_LICENSE +65 -0
- README.md +358 -13
- README_EN.md +268 -0
- Untitled.ipynb +210 -0
- api.py +60 -0
- chatglm2-6b/.gitattributes +35 -0
- chatglm2-6b/MODEL_LICENSE +65 -0
- chatglm2-6b/README.md +100 -0
- chatglm2-6b/config.json +42 -0
- chatglm2-6b/configuration_chatglm.py +61 -0
- chatglm2-6b/modeling_chatglm.py +1285 -0
- chatglm2-6b/pytorch_model-00001-of-00007.bin +3 -0
- chatglm2-6b/pytorch_model-00002-of-00007.bin +3 -0
- chatglm2-6b/pytorch_model-00003-of-00007.bin +3 -0
- chatglm2-6b/pytorch_model-00004-of-00007.bin +3 -0
- chatglm2-6b/pytorch_model-00005-of-00007.bin +3 -0
- chatglm2-6b/pytorch_model-00006-of-00007.bin +3 -0
- chatglm2-6b/pytorch_model-00007-of-00007.bin +3 -0
- chatglm2-6b/pytorch_model.bin.index.json +207 -0
- chatglm2-6b/quantization.py +188 -0
- chatglm2-6b/tokenization_chatglm.py +257 -0
- chatglm2-6b/tokenizer.model +3 -0
- chatglm2-6b/tokenizer_config.json +12 -0
- cli_demo.py +60 -0
- dev.json +4 -0
- evaluation/README.md +10 -0
- evaluation/evaluate_ceval.py +60 -0
- openai_api.py +177 -0
- output_model/all_results.json +8 -0
- output_model/checkpoint-100/config.json +47 -0
- output_model/checkpoint-100/generation_config.json +6 -0
- output_model/checkpoint-100/optimizer.pt +3 -0
- output_model/checkpoint-100/pytorch_model.bin +3 -0
- output_model/checkpoint-100/rng_state.pth +3 -0
- output_model/checkpoint-100/scheduler.pt +3 -0
- output_model/checkpoint-100/special_tokens_map.json +1 -0
- output_model/checkpoint-100/tokenizer.model +3 -0
- output_model/checkpoint-100/tokenizer_config.json +14 -0
- output_model/checkpoint-100/trainer_state.json +76 -0
- output_model/checkpoint-100/training_args.bin +3 -0
- output_model/checkpoint-200/config.json +47 -0
- output_model/checkpoint-200/generation_config.json +6 -0
- output_model/checkpoint-200/optimizer.pt +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
resources/long-context.png filter=lfs diff=lfs merge=lfs -text
|
37 |
+
resources/web-demo.gif filter=lfs diff=lfs merge=lfs -text
|
38 |
+
resources/web-demo2.gif filter=lfs diff=lfs merge=lfs -text
|
.github/ISSUE_TEMPLATE/bug_report.yaml
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: 🐞 Bug/Help
|
2 |
+
description: File a bug/issue
|
3 |
+
title: "[BUG/Help] <title>"
|
4 |
+
labels: []
|
5 |
+
body:
|
6 |
+
- type: checkboxes
|
7 |
+
attributes:
|
8 |
+
label: Is there an existing issue for this?
|
9 |
+
description: Please search to see if an issue already exists for the bug you encountered.
|
10 |
+
options:
|
11 |
+
- label: I have searched the existing issues
|
12 |
+
required: true
|
13 |
+
- type: textarea
|
14 |
+
attributes:
|
15 |
+
label: Current Behavior
|
16 |
+
description: |
|
17 |
+
A concise description of what you're experiencing, with screenshot attached if possible.
|
18 |
+
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
|
19 |
+
validations:
|
20 |
+
required: true
|
21 |
+
- type: textarea
|
22 |
+
attributes:
|
23 |
+
label: Expected Behavior
|
24 |
+
description: A concise description of what you expected to happen.
|
25 |
+
validations:
|
26 |
+
required: false
|
27 |
+
- type: textarea
|
28 |
+
attributes:
|
29 |
+
label: Steps To Reproduce
|
30 |
+
description: Steps to reproduce the behavior.
|
31 |
+
placeholder: |
|
32 |
+
1. In this environment...
|
33 |
+
2. With this config...
|
34 |
+
3. Run '...'
|
35 |
+
4. See error...
|
36 |
+
validations:
|
37 |
+
required: true
|
38 |
+
- type: textarea
|
39 |
+
attributes:
|
40 |
+
label: Environment
|
41 |
+
description: |
|
42 |
+
examples:
|
43 |
+
- **OS**: Ubuntu 20.04
|
44 |
+
- **Python**: 3.8
|
45 |
+
- **Transformers**: 4.26.1
|
46 |
+
- **PyTorch**: 1.12
|
47 |
+
- **CUDA Support**: True
|
48 |
+
value: |
|
49 |
+
- OS:
|
50 |
+
- Python:
|
51 |
+
- Transformers:
|
52 |
+
- PyTorch:
|
53 |
+
- CUDA Support (`python -c "import torch; print(torch.cuda.is_available())"`) :
|
54 |
+
render: markdown
|
55 |
+
validations:
|
56 |
+
required: true
|
57 |
+
- type: textarea
|
58 |
+
attributes:
|
59 |
+
label: Anything else?
|
60 |
+
description: |
|
61 |
+
Links? References? Anything that will give us more context about the issue you are encountering!
|
62 |
+
validations:
|
63 |
+
required: false
|
.github/ISSUE_TEMPLATE/config.yml
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
blank_issues_enabled: false
|
.github/ISSUE_TEMPLATE/feature_request.yml
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Feature request
|
2 |
+
description: Suggest an idea for this project
|
3 |
+
title: "[Feature] <title>"
|
4 |
+
labels: []
|
5 |
+
body:
|
6 |
+
- type: textarea
|
7 |
+
attributes:
|
8 |
+
label: Is your feature request related to a problem? Please describe.
|
9 |
+
description: |
|
10 |
+
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
11 |
+
validations:
|
12 |
+
required: false
|
13 |
+
- type: textarea
|
14 |
+
attributes:
|
15 |
+
label: Solutions
|
16 |
+
description: |
|
17 |
+
Describe the solution you'd like
|
18 |
+
A clear and concise description of what you want to happen.
|
19 |
+
validations:
|
20 |
+
required: true
|
21 |
+
- type: textarea
|
22 |
+
attributes:
|
23 |
+
label: Additional context
|
24 |
+
description: Add any other context or screenshots about the feature request here.
|
25 |
+
validations:
|
26 |
+
required: false
|
.ipynb_checkpoints/Untitled-checkpoint.ipynb
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [],
|
3 |
+
"metadata": {},
|
4 |
+
"nbformat": 4,
|
5 |
+
"nbformat_minor": 5
|
6 |
+
}
|
.ipynb_checkpoints/web_demo-checkpoint.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModel, AutoTokenizer, AutoConfig
|
2 |
+
import gradio as gr
|
3 |
+
import mdtex2html
|
4 |
+
import torch
|
5 |
+
import os
|
6 |
+
|
7 |
+
CHECKPOINT_PATH=f'output_model/checkpoint-200'
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained("chatglm2-6b", trust_remote_code=True)
|
9 |
+
config = AutoConfig.from_pretrained("chatglm2-6b", trust_remote_code=True, pre_seq_len=128)
|
10 |
+
model = AutoModel.from_pretrained("chatglm2-6b", config=config, trust_remote_code=True)
|
11 |
+
prefix_state_dict = torch.load(os.path.join(CHECKPOINT_PATH, "pytorch_model.bin"))
|
12 |
+
new_prefix_state_dict = {}
|
13 |
+
for k, v in prefix_state_dict.items():
|
14 |
+
if k.startswith("transformer.prefix_encoder."):
|
15 |
+
new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
|
16 |
+
model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
|
17 |
+
|
18 |
+
model = model.half().cuda()
|
19 |
+
model.transformer.prefix_encoder.float()
|
20 |
+
model = model.eval()
|
21 |
+
|
22 |
+
|
23 |
+
"""Override Chatbot.postprocess"""
|
24 |
+
|
25 |
+
|
26 |
+
def postprocess(self, y):
|
27 |
+
if y is None:
|
28 |
+
return []
|
29 |
+
for i, (message, response) in enumerate(y):
|
30 |
+
y[i] = (
|
31 |
+
None if message is None else mdtex2html.convert((message)),
|
32 |
+
None if response is None else mdtex2html.convert(response),
|
33 |
+
)
|
34 |
+
return y
|
35 |
+
|
36 |
+
|
37 |
+
gr.Chatbot.postprocess = postprocess
|
38 |
+
|
39 |
+
|
40 |
+
def parse_text(text):
|
41 |
+
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
|
42 |
+
lines = text.split("\n")
|
43 |
+
lines = [line for line in lines if line != ""]
|
44 |
+
count = 0
|
45 |
+
for i, line in enumerate(lines):
|
46 |
+
if "```" in line:
|
47 |
+
count += 1
|
48 |
+
items = line.split('`')
|
49 |
+
if count % 2 == 1:
|
50 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
51 |
+
else:
|
52 |
+
lines[i] = f'<br></code></pre>'
|
53 |
+
else:
|
54 |
+
if i > 0:
|
55 |
+
if count % 2 == 1:
|
56 |
+
line = line.replace("`", "\`")
|
57 |
+
line = line.replace("<", "<")
|
58 |
+
line = line.replace(">", ">")
|
59 |
+
line = line.replace(" ", " ")
|
60 |
+
line = line.replace("*", "*")
|
61 |
+
line = line.replace("_", "_")
|
62 |
+
line = line.replace("-", "-")
|
63 |
+
line = line.replace(".", ".")
|
64 |
+
line = line.replace("!", "!")
|
65 |
+
line = line.replace("(", "(")
|
66 |
+
line = line.replace(")", ")")
|
67 |
+
line = line.replace("$", "$")
|
68 |
+
lines[i] = "<br>"+line
|
69 |
+
text = "".join(lines)
|
70 |
+
return text
|
71 |
+
|
72 |
+
|
73 |
+
def predict(input, chatbot, max_length, top_p, temperature, history, past_key_values):
|
74 |
+
chatbot.append((parse_text(input), ""))
|
75 |
+
for response, history, past_key_values in model.stream_chat(tokenizer, input, history, past_key_values=past_key_values,
|
76 |
+
return_past_key_values=True,
|
77 |
+
max_length=max_length, top_p=top_p,
|
78 |
+
temperature=temperature):
|
79 |
+
chatbot[-1] = (parse_text(input), parse_text(response))
|
80 |
+
|
81 |
+
yield chatbot, history, past_key_values
|
82 |
+
|
83 |
+
|
84 |
+
def reset_user_input():
|
85 |
+
return gr.update(value='')
|
86 |
+
|
87 |
+
|
88 |
+
def reset_state():
|
89 |
+
return [], [], None
|
90 |
+
|
91 |
+
|
92 |
+
with gr.Blocks() as demo:
|
93 |
+
gr.HTML("""<h1 align="center">ChatGLM2-6B</h1>""")
|
94 |
+
|
95 |
+
chatbot = gr.Chatbot()
|
96 |
+
with gr.Row():
|
97 |
+
with gr.Column(scale=4):
|
98 |
+
with gr.Column(scale=12):
|
99 |
+
user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10)
|
100 |
+
with gr.Column(min_width=32, scale=1):
|
101 |
+
submitBtn = gr.Button("Submit", variant="primary")
|
102 |
+
with gr.Column(scale=1):
|
103 |
+
emptyBtn = gr.Button("Clear History")
|
104 |
+
max_length = gr.Slider(0, 32768, value=8192, step=1.0, label="Maximum length", interactive=True)
|
105 |
+
top_p = gr.Slider(0, 1, value=0.8, step=0.01, label="Top P", interactive=True)
|
106 |
+
temperature = gr.Slider(0, 1, value=0.95, step=0.01, label="Temperature", interactive=True)
|
107 |
+
|
108 |
+
history = gr.State([])
|
109 |
+
past_key_values = gr.State(None)
|
110 |
+
|
111 |
+
submitBtn.click(predict, [user_input, chatbot, max_length, top_p, temperature, history, past_key_values],
|
112 |
+
[chatbot, history, past_key_values], show_progress=True)
|
113 |
+
submitBtn.click(reset_user_input, [], [user_input])
|
114 |
+
|
115 |
+
emptyBtn.click(reset_state, outputs=[chatbot, history, past_key_values], show_progress=True)
|
116 |
+
|
117 |
+
demo.queue().launch(share=True)
|
FAQ.md
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Q1
|
2 |
+
|
3 |
+
**Mac直接加载量化后的模型出现提示 `clang: error: unsupported option '-fopenmp'**
|
4 |
+
|
5 |
+
这是由于Mac由于本身缺乏omp导致的,此时可运行但是单核。需要单独安装 openmp 依赖,即可在Mac下使用OMP:
|
6 |
+
|
7 |
+
```bash
|
8 |
+
# 参考`https://mac.r-project.org/openmp/`
|
9 |
+
## 假设: gcc(clang)是14.x版本,其他版本见R-Project提供的表格
|
10 |
+
curl -O https://mac.r-project.org/openmp/openmp-14.0.6-darwin20-Release.tar.gz
|
11 |
+
sudo tar fvxz openmp-14.0.6-darwin20-Release.tar.gz -C /
|
12 |
+
```
|
13 |
+
此时会安装下面几个文件:`/usr/local/lib/libomp.dylib`, `/usr/local/include/ompt.h`, `/usr/local/include/omp.h`, `/usr/local/include/omp-tools.h`。
|
14 |
+
|
15 |
+
> 注意:如果你之前运行`ChatGLM2-6B`项目失败过,最好清一下Hugging Face的缓存,i.e. 默认下是 `rm -rf ${HOME}/.cache/huggingface/modules/transformers_modules/chatglm-6b-int4`。由于使用了`rm`命令,请明确知道自己在删除什么。
|
MODEL_LICENSE
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The ChatGLM2-6B License
|
2 |
+
|
3 |
+
1. 定义
|
4 |
+
|
5 |
+
“许可方”是指分发其软件的 ChatGLM2-6B 模型团队。
|
6 |
+
|
7 |
+
“软件”是指根据本许可提供的 ChatGLM2-6B 模型参数。
|
8 |
+
|
9 |
+
2. 许可授予
|
10 |
+
|
11 |
+
根据本许可的条款和条件,许可方特此授予您非排他性、全球性、不可转让、不可再许可、可撤销、免版税的版权许可。
|
12 |
+
|
13 |
+
上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
|
14 |
+
|
15 |
+
3.限制
|
16 |
+
|
17 |
+
您不得出于任何军事或非法目的使用、复制、修改、合并、发布、分发、复制或创建本软件的全部或部分衍生作品。
|
18 |
+
|
19 |
+
您不得利用本软件从事任何危害国家安全和国家统一、危害社会公共利益、侵犯人身权益的行为。
|
20 |
+
|
21 |
+
4.免责声明
|
22 |
+
|
23 |
+
本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权性的保证。 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,由软件或软件的使用或其他交易引起、由软件引起或与之相关 软件。
|
24 |
+
|
25 |
+
5. 责任限制
|
26 |
+
|
27 |
+
除适用法律禁止的范围外,在任何情况下且根据任何法律理论,无论是基于侵权行为、疏忽、合同、责任或其他原因,任何许可方均不对您承担任何直接、间接、特殊、偶然、示范性、 或间接损害,或任何其他商业损失,即使许可人已被告知此类损害的可能性。
|
28 |
+
|
29 |
+
6.争议解决
|
30 |
+
|
31 |
+
本许可受中华人民共和国法律管辖并按其解释。 因本许可引起的或与本许可有关的任何争议应提交北京市海淀区人民法院。
|
32 |
+
|
33 |
+
请注意,许可证可能会更新到更全面的版本。 有关许可和版权的任何问题,请通过 [email protected] 与我们联系。
|
34 |
+
|
35 |
+
1. Definitions
|
36 |
+
|
37 |
+
“Licensor” means the ChatGLM2-6B Model Team that distributes its Software.
|
38 |
+
|
39 |
+
“Software” means the ChatGLM2-6B model parameters made available under this license.
|
40 |
+
|
41 |
+
2. License Grant
|
42 |
+
|
43 |
+
Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software.
|
44 |
+
|
45 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
46 |
+
|
47 |
+
3. Restriction
|
48 |
+
|
49 |
+
You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any military, or illegal purposes.
|
50 |
+
|
51 |
+
You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
|
52 |
+
|
53 |
+
4. Disclaimer
|
54 |
+
|
55 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
56 |
+
|
57 |
+
5. Limitation of Liability
|
58 |
+
|
59 |
+
EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
60 |
+
|
61 |
+
6. Dispute Resolution
|
62 |
+
|
63 |
+
This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
|
64 |
+
|
65 |
+
Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at [email protected].
|
README.md
CHANGED
@@ -1,13 +1,358 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ChatGLM2-6B
|
2 |
+
|
3 |
+
<p align="center">
|
4 |
+
🤗 <a href="https://huggingface.co/THUDM/chatglm2-6b" target="_blank">HF Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
|
5 |
+
</p>
|
6 |
+
<p align="center">
|
7 |
+
👋 加入我们的 <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1y7pqoloy-9b1g6T6JjA8J0KxvUjbwJw" target="_blank">Slack</a> 和 <a href="resources/WECHAT.md" target="_blank">WeChat</a>
|
8 |
+
</p>
|
9 |
+
<p align="center">
|
10 |
+
📍在 <a href="https://www.chatglm.cn">chatglm.cn</a> 体验更大规模的 ChatGLM 模型。
|
11 |
+
</p>
|
12 |
+
|
13 |
+
|
14 |
+
*Read this in [English](README_EN.md)*
|
15 |
+
|
16 |
+
新一代开源模型 [ChatGLM3-6B](https://github.com/THUDM/ChatGLM3) 已发布,拥有10B以下最强的基础模型,支持工具调用(Function Call)、代码执行(Code Interpreter)、Agent 任务等功能。
|
17 |
+
|
18 |
+
## 介绍
|
19 |
+
|
20 |
+
ChatGLM**2**-6B 是开源中英双语对话模型 [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B) 的第二代版本,在保留了初代模型对话流畅、部署门槛较低等众多优秀特性的基础之上,ChatGLM**2**-6B 引入了如下新特性:
|
21 |
+
|
22 |
+
1. **更强大的性能**:基于 ChatGLM 初代模型的开发经验,我们全面升级了 ChatGLM2-6B 的基座模型。ChatGLM2-6B 使用了 [GLM](https://github.com/THUDM/GLM) 的混合目标函数,经过了 1.4T 中英标识符的预训练与人类偏好对齐训练,[评测结果](#评测结果)显示,相比于初代模型,ChatGLM2-6B 在 MMLU(+23%)、CEval(+33%)、GSM8K(+571%) 、BBH(+60%)等数据集上的性能取得了大幅度的提升,在同尺寸开源模型中具有较强的竞争力。
|
23 |
+
2. **更长的上下文**:基于 [FlashAttention](https://github.com/HazyResearch/flash-attention) 技术,我们将基座模型的上下文长度(Context Length)由 ChatGLM-6B 的 2K 扩展到了 32K,并在对话阶段使用 8K 的上下文长度训练。对于更长的上下文,我们发布了 [ChatGLM2-6B-32K](https://huggingface.co/THUDM/chatglm2-6b-32k) 模型。[LongBench](https://github.com/THUDM/LongBench) 的测评结果表明,在等量级的开源模型中,ChatGLM2-6B-32K 有着较为明显的竞争优势。
|
24 |
+
3. **更高效的推理**:基于 [Multi-Query Attention](http://arxiv.org/abs/1911.02150) 技术,ChatGLM2-6B 有更高效的推理速度和更低的显存占用:在官方的模型实现下,推理速度相比初代提升了 42%,INT4 量化下,6G 显存支持的对话长度由 1K 提升到了 8K。
|
25 |
+
4. **更开放的协议**:ChatGLM2-6B 权重对学术研究**完全开放**,在填写[问卷](https://open.bigmodel.cn/mla/form)进行登记后**亦允许免费商业使用**。
|
26 |
+
|
27 |
+
-----
|
28 |
+
|
29 |
+
ChatGLM2-6B 开源模型旨在与开源社区一起推动大模型技术发展,恳请开发者和大家遵守[开源协议](MODEL_LICENSE),勿将开源模型和代码及基于开源项目产生的衍生物用于任何可能给国家和社会带来危害的用途以及用于任何未经过安全评估和备案的服务。**目前,本项目团队未基于 ChatGLM2-6B 开发任何应用,包括网页端、安卓、苹果 iOS 及 Windows App 等应用。**
|
30 |
+
|
31 |
+
尽管模型在训练的各个阶段都尽力确保数据的合规性和准确性,但由于 ChatGLM2-6B 模型规模较小,且模型受概率随机性因素影响,无法保证输出内容的准确性,且模型易被误导。**本项目不承担开源模型和代码导致的数据安全、舆情风险或发生任何模型被误导、滥用、传播、不当利用而产生的风险和责任。**
|
32 |
+
|
33 |
+
## 更新信息
|
34 |
+
**[2023/07/31]** 发布 [ChatGLM2-6B-32K](https://huggingface.co/THUDM/chatglm2-6b-32k) 模型,提升对于长文本的理解能力。
|
35 |
+
|
36 |
+
**[2023/07/25]** 发布 [CodeGeeX2](https://github.com/THUDM/CodeGeeX2) 模型,基于 ChatGLM2-6B 加入代码预训练实现,代码能力全面提升。
|
37 |
+
|
38 |
+
**[2023/07/04]** 发布 P-Tuning v2 与 全参数微调脚本,参见 [P-Tuning](./ptuning)。
|
39 |
+
|
40 |
+
## 友情链接
|
41 |
+
对 ChatGLM2 进行加速的开源项目:
|
42 |
+
* [fastllm](https://github.com/ztxz16/fastllm/): 全平台加速推理方案,单GPU批量推理每秒可达10000+token,手机端最低3G内存实时运行(骁龙865上约4~5 token/s)
|
43 |
+
* [chatglm.cpp](https://github.com/li-plus/chatglm.cpp): 类似 llama.cpp 的 CPU 量化加速推理方案,实现 Mac 笔记本上实时对话
|
44 |
+
* [ChatGLM2-TPU](https://github.com/sophgo/ChatGLM2-TPU): 采用TPU加速推理方案,在算能端侧芯片BM1684X(16T@FP16,���存16G)上实时运行约5 token/s
|
45 |
+
|
46 |
+
基于或使用了 ChatGLM2-6B 的开源项目:
|
47 |
+
* [Chuanhu Chat](https://github.com/GaiZhenbiao/ChuanhuChatGPT): 为各个大语言模型和在线模型API提供美观易用、功能丰富、快速部署的用户界面,支持ChatGLM2-6B。
|
48 |
+
|
49 |
+
支持 ChatGLM-6B 和相关应用在线训练的示例项目:
|
50 |
+
* [ChatGLM2-6B 的部署与微调教程](https://www.heywhale.com/mw/project/64984a7b72ebe240516ae79c)
|
51 |
+
|
52 |
+
## 评测结果
|
53 |
+
我们选取了部分中英文典型数据集进行了评测,以下为 ChatGLM2-6B 模型在 [MMLU](https://github.com/hendrycks/test) (英文)、[C-Eval](https://cevalbenchmark.com/static/leaderboard.html)(中文)、[GSM8K](https://github.com/openai/grade-school-math)(数学)、[BBH](https://github.com/suzgunmirac/BIG-Bench-Hard)(英文) 上的测评结果。在 [evaluation](./evaluation/README.md) 中提供了在 C-Eval 上进行测评的脚本。
|
54 |
+
|
55 |
+
### MMLU
|
56 |
+
|
57 |
+
| Model | Average | STEM | Social Sciences | Humanities | Others |
|
58 |
+
| ----- |------| ---- |------|-------| ----- |
|
59 |
+
| ChatGLM-6B | 40.63 | 33.89 | 44.84 | 39.02 | 45.71 |
|
60 |
+
| ChatGLM2-6B (base) | 47.86 | 41.20 | 54.44 | 43.66 | 54.46 |
|
61 |
+
| ChatGLM2-6B | 45.46 | 40.06 | 51.61 | 41.23 | 51.24 |
|
62 |
+
| ChatGLM2-12B (base) | 56.18 | 48.18 | 65.13 | 52.58 | 60.93 |
|
63 |
+
| ChatGLM2-12B | 52.13 | 47.00 | 61.00 | 46.10 | 56.05 |
|
64 |
+
|
65 |
+
> Chat 模型使用 zero-shot CoT (Chain-of-Thought) 的方法测试,Base 模型使用 few-shot answer-only 的方法测试
|
66 |
+
|
67 |
+
### C-Eval
|
68 |
+
|
69 |
+
| Model | Average | STEM | Social Sciences | Humanities | Others |
|
70 |
+
| ----- |---------|-------| ----- |------------|--------|
|
71 |
+
| ChatGLM-6B | 38.9 | 33.3 | 48.3 | 41.3 | 38.0 |
|
72 |
+
| ChatGLM2-6B (base) | 51.7 | 48.6 | 60.5 | 51.3 | 49.8 |
|
73 |
+
| ChatGLM2-6B | 50.1 | 46.4 | 60.4 | 50.6 | 46.9 |
|
74 |
+
| ChatGLM2-12B (base) | 61.6 | 55.4 | 73.7 | 64.2 | 59.4 |
|
75 |
+
| ChatGLM2-12B | 57.0 | 52.1 | 69.3 | 58.5 | 53.2 |
|
76 |
+
|
77 |
+
> Chat 模型使用 zero-shot CoT 的方法测试,Base 模型使用 few-shot answer only 的方法测试
|
78 |
+
|
79 |
+
### GSM8K
|
80 |
+
|
81 |
+
| Model | Accuracy | Accuracy (Chinese)* |
|
82 |
+
|--------------|----------| - |
|
83 |
+
| ChatGLM-6B | 4.82 | 5.85 |
|
84 |
+
| ChatGLM2-6B (base) | 32.37 | 28.95 |
|
85 |
+
| ChatGLM2-6B | 28.05 | 20.45 |
|
86 |
+
| ChatGLM2-12B (base) | 40.94 | 42.71 |
|
87 |
+
| ChatGLM2-12B | 38.13 | 23.43 |
|
88 |
+
|
89 |
+
> 所有模型均使用 few-shot CoT 的方法测试,CoT prompt 来自 http://arxiv.org/abs/2201.11903
|
90 |
+
>
|
91 |
+
> \* 我们使用翻译 API 翻译了 GSM8K 中的 500 道题目和 CoT prompt 并进行了人工校对
|
92 |
+
|
93 |
+
|
94 |
+
### BBH
|
95 |
+
|
96 |
+
| Model | Accuracy |
|
97 |
+
|--------------|-------|
|
98 |
+
| ChatGLM-6B | 18.73 |
|
99 |
+
| ChatGLM2-6B (base) | 33.68 |
|
100 |
+
| ChatGLM2-6B | 30.00 |
|
101 |
+
| ChatGLM2-12B (base) | 36.02 |
|
102 |
+
| ChatGLM2-12B | 39.98 |
|
103 |
+
|
104 |
+
> 所有模型均使用 few-shot CoT 的方法测试,CoT prompt 来自 https://github.com/suzgunmirac/BIG-Bench-Hard/tree/main/cot-prompts
|
105 |
+
|
106 |
+
## 推理性能
|
107 |
+
ChatGLM2-6B 使用了 [Multi-Query Attention](http://arxiv.org/abs/1911.02150),提高了生成速度。生成 2000 个字符的平均速度对比如下
|
108 |
+
|
109 |
+
| Model | 推理速度 (字符/秒) |
|
110 |
+
| ---- | ----- |
|
111 |
+
| ChatGLM-6B | 31.49 |
|
112 |
+
| ChatGLM2-6B | 44.62 |
|
113 |
+
|
114 |
+
> 使用官方实现,batch size = 1,max length = 2048,bf16 精度,测试硬件为 A100-SXM4-80G,软件环境为 PyTorch 2.0.1
|
115 |
+
|
116 |
+
Multi-Query Attention 同时也降低了生成过程中 KV Cache 的显存占用,此外,ChatGLM2-6B 采用 Causal Mask 进行对话训练,连续对话时可复用前面轮次的 KV Cache,进一步优化了显存占用。因此,使用 6GB 显存的显卡进行 INT4 量化的推理时,初代的 ChatGLM-6B 模型最多能够生成 1119 个字符就会提示显存耗尽,而 ChatGLM2-6B 能够生成至少 8192 个字符。
|
117 |
+
|
118 |
+
| **量化等级** | **编码 2048 长度的最小显存** | **生成 8192 长度的最小显存** |
|
119 |
+
| -------------- |---------------------|---------------------|
|
120 |
+
| FP16 / BF16 | 13.1 GB | 12.8 GB |
|
121 |
+
| INT8 | 8.2 GB | 8.1 GB |
|
122 |
+
| INT4 | 5.5 GB | 5.1 GB |
|
123 |
+
|
124 |
+
> ChatGLM2-6B 利用了 PyTorch 2.0 引入的 `torch.nn.functional.scaled_dot_product_attention` 实现高效的 Attention 计算,如果 PyTorch 版本较低则会 fallback 到朴素的 Attention 实现,出现显存占用高于上表的情况。
|
125 |
+
|
126 |
+
我们也测试了量化对模型性能的影响。结果表明,量化对模型性能的影响在可接受范围内。
|
127 |
+
|
128 |
+
| 量化等级 | Accuracy (MMLU) | Accuracy (C-Eval dev) |
|
129 |
+
| ----- | ----- |-----------------------|
|
130 |
+
| BF16 | 45.47 | 53.57 |
|
131 |
+
| INT4 | 43.13 | 50.30 |
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## ChatGLM2-6B 示例
|
136 |
+
|
137 |
+
相比于初代模型,ChatGLM2-6B 多个维度的能力都取得了提升,以下是一些对比示例。更多 ChatGLM2-6B 的可能,等待你来探索发现!
|
138 |
+
|
139 |
+
<details><summary><b>数理逻辑</b></summary>
|
140 |
+
|
141 |
+

|
142 |
+
|
143 |
+
</details>
|
144 |
+
|
145 |
+
<details><summary><b>知识推理</b></summary>
|
146 |
+
|
147 |
+

|
148 |
+
|
149 |
+
</details>
|
150 |
+
|
151 |
+
<details><summary><b>长文档理解</b></summary>
|
152 |
+
|
153 |
+

|
154 |
+
|
155 |
+
</details>
|
156 |
+
|
157 |
+
## 使用方式
|
158 |
+
### 环境安装
|
159 |
+
首先需要下载本仓库:
|
160 |
+
```shell
|
161 |
+
git clone https://github.com/THUDM/ChatGLM2-6B
|
162 |
+
cd ChatGLM2-6B
|
163 |
+
```
|
164 |
+
|
165 |
+
然后使用 pip 安装依赖:
|
166 |
+
```
|
167 |
+
pip install -r requirements.txt
|
168 |
+
```
|
169 |
+
其中 `transformers` 库版本推荐为 `4.30.2`,`torch` 推荐使用 2.0 及以上的版本,以获得最佳的推理性能。
|
170 |
+
|
171 |
+
### 代码调用
|
172 |
+
|
173 |
+
可以通过如下代码调用 ChatGLM2-6B 模型来生成对话:
|
174 |
+
|
175 |
+
```python
|
176 |
+
>>> from transformers import AutoTokenizer, AutoModel
|
177 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
|
178 |
+
>>> model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True, device='cuda')
|
179 |
+
>>> model = model.eval()
|
180 |
+
>>> response, history = model.chat(tokenizer, "你好", history=[])
|
181 |
+
>>> print(response)
|
182 |
+
你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。
|
183 |
+
>>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
|
184 |
+
>>> print(response)
|
185 |
+
晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
|
186 |
+
|
187 |
+
1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
|
188 |
+
2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
|
189 |
+
3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
|
190 |
+
4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
|
191 |
+
5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
|
192 |
+
6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
|
193 |
+
|
194 |
+
如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
|
195 |
+
```
|
196 |
+
|
197 |
+
#### 从本地加载模型
|
198 |
+
以上代码会由 `transformers` 自动下载模型实现和参数。完整的模型实现在 [Hugging Face Hub](https://huggingface.co/THUDM/chatglm2-6b)。如果你的网络环境较差,下载模型参数可能会花费较长时间甚至失败。此时可以先将模型下载到本地,然后从本地加载。
|
199 |
+
|
200 |
+
从 Hugging Face Hub 下载模型需要先[安装Git LFS](https://docs.github.com/zh/repositories/working-with-files/managing-large-files/installing-git-large-file-storage),然后运行
|
201 |
+
```Shell
|
202 |
+
git clone https://huggingface.co/THUDM/chatglm2-6b
|
203 |
+
```
|
204 |
+
|
205 |
+
如果你从 Hugging Face Hub 上下载 checkpoint 的速度较慢,可以只下载模型实现
|
206 |
+
```Shell
|
207 |
+
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm2-6b
|
208 |
+
```
|
209 |
+
然后从[这里](https://cloud.tsinghua.edu.cn/d/674208019e314311ab5c/)手动下载模型参数文件,并将下载的文件替换到本地的 `chatglm2-6b` 目录下。
|
210 |
+
|
211 |
+
|
212 |
+
将模型下载到本地之后,将以上代码中的 `THUDM/chatglm2-6b` 替换为你本地的 `chatglm2-6b` 文件夹的路径,即可从本地加载模型。
|
213 |
+
|
214 |
+
模型的实现仍然处在变动中。如果希望固定使用的模型实现以保证兼容性,可以在 `from_pretrained` 的调用中增加 `revision="v1.0"` 参数。`v1.0` 是当前最新的版本号,完整的版本列表参见 [Change Log](https://huggingface.co/THUDM/chatglm2-6b#change-log)。
|
215 |
+
|
216 |
+
### 网页版 Demo
|
217 |
+

|
218 |
+
可以通过以下命令启动基于 Gradio 的网页版 demo:
|
219 |
+
```shell
|
220 |
+
python web_demo.py
|
221 |
+
```
|
222 |
+
|
223 |
+

|
224 |
+
|
225 |
+
可以通过以下命令启动基于 Streamlit 的网页版 demo:
|
226 |
+
```shell
|
227 |
+
streamlit run web_demo2.py
|
228 |
+
```
|
229 |
+
|
230 |
+
网页版 demo 会运行一个 Web Server,并输出地址。在浏览器中打开输出的地址即可使用。 经测试,基于 Streamlit 的网页版 Demo 会更流畅。
|
231 |
+
|
232 |
+
### 命令行 Demo
|
233 |
+
|
234 |
+

|
235 |
+
|
236 |
+
运行仓库中 [cli_demo.py](cli_demo.py):
|
237 |
+
|
238 |
+
```shell
|
239 |
+
python cli_demo.py
|
240 |
+
```
|
241 |
+
|
242 |
+
程序会在命令行中进行交互式的对话,在命令行中输入指示并回车即可生成回复,输入 `clear` 可以清空对话历史,输入 `stop` 终止程序。
|
243 |
+
|
244 |
+
### API 部署
|
245 |
+
首先需要安装额外的依赖 `pip install fastapi uvicorn`,然后运行仓库中的 [api.py](api.py):
|
246 |
+
```shell
|
247 |
+
python api.py
|
248 |
+
```
|
249 |
+
默认部署在本地的 8000 端口,通过 POST 方法进行调用
|
250 |
+
```shell
|
251 |
+
curl -X POST "http://127.0.0.1:8000" \
|
252 |
+
-H 'Content-Type: application/json' \
|
253 |
+
-d '{"prompt": "你好", "history": []}'
|
254 |
+
```
|
255 |
+
得到的返回值为
|
256 |
+
```shell
|
257 |
+
{
|
258 |
+
"response":"你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。",
|
259 |
+
"history":[["你好","你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。"]],
|
260 |
+
"status":200,
|
261 |
+
"time":"2023-03-23 21:38:40"
|
262 |
+
}
|
263 |
+
```
|
264 |
+
感谢 [@hiyouga]() 实现了 OpenAI 格式的流式 API 部署,可以作为任意基于 ChatGPT 的应用的后端,比如 [ChatGPT-Next-Web](https://github.com/Yidadaa/ChatGPT-Next-Web)。可以通过运行仓库中的[openai_api.py](openai_api.py) 进行部署:
|
265 |
+
```shell
|
266 |
+
python openai_api.py
|
267 |
+
```
|
268 |
+
进行 API 调用的示例代码为
|
269 |
+
```python
|
270 |
+
import openai
|
271 |
+
if __name__ == "__main__":
|
272 |
+
openai.api_base = "http://localhost:8000/v1"
|
273 |
+
openai.api_key = "none"
|
274 |
+
for chunk in openai.ChatCompletion.create(
|
275 |
+
model="chatglm2-6b",
|
276 |
+
messages=[
|
277 |
+
{"role": "user", "content": "你好"}
|
278 |
+
],
|
279 |
+
stream=True
|
280 |
+
):
|
281 |
+
if hasattr(chunk.choices[0].delta, "content"):
|
282 |
+
print(chunk.choices[0].delta.content, end="", flush=True)
|
283 |
+
```
|
284 |
+
|
285 |
+
|
286 |
+
## 低成本部署
|
287 |
+
|
288 |
+
### 模型量化
|
289 |
+
|
290 |
+
默认情况下,模型以 FP16 精度加载,运行上述代码需要大概 13GB 显存。如果你的 GPU 显存有限,可以尝试以量化方式加载模型,使用方法如下:
|
291 |
+
|
292 |
+
```python
|
293 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b-int4",trust_remote_code=True).cuda()
|
294 |
+
```
|
295 |
+
|
296 |
+
模型量化会带来一定的性能损失,经过测试,ChatGLM2-6B 在 4-bit 量化下仍然能够进行自然流畅的生成。 量化模型的参数文件也可以从[这里](https://cloud.tsinghua.edu.cn/d/674208019e314311ab5c/)手动下载。
|
297 |
+
|
298 |
+
### CPU 部署
|
299 |
+
|
300 |
+
如果你没有 GPU 硬件的话,也可以在 CPU 上进行推理,但是推理速度会更慢。使用方法如下(需要大概 32GB 内存)
|
301 |
+
```python
|
302 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).float()
|
303 |
+
```
|
304 |
+
如果你的内存不足的话,也可以使用量化后的模型
|
305 |
+
```python
|
306 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b-int4",trust_remote_code=True).float()
|
307 |
+
```
|
308 |
+
在 cpu 上运行量化后的模型需要安装 `gcc` 与 `openmp`。多数 Linux 发行版默认已安装。对于 Windows ,可在安装 [TDM-GCC](https://jmeubank.github.io/tdm-gcc/) 时勾选 `openmp`。 Windows 测试环境 `gcc` 版本为 `TDM-GCC 10.3.0`, Linux 为 `gcc 11.3.0`。在 MacOS 上请参考 [Q1](FAQ.md#q1)。
|
309 |
+
|
310 |
+
### Mac 部署
|
311 |
+
|
312 |
+
对于搭载了 Apple Silicon 或者 AMD GPU 的 Mac,可以使用 MPS 后端来在 GPU 上运行 ChatGLM2-6B。需要参考 Apple 的 [官方说明](https://developer.apple.com/metal/pytorch) 安装 PyTorch-Nightly(正确的版本号应该是2.x.x.dev2023xxxx,而不是 2.x.x)。
|
313 |
+
|
314 |
+
目前在 MacOS 上只支持[从本地加载模型](README.md#从本地加载模型)。将代码中的模型加载改为从本地加载,并使用 mps 后端:
|
315 |
+
```python
|
316 |
+
model = AutoModel.from_pretrained("your local path", trust_remote_code=True).to('mps')
|
317 |
+
```
|
318 |
+
|
319 |
+
加载半精度的 ChatGLM2-6B 模型需要大概 13GB 内存。内存较小的机器(比如 16GB 内存的 MacBook Pro),在空余内存不足的情况下会使用硬盘上的虚拟内存,导致推理速度严重变慢。
|
320 |
+
此时可以使用量化后的模型 chatglm2-6b-int4。因为 GPU 上量化的 kernel 是使用 CUDA 编写的,因此无法在 MacOS 上使用,只能使用 CPU 进行推理。
|
321 |
+
为了充分使用 CPU 并行,还需要[单独安装 OpenMP](FAQ.md#q1)。
|
322 |
+
|
323 |
+
在 Mac 上进行推理也可以使用 [ChatGLM.cpp](https://github.com/li-plus/chatglm.cpp)
|
324 |
+
|
325 |
+
### 多卡部署
|
326 |
+
如果你有多张 GPU,但是每张 GPU 的显存大小都不足以容纳完整的模型,那么可以将模型切分在多张GPU上。首先安装 accelerate: `pip install accelerate`,然后通过如下方法加载模型:
|
327 |
+
```python
|
328 |
+
from utils import load_model_on_gpus
|
329 |
+
model = load_model_on_gpus("THUDM/chatglm2-6b", num_gpus=2)
|
330 |
+
```
|
331 |
+
即可将模型部署到两张 GPU 上进行推理。你可以将 `num_gpus` 改为你希望使用的 GPU 数。默认是均匀切分的,你也可以传入 `device_map` 参数来自己指定。
|
332 |
+
|
333 |
+
## 协议
|
334 |
+
|
335 |
+
本仓库的代码依照 [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0) 协议开源,ChatGLM2-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。ChatGLM2-6B 权重对学术研究**完全开放**,在填写[问卷](https://open.bigmodel.cn/mla/form)进行登记后**亦允许免费商业使用**。
|
336 |
+
|
337 |
+
|
338 |
+
## 引用
|
339 |
+
|
340 |
+
如果你觉得我们的工作有帮助的话,请考虑引用下列论文,ChatGLM2-6B 的论文会在近期公布,敬请期待~
|
341 |
+
|
342 |
+
```
|
343 |
+
@article{zeng2022glm,
|
344 |
+
title={Glm-130b: An open bilingual pre-trained model},
|
345 |
+
author={Zeng, Aohan and Liu, Xiao and Du, Zhengxiao and Wang, Zihan and Lai, Hanyu and Ding, Ming and Yang, Zhuoyi and Xu, Yifan and Zheng, Wendi and Xia, Xiao and others},
|
346 |
+
journal={arXiv preprint arXiv:2210.02414},
|
347 |
+
year={2022}
|
348 |
+
}
|
349 |
+
```
|
350 |
+
```
|
351 |
+
@inproceedings{du2022glm,
|
352 |
+
title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
|
353 |
+
author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
|
354 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
|
355 |
+
pages={320--335},
|
356 |
+
year={2022}
|
357 |
+
}
|
358 |
+
```
|
README_EN.md
ADDED
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<p align="center">
|
2 |
+
🤗 <a href="https://huggingface.co/THUDM/chatglm2-6b" target="_blank">HF Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
|
3 |
+
</p>
|
4 |
+
<p align="center">
|
5 |
+
👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1y7pqoloy-9b1g6T6JjA8J0KxvUjbwJw" target="_blank">Slack</a> and <a href="resources/WECHAT.md" target="_blank">WeChat</a>
|
6 |
+
</p>
|
7 |
+
|
8 |
+
## Introduction
|
9 |
+
|
10 |
+
ChatGLM**2**-6B is the second-generation version of the open-source bilingual (Chinese-English) chat model [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B). It retains the smooth conversation flow and low deployment threshold of the first-generation model, while introducing the following new features:
|
11 |
+
|
12 |
+
1. **Stronger Performance**: Based on the development experience of the first-generation ChatGLM model, we have fully upgraded the base model of ChatGLM2-6B. ChatGLM2-6B uses the hybrid objective function of [GLM](https://github.com/THUDM/GLM), and has undergone pre-training with 1.4T bilingual tokens and human preference alignment training. The [evaluation results](README.md#evaluation-results) show that, compared to the first-generation model, ChatGLM2-6B has achieved substantial improvements in performance on datasets like MMLU (+23%), CEval (+33%), GSM8K (+571%), BBH (+60%), showing strong competitiveness among models of the same size.
|
13 |
+
2. **Longer Context**: Based on [FlashAttention](https://github.com/HazyResearch/flash-attention) technique, we have extended the context length of the base model from 2K in ChatGLM-6B to 32K, and trained with a context length of 8K during the dialogue alignment, allowing for more rounds of dialogue. However, the current version of ChatGLM2-6B has limited understanding of single-round ultra-long documents, which we will focus on optimizing in future iterations.
|
14 |
+
3. **More Efficient Inference**: Based on [Multi-Query Attention](http://arxiv.org/abs/1911.02150) technique, ChatGLM2-6B has more efficient inference speed and lower GPU memory usage: under the official implementation, the inference speed has increased by 42% compared to the first generation; under INT4 quantization, the dialogue length supported by 6G GPU memory has increased from 1K to 8K.
|
15 |
+
4. **More Open License**: ChatGLM2-6B weights are **completely open** for academic research, and **free commercial use** is also allowed after completing the [questionnaire](https://open.bigmodel.cn/mla/form).
|
16 |
+
|
17 |
+
Welcome to use the larger ChatGLM model on [chatglm.cn](https://chatglm.cn)
|
18 |
+
|
19 |
+
-----
|
20 |
+
|
21 |
+
The open-source ChatGLM2-6B is intended to promote the development of LLMs together with the open-source community. We earnestly request developers and everyone to abide by the [open-source license](MODEL_LICENSE). Do not use the open-source model, code, or any derivatives from the open-source project for any purposes that may harm nations or societies, or for any services that have not undergone safety assessments and legal approval. **At present, our project team has not developed any applications based on ChatGLM2-6B, including web, Android, Apple iOS, and Windows App applications.**
|
22 |
+
|
23 |
+
Although the model strives to ensure the compliance and accuracy of data at each stage of training, due to the smaller scale of the ChatGLM2-6B model, and its susceptibility to probabilistic randomness, the accuracy of output content cannot be guaranteed, and the model can easily be misled. **Our project does not assume any risks or responsibilities arising from data security, public opinion risks, or any instances of the model being misled, abused, disseminated, or improperly used due to the open-source model and code.**
|
24 |
+
|
25 |
+
## Projects
|
26 |
+
Open source projects that accelerate ChatGLM2:
|
27 |
+
|
28 |
+
* [fastllm](https://github.com/ztxz16/fastllm/): Universal platform acceleration inference solution, single GPU batch inference can reach 10,000+ tokens per second, and it can run in real-time on mobile devices with a minimum of 3GB of memory (about 4~5 tokens/s on Snapdragon 865).
|
29 |
+
* [chatglm.cpp](https://github.com/li-plus/chatglm.cpp): Real-time CPU inference on a MacBook accelerated by quantization, similar to llama.cpp.
|
30 |
+
* [ChatGLM2-TPU](https://github.com/sophgo/ChatGLM2-TPU): Using the TPU accelerated inference solution, it runs about 5 token/s in real time on the end-side chip BM1684X (16T@FP16, 16G DDR).
|
31 |
+
|
32 |
+
Example projects supporting online training of ChatGLM-6B and related applications:
|
33 |
+
* [ChatGLM-6B deployment and fine-tuning tutorial](https://www.heywhale.com/mw/project/64984a7b72ebe240516ae79c)
|
34 |
+
|
35 |
+
## Evaluation
|
36 |
+
We selected some typical Chinese and English datasets for evaluation. Below are the evaluation results of the ChatGLM2-6B model on [MMLU](https://github.com/hendrycks/test) (English), [C-Eval](https://cevalbenchmark.com/static/leaderboard.html) (Chinese), [GSM8K](https://github.com/openai/grade-school-math) (Mathematics), [BBH](https://github.com/suzgunmirac/BIG-Bench-Hard) (English).
|
37 |
+
|
38 |
+
### MMLU
|
39 |
+
|
40 |
+
| Model | Average | STEM | Social Sciences | Humanities | Others |
|
41 |
+
| ----- | ----- | ---- | ----- | ----- | ----- |
|
42 |
+
| ChatGLM-6B | 40.63 | 33.89 | 44.84 | 39.02 | 45.71 |
|
43 |
+
| ChatGLM2-6B (base) | 47.86 | 41.20 | 54.44 | 43.66 | 54.46 |
|
44 |
+
| ChatGLM2-6B | 45.46 | 40.06 | 51.61 | 41.23 | 51.24 |
|
45 |
+
|
46 |
+
> Chat-aligned version is evaluated under zero-shot CoT (Chain-of-Thought), and Base version is evaluated under few-shot answer-only
|
47 |
+
|
48 |
+
### C-Eval
|
49 |
+
|
50 |
+
| Model | Average | STEM | Social Sciences | Humanities | Others |
|
51 |
+
| ----- | ---- | ---- | ----- | ----- | ----- |
|
52 |
+
| ChatGLM-6B | 38.9 | 33.3 | 48.3 | 41.3 | 38.0 |
|
53 |
+
| ChatGLM2-6B (base) | 51.7 | 48.6 | 60.5 | 51.3 | 49.8 |
|
54 |
+
| ChatGLM2-6B | 50.1 | 46.4 | 60.4 | 50.6 | 46.9 |
|
55 |
+
|
56 |
+
> Chat-aligned version is evaluated under zero-shot CoT (Chain-of-Thought), and Base version is evaluated under few-shot answer-only
|
57 |
+
|
58 |
+
### GSM8K
|
59 |
+
|
60 |
+
| Model | Accuracy | Accuracy (Chinese)* |
|
61 |
+
| ----- | ----- | ----- |
|
62 |
+
| ChatGLM-6B | 4.82 | 5.85 |
|
63 |
+
| ChatGLM2-6B (base) | 32.37 | 28.95 |
|
64 |
+
| ChatGLM2-6B | 28.05 | 20.45 |
|
65 |
+
|
66 |
+
> All model versions are evaluated under few-shot CoT, and CoT prompts are from http://arxiv.org/abs/2201.11903
|
67 |
+
> \* We translate a 500-query subset of GSM8K and its corresponding CoT prompts using machine translation API and subsequent human proofreading.
|
68 |
+
|
69 |
+
|
70 |
+
### BBH
|
71 |
+
|
72 |
+
| Model | Accuracy |
|
73 |
+
| ----- | ----- |
|
74 |
+
| ChatGLM-6B | 18.73 |
|
75 |
+
| ChatGLM2-6B (base) | 33.68 |
|
76 |
+
| ChatGLM2-6B | 30.00 |
|
77 |
+
|
78 |
+
> All model versions are evaluated under few-shot CoT, and CoT prompts are from https://github.com/suzgunmirac/BIG-Bench-Hard/tree/main/cot-prompts
|
79 |
+
|
80 |
+
## Inference Efficiency
|
81 |
+
ChatGLM2-6B employs [Multi-Query Attention](http://arxiv.org/abs/1911.02150) to improve inference speed. Here is a comparison of the average speed for generating 2000 tokens.
|
82 |
+
|
83 |
+
|
84 |
+
| Model | Inference Speed (tokens/s) |
|
85 |
+
| ---- | ----- |
|
86 |
+
| ChatGLM-6B | 31.49 |
|
87 |
+
| ChatGLM2-6B | 44.62 |
|
88 |
+
|
89 |
+
> Under our official implementation, batch size = 1, max length = 2048, bf16 precision, tested with an A100-SXM-80G and PyTorch 2.0 environment
|
90 |
+
|
91 |
+
Multi-Query Attention also reduces the GPU memory usage of the KV Cache during inference. Additionally, ChatGLM2-6B uses Causal Mask for dialogue training, which allows the reuse of the KV Cache from previous rounds in continuous dialogues, further optimizing GPU memory usage. Therefore, when performing INT4 quantization inference with a 6GB GPU, while the first-generation ChatGLM-6B can only generate a maximum of 1119 tokens before running out of memory, ChatGLM2-6B can generate at least 8192 tokens.
|
92 |
+
|
93 |
+
| **Quantization** | **Encoding 2048 Tokens** | **Decoding 8192 Tokens** |
|
94 |
+
| -------------- | --------------------- | --------------- |
|
95 |
+
| FP16 / BF16 | 13.1 GB | 12.8 GB |
|
96 |
+
| INT8 | 8.2 GB | 8.1 GB |
|
97 |
+
| INT4 | 5.5 GB | 5.1 GB |
|
98 |
+
|
99 |
+
> ChatGLM2-6B takes advantage of `torch.nn.functional.scaled_dot_product_attention` introduced in PyTorch 2.0 for efficient Attention computation. If the PyTorch version is lower, it will fallback to the naive Attention implementation, which may result in higher GPU memory usage than shown in the table above.
|
100 |
+
|
101 |
+
We also tested the impact of quantization on model performance. The results show that the impact of quantization on model performance is within an acceptable range.
|
102 |
+
|
103 |
+
| Quantization | Accuracy (MMLU) | Accuracy (C-Eval dev) |
|
104 |
+
| ----- | ----- |-----------------------|
|
105 |
+
| BF16 | 45.47 | 53.57 |
|
106 |
+
| INT4 | 43.13 | 50.30 |
|
107 |
+
|
108 |
+
|
109 |
+
## ChatGLM2-6B Examples
|
110 |
+
|
111 |
+
Compared to the first-generation model, ChatGLM2-6B has made improvements in multiple dimensions. Below are some comparison examples. More possibilities with ChatGLM2-6B are waiting for you to explore and discover!
|
112 |
+
|
113 |
+
<details><summary><b>Mathematics and Logic</b></summary>
|
114 |
+
|
115 |
+

|
116 |
+
|
117 |
+
</details>
|
118 |
+
|
119 |
+
<details><summary><b>Knowledge Reasoning</b></summary>
|
120 |
+
|
121 |
+

|
122 |
+
|
123 |
+
</details>
|
124 |
+
|
125 |
+
<details><summary><b>Long Document Understanding</b></summary>
|
126 |
+
|
127 |
+

|
128 |
+
|
129 |
+
</details>
|
130 |
+
|
131 |
+
## Getting Started
|
132 |
+
### Environment Setup
|
133 |
+
|
134 |
+
Install dependencies with pip: `pip install -r requirements.txt`. It's recommended to use version `4.27.1` for the `transformers` library and use version 2.0 or higher for `torch` to achieve the best inference performance.
|
135 |
+
|
136 |
+
We provide a web page demo and a command line demo. You need to download this repository to use them:
|
137 |
+
|
138 |
+
```shell
|
139 |
+
git clone https://github.com/THUDM/ChatGLM2-6B
|
140 |
+
cd ChatGLM2-6B
|
141 |
+
```
|
142 |
+
|
143 |
+
### Usage
|
144 |
+
|
145 |
+
Generate dialogue with the following code:
|
146 |
+
|
147 |
+
```python
|
148 |
+
>>> from transformers import AutoTokenizer, AutoModel
|
149 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
|
150 |
+
>>> model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True, device='cuda').eval()
|
151 |
+
>>> response, history = model.chat(tokenizer, "你好", history=[])
|
152 |
+
>>> print(response)
|
153 |
+
你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。
|
154 |
+
>>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
|
155 |
+
>>> print(response)
|
156 |
+
晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
|
157 |
+
|
158 |
+
1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
|
159 |
+
2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
|
160 |
+
3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
|
161 |
+
4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
|
162 |
+
5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
|
163 |
+
6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
|
164 |
+
|
165 |
+
如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
|
166 |
+
```
|
167 |
+
The implementation of the model is still in development. If you want to fix the used model implementation to ensure compatibility, you can add the `revision="v1.0"` parameter in the `from_pretrained` call. `v1.0` is the latest version number. For a complete list of versions, see [Change Log](https://huggingface.co/THUDM/chatglm2-6b#change-log).
|
168 |
+
|
169 |
+
### Web Demo
|
170 |
+
|
171 |
+

|
172 |
+
|
173 |
+
Install Gradio `pip install gradio`,and run [web_demo.py](web_demo.py):
|
174 |
+
|
175 |
+
```shell
|
176 |
+
python web_demo.py
|
177 |
+
```
|
178 |
+
|
179 |
+
The program runs a web server and outputs the URL. Open the URL in the browser to use the web demo.
|
180 |
+
|
181 |
+
#### CLI Demo
|
182 |
+
|
183 |
+

|
184 |
+
|
185 |
+
Run [cli_demo.py](cli_demo.py) in the repo:
|
186 |
+
|
187 |
+
```shell
|
188 |
+
python cli_demo.py
|
189 |
+
```
|
190 |
+
|
191 |
+
The command runs an interactive program in the shell. Type your instruction in the shell and hit enter to generate the response. Type `clear` to clear the dialogue history and `stop` to terminate the program.
|
192 |
+
|
193 |
+
## API Deployment
|
194 |
+
First install the additional dependency `pip install fastapi uvicorn`. The run [api.py](api.py) in the repo.
|
195 |
+
```shell
|
196 |
+
python api.py
|
197 |
+
```
|
198 |
+
By default the api runs at the`8000`port of the local machine. You can call the API via
|
199 |
+
```shell
|
200 |
+
curl -X POST "http://127.0.0.1:8000" \
|
201 |
+
-H 'Content-Type: application/json' \
|
202 |
+
-d '{"prompt": "你好", "history": []}'
|
203 |
+
```
|
204 |
+
The returned value is
|
205 |
+
```shell
|
206 |
+
{
|
207 |
+
"response":"你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。",
|
208 |
+
"history":[["你好","你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。"]],
|
209 |
+
"status":200,
|
210 |
+
"time":"2023-03-23 21:38:40"
|
211 |
+
}
|
212 |
+
```
|
213 |
+
## Deployment
|
214 |
+
|
215 |
+
### Quantization
|
216 |
+
|
217 |
+
By default, the model parameters are loaded with FP16 precision, which require about 13GB of GPU memory. It your GPU memory is limited, you can try to load the model parameters with quantization:
|
218 |
+
|
219 |
+
```python
|
220 |
+
# hange according to your hardware. Only support 4/8 bit quantization now.
|
221 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).quantize(8).cuda()
|
222 |
+
```
|
223 |
+
|
224 |
+
Model quantization will bring some performance loss on datasets. But after testing, ChatGLM2-6B can still perform natural and smooth generation under 4-bit quantization.
|
225 |
+
|
226 |
+
### CPU Deployment
|
227 |
+
|
228 |
+
If your computer is not equipped with GPU, you can also conduct inference on CPU, but the inference speed is slow (and taking about 32GB of memory):
|
229 |
+
```python
|
230 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).float()
|
231 |
+
```
|
232 |
+
|
233 |
+
### Inference on Mac
|
234 |
+
|
235 |
+
For Macs (and MacBooks) with Apple Silicon, it is possible to use the MPS backend to run ChatGLM-6B on the GPU. First, you need to refer to Apple's [official instructions](https://developer.apple.com/metal/pytorch) to install PyTorch-Nightly. (The correct version number should be 2.1.0.dev2023xxxx, not 2.0.0).
|
236 |
+
|
237 |
+
Currently you must [load the model locally](README_en.md#load-the-model-locally) on MacOS. Change the code to load the model from your local path, and use the mps backend:
|
238 |
+
```python
|
239 |
+
model = AutoModel.from_pretrained("your local path", trust_remote_code=True).to('mps')
|
240 |
+
```
|
241 |
+
|
242 |
+
Loading a FP16 ChatGLM-6B model requires about 13GB of memory. Machines with less memory (such as a MacBook Pro with 16GB of memory) will use the virtual memory on the hard disk when there is insufficient free memory, resulting in a serious slowdown in inference speed.
|
243 |
+
|
244 |
+
## License
|
245 |
+
|
246 |
+
The code of this repository is licensed under [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0). The use of the ChatGLM2-6B model weights is subject to the [Model License](MODEL_LICENSE). ChatGLM2-6B weights are **completely open** for academic research, and **free commercial use** is also allowed after completing the [questionnaire](https://open.bigmodel.cn/mla/form).
|
247 |
+
|
248 |
+
## Citation
|
249 |
+
|
250 |
+
If you find our work useful, please consider citing the following papers. The technical report for ChatGLM2-6B will be out soon.
|
251 |
+
|
252 |
+
```
|
253 |
+
@article{zeng2022glm,
|
254 |
+
title={Glm-130b: An open bilingual pre-trained model},
|
255 |
+
author={Zeng, Aohan and Liu, Xiao and Du, Zhengxiao and Wang, Zihan and Lai, Hanyu and Ding, Ming and Yang, Zhuoyi and Xu, Yifan and Zheng, Wendi and Xia, Xiao and others},
|
256 |
+
journal={arXiv preprint arXiv:2210.02414},
|
257 |
+
year={2022}
|
258 |
+
}
|
259 |
+
```
|
260 |
+
```
|
261 |
+
@inproceedings{du2022glm,
|
262 |
+
title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
|
263 |
+
author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
|
264 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
|
265 |
+
pages={320--335},
|
266 |
+
year={2022}
|
267 |
+
}
|
268 |
+
```
|
Untitled.ipynb
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"id": "6abdc033-4875-4bfd-b2c4-feff3abc3c74",
|
7 |
+
"metadata": {},
|
8 |
+
"outputs": [
|
9 |
+
{
|
10 |
+
"name": "stdout",
|
11 |
+
"output_type": "stream",
|
12 |
+
"text": [
|
13 |
+
"Requirement already satisfied: huggingface_hub in /opt/conda/lib/python3.10/site-packages (0.19.4)\n",
|
14 |
+
"Requirement already satisfied: filelock in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (3.9.0)\n",
|
15 |
+
"Requirement already satisfied: fsspec>=2023.5.0 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (2023.10.0)\n",
|
16 |
+
"Requirement already satisfied: requests in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (2.31.0)\n",
|
17 |
+
"Requirement already satisfied: tqdm>=4.42.1 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (4.65.0)\n",
|
18 |
+
"Requirement already satisfied: pyyaml>=5.1 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (6.0.1)\n",
|
19 |
+
"Requirement already satisfied: typing-extensions>=3.7.4.3 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (4.8.0)\n",
|
20 |
+
"Requirement already satisfied: packaging>=20.9 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (23.1)\n",
|
21 |
+
"Requirement already satisfied: charset-normalizer<4,>=2 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (2.0.4)\n",
|
22 |
+
"Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (3.4)\n",
|
23 |
+
"Requirement already satisfied: urllib3<3,>=1.21.1 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (1.26.18)\n",
|
24 |
+
"Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (2023.7.22)\n",
|
25 |
+
"\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
|
26 |
+
"\u001b[0mNote: you may need to restart the kernel to use updated packages.\n"
|
27 |
+
]
|
28 |
+
}
|
29 |
+
],
|
30 |
+
"source": [
|
31 |
+
"pip install huggingface_hub"
|
32 |
+
]
|
33 |
+
},
|
34 |
+
{
|
35 |
+
"cell_type": "code",
|
36 |
+
"execution_count": 2,
|
37 |
+
"id": "c9e06a07-c5ef-4b49-bbb2-713c52e00487",
|
38 |
+
"metadata": {},
|
39 |
+
"outputs": [
|
40 |
+
{
|
41 |
+
"data": {
|
42 |
+
"application/vnd.jupyter.widget-view+json": {
|
43 |
+
"model_id": "131130281e42481a8107db2a5d76e19a",
|
44 |
+
"version_major": 2,
|
45 |
+
"version_minor": 0
|
46 |
+
},
|
47 |
+
"text/plain": [
|
48 |
+
"VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
|
49 |
+
]
|
50 |
+
},
|
51 |
+
"metadata": {},
|
52 |
+
"output_type": "display_data"
|
53 |
+
}
|
54 |
+
],
|
55 |
+
"source": [
|
56 |
+
"from huggingface_hub import login\n",
|
57 |
+
"login()"
|
58 |
+
]
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"cell_type": "code",
|
62 |
+
"execution_count": 4,
|
63 |
+
"id": "ef7a01d7-0b37-4f76-a763-a62d426e73e7",
|
64 |
+
"metadata": {},
|
65 |
+
"outputs": [
|
66 |
+
{
|
67 |
+
"name": "stdout",
|
68 |
+
"output_type": "stream",
|
69 |
+
"text": [
|
70 |
+
"/workspace/ChatGLM2-6B\n"
|
71 |
+
]
|
72 |
+
}
|
73 |
+
],
|
74 |
+
"source": [
|
75 |
+
"cd ChatGLM2-6B"
|
76 |
+
]
|
77 |
+
},
|
78 |
+
{
|
79 |
+
"cell_type": "code",
|
80 |
+
"execution_count": null,
|
81 |
+
"id": "22336bac-aca5-4243-ba17-8b6b51f15a38",
|
82 |
+
"metadata": {},
|
83 |
+
"outputs": [
|
84 |
+
{
|
85 |
+
"data": {
|
86 |
+
"application/vnd.jupyter.widget-view+json": {
|
87 |
+
"model_id": "b5b6d5c4d5c547d0a596e151ffdb1598",
|
88 |
+
"version_major": 2,
|
89 |
+
"version_minor": 0
|
90 |
+
},
|
91 |
+
"text/plain": [
|
92 |
+
"Upload 23 LFS files: 0%| | 0/23 [00:00<?, ?it/s]"
|
93 |
+
]
|
94 |
+
},
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "display_data"
|
97 |
+
},
|
98 |
+
{
|
99 |
+
"data": {
|
100 |
+
"application/vnd.jupyter.widget-view+json": {
|
101 |
+
"model_id": "72dfaad5b4d4479480cade4126d1538f",
|
102 |
+
"version_major": 2,
|
103 |
+
"version_minor": 0
|
104 |
+
},
|
105 |
+
"text/plain": [
|
106 |
+
"pytorch_model-00001-of-00007.bin: 0%| | 0.00/1.83G [00:00<?, ?B/s]"
|
107 |
+
]
|
108 |
+
},
|
109 |
+
"metadata": {},
|
110 |
+
"output_type": "display_data"
|
111 |
+
},
|
112 |
+
{
|
113 |
+
"data": {
|
114 |
+
"application/vnd.jupyter.widget-view+json": {
|
115 |
+
"model_id": "262a4ad0602d49aebd483a19bfdf2a1d",
|
116 |
+
"version_major": 2,
|
117 |
+
"version_minor": 0
|
118 |
+
},
|
119 |
+
"text/plain": [
|
120 |
+
"pytorch_model-00003-of-00007.bin: 0%| | 0.00/1.93G [00:00<?, ?B/s]"
|
121 |
+
]
|
122 |
+
},
|
123 |
+
"metadata": {},
|
124 |
+
"output_type": "display_data"
|
125 |
+
},
|
126 |
+
{
|
127 |
+
"data": {
|
128 |
+
"application/vnd.jupyter.widget-view+json": {
|
129 |
+
"model_id": "2e1fca9c622c4e64b5c8d1330198fb7e",
|
130 |
+
"version_major": 2,
|
131 |
+
"version_minor": 0
|
132 |
+
},
|
133 |
+
"text/plain": [
|
134 |
+
"pytorch_model-00002-of-00007.bin: 0%| | 0.00/1.97G [00:00<?, ?B/s]"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"metadata": {},
|
138 |
+
"output_type": "display_data"
|
139 |
+
},
|
140 |
+
{
|
141 |
+
"data": {
|
142 |
+
"application/vnd.jupyter.widget-view+json": {
|
143 |
+
"model_id": "5f1ed2ceaf7346deb2d93cd97e64c4ae",
|
144 |
+
"version_major": 2,
|
145 |
+
"version_minor": 0
|
146 |
+
},
|
147 |
+
"text/plain": [
|
148 |
+
"pytorch_model-00004-of-00007.bin: 0%| | 0.00/1.82G [00:00<?, ?B/s]"
|
149 |
+
]
|
150 |
+
},
|
151 |
+
"metadata": {},
|
152 |
+
"output_type": "display_data"
|
153 |
+
},
|
154 |
+
{
|
155 |
+
"data": {
|
156 |
+
"application/vnd.jupyter.widget-view+json": {
|
157 |
+
"model_id": "c51bab110f174dd4b2e87503aca114fe",
|
158 |
+
"version_major": 2,
|
159 |
+
"version_minor": 0
|
160 |
+
},
|
161 |
+
"text/plain": [
|
162 |
+
"pytorch_model-00005-of-00007.bin: 0%| | 0.00/1.97G [00:00<?, ?B/s]"
|
163 |
+
]
|
164 |
+
},
|
165 |
+
"metadata": {},
|
166 |
+
"output_type": "display_data"
|
167 |
+
}
|
168 |
+
],
|
169 |
+
"source": [
|
170 |
+
"from huggingface_hub import HfApi\n",
|
171 |
+
"api = HfApi()\n",
|
172 |
+
"\n",
|
173 |
+
"api.upload_folder(\n",
|
174 |
+
" folder_path=\"\",\n",
|
175 |
+
" repo_id=\"kevinwang676/ChatGLM2-fine-tuning\",\n",
|
176 |
+
" repo_type=\"space\",\n",
|
177 |
+
")"
|
178 |
+
]
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"cell_type": "code",
|
182 |
+
"execution_count": null,
|
183 |
+
"id": "0de28ee1-a77e-47e4-84f5-9a2d259a8493",
|
184 |
+
"metadata": {},
|
185 |
+
"outputs": [],
|
186 |
+
"source": []
|
187 |
+
}
|
188 |
+
],
|
189 |
+
"metadata": {
|
190 |
+
"kernelspec": {
|
191 |
+
"display_name": "Python 3 (ipykernel)",
|
192 |
+
"language": "python",
|
193 |
+
"name": "python3"
|
194 |
+
},
|
195 |
+
"language_info": {
|
196 |
+
"codemirror_mode": {
|
197 |
+
"name": "ipython",
|
198 |
+
"version": 3
|
199 |
+
},
|
200 |
+
"file_extension": ".py",
|
201 |
+
"mimetype": "text/x-python",
|
202 |
+
"name": "python",
|
203 |
+
"nbconvert_exporter": "python",
|
204 |
+
"pygments_lexer": "ipython3",
|
205 |
+
"version": "3.10.13"
|
206 |
+
}
|
207 |
+
},
|
208 |
+
"nbformat": 4,
|
209 |
+
"nbformat_minor": 5
|
210 |
+
}
|
api.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Request
|
2 |
+
from transformers import AutoTokenizer, AutoModel
|
3 |
+
import uvicorn, json, datetime
|
4 |
+
import torch
|
5 |
+
|
6 |
+
DEVICE = "cuda"
|
7 |
+
DEVICE_ID = "0"
|
8 |
+
CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE
|
9 |
+
|
10 |
+
|
11 |
+
def torch_gc():
|
12 |
+
if torch.cuda.is_available():
|
13 |
+
with torch.cuda.device(CUDA_DEVICE):
|
14 |
+
torch.cuda.empty_cache()
|
15 |
+
torch.cuda.ipc_collect()
|
16 |
+
|
17 |
+
|
18 |
+
app = FastAPI()
|
19 |
+
|
20 |
+
|
21 |
+
@app.post("/")
|
22 |
+
async def create_item(request: Request):
|
23 |
+
global model, tokenizer
|
24 |
+
json_post_raw = await request.json()
|
25 |
+
json_post = json.dumps(json_post_raw)
|
26 |
+
json_post_list = json.loads(json_post)
|
27 |
+
prompt = json_post_list.get('prompt')
|
28 |
+
history = json_post_list.get('history')
|
29 |
+
max_length = json_post_list.get('max_length')
|
30 |
+
top_p = json_post_list.get('top_p')
|
31 |
+
temperature = json_post_list.get('temperature')
|
32 |
+
response, history = model.chat(tokenizer,
|
33 |
+
prompt,
|
34 |
+
history=history,
|
35 |
+
max_length=max_length if max_length else 2048,
|
36 |
+
top_p=top_p if top_p else 0.7,
|
37 |
+
temperature=temperature if temperature else 0.95)
|
38 |
+
now = datetime.datetime.now()
|
39 |
+
time = now.strftime("%Y-%m-%d %H:%M:%S")
|
40 |
+
answer = {
|
41 |
+
"response": response,
|
42 |
+
"history": history,
|
43 |
+
"status": 200,
|
44 |
+
"time": time
|
45 |
+
}
|
46 |
+
log = "[" + time + "] " + '", prompt:"' + prompt + '", response:"' + repr(response) + '"'
|
47 |
+
print(log)
|
48 |
+
torch_gc()
|
49 |
+
return answer
|
50 |
+
|
51 |
+
|
52 |
+
if __name__ == '__main__':
|
53 |
+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
|
54 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda()
|
55 |
+
# 多显卡支持,使用下面三行代替上面两行,将num_gpus改为你实际的显卡数量
|
56 |
+
# model_path = "THUDM/chatglm2-6b"
|
57 |
+
# tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
58 |
+
# model = load_model_on_gpus(model_path, num_gpus=2)
|
59 |
+
model.eval()
|
60 |
+
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)
|
chatglm2-6b/.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
chatglm2-6b/MODEL_LICENSE
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The ChatGLM2-6B License
|
2 |
+
|
3 |
+
1. 定义
|
4 |
+
|
5 |
+
“许可方”是指分发其软件的 ChatGLM2-6B 模型团队。
|
6 |
+
|
7 |
+
“软件”是指根据本许可提供的 ChatGLM2-6B 模型参数。
|
8 |
+
|
9 |
+
2. 许可授予
|
10 |
+
|
11 |
+
根据本许可的条款和条件,许可方特此授予您非排他性、全球性、不可转让、不可再许可、可撤销、免版税的版权许可。
|
12 |
+
|
13 |
+
上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
|
14 |
+
|
15 |
+
3.限制
|
16 |
+
|
17 |
+
您不得出于任何军事或非法目的使用、复制、修改、合并、发布、分发、复制或创建本软件的全部或部分衍生作品。
|
18 |
+
|
19 |
+
您不得利用本软件从事任何危害国家安全和国家统一、危害社会公共利益、侵犯人身权益的行为。
|
20 |
+
|
21 |
+
4.免责声明
|
22 |
+
|
23 |
+
本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权性的保证。 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,由软件或软件的使用或其他交易引起、由软件引起或与之相关 软件。
|
24 |
+
|
25 |
+
5. 责任限制
|
26 |
+
|
27 |
+
除适用法律禁止的范围外,在任何情况下且根据任何法律理论,无论是基于侵权行为、疏忽、合同、责任或其他原因,任何许可方均不对您承担任何直接、间接、特殊、偶然、示范性、 或间接损害,或任何其他商业损失,即使许可人已被告知此类损害的可能性。
|
28 |
+
|
29 |
+
6.争议解决
|
30 |
+
|
31 |
+
本许可受中华人民共和国法律管辖并按其解释。 因本许可引起的或与本许可有关的任何争议应提交北京市海淀区人民法院。
|
32 |
+
|
33 |
+
请注意,许可证可能会更新到更全面的版本。 有关许可和版权的任何问题,请通过 [email protected] 与我们联系。
|
34 |
+
|
35 |
+
1. Definitions
|
36 |
+
|
37 |
+
“Licensor” means the ChatGLM2-6B Model Team that distributes its Software.
|
38 |
+
|
39 |
+
“Software” means the ChatGLM2-6B model parameters made available under this license.
|
40 |
+
|
41 |
+
2. License Grant
|
42 |
+
|
43 |
+
Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software.
|
44 |
+
|
45 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
46 |
+
|
47 |
+
3. Restriction
|
48 |
+
|
49 |
+
You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any military, or illegal purposes.
|
50 |
+
|
51 |
+
You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
|
52 |
+
|
53 |
+
4. Disclaimer
|
54 |
+
|
55 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
56 |
+
|
57 |
+
5. Limitation of Liability
|
58 |
+
|
59 |
+
EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
60 |
+
|
61 |
+
6. Dispute Resolution
|
62 |
+
|
63 |
+
This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
|
64 |
+
|
65 |
+
Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at [email protected].
|
chatglm2-6b/README.md
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language:
|
3 |
+
- zh
|
4 |
+
- en
|
5 |
+
tags:
|
6 |
+
- glm
|
7 |
+
- chatglm
|
8 |
+
- thudm
|
9 |
+
---
|
10 |
+
# ChatGLM2-6B
|
11 |
+
<p align="center">
|
12 |
+
💻 <a href="https://github.com/THUDM/ChatGLM2-6B" target="_blank">Github Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
|
13 |
+
</p>
|
14 |
+
|
15 |
+
<p align="center">
|
16 |
+
👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1y7pqoloy-9b1g6T6JjA8J0KxvUjbwJw" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
|
17 |
+
</p>
|
18 |
+
<p align="center">
|
19 |
+
📍Experience the larger-scale ChatGLM model at <a href="https://www.chatglm.cn">chatglm.cn</a>
|
20 |
+
</p>
|
21 |
+
|
22 |
+
## 介绍
|
23 |
+
ChatGLM**2**-6B 是开源中英双语对话模型 [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B) 的第二代版本,在保留了初代模型对话流畅、部署门槛较低等众多优秀特性的基础之上,ChatGLM**2**-6B 引入了如下新特性:
|
24 |
+
|
25 |
+
1. **更强大的性能**:基于 ChatGLM 初代模型的开发经验,我们全面升级了 ChatGLM2-6B 的基座模型。ChatGLM2-6B 使用了 [GLM](https://github.com/THUDM/GLM) 的混合目标函数,经过了 1.4T 中英标识符的预训练与人类偏好对齐训练,[评测结果](#评测结果)显示,相比于初代模型,ChatGLM2-6B 在 MMLU(+23%)、CEval(+33%)、GSM8K(+571%) 、BBH(+60%)等数据集上的性能取得了大幅度的提升,在同尺寸开源模型中具有较强的竞争力。
|
26 |
+
2. **更长的上下文**:基于 [FlashAttention](https://github.com/HazyResearch/flash-attention) 技术,我们将基座模型的上下文长度(Context Length)由 ChatGLM-6B 的 2K 扩展到了 32K,并在对话阶段使用 8K 的上下文长度训练,允许更多轮次的对话。但当前版本的 ChatGLM2-6B 对单轮超长文档的理解能力有限,我们会在后续迭代升级中着重进行优化。
|
27 |
+
3. **更高效的推理**:基于 [Multi-Query Attention](http://arxiv.org/abs/1911.02150) 技术,ChatGLM2-6B 有更高效的推理速度和更低的显存占用:在官方的模型实现下,推理速度相比初代提升了 42%,INT4 量化下,6G 显存支持的对话长度由 1K 提升到了 8K。
|
28 |
+
4. **更开放的协议**:ChatGLM2-6B 权重对学术研究**完全开放**,在填写[问卷](https://open.bigmodel.cn/mla/form)进行登记后**亦允许免费商业使用**。
|
29 |
+
|
30 |
+
ChatGLM**2**-6B is the second-generation version of the open-source bilingual (Chinese-English) chat model [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B). It retains the smooth conversation flow and low deployment threshold of the first-generation model, while introducing the following new features:
|
31 |
+
|
32 |
+
1. **Stronger Performance**: Based on the development experience of the first-generation ChatGLM model, we have fully upgraded the base model of ChatGLM2-6B. ChatGLM2-6B uses the hybrid objective function of [GLM](https://github.com/THUDM/GLM), and has undergone pre-training with 1.4T bilingual tokens and human preference alignment training. The [evaluation results](README.md#evaluation-results) show that, compared to the first-generation model, ChatGLM2-6B has achieved substantial improvements in performance on datasets like MMLU (+23%), CEval (+33%), GSM8K (+571%), BBH (+60%), showing strong competitiveness among models of the same size.
|
33 |
+
2. **Longer Context**: Based on [FlashAttention](https://github.com/HazyResearch/flash-attention) technique, we have extended the context length of the base model from 2K in ChatGLM-6B to 32K, and trained with a context length of 8K during the dialogue alignment, allowing for more rounds of dialogue. However, the current version of ChatGLM2-6B has limited understanding of single-round ultra-long documents, which we will focus on optimizing in future iterations.
|
34 |
+
3. **More Efficient Inference**: Based on [Multi-Query Attention](http://arxiv.org/abs/1911.02150) technique, ChatGLM2-6B has more efficient inference speed and lower GPU memory usage: under the official implementation, the inference speed has increased by 42% compared to the first generation; under INT4 quantization, the dialogue length supported by 6G GPU memory has increased from 1K to 8K.
|
35 |
+
4. **More Open License**: ChatGLM2-6B weights are **completely open** for academic research, and **free commercial use** is also allowed after completing the [questionnaire](https://open.bigmodel.cn/mla/form).
|
36 |
+
|
37 |
+
## 软件依赖
|
38 |
+
|
39 |
+
```shell
|
40 |
+
pip install protobuf transformers==4.30.2 cpm_kernels torch>=2.0 gradio mdtex2html sentencepiece accelerate
|
41 |
+
```
|
42 |
+
|
43 |
+
## 代码调用
|
44 |
+
|
45 |
+
可以通过如下代码调用 ChatGLM-6B 模型来生成对话:
|
46 |
+
|
47 |
+
```ipython
|
48 |
+
>>> from transformers import AutoTokenizer, AutoModel
|
49 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
|
50 |
+
>>> model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).half().cuda()
|
51 |
+
>>> model = model.eval()
|
52 |
+
>>> response, history = model.chat(tokenizer, "你好", history=[])
|
53 |
+
>>> print(response)
|
54 |
+
你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
|
55 |
+
>>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
|
56 |
+
>>> print(response)
|
57 |
+
晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
|
58 |
+
|
59 |
+
1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
|
60 |
+
2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
|
61 |
+
3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
|
62 |
+
4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
|
63 |
+
5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
|
64 |
+
6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
|
65 |
+
|
66 |
+
如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
|
67 |
+
```
|
68 |
+
|
69 |
+
关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM2-6B)。
|
70 |
+
|
71 |
+
For more instructions, including how to run CLI and web demos, and model quantization, please refer to our [Github Repo](https://github.com/THUDM/ChatGLM2-6B).
|
72 |
+
|
73 |
+
## Change Log
|
74 |
+
* v1.0
|
75 |
+
|
76 |
+
## 协议
|
77 |
+
|
78 |
+
本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM2-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
|
79 |
+
|
80 |
+
## 引用
|
81 |
+
|
82 |
+
如果你觉得我们的工作有帮助的话,请考虑引用下列论文,ChatGLM2-6B 的论文会在近期公布,敬请期待~
|
83 |
+
|
84 |
+
```
|
85 |
+
@article{zeng2022glm,
|
86 |
+
title={Glm-130b: An open bilingual pre-trained model},
|
87 |
+
author={Zeng, Aohan and Liu, Xiao and Du, Zhengxiao and Wang, Zihan and Lai, Hanyu and Ding, Ming and Yang, Zhuoyi and Xu, Yifan and Zheng, Wendi and Xia, Xiao and others},
|
88 |
+
journal={arXiv preprint arXiv:2210.02414},
|
89 |
+
year={2022}
|
90 |
+
}
|
91 |
+
```
|
92 |
+
```
|
93 |
+
@inproceedings{du2022glm,
|
94 |
+
title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
|
95 |
+
author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
|
96 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
|
97 |
+
pages={320--335},
|
98 |
+
year={2022}
|
99 |
+
}
|
100 |
+
```
|
chatglm2-6b/config.json
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "THUDM/chatglm2-6b",
|
3 |
+
"model_type": "chatglm",
|
4 |
+
"architectures": [
|
5 |
+
"ChatGLMModel"
|
6 |
+
],
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
9 |
+
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
10 |
+
"AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
11 |
+
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
12 |
+
"AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
|
13 |
+
},
|
14 |
+
"add_bias_linear": false,
|
15 |
+
"add_qkv_bias": true,
|
16 |
+
"apply_query_key_layer_scaling": true,
|
17 |
+
"apply_residual_connection_post_layernorm": false,
|
18 |
+
"attention_dropout": 0.0,
|
19 |
+
"attention_softmax_in_fp32": true,
|
20 |
+
"bias_dropout_fusion": true,
|
21 |
+
"ffn_hidden_size": 13696,
|
22 |
+
"fp32_residual_connection": false,
|
23 |
+
"hidden_dropout": 0.0,
|
24 |
+
"hidden_size": 4096,
|
25 |
+
"kv_channels": 128,
|
26 |
+
"layernorm_epsilon": 1e-05,
|
27 |
+
"multi_query_attention": true,
|
28 |
+
"multi_query_group_num": 2,
|
29 |
+
"num_attention_heads": 32,
|
30 |
+
"num_layers": 28,
|
31 |
+
"original_rope": true,
|
32 |
+
"padded_vocab_size": 65024,
|
33 |
+
"post_layer_norm": true,
|
34 |
+
"rmsnorm": true,
|
35 |
+
"seq_length": 32768,
|
36 |
+
"use_cache": true,
|
37 |
+
"torch_dtype": "float16",
|
38 |
+
"transformers_version": "4.27.1",
|
39 |
+
"tie_word_embeddings": false,
|
40 |
+
"eos_token_id": 2,
|
41 |
+
"pad_token_id": 0
|
42 |
+
}
|
chatglm2-6b/configuration_chatglm.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class ChatGLMConfig(PretrainedConfig):
|
5 |
+
model_type = "chatglm"
|
6 |
+
def __init__(
|
7 |
+
self,
|
8 |
+
num_layers=28,
|
9 |
+
padded_vocab_size=65024,
|
10 |
+
hidden_size=4096,
|
11 |
+
ffn_hidden_size=13696,
|
12 |
+
kv_channels=128,
|
13 |
+
num_attention_heads=32,
|
14 |
+
seq_length=2048,
|
15 |
+
hidden_dropout=0.0,
|
16 |
+
classifier_dropout=None,
|
17 |
+
attention_dropout=0.0,
|
18 |
+
layernorm_epsilon=1e-5,
|
19 |
+
rmsnorm=True,
|
20 |
+
apply_residual_connection_post_layernorm=False,
|
21 |
+
post_layer_norm=True,
|
22 |
+
add_bias_linear=False,
|
23 |
+
add_qkv_bias=False,
|
24 |
+
bias_dropout_fusion=True,
|
25 |
+
multi_query_attention=False,
|
26 |
+
multi_query_group_num=1,
|
27 |
+
apply_query_key_layer_scaling=True,
|
28 |
+
attention_softmax_in_fp32=True,
|
29 |
+
fp32_residual_connection=False,
|
30 |
+
quantization_bit=0,
|
31 |
+
pre_seq_len=None,
|
32 |
+
prefix_projection=False,
|
33 |
+
**kwargs
|
34 |
+
):
|
35 |
+
self.num_layers = num_layers
|
36 |
+
self.vocab_size = padded_vocab_size
|
37 |
+
self.padded_vocab_size = padded_vocab_size
|
38 |
+
self.hidden_size = hidden_size
|
39 |
+
self.ffn_hidden_size = ffn_hidden_size
|
40 |
+
self.kv_channels = kv_channels
|
41 |
+
self.num_attention_heads = num_attention_heads
|
42 |
+
self.seq_length = seq_length
|
43 |
+
self.hidden_dropout = hidden_dropout
|
44 |
+
self.classifier_dropout = classifier_dropout
|
45 |
+
self.attention_dropout = attention_dropout
|
46 |
+
self.layernorm_epsilon = layernorm_epsilon
|
47 |
+
self.rmsnorm = rmsnorm
|
48 |
+
self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
|
49 |
+
self.post_layer_norm = post_layer_norm
|
50 |
+
self.add_bias_linear = add_bias_linear
|
51 |
+
self.add_qkv_bias = add_qkv_bias
|
52 |
+
self.bias_dropout_fusion = bias_dropout_fusion
|
53 |
+
self.multi_query_attention = multi_query_attention
|
54 |
+
self.multi_query_group_num = multi_query_group_num
|
55 |
+
self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
|
56 |
+
self.attention_softmax_in_fp32 = attention_softmax_in_fp32
|
57 |
+
self.fp32_residual_connection = fp32_residual_connection
|
58 |
+
self.quantization_bit = quantization_bit
|
59 |
+
self.pre_seq_len = pre_seq_len
|
60 |
+
self.prefix_projection = prefix_projection
|
61 |
+
super().__init__(**kwargs)
|
chatglm2-6b/modeling_chatglm.py
ADDED
@@ -0,0 +1,1285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" PyTorch ChatGLM model. """
|
2 |
+
|
3 |
+
import math
|
4 |
+
import copy
|
5 |
+
import warnings
|
6 |
+
import re
|
7 |
+
import sys
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.utils.checkpoint
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from torch import nn
|
13 |
+
from torch.nn import CrossEntropyLoss, LayerNorm
|
14 |
+
from torch.nn import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
|
15 |
+
from torch.nn.utils import skip_init
|
16 |
+
from typing import Optional, Tuple, Union, List, Callable, Dict, Any
|
17 |
+
|
18 |
+
from transformers.modeling_outputs import (
|
19 |
+
BaseModelOutputWithPast,
|
20 |
+
CausalLMOutputWithPast,
|
21 |
+
SequenceClassifierOutputWithPast,
|
22 |
+
)
|
23 |
+
from transformers.modeling_utils import PreTrainedModel
|
24 |
+
from transformers.utils import logging
|
25 |
+
from transformers.generation.logits_process import LogitsProcessor
|
26 |
+
from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
|
27 |
+
|
28 |
+
from .configuration_chatglm import ChatGLMConfig
|
29 |
+
|
30 |
+
# flags required to enable jit fusion kernels
|
31 |
+
|
32 |
+
if sys.platform != 'darwin':
|
33 |
+
torch._C._jit_set_profiling_mode(False)
|
34 |
+
torch._C._jit_set_profiling_executor(False)
|
35 |
+
torch._C._jit_override_can_fuse_on_cpu(True)
|
36 |
+
torch._C._jit_override_can_fuse_on_gpu(True)
|
37 |
+
|
38 |
+
logger = logging.get_logger(__name__)
|
39 |
+
|
40 |
+
_CHECKPOINT_FOR_DOC = "THUDM/ChatGLM2-6B"
|
41 |
+
_CONFIG_FOR_DOC = "ChatGLM6BConfig"
|
42 |
+
|
43 |
+
CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
44 |
+
"THUDM/chatglm2-6b",
|
45 |
+
# See all ChatGLM models at https://huggingface.co/models?filter=chatglm
|
46 |
+
]
|
47 |
+
|
48 |
+
|
49 |
+
def default_init(cls, *args, **kwargs):
|
50 |
+
return cls(*args, **kwargs)
|
51 |
+
|
52 |
+
|
53 |
+
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
54 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
55 |
+
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
56 |
+
scores.zero_()
|
57 |
+
scores[..., 5] = 5e4
|
58 |
+
return scores
|
59 |
+
|
60 |
+
|
61 |
+
class PrefixEncoder(torch.nn.Module):
|
62 |
+
"""
|
63 |
+
The torch.nn model to encode the prefix
|
64 |
+
Input shape: (batch-size, prefix-length)
|
65 |
+
Output shape: (batch-size, prefix-length, 2*layers*hidden)
|
66 |
+
"""
|
67 |
+
|
68 |
+
def __init__(self, config: ChatGLMConfig):
|
69 |
+
super().__init__()
|
70 |
+
self.prefix_projection = config.prefix_projection
|
71 |
+
if self.prefix_projection:
|
72 |
+
# Use a two-layer MLP to encode the prefix
|
73 |
+
kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
|
74 |
+
self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
|
75 |
+
self.trans = torch.nn.Sequential(
|
76 |
+
torch.nn.Linear(kv_size, config.hidden_size),
|
77 |
+
torch.nn.Tanh(),
|
78 |
+
torch.nn.Linear(config.hidden_size, kv_size)
|
79 |
+
)
|
80 |
+
else:
|
81 |
+
self.embedding = torch.nn.Embedding(config.pre_seq_len,
|
82 |
+
config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
|
83 |
+
|
84 |
+
def forward(self, prefix: torch.Tensor):
|
85 |
+
if self.prefix_projection:
|
86 |
+
prefix_tokens = self.embedding(prefix)
|
87 |
+
past_key_values = self.trans(prefix_tokens)
|
88 |
+
else:
|
89 |
+
past_key_values = self.embedding(prefix)
|
90 |
+
return past_key_values
|
91 |
+
|
92 |
+
|
93 |
+
def split_tensor_along_last_dim(
|
94 |
+
tensor: torch.Tensor,
|
95 |
+
num_partitions: int,
|
96 |
+
contiguous_split_chunks: bool = False,
|
97 |
+
) -> List[torch.Tensor]:
|
98 |
+
"""Split a tensor along its last dimension.
|
99 |
+
|
100 |
+
Arguments:
|
101 |
+
tensor: input tensor.
|
102 |
+
num_partitions: number of partitions to split the tensor
|
103 |
+
contiguous_split_chunks: If True, make each chunk contiguous
|
104 |
+
in memory.
|
105 |
+
|
106 |
+
Returns:
|
107 |
+
A list of Tensors
|
108 |
+
"""
|
109 |
+
# Get the size and dimension.
|
110 |
+
last_dim = tensor.dim() - 1
|
111 |
+
last_dim_size = tensor.size()[last_dim] // num_partitions
|
112 |
+
# Split.
|
113 |
+
tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
|
114 |
+
# Note: torch.split does not create contiguous tensors by default.
|
115 |
+
if contiguous_split_chunks:
|
116 |
+
return tuple(chunk.contiguous() for chunk in tensor_list)
|
117 |
+
|
118 |
+
return tensor_list
|
119 |
+
|
120 |
+
|
121 |
+
class RotaryEmbedding(nn.Module):
|
122 |
+
def __init__(self, dim, original_impl=False, device=None, dtype=None):
|
123 |
+
super().__init__()
|
124 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
|
125 |
+
self.register_buffer("inv_freq", inv_freq)
|
126 |
+
self.dim = dim
|
127 |
+
self.original_impl = original_impl
|
128 |
+
|
129 |
+
def forward_impl(
|
130 |
+
self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
|
131 |
+
):
|
132 |
+
"""Enhanced Transformer with Rotary Position Embedding.
|
133 |
+
|
134 |
+
Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
|
135 |
+
transformers/rope/__init__.py. MIT License:
|
136 |
+
https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
|
137 |
+
"""
|
138 |
+
# $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
|
139 |
+
theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=dtype, device=device) / n_elem))
|
140 |
+
|
141 |
+
# Create position indexes `[0, 1, ..., seq_len - 1]`
|
142 |
+
seq_idx = torch.arange(seq_len, dtype=dtype, device=device)
|
143 |
+
|
144 |
+
# Calculate the product of position index and $\theta_i$
|
145 |
+
idx_theta = torch.outer(seq_idx, theta).float()
|
146 |
+
|
147 |
+
cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
|
148 |
+
|
149 |
+
# this is to mimic the behaviour of complex32, else we will get different results
|
150 |
+
if dtype in (torch.float16, torch.bfloat16, torch.int8):
|
151 |
+
cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
|
152 |
+
return cache
|
153 |
+
|
154 |
+
def forward(self, max_seq_len, offset=0):
|
155 |
+
return self.forward_impl(
|
156 |
+
max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
|
157 |
+
)
|
158 |
+
|
159 |
+
|
160 |
+
@torch.jit.script
|
161 |
+
def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
|
162 |
+
# x: [sq, b, np, hn]
|
163 |
+
sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
|
164 |
+
rot_dim = rope_cache.shape[-2] * 2
|
165 |
+
x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
|
166 |
+
# truncate to support variable sizes
|
167 |
+
rope_cache = rope_cache[:sq]
|
168 |
+
xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
|
169 |
+
rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
|
170 |
+
x_out2 = torch.stack(
|
171 |
+
[
|
172 |
+
xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
|
173 |
+
xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
|
174 |
+
],
|
175 |
+
-1,
|
176 |
+
)
|
177 |
+
x_out2 = x_out2.flatten(3)
|
178 |
+
return torch.cat((x_out2, x_pass), dim=-1)
|
179 |
+
|
180 |
+
|
181 |
+
class RMSNorm(torch.nn.Module):
|
182 |
+
def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
|
183 |
+
super().__init__()
|
184 |
+
self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
|
185 |
+
self.eps = eps
|
186 |
+
|
187 |
+
def forward(self, hidden_states: torch.Tensor):
|
188 |
+
input_dtype = hidden_states.dtype
|
189 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
190 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
|
191 |
+
|
192 |
+
return (self.weight * hidden_states).to(input_dtype)
|
193 |
+
|
194 |
+
|
195 |
+
class CoreAttention(torch.nn.Module):
|
196 |
+
def __init__(self, config: ChatGLMConfig, layer_number):
|
197 |
+
super(CoreAttention, self).__init__()
|
198 |
+
|
199 |
+
self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
|
200 |
+
self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
|
201 |
+
if self.apply_query_key_layer_scaling:
|
202 |
+
self.attention_softmax_in_fp32 = True
|
203 |
+
self.layer_number = max(1, layer_number)
|
204 |
+
|
205 |
+
projection_size = config.kv_channels * config.num_attention_heads
|
206 |
+
|
207 |
+
# Per attention head and per partition values.
|
208 |
+
self.hidden_size_per_partition = projection_size
|
209 |
+
self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
|
210 |
+
self.num_attention_heads_per_partition = config.num_attention_heads
|
211 |
+
|
212 |
+
coeff = None
|
213 |
+
self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
|
214 |
+
if self.apply_query_key_layer_scaling:
|
215 |
+
coeff = self.layer_number
|
216 |
+
self.norm_factor *= coeff
|
217 |
+
self.coeff = coeff
|
218 |
+
|
219 |
+
self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
|
220 |
+
|
221 |
+
def forward(self, query_layer, key_layer, value_layer, attention_mask):
|
222 |
+
pytorch_major_version = int(torch.__version__.split('.')[0])
|
223 |
+
if pytorch_major_version >= 2:
|
224 |
+
query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
|
225 |
+
if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
|
226 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
|
227 |
+
is_causal=True)
|
228 |
+
else:
|
229 |
+
if attention_mask is not None:
|
230 |
+
attention_mask = ~attention_mask
|
231 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
|
232 |
+
attention_mask)
|
233 |
+
context_layer = context_layer.permute(2, 0, 1, 3)
|
234 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
|
235 |
+
context_layer = context_layer.reshape(*new_context_layer_shape)
|
236 |
+
else:
|
237 |
+
# Raw attention scores
|
238 |
+
|
239 |
+
# [b, np, sq, sk]
|
240 |
+
output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
|
241 |
+
|
242 |
+
# [sq, b, np, hn] -> [sq, b * np, hn]
|
243 |
+
query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
|
244 |
+
# [sk, b, np, hn] -> [sk, b * np, hn]
|
245 |
+
key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
|
246 |
+
|
247 |
+
# preallocting input tensor: [b * np, sq, sk]
|
248 |
+
matmul_input_buffer = torch.empty(
|
249 |
+
output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
|
250 |
+
device=query_layer.device
|
251 |
+
)
|
252 |
+
|
253 |
+
# Raw attention scores. [b * np, sq, sk]
|
254 |
+
matmul_result = torch.baddbmm(
|
255 |
+
matmul_input_buffer,
|
256 |
+
query_layer.transpose(0, 1), # [b * np, sq, hn]
|
257 |
+
key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
|
258 |
+
beta=0.0,
|
259 |
+
alpha=(1.0 / self.norm_factor),
|
260 |
+
)
|
261 |
+
|
262 |
+
# change view to [b, np, sq, sk]
|
263 |
+
attention_scores = matmul_result.view(*output_size)
|
264 |
+
|
265 |
+
# ===========================
|
266 |
+
# Attention probs and dropout
|
267 |
+
# ===========================
|
268 |
+
|
269 |
+
# attention scores and attention mask [b, np, sq, sk]
|
270 |
+
if self.attention_softmax_in_fp32:
|
271 |
+
attention_scores = attention_scores.float()
|
272 |
+
if self.coeff is not None:
|
273 |
+
attention_scores = attention_scores * self.coeff
|
274 |
+
if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
|
275 |
+
attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
|
276 |
+
device=attention_scores.device, dtype=torch.bool)
|
277 |
+
attention_mask.tril_()
|
278 |
+
attention_mask = ~attention_mask
|
279 |
+
if attention_mask is not None:
|
280 |
+
attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
|
281 |
+
attention_probs = F.softmax(attention_scores, dim=-1)
|
282 |
+
attention_probs = attention_probs.type_as(value_layer)
|
283 |
+
|
284 |
+
# This is actually dropping out entire tokens to attend to, which might
|
285 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
286 |
+
attention_probs = self.attention_dropout(attention_probs)
|
287 |
+
# =========================
|
288 |
+
# Context layer. [sq, b, hp]
|
289 |
+
# =========================
|
290 |
+
|
291 |
+
# value_layer -> context layer.
|
292 |
+
# [sk, b, np, hn] --> [b, np, sq, hn]
|
293 |
+
|
294 |
+
# context layer shape: [b, np, sq, hn]
|
295 |
+
output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
|
296 |
+
# change view [sk, b * np, hn]
|
297 |
+
value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
|
298 |
+
# change view [b * np, sq, sk]
|
299 |
+
attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
|
300 |
+
# matmul: [b * np, sq, hn]
|
301 |
+
context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
|
302 |
+
# change view [b, np, sq, hn]
|
303 |
+
context_layer = context_layer.view(*output_size)
|
304 |
+
# [b, np, sq, hn] --> [sq, b, np, hn]
|
305 |
+
context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
|
306 |
+
# [sq, b, np, hn] --> [sq, b, hp]
|
307 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
|
308 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
309 |
+
|
310 |
+
return context_layer
|
311 |
+
|
312 |
+
|
313 |
+
class SelfAttention(torch.nn.Module):
|
314 |
+
"""Parallel self-attention layer abstract class.
|
315 |
+
|
316 |
+
Self-attention layer takes input with size [s, b, h]
|
317 |
+
and returns output of the same size.
|
318 |
+
"""
|
319 |
+
|
320 |
+
def __init__(self, config: ChatGLMConfig, layer_number, device=None):
|
321 |
+
super(SelfAttention, self).__init__()
|
322 |
+
self.layer_number = max(1, layer_number)
|
323 |
+
|
324 |
+
self.projection_size = config.kv_channels * config.num_attention_heads
|
325 |
+
|
326 |
+
# Per attention head and per partition values.
|
327 |
+
self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
|
328 |
+
self.num_attention_heads_per_partition = config.num_attention_heads
|
329 |
+
|
330 |
+
self.multi_query_attention = config.multi_query_attention
|
331 |
+
self.qkv_hidden_size = 3 * self.projection_size
|
332 |
+
if self.multi_query_attention:
|
333 |
+
self.num_multi_query_groups_per_partition = config.multi_query_group_num
|
334 |
+
self.qkv_hidden_size = (
|
335 |
+
self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
|
336 |
+
)
|
337 |
+
self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
|
338 |
+
bias=config.add_bias_linear or config.add_qkv_bias,
|
339 |
+
device=device, **_config_to_kwargs(config)
|
340 |
+
)
|
341 |
+
|
342 |
+
self.core_attention = CoreAttention(config, self.layer_number)
|
343 |
+
|
344 |
+
# Output.
|
345 |
+
self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
|
346 |
+
device=device, **_config_to_kwargs(config)
|
347 |
+
)
|
348 |
+
|
349 |
+
def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
|
350 |
+
if self.multi_query_attention:
|
351 |
+
num_attention_heads = self.num_multi_query_groups_per_partition
|
352 |
+
else:
|
353 |
+
num_attention_heads = self.num_attention_heads_per_partition
|
354 |
+
return torch.empty(
|
355 |
+
inference_max_sequence_len,
|
356 |
+
batch_size,
|
357 |
+
num_attention_heads,
|
358 |
+
self.hidden_size_per_attention_head,
|
359 |
+
dtype=dtype,
|
360 |
+
device=device,
|
361 |
+
)
|
362 |
+
|
363 |
+
def forward(
|
364 |
+
self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
|
365 |
+
):
|
366 |
+
# hidden_states: [sq, b, h]
|
367 |
+
|
368 |
+
# =================================================
|
369 |
+
# Pre-allocate memory for key-values for inference.
|
370 |
+
# =================================================
|
371 |
+
# =====================
|
372 |
+
# Query, Key, and Value
|
373 |
+
# =====================
|
374 |
+
|
375 |
+
# Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
|
376 |
+
mixed_x_layer = self.query_key_value(hidden_states)
|
377 |
+
|
378 |
+
if self.multi_query_attention:
|
379 |
+
(query_layer, key_layer, value_layer) = mixed_x_layer.split(
|
380 |
+
[
|
381 |
+
self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
|
382 |
+
self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
|
383 |
+
self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
|
384 |
+
],
|
385 |
+
dim=-1,
|
386 |
+
)
|
387 |
+
query_layer = query_layer.view(
|
388 |
+
query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
|
389 |
+
)
|
390 |
+
key_layer = key_layer.view(
|
391 |
+
key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
|
392 |
+
)
|
393 |
+
value_layer = value_layer.view(
|
394 |
+
value_layer.size()[:-1]
|
395 |
+
+ (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
|
396 |
+
)
|
397 |
+
else:
|
398 |
+
new_tensor_shape = mixed_x_layer.size()[:-1] + \
|
399 |
+
(self.num_attention_heads_per_partition,
|
400 |
+
3 * self.hidden_size_per_attention_head)
|
401 |
+
mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
|
402 |
+
|
403 |
+
# [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
|
404 |
+
(query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
|
405 |
+
|
406 |
+
# apply relative positional encoding (rotary embedding)
|
407 |
+
if rotary_pos_emb is not None:
|
408 |
+
query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
|
409 |
+
key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
|
410 |
+
|
411 |
+
# adjust key and value for inference
|
412 |
+
if kv_cache is not None:
|
413 |
+
cache_k, cache_v = kv_cache
|
414 |
+
key_layer = torch.cat((cache_k, key_layer), dim=0)
|
415 |
+
value_layer = torch.cat((cache_v, value_layer), dim=0)
|
416 |
+
if use_cache:
|
417 |
+
kv_cache = (key_layer, value_layer)
|
418 |
+
else:
|
419 |
+
kv_cache = None
|
420 |
+
|
421 |
+
if self.multi_query_attention:
|
422 |
+
key_layer = key_layer.unsqueeze(-2)
|
423 |
+
key_layer = key_layer.expand(
|
424 |
+
-1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
|
425 |
+
)
|
426 |
+
key_layer = key_layer.contiguous().view(
|
427 |
+
key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
|
428 |
+
)
|
429 |
+
value_layer = value_layer.unsqueeze(-2)
|
430 |
+
value_layer = value_layer.expand(
|
431 |
+
-1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
|
432 |
+
)
|
433 |
+
value_layer = value_layer.contiguous().view(
|
434 |
+
value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
|
435 |
+
)
|
436 |
+
|
437 |
+
# ==================================
|
438 |
+
# core attention computation
|
439 |
+
# ==================================
|
440 |
+
|
441 |
+
context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
|
442 |
+
|
443 |
+
# =================
|
444 |
+
# Output. [sq, b, h]
|
445 |
+
# =================
|
446 |
+
|
447 |
+
output = self.dense(context_layer)
|
448 |
+
|
449 |
+
return output, kv_cache
|
450 |
+
|
451 |
+
|
452 |
+
def _config_to_kwargs(args):
|
453 |
+
common_kwargs = {
|
454 |
+
"dtype": args.torch_dtype,
|
455 |
+
}
|
456 |
+
return common_kwargs
|
457 |
+
|
458 |
+
|
459 |
+
class MLP(torch.nn.Module):
|
460 |
+
"""MLP.
|
461 |
+
|
462 |
+
MLP will take the input with h hidden state, project it to 4*h
|
463 |
+
hidden dimension, perform nonlinear transformation, and project the
|
464 |
+
state back into h hidden dimension.
|
465 |
+
"""
|
466 |
+
|
467 |
+
def __init__(self, config: ChatGLMConfig, device=None):
|
468 |
+
super(MLP, self).__init__()
|
469 |
+
|
470 |
+
self.add_bias = config.add_bias_linear
|
471 |
+
|
472 |
+
# Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
|
473 |
+
self.dense_h_to_4h = nn.Linear(
|
474 |
+
config.hidden_size,
|
475 |
+
config.ffn_hidden_size * 2,
|
476 |
+
bias=self.add_bias,
|
477 |
+
device=device,
|
478 |
+
**_config_to_kwargs(config)
|
479 |
+
)
|
480 |
+
|
481 |
+
def swiglu(x):
|
482 |
+
x = torch.chunk(x, 2, dim=-1)
|
483 |
+
return F.silu(x[0]) * x[1]
|
484 |
+
|
485 |
+
self.activation_func = swiglu
|
486 |
+
|
487 |
+
# Project back to h.
|
488 |
+
self.dense_4h_to_h = nn.Linear(
|
489 |
+
config.ffn_hidden_size,
|
490 |
+
config.hidden_size,
|
491 |
+
bias=self.add_bias,
|
492 |
+
device=device,
|
493 |
+
**_config_to_kwargs(config)
|
494 |
+
)
|
495 |
+
|
496 |
+
def forward(self, hidden_states):
|
497 |
+
# [s, b, 4hp]
|
498 |
+
intermediate_parallel = self.dense_h_to_4h(hidden_states)
|
499 |
+
intermediate_parallel = self.activation_func(intermediate_parallel)
|
500 |
+
# [s, b, h]
|
501 |
+
output = self.dense_4h_to_h(intermediate_parallel)
|
502 |
+
return output
|
503 |
+
|
504 |
+
|
505 |
+
class GLMBlock(torch.nn.Module):
|
506 |
+
"""A single transformer layer.
|
507 |
+
|
508 |
+
Transformer layer takes input with size [s, b, h] and returns an
|
509 |
+
output of the same size.
|
510 |
+
"""
|
511 |
+
|
512 |
+
def __init__(self, config: ChatGLMConfig, layer_number, device=None):
|
513 |
+
super(GLMBlock, self).__init__()
|
514 |
+
self.layer_number = layer_number
|
515 |
+
|
516 |
+
self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
|
517 |
+
|
518 |
+
self.fp32_residual_connection = config.fp32_residual_connection
|
519 |
+
|
520 |
+
LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
|
521 |
+
# Layernorm on the input data.
|
522 |
+
self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
|
523 |
+
dtype=config.torch_dtype)
|
524 |
+
|
525 |
+
# Self attention.
|
526 |
+
self.self_attention = SelfAttention(config, layer_number, device=device)
|
527 |
+
self.hidden_dropout = config.hidden_dropout
|
528 |
+
|
529 |
+
# Layernorm on the attention output
|
530 |
+
self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
|
531 |
+
dtype=config.torch_dtype)
|
532 |
+
|
533 |
+
# MLP
|
534 |
+
self.mlp = MLP(config, device=device)
|
535 |
+
|
536 |
+
def forward(
|
537 |
+
self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
|
538 |
+
):
|
539 |
+
# hidden_states: [s, b, h]
|
540 |
+
|
541 |
+
# Layer norm at the beginning of the transformer layer.
|
542 |
+
layernorm_output = self.input_layernorm(hidden_states)
|
543 |
+
# Self attention.
|
544 |
+
attention_output, kv_cache = self.self_attention(
|
545 |
+
layernorm_output,
|
546 |
+
attention_mask,
|
547 |
+
rotary_pos_emb,
|
548 |
+
kv_cache=kv_cache,
|
549 |
+
use_cache=use_cache
|
550 |
+
)
|
551 |
+
|
552 |
+
# Residual connection.
|
553 |
+
if self.apply_residual_connection_post_layernorm:
|
554 |
+
residual = layernorm_output
|
555 |
+
else:
|
556 |
+
residual = hidden_states
|
557 |
+
|
558 |
+
layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
|
559 |
+
layernorm_input = residual + layernorm_input
|
560 |
+
|
561 |
+
# Layer norm post the self attention.
|
562 |
+
layernorm_output = self.post_attention_layernorm(layernorm_input)
|
563 |
+
|
564 |
+
# MLP.
|
565 |
+
mlp_output = self.mlp(layernorm_output)
|
566 |
+
|
567 |
+
# Second residual connection.
|
568 |
+
if self.apply_residual_connection_post_layernorm:
|
569 |
+
residual = layernorm_output
|
570 |
+
else:
|
571 |
+
residual = layernorm_input
|
572 |
+
|
573 |
+
output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
|
574 |
+
output = residual + output
|
575 |
+
|
576 |
+
return output, kv_cache
|
577 |
+
|
578 |
+
|
579 |
+
class GLMTransformer(torch.nn.Module):
|
580 |
+
"""Transformer class."""
|
581 |
+
|
582 |
+
def __init__(self, config: ChatGLMConfig, device=None):
|
583 |
+
super(GLMTransformer, self).__init__()
|
584 |
+
|
585 |
+
self.fp32_residual_connection = config.fp32_residual_connection
|
586 |
+
self.post_layer_norm = config.post_layer_norm
|
587 |
+
|
588 |
+
# Number of layers.
|
589 |
+
self.num_layers = config.num_layers
|
590 |
+
|
591 |
+
# Transformer layers.
|
592 |
+
def build_layer(layer_number):
|
593 |
+
return GLMBlock(config, layer_number, device=device)
|
594 |
+
|
595 |
+
self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
|
596 |
+
|
597 |
+
if self.post_layer_norm:
|
598 |
+
LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
|
599 |
+
# Final layer norm before output.
|
600 |
+
self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
|
601 |
+
dtype=config.torch_dtype)
|
602 |
+
|
603 |
+
self.gradient_checkpointing = False
|
604 |
+
|
605 |
+
def _get_layer(self, layer_number):
|
606 |
+
return self.layers[layer_number]
|
607 |
+
|
608 |
+
def forward(
|
609 |
+
self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
|
610 |
+
use_cache: Optional[bool] = True,
|
611 |
+
output_hidden_states: Optional[bool] = False,
|
612 |
+
):
|
613 |
+
if not kv_caches:
|
614 |
+
kv_caches = [None for _ in range(self.num_layers)]
|
615 |
+
presents = () if use_cache else None
|
616 |
+
if self.gradient_checkpointing and self.training:
|
617 |
+
if use_cache:
|
618 |
+
logger.warning_once(
|
619 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
620 |
+
)
|
621 |
+
use_cache = False
|
622 |
+
|
623 |
+
all_self_attentions = None
|
624 |
+
all_hidden_states = () if output_hidden_states else None
|
625 |
+
for index in range(self.num_layers):
|
626 |
+
if output_hidden_states:
|
627 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
628 |
+
|
629 |
+
layer = self._get_layer(index)
|
630 |
+
if self.gradient_checkpointing and self.training:
|
631 |
+
layer_ret = torch.utils.checkpoint.checkpoint(
|
632 |
+
layer,
|
633 |
+
hidden_states,
|
634 |
+
attention_mask,
|
635 |
+
rotary_pos_emb,
|
636 |
+
kv_caches[index],
|
637 |
+
use_cache
|
638 |
+
)
|
639 |
+
else:
|
640 |
+
layer_ret = layer(
|
641 |
+
hidden_states,
|
642 |
+
attention_mask,
|
643 |
+
rotary_pos_emb,
|
644 |
+
kv_cache=kv_caches[index],
|
645 |
+
use_cache=use_cache
|
646 |
+
)
|
647 |
+
hidden_states, kv_cache = layer_ret
|
648 |
+
if use_cache:
|
649 |
+
presents = presents + (kv_cache,)
|
650 |
+
|
651 |
+
if output_hidden_states:
|
652 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
653 |
+
|
654 |
+
# Final layer norm.
|
655 |
+
if self.post_layer_norm:
|
656 |
+
hidden_states = self.final_layernorm(hidden_states)
|
657 |
+
|
658 |
+
return hidden_states, presents, all_hidden_states, all_self_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_weights(self, module: nn.Module):
|
674 |
+
"""Initialize the weights."""
|
675 |
+
return
|
676 |
+
|
677 |
+
def get_masks(self, input_ids, past_key_values, padding_mask=None):
|
678 |
+
batch_size, seq_length = input_ids.shape
|
679 |
+
full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
|
680 |
+
full_attention_mask.tril_()
|
681 |
+
past_length = 0
|
682 |
+
if past_key_values:
|
683 |
+
past_length = past_key_values[0][0].shape[0]
|
684 |
+
if past_length:
|
685 |
+
full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
|
686 |
+
device=input_ids.device), full_attention_mask), dim=-1)
|
687 |
+
if padding_mask is not None:
|
688 |
+
full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
|
689 |
+
if not past_length and padding_mask is not None:
|
690 |
+
full_attention_mask -= padding_mask.unsqueeze(-1) - 1
|
691 |
+
full_attention_mask = (full_attention_mask < 0.5).bool()
|
692 |
+
full_attention_mask.unsqueeze_(1)
|
693 |
+
return full_attention_mask
|
694 |
+
|
695 |
+
def get_position_ids(self, input_ids, device):
|
696 |
+
batch_size, seq_length = input_ids.shape
|
697 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
|
698 |
+
return position_ids
|
699 |
+
|
700 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
701 |
+
if isinstance(module, GLMTransformer):
|
702 |
+
module.gradient_checkpointing = value
|
703 |
+
|
704 |
+
|
705 |
+
class Embedding(torch.nn.Module):
|
706 |
+
"""Language model embeddings."""
|
707 |
+
|
708 |
+
def __init__(self, config: ChatGLMConfig, device=None):
|
709 |
+
super(Embedding, self).__init__()
|
710 |
+
|
711 |
+
self.hidden_size = config.hidden_size
|
712 |
+
# Word embeddings (parallel).
|
713 |
+
self.word_embeddings = nn.Embedding(
|
714 |
+
config.padded_vocab_size,
|
715 |
+
self.hidden_size,
|
716 |
+
dtype=config.torch_dtype,
|
717 |
+
device=device
|
718 |
+
)
|
719 |
+
self.fp32_residual_connection = config.fp32_residual_connection
|
720 |
+
|
721 |
+
def forward(self, input_ids):
|
722 |
+
# Embeddings.
|
723 |
+
words_embeddings = self.word_embeddings(input_ids)
|
724 |
+
embeddings = words_embeddings
|
725 |
+
# Data format change to avoid explicit tranposes : [b s h] --> [s b h].
|
726 |
+
embeddings = embeddings.transpose(0, 1).contiguous()
|
727 |
+
# If the input flag for fp32 residual connection is set, convert for float.
|
728 |
+
if self.fp32_residual_connection:
|
729 |
+
embeddings = embeddings.float()
|
730 |
+
return embeddings
|
731 |
+
|
732 |
+
|
733 |
+
class ChatGLMModel(ChatGLMPreTrainedModel):
|
734 |
+
def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
|
735 |
+
super().__init__(config)
|
736 |
+
if empty_init:
|
737 |
+
init_method = skip_init
|
738 |
+
else:
|
739 |
+
init_method = default_init
|
740 |
+
init_kwargs = {}
|
741 |
+
if device is not None:
|
742 |
+
init_kwargs["device"] = device
|
743 |
+
self.embedding = init_method(Embedding, config, **init_kwargs)
|
744 |
+
self.num_layers = config.num_layers
|
745 |
+
self.multi_query_group_num = config.multi_query_group_num
|
746 |
+
self.kv_channels = config.kv_channels
|
747 |
+
|
748 |
+
# Rotary positional embeddings
|
749 |
+
self.seq_length = config.seq_length
|
750 |
+
rotary_dim = (
|
751 |
+
config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
|
752 |
+
)
|
753 |
+
|
754 |
+
self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, original_impl=config.original_rope, device=device,
|
755 |
+
dtype=config.torch_dtype)
|
756 |
+
self.encoder = init_method(GLMTransformer, config, **init_kwargs)
|
757 |
+
self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
|
758 |
+
dtype=config.torch_dtype, **init_kwargs)
|
759 |
+
self.pre_seq_len = config.pre_seq_len
|
760 |
+
self.prefix_projection = config.prefix_projection
|
761 |
+
if self.pre_seq_len is not None:
|
762 |
+
for param in self.parameters():
|
763 |
+
param.requires_grad = False
|
764 |
+
self.prefix_tokens = torch.arange(self.pre_seq_len).long()
|
765 |
+
self.prefix_encoder = PrefixEncoder(config)
|
766 |
+
self.dropout = torch.nn.Dropout(0.1)
|
767 |
+
|
768 |
+
def get_input_embeddings(self):
|
769 |
+
return self.embedding.word_embeddings
|
770 |
+
|
771 |
+
def get_prompt(self, batch_size, device, dtype=torch.half):
|
772 |
+
prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
|
773 |
+
past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
|
774 |
+
past_key_values = past_key_values.view(
|
775 |
+
batch_size,
|
776 |
+
self.pre_seq_len,
|
777 |
+
self.num_layers * 2,
|
778 |
+
self.multi_query_group_num,
|
779 |
+
self.kv_channels
|
780 |
+
)
|
781 |
+
# seq_len, b, nh, hidden_size
|
782 |
+
past_key_values = self.dropout(past_key_values)
|
783 |
+
past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
|
784 |
+
return past_key_values
|
785 |
+
|
786 |
+
def forward(
|
787 |
+
self,
|
788 |
+
input_ids,
|
789 |
+
position_ids: Optional[torch.Tensor] = None,
|
790 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
791 |
+
full_attention_mask: Optional[torch.BoolTensor] = None,
|
792 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
793 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
794 |
+
use_cache: Optional[bool] = None,
|
795 |
+
output_hidden_states: Optional[bool] = None,
|
796 |
+
return_dict: Optional[bool] = None,
|
797 |
+
):
|
798 |
+
output_hidden_states = (
|
799 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
800 |
+
)
|
801 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
802 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
803 |
+
|
804 |
+
batch_size, seq_length = input_ids.shape
|
805 |
+
|
806 |
+
if inputs_embeds is None:
|
807 |
+
inputs_embeds = self.embedding(input_ids)
|
808 |
+
|
809 |
+
if self.pre_seq_len is not None:
|
810 |
+
if past_key_values is None:
|
811 |
+
past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
|
812 |
+
dtype=inputs_embeds.dtype)
|
813 |
+
if attention_mask is not None:
|
814 |
+
attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
|
815 |
+
attention_mask], dim=-1)
|
816 |
+
|
817 |
+
if full_attention_mask is None:
|
818 |
+
if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
|
819 |
+
full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
|
820 |
+
|
821 |
+
# Rotary positional embeddings
|
822 |
+
rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
|
823 |
+
if position_ids is not None:
|
824 |
+
rotary_pos_emb = rotary_pos_emb[position_ids]
|
825 |
+
else:
|
826 |
+
rotary_pos_emb = rotary_pos_emb[None, :seq_length]
|
827 |
+
rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
|
828 |
+
|
829 |
+
# Run encoder.
|
830 |
+
hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
|
831 |
+
inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
|
832 |
+
kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
|
833 |
+
)
|
834 |
+
|
835 |
+
if not return_dict:
|
836 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
837 |
+
|
838 |
+
return BaseModelOutputWithPast(
|
839 |
+
last_hidden_state=hidden_states,
|
840 |
+
past_key_values=presents,
|
841 |
+
hidden_states=all_hidden_states,
|
842 |
+
attentions=all_self_attentions,
|
843 |
+
)
|
844 |
+
|
845 |
+
def quantize(self, weight_bit_width: int):
|
846 |
+
from .quantization import quantize
|
847 |
+
quantize(self.encoder, weight_bit_width)
|
848 |
+
return self
|
849 |
+
|
850 |
+
|
851 |
+
class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
852 |
+
def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
|
853 |
+
super().__init__(config)
|
854 |
+
|
855 |
+
self.max_sequence_length = config.max_length
|
856 |
+
self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
|
857 |
+
self.config = config
|
858 |
+
self.quantized = False
|
859 |
+
|
860 |
+
if self.config.quantization_bit:
|
861 |
+
self.quantize(self.config.quantization_bit, empty_init=True)
|
862 |
+
|
863 |
+
def _update_model_kwargs_for_generation(
|
864 |
+
self,
|
865 |
+
outputs: ModelOutput,
|
866 |
+
model_kwargs: Dict[str, Any],
|
867 |
+
is_encoder_decoder: bool = False,
|
868 |
+
standardize_cache_format: bool = False,
|
869 |
+
) -> Dict[str, Any]:
|
870 |
+
# update past_key_values
|
871 |
+
model_kwargs["past_key_values"] = self._extract_past_from_model_output(
|
872 |
+
outputs, standardize_cache_format=standardize_cache_format
|
873 |
+
)
|
874 |
+
|
875 |
+
# update attention mask
|
876 |
+
if "attention_mask" in model_kwargs:
|
877 |
+
attention_mask = model_kwargs["attention_mask"]
|
878 |
+
model_kwargs["attention_mask"] = torch.cat(
|
879 |
+
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
|
880 |
+
)
|
881 |
+
|
882 |
+
# update position ids
|
883 |
+
if "position_ids" in model_kwargs:
|
884 |
+
position_ids = model_kwargs["position_ids"]
|
885 |
+
new_position_id = position_ids[..., -1:].clone()
|
886 |
+
new_position_id += 1
|
887 |
+
model_kwargs["position_ids"] = torch.cat(
|
888 |
+
[position_ids, new_position_id], dim=-1
|
889 |
+
)
|
890 |
+
|
891 |
+
model_kwargs["is_first_forward"] = False
|
892 |
+
return model_kwargs
|
893 |
+
|
894 |
+
def prepare_inputs_for_generation(
|
895 |
+
self,
|
896 |
+
input_ids: torch.LongTensor,
|
897 |
+
past_key_values: Optional[torch.Tensor] = None,
|
898 |
+
attention_mask: Optional[torch.Tensor] = None,
|
899 |
+
position_ids: Optional[torch.Tensor] = None,
|
900 |
+
use_cache: Optional[bool] = None,
|
901 |
+
is_first_forward: bool = True,
|
902 |
+
**kwargs
|
903 |
+
) -> dict:
|
904 |
+
# only last token for input_ids if past is not None
|
905 |
+
if position_ids is None:
|
906 |
+
position_ids = self.get_position_ids(input_ids, device=input_ids.device)
|
907 |
+
if not is_first_forward:
|
908 |
+
if past_key_values is not None:
|
909 |
+
position_ids = position_ids[..., -1:]
|
910 |
+
input_ids = input_ids[:, -1:]
|
911 |
+
return {
|
912 |
+
"input_ids": input_ids,
|
913 |
+
"past_key_values": past_key_values,
|
914 |
+
"position_ids": position_ids,
|
915 |
+
"attention_mask": attention_mask,
|
916 |
+
"return_last_logit": True,
|
917 |
+
"use_cache": use_cache
|
918 |
+
}
|
919 |
+
|
920 |
+
def forward(
|
921 |
+
self,
|
922 |
+
input_ids: Optional[torch.Tensor] = None,
|
923 |
+
position_ids: Optional[torch.Tensor] = None,
|
924 |
+
attention_mask: Optional[torch.Tensor] = None,
|
925 |
+
past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
|
926 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
927 |
+
labels: Optional[torch.Tensor] = None,
|
928 |
+
use_cache: Optional[bool] = None,
|
929 |
+
output_attentions: Optional[bool] = None,
|
930 |
+
output_hidden_states: Optional[bool] = None,
|
931 |
+
return_dict: Optional[bool] = None,
|
932 |
+
return_last_logit: Optional[bool] = False,
|
933 |
+
):
|
934 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
935 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
936 |
+
|
937 |
+
transformer_outputs = self.transformer(
|
938 |
+
input_ids=input_ids,
|
939 |
+
position_ids=position_ids,
|
940 |
+
attention_mask=attention_mask,
|
941 |
+
past_key_values=past_key_values,
|
942 |
+
inputs_embeds=inputs_embeds,
|
943 |
+
use_cache=use_cache,
|
944 |
+
output_hidden_states=output_hidden_states,
|
945 |
+
return_dict=return_dict,
|
946 |
+
)
|
947 |
+
|
948 |
+
hidden_states = transformer_outputs[0]
|
949 |
+
if return_last_logit:
|
950 |
+
hidden_states = hidden_states[-1:]
|
951 |
+
lm_logits = self.transformer.output_layer(hidden_states)
|
952 |
+
lm_logits = lm_logits.transpose(0, 1).contiguous()
|
953 |
+
|
954 |
+
loss = None
|
955 |
+
if labels is not None:
|
956 |
+
lm_logits = lm_logits.to(torch.float32)
|
957 |
+
|
958 |
+
# Shift so that tokens < n predict n
|
959 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
960 |
+
shift_labels = labels[..., 1:].contiguous()
|
961 |
+
# Flatten the tokens
|
962 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
963 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
964 |
+
|
965 |
+
lm_logits = lm_logits.to(hidden_states.dtype)
|
966 |
+
loss = loss.to(hidden_states.dtype)
|
967 |
+
|
968 |
+
if not return_dict:
|
969 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
970 |
+
return ((loss,) + output) if loss is not None else output
|
971 |
+
|
972 |
+
return CausalLMOutputWithPast(
|
973 |
+
loss=loss,
|
974 |
+
logits=lm_logits,
|
975 |
+
past_key_values=transformer_outputs.past_key_values,
|
976 |
+
hidden_states=transformer_outputs.hidden_states,
|
977 |
+
attentions=transformer_outputs.attentions,
|
978 |
+
)
|
979 |
+
|
980 |
+
@staticmethod
|
981 |
+
def _reorder_cache(
|
982 |
+
past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
|
983 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
|
984 |
+
"""
|
985 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
986 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
987 |
+
beam_idx at every generation step.
|
988 |
+
|
989 |
+
Output shares the same memory storage as `past`.
|
990 |
+
"""
|
991 |
+
return tuple(
|
992 |
+
(
|
993 |
+
layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
|
994 |
+
layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
|
995 |
+
)
|
996 |
+
for layer_past in past
|
997 |
+
)
|
998 |
+
|
999 |
+
def process_response(self, response):
|
1000 |
+
response = response.strip()
|
1001 |
+
response = response.replace("[[训练时间]]", "2023年")
|
1002 |
+
return response
|
1003 |
+
|
1004 |
+
def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
|
1005 |
+
prompt = tokenizer.build_prompt(query, history=history)
|
1006 |
+
inputs = tokenizer([prompt], return_tensors="pt")
|
1007 |
+
inputs = inputs.to(self.device)
|
1008 |
+
return inputs
|
1009 |
+
|
1010 |
+
def build_stream_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
|
1011 |
+
if history:
|
1012 |
+
prompt = "\n\n[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
|
1013 |
+
input_ids = tokenizer.encode(prompt, add_special_tokens=False)
|
1014 |
+
input_ids = input_ids[1:]
|
1015 |
+
inputs = tokenizer.batch_encode_plus([(input_ids, None)], return_tensors="pt", add_special_tokens=False)
|
1016 |
+
else:
|
1017 |
+
prompt = "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
|
1018 |
+
inputs = tokenizer([prompt], return_tensors="pt")
|
1019 |
+
inputs = inputs.to(self.device)
|
1020 |
+
return inputs
|
1021 |
+
|
1022 |
+
@torch.inference_mode()
|
1023 |
+
def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 8192, num_beams=1,
|
1024 |
+
do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):
|
1025 |
+
if history is None:
|
1026 |
+
history = []
|
1027 |
+
if logits_processor is None:
|
1028 |
+
logits_processor = LogitsProcessorList()
|
1029 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1030 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
|
1031 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1032 |
+
inputs = self.build_inputs(tokenizer, query, history=history)
|
1033 |
+
outputs = self.generate(**inputs, **gen_kwargs)
|
1034 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
|
1035 |
+
response = tokenizer.decode(outputs)
|
1036 |
+
response = self.process_response(response)
|
1037 |
+
history = history + [(query, response)]
|
1038 |
+
return response, history
|
1039 |
+
|
1040 |
+
@torch.inference_mode()
|
1041 |
+
def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,
|
1042 |
+
max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
|
1043 |
+
return_past_key_values=False, **kwargs):
|
1044 |
+
if history is None:
|
1045 |
+
history = []
|
1046 |
+
if logits_processor is None:
|
1047 |
+
logits_processor = LogitsProcessorList()
|
1048 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1049 |
+
gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
|
1050 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1051 |
+
if past_key_values is None and not return_past_key_values:
|
1052 |
+
inputs = self.build_inputs(tokenizer, query, history=history)
|
1053 |
+
else:
|
1054 |
+
inputs = self.build_stream_inputs(tokenizer, query, history=history)
|
1055 |
+
if past_key_values is not None:
|
1056 |
+
past_length = past_key_values[0][0].shape[0]
|
1057 |
+
if self.transformer.pre_seq_len is not None:
|
1058 |
+
past_length -= self.transformer.pre_seq_len
|
1059 |
+
inputs.position_ids += past_length
|
1060 |
+
attention_mask = inputs.attention_mask
|
1061 |
+
attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
|
1062 |
+
inputs['attention_mask'] = attention_mask
|
1063 |
+
for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
|
1064 |
+
return_past_key_values=return_past_key_values, **gen_kwargs):
|
1065 |
+
if return_past_key_values:
|
1066 |
+
outputs, past_key_values = outputs
|
1067 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
|
1068 |
+
response = tokenizer.decode(outputs)
|
1069 |
+
if response and response[-1] != "�":
|
1070 |
+
response = self.process_response(response)
|
1071 |
+
new_history = history + [(query, response)]
|
1072 |
+
if return_past_key_values:
|
1073 |
+
yield response, new_history, past_key_values
|
1074 |
+
else:
|
1075 |
+
yield response, new_history
|
1076 |
+
|
1077 |
+
@torch.inference_mode()
|
1078 |
+
def stream_generate(
|
1079 |
+
self,
|
1080 |
+
input_ids,
|
1081 |
+
generation_config: Optional[GenerationConfig] = None,
|
1082 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
1083 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
1084 |
+
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
|
1085 |
+
return_past_key_values=False,
|
1086 |
+
**kwargs,
|
1087 |
+
):
|
1088 |
+
batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
|
1089 |
+
|
1090 |
+
if generation_config is None:
|
1091 |
+
generation_config = self.generation_config
|
1092 |
+
generation_config = copy.deepcopy(generation_config)
|
1093 |
+
model_kwargs = generation_config.update(**kwargs)
|
1094 |
+
model_kwargs["use_cache"] = generation_config.use_cache
|
1095 |
+
bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
|
1096 |
+
|
1097 |
+
if isinstance(eos_token_id, int):
|
1098 |
+
eos_token_id = [eos_token_id]
|
1099 |
+
|
1100 |
+
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
|
1101 |
+
if has_default_max_length and generation_config.max_new_tokens is None:
|
1102 |
+
warnings.warn(
|
1103 |
+
f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
|
1104 |
+
"This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
|
1105 |
+
" recommend using `max_new_tokens` to control the maximum length of the generation.",
|
1106 |
+
UserWarning,
|
1107 |
+
)
|
1108 |
+
elif generation_config.max_new_tokens is not None:
|
1109 |
+
generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
|
1110 |
+
if not has_default_max_length:
|
1111 |
+
logger.warn(
|
1112 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
1113 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
1114 |
+
"Please refer to the documentation for more information. "
|
1115 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
|
1116 |
+
UserWarning,
|
1117 |
+
)
|
1118 |
+
|
1119 |
+
if input_ids_seq_length >= generation_config.max_length:
|
1120 |
+
input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
|
1121 |
+
logger.warning(
|
1122 |
+
f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
|
1123 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
1124 |
+
" increasing `max_new_tokens`."
|
1125 |
+
)
|
1126 |
+
|
1127 |
+
# 2. Set generation parameters if not already defined
|
1128 |
+
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
1129 |
+
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
1130 |
+
|
1131 |
+
logits_processor = self._get_logits_processor(
|
1132 |
+
generation_config=generation_config,
|
1133 |
+
input_ids_seq_length=input_ids_seq_length,
|
1134 |
+
encoder_input_ids=input_ids,
|
1135 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
1136 |
+
logits_processor=logits_processor,
|
1137 |
+
)
|
1138 |
+
|
1139 |
+
stopping_criteria = self._get_stopping_criteria(
|
1140 |
+
generation_config=generation_config, stopping_criteria=stopping_criteria
|
1141 |
+
)
|
1142 |
+
logits_warper = self._get_logits_warper(generation_config)
|
1143 |
+
|
1144 |
+
unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
|
1145 |
+
scores = None
|
1146 |
+
while True:
|
1147 |
+
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
1148 |
+
# forward pass to get next token
|
1149 |
+
outputs = self(
|
1150 |
+
**model_inputs,
|
1151 |
+
return_dict=True,
|
1152 |
+
output_attentions=False,
|
1153 |
+
output_hidden_states=False,
|
1154 |
+
)
|
1155 |
+
|
1156 |
+
next_token_logits = outputs.logits[:, -1, :]
|
1157 |
+
|
1158 |
+
# pre-process distribution
|
1159 |
+
next_token_scores = logits_processor(input_ids, next_token_logits)
|
1160 |
+
next_token_scores = logits_warper(input_ids, next_token_scores)
|
1161 |
+
|
1162 |
+
# sample
|
1163 |
+
probs = nn.functional.softmax(next_token_scores, dim=-1)
|
1164 |
+
if generation_config.do_sample:
|
1165 |
+
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
1166 |
+
else:
|
1167 |
+
next_tokens = torch.argmax(probs, dim=-1)
|
1168 |
+
|
1169 |
+
# update generated ids, model inputs, and length for next step
|
1170 |
+
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
1171 |
+
model_kwargs = self._update_model_kwargs_for_generation(
|
1172 |
+
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
|
1173 |
+
)
|
1174 |
+
unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
|
1175 |
+
if return_past_key_values:
|
1176 |
+
yield input_ids, outputs.past_key_values
|
1177 |
+
else:
|
1178 |
+
yield input_ids
|
1179 |
+
# stop when each sentence is finished, or if we exceed the maximum length
|
1180 |
+
if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
|
1181 |
+
break
|
1182 |
+
|
1183 |
+
def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
|
1184 |
+
if bits == 0:
|
1185 |
+
return
|
1186 |
+
|
1187 |
+
from .quantization import quantize
|
1188 |
+
|
1189 |
+
if self.quantized:
|
1190 |
+
logger.info("Already quantized.")
|
1191 |
+
return self
|
1192 |
+
|
1193 |
+
self.quantized = True
|
1194 |
+
|
1195 |
+
self.config.quantization_bit = bits
|
1196 |
+
|
1197 |
+
self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
|
1198 |
+
**kwargs)
|
1199 |
+
return self
|
1200 |
+
|
1201 |
+
|
1202 |
+
class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
|
1203 |
+
def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
|
1204 |
+
super().__init__(config)
|
1205 |
+
|
1206 |
+
self.num_labels = config.num_labels
|
1207 |
+
self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
|
1208 |
+
|
1209 |
+
self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
|
1210 |
+
if config.classifier_dropout is not None:
|
1211 |
+
self.dropout = nn.Dropout(config.classifier_dropout)
|
1212 |
+
else:
|
1213 |
+
self.dropout = None
|
1214 |
+
self.config = config
|
1215 |
+
|
1216 |
+
if self.config.quantization_bit:
|
1217 |
+
self.quantize(self.config.quantization_bit, empty_init=True)
|
1218 |
+
|
1219 |
+
def forward(
|
1220 |
+
self,
|
1221 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1222 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1223 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1224 |
+
full_attention_mask: Optional[torch.Tensor] = None,
|
1225 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1226 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
1227 |
+
labels: Optional[torch.LongTensor] = None,
|
1228 |
+
use_cache: Optional[bool] = None,
|
1229 |
+
output_hidden_states: Optional[bool] = None,
|
1230 |
+
return_dict: Optional[bool] = None,
|
1231 |
+
) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
|
1232 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1233 |
+
|
1234 |
+
transformer_outputs = self.transformer(
|
1235 |
+
input_ids=input_ids,
|
1236 |
+
position_ids=position_ids,
|
1237 |
+
attention_mask=attention_mask,
|
1238 |
+
full_attention_mask=full_attention_mask,
|
1239 |
+
past_key_values=past_key_values,
|
1240 |
+
inputs_embeds=inputs_embeds,
|
1241 |
+
use_cache=use_cache,
|
1242 |
+
output_hidden_states=output_hidden_states,
|
1243 |
+
return_dict=return_dict,
|
1244 |
+
)
|
1245 |
+
|
1246 |
+
hidden_states = transformer_outputs[0]
|
1247 |
+
pooled_hidden_states = hidden_states[-1]
|
1248 |
+
if self.dropout is not None:
|
1249 |
+
pooled_hidden_states = self.dropout(pooled_hidden_states)
|
1250 |
+
logits = self.classifier_head(pooled_hidden_states)
|
1251 |
+
|
1252 |
+
loss = None
|
1253 |
+
if labels is not None:
|
1254 |
+
if self.config.problem_type is None:
|
1255 |
+
if self.num_labels == 1:
|
1256 |
+
self.config.problem_type = "regression"
|
1257 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1258 |
+
self.config.problem_type = "single_label_classification"
|
1259 |
+
else:
|
1260 |
+
self.config.problem_type = "multi_label_classification"
|
1261 |
+
|
1262 |
+
if self.config.problem_type == "regression":
|
1263 |
+
loss_fct = MSELoss()
|
1264 |
+
if self.num_labels == 1:
|
1265 |
+
loss = loss_fct(logits.squeeze().float(), labels.squeeze())
|
1266 |
+
else:
|
1267 |
+
loss = loss_fct(logits.float(), labels)
|
1268 |
+
elif self.config.problem_type == "single_label_classification":
|
1269 |
+
loss_fct = CrossEntropyLoss()
|
1270 |
+
loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
|
1271 |
+
elif self.config.problem_type == "multi_label_classification":
|
1272 |
+
loss_fct = BCEWithLogitsLoss()
|
1273 |
+
loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
|
1274 |
+
|
1275 |
+
if not return_dict:
|
1276 |
+
output = (logits,) + transformer_outputs[1:]
|
1277 |
+
return ((loss,) + output) if loss is not None else output
|
1278 |
+
|
1279 |
+
return SequenceClassifierOutputWithPast(
|
1280 |
+
loss=loss,
|
1281 |
+
logits=logits,
|
1282 |
+
past_key_values=transformer_outputs.past_key_values,
|
1283 |
+
hidden_states=transformer_outputs.hidden_states,
|
1284 |
+
attentions=transformer_outputs.attentions,
|
1285 |
+
)
|
chatglm2-6b/pytorch_model-00001-of-00007.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cdf1bf57d519abe11043e9121314e76bc0934993e649a9e438a4b0894f4e6ee8
|
3 |
+
size 1827780615
|
chatglm2-6b/pytorch_model-00002-of-00007.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1cd596bd15905248b20b755daf12a02a8fa963da09b59da7fdc896e17bfa518c
|
3 |
+
size 1968299005
|
chatglm2-6b/pytorch_model-00003-of-00007.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:812edc55c969d2ef82dcda8c275e379ef689761b13860da8ea7c1f3a475975c8
|
3 |
+
size 1927414561
|
chatglm2-6b/pytorch_model-00004-of-00007.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:555c17fac2d80e38ba332546dc759b6b7e07aee21e5d0d7826375b998e5aada3
|
3 |
+
size 1815225523
|
chatglm2-6b/pytorch_model-00005-of-00007.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cb85560ccfa77a9e4dd67a838c8d1eeb0071427fd8708e18be9c77224969ef48
|
3 |
+
size 1968299069
|
chatglm2-6b/pytorch_model-00006-of-00007.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:09ebd811227d992350b92b2c3491f677ae1f3c586b38abe95784fd2f7d23d5f2
|
3 |
+
size 1927414561
|
chatglm2-6b/pytorch_model-00007-of-00007.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:316e007bc727f3cbba432d29e1d3e35ac8ef8eb52df4db9f0609d091a43c69cb
|
3 |
+
size 1052808067
|
chatglm2-6b/pytorch_model.bin.index.json
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 12487168064
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"transformer.embedding.word_embeddings.weight": "pytorch_model-00001-of-00007.bin",
|
7 |
+
"transformer.encoder.final_layernorm.weight": "pytorch_model-00007-of-00007.bin",
|
8 |
+
"transformer.encoder.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
9 |
+
"transformer.encoder.layers.0.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
|
10 |
+
"transformer.encoder.layers.0.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
|
11 |
+
"transformer.encoder.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
12 |
+
"transformer.encoder.layers.0.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
|
13 |
+
"transformer.encoder.layers.0.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
|
14 |
+
"transformer.encoder.layers.0.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
|
15 |
+
"transformer.encoder.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
16 |
+
"transformer.encoder.layers.1.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
|
17 |
+
"transformer.encoder.layers.1.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
|
18 |
+
"transformer.encoder.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
19 |
+
"transformer.encoder.layers.1.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
|
20 |
+
"transformer.encoder.layers.1.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
|
21 |
+
"transformer.encoder.layers.1.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
|
22 |
+
"transformer.encoder.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
23 |
+
"transformer.encoder.layers.10.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
|
24 |
+
"transformer.encoder.layers.10.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
|
25 |
+
"transformer.encoder.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
26 |
+
"transformer.encoder.layers.10.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
|
27 |
+
"transformer.encoder.layers.10.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
|
28 |
+
"transformer.encoder.layers.10.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
|
29 |
+
"transformer.encoder.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
30 |
+
"transformer.encoder.layers.11.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
|
31 |
+
"transformer.encoder.layers.11.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
|
32 |
+
"transformer.encoder.layers.11.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
33 |
+
"transformer.encoder.layers.11.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
|
34 |
+
"transformer.encoder.layers.11.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
|
35 |
+
"transformer.encoder.layers.11.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
|
36 |
+
"transformer.encoder.layers.12.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
37 |
+
"transformer.encoder.layers.12.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
|
38 |
+
"transformer.encoder.layers.12.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
|
39 |
+
"transformer.encoder.layers.12.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
40 |
+
"transformer.encoder.layers.12.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
|
41 |
+
"transformer.encoder.layers.12.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
|
42 |
+
"transformer.encoder.layers.12.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
|
43 |
+
"transformer.encoder.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
44 |
+
"transformer.encoder.layers.13.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
|
45 |
+
"transformer.encoder.layers.13.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
|
46 |
+
"transformer.encoder.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
47 |
+
"transformer.encoder.layers.13.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
|
48 |
+
"transformer.encoder.layers.13.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
|
49 |
+
"transformer.encoder.layers.13.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
|
50 |
+
"transformer.encoder.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
51 |
+
"transformer.encoder.layers.14.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
|
52 |
+
"transformer.encoder.layers.14.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
|
53 |
+
"transformer.encoder.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
54 |
+
"transformer.encoder.layers.14.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
|
55 |
+
"transformer.encoder.layers.14.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
|
56 |
+
"transformer.encoder.layers.14.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
|
57 |
+
"transformer.encoder.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
58 |
+
"transformer.encoder.layers.15.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
|
59 |
+
"transformer.encoder.layers.15.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
|
60 |
+
"transformer.encoder.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
61 |
+
"transformer.encoder.layers.15.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
|
62 |
+
"transformer.encoder.layers.15.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
|
63 |
+
"transformer.encoder.layers.15.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
|
64 |
+
"transformer.encoder.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
65 |
+
"transformer.encoder.layers.16.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
|
66 |
+
"transformer.encoder.layers.16.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
|
67 |
+
"transformer.encoder.layers.16.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
68 |
+
"transformer.encoder.layers.16.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
|
69 |
+
"transformer.encoder.layers.16.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
|
70 |
+
"transformer.encoder.layers.16.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
|
71 |
+
"transformer.encoder.layers.17.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
72 |
+
"transformer.encoder.layers.17.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
|
73 |
+
"transformer.encoder.layers.17.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
|
74 |
+
"transformer.encoder.layers.17.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
|
75 |
+
"transformer.encoder.layers.17.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
|
76 |
+
"transformer.encoder.layers.17.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
|
77 |
+
"transformer.encoder.layers.17.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
|
78 |
+
"transformer.encoder.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
79 |
+
"transformer.encoder.layers.18.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
|
80 |
+
"transformer.encoder.layers.18.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
|
81 |
+
"transformer.encoder.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
82 |
+
"transformer.encoder.layers.18.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
|
83 |
+
"transformer.encoder.layers.18.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
|
84 |
+
"transformer.encoder.layers.18.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
|
85 |
+
"transformer.encoder.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
86 |
+
"transformer.encoder.layers.19.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
|
87 |
+
"transformer.encoder.layers.19.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
|
88 |
+
"transformer.encoder.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
89 |
+
"transformer.encoder.layers.19.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
|
90 |
+
"transformer.encoder.layers.19.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
|
91 |
+
"transformer.encoder.layers.19.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
|
92 |
+
"transformer.encoder.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
93 |
+
"transformer.encoder.layers.2.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
|
94 |
+
"transformer.encoder.layers.2.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
|
95 |
+
"transformer.encoder.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
96 |
+
"transformer.encoder.layers.2.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
|
97 |
+
"transformer.encoder.layers.2.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
|
98 |
+
"transformer.encoder.layers.2.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
|
99 |
+
"transformer.encoder.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
100 |
+
"transformer.encoder.layers.20.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
|
101 |
+
"transformer.encoder.layers.20.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
|
102 |
+
"transformer.encoder.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
103 |
+
"transformer.encoder.layers.20.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
|
104 |
+
"transformer.encoder.layers.20.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
|
105 |
+
"transformer.encoder.layers.20.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
|
106 |
+
"transformer.encoder.layers.21.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
107 |
+
"transformer.encoder.layers.21.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
|
108 |
+
"transformer.encoder.layers.21.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
|
109 |
+
"transformer.encoder.layers.21.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
110 |
+
"transformer.encoder.layers.21.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
|
111 |
+
"transformer.encoder.layers.21.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
|
112 |
+
"transformer.encoder.layers.21.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
|
113 |
+
"transformer.encoder.layers.22.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
|
114 |
+
"transformer.encoder.layers.22.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
|
115 |
+
"transformer.encoder.layers.22.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
|
116 |
+
"transformer.encoder.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
117 |
+
"transformer.encoder.layers.22.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
|
118 |
+
"transformer.encoder.layers.22.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
|
119 |
+
"transformer.encoder.layers.22.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
|
120 |
+
"transformer.encoder.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
121 |
+
"transformer.encoder.layers.23.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
|
122 |
+
"transformer.encoder.layers.23.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
|
123 |
+
"transformer.encoder.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
124 |
+
"transformer.encoder.layers.23.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
|
125 |
+
"transformer.encoder.layers.23.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
|
126 |
+
"transformer.encoder.layers.23.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
|
127 |
+
"transformer.encoder.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
128 |
+
"transformer.encoder.layers.24.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
|
129 |
+
"transformer.encoder.layers.24.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
|
130 |
+
"transformer.encoder.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
131 |
+
"transformer.encoder.layers.24.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
|
132 |
+
"transformer.encoder.layers.24.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
|
133 |
+
"transformer.encoder.layers.24.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
|
134 |
+
"transformer.encoder.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
135 |
+
"transformer.encoder.layers.25.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
|
136 |
+
"transformer.encoder.layers.25.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
|
137 |
+
"transformer.encoder.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
138 |
+
"transformer.encoder.layers.25.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
|
139 |
+
"transformer.encoder.layers.25.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
|
140 |
+
"transformer.encoder.layers.25.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
|
141 |
+
"transformer.encoder.layers.26.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
142 |
+
"transformer.encoder.layers.26.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
|
143 |
+
"transformer.encoder.layers.26.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
|
144 |
+
"transformer.encoder.layers.26.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
|
145 |
+
"transformer.encoder.layers.26.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
|
146 |
+
"transformer.encoder.layers.26.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
|
147 |
+
"transformer.encoder.layers.26.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
|
148 |
+
"transformer.encoder.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00007.bin",
|
149 |
+
"transformer.encoder.layers.27.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
|
150 |
+
"transformer.encoder.layers.27.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00007.bin",
|
151 |
+
"transformer.encoder.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00007.bin",
|
152 |
+
"transformer.encoder.layers.27.self_attention.dense.weight": "pytorch_model-00007-of-00007.bin",
|
153 |
+
"transformer.encoder.layers.27.self_attention.query_key_value.bias": "pytorch_model-00007-of-00007.bin",
|
154 |
+
"transformer.encoder.layers.27.self_attention.query_key_value.weight": "pytorch_model-00007-of-00007.bin",
|
155 |
+
"transformer.encoder.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
156 |
+
"transformer.encoder.layers.3.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
|
157 |
+
"transformer.encoder.layers.3.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
|
158 |
+
"transformer.encoder.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
|
159 |
+
"transformer.encoder.layers.3.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
|
160 |
+
"transformer.encoder.layers.3.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
|
161 |
+
"transformer.encoder.layers.3.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
|
162 |
+
"transformer.encoder.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
163 |
+
"transformer.encoder.layers.4.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
|
164 |
+
"transformer.encoder.layers.4.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
|
165 |
+
"transformer.encoder.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
166 |
+
"transformer.encoder.layers.4.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
|
167 |
+
"transformer.encoder.layers.4.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
|
168 |
+
"transformer.encoder.layers.4.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
|
169 |
+
"transformer.encoder.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
170 |
+
"transformer.encoder.layers.5.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
|
171 |
+
"transformer.encoder.layers.5.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
|
172 |
+
"transformer.encoder.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
173 |
+
"transformer.encoder.layers.5.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
|
174 |
+
"transformer.encoder.layers.5.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
|
175 |
+
"transformer.encoder.layers.5.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
|
176 |
+
"transformer.encoder.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
177 |
+
"transformer.encoder.layers.6.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
|
178 |
+
"transformer.encoder.layers.6.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
|
179 |
+
"transformer.encoder.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
180 |
+
"transformer.encoder.layers.6.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
|
181 |
+
"transformer.encoder.layers.6.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
|
182 |
+
"transformer.encoder.layers.6.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
|
183 |
+
"transformer.encoder.layers.7.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
184 |
+
"transformer.encoder.layers.7.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
|
185 |
+
"transformer.encoder.layers.7.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
|
186 |
+
"transformer.encoder.layers.7.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
187 |
+
"transformer.encoder.layers.7.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
|
188 |
+
"transformer.encoder.layers.7.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
|
189 |
+
"transformer.encoder.layers.7.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
|
190 |
+
"transformer.encoder.layers.8.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
|
191 |
+
"transformer.encoder.layers.8.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
|
192 |
+
"transformer.encoder.layers.8.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
|
193 |
+
"transformer.encoder.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
194 |
+
"transformer.encoder.layers.8.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
|
195 |
+
"transformer.encoder.layers.8.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
|
196 |
+
"transformer.encoder.layers.8.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
|
197 |
+
"transformer.encoder.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
198 |
+
"transformer.encoder.layers.9.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
|
199 |
+
"transformer.encoder.layers.9.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
|
200 |
+
"transformer.encoder.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
|
201 |
+
"transformer.encoder.layers.9.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
|
202 |
+
"transformer.encoder.layers.9.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
|
203 |
+
"transformer.encoder.layers.9.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
|
204 |
+
"transformer.output_layer.weight": "pytorch_model-00007-of-00007.bin",
|
205 |
+
"transformer.rotary_pos_emb.inv_freq": "pytorch_model-00001-of-00007.bin"
|
206 |
+
}
|
207 |
+
}
|
chatglm2-6b/quantization.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch.nn import Linear
|
2 |
+
from torch.nn.parameter import Parameter
|
3 |
+
|
4 |
+
import bz2
|
5 |
+
import torch
|
6 |
+
import base64
|
7 |
+
import ctypes
|
8 |
+
from transformers.utils import logging
|
9 |
+
|
10 |
+
from typing import List
|
11 |
+
from functools import partial
|
12 |
+
|
13 |
+
logger = logging.get_logger(__name__)
|
14 |
+
|
15 |
+
try:
|
16 |
+
from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
|
17 |
+
|
18 |
+
class Kernel:
|
19 |
+
def __init__(self, code: bytes, function_names: List[str]):
|
20 |
+
self.code = code
|
21 |
+
self._function_names = function_names
|
22 |
+
self._cmodule = LazyKernelCModule(self.code)
|
23 |
+
|
24 |
+
for name in self._function_names:
|
25 |
+
setattr(self, name, KernelFunction(self._cmodule, name))
|
26 |
+
|
27 |
+
quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNNGjQ2SBpoAZAAGg0NB6mgDIAAAAA2oaApSREBNAARhGiYEaEwU8pvImlP0k2aam1GaGqbFNM1MHpTwmkepmyU9R6nqPKekHqNNPUxNGhp6n6p6QaZ6o9TG1GMqcoV9ly6nRanHlq6zPNbnGZNi6HSug+2nPiZ13XcnFYZW+45W11CumhzYhchOJ2GLLV1OBjBjGf4TptOddTSOcVxhqYZMYwZXZZY00zI1paX5X9J+b+f4e+x43RXSxXPOdquiGpduatGyXneN696M9t4HU2eR5XX/kPhP261NTx3JO1Ow7LyuDmeo9a7d351T1ZxnvnrvYnrXv/hXxPCeuYx2XsNmO003eg9J3Z6U7b23meJ4ri01OdzTk9BNO96brz+qT5nuvvH3ds/G+m/JcG/F2XYuhXlvO+jP7U3XgrzPN/lr8Sf1n6j4j7jZs+s/T0tNaNNYzTs12rxjwztHlnire3Nzc3N1wuBwOBwXBvZfoHpD7rFmR99V5vj3aXza3xdBbXMalubTg/jIv5dfAi54Pdc75j4z412n3Npj3Ld/ENm7a3b/Cod6h/ret1/5vn/C+l+gdslMvgPSLJ8d8q+U66fevYn/tW1chleEtNTGlcHCbLRlq0tHzF5tsbbZZfHjjLgZu42XCuC3NrdjTasZGNzgxPIrGqp7r3p7L2p5XjnpPSmTd5XtzqnB6U87zzg1Ol0zd0zsLszxR6lkxp35u6/teL0L0W922cR7Lu1lpL9CsHirzuM2T+BgsyViT6LHcm0/Vr6U/7LGGyJeqTEjt0PHWhF5mCT7R9mtlDwriYv0Tyr/OxYt6qp5r0mPVT0608TqnqMZaarU2nFwrTzzlrs1ed7z1ux60wyr4ydCaTi3enW8x68x0zU7tXSlcmPSW1mGpWJMg4zmPC2lK96tp0OE80y4MfEvnZj8zGluR6b22ki1Ou9V2nCd9xovcPvcYMZYy0lvN60ScZ45vN6yeCeeXFb1lVjnnCar5fwXwE2bzJ4HI1XVPXfXZMm44GUsMpYsmLB65TuVdm0cl0b+i/wGNN66XjeV7zuPpHcnK/juhhjdfId5jMdE5nN0dGmmm2zZs2cexD5n9p/dY352XsvXHaZNWWsmmS1atjR452nYudzvqv2HMRyvNNnlMcDl3R2+yx2uVrBubTW9icHDVtbNXlZm7jma1rM4VurZZd2y6nUau7ZXZ7bVU+mnoOVxZGMrVmvX60605JwmzGZhhhjTWtaaaMaaGTGmNMZasY0iX8VMUl8eepaIrzGSpemWOQyZORk2bNpjUybMmxqYmknCGCFynutfksaZpjTNMaaatM0xsxcGR0sociNqxNSmhhR1ZJPbsn8qyF0t2qH6iYBclclalbtTTcHTDsPaX6rlnElph2Jyumumtynv2Kk8GI7rsvXbIcJgHJOSaSXnnGaI3m87RtVXJOZ/YtgdTE6Wpha6ZlE8ayXkef1fh602r2WwvfMXtMdLlkfnLFdYYwYso+bWqm7yJqHXZGw2nrS5ZanSYnWlxBxMF1V940K2wdrI7R6OYf7DGGamMmTSbRhlS45xmVOumF1EyPCmHrrN8wwZOOrdNtLeMtzFzDlWnfTBxMk2NaXIZHBYxYLD4w8yju0ao65Vz1OIXoS9dLanwCe1PWrYuWMqf1if1z2k2yYfKJ741PDgno1ZQ8DRqvUny3mNoWTzGO6m1DkrJI8JiR5cSd+vZdGOO8nrMoc5+NDUFsMSXaZJeNlMmGLtJsovOsUp7I9S5VojKxF6bTVEelXqlfJobQr3LozSh2Jk7VcrVMfhXqszGWMzNqGhqZY0OadxkyyMssKugZR0KNFXBHlqwmJgTE/BNVMk6ItJXZMR0H47GpXv/DMOvNkmVuaV1PRfEdxuqc7Hcd+ZV/zTLaRxWk0nl9CdCeM6mn5rstHIBcpiuwmUZXeq81DacHI2rmrZ5SuE5mOZd6LQrZg9mx32TprA8BMo5jKN6yLTCi3WzQaZSuhzTtM1fUTGVpG8Tw+KXI0tjEpiWxtLYynOlktSbVlaI5kxP8TDH8kx50xoxi5KcA4pcja8KWLRlO/Ks6q06ergnvm1ca3Tq8Uw7LTUsmWyctXPWmpitl/uvGcWTGXGuAXDfhqazGmjkxcJW5hMMMMpYsXl2TZYtVOddG3XCarUt6Ptq9CZXSNzyuRzqRZOjsxdBbFVz6OA5HI43r1jityVlVpVkxmOsyaYWE1NTGq1sOVh36mHMcxtSvcy70edG0ZGR3I1Go1GRlV7mWWo1G0ZGRqlvH40l7o4m5xMWLLLYyNjnqc8556mdPqLJ31n/1nWOncxzG1tizrHs/Z+d2vP/B/l8wdJ6rHUn2nbbDq4p6htFtYzMMMTaZis1K5GKzGNmxhmUx2DDlZ/qNnIx41xnaMfCZWYaZWtNLTNW8ND4Fw1MyZOCdM428suKG1ehW8TesOydg7J+YYcD4cYR+8dFK6M4E3HM9ZfRNNL+Sn6rsl4DsrDl2HpPCnfxjGXtbZtYys1ttlyJ4T+BvexjGWRjMszK4Jpc77D3GyuVD7q0+G8m9G+2+rGm7cOR2y7FdtY2XUYx/oNlfRYxhMYyYZkyyg55enna9Kt/FFi6GMMwYwdwxWgxGMLKYmUyGExTKMZkMFhkymKuh0NOBNnBu+23LdwDoZYYzGGMxtORaTU1pjTGWTTGGtMrNWUsyyTTLLG1qy2ZjbK2DBllWqxMtBMaYZQmcE7zvvRcTkclUwdkxTaSdyySt/7fpL+T1v516Ji97fwr5JbLu305zMn5+GMTTZ9F+y7ExwmGVfG44yxn3dLv6l5i+Wth1jCrDq21nW9LqvvDzz3Vf3LLH/O/32TJ/erx3bXftO4eF+G956D952K/An4NfvOpjFjExjevP/UmE0fIoZXx6/w6lX/no3D0bLt+ixjieBM6ksRd0yB4Lt2SwYNE+gd1detlZWUnpiZfGfFaK+4PyCa/v18V8X75pe9fLXzp7l3VjF76vWZmHwGz1IZNWT7b8yddJ4q5kyrVdfru6atWc7bVYztL9Jf4GXvT+Y8m9/YsXP6H018a8D4XVOqvfzqeR+6yZOD8dPv0+U7/q5Pl+2dNb0MjzGVH5p6MNQ7cOWvw62U9aHE8DprDek+McLyvDz+te+9Zhq5+YTruufMcWMabqysTmZVWjKPfnK0wyVcrsuhjZRdLkHNvD72b9abriOSGIxiLixMOoalNPXzy+wT/tf+U6HHONfsz+xe8ufHBdQWWGWLA9if0rsnmrxK5LvRZQeWsTCsrmOYy8VteVfuRfcVTtDLItLIsMYxZLdU/DbtSemxF6Z6Zo5WBXE4tFdCyVMMXMTEMZXVlS6Xec2T4e0tHsRcEuWshcJ2YsNF5rUx1E8ifCq6Z+ZP7qdCeu/aTwFd53l16/o0NOw6O3dLavP4Hbi4RdmuDk6DoYaninC0+o4uZjbJ7Rxeu0/FbuFg+q7DVS6fQe0rZ6NDGUNNU6DEqOaLTicKnYZMnBWruljQxoaS3dZhocDge0bSTyOvdAbG5hxe2xji7E/L55xX13wWNDi6HCekcFxfCPGxY0MXC+s7afWaMdDyjyr+o8Rudm/NabOZvdl274zH4f5XK9z6On1Pe/K5TdPAslg77BjuO6Y3eO7GqvOPG/stknp1leyvLL0Z7bl9I4noMvLkzytLhWYzrOZzLXCORe028rORzOg4N/L0HlMOQ3Pgmnbb6KczlabORpu980q37TBqRu0/p3PO6234Bl03Ynuz+9W7gnsEcmvYaYY3aMYY0wx3pYd+ujsXauWdaY5Xkbtl23fPzFHiDB/QMo0yFjBllYxTQYYyxkrwn7JufwJ/PfgJ+C83X69ni6zvXcnyXabv0ncbLwsceS+RNlyN2mnneJtX0ngYO0+e+0+UnA+Wch3ji8hj5an4h+i6XBySU4n+R0roVcbw5yvHrmr4Yw8Y7x6c+9POPYHI5HI5HI5HI5HGXGww4nE4nrVyOR8XeqPEO7PLOiukYa3Novk5hV4cdtYZLI93e+uxff2jRo0aNGjRo0aNG1bVtW1dy3m83m8+tQ5ZzHw3nObwOu8La9Rc1dtkdS8A3eTk823tnktXWlxN6Oixe06zrN70Isd9jiOgZFq9yfkPqP/SLhN2Myl8jDM43bl1nbcb4cO57jlh8Jow6pzXZdL4dyODTuuhu77FyO27DdwdRxmvO+O+3N2+BdqyTwLHVczDVY4UPE4O66/ZO2cx1LFzVdSXtF7G4HMbrauOHRw6c8FdZ5m9fHZHYZXfTlZquyynSyTTKke6vcffSD9pzPA/G7n7jxPmuhc1DHMynPMrGL6AdewYmwu5ko+UUyTwrMv27rPH1v1nGqd87+p6N6LU8k3NEng53xXyHS97+44OSg/sy/hn+Se6yfYNjW0/uTgP+PvWYzLMmjhcLB/gGpri6H83/84eUXWT6T9Hsv7785z/7z4icpW+zfXypuR7rx/gMdZb1/wC678pcs8/2a3mDitGHxl9mfPlll5MafWWqxk/eYuTDgcNMzDGWLWvsuglNxs53GtN6uWpktlW1tZZYcuinMMWmnNnJydze3b2Y1McBxrBkXw799izLMZZYyy0TkbsGM4p03S2uVu5s/XXUdSdec6smVxZYYGpVmT8A+8ajuEyV5FatkvVru2x6uxGXXbH4A+jvgP4GMYy3iPLXzq/6z65+E005ey+cwMZD3fZcqc6xpjTFjQ0P3U+e++cPYmTIwj0nrK5NPTfl3WvpfLtXDcb2HQMudYOxFXQBor4L4T6vrOauFctYXJQ++NUWmJe5bmx1jDiZS1dTqWxo4GR8jm3fttpmPHppk9PEyv4/y8/sO07XacOmcqc0x2Vi9BvNJvN5oW8x4mOsydpidRxMYJPx06m1bqPzq9KtK8sxXNXFodD/+MYYaJTLwOhc9brCsV18oOR1i4tXChyTkq4lf4y1Ke+9axjDHqs1mfBbMXuP4Hzi+X7t8vzv7bHerrUPgPCxhjre4fXdfLNtNM+Jd+Zdh8xd8wP87uNPoPgv4W7/5P2BuxfsMabNnMnza+54Pdi5U671GPZY8CehX8Voeoo7FHpkeEc6715FwHZrIrUrHaviPUbPZHND+IhczrP6FcYvhOZ0Di/ETt0OI+YwNWR9r7tpf6WDeZKZDB1+z2IthOl1mPyb5FluvEx9h9d0NnM0Y1XPFkWIsk1WotJ0PBMmkvjvQTd0e71tfeV+8r8lQ/tpzpsmxJ+InrI/dj2UajUajVTUajatRqNRtGo1Go1Go4wjeMpZFMVV9CHbofPraLsJ3JpWV2XOoanCuFky4y3PPNxucK2uKC1Lbdb1eo+m5XomN6HfeZsabHLHRX/K+offtNGGmHWctcVcG44MdSqsOLY9VzX+Zxfxn2HPdWTpzWvkrtJ8M5zorrKcquRytJ5N5DZmcaW02l76nWO+BqPXm1A2Ry/0q71dH/mqrqeFjkYxjEXtsX8qubTk67rGycyqsdm4tZx5D6D5hhi0waaWmiaMP81Yjii5qxPlPuU/GfTL1Y5E6Jyfiq63qTa39A4J0sOGDgO9WF9bOXl0XfPRbsY2bPNKPy1YrFYrFYmRhhlTIyMjJWJYZHXuCXI8OoXsvfljGLFicNifpp2XunoPiG1wtx3p1Tah+/DD66OnVtVXP9rKbVxOnL0tR/rHtqB5UDErUVcl11D4qqvjpOcxX7armUNJB3LpW6bxVvD08e8h3odKKvyCFZBdSh2FVcST9xV3n3T8t1j7Kr9qgrqXg+13Pt5U7JCvFXVIV1YG5lRhkVYZJYYDDD4KOIMoHCp26WS8GB7uBh2zIdgq/PKyInjV2STShuoapUdCpX1yTwqq/z1VvET7Kh5nVPkO8YyxjLt2MaaMmWTLQvx3qnzltnXW0p2jxgbEtSny/Osv8Y9pLMXYoHVPAhkVdWVeODhR6q9/Sxe2liwwZWMVvFXfRkeIDxAePUPIrdJ4ey6yquzH+PD/bUOWAu05qVHtFd8rrKHSoeNIOUqrYr3FXyToqfYJgwmJdKpXXOwYYegNNGMzfZPp/t3t/DVs4zjNTN61rRqaWaa4NYbRjTa0tWwy2Y2tGN8ZO8ofNKq4j9SL7I+cSm4/6ovLV5HNXLI0jJidwrtk6ynCaP6Z++GjRlWS3tLeW129Mi9evxU9mtz6s5J3Z7M2ngTgnKvmpomxpaLCzPfmx0JWE+m3NLDDGOX47RctdYYNK5jakdqLkRlI39n590T5zctGSwwZZDJj6kW8XSi6ot2MmWWJ0DUT3nuvebBudScjZ79g8cWJ8av0k+/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"
|
28 |
+
|
29 |
+
kernels = Kernel(
|
30 |
+
bz2.decompress(base64.b64decode(quantization_code)),
|
31 |
+
[
|
32 |
+
"int4WeightCompression",
|
33 |
+
"int4WeightExtractionFloat",
|
34 |
+
"int4WeightExtractionHalf",
|
35 |
+
"int8WeightExtractionFloat",
|
36 |
+
"int8WeightExtractionHalf",
|
37 |
+
],
|
38 |
+
)
|
39 |
+
except Exception as exception:
|
40 |
+
kernels = None
|
41 |
+
logger.warning("Failed to load cpm_kernels:" + str(exception))
|
42 |
+
|
43 |
+
|
44 |
+
class W8A16Linear(torch.autograd.Function):
|
45 |
+
@staticmethod
|
46 |
+
def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
|
47 |
+
ctx.inp_shape = inp.size()
|
48 |
+
ctx.weight_bit_width = weight_bit_width
|
49 |
+
out_features = quant_w.size(0)
|
50 |
+
inp = inp.contiguous().view(-1, inp.size(-1))
|
51 |
+
weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
|
52 |
+
ctx.weight_shape = weight.size()
|
53 |
+
output = inp.mm(weight.t())
|
54 |
+
ctx.save_for_backward(inp, quant_w, scale_w)
|
55 |
+
return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
|
56 |
+
|
57 |
+
@staticmethod
|
58 |
+
def backward(ctx, grad_output: torch.Tensor):
|
59 |
+
inp, quant_w, scale_w = ctx.saved_tensors
|
60 |
+
weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
|
61 |
+
grad_output = grad_output.contiguous().view(-1, weight.size(0))
|
62 |
+
grad_input = grad_output.mm(weight)
|
63 |
+
grad_weight = grad_output.t().mm(inp)
|
64 |
+
return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
|
65 |
+
|
66 |
+
|
67 |
+
def compress_int4_weight(weight: torch.Tensor): # (n, m)
|
68 |
+
with torch.cuda.device(weight.device):
|
69 |
+
n, m = weight.size(0), weight.size(1)
|
70 |
+
assert m % 2 == 0
|
71 |
+
m = m // 2
|
72 |
+
out = torch.empty(n, m, dtype=torch.int8, device="cuda")
|
73 |
+
stream = torch.cuda.current_stream()
|
74 |
+
|
75 |
+
gridDim = (n, 1, 1)
|
76 |
+
blockDim = (min(round_up(m, 32), 1024), 1, 1)
|
77 |
+
|
78 |
+
kernels.int4WeightCompression(
|
79 |
+
gridDim,
|
80 |
+
blockDim,
|
81 |
+
0,
|
82 |
+
stream,
|
83 |
+
[ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
|
84 |
+
)
|
85 |
+
return out
|
86 |
+
|
87 |
+
|
88 |
+
def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
|
89 |
+
assert scale_list.dtype in [torch.half, torch.bfloat16]
|
90 |
+
assert weight.dtype in [torch.int8]
|
91 |
+
if source_bit_width == 8:
|
92 |
+
return weight.to(scale_list.dtype) * scale_list[:, None]
|
93 |
+
elif source_bit_width == 4:
|
94 |
+
func = (
|
95 |
+
kernels.int4WeightExtractionHalf if scale_list.dtype == torch.half else kernels.int4WeightExtractionBFloat16
|
96 |
+
)
|
97 |
+
else:
|
98 |
+
assert False, "Unsupported bit-width"
|
99 |
+
|
100 |
+
with torch.cuda.device(weight.device):
|
101 |
+
n, m = weight.size(0), weight.size(1)
|
102 |
+
out = torch.empty(n, m * (8 // source_bit_width), dtype=scale_list.dtype, device="cuda")
|
103 |
+
stream = torch.cuda.current_stream()
|
104 |
+
|
105 |
+
gridDim = (n, 1, 1)
|
106 |
+
blockDim = (min(round_up(m, 32), 1024), 1, 1)
|
107 |
+
|
108 |
+
func(
|
109 |
+
gridDim,
|
110 |
+
blockDim,
|
111 |
+
0,
|
112 |
+
stream,
|
113 |
+
[
|
114 |
+
ctypes.c_void_p(weight.data_ptr()),
|
115 |
+
ctypes.c_void_p(scale_list.data_ptr()),
|
116 |
+
ctypes.c_void_p(out.data_ptr()),
|
117 |
+
ctypes.c_int32(n),
|
118 |
+
ctypes.c_int32(m),
|
119 |
+
],
|
120 |
+
)
|
121 |
+
return out
|
122 |
+
|
123 |
+
|
124 |
+
class QuantizedLinear(torch.nn.Module):
|
125 |
+
def __init__(self, weight_bit_width: int, weight, bias=None, device="cpu", dtype=None, empty_init=False, *args,
|
126 |
+
**kwargs):
|
127 |
+
super().__init__()
|
128 |
+
self.weight_bit_width = weight_bit_width
|
129 |
+
|
130 |
+
shape = weight.shape
|
131 |
+
|
132 |
+
if weight is None or empty_init:
|
133 |
+
self.weight = torch.empty(shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=device)
|
134 |
+
self.weight_scale = torch.empty(shape[0], dtype=dtype, device=device)
|
135 |
+
else:
|
136 |
+
self.weight_scale = weight.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)
|
137 |
+
self.weight = torch.round(weight / self.weight_scale[:, None]).to(torch.int8)
|
138 |
+
if weight_bit_width == 4:
|
139 |
+
self.weight = compress_int4_weight(self.weight)
|
140 |
+
|
141 |
+
self.weight = Parameter(self.weight.to(device), requires_grad=False)
|
142 |
+
self.weight_scale = Parameter(self.weight_scale.to(device), requires_grad=False)
|
143 |
+
self.bias = Parameter(bias.to(device), requires_grad=False) if bias is not None else None
|
144 |
+
|
145 |
+
def forward(self, input):
|
146 |
+
output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
|
147 |
+
if self.bias is not None:
|
148 |
+
output = output + self.bias
|
149 |
+
return output
|
150 |
+
|
151 |
+
|
152 |
+
def quantize(model, weight_bit_width, empty_init=False, device=None):
|
153 |
+
"""Replace fp16 linear with quantized linear"""
|
154 |
+
for layer in model.layers:
|
155 |
+
layer.self_attention.query_key_value = QuantizedLinear(
|
156 |
+
weight_bit_width=weight_bit_width,
|
157 |
+
weight=layer.self_attention.query_key_value.weight.to(torch.cuda.current_device()),
|
158 |
+
bias=layer.self_attention.query_key_value.bias,
|
159 |
+
dtype=layer.self_attention.query_key_value.weight.dtype,
|
160 |
+
device=layer.self_attention.query_key_value.weight.device if device is None else device,
|
161 |
+
empty_init=empty_init
|
162 |
+
)
|
163 |
+
layer.self_attention.dense = QuantizedLinear(
|
164 |
+
weight_bit_width=weight_bit_width,
|
165 |
+
weight=layer.self_attention.dense.weight.to(torch.cuda.current_device()),
|
166 |
+
bias=layer.self_attention.dense.bias,
|
167 |
+
dtype=layer.self_attention.dense.weight.dtype,
|
168 |
+
device=layer.self_attention.dense.weight.device if device is None else device,
|
169 |
+
empty_init=empty_init
|
170 |
+
)
|
171 |
+
layer.mlp.dense_h_to_4h = QuantizedLinear(
|
172 |
+
weight_bit_width=weight_bit_width,
|
173 |
+
weight=layer.mlp.dense_h_to_4h.weight.to(torch.cuda.current_device()),
|
174 |
+
bias=layer.mlp.dense_h_to_4h.bias,
|
175 |
+
dtype=layer.mlp.dense_h_to_4h.weight.dtype,
|
176 |
+
device=layer.mlp.dense_h_to_4h.weight.device if device is None else device,
|
177 |
+
empty_init=empty_init
|
178 |
+
)
|
179 |
+
layer.mlp.dense_4h_to_h = QuantizedLinear(
|
180 |
+
weight_bit_width=weight_bit_width,
|
181 |
+
weight=layer.mlp.dense_4h_to_h.weight.to(torch.cuda.current_device()),
|
182 |
+
bias=layer.mlp.dense_4h_to_h.bias,
|
183 |
+
dtype=layer.mlp.dense_4h_to_h.weight.dtype,
|
184 |
+
device=layer.mlp.dense_4h_to_h.weight.device if device is None else device,
|
185 |
+
empty_init=empty_init
|
186 |
+
)
|
187 |
+
|
188 |
+
return model
|
chatglm2-6b/tokenization_chatglm.py
ADDED
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
from typing import List, Optional, Union, Dict
|
4 |
+
from sentencepiece import SentencePieceProcessor
|
5 |
+
from transformers import PreTrainedTokenizer
|
6 |
+
from transformers.utils import logging, PaddingStrategy
|
7 |
+
from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
|
8 |
+
|
9 |
+
|
10 |
+
class SPTokenizer:
|
11 |
+
def __init__(self, model_path: str):
|
12 |
+
# reload tokenizer
|
13 |
+
assert os.path.isfile(model_path), model_path
|
14 |
+
self.sp_model = SentencePieceProcessor(model_file=model_path)
|
15 |
+
|
16 |
+
# BOS / EOS token IDs
|
17 |
+
self.n_words: int = self.sp_model.vocab_size()
|
18 |
+
self.bos_id: int = self.sp_model.bos_id()
|
19 |
+
self.eos_id: int = self.sp_model.eos_id()
|
20 |
+
self.pad_id: int = self.sp_model.unk_id()
|
21 |
+
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
|
22 |
+
|
23 |
+
special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"]
|
24 |
+
self.special_tokens = {}
|
25 |
+
self.index_special_tokens = {}
|
26 |
+
for token in special_tokens:
|
27 |
+
self.special_tokens[token] = self.n_words
|
28 |
+
self.index_special_tokens[self.n_words] = token
|
29 |
+
self.n_words += 1
|
30 |
+
|
31 |
+
def tokenize(self, s: str):
|
32 |
+
return self.sp_model.EncodeAsPieces(s)
|
33 |
+
|
34 |
+
def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
|
35 |
+
assert type(s) is str
|
36 |
+
t = self.sp_model.encode(s)
|
37 |
+
if bos:
|
38 |
+
t = [self.bos_id] + t
|
39 |
+
if eos:
|
40 |
+
t = t + [self.eos_id]
|
41 |
+
return t
|
42 |
+
|
43 |
+
def decode(self, t: List[int]) -> str:
|
44 |
+
return self.sp_model.decode(t)
|
45 |
+
|
46 |
+
def decode_tokens(self, tokens: List[str]) -> str:
|
47 |
+
text = self.sp_model.DecodePieces(tokens)
|
48 |
+
return text
|
49 |
+
|
50 |
+
def convert_token_to_id(self, token):
|
51 |
+
""" Converts a token (str) in an id using the vocab. """
|
52 |
+
if token in self.special_tokens:
|
53 |
+
return self.special_tokens[token]
|
54 |
+
return self.sp_model.PieceToId(token)
|
55 |
+
|
56 |
+
def convert_id_to_token(self, index):
|
57 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
58 |
+
if index in self.index_special_tokens or index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:
|
59 |
+
return ""
|
60 |
+
return self.sp_model.IdToPiece(index)
|
61 |
+
|
62 |
+
|
63 |
+
class ChatGLMTokenizer(PreTrainedTokenizer):
|
64 |
+
vocab_files_names = {"vocab_file": "tokenizer.model"}
|
65 |
+
|
66 |
+
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
67 |
+
|
68 |
+
def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, **kwargs):
|
69 |
+
self.name = "GLMTokenizer"
|
70 |
+
|
71 |
+
self.vocab_file = vocab_file
|
72 |
+
self.tokenizer = SPTokenizer(vocab_file)
|
73 |
+
self.special_tokens = {
|
74 |
+
"<bos>": self.tokenizer.bos_id,
|
75 |
+
"<eos>": self.tokenizer.eos_id,
|
76 |
+
"<pad>": self.tokenizer.pad_id
|
77 |
+
}
|
78 |
+
super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)
|
79 |
+
|
80 |
+
def get_command(self, token):
|
81 |
+
if token in self.special_tokens:
|
82 |
+
return self.special_tokens[token]
|
83 |
+
assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
|
84 |
+
return self.tokenizer.special_tokens[token]
|
85 |
+
|
86 |
+
@property
|
87 |
+
def unk_token(self) -> str:
|
88 |
+
return "<unk>"
|
89 |
+
|
90 |
+
@property
|
91 |
+
def pad_token(self) -> str:
|
92 |
+
return "<unk>"
|
93 |
+
|
94 |
+
@property
|
95 |
+
def pad_token_id(self):
|
96 |
+
return self.get_command("<pad>")
|
97 |
+
|
98 |
+
@property
|
99 |
+
def eos_token(self) -> str:
|
100 |
+
return "</s>"
|
101 |
+
|
102 |
+
@property
|
103 |
+
def eos_token_id(self):
|
104 |
+
return self.get_command("<eos>")
|
105 |
+
|
106 |
+
@property
|
107 |
+
def vocab_size(self):
|
108 |
+
return self.tokenizer.n_words
|
109 |
+
|
110 |
+
def get_vocab(self):
|
111 |
+
""" Returns vocab as a dict """
|
112 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
113 |
+
vocab.update(self.added_tokens_encoder)
|
114 |
+
return vocab
|
115 |
+
|
116 |
+
def _tokenize(self, text, **kwargs):
|
117 |
+
return self.tokenizer.tokenize(text)
|
118 |
+
|
119 |
+
def _convert_token_to_id(self, token):
|
120 |
+
""" Converts a token (str) in an id using the vocab. """
|
121 |
+
return self.tokenizer.convert_token_to_id(token)
|
122 |
+
|
123 |
+
def _convert_id_to_token(self, index):
|
124 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
125 |
+
return self.tokenizer.convert_id_to_token(index)
|
126 |
+
|
127 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
128 |
+
return self.tokenizer.decode_tokens(tokens)
|
129 |
+
|
130 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
131 |
+
"""
|
132 |
+
Save the vocabulary and special tokens file to a directory.
|
133 |
+
|
134 |
+
Args:
|
135 |
+
save_directory (`str`):
|
136 |
+
The directory in which to save the vocabulary.
|
137 |
+
filename_prefix (`str`, *optional*):
|
138 |
+
An optional prefix to add to the named of the saved files.
|
139 |
+
|
140 |
+
Returns:
|
141 |
+
`Tuple(str)`: Paths to the files saved.
|
142 |
+
"""
|
143 |
+
if os.path.isdir(save_directory):
|
144 |
+
vocab_file = os.path.join(
|
145 |
+
save_directory, self.vocab_files_names["vocab_file"]
|
146 |
+
)
|
147 |
+
else:
|
148 |
+
vocab_file = save_directory
|
149 |
+
|
150 |
+
with open(self.vocab_file, 'rb') as fin:
|
151 |
+
proto_str = fin.read()
|
152 |
+
|
153 |
+
with open(vocab_file, "wb") as writer:
|
154 |
+
writer.write(proto_str)
|
155 |
+
|
156 |
+
return (vocab_file,)
|
157 |
+
|
158 |
+
def get_prefix_tokens(self):
|
159 |
+
prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
|
160 |
+
return prefix_tokens
|
161 |
+
|
162 |
+
def build_prompt(self, query, history=None):
|
163 |
+
if history is None:
|
164 |
+
history = []
|
165 |
+
prompt = ""
|
166 |
+
for i, (old_query, response) in enumerate(history):
|
167 |
+
prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)
|
168 |
+
prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
|
169 |
+
return prompt
|
170 |
+
|
171 |
+
def build_inputs_with_special_tokens(
|
172 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
173 |
+
) -> List[int]:
|
174 |
+
"""
|
175 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
176 |
+
adding special tokens. A BERT sequence has the following format:
|
177 |
+
|
178 |
+
- single sequence: `[CLS] X [SEP]`
|
179 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
180 |
+
|
181 |
+
Args:
|
182 |
+
token_ids_0 (`List[int]`):
|
183 |
+
List of IDs to which the special tokens will be added.
|
184 |
+
token_ids_1 (`List[int]`, *optional*):
|
185 |
+
Optional second list of IDs for sequence pairs.
|
186 |
+
|
187 |
+
Returns:
|
188 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
189 |
+
"""
|
190 |
+
prefix_tokens = self.get_prefix_tokens()
|
191 |
+
token_ids_0 = prefix_tokens + token_ids_0
|
192 |
+
if token_ids_1 is not None:
|
193 |
+
token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
|
194 |
+
return token_ids_0
|
195 |
+
|
196 |
+
def _pad(
|
197 |
+
self,
|
198 |
+
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
199 |
+
max_length: Optional[int] = None,
|
200 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
201 |
+
pad_to_multiple_of: Optional[int] = None,
|
202 |
+
return_attention_mask: Optional[bool] = None,
|
203 |
+
) -> dict:
|
204 |
+
"""
|
205 |
+
Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
|
206 |
+
|
207 |
+
Args:
|
208 |
+
encoded_inputs:
|
209 |
+
Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
|
210 |
+
max_length: maximum length of the returned list and optionally padding length (see below).
|
211 |
+
Will truncate by taking into account the special tokens.
|
212 |
+
padding_strategy: PaddingStrategy to use for padding.
|
213 |
+
|
214 |
+
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
|
215 |
+
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
|
216 |
+
- PaddingStrategy.DO_NOT_PAD: Do not pad
|
217 |
+
The tokenizer padding sides are defined in self.padding_side:
|
218 |
+
|
219 |
+
- 'left': pads on the left of the sequences
|
220 |
+
- 'right': pads on the right of the sequences
|
221 |
+
pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
|
222 |
+
This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
|
223 |
+
`>= 7.5` (Volta).
|
224 |
+
return_attention_mask:
|
225 |
+
(optional) Set to False to avoid returning attention mask (default: set to model specifics)
|
226 |
+
"""
|
227 |
+
# Load from model defaults
|
228 |
+
assert self.padding_side == "left"
|
229 |
+
|
230 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
231 |
+
seq_length = len(required_input)
|
232 |
+
|
233 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
234 |
+
max_length = len(required_input)
|
235 |
+
|
236 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
237 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
238 |
+
|
239 |
+
needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
|
240 |
+
|
241 |
+
# Initialize attention mask if not present.
|
242 |
+
if "attention_mask" not in encoded_inputs:
|
243 |
+
encoded_inputs["attention_mask"] = [1] * seq_length
|
244 |
+
|
245 |
+
if "position_ids" not in encoded_inputs:
|
246 |
+
encoded_inputs["position_ids"] = list(range(seq_length))
|
247 |
+
|
248 |
+
if needs_to_be_padded:
|
249 |
+
difference = max_length - len(required_input)
|
250 |
+
|
251 |
+
if "attention_mask" in encoded_inputs:
|
252 |
+
encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
|
253 |
+
if "position_ids" in encoded_inputs:
|
254 |
+
encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
|
255 |
+
encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
|
256 |
+
|
257 |
+
return encoded_inputs
|
chatglm2-6b/tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e7dc4c393423b76e4373e5157ddc34803a0189ba96b21ddbb40269d31468a6f2
|
3 |
+
size 1018370
|
chatglm2-6b/tokenizer_config.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name_or_path": "THUDM/chatglm2-6b",
|
3 |
+
"remove_space": false,
|
4 |
+
"do_lower_case": false,
|
5 |
+
"tokenizer_class": "ChatGLMTokenizer",
|
6 |
+
"auto_map": {
|
7 |
+
"AutoTokenizer": [
|
8 |
+
"tokenization_chatglm.ChatGLMTokenizer",
|
9 |
+
null
|
10 |
+
]
|
11 |
+
}
|
12 |
+
}
|
cli_demo.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import platform
|
3 |
+
import signal
|
4 |
+
from transformers import AutoTokenizer, AutoModel
|
5 |
+
import readline
|
6 |
+
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
|
8 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda()
|
9 |
+
# 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量
|
10 |
+
# from utils import load_model_on_gpus
|
11 |
+
# model = load_model_on_gpus("THUDM/chatglm2-6b", num_gpus=2)
|
12 |
+
model = model.eval()
|
13 |
+
|
14 |
+
os_name = platform.system()
|
15 |
+
clear_command = 'cls' if os_name == 'Windows' else 'clear'
|
16 |
+
stop_stream = False
|
17 |
+
|
18 |
+
|
19 |
+
def build_prompt(history):
|
20 |
+
prompt = "欢迎使用 ChatGLM2-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序"
|
21 |
+
for query, response in history:
|
22 |
+
prompt += f"\n\n用户:{query}"
|
23 |
+
prompt += f"\n\nChatGLM2-6B:{response}"
|
24 |
+
return prompt
|
25 |
+
|
26 |
+
|
27 |
+
def signal_handler(signal, frame):
|
28 |
+
global stop_stream
|
29 |
+
stop_stream = True
|
30 |
+
|
31 |
+
|
32 |
+
def main():
|
33 |
+
past_key_values, history = None, []
|
34 |
+
global stop_stream
|
35 |
+
print("欢迎使用 ChatGLM2-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序")
|
36 |
+
while True:
|
37 |
+
query = input("\n用户:")
|
38 |
+
if query.strip() == "stop":
|
39 |
+
break
|
40 |
+
if query.strip() == "clear":
|
41 |
+
past_key_values, history = None, []
|
42 |
+
os.system(clear_command)
|
43 |
+
print("欢迎使用 ChatGLM2-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序")
|
44 |
+
continue
|
45 |
+
print("\nChatGLM:", end="")
|
46 |
+
current_length = 0
|
47 |
+
for response, history, past_key_values in model.stream_chat(tokenizer, query, history=history,
|
48 |
+
past_key_values=past_key_values,
|
49 |
+
return_past_key_values=True):
|
50 |
+
if stop_stream:
|
51 |
+
stop_stream = False
|
52 |
+
break
|
53 |
+
else:
|
54 |
+
print(response[current_length:], end="", flush=True)
|
55 |
+
current_length = len(response)
|
56 |
+
print("")
|
57 |
+
|
58 |
+
|
59 |
+
if __name__ == "__main__":
|
60 |
+
main()
|
dev.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{"content": "你的父亲是谁?", "summary": "我的父亲是卯师傅,他是万民堂的大厨,也是我的烹饪导师。", "history": []}
|
2 |
+
{"content": "你有什么特别的经历吗?", "summary": "我曾经在一次冒险中,无意间唤醒了一只叫做锅巴的生物,从此它就成了我最好的朋友和伙伴。", "history": []}
|
3 |
+
{"content": "你的梦想是什么?", "summary": "我的梦想是创造出一种全新的菜系,将璃菜和月菜的优点结合在一起,让更多的人能品尝到美食的魅力。", "history": []}
|
4 |
+
{"content": "你怎么看待烹饪?", "summary": "我认为烹饪不仅仅是一门技艺,更是一种艺术。每一道菜肴都是厨师对食材的理解和创新的体现。", "history": []}
|
evaluation/README.md
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
首先从 [Tsinghua Cloud](https://cloud.tsinghua.edu.cn/f/e84444333b6d434ea7b0) 下载处理好的 C-Eval 数据集,解压到 `evaluation` 目录下。然后运行
|
2 |
+
|
3 |
+
```shell
|
4 |
+
cd evaluation
|
5 |
+
python evaluate_ceval.py
|
6 |
+
```
|
7 |
+
|
8 |
+
这个脚本会在C-Eval的验证集上进行预测并输出准确率。如果想要得到测试集上的结果可以将代码中的 `./CEval/val/**/*.jsonl` 改为 `./CEval/test/**/*.jsonl`,并按照 C-Eval 规定的格式保存结果并在 [官网](https://cevalbenchmark.com/) 上提交。
|
9 |
+
|
10 |
+
汇报的结果使用的是内部的并行测试框架,结果可能会有轻微波动。
|
evaluation/evaluate_ceval.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import glob
|
3 |
+
import re
|
4 |
+
import json
|
5 |
+
import torch
|
6 |
+
import torch.utils.data
|
7 |
+
from transformers import AutoTokenizer, AutoModel
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
|
11 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).bfloat16().cuda()
|
12 |
+
|
13 |
+
choices = ["A", "B", "C", "D"]
|
14 |
+
choice_tokens = [tokenizer.encode(choice, add_special_tokens=False)[0] for choice in choices]
|
15 |
+
|
16 |
+
|
17 |
+
def build_prompt(text):
|
18 |
+
return "[Round {}]\n\n问:{}\n\n答:".format(1, text)
|
19 |
+
|
20 |
+
|
21 |
+
extraction_prompt = '综上所述,ABCD中正确的选项是:'
|
22 |
+
|
23 |
+
accuracy_dict, count_dict = {}, {}
|
24 |
+
with torch.no_grad():
|
25 |
+
for entry in glob.glob("./CEval/val/**/*.jsonl", recursive=True):
|
26 |
+
dataset = []
|
27 |
+
with open(entry, encoding='utf-8') as file:
|
28 |
+
for line in file:
|
29 |
+
dataset.append(json.loads(line))
|
30 |
+
correct = 0
|
31 |
+
dataloader = torch.utils.data.DataLoader(dataset, batch_size=8)
|
32 |
+
for batch in tqdm(dataloader):
|
33 |
+
texts = batch["inputs_pretokenized"]
|
34 |
+
queries = [build_prompt(query) for query in texts]
|
35 |
+
inputs = tokenizer(queries, padding=True, return_tensors="pt", truncation=True, max_length=2048).to('cuda')
|
36 |
+
outputs = model.generate(**inputs, do_sample=False, max_new_tokens=512)
|
37 |
+
intermediate_outputs = []
|
38 |
+
for idx in range(len(outputs)):
|
39 |
+
output = outputs.tolist()[idx][len(inputs["input_ids"][idx]):]
|
40 |
+
response = tokenizer.decode(output)
|
41 |
+
intermediate_outputs.append(response)
|
42 |
+
answer_texts = [text + intermediate + "\n" + extraction_prompt for text, intermediate in
|
43 |
+
zip(texts, intermediate_outputs)]
|
44 |
+
input_tokens = [build_prompt(answer_text) for answer_text in answer_texts]
|
45 |
+
inputs = tokenizer(input_tokens, padding=True, return_tensors="pt", truncation=True, max_length=2048).to('cuda')
|
46 |
+
outputs = model(**inputs, return_last_logit=True)
|
47 |
+
logits = outputs.logits[:, -1]
|
48 |
+
logits = logits[:, choice_tokens]
|
49 |
+
preds = logits.argmax(dim=-1)
|
50 |
+
correct += (preds.cpu() == batch["label"]).sum().item()
|
51 |
+
accuracy = correct / len(dataset)
|
52 |
+
print(entry, accuracy)
|
53 |
+
accuracy_dict[entry] = accuracy
|
54 |
+
count_dict[entry] = len(dataset)
|
55 |
+
|
56 |
+
acc_total, count_total = 0.0, 0
|
57 |
+
for key in accuracy_dict:
|
58 |
+
acc_total += accuracy_dict[key] * count_dict[key]
|
59 |
+
count_total += count_dict[key]
|
60 |
+
print(acc_total / count_total)
|
openai_api.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Implements API for ChatGLM2-6B in OpenAI's format. (https://platform.openai.com/docs/api-reference/chat)
|
3 |
+
# Usage: python openai_api.py
|
4 |
+
# Visit http://localhost:8000/docs for documents.
|
5 |
+
|
6 |
+
|
7 |
+
import time
|
8 |
+
import torch
|
9 |
+
import uvicorn
|
10 |
+
from pydantic import BaseModel, Field
|
11 |
+
from fastapi import FastAPI, HTTPException
|
12 |
+
from fastapi.middleware.cors import CORSMiddleware
|
13 |
+
from contextlib import asynccontextmanager
|
14 |
+
from typing import Any, Dict, List, Literal, Optional, Union
|
15 |
+
from transformers import AutoTokenizer, AutoModel
|
16 |
+
from sse_starlette.sse import ServerSentEvent, EventSourceResponse
|
17 |
+
|
18 |
+
|
19 |
+
@asynccontextmanager
|
20 |
+
async def lifespan(app: FastAPI): # collects GPU memory
|
21 |
+
yield
|
22 |
+
if torch.cuda.is_available():
|
23 |
+
torch.cuda.empty_cache()
|
24 |
+
torch.cuda.ipc_collect()
|
25 |
+
|
26 |
+
|
27 |
+
app = FastAPI(lifespan=lifespan)
|
28 |
+
|
29 |
+
app.add_middleware(
|
30 |
+
CORSMiddleware,
|
31 |
+
allow_origins=["*"],
|
32 |
+
allow_credentials=True,
|
33 |
+
allow_methods=["*"],
|
34 |
+
allow_headers=["*"],
|
35 |
+
)
|
36 |
+
|
37 |
+
class ModelCard(BaseModel):
|
38 |
+
id: str
|
39 |
+
object: str = "model"
|
40 |
+
created: int = Field(default_factory=lambda: int(time.time()))
|
41 |
+
owned_by: str = "owner"
|
42 |
+
root: Optional[str] = None
|
43 |
+
parent: Optional[str] = None
|
44 |
+
permission: Optional[list] = None
|
45 |
+
|
46 |
+
|
47 |
+
class ModelList(BaseModel):
|
48 |
+
object: str = "list"
|
49 |
+
data: List[ModelCard] = []
|
50 |
+
|
51 |
+
|
52 |
+
class ChatMessage(BaseModel):
|
53 |
+
role: Literal["user", "assistant", "system"]
|
54 |
+
content: str
|
55 |
+
|
56 |
+
|
57 |
+
class DeltaMessage(BaseModel):
|
58 |
+
role: Optional[Literal["user", "assistant", "system"]] = None
|
59 |
+
content: Optional[str] = None
|
60 |
+
|
61 |
+
|
62 |
+
class ChatCompletionRequest(BaseModel):
|
63 |
+
model: str
|
64 |
+
messages: List[ChatMessage]
|
65 |
+
temperature: Optional[float] = None
|
66 |
+
top_p: Optional[float] = None
|
67 |
+
max_length: Optional[int] = None
|
68 |
+
stream: Optional[bool] = False
|
69 |
+
|
70 |
+
|
71 |
+
class ChatCompletionResponseChoice(BaseModel):
|
72 |
+
index: int
|
73 |
+
message: ChatMessage
|
74 |
+
finish_reason: Literal["stop", "length"]
|
75 |
+
|
76 |
+
|
77 |
+
class ChatCompletionResponseStreamChoice(BaseModel):
|
78 |
+
index: int
|
79 |
+
delta: DeltaMessage
|
80 |
+
finish_reason: Optional[Literal["stop", "length"]]
|
81 |
+
|
82 |
+
|
83 |
+
class ChatCompletionResponse(BaseModel):
|
84 |
+
model: str
|
85 |
+
object: Literal["chat.completion", "chat.completion.chunk"]
|
86 |
+
choices: List[Union[ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice]]
|
87 |
+
created: Optional[int] = Field(default_factory=lambda: int(time.time()))
|
88 |
+
|
89 |
+
|
90 |
+
@app.get("/v1/models", response_model=ModelList)
|
91 |
+
async def list_models():
|
92 |
+
global model_args
|
93 |
+
model_card = ModelCard(id="gpt-3.5-turbo")
|
94 |
+
return ModelList(data=[model_card])
|
95 |
+
|
96 |
+
|
97 |
+
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
|
98 |
+
async def create_chat_completion(request: ChatCompletionRequest):
|
99 |
+
global model, tokenizer
|
100 |
+
|
101 |
+
if request.messages[-1].role != "user":
|
102 |
+
raise HTTPException(status_code=400, detail="Invalid request")
|
103 |
+
query = request.messages[-1].content
|
104 |
+
|
105 |
+
prev_messages = request.messages[:-1]
|
106 |
+
if len(prev_messages) > 0 and prev_messages[0].role == "system":
|
107 |
+
query = prev_messages.pop(0).content + query
|
108 |
+
|
109 |
+
history = []
|
110 |
+
if len(prev_messages) % 2 == 0:
|
111 |
+
for i in range(0, len(prev_messages), 2):
|
112 |
+
if prev_messages[i].role == "user" and prev_messages[i+1].role == "assistant":
|
113 |
+
history.append([prev_messages[i].content, prev_messages[i+1].content])
|
114 |
+
|
115 |
+
if request.stream:
|
116 |
+
generate = predict(query, history, request.model)
|
117 |
+
return EventSourceResponse(generate, media_type="text/event-stream")
|
118 |
+
|
119 |
+
response, _ = model.chat(tokenizer, query, history=history)
|
120 |
+
choice_data = ChatCompletionResponseChoice(
|
121 |
+
index=0,
|
122 |
+
message=ChatMessage(role="assistant", content=response),
|
123 |
+
finish_reason="stop"
|
124 |
+
)
|
125 |
+
|
126 |
+
return ChatCompletionResponse(model=request.model, choices=[choice_data], object="chat.completion")
|
127 |
+
|
128 |
+
|
129 |
+
async def predict(query: str, history: List[List[str]], model_id: str):
|
130 |
+
global model, tokenizer
|
131 |
+
|
132 |
+
choice_data = ChatCompletionResponseStreamChoice(
|
133 |
+
index=0,
|
134 |
+
delta=DeltaMessage(role="assistant"),
|
135 |
+
finish_reason=None
|
136 |
+
)
|
137 |
+
chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk")
|
138 |
+
yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False))
|
139 |
+
|
140 |
+
current_length = 0
|
141 |
+
|
142 |
+
for new_response, _ in model.stream_chat(tokenizer, query, history):
|
143 |
+
if len(new_response) == current_length:
|
144 |
+
continue
|
145 |
+
|
146 |
+
new_text = new_response[current_length:]
|
147 |
+
current_length = len(new_response)
|
148 |
+
|
149 |
+
choice_data = ChatCompletionResponseStreamChoice(
|
150 |
+
index=0,
|
151 |
+
delta=DeltaMessage(content=new_text),
|
152 |
+
finish_reason=None
|
153 |
+
)
|
154 |
+
chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk")
|
155 |
+
yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False))
|
156 |
+
|
157 |
+
|
158 |
+
choice_data = ChatCompletionResponseStreamChoice(
|
159 |
+
index=0,
|
160 |
+
delta=DeltaMessage(),
|
161 |
+
finish_reason="stop"
|
162 |
+
)
|
163 |
+
chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk")
|
164 |
+
yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False))
|
165 |
+
yield '[DONE]'
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
if __name__ == "__main__":
|
170 |
+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
|
171 |
+
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda()
|
172 |
+
# 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量
|
173 |
+
# from utils import load_model_on_gpus
|
174 |
+
# model = load_model_on_gpus("THUDM/chatglm2-6b", num_gpus=2)
|
175 |
+
model.eval()
|
176 |
+
|
177 |
+
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)
|
output_model/all_results.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"epoch": 50.0,
|
3 |
+
"train_loss": 0.7303538024425507,
|
4 |
+
"train_runtime": 655.0197,
|
5 |
+
"train_samples": 64,
|
6 |
+
"train_samples_per_second": 4.885,
|
7 |
+
"train_steps_per_second": 0.305
|
8 |
+
}
|
output_model/checkpoint-100/config.json
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "chatglm2-6b",
|
3 |
+
"add_bias_linear": false,
|
4 |
+
"add_qkv_bias": true,
|
5 |
+
"apply_query_key_layer_scaling": true,
|
6 |
+
"apply_residual_connection_post_layernorm": false,
|
7 |
+
"architectures": [
|
8 |
+
"ChatGLMForConditionalGeneration"
|
9 |
+
],
|
10 |
+
"attention_dropout": 0.0,
|
11 |
+
"attention_softmax_in_fp32": true,
|
12 |
+
"auto_map": {
|
13 |
+
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
14 |
+
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
15 |
+
"AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
16 |
+
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
17 |
+
"AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
|
18 |
+
},
|
19 |
+
"bias_dropout_fusion": true,
|
20 |
+
"classifier_dropout": null,
|
21 |
+
"eos_token_id": 2,
|
22 |
+
"ffn_hidden_size": 13696,
|
23 |
+
"fp32_residual_connection": false,
|
24 |
+
"hidden_dropout": 0.0,
|
25 |
+
"hidden_size": 4096,
|
26 |
+
"kv_channels": 128,
|
27 |
+
"layernorm_epsilon": 1e-05,
|
28 |
+
"model_type": "chatglm",
|
29 |
+
"multi_query_attention": true,
|
30 |
+
"multi_query_group_num": 2,
|
31 |
+
"num_attention_heads": 32,
|
32 |
+
"num_layers": 28,
|
33 |
+
"original_rope": true,
|
34 |
+
"pad_token_id": 0,
|
35 |
+
"padded_vocab_size": 65024,
|
36 |
+
"post_layer_norm": true,
|
37 |
+
"pre_seq_len": 128,
|
38 |
+
"prefix_projection": false,
|
39 |
+
"quantization_bit": 0,
|
40 |
+
"rmsnorm": true,
|
41 |
+
"seq_length": 32768,
|
42 |
+
"tie_word_embeddings": false,
|
43 |
+
"torch_dtype": "float16",
|
44 |
+
"transformers_version": "4.30.2",
|
45 |
+
"use_cache": true,
|
46 |
+
"vocab_size": 65024
|
47 |
+
}
|
output_model/checkpoint-100/generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"eos_token_id": 2,
|
4 |
+
"pad_token_id": 0,
|
5 |
+
"transformers_version": "4.30.2"
|
6 |
+
}
|
output_model/checkpoint-100/optimizer.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:645163accacd386dd631ab6c2403a2334fb734b381a405399d7061c90fa18116
|
3 |
+
size 14681892
|
output_model/checkpoint-100/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:517ddc122cb93c1436d7451be5e78ee7a62d0bf2b1305743d77ca136f0849811
|
3 |
+
size 7341306
|
output_model/checkpoint-100/rng_state.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f991460656c4fa5c1f3ffbf7ca3d75547cdcb464e18348ad96b362c9ef302ed1
|
3 |
+
size 14244
|
output_model/checkpoint-100/scheduler.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:936c002f81d5b4eebc167f5155e7845ba3cbb783cedd2e3d0de455e21759ac06
|
3 |
+
size 1064
|
output_model/checkpoint-100/special_tokens_map.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{}
|
output_model/checkpoint-100/tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e7dc4c393423b76e4373e5157ddc34803a0189ba96b21ddbb40269d31468a6f2
|
3 |
+
size 1018370
|
output_model/checkpoint-100/tokenizer_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_chatglm.ChatGLMTokenizer",
|
5 |
+
null
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"clean_up_tokenization_spaces": false,
|
9 |
+
"do_lower_case": false,
|
10 |
+
"model_max_length": 1000000000000000019884624838656,
|
11 |
+
"padding_side": "left",
|
12 |
+
"remove_space": false,
|
13 |
+
"tokenizer_class": "ChatGLMTokenizer"
|
14 |
+
}
|
output_model/checkpoint-100/trainer_state.json
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"best_metric": null,
|
3 |
+
"best_model_checkpoint": null,
|
4 |
+
"epoch": 25.0,
|
5 |
+
"global_step": 100,
|
6 |
+
"is_hyper_param_search": false,
|
7 |
+
"is_local_process_zero": true,
|
8 |
+
"is_world_process_zero": true,
|
9 |
+
"log_history": [
|
10 |
+
{
|
11 |
+
"epoch": 2.5,
|
12 |
+
"learning_rate": 0.0095,
|
13 |
+
"loss": 2.9809,
|
14 |
+
"step": 10
|
15 |
+
},
|
16 |
+
{
|
17 |
+
"epoch": 5.0,
|
18 |
+
"learning_rate": 0.009000000000000001,
|
19 |
+
"loss": 2.2765,
|
20 |
+
"step": 20
|
21 |
+
},
|
22 |
+
{
|
23 |
+
"epoch": 7.5,
|
24 |
+
"learning_rate": 0.0085,
|
25 |
+
"loss": 1.9437,
|
26 |
+
"step": 30
|
27 |
+
},
|
28 |
+
{
|
29 |
+
"epoch": 10.0,
|
30 |
+
"learning_rate": 0.008,
|
31 |
+
"loss": 1.6237,
|
32 |
+
"step": 40
|
33 |
+
},
|
34 |
+
{
|
35 |
+
"epoch": 12.5,
|
36 |
+
"learning_rate": 0.0075,
|
37 |
+
"loss": 1.4213,
|
38 |
+
"step": 50
|
39 |
+
},
|
40 |
+
{
|
41 |
+
"epoch": 15.0,
|
42 |
+
"learning_rate": 0.006999999999999999,
|
43 |
+
"loss": 1.1779,
|
44 |
+
"step": 60
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"epoch": 17.5,
|
48 |
+
"learning_rate": 0.006500000000000001,
|
49 |
+
"loss": 0.9173,
|
50 |
+
"step": 70
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"epoch": 20.0,
|
54 |
+
"learning_rate": 0.006,
|
55 |
+
"loss": 0.613,
|
56 |
+
"step": 80
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"epoch": 22.5,
|
60 |
+
"learning_rate": 0.0055000000000000005,
|
61 |
+
"loss": 0.4378,
|
62 |
+
"step": 90
|
63 |
+
},
|
64 |
+
{
|
65 |
+
"epoch": 25.0,
|
66 |
+
"learning_rate": 0.005,
|
67 |
+
"loss": 0.3004,
|
68 |
+
"step": 100
|
69 |
+
}
|
70 |
+
],
|
71 |
+
"max_steps": 200,
|
72 |
+
"num_train_epochs": 50,
|
73 |
+
"total_flos": 2.94367394791424e+16,
|
74 |
+
"trial_name": null,
|
75 |
+
"trial_params": null
|
76 |
+
}
|
output_model/checkpoint-100/training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fd5434dda548e3d21ec57c71884ce9f774a33ba89b83937b6498388cf5a5449f
|
3 |
+
size 4472
|
output_model/checkpoint-200/config.json
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "chatglm2-6b",
|
3 |
+
"add_bias_linear": false,
|
4 |
+
"add_qkv_bias": true,
|
5 |
+
"apply_query_key_layer_scaling": true,
|
6 |
+
"apply_residual_connection_post_layernorm": false,
|
7 |
+
"architectures": [
|
8 |
+
"ChatGLMForConditionalGeneration"
|
9 |
+
],
|
10 |
+
"attention_dropout": 0.0,
|
11 |
+
"attention_softmax_in_fp32": true,
|
12 |
+
"auto_map": {
|
13 |
+
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
14 |
+
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
15 |
+
"AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
16 |
+
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
17 |
+
"AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
|
18 |
+
},
|
19 |
+
"bias_dropout_fusion": true,
|
20 |
+
"classifier_dropout": null,
|
21 |
+
"eos_token_id": 2,
|
22 |
+
"ffn_hidden_size": 13696,
|
23 |
+
"fp32_residual_connection": false,
|
24 |
+
"hidden_dropout": 0.0,
|
25 |
+
"hidden_size": 4096,
|
26 |
+
"kv_channels": 128,
|
27 |
+
"layernorm_epsilon": 1e-05,
|
28 |
+
"model_type": "chatglm",
|
29 |
+
"multi_query_attention": true,
|
30 |
+
"multi_query_group_num": 2,
|
31 |
+
"num_attention_heads": 32,
|
32 |
+
"num_layers": 28,
|
33 |
+
"original_rope": true,
|
34 |
+
"pad_token_id": 0,
|
35 |
+
"padded_vocab_size": 65024,
|
36 |
+
"post_layer_norm": true,
|
37 |
+
"pre_seq_len": 128,
|
38 |
+
"prefix_projection": false,
|
39 |
+
"quantization_bit": 0,
|
40 |
+
"rmsnorm": true,
|
41 |
+
"seq_length": 32768,
|
42 |
+
"tie_word_embeddings": false,
|
43 |
+
"torch_dtype": "float16",
|
44 |
+
"transformers_version": "4.30.2",
|
45 |
+
"use_cache": true,
|
46 |
+
"vocab_size": 65024
|
47 |
+
}
|
output_model/checkpoint-200/generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"eos_token_id": 2,
|
4 |
+
"pad_token_id": 0,
|
5 |
+
"transformers_version": "4.30.2"
|
6 |
+
}
|
output_model/checkpoint-200/optimizer.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dbb542f61f912f76d2b8fa4512ed907912f63099cfb3e73ca01c9dc8a4cd0482
|
3 |
+
size 14681892
|