AirLLM 2.8T LLM inference with single 4GB GPU
Python chinese-llmchinese-nlpfinetunegenerative-aiinstruct-gptinstruction-setllamallmloraopen-modelsopen-sourceopen-source-modelsqlora
Add PyPI release workflow and make root README the single source of truth
Yu Li07f45114c95d
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..d0c2fa6--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,66 @@+name: Publish to PyPI++# Publishes the `airllm` package to PyPI whenever a GitHub Release is published.+# Uses PyPI Trusted Publishing (OIDC) — no API tokens stored in the repo.+#+# To cut a release:+# 1. Bump `version=` in air_llm/setup.py and commit.+# 2. Create a GitHub Release whose tag matches that version (e.g. tag "3.0.1" or "v3.0.1").+# The version guard below fails the run if the tag and setup.py version disagree.++on:+ release:+ types: [published]+ workflow_dispatch:+ inputs:+ dry_run:+ description: "Build only, do not publish to PyPI"+ type: boolean+ default: true++jobs:+ build-and-publish:+ runs-on: ubuntu-latest+ environment: pypi+ permissions:+ id-token: write # required for PyPI Trusted Publishing (OIDC)+ contents: read+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-python@v5+ with:+ python-version: "3.11"++ - name: Ship the current top-level README inside the package+ run: cp README.md air_llm/README.md++ - name: Verify release tag matches setup.py version+ if: github.event_name == 'release'+ run: |+ PKG_VERSION=$(cd air_llm && python -c "import re,pathlib;print(re.search(r'version=\"([^\"]+)\"', pathlib.Path('setup.py').read_text()).group(1))")+ TAG="${GITHUB_REF_NAME#v}"+ echo "setup.py version: $PKG_VERSION"+ echo "release tag: $TAG"+ if [ "$PKG_VERSION" != "$TAG" ]; then+ echo "::error::Release tag '$TAG' does not match setup.py version '$PKG_VERSION'. Bump setup.py or fix the tag."+ exit 1+ fi++ - name: Build sdist and wheel+ run: |+ cd air_llm+ python -m pip install --upgrade build+ python -m build++ - name: Check distribution metadata+ run: |+ cd air_llm+ python -m pip install --upgrade twine+ twine check dist/*++ - name: Publish to PyPI+ if: github.event_name == 'release' || inputs.dry_run == false+ uses: pypa/gh-action-pypi-publish@release/v1+ with:+ packages-dir: air_llm/distdiff --git a/.gitignore b/.gitignoreindex 139b4ce..5a1e664 100644--- a/.gitignore+++ b/.gitignore@@ -4,4 +4,6 @@airllm.egg-infobuilddist-__pycache__\ No newline at end of file+__pycache__+# Package README is generated from the top-level README.md at build time+air_llm/README.mddiff --git a/air_llm/README.md b/air_llm/README.mddeleted file mode 100644index c75db05..0000000--- a/air_llm/README.md+++ /dev/null@@ -1,321 +0,0 @@---[**Quickstart**](#quickstart) |-[**Configurations**](#configurations) |-[**MacOS**](#macos) |-[**Example notebooks**](#example-python-notebook) |-[**FAQ**](#faq)--**AirLLM** optimizes inference memory usage, allowing 70B large language models to run inference on a single 4GB GPU card. No quantization, distillation, pruning or other model compression techniques that would result in degraded model performance are needed.--<a href="https://github.com/lyogavin/Anima/stargazers"></a>-[](https://pepy.tech/project/airllm)--[](https://github.com/LianjiaTech/BELLE/blob/main/LICENSE)-[](https://static.aicompose.cn/static/wecom_barcode.png?t=1671918938)-[](https://discord.gg/2xffU5sn)-[-](https://pypi.org/project/airllm/)-[](https://medium.com/@lyo.gavin)-[](https://patreon.com/gavinli)-[](https://github.com/sponsors/lyogavin)---## Updates--[2024/04/20] AirLLM supports Llama3 natively already. Run Llama3 70B on 4GB single GPU.--[2023/12/25] v2.8.2: Support MacOS running 70B large language models.--[2023/12/20] v2.7: Support AirLLMMixtral.--[2023/12/20] v2.6: Added AutoModel, automatically detect model type, no need to provide model class to initialize model.--[2023/12/18] v2.5: added prefetching to overlap the model loading and compute. 10% speed improvement.--[2023/12/03] added support of **ChatGLM**, **QWen**, **Baichuan**, **Mistral**, **InternLM**!--[2023/12/02] added support for safetensors. Now support all top 10 models in open llm leaderboard.--[2023/12/01] airllm 2.0. Support compressions: **3x run time speed up!**--[2023/11/20] airllm Initial verion!--## Table of Contents--* [Quick start](#quickstart)-* [Model Compression](#model-compression---3x-inference-speed-up)-* [Configurations](#configurations)-* [Run on MacOS](#macos)-* [Example notebooks](#example-python-notebook)-* [Supported Models](#supported-models)-* [Acknowledgement](#acknowledgement)-* [FAQ](#faq)--## Quickstart--### 1. Install package--First, install the airllm pip package.--```bash-pip install airllm-```--### 2. Inference--Then, initialize AirLLMLlama2, pass in the huggingface repo ID of the model being used, or the local path, and inference can be performed similar to a regular transformer model.--(*You can also specify the path to save the splitted layered model through **layer_shards_saving_path** when init AirLLMLlama2.*--```python-from airllm import AutoModel--MAX_LENGTH = 128-# could use hugging face model repo id:-model = AutoModel.from_pretrained("garage-bAInd/Platypus2-70B-instruct")--# or use model's local path...-#model = AutoModel.from_pretrained("/home/ubuntu/.cache/huggingface/hub/models--garage-bAInd--Platypus2-70B-instruct/snapshots/b585e74bcaae02e52665d9ac6d23f4d0dbc81a0f")--input_text = [- 'What is the capital of United States?',- #'I like',- ]--input_tokens = model.tokenizer(input_text,- return_tensors="pt",- return_attention_mask=False,- truncation=True,- max_length=MAX_LENGTH,- padding=False)--generation_output = model.generate(- input_tokens['input_ids'].cuda(),- max_new_tokens=20,- use_cache=True,- return_dict_in_generate=True)--output = model.tokenizer.decode(generation_output.sequences[0])--print(output)--```---Note: During inference, the original model will first be decomposed and saved layer-wise. Please ensure there is sufficient disk space in the huggingface cache directory.---## Model Compression - 3x Inference Speed Up!--We just added model compression based on block-wise quantization-based model compression. Which can further **speed up the inference speed** for up to **3x** , with **almost ignorable accuracy loss!** (see more performance evaluation and why we use block-wise quantization in [this paper](https://arxiv.org/abs/2212.09720))----#### How to enable model compression speed up:--* Step 1. make sure you have [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) installed by `pip install -U bitsandbytes `-* Step 2. make sure airllm verion later than 2.0.0: `pip install -U airllm`-* Step 3. when initialize the model, passing the argument compression ('4bit' or '8bit'):--```python-model = AutoModel.from_pretrained("garage-bAInd/Platypus2-70B-instruct",- compression='4bit' # specify '8bit' for 8-bit block-wise quantization- )-```--#### What are the differences between model compression and quantization?--Quantization normally needs to quantize both weights and activations to really speed things up. Which makes it harder to maintain accuracy and avoid the impact of outliers in all kinds of inputs.--While in our case the bottleneck is mainly at the disk loading, we only need to make the model loading size smaller. So, we get to only quantize the weights' part, which is easier to ensure the accuracy.--## Configurations--When initialize the model, we support the following configurations:--* **compression**: supported options: 4bit, 8bit for 4-bit or 8-bit block-wise quantization, or by default None for no compression-* **profiling_mode**: supported options: True to output time consumptions or by default False-* **layer_shards_saving_path**: optionally another path to save the splitted model-* **hf_token**: huggingface token can be provided here if downloading gated models like: *meta-llama/Llama-2-7b-hf*-* **prefetching**: prefetching to overlap the model loading and compute. By default, turned on. For now, only AirLLMLlama2 supports this.-* **delete_original**: if you don't have too much disk space, you can set delete_original to true to delete the original downloaded hugging face model, only keep the transformed one to save half of the disk space.--## MacOS--Just install airllm and run the code the same as on linux. See more in [Quick Start](#quickstart).--* make sure you installed [mlx](https://github.com/ml-explore/mlx?tab=readme-ov-file#installation) and torch-* you probabaly need to install python native see more [here](https://stackoverflow.com/a/65432861/21230266)-* only [Apple silicon](https://support.apple.com/en-us/HT211814) is supported--Example [python notebook] (https://github.com/lyogavin/Anima/blob/main/air_llm/examples/run_on_macos.ipynb)---## Example Python Notebook--Example colabs here:--<a target="_blank" href="https://colab.research.google.com/github/lyogavin/Anima/blob/main/air_llm/examples/run_all_types_of_models.ipynb">- <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>-</a>--#### example of other models (ChatGLM, QWen, Baichuan, Mistral, etc):--<details>---* ChatGLM:--```python-from airllm import AutoModel-MAX_LENGTH = 128-model = AutoModel.from_pretrained("THUDM/chatglm3-6b-base")-input_text = ['What is the capital of China?',]-input_tokens = model.tokenizer(input_text,- return_tensors="pt",- return_attention_mask=False,- truncation=True,- max_length=MAX_LENGTH,- padding=True)-generation_output = model.generate(- input_tokens['input_ids'].cuda(),- max_new_tokens=5,- use_cache= True,- return_dict_in_generate=True)-model.tokenizer.decode(generation_output.sequences[0])-```--* QWen:--```python-from airllm import AutoModel-MAX_LENGTH = 128-model = AutoModel.from_pretrained("Qwen/Qwen-7B")-input_text = ['What is the capital of China?',]-input_tokens = model.tokenizer(input_text,- return_tensors="pt",- return_attention_mask=False,- truncation=True,- max_length=MAX_LENGTH)-generation_output = model.generate(- input_tokens['input_ids'].cuda(),- max_new_tokens=5,- use_cache=True,- return_dict_in_generate=True)-model.tokenizer.decode(generation_output.sequences[0])-```---* Baichuan, InternLM, Mistral, etc:--```python-from airllm import AutoModel-MAX_LENGTH = 128-model = AutoModel.from_pretrained("baichuan-inc/Baichuan2-7B-Base")-#model = AutoModel.from_pretrained("internlm/internlm-20b")-#model = AutoModel.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1")-input_text = ['What is the capital of China?',]-input_tokens = model.tokenizer(input_text,- return_tensors="pt",- return_attention_mask=False,- truncation=True,- max_length=MAX_LENGTH)-generation_output = model.generate(- input_tokens['input_ids'].cuda(),- max_new_tokens=5,- use_cache=True,- return_dict_in_generate=True)-model.tokenizer.decode(generation_output.sequences[0])-```---</details>---#### To request other model support: [here](https://docs.google.com/forms/d/e/1FAIpQLSe0Io9ANMT964Zi-OQOq1TJmnvP-G3_ZgQDhP7SatN0IEdbOg/viewform?usp=sf_link)----## Acknowledgement--A lot of the code are based on SimJeg's great work in the Kaggle exam competition. Big shoutout to SimJeg:--[GitHub account @SimJeg](https://github.com/SimJeg),-[the code on Kaggle](https://www.kaggle.com/code/simjeg/platypus2-70b-with-wikipedia-rag),-[the associated discussion](https://www.kaggle.com/competitions/kaggle-llm-science-exam/discussion/446414).---## FAQ--### 1. MetadataIncompleteBuffer--safetensors_rust.SafetensorError: Error while deserializing header: MetadataIncompleteBuffer--If you run into this error, most possible cause is you run out of disk space. The process of splitting model is very disk-consuming. See [this](https://huggingface.co/TheBloke/guanaco-65B-GPTQ/discussions/12). You may need to extend your disk space, clear huggingface [.cache](https://huggingface.co/docs/datasets/cache) and rerun.--### 2. ValueError: max() arg is an empty sequence--Most likely you are loading QWen or ChatGLM model with Llama2 class. Try the following:--For QWen model:--```python-from airllm import AutoModel #<----- instead of AirLLMLlama2-AutoModel.from_pretrained(...)-```--For ChatGLM model:--```python-from airllm import AutoModel #<----- instead of AirLLMLlama2-AutoModel.from_pretrained(...)-```--### 3. 401 Client Error....Repo model ... is gated.--Some models are gated models, needs huggingface api token. You can provide hf_token:--```python-model = AutoModel.from_pretrained("meta-llama/Llama-2-7b-hf", #hf_token='HF_API_TOKEN')-```--### 4. ValueError: Asking to pad but the tokenizer does not have a padding token.--Some model's tokenizer doesn't have padding token, so you can set a padding token or simply turn the padding config off:-- ```python-input_tokens = model.tokenizer(input_text,- return_tensors="pt",- return_attention_mask=False,- truncation=True,- max_length=MAX_LENGTH,- padding=False #<----------- turn off padding-)-```--## Citing AirLLM--If you find-AirLLM useful in your research and wish to cite it, please use the following-BibTex entry:--```-@software{airllm2023,- author = {Gavin Li},- title = {AirLLM: scaling large language models on low-end commodity computers},- url = {https://github.com/lyogavin/Anima/tree/main/air_llm},- version = {0.0},- year = {2023},-}-```---## Contribution--Welcomed contributions, ideas and discussions!--If you find it useful, please ⭐ or buy me a coffee! 🙏--[](https://bmc.link/lyogavinQ)diff --git a/air_llm/setup.py b/air_llm/setup.pyindex 1b8cc30..a3e50ba 100644--- a/air_llm/setup.py+++ b/air_llm/setup.py@@ -1,15 +1,25 @@+import osimport setuptools-# Windows uses a different default encoding (use a consistent encoding)-with open("README.md", "r", encoding="utf-8") as fh:- long_description = fh.read()+here = os.path.abspath(os.path.dirname(__file__))++# The single source of truth for the README is the repository's top-level README.md. The release+# workflow copies it next to this setup.py before building, so it ships in both the sdist and the+# wheel; for a plain local checkout we fall back to the copy one directory up.+long_description = ""+for _readme in (os.path.join(here, "README.md"), os.path.join(here, os.pardir, "README.md")):+ if os.path.exists(_readme):+ with open(_readme, "r", encoding="utf-8") as fh:+ long_description = fh.read()+ breaksetuptools.setup(name="airllm",version="3.0.0",author="Gavin Li",author_email="[email protected]",- description="AirLLM allows single 4GB GPU card to run 70B large language models without quantization, distillation or pruning. 8GB vmem to run 405B Llama3.1.",+ description="AirLLM runs 70B large language models on a single 4GB GPU without quantization, "+ "distillation or pruning. 405B Llama 3.1 on 8GB, DeepSeek-V3 671B on ~12GB.",long_description=long_description,long_description_content_type="text/markdown",url="https://github.com/lyogavin/airllm",