47 / 90

Day 47: Feedforward Networks (FFN), SwiGLU, and Stacking Blocks

Construct position-wise feedforward networks, trace intermediate expansion and projection dimensions, and stack multiple Transformer blocks with strict tensor invariants.

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

Position-wise Feedforward Network (FFN) Architecture

Agent-Assisted Engineering Check

Prerequisites

Day 46 Transformer Block and Day 41 MLP fundamentals.

Learning Objective

Explain the role of the FFN as a key-value memory over tokens, with expansion dimension d_ff = 4 * d_model.

Instructions

1. Write the FFN with every shape: x is (T, d_model), W1 is (d_model, d_ff), b1 is (d_ff), W2 is (d_ff, d_model), b2 is (d_model), so FFN(x) = act(x W1 + b1) W2 + b2 is (T, d_model) again.
2. Explain "position-wise": the same W1, b1, W2, b2 act on every row x_t separately; no value from token s enters the FFN output at token t. Mixing across tokens is attention's job.
3. Compare the activations: ReLU max(0, z) has a hard zero; GELU z * Phi(z) is smooth and lets small negative values through; SwiGLU uses a gate, (Swish(x W) ⊙ (x V)) W2, and so needs three matrices instead of two.
4. Count the parameters for d_model = 64, d_ff = 256, first without biases, then with them.
5. Work out the hidden width that gives SwiGLU about the same parameter count, using d_ff' ≈ (2/3) d_ff rounded to an integer.

Time plan (120 min): reading 30 + exercise 60 + check 30. Reading: Vaswani et al. Section 3.3 (position-wise feed-forward networks) and the MLP class in nanoGPT model.py. Exercise: items 1-5. Check: the mastery item, with both parameter counts done unaided.

Practice & Prediction Log

1. Write the standard two-layer FFN formula with the shape of every tensor.
2. Why is the FFN called 'position-wise'?
3. Calculate the parameter count of W1 (64x256) and W2 (256x64) without biases.
4. Add the biases b1 and b2 and give the new total.
5. SwiGLU uses three matrices (W, V of size d_model x d_ff' and W2 of size d_ff' x d_model). Choose d_ff' so that its count stays close to item 3, and give that count.

Independent Mastery Criterion

Articulates the position-wise nature and correctly calculates the 4x expansion parameter ledger.

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

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.

linking MIT

nanoGPT: model.py architecture implementation

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

Verified Version & Date: Git master (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 43-45 attention fundamentals.

Safe Fallback (Offline Resilience):

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

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

Hand Computation of an FFN Forward Pass and Hidden Expansion

Agent-Assisted Engineering Check

Prerequisites

Activity 47-01 and matrix multiplication from Day 22.

Learning Objective

Hand-compute the forward pass of an FFN for a 2-D vector x = [1.0, 2.0] through d_model=2 to d_ff=3 and back to d_model=2.

Instructions

1. Write the shapes first: x is 1x2, W1 is 2x3, so z = x W1 is 1x3; h is 1x3; W2 is 3x2, so y is 1x2.
2. Compute each entry of z as a dot product of x with one column of W1, writing every product.
3. Apply ReLU entry by entry and note which entries, if any, become zero.
4. Compute y as dot products of h with the columns of W2.
5. Add the residual: in a block, the sublayer output is added back, so the block output is x + y.
6. Repeat the whole pass for the variant x = [2, -1] and compare how many hidden units are active.

Time plan (120 min): reading 20 + exercise 70 + check 30. Reading: the position-wise FFN in The Annotated Transformer and nanoGPT's MLP forward. Exercise: items 1-5 by hand. Check: redo the variant from a blank page and verify one entry with a calculator or NumPy.

Practice & Prediction Log

1. Compute pre-activation z = x W1.
2. Apply ReLU to obtain h.
3. Compute output y = h W2.
4. Add the residual connection and give x + y.
5. Repeat items 1-3 for x = [2, -1] and say which hidden units ReLU switches off.

Independent Mastery Criterion

Flawless hand computation of the expanding and projecting matrix multiplications.

Authoritative Source Resources & Provenance

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: Position-wise Feed-Forward Networks (class PositionwiseFeedForward)

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

Selection Rationale:

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

Source Prerequisites:

PyTorch tensor operations and attention theory.

Safe Fallback (Offline Resilience):

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

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

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

Verified Version & Date: Git master (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 43-45 attention fundamentals.

Safe Fallback (Offline Resilience):

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

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

Stacking Transformer Blocks and Tensor Invariants

Agent-Assisted Engineering Check

Prerequisites

Activities 47-01 and 47-02.

Learning Objective

Trace a batch of tokens (B=2, T=4, d=64) through 2 consecutive Transformer blocks, asserting tensor shape and dtype preservation.

Instructions

1. Write one Pre-LN block as two residual sublayers: x = x + Attn(LN1(x)), then x = x + FFN(LN2(x)).
2. Fix the example: B = 2, T = 4, d_model = 64, n_heads = 4 (head_dim = 16), d_ff = 256.
3. Trace the shapes inside attention (Q, K, V per head, the score matrix, the merged output) and inside the FFN (the hidden layer).
4. Mark every point where a shape differs from (B, T, d_model) and check that it returns to (B, T, d_model) before each residual addition.
5. Check the dtype too: the block must return the same dtype it received.
6. Explain why identical block interfaces let you stack L blocks and why the residual addition needs matching shapes.

Time plan (120 min): reading 25 + exercise 60 + check 35. Reading: Vaswani et al. Section 3.1 (encoder and decoder stacks) and the EncoderLayer/SublayerConnection code in The Annotated Transformer. Exercise: items 1-4 with a full shape table. Check: explain the shape contract without notes, then compare.

Practice & Prediction Log

1. Write the sequence of sublayers in a 2-block Pre-LN Transformer.
2. State the tensor shape at every intermediate point between block 1 and block 2.
3. Why is uniform layer sizing essential for weight initialization and residual additions?
4. Assume 4 heads and d_ff = 256. Give the shapes of Q (per head), the attention scores, and the FFN hidden layer.

Independent Mastery Criterion

Clear understanding of the modular block contract and shape invariant.

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

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.

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: Encoder and Decoder Stacks

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

Selection Rationale:

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

Source Prerequisites:

PyTorch tensor operations and attention theory.

Safe Fallback (Offline Resilience):

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

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

Transformer Block Parameter and FLOPs Accounting

Independent Mastery Check

Prerequisites

Complete activities 47-01 through 47-03.

Learning Objective

Calculate the exact parameter budget and floating-point operations of a complete Transformer block (Attention + FFN).

Instructions

1. Use the GPT-2 small block: d_model = 768, n_heads = 12 (head_dim = 64), d_ff = 3072.
2. Count attention weights (Q, K, V, O: 4 * 768 * 768) and FFN weights (2 * 768 * 3072), then the ratio.
3. Add the biases (768 per attention projection, 3072 for the FFN up-projection, 768 for the down-projection) and the two LayerNorms (gain and bias, 2 * 768 each).
4. Scale to the full model: 12 blocks, token embeddings 50257 x 768, position embeddings 1024 x 768, the final LayerNorm, and a tied LM head (no extra parameters).
5. Estimate forward FLOPs per token: about 2 FLOPs per weight in the matrix products, plus the attention score and value products, about 4 * T * d_model per layer.
6. Compare the FFN and attention shares of parameters and of FLOPs at T = 1024.

Time plan (120 min): reading 25 + exercise 60 + check 35. Reading: nanoGPT model.py (Block, CausalSelfAttention, MLP, get_num_params) and Vaswani et al. Table 1. Exercise: items 1-6. Check: recompute the 124M total unaided and compare with get_num_params.

Practice & Prediction Log

1. Compute total parameters in the Attention sublayer (without biases).
2. Compute total parameters in the FFN sublayer (without biases).
3. What ratio of the block's parameters belongs to the FFN versus Attention?
4. Add biases and the two LayerNorms to get the full block count.
5. For a 12-block model with vocabulary 50257, context 1024 and a tied LM head, compute the total parameter count.
6. Estimate the forward FLOPs per token for one block at T = 1024.

Independent Mastery Criterion

Exact parameter derivation and recognizing the 2:1 parameter ratio between FFN and Attention.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: model.py architecture implementation

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: model.py: GPT.get_num_params and GPT.estimate_mfu

Verified Version & Date: Git master (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 43-45 attention fundamentals.

Safe Fallback (Offline Resilience):

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

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

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

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.