64 / 90

第 64 天:LoRA 数学原理:低秩矩阵分解与缩放因子推导

数学推导低秩更新公式 W = W0 + (alpha/r)*BA、剖析初始化动力学并精确核算可训练参数账本。

模型与预训练 480 分钟有效研习(8 小时)
01 120 分钟

内在维度假说与低秩矩阵分解数学机理

Agent 辅助工程检查

前置要求

第 48 天线性层与矩阵乘法代数基础。

学习目标

透彻理解内在维度假说(Intrinsic Dimensionality),将全量微调增量 Delta W 精确因子化为低秩分解式 Delta W = (alpha/r) * B @ A,其中 r << min(d, k)。

操作指引

1. 研读 Aghajanyan 等人(2020)内在维度理论:超参数化大模型在特定下游任务微调时,其有效参数变化实质收敛于极低维度的子空间。
2. 传统全量微调更新为 W = W0 + Delta W,Delta W 为全秩实数矩阵 R^{d x k},更新开销随维度呈二次方膨胀。
3. LoRA(Hu 等人 2021)将增量约束为两个低秩小矩阵相乘:B in R^{d x r},A in R^{r x k},秩 r 通常取 4, 8, 16 即可满足需求。
4. 当 d=4096, k=4096, r=8 时:全量权重需 16,777,216 参数,而 LoRA 仅需 8*(4096+4096) = 65,536 参数,压缩率高达 99.6%。

自主演练与记录

给定输入维度 d_in=1024,输出维度 d_out=2048 的线性层。计算全量矩阵 W0 与秩 r=8 的 LoRA 矩阵 A、B 的参数量,并求出参数削减百分比。

独立掌握标准

能准确写出低秩矩阵因子化公式并推算任意维度下的参数削减账目。

权威源资源与权利证明

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

作者 / 机构: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | 原始出处链接 ↗

对应章节 / 时间戳: Section 4.1 Low-Rank-Parametrized Update Matrices; Section 7.2 What Is the Optimal Rank r for LoRA?

验证版本与日期: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

入选理由:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

来源前置条件:

Matrix factorization, rank, linear layers, and transformer attention.

安全回退方案(离线弹性):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

对比候选资源与选型分析 (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Open Access / CC BY 4.0

Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning

作者 / 机构: Armen Aghajanyan, Luke Zettlemoyer, Sonal Gupta | 原始出处链接 ↗

对应章节 / 时间戳: Section 3 Intrinsic Dimensionality of Finetuning

验证版本与日期: ACL 2021 / arXiv:2012.13255v1 (Verified: 2026-10-30)

入选理由:

Key theoretical foundation demonstrating that overparameterized pre-trained language models reside on a low-dimensional manifold, proving why low rank r (e.g. 4 to 16) is sufficient for task adaptation.

来源前置条件:

Linear algebra, matrix subspace projection, and pretraining representations.

安全回退方案(离线弹性):

The intrinsic dimensionality concept, subspace projections, and parameter reduction trade-offs are fully explained in lesson text.

对比候选资源与选型分析 (2)

General neural network optimization landscapes; Aghajanyan focuses explicitly on foundation language models.

Measures how low-rank LoRA trades target-domain learning for less forgetting; Aghajanyan provides the direct theoretical motivation for LoRA's low-rank assumption.

02 120 分钟

适配器初始化动力学与 Alpha/Rank 缩放因子推导

独立掌握检查(无 AI 辅助)

前置要求

第 64 天活动 1 与高斯随机分布基础。

学习目标

区分 LoRA 论文对 A 的高斯初始化(未指定方差)与本课程实现采用的 Kaiming 均匀初始化。说明为什么 B = 0 可使初始 Delta W = 0,并解释 alpha/r 缩放的作用。

操作指引

1. 审查初始化。LoRA 论文(Section 4.1)对 A 使用随机高斯初始化(未给出方差),对 B 使用零初始化。本课程讲授的代码(act-04,projects/lora/model.py)遵循 microsoft/LoRA 与 Hugging Face PEFT 的默认设置(init_lora_weights=True):A 使用与 nn.Linear 默认相同的 nn.init.kaiming_uniform_(A, a=math.sqrt(5)),B = 0(所有元素严格为零)。PEFT 的 init_lora_weights="gaussian" 选项则从标准差为 1/r 的正态分布中采样 A。无论哪种方式,B 都为 0。
2. 洞悉 B=0 的工程哲学:在训练第 0 步,Delta W = (alpha/r) * B @ A = 0,模型前向行为与冻结基座 100% 相同,避免未经训练的随机扰动破坏预训练常识。
3. 剖析缩放因子 alpha / r:固定超参 alpha(通常设为 16 或 32),当探索不同秩 r 时,自动保持梯度更新的有效尺度,使学习率无需因秩变动而剧烈重调。
4. 前向计算优先级技巧:y = W0 @ x + (alpha / r) * (B @ (A @ x))。先算 A @ x,每个词元代价为 O(r * k),再算 B @ (A @ x),代价为 O(d * r);因此 b * s 个词元的批次总代价为 O(b * s * r * (d + k)),前向过程中严禁先求 d x k 的大增量矩阵。

自主演练与记录

编写手写 LoRA 前向传播函数 lora_forward(x, W0, A, B, alpha, r)。在 B=0 的初始化条件下,用 torch.equal 验证 lora_forward(x, W0, A, B, alpha, r) 与 x @ W0.T 完全相等。

独立掌握标准

从数学与工程代码双重维度证实 step 0 恒等成立,并准确运用结合律降低计算复杂度。

权威源资源与权利证明

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

作者 / 机构: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | 原始出处链接 ↗

对应章节 / 时间戳: Section 4.1 Low-Rank-Parametrized Update Matrices (W0 + BA, B initialized to zero, scaling by alpha/r)

验证版本与日期: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

入选理由:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

来源前置条件:

Matrix factorization, rank, linear layers, and transformer attention.

安全回退方案(离线弹性):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

对比候选资源与选型分析 (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Apache-2.0

PEFT: State-of-the-art Parameter-Efficient Fine-Tuning Methods

作者 / 机构: Sourab Mangrulkar, Sylvain Gugger, Lysandre Debut, Younes Belkada, Sayak Paul, Benjamin Bossan | 原始出处链接 ↗

对应章节 / 时间戳: README 'Quickstart' (LoraConfig, get_peft_model, print_trainable_parameters)

验证版本与日期: PEFT 0.10.x / GitHub (Verified: 2026-10-30)

入选理由:

Widely adopted open-source library implementing LoRA configuration classes (LoraConfig), get_peft_model, and adapter serialization.

来源前置条件:

PyTorch nn.Module, Hugging Face transformers, and LoRA equations.

安全回退方案(离线弹性):

Standalone, zero-dependency PyTorch implementations of LoRALinear layers and save/reload logic are provided in curriculum scripts.

对比候选资源与选型分析 (2)

Original reference code by Hu et al.; PEFT expands this to broader multi-model ecosystem integration.

Lit-GPT LoRA implementation (Lightning AI) ↗ compared_alternative [Apache 2.0]

High-performance clean implementation; compared alongside PEFT for modular code architecture.

03 120 分钟

可训练参数核算账本与理论显存削减幅度测算

Agent 辅助工程检查

前置要求

第 64 天活动 1 与 2,第 56 天参数算力核算公式。

学习目标

构建跨 Transformer 全层的精确适配器参数账本,严谨界定标准 FP16/BF16 LoRA 与 4-bit 量化 QLoRA 的数学与工程界限。

操作指引

1. 推导目标模块下的参数精确统计公式:
- 仅针对注意力 Wq, Wv(每层 2 个矩阵):N_lora = n_layer * 2 * r * (d + d) = 4 * n_layer * r * d。
- 针对全部线性层(Wq, Wk, Wv, Wo, Gate, Up, Down - 7 个矩阵):N_lora = n_layer * r * sum(d_in + d_out)。
2. 以典型 7B 模型(d=4096,MLP 宽度 11008,32 层)为例,在 r=16 下适配全部 7 个线性投影:每层 4 * 16 * (4096 + 4096) + 3 * 16 * (4096 + 11008) = 1,249,280,总适配器参数量 = 32 * 1,249,280 = 39,976,960(约 40.0M,约占基座的 0.6%)。
3. 严禁混淆概念:标准 LoRA 的基座权重维持原生的 FP16/BF16 浮点格式;而 QLoRA(Dettmers 等人 2023)将基座权重量化为 4-bit NormalFloat(NF4),并结合量化常数的双重量化(double quantization)与分页优化器。没有真实 4-bit 量化证据严禁滥用 QLoRA 标签。
4. 测算检查点磁盘体积:FP16 全量权重 7e9 * 2 字节 = 14 GB,适配器检查点 39,976,960 * 2 字节 ≈ 80 MB。

自主演练与记录

对于一个 8 层、隐层维度 d=512 的模型,仅在 Wq 和 Wv 上配置秩 r=8 的 LoRA。计算可训练参数总数及在 FP16 精度下的权重文件体积(KB)。

独立掌握标准

能准确给出任意架构下 LoRA 适配参数账本,并坚守技术概念严密性。

权威源资源与权利证明

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

作者 / 机构: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | 原始出处链接 ↗

对应章节 / 时间戳: Section 4.2 Applying LoRA to Transformer (frozen W0, VRAM and checkpoint-size reduction)

验证版本与日期: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

入选理由:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

来源前置条件:

Matrix factorization, rank, linear layers, and transformer attention.

安全回退方案(离线弹性):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

对比候选资源与选型分析 (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Open Access / CC BY 4.0

QLoRA: Efficient Finetuning of Quantized LLMs

作者 / 机构: Tim Dettmers, Artidoro Pagnoni, Ari Holtzman, Luke Zettlemoyer | 原始出处链接 ↗

对应章节 / 时间戳: Section 3 QLoRA Finetuning and Appendix G Memory Footprint

验证版本与日期: NeurIPS 2023 / arXiv:2305.14314v1 (Verified: 2026-10-30)

入选理由:

Primary paper cited to clearly distinguish pure unquantized FP16/BF16 LoRA from 4-bit quantized QLoRA with paged optimizers, preventing misleading terminology conflation.

来源前置条件:

Quantization (NF4/FP4), double quantization, and standard LoRA.

安全回退方案(离线弹性):

The mathematical distinction between LoRA adapter updates and 4-bit base weight dequantization is explicitly detailed in curriculum comparisons.

对比候选资源与选型分析 (2)

Post-training quantization only; QLoRA combines backpropagation through quantized weights with LoRA adapters.

Inference quantization; Dettmers QLoRA focuses specifically on parameter-efficient fine-tuning memory reduction.

04 120 分钟

考核评估:纯 PyTorch LoRALinear 模块手写与初始化恒等性验证

独立掌握检查(无 AI 辅助)

前置要求

第 64 天活动 1 至 3 全部内容。

学习目标

零依赖任何外部 PEFT 库,在纯 PyTorch 下手写工程级 LoRALinear(nn.Module),验证前向传播精度、缩放系数及 step 0 恒等保真特性。

操作指引

1. 继承 nn.Module 编写 LoRALinear(in_features, out_features, r=8, lora_alpha=16) 模块。
2. 内置 nn.Linear 作为基座投影层,并调用 self.linear.requires_grad_(False) 同时冻结权重 W0 与偏置。
3. 定义可学习参数 self.lora_A (r, in_features) 与 self.lora_B (out_features, r)。
4. 严谨初始化:lora_A 采用 Kaiming uniform 初始化,lora_B 严格填充全零。
5. 实现 forward(x) 函数:base = self.linear(x); lora = self.scaling * (x @ self.lora_A.T @ self.lora_B.T)(其中 self.scaling = lora_alpha / r); return base + lora。
6. 编写断言测试:输入任意随机张量 x,确认输出张量与 self.linear(x) 的最大绝对误差严格为 0.0。

自主演练与记录

运行针对 LoRALinear 的单元测试套件。核验参数量符合预期,且在初始化状态下与未修改线性层达成机器级精度一致。

独立掌握标准

独立手写出结构清晰且通过 100% 恒等性断言的纯 PyTorch LoRALinear 模块。

权威源资源与权利证明

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

作者 / 机构: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | 原始出处链接 ↗

对应章节 / 时间戳: Section 4.1 Low-Rank-Parametrized Update Matrices (W0 + BA, B initialized to zero, scaling by alpha/r)

验证版本与日期: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

入选理由:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

来源前置条件:

Matrix factorization, rank, linear layers, and transformer attention.

安全回退方案(离线弹性):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

对比候选资源与选型分析 (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Apache-2.0

PEFT: State-of-the-art Parameter-Efficient Fine-Tuning Methods

作者 / 机构: Sourab Mangrulkar, Sylvain Gugger, Lysandre Debut, Younes Belkada, Sayak Paul, Benjamin Bossan | 原始出处链接 ↗

对应章节 / 时间戳: README 'Quickstart' (LoraConfig, get_peft_model, print_trainable_parameters)

验证版本与日期: PEFT 0.10.x / GitHub (Verified: 2026-10-30)

入选理由:

Widely adopted open-source library implementing LoRA configuration classes (LoraConfig), get_peft_model, and adapter serialization.

来源前置条件:

PyTorch nn.Module, Hugging Face transformers, and LoRA equations.

安全回退方案(离线弹性):

Standalone, zero-dependency PyTorch implementations of LoRALinear layers and save/reload logic are provided in curriculum scripts.

对比候选资源与选型分析 (2)

Original reference code by Hu et al.; PEFT expands this to broader multi-model ecosystem integration.

Lit-GPT LoRA implementation (Lightning AI) ↗ compared_alternative [Apache 2.0]

High-performance clean implementation; compared alongside PEFT for modular code architecture.