66 / 90

第 66 天:適配器生命週期:獨立序列化、權重融合與零延遲部署

推理期權重折疊實現零延遲服務、反向折疊支撐多任務高速熱插拔,規範輕量增量資產交付。

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

權重融合(Merge)數學推導與零推理延遲部署方案

Agent 輔助工程檢查

前置要求

第 64-65 天 LoRA 數學模型與矩陣加法代數運算。

學習目標

推導並實現權重折疊融合公式 W_merged = W0 + (alpha/r)*B@A,將適配器增量無損注入基座權重,在生產推理階段徹底消除顯存讀取與核函數調度引入的額外延遲。

操作指引

1. 寫出未融合的前向:y = W0 @ x + b + (alpha/r) * B @ (A @ x)。部署時每層要多做兩次小矩陣乘法並多讀一次顯存。
2. 推導融合後的權重:W_merged = W0 + (alpha/r) * B @ A。檢查形狀:B @ A 為 (out, r) @ (r, in) = (out, in),與 W0 相同。
3. 用線性性證明等價:W_merged @ x = W0 @ x + (alpha/r) * B @ A @ x。
4. 用一個保護旗標實作 merge(),避免融合兩次時增量被加兩次,並讓 forward() 在融合後跳過適配器路徑。
5. 用隨機輸入比較融合前後的輸出。精確算術下二者相等;fp32 以不同順序對求和進行捨入,所以要測量最大差值並與 1e-6 目標比較。
6. 對 in = out = 4096、r = 16 計算節省的延遲:未融合路徑每層每個詞元額外增加的 FLOPs。

時間安排(120 分鐘):閱讀 25 + 練習 65 + 檢查 30。 閱讀:Hu et al. 第 4.1 節(不增加推理延遲)和 PEFT 的 merge_and_unload 文件。練習:第 1-6 步。檢查:憑記憶推導融合公式及其形狀。

自主實作與記錄

為手寫的 LoRALinear 編寫 merge() 方法。斷言對於任意隨機輸入 x,融合後的 self.linear(x) 輸出與融合前的 LoRA 輸出在 1e-6 浮點容差內嚴格一致。

獨立掌握標準

推導並落地權重折疊算法,用嚴格的機器浮點誤差驗證融合前後輸出的完全一致性。

權威來源資源與權利證明

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, paragraph 'No Additional Inference Latency' (store W = W0 + BA)

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

權重反融合(Unmerge)逆運算與多租戶適配器熱插拔切換

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

前置要求

第 66 天活動 1,張量可逆數學運算原理。

學習目標

編寫權重反折疊逆運算 W0 = W_merged - (alpha/r)*B@A,在單張 GPU 駐留的單一基座模型上實現多任務特化適配器(如醫療、法律、編程)的毫秒級動態熱插拔。

操作指引

1. 計算服務成本:十個獨立的 bf16 7B 模型需要 10 * 14 GB = 140 GB。一個共享的 14 GB 基座加十個適配器則少得多:在全部 7 個投影上取 r=16 為 39,976,960 個參數,bf16 下每個約 80 MB。
2. 將 unmerge() 實作為 merge() 的精確逆運算:用相同的 A、B 和縮放係數減去 (alpha/r) * B @ A,並加保護,避免對未融合的層再次反融合。
3. 執行切換循環:載入 Adapter_Medical,融合、推理、反融合;載入 Adapter_Legal,融合、推理、反融合。重複若干輪。
4. 每次反融合後,測量基座權重與原始 W0 的最大差值,並檢查它保持在 1e-6 之內。
5. 解釋為何漂移很小卻不總是零:在浮點中 (w0 + d) - d 不一定等於 w0。
6. 用 bf16 重複一輪並記錄漂移。總結在什麼情況下把適配器融合進將來要反融合的權重是不安全的。

時間安排(120 分鐘):閱讀 20 + 練習 70 + 檢查 30。 閱讀:PEFT 關於載入多個適配器並在其間切換的文件,以及活動 1 的筆記。練習:unmerge()、切換循環和 bf16 對比。檢查:不看筆記解釋漂移結果。

自主實作與記錄

構造熱插拔仿真測試:加載適配器 A -> 融合推理 -> 反融合 -> 校驗基座恢復至 W0 -> 切換加載適配器 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, paragraph 'No Additional Inference Latency' (store W = W0 + BA)

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

輕量級適配器獨立序列化標準與配置元數據(adapter_config)規範

Agent 輔助工程檢查

前置要求

第 66 天活動 1 與 2,JSON 及 Safetensors 序列化格式規範。

學習目標

規範適配器增量權重的輕量化序列化標準:剝離基座模型冗餘參數,獨立落盤包含 r, alpha, target_modules 的 adapter_config.json 與純適配器權重文件。

操作指引

1. 確定成果物結構:只有 adapter_model.safetensors 和 adapter_config.json。舊的匯出使用 adapter_model.bin(pickle);應使用 safetensors(Day 60)。
2. 在設定中寫入 r、lora_alpha、target_modules、lora_dropout 和 base_model_name_or_path。
3. 把狀態字典過濾為鍵名包含 'lora_' 的項,使凍結的基座權重不會進入檔案。
4. 編寫 save_adapter(model, path, ...) 和 load_adapter(model, path)。由於檔案刻意不含基座權重,用 strict=False 載入,然後斷言沒有遺漏任何適配器鍵,也沒有載入意外的鍵。
5. 測量目錄大小並與預測值比較:r * (in + out) 個值乘以 fp32 的 4 位元組。
6. 重新載入到新模型中,檢查其輸出與訓練好的模型一致。

時間安排(120 分鐘):閱讀 20 + 練習 70 + 檢查 30。 閱讀:PEFT 的 save_pretrained/from_pretrained 文件和 safetensors 格式說明。練習:兩個函數、大小檢查和重新載入檢查。檢查:預測 1024 x 1024 層在 r=8 時的檔案大小,再驗證。

自主實作與記錄

將訓練好的微調適配器保存至獨立目錄。檢查該目錄:斷言總大小嚴格小於 1MB,且 adapter_config.json 包含合規的結構字段。

獨立掌握標準

規範產出體積極小、元數據完備且與基座模型嚴格物理隔離的適配器發布包。

權威來源資源與權利證明

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.

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.

04 120 分鐘

考核評估:LoRA 訓練收斂、權重融合等價性與適配器獨立導出實戰

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

前置要求

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

學習目標

執行全流程綜合集成演練:在合成數據上微調 LoRA 適配器,獨立導出輕量成果物,加載至全新的基座模型,執行權重折疊,嚴格斷言 1e-6 容差內的輸出數值等價性。

操作指引

1. 重複使用已有部件:Day 64 的 LoRALinear、活動 1-2 的 merge() 和 unmerge(),以及活動 3 的 save_adapter/load_adapter。
2. 在合成資料上只訓練 lora_A 和 lora_B 15 步,並記錄每一步的損失。
3. 把適配器匯出到 'exported_adapter/'。
4. 建構一個基座權重相同的新模型,載入適配器,計算 y_unmerged = model(x)。
5. 呼叫 merge(),計算 y_merged = model(x)。
6. 斷言損失下降、融合後基座權重已變化、max(abs(y_unmerged - y_merged)) < 1e-5(fp32 融合會改變加法順序,因此容差取 1e-5),並且重新載入的模型重現了訓練好的模型。

時間安排(120 分鐘):閱讀 15 + 練習 75 + 檢查 30。 閱讀:活動 1-3 的筆記。練習:完整生命週期腳本。檢查:通過全部斷言的精熟執行,再在新進程中重跑一次。

自主實作與記錄

運行端到端 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.1, paragraph 'No Additional Inference Latency' (store W = W0 + BA)

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