From c1d25a51a82f39af01422ac08ba9140f306b5d48 Mon Sep 17 00:00:00 2001 From: binbin Deng <108676127+plusbang@users.noreply.github.com> Date: Mon, 18 Sep 2023 16:18:35 +0800 Subject: [PATCH] LLM: add `optimize_model` example for bert (#8975) --- python/llm/example/pytorch-models/README.md | 1 + .../llm/example/pytorch-models/bert/README.md | 48 ++++++++++++++++ .../pytorch-models/bert/extract_feature.py | 55 +++++++++++++++++++ 3 files changed, 104 insertions(+) create mode 100644 python/llm/example/pytorch-models/bert/README.md create mode 100644 python/llm/example/pytorch-models/bert/extract_feature.py diff --git a/python/llm/example/pytorch-models/README.md b/python/llm/example/pytorch-models/README.md index ad60d414..ddbb5c21 100644 --- a/python/llm/example/pytorch-models/README.md +++ b/python/llm/example/pytorch-models/README.md @@ -7,6 +7,7 @@ You can use `optimize_model` API to accelerate general PyTorch models on Intel s | LLaMA 2 | [link](llama2) | | ChatGLM | [link](chatglm) | | Openai Whisper | [link](openai-whisper) | +| BERT | [link](bert) | ## Recommended Requirements To run the examples, we recommend using Intel® Xeon® processors (server), or >= 12th Gen Intel® Core™ processor (client). diff --git a/python/llm/example/pytorch-models/bert/README.md b/python/llm/example/pytorch-models/bert/README.md new file mode 100644 index 00000000..522d1cb8 --- /dev/null +++ b/python/llm/example/pytorch-models/bert/README.md @@ -0,0 +1,48 @@ +# BERT +In this directory, you will find examples on how you could use BigDL-LLM `optimize_model` API to accelerate BERT models. For illustration purposes, we utilize the [bert-large-uncased](https://huggingface.co/bert-large-uncased) as reference BERT 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: Extract the feature of given text +In the example [extract_feature.py](./extract_feature.py), we show a basic use case for a BERT model to extract the feature of given text, with BigDL-LLM INT4 optimizations. +### 1. Install +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 + +pip install --pre --upgrade bigdl-llm[all] # install the latest bigdl-llm nightly build with 'all' option +``` + +### 2. Run +After setting up the Python environment, you could run the example by following steps. + +#### 2.1 Client +On client Windows machines, it is recommended to run directly with full utilization of all cores: +```powershell +python ./extract_feature.py --text 'This is an example text for feature extraction.' +``` +More information about arguments can be found in [Arguments Info](#23-arguments-info) section. + +#### 2.2 Server +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. + +E.g. on Linux, +```bash +# set BigDL-Nano env variables +source bigdl-nano-init + +# e.g. for a server with 48 cores per socket +export OMP_NUM_THREADS=48 +numactl -C 0-47 -m 0 python ./extract_feature.py --text 'This is an example text for feature extraction.' +``` +More information about arguments can be found in [Arguments Info](#23-arguments-info) section. + +#### 2.3 Arguments Info +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 BERT model (e.g. `bert-large-uncased`) to be downloaded, or the path to the huggingface checkpoint folder. It is default to be `'bert-large-uncased'`. +- `--text TEXT`: argument defining the text to be extracted features. It is default to be `'This is an example text for feature extraction.'`. diff --git a/python/llm/example/pytorch-models/bert/extract_feature.py b/python/llm/example/pytorch-models/bert/extract_feature.py new file mode 100644 index 00000000..aab47ff7 --- /dev/null +++ b/python/llm/example/pytorch-models/bert/extract_feature.py @@ -0,0 +1,55 @@ +# +# 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 time +import argparse + +from transformers import BertTokenizer, BertModel +from bigdl.llm import optimize_model + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Extract the feature of given text using BERT model') + parser.add_argument('--repo-id-or-model-path', type=str, default="bert-large-uncased", + help='The huggingface repo id for the BERT (e.g. `bert-large-uncased`) to be downloaded' + ', or the path to the huggingface checkpoint folder') + parser.add_argument('--text', type=str, default="This is an example text for feature extraction.", + help='Text to extract features') + + args = parser.parse_args() + model_path = args.repo_id_or_model_path + + # Load model + model = BertModel.from_pretrained(model_path, + torch_dtype="auto", + low_cpu_mem_usage=True) + + # With only one line to enable BigDL-LLM optimization on model + model = optimize_model(model) + + # Load tokenizer + tokenizer = BertTokenizer.from_pretrained(model_path) + + # Extract the feature of given text + text = args.text + encoded_input = tokenizer(text, return_tensors='pt') + st = time.time() + output = model(**encoded_input) + end = time.time() + print(f'Time cost: {end-st} s') + print('-'*20, 'Output', '-'*20) + print(output)