# 概述

量化将模型的权重，有时还包括其激活值，以更少的位数存储，从而降低模型的内存需求。模型通常以 bf16 格式加载，每个参数占用 2 字节。一个 8B 模型在 bf16 下其权重大约需要 16GB 内存，在 8 位下大约需要 8GB，在 4 位下大约需要 4–5GB。位数减少会损失一定的精度，并且每种量化方法在内存、速度和精度之间做出的权衡各不相同。

Transformers 通过 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 集成了 20 多种量化方法，因此无论您选择哪种方法，都可以使用相同的加载代码。

## 使用量化模型的两种方法

如何使用量化取决于您的检查点是否已经过量化。

| 您已 | 你的操作 | 方法 |
|---|---|---|
| 全精度检查点 | 将量化配置传递给 `from_pretrained`，权重将在加载时进行量化。 | [在加载时量化模型](#quantize-a-model-while-loading) |
| 已经量化的检查点 | 调用 `from_pretrained` 时不传入量化配置。Transformers 会从检查点的 `config.json` 或您指定的 GGUF 文件中读取量化方法。 | [加载预量化检查点](#load-a-pre-quantized-checkpoint) |

某些方法（例如 AWQ、AutoRound、AQLM、compressed-tensors 和 GGUF）只能从检查点加载。您需要先使用该方法的专用库对模型进行量化，然后在 Transformers 中加载量化结果。

## 在加载时量化模型

创建该方法的配置类并将其传递给 `quantization_config`。下面的示例使用 [bitsandbytes](./bitsandbytes) 以 4 位加载一个 8B 模型。

```py
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B-Instruct",
    quantization_config=quantization_config,
    device_map="auto",
)
```

该组中的每个方法都有自己独立的配置类，例如 [TorchAoConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.TorchAoConfig) 或 [BitsAndBytesConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.BitsAndBytesConfig)。其中大多数方法不需要校准数据集。[GPTQ](./gptq) 是例外，因为它在模型加载过程中会使用数据集进行校准。

## 加载预量化检查点

预量化检查点会在其 `config.json` 中存储一个 `quantization_config`。当 `from_pretrained` 找到该配置时，会自动选择对应的量化器。

```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(
    "TheBloke/zephyr-7B-alpha-AWQ",
    device_map="auto",
)
print(model.config.quantization_config.quant_method)
```

在加载检查点之前，请先安装该方法所依赖的库。每个方法页面都会列出需要安装的内容。若要更改加载选项（例如指定运行哪个内核后端），请传入一个相同类型的配置。其选项将与检查点中存储的选项合并。

### GGUF 检查点

GGUF 检查点是一个包含权重、配置和分词器的单一文件，没有供 `from_pretrained` 读取的 `config.json`。请使用 `gguf_file` 来指定该文件。

```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(
    "unsloth/Qwen3.5-4B-GGUF",
    gguf_file="Qwen3.5-4B-Q4_K_M.gguf",
)
```

大多数 GGUF 模型在加载时会被反量化为全精度，因此其内存占用与未量化模型相当。只有在安装了 [kernels](https://huggingface.co/docs/kernels/index) 包且使用 MPS 的情况下，Qwen3.5 和 Qwen3.5 MoE 的权重才会保持打包状态。详情请参阅 [GGUF](./gguf)。

## 保存量化模型

调用 [save_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.save_pretrained) 或 [push_to_hub()](/docs/transformers/main/zh/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) 以保存量化权重及其 `quantization_config`。并非所有方法都能保存其量化权重。

## 选择一种方法

[选择方法](./selecting) 针对常见目标推荐了起点，并从硬件、位宽、节省空间、微调以及 `torch.compile` 支持等方面对比了所有方法。使用 [量化选择器](https://huggingface.co/spaces/stevhliu/quantization-picker) 可以检查模型在每种精度下是否适合您的硬件内存。

## 其他工具

这些工具在 Transformers 之外对模型进行量化。

- [Optimum](https://huggingface.co/docs/optimum/index) 针对特定硬件和运行时（如 Intel CPU 和 ONNX Runtime）对模型进行量化。
- Hub Spaces 会对模型进行量化，并将结果推送到您的账户：[bitsandbytes](https://huggingface.co/spaces/bnb-community/bnb-my-repo)、[GGUF](https://huggingface.co/spaces/ggml-org/gguf-my-repo) 和 [MLX](https://huggingface.co/spaces/mlx-community/mlx-my-repo)。

## 资源

- [使用 Hugging Face 学习量化基础](https://www.deeplearning.ai/short-courses/quantization-fundamentals-with-hugging-face/) 课程
- [深入量化](https://www.deeplearning.ai/short-courses/quantization-in-depth) 课程

## 后续步骤

- 阅读[量化概念](./concept_guide)，了解量化方案、粒度以及技术的工作原理。
- 使用[量化缓存](../kv_cache#quantized-cache)对 KV 缓存进行量化，以在生成长文本时节省内存。
- 在导出模型时，使用[量化导出](../exporters_quantization)对其进行量化。
- 使用 [贡献量化方法](./contribute) 贡献一种新方法。

