Skip to content

Commit 6b9d694

Browse files
committed
feat: initial commit
1 parent effb9bb commit 6b9d694

File tree

2 files changed

+217
-0
lines changed

2 files changed

+217
-0
lines changed
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# GLM-Edge
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on GLM-Edge models on [Intel GPUs](../../../README.md). For illustration purposes, we utilize the [THUDM/glm-edge-1.5b-chat](https://hf-mirror.com/THUDM/glm-edge-1.5b-chat) as a reference InternLM model.
3+
4+
## 0. Requirements
5+
To run these examples with IPEX-LLM on Intel GPUs, we have some recommended requirements for your machine, please refer to [here](../../../README.md#requirements) for more information.
6+
7+
## 1. Install
8+
### 1.1 Installation on Linux
9+
We suggest using conda to manage environment:
10+
```bash
11+
conda create -n llm python=3.11
12+
conda activate llm
13+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
14+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
15+
16+
# install packages required for GLM-Edge
17+
pip install git+https://github.com/huggingface/transformers.git
18+
pip install "tiktoken>=0.7.0" "trl<0.12.0"
19+
```
20+
21+
### 1.2 Installation on Windows
22+
We suggest using conda to manage environment:
23+
```bash
24+
conda create -n llm python=3.11 libuv
25+
conda activate llm
26+
27+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
28+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
29+
30+
# install packages required for GLM-Edge
31+
pip install git+https://github.com/huggingface/transformers.git
32+
pip install "tiktoken>=0.7.0" "trl<0.12.0"
33+
```
34+
35+
## 2. Configures OneAPI environment variables for Linux
36+
37+
> [!NOTE]
38+
> Skip this step if you are running on Windows.
39+
40+
This is a required step on Linux for APT or offline installed oneAPI. Skip this step for PIP-installed oneAPI.
41+
42+
```bash
43+
source /opt/intel/oneapi/setvars.sh
44+
```
45+
46+
## 3. Runtime Configurations
47+
For optimal performance, it is recommended to set several environment variables. Please check out the suggestions based on your device.
48+
### 3.1 Configurations for Linux
49+
<details>
50+
51+
<summary>For Intel Arc™ A-Series Graphics and Intel Data Center GPU Flex Series</summary>
52+
53+
```bash
54+
export USE_XETLA=OFF
55+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
56+
export SYCL_CACHE_PERSISTENT=1
57+
```
58+
59+
</details>
60+
61+
<details>
62+
63+
<summary>For Intel Data Center GPU Max Series</summary>
64+
65+
```bash
66+
export LD_PRELOAD=${LD_PRELOAD}:${CONDA_PREFIX}/lib/libtcmalloc.so
67+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
68+
export SYCL_CACHE_PERSISTENT=1
69+
export ENABLE_SDP_FUSION=1
70+
```
71+
> Note: Please note that `libtcmalloc.so` can be installed by `conda install -c conda-forge -y gperftools=2.10`.
72+
</details>
73+
74+
<details>
75+
76+
<summary>For Intel iGPU</summary>
77+
78+
```bash
79+
export SYCL_CACHE_PERSISTENT=1
80+
```
81+
82+
</details>
83+
84+
### 3.2 Configurations for Windows
85+
<details>
86+
87+
<summary>For Intel iGPU and Intel Arc™ A-Series Graphics</summary>
88+
89+
```cmd
90+
set SYCL_CACHE_PERSISTENT=1
91+
```
92+
93+
</details>
94+
95+
96+
> [!NOTE]
97+
> For the first time that each model runs on Intel iGPU/Intel Arc™ A300-Series or Pro A60, it may take several minutes to compile.
98+
## 4. Running examples
99+
100+
### Example 1: Predict Tokens using `generate()` API
101+
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 on Intel GPUs.
102+
103+
```
104+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --prompt PROMPT --n-predict N_PREDICT
105+
```
106+
107+
Arguments info:
108+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the GLM-4 model (e.g. `THUDM/glm-edge-1.5b-chat`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'THUDM/glm-edge-1.5b-chat'`.
109+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'AI是什么?'`.
110+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
111+
112+
#### Sample Output
113+
#### [THUDM/glm-edge-1.5b-chat](https://hf-mirror.com/THUDM/glm-edge-1.5b-chat)
114+
```log
115+
Inference time: xxxx s
116+
-------------------- Prompt --------------------
117+
<|user|>
118+
AI是什么?
119+
<|assistant|>
120+
-------------------- Output --------------------
121+
122+
AI是什么?
123+
124+
AI,即人工智能,指的是由人制造出来的系统或机器能够执行通常需要人类智能才能完成的任务。人工智能可以执行多种任务,包括视觉识别、语言
125+
```
126+
127+
```log
128+
Inference time: xxxx s
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
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 AutoModelForCausalLM
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://hf-mirror.com/THUDM/glm-edge-1.5b-chat
27+
28+
29+
if __name__ == '__main__':
30+
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for GLM-Edge model')
31+
parser.add_argument('--repo-id-or-model-path', type=str, default="THUDM/glm-edge-1.5b-chat",
32+
help='The huggingface repo id for the GLM-Edge 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+
# When running LLMs on Intel iGPUs for Windows users, we recommend setting `cpu_embedding=True` in the from_pretrained function.
45+
# This will allow the memory-intensive embedding layer to utilize the CPU instead of iGPU.
46+
model = AutoModelForCausalLM.from_pretrained(model_path,
47+
load_in_4bit=True,
48+
optimize_model=True,
49+
trust_remote_code=True,
50+
use_cache=True)
51+
model = model.to("xpu")
52+
53+
# Load tokenizer
54+
tokenizer = AutoTokenizer.from_pretrained(model_path,
55+
trust_remote_code=True)
56+
57+
# Generate predicted tokens
58+
with torch.inference_mode():
59+
message = [{"role": "user", "content": args.prompt}]
60+
61+
inputs = tokenizer.apply_chat_template(
62+
message,
63+
return_tensors="pt",
64+
add_generation_prompt=True,
65+
return_dict=True,
66+
).to(model.device)
67+
68+
generate_kwargs = {
69+
"input_ids": inputs["input_ids"],
70+
"attention_mask": inputs["attention_mask"],
71+
"max_new_tokens": args.n_predict,
72+
"do_sample": False,
73+
}
74+
75+
# ipex_llm model needs a warmup, then inference time can be accurate
76+
output = model.generate(**generate_kwargs)
77+
78+
st = time.time()
79+
80+
output = model.generate(**generate_kwargs)
81+
82+
torch.xpu.synchronize()
83+
end = time.time()
84+
output_str = tokenizer.decode(output[0], skip_special_tokens=True)
85+
print(f'Inference time: {end-st} s')
86+
print('-'*20, 'Prompt', '-'*20)
87+
print(args.prompt)
88+
print('-'*20, 'Output', '-'*20)
89+
print(output_str)

0 commit comments

Comments
 (0)