Add CPU examples of fuyu (#9393)
* add fuyu cpu examples * add gpu example * add comments * add license * remove gpu example * fix inference time
This commit is contained in:
parent
df8e4d7889
commit
36fbe2144d
6 changed files with 284 additions and 0 deletions
|
|
@ -163,6 +163,7 @@ Over 20 models have been optimized/verified on `bigdl-llm`, including *LLaMA/LLa
|
|||
| InternLM-XComposer | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/internlm-xcomposer) | |
|
||||
| WizardCoder-Python | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/wizardcoder-python) | |
|
||||
| CodeShell | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/CodeShell) | |
|
||||
| Fuyu | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/fuyu) | |
|
||||
|
||||
|
||||
***For more details, please refer to the `bigdl-llm` [Document](https://test-bigdl-llm.readthedocs.io/en/main/doc/LLM/index.html), [Readme](python/llm), [Tutorial](https://github.com/intel-analytics/bigdl-llm-tutorial) and [API Doc](https://bigdl.readthedocs.io/en/latest/doc/PythonAPI/LLM/index.html).***
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ Over 20 models have been optimized/verified on `bigdl-llm`, including *LLaMA/LLa
|
|||
| InternLM-XComposer | [link](example/CPU/HF-Transformers-AutoModels/Model/internlm-xcomposer) | |
|
||||
| WizardCoder-Python | [link](example/CPU/HF-Transformers-AutoModels/Model/wizardcoder-python) | |
|
||||
| CodeShell | [link](example/CPU/HF-Transformers-AutoModels/Model/CodeShell) | |
|
||||
| Fuyu | [link](example/CPU/HF-Transformers-AutoModels/Model/fuyu) | |
|
||||
|
||||
### Working with `bigdl-llm`
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,74 @@
|
|||
# Fuyu
|
||||
In this directory, you will find examples on how you could apply BigDL-LLM INT4 optimizations on Fuyu models. For illustration purposes, we utilize the [adept/fuyu-8b](https://huggingface.co/adept/fuyu-8b) as a reference Fuyu model.
|
||||
|
||||
## Requirements
|
||||
To run these examples with BigDL-LLM, we have some recommended requirements for your machine, please refer to [here](../README.md#recommended-requirements) for more information.
|
||||
|
||||
## Example: Predict Tokens using `generate()` API
|
||||
In the example [generate.py](./generate.py), we show a basic use case for an Fuyu model to predict the next N tokens using `generate()` API, with BigDL-LLM INT4 optimizations.
|
||||
### 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
|
||||
|
||||
pip install --pre --upgrade bigdl-llm[all] # install the latest bigdl-llm nightly build with 'all' option
|
||||
|
||||
pip install transformers==4.35 pillow # additional package required for Fuyu to conduct generation
|
||||
```
|
||||
|
||||
### 2. Run
|
||||
After setting up the Python environment, you could run the example by following steps.
|
||||
|
||||
> **Note**: When loading the model in 4-bit, BigDL-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.
|
||||
>
|
||||
> Please select the appropriate size of the Fuyu model based on the capabilities of your machine.
|
||||
|
||||
#### 2.1 Client
|
||||
On client Windows machines, it is recommended to run directly with full utilization of all cores:
|
||||
```powershell
|
||||
python ./generate.py --image-path demo.jpg
|
||||
```
|
||||
More information about arguments can be found in [Arguments Info](#23-arguments-info) section. The expected output can be found in [Sample Output](#24-sample-output) section.
|
||||
|
||||
#### 2.2 Server
|
||||
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.
|
||||
|
||||
E.g. on Linux,
|
||||
```bash
|
||||
# set BigDL-Nano env variables
|
||||
source bigdl-nano-init
|
||||
|
||||
# e.g. for a server with 48 cores per socket
|
||||
export OMP_NUM_THREADS=48
|
||||
numactl -C 0-47 -m 0 python ./generate.py --image-path demo.jpg
|
||||
```
|
||||
More information about arguments can be found in [Arguments Info](#23-arguments-info) section. The expected output can be found in [Sample Output](#24-sample-output) section.
|
||||
|
||||
#### 2.3 Arguments Info
|
||||
In the example, several arguments can be passed to satisfy your requirements:
|
||||
|
||||
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Fuyu model (e.g. `adept/fuyu-8b`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'adept/fuyu-8b'`.
|
||||
- `--prompt PROMPT`: argument defining the prompt to be inferred (with the image for chat). It is default to be `'Generate a coco-style caption.'`.
|
||||
- `--image-path IMAGE_PATH`: argument defining the input image that the chat will focus on. It is required and should be a local path (not url).
|
||||
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `512`.
|
||||
|
||||
|
||||
#### 2.4 Sample Output
|
||||
#### [adept/fuyu-8b](https://huggingface.co/adept/fuyu-8b)
|
||||
|
||||
```log
|
||||
Inference time: xxxx s
|
||||
-------------------- Prompt --------------------
|
||||
Generate a coco-style caption.
|
||||
-------------------- Output --------------------
|
||||
An orange bus parked on the side of a road.
|
||||
```
|
||||
|
||||
The sample input image is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=178242)):
|
||||
|
||||
[demo.jpg](https://cocodataset.org/#explore?id=178242)
|
||||
|
||||
<a href="http://farm6.staticflickr.com/5331/8954873157_539393fece_z.jpg"><img width=400px src="http://farm6.staticflickr.com/5331/8954873157_539393fece_z.jpg" ></a>
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
from transformers import FuyuProcessor
|
||||
import torch
|
||||
import argparse
|
||||
import time
|
||||
from PIL import Image
|
||||
from bigdl.llm.transformers import AutoModelForCausalLM
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for Fuyu model')
|
||||
parser.add_argument('--repo-id-or-model-path', type=str, default="adept/fuyu-8b",
|
||||
help='The huggingface repo id for the Fuyu model to be downloaded'
|
||||
', or the path to the huggingface checkpoint folder')
|
||||
parser.add_argument('--prompt', type=str, default="Generate a coco-style caption.",
|
||||
help='Prompt to infer')
|
||||
parser.add_argument('--image-path', type=str, required=True,
|
||||
help='Image path for the input image that the chat will focus on')
|
||||
parser.add_argument('--n-predict', type=int, default=512, help='Max tokens to predict')
|
||||
|
||||
args = parser.parse_args()
|
||||
model_path = args.repo_id_or_model_path
|
||||
prompt = args.prompt
|
||||
image = Image.open(args.image_path)
|
||||
|
||||
# Load model
|
||||
# For successful BigDL-LLM optimization on Fuyu, skip the 'vision_embed_tokens' module during optimization
|
||||
model = AutoModelForCausalLM.from_pretrained(model_path, device_map='cpu',
|
||||
load_in_4bit = True,
|
||||
trust_remote_code=True,
|
||||
modules_to_not_convert=['vision_embed_tokens'])
|
||||
|
||||
# Load processor
|
||||
processor = FuyuProcessor.from_pretrained(model_path)
|
||||
|
||||
# Generate predicted tokens
|
||||
with torch.inference_mode():
|
||||
inputs = processor(text=prompt, images=image, return_tensors="pt")
|
||||
st = time.time()
|
||||
generation_outputs = model.generate(**inputs,
|
||||
max_new_tokens=args.n_predict)
|
||||
end = time.time()
|
||||
outputs = processor.batch_decode(generation_outputs[:, -args.n_predict:], skip_special_tokens=True)
|
||||
print(f'Inference time: {end-st} s')
|
||||
print('-'*20, 'Prompt', '-'*20)
|
||||
print(prompt)
|
||||
print('-'*20, 'Output', '-'*20)
|
||||
for output in outputs:
|
||||
# '\x04' is the "beginning of answer" token
|
||||
# See https://huggingface.co/adept/fuyu-8b#how-to-use
|
||||
answer = output.split('\x04 ', 1)[1] if '\x04' in output else ''
|
||||
print(answer)
|
||||
74
python/llm/example/CPU/PyTorch-Models/Model/fuyu/README.md
Normal file
74
python/llm/example/CPU/PyTorch-Models/Model/fuyu/README.md
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
# Fuyu
|
||||
In this directory, you will find examples on how you could apply BigDL-LLM INT4 optimizations on Fuyu models. For illustration purposes, we utilize the [adept/fuyu-8b](https://huggingface.co/adept/fuyu-8b) as a reference Fuyu model.
|
||||
|
||||
## Requirements
|
||||
To run these examples with BigDL-LLM, we have some recommended requirements for your machine, please refer to [here](../README.md#recommended-requirements) for more information.
|
||||
|
||||
## Example: Predict Tokens using `generate()` API
|
||||
In the example [generate.py](./generate.py), we show a basic use case for an Fuyu model to predict the next N tokens using `generate()` API, with BigDL-LLM INT4 optimizations.
|
||||
### 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
|
||||
|
||||
pip install --pre --upgrade bigdl-llm[all] # install the latest bigdl-llm nightly build with 'all' option
|
||||
|
||||
pip install transformers==4.35 pillow # additional package required for Fuyu to conduct generation
|
||||
```
|
||||
|
||||
### 2. Run
|
||||
After setting up the Python environment, you could run the example by following steps.
|
||||
|
||||
> **Note**: When loading the model in 4-bit, BigDL-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.
|
||||
>
|
||||
> Please select the appropriate size of the Fuyu model based on the capabilities of your machine.
|
||||
|
||||
#### 2.1 Client
|
||||
On client Windows machines, it is recommended to run directly with full utilization of all cores:
|
||||
```powershell
|
||||
python ./generate.py --image-path demo.jpg
|
||||
```
|
||||
More information about arguments can be found in [Arguments Info](#23-arguments-info) section. The expected output can be found in [Sample Output](#24-sample-output) section.
|
||||
|
||||
#### 2.2 Server
|
||||
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.
|
||||
|
||||
E.g. on Linux,
|
||||
```bash
|
||||
# set BigDL-Nano env variables
|
||||
source bigdl-nano-init
|
||||
|
||||
# e.g. for a server with 48 cores per socket
|
||||
export OMP_NUM_THREADS=48
|
||||
numactl -C 0-47 -m 0 python ./generate.py --image-path demo.jpg
|
||||
```
|
||||
More information about arguments can be found in [Arguments Info](#23-arguments-info) section. The expected output can be found in [Sample Output](#24-sample-output) section.
|
||||
|
||||
#### 2.3 Arguments Info
|
||||
In the example, several arguments can be passed to satisfy your requirements:
|
||||
|
||||
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Fuyu model (e.g. `adept/fuyu-8b`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'adept/fuyu-8b'`.
|
||||
- `--prompt PROMPT`: argument defining the prompt to be inferred (with the image for chat). It is default to be `'Generate a coco-style caption.'`.
|
||||
- `--image-path IMAGE_PATH`: argument defining the input image that the chat will focus on. It is required and should be a local path (not url).
|
||||
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `512`.
|
||||
|
||||
|
||||
#### 2.4 Sample Output
|
||||
#### [adept/fuyu-8b](https://huggingface.co/adept/fuyu-8b)
|
||||
|
||||
```log
|
||||
Inference time: xxxx s
|
||||
-------------------- Prompt --------------------
|
||||
Generate a coco-style caption.
|
||||
-------------------- Output --------------------
|
||||
An orange bus parked on the side of a road.
|
||||
```
|
||||
|
||||
The sample input image is (which is fetched from [COCO dataset](https://cocodataset.org/#explore?id=178242)):
|
||||
|
||||
[demo.jpg](https://cocodataset.org/#explore?id=178242)
|
||||
|
||||
<a href="http://farm6.staticflickr.com/5331/8954873157_539393fece_z.jpg"><img width=400px src="http://farm6.staticflickr.com/5331/8954873157_539393fece_z.jpg" ></a>
|
||||
68
python/llm/example/CPU/PyTorch-Models/Model/fuyu/generate.py
Normal file
68
python/llm/example/CPU/PyTorch-Models/Model/fuyu/generate.py
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
from transformers import AutoModelForCausalLM, FuyuProcessor
|
||||
import torch
|
||||
import argparse
|
||||
import time
|
||||
from PIL import Image
|
||||
from bigdl.llm import optimize_model
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for Fuyu model')
|
||||
parser.add_argument('--repo-id-or-model-path', type=str, default="adept/fuyu-8b",
|
||||
help='The huggingface repo id for the Fuyu model to be downloaded'
|
||||
', or the path to the huggingface checkpoint folder')
|
||||
parser.add_argument('--prompt', type=str, default="Generate a coco-style caption.",
|
||||
help='Prompt to infer')
|
||||
parser.add_argument('--image-path', type=str, required=True,
|
||||
help='Image path for the input image that the chat will focus on')
|
||||
parser.add_argument('--n-predict', type=int, default=512, help='Max tokens to predict')
|
||||
|
||||
args = parser.parse_args()
|
||||
model_path = args.repo_id_or_model_path
|
||||
prompt = args.prompt
|
||||
image = Image.open(args.image_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 Fuyu, skip the 'vision_embed_tokens' module during optimization
|
||||
model = optimize_model(model,
|
||||
low_bit='sym_int4',
|
||||
modules_to_not_convert=['vision_embed_tokens'])
|
||||
|
||||
# Load processor
|
||||
processor = FuyuProcessor.from_pretrained(model_path)
|
||||
|
||||
# Generate predicted tokens
|
||||
with torch.inference_mode():
|
||||
inputs = processor(text=prompt, images=image, return_tensors="pt")
|
||||
st = time.time()
|
||||
generation_outputs = model.generate(**inputs,
|
||||
max_new_tokens=args.n_predict)
|
||||
end = time.time()
|
||||
outputs = processor.batch_decode(generation_outputs[:, -args.n_predict:], skip_special_tokens=True)
|
||||
print(f'Inference time: {end-st} s')
|
||||
print('-'*20, 'Prompt', '-'*20)
|
||||
print(prompt)
|
||||
print('-'*20, 'Output', '-'*20)
|
||||
for output in outputs:
|
||||
# '\x04' is the "beginning of answer" token
|
||||
# See https://huggingface.co/adept/fuyu-8b#how-to-use
|
||||
answer = output.split('\x04 ', 1)[1] if '\x04' in output else ''
|
||||
print(answer)
|
||||
Loading…
Reference in a new issue