airllm

lyogavinApache-2.0活跃维护

单张 4GB 显存显卡就能跑 70B 甚至 2.8T 参数大模型的分层推理方案,通过逐层加载权重把显存需求压到极低,适合本地低配设备部署大模型。

AirLLM 2.8T LLM inference with single 4GB GPU

v4.0.0发布于 2026-09-05 15:43 UTC42,102star +218 / 7 天4,338fork同步于 2026-11-10 17:19 UTC

怎么上手

由 README 提炼,执行前请确认
pip install airllm
硬件要求按 README 说明

README 称 70B 模型可在单张 4GB 显卡上运行,DeepSeek-V3 671B 约需 12GB 显存,Kimi K3 实测 3.72GB;支持 CPU 推理与 Apple silicon(macOS 仅限 Llama/Mistral 架构)。

支持 Apple Silicon需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

让单张 4GB 显卡跑起 70B 甚至 2.8T 大模型的分层流式推理库

单张 4GB 显存显卡就能跑 70B 甚至 2.8T 参数大模型的分层推理方案,通过逐层加载权重把显存需求压到极低,适合本地低配设备部署大模型。

核心能力

  • 按层切分模型权重,推理时逐层从磁盘流式加载
  • 支持 4bit/8bit 分块量化压缩,最高提速 3 倍
  • 用 AutoModel 自动识别模型类型,一行加载主流模型
  • prefetching 预取重叠加载与计算,减少等待
  • 支持在 6GB 显存下微调 125B 大模型

容易踩的坑

首次推理会把原模型按层拆分并写入 HuggingFace 缓存目录,需预留充足磁盘空间;启用压缩需另装 bitsandbytes,部分新模型还要求特定 transformers 版本或额外安装 flash-attn;macOS 仅支持 Apple silicon 且只支持 Llama 风格模型。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v4.0.0
  1. v4.0.0AirLLM v4.0.0 — train Qwen3.8-Flash-Next under 6GB最新正式版2026-09-05 · 2026-09-05 15:43 UTC

    Streamed LoRA: frozen weights stay on disk, adapters stay on GPU. Qwen3.8-Flash-Next trains under 6GB (RTX 3060 Ti); Qwen3.8-27B trains in ~2GB at seq 512.

    pip install -U airllm
    pip install git+https://github.com/huggingface/transformers.git
    

    Point --data at a JSONL file ({"text": "..."} or {"prompt": "...", "completion": "..."}):

    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
    

    Flash-Next still needs in-tree qwen4_exp (GitHub transformers main today).

  2. v3.3.0AirLLM v3.3.0 — Qwen3.8-Flash-Next on 5.95GB2026-08-28 · 2026-08-28 02:11 UTC
    查看更新说明

    Qwen3.8-Flash-Next (Qwen/Qwen3.8-Flash-Next) streams on a single card in 5.95GB VRAM (RTX 4090). The ~51B n-gram table is file-mapped on the host; decoder layers stream.

    pip install -U airllm
    pip install git+https://github.com/huggingface/transformers.git
    

    Flash-Next needs in-tree qwen4_exp (GitHub transformers main today). A 64GB RAM machine is enough; plan ~360GB disk, or pass delete_original=True to reclaim the originals after the split.

  3. v3.2.0AirLLM v3.2.0 — Qwen3.8-27B on 3.33GB2026-08-18 · 2026-08-18 23:15 UTC

    这个版本没有写更新说明。

  4. v3.1.0AirLLM v3.1.0 — Kimi K3 (2.8T) on a single card2026-07-29 · 2026-07-29 01:08 UTC
    查看更新说明

    Kimi K3 (2.8T) runs on a single card in 3.72GB

    Kimi K3 is the largest open-source model released to date. AirLLM runs it on one consumer-class GPU.

    Measured end to end on a single RTX 6000 Ada (48GB) against the full 1.56TB checkpoint, generating real tokens:

    Peak VRAM during generation3.72 GB
    Peak VRAM after init0.83 GB
    Init (one-time per process)900 s
    Generation292 s/token, disk-bound

    The reason a 2.8T model needs less VRAM than a 671B one is that sparse MoE checkpoints stream one expert at a time rather than a whole layer. K3 holds 896 experts per layer and routes each token to 16 of them — expanded, a layer's experts are ~55GB, but a token only needs ~1GB. AirLLM loads just those. MXFP4 weights also cross PCIe packed and expand on the GPU, moving 4x less data.

    Fitting the checkpoint on disk needed the same kind of trick: a naive split would want 3.12TB for a 1.56TB model. K3's shards turn out to be pure, one module each, so split layers are hardlinked to the originals instead of copied.

    Before you run K3

    K3 brings three requirements of its own, none of them optional:

    pip install airllm compressed-tensors flash-attn
    
    • flash-attn is mandatory. K3's model code overwrites whatever attention implementation you request.
    • A CUDA 12 build of torch, because no prebuilt flash-attn wheel exists for CUDA 13 yet.
    • transformers 4.56.x, as K3's remote code does not load on 5.x.

    Also in this release

    Four fixes that came out of the K3 work but are not K3-specific, and should help other models:

    • Adopt the checkpoint's shape when a model class builds a different one for a parameter it never materialises.
    • Expand packed weights for modules whose forward reads a plain weight rather than the packed payload.
    • Read scheme.format across compressed-tensors versions, where it is an enum in some and a plain string in others.
    • Propagate the attention implementation into nested sub-configs, which multimodal wrappers keep their decoder under.

    Full details in #316.

  5. v3.0.1AirLLM v3.0.12026-06-30 · 2026-06-30 23:02 UTC
    查看更新说明

    AirLLM v3.0.1

    Patch release.

    • Fix: import airllm failed on a clean install with ModuleNotFoundError: No module named 'sentencepiece'. sentencepiece is now a declared dependency, so pip install airllm works out of the box.
    • Model-family imports are now defensive: a missing optional dependency for one niche model family no longer breaks the whole package — the generic streaming path always loads.

    Upgrade

    pip install --upgrade airllm
    

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    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

    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 split 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'].to(model.device), 
        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:
    • Step 1. make sure you have bitsandbytes installed by pip install -U bitsandbytes
    • Step 2. make sure airllm version later than 2.0.0: pip install -U airllm
    • Step 3. when initialize the model, passing the argument compression ('4bit' or '8bit'):
    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 split 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.

    • make sure you installed mlx and torch
    • you probably need to install python native see more here
    • only Apple silicon is supported
    • only Llama-style models (LlamaForCausalLM, MistralForCausalLM) run on macOS for now; other architectures raise an error before anything is downloaded

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

    Example Python Notebook

    Example colabs here:

    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'].to(model.device), 
        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'].to(model.device), 
        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'].to(model.device), 
        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:

    ModelSizeGPU VRAM
    Qwen3 / Mistral / Phi (≈8B)8B~1–2 GB
    Qwen3-30B / Mixtral (MoE)30–47B~1–3 GB
    Qwen3.8-27B (dense VL)27B3.33 GB
    Qwen3.8-Flash-Next (MoE + PLE)~180B5.95 GB
    Qwen3-235B (MoE)235B~3 GB
    Llama 3.x 70B (full precision)70B~4 GB
    Llama 3.1 405B405B~8 GB
    DeepSeek-V3671B~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"].to(model.device),
        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! 🙏

    "Buy Me A Coffee"