ベースモデル凍結セマンティクスと勾配伝播経路の完全分離
Agent支援エンジニアリングチェック
前提条件
第64日LoRA順伝播式およびPyTorch autogradの基本。
学習目標
LoRA学習時の計算グラフ分岐を理解し、元重みへの勾配計算を遮断しつつアダプタ行列のみに正確に逆伝播が流れる仕組みを解明する。
手順
1. 2 つの経路を持つ順伝播を書く:y = W0 @ x + (alpha/r) * B @ A @ x。1 つ目の経路は凍結した W0 だけを使い、2 つ目は学習可能な 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. B がゼロで初期化されているステップ 0 で何が起きるか予測する:2 つの勾配のうちどちらがちょうどゼロになるか。
5. 逆伝播を 1 回実行し、問題にある 3 つの勾配の事実を assert で確かめ、次に手順 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 が None ではないテンソルであることを assert で検証してください。
assert param.grad is None を基座パラメータに対して検証します。
import torch
import torch.nn as nn
class TinyLoRA(nn.Module):
def __init__(self, d_in=8, d_out=4, r=2, alpha=4):
super().__init__()
self.linear = nn.Linear(d_in, d_out, bias=False)
self.linear.weight.requires_grad_(False) # freeze W0
self.lora_A = nn.Parameter(torch.randn(r, d_in) * 0.01)
self.lora_B = nn.Parameter(torch.zeros(d_out, r)) # B = 0, so the adapter starts as a no-op
self.scale = alpha / r
def forward(self, x):
return self.linear(x) + self.scale * (x @ self.lora_A.T @ self.lora_B.T)
torch.manual_seed(0)
model = TinyLoRA()
x, target = torch.randn(5, 8), torch.randn(5, 4)
loss = nn.functional.mse_loss(model(x), target)
loss.backward()
assert model.linear.weight.grad is None # no .grad buffer was ever allocated
assert model.lora_A.grad is not None
assert model.lora_B.grad is not None
# Surprise worth recording: at step 0, dL/dA = scale * B.T @ dL/dy @ x is exactly zero because
# B = 0, while dL/dB = scale * dL/dy.T @ (x @ A.T) is not. A receives signal only after B moves.
assert torch.count_nonzero(model.lora_A.grad) == 0
assert torch.count_nonzero(model.lora_B.grad) > 0
trainable = [n for n, p in model.named_parameters() if p.requires_grad]
frozen = sum(p.numel() for p in model.parameters() if not p.requires_grad)
print(trainable, frozen) # ['lora_A', 'lora_B'] 32
# Saving: 32 frozen weights x 4 bytes = 128 bytes of fp32 gradient that is never allocated;
# for a 7B base in bf16 the same rule saves 7e9 x 2 bytes = 14 GB.
基座凍結とアダプタへの勾配ルーティングの完全性を実証できる。
公式ソースリソースと権利証跡
LoRA: Low-Rank Adaptation of Large Language Models
該当セクション・タイムスタンプ: 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.
PEFT: State-of-the-art Parameter-Efficient Fine-Tuning Methods
該当セクション・タイムスタンプ: 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.
High-performance clean implementation; compared alongside PEFT for modular code architecture.