Skip to content

Commit f224e98

Browse files
authored
Add GLM-4 CPU example (#11223)
* Add GLM-4 example * add tiktoken dependency * fix * fix
1 parent 40fc870 commit f224e98

File tree

7 files changed

+455
-0
lines changed

7 files changed

+455
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ Over 50 models have been optimized/verified on `ipex-llm`, including *LLaMA/LLaM
154154
| ChatGLM | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm) | |
155155
| ChatGLM2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm2) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/chatglm2) |
156156
| ChatGLM3 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm3) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/chatglm3) |
157+
| GLM-4 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/glm4) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/glm4) |
157158
| Mistral | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/mistral) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/mistral) |
158159
| Mixtral | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/mixtral) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/mixtral) |
159160
| Falcon | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/falcon) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/falcon) |

docs/readthedocs/source/index.rst

+7
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,13 @@ Verified Models
257257
<td>
258258
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/GPU/HF-Transformers-AutoModels/Model/chatglm3">link</a></td>
259259
</tr>
260+
<tr>
261+
<td>GLM-4</td>
262+
<td>
263+
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/CPU/HF-Transformers-AutoModels/Model/glm4">link</a></td>
264+
<td>
265+
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/GPU/HF-Transformers-AutoModels/Model/glm4">link</a></td>
266+
</tr>
260267
<tr>
261268
<td>Mistral</td>
262269
<td>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
# GLM-4
2+
3+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on GLM-4 models. For illustration purposes, we utilize the [THUDM/glm-4-9b-chat](https://huggingface.co/THUDM/glm-4-9b-chat) as a reference GLM-4 model.
4+
5+
## 0. Requirements
6+
To run these examples with IPEX-LLM, we have some recommended requirements for your machine, please refer to [here](../README.md#recommended-requirements) for more information.
7+
8+
## Example 1: Predict Tokens using `generate()` API
9+
In the example [generate.py](./generate.py), we show a basic use case for a GLM-4 model to predict the next N tokens using `generate()` API, with IPEX-LLM INT4 optimizations.
10+
### 1. Install
11+
We suggest using conda to manage environment:
12+
13+
On Linux:
14+
15+
```bash
16+
conda create -n llm python=3.11 # recommend to use Python 3.11
17+
conda activate llm
18+
19+
# install the latest ipex-llm nightly build with 'all' option
20+
pip install --pre --upgrade ipex-llm[all] --extra-index-url https://download.pytorch.org/whl/cpu
21+
22+
# install tiktoken required for GLM-4
23+
pip install tiktoken
24+
```
25+
26+
On Windows:
27+
28+
```cmd
29+
conda create -n llm python=3.11
30+
conda activate llm
31+
32+
pip install --pre --upgrade ipex-llm[all]
33+
34+
pip install tiktoken
35+
```
36+
37+
### 2. Run
38+
```
39+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --prompt PROMPT --n-predict N_PREDICT
40+
```
41+
42+
Arguments info:
43+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the GLM-4 model to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'THUDM/glm-4-9b-chat'`.
44+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'AI是什么?'`.
45+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
46+
47+
> **Note**: When loading the model in 4-bit, IPEX-LLM converts linear layers in the model into INT4 format. In theory, a *X*B model saved in 16-bit will requires approximately 2*X* GB of memory for loading, and ~0.5*X* GB memory for further inference.
48+
>
49+
> Please select the appropriate size of the GLM-4 model based on the capabilities of your machine.
50+
51+
#### 2.1 Client
52+
On client Windows machine, it is recommended to run directly with full utilization of all cores:
53+
```cmd
54+
python ./generate.py
55+
```
56+
57+
#### 2.2 Server
58+
For optimal performance on server, it is recommended to set several environment variables (refer to [here](../README.md#best-known-configuration-on-linux) for more information), and run the example with all the physical cores of a single socket.
59+
60+
E.g. on Linux,
61+
```bash
62+
# set IPEX-LLM env variables
63+
source ipex-llm-init
64+
65+
# e.g. for a server with 48 cores per socket
66+
export OMP_NUM_THREADS=48
67+
numactl -C 0-47 -m 0 python ./generate.py
68+
```
69+
70+
#### 2.3 Sample Output
71+
##### [THUDM/glm-4-9b-chat](https://huggingface.co/THUDM/glm-4-9b-chat)
72+
```log
73+
Inference time: xxxx s
74+
-------------------- Prompt --------------------
75+
<|user|>
76+
AI是什么?
77+
<|assistant|>
78+
-------------------- Output --------------------
79+
80+
AI是什么?
81+
82+
AI,即人工智能(Artificial Intelligence),是指由人创造出来的,能够模拟、延伸和扩展人的智能的计算机系统或机器。人工智能技术
83+
```
84+
85+
```log
86+
Inference time: xxxx s
87+
-------------------- Prompt --------------------
88+
<|user|>
89+
What is AI?
90+
<|assistant|>
91+
-------------------- Output --------------------
92+
93+
What is AI?
94+
95+
Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think like humans and mimic their actions. The term "art
96+
```
97+
98+
## Example 2: Stream Chat using `stream_chat()` API
99+
In the example [streamchat.py](./streamchat.py), we show a basic use case for a GLM-4 model to stream chat, with IPEX-LLM INT4 optimizations.
100+
### 1. Install
101+
We suggest using conda to manage environment:
102+
103+
On Linux:
104+
105+
```bash
106+
conda create -n llm python=3.11 # recommend to use Python 3.11
107+
conda activate llm
108+
109+
# install the latest ipex-llm nightly build with 'all' option
110+
pip install --pre --upgrade ipex-llm[all] --extra-index-url https://download.pytorch.org/whl/cpu
111+
112+
# install tiktoken required for GLM-4
113+
pip install tiktoken
114+
```
115+
116+
On Windows:
117+
118+
```cmd
119+
conda create -n llm python=3.11
120+
conda activate llm
121+
122+
pip install --pre --upgrade ipex-llm[all]
123+
124+
pip install tiktoken
125+
```
126+
127+
### 2. Run
128+
**Stream Chat using `stream_chat()` API**:
129+
```
130+
python ./streamchat.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --question QUESTION
131+
```
132+
133+
**Chat using `chat()` API**:
134+
```
135+
python ./streamchat.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --question QUESTION --disable-stream
136+
```
137+
138+
Arguments info:
139+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the GLM-4 model to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'THUDM/glm-4-9b-chat'`.
140+
- `--question QUESTION`: argument defining the question to ask. It is default to be `"晚上睡不着应该怎么办"`.
141+
- `--disable-stream`: argument defining whether to stream chat. If include `--disable-stream` when running the script, the stream chat is disabled and `chat()` API is used.
142+
143+
> **Note**: When loading the model in 4-bit, IPEX-LLM converts linear layers in the model into INT4 format. In theory, a *X*B model saved in 16-bit will requires approximately 2*X* GB of memory for loading, and ~0.5*X* GB memory for further inference.
144+
>
145+
> Please select the appropriate size of the GLM-4 model based on the capabilities of your machine.
146+
147+
#### 2.1 Client
148+
On client Windows machine, it is recommended to run directly with full utilization of all cores:
149+
```cmd
150+
$env:PYTHONUNBUFFERED=1 # ensure stdout and stderr streams are sent straight to terminal without being first buffered
151+
python ./streamchat.py
152+
```
153+
154+
#### 2.2 Server
155+
For optimal performance on server, it is recommended to set several environment variables (refer to [here](../README.md#best-known-configuration-on-linux) for more information), and run the example with all the physical cores of a single socket.
156+
157+
E.g. on Linux,
158+
```bash
159+
# set IPEX-LLM env variables
160+
source ipex-llm-init
161+
162+
# e.g. for a server with 48 cores per socket
163+
export OMP_NUM_THREADS=48
164+
export PYTHONUNBUFFERED=1 # ensure stdout and stderr streams are sent straight to terminal without being first buffered
165+
numactl -C 0-47 -m 0 python ./streamchat.py
166+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#
2+
# Copyright 2016 The BigDL Authors.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
#
16+
17+
import torch
18+
import time
19+
import argparse
20+
import numpy as np
21+
22+
from ipex_llm.transformers import AutoModel
23+
from transformers import AutoTokenizer
24+
25+
# you could tune the prompt based on your own model,
26+
# here the prompt tuning refers to https://huggingface.co/THUDM/glm-4-9b-chat/blob/main/tokenization_chatglm.py
27+
GLM4_PROMPT_FORMAT = "<|user|>\n{prompt}\n<|assistant|>"
28+
29+
if __name__ == '__main__':
30+
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for GLM-4 model')
31+
parser.add_argument('--repo-id-or-model-path', type=str, default="THUDM/glm-4-9b-chat",
32+
help='The huggingface repo id for the GLM-4 model to be downloaded'
33+
', or the path to the huggingface checkpoint folder')
34+
parser.add_argument('--prompt', type=str, default="AI是什么?",
35+
help='Prompt to infer')
36+
parser.add_argument('--n-predict', type=int, default=32,
37+
help='Max tokens to predict')
38+
39+
args = parser.parse_args()
40+
model_path = args.repo_id_or_model_path
41+
42+
# Load model in 4 bit,
43+
# which convert the relevant layers in the model into INT4 format
44+
model = AutoModel.from_pretrained(model_path,
45+
load_in_4bit=True,
46+
optimize_model=True,
47+
trust_remote_code=True,
48+
use_cache=True)
49+
50+
# Load tokenizer
51+
tokenizer = AutoTokenizer.from_pretrained(model_path,
52+
trust_remote_code=True)
53+
54+
# Generate predicted tokens
55+
with torch.inference_mode():
56+
prompt = GLM4_PROMPT_FORMAT.format(prompt=args.prompt)
57+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
58+
st = time.time()
59+
output = model.generate(input_ids,
60+
max_new_tokens=args.n_predict)
61+
end = time.time()
62+
output_str = tokenizer.decode(output[0], skip_special_tokens=True)
63+
print(f'Inference time: {end-st} s')
64+
print('-'*20, 'Prompt', '-'*20)
65+
print(prompt)
66+
print('-'*20, 'Output', '-'*20)
67+
print(output_str)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#
2+
# Copyright 2016 The BigDL Authors.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
#
16+
17+
import torch
18+
import time
19+
import argparse
20+
import numpy as np
21+
22+
from ipex_llm.transformers import AutoModel
23+
from transformers import AutoTokenizer
24+
25+
26+
if __name__ == '__main__':
27+
parser = argparse.ArgumentParser(description='Stream Chat for GLM-4 model')
28+
parser.add_argument('--repo-id-or-model-path', type=str, default="THUDM/glm-4-9b-chat",
29+
help='The huggingface repo id for the GLM-4 model to be downloaded'
30+
', or the path to the huggingface checkpoint folder')
31+
parser.add_argument('--question', type=str, default="晚上睡不着应该怎么办",
32+
help='Qustion you want to ask')
33+
parser.add_argument('--disable-stream', action="store_true",
34+
help='Disable stream chat')
35+
36+
args = parser.parse_args()
37+
model_path = args.repo_id_or_model_path
38+
disable_stream = args.disable_stream
39+
40+
# Load model in 4 bit,
41+
# which convert the relevant layers in the model into INT4 format
42+
model = AutoModel.from_pretrained(model_path,
43+
load_in_4bit=True,
44+
trust_remote_code=True)
45+
46+
# Load tokenizer
47+
tokenizer = AutoTokenizer.from_pretrained(model_path,
48+
trust_remote_code=True)
49+
50+
with torch.inference_mode():
51+
if disable_stream:
52+
# Chat
53+
response, history = model.chat(tokenizer, args.question, history=[])
54+
print('-'*20, 'Chat Output', '-'*20)
55+
print(response)
56+
else:
57+
# Stream chat
58+
response_ = ""
59+
print('-'*20, 'Stream Chat Output', '-'*20)
60+
for response, history in model.stream_chat(tokenizer, args.question, history=[]):
61+
print(response.replace(response_, ""), end="")
62+
response_ = response

0 commit comments

Comments
 (0)