LoRA微调实战指南:从数据准备到模型部署
LoRA:参数高效微调的工程选择 全参数微调一个7B模型需要至少60GB显存,而LoRA(Low-Rank Adaptation)只需不到20GB。这个差距让LoRA成为2026年最主流的微调方案——不是因为它效果最好,而是它在效果与成本之间提供了最优的性价比。 LoRA原理速览 LoRA的核心思想是冻结预训练权重,在旁边训练一个低秩矩阵: $$W_{new} = W_{pretrained} + \Delta W = W_{pretrained} + B \times A$$ 其中 $A \in \mathbb{R}^{r \times d}$,$B \in \mathbb{R}^{d \times r}$,秩 $r \ll d$。以7B模型为例,全参数微调需要更新70亿参数,而LoRA(r=8)只需更新约2000万参数,缩减了99.7%。 第一步:数据准备 数据格式标准化 推荐使用ShareGPT格式,兼容主流训练框架: { "conversations": [ {"from": "human", "value": "解释一下什么是联邦学习"}, {"from": "gpt", "value": "联邦学习是一种分布式机器学习技术..."} ] } 数据清洗管线 import json import re from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3-8B") def clean_and_filter(data_path, output_path, max_length=2048): """数据清洗与过滤管线""" cleaned = [] with open(data_path, 'r', encoding='utf-8') as f: raw_data = [json.loads(line) for line in f] for sample in raw_data: conversations = sample.get("conversations", []) if len(conversations) < 2: continue # 检查每轮对话质量 valid = True for turn in conversations: text = turn.get("value", "") # 过滤空回复 if len(text.strip()) < 10: valid = False break # 过滤过长回复 if len(tokenizer.encode(text)) > max_length: valid = False break # 过滤重复内容 if text.count("。") > 0 and text.count("。") / len(text) > 0.1: valid = False break if valid: cleaned.append(sample) with open(output_path, 'w', encoding='utf-8') as f: for sample in cleaned: f.write(json.dumps(sample, ensure_ascii=False) + '\n') print(f"原始数据: {len(raw_data)} → 清洗后: {len(cleaned)}") return cleaned 数据质量分布检查 在微调前务必检查数据分布,避免领域偏斜: ...