lora vs dora vs qlora

LoRA vs DoRA vs QLoRA:参数高效微调三剑客对比

LoRA vs DoRA vs QLoRA:参数高效微调三剑客对比 引言 全量微调一个 7B 模型需要 ~60GB 显存,这让大多数开发者望而却步。参数高效微调(PEFT)方法通过只训练极少量参数,实现了接近全量微调的效果。其中最具代表性的是: LoRA(2021):低秩分解,PEFT 的奠基之作 QLoRA(2023):4bit 量化 + LoRA,把显存门槛打到 6GB DoRA(2024):解耦方向与大小,效果逼近全量微调 本文从原理到实践,完整对比三者。 1. LoRA:低秩适配 1.1 核心原理 LoRA 假设模型微调时的权重更新 ΔW 是低秩的: W' = W + ΔW = W + BA 其中: W ∈ R^{d×k}:原始权重(冻结,不训练) B ∈ R^{d×r}:可训练矩阵 A ∈ R^{r×k}:可训练矩阵 r << min(d, k):秩,通常 r=8/16/64 # LoRA 的数学表达 # 前向:h = Wx + BAx = (W + BA)x # 反向:只计算 B 和 A 的梯度,W 的梯度为零 # 初始化策略 # A: 正态分布初始化 N(0, σ²) # B: 零初始化(确保训练开始时 ΔW = BA = 0) 1.2 代码实现 import torch import torch.nn as nn class LoRALayer(nn.Module): """LoRA 层的独立实现""" def __init__( self, in_features: int, out_features: int, r: int = 8, alpha: int = 16, dropout: float = 0.0, ): super().__init__() self.r = r self.scale = alpha / r # 缩放系数 # 原始权重(冻结) self.base_weight = nn.Parameter( torch.randn(out_features, in_features), requires_grad=False ) # LoRA 矩阵 self.lora_A = nn.Parameter(torch.randn(r, in_features) * 0.01) self.lora_B = nn.Parameter(torch.zeros(out_features, r)) self.dropout = nn.Dropout(dropout) def forward(self, x: torch.Tensor) -> torch.Tensor: base_out = x @ self.base_weight.T lora_out = (self.dropout(x) @ self.lora_A.T @ self.lora_B.T) * self.scale return base_out + lora_out # 使用 PEFT 库(推荐) from peft import LoraConfig, get_peft_model config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], bias="none", task_type="CAUSAL_LM", ) model = get_peft_model(base_model, config) 1.3 参数量分析 以 LLaMA-7B(hidden_dim=4096)为例: ...

2026-06-25 · 7 min · 1318 words · 硅基 AGI 探索者
鲁ICP备2026018361号