Skip to content

Commit f4c615b

Browse files
authored
Add cohere example (intel#10954)
* add link first * add_cpu_example * add GPU example
1 parent 7e7d969 commit f4c615b

File tree

10 files changed

+638
-0
lines changed

10 files changed

+638
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ Over 50 models have been optimized/verified on `ipex-llm`, including *LLaMA/LLaM
184184
| Deepseek | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/deepseek) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/deepseek) |
185185
| StableLM | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/stablelm) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/stablelm) |
186186
| CodeGemma | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/codegemma) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/codegemma) |
187+
| Command-R/cohere | [link](python/llm/example/CPU/HF-Transformers-AutoModels/Model/cohere) | [link](python/llm/example/GPU/HF-Transformers-AutoModels/Model/cohere) |
187188

188189
## Get Support
189190
- Please report a bug or raise a feature request by opening a [Github Issue](https://github.com/intel-analytics/ipex-llm/issues)

docs/readthedocs/source/index.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,13 @@ Verified Models
587587
<td>
588588
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/GPU/HF-Transformers-AutoModels/Model/codegemma">link</a></td>
589589
</tr>
590+
<tr>
591+
<td>Command-R/cohere</td>
592+
<td>
593+
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/CPU/HF-Transformers-AutoModels/Model/cohere">link</a></td>
594+
<td>
595+
<a href="https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/GPU/HF-Transformers-AutoModels/Model/cohere">link</a></td>
596+
</tr>
590597
</tbody>
591598
</table>
592599

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# CoHere/command-r
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on cohere models. For illustration purposes, we utilize the [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01) as reference 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 cohere 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+
```bash
12+
conda create -n llm python=3.11
13+
conda activate llm
14+
15+
pip install --pre --upgrade ipex-llm[all] # install ipex-llm with 'all' option
16+
pip install tansformers==4.40.0
17+
```
18+
19+
### 2. Run
20+
```
21+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --prompt PROMPT --n-predict N_PREDICT
22+
```
23+
24+
Arguments info:
25+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the cohere model to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'CohereForAI/c4ai-command-r-v01'`.
26+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'What is AI?'`.
27+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
28+
29+
> **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.
30+
>
31+
> Please select the appropriate size of the cohere model based on the capabilities of your machine.
32+
33+
#### 2.1 Client
34+
On client Windows machine, it is recommended to run directly with full utilization of all cores:
35+
```powershell
36+
python ./generate.py
37+
```
38+
39+
#### 2.2 Server
40+
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.
41+
42+
E.g. on Linux,
43+
```bash
44+
# set IPEX-LLM env variables
45+
source ipex-llm-init -t
46+
47+
# e.g. for a server with 48 cores per socket
48+
export OMP_NUM_THREADS=48
49+
numactl -C 0-47 -m 0 python ./generate.py
50+
```
51+
52+
#### 2.3 Sample Output
53+
#### [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01)
54+
```log
55+
Inference time: xxxxx s
56+
-------------------- Prompt --------------------
57+
58+
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|USER_TOKEN|>What is AI?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
59+
60+
-------------------- Output --------------------
61+
62+
<|START_OF_TURN_TOKEN|><|USER_TOKEN|>What is AI?<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
63+
Artificial Intelligence, or AI, is a fascinating field of study that aims to create intelligent machines that can mimic human cognitive functions and perform complex tasks. AI strives to
64+
```
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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+
# Refer to https://huggingface.co/CohereForAI/c4ai-command-r-v01
26+
COHERE_PROMPT_FORMAT = """
27+
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|USER_TOKEN|>{prompt}<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
28+
"""
29+
30+
if __name__ == '__main__':
31+
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for cohere model')
32+
parser.add_argument('--repo-id-or-model-path', type=str, default="CohereForAI/c4ai-command-r-v01",
33+
help='The huggingface repo id for the cohere to be downloaded'
34+
', or the path to the huggingface checkpoint folder')
35+
parser.add_argument('--prompt', type=str, default="What is AI?",
36+
help='Prompt to infer')
37+
parser.add_argument('--n-predict', type=int, default=32,
38+
help='Max tokens to predict')
39+
40+
args = parser.parse_args()
41+
model_path = args.repo_id_or_model_path
42+
43+
# Load model in 4 bit,
44+
# which convert the relevant layers in the model into INT4 format
45+
model = AutoModelForCausalLM.from_pretrained(model_path,
46+
load_in_4bit=True,
47+
trust_remote_code=True)
48+
49+
# Load tokenizer
50+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
51+
52+
# Generate predicted tokens
53+
with torch.inference_mode():
54+
prompt = COHERE_PROMPT_FORMAT.format(prompt=args.prompt)
55+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
56+
st = time.time()
57+
# if your selected model is capable of utilizing previous key/value attentions
58+
# to enhance decoding speed, but has `"use_cache": false` in its model config,
59+
# it is important to set `use_cache=True` explicitly in the `generate` function
60+
# to obtain optimal performance with IPEX-LLM INT4 optimizations
61+
output = model.generate(input_ids,
62+
max_new_tokens=args.n_predict)
63+
end = time.time()
64+
output_str = tokenizer.decode(output[0], skip_special_tokens=True)
65+
print(f'Inference time: {end-st} s')
66+
print('-'*20, 'Prompt', '-'*20)
67+
print(prompt)
68+
print('-'*20, 'Output', '-'*20)
69+
print(output_str)
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# CoHere/command-r
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on cohere models. For illustration purposes, we utilize the [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01) as reference 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 cohere 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+
```bash
12+
conda create -n llm python=3.11
13+
conda activate llm
14+
15+
pip install --pre --upgrade ipex-llm[all] # install ipex-llm with 'all' option
16+
pip install tansformers==4.40.0
17+
```
18+
19+
### 2. Run
20+
```
21+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --prompt PROMPT --n-predict N_PREDICT
22+
```
23+
24+
Arguments info:
25+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the cohere model to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'CohereForAI/c4ai-command-r-v01'`.
26+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'What is AI?'`.
27+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
28+
29+
> **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.
30+
>
31+
> Please select the appropriate size of the cohere model based on the capabilities of your machine.
32+
33+
#### 2.1 Client
34+
On client Windows machine, it is recommended to run directly with full utilization of all cores:
35+
```powershell
36+
python ./generate.py
37+
```
38+
39+
#### 2.2 Server
40+
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.
41+
42+
E.g. on Linux,
43+
```bash
44+
# set IPEX-LLM env variables
45+
source ipex-llm-init -t
46+
47+
# e.g. for a server with 48 cores per socket
48+
export OMP_NUM_THREADS=48
49+
numactl -C 0-47 -m 0 python ./generate.py
50+
```
51+
52+
#### 2.3 Sample Output
53+
#### [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01)
54+
```log
55+
Inference time: xxxxx s
56+
-------------------- Prompt --------------------
57+
58+
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|USER_TOKEN|>What is AI?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
59+
60+
-------------------- Output --------------------
61+
62+
<|START_OF_TURN_TOKEN|><|USER_TOKEN|>What is AI?<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
63+
Artificial Intelligence, or AI, is a fascinating field of study that aims to create intelligent machines that can mimic human cognitive functions and perform complex tasks. AI strives to
64+
```
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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+
# Refer to https://huggingface.co/CohereForAI/c4ai-command-r-v01
26+
COHERE_PROMPT_FORMAT = """
27+
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|USER_TOKEN|>{prompt}<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
28+
"""
29+
30+
if __name__ == '__main__':
31+
parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for cohere model')
32+
parser.add_argument('--repo-id-or-model-path', type=str, default="CohereForAI/c4ai-command-r-v01",
33+
help='The huggingface repo id for the cohere to be downloaded'
34+
', or the path to the huggingface checkpoint folder')
35+
parser.add_argument('--prompt', type=str, default="What is AI?",
36+
help='Prompt to infer')
37+
parser.add_argument('--n-predict', type=int, default=32,
38+
help='Max tokens to predict')
39+
40+
args = parser.parse_args()
41+
model_path = args.repo_id_or_model_path
42+
43+
# Load model in 4 bit,
44+
# which convert the relevant layers in the model into INT4 format
45+
model = AutoModelForCausalLM.from_pretrained(model_path,
46+
load_in_4bit=True,
47+
trust_remote_code=True)
48+
49+
# Load tokenizer
50+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
51+
52+
# Generate predicted tokens
53+
with torch.inference_mode():
54+
prompt = COHERE_PROMPT_FORMAT.format(prompt=args.prompt)
55+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
56+
st = time.time()
57+
# if your selected model is capable of utilizing previous key/value attentions
58+
# to enhance decoding speed, but has `"use_cache": false` in its model config,
59+
# it is important to set `use_cache=True` explicitly in the `generate` function
60+
# to obtain optimal performance with IPEX-LLM INT4 optimizations
61+
output = model.generate(input_ids,
62+
max_new_tokens=args.n_predict)
63+
end = time.time()
64+
output_str = tokenizer.decode(output[0], skip_special_tokens=True)
65+
print(f'Inference time: {end-st} s')
66+
print('-'*20, 'Prompt', '-'*20)
67+
print(prompt)
68+
print('-'*20, 'Output', '-'*20)
69+
print(output_str)
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# CoHere/command-r
2+
In this directory, you will find examples on how you could apply IPEX-LLM INT4 optimizations on cohere models on [Intel GPUs](../../../README.md). For illustration purposes, we utilize the [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01) as a reference model.
3+
> **Note**: Because the size of this cohere model is 35B, even running low_bit `sym_int4` still requires about 17.5GB. So currently it can only be run on MAX GPU, or run with [Pipeline-Parallel-Inference](https://github.com/intel-analytics/ipex-llm/tree/main/python/llm/example/GPU/Pipeline-Parallel-Inference) on multiple Arc GPUs.
4+
>
5+
> Please select the appropriate size of the cohere model based on the capabilities of your machine.
6+
7+
## 0. Requirements
8+
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.
9+
10+
## Example: Predict Tokens using `generate()` API
11+
In the example [generate.py](./generate.py), we show a basic use case for a cohere model to predict the next N tokens using `generate()` API, with IPEX-LLM INT4 optimizations on Intel GPUs.
12+
### 1. Install
13+
#### 1.1 Installation on Linux
14+
We suggest using conda to manage environment:
15+
```bash
16+
conda create -n llm python=3.11
17+
conda activate llm
18+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
19+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
20+
pip install tansformers==4.40.0
21+
conda install -c conda-forge -y gperftools=2.10 # to enable tcmalloc
22+
```
23+
24+
#### 1.2 Installation on Windows
25+
We suggest using conda to manage environment:
26+
```bash
27+
conda create -n llm python=3.11 libuv
28+
conda activate llm
29+
# below command will use pip to install the Intel oneAPI Base Toolkit 2024.0
30+
pip install dpcpp-cpp-rt==2024.0.2 mkl-dpcpp==2024.0.0 onednn==2024.0.0
31+
32+
# below command will install intel_extension_for_pytorch==2.1.10+xpu as default
33+
pip install --pre --upgrade ipex-llm[xpu] --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/
34+
pip install tansformers==4.40.0
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+
### 4. Running examples
77+
78+
```
79+
python ./generate.py --repo-id-or-model-path REPO_ID_OR_MODEL_PATH --prompt PROMPT --n-predict N_PREDICT
80+
```
81+
82+
Arguments info:
83+
- `--repo-id-or-model-path REPO_ID_OR_MODEL_PATH`: argument defining the huggingface repo id for the cohere model to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'CohereForAI/c4ai-command-r-v01'`.
84+
- `--prompt PROMPT`: argument defining the prompt to be infered (with integrated prompt format for chat). It is default to be `'What is AI?'`.
85+
- `--n-predict N_PREDICT`: argument defining the max number of tokens to predict. It is default to be `32`.
86+
87+
#### Sample Output
88+
#### [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01)
89+
```log
90+
Inference time: xxxxx s
91+
-------------------- Prompt --------------------
92+
93+
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|USER_TOKEN|>What is AI?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
94+
95+
-------------------- Output --------------------
96+
97+
<|START_OF_TURN_TOKEN|><|USER_TOKEN|>What is AI?<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
98+
Artificial Intelligence Quora User,
99+
100+
Artificial Intelligence (AI) is the simulation of human intelligence in machines, typically by machines, that have become a very complex
101+
```

0 commit comments

Comments
 (0)