LLM: Add qwen-vl gpu example (#9290)
* create qwen-vl gpu example. * add readme. * fix. * change input figure and update outputs. * add qwen-vl pytorch model gpu example. * fix. * add readme.
This commit is contained in:
		
							parent
							
								
									7e73c354a6
								
							
						
					
					
						commit
						9f3d4676c6
					
				
					 6 changed files with 356 additions and 0 deletions
				
			
		| 
						 | 
				
			
			@ -149,6 +149,7 @@ Over 20 models have been optimized/verified on `bigdl-llm`, including *LLaMA/LLa
 | 
			
		|||
| Baichuan2  | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/baichuan2) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/baichuan2)  |
 | 
			
		||||
| InternLM   | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/internlm)  | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/internlm)   |
 | 
			
		||||
| Qwen       | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/qwen)      | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/qwen)       |
 | 
			
		||||
| Qwen-VL    | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/qwen-vl)   | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/qwen-vl)    |
 | 
			
		||||
| Aquila     | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/aquila)    | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/aquila)     |
 | 
			
		||||
| MOSS       | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/moss)      |    | 
 | 
			
		||||
| Whisper    | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/whisper)   | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/whisper)    |
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -56,6 +56,7 @@ Over 20 models have been optimized/verified on `bigdl-llm`, including *LLaMA/LLa
 | 
			
		|||
| Baichuan2  | [link](example/CPU/HF-Transformers-AutoModels/Model/baichuan2) | [link](example/GPU/HF-Transformers-AutoModels/Model/baichuan2)  |
 | 
			
		||||
| InternLM   | [link](example/CPU/HF-Transformers-AutoModels/Model/internlm)  | [link](example/GPU/HF-Transformers-AutoModels/Model/internlm)   |
 | 
			
		||||
| Qwen       | [link](example/CPU/HF-Transformers-AutoModels/Model/qwen)      | [link](example/GPU/HF-Transformers-AutoModels/Model/qwen)       |
 | 
			
		||||
| Qwen-VL    | [link](example/CPU/HF-Transformers-AutoModels/Model/qwen-vl)   | [link](example/GPU/HF-Transformers-AutoModels/Model/qwen-vl)    |
 | 
			
		||||
| Aquila     | [link](example/CPU/HF-Transformers-AutoModels/Model/aquila)    | [link](example/GPU/HF-Transformers-AutoModels/Model/aquila)     |
 | 
			
		||||
| MOSS       | [link](example/CPU/HF-Transformers-AutoModels/Model/moss)      |    | 
 | 
			
		||||
| Whisper    | [link](example/CPU/HF-Transformers-AutoModels/Model/whisper)   | [link](example/GPU/HF-Transformers-AutoModels/Model/whisper)    |
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -0,0 +1,78 @@
 | 
			
		|||
# Qwen-VL
 | 
			
		||||
In this directory, you will find examples on how you could apply BigDL-LLM INT4 optimizations on Qwen-VL models on [Intel GPUs](../README.md). For illustration purposes, we utilize the [Qwen/Qwen-VL-Chat](https://huggingface.co/Qwen/Qwen-VL-Chat) as a reference Qwen-VL model.
 | 
			
		||||
 | 
			
		||||
## Requirements
 | 
			
		||||
To run these examples with BigDL-LLM on Intel GPUs, we have some recommended requirements for your machine, please refer to [here](../README.md#recommended-requirements) for more information.
 | 
			
		||||
 | 
			
		||||
## Example: Multimodal chat using `chat()` API
 | 
			
		||||
In the example [chat.py](./chat.py), we show a basic use case for a Qwen-VL model to start a multimodal chat using `chat()` API, with BigDL-LLM INT4 optimizations on Intel GPUs.
 | 
			
		||||
### 1. Install
 | 
			
		||||
We suggest using conda to manage the Python environment. For more information about conda installation, please refer to [here](https://docs.conda.io/en/latest/miniconda.html#).
 | 
			
		||||
 | 
			
		||||
After installing conda, create a Python environment for BigDL-LLM:
 | 
			
		||||
```bash
 | 
			
		||||
conda create -n llm python=3.9 # recommend to use Python 3.9
 | 
			
		||||
conda activate llm
 | 
			
		||||
# below command will install intel_extension_for_pytorch==2.0.110+xpu as default
 | 
			
		||||
# you can install specific ipex/torch version for your need
 | 
			
		||||
pip install --pre --upgrade bigdl-llm[xpu] -f https://developer.intel.com/ipex-whl-stable-xpu
 | 
			
		||||
pip install accelerate tiktoken einops transformers_stream_generator==0.0.4 scipy torchvision pillow tensorboard matplotlib # additional package required for Qwen-VL-Chat to conduct generation
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### 2. Configures OneAPI environment variables
 | 
			
		||||
```bash
 | 
			
		||||
source /opt/intel/oneapi/setvars.sh
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### 3. Run
 | 
			
		||||
 | 
			
		||||
For optimal performance on Arc, it is recommended to set several environment variables.
 | 
			
		||||
 | 
			
		||||
```bash
 | 
			
		||||
export USE_XETLA=OFF
 | 
			
		||||
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
 | 
			
		||||
```
 | 
			
		||||
```
 | 
			
		||||
python ./chat.py
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
Arguments info:
 | 
			
		||||
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Qwen-VL model (e.g `Qwen/Qwen-VL-Chat`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'Qwen/Qwen-VL-Chat'`.
 | 
			
		||||
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
 | 
			
		||||
  
 | 
			
		||||
In every session, image and text can be entered into cmd (user can skip the input by type **'Enter'**) ; please type **'exit'** anytime you want to quit the dialouge.
 | 
			
		||||
 | 
			
		||||
Every image output will be named as the round of session and placed under the current directory.
 | 
			
		||||
 | 
			
		||||
#### Sample Chat
 | 
			
		||||
#### [Qwen/Qwen-VL-Chat](https://huggingface.co/Qwen/Qwen-VL-Chat)
 | 
			
		||||
 | 
			
		||||
```log
 | 
			
		||||
-------------------- Session 1 --------------------
 | 
			
		||||
 Please input a picture: http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg
 | 
			
		||||
 Please enter the text: 这是什么?
 | 
			
		||||
---------- Response ----------
 | 
			
		||||
这是一张图片,展现了一个穿着粉色条纹连衣裙的小女孩,她手持一只穿粉色裙子的小熊。这个场景发生在一个户外环境,有砖块背景墙和花朵。
 | 
			
		||||
 | 
			
		||||
-------------------- Session 2 --------------------
 | 
			
		||||
 Please input a picture:
 | 
			
		||||
 Please enter the text: 这个小女孩多大了?
 | 
			
		||||
---------- Response ----------
 | 
			
		||||
根据图片中的描述,这个小女孩应该是年龄较小的孩子,但具体年龄难以确定。从她的外表来看,可能是在5岁左右。。 
 | 
			
		||||
 | 
			
		||||
-------------------- Session 3 --------------------
 | 
			
		||||
 Please input a picture: 
 | 
			
		||||
 Please enter the text: 在图中检测框出玩具熊
 | 
			
		||||
---------- Response ----------
 | 
			
		||||
<ref>玩具熊</ref><box>(330,267),(603,869)</box>
 | 
			
		||||
 | 
			
		||||
-------------------- Session 4 --------------------
 | 
			
		||||
 Please input a picture: exit
 | 
			
		||||
```
 | 
			
		||||
The sample input image in Session 1 is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=264959)):
 | 
			
		||||
 | 
			
		||||
<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>
 | 
			
		||||
 | 
			
		||||
The sample output image in Session 3 is:
 | 
			
		||||
 | 
			
		||||
<a href="https://llm-assets.readthedocs.io/en/latest/_images/qwen-vl-example-output-gpu.png"><img width=400px src="https://llm-assets.readthedocs.io/en/latest/_images/qwen-vl-example-output-gpu.png" ></a>
 | 
			
		||||
| 
						 | 
				
			
			@ -0,0 +1,98 @@
 | 
			
		|||
#
 | 
			
		||||
# Copyright 2016 The BigDL Authors.
 | 
			
		||||
#
 | 
			
		||||
# Licensed under the Apache License, Version 2.0 (the "License");
 | 
			
		||||
# you may not use this file except in compliance with the License.
 | 
			
		||||
# You may obtain a copy of the License at
 | 
			
		||||
#
 | 
			
		||||
#     http://www.apache.org/licenses/LICENSE-2.0
 | 
			
		||||
#
 | 
			
		||||
# Unless required by applicable law or agreed to in writing, software
 | 
			
		||||
# distributed under the License is distributed on an "AS IS" BASIS,
 | 
			
		||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
			
		||||
# See the License for the specific language governing permissions and
 | 
			
		||||
# limitations under the License.
 | 
			
		||||
#
 | 
			
		||||
 | 
			
		||||
import argparse
 | 
			
		||||
import os
 | 
			
		||||
 | 
			
		||||
import torch
 | 
			
		||||
from transformers import AutoTokenizer
 | 
			
		||||
from transformers.generation import GenerationConfig
 | 
			
		||||
 | 
			
		||||
from bigdl.llm.transformers import AutoModelForCausalLM
 | 
			
		||||
import intel_extension_for_pytorch as ipex
 | 
			
		||||
 | 
			
		||||
torch.manual_seed(1234)
 | 
			
		||||
 | 
			
		||||
if __name__ == '__main__':
 | 
			
		||||
    parser = argparse.ArgumentParser(description='Predict Tokens using `chat()` API for Qwen-VL model')
 | 
			
		||||
    parser.add_argument('--repo-id-or-model-path', type=str, default="Qwen/Qwen-VL-Chat",
 | 
			
		||||
                        help='The huggingface repo id for the Qwen-VL model to be downloaded'
 | 
			
		||||
                             ', or the path to the huggingface checkpoint folder')
 | 
			
		||||
    parser.add_argument('--n-predict', type=int, default=32, help='Max tokens to predict')
 | 
			
		||||
    
 | 
			
		||||
    current_path = os.path.dirname(os.path.abspath(__file__))
 | 
			
		||||
    args = parser.parse_args()
 | 
			
		||||
    model_path = args.repo_id_or_model_path  
 | 
			
		||||
        
 | 
			
		||||
    # Load model
 | 
			
		||||
    # For successful BigDL-LLM optimization on Qwen-VL-Chat, skip the 'c_fc' and 'out_proj' modules during optimization
 | 
			
		||||
    model = AutoModelForCausalLM.from_pretrained(model_path, 
 | 
			
		||||
                                                 load_in_4bit=True, 
 | 
			
		||||
                                                 trust_remote_code=True, 
 | 
			
		||||
                                                 modules_to_not_convert=['c_fc', 'out_proj'])
 | 
			
		||||
    model = model.to('xpu')
 | 
			
		||||
    # Due to issue https://github.com/intel/intel-extension-for-pytorch/issues/454,
 | 
			
		||||
    # currently put interpolation execution into cpu
 | 
			
		||||
    def to_cpu(module, input, output):
 | 
			
		||||
        return output.to("cpu")
 | 
			
		||||
 | 
			
		||||
    def to_xpu(module, input):
 | 
			
		||||
        return (input[0].to("xpu"),)
 | 
			
		||||
 | 
			
		||||
    model.transformer.visual.ln_pre.register_forward_hook(to_cpu)
 | 
			
		||||
    model.transformer.visual.transformer.register_forward_pre_hook(to_xpu)
 | 
			
		||||
 | 
			
		||||
    # Specify hyperparameters for generation (No need to do this if you are using transformers>=4.32.0)
 | 
			
		||||
    model.generation_config = GenerationConfig.from_pretrained(model_path, trust_remote_code=True)
 | 
			
		||||
    
 | 
			
		||||
    # Load tokenizer
 | 
			
		||||
    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
 | 
			
		||||
 | 
			
		||||
    # Session ID
 | 
			
		||||
    session_id = 1
 | 
			
		||||
 | 
			
		||||
    while True:
 | 
			
		||||
      print('-'*20, 'Session %d' % session_id, '-'*20)
 | 
			
		||||
      image_input = input(f' Please input a picture: ')
 | 
			
		||||
      if image_input.lower() == 'exit' : # type 'exit' to quit the dialouge
 | 
			
		||||
         break
 | 
			
		||||
 | 
			
		||||
      text_input = input(f' Please enter the text: ')
 | 
			
		||||
      if text_input.lower() == 'exit' : # type 'exit' to quit the dialouge
 | 
			
		||||
         break
 | 
			
		||||
      
 | 
			
		||||
      if session_id == 1:
 | 
			
		||||
         history = None
 | 
			
		||||
 | 
			
		||||
      all_input = [{'image': image_input}, {'text': text_input}]
 | 
			
		||||
      input_list = [_input for _input in all_input if list(_input.values())[0] != '']
 | 
			
		||||
 | 
			
		||||
      if len(input_list) == 0:
 | 
			
		||||
         print("Input list should not be empty. Please try again with valid input.")
 | 
			
		||||
         continue
 | 
			
		||||
      
 | 
			
		||||
      query = tokenizer.from_list_format(input_list)
 | 
			
		||||
      response, history = model.chat(tokenizer, query = query, history = history)
 | 
			
		||||
      torch.xpu.synchronize()
 | 
			
		||||
 | 
			
		||||
      print('-'*10, 'Response', '-'*10)
 | 
			
		||||
      print(response, '\n')
 | 
			
		||||
 | 
			
		||||
      image = tokenizer.draw_bbox_on_latest_picture(response, history)
 | 
			
		||||
      if image is not None:
 | 
			
		||||
         image.save(os.path.join(current_path, f'Session_{session_id}.png'), )
 | 
			
		||||
 | 
			
		||||
      session_id += 1
 | 
			
		||||
| 
						 | 
				
			
			@ -0,0 +1,78 @@
 | 
			
		|||
# Qwen-VL
 | 
			
		||||
In this directory, you will find examples on how you could use BigDL-LLM `optimize_model` API to accelerate Qwen-VL models on [Intel GPUs](../README.md). For illustration purposes, we utilize the [Qwen/Qwen-VL-Chat](https://huggingface.co/Qwen/Qwen-VL-Chat) as a reference Qwen-VL model.
 | 
			
		||||
 | 
			
		||||
## Requirements
 | 
			
		||||
To run these examples with BigDL-LLM on Intel GPUs, we have some recommended requirements for your machine, please refer to [here](../README.md#recommended-requirements) for more information.
 | 
			
		||||
 | 
			
		||||
## Example: Multimodal chat using `chat()` API
 | 
			
		||||
In the example [chat.py](./chat.py), we show a basic use case for a Qwen-VL model to start a multimodal chat using `chat()` API, with BigDL-LLM 'optimize_model' API on Intel GPUs.
 | 
			
		||||
### 1. Install
 | 
			
		||||
We suggest using conda to manage the Python environment. For more information about conda installation, please refer to [here](https://docs.conda.io/en/latest/miniconda.html#).
 | 
			
		||||
 | 
			
		||||
After installing conda, create a Python environment for BigDL-LLM:
 | 
			
		||||
```bash
 | 
			
		||||
conda create -n llm python=3.9 # recommend to use Python 3.9
 | 
			
		||||
conda activate llm
 | 
			
		||||
# below command will install intel_extension_for_pytorch==2.0.110+xpu as default
 | 
			
		||||
# you can install specific ipex/torch version for your need
 | 
			
		||||
pip install --pre --upgrade bigdl-llm[xpu] -f https://developer.intel.com/ipex-whl-stable-xpu
 | 
			
		||||
pip install accelerate tiktoken einops transformers_stream_generator==0.0.4 scipy torchvision pillow tensorboard matplotlib # additional package required for Qwen-VL-Chat to conduct generation
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### 2. Configures OneAPI environment variables
 | 
			
		||||
```bash
 | 
			
		||||
source /opt/intel/oneapi/setvars.sh
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### 3. Run
 | 
			
		||||
 | 
			
		||||
For optimal performance on Arc, it is recommended to set several environment variables.
 | 
			
		||||
 | 
			
		||||
```bash
 | 
			
		||||
export USE_XETLA=OFF
 | 
			
		||||
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
 | 
			
		||||
```
 | 
			
		||||
```
 | 
			
		||||
python ./chat.py
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
Arguments info:
 | 
			
		||||
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Qwen-VL model (e.g `Qwen/Qwen-VL-Chat`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'Qwen/Qwen-VL-Chat'`.
 | 
			
		||||
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
 | 
			
		||||
  
 | 
			
		||||
In every session, image and text can be entered into cmd (user can skip the input by type **'Enter'**) ; please type **'exit'** anytime you want to quit the dialouge.
 | 
			
		||||
 | 
			
		||||
Every image output will be named as the round of session and placed under the current directory.
 | 
			
		||||
 | 
			
		||||
#### Sample Chat
 | 
			
		||||
#### [Qwen/Qwen-VL-Chat](https://huggingface.co/Qwen/Qwen-VL-Chat)
 | 
			
		||||
 | 
			
		||||
```log
 | 
			
		||||
-------------------- Session 1 --------------------
 | 
			
		||||
 Please input a picture: http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg
 | 
			
		||||
 Please enter the text: 这是什么?
 | 
			
		||||
---------- Response ----------
 | 
			
		||||
这是一张图片,展现了一个穿着粉色条纹连衣裙的小女孩,她手持一只穿粉色裙子的小熊。这个场景发生在一个户外环境,有砖块背景墙和花朵。
 | 
			
		||||
 | 
			
		||||
-------------------- Session 2 --------------------
 | 
			
		||||
 Please input a picture:
 | 
			
		||||
 Please enter the text: 这个小女孩多大了?
 | 
			
		||||
---------- Response ----------
 | 
			
		||||
根据图片中的描述,这个小女孩应该是年龄较小的孩子,但具体年龄难以确定。从她的外表来看,可能是在5岁左右。。 
 | 
			
		||||
 | 
			
		||||
-------------------- Session 3 --------------------
 | 
			
		||||
 Please input a picture: 
 | 
			
		||||
 Please enter the text: 在图中检测框出玩具熊
 | 
			
		||||
---------- Response ----------
 | 
			
		||||
<ref>玩具熊</ref><box>(330,267),(603,869)</box>
 | 
			
		||||
 | 
			
		||||
-------------------- Session 4 --------------------
 | 
			
		||||
 Please input a picture: exit
 | 
			
		||||
```
 | 
			
		||||
The sample input image in Session 1 is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=264959)):
 | 
			
		||||
 | 
			
		||||
<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>
 | 
			
		||||
 | 
			
		||||
The sample output image in Session 3 is:
 | 
			
		||||
 | 
			
		||||
<a href="https://llm-assets.readthedocs.io/en/latest/_images/qwen-vl-example-output-gpu.png"><img width=400px src="https://llm-assets.readthedocs.io/en/latest/_images/qwen-vl-example-output-gpu.png" ></a>
 | 
			
		||||
							
								
								
									
										100
									
								
								python/llm/example/GPU/PyTorch-Models/Model/qwen-vl/chat.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										100
									
								
								python/llm/example/GPU/PyTorch-Models/Model/qwen-vl/chat.py
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
				
			
			@ -0,0 +1,100 @@
 | 
			
		|||
#
 | 
			
		||||
# Copyright 2016 The BigDL Authors.
 | 
			
		||||
#
 | 
			
		||||
# Licensed under the Apache License, Version 2.0 (the "License");
 | 
			
		||||
# you may not use this file except in compliance with the License.
 | 
			
		||||
# You may obtain a copy of the License at
 | 
			
		||||
#
 | 
			
		||||
#     http://www.apache.org/licenses/LICENSE-2.0
 | 
			
		||||
#
 | 
			
		||||
# Unless required by applicable law or agreed to in writing, software
 | 
			
		||||
# distributed under the License is distributed on an "AS IS" BASIS,
 | 
			
		||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
			
		||||
# See the License for the specific language governing permissions and
 | 
			
		||||
# limitations under the License.
 | 
			
		||||
#
 | 
			
		||||
 | 
			
		||||
import argparse
 | 
			
		||||
import os
 | 
			
		||||
 | 
			
		||||
import torch
 | 
			
		||||
from transformers import AutoModelForCausalLM, AutoTokenizer
 | 
			
		||||
from transformers.generation import GenerationConfig
 | 
			
		||||
 | 
			
		||||
from bigdl.llm import optimize_model
 | 
			
		||||
import intel_extension_for_pytorch as ipex
 | 
			
		||||
 | 
			
		||||
torch.manual_seed(1234)
 | 
			
		||||
 | 
			
		||||
if __name__ == '__main__':
 | 
			
		||||
    parser = argparse.ArgumentParser(description='Predict Tokens using `chat()` API for Qwen-VL model')
 | 
			
		||||
    parser.add_argument('--repo-id-or-model-path', type=str, default="Qwen/Qwen-VL-Chat",
 | 
			
		||||
                        help='The huggingface repo id for the Qwen-VL model to be downloaded'
 | 
			
		||||
                             ', or the path to the huggingface checkpoint folder')
 | 
			
		||||
    parser.add_argument('--n-predict', type=int, default=32, help='Max tokens to predict')
 | 
			
		||||
    
 | 
			
		||||
    current_path = os.path.dirname(os.path.abspath(__file__))
 | 
			
		||||
    args = parser.parse_args()
 | 
			
		||||
    model_path = args.repo_id_or_model_path  
 | 
			
		||||
        
 | 
			
		||||
    # Load model
 | 
			
		||||
    model = AutoModelForCausalLM.from_pretrained(model_path, device_map="cpu",  trust_remote_code=True)
 | 
			
		||||
 | 
			
		||||
    # With only one line to enable BigDL-LLM optimization on model
 | 
			
		||||
    # For successful BigDL-LLM optimization on Qwen-VL-Chat, skip the 'c_fc' and 'out_proj' modules during optimization
 | 
			
		||||
    model = optimize_model(model, 
 | 
			
		||||
                           low_bit='sym_int4', 
 | 
			
		||||
                           modules_to_not_convert=['c_fc', 'out_proj'])
 | 
			
		||||
    model = model.to('xpu')
 | 
			
		||||
    # Due to issue https://github.com/intel/intel-extension-for-pytorch/issues/454,
 | 
			
		||||
    # currently put interpolation execution into cpu
 | 
			
		||||
    def to_cpu(module, input, output):
 | 
			
		||||
        return output.to("cpu")
 | 
			
		||||
 | 
			
		||||
    def to_xpu(module, input):
 | 
			
		||||
        return (input[0].to("xpu"),)
 | 
			
		||||
 | 
			
		||||
    model.transformer.visual.ln_pre.register_forward_hook(to_cpu)
 | 
			
		||||
    model.transformer.visual.transformer.register_forward_pre_hook(to_xpu)
 | 
			
		||||
 | 
			
		||||
    # Specify hyperparameters for generation (No need to do this if you are using transformers>=4.32.0)
 | 
			
		||||
    model.generation_config = GenerationConfig.from_pretrained(model_path, trust_remote_code=True)
 | 
			
		||||
    
 | 
			
		||||
    # Load tokenizer
 | 
			
		||||
    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
 | 
			
		||||
 | 
			
		||||
    # Session ID
 | 
			
		||||
    session_id = 1
 | 
			
		||||
 | 
			
		||||
    while True:
 | 
			
		||||
      print('-'*20, 'Session %d' % session_id, '-'*20)
 | 
			
		||||
      image_input = input(f' Please input a picture: ')
 | 
			
		||||
      if image_input.lower() == 'exit' : # type 'exit' to quit the dialouge
 | 
			
		||||
         break
 | 
			
		||||
 | 
			
		||||
      text_input = input(f' Please enter the text: ')
 | 
			
		||||
      if text_input.lower() == 'exit' : # type 'exit' to quit the dialouge
 | 
			
		||||
         break
 | 
			
		||||
      
 | 
			
		||||
      if session_id == 1:
 | 
			
		||||
         history = None
 | 
			
		||||
 | 
			
		||||
      all_input = [{'image': image_input}, {'text': text_input}]
 | 
			
		||||
      input_list = [_input for _input in all_input if list(_input.values())[0] != '']
 | 
			
		||||
 | 
			
		||||
      if len(input_list) == 0:
 | 
			
		||||
         print("Input list should not be empty. Please try again with valid input.")
 | 
			
		||||
         continue
 | 
			
		||||
      
 | 
			
		||||
      query = tokenizer.from_list_format(input_list)
 | 
			
		||||
      response, history = model.chat(tokenizer, query = query, history = history)
 | 
			
		||||
      torch.xpu.synchronize()
 | 
			
		||||
 | 
			
		||||
      print('-'*10, 'Response', '-'*10)
 | 
			
		||||
      print(response, '\n')
 | 
			
		||||
 | 
			
		||||
      image = tokenizer.draw_bbox_on_latest_picture(response, history)
 | 
			
		||||
      if image is not None:
 | 
			
		||||
         image.save(os.path.join(current_path, f'Session_{session_id}.png'), )
 | 
			
		||||
 | 
			
		||||
      session_id += 1
 | 
			
		||||
		Loading…
	
		Reference in a new issue