# Bitsandbytes

[bitsandbytes](https://github.com/bitsandbytes-foundation/bitsandbytes) 库通过一个轻量级的 Python 封装来调用硬件加速函数，为 LLM 提供量化工具。它通过降低内存占用，使在有限的计算资源下运行大型模型成为可能。

其核心功能，bitsandbytes 提供：

- **量化线性层**：`Linear8bitLt` 和 `Linear4bit` 层，用于以内存高效的量化替代方案替换标准的 PyTorch 线性层
- **优化后的优化器**：通过其 `optim` 模块提供常见优化器的 8 位版本，从而以较低的内存需求训练大型模型
- **矩阵乘法**：利用量化格式优化的矩阵乘法运算

bitsandbytes 提供两种主要的量化功能：

1. **LLM.int8()** - 一种 8 位量化方法，可在不显著降低性能的情况下使推理更易用。与朴素的量化不同，[LLM.int8()](https://hf.co/papers/2208.07339) 会为关键计算动态保留更高的精度，从而防止模型敏感部分出现信息丢失。

2. **QLoRA** - 一种 4 位量化技术，通过插入一组小型可训练的低秩适配（LoRA）权重，在保持模型可训练性的同时进一步压缩模型。

> **注意：** 如需更友好的量化体验，您可以使用 `bitsandbytes` [社区空间](https://huggingface.co/spaces/bnb-community/bnb-my-repo)。

运行以下命令以安装 bitsandbytes。

```bash
pip install --upgrade transformers accelerate bitsandbytes
```

要从源代码编译，请按照 [bitsandbytes 安装指南](https://huggingface.co/docs/bitsandbytes/main/en/installation) 中的说明操作。

## 硬件兼容性

bitsandbytes 支持 CUDA 版本 11.8 - 13.0 的 NVIDIA GPU、Intel XPU、Intel Gaudi (HPU) 以及 CPU。目前正在进行支持更多平台的工作。如果您有兴趣提供反馈或进行测试，请查看 [bitsandbytes 仓库](https://github.com/bitsandbytes-foundation/bitsandbytes) 以获取更多信息。

### NVIDIA GPU（CUDA）

此后端支持 Linux x86-64、Linux aarch64 和 Windows 平台。

| 功能 | 最低硬件要求 |
|---------|-------------------------------|
| 8 位优化器 | NVIDIA Pascal（GTX 10X0 系列、P100）或更新的 GPU * |
| LLM.int8() | NVIDIA Turing（RTX 20X0 系列、T4）或更新的 GPU |
| NF4/FP4 量化 | NVIDIA Pascal（GTX 10X0 系列、P100）或更新的 GPU * |

### Intel GPU（XPU）

此后端支持 Linux x86-64 和 Windows x86-64 平台。

### Intel Gaudi (HPU)

此后端在 Gaudi2 和 Gaudi3 上支持 Linux x86-64。

### CPU

该后端支持 Linux x86-64、Linux aarch64 和 Windows x86-64 平台。

## 量化示例

通过向 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 传入 [BitsAndBytesConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.BitsAndBytesConfig) 来量化模型。只要模型支持 [Accelerate](https://huggingface.co/docs/accelerate/index) 并包含 [torch.nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) 层，此方法适用于任何模态下的任何模型。

将模型量化为 8 位可将内存占用减半，对于大型模型，请设置 `device_map="auto"` 以在所有可用 GPU 之间高效分配权重。

```py
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_8bit=True)

model_8bit = AutoModelForCausalLM.from_pretrained(
    "bigscience/bloom-1b7", 
    device_map="auto",
    quantization_config=quantization_config
)
```

默认情况下，所有其他模块（例如 [torch.nn.LayerNorm](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html)）都会设置为默认的 torch 数据类型。您可以使用 `dtype` 参数来更改这些模块的数据类型。将 `dtype="auto"` 设置为该值时，模型会以 `config.json` 文件中定义的数据类型加载。

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

quantization_config = BitsAndBytesConfig(load_in_8bit=True)

model_8bit = AutoModelForCausalLM.from_pretrained(
    "facebook/opt-350m", 
    device_map="auto",
    quantization_config=quantization_config, 
    dtype="auto"
)
model_8bit.model.decoder.layers[-1].final_layer_norm.weight.dtype
```

模型量化为 8 位后，除非使用最新版本的 Transformers 和 bitsandbytes，否则无法将量化后的权重推送到 Hub。如果您已使用最新版本，则可以通过 [push_to_hub()](/docs/transformers/main/zh/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) 将 8 位模型推送到 Hub。量化配置 config.json 文件会先被推送，随后是量化后的模型权重。

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

quantization_config = BitsAndBytesConfig(load_in_8bit=True)

model = AutoModelForCausalLM.from_pretrained(
    "bigscience/bloom-560m", 
    device_map="auto",
    quantization_config=quantization_config
)

model.push_to_hub("bloom-560m-8bit")
```

将模型量化为 4-bit 可将内存占用降低 4 倍，对于大型模型，请设置 `device_map="auto"` 以在所有可用 GPU 之间高效分配权重。

```py
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_4bit=True)

model_4bit = AutoModelForCausalLM.from_pretrained(
    "bigscience/bloom-1b7",
    device_map="auto",
    quantization_config=quantization_config
)
```

默认情况下，所有其他模块（例如 [torch.nn.LayerNorm](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html)）都会被转换为 `torch.float16`。您可以通过 `dtype` 参数更改这些模块的数据类型。将 `dtype="auto"` 设置为该值时，模型将以 `config.json` 文件中定义的数据类型加载。

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

quantization_config = BitsAndBytesConfig(load_in_4bit=True)

model_4bit = AutoModelForCausalLM.from_pretrained(
    "facebook/opt-350m",
    device_map="auto",
    quantization_config=quantization_config, 
    dtype="auto"
)
model_4bit.model.decoder.layers[-1].final_layer_norm.weight.dtype
```

请确保你已安装最新版本的 bitsandbytes，以便能够序列化 4-bit 模型并通过 [push_to_hub()](/docs/transformers/main/zh/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) 将其推送到 Hub。使用 [save_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.save_pretrained) 将 4-bit 模型保存到本地。

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

quantization_config = BitsAndBytesConfig(load_in_4bit=True)

model = AutoModelForCausalLM.from_pretrained(
    "bigscience/bloom-560m", 
    device_map="auto",
    quantization_config=quantization_config
)

model.push_to_hub("bloom-560m-4bit")
```

> [!WARNING]
> 8 位和 4 位训练仅支持训练 *额外* 参数。

使用 `get_memory_footprint` 检查您的内存占用。

```py
print(model.get_memory_footprint())
```

使用 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 加载量化模型，无需提供 `quantization_config`。

```py
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("{your_username}/bloom-560m-8bit", device_map="auto")
```

## LLM.int8

本节将探讨 8 位量化的若干具体特性，例如 offloading、outlier 阈值、跳过模块转换以及微调。

### Offloading

8-bit 模型可以在 CPU 和 GPU 之间卸载权重，从而将非常大的模型装入内存。调度到 CPU 的权重以 **float32** 格式存储，不会被转换为 8-bit。例如，通过 [BitsAndBytesConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.BitsAndBytesConfig) 为 [bigscience/bloom-1b7](https://huggingface.co/bigscience/bloom-1b7) 启用卸载。

```py
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True)
```

设计一个自定义设备映射，将除 `lm_head` 之外的所有内容都放到 GPU 上，并将 `lm_head` 调度到 CPU。

```py
device_map = {
    "transformer.word_embeddings": 0,
    "transformer.word_embeddings_layernorm": 0,
    "lm_head": "cpu",
    "transformer.h": 0,
    "transformer.ln_f": 0,
}
```

现在使用自定义的 `device_map` 和 `quantization_config` 加载您的模型。

```py
model_8bit = AutoModelForCausalLM.from_pretrained(
    "bigscience/bloom-1b7",
    dtype="auto",
    device_map=device_map,
    quantization_config=quantization_config,
)
```

### 异常值阈值

“离群值”是指大于某个阈值的隐藏状态值，这些值以 fp16 计算。虽然这些值通常呈正态分布（[-3.5, 3.5]），但对于大型模型，该分布可能差异很大（[-60, 6] 或 [6, 60]）。8 位量化在数值约为 5 时效果良好，但超出该范围后，性能会显著下降。一个好的默认阈值是 6，但对于更不稳定的模型（小型模型或微调），可能需要更低的阈值。

要找到适合您模型的最佳阈值，请尝试调整 [BitsAndBytesConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.BitsAndBytesConfig) 中的 `llm_int8_threshold` 参数。例如，将阈值设置为 `0.0` 可以显著加快推理速度，但可能会以牺牲部分准确性为代价。

```py
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

model_id = "bigscience/bloom-1b7"

quantization_config = BitsAndBytesConfig(
    llm_int8_threshold=0.0,
    llm_int8_enable_fp32_cpu_offload=True
)

model_8bit = AutoModelForCausalLM.from_pretrained(
    model_id,
    dtype="auto",
    device_map=device_map,
    quantization_config=quantization_config,
)
```

### 跳过模块转换

对于某些模型（例如 Jukebox），无需将每个模块都量化为 8 位，因为这实际上可能导致不稳定。对于 Jukebox，有几个 `lm_head` 模块应使用 [BitsAndBytesConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.BitsAndBytesConfig) 中的 `llm_int8_skip_modules` 参数跳过。

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

model_id = "bigscience/bloom-1b7"

quantization_config = BitsAndBytesConfig(
    llm_int8_skip_modules=["lm_head"],
)

model_8bit = AutoModelForCausalLM.from_pretrained(
    model_id,
    dtype="auto",
    device_map="auto",
    quantization_config=quantization_config,
)
```

### 微调

[PEFT](https://github.com/huggingface/peft) 库支持使用 8 位量化对 [flan-t5-large](https://huggingface.co/google/flan-t5-large) 和 [facebook/opt-6.7b](https://huggingface.co/facebook/opt-6.7b) 等大型模型进行微调。由于该库会自动将模型加载到 GPU 上，因此训练时无需传递 `device_map` 参数。不过，你仍然可以通过 `device_map` 参数自定义设备映射（`device_map="auto"` 仅应用于推理）。

## QLoRA

本节将探讨 4 位量化的一些具体特性，例如更改计算数据类型、Normal Float 4 (NF4) 数据类型以及嵌套量化。

### 计算数据类型

在 [BitsAndBytesConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.BitsAndBytesConfig) 中将数据类型从 float32（默认值）更改为 bf16，以加快计算速度。

```py
import torch
from transformers import BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
```

### 常规 Float 4 (NF4)

NF4 是 [QLoRA](https://hf.co/papers/2305.14314) 论文中提出的一种 4 位数据类型，专为从正态分布初始化的权重而设计。在训练 4 位基础模型时，应使用 NF4。

```py
from transformers import BitsAndBytesConfig

nf4_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
)

model_nf4 = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto", quantization_config=nf4_config)
```

在推理阶段，`bnb_4bit_quant_type` 对性能的影响并不大。但为了与模型权重保持一致，您应使用 `bnb_4bit_compute_dtype` 和 `dtype` 的值。

### 嵌套量化

嵌套量化可以在不增加额外性能开销的情况下进一步节省内存。该功能会对已量化的权重进行第二次量化，从而额外节省 0.4 位/参数。例如，使用嵌套量化，您可以在 16GB 的 NVIDIA T4 GPU 上微调 [Llama-13b](https://huggingface.co/meta-llama/Llama-2-13b) 模型，序列长度为 1024，批大小为 1，并启用 4 步的梯度累积。

```py
from transformers import BitsAndBytesConfig

double_quant_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
)

model_double_quant = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf", dtype="auto", quantization_config=double_quant_config)
```

## 反量化 bitsandbytes 模型

量化完成后，你可以使用 [dequantize()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.dequantize) 将模型恢复到原始精度，但这可能会导致一定程度的质量损失。请确保你有足够的 GPU 内存来容纳反量化后的模型。

```python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m", BitsAndBytesConfig(load_in_4bit=True))
model.dequantize()
```

## 资源

有关 8 位量化的详细信息，请参阅 [使用 Hugging Face Transformers、Accelerate 和 bitsandbytes 对大规模 transformers 进行 8 位矩阵乘法的温和介绍](https://huggingface.co/blog/hf-bitsandbytes-integration)。

在此 [notebook](https://colab.research.google.com/drive/1ge2F1QSK8Q7h0hn3YKuBCOAS0bK8E0wf) 中尝试 4-bit 量化，并在 [通过 bitsandbytes、4-bit 量化和 QLoRA 让 LLM 更易于访问](https://huggingface.co/blog/4bit-transformers-bitsandbytes) 中了解其更多细节。

