You are viewing main version, which requires installation from source. If you'd like
regular pip install, checkout the latest stable version (v5.22.2).
微调模型
量化权重无法通过梯度直接更新,因此你需要在冻结的量化权重之上训练一个小型适配器来微调量化模型。在 4 位模型上训练 LoRA 适配器被称为 QLoRA,它允许你微调那些在 bf16 下无法装入内存的模型。
Trainer 会在训练前检查模型,以确保:
训练适配器
安装 PEFT。
pip install -U peft
使用支持训练的方法加载模型,通过 add_adapter() 附加一个 LoRA 适配器,并将模型传递给 Trainer。下面的示例使用 4-bit bitsandbytes,并假设 train_dataset 是一个已分词的数据集。
import torch
from peft import LoraConfig
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, Trainer, TrainingArguments
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen3-0.6B",
quantization_config=quantization_config,
device_map="auto",
)
lora_config = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM")
model.add_adapter(lora_config)
trainer = Trainer(
model=model,
args=TrainingArguments(output_dir="qwen3-qlora", bf16=True),
train_dataset=train_dataset,
)
trainer.train()仅适配器权重参与训练。量化后的基础权重保持冻结。
保存适配器
save_pretrained() 仅保存适配器权重,其大小仅为几 MB。此方法适用于所有方法,包括那些无法保存其量化权重的方法。
model.save_pretrained("qwen3-qlora-adapter")要使用该适配器,请使用相同的量化配置加载基础模型,并在其上加载适配器。有关详细信息,请参阅加载适配器。
量化感知训练
BitNet 和 compressed-tensors 可以在不使用适配器的情况下训练完整模型,前提是权重保持可训练的形式。
- BitNet 需要在 BitNetQuantConfig 中设置
linear_class="autobitlinear"和quantization_mode="online"。 - compressed-tensors 需要一个未压缩的检查点,或者在 CompressedTensorsConfig 中设置
dequantize=True。使用 FP8 内核的检查点无法进行训练。
有关量化感知训练与训练后量化之间的区别,请参阅量化概念。
Update on GitHub