Skip to content

Commit 50cf563

Browse files
authored
Add example: MiniCPM-V (#11570)
1 parent 06745e5 commit 50cf563

File tree

3 files changed

+311
-0
lines changed

3 files changed

+311
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,7 @@ Over 50 models have been optimized/verified on `ipex-llm`, including *LLaMA/LLaM
305305
| Command-R/cohere | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/cohere) | [link](python/llm/example/GPU/HuggingFace/LLM/cohere) |
306306
| CodeGeeX2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/codegeex2) | [link](python/llm/example/GPU/HuggingFace/LLM/codegeex2) |
307307
| MiniCPM | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/minicpm) | [link](python/llm/example/GPU/HuggingFace/LLM/minicpm) |
308+
| MiniCPM-V | | [link](python/llm/example/GPU/HuggingFace/Multimodal/MiniCPM-V) |
308309

309310
## Get Support
310311
- Please report a bug or raise a feature request by opening a [Github Issue](https://github.com/intel-analytics/ipex-llm/issues)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# MiniCPM-V
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on MiniCPM-V models on [Intel GPUs](../../../README.md). For illustration purposes, we utilize the [openbmb/MiniCPM-V](https://huggingface.co/openbmb/MiniCPM-V) as a reference MiniCPM-V 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 `chat()` API
8+
In the example [generate.py](./generate.py), we show a basic use case for a MiniCPM-V model to predict the next N tokens using `chat()` API, with IPEX-LLM INT4 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 timm
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 timm
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 MiniCPM-V (e.g. `openbmb/MiniCPM-V`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'openbmb/MiniCPM-V'`.
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+
121+
#### [openbmb/MiniCPM-V](https://huggingface.co/openbmb/MiniCPM-V)
122+
123+
```log
124+
Inference time: xxxx s
125+
-------------------- Input --------------------
126+
https://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg
127+
-------------------- Prompt --------------------
128+
What is in the image?
129+
-------------------- Output --------------------
130+
The image showcases a young child holding a small white teddy bear. The teddy bear has a pink ribbon around its neck, and the child seems to be showing it off with a smile. Behind the child, there's a stone wall with red flowers, adding a touch of color to the scene.
131+
```
132+
133+
The sample input image is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=264959)):
134+
135+
<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,175 @@
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+
18+
from typing import List, Tuple, Optional, Union
19+
import math
20+
import timm
21+
import torch
22+
import torch.nn.functional as F
23+
24+
# patched: `timm` has limited support for XPU backend, so we need to use CPU as a workaround
25+
def resample_abs_pos_embed(
26+
posemb: torch.Tensor,
27+
new_size: List[int],
28+
old_size: Optional[List[int]] = None,
29+
num_prefix_tokens: int = 1,
30+
interpolation: str = 'bicubic',
31+
antialias: bool = True,
32+
verbose: bool = False,
33+
):
34+
# sort out sizes, assume square if old size not provided
35+
num_pos_tokens = posemb.shape[1]
36+
num_new_tokens = new_size[0] * new_size[1] + num_prefix_tokens
37+
if num_new_tokens == num_pos_tokens and new_size[0] == new_size[1]:
38+
return posemb
39+
40+
if old_size is None:
41+
hw = int(math.sqrt(num_pos_tokens - num_prefix_tokens))
42+
old_size = hw, hw
43+
44+
if num_prefix_tokens:
45+
posemb_prefix, posemb = posemb[:, :num_prefix_tokens], posemb[:, num_prefix_tokens:]
46+
else:
47+
posemb_prefix, posemb = None, posemb
48+
49+
# do the interpolation
50+
embed_dim = posemb.shape[-1]
51+
orig_dtype = posemb.dtype
52+
posemb = posemb.float() # interpolate needs float32
53+
posemb = posemb.reshape(1, old_size[0], old_size[1], -1).permute(0, 3, 1, 2)
54+
#posemb = F.interpolate(posemb, size=new_size, mode=interpolation, antialias=antialias)
55+
posemb = F.interpolate(posemb.to("cpu"), size=new_size, mode=interpolation, antialias=antialias).to(posemb.device)
56+
posemb = posemb.permute(0, 2, 3, 1).reshape(1, -1, embed_dim)
57+
posemb = posemb.to(orig_dtype)
58+
59+
# add back extra (class, etc) prefix tokens
60+
if posemb_prefix is not None:
61+
posemb = torch.cat([posemb_prefix, posemb], dim=1)
62+
63+
if not torch.jit.is_scripting() and verbose:
64+
_logger.info(f'Resized position embedding: {old_size} to {new_size}.')
65+
66+
return posemb
67+
68+
69+
def _pos_embed(self, x: torch.Tensor) -> torch.Tensor:
70+
if self.pos_embed is None:
71+
return x.view(x.shape[0], -1, x.shape[-1])
72+
73+
if self.dynamic_img_size:
74+
B, H, W, C = x.shape
75+
pos_embed = resample_abs_pos_embed(
76+
self.pos_embed,
77+
(H, W),
78+
num_prefix_tokens=0 if self.no_embed_class else self.num_prefix_tokens,
79+
)
80+
x = x.view(B, -1, C)
81+
else:
82+
pos_embed = self.pos_embed
83+
84+
to_cat = []
85+
if self.cls_token is not None:
86+
to_cat.append(self.cls_token.expand(x.shape[0], -1, -1))
87+
if self.reg_token is not None:
88+
to_cat.append(self.reg_token.expand(x.shape[0], -1, -1))
89+
90+
if self.no_embed_class:
91+
# deit-3, updated JAX (big vision)
92+
# position embedding does not overlap with class token, add then concat
93+
x = x + pos_embed
94+
if to_cat:
95+
x = torch.cat(to_cat + [x], dim=1)
96+
else:
97+
# original timm, JAX, and deit vit impl
98+
# pos_embed has entry for class token, concat then add
99+
if to_cat:
100+
x = torch.cat(to_cat + [x], dim=1)
101+
x = x + pos_embed
102+
103+
return self.pos_drop(x)
104+
105+
106+
setattr(timm.models.VisionTransformer, "_pos_embed", _pos_embed)
107+
108+
import os
109+
import time
110+
import argparse
111+
import requests
112+
from PIL import Image
113+
from ipex_llm.transformers import AutoModel
114+
from transformers import AutoTokenizer
115+
116+
117+
if __name__ == '__main__':
118+
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for openbmb/MiniCPM-V model')
119+
parser.add_argument('--repo-id-or-model-path', type=str, default="openbmb/MiniCPM-V",
120+
help='The huggingface repo id for the openbmb/MiniCPM-V model to be downloaded'
121+
', or the path to the huggingface checkpoint folder')
122+
parser.add_argument('--image-url-or-path', type=str,
123+
default='http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg',
124+
help='The URL or path to the image to infer')
125+
parser.add_argument('--prompt', type=str, default="What is in the image?",
126+
help='Prompt to infer')
127+
parser.add_argument('--n-predict', type=int, default=32,
128+
help='Max tokens to predict')
129+
130+
args = parser.parse_args()
131+
model_path = args.repo_id_or_model_path
132+
image_path = args.image_url_or_path
133+
134+
# Load model in 4 bit,
135+
# which convert the relevant layers in the model into INT4 format
136+
# When running LLMs on Intel iGPUs for Windows users, we recommend setting `cpu_embedding=True` in the from_pretrained function.
137+
# This will allow the memory-intensive embedding layer to utilize the CPU instead of iGPU.
138+
model = AutoModel.from_pretrained(model_path,
139+
load_in_4bit=True,
140+
optimize_model=False,
141+
trust_remote_code=True,
142+
modules_to_not_convert=["vpm", "resampler"],
143+
use_cache=True)
144+
model = model.float().to(device='xpu')
145+
tokenizer = AutoTokenizer.from_pretrained(model_path,
146+
trust_remote_code=True)
147+
model.eval()
148+
149+
query = args.prompt
150+
if os.path.exists(image_path):
151+
image = Image.open(image_path).convert('RGB')
152+
else:
153+
image = Image.open(requests.get(image_path, stream=True).raw).convert('RGB')
154+
155+
# Generate predicted tokens
156+
# here the prompt tuning refers to https://huggingface.co/openbmb/MiniCPM-V/blob/main/README.md
157+
msgs = [{'role': 'user', 'content': args.prompt}]
158+
st = time.time()
159+
res, context, _ = model.chat(
160+
image=image,
161+
msgs=msgs,
162+
context=None,
163+
tokenizer=tokenizer,
164+
sampling=True,
165+
temperature=0.7
166+
)
167+
end = time.time()
168+
print(f'Inference time: {end-st} s')
169+
print('-'*20, 'Input', '-'*20)
170+
print(image_path)
171+
print('-'*20, 'Prompt', '-'*20)
172+
print(args.prompt)
173+
output_str = res
174+
print('-'*20, 'Output', '-'*20)
175+
print(output_str)

0 commit comments

Comments
 (0)