Skip to content

Commit cc5806f

Browse files
authored
LLM: add save/load example for hf-transformers (#10432)
1 parent a7da619 commit cc5806f

File tree

3 files changed

+212
-0
lines changed

3 files changed

+212
-0
lines changed

python/llm/example/GPU/HF-Transformers-AutoModels/Save-Load/.keep

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
# Save/Load Low-Bit Models with BigDL-LLM Optimizations
2+
3+
In this directory, you will find example on how you could save/load models with BigDL-LLM INT4 optimizations on Llama2 models on [Intel GPUs](../../../README.md). For illustration purposes, we utilize the [meta-llama/Llama-2-7b-chat-hf](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf) and [meta-llama/Llama-2-13b-chat-hf](https://huggingface.co/meta-llama/Llama-2-13b-chat-hf) as reference Llama2 models.
4+
5+
## 0. Requirements
6+
To run this example with BigDL-LLM, we have some recommended requirements for your machine, please refer to [here](../../README.md#system-support) for more information.
7+
8+
## Example: Save/Load Model in Low-Bit Optimization
9+
In the example [generate.py](./generate.py), we show a basic use case of saving/loading model in low-bit optimizations to predict the next N tokens using `generate()` API. Also, saving and loading operations are platform-independent, so you could run it on different platforms.
10+
### 1. Install
11+
#### 1.1 Installation on Linux
12+
We suggest using conda to manage environment:
13+
```bash
14+
conda create -n llm python=3.9
15+
conda activate llm
16+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
17+
pip install --pre --upgrade bigdl-llm[xpu] -f https://developer.intel.com/ipex-whl-stable-xpu
18+
```
19+
20+
#### 1.2 Installation on Windows
21+
We suggest using conda to manage environment:
22+
```bash
23+
conda create -n llm python=3.9 libuv
24+
conda activate llm
25+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
26+
pip install --pre --upgrade bigdl-llm[xpu] -f https://developer.intel.com/ipex-whl-stable-xpu
27+
```
28+
29+
### 2. Configures OneAPI environment variables
30+
#### 2.1 Configurations for Linux
31+
```bash
32+
source /opt/intel/oneapi/setvars.sh
33+
```
34+
35+
#### 2.2 Configurations for Windows
36+
```cmd
37+
call "C:\Program Files (x86)\Intel\oneAPI\setvars.bat"
38+
```
39+
> Note: Please make sure you are using **CMD** (**Anaconda Prompt** if using conda) to run the command as PowerShell is not supported.
40+
41+
42+
### 3. Run
43+
#### 3.1 Configurations for Linux
44+
<details>
45+
46+
<summary>For Intel Arc™ A-Series Graphics and Intel Data Center GPU Flex Series</summary>
47+
48+
```bash
49+
export USE_XETLA=OFF
50+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
51+
```
52+
53+
</details>
54+
55+
<details>
56+
57+
<summary>For Intel Data Center GPU Max Series</summary>
58+
59+
```bash
60+
export LD_PRELOAD=${LD_PRELOAD}:${CONDA_PREFIX}/lib/libtcmalloc.so
61+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
62+
export ENABLE_SDP_FUSION=1
63+
```
64+
> Note: Please note that `libtcmalloc.so` can be installed by `conda install -c conda-forge -y gperftools=2.10`.
65+
</details>
66+
67+
#### 3.2 Configurations for Windows
68+
<details>
69+
70+
<summary>For Intel iGPU</summary>
71+
72+
```cmd
73+
set SYCL_CACHE_PERSISTENT=1
74+
set BIGDL_LLM_XMX_DISABLED=1
75+
```
76+
77+
</details>
78+
79+
<details>
80+
81+
<summary>For Intel Arc™ A300-Series or Pro A60</summary>
82+
83+
```cmd
84+
set SYCL_CACHE_PERSISTENT=1
85+
```
86+
87+
</details>
88+
89+
<details>
90+
91+
<summary>For other Intel dGPU Series</summary>
92+
93+
There is no need to set further environment variables.
94+
95+
</details>
96+
97+
> 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.
98+
99+
### 4. Running examples
100+
101+
If you want to save the optimized low-bit model, run:
102+
```
103+
python ./generate.py --save-path path/to/save/model
104+
```
105+
106+
If you want to load the optimized low-bit model, run:
107+
```
108+
python ./generate.py --load-path path/to/load/model
109+
```
110+
111+
In the example, several arguments can be passed to satisfy your requirements:
112+
113+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Llama2 model to be downloaded, or the path to the ModelScope checkpoint folder. It is default to be `'meta-llama/Llama-2-7b-chat-hf'`.
114+
- `--save-path`: argument defining the path to save the low-bit model. Then you can load the low-bit directly.
115+
- `--load-path`: argument defining the path to load low-bit model.
116+
- `--prompt PROMPT`: argument defining the prompt to be inferred (with integrated prompt format for chat). It is default to be `'What is AI?'`.
117+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
118+
119+
#### Sample Output
120+
#### [meta-llama/Llama-2-7b-chat-hf](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf)
121+
```log
122+
Inference time: xxxx s
123+
-------------------- Output --------------------
124+
### HUMAN:
125+
What is AI?
126+
127+
### RESPONSE:
128+
129+
AI is a term used to describe the development of computer systems that can perform tasks that typically require human intelligence, such as understanding natural language, recognizing images
130+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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 torch
18+
import time
19+
import argparse
20+
from bigdl.llm.transformers import AutoModelForCausalLM
21+
from transformers import LlamaTokenizer
22+
23+
# you could tune the prompt based on your own model,
24+
# here the prompt tuning refers to https://huggingface.co/georgesung/llama2_7b_chat_uncensored#prompt-style
25+
LLAMA2_PROMPT_FORMAT = """### HUMAN:
26+
{prompt}
27+
28+
### RESPONSE:
29+
"""
30+
31+
if __name__ == '__main__':
32+
parser = argparse.ArgumentParser(description='Example of saving and loading the optimized model')
33+
parser.add_argument('--repo-id-or-model-path', type=str, default="meta-llama/Llama-2-7b-chat-hf",
34+
help='The huggingface repo id for the Llama2 (e.g. `meta-llama/Llama-2-7b-chat-hf` and `meta-llama/Llama-2-13b-chat-hf`) to be downloaded'
35+
', or the path to the huggingface checkpoint folder')
36+
parser.add_argument('--save-path', type=str, default=None,
37+
help='The path to save the low-bit model.')
38+
parser.add_argument('--load-path', type=str, default=None,
39+
help='The path to load the low-bit model.')
40+
parser.add_argument('--prompt', type=str, default="What is AI?",
41+
help='Prompt to infer')
42+
parser.add_argument('--n-predict', type=int, default=32,
43+
help='Max tokens to predict')
44+
args = parser.parse_args()
45+
model_path = args.repo_id_or_model_path
46+
load_path = args.load_path
47+
if load_path:
48+
model = AutoModelForCausalLM.load_low_bit(load_path, trust_remote_code=True)
49+
tokenizer = LlamaTokenizer.from_pretrained(load_path)
50+
else:
51+
model = AutoModelForCausalLM.from_pretrained(model_path,
52+
load_in_4bit=True,
53+
trust_remote_code=True)
54+
tokenizer = LlamaTokenizer.from_pretrained(model_path, trust_remote_code=True)
55+
56+
save_path = args.save_path
57+
if save_path:
58+
model.save_low_bit(save_path)
59+
tokenizer.save_pretrained(save_path)
60+
print(f"Model and tokenizer are saved to {save_path}")
61+
62+
# please save/load model before you run it on GPU
63+
model = model.to('xpu')
64+
65+
# Generate predicted tokens
66+
with torch.inference_mode():
67+
prompt = LLAMA2_PROMPT_FORMAT.format(prompt=args.prompt)
68+
input_ids = tokenizer.encode(prompt, return_tensors="pt").to('xpu')
69+
# ipex model needs a warmup, then inference time can be accurate
70+
output = model.generate(input_ids,
71+
max_new_tokens=args.n_predict)
72+
73+
st = time.time()
74+
output = model.generate(input_ids,
75+
max_new_tokens=args.n_predict)
76+
torch.xpu.synchronize()
77+
end = time.time()
78+
output = output.cpu()
79+
output_str = tokenizer.decode(output[0], skip_special_tokens=True)
80+
print(f'Inference time: {end-st} s')
81+
print('-'*20, 'Output', '-'*20)
82+
print(output_str)

0 commit comments

Comments
 (0)