From 2f4c754759fc4ab42912eafe46ae961b9571f86f Mon Sep 17 00:00:00 2001
From: Jin Qiao <89779290+JinBridger@users.noreply.github.com>
Date: Wed, 7 Feb 2024 10:47:11 +0800
Subject: [PATCH] LLM: add bark gpu example (#10091)
* add bark gpu example
* fix
* fix license
* add bark
* add example
* fix
* another way
---
.../GPU/PyTorch-Models/Model/bark/README.md | 120 ++++++++++++++++++
.../Model/bark/synthesize_speech.py | 69 ++++++++++
2 files changed, 189 insertions(+)
create mode 100644 python/llm/example/GPU/PyTorch-Models/Model/bark/README.md
create mode 100644 python/llm/example/GPU/PyTorch-Models/Model/bark/synthesize_speech.py
diff --git a/python/llm/example/GPU/PyTorch-Models/Model/bark/README.md b/python/llm/example/GPU/PyTorch-Models/Model/bark/README.md
new file mode 100644
index 00000000..0ec27177
--- /dev/null
+++ b/python/llm/example/GPU/PyTorch-Models/Model/bark/README.md
@@ -0,0 +1,120 @@
+# Bark
+In this directory, you will find examples on how you could use BigDL-LLM `optimize_model` API to accelerate Bark models. For illustration purposes, we utilize the [suno/bark-small](https://huggingface.co/suno/bark-small) as reference Bark models.
+
+## 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: Synthesize speech with the given input text
+In the example [synthesize_speech.py](./synthesize_speech.py), we show a basic use case for Bark model to synthesize speech based on the given text, with BigDL-LLM INT4 optimizations.
+### 1. Install
+#### 1.1 Installation on Linux
+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.1.10+xpu as default
+pip install --pre --upgrade bigdl-llm[xpu] -f https://developer.intel.com/ipex-whl-stable-xpu
+pip install scipy
+```
+
+#### 1.2 Installation on Windows
+We suggest using conda to manage environment:
+```bash
+conda create -n llm python=3.9 libuv
+conda activate llm
+
+# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
+pip install --pre --upgrade bigdl-llm[xpu] -f https://developer.intel.com/ipex-whl-stable-xpu
+pip install scipy
+```
+
+### 2. Configures OneAPI environment variables
+#### 2.1 Configurations for Linux
+```bash
+source /opt/intel/oneapi/setvars.sh
+```
+
+#### 2.2 Configurations for Windows
+```cmd
+call "C:\Program Files (x86)\Intel\oneAPI\setvars.bat"
+```
+> Note: Please make sure you are using **CMD** (**Anaconda Prompt** if using conda) to run the command as PowerShell is not supported.
+### 3. Runtime Configurations
+For optimal performance, it is recommended to set several environment variables. Please check out the suggestions based on your device.
+#### 3.1 Configurations for Linux
+
+
+For Intel Arc™ A-Series Graphics and Intel Data Center GPU Flex Series
+
+```bash
+export USE_XETLA=OFF
+export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
+```
+
+
+
+
+
+For Intel Data Center GPU Max Series
+
+```bash
+export LD_PRELOAD=${LD_PRELOAD}:${CONDA_PREFIX}/lib/libtcmalloc.so
+export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
+export ENABLE_SDP_FUSION=1
+```
+> Note: Please note that `libtcmalloc.so` can be installed by `conda install -c conda-forge -y gperftools=2.10`.
+
+
+#### 3.2 Configurations for Windows
+
+
+For Intel iGPU
+
+```cmd
+set SYCL_CACHE_PERSISTENT=1
+set BIGDL_LLM_XMX_DISABLED=1
+```
+
+
+
+
+
+For Intel Arc™ A300-Series or Pro A60
+
+```cmd
+set SYCL_CACHE_PERSISTENT=1
+```
+
+
+
+
+
+For other Intel dGPU Series
+
+There is no need to set further environment variables.
+
+
+
+> Note: 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.
+### 4. Running examples
+
+```bash
+python ./synthesize_speech.py --text 'BigDL-LLM is a library for running large language model on Intel XPU with very low latency.'
+```
+
+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 Bark model (e.g. `suno/bark-small` and `suno/bark`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'suno/bark-small'`.
+- `--voice-preset`: argument defining the voice preset of model. It is default to be `'v2/en_speaker_6'`.
+- `--text TEXT`: argument defining the text to synthesize speech. It is default to be `"BigDL-LLM is a library for running large language model on Intel XPU with very low latency."`.
+
+#### 4.1 Sample Output
+
+#### [suno/bark-small](https://huggingface.co/suno/bark-small)
+
+Text: BigDL-LLM is a library for running large language model on Intel XPU with very low latency.
+
+[Click here to hear sample output.](https://llm-assets.readthedocs.io/en/latest/_downloads/e92874986553193acbd321d1cfe29739/bark-example-output.wav)
diff --git a/python/llm/example/GPU/PyTorch-Models/Model/bark/synthesize_speech.py b/python/llm/example/GPU/PyTorch-Models/Model/bark/synthesize_speech.py
new file mode 100644
index 00000000..c7c3a3f0
--- /dev/null
+++ b/python/llm/example/GPU/PyTorch-Models/Model/bark/synthesize_speech.py
@@ -0,0 +1,69 @@
+#
+# 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 torch
+import scipy
+import time
+import argparse
+
+from bigdl.llm import optimize_model
+from transformers import AutoProcessor, BarkModel
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Synthesize speech with the given input text using Bark model')
+ parser.add_argument('--repo-id-or-model-path', type=str, default='suno/bark-small',
+ help='The huggingface repo id for the Bark model to be downloaded'
+ ', or the path to the huggingface checkpoint folder')
+ parser.add_argument('--voice-preset', type=str, default='v2/en_speaker_6',
+ help='The voice preset of model')
+ parser.add_argument('--text', type=str, default="BigDL-LLM is a library for running large language model on Intel XPU with very low latency.",
+ help='Text to synthesize speech')
+
+ args = parser.parse_args()
+ model_path = args.repo_id_or_model_path
+ voice_preset = args.voice_preset
+ text = args.text
+
+ # Load model
+ processor = AutoProcessor.from_pretrained(model_path)
+ model = BarkModel.from_pretrained(model_path)
+
+ # With only one line to enable BigDL-LLM optimization on model
+ # When running LLMs on Intel iGPUs for Windows users, we recommend setting `cpu_embedding=True` in the optimize_model function.
+ # This will allow the memory-intensive embedding layer to utilize the CPU instead of iGPU.
+ model = optimize_model(model)
+ model = model.to('xpu')
+
+ inputs = processor(text, voice_preset=voice_preset).to('xpu')
+
+ with torch.inference_mode():
+ # ipex model needs a warmup, then inference time can be accurate
+ audio_array = model.generate(**inputs)
+
+ st = time.time()
+ audio_array = model.generate(**inputs)
+ torch.xpu.synchronize()
+ end = time.time()
+
+ print(f"Inference time: {end-st} s")
+
+ audio_array = audio_array.cpu().numpy().squeeze()
+
+ from scipy.io.wavfile import write as write_wav
+ sample_rate = model.generation_config.sample_rate
+ write_wav("bigdl_llm_bark_out.wav", sample_rate, audio_array)