Skip to content

Commit 549cdeb

Browse files
authored
Merge pull request THUDM#23 from qinjx/main
Multiple GPUs support. 多显卡支持
2 parents 9f247f6 + 5916e3f commit 549cdeb

File tree

7 files changed

+94
-9
lines changed

7 files changed

+94
-9
lines changed

Diff for: README.md

+7
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,13 @@ cd ChatGLM2-6B
165165
git clone https://huggingface.co/THUDM/chatglm2-6b
166166
```
167167

168+
如果你从 Hugging Face Hub 上下载 checkpoint 的速度较慢,可以只下载模型实现
169+
```Shell
170+
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm2-6b
171+
```
172+
然后从[这里](https://cloud.tsinghua.edu.cn/d/674208019e314311ab5c/)手动下载模型参数文件,并将下载的文件替换到本地的 `chatglm2-6b` 目录下。
173+
174+
168175
将模型下载到本地之后,将以上代码中的 `THUDM/chatglm2-6b` 替换为你本地的 `chatglm2-6b` 文件夹的路径,即可从本地加载模型。
169176

170177
模型的实现仍然处在变动中。如果希望固定使用的模型实现以保证兼容性,可以在 `from_pretrained` 的调用中增加 `revision="v1.0"` 参数。`v1.0` 是当前最新的版本号,完整的版本列表参见 [Change Log](https://huggingface.co/THUDM/chatglm2-6b#change-log)

Diff for: api.py

+4
Original file line numberDiff line numberDiff line change
@@ -52,5 +52,9 @@ async def create_item(request: Request):
5252
if __name__ == '__main__':
5353
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
5454
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)
5559
model.eval()
5660
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)

Diff for: cli_demo.py

+11-9
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,14 @@
33
import signal
44
from transformers import AutoTokenizer, AutoModel
55
import readline
6+
from utils import load_model_on_gpus
67

78
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
89
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda()
10+
# 多显卡支持,使用下面三行代替上面两行,将num_gpus改为你实际的显卡数量
11+
# model_path = "THUDM/chatglm2-6b"
12+
# tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
13+
# model = load_model_on_gpus(model_path, num_gpus=2)
914
model = model.eval()
1015

1116
os_name = platform.system()
@@ -17,7 +22,7 @@ def build_prompt(history):
1722
prompt = "欢迎使用 ChatGLM2-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序"
1823
for query, response in history:
1924
prompt += f"\n\n用户:{query}"
20-
prompt += f"\n\nChatGLM-6B:{response}"
25+
prompt += f"\n\nChatGLM2-6B:{response}"
2126
return prompt
2227

2328

@@ -39,21 +44,18 @@ def main():
3944
os.system(clear_command)
4045
print("欢迎使用 ChatGLM2-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序")
4146
continue
42-
count = 0
47+
print("\nChatGLM:", end="")
48+
current_length = 0
4349
for response, history, past_key_values in model.stream_chat(tokenizer, query, history=history,
4450
past_key_values=past_key_values,
4551
return_past_key_values=True):
4652
if stop_stream:
4753
stop_stream = False
4854
break
4955
else:
50-
count += 1
51-
if count % 8 == 0:
52-
os.system(clear_command)
53-
print(build_prompt(history), flush=True)
54-
signal.signal(signal.SIGINT, signal_handler)
55-
os.system(clear_command)
56-
print(build_prompt(history), flush=True)
56+
print(response[current_length:], end="", flush=True)
57+
current_length = len(response)
58+
print("")
5759

5860

5961
if __name__ == "__main__":

Diff for: openai_api.py

+4
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,10 @@ async def predict(query: str, history: List[List[str]], model_id: str):
158158
if __name__ == "__main__":
159159
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
160160
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda()
161+
# 多显卡支持,使用下面三行代替上面两行,将num_gpus改为你实际的显卡数量
162+
# model_path = "THUDM/chatglm2-6b"
163+
# tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
164+
# model = load_model_on_gpus(model_path, num_gpus=2)
161165
model.eval()
162166

163167
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)

Diff for: utils.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import os
2+
from typing import Dict, Tuple, Union, Optional
3+
4+
from torch.nn import Module
5+
from transformers import AutoModel
6+
7+
8+
def auto_configure_device_map(num_gpus: int) -> Dict[str, int]:
9+
# transformer.word_embeddings 占用1层
10+
# transformer.final_layernorm 和 lm_head 占用1层
11+
# transformer.layers 占用 28 层
12+
# 总共30层分配到num_gpus张卡上
13+
num_trans_layers = 28
14+
per_gpu_layers = 30 / num_gpus
15+
16+
# bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError
17+
# windows下 model.device 会被设置成 transformer.word_embeddings.device
18+
# linux下 model.device 会被设置成 lm_head.device
19+
# 在调用chat或者stream_chat时,input_ids会被放到model.device上
20+
# 如果transformer.word_embeddings.device和model.device不同,则会导致RuntimeError
21+
# 因此这里将transformer.word_embeddings,transformer.final_layernorm,lm_head都放到第一张卡上
22+
# 本文件来源于https://github.com/THUDM/ChatGLM-6B/blob/main/utils.py
23+
# 仅此处做少许修改以支持ChatGLM2
24+
device_map = {
25+
'transformer.embedding.word_embeddings': 0,
26+
'transformer.encoder.final_layernorm': 0,
27+
'transformer.output_layer': 0,
28+
'transformer.rotary_pos_emb': 0,
29+
'lm_head': 0
30+
}
31+
32+
used = 2
33+
gpu_target = 0
34+
for i in range(num_trans_layers):
35+
if used >= per_gpu_layers:
36+
gpu_target += 1
37+
used = 0
38+
assert gpu_target < num_gpus
39+
device_map[f'transformer.encoder.layers.{i}'] = gpu_target
40+
used += 1
41+
42+
return device_map
43+
44+
45+
def load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2,
46+
device_map: Optional[Dict[str, int]] = None, **kwargs) -> Module:
47+
if num_gpus < 2 and device_map is None:
48+
model = AutoModel.from_pretrained(checkpoint_path, trust_remote_code=True, **kwargs).half().cuda()
49+
else:
50+
from accelerate import dispatch_model
51+
52+
model = AutoModel.from_pretrained(checkpoint_path, trust_remote_code=True, **kwargs).half()
53+
54+
if device_map is None:
55+
device_map = auto_configure_device_map(num_gpus)
56+
57+
model = dispatch_model(model, device_map=device_map)
58+
59+
return model

Diff for: web_demo.py

+5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
from transformers import AutoModel, AutoTokenizer
22
import gradio as gr
33
import mdtex2html
4+
from utils import load_model_on_gpus
45

56
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
67
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda()
8+
# 多显卡支持,使用下面三行代替上面两行,将num_gpus改为你实际的显卡数量
9+
# model_path = "THUDM/chatglm2-6b"
10+
# tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
11+
# model = load_model_on_gpus(model_path, num_gpus=2)
712
model = model.eval()
813

914
"""Override Chatbot.postprocess"""

Diff for: web_demo2.py

+4
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
def get_model():
1515
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
1616
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda()
17+
# 多显卡支持,使用下面三行代替上面两行,将num_gpus改为你实际的显卡数量
18+
# model_path = "THUDM/chatglm2-6b"
19+
# tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
20+
# model = load_model_on_gpus(model_path, num_gpus=2)
1721
model = model.eval()
1822
return tokenizer, model
1923

0 commit comments

Comments
 (0)