重み融合(マージ)の数理とゼロ遅延推論デプロイの実現
Agent支援エンジニアリングチェック
前提条件
第64〜65日LoRA数学および行列加算の基本。
学習目標
W_merged = W0 + (alpha/r)*BA による重みマージを定式化・実装し、推論時の分岐カーネルを消去して完全なゼロ遅延デプロイを達成する。
手順
1. マージ前の順伝播を書く:y = W0 @ x + b + (alpha/r) * B @ (A @ x)。これを提供すると、層ごとに小さな行列積が 2 つとメモリ読み込みが余分にかかる。
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. 2 回マージしても差分が 2 回加わらないよう、ガードのフラグ付きで 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() メソッドを実装し、マージ後の線形層の出力がマージ前の出力と許容誤差 1e-6 内で完全一致することを検証してください。
delta = (self.alpha / self.r) * torch.matmul(self.lora_B, self.lora_A); self.linear.weight.data.add_(delta)。
def merge(self):
# Fold the adapter into the base weight: W_merged = W0 + (alpha / r) * B @ A.
# B @ A has shape (out, r) @ (r, in) = (out, in), the same shape as linear.weight.
if not self.merged: # guard: merging twice would add the delta twice
delta = (self.alpha / self.r) * torch.matmul(self.lora_B, self.lora_A)
self.linear.weight.data.add_(delta)
self.merged = True # forward() now skips the adapter path
def check_merge(layer, x, atol=1e-5):
# Worked check. Before: y = W0 x + b + s * B (A x). After: y = (W0 + s B A) x + b.
# Matrix products are linear, so the two are equal in exact arithmetic; fp32 rounds the
# sums in a different order, so compare with a tolerance (about 1e-6 for small layers).
y_before = layer(x)
layer.merge()
y_after = layer(x)
return (y_after - y_before).abs().max().item() < atol
# Latency: the merged layer is one GEMM, exactly like the base model, so serving cost is
# unchanged. Example: in=out=4096, r=16 adds 2 * 16 * (4096 + 4096) = 262,144 FLOPs per token
# per layer when unmerged; merged, the extra cost is zero.
重み融合処理を実装し、マージ前後での数値的等価性を単体テストで証明できる。
公式ソースリソースと権利証跡
LoRA: Low-Rank Adaptation of Large Language Models
該当セクション・タイムスタンプ: 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.
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.