49 / 90

第49日: 第7週の総復習: Attention からロジットまで + 事前学習データパイプライン

第43〜48日(Attention、マスク、マルチヘッド、ブロック構造、順伝播)を想起してつなげ、事前学習ループに必要な唯一の新要素である自己回帰 (x, y) バッチを加える。

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

新規内容: 自己回帰 (x, y) バッチと get_batch

Agent支援工学分析

前提条件

第1〜3日のトークン化、第36日の交差エントロピー、第48日の順伝播。

学習目標

平坦なトークン配列から因果的な入力・ターゲットの組を作り、get_batch でバッチをサンプリングし、バッチテンソルのサイズを求め、最初の損失を ln(V) と照合する。

手順

今日の新しい内容はこれだけで、残りは第7週の復習です。デコーダは t までのトークンからトークン t+1 を予測します。コンテキスト長 L では L + 1 トークンの窓 chunk = tokens[i : i + L + 1] を切り出し、x = chunk[:-1]、y = chunk[1:] とします。どちらも形状は (L,) です。バッチは B 個のランダムな窓を積み重ね、形状 (B, T) の x と y にします。モデルの出力ロジットは (B, T, V) ですが、F.cross_entropy は (N, V) と (N,) を受け取るので、logits.view(-1, V) と y.view(-1) に平坦化します。学習前はすべてのトークンが等確率なので、最初の損失は ln(V) に近いはずです。

演習と予測記録

1. tokens = [502, 1204, 33, 991, 88, 412]、L = 4、開始位置 0 のとき x と y を書け。窓に L + 1 トークン必要なのはなぜか。
2. get_batch(data, batch_size, block_size, device) を書け。
3. B = 64、T = 1024 のとき、x と y の合計は int64 で何バイトか。int32 ではどうか。
4. 正しく平坦化した cross_entropy の呼び出しを書き、V = 50,257 での最初の損失の期待値を答えよ。
5. y = x(シフトなし)だと何が起きるか。

独立習得基準

シフトした (x, y) の組を導き、動く get_batch を書き、バッチテンソルのサイズを正確に求め、ln(V) で最初の損失を検証できる。

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

linking MIT

nanoGPT: train.py pretraining loop

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

該当セクション・タイムスタンプ: train.py: get_batch(split): x = data[i:i+block_size], y = data[i+1:i+1+block_size]

検証バージョンと日付: Git master commit 71c3905 (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 46-48 Transformer model architecture.

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

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

比較対象候補リソースと選定評価 (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

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

該当セクション・タイムスタンプ: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

検証バージョンと日付: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

選定理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

ソース前提知識:

Fluent Python, PyTorch, and linear algebra

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

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

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

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

02 120 分

復習ドリル: スケーリング・マスク・マルチヘッド Attention(第43〜45日)

コア導出の自立実施

前提条件

第43日のスケール化内積 Attention、第44日の因果マスク、第45日のマルチヘッド Attention。クローズドブックで解き、答え合わせのときだけ第43〜45日のノートを開くこと。

学習目標

因果 Attention の出力を手計算で再現し、第43〜45日の形状・パラメータ・数値安定性の知識をノートなしで想起する。

手順

想起練習です。まず記憶から答え、その後で確認します。1) 第43〜44日と同様に S = Q K^T / sqrt(d_k) を計算し、因果マスクを加え(第44日)、最大値シフト付きの行ごとの softmax を適用し(第45日)、V を掛ける。2) 第45日のマルチヘッドの形状を追う: (B, T, d_model) -> (B, T, h, d_k) -> (B, h, T, d_k) -> スコア (B, h, T, T) -> (B, T, d_model) に戻す。3) 何かを調べる前に、各事実を一文で説明する。

演習と予測記録

1. Q = [[1, 1], [0, 2]]、K = [[1, 1], [2, 0]]、V = [[1, 0], [0, 1]]、d_k = 2。スケール後のスコア、因果 Attention の重み、Out を求めよ。マスクがなければ Out[0] はどうなるか。
2. B = 2、T = 5、d_model = 12、h = 3。d_k と、ヘッド分割後の Q、スコアテンソル、結合後の出力の形状を答えよ。
3. d_model = 12 のとき W^Q、W^K、W^V、W^O のパラメータ数はバイアス込みでいくつか。バイアスなしではどうか。
4. 記憶から答えよ: なぜ sqrt(d_k) で割るのか(第43日)。なぜ exp(15) は float16 で破綻するのか(第45日)。トークン 1 が変わると Out[0] はどうなるか(第44日)。

独立習得基準

因果 Attention の出力、マルチヘッドの形状、パラメータ数をノートなしで再現し、sqrt(d_k)・float16・因果不変性の事実を自分の言葉で説明できる。

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

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

The Annotated Transformer

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

該当セクション・タイムスタンプ: subsequent_mask implementation using torch.triu and triangular boolean masking

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

復習演習: ブロック構造・パラメータ台帳・順伝播(第46〜48日)

Agent支援工学分析

前提条件

第46日の LayerNorm・RMSNorm・残差接続、第47日の FFN とブロックの計数、第48日の位置情報・重み共有・順伝播全体。

学習目標

正規化、Pre-LN ブロック、FFN、重み共有を、小さな GPT の 1 つのパラメータ台帳と 1 つの形状トレースにまとめる。

手順

次の小さな GPT を使う: V = 100、コンテキスト 16、d_model = 32、n_layer = 2、n_head = 4、d_ff = 4 * d_model、学習可能な位置埋め込み、重みとバイアスを持つ LayerNorm、バイアスなしの線形層、出力ヘッドは重み共有。1) 第46日と同様に LayerNorm と RMSNorm を手計算する。2) 第46日の Pre-LN ブロックの式と、第48日の順伝播全体を書く。3) 第47日と同様にパラメータ台帳を 1 行ずつ作り、重み共有による削減分(第48日)を加える。

演習と予測記録

1. x = [4, 0, -2, 2] について LayerNorm(epsilon なし、ゲイン 1、バイアス 0)と RMSNorm を計算せよ。
2. 1 ブロックの Pre-LN 残差の 2 行を書き、Pre-LN が Post-LN より安定に学習できる理由を一文で述べよ。
3. この GPT のパラメータ数を、ブロックごと、全ブロック、埋め込み、最終 LayerNorm、合計の順に求めよ。重み共有しないヘッドではいくつ増えるか。
4. 各ブロックの行列重みのうち FFN が占める割合はいくらか。
5. B = 8、T = 16 で idx からロジットまでの形状を追い、次トークンのサンプリングに使うスライスを答えよ。

独立習得基準

正規化の値、Pre-LN の式、合計 28,608 となるパラメータ台帳(重み共有の差の説明付き)、正しい端から端までの形状トレースを示せる。

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

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 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 Model Architecture (3.1-3.5)

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

04 120 分

第7週の評価: 小さな GPT の 4 つのバグを見つける(第43〜49日)

完全自立閉本テスト

前提条件

第43〜48日と第49日の活動 1〜3。クローズドブック、AI 不使用を申告して解く。

学習目標

第7週の規則をそれぞれ破る 4 つの仕込まれたバグを独力で見つけ、説明し、修正し、学習中にどう現れるかを予測する。

手順

下のコードを実行せずに一度読む。印の付いた各行は第7週の規則のどれかを破っている: Attention のスケーリング(第43日)、因果マスク(第44日)、数値安定性(第45日)、Pre-LN 残差(第46日)、(x, y) のシフト(第49日)。

def attention(q, k, v):                      # q, k, v: (B, h, T, d_k)
T, d_model = q.size(-2), q.size(-1) * q.size(1)
scores = q @ k.transpose(-2, -1) / d_model # (A)
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=0) # (B)
scores = scores.masked_fill(mask, float('-inf'))
return scores.softmax(dim=-1) @ v

class Block(nn.Module):
def forward(self, x):
x = self.ln_1(x + self.attn(x)) # (C)
return x + self.mlp(self.ln_2(x))

x, y = chunk[:-1], chunk[:-1] # (D)

演習と予測記録

1. (A)、(B)、(C)、(D) の各行について、バグの内容、破っている規則の日、修正を答えよ。
2. 最初の順伝播で NaN を出すのはどのバグか。その理由は。
3. 損失が不自然に速く下がるのに、モデルが有用なことを何も学ばないのはどのバグか。
4. すべて修正した後、V = 100 で期待される最初の損失はいくらか。

独立習得基準

4 つのバグをすべて特定して出典の日に対応づけ、動作する修正を示し、NaN と損失の急低下という症状を支援なしで正しく予測できる。

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

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 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.