要在Google Colab(免费)上运行QLoRA,请按照以下步骤操作:
# 安装依赖
!pip install -q bitsandbytes transformers accelerate peft trl
# 验证GPU
import torch
print(f"GPU可用: {torch.cuda.is_available()}")
print(f"GPU名称: {torch.cuda.get_device_name(0)}")
注意:在Colab中,确保选择T4 GPU(Runtime → Change runtime type → GPU)。
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
# 量化配置
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
# 加载模型和tokenizer
model_name = "Qwen/Qwen2.5-0.5B-Instruct"
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=bnb_config,
device_map="auto", # 自动在GPU/CPU间分配层
trust_remote_code=True # 某些模型如Qwen需要
)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
from peft import LoraConfig
lora_config = LoraConfig(
r=8, # 低秩矩阵维度
lora_alpha=16, # 缩放因子(通常为2x r)
target_modules=["q_proj", "v_proj"], # 应用LoRA的模块
lora_dropout=0.05, # 正则化dropout
bias="none", # 不训练偏置
task_type="CAUSAL_LM" # 任务类型:因果语言建模
)
# 将PEFT应用于模型
from peft import get_peft_model
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
预期输出:
trainable params: 327,680 || all params: 510,550,016 || trainable%: 0.0642
这确认只有0.06%的参数被训练 — 超过5.1亿个参数被冻结!
target_modules是应用LoRA矩阵的模型层。正确的选择对性能至关重要。
["q_proj", "v_proj"] — 注意力层中的查询和值投影。["q_proj", "k_proj", "v_proj", "o_proj"] — 所有注意力投影(更多参数,复杂任务可能有所改善)。["gate_proj", "up_proj", "down_proj"](在Llama中)或["fc1", "fc2"](在其他模型中)。# 列出模型中的所有线性模块
from peft.utils import TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING
# 或手动检查
for name, module in model.named_modules():
if isinstance(module, torch.nn.Linear):
print(name)
提示:从
["q_proj", "v_proj"]开始。如果性能不足,可以尝试添加更多模块。
r(秩): 从8开始。如果模型学习效果不好,尝试16或32。如果出现过拟合,减少到4。lora_alpha: 通常设置为2 * r。如果r=8,alpha=16。控制LoRA更新的"强度"。lora_dropout: 小数据集用0.05或0.1。大数据集用0.0。bias: "none"最常见。"all"或"lora_only"很少能提高性能。