34 / 90

Day 34: MLP Structure and the Forward Pass

Move from the historical perceptron to differentiable neurons, assemble a 2-2-1 multilayer perceptron on the projects/autograd scalar engine, hand-compute every forward value, and collect the parameter gradients that Day 35 will derive by hand.

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

From Perceptron to Differentiable MLP: Layers, Weights, and Activations

Agent-Assisted Engineering Check

Prerequisites

Day 33 autograd mastery check and the verified Value backward() semantics.

Learning Objective

Distinguish the historical perceptron (step activation) from a differentiable neuron $z = \sum_i w_i x_i + b$, $a = \sigma(z)$; explain why stacked layers with nonlinear activations are required for functions such as XOR; and state the exact structure of the reference 2-2-1 network used today.

Instructions

Read the concept decomposition below, then predict before computing.

A perceptron computes $z = \sum_i w_i x_i + b$ and fires $1$ if $z > 0$ else $0$. Its step activation makes the input-output map piecewise constant: the gradient is $0$ almost everywhere and undefined at the kink, so gradient-based training cannot improve it. A differentiable neuron replaces the step with a smooth activation such as $\tanh$.

A multilayer perceptron (MLP) stacks fully-connected layers: every neuron in layer $l$ consumes every activation in layer $l-1$. A single linear unit can only draw one straight decision boundary and cannot represent XOR; two or more layers with a nonlinear activation can.

Reference network N1 (used all day): inputs $x=(2.0, -1.0)$; hidden neuron $h_1$: weights $(0.5, -0.25)$, bias $0.1$, $\tanh$; hidden neuron $h_2$: weights $(-0.5, 1.0)$, bias $-0.2$, $\tanh$; output neuron $o$: weights $(1.0, -2.0)$, bias $0.3$, linear (no activation); loss $L = (o - y)^2$ with target $y = 1.0$.

Practice & Prediction Log

1. Before any computation, predict the signs of $z_1$ and $z_2$ and whether either hidden neuron is near saturation.
2. Count the trainable parameters of N1 and split them into weights and biases.
3. In one sentence, state why a step-activated perceptron cannot be trained by gradient descent.
4. Predict whether $o$ will be above or below the target $y = 1.0$.

Independent Mastery Criterion

The learner states the $z = \sum w_i x_i + b$ and $a = \sigma(z)$ equations, counts N1's nine parameters correctly, and explains in their own words why differentiability is required for gradient-based learning.

Authoritative Source Resources & Provenance

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

Author: Michael Nielsen | Original Source Link ↗

Relevant Section / Range: Sections: Perceptrons, Sigmoid neurons, The architecture of neural networks

Verified Version & Date: Online book (Verified: 2026-10-30)

Selection Rationale:

Clear four-equation derivation of backpropagation with scalar and matrix notation.

Source Prerequisites:

Matrix multiplication and the multivariable chain rule from Days 19-24.

Safe Fallback (Offline Resilience):

All four backprop equations and derivations are self-contained within the lesson text.

Compared Candidate Sources & Selection Analysis (2)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.

Modular computational graph view; used as secondary source on Days 35-36.

linking MIT

micrograd: A tiny scalar-valued autograd engine

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

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

Selection Rationale:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

Source Prerequisites:

Python object-oriented programming and operator overloading from Day 31.

Safe Fallback (Offline Resilience):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

Compared Candidate Sources & Selection Analysis (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

02 120 min

Hand-Computed Forward Pass Through a 2-2-1 Network

Independent Mastery Check

Prerequisites

Activity 34-01 network definition and tanh evaluation.

Learning Objective

Compute every intermediate value of network N1 by hand — $z_1, a_1, z_2, a_2, o, L$ — record the results in a forward-pass ledger, and then verify each entry against the scalar autograd engine.

Instructions

Work the forward pass on paper or in a plain calculator before touching the engine. Fill a ledger with one row per node: node name, local inputs, computed value.

Then verify with the engine:

python3 - <<'EOF'
import sys; sys.path.insert(0, '.')
from projects.autograd.engine import Value
x1, x2 = Value(2.0), Value(-1.0)
a1 = (x1*Value(0.5) + x2*Value(-0.25) + Value(0.1)).tanh()
a2 = (x1*Value(-0.5) + x2*Value(1.0) + Value(-0.2)).tanh()
o = a1*Value(1.0) + a2*Value(-2.0) + Value(0.3)
loss = (o - 1.0)**2
print(a1.data, a2.data, o.data, loss.data)
EOF

Compare each printed value with your ledger row by row. Any disagreement means a ledger row is wrong — find the first one.

Practice & Prediction Log

Produce a complete forward ledger for N1: $z_1$, $a_1 = \tanh(z_1)$, $z_2$, $a_2 = \tanh(z_2)$, $o$, and $L = (o - 1.0)^2$. Record your hand values to at least 4 decimal places and mark which engine outputs confirmed or contradicted them.

Independent Mastery Criterion

Every ledger entry is within $10^{-3}$ of the engine value, the linear output neuron is not passed through tanh, and the learner identifies the first divergent row if any disagreement occurred.

Authoritative Source Resources & Provenance

linking 3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions No video, audio, transcript or frame redistribution permitted

What is backpropagation really doing? (Chapter 3, Deep Learning)

Author: Grant Sanderson (3Blue1Brown) | Original Source Link ↗

Relevant Section / Range: The Intuition for Backpropagation

Verified Version & Date: Online video and article (Verified: 2026-10-30)

Selection Rationale:

Visual and geometric intuition for how nudging weights impacts the final cost function.

Source Prerequisites:

Basic derivative intuition from Days 16-18.

Safe Fallback (Offline Resilience):

The lesson derives the network gradient equations step by step without requiring video playback.

Compared Candidate Sources & Selection Analysis (2)
StatQuest Neural Networks Part 3 ↗ compared_alternative [Proprietary]

Step-by-step arithmetic without calculus notation; 3Blue1Brown provides the calculus-visual link needed.

Khan Academy Multivariable Chain Rule ↗ compared_alternative [CC BY-NC-SA 3.0]

Pure math focus; 3Blue1Brown contextualizes the chain rule specifically for neural network graphs.

linking MIT

micrograd: A tiny scalar-valued autograd engine

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

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

Selection Rationale:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

Source Prerequisites:

Python object-oriented programming and operator overloading from Day 31.

Safe Fallback (Offline Resilience):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

Compared Candidate Sources & Selection Analysis (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

03 120 min

Composing Neuron, Layer, and MLP Classes on the Scalar Autograd Engine

Agent-Assisted Engineering Check

Prerequisites

Verified forward ledger from Activity 34-02.

Learning Objective

Implement Module/Neuron/Layer/MLP classes that compose projects/autograd `Value` objects exactly like the micrograd `nn.py` pattern: a neuron holds weights and a bias, a layer holds neurons, an MLP holds layers, and `parameters()` returns every trainable `Value`.

Instructions

Write a small module (for example mlp_scratch.py in a scratch directory, not inside lessons/ or projects/autograd/) with this skeleton:

from projects.autograd.engine import Value

class Module:
def parameters(self):
return []

class Neuron(Module):
def __init__(self, weights, bias):
assert len(weights) > 0
self.w = [Value(w) for w in weights]
self.b = Value(bias)
def __call__(self, x):
assert len(x) == len(self.w), 'input/weight length mismatch'
z = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return z.tanh()
def parameters(self):
return self.w + [self.b]

Extend it with Layer (a list of neurons evaluated on the same input) and MLP (a list of layers applied in sequence). Build N1 with Linear output: give the output neuron a flag that skips tanh. Evaluate the loss on the Day 34 sample, call loss.backward(), and print all nine parameter gradients.

For a reference neuron trace, compare with:

python3 projects/autograd/cli.py forward-backward --preset neuron --json

Practice & Prediction Log

1. Implement the three classes and collect exactly nine parameters for N1.
2. Evaluate loss.data and confirm it equals your hand-computed $4.5179$.
3. After loss.backward(), record all nine .grad values — you will re-derive them by hand on Day 35.
4. State one advantage of keeping every parameter reachable through parameters().

Independent Mastery Criterion

The learner's classes reproduce the forward values and produce nine parameter gradients matching the engine within $10^{-3}$, with an explicit length check guarding the weighted sum.

Authoritative Source Resources & Provenance

linking MIT

micrograd: A tiny scalar-valued autograd engine

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

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

Selection Rationale:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

Source Prerequisites:

Python object-oriented programming and operator overloading from Day 31.

Safe Fallback (Offline Resilience):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

Compared Candidate Sources & Selection Analysis (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

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.

04 120 min

Independent Mastery Check: MLP Structure and Forward-Pass Numeracy

Independent Mastery Check

Prerequisites

Activities 34-01 through 34-03.

Learning Objective

Demonstrate unassisted command of perceptron-vs-MLP structure, parameter accounting, and a complete numeric forward pass, verified by the objective quiz below.

Instructions

Without consulting earlier activities or AI tools: write the forward equations for a generic neuron, compute the output of N1 for the new input $x = (1.0, 1.0)$ (all weights and biases unchanged), and then complete the objective quiz. Record your scratch work in the draft space before submitting.

Practice & Prediction Log

Independent tasks:
1. For $x = (1.0, 1.0)$: compute $z_1, a_1, z_2, a_2, o$ and $L$ by hand.
2. Explain why evaluating this new input requires no change to any parameter.
3. Complete the 3-question objective quiz at 100% in Independent mode.

Objective Knowledge Check: MLP Structure & Forward Pass

Answer the following questions to verify your understanding. Select your declared assistance condition before submitting.

Declared Assistance Condition

Note: AI-free work is an honest declared condition, not claimed surveillance.

1.

Why can't a classic perceptron with a step activation be trained by gradient descent?

2.

For network N1 with input $x = (2.0, -1.0)$, what is the output $o$?

3.

How many trainable parameters does the 2-2-1 network N1 contain?

Attempt History & Evidence

    Independent Mastery Criterion

    Unaided forward pass for the new input matches $o \approx 0.0538$ and $L \approx 0.8954$ within $10^{-3}$, plus a 100% independent quiz score.

    Authoritative Source Resources & Provenance

    linking CC BY-NC 3.0 noncommercial

    Neural Networks and Deep Learning: How the backpropagation algorithm works

    Author: Michael Nielsen | Original Source Link ↗

    Relevant Section / Range: Sections: Perceptrons, Sigmoid neurons

    Verified Version & Date: Online book (Verified: 2026-10-30)

    Selection Rationale:

    Clear four-equation derivation of backpropagation with scalar and matrix notation.

    Source Prerequisites:

    Matrix multiplication and the multivariable chain rule from Days 19-24.

    Safe Fallback (Offline Resilience):

    All four backprop equations and derivations are self-contained within the lesson text.

    Compared Candidate Sources & Selection Analysis (2)
    Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

    Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.

    Modular computational graph view; used as secondary source on Days 35-36.

    linking MIT

    micrograd: A tiny scalar-valued autograd engine

    Author: Andrej Karpathy | Original Source Link ↗

    Relevant Section / Range: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

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

    Selection Rationale:

    Deepest bottom-up mechanical clarity for backpropagation engine and computational graph visualization.

    Source Prerequisites:

    High-school calculus (derivatives) and basic Python syntax

    Safe Fallback (Offline Resilience):

    Authored mathematical derivations, interactive Pyodide engine, and local tests provide complete offline study without video streaming.

    Compared Candidate Sources & Selection Analysis (2)
    PyTorch Autograd Internals ↗ compared_alternative [Modified BSD]

    Normative production documentation, but micrograd's pure Python implementation provides far superior initial clarity.

    3Blue1Brown: What is Backpropagation? ↗ compared_alternative [3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions]

    High visual quality, pairs cleanly as optional supplementary visual reference.