LoRA/QLoRA 高效微调实战
LoRA(Low-Rank Adaptation)通过低秩矩阵分解实现参数高效微调,仅训练不到 1% 的参数即可达到全量微调的效果。
LoRA 原理
python
class LoRALayer(nn.Module):
def __init__(self, original_layer, rank=8, alpha=16):
self.original = original_layer
d_in, d_out = original_layer.weight.shape
self.lora_A = nn.Linear(d_in, rank, bias=False)
self.lora_B = nn.Linear(rank, d_out, bias=False)
self.scaling = alpha / rank
nn.init.kaiming_uniform_(self.lora_A.weight)
nn.init.zeros_(self.lora_B.weight)
def forward(self, x):
return self.original(x) + self.scaling * self.lora_B(self.lora_A(x))QLoRA:量化 + LoRA
QLoRA 将基模型量化为 4-bit NF4 格式,同时保持 LoRA 适配器为 BF16 精度:
- 4-bit NormalFloat 量化
- 双重量化(量化量化常数)
- 分页优化器(避免 OOM)
LoRA 秩的选择
秩 r=8 适合大多数任务,r=16-64 用于需要更强表达能力的场景。alpha 通常设为 2*r。