65 / 90

第 65 天:LoRA 工程實現:基座權重凍結、梯度路由與顯存雪崩

確立基座模型凍結語義、追踪適配器反向梯度傳導,實證 AdamW 優化器顯存雪崩式縮減。

模型與預訓練 480 分鐘有效研習(8 小時)
01 120 分鐘

基座模型凍結語義規範與反向梯度傳播路徑物理隔離

Agent 輔助工程檢查

前置要求

第 64 天 LoRA 前向公式與 PyTorch 自動微分機制。

學習目標

透徹掌握 LoRA 訓練下的計算圖拓撲分支結構:探究基座權重為何不分配梯度內存,而適配器矩陣 A 與 B 能夠精準接收反向導數更新。

操作指引

1. 寫出含兩條路徑的前向:y = W0 @ x + (alpha/r) * B @ A @ x。第一條路徑只用凍結的 W0;第二條用可訓練的 A(r x d_in)和 B(d_out x r)。
2. 在前向之前用 requires_grad_(False) 凍結 W0。這樣 autograd 不會記錄通向 W0 的梯度邊,也不會分配 W0.grad。
3. 推導適配器梯度:dL/dB = (alpha/r) * (dL/dy) @ (A @ x)^T,dL/dA = (alpha/r) * B^T @ (dL/dy) @ x^T。注意形狀。
4. 預測第 0 步(B 初始化為零)會發生什麼:兩個梯度中哪一個恰好為零?
5. 執行一次反向傳播,斷言題目中的三個梯度事實,再檢驗第 4 步的預測。
6. 計算省下的梯度顯存:凍結參數數量 × 2 位元組(bf16)或 4 位元組(fp32)。

時間安排(120 分鐘):閱讀 25 + 練習 65 + 檢查 30。 閱讀:Hu et al. 第 4.1 節(LoRA 更新及其初始化)和 PEFT 的 LoRA 概念指南。練習:用參考模型完成第 1-6 步。檢查:不看筆記解釋為什麼第 0 步 lora_A.grad 為零。

自主實作與記錄

實例化包含凍結線性層與可學習 LoRA 適配器的模型,執行前向反向傳播。嚴密斷言 model.linear.weight.grad 嚴格為 None,而 lora_A.grad 與 lora_B.grad 為非空有效張量。

獨立掌握標準

能準確分析並斷言基座與適配器在自動求導圖中的物理隔離屬性。

權威來源資源與權利證明

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 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.

02 120 分鐘

優化器顯存雪崩式縮減:適配器訓練下 AdamW 狀態內存解構

獨立掌握檢查(無 AI 輔助)

前置要求

第 65 天活動 1 與第 56 天每參數 16 位元組 AdamW 顯存定律。

學習目標

數理推導 LoRA 下優化器狀態顯存的雪崩式驟降:從全量參數每參數 16 位元組(FP32 主權重、一階動量、二階方差),驟降至僅針對可訓練增量參數維護的工程實質。

操作指引

1. 回顧第 56 天的拆解:混合精度 AdamW 下,每個可訓練參數需要 16 位元組靜態訓練狀態:4 B fp32 主權重 + 4 B 一階動量 + 4 B 二階動量 + 4 B 梯度。
2. 7B 模型全量微調:7 * 10^9 * 16 位元組 = 112 GB(不含激活)。
3. 在 r=16、覆蓋全部 7 個線性投影的 LoRA 下訓練 39,976,960 個參數(約 40.0M,見第 64 天),優化器狀態為 39,976,960 * 16 位元組 ≈ 640 MB。
4. 這是約 99.4% 的優化器顯存削減。凍結的基座權重仍然需要:7B 的 bf16 約 14 GB,所以只有在小批次或量化基座(QLoRA)下才能放進單張 16 GB 或 24 GB 顯示卡。
5. 先以位元組完成題目計算,再換算為十進位單位(MB、GB)和二進位單位(MiB、GiB),並逐一標註。
6. 加上凍結基座來比較整體靜態顯存,而不只是優化器部分。

時間安排(120 分鐘):閱讀 25 + 練習 60 + 檢查 35。 閱讀:Dettmers et al.(QLoRA)第 2 節關於顯存的討論和第 56 天的 AdamW 拆解。練習:題目計算及 (b)(c)。檢查:獨立重做 (c) 並寫明每個單位。

自主實作與記錄

計算訓練一個 1B(10 億參數)模型在全量微調下,與採用 10M(1000 萬參數)LoRA 適配器訓練時,AdamW 優化器各自佔用的精確物理顯存(MB/GB)。(b) 在 LoRA 情形中加上以 bf16 儲存的凍結 1B 基座,與全量微調比較整體靜態顯存。(c) 將同一規則用於含 39,976,960 個可訓練參數的 7B 全線性適配器,以 MB 和 MiB 給出結果。

獨立掌握標準

熟練運用 16 位元組定律,嚴謹測算出 LoRA 帶來得多 GB 級顯存釋放效益。

權威來源資源與權利證明

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.

03 120 分鐘

適配目標模組選型策略:注意力投影層與前饋網絡全覆蓋權衡

Agent 輔助工程檢查

前置要求

第 65 天活動 1 與 2,Transformer 核心網絡拓撲結構。

學習目標

系統權衡適配目標模組覆蓋範式:深入對比原論文僅適配 Wq, Wv 與當代工業界全面適配所有線性層(Wq, Wk, Wv, Wo, Gate, Up, Down)的泛化表現與算力成本差異。

操作指引

1. 從歷史講起:Hu et al. 為了控制參數預算,只在 Wq 和 Wv 上做適配。
2. 閱讀後來的證據:QLoRA(Dettmers et al. 2023)發現,即使在 r=8 或 16 這樣的低秩下,也需要適配所有線性層(注意力和 MLP)才能追平全量微調。
3. 編寫 count_target_params(model, targets, rank):對名稱最後一段在目標集合中的每個 nn.Linear,累加 rank * (in_features + out_features)。按整段比對,而不是子字串。
4. 在 meta 裝置上建構 LLaMA-7B 的形狀(d=4096,MLP 寬度 11008,32 層)進行測試,不分配任何顯存。
5. 比較兩種配置:target_modules=['q_proj', 'v_proj'] 與全部七個投影('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj')。全部七個使適配器參數約為 4.8 倍(r=16 時為 39,976,960 對 8,388,608),但仍低於基座的 1%。
6. 檢查數量與秩成正比:r 加倍,數量也加倍。

時間安排(120 分鐘):閱讀 25 + 練習 65 + 檢查 30。 閱讀:Hu et al. 第 7.1 節(應適配哪些權重矩陣)、QLoRA 第 4 節和 PEFT 的 target_modules 文件。練習:輔助函數及其三項檢查。檢查:手算每層的數量並與腳本對照。

自主實作與記錄

編寫參數審計輔助函數 count_target_params(model, target_module_names, rank),動態統計選定投影層集合下的可訓練參數總量。

獨立掌握標準

能夠根據任務複雜度和顯存天花板,科學決策適配模組覆蓋矩陣並精確測算增量。

權威來源資源與權利證明

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 7.1 Which Weight Matrices in Transformer Should We Apply LoRA To?

驗證版本與日期: 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.

04 120 分鐘

考核評估:基座凍結性與適配器求導更新全自動化單元測試

獨立掌握檢查(無 AI 輔助)

前置要求

第 65 天活動 1 至 3 全部內容。

學習目標

構建完整的自動化單元測試套件,嚴密驗證基座權重零篡改、優化器僅註冊適配器張量,且在 10 步微調訓練中 Loss 正常收斂下降。

操作指引

1. 建構一個小模型,包含凍結的嵌入、凍結的輸出層 W0(model.linear)以及可訓練的 LoRA 矩陣 lora_A 和 lora_B。
2. 訓練前保存 W0、lora_A 和 lora_B 的分離複本。
3. 只把 requires_grad=True 的參數交給 AdamW。
4. 在一個玩具下一詞元批次上訓練 10 步(輸入為 tokens[:, :-1],目標為 tokens[:, 1:]),並記錄每一步的損失。
5. 斷言四個性質:W0.grad 為 None;W0 與其複本逐位元相等(用 torch.equal,而不是 allclose);lora_A 和 lora_B 已改變且損失下降;優化器恰好只持有 lora_A 和 lora_B。
6. 變異檢查:刪除一次凍結那一行,確認前兩個斷言此時失敗。仍然通過的測試並沒有在測試凍結。

時間安排(120 分鐘):閱讀 15 + 練習 75 + 檢查 30。 閱讀:活動 1 的筆記以及 PEFT 關於可訓練參數的除錯說明。練習:測試套件和變異檢查。檢查:通過全部斷言的精熟執行。

自主實作與記錄

運行基座凍結與梯度路由測試套件,確認基座權重未發生任何位變動,適配器順利更新收斂。

獨立掌握標準

編寫出能夠 100% 證實基座零變異且適配器收斂更新的工程級單元測試套件。

權威來源資源與權利證明

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 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.