[ PROMPT_NODE_22804 ]
qlora-training
[ SKILL_DOCUMENTATION ]
# QLoRA 训练
使用 QLoRA(量化低秩适配,Quantized Low-Rank Adaptation)通过 4-bit 量化微调大语言模型的完整指南。
## 概述
QLoRA 通过以下方式使在消费级 GPU 上微调 70B+ 参数模型成为可能:
- 以 4-bit 加载基础模型(内存减少 75%)
- 仅训练小型 LoRA 适配器(约 20MB)
- 保持接近全精度的质量
**内存节省**:
- Llama 2 70B: 140GB → 35GB (4-bit) + 20MB (LoRA) = **总计 35GB**
- 可在单张 A100 80GB 上运行!
**准确度**:相比全参数微调,性能下降 <1%
## 快速开始
### 基础 QLoRA 微调
python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, TrainingArguments
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
import torch
# 第 1 步:以 4-bit 加载模型
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-70b-hf",
quantization_config=bnb_config,
device_map="auto",
torch_dtype=torch.bfloat16
)
# 第 2 步:为 k-bit 训练做准备
model = prepare_model_for_kbit_training(model)
# 第 3 步:添加 LoRA 适配器
lora_config = LoraConfig(
r=64,
lora_alpha=16,
target_modules="all-linear",
lora_dropout=0.1,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# 可训练参数: 335M || 总参数: 70B || 可训练占比: 0.48%
# 第 4 步:训练
from trl import SFTTrainer
training_args = TrainingArguments(
output_dir="./qlora-70b",
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
num_train_epochs=3,
learning_rate=2e-4,
bf16=True,
optim="paged_adamw_8bit",
logging_steps=10,
save_strategy="epoch"
)
trainer = SFTTrainer(
model=model,
args=training_args,
train_dataset=dataset,
tokenizer=tokenizer
)
trainer.train()
## 完整训练工作流
### 工作流 1:单 GPU 训练(消费级 GPU)
在 RTX 4090 (24GB) 上训练 Llama 2 13B。
**第 1 步:准备数据集**
python
from datasets import load_dataset
# 加载指令数据集
dataset = load_dataset("timdettmers/openassistant-guanaco")
# 指令微调格式化
def format_instruction(example):
return {
"text": f"### Human: {example['text']}n### Assistant: {example['output']}"
}
dataset = dataset.map(format_instruction)