SuperAPI AI 工具集

quantizing-models-bitsandbytes

智能体与模型

查看项目

更新于 10-15 13:10

技能介绍

用途

bitsandbytes 用于对大语言模型进行量化,降低显存占用。官方说明指出,8 位量化可减少约 50% 内存,4 位量化可减少约 75% 内存,精度损失小于 1%。适用场景包括 GPU 显存受限、需要加载更大模型、仅做推理、使用 HuggingFace Transformers,以及可接受 0-2% 精度下降的情况。若用于生产服务(追求更快推理)可考虑 GPTQ/AWQ;CPU 推理可考虑 GGUF(llama.cpp);H100 GPU 可考虑 FP8;对精度要求极高且显存不受限则使用全精度。

主要能力

  1. 8 位量化:约 50% 内存下降。示例中 Llama-2-7B 从 14GB 降至 7GB。
  2. 4 位量化:约 75% 内存下降。示例中 Llama-2-7B 从 14GB 降至 3.5GB。可配置计算精度为 FP16、量化类型 nf4、启用双重量化。
  3. QLoRA 微调:在 4 位基座模型上添加 LoRA 适配器进行训练,适配器文件约 20MB。
  4. 8 位优化器:如 AdamW8bit,官方称可减少约 75% 优化器内存。
  5. 内存优化相关能力:CPU 卸载、磁盘卸载等。

使用方式

安装:

pip install bitsandbytes transformers accelerate

QLoRA 微调需额外依赖:

pip install bitsandbytes transformers peft accelerate datasets

8 位量化示例:

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"
)

4 位量化示例:

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"
)

更细的 8 位配置:

config = BitsAndBytesConfig(
    load_in_8bit=True,
    llm_int8_threshold=6.0,
    llm_int8_has_fp16_weight=False
)

更细的 4 位配置:

config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True
)

内存估算公式: FP16 内存(GB)= 参数量 × 2 bytes / 1e9;INT8 = 参数量 × 1 byte / 1e9;INT4 = 参数量 × 0.5 bytes / 1e9。官方给出 Llama 2 7B 示例:FP16 为 14GB,INT8 为 7GB,INT4 为 3.5GB。

量化级别选择建议(资料原文):8GB VRAM 对应 3B 模型建议 4-bit;12GB 对应 7B 建议 4-bit;16GB 对应 7B 可选 8-bit 或 4-bit;24GB 对应 13B 可选 8-bit,或 70B 选 4-bit;40GB 以上对应 70B 可选 8-bit。

QLoRA 微调流程

  1. 安装依赖(同上)。
  2. 配置 4 位基座模型(同 4 位量化示例,含 nf4 与双重量化)。
  3. 添加 LoRA 适配器:
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

model = prepare_model_for_kbit_training(model)

lora_config = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM"
)

model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
  1. 使用标准 Trainer 训练,并保存 LoRA 适配器(约 20MB):
from transformers import Trainer, TrainingArguments

training_args = TrainingArguments(
    output_dir="./qlora-output",
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,
    num_train_epochs=3,
    learning_rate=2e-4,
    fp16=True,
    logging_steps=10,
    save_strategy="epoch"
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    tokenizer=tokenizer
)

trainer.train()
model.save_pretrained("./qlora-adapters")

8 位优化器

可在 TrainingArguments 中设置 optim="paged_adamw_8bit",或手动使用:

import bitsandbytes as bnb

optimizer = bnb.optim.AdamW8bit(
    model.parameters(),
    lr=1e-4,
    betas=(0.9, 0.999),
    eps=1e-8
)

官方给出的对比:标准 AdamW 优化器内存 = 参数量 × 8 bytes,8-bit AdamW = 参数量 × 2 bytes,节省 75%。Llama 2 7B 示例中标准为 56GB,8 位为 14GB。

常见问题处理(资料原文)

  • 加载时 CUDA 错误:检查 CUDA 版本(nvcc --version),安装匹配版本:pip install bitsandbytes --no-cache-dir。
  • 模型加载慢:使用 CPU offload,如设置 max_memory={0: "20GB", "cpu": "30GB"}。
  • 精度低于预期:改用 8 位(官方称 8 位精度损失 <0.5%,4 位为 1-2%),或使用 NF4 加双重量化。
  • 4 位仍 OOM:启用 CPU/磁盘 offload,如 offload_folder="offload", offload_state_dict=True。

硬件要求

GPU:NVIDIA,计算能力 7.0 以上(Turing、Ampere、Hopper)。VRAM 取决于模型与量化:4-bit Llama 2 7B 约 4GB,4-bit Llama 2 13B 约 8GB,4-bit Llama 2 70B 约 24GB。CUDA 11.1+(建议 12.0+),PyTorch 2.0+。支持平台:NVIDIA GPU(主要)、AMD ROCm、Intel GPU(实验性)。

参考资源(资料原文)

GitHub:https://github.com/bitsandbytes-foundation/bitsandbytes HuggingFace 文档:https://huggingface.co/docs/transformers/quantization/bitsandbytes QLoRA 论文:"QLoRA: Efficient Finetuning of Quantized LLMs"(2023) LLM.int8() 论文:"LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale"(2022)

限制

资料未提供具体定价与收费信息,暂未提供。资料未提供国内平台支持情况,暂未提供。其他未在资料中说明的性能指标、精度数值、兼容性细节等,暂未提供。