45 / 90

第 45 日:マルチヘッドアテンション機構と数値的安定性

マルチヘッドアテンションを線形部分空間射影 W^Q, W^K, W^V, W^O に分解します。h 個の並列ヘッドにわたるテンソル変形 (B, h, T, d_k) を習得し、厳密なパラメータ台帳を検証し、アテンション実装における境界値の数値的不安定性を解消します。

モデルと訓練 480 分のアクティブ学習(8 時間の集中学習)
01 120 分

マルチヘッド部分空間:なぜ、どのように d_model を分割するか

AI アシスタント協力エンジニアリングチェック

前提条件

第 43-44 日のスケール化内積アテンションと因果マスク機構。

学習目標

マルチヘッドアテンションの表現上の必要性を説明し、線形射影 W^Q, W^K, W^V, W^O を定式化し、微小規模および標準 GPT 規模のパラメータ台帳を導出する。

手順

必須タスク:単一のアテンションヘッドが異なる種類の関係(構文的依存と長距離の意味的照応など)を単一の加重平均に圧縮してしまう限界を説明します。MultiHead(Q,K,V) = Concat(head_1, ..., head_h) W^O(各 head_i = Attention(Q W_i^Q, K W_i^K, V W_i^V))を定式化してください。d_model = 4, h = 2 のとき、d_k = d_v = 2 です。パラメータ台帳:W^Q, W^K, W^V, W^O はそれぞれ (4, 4) 行列で各 16 パラメータ(バイアスなし計 64、バイアスあり計 80)。GPT-2 Small(d_model = 768, h = 12, d_k = 64)の台帳:重み 4 * 768*768 = 2,359,296、バイアス 4*768 = 3,072、合計 2,362,368 パラメータを算出してください。

演習と予測記録

1. 単一のアテンションヘッドが局所的近接性と長距離構文一致を同時に捕捉できないのはなぜですか?
2. d_model = 4, h = 2 のバイアス有無両方での正確なパラメータ台帳を記述してください。
3. GPT-2 Small アテンション層(d_model = 768, h = 12)のパラメータ台帳を導出してください。

独立習得基準

部分空間ルーティングの概念を明確に説明し、微小規模および GPT-2 規模のパラメータ台帳を誤りなく導出できること。

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

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

著者・提供機関: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 3.2.2: Multi-Head Attention architecture, linear projections, and parameter equations

検証バージョンと日付: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

選定理由:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

ソース前提知識:

Linear algebra, matrix multiplication, softmax probability distributions

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

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

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

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

The Annotated Transformer

著者・提供機関: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | オリジナル出所URL ↗

該当セクション・タイムスタンプ: MultiHeadedAttention module implementation: linear projections and subspace splitting

検証バージョンと日付: Updated 2022 edition (Verified: 2026-10-30)

選定理由:

Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

ソース前提知識:

Intermediate Python, PyTorch broadcasting and tensor slicing semantics

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

The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

比較対象候補リソースと選定評価 (3)
Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

The original primary paper; Annotated Transformer annotates it directly.

02 120 分

テンソル変形、転置、バッチ並列アテンション (B, h, T, d_k)

自立型習得チェック

前提条件

第 45 日アクティビティ 1 を完了していること。

学習目標

アテンション順伝播におけるテンソルの階数と次元変換(射影、ヘッド分割転置 (B, T, h, d_k) -> (B, h, T, d_k)、バッチ行列積、連結)を完全に追跡する。

手順

必須タスク:入力バッチ X (B, T, d_model) = (1, 2, 4) に対する h=2, d_k=2 のマルチヘッドアテンションの全計算ステップを追跡します。ステップ 1:線形射影 Q, K, V (1, 2, 4)。ステップ 2:view による (B, T, h, d_k) = (1, 2, 2, 2) への変形。ステップ 3:次元 1 と 2 の転置により (B, h, T, d_k) = (1, 2, 2, 2)。ステップ 4:バッチ行列積 Q @ K^T により (1, 2, 2, 2)。ステップ 5:sqrt(2) スケーリングと因果マスク。ステップ 6:V との積により (1, 2, 2, 2)。ステップ 7:転置と平坦化により (1, 2, 4)。ステップ 8:W^O 射影により (1, 2, 4)。X = [[1, 0, 1, 0], [0, 2, 0, 1]] と単位射影重みで手計算してください。

演習と予測記録

1. 入力 X から最終出力 Out までの各ステップのテンソル形状を列挙してください。
2. X = [[1, 0, 1, 0], [0, 2, 0, 1]](単位陣射影)に対し、Head 0 と Head 1 の因果アテンション行列を計算してください。
3. W^O による最終連結出力を求めてください。

独立習得基準

全テンソル形状の遷移を漏れなく記述し、2 ヘッドの具体的出力を正確に計算できること。

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

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

著者・提供機関: Andrej Karpathy | オリジナル出所URL ↗

該当セクション・タイムスタンプ: model.py: view and transpose operations: B, T, nh, hs -> B, nh, T, hs

検証バージョンと日付: GitHub master commit (Verified: 2026-10-30)

選定理由:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

ソース前提知識:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

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

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

比較対象候補リソースと選定評価 (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

linking MIT

The Annotated Transformer

著者・提供機関: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | オリジナル出所URL ↗

該当セクション・タイムスタンプ: MultiHeadedAttention forward pass tensor reshaping and transposition trace

検証バージョンと日付: Updated 2022 edition (Verified: 2026-10-30)

選定理由:

Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

ソース前提知識:

Intermediate Python, PyTorch broadcasting and tensor slicing semantics

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

The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

比較対象候補リソースと選定評価 (3)
Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

The original primary paper; Annotated Transformer annotates it directly.

03 120 分

アテンションの数値的安定性:最大値シフト、精度限界、マスクの落とし穴

AI アシスタント協力エンジニアリングチェック

前提条件

第 45 日アクティビティ 2 を完了していること。

学習目標

アテンション実装における浮動小数点数の脆弱性を分析・解消する:最大値シフト Softmax の不変性証明、全マスク行による NaN 発生の防止、fp16/fp32 のダイナミックレンジ限界。

手順

必須タスク:3 つの重要な数値的境界ケースを分析します。ケース 1:未シフト指数のオーバーフロー。float32 では z >= 88.7 で exp(z) が inf に溢れ、float16 では z >= 11.1 で溢れます。softmax(z)_i = softmax(z - c)_i のシフト不変性を代数的に証明してください。ケース 2:全マスク行のクラッシュ。行全体が -inf の場合(パディングされた文脈など)、max(z) = -inf となり、-inf - (-inf) = NaN が発生します。NaN 行を回避する実装法を提示してください。ケース 3:混合精度におけるマスク値の選定。float16 においてなぜ -1e4 が -1e9 より安全であるかを説明してください。

演習と予測記録

1. 任意のスカラー c に対し softmax(z - c) = softmax(z) を代数的に証明してください。
2. PyTorch float16 で torch.exp(torch.tensor(15.0, dtype=torch.float16)) を計算すると何が生じますか?
3. 全体がマスクされた行に遭遇した際、モデルが NaN を出力しないようにする工学的対策は何ですか?

独立習得基準

シフト不変性の厳密な証明を記述し、float16 のオーバーフローおよび全マスク行の対処法を正しく提示できること。

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

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

著者・提供機関: Andrej Karpathy | オリジナル出所URL ↗

該当セクション・タイムスタンプ: model.py: FlashAttention / scaled_dot_product_attention numerical stability and fallback path

検証バージョンと日付: GitHub master commit (Verified: 2026-10-30)

選定理由:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

ソース前提知識:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

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

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

比較対象候補リソースと選定評価 (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

著者・提供機関: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 3.2.1: Softmax numerical behavior and score magnitude scaling

検証バージョンと日付: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

選定理由:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

ソース前提知識:

Linear algebra, matrix multiplication, softmax probability distributions

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

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

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

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

04 120 分

自立型習得チェック:マルチヘッド台帳、因果不変性、安定性検証

自立型習得チェック

前提条件

アクティビティ 45-01 から 45-03。

学習目標

AI 支援なしの宣言条件下で、中規模モデルのパラメータ台帳計算、端ツー端の順伝播追跡、ヘッドを跨いだ因果不変性証明、数値安定性の検証を自力で達成する。

手順

必須タスク:自力で解答してください。1. 中規模 GPT(d_model = 1024, h = 16)の単層アテンション層の正確なパラメータ数を計算する(W^Q, W^K, W^V, W^O の重みとバイアス)。2. 各単一ヘッドが因果的であるとき、出力射影 W^O が将来情報を絶対に漏洩しない理由を証明する。3. ロジット [500.0, 502.0] に対する正確な最大値シフト Softmax 確率を求める。4. 客観テストに解答する。

演習と予測記録

1. d_model = 1024, h = 16 アテンション層の総パラメータ数(バイアス有無)?
2. なぜ W^O は各ヘッドの因果不変性を破壊しないのかを証明してください。
3. ロジット [500.0, 502.0] の正確な Softmax 出力を計算してください。
4. 3 問の客観クイズに解答してください。

客観的理解度チェック:マルチヘッドアテンションと安定性

以下の設問に解答して理解度を確認してください。提出前に利用した補助条件を誠実に申告してください。

申告補助条件

注記: AI不使用は誠実な申告条件であり、監視や強制検知ではありません。

1.

モデル埋め込み次元 d_model = 768、ヘッド数 h = 12 のマルチヘッドアテンションブロックにおいて、各ヘッドの次元 d_k はいくつですか?

2.

バイアスなしの射影行列 W^Q, W^K, W^V, W^O in R^{d_model x d_model} を持つ標準マルチヘッドアテンション層において、d_model = 768 の場合の総重みパラメータ数はいくつですか?

3.

最大値シフトを適用した Softmax 実装 softmax(z)_i = exp(z_i - max(z)) / sum_j exp(z_j - max(z)) において、max(z) を減算する数学的・計算的正当性は何ですか?

解答根拠と履歴

    独立習得基準

    中規模モデル台帳(4,194,304 / 4,198,400)を正確に計算し、W^O の位置単位因果保持性を厳密に証明してクイズで 100% 満点を獲得できること。

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

    linking arXiv.org perpetual non-exclusive license / Open Access

    Attention Is All You Need

    著者・提供機関: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | オリジナル出所URL ↗

    該当セクション・タイムスタンプ: Section 3.2.2: Multi-Head Attention parameter count equations and projection matrices

    検証バージョンと日付: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

    選定理由:

    The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

    ソース前提知識:

    Linear algebra, matrix multiplication, softmax probability distributions

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

    Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

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

    Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

    Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

    Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

    Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

    linking MIT

    nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

    著者・提供機関: Andrej Karpathy | オリジナル出所URL ↗

    該当セクション・タイムスタンプ: model.py: CausalSelfAttention parameter accounting and projection weights verification

    検証バージョンと日付: GitHub master commit (Verified: 2026-10-30)

    選定理由:

    Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

    ソース前提知識:

    Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

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

    Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

    比較対象候補リソースと選定評価 (3)
    Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

    Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

    Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

    Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

    Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.