LoRA微调实战:最省显存的模型训练方法

📘 AI教程 💬 🔥 Trending 发布者: leakey
LoRA微调实战:最省显存的模型训练方法

🩺 摘要

全量微调一个7B模型要24GB显存,一般人没有这个硬件。LoRA说:4GB够了。

📝 详情

LoRA是什么

LoRA(Low-Rank Adaptation)是一种高效的模型微调方法。

常规微调:修改模型的所有参数(7B模型=140亿参数,全调) LoRA微调:只修改一小部分参数(0.1%-1%),其他参数冻住不动

效果:几乎一样,但资源消耗降低90%。

环境准备

pip install torch transformers datasets accelerate peft

准备数据

Alpaca格式:

[
  {
    "instruction": "翻译成英文",
    "input": "今天天气真好",
    "output": "The weather is nice today."
  },
  {
    "instruction": "写一首关于春天的诗",
    "input": "",
    "output": "春风拂面来,桃花满树开……"
  }
]

至少50-100条。质量比数量重要。

开始微调

from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model
import torch

# 加载模型(4bit量化节省显存)
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2.5-7B-Instruct",
    load_in_4bit=True,
    torch_dtype=torch.float16
)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")

# 配置LoRA
lora_config = LoraConfig(
    r=8,           # 秩,越大效果越好
    lora_alpha=32, # 缩放系数
    target_modules=["q_proj", "v_proj"],  # 只训练这两个模块
    lora_dropout=0.05,
    bias="none"
)

model = get_peft_model(model, lora_config)
print(f"可训练参数: {model.num_parameters(only_trainable=True)/1e6:.2f}M")
# 输出大概只有几百万参数(原模型140亿的0.1%)

训练参数

from transformers import TrainingArguments, Trainer

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

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=dataset
)
trainer.train()

合并模型

训练完保存的只是LoRA权重(几MB),需要合并到原模型才能用:

from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
lora_model = PeftModel.from_pretrained(base_model, "./lora-output/checkpoint-xxx")
merged = lora_model.merge_and_unload()
merged.save_pretrained("./final-model")

硬件要求

模型 全量微调 LoRA微调
1.5B 12GB 4GB
7B 24GB 6GB
13B 48GB 12GB
70B 320GB 48GB

RTX 3060 12GB就能微调7B模型。

一句话

LoRA让模型微调从「大厂才能做的事」变成了「个人开发者也能做的事」。