65 / 90

第65日: LoRAの工学: 重み凍結、勾配ルーティングとオプティマイザメモリの激減

基座モデルの厳格な凍結、アダプタ行列の勾配逆伝播追跡、AdamWオプティマイザメモリ削減の検証。

モデルと事前学習 480 分(8時間)
01 120 分

ベースモデル凍結セマンティクスと勾配伝播経路の完全分離

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 で検証してください。

独立習得基準

基座凍結とアダプタへの勾配ルーティングの完全性を実証できる。

公式ソースリソースと権利証跡

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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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日AdamW 16バイト則。

学習目標

AdamWオプティマイザの状態メモリが元パラメータあたり16バイトから、アダプタパラメータのみの16バイトへと数千分の一に縮小する数理を解析する。

手順

1. 第 56 日の内訳を思い出す:混合精度の AdamW では、学習可能なパラメータ 1 個ごとに 16 バイトの静的な訓練状態が必要である:fp32 マスター重み 4 B + 1 次モーメント 4 B + 2 次モーメント 4 B + 勾配 4 B。
2. 7B モデルの全量微調:7 * 10^9 * 16 バイト = 112 GB(活性化を除く)。
3. ランク r=16 で 7 つの線形射影すべてに LoRA を適用すると 39,976,960 パラメータ(約 40.0M、Day 64)を学習するので、オプティマイザ状態は 39,976,960 * 16 バイト ≈ 640 MB。
4. これはオプティマイザメモリの約 99.4% 削減である。凍結したベースの重みは依然として必要で、7B の bf16 では約 14 GB になる。そのため 16 GB や 24 GB の単一 GPU に収まるのは、小さなバッチか量子化したベース(QLoRA)の場合だけである。
5. 問題の計算をまずバイトで行い、次に 10 進単位(MB、GB)と 2 進単位(MiB、GiB)の両方に換算して、それぞれに単位を付ける。
6. オプティマイザ部分だけでなく、凍結ベースを加えた静的メモリ全体を比べる。

時間配分(120 分):読解 25 + 演習 60 + 確認 35。 読解:Dettmers et al.(QLoRA)2 節のメモリの議論と第 56 日の AdamW 内訳。演習:問題の計算と項目 (b)(c)。確認:項目 (c) を補助なしでやり直し、すべての単位を明記する。

演習と予測記録

1Bパラメータの全量微調と、10MパラメータのLoRA適用時におけるAdamWオプティマイザのVRAM使用量(MB/GB)を算出し比較してください。(b) LoRA の場合に bf16 で保存した凍結 1B ベースを加え、全量微調と静的メモリ全体を比べてください。(c) 同じ規則を、学習可能パラメータ 39,976,960 個の 7B 全線形アダプタに当てはめ、MB と MiB で答えてください。

独立習得基準

AdamWのメモリ消費量が激減する数理的根拠を正確に計算・説明できる。

公式ソースリソースと権利証跡

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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 分

対象モジュールの選定方針: アテンション射影層とMLP層のトレードオフ

Agent支援エンジニアリングチェック

前提条件

第65日アクティビティ1〜2およびTransformerブロック構造。

学習目標

対象モジュールの適応におけるトレードオフを評価します。Wq, Wv のみ(Hu et al. 2021)に適応させる場合と、すべての線形射影(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. 2 つの構成を比べる:target_modules=['q_proj', 'v_proj'] と 7 つの射影すべて('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj')。7 つすべてではアダプタのパラメータ数が約 4.8 倍になる(r=16 で 39,976,960 対 8,388,608)が、それでもベースの 1% 未満である。
6. 数がランクに比例することを確かめる:r を 2 倍にすると数も 2 倍になる。

時間配分(120 分):読解 25 + 演習 65 + 確認 30。 読解:Hu et al. 7.1 節(どの重み行列に適応させるか)、QLoRA 4 節、PEFT の target_modules のドキュメント。演習:補助関数とその 3 つの確認。確認:1 層あたりの数を手で計算し、スクリプトと比べる。

演習と予測記録

指定された対象モジュール名リストに基づき、訓練可能パラメータ総数を動的に計算する count_target_params 関数を実装してください。

独立習得基準

対象モジュールの選定方針とパラメータ規模のトレードオフを正確に評価できる。

公式ソースリソースと権利証跡

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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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ステップの学習で損失が低下することを検証する単体テストを構築する。

手順

1. 凍結した埋め込み、凍結した出力層 W0(model.linear)、学習可能な LoRA 行列 lora_A と lora_B を持つ小さなモデルを作る。
2. 訓練の前に、W0、lora_A、lora_B の切り離したクローンを保存する。
3. AdamW には requires_grad=True のパラメータだけを渡す。
4. 簡易な次トークンのバッチ(入力は tokens[:, :-1]、目標は tokens[:, 1:])で 10 ステップ訓練し、各ステップの損失を記録する。
5. 4 つの性質を assert する:W0.grad は None。W0 はクローンとビット単位で一致する(allclose ではなく torch.equal)。lora_A と lora_B が変化し、損失が減少した。オプティマイザが持つのはちょうど lora_A と lora_B である。
6. 変異チェック:凍結の行を一度削除し、最初の 2 つの assert が失敗することを確かめる。それでも通るテストは凍結をテストしていない。

時間配分(120 分):読解 15 + 演習 75 + 確認 30。 読解:活動 1 のノートと、学習可能パラメータに関する PEFT のトラブルシューティング。演習:テストスイートと変異チェック。確認:すべての assert が通る習熟実行。

演習と予測記録

凍結検証テストスイートを実行し、基座モデルの不変性とアダプタの正常な学習収束を確認してください。

独立習得基準

基座重みの不変性とアダプタの勾配更新を厳密な単体テストで証明できる。

公式ソースリソースと権利証跡

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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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.