[ PROMPT_NODE_22800 ]
quantizing-models-bitsandbytes
[ SKILL_DOCUMENTATION ]
# bitsandbytes - LLM 量化
## 快速开始
bitsandbytes 可将 LLM 内存占用减少 50% (8-bit) 或 75% (4-bit),精度损失 <1%。
**安装**:
bash
pip install bitsandbytes transformers accelerate
**8-bit 量化** (50% 内存节省):
python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
config = BitsAndBytesConfig(load_in_8bit=True)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
quantization_config=config,
device_map="auto"
)
# 内存:14GB → 7GB
**4-bit 量化** (75% 内存节省):
python
config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
quantization_config=config,
device_map="auto"
)
# 内存:14GB → 3.5GB
## 常见工作流
### 工作流 1:在有限 GPU 显存中加载大模型
复制此清单:
量化加载:
- [ ] 第 1 步:计算内存需求
- [ ] 第 2 步:选择量化级别(4-bit 或 8-bit)
- [ ] 第 3 步:配置量化
- [ ] 第 4 步:加载并验证模型
**第 1 步:计算内存需求**
估算模型内存:
FP16 内存 (GB) = 参数量 × 2 字节 / 1e9
INT8 内存 (GB) = 参数量 × 1 字节 / 1e9
INT4 内存 (GB) = 参数量 × 0.5 字节 / 1e9
示例 (Llama 2 7B):
FP16: 7B × 2 / 1e9 = 14 GB
INT8: 7B × 1 / 1e9 = 7 GB
INT4: 7B × 0.5 / 1e9 = 3.5 GB
**第 2 步:选择量化级别**
| GPU 显存 | 模型大小 | 推荐 |
|----------|------------|-------------|
| 8 GB | 3B | 4-bit |
| 12 GB | 7B | 4-bit |
| 16 GB | 7B | 8-bit 或 4-bit |
| 24 GB | 13B | 8-bit 或 70B 4-bit |
| 40+ GB | 70B | 8-bit |
**第 3 步:配置量化**
针对 8-bit(精度更高):
python
from transformers import BitsAndBytesConfig
import torch
config = BitsAndBytesConfig(
load_in_8bit=True,
llm_int8_threshold=6.0, # 异常值阈值
llm_int8_has_fp16_weight=False
)
针对 4-bit(最大内存节省):
python
config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16, # 在 FP16 中计算
bnb_4bit_quant_type="nf4", # NormalFloat4 (推荐)
bnb_4bit_use_double_quant=True # 嵌套量化
)
**第 4 步:加载并验证模型**
python
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-13b-hf",
q