Skip to content

Commit 730d9ec

Browse files
authored
Add Qwen2-audio example (#11835)
* add draft for qwen2-audio * update example for `Qwen2-Audio` * update * update * add warmup
1 parent b11b28e commit 730d9ec

File tree

3 files changed

+203
-0
lines changed

3 files changed

+203
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@ Over 50 models have been optimized/verified on `ipex-llm`, including *LLaMA/LLaM
276276
| Qwen1.5 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/qwen1.5) | [link](python/llm/example/GPU/HuggingFace/LLM/qwen1.5) |
277277
| Qwen2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/qwen2) | [link](python/llm/example/GPU/HuggingFace/LLM/qwen2) |
278278
| Qwen-VL | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/qwen-vl) | [link](python/llm/example/GPU/HuggingFace/Multimodal/qwen-vl) |
279+
| Qwen2-Audio | | [link](python/llm/example/GPU/HuggingFace/Multimodal/qwen2-audio) |
279280
| Aquila | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/aquila) | [link](python/llm/example/GPU/HuggingFace/LLM/aquila) |
280281
| Aquila2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/aquila2) | [link](python/llm/example/GPU/HuggingFace/LLM/aquila2) |
281282
| MOSS | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/moss) | |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# Qwen2-Audio
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on Qwen2-Audio models on [Intel GPUs](../../../README.md). For illustration purposes, we utilize [Qwen/Qwen2-Audio-7B-Instruct](https://huggingface.co/Qwen/Qwen2-Audio-7B-Instruct) as reference 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+
8+
## Example: Predict Tokens using `generate()` API
9+
In the example [generate.py](./generate.py), we show a basic use case for a Qwen2-Audio model to conduct transcription using `processor` API, then use the recoginzed text as the input for Qwen2-Audio model to perform an English-Chinese translation using `generate()` API, with IPEX-LLM INT4 optimizations on Intel GPUs.
10+
### 1. Install
11+
12+
> [!NOTE]
13+
> Qwen2-Audio requires minimal `transformers` version of 4.35.0, which is not yet released. Currently, you can install the latest version of `transformers` from GitHub. When such a version is released, you can install it using `pip install transformers==4.35.0`.
14+
15+
#### 1.1 Installation on Linux
16+
We suggest using conda to manage environment:
17+
```bash
18+
conda create -n llm python=3.11
19+
conda activate llm
20+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
21+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
22+
23+
pip install librosa
24+
pip install git+https://github.com/huggingface/transformers
25+
```
26+
27+
#### 1.2 Installation on Windows
28+
We suggest using conda to manage environment:
29+
```bash
30+
conda create -n llm python=3.11 libuv
31+
conda activate llm
32+
33+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
34+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
35+
36+
pip install librosa
37+
pip install git+https://github.com/huggingface/transformers
38+
```
39+
40+
### 2. Configures OneAPI environment variables for Linux
41+
42+
> [!NOTE]
43+
> Skip this step if you are running on Windows.
44+
45+
This is a required step on Linux for APT or offline installed oneAPI. Skip this step for PIP-installed oneAPI.
46+
47+
```bash
48+
source /opt/intel/oneapi/setvars.sh
49+
```
50+
51+
### 3. Runtime Configurations
52+
For optimal performance, it is recommended to set several environment variables. Please check out the suggestions based on your device.
53+
#### 3.1 Configurations for Linux
54+
<details>
55+
56+
<summary>For Intel Arc™ A-Series Graphics and Intel Data Center GPU Flex Series</summary>
57+
58+
```bash
59+
export USE_XETLA=OFF
60+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
61+
export SYCL_CACHE_PERSISTENT=1
62+
```
63+
64+
</details>
65+
66+
<details>
67+
68+
<summary>For Intel Data Center GPU Max Series</summary>
69+
70+
```bash
71+
export LD_PRELOAD=${LD_PRELOAD}:${CONDA_PREFIX}/lib/libtcmalloc.so
72+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
73+
export SYCL_CACHE_PERSISTENT=1
74+
export ENABLE_SDP_FUSION=1
75+
```
76+
> Note: Please note that `libtcmalloc.so` can be installed by `conda install -c conda-forge -y gperftools=2.10`.
77+
</details>
78+
79+
<details>
80+
81+
<summary>For Intel iGPU</summary>
82+
83+
```bash
84+
export SYCL_CACHE_PERSISTENT=1
85+
export BIGDL_LLM_XMX_DISABLED=1
86+
```
87+
88+
</details>
89+
90+
#### 3.2 Configurations for Windows
91+
<details>
92+
93+
<summary>For Intel iGPU</summary>
94+
95+
```cmd
96+
set SYCL_CACHE_PERSISTENT=1
97+
set BIGDL_LLM_XMX_DISABLED=1
98+
```
99+
100+
</details>
101+
102+
<details>
103+
104+
<summary>For Intel Arc™ A-Series Graphics</summary>
105+
106+
```cmd
107+
set SYCL_CACHE_PERSISTENT=1
108+
```
109+
110+
</details>
111+
112+
> [!NOTE]
113+
> 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.
114+
### 4. Running examples
115+
116+
```
117+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH
118+
```
119+
120+
Arguments info:
121+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Qwen2-Audio model (e.g. `Qwen/Qwen2-Audio-7B-Instruct`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'Qwen/Qwen2-Audio-7B-Instruct'`.
122+
123+
#### Sample Output
124+
In `generate.py`, [an audio clip](https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/translate_to_chinese.wav) is used as the input, which asks the model to translate an English sentence into Chinese. The response from the model is expected to be similar to:
125+
```bash
126+
['每个人都希望被赏识,所以如果你欣赏某人,不要保密。']
127+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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 argparse
18+
from io import BytesIO
19+
from urllib.request import urlopen
20+
import librosa
21+
import torch
22+
from transformers import Qwen2AudioForConditionalGeneration, AutoProcessor
23+
from ipex_llm import optimize_model
24+
25+
def main(args):
26+
model_path = args.repo_id_or_model_path
27+
max_length = args.max_length
28+
audio_url = args.audio_url
29+
30+
processor = AutoProcessor.from_pretrained(model_path)
31+
model = Qwen2AudioForConditionalGeneration.from_pretrained(model_path)
32+
model = optimize_model(model, low_bit='sym_int4', optimize_llm=True)
33+
model = model.half().to('xpu')
34+
35+
conversation = [
36+
{"role": "user", "content": [
37+
{"type": "audio", "audio_url": audio_url},
38+
]},
39+
]
40+
text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
41+
audios = []
42+
for message in conversation:
43+
if isinstance(message["content"], list):
44+
for ele in message["content"]:
45+
if ele["type"] == "audio":
46+
audios.append(librosa.load(
47+
BytesIO(urlopen(ele['audio_url']).read()),
48+
sr=processor.feature_extractor.sampling_rate)[0]
49+
)
50+
51+
inputs = processor(text=text, audios=audios, return_tensors="pt", padding=True)
52+
inputs = inputs.to('xpu')
53+
54+
with torch.inference_mode():
55+
generate_ids = model.generate(**inputs, max_length=max_length) # warmup
56+
import time
57+
st = time.time()
58+
generate_ids = model.generate(**inputs, max_length=max_length)
59+
generate_ids = generate_ids[:, inputs.input_ids.size(1):]
60+
et = time.time()
61+
print(f'Inference time: {et-st} s')
62+
63+
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
64+
print(response)
65+
66+
if __name__=="__main__":
67+
parser = argparse.ArgumentParser(description="Qwen2-Audio")
68+
parser.add_argument('--repo-id-or-model-path', type=str, default="Qwen/Qwen2-Audio-7B-Instruct",
69+
help='The huggingface repo id for the Qwen2-Audio model checkpoint')
70+
parser.add_argument('--max-length', type=int, default=256,
71+
help='The max length of input text')
72+
parser.add_argument('--audio-url', type=str, default="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/translate_to_chinese.wav",
73+
help='The URL to the input audio file')
74+
args = parser.parse_args()
75+
main(args)

0 commit comments

Comments
 (0)