43 / 90

第 43 日:スケール化内積アテンションとクエリ・キー・バリュー射影

アテンションを、クエリをキーに照合してバリューを加重平均するルーティング機構として定式化します。R^{d_k} 内積の分散を導出し、1/sqrt(d_k) スケール係数が Softmax の勾配消失を防ぐ理由を証明し、(T, d_k) スコア行列を手計算とコードで追跡します。

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

クエリ、キー、バリュー:ベクトルの役割とアテンションの定式化

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

前提条件

第 41-42 日の順伝播、行列積、行単位 Softmax の仕組み。

学習目標

アテンションをクエリとキーの照合によるバリューの動的集約として分解し、テンソル次元を導出し、生の内積スコア行列を計算する。

手順

参照資料: この活動に割り当てられた既存の読解・練習時間内で、Stanford CS224N: Natural Language Processing with Deep Learning の Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides を参照し、ローカル課題とのつながりを一つ自分の言葉で説明する。既存の演習と合格基準は維持し、外部資料が開けない場合は本コース独自の説明を使う。必須タスク:スケール化内積アテンション Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V を定式化します。系列長 T=3、キー次元 d_k=4、バリュー次元 d_v=2 とします。Q の各行を q_0=[2.0, 0.0, 2.0, 0.0], q_1=[0.0, 2.0, 0.0, 2.0], q_2=[1.0, 1.0, 1.0, 1.0];K の各行を k_0=[1.0, 0.0, 1.0, 0.0], k_1=[0.0, 2.0, 0.0, 1.0], k_2=[2.0, 1.0, 0.0, 1.0];V の各行を v_0=[1.0, 0.0], v_1=[0.0, 2.0], v_2=[1.0, 1.0] と設定します。生の内積行列 S_raw = Q K^T を段階的に手計算してください。クエリ(何を探しているか)、キー(何を提供しているか)、バリュー(渡される具体的情報)の役割を説明してください。

演習と予測記録

1. S_raw = Q K^T の 3x3 行列の全要素を計算してください。
2. Q、K、V、Q K^T、および最終出力行列のテンソル形状を答えてください。
3. なぜアテンションは固定線形層ではなく、データ駆動型の連想検索機構と言えるのですか?

独立習得基準

行列積の各ステップを正しく計算し、正確な 3x3 S_raw 行列とテンソル形状を導出できること。

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

linking Stanford University copyright; no course-wide open reuse license verified linking only; no reproduction

Stanford CS224N: Natural Language Processing with Deep Learning

著者・提供機関: Stanford University CS224N staff | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides

検証バージョンと日付: Public edition checked 2026-11-01; moving pages may change

選定理由:

Selected attention/Transformer lecture slides provide a coherent teaching check on Q/K/V and architecture; original papers remain definition references and local code exercises remain required.

ソース前提知識:

Linear algebra, gradients, basic neural language models and PyTorch.

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

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

比較対象候補リソースと選定評価 (2)
The Annotated Transformer ↗ compared_alternative [MIT]

Runnable code commentary remains the implementation spine; its sublayer convention must not be mistaken for the original paper.

The Illustrated Transformer ↗ compared_alternative [Copyright Jay Alammar; edition-specific reuse terms unverified]

Concise diagrams are useful, but provide neither the wider lecture sequence nor checked implementation exercises.

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: Scaled Dot-Product Attention equation and query/key/value matrix definitions

検証バージョンと日付: 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 forward pass query/key/value projection extraction

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

02 120 分

スケール係数 sqrt(d_k) とアテンションスコア行列の Softmax

自立型習得チェック

前提条件

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

学習目標

スコア行列に 1/sqrt(d_k) スケール係数を適用し、数値的に安定な行単位 Softmax 確率分布を求め、バリューの加重平均出力を導出する。

手順

必須タスク:d_k = 4 のとき、スケール係数は sqrt(4) = 2.0 です。S_raw の各要素を 2.0 で除算してスケール化行列 S = S_raw / 2.0 を得ます。最大値シフト法を用いて行ごとに Softmax を計算します:第 0 行のスケール値は [2.0, 0.0, 2.0];第 1 行は [0.0, 3.0, 2.0];第 2 行は [1.0, 1.5, 2.0]。アテンション重み A = softmax(S) と出力 Out = A V を求めてください。A の各行の和が厳密に 1.0 になることを確認します。

演習と予測記録

1. スケール化スコア行列 S = S_raw / 2.0 を記述してください。
2. 小数点以下 6 桁まで正確な Softmax アテンション行列 A を求めてください。
3. 3 つの位置すべての出力表現ベクトル Out = A V を計算してください。

独立習得基準

S 行列を自力で導出し、参照値と 4 桁一致するアテンション確率および正しい Out を算出できること。

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

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: Mathematical justification for scaling factor 1/sqrt(d_k) to prevent vanishing softmax gradients

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

該当セクション・タイムスタンプ: Scaled Dot Product Attention code cell and attention matrix visualization

検証バージョンと日付: 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 アシスタント協力エンジニアリングチェック

前提条件

第 43 日アクティビティ 2 を完了していること;初等確率統計と微分積分学の基礎。

学習目標

d_k 次元独立ランダムベクトルの内積の分散が d_k になることを数学的に証明し、スケーリングを欠いた場合に Softmax 勾配が消失する反例を定量的に分析する。

手順

必須タスク:q と k の各成分 q_i, k_i が独立で、E[q_i] = E[k_i] = 0、Var(q_i) = Var(k_i) = 1 とします。E[q . k] = 0 および Var(q . k) = d_k を証明してください。さらに Var((q . k) / sqrt(d_k)) = 1 を示します。次に反例分析として、d_k = 64 (sqrt(d_k) = 8) の場合を考えます。未スケールの場合、標準偏差が 8 に達し、ロジットが +16 や -16 に跳ね上がります。softmax([16, 0, -16]) を計算し、導関数 dp_i / dz_j = p_i (delta_ij - p_j) から勾配がほぼゼロに潰れる理由を説明してください。

演習と予測記録

1. 独立なゼロ平均変数の性質 Var(XY) = E[X^2]E[Y^2] を用いて分散証明を段階的に記述してください。
2. softmax([16, 0, -16]) を計算し、局所勾配の大きさを数値で示してください。
3. なぜスケール化を省くと深層 Transformer の学習初期に最適化が停止してしまうのですか?

独立習得基準

代数的導出の全ステップを記述し、極端なロジットにおける勾配飽和の具体的数値を提示できること。

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

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 footnote and variance derivation for inner products of unit-variance components

検証バージョンと日付: 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: scaling by 1.0 / math.sqrt(k.size(-1)) in attention calculation

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

04 120 分

自立型習得チェック:内積アテンション演算とテンソル形状

自立型習得チェック

前提条件

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

学習目標

AI 支援なしの宣言条件下で、新しいパラメータ配置に対するスケール化内積アテンションの計算、分散導出、テンソル形状契約の検証を独力で達成する。

手順

必須タスク:AI ツールや外部計算機を用いずに独力で解答してください。新たな配置 T=2, d_k=4, d_v=2 に対し:Q 行列は [0.0, 2.0, 0.0, 2.0], [2.0, 0.0, 2.0, 0.0];K 行列は [0.0, 2.0, 0.0, 2.0], [1.0, 0.0, 1.0, 0.0];V 行列は [2.0, 1.0], [0.0, 3.0] です。生の内積行列 S_raw を計算し、sqrt(4)=2 でスケールし、正確な Softmax 行列と最終出力表現を算出してください。客観テストに解答します。

演習と予測記録

1. S_raw とスケール化後の S = S_raw / 2.0 を計算してください。
2. 正確な 2x2 Softmax 重み行列 A を求めてください。
3. 2x2 出力表現行列 Out = A V を計算してください。
4. 3 問の客観クイズに解答してください。

客観的理解度チェック:スケール化内積アテンション機構

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

申告補助条件

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

1.

内積結果 Q K^T を sqrt(d_k) で除算する主たる数学的動機は何ですか?

2.

系列長 T=3、キー次元 d_k=4、バリュー次元 d_v=2 の入力に対し、アテンションスコア行列 S = (Q K^T) / sqrt(d_k) のテンソル形状はどうなりますか?

3.

ベクトル q, k in R^{d_k} の各成分が独立かつ平均 0、分散 1 の分布に従う場合、スケーリング前の内積 q . k の分散はいくつですか?

解答根拠と履歴

    独立習得基準

    S、A、Out 行列の全数値を自力で算出し、客観確認クイズで 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.1: Attention equation verification and tensor shape dimensions

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

    該当セクション・タイムスタンプ: Attention function test assertions and shape contracts

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