The spelled-out intro to neural networks and backpropagation: building micrograd
Overview
Andrej Karpathy builds micrograd from scalar arithmetic to a trainable multilayer perceptron, showing how computation graphs, local derivatives, and the chain rule make backpropagation work. The roughly 100-line autograd engine accumulates gradients through a topologically sorted graph; a 41-parameter network then learns a small classification task with gradient descent, illustrating both the mechanics and common training bugs.
Key takeaways
- Backpropagation is repeated application of the chain rule over a computation graph, multiplying each node’s local derivative by the gradient arriving from downstream.
- Gradients from multiple uses of the same value must be added, not overwritten; micrograd’s backward closures therefore use += to handle shared subexpressions correctly.
- A training loop must clear parameter gradients before each backward pass because gradient accumulation is intentional within one pass but stale gradients distort later updates.
- Neural network training alternates forward evaluation, loss calculation, backpropagation, and parameter updates in the negative gradient direction; learning rate controls the tradeoff between slow progress and unstable overshooting.
- Micrograd’s scalar operations explain the same autograd principles used by PyTorch, while PyTorch tensors make computation efficient by grouping many scalar operations for parallel execution.
Chapters
- Andrej Karpathy introduces micrograd, a scalar-valued automatic differentiation engine that implements backpropagation.
- Gradients of a loss with respect to neural network weights indicate how parameter changes affect predictions and guide optimization.
- The engine’s core is about 100 lines of Python, with a small neural network library built on top.
- Karpathy plots f(x) = 3x² - 4x + 5 and explains derivatives as local sensitivity to a small positive change in x.
- A finite-difference estimate uses (f(x + h) - f(x)) / h, with h = 0.001 as a practical approximation.
- At x = 3 the derivative is 14, at x = -3 it is -22, and the slope is zero at x = 2/3.
- For d = a × b + c with a = 2, b = -3, and c = 10, perturbing one input at a time estimates its derivative.
- The derivatives are ∂d/∂a = b = -3, ∂d/∂b = a = 2, and ∂d/∂c = 1.
- The example connects each derivative’s sign and magnitude to the effect of changing its corresponding input.
- Karpathy creates a Value class that wraps a scalar and overloads Python’s __add__ and __mul__ methods.
- Expressions such as a × b + c produce new Value objects while computing their ordinary scalar data.
- A readable representation method makes results easier to inspect in a notebook.
- Each Value stores its child nodes and the operation that produced it, preserving the expression graph behind the forward calculation.
- The graph for d = a × b + c shows a multiplication node feeding an addition node.
- A Graphviz-based draw routine adds operation nodes and labels, making larger expressions easier to trace.
- Karpathy assigns each node a grad field representing the derivative of the final output with respect to that node.
- For l = d × f, the base case is ∂l/∂l = 1, while ∂l/∂d = f and ∂l/∂f = d.
- For d = e + c, the local derivatives with respect to both children are 1.
- The chain rule multiplies the derivative of the final output with respect to an intermediate node by that node’s local derivative.
- With l = d × f and d = e + c, the gradient from l flows through d to both e and c.
- A plus node routes the incoming gradient unchanged to each child because each local derivative is 1.
- For e = a × b, the local derivatives are ∂e/∂a = b and ∂e/∂b = a.
- Backpropagating through l = (a × b + c) × f gives each leaf a gradient by multiplying local derivatives along the graph.
- Nudging inputs in the gradient direction increases l; minimizing a loss later requires moving in the opposite direction.
- A simple neuron sums products of inputs and weights, adds a bias, then applies an activation function.
- Weights represent synaptic strengths, while the bias shifts how readily the neuron activates.
- Karpathy uses a two-input neuron to expose each intermediate scalar calculation in the graph.
- The tanh activation smoothly squashes inputs toward -1 and 1, unlike an unbounded linear output.
- Karpathy implements tanh as a single Value operation rather than decomposing it immediately into exponentials.
- An operation can be treated as a graph node at any level of abstraction, provided its local derivative is known.
- The derivative of tanh(n) is 1 - tanh(n)², which can be computed from the operation’s output.
- For the chosen example, the tanh output is 0.7 and its local derivative is 0.5.
- The incoming gradient then propagates through addition and multiplication nodes to the neuron’s weights, inputs, and bias.
- For a product x × w, the gradient with respect to w is the other factor x times the incoming gradient.
- When x₂ = 0, the weight w₂ has zero influence on the neuron output and therefore receives a zero gradient.
- The example illustrates how gradients quantify a parameter’s actual effect, not merely whether that parameter exists.
- Each Value stores a backward closure that applies its operation’s local chain rule to its children.
- Addition copies the output gradient to both children; multiplication scales each child’s gradient by the other child’s data.
- The tanh backward function multiplies the incoming gradient by 1 - output².
- A depth-first traversal builds a topological ordering in which each node is placed after its children.
- Reversing that order ensures downstream gradients arrive before a node propagates them further backward.
- Value.backward initializes the output gradient to 1 and invokes each node’s backward function in reverse topological order.
- For b = a + a, the correct derivative ∂b/∂a is 2, since both uses contribute a gradient of 1.
- Assigning gradients overwrites one contribution when the same node appears on multiple paths.
- Changing backward rules to use += accumulates contributions and correctly handles shared subexpressions.
- Value arithmetic wraps ordinary numbers as Value objects, while __rmul__ supports expressions such as 2 × a.
- The engine adds exponentiation with the derivative rule d(xⁿ)/dx = n × xⁿ⁻¹ and the exponential rule d(eˣ)/dx = eˣ.
- Division is expressed as multiplication by a power of -1, and subtraction as addition of a negated value.
- PyTorch represents values as tensors, including single-element tensors that correspond to micrograd’s scalars.
- The example uses double precision and explicitly enables gradients on leaf tensors.
- PyTorch matches micrograd’s forward output of about 0.707 and gradients of 0.5, 0, -1.5, and 1.
- A Neuron initializes one random weight per input, plus a bias, and computes a weighted sum followed by tanh.
- Python’s __call__ method lets an instance run like a function on an input list.
- A Layer is a list of independently evaluated neurons, each connected to the layer’s inputs.
- An MLP chains layers sequentially, with layer sizes specified by a list such as [4, 4, 1].
- Karpathy constructs a network with three input features, two hidden layers of four neurons, and one output neuron.
- The forward pass produces a scalar prediction while retaining the full graph needed for backpropagation.
- The toy dataset has four inputs with target labels 1, -1, -1, and 1.
- Mean squared error sums squared differences between each prediction and its target, yielding zero only for exact matches.
- The initial loss is about 7, reflecting predictions that are far from several target values.
- Neuron, Layer, and MLP parameter methods gather weights and biases into one list.
- The demonstrated network contains 41 trainable parameters.
- Backpropagation through the loss assigns gradients to those parameters, identifying how each can affect model error.
- Gradient descent updates each parameter with p.data -= learning_rate × p.grad to move toward lower loss.
- A small update can lower the loss because the gradient estimates the local direction of increase.
- An overly large learning rate can overshoot or destabilize training, while a very small rate makes progress slow.
- Each training iteration computes predictions and loss, runs loss.backward(), and updates all parameters.
- A moderate learning rate converges more steadily than the larger steps used in the exploratory demonstration.
- The four predictions move toward their intended targets as the loss falls.
- Because backward uses +=, parameter gradients persist across training iterations unless explicitly reset.
- The correction sets each parameter’s grad to zero before running the next backward pass.
- The earlier apparent fast convergence came from unintentionally accumulating gradients, which acted like a changing, oversized step.
- A neural network is a mathematical expression taking data and parameters as inputs, followed by a loss that scores its predictions.
- Backpropagation computes parameter gradients, and gradient descent repeatedly uses them to reduce the loss.
- The same basic process scales from a 41-parameter MLP to large models, though practical systems use tensor operations and often different losses and optimizers.
- The engine stores scalar data, gradients, child references, and the operation that created each value.
- The released micrograd uses ReLU rather than the lecture’s tanh example, while its backward mechanics follow the same principle.
- Its neural network code defines modules, neurons, layers, parameter collection, and zero_grad.
- The repository demo separates red and blue two-dimensional points using a larger MLP.
- It adds mini-batches, a max-margin classification loss, and L2 regularization, none of which are needed for the four-example exercise.
- Learning-rate decay reduces update sizes as training approaches a useful decision boundary.
- Karpathy compares micrograd’s tanh derivative, incoming gradient times 1 - output², with PyTorch’s implementation.
- The production code has separate CPU and GPU kernels and branches for data types, making the simple rule harder to locate.
- The example contrasts micrograd’s pedagogical clarity with the complexity of a high-performance library.
- A custom PyTorch operation needs a forward computation and a backward rule that provides its local derivative.
- Once those are defined, autograd can compose the operation with existing graph nodes and propagate gradients through it.
- The closing notebook glitches do not change the central implementation principle: every operation must expose a valid local gradient.
Transcript excerpt
0:00 hello my name is andre and i've been training deep neural networks for a bit more than a decade and in this lecture i'd like to show you what neural network training looks like under the hood so in particular we are going to start with a blank jupiter notebook and by the end of this lecture we will define and train in neural net and you'll get to see everything that goes on under the hood and exactly sort of how that works on an intuitive level now specifically what i would like to do is i would like to take you through building of micrograd now micrograd is this library that i released on github about two years ago but at the time i only uploaded the source code and you'd have to go in by yourself and really figure out how it works so in this lecture i will take you through it step by step and kind of comment on all the pieces of it so what is micrograd and why is it interesting good
0:49 um micrograd is basically an autograd engine autograd is short for automatic gradient and really what it does is it implements backpropagation now backpropagation is this algorithm that allows you to efficiently evaluate the gradient of some kind of a loss function with respect to the weights of a neural network and what that allows us to do then is we can iteratively tune the weights of that neural network to minimize the loss function and therefore improve the accuracy of the network so back propagation would be at the mathematical core of any modern deep neural network library like say pytorch or jaxx so the functionality of microgrant is i think best illustrated by an example so if we just scroll down here
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Andrej Karpathy.