airllm README

The project's README from github.com/lyogavin/airllm. As one markdown file: README.md.

airllm_logo

Quickstart | Configurations | MacOS | Example notebooks | FAQ

AirLLM dramatically reduces inference memory usage, letting 70B large language models run on a single 4GB GPU card — without quantization, distillation, or pruning. You can even run Kimi K3 (2.8T) — the largest open-source model released to date — on under 4GB, Qwen3.8-Flash-Next (125B) on 6GB, and DeepSeek-V3 (671B) on ~12GB. We now also support training huge models on small VRAM: Qwen3.8-Flash-Next (125B) under 6GB.

GitHub Repo stars Downloads

Code License Generic badge Discord PyPI - AirLLM Website Website Support me on Patreon GitHub Sponsors

AI Agents Recommendation:

Updates

[2026/09] Training support: stream frozen weights one layer at a time and keep adapters on the GPU. Qwen3.8-Flash-Next (125B) trains under 6GB (RTX 3060 Ti); Qwen3.8-27B trains in ~2GB at seq 512. See Training.

[2026/08] Qwen3.8-Flash-Next support: Qwen's 125B MoE flagship (Qwen4ExpForConditionalGeneration) with a ~51B n-gram embedding runs in 5.95GB of VRAM, measured end to end on one RTX 4090. The n-gram table is file-mapped on the host (a 64GB machine is enough); decoder layers stream. Needs a transformers build with in-tree qwen4_exp (pip install git+https://github.com/huggingface/transformers.git today) and ~360GB of checkpoint disk (delete_original=True reclaims the originals after the split).

[2026/08] Qwen3.8-27B support: Qwen's new dense VL (Gated DeltaNet + Gated Attention, native vision) runs in 3.33GB of VRAM, measured end to end on one RTX 3090. Needs transformers 5.8+.

[2026/07] Kimi K3 (2.8T) support: the largest open-source model runs on a single card in 3.72GB of VRAM, measured end to end on one RTX 6000 Ada. Per-expert streaming loads only the experts a token actually routes to. K3 brings three requirements of its own: pip install compressed-tensors flash-attn (its model code mandates flash attention regardless of what you request), a CUDA 12 build of torch, since no prebuilt flash-attn wheel exists for CUDA 13 yet, and transformers 4.56.x, as its remote code does not load on 5.x.

[2026/06] v3.0: FP8 model support + the latest models. Run DeepSeek-V3 (671B) on ~12GB and Qwen3-235B on ~3GB, plus Qwen3, Llama 3.x/4, DeepSeek V2/V3, Phi-4, Gemma and more — all through a single AutoModel.

[2024/08/20] v2.11.0: Support Qwen2.5

[2024/08/18] v2.10.1 Support CPU inference. Support non sharded models. Thanks @NavodPeiris for the great work!

[2024/07/30] Support Llama3.1 405B (example notebook). Support 8bit/4bit quantization.

[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 version!

Star History

Star History Chart

Table of Contents

Quickstart

1. Install package

First, install the airllm pip package.

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.

from airllm import AutoModel

MAX_LENGTH = 128
# just pass a hugging face repo id — works with almost any popular model:
model = AutoModel.from_pretrained("Qwen/Qwen3-32B")

# go bigger with the exact same one line:
#model = AutoModel.from_pretrained("Qwen/Qwen3.8-27B")          # 27B dense VL, 3.33GB
#model = AutoModel.from_pretrained("Qwen/Qwen3.8-Flash-Next")    # 125B MoE + 51B PLE, 5.95GB
#model = AutoModel.from_pretrained("Qwen/Qwen3-235B-A22B")     # 235B, runs in ~3GB
#model = AutoModel.from_pretrained("deepseek-ai/DeepSeek-V3")  # 671B, runs in ~12GB

# or use a model's local path...
#model = AutoModel.from_pretrained("/home/ubuntu/.cache/huggingface/hub/models--Qwen--Qwen3-32B/snapshots/...")

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)

speed_improvement

How to enable model compression speed up:

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:

MacOS

Just install airllm and run the code the same as on linux. See more in Quick Start.

Example [python notebook] (https://github.com/lyogavin/airllm/blob/main/air_llm/examples/run_on_macos.ipynb)

Example Python Notebook

Example colabs here:

Open In Colab

example of other models (ChatGLM, QWen, Baichuan, Mistral, etc):

  • ChatGLM:
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:
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:
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])

To request other model support: here

Supported Models

AirLLM works out of the box with virtually every popular open LLM — just pass its Hugging Face ID to AutoModel.from_pretrained(...). That covers all the major families:

Llama (2 / 3 / 3.1 / 3.3 / 4) · Qwen (1 / 2 / 2.5 / 3 / 3.5 / 3.8, including MoE, Flash-Next, FP8, and native VL) · DeepSeek (V2 / V3 / R1) · Mistral & Mixtral · Phi · Gemma · ChatGLM · Baichuan · InternLM · Yi · Kimi K3 — and most new models the day they're released.

Tiny GPU, huge models

The trick: AirLLM only ever keeps one layer on the GPU at a time, so the VRAM you need depends on the model's layer size — not its total size. That's how a 671B model fits on a hobbyist card:

Model Size GPU VRAM
Qwen3 / Mistral / Phi (≈8B) 8B ~1–2 GB
Qwen3-30B / Mixtral (MoE) 30–47B ~1–3 GB
Qwen3.8-27B (dense VL) 27B 3.33 GB
Qwen3.8-Flash-Next (MoE + PLE) ~180B 5.95 GB
Qwen3-235B (MoE) 235B ~3 GB
Llama 3.x 70B (full precision) 70B ~4 GB
Llama 3.1 405B 405B ~8 GB
DeepSeek-V3 671B ~12 GB

Same one line of code for all of them — no special setup.

Training

AirLLM can fine-tune huge models on a small GPU. Frozen base weights stream from disk one decoder layer at a time; only the adapters stay resident. Qwen3.8-Flash-Next (125B) trains under 6GB; Qwen3.8-27B trains in ~2GB at seq 512.

This is not Hugging Face Trainer / bitsandbytes QLoRA. Flash-Next needs a transformers build with in-tree qwen4_exp (pip install git+https://github.com/huggingface/transformers.git today).

1. Prepare a dataset

One JSON object per line (.jsonl). The usual field is text — next-token prediction over the whole string:

{"text": "Your first training document. Can be a few sentences or a few paragraphs."}
{"text": "Your second training document."}

Instruction pairs work too. Loss is applied on the completion only:

{"prompt": "What is AirLLM?", "completion": "A library that runs and trains huge models on small VRAM."}
{"instruction": "Translate to English", "input": "bonjour", "output": "hello"}

A .txt file is also fine: one example per blank-line-separated block. A two-line starter file lives at air_llm/examples/sft_example.jsonl.

2. Run training

From the repo root, point --data at your file:

python air_llm/examples/train_qwen38_flash_next_lora.py \
  --data my_data.jsonl \
  --seq-len 512 \
  --epochs 1 \
  --save-adapter qwen38-flash-next-lora.pt

For the 27B dense model:

python air_llm/examples/train_qwen38_lora.py \
  --data my_data.jsonl \
  --seq-len 512 \
  --epochs 1 \
  --save-adapter qwen38-27b-lora.pt

--steps N stops after N examples (useful for a smoke test). Omit --data and the script overfits a built-in snippet.

Python API

from airllm import AirLLMLoRAQwen4Exp

trainer = AirLLMLoRAQwen4Exp(
    "Qwen/Qwen3.8-Flash-Next",
    max_seq_len=512,
    lora_r=16,
    delete_original=True,
)

tok = trainer.tokenizer
if tok.pad_token_id is None:
    tok.pad_token = tok.eos_token

encoded = tok(
    "Your training text here.",
    return_tensors="pt",
    truncation=True,
    max_length=512,
)
loss = trainer.train_step(
    encoded["input_ids"].cuda(),
    attention_mask=encoded.get("attention_mask"),
)
print(loss)
trainer.save_adapter("qwen38-flash-next-lora.pt")

AirLLMLoRA is the same API for Qwen/Qwen3.8-27B.

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, the code on Kaggle, the associated discussion.

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. You may need to extend your disk space, clear huggingface .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:

from airllm import AutoModel #<----- instead of AirLLMLlama2
AutoModel.from_pretrained(...)

For ChatGLM model:

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:

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:

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/airllm/},
  version = {0.0},
  year = {2023},
}

Contribution

Welcomed contributions, ideas and discussions!

If you find it useful, please ⭐ or buy me a coffee! 🙏

airllm (lyogavin/airllm)

Searching Database…

39.2K ·GitHub
这是什么?一个开源 Python 库,可以在很小的显卡上运行超大规模大语言模型:70B 模型不用量化、蒸馏或剪枝,单张 4GB 显存的卡就能跑起来——甚至 2.8 万亿参数的 Kimi K3 也能在 4GB 以内运行。
这是我运行的应用,还是我写代码时调用的库?它是一个用 pip 安装的 Python 库,不是独立应用:你用模型的 Hugging Face 仓库 ID 或本地路径来初始化它,然后像调用普通 transformers 模型一样使用它。里面还附带了示例 notebook 和 Colab。
我怎么把它跑起来?先运行 pip install airllm,然后用模型的 Hugging Face 仓库 ID 或本地路径初始化,再像调用普通 transformers 模型一样使用它——AutoModel 会自动识别模型类型。
除了 pip 包,我还需要什么?基本只要 pip 就够了。开启 4-bit 或 8-bit 压缩需要 bitsandbytes,最新的模型另有自己的依赖要求——比如 Kimi K3 需要 CUDA 12 版本的 torch 配合 flash-attn,再加上 transformers 4.56.x。
有什么代价——会很慢吗?速度方面:每次推理都要从磁盘逐层读取,所以瓶颈在磁盘。分块 4-bit 或 8-bit 权重压缩可以带来最多 3 倍的提速,而精度损失几乎可以忽略。
在我的 Mac 上能跑吗?macOS 和 Linux 运行同一套 Python 代码;Mac 上只支持 Apple 芯片,而且还需要安装 mlx 和 torch。
跑 70B 模型需要多大的显卡?要求很低:AirLLM 每次只在显卡上保留一层,所以显存占用取决于层的大小而不是模型大小——8B 模型需要 1-2GB,Llama 70B 大约 4GB,Llama 3.1 405B 大约 8GB,DeepSeek-V3(671B)大约 12GB。
我能用它跑哪些模型?通过一次 AutoModel 调用,几乎所有热门开源大模型都能跑:Llama 2/3/3.1/3.3/4,Qwen 1 到 3.8(包括 MoE 和视觉版本),DeepSeek V2/V3/R1,Mistral 和 Mixtral,Phi,Gemma,ChatGLM,Baichuan,InternLM,Yi 以及 Kimi K3——大多数新模型发布当天就能用。
它也能微调模型,还是只能做推理?它可以微调:冻结的基础权重从磁盘逐个 decoder 层流式读取,只有适配器( adapters)留在显卡上,所以 125B 模型在 6GB 以内就能训练,27B 模型大约 2GB。它自带训练器,不是 Hugging Face Trainer 或 bitsandbytes QLoRA,用简单的 .jsonl 或 .txt 文件喂数据。
我需要 API 密钥或账号吗?不需要任何服务商的密钥——模型直接从 Hugging Face 拉取。唯一的例外是像 meta-llama/Llama-2-7b-hf 这类受限仓库,需要通过 hftoken 选项传入 Hugging Face 令牌。
大模型需要多少磁盘空间?AirLLM 会先下载原始模型,然后把切分后的层分片保存在它旁边——Kimi K3 的权重文件大约 360GB,deleteoriginal=true 可以在切分完成后删除原始文件释放空间。切分过程中磁盘空间不足,是导致 MetadataIncompleteBuffer safetensors 报错的最常见原因。
What are similar projects?jeeves, litgpt, unsloth, qlora, petals, jeff, Soup, ms-swift
Creator
lyogavin
Size
13 MB
Stars
39.2K
Age
3y
Commits · 90 Days