49 / 90

Day 49: Week 7 Consolidation: Attention to Logits, plus the Pretraining Data Pipeline

Retrieve and connect Days 43-48 (attention, masking, multi-head, block anatomy, forward pass) and add the one new piece the pretraining loop needs: autoregressive (x, y) batches.

Models, Pretraining & LoRA 480 active minutes (8 hours focused study)
01 120 min

New Material: Autoregressive (x, y) Batches and get_batch

Agent-Assisted Engineering Check

Prerequisites

Tokenization from Days 01-03, cross-entropy from Day 36, and the forward pass from Day 48.

Learning Objective

Build causal input-target pairs from a flat token array, sample batches with get_batch, size the batch tensors, and check the first loss against ln(V).

Instructions

This is the only new topic today; the rest of the day reviews Week 7. A decoder predicts token t+1 from tokens up to t. For context length L, slice a window of L + 1 tokens, chunk = tokens[i : i + L + 1], then set x = chunk[:-1] and y = chunk[1:]. Both have shape (L,). A batch stacks B random windows into x and y of shape (B, T). The model returns logits of shape (B, T, V); F.cross_entropy wants (N, V) and (N,), so flatten with logits.view(-1, V) and y.view(-1). Before training, every token is equally likely, so the first loss should be close to ln(V).

Practice & Prediction Log

1. For tokens = [502, 1204, 33, 991, 88, 412] and L = 4 starting at index 0, write x and y. Why does the window need L + 1 tokens?
2. Write get_batch(data, batch_size, block_size, device).
3. How many bytes do x and y take together for B = 64, T = 1024 as int64? As int32?
4. Write the cross_entropy call with the right flattening, and state the expected first loss for V = 50,257.
5. What goes wrong if y = x (no shift)?

Independent Mastery Criterion

Learner derives the shifted (x, y) pairs, writes a working get_batch, sizes the batch tensors exactly, and uses ln(V) to sanity-check the first loss.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: get_batch(split): x = data[i:i+block_size], y = data[i+1:i+1+block_size]

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

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.

Source Prerequisites:

Python, PyTorch, and Day 46-48 Transformer model architecture.

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

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

Source Prerequisites:

Fluent Python, PyTorch, and linear algebra

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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 min

Review Drill: Scaled, Masked, Multi-Head Attention (Days 43-45)

Independent Mastery Check

Prerequisites

Day 43 scaled dot-product attention, Day 44 causal masking, and Day 45 multi-head attention. Work closed-book; open your Day 43-45 notes only to check answers afterwards.

Learning Objective

Recompute a causal attention output by hand and retrieve the shape, parameter, and stability facts from Days 43-45 without notes.

Instructions

Retrieval practice: answer from memory first, then check. 1) Recompute attention as on Days 43-44: S = Q K^T / sqrt(d_k), add the causal mask (Day 44), apply a row-wise softmax with max-shift (Day 45), and multiply by V. 2) Trace the multi-head shapes from Day 45: (B, T, d_model) -> (B, T, h, d_k) -> (B, h, T, d_k) -> scores (B, h, T, T) -> back to (B, T, d_model). 3) Explain each fact in one sentence before you look anything up.

Practice & Prediction Log

1. Q = [[1, 1], [0, 2]], K = [[1, 1], [2, 0]], V = [[1, 0], [0, 1]], d_k = 2. Compute the scaled scores, the causal attention weights, and Out. What would Out[0] be without the mask?
2. B = 2, T = 5, d_model = 12, h = 3. Give d_k and the shapes of Q after the head split, the score tensor, and the output after concatenation.
3. How many parameters do W^Q, W^K, W^V and W^O have for d_model = 12, with biases? Without?
4. From memory: why divide by sqrt(d_k) (Day 43)? Why does exp(15) break float16 (Day 45)? If token 1 changes, what happens to Out[0] (Day 44)?

Independent Mastery Criterion

Learner reproduces the causal attention output, the multi-head shapes, and the parameter count without notes, and explains the sqrt(d_k), float16, and causal-invariance facts in their own words.

Authoritative Source Resources & Provenance

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

Attention Is All You Need

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3.2.1: Scaled Dot-Product Attention equation and query/key/value matrix definitions

Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

Linear algebra, matrix multiplication, softmax probability distributions

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | Original Source Link ↗

Relevant Section / Range: subsequent_mask implementation using torch.triu and triangular boolean masking

Verified Version & Date: Updated 2022 edition (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

Intermediate Python, PyTorch broadcasting and tensor slicing semantics

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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 min

Review Practice: Block Anatomy, Parameter Ledger, and Forward Pass (Days 46-48)

Agent-Assisted Engineering Check

Prerequisites

Day 46 LayerNorm, RMSNorm and residuals; Day 47 FFN and block accounting; Day 48 positions, weight tying and the full forward pass.

Learning Objective

Connect normalization, the Pre-LN block, the FFN, and weight tying into one parameter ledger and one shape trace for a small GPT.

Instructions

Use a toy GPT: V = 100, context 16, d_model = 32, n_layer = 2, n_head = 4, d_ff = 4 * d_model, learned positional embeddings, LayerNorm with weight and bias, linear layers without bias, and a tied output head. 1) Recompute LayerNorm and RMSNorm by hand as on Day 46. 2) Write the Pre-LN block equations from Day 46 and the full forward pass from Day 48. 3) Build the parameter ledger line by line as on Day 47, then add what tying saves (Day 48).

Practice & Prediction Log

1. For x = [4, 0, -2, 2], compute LayerNorm (no epsilon, gain 1, bias 0) and RMSNorm.
2. Write the two Pre-LN residual lines of one block, and explain in one sentence why Pre-LN trains more stably than Post-LN.
3. Count the parameters of the toy GPT: per block, all blocks, embeddings, final LayerNorm, and total. How many more would an untied head add?
4. What share of each block's matrix weights is in the FFN?
5. Trace shapes for B = 8, T = 16 from idx to logits, and name the slice used to sample the next token.

Independent Mastery Criterion

Learner produces the normalization values, the Pre-LN equations, a parameter ledger that totals 28,608 with the tying difference explained, and a correct end-to-end shape trace.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

Root Mean Square Layer Normalization

Author: Biao Zhang, Rico Sennrich (University of Edinburgh) | Original Source Link ↗

Relevant Section / Range: Section 4 RMSNorm (Equation 4) and Section 4.1 Invariance Analysis

Verified Version & Date: NeurIPS 2019 / arXiv:1910.07467v1 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

Variance, standard deviation, and LayerNorm basics.

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3 Model Architecture (3.1-3.5)

Verified Version & Date: arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

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

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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 min

Week 7 Assessment: Find the Four Bugs in a Tiny GPT (Days 43-49)

Independent Mastery Check

Prerequisites

Days 43-48 and Day 49 activities 1-3. Closed-book, declared AI-free.

Learning Objective

Independently find, explain, and fix four planted bugs that each break a Week 7 rule, and predict how each shows up during training.

Instructions

Read the code below once without running it. Each marked line breaks one rule from Week 7: attention scaling (Day 43), causal masking (Day 44), numerical stability (Day 45), Pre-LN residuals (Day 46), or the (x, y) shift (Day 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)

Practice & Prediction Log

1. For lines (A), (B), (C) and (D): name the bug, the day whose rule it breaks, and the fix.
2. Which bug produces NaN on the very first forward pass, and why?
3. Which bug lets the loss fall suspiciously fast while the model learns nothing useful?
4. After all fixes, what first loss do you expect for V = 100?

Independent Mastery Criterion

Learner identifies all four bugs, maps each one to its source day, gives working fixes, and correctly predicts the NaN and fast-falling-loss symptoms without assistance.

Authoritative Source Resources & Provenance

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

Attention Is All You Need

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3.2.1: Scaled Dot-Product Attention equation and query/key/value matrix definitions

Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

Linear algebra, matrix multiplication, softmax probability distributions

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: Biao Zhang, Rico Sennrich (University of Edinburgh) | Original Source Link ↗

Relevant Section / Range: Section 4 RMSNorm (Equation 4) and Section 4.1 Invariance Analysis

Verified Version & Date: NeurIPS 2019 / arXiv:1910.07467v1 (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

Variance, standard deviation, and LayerNorm basics.

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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.