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.