Krys Newman/AI Frontier/01 · From Derivatives to a Backprop Graph Search

Notebook 01

01 · From Derivatives to a Backprop Graph

Building up to backpropagation from the definition of a derivative: first estimating slopes numerically, then wrapping scalars in a Value object that records how it was computed, then walking that graph backwards by hand, and finally training a small network with the gradients it produces.

Building up to backpropagation from the definition of a derivative: first estimating slopes numerically, then wrapping scalars in a Value object that records how it was computed, then walking that graph backwards by hand, and finally training a small network with the gradients it produces.

Working through Andrej Karpathy's Neural Networks: Zero to Hero, lecture 1 (micrograd).

Run top to bottom. Several cells rebind names that earlier cells define, and the single-neuron graph is rebuilt from scratch each time it is rewritten, because grad accumulates.

Setup

Nothing here differentiates anything. numpy and matplotlib build sample points and draw plots, math supplies exp for $\tanh$, and random initialises weights in the last sections. graphviz arrives with the first graph drawing, torch near the end as a cross-check.

In [1]:
import math
import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

A function to differentiate

A quadratic, chosen because its derivative is checkable by hand:

$$f(x) = 3x^2 - 4x + 5 \qquad f'(x) = 6x - 4$$

Power rule, $\frac{d}{dx}x^n = n x^{n-1}$, term by term. Everything built below gets checked against that closed form.

In [2]:
def f(x):
    return 3*x**2 - 4*x + 5
In [3]:
f(3.0)
Out[3]:
20.0

What the function looks like

The parabola over $[-5, 5)$, slope visibly negative, then zero, then positive. Zero at the vertex, where $f'(x) = 6x - 4 = 0$, so at $x = \tfrac{2}{3}$. The derivative is that reading made precise: at each $x$, the slope of the line the curve is momentarily travelling along.

In [4]:
xs = np.arange(-5, 5, 0.25)
ys = f(xs)
plt.plot(xs, ys);
No description has been provided for this image

The derivative, numerically

The derivative is a limit:

$$f'(x) = \lim_{h \to 0} \frac{f(x + h) - f(x)}{h}$$

A computer can't take a limit, so it picks a small $h$. Taylor gives the price:

$$f(x + h) = f(x) + h f'(x) + \tfrac{h^2}{2} f''(x) + O(h^3) \quad\Longrightarrow\quad \frac{f(x + h) - f(x)}{h} = f'(x) + \tfrac{h}{2} f''(x) + O(h^2)$$

Error linear in $h$. Here $f'' = 6$, so $h = 0.001$ should overshoot by about $0.003$: expect 14.003 against an exact $6(3) - 4 = 14$.

In [5]:
h = 0.001
x = 3.0
(f(x + h) - f(x))/h #slope function
Out[5]:
14.00300000000243

14.003, the predicted overshoot to the digit. Shrinking $h$ trades one error for another:

  • Truncation, $\approx \tfrac{h}{2} f''(x)$, falls with $h$.
  • Cancellation, $\approx \varepsilon\,|f(x)| / h$, from subtracting two nearly equal doubles ($\varepsilon \approx 2 \times 10^{-16}$), grows as $h$ falls.

The sum bottoms out near $h \approx \sqrt{\varepsilon} \approx 10^{-8}$, with about half the digits intact. A symmetric difference, $\frac{f(x + h) - f(x - h)}{2h}$, drops the $f''$ term for $O(h^2)$ accuracy at the cost of a second evaluation, but it buys an exponent, not an exact answer.

Backpropagation avoids the tradeoff: exact derivatives, analytically, one operation at a time.

Next: the Value object that records those operations.


Derivatives with more than one input

$$d = a \cdot b + c$$

A function of several variables has one partial derivative per input, each taken with the others held fixed:

$$\frac{\partial d}{\partial a} = \lim_{h \to 0} \frac{d(a + h,\, b,\, c) - d(a,\, b,\, c)}{h}$$

Stacked into a vector they are the gradient, $\nabla d = \left(\frac{\partial d}{\partial a}, \frac{\partial d}{\partial b}, \frac{\partial d}{\partial c}\right)$, pointing the way $d$ increases fastest. Training is computing that vector for a loss and stepping the other way. Numerically: nudge one input by $h$, hold the rest, measure the move.

In [6]:
a = 2.0
b = -3.0
c = 10.0
d = a*b+c
print(d)
4.0
In [7]:
h = 0.0001

#inputs
a = 2.0
b = -3.0
c = 10.0

d1 = a*b+c
a += h
d2 = a*b+c

print('d1:', d1)
print('d2:', d2)
print('slope:', (d2-d1)/h)
d1: 4.0
d2: 3.999699999999999
slope: -3.000000000010772

Nudging a gives $-3$, which is b: $\partial d / \partial a = b$. Likewise $\partial d / \partial c = 1$ and $\partial d / \partial b = a$, so $\nabla d = (b,\, a,\, 1) = (-3,\, 2,\, 1)$.

As a method it doesn't scale. One forward pass per input is $n + 1$ evaluations for $n$ parameters, each carrying its $h$-sized error. Toy networks have thousands of parameters; frontier models have hundreds of billions.

Reverse-mode automatic differentiation, which is what backpropagation is, returns all $n$ partials exactly, from one backward sweep costing about what the forward pass costs. The rest of the notebook builds it.


The Value object

A scalar that remembers where it came from and how to push a gradient back through the operation that made it. Four fields beyond the number:

  • _prev: the operands it was computed from
  • _op: the operation that produced it
  • grad: the derivative of the final output with respect to this node
  • _backward: a closure that takes this node's grad and adds each operand's share to its grad. A no-op on leaves.

The rule being encoded

Backprop is the chain rule applied once per edge. If $L$ depends on $x$ only through $y$:

$$\frac{\partial L}{\partial x} = \frac{\partial L}{\partial y} \cdot \frac{\partial y}{\partial x}$$

The first factor arrives from above. The second is local to the single operation that produced $y$. That split is what makes the scheme composable: no operation needs to know anything about the rest of the graph.

When $x$ feeds several consumers, every path contributes:

$$\frac{\partial L}{\partial x} = \sum_{i=1}^{k} \frac{\partial L}{\partial y_i} \frac{\partial y_i}{\partial x}$$

Hence += rather than = in every closure, and hence the need to clear gradients before a second backward pass.

Local derivatives

operation forward local derivatives
add $c = a + b$ $\partial c/\partial a = 1$, $\partial c/\partial b = 1$
mul $c = a \cdot b$ $\partial c/\partial a = b$, $\partial c/\partial b = a$
pow $c = a^{n}$ $\partial c/\partial a = n\,a^{\,n-1}$
exp $c = e^{a}$ $\partial c/\partial a = c$
tanh $c = \tanh(a)$ $\partial c/\partial a = 1 - c^2$

Subtraction and division reduce to those, $a - b = a + (-1 \cdot b)$ and $a / b = a \cdot b^{-1}$, so neither needs a rule of its own. __radd__ needs no rule either; it is what makes 2 + value work, Python having offered the addition to int first and been refused.

Overloading __add__ and __mul__ makes ordinary arithmetic build the graph as a side effect, each operation installing the local rule it will need. backward() seeds $\partial L / \partial L = 1$ at the root and walks the graph in reverse topological order, so no node propagates before its own gradient is complete.

The expression built below:

$$e = a \cdot b \qquad d = e + c \qquad L = d \cdot f$$

with $a = 2$, $b = -3$, $c = 10$, $f = -2$, giving $e = -6$, $d = 4$, $L = -8$.

In [8]:
class Value:
  
  def __init__(self, data, _children=(), _op='', label=''):
    self.data = data
    self.grad = 0.0
    self._backward = lambda: None
    self._prev = set(_children)
    self._op = _op
    self.label = label

  def __repr__(self):
    return f"Value(data={self.data})"
  
  def __add__(self, other):
    other = other if isinstance(other, Value) else Value(other)
    out = Value(self.data + other.data, (self, other), '+')
    
    def _backward():
      self.grad += 1.0 * out.grad
      other.grad += 1.0 * out.grad
    out._backward = _backward
    
    return out

  def __mul__(self, other):
    other = other if isinstance(other, Value) else Value(other)
    out = Value(self.data * other.data, (self, other), '*')
    
    def _backward():
      self.grad += other.data * out.grad
      other.grad += self.data * out.grad
    out._backward = _backward
      
    return out
  
  def __pow__(self, other):
    assert isinstance(other, (int, float)), "only supporting int/float powers for now"
    out = Value(self.data**other, (self,), f'**{other}')

    def _backward():
        self.grad += other * (self.data ** (other - 1)) * out.grad
    out._backward = _backward

    return out
  
  def __rmul__(self, other): # other * self
    return self * other

  def __truediv__(self, other): # self / other
    return self * other**-1

  def __neg__(self): # -self
    return self * -1

  def __sub__(self, other): # self - other
    return self + (-other)

  def __radd__(self, other): # other + self
    return self + other

  def tanh(self):
    x = self.data
    t = (math.exp(2*x) - 1)/(math.exp(2*x) + 1)
    out = Value(t, (self, ), 'tanh')
    
    def _backward():
      self.grad += (1 - t**2) * out.grad
    out._backward = _backward
    
    return out
  
  def exp(self):
    x = self.data
    out = Value(math.exp(x), (self, ), 'exp')
    
    def _backward():
      self.grad += out.data * out.grad # NOTE: in the video I incorrectly used = instead of +=. Fixed here.
    out._backward = _backward
    
    return out
  
  
  def backward(self):
    
    topo = []
    visited = set()
    def build_topo(v):
      if v not in visited:
        visited.add(v)
        for child in v._prev:
          build_topo(child)
        topo.append(v)
    build_topo(self)
    
    self.grad = 1.0
    for node in reversed(topo):
      node._backward()
    def __init__(self, data, _children=(), _op='', label=''):
        self.data = data
        self.grad = 0.0
        self._backward = lambda: None
        self._prev = set(_children)
        self._op = _op
        self.label = label

    def __repr__(self):
        return f"Value(data={self.data})"

    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, (self, other), '+')

        def _backward():
            self.grad += 1.0 * out.grad
            other.grad += 1.0 * out.grad
        out._backward = _backward
        return out

    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, (self, other), '*')

        def _backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = _backward
        return out

    def __rmul__(self, other): # other * self
        return self * other

    def __truediv__(self, other): # self / other
        return self * other**-1

    def __neg__(self): # -self
        return self * -1

    def __sub__(self, other): # self - other
        return self + (-other)

    def __pow__(self, other): # self ** other
        assert isinstance(other, (int, float)), "only supporting int/float powers for now"
        out = Value(self.data**other, (self, ), f'**{other}')

        def _backward():
            self.grad += (other * self.data**(other-1)) * out.grad
        out._backward = _backward

        return out
    
    def tanh(self):
        x = self.data
        t = (math.exp(2*x) - 1)/(math.exp(2*x) + 1)
        out = Value(t, (self, ), 'tanh')
        
        def _backward():
          self.grad += (1 - t**2) * out.grad
        out._backward = _backward
    
        return out

    def exp(self):
        x = self.data
        out = Value(math.exp(x), (self, ), 'exp')

        def _backward():
            self.grad += out.data * out.grad
        out._backward = _backward

        return out

    def backward(self):        
        # topological sort
        topo = []
        visited = set()
        def build_topo(v):
            if v not in visited:
                visited.add(v)
                for child in v._prev:
                    build_topo(child)
                topo.append(v)
        build_topo(self)

        self.grad = 1.0
        for node in reversed(topo):
            node._backward()
In [9]:
a = Value(2.0, label='a')
b = Value(-3.0, label='b')
c = Value(10.0, label='c')
f = Value(-2.0, label='f')

e = a*b;  e.label = 'e'
d = e+c;  d.label = 'd'
L = d*f;  L.label = 'L'

L
Out[9]:
Value(data=-8.0)

Drawing the graph

trace walks _prev depth-first collecting nodes and edges; draw_dot renders each value as a record box of label, data and grad, with a small circle for the operation feeding it. Left to right is the forward pass, right to left the backward pass. Every grad reads 0.0000: evaluated, not yet differentiated.

Needs the graphviz system binary, not just the Python package: brew install graphviz.

In [10]:
from graphviz import Digraph

def trace(root):
    #builds a set of all notes and edges in a graph
    nodes, edges = set(), set()
    def build(v):
        if v not in nodes:
            nodes.add(v)
            for child in v._prev:
                edges.add((child, v))
                build(child)

    build(root)
    return nodes, edges

def draw_dot(root):
    dot = Digraph(format='svg', graph_attr={'rankdir': 'LR'}) # Left to Right

    nodes, edges = trace(root)
    for n in nodes:
        uid = str(id(n))
        # for any value in the graph, create a rectangular record node for it
        dot.node(name = uid, label = "{ %s | data %.4f | grad %.4f}" % (n.label, n.data, n.grad), shape='record')
        if n._op:
            #if this value is a result of some operation, create an op node for it
            dot.node(name = uid + n._op, label = n._op)
            # and connect this node to it
            dot.edge(uid + n._op, uid)

    for n1, n2 in edges:
        # connect n1 to the op node of n2
        dot.edge(str(id(n1)), str(id(n2)) + n2._op)

    return dot
In [11]:
draw_dot(L)
Out[11]:
No description has been provided for this image

Backprop by hand

backward() automates this, but one pass by hand is what makes the closures above legible. Gradients assigned manually, starting from $\frac{\partial L}{\partial L} = 1$ and walking back through the chain rule:

node derivative value
L $\partial L/\partial L$ 1.0
d $\partial L/\partial d = f$ -2.0
f $\partial L/\partial f = d$ 4.0
c $\partial L/\partial c = \partial L/\partial d$ -2.0
e $\partial L/\partial e = \partial L/\partial d$ -2.0
a $\partial L/\partial a = (\partial L/\partial e) \cdot b$ 6.0
b $\partial L/\partial b = (\partial L/\partial e) \cdot a$ -4.0

Two patterns fall out, and they're the ones the automated version encodes:

  • Addition distributes the gradient unchanged. d = e + c, so e and c both inherit d.grad as-is.
  • Multiplication routes each operand the other's value, scaled by the output's gradient. e = a * b, so a gets e.grad * b and b gets e.grad * a.

Redrawing the graph now shows real numbers in every grad field.

In [12]:
# the table above, in the order the chain rule visits the nodes
L.grad = 1.0
d.grad = f.data * L.grad    # L = d*f  ->  dL/dd = f
f.grad = d.data * L.grad    #          ->  dL/df = d
c.grad = 1.0 * d.grad       # d = e+c  ->  the gradient passes straight through
e.grad = 1.0 * d.grad
a.grad = b.data * e.grad    # e = a*b  ->  each operand gets the other's value
b.grad = a.data * e.grad

draw_dot(L)
Out[12]:
No description has been provided for this image

Checking the hand-derived gradients

A gradient is a slope, so $\partial L / \partial a = 6$ has to survive nudging a and re-running the forward pass. $L(a) = (ab + c)f = 6a - 20$ is linear in a, so there is no truncation error to see and the two agree to the last bits.

The rebuild is the point: grad accumulates, so backward() on a graph that already carries gradients stacks a second pass on the first.

In [13]:
def expression(a_val=2.0):
    # rebuilt from scratch so no gradients carry over
    a = Value(a_val, label='a')
    b = Value(-3.0, label='b')
    c = Value(10.0, label='c')
    f = Value(-2.0, label='f')
    e = a*b;  e.label = 'e'
    d = e+c;  d.label = 'd'
    L = d*f;  L.label = 'L'
    return a, L

h = 0.0001
_, L1 = expression()
_, L2 = expression(2.0 + h)

a_fresh, L_fresh = expression()
L_fresh.backward()

print('numeric  dL/da:', (L2.data - L1.data)/h)
print('backprop dL/da:', a_fresh.grad)
numeric  dL/da: 6.000000000021544
backprop dL/da: 6.0

A squashing function

Affine layers compose into one affine layer:

$$W_2(W_1 x + b_1) + b_2 = (W_2 W_1)x + (W_2 b_1 + b_2) = W'x + b'$$

A hundred stacked linear layers have the expressive power of a single matrix. A nonlinearity between them is what makes depth worth anything.

$\tanh$ maps $\mathbb{R}$ into $(-1, 1)$, flat at the extremes, steepest at zero:

$$\tanh(x) = \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}} = \frac{e^{2x} - 1}{e^{2x} + 1} \qquad \frac{d}{dx}\tanh(x) = 1 - \tanh^2(x)$$

The derivative needs only the output, which is what Value.tanh closes over. It peaks at $1$ and decays towards $0$ as $|x|$ grows, so a saturated unit passes almost nothing back and a stack of them starves the early weights. That is the case for ReLU later.

In [14]:
#activation function 
plt.plot(np.arange(-5,5,0.2), np.tanh(np.arange(-5,5, 0.2))); plt.grid();
No description has been provided for this image

A single neuron

Two inputs, two weights, a bias, one squash:

$$n = x_1 w_1 + x_2 w_2 + b = \mathbf{w} \cdot \mathbf{x} + b \qquad o = \tanh(n)$$

The weighted sum is the only place inputs meet parameters, and it is linear: $\mathbf{w} \cdot \mathbf{x}$ measures how far the input points along $\mathbf{w}$. The bias moves where the unit turns on. $\tanh$ bounds the result.

The gradients that matter are the ones on the parameters, since those are what a training step is allowed to move:

$$\frac{\partial o}{\partial w_i} = (1 - o^2)\,x_i \qquad \frac{\partial o}{\partial b} = 1 - o^2 \qquad \frac{\partial o}{\partial x_i} = (1 - o^2)\,w_i$$

A weight's gradient is the local slope times the input feeding it, so $w_2$ gets nothing here: $x_2 = 0$.

b is 6.8813735870195432 so that $o = \tanh(n) = 0.7071$ and $1 - o^2 = 0.5$ exactly, which makes the drawing checkable by hand.

In [15]:
# inputs x1,x2
x1 = Value(2.0, label='x1')
x2 = Value(0.0, label='x2')

# weights w1,w2
w1 = Value(-3.0, label='w1')
w2 = Value(1.0, label='w2')

# bias of the neuron
b = Value(6.8813735870195432, label='b')

# x1*w1 + x2*w2 + b
x1w1 = x1*w1; x1w1.label = 'x1*w1'
x2w2 = x2*w2; x2w2.label = 'x2*w2'

x1w1x2w2 = x1w1 + x2w2; x1w1x2w2.label = 'x1*w1 + x2*w2'

n = x1w1x2w2 + b; n.label = 'n'
o = n.tanh(); o.label = 'o'

One call instead of nine

o.backward() does the manual block above for the whole graph: seed the root at 1.0, sort, run each _backward in reverse. Every grad below came from that one call.

Ordering is the only subtle part. A node's gradient is complete only once every node it feeds has pushed its share back, so the walk has to be reverse topological: build_topo appends a node after its children, and reversing puts consumers ahead of operands. Without the sort, a node can propagate a gradient it is still collecting.

Cost is one traversal and one multiply-add per edge, so the backward pass scales with the forward pass regardless of the input count. That is the whole win over nudging inputs one at a time, and the reason billion-parameter models are trainable.

Checking the drawing: $\partial o / \partial n = 1 - o^2 = 0.5$, passed unchanged through the additions to x1*w1, x2*w2 and b, then crossed over by the multiplications, giving x1.grad $= 0.5\,w_1 = -1.5$ and w1.grad $= 0.5\,x_1 = 1.0$.

In [16]:
o.backward()
draw_dot(o)
Out[16]:
No description has been provided for this image

The same neuron, with tanh taken apart

Backprop doesn't care how finely the graph is carved. Here tanh is rebuilt from its definition rather than kept as one node with one rule:

$$o = \frac{e^{2n} - 1}{e^{2n} + 1}$$

That needs exp, a scalar multiply, an add, a subtract and a divide, the last two routing through __neg__ and __pow__(-1). Several nodes where there was one, and the chain rule reassembles the same $1 - o^2$ out of their local derivatives.

Identical gradients. An operation is a primitive only because someone gave it a derivative rule; where to draw that line is an efficiency and stability decision, the same call a framework makes when it fuses ops into one kernel.

In [17]:
# inputs x1,x2
x1 = Value(2.0, label='x1')
x2 = Value(0.0, label='x2')

# weights w1,w2
w1 = Value(-3.0, label='w1')
w2 = Value(1.0, label='w2')

# bias of the neuron
b = Value(6.8813735870195432, label='b')

# x1*w1 + x2*w2 + b
x1w1 = x1*w1; x1w1.label = 'x1*w1'
x2w2 = x2*w2; x2w2.label = 'x2*w2'

x1w1x2w2 = x1w1 + x2w2; x1w1x2w2.label = 'x1*w1 + x2*w2'

n = x1w1x2w2 + b; n.label = 'n'

# manually compute the tanh function using the formula (e^(2n) - 1)/(e^(2n) + 1) with the new additions to the Value class
# ----
e = (2*n).exp()
o = (e - 1) / (e + 1)
# --- 

o.label = 'o'
o.backward()
draw_dot(o)
Out[17]:
No description has been provided for this image

A second opinion, from PyTorch

The same neuron in PyTorch, which does what Value does on tensors, with the backward rules in C++.

The vocabulary maps across: a tensor with requires_grad = True is a leaf that wants a gradient, the forward expression records a graph, o.backward() seeds the root and sweeps in reverse, and each leaf's .grad holds $\partial o / \partial\,\cdot$ afterwards. .double() is only so the digits match the drawings above; the 32-bit default agrees to about seven places.

Output: x1 $-1.5$, w1 $1.0$, x2 $0.5$, w2 $0.0$. The differences show up at scale, where a node holds an array rather than a scalar and the graph is freed after the sweep.

In [18]:
# same as above but using pytorch
import torch

x1 = torch.Tensor([2.0]).double(); x1.requires_grad = True
x2 = torch.Tensor([0.0]).double(); x2.requires_grad = True

w1 = torch.Tensor([-3.0]).double(); w1.requires_grad = True
w2 = torch.Tensor([1.0]).double(); w2.requires_grad = True

b = torch.Tensor([6.8813735870195432]).double(); b.requires_grad = True

n = x1*w1 + x2*w2 + b
o = torch.tanh(n)

print(o.data.item())
o.backward()


print('----')
print('x2', x2.grad.item())
print('w2', w2.grad.item())
print('x1', x1.grad.item())
print('w1', w1.grad.item())
0.7071066904050358
----
x2 0.5000001283844369
w2 0.0
x1 -1.5000003851533106
w1 1.0000002567688737

From one neuron to a network

Three classes, the third a multi-layer perceptron:

  • Neuron: nin weights and a bias, uniform in $[-1, 1]$, computing $\tanh(\mathbf{w} \cdot \mathbf{x} + b)$.
  • Layer: a list of neurons over the same input, one output each, the row-by-row view of $\mathbf{a}^{(l)} = \tanh\!\left(W^{(l)} \mathbf{a}^{(l-1)} + \mathbf{b}^{(l)}\right)$ with one row of $W^{(l)}$ per neuron. A layer of one neuron returns that Value rather than a list of one, so the output layer reads as a scalar.
  • MLP: layers chained, each one's outputs feeding the next.

parameters() flattens the Value leaves underneath each class. Nothing else collects them, and a training step needs that list twice: once to clear gradients, once to apply the update.

MLP(3, [4, 4, 1]) holds $(3 \cdot 4 + 4) + (4 \cdot 4 + 4) + (4 \cdot 1 + 1) = 41$ of them, and one forward pass builds a few hundred nodes. draw_dot still renders it, barely.

Scale is the only thing between this and a real network: tensors for scalars, ReLU for $\tanh$, GPU kernels for the Python loops.

In [19]:
from typing import Any

class Neuron:
  
  def __init__(self, nin):
    self.w = [Value(random.uniform(-1,1)) for _ in range(nin)]
    self.b = Value(random.uniform(-1,1))
  
  def __call__(self, x):
    # w * x + b
    act = sum((wi*xi for wi, xi in zip(self.w, x)), self.b)
    out = act.tanh()
    return out
  
  def parameters(self):
    return self.w + [self.b]

class Layer:
  
  def __init__(self, nin, nout):
    self.neurons = [Neuron(nin) for _ in range(nout)]
  
  def __call__(self, x) -> Any:  # Value for one neuron, list[Value] for more
    outs = [n(x) for n in self.neurons]
    return outs[0] if len(outs) == 1 else outs
  
  def parameters(self):
    return [p for neuron in self.neurons for p in neuron.parameters()]

class MLP:
  
  def __init__(self, nin, nouts):
    sz = [nin] + nouts
    self.layers = [Layer(sz[i], sz[i+1]) for i in range(len(nouts))]
  
  def __call__(self, x):
    for layer in self.layers:
      x = layer(x)
    return x
  
  def parameters(self):
    return [p for layer in self.layers for p in layer.parameters()]

x = [2.0, 3.0, -1.0]
n = MLP(3, [4, 4, 1])
n(x)

draw_dot(n(x))
Out[19]:
No description has been provided for this image

Four examples and a target

One forward pass through the untrained network, then the smallest dataset that asks it for anything: four three-dimensional inputs, each labelled $+1$ or $-1$. Binary classification in the shape of a regression.

Weights are random and unseeded, so the first prediction is arbitrary ($-0.489$ on this run) and every number below it moves when the notebook is re-run.

In [20]:
n(x)
Out[20]:
Value(data=-0.48919960503935045)
In [21]:
xs = [
  [2.0, 3.0, -1.0],
  [3.0, -1.0, 0.5],
  [0.5, 1.0, 1.0],
  [1.0, 1.0, -1.0],
]
ys = [1.0, -1.0, -1.0, 1.0] # desired targets

Gradient descent

A loss collapses four predictions into one number to differentiate, and squared error is the usual first choice:

$$\mathcal{L} = \sum_{i} \left(\hat{y}_i - y_i\right)^2$$

Zero when every prediction matches its target, and built from the same Value arithmetic as everything else, so one loss.backward() reaches all 41 parameters through the four forward graphs at once. sum() is given an explicit Value(0.0) to start from: the arithmetic works either way, but the default start is the integer 0, which leaves the sum typed as Value | int and every later .backward() looking like an error.

Each step moves every parameter against its gradient:

$$p \leftarrow p - \eta \frac{\partial \mathcal{L}}{\partial p}$$

with $\eta = 0.1$ here. The sign is the algorithm: the gradient points the way the loss increases, so the step goes the other way, and $\eta$ has to be small enough that the local slope still describes the surface after the move.

Clearing p.grad first is not optional. _backward accumulates with +=, so without the reset step two would descend on the sum of two gradients and step three on the sum of three.

Twenty steps take the loss from $5.78$ to $0.0263$ on this run, leaving the predictions below within about $0.1$ of their targets. Re-running the cell carries on from the parameters it left rather than starting over, which is how the loss gets driven arbitrarily low.

In [22]:
for k in range(20):
  
  # forward pass
  ypred = [n(x) for x in xs]
  loss = sum(((yout - ygt)**2 for ygt, yout in zip(ys, ypred)), Value(0.0))
  
  # backward pass
  for p in n.parameters():
    p.grad = 0.0
  loss.backward()
  
  # update
  for p in n.parameters():
    p.data += -0.1 * p.grad
  
  print(k, loss.data)
0 5.783326277097244
1 3.535132232518448
2 2.8511011973217575
3 1.9832457332023594
4 1.1377373899841012
5 0.4758563185289003
6 0.22587499949263676
7 0.14888278573193228
8 0.11231000606422327
9 0.0896319624964053
10 0.07415488438607462
11 0.06291768930429122
12 0.05439642485803337
13 0.047722528836960314
14 0.0423631307556695
15 0.03797252855128553
16 0.03431637305026028
17 0.031230052997481876
18 0.02859449423479363
19 0.026321406456250463
In [23]:
ypred
Out[23]:
[Value(data=0.8982416031730811),
 Value(data=-0.9072153084409798),
 Value(data=-0.9334768304135697),
 Value(data=0.9458492469864151)]