64 / 90

第64日: LoRAの数学: 低ランク行列分解とスケーリング係数

低ランク更新式 W = W0 + (alpha/r)*BA の導出、初期化の動特性解析、訓練可能パラメータの厳密な算定。

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

内在次元仮説と低ランク行列分解の数理

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

前提条件

第48日線形層および行列積の基礎知識。

学習目標

内在次元仮説を理解し、パラメータ更新を Delta W = (alpha/r) * B @ A として表現する(ただし r << min(d, k))。

手順

1. Aghajanyan et al. (2020) の論文を精読します: 過剰パラメータ化された大規模言語モデルは、下流タスクへの適応時に驚くほど低い内在次元を持ちます。
2. 標準的な全量微調では W = W0 + Delta W とし、Delta W は R^{d x k} に属します(フルランク、d*k 個のパラメータを必要とします)。
3. LoRA(Hu et al. 2021)では、Delta W = B @ A と因数分解します。ここで B は R^{d x r}、A は R^{r x k} に属し、ランク r は通常 4、8、16 です。
4. d=4096, k=4096, r=8 の場合、全量微調では 16,777,216 個のパラメータが必要ですが、LoRA では 8*(4096+4096) = 65,536 個のパラメータのみで済むことに注意してください。

演習と予測記録

入力次元1024、出力次元2048の線形層において、全結合重みとランクr=8の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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 4.1 Low-Rank-Parametrized Update Matrices; Section 7.2 What Is the Optimal Rank r for LoRA?

検証バージョンと日付: 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

Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning

著者・提供機関: Armen Aghajanyan, Luke Zettlemoyer, Sonal Gupta | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 3 Intrinsic Dimensionality of Finetuning

検証バージョンと日付: ACL 2021 / arXiv:2012.13255v1 (Verified: 2026-10-30)

選定理由:

Key theoretical foundation demonstrating that overparameterized pre-trained language models reside on a low-dimensional manifold, proving why low rank r (e.g. 4 to 16) is sufficient for task adaptation.

ソース前提知識:

Linear algebra, matrix subspace projection, and pretraining representations.

安全フォールバック(オフライン回復性):

The intrinsic dimensionality concept, subspace projections, and parameter reduction trade-offs are fully explained in lesson text.

比較対象候補リソースと選定評価 (2)

General neural network optimization landscapes; Aghajanyan focuses explicitly on foundation language models.

Measures how low-rank LoRA trades target-domain learning for less forgetting; Aghajanyan provides the direct theoretical motivation for LoRA's low-rank assumption.

02 120 分

アダプタ初期化ダイナミクスと alpha/rank スケーリング係数

独立習得チェック(AI 支援なし)

前提条件

第64日アクティビティ1および正規分布の確率的特性。

学習目標

LoRA論文のAのガウス初期化(分散は未指定)と、本コースの実装のKaiming一様初期化を区別する。B = 0 によって初期の Delta W = 0 が成り立つ理由と、alpha/r スケーリングの役割を説明する。

手順

1. 初期化を確認します。LoRA論文(Section 4.1)はAをランダムなガウス分布(分散は明記されていない)で、Bをゼロで初期化します。本コースで扱うコード(act-04、projects/lora/model.py)はmicrosoft/LoRAとHugging Face PEFTの既定値(init_lora_weights=True)に従い、Aをnn.Linearの既定と同じ nn.init.kaiming_uniform_(A, a=math.sqrt(5)) で、Bを全要素ゼロで初期化します。PEFTの init_lora_weights="gaussian" オプションでは、Aを標準偏差 1/r の正規分布から生成します。どの方式でも B = 0 です。
2. B = 0 が重要な理由に注目します: ステップ 0 では Delta W = (alpha/r) * 0 * A = 0 となるため、モデルはランダムな劣化なしに、事前学習済みベースモデルと厳密に同じ振る舞いから始まります。
3. スケーリング定数 alpha / r を分析します: 固定の alpha(例: 16 または 32)がアダプタの出力をスケールします。異なるランク r を試す際も、このスケーリングによって学習率を大幅に再調整する必要がなくなります。
4. 順伝播の式を書け: y = W0 @ x + (alpha / r) * (B @ (A @ x))。演算順序に注意する: 先に A @ x を計算するとトークンあたり O(r * k)、続く B @ (A @ x) は O(d * r) なので、b * s 個のトークンからなるバッチ全体では O(b * s * r * (d + k)) となり、大きな d x k 行列を順伝播中に作らずに済む。

演習と予測記録

純粋な Python で順伝播関数 lora_forward(x, W0, A, B, alpha, r) を書け。B=0 の初期化状態で、lora_forward(x, W0, A, B, alpha, r) が x @ W0.T と完全に一致することを torch.equal で確認せよ。

独立習得基準

初期化時の恒等性保証とスケーリング係数 alpha/r の数理的意義を説明・検証できる。

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

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.1 Low-Rank-Parametrized Update Matrices (W0 + BA, B initialized to zero, scaling by alpha/r)

検証バージョンと日付: 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.

03 120 分

訓練可能パラメータ台帳と理論的メモリ削減効果の算出

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

前提条件

第64日アクティビティ1〜2および第56日パラメータ算術。

学習目標

Transformer各層におけるLoRAパラメータ台帳を作成し、純粋なFP16 LoRAと4bit QLoRAの概念的境界を厳格に識別する。

手順

1. 対象モジュールごとのアダプタのパラメータ数を正確に定式化します:
- Wq と Wv を対象とする場合(各層 2 行列): N_lora = n_layer * 2 * r * (d + d) = 4 * n_layer * r * d。
- すべての線形射影(Wq, Wk, Wv, Wo, Gate, Up, Down の 7 行列)を対象とする場合: N_lora = n_layer * r * sum(d_in + d_out)。
2. 7B モデル(d=4096、MLP 幅 11008、32 層)で 7 つの線形射影すべてを r=16 で適応する場合のパラメータ比を計算せよ: 1 層あたり 4 * 16 * (4096 + 4096) + 3 * 16 * (4096 + 11008) = 1,249,280 なので、LoRA パラメータ総数は 32 * 1,249,280 = 39,976,960(約 40.0M、ベースモデルの約 0.6%)。
3. 用語の境界を明確にせよ: 標準の LoRA はベースモデルの重みを FP16 または BF16 のまま保持する。QLoRA(Dettmers et al. 2023)はベース重みを 4-bit NormalFloat(NF4)に量子化し、量子化定数の二重量子化(double quantization)とページドオプティマイザを併用する。実際の 4-bit 量子化の証拠なしに、純粋な LoRA を QLoRA と呼んではならない。
4. チェックポイント容量の削減を計算せよ: FP16 のフルチェックポイント = 7e9 * 2 bytes = 14 GB、LoRA アダプタのチェックポイント = 39,976,960 * 2 bytes = 約 80 MB。

演習と予測記録

層数8、d=512、WqとWvにランクr=8でLoRAを適用した際の全訓練可能パラメータ数とFP16でのファイル容量(KB)を計算してください。

独立習得基準

対象モジュール構成に応じたパラメータ数とファイルサイズを正確に算出できる。

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

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.

04 120 分

評価課題: 純粋PyTorchによるLoRALinear実装と初期順伝播恒等性の検証

独立習得チェック(AI 支援なし)

前提条件

第64日アクティビティ1〜3の全知識。

学習目標

外部ライブラリに頼らず純粋なPyTorchのみで LoRALinear(nn.Module) を実装し、順伝播の正確性と初期恒等性を実証する。

手順

1. nn.Module を継承して LoRALinear(in_features, out_features, r=8, lora_alpha=16) を作成します。
2. ベース層を凍結された nn.Linear として登録せよ: self.linear.requires_grad_(False) を呼び、重み W0 とバイアスの両方を凍結する。
3. 形状 (r, in_features) の nn.Parameter として lora_A を、形状 (out_features, r) の nn.Parameter として lora_B を作成します。
4. A は Kaiming 一様分布、B はゼロで初期化します。
5. forward(x) を実装せよ: base = self.linear(x); adapter = self.scaling * (x @ self.lora_A.T @ self.lora_B.T)(self.scaling = lora_alpha / r); return base + adapter。
6. ランダムな入力 x に対し、forward(x) と self.linear(x) の最大差が厳密に 0.0 であることを assert で検証します。

演習と予測記録

実装した LoRALinear に対する単体テストを実行し、B=0 の条件下で完全な出力一致を検証してください。

独立習得基準

外部依存なしで完全なLoRALinear層を構築し、初期恒等性を単体テストで証明できる。

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

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.1 Low-Rank-Parametrized Update Matrices (W0 + BA, B initialized to zero, scaling by alpha/r)

検証バージョンと日付: 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.