Skip to content

Commit 32e8362

Browse files
authored
added minicpm cpu examples (#12027)
* minicpm cpu examples * add link for minicpm-2
1 parent a0c73c2 commit 32e8362

File tree

4 files changed

+205
-2
lines changed

4 files changed

+205
-2
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ Over 50 models have been optimized/verified on `ipex-llm`, including *LLaMA/LLaM
317317
| CodeGeeX2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/codegeex2) | [link](python/llm/example/GPU/HuggingFace/LLM/codegeex2) |
318318
| MiniCPM | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/minicpm) | [link](python/llm/example/GPU/HuggingFace/LLM/minicpm) |
319319
| MiniCPM-V | | [link](python/llm/example/GPU/HuggingFace/Multimodal/MiniCPM-V) |
320-
| MiniCPM-V-2 | | [link](python/llm/example/GPU/HuggingFace/Multimodal/MiniCPM-V-2) |
320+
| MiniCPM-V-2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/minicpm-v-2) | [link](python/llm/example/GPU/HuggingFace/Multimodal/MiniCPM-V-2) |
321321
| MiniCPM-Llama3-V-2_5 | | [link](python/llm/example/GPU/HuggingFace/Multimodal/MiniCPM-Llama3-V-2_5) |
322322
| MiniCPM-V-2_6 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/minicpm-v-2_6) | [link](python/llm/example/GPU/HuggingFace/Multimodal/MiniCPM-V-2_6) |
323323

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# MiniCPM-V-2
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on MiniCPM-V-2 models. For illustration purposes, we utilize the [openbmb/MiniCPM-V-2](https://huggingface.co/openbmb/MiniCPM-V-2) as a reference MiniCPM-V-2 model.
3+
4+
## 0. Requirements
5+
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.
6+
7+
## Example: Predict Tokens using `chat()` API
8+
In the example [chat.py](./chat.py), we show a basic use case for a MiniCPM-V-2 model to predict the next N tokens using `chat()` API, with IPEX-LLM INT4 optimizations.
9+
### 1. Install
10+
We suggest using conda to manage environment:
11+
12+
On Linux:
13+
14+
```bash
15+
conda create -n llm python=3.11
16+
conda activate llm
17+
18+
# install ipex-llm with 'all' option
19+
pip install --pre --upgrade ipex-llm[all] --extra-index-url https://download.pytorch.org/whl/cpu
20+
pip install torchvision==0.16.2 --index-url https://download.pytorch.org/whl/cpu
21+
pip install peft timm
22+
```
23+
On Windows:
24+
25+
```cmd
26+
conda create -n llm python=3.11
27+
conda activate llm
28+
29+
pip install --pre --upgrade ipex-llm[all]
30+
pip install torchvision==0.16.2 --index-url https://download.pytorch.org/whl/cpu
31+
pip install peft timm
32+
```
33+
34+
### 2. Run
35+
36+
- chat without streaming mode:
37+
```
38+
python ./chat.py --prompt 'What is in the image?'
39+
```
40+
- chat in streaming mode:
41+
```
42+
python ./chat.py --prompt 'What is in the image?' --stream
43+
```
44+
45+
> [!TIP]
46+
> For chatting in streaming mode, it is recommended to set the environment variable `PYTHONUNBUFFERED=1`.
47+
48+
49+
Arguments info:
50+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the MiniCPM-V-2 model (e.g. `openbmb/MiniCPM-V-2`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'openbmb/MiniCPM-V-2'`.
51+
- `--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'`.
52+
- `--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?'`.
53+
- `--stream`: flag to chat in streaming mode
54+
55+
> **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.
56+
>
57+
> Please select the appropriate size of the MiniCPM model based on the capabilities of your machine.
58+
59+
#### 2.1 Client
60+
On client Windows machine, it is recommended to run directly with full utilization of all cores:
61+
```cmd
62+
python ./chat.py
63+
```
64+
65+
#### 2.2 Server
66+
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.
67+
68+
E.g. on Linux,
69+
```bash
70+
# set IPEX-LLM env variables
71+
source ipex-llm-init
72+
73+
# e.g. for a server with 48 cores per socket
74+
export OMP_NUM_THREADS=48
75+
numactl -C 0-47 -m 0 python ./chat.py
76+
```
77+
78+
#### 2.3 Sample Output
79+
#### [openbmb/MiniCPM-V-2](https://huggingface.co/openbmb/MiniCPM-V-2)
80+
```log
81+
Inference time: xxxx s
82+
-------------------- Input Image --------------------
83+
http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg
84+
-------------------- Input Prompt --------------------
85+
What is in the image?
86+
-------------------- Chat Output --------------------
87+
The image features a young child holding a white teddy bear dressed in pink. The background includes some red flowers and what appears to be a stone wall.
88+
```
89+
90+
```log
91+
-------------------- Input Image --------------------
92+
http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg
93+
-------------------- Input Prompt --------------------
94+
图片里有什么?
95+
-------------------- Stream Chat Output --------------------
96+
图片中有一个小女孩,她手里拿着一个穿着粉色裙子的白色小熊玩偶。背景中有红色花朵和石头结构,可能是一个花园或庭院。
97+
```
98+
99+
The sample input image is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=264959)):
100+
101+
<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,102 @@
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+
import os
19+
import time
20+
import argparse
21+
import requests
22+
import torch
23+
from PIL import Image
24+
from ipex_llm.transformers import AutoModel
25+
from transformers import AutoTokenizer
26+
27+
28+
if __name__ == '__main__':
29+
parser = argparse.ArgumentParser(description='Predict Tokens using `chat()` API for MiniCPM-V-2_6 model')
30+
parser.add_argument('--repo-id-or-model-path', type=str, default="openbmb/MiniCPM-V-2_6",
31+
help='The huggingface repo id for the MiniCPM-V-2_6 model to be downloaded'
32+
', or the path to the huggingface checkpoint folder')
33+
parser.add_argument('--image-url-or-path', type=str,
34+
default='http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg',
35+
help='The URL or path to the image to infer')
36+
parser.add_argument('--prompt', type=str, default="What is in the image?",
37+
help='Prompt to infer')
38+
parser.add_argument('--stream', action='store_true',
39+
help='Whether to chat in streaming mode')
40+
41+
args = parser.parse_args()
42+
model_path = args.repo_id_or_model_path
43+
image_path = args.image_url_or_path
44+
45+
# Load model in 4 bit,
46+
# which convert the relevant layers in the model into INT4 format
47+
model = AutoModel.from_pretrained(model_path,
48+
load_in_low_bit="asym_int4",
49+
optimize_model=True,
50+
trust_remote_code=True,
51+
use_cache=True,
52+
torch_dtype=torch.float32,
53+
modules_to_not_convert=["vpm", "resampler"])
54+
55+
# Load tokenizer
56+
tokenizer = AutoTokenizer.from_pretrained(model_path,
57+
trust_remote_code=True)
58+
model.eval()
59+
60+
query = args.prompt
61+
if os.path.exists(image_path):
62+
image = Image.open(image_path).convert('RGB')
63+
else:
64+
image = Image.open(requests.get(image_path, stream=True).raw).convert('RGB')
65+
66+
# Generate predicted tokens
67+
# here the prompt tuning refers to https://huggingface.co/openbmb/MiniCPM-V-2_6/blob/main/README.md
68+
msgs = [{'role': 'user', 'content': args.prompt}]
69+
70+
if args.stream:
71+
res, context, _ = model.chat(
72+
image=image,
73+
msgs=msgs,
74+
context= None,
75+
tokenizer=tokenizer,
76+
stream=True
77+
)
78+
79+
print('-'*20, 'Input Image', '-'*20)
80+
print(image_path)
81+
print('-'*20, 'Input Prompt', '-'*20)
82+
print(args.prompt)
83+
print('-'*20, 'Stream Chat Output', '-'*20)
84+
for new_text in res:
85+
print(new_text, flush=True, end='')
86+
else:
87+
st = time.time()
88+
res, context, _ = model.chat(
89+
image=image,
90+
msgs=msgs,
91+
context=None,
92+
tokenizer=tokenizer,
93+
)
94+
end = time.time()
95+
96+
print(f'Inference time: {end-st} s')
97+
print('-'*20, 'Input Image', '-'*20)
98+
print(image_path)
99+
print('-'*20, 'Input Prompt', '-'*20)
100+
print(args.prompt)
101+
print('-'*20, 'Chat Output', '-'*20)
102+
print(res)

python/llm/example/CPU/HF-Transformers-AutoModels/Model/minicpm-v-2_6/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ conda activate llm
2828
2929
pip install --pre --upgrade ipex-llm[all]
3030
pip install torchvision==0.16.2 --index-url https://download.pytorch.org/whl/cpu
31-
pip install transformers==4.40.0 trl
31+
pip install transformers==4.41.0 trl
3232
```
3333

3434
### 2. Run

0 commit comments

Comments
 (0)