Transformers 原生支持 llama.cpp GGUF 量化模型
Hugging Face Transformers 库正式集成对 llama.cpp GGUF 格式量化模型的直接加载与推理支持。用户可通过标准的 `from_pretrained` API 在本地设备上高效运行经过量化的模型,无需依赖外部引擎如 Ollama 或 LM Studio。这一更新显著降低了本地部署大模型的门槛,实现了生态工具链的互通。
报道正文
本文目录12 个章节
Transformers 现已支持运行 llama.cpp 量化模型
发布于 2026 年 9 月 22 日 在 GitHub 上更新 点赞 101
Marc Sun marcsun13 Arthur Zucker ArthurZ Lysandre lysandre
我们在 transformers 中新增了对高效运行 GGUF 模型的支持,让你可以通过熟悉的 transformers API,使用适配笔记本内存大小的检查点。从 Hub 选择一个 GGUF 模型,使用 from_pretrained 加载它,即可在你的本地机器上开始生成内容。
在笔记本电脑上运行 AI 模型变得更加容易,而 llama.cpp 在其中发挥了重要作用。其推理引擎为 Ollama、LM Studio 和 Jan 等本地 AI 工具提供了动力。与 MLX 等项目一起,它使本地推理成为日常使用中切实可行的选择。
近期一个展示本地 AI 体验的例子:
这就是我们目前的水平。我不妨直说,这感觉相当神奇 🧙♀️ Qwen3.6 27B 通过 Llama.cpp 在 MacBook Pro 上的 Pi coding agent 中运行 对于 @huggingface 代码库中的非平凡任务,这种体验非常接近最新的 Claude Opus…… pic.twitter.com/lsIxLoUneU — Julien Chaumond (@julien_c) 2026 年 4 月 24 日
由 llama.cpp 团队开发的 GGUF 是本地推理中广泛使用的格式。该团队还在 Hub 上的 ggml-org 下分享了量化检查点。此外,Unsloth、LM Studio Community 和 bartowski 等发布者也在各种量化级别下提供现成的 GGUF 检查点,以便用户选择适合其设备的版本。GGUF 模型的下载量已达数百万次。
我们也希望让在本地通过 transformers 运行这些模型变得更加容易。只有当模型运行体验良好时,兼容性才有意义。为了将性能提升至接近 llama.cpp 的水平,我们通过 kernels 库复用了其底层的 ggml 内核,并减少了 generate 过程中的开销。我们初期的重点是 Apple Silicon 上的本地推理,首先从 Qwen3.5 架构开始。
GGUF 文件格式是什么?
GGUF 将模型权重和元数据(包括分词器信息和可选的聊天模板)打包在一个文件中。它支持不同的量化级别,允许你以牺牲部分精度为代价来减小内存占用。诸如 Q4_K_M 这样的变体混合了张量精度,主要使用 4-bit 权重,同时保持敏感张量的较高精度。
以下是量化如何改变 Unsloth's Qwen3.5-4B 文件大小的示例:
我们建议从 Q4_K_M 开始,如果可用内存更多,可以尝试 Q5_K_M 或 Q6_K。更激进的量化有助于让更大的模型适配内存,但质量损失取决于具体模型和任务。请根据你实际希望模型执行的工作进行评估。Hub 的 GGUF 文档描述了可用的量化类型。
使用 transformers 加载 GGUF
要开始使用,你需要:
- 一台 Apple Silicon Mac。
- 一个受已发布的 ggml-quantization kernel builds 支持的 PyTorch 版本,通常是最新的两个 PyTorch 发布版。
- 最新版本的 transformers(目前为主分支 main,直到下一次发布)以及兼容版本的
kernels。
pip install -U "git+https://github.com/huggingface/transformers.git" kernels要加载 GGUF 模型,请将 Hub 上的 model_id 和文件名作为 gguf_file 参数传递给 from_pretrained。
无需额外配置:当权重在 Metal 上保持打包状态时,transformers 会自动加载兼容的 ggml/Metal 层内核,并使用 ggml-org/ggml-attn 作为注意力实现。如果无法获取该内核,模型将回退到 "sdpa" 并发出警告;你也可以通过显式传入 attn_implementation="sdpa" 来强制使用 "sdpa"。有关更多加载选项,请参阅 GGUF 文档。
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "unsloth/Qwen3.5-4B-GGUF"
filename = "Qwen3.5-4B-Q4_K_M.gguf"
tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)
model = AutoModelForCausalLM.from_pretrained(
model_id,
gguf_file=filename
)这是唯一与 GGUF 相关的步骤。之后的所有内容均使用标准的 transformers API:
messages = [{"role": "user", "content": "Explain why the sky is blue in a few sentences."}]
inputs = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
with torch.inference_mode():
outputs = model.generate(**inputs, max_new_tokens=256)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))使用你偏好的接口部署 GGUF
你还可以使用 transformers serve 配合相同的检查点,它提供了兼容 OpenAI 的 API:
pip install -U "transformers[serving] @ git+https://github.com/huggingface/transformers.git" kernels
transformers serve "unsloth/Qwen3.5-4B-GGUF:Qwen3.5-4B-Q4_K_M.gguf"模型参数采用 <model_id>:<filename>.gguf 格式:冒号之前是 Hub 仓库(unsloth/Qwen3.5-4B-GGUF),之后是要加载的文件(Qwen3.5-4B-Q4_K_M.gguf)。这可以从包含多个量化版本的仓库中选择特定的量化版本。
对于聊天模板支持思考(thinking)功能的模型,可以添加 --reasoning off 以跳过该功能,或添加 --reasoning on 以启用该功能。默认值 --reasoning auto 会遵循聊天模板的默认设置。有关详细信息,请参阅推理选项。
You can connect a client such as Jan or Pi by adding a custom OpenAI-compatible provider with these settings:
| Setting | Value |
|---|---|
| Base URL | http://localhost:8000/v1 |
| Model ID | unsloth/Qwen3.5-4B-GGUF:Qwen3.5-4B-Q4_K_M.gguf |
transformers runs the model on your Mac, while the client provides the conversation interface. The same endpoint can be used by other clients that support this API.
Benchmarking against llama.cpp
Our reference for local inference performance is llama.cpp. The comparison below focuses on three GGUF checkpoints: a small dense model, a larger dense model, and a mixture-of-experts model.
The llama.cpp column comes from the llama-bench tool (build 5f55650a7, release b10200, Metal backend from ggml 0.18.0), run as llama-bench -m <file> -p 0 -n 128 -r 3, which reports tg128: the token-generation rate over 128 decoded tokens, averaged across three repetitions, with prompt processing excluded. The transformers column is generate producing the same 128 tokens from a 12-token prompt, best of three warmed runs, and it includes prefill.
Measured on a MacBook Pro M2 Max, 32 GB unified memory, macOS 26.6, PyTorch 2.12.1, kernels 0.17.0, plugged in.
The benchmark script
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id, filename = "unsloth/Qwen3.5-4B-GGUF", "Qwen3.5-4B-Q4_K_M.gguf"
model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)
tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)
inputs = tokenizer("The capital of France is Paris. The capital of Germany is", return_tensors="pt")
inputs = inputs.to(model.device)
with torch.inference_mode():
model.generate(**inputs, max_new_tokens=8, min_new_tokens=8, do_sample=False)
torch.mps.synchronize()
for _ in range(3):
time.sleep(90)
start = time.perf_counter()
model.generate(**inputs, max_new_tokens=128, min_new_tokens=128, do_sample=False)
torch.mps.synchronize()
print(f"{128 / (time.perf_counter() - start):.1f} tok/s")For the other column:
llama-bench -hf unsloth/Qwen3.5-4B-GGUF:Q4_K_M -p 0 -n 128 -r 3[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]
Transformers is close to llama.cpp across all three checkpoints. The chart uses the same measurements described above; it does not imply identical benchmark conditions, since the Transformers measurement includes prefill while llama-bench reports decode-only throughput.
transformers and llama.cpp
When GGML and llama.cpp joined Hugging Face, we described their complementary roles: llama.cpp provides a foundation for local inference, while transformers provides a foundation for model definition. GGUF support brings those two closer together.
llama.cpp remains our recommended engine when your priority is efficient local inference. Its dedicated runtime, memory management, and broad hardware support are built around that goal. This integration gives developers a convenient way to work with the same GGUF checkpoints inside transformers:
- Experiment with GGUF in Python and PyTorch. Inspect intermediate activations with hooks, modify a model's forward pass, or prototype custom layers using familiar PyTorch tools.
- Evaluate GGUF models. Use your existing transformers evaluation workflows to measure the quality of quantized checkpoints.
- Validate GGUF conversions. For us as developers, loading the original checkpoint and its GGUF conversion in transformers makes it easier to check that the weights were converted correctly, accounting for quantization error.
- Try new decoding ideas. Use custom logits processors and stopping criteria with
generate, or write your own generation loop in Python. - Fine-tune from a GGUF checkpoint. Dequantize the weights and continue with a standard transformers training workflow.
For that last case, use GgufConfig(dequantize=True):
import torch
from transformers import AutoModelForCausalLM, GgufConfig
model = AutoModelForCausalLM.from_pretrained(
"unsloth/Qwen3.5-4B-GGUF",
gguf_file="Qwen3.5-4B-Q4_K_M.gguf",
quantization_config=GgufConfig(dequantize=True),
dtype=torch.bfloat16,
)Beyond GGUF: ggml kernels for more models
The bigger opportunity is bringing ggml's performance to models that llama.cpp does not support.
transformers already provides the PyTorch implementations of these architectures. With ggml kernels and quantization schemes available in PyTorch, we can work toward accelerating their supported operations without first implementing the entire model in llama.cpp. This is especially useful for new architectures, research models, and custom variants that may never receive a dedicated llama.cpp implementation.
That opportunity extends beyond the GGUF format itself. A kernel operates on tensors; it does not require the whole model to come from a GGUF file. The same building blocks can be integrated into other transformers models and loading workflows. This also opens a path to other modalities: computer vision models, audio models, and multimodal models could reuse compatible attention, normalization, and matrix multiplication kernels without first having a full implementation in llama.cpp. Each architecture still needs integration and validation; the initial GGUF examples here cover text generation.
Fast local inference with Python and PyTorch
We also wanted to show how far we can get while keeping the model and generation loop in Python. With the right kernels and an efficient generation loop, Python and PyTorch can deliver strong local inference performance. The kernels handle the heavy computation, while the generation loop keeps the GPU busy by avoiding unnecessary synchronization.
Our focus was to make eager execution fast without requiring torch.compile. For interactive use, we wanted a quick start and a steady stream of tokens, without compilation pauses or recompilation when input shapes change. The two main pieces of that work are the kernels and generate itself.
Reusing ggml's Metal kernels
A kernel is a small program that performs an operation on the GPU. PyTorch supplies general-purpose implementations; a specialized kernel can do less work, combine several operations, or read quantized weights directly in their stored format.
The kernels library lets us distribute compatible builds of ggml's Metal kernels on the Hub and call them from transformers. That brings ggml's work into the PyTorch model without replacing the model with a separate inference runtime.
| Kernel | What it does |
|---|---|
ggml-quantization | Reads packed quantized weights for matrix operations, including the selected experts in an MoE model. It avoids expanding the whole weight matrix before each decode operation. |
ggml-norm | Fuses normalization operations, including the zero-centered RMSNorm used by Qwen3.5 and Qwen3.8. |
ggml-attn | Provides ggml's Metal flash attention for prompt processing and token decoding. |
ggml-gated-delta-net | Accelerates the gated delta network used in the linear-attention layers of the Qwen3.5 and Qwen3.8 hybrid architectures. |
topk | Selects the experts for each token in an MoE model, combining softmax and top-k routing. This is our own Metal implementation. |
The first four packages build on ggml's kernels; the top-k kernel addresses a separate bottleneck in MoE routing. Together they reduce the GPU work needed for each generated token.
To show the contribution of the layer kernels, we compare the same packed GGUF checkpoints with and without them. The quantization kernel stays enabled in both configurations: disabling it would also change how weights are represented and would measure a different tradeoff.
Keeping the CPU and GPU working together
Faster kernels only help if the GPU has work to do. During generation, the CPU schedules GPU operations and controls the loop that produces the next token. Reading a result back from the GPU can force the CPU to wait until queued operations finish. Repeating even a small wait for every token can noticeably reduce throughput.
Two changes address this in generate, which results in improvements for all transformers models (not just when running GGUF files):
- Drop an unnecessary attention mask early (#48814). When a supported decoder-only input has no padding, its all-ones padding mask can be removed at the start of generation. Downstream attention code no longer needs to inspect that mask repeatedly to determine whether it can be skipped. Causal attention is still preserved.
- Defer the stopping check (#47975). On supported paths,
generatecopies the stopping decision asynchronously and consumes it on the following step. The CPU can keep scheduling work while the GPU runs. Streaming tokens use the same approach, and any extra step past the stopping condition is removed from the result.
These changes improve the generation loop around the model, so their usefulness extends beyond GGUF. They complement the kernel work: kernels reduce the cost of an operation, while fewer synchronization points let CPU scheduling and GPU execution overlap.
These measurements keep all layer kernels enabled; the bars isolate the changes to the generation loop.
Current limitations and next steps
The initial target is a single interactive conversation on Apple Silicon. There are a few boundaries to keep in mind:
- The packed inference path is MPS-only for now. GGUF import through dequantization remains a separate option; support for the file format does not imply that packed kernels are available on every device.
- Padding and batching still need work. Unpadded inputs benefit from the mask optimization described above. Padded batches cannot take the same shortcut and can have lower performance. We want to extend the work to
generate_batchon MPS. - Architecture coverage is limited. The packed loader currently covers the Qwen3.5 dense and MoE architectures, including compatible Qwen3.8 checkpoints. Adding support for other architectures is relatively straightforward, and we’ll expand coverage gradually.
If you have a GGUF model you would like to use in transformers, open an issue with the checkpoint and your use case. That will help us prioritize support for the models people are running locally.
Acknowledgments
We would like to thank Arthur Zucker for initiating this work and reviewing all of my PRs, and Cyril Vallez for the generate PRs. We are grateful to Sayak Paul, the llama.cpp team, and Bertrand Chevalier for their help integrating the kernels. We also thank Aritra Roy Gosthipaty and Pedro Cuenca for reviewing this blog post, and Lysandre Debut for overseeing the project.