Skip to content

Commit 5079ed9

Browse files
authored
Add Llama3.1 example (#11689)
* Add Llama3.1 example Add Llama3.1 example for Linux arc and Windows MTL * Changes made to adjust compatibilities transformers changed to 4.43.1 * Update index.rst * Update README.md * Update index.rst * Update index.rst * Update index.rst
1 parent 6e3ce28 commit 5079ed9

File tree

5 files changed

+398
-0
lines changed

5 files changed

+398
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ Over 50 models have been optimized/verified on `ipex-llm`, including *LLaMA/LLaM
247247
| LLaMA *(such as Vicuna, Guanaco, Koala, Baize, WizardLM, etc.)* | [link1](python/llm/example/CPU/Native-Models), [link2](python/llm/example/CPU/HF-Transformers-AutoModels/Model/vicuna) |[link](python/llm/example/GPU/HuggingFace/LLM/vicuna)|
248248
| LLaMA 2 | [link1](python/llm/example/CPU/Native-Models), [link2](python/llm/example/CPU/HF-Transformers-AutoModels/Model/llama2) | [link](python/llm/example/GPU/HuggingFace/LLM/llama2) |
249249
| LLaMA 3 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/llama3) | [link](python/llm/example/GPU/HuggingFace/LLM/llama3) |
250+
| LLaMA 3.1 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/llama3.1) | [link](python/llm/example/GPU/HuggingFace/LLM/llama3.1) |
250251
| ChatGLM | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm) | |
251252
| ChatGLM2 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm2) | [link](python/llm/example/GPU/HuggingFace/LLM/chatglm2) |
252253
| ChatGLM3 | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/chatglm3) | [link](python/llm/example/GPU/HuggingFace/LLM/chatglm3) |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Llama3.1
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on Llama3.1 models. For illustration purposes, we utilize the [meta-llama/Meta-Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct) as a reference Llama3.1 model.
3+
4+
## 0. Requirements
5+
To run these examples with IPEX-LLM, we have some recommended requirements for your machine, please refer to [here](../README.md#recommended-requirements) for more information.
6+
7+
## Example: Predict Tokens using `generate()` API
8+
In the example [generate.py](./generate.py), we show a basic use case for a Llama3.1 model to predict the next N tokens using `generate()` API, with IPEX-LLM INT4 optimizations.
9+
### 1. Install
10+
We suggest using conda to manage environment:
11+
12+
On Linux:
13+
14+
```bash
15+
conda create -n llm python=3.11
16+
conda activate llm
17+
18+
# install ipex-llm with 'all' option
19+
pip install --pre --upgrade ipex-llm[all] --extra-index-url https://download.pytorch.org/whl/cpu
20+
21+
# transformers>=4.43.1 is required for Llama3.1 with IPEX-LLM optimizations
22+
pip install transformers==4.43.1
23+
pip install trl
24+
```
25+
On Windows:
26+
27+
```cmd
28+
conda create -n llm python=3.11
29+
conda activate llm
30+
31+
pip install --pre --upgrade ipex-llm[all]
32+
33+
pip install transformers==4.43.1
34+
pip install trl
35+
```
36+
37+
### 2. Run
38+
```
39+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --prompt PROMPT --n-predict N_PREDICT
40+
```
41+
42+
Arguments info:
43+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Llama3.1 model (e.g. `meta-llama/Meta-Llama-3.1-8B-Instruct`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'meta-llama/Meta-Llama-3.1-8B-Instruct'`.
44+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'What is AI?'`.
45+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
46+
47+
> **Note**: When loading the model in 4-bit, IPEX-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.
48+
>
49+
> Please select the appropriate size of the Llama3.1 model based on the capabilities of your machine.
50+
51+
#### 2.1 Client
52+
On client Windows machine, it is recommended to run directly with full utilization of all cores:
53+
```cmd
54+
python ./generate.py
55+
```
56+
57+
#### 2.2 Server
58+
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.
59+
60+
E.g. on Linux,
61+
```bash
62+
# set IPEX-LLM env variables
63+
source ipex-llm-init
64+
65+
# e.g. for a server with 48 cores per socket
66+
export OMP_NUM_THREADS=48
67+
numactl -C 0-47 -m 0 python ./generate.py
68+
```
69+
70+
#### 2.3 Sample Output
71+
#### [meta-llama/Meta-Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct)
72+
```log
73+
Inference time: xxxx s
74+
-------------------- Prompt --------------------
75+
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
76+
77+
What is AI?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
78+
79+
80+
-------------------- Output (skip_special_tokens=False) --------------------
81+
<|begin_of_text|><|begin_of_text|><|start_header_id|>user<|end_header_id|>
82+
83+
What is AI?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
84+
85+
Artificial intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think and learn like humans. The term may also be applied to
86+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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+
21+
from ipex_llm.transformers import AutoModelForCausalLM
22+
from transformers import AutoTokenizer
23+
24+
# you could tune the prompt based on your own model,
25+
# here the prompt tuning refers to https://llama.meta.com/docs/model-cards-and-prompt-formats/llama3_1
26+
DEFAULT_SYSTEM_PROMPT = """\
27+
"""
28+
29+
def get_prompt(user_input: str, chat_history: list[tuple[str, str]],
30+
system_prompt: str) -> str:
31+
prompt_texts = [f'<|begin_of_text|>']
32+
33+
if system_prompt != '':
34+
prompt_texts.append(f'<|start_header_id|>system<|end_header_id|>\n\n{system_prompt}<|eot_id|>')
35+
36+
for history_input, history_response in chat_history:
37+
prompt_texts.append(f'<|start_header_id|>user<|end_header_id|>\n\n{history_input.strip()}<|eot_id|>')
38+
prompt_texts.append(f'<|start_header_id|>assistant<|end_header_id|>\n\n{history_response.strip()}<|eot_id|>')
39+
40+
prompt_texts.append(f'<|start_header_id|>user<|end_header_id|>\n\n{user_input.strip()}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n')
41+
return ''.join(prompt_texts)
42+
43+
if __name__ == '__main__':
44+
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for Llama3.1 model')
45+
parser.add_argument('--repo-id-or-model-path', type=str, default="meta-llama/Meta-Llama-3.1-8B-Instruct",
46+
help='The huggingface repo id for the Llama3 (e.g. `meta-llama/Meta-Llama-3.1-8B-Instruct`) to be downloaded'
47+
', or the path to the huggingface checkpoint folder')
48+
parser.add_argument('--prompt', type=str, default="What is AI?",
49+
help='Prompt to infer')
50+
parser.add_argument('--n-predict', type=int, default=32,
51+
help='Max tokens to predict')
52+
53+
args = parser.parse_args()
54+
model_path = args.repo_id_or_model_path
55+
56+
# Load model in 4 bit,
57+
# which convert the relevant layers in the model into INT4 format
58+
model = AutoModelForCausalLM.from_pretrained(model_path,
59+
load_in_4bit=True,
60+
optimize_model=True,
61+
trust_remote_code=True,
62+
use_cache=True)
63+
64+
# Load tokenizer
65+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
66+
67+
# Generate predicted tokens
68+
with torch.inference_mode():
69+
prompt = get_prompt(args.prompt, [], system_prompt=DEFAULT_SYSTEM_PROMPT)
70+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
71+
st = time.time()
72+
output = model.generate(input_ids,
73+
max_new_tokens=args.n_predict)
74+
end = time.time()
75+
output_str = tokenizer.decode(output[0], skip_special_tokens=False)
76+
print(f'Inference time: {end-st} s')
77+
print('-'*20, 'Prompt', '-'*20)
78+
print(prompt)
79+
print('-'*20, 'Output (skip_special_tokens=False)', '-'*20)
80+
print(output_str)
81+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# Llama3.1
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on Llama3.1 models on [Intel GPUs](../../../README.md). For illustration purposes, we utilize the [meta-llama/Meta-Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct) as a reference Llama3.1 models.
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+
## Example: Predict Tokens using `generate()` API
8+
In the example [generate.py](./generate.py), we show a basic use case for a Llama3.1 model to predict the next N tokens using `generate()` API, with IPEX-LLM INT4 optimizations on Intel GPUs.
9+
### 1. Install
10+
#### 1.1 Installation on Linux
11+
We suggest using conda to manage environment:
12+
```bash
13+
conda create -n llm python=3.11
14+
conda activate llm
15+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
16+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
17+
18+
# transformers>=4.43.1 is required for Llama3.1 with IPEX-LLM optimizations
19+
pip install transformers==4.43.1
20+
pip install trl
21+
```
22+
23+
#### 1.2 Installation on Windows
24+
We suggest using conda to manage environment:
25+
```bash
26+
conda create -n llm python=3.11 libuv
27+
conda activate llm
28+
29+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
30+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
31+
32+
# transformers>=4.43.1 is required for Llama3.1 with IPEX-LLM optimizations
33+
pip install transformers==4.43.1
34+
pip install trl
35+
```
36+
37+
### 2. Configures OneAPI environment variables for Linux
38+
39+
> [!NOTE]
40+
> Skip this step if you are running on Windows.
41+
42+
This is a required step on Linux for APT or offline installed oneAPI. Skip this step for PIP-installed oneAPI.
43+
44+
```bash
45+
source /opt/intel/oneapi/setvars.sh
46+
```
47+
48+
### 3. Runtime Configurations
49+
For optimal performance, it is recommended to set several environment variables. Please check out the suggestions based on your device.
50+
#### 3.1 Configurations for Linux
51+
<details>
52+
53+
<summary>For Intel Arc™ A-Series Graphics and Intel Data Center GPU Flex Series</summary>
54+
55+
```bash
56+
export USE_XETLA=OFF
57+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
58+
export SYCL_CACHE_PERSISTENT=1
59+
```
60+
61+
</details>
62+
63+
<details>
64+
65+
<summary>For Intel Data Center GPU Max Series</summary>
66+
67+
```bash
68+
export LD_PRELOAD=${LD_PRELOAD}:${CONDA_PREFIX}/lib/libtcmalloc.so
69+
export SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS=1
70+
export SYCL_CACHE_PERSISTENT=1
71+
export ENABLE_SDP_FUSION=1
72+
```
73+
> Note: Please note that `libtcmalloc.so` can be installed by `conda install -c conda-forge -y gperftools=2.10`.
74+
</details>
75+
76+
<details>
77+
78+
<summary>For Intel iGPU</summary>
79+
80+
```bash
81+
export SYCL_CACHE_PERSISTENT=1
82+
export BIGDL_LLM_XMX_DISABLED=1
83+
```
84+
85+
</details>
86+
87+
#### 3.2 Configurations for Windows
88+
<details>
89+
90+
<summary>For Intel iGPU</summary>
91+
92+
```cmd
93+
set SYCL_CACHE_PERSISTENT=1
94+
set BIGDL_LLM_XMX_DISABLED=1
95+
```
96+
97+
</details>
98+
99+
<details>
100+
101+
<summary>For Intel Arc™ A-Series Graphics</summary>
102+
103+
```cmd
104+
set SYCL_CACHE_PERSISTENT=1
105+
```
106+
107+
</details>
108+
109+
> [!NOTE]
110+
> 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.
111+
### 4. Running examples
112+
113+
```
114+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --prompt PROMPT --n-predict N_PREDICT
115+
```
116+
117+
Arguments info:
118+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the Llama3.1 model (e.g. `meta-llama/Meta-Llama-3.1-8B-Instruct`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'meta-llama/Meta-Llama-3.1-8B-Instruct'`.
119+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'What is AI?'`.
120+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
121+
122+
#### Sample Output
123+
#### [meta-llama/Meta-Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct)
124+
```log
125+
Inference time: xxxx s
126+
-------------------- Prompt --------------------
127+
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
128+
129+
What is AI?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
130+
131+
132+
-------------------- Output (skip_special_tokens=False) --------------------
133+
<|begin_of_text|><|begin_of_text|><|start_header_id|>user<|end_header_id|>
134+
135+
What is AI?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
136+
137+
AI, or Artificial Intelligence, refers to the development of computer systems that can perform tasks that typically require human intelligence, such as:
138+
139+
1. **Learning**: AI
140+
```

0 commit comments

Comments
 (0)