47 / 90

第47日:位置順適応型前向ネットワーク(FFN)、SwiGLUとブロックの多層積層

トークンごとの前向ネットワークを構築し、中間隠れ層の拡張と逆射影を追跡し、厳密なテンソル不変性をもって複数のTransformerブロックを積層する。

モデル・事前学習とLoRA 480分の集中学習(8時間)
01 120 分

位置順適応型前向ネットワーク(FFN)のアーキテクチャ

Agent支援工学分析

前提条件

第46日のTransformerブロックと第41日のMLPの基礎。

学習目標

FFNがトークンのキー・バリュー記憶として機能すること、および4倍の隠れ層拡張 d_ff = 4 * d_model を理解する。

手順

1. すべての形状を付けて FFN を書く:x は (T, d_model)、W1 は (d_model, d_ff)、b1 は (d_ff)、W2 は (d_ff, d_model)、b2 は (d_model)。したがって FFN(x) = act(x W1 + b1) W2 + b2 は再び (T, d_model) になる。
2. 「位置ごと(position-wise)」を説明する:同じ W1, b1, W2, b2 が各行 x_t に個別に作用し、トークン s の値がトークン t の FFN 出力に入ることはない。トークン間の混合は注意機構の役割である。
3. 活性化関数を比べる:ReLU max(0, z) は硬いゼロを持つ。GELU z * Phi(z) は滑らかで小さな負の値を通す。SwiGLU はゲート (Swish(x W) ⊙ (x V)) W2 を使うため、行列が 2 つではなく 3 つ必要になる。
4. d_model = 64、d_ff = 256 のパラメータ数を、まずバイアスなし、次にバイアス込みで数える。
5. d_ff' ≈ (2/3) d_ff を整数に丸め、SwiGLU のパラメータ数がほぼ同じになる隠れ幅を求める。

時間配分(120 分):読解 30 + 演習 60 + 確認 30。 読解:Vaswani et al. 3.3 節(位置ごとのフィードフォワードネットワーク)と nanoGPT model.py の MLP クラス。演習:項目 1-5。確認:習熟項目として、両方のパラメータ数を補助なしで求める。

演習と予測記録

1. 各テンソルの形状を付けて、標準的な2層FFNの式を書け。
2. なぜFFNは「位置順適応型(position-wise)」と呼ばれるのか?
3. バイアスを含めずに、W1 (64x256) と W2 (256x64) のパラメータ数を計算せよ。
4. バイアス b1 と b2 を加えた合計を求めよ。
5. SwiGLU は 3 つの行列(d_model x d_ff' の W と V、d_ff' x d_model の W2)を使う。パラメータ数が項目 3 に近くなるよう d_ff' を選び、その数を求めよ。

独立習得基準

位置独立性の概念と4倍拡張のパラメータ計算を正しく導出できること。

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

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.3 Position-wise Feed-Forward Networks

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

選定理由:

Foundational primary literature defining the Transformer architecture, multi-head attention, and scaled dot-product attention.

ソース前提知識:

Matrix multiplication and basic neural network concepts from Days 22-24 and 34-36.

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

All mathematical formulas and structural definitions are self-contained in the lesson text.

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.

linking MIT

nanoGPT: model.py architecture implementation

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

該当セクション・タイムスタンプ: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

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

選定理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

ソース前提知識:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

比較対象候補リソースと選定評価 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

02 120 分

手計算によるFFN順伝播と隠れ層拡張の導出

Agent支援工学分析

前提条件

活動01および第22日の行列積。

学習目標

x = [1.0, 2.0] を d_model=2 から d_ff=3 へ拡張し、再度 d_model=2 へ逆射影するFFN手計算を完遂する。

手順

1. 先に形状を書く:x は 1x2、W1 は 2x3 なので z = x W1 は 1x3。h は 1x3。W2 は 3x2 なので y は 1x2。
2. z の各成分を、x と W1 の 1 列との内積として、すべての積を書いて計算する。
3. ReLU を成分ごとに適用し、ゼロになる成分があれば記録する。
4. y を h と W2 の各列との内積として計算する。
5. 残差を加える:ブロック内ではサブレイヤーの出力が足し戻されるので、ブロックの出力は x + y である。
6. 変形 x = [2, -1] で全体をもう一度計算し、有効な隠れユニットの数を比べる。

時間配分(120 分):読解 20 + 演習 70 + 確認 30。 読解:The Annotated Transformer の位置ごと FFN と nanoGPT の MLP forward。演習:項目 1-5 を手計算。確認:白紙から変形問題を解き直し、1 成分を電卓か NumPy で確かめる。

演習と予測記録

1. 活性化前スコア z = x W1 を求めよ。
2. ReLU適用後の h を求めよ。
3. 最終出力 y = h W2 を求めよ。
4. 残差接続を加え、x + y を求めよ。
5. x = [2, -1] について項目 1-3 を繰り返し、ReLU がどの隠れユニットを止めるか述べよ。

独立習得基準

拡張と射影の行列積計算を誤差なく手計算できること。

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

linking MIT

The Annotated Transformer

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

該当セクション・タイムスタンプ: Position-wise Feed-Forward Networks (class PositionwiseFeedForward)

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

選定理由:

Clear reference implementation of Transformer modules, residual connections, and layer normalization.

ソース前提知識:

PyTorch tensor operations and attention theory.

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

All block assembly and normalization logic are provided in runnable local Python snippets.

比較対象候補リソースと選定評価 (2)
HuggingFace Transformers library source ↗ compared_alternative [Apache 2.0]

Industrial scale with hundreds of model variations; Annotated Transformer is pedagogically focused on the core architecture.

PyTorch nn.Transformer documentation ↗ compared_alternative [Modified BSD]

Standard library implementation, but internal C++ bindings obscure the first-principles data flow.

linking MIT

nanoGPT: model.py architecture implementation

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

該当セクション・タイムスタンプ: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

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

選定理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

ソース前提知識:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

比較対象候補リソースと選定評価 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

03 120 分

Transformerブロックの積層とテンソル不変性

Agent支援工学分析

前提条件

活動 47-01 および 47-02。

学習目標

トークンのバッチ (B=2, T=4, d=64) を連続する2つのTransformerブロックに通して追跡し、テンソル形状とdtypeが保存されることをassertで検証する。

手順

1. Pre-LN ブロック 1 つを 2 つの残差サブレイヤーとして書く:x = x + Attn(LN1(x))、次に x = x + FFN(LN2(x))。
2. 例を固定する:B = 2、T = 4、d_model = 64、n_heads = 4(head_dim = 16)、d_ff = 256。
3. 注意機構の内部(ヘッドごとの Q, K, V、スコア行列、結合後の出力)と FFN の内部(隠れ層)の形状を追跡する。
4. 形状が (B, T, d_model) と異なる箇所すべてに印を付け、各残差加算の前に (B, T, d_model) に戻ることを確かめる。
5. dtype も確認する:ブロックは受け取ったのと同じ dtype を返さなければならない。
6. 同一のブロックインターフェースによって L 個のブロックを積み重ねられる理由と、残差加算に形状の一致が必要な理由を説明する。

時間配分(120 分):読解 25 + 演習 60 + 確認 35。 読解:Vaswani et al. 3.1 節(エンコーダとデコーダの積層)と The Annotated Transformer の EncoderLayer/SublayerConnection のコード。演習:項目 1-4 と完全な形状表。確認:ノートなしで形状の契約を説明し、比べる。

演習と予測記録

1. 2ブロックのPre-LN Transformerにおけるサブレイヤーの実行順序を書け。
2. ブロック1とブロック2の間にある各中間点でのテンソル形状を述べよ。
3. 重みの初期化と残差加算にとって、各層の次元を統一することが不可欠なのはなぜか?
4. ヘッド数 4、d_ff = 256 と仮定する。ヘッドごとの Q、注意スコア、FFN 隠れ層の形状を答えよ。

独立習得基準

モジュール契約とテンソル形状不変性の意義を論理的に解説できること。

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

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.1 Encoder and Decoder Stacks (N = 6 identical layers, d_model = 512)

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

選定理由:

Foundational primary literature defining the Transformer architecture, multi-head attention, and scaled dot-product attention.

ソース前提知識:

Matrix multiplication and basic neural network concepts from Days 22-24 and 34-36.

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

All mathematical formulas and structural definitions are self-contained in the lesson text.

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.

linking MIT

The Annotated Transformer

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

該当セクション・タイムスタンプ: Encoder and Decoder Stacks

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

選定理由:

Clear reference implementation of Transformer modules, residual connections, and layer normalization.

ソース前提知識:

PyTorch tensor operations and attention theory.

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

All block assembly and normalization logic are provided in runnable local Python snippets.

比較対象候補リソースと選定評価 (2)
HuggingFace Transformers library source ↗ compared_alternative [Apache 2.0]

Industrial scale with hundreds of model variations; Annotated Transformer is pedagogically focused on the core architecture.

PyTorch nn.Transformer documentation ↗ compared_alternative [Modified BSD]

Standard library implementation, but internal C++ bindings obscure the first-principles data flow.

04 120 分

Transformerブロックのパラメータ数と計算量の精密分析

コア導出の自立実施

前提条件

活動01-03の完了。

学習目標

d_model=768, d_ff=3072 のブロックについて注意力層とFFNのパラメータ比率(1:2)を導出する。

手順

1. GPT-2 small のブロックを使う:d_model = 768、n_heads = 12(head_dim = 64)、d_ff = 3072。
2. 注意機構の重み(Q, K, V, O:4 * 768 * 768)と FFN の重み(2 * 768 * 3072)を数え、比を求める。
3. バイアス(注意の射影ごとに 768、FFN の上方射影に 3072、下方射影に 768)と 2 つの LayerNorm(ゲインとバイアスで各 2 * 768)を加える。
4. モデル全体に広げる:12 ブロック、トークン埋め込み 50257 x 768、位置埋め込み 1024 x 768、最終 LayerNorm、重み共有された LM ヘッド(追加パラメータなし)。
5. トークンあたりの順伝播 FLOPs を見積もる:行列積で重み 1 つあたり約 2 FLOPs、さらに注意のスコアと値の積で層あたり約 4 * T * d_model。
6. T = 1024 で、パラメータと FLOPs のそれぞれについて FFN と注意機構の割合を比べる。

時間配分(120 分):読解 25 + 演習 60 + 確認 35。 読解:nanoGPT model.py(Block、CausalSelfAttention、MLP、get_num_params)と Vaswani et al. の表 1。演習:項目 1-6。確認:124M の合計を補助なしで計算し直し、get_num_params と比べる。

演習と予測記録

1. 注意力層の総パラメータ数を求めよ(バイアスなし)。
2. FFN層の総パラメータ数を求めよ(バイアスなし)。
3. 1ブロック内での両者のパラメータ比率はいくつか?
4. バイアスと 2 つの LayerNorm を加え、ブロック全体のパラメータ数を求めよ。
5. 語彙 50257、文脈長 1024、重み共有 LM ヘッドの 12 ブロックモデルについて、総パラメータ数を求めよ。
6. T = 1024 で 1 ブロックのトークンあたり順伝播 FLOPs を見積もれ。

独立習得基準

パラメータ数を正確に導出し、FFNと注意力の2:1比率を指摘できること。

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

linking MIT

nanoGPT: model.py architecture implementation

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

該当セクション・タイムスタンプ: model.py: GPT.get_num_params and GPT.estimate_mfu

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

選定理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

ソース前提知識:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

比較対象候補リソースと選定評価 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

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.3 Position-wise Feed-Forward Networks and Section 4 Why Self-Attention (Table 1)

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

選定理由:

Foundational primary literature defining the Transformer architecture, multi-head attention, and scaled dot-product attention.

ソース前提知識:

Matrix multiplication and basic neural network concepts from Days 22-24 and 34-36.

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

All mathematical formulas and structural definitions are self-contained in the lesson text.

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.