Skip to content

Commit 21fc781

Browse files
ivy-lv11JinBridger
andauthored
Add GLM-4V example (#11343)
* add example * modify * modify * add line * add * add link and replace with phi-3-vision template * fix generate options * fix * fix --------- Co-authored-by: jinbridge <[email protected]>
1 parent 9b475c0 commit 21fc781

File tree

6 files changed

+383
-0
lines changed

6 files changed

+383
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ Over 50 models have been optimized/verified on `ipex-llm`, including *LLaMA/LLaM
232232
| ChatGLM2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm2) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/chatglm2) |
233233
| ChatGLM3 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm3) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/chatglm3) |
234234
| GLM-4 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/glm4) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/glm4) |
235+
| GLM-4V | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/glm-4v) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/glm-4v) |
235236
| Mistral | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/mistral) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/mistral) |
236237
| Mixtral | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/mixtral) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/mixtral) |
237238
| 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
@@ -313,6 +313,13 @@ Verified Models
313313
<td>
314314
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/GPU/HF-Transformers-AutoModels/Model/glm4">link</a></td>
315315
</tr>
316+
<tr>
317+
<td>GLM-4V</td>
318+
<td>
319+
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/CPU/HF-Transformers-AutoModels/Model/glm-4v">link</a></td>
320+
<td>
321+
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/GPU/HF-Transformers-AutoModels/Model/glm-4v">link</a></td>
322+
</tr>
316323
<tr>
317324
<td>Mistral</td>
318325
<td>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# GLM-4V
2+
3+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on GLM-4V models. For illustration purposes, we utilize the [THUDM/glm-4v-9b](https://huggingface.co/THUDM/glm-4v-9b) as a reference GLM-4V 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: Predict Tokens using `generate()` API
9+
In the example [generate.py](./generate.py), we show a basic use case for a GLM-4V 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 ipex-llm with 'all' option
20+
pip install --pre --upgrade ipex-llm[all] --extra-index-url https://download.pytorch.org/whl/cpu
21+
22+
pip install torchvision tiktoken
23+
```
24+
25+
On Windows:
26+
27+
```cmd
28+
conda create -n llm python=3.11
29+
conda activate llm
30+
31+
pip install --pre --upgrade ipex-llm[all]
32+
33+
pip install torchvision tiktoken
34+
```
35+
36+
### 2. Run
37+
```
38+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --image-url-or-path IMAGE_URL_OR_PATH --prompt PROMPT --n-predict N_PREDICT
39+
```
40+
41+
Arguments Info:
42+
43+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the GLM-4V model (e.g. `THUDM/glm-4v-9b`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'THUDM/glm-4v-9b'`.
44+
- `--image-url-or-path IMAGE_URL_OR_PATH`: argument defining the image to be infered. It is default to be `'http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg'`.
45+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'What is in the image?'`.
46+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
47+
48+
> **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.
49+
>
50+
> Please select the appropriate size of the GLM-4V model based on the capabilities of your machine.
51+
52+
#### 2.1 Client
53+
On client Windows machines, it is recommended to run directly with full utilization of all cores:
54+
```cmd
55+
python ./generate.py
56+
```
57+
58+
#### 2.2 Server
59+
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.
60+
61+
E.g. on Linux,
62+
```bash
63+
# set IPEX-LLM env variables
64+
source ipex-llm-init
65+
66+
# e.g. for a server with 48 cores per socket
67+
export OMP_NUM_THREADS=48
68+
numactl -C 0-47 -m 0 python ./generate.py
69+
```
70+
71+
#### 2.3 Sample Output
72+
#### [THUDM/glm-4v-9b](https://huggingface.co/THUDM/glm-4v-9b)
73+
74+
```log
75+
Inference time: xxxx s
76+
-------------------- Prompt --------------------
77+
What is in the image?
78+
-------------------- Output --------------------
79+
The image shows a young child holding up a small white teddy bear dressed in a pink
80+
```
81+
82+
The sample input image is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=264959)):
83+
84+
<a href="http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg"><img width=400px src="http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg" ></a>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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 os
18+
import time
19+
import torch
20+
import argparse
21+
import requests
22+
23+
from PIL import Image
24+
from ipex_llm.transformers import AutoModelForCausalLM
25+
from transformers import AutoTokenizer
26+
27+
if __name__ == '__main__':
28+
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for THUDM/glm-4v-9b model')
29+
parser.add_argument('--repo-id-or-model-path', type=str, default="THUDM/glm-4v-9b",
30+
help='The huggingface repo id for the THUDM/glm-4v-9b model to be downloaded'
31+
', or the path to the huggingface checkpoint folder')
32+
parser.add_argument('--image-url-or-path', type=str,
33+
default="http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg",
34+
help='The URL or path to the image to infer')
35+
parser.add_argument('--prompt', type=str, default="What is in the image?",
36+
help='Prompt to infer')
37+
parser.add_argument('--n-predict', type=int, default=32,
38+
help='Max tokens to predict')
39+
40+
args = parser.parse_args()
41+
model_path = args.repo_id_or_model_path
42+
image_path = args.image_url_or_path
43+
44+
# Load model in 4 bit,
45+
# which convert the relevant layers in the model into INT4 format
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+
52+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
53+
54+
query = args.prompt
55+
if os.path.exists(image_path):
56+
image = Image.open(image_path)
57+
else:
58+
image = Image.open(requests.get(image_path, stream=True).raw)
59+
60+
# here the prompt tuning refers to https://huggingface.co/THUDM/glm-4v-9b/blob/main/README.md
61+
inputs = tokenizer.apply_chat_template([{"role": "user", "image": image, "content": query}],
62+
add_generation_prompt=True,
63+
tokenize=True,
64+
return_tensors="pt",
65+
return_dict=True) # chat mode
66+
inputs = inputs.to('cpu')
67+
68+
# Generate predicted tokens
69+
with torch.inference_mode():
70+
gen_kwargs = {"max_length": args.n_predict, "do_sample": True, "top_k": 1}
71+
st = time.time()
72+
outputs = model.generate(**inputs, **gen_kwargs)
73+
outputs = outputs[:, inputs['input_ids'].shape[1]:]
74+
end = time.time()
75+
print(f'Inference time: {end-st} s')
76+
output_str = tokenizer.decode(outputs[0])
77+
print('-'*20, 'Output', '-'*20)
78+
print(output_str)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# GLM-4V
2+
In this directory, you will find examples on how you could apply IPEX-LLM FP8 optimizations on GLM-4V models on [Intel GPUs](../../../README.md). For illustration purposes, we utilize the [THUDM/glm-4v-9b](https://huggingface.co/THUDM/glm-4v-9b) as a reference GLM-4V 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+
## Example: Predict Tokens using `generate()` API
8+
In the example [generate.py](./generate.py), we show a basic use case for a GLM-4V model to predict the next N tokens using `generate()` API, with IPEX-LLM FP8 optimizations on Intel GPUs.
9+
### 1. Install
10+
#### 1.1 Installation on Linux
11+
We suggest using conda to manage environment:
12+
```bash
13+
conda create -n llm python=3.11
14+
conda activate llm
15+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
16+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
17+
18+
pip install tiktoken
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+
pip install tiktoken
31+
```
32+
33+
### 2. Configures OneAPI environment variables for Linux
34+
35+
> [!NOTE]
36+
> Skip this step if you are running on Windows.
37+
38+
This is a required step on Linux for APT or offline installed oneAPI. Skip this step for PIP-installed oneAPI.
39+
40+
```bash
41+
source /opt/intel/oneapi/setvars.sh
42+
```
43+
44+
### 3. Runtime Configurations
45+
For optimal performance, it is recommended to set several environment variables. Please check out the suggestions based on your device.
46+
#### 3.1 Configurations for Linux
47+
<details>
48+
49+
<summary>For Intel Arc™ A-Series Graphics and Intel Data Center GPU Flex Series</summary>
50+
51+
```bash
52+
export USE_XETLA=OFF
53+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
54+
export SYCL_CACHE_PERSISTENT=1
55+
```
56+
57+
</details>
58+
59+
<details>
60+
61+
<summary>For Intel Data Center GPU Max Series</summary>
62+
63+
```bash
64+
export LD_PRELOAD=${LD_PRELOAD}:${CONDA_PREFIX}/lib/libtcmalloc.so
65+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
66+
export SYCL_CACHE_PERSISTENT=1
67+
export ENABLE_SDP_FUSION=1
68+
```
69+
> Note: Please note that `libtcmalloc.so` can be installed by `conda install -c conda-forge -y gperftools=2.10`.
70+
</details>
71+
72+
<details>
73+
74+
<summary>For Intel iGPU</summary>
75+
76+
```bash
77+
export SYCL_CACHE_PERSISTENT=1
78+
export BIGDL_LLM_XMX_DISABLED=1
79+
```
80+
81+
</details>
82+
83+
#### 3.2 Configurations for Windows
84+
<details>
85+
86+
<summary>For Intel iGPU</summary>
87+
88+
```cmd
89+
set SYCL_CACHE_PERSISTENT=1
90+
set BIGDL_LLM_XMX_DISABLED=1
91+
```
92+
93+
</details>
94+
95+
<details>
96+
97+
<summary>For Intel Arc™ A-Series Graphics</summary>
98+
99+
```cmd
100+
set SYCL_CACHE_PERSISTENT=1
101+
```
102+
103+
</details>
104+
105+
> [!NOTE]
106+
> 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.
107+
### 4. Running examples
108+
109+
```
110+
python ./generate.py --prompt 'What is in the image?'
111+
```
112+
113+
Arguments info:
114+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the GLM-4V model (e.g. `THUDM/glm-4v-9b`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'THUDM/glm-4v-9b'`.
115+
- `--image-url-or-path IMAGE_URL_OR_PATH`: argument defining the image to be infered. It is default to be `'http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg'`.
116+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'What is in the image?'`.
117+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
118+
119+
#### Sample Output
120+
#### [THUDM/glm-4v-9b](https://huggingface.co/THUDM/glm-4v-9b)
121+
122+
```log
123+
Inference time: xxxx s
124+
-------------------- Prompt --------------------
125+
What is in the image?
126+
-------------------- Output --------------------
127+
The image shows a young child holding up a small white teddy bear dressed in a pink
128+
```
129+
130+
The sample input image is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=264959)):
131+
132+
<a href="http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg"><img width=400px src="http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg" ></a>

0 commit comments

Comments
 (0)