46 / 90

第46日:Transformerブロックの組み立て:LayerNorm、RMSNormと残差接続

具体値を用いてLayerNormとRMSNormを計算し、残差接続がなぜ勾配高速道路を形成するかを導出し、Pre-LNとPost-LNの収束安定性を比較する。

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

Layer NormalizationとRMSNorm:数学的原理と数値安定性

Agent支援工学分析

前提条件

第28日の分散と標準偏差;第22日のベクトル代数。

学習目標

入力ベクトル x = [2.0, -1.0, 0.0, 3.0] に対しLayerNormとRMSNormを順に計算し、現代アーキテクチャがRMSNormを好む理由を説明する。

手順

次元 d=4 のベクトル x = [2.0, -1.0, 0.0, 3.0] について:(1) 平均 mu = 1.0、分散 sigma^2 = 2.5 を求め、eps=1e-5 の場合の LayerNorm 出力を計算せよ。(2) RMS(x) = sqrt(mean(x^2)) = sqrt(3.5) ≈ 1.8708 を求め、RMSNorm 出力 x / RMS(x) を計算せよ。(3) 計算コストを対比せよ:RMSNorm はメモリ上の平均中心化のパスを省く。

演習と予測記録

1. LayerNorm(x) を小数点以下4桁まで求めよ。
2. RMSNorm(x) を小数点以下4桁まで求めよ。
3. RMSNormがGPU実行において帯域幅効率で有利な理由を述べよ。

独立習得基準

両方の正規化を手計算し、RMSNormのメモリ効率の優位性を説明できること。

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

linking arXiv non-exclusive license / Open Access

Root Mean Square Layer Normalization

著者・提供機関: Biao Zhang, Rico Sennrich (University of Edinburgh) | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 4 RMSNorm (Equation 4) and Section 4.1 Invariance Analysis

検証バージョンと日付: NeurIPS 2019 / arXiv:1910.07467v1 (Verified: 2026-10-30)

選定理由:

Primary paper showing that mean-centering in LayerNorm can be discarded without performance loss, speeding up modern LLMs (LLaMA, Gemma).

ソース前提知識:

Variance, standard deviation, and LayerNorm basics.

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

RMSNorm formulas and numerical comparisons are derived completely in the lesson.

比較対象候補リソースと選定評価 (2)
Ba et al. Layer Normalization (2016) ↗ compared_selected_for_day46 [Open Access]

Original LayerNorm formulation with mean-centering; RMSNorm is compared directly against it as an optimization.

Ioffe & Szegedy Batch Normalization (2015) ↗ compared_alternative [Open Access]

Batch-dependent statistics; unsuitable for autoregressive sequence modeling.

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 (class LayerNorm, class SublayerConnection)

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

02 120 分

残差接続と恒等勾配ハイウェイ

Agent支援工学分析

前提条件

活動 46-01 および第35日の誤差逆伝播法の連鎖律。

学習目標

残差加算 y = x + F(x) が減衰しない恒等勾配項 dL/dx = dL/dy + dL/dy * dF/dx を供給する仕組みを導出する。

手順

y = x + F(x) の x に関するベクトル微分を書き出せ。dF/dx が小さい、あるいはゼロ付近で飽和している場合でも、dL/dx は恒等項 dL/dy を直接保持し、100+層の深いTransformerにおける勾配消失を防ぐことを示せ。

演習と予測記録

1. y = x + F(x) のとき、dL/dx の連鎖律による展開式を示せ。
2. dF/dx の固有値の大きさがいずれも 0.1 未満の場合、何が勾配の消失を防ぐのか?
3. 加算 x + F(x) が定義されるために必要な次元の不変条件を述べよ。

独立習得基準

勾配ハイウェイの数式を導出し、厳密なテンソル形状不変性を示せること。

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

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 (residual connection around each sub-layer, then layer normalization)

検証バージョンと日付: 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 Block (x = x + attn(ln_1(x)); x = x + mlp(ln_2(x)))

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

Pre-LNとPost-LNの構造比較分析

Agent支援工学分析

前提条件

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

学習目標

Pre-LN(x = x + Attn(LN(x)))と元のPost-LN(x = LN(x + Attn(x)))を対比する。Xiong et al.(2020)の初期化とウォームアップに関する結果を説明し、GPT-2とLlama 2を事前正規化の具体例(Llama 2はRMSNorm)として示す。すべてのモデルが採用しているとは主張しない。

手順

両方の構成について活性化と勾配の流れを追跡し、学習の安定性の違いを説明せよ。Xiong et al.(2020)は、初期化時のPost-LN Transformerでは出力層付近のパラメータの勾配の期待値が大きく、そのため安定した学習には学習率のウォームアップ段階が必要になることを示した。Pre-LNでは初期化時の勾配が適切な大きさに保たれ、同論文の実験ではウォームアップなしで学習したPre-LN Transformerが同等の結果に達した。GPT-2(Section 2.3)は層正規化を各サブブロックの入力側に移し、Llama 2(Section 2.2)はRMSNormによる事前正規化を採用している。これらは例であって網羅的な調査ではない。現代のすべてのLLMがPre-LNを使うと主張してはならない。

演習と予測記録

1. 両構成の数式を示せ。
2. Post-LNで残差パスが純粋な恒等ハイウェイにならない理由は何か?
3. Xiong et al.(2020)によれば、Post-LNが必要とする学習率ウォームアップ段階なしでPre-LNを学習できるのはなぜか?

独立習得基準

構造的差異を明示し、主幹残差の非正規化による安定性を正しく説明できること。

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

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 (LayerNorm(x + Sublayer(x)), the post-LN placement)

検証バージョンと日付: 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 (class SublayerConnection: x + dropout(sublayer(norm(x))))

検証バージョンと日付: 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 arXiv.org perpetual non-exclusive license / Open Access

On Layer Normalization in the Transformer Architecture

著者・提供機関: Ruibin Xiong, Yunchang Yang, Di He, Kai Zheng, Shuxin Zheng, Chen Xing, Huishuai Zhang, Yanyan Lan, Liwei Wang, Tie-Yan Liu | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Abstract; Section 3.3 Understanding the Transformer at initialization (Theorem 1, gradients of the last layer); Section 4 Experiments (Pre-LN without warm-up)

検証バージョンと日付: arXiv:2002.04745v2 (Verified: 2026-11-01)

選定理由:

Supports the activity's stability claim: Post-LN has large expected gradients near the output at initialization and needs warm-up; Pre-LN trained without warm-up reached comparable results in the paper's experiments.

ソース前提知識:

LayerNorm and residual connections from Days 46-01 and 46-02; gradients from Days 31-36.

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

The lesson states the Pre-LN and Post-LN formulas and the warm-up finding in its own words.

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

Argues that Post-LN instability comes from amplified dependence on the residual branch and proposes Admin initialization; deeper than this activity needs, so deferred.

Reports that pre-norm Transformers train deeper stacks than post-norm ones, but is empirical and specific to translation; Xiong et al. give the gradient analysis this activity asks learners to explain.

linking Open Access / OpenAI Public Publication

Language Models are Unsupervised Multitask Learners

著者・提供機関: Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 2.3 Model (layer normalization moved to the input of each sub-block)

検証バージョンと日付: OpenAI Technical Report 2019 (Verified: 2026-10-30)

選定理由:

Example of a widely used decoder-only LM that places layer normalization before each sub-block.

ソース前提知識:

Autoregressive conditional likelihood, cross-entropy loss, perplexity exponentiation.

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

Conditional log-likelihood equations, length normalization factors, and held-out cross-entropy calculations are fully derived in lesson material.

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

Focuses on empirical power-law loss curves; Radford et al. establishes the zero-shot log-likelihood task evaluation protocol.

Optimal compute scaling; Radford provides the fundamental zero-shot conditional probability formulation.

linking Open Access

Llama 2: Open Foundation and Fine-Tuned Chat Models

著者・提供機関: Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, et al. | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 2.2 Training Details (pre-normalization using RMSNorm)

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

選定理由:

Example of a widely used decoder-only LLM that normalizes before each sub-layer, with RMSNorm in place of LayerNorm.

ソース前提知識:

Transformer architecture, RLHF/SFT pipelines.

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

The LLaMA-2 prompt structure, token boundary rules, and comparative analysis are fully worked out in curriculum lessons.

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

Original foundation model paper without conversational chat tuning details; LLaMA-2 formalizes dialogue formatting.

Jiang et al. Mistral 7B ↗ compared_alternative [Open Access]

Adopts similar [INST] formatting; LLaMA-2 provides the foundational ablation on system prompt integration.

04 120 分

独立Transformerブロック組み立てチェック

完全自立閉本テスト

前提条件

活動01-03の完了。

学習目標

Pre-LN Transformerブロックを実装し、入出力テンソルの形状不変性を検証する。

手順

RMSNorm/LayerNorm、CausalSelfAttention、残差加算を備えたクラス Block(nn.Module) を実装せよ。形状 (2, 8, 64) の入力テンソルを与えたとき、出力テンソルの形状が (2, 8, 64) と完全一致することを assert で検証せよ。

演習と予測記録

1. 注意力サブレイヤーの forward コードを示せ。
2. 出力形状が厳密に一致することを確かめよ。
3. 射影の次元が一致しない場合に生じるエラーを答えよ。

独立習得基準

形状不変性と数値テストを通過するモジュール実装を提示できること。

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

linking MIT

nanoGPT: model.py architecture implementation

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

該当セクション・タイムスタンプ: model.py: class Block (x = x + attn(ln_1(x)); x = x + mlp(ln_2(x)))

検証バージョンと日付: 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 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 (class EncoderLayer, class DecoderLayer)

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