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.