M5-130M5: NLP & Large Language ModelsPEFT (LoRA / QLoRA / Prefix Tuning)Easy
⚡Flashcard Drill➔Mastery:
LoRA Foundations, Mathematical Formulation, and Hyperparameter Dynamics
📐 Mathematical Definition
⚡ One-Sentence Core Answer
LoRA freezes pre-trained base weights and injects trainable rank-decomposition matrices into transformer layers, drastically slashing trainable parameter counts and GPU memory while preserving full adaptation performance.
📌 Key Takeaways
- •Low-rank parameterization: represents weight delta as , with initialized from Gaussian noise and initialized to zero
- •Zero initial divergence: zero-initialization of guarantees that training begins exactly at the pre-trained base model state with
- •Hyperparameter mechanics: rank bounds adaptation subspace capacity, while scaling factor stabilizes learning rate dynamics across rank adjustments
📐 Mathematical Derivations
Mathematical Mechanism: 1. Intrinsic Dimensionality Hypothesis (Hu et al., 2021): Drawing on Aghajanyan et al., fine-tuning updates occupy a low intrinsic dimension. For a frozen pre-trained weight matrix , LoRA decomposes the adaptation increment into two low-rank matrices: where . For and , parameters shrink from to (a reduction). 2. Forward Pass Formulation: For input hidden state : Computing requires FLOPs, which is negligible compared to the base projection. 3. Initialization Protocol: Matrix is drawn from a Gaussian distribution or He uniform initialization, and matrix is initialized strictly to zero (). This guarantees: ensuring that fine-tuning starts smoothly from the pre-trained baseline without initial degradation. 4. Role of Scaling Factor $\alpha$: The scaling multiplier stabilizes optimizer dynamics. When experimenting with different ranks , keeping the ratio constant eliminates the need to recalibrate learning rates.
🏭 Production Trade-offs
Deep Dive & Engineering Trade-offs: ① Target Module Selection: While the original paper targeted only attention projection weights (), modern consensus (Dettmers et al., QLoRA) proves that applying LoRA across all linear layers (, plus MLP gates ) at a lower rank ( or ) universally outperforms applying a higher rank () exclusively to attention layers. ② Optimizer Memory Slashed: In full fine-tuning, AdamW stores first and second moment states for all parameters ( bytes per parameter in FP32), consuming model size in optimizer states alone. By restricting gradients to low-rank matrices ( of parameters), optimizer state memory drops to near zero, unlocking single-GPU training of massive models. ③ Zero Inference Latency Penalty: Prior to production deployment, compute . Serving runs on standard optimized GEMM kernels without latency overhead. ④ Rank Over-Parameterization Risks: Setting unnecessarily high () increases vulnerability to overfitting on small instruction datasets and inflates checkpoint storage without improving generalization. ⑤ Interview Strategy: State the formula , articulate the asymmetric initialization (), explain the optimizer memory savings mechanism, and advocate for 'all linear modules at low rank'.
⚠️ Common Interview Pitfalls
- ✕Initializing matrix with random non-zero weights, destroying pre-trained representations and destabilizing early training
- ✕Targeting only attention query and value projections while ignoring feed-forward network (FFN) layers, constraining model capacity
- ✕Adjusting rank without scaling proportionally, inadvertently destabilizing the effective learning rate schedule
🎯 Interviewer Follow-up Inquiries
- ?Why is matrix initialized to zero while matrix is initialized to random Gaussian values rather than vice versa?
- ?Why does applying LoRA across all linear layers with rank outperform applying rank strictly to attention weights?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
📚
Associated Knowledge Base Guides & Mindmaps
Explore the comprehensive technical article, exam cards, and global architecture tree.
中文速览与面试要点
解释 LoRA 的原理与超参作用。
用低秩增量 ΔW=BA 参数化微调,冻结基座;关键超参是秩 r、缩放 α/r、应用位置与 dropout。
核心要点
- 数学机理: LoRA(Low-Rank Adaptation,Hu 等 2021) ——观察到'微调时的权重变化 ΔW 具有低秩性'(微调主要在权重空间的少数方向上移动);故用 低秩分解 参数化增量:W' = W + (α/r)·BA,其中 B∈ℝ^d×r、A∈ℝ^r×k(r≪min(d,k)), 冻结 W 、只训练 A 与 B。 参数量 ——从 d×k 降到 r×(d+k);以 d=k=4096、r=8 为例,从 16.7M 降到 65K(降 256 倍);对整个模型可降 10⁴ 倍。 初始化 ——A 用随机高斯初始化、 B 初始化为 0 (使训练开始时 ΔW=0,模型行为与基座一致);这是保证'从基座出发'的关键。 超参 :(1) 秩 r ——控制表达力;r 大则增量空间更大(更接近全参微调)但参数更多;常用 8~64(简单任务 8、复杂/领域远任务 64~256)。(2) 缩放 α/r ——α 是缩放因子; 固定 α/r 的比例 可让'改变 r 时不必重调学习率'(α 通常设为 r 的 1~2 倍,如 α=16、r=8 得 α/r=2);若把 α/r 视为'有效学习率'的一部分,则固定它使超参可迁移。(3) 应用位置 ——(a) 只在 Q/K/V/O 投影(省参数);(b) 在所有线性层(覆盖更广、效果更好,QLoRA 论文建议);(c) 可对不同层用不同 r。(4) LoRA dropout ——对 LoRA 输入施加 dropout(防过拟合,小数据时有用)。(5) 学习率 ——LoRA 因参数少,可用 更大的学习率 (1e-4~2e-4,比全参高一个量级)。 优点 ——(a) 显存 (优化器状态只针对少量参数);(b) 存储 (适配器几十 MB,可多任务共存);(c) 无推理延迟 (可合并回 W);(d) 缓解灾难性遗忘 (基座冻结)。 局限 ——(a) 表达力受秩限制(极难任务可能不足);(b) 不改变基座知识(只能'引导');(c) 合并多适配器时有干扰。
- 深度剖析与工程权衡:① 'B 初始化为 0'是重要细节 ——它保证训练从'基座行为'开始(ΔW=0),避免随机初始化破坏预训练知识;漏掉这一点会显著损害效果。② '低秩性'的理论依据 ——Aghajanyan 等发现'微调的 intrinsic dimension 远小于参数量';但注意: 预训练 不能低秩(需充分探索),低秩性是 微调 的特性。③ 'α/r 固定比例'的实用价值 ——它使'调 r 不必重调 lr';这是实践中的便利约定(虽然严格来说 α/r 与 lr 的乘积才决定有效更新幅度)。④ '应用位置'的影响 ——研究表明 (a) 只加在注意力层已能获得大部分收益;(b) 加在 FFN 也能提升(覆盖更多);(c) QLoRA 建议'所有线性层'。故需按资源与效果权衡。⑤ 'LoRA lr 更大'的原因 ——参数量少 → 单步更新的'有效影响'小 → 需更大 lr 补偿;但过大则发散(需调)。⑥ 面试要点 ——被问'LoRA 的原理与超参',应给出' 低秩增量 W+BA + 冻结基座 + B 初始化为 0 + 秩 r 与缩放 α/r '与' 应用位置、lr 更大、可合并 ';能指出'低秩性是微调特性、预训练不能低秩'是深度理解的标志。
- 冻结 W,只训低秩 A、B(参数量降 10⁴ 倍)
- 秩 r:表达力(r 大则强);α/r:缩放(控制增量幅度)
- 应用位置:通常在 Q/K/V/O 投影;也有全线性层
常见陷阱
- B 用随机初始化(破坏基座行为)
- 改变 r 时不调整 α(α/r 比例失衡)