轻量级大模型训练实践:LoRA、Baichuan与LLaMA模型微调实战
1 LoRA微调的DIY改装记
大模型训练听起来像造火箭,但有了 LoRA(Low-Rank Adaptation),我这种“技术宅”也能在普通 GPU 上改装 Baichuan 和 LLaMA 模型!最近帮一个创业团队微调模型,让它擅长写中文科技文档,折腾了半个月,从数据集准备到部署,踩了一堆坑,终于把模型调得又快又准。
客户需求是让模型基于 500 篇中文科技文章(约 100MB 文本)生成专业文档,比如“AI 在医疗领域的应用”。我选了 Baichuan-7B(中文优化)和 LLaMA-7B(通用强),用 LoRA 微调,跑在单台 VPS(16 核 32G,NVIDIA A100)。下面是完整流程。
2 准备阶段:给模型“喂料”
微调的第一步是准备数据集,我用的是 500 篇科技文章(TXT 格式)。
2.1 数据清洗
用 Python 清洗数据,去掉乱码、重复内容:
import re
import glob
def clean_text(text):
text = re.sub(r"\s+", " ", text) # 合并多余空格
text = re.sub(r"[^\w\s,.!?]", "", text) # 去掉特殊字符
return text
files = glob.glob("articles/*.txt")
dataset = []
for file in files:
with open(file, "r", encoding="utf-8") as f:
text = clean_text(f.read())
dataset.append({"text": text})
import json
with open("cleaned_data.json", "w", encoding="utf-8") as f:
json.dump(dataset, f, ensure_ascii=False)
结果:清洗后数据从 100MB 压缩到 80MB,乱码没了,文本更干净。
踩坑记:我一开始没清理换行符,训练时模型输出全是“\n\n”,像得了“换行强迫症”。加 re.sub(r"\n+", "\n", text)
后正常。
3 微调阶段:用LoRA给模型“装涡轮”
LoRA 是轻量微调神器,只更新模型的部分参数,省显存又高效。我用 peft
库微调 Baichuan 和 LLaMA。
3.1 Baichuan-7B 微调
安装依赖:
pip install torch==2.0.1 transformers==4.30.2 peft==0.4.0 datasets==2.14.0
配置 LoRA:
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model
model_name = "baichuan-inc/Baichuan-7B"
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_name)
lora_config = LoraConfig(
r=8, # 低秩维度
lora_alpha=16,
target_modules=["W_pack"], # Baichuan 特定模块
lora_dropout=0.1,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
训练代码:
from datasets import load_dataset
from transformers import Trainer, TrainingArguments
dataset = load_dataset("json", data_files="cleaned_data.json")
training_args = TrainingArguments(
output_dir="./baichuan_lora",
per_device_train_batch_size=2,
gradient_accumulation_steps=4,
num_train_epochs=3,
learning_rate=2e-4,
fp16=True,
save_steps=500,
logging_steps=100
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset["train"]
)
trainer.train()
结果:训练 3 小时,显存占用 20G,模型生成科技文档逻辑清晰,中文表达流畅,像专业编辑。
踩坑记:Baichuan 的 W_pack
模块得精准指定,不然 LoRA 无效。查官方文档才找到正确配置。
3.2 LLaMA-7B 微调
LLaMA 配置类似,调整 target_modules
:
model_name = "meta-llama/Llama-2-7b-hf"
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_name)
lora_config = LoraConfig(
r=8,
lora_alpha=16,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
结果:训练 3.5 小时,显存 22G,生成文档专业但中文稍显“翻译腔”。加更多中文数据后改善。
踩坑:LLaMA 的 tokenizer 对中文分词不好,生成文本偶尔断句怪怪的。加 trust_remote_code=True
加载专用 tokenizer 后好多了。
小对比:Baichuan 中文更自然,LLaMA 逻辑更强但需额外中文优化。
扩展阅读:想深入微调,fine-tuning-mobius-12b-base-model 有硬核经验。
4 部署阶段:让模型“上路”
微调完模型,我用 Text Generation WebUI 部署,方便测试。
4.1 部署 WebUI
git clone https://github.com/oobabooga/text-generation-webui
cd text-generation-webui
pip install -r requirements.txt
python server.py --model ./baichuan_lora --load-in-4bit
结果:WebUI 启动 5 分钟,加载 Baichuan 模型后可通过网页输入 prompt,生成 500 字科技文档只需 10 秒,效果媲美专业写作。
踩坑:WebUI 默认吃显存,32G 勉强跑。加 --load-in-4bit
后显存降到 15G,速度略慢但稳定。
扩展阅读:部署更省心,text-generation-webui部署最新教程 有详细配置。
5 性能测试:谁更快更省?
我测试了生成 500 字文档的速度和显存占用:
- Baichuan-7B:生成 10 秒,显存 15G(4bit 量化),中文流畅度 90%。
- LLaMA-7B:生成 12 秒,显存 18G(4bit 量化),中文稍逊,逻辑更严密。
**踩坑:训练时 batch_size
设成 4,显存爆了。调成 2+4(gradient_accumulation_steps
)后稳住,用 nvidia-smi
监控救命。
6 适用场景:选谁不翻车?
- Baichuan-7B:中文场景(e.g., 科技文档、客服)首选,生成自然,部署简单。缺点是英文稍弱。
- LLaMA-7B:通用场景强,适合逻辑密集任务(e.g., 代码注释)。缺点是中文需优化。
- LoRA:低配 GPU 的救星,单卡 A100 就能跑。局限是复杂任务效果不如全参微调。
扩展阅读:想玩更多模型,chatglm-deepseek-baichuan-compare 有国产模型对比。
7 改装心得:
- 数据质量:清洗数据别偷懒,乱码和换行会让模型“学坏”。
- 显存管理:用
nvidia-smi
盯着,LoRA 的r
参数别超 16,显存吃不消。 - 模型部署:WebUI 配 4bit 量化,省显存又稳定。