Build PyTorch from Scratch

A deep learning framework is five small parts stacked on each other: a tensor, an autograd engine, modules, optimizers and a data loader. In eight Code Labs you write each part in plain numpy. Then your engine trains a classifier and matches PyTorch's loss curve, step for step.

This is the capstone of the series. You build the same design that runs every Code Lab on this site, then read the real files it is made of, and see what real PyTorch adds on top: a C++ engine, a dispatcher and fast kernels.

Press Train to watch the whole stack learn a spiral. Pull a part out to see what breaks. Each part lights up when you pass its lab below, and after Lab 8 your own engine's loss curve appears here.

You need Autograd, nn.Module Inside Out and The Training Loop. Numpy basics help. We build everything else from zero.

The stack you will build

Ready
Pull out

The page trains a 2 → 32 → 3 MLP with AdamW (lr 0.02) on 300 spiral points in batches of 50, using a JavaScript copy of the engine you build below. A part lights up warm when you pass its labs (your progress is kept only in this browser). After Lab 8 runs, its printed curve: line is drawn here in warm: your engine's real run. Its random start differs from the page's, so the two curves are close, not identical.

Chapter 0

Six lines you have typed a thousand times

Every training loop is the same six lines. Find out which part of a framework runs each one, then see the plan for building all of them

You have written this loop many times. You load a batch. You clear the old gradients. You run the model, compute the loss, call backward(), and take a step. The loss falls and you move on.

Now something goes wrong. After a refactor the gradients are twice as large as before. Or a bias of shape (64,) trains and one of shape (1, 64) does not. Or the loss turns into nan when the logits get large. Where do you look?

If you have written the code behind those six lines, you know. That is the point of this lesson. You will build a working copy of PyTorch's core, small enough to read in one sitting, and check every number it makes against real PyTorch. Start by seeing which part runs which line.

Who runs this line?

Pick a line, or press Play to step through one training step. The part of the stack that does the work lights up. The strip below shows what goes in and what comes out, with real shapes.

The model is the 2 → 32 → 3 network of Lab 8 with a batch of 50. Shapes are what PyTorch 2.10 prints for it.

Notice what does most of the work. model(xb) looks like one call, but it runs a dozen tensor ops, and each op quietly records how to undo itself. loss.backward() is the part that walks those records backwards. Everything else is bookkeeping around it.

The classic version: micrograd

This idea has a famous small version. Andrej Karpathy's micrograd is an autograd engine of about 100 lines and a neural network library of about 50, with a PyTorch-like API. Its README says it works on scalars only: each neuron is chopped into its single adds and multiplies.

We follow micrograd's design closely: each value keeps its parents and a small _backward function, and backward() sorts the graph and runs those functions in reverse. Then we take the step micrograd leaves out. Our values are whole tensors: numpy arrays of any shape. Chapter 1 shows what that one change costs and buys.

The road map of this lesson

Each chapter adds one part to the stack and ends in a Code Lab. Each lab pastes in your solved code from the lab before, so every lab runs on its own.

  1. From micrograd to tensors: what changes when a value is an array.
  2. Broadcasting, forward and back: why a stretched tensor must sum its gradient. Lab 1: a Tensor that broadcasts.
  3. The engine: topological order and gradient accumulation. Lab 2: write backward().
  4. The gradient rules: matmul, sum, ReLU, exp and log, found from shapes. Lab 3.
  5. Module and Parameter: the __setattr__ registry and dotted names. Lab 4.
  6. Cross-entropy without overflow: the log-sum-exp trick. Lab 5.
  7. SGD and AdamW: momentum, bias correction, decoupled weight decay. Lab 6.
  8. Dataset and DataLoader: batching, shuffling, collating. Lab 7.
  9. Train it, and match PyTorch: the whole stack on a real job. Lab 8.
  10. The same design, scaled up: the mini-torch files behind every lab on this site, and what real PyTorch adds.
  11. Connections: a cheat sheet, the honest limits, and where to go next.

PyTorch, Zero to Expert

This is part 11, the last part of the series in The Builder's Toolkit.

  1. Tensors: Storage, Strides and Views
  2. Autograd: the Graph Behind backward()
  3. nn.Module Inside Out
  4. Datasets and DataLoaders
  5. The Training Loop, Line by Line
  6. Debugging Training: When the Loss Won't Go Down
  7. Memory and Mixed Precision
  8. Making PyTorch Fast
  9. Distributed PyTorch: DDP and FSDP from the Inside
  10. PyTorch Internals: From a Python Call to a Kernel
  11. Build PyTorch from Scratch (this lesson)
Which line of a training step walks the recorded graph backwards to fill every .grad?

Chapter 1 How it works

From micrograd to tensors

A scalar engine makes one graph node per multiply. A tensor engine makes one node per layer. Count the difference, then see the three things that change

In micrograd, a Value is one number with a history. A neuron with 2 inputs becomes 2 multiplies, 2 adds and a ReLU: 5 nodes in the graph. Each node is a small Python object, and backward() visits every one of them.

A tensor is an array of numbers with one shared history. A whole layer, x @ W.T + b, is three nodes: a transpose, a matrix multiply and an add. The arithmetic inside each node runs in numpy's compiled loops, not in Python. Count how much that saves for a real batch.

Count the graph

Move the sliders. The bars count the graph nodes that one forward pass of a 2 → H → 3 MLP builds. The scale is logarithmic: each grid line is ten times the last.

32
32

Scalar counts follow micrograd's Neuron: nin multiplies and nin adds (the sum starts at the bias), plus a ReLU on hidden neurons only. Tensor counts follow the engine you build: per layer one transpose, one matmul and one add, plus a ReLU after the first layer. The loss is not counted.

The node count is the Python cost: one object, one closure call per node. For a batch of 32 and a hidden width of 32, the scalar engine builds over ten thousand nodes. The tensor engine builds 7, whatever the batch. That is why every real framework works on tensors.

What changes when a value is an array

Three things change, and each one is a chapter of this lesson.

  1. The gradient has a shape. It is an array the same shape as the tensor. The rule grad of input = local derivative × grad of output becomes a product of arrays.
  2. Broadcasting needs undoing. Numpy silently stretches a (64,) bias to (32, 64). The backward pass must squeeze the gradient back down by summing (Chapter 2).
  3. Matmul gets its own rule. The gradient of a matrix product is another matrix product, and shapes tell you which one (Chapter 4).

The rule each node follows is the vector-Jacobian product. Think of it as "each output sends gradient back to each input, weighted by how much that input moved it". For one input a and outputs y:

ȳj
The gradient of the final loss with respect to output j. It arrives from above, in out.grad.
∂yj/∂ai
The local derivative: how much output j moves when input i moves. Only the op knows it.
āi
The gradient for input i: what the op's _backward adds into a.grad.

Worked, an element-wise multiply y = a · b with a = [2, 3], b = [5, 7] and ȳ = [1, 1]: each yj depends only on aj, with ∂yj/∂aj = bj. So ā = ȳ · b = [5, 7]. Nobody builds the full Jacobian matrix; each op computes the product directly.

A batch of 64 goes through a 2 → 128 → 3 MLP. Roughly how does the number of graph nodes compare between a scalar engine and a tensor engine?

Chapter 2 How it works Lab 1

Broadcasting, forward and back

Broadcasting copies a tensor without copying memory. In the backward pass, every copy sends a gradient home, and the copies must be summed

Add a bias of shape (3,) to a batch of shape (4, 3). Numpy and PyTorch both accept it. They act as if the bias were written out four times, once per row. This is broadcasting: line the shapes up from the right; a missing axis or an axis of size 1 is stretched to match.

Now run it backwards. Each of the four copies of b[0] took part in one output. Each sends back a gradient. So the gradient of b[0] is the sum of four numbers: one column of the upstream gradient. Pick a shape pair and see it.

Stretch forward, sum back

Pick a pair of shapes. Top: a + b with b's stretched copies drawn faint. Bottom: the gradient arriving from above, and the gradient each input gets. Click a cell of b.grad to see which upstream cells were summed into it.

The upstream gradient G holds small whole numbers so you can add them in your head. a.grad and b.grad are what PyTorch puts in .grad for (a + b).backward(G).

The fix is a function PyTorch calls sum_to and we call unbroadcast. It takes the upstream gradient and the input's shape, and undoes the two kinds of stretching:

G
The upstream gradient, in the output's shape, e.g. (4, 3).
sum over stretched axes
Sum over each leading axis broadcasting added, then over each axis where b had size 1 (keeping it as size 1).
grad b
b's gradient, back in b's own shape.

Worked, b of shape (3,) and G = [[1,2,0],[0,1,1],[2,0,1],[1,1,1]]: the leading axis was added, so sum it: grad b = [1+0+2+1, 2+1+0+1, 0+1+1+1] = [4, 4, 3]. With b of shape (4, 1), sum the stretched axis 1 instead: grad b = [[3], [2], [3], [3]].

def unbroadcast(g, shape):
    while g.ndim > len(shape):                 # leading axes that broadcasting added
        g = g.sum(axis=0)
    for i, n in enumerate(shape):
        if n == 1 and g.shape[i] != 1:         # a size-1 axis that was stretched
            g = g.sum(axis=i, keepdims=True)
    return g

Every binary op calls it on both inputs, inside its _backward. In the lab you write it, inside a Tensor class whose __add__ and __mul__ record their parents and their gradient rules.

x has shape (32, 10) and a scale s has shape (1, 10). For y = x * s, what shape must s.grad have, and how is it made?

Chapter 3 How it works Lab 2

The engine: run every node after all its users

backward() is a loop over the graph in one special order. Run the nodes yourself in the wrong order, see a gradient go missing, then write the order that cannot fail

After a forward pass, the graph is a web of tensors, each pointing to its parents. backward() must call every node's _backward once. The question is the order.

A node's _backward passes its gradient to its parents. So it may only run when its own gradient is complete: when every tensor that used it has already sent its share. A tensor used twice gets two shares, and they add. That adding is called gradient accumulation.

Try it on a small graph. Here h = a · b is used twice: by u, deep in the graph, and by L, right at the top.

Run backward by hand

Click a node to run its _backward. It sends its current gradient to its parents. The ring around each node fills as its users report in. Or press one of the orders. Leaves turn green or red against the true gradient.

Values: a = 2, b = 1, c = −1, so h = 2, u = 1, v = 1 and L = 2. True gradients of L with respect to each node: L 1, v 2, u 4, h 5, c 4, a 5, b 10.

Breadth-first fails here. It reaches h one step from the top, through L, and runs it before the deeper path through u has delivered its share. h passes on 1 instead of 5, and a and b get the wrong gradients. Nothing crashes. The numbers are just wrong.

k uses h
Every op whose inputs include h. Here: u = h + c and L = v · h.
share from k
What k's _backward adds into h.grad: its local derivative times its own gradient.
grad h
h's full gradient. It is complete only after every user has run.

Worked: from L = v · h, the share is v × (grad L) = 1 × 1 = 1. From u = h + c, the share is grad u = 2u × (grad v) = 2 × 1 × 2 = 4. So grad h = 1 + 4 = 5, then grad a = b × 5 = 5 and grad b = a × 5 = 10.

The order that cannot fail

A topological order lists every node after all of its parents. Build it with a depth-first walk: visit a node's parents first, then append the node. Reverse that list, and every node comes after all of its users. That is the whole engine:

def backward(self):
    topo, seen = [], set()
    def visit(t):                    # parents first, then the node
        if id(t) not in seen:
            seen.add(id(t))
            for p in t._parents:
                visit(p)
            topo.append(t)
    visit(self)
    self.grad = np.ones_like(self.data)  # dL/dL = 1
    for t in reversed(topo):          # users before the node they use
        t._backward()

This is micrograd's backward, line for line, on tensors. In the lab you replace a breadth-first engine with it, on the same graph, and check every gradient against PyTorch.

In the graph above, breadth-first order gives a gradient of 1 for a and 2 for b, instead of 5 and 10. Why?

Chapter 4 How it works Lab 3

The gradient rules a network needs

Five more ops make a neural network: matmul, sum, ReLU, exp and log. Find the matmul rule from shapes alone, then write the rules and check them against PyTorch

The engine is general. What makes it useful is its library of ops, each with a forward line and a gradient rule. A two-layer network needs only a few: a matrix multiply, a transpose, a sum, a ReLU, and for the loss, exp and log.

The element-wise rules are school calculus. ReLU passes the gradient where its input was positive and blocks it elsewhere. exp's derivative is itself. log's is 1/x. Matmul is the one that looks hard, and it is the easiest to find, because only one answer has the right shape.

Find the rule from the shapes

C = A @ B, and G is C's gradient. Pick a candidate for dA. The device multiplies the shapes. Only one candidate is legal and comes out in A's shape for every choice of sizes.

4
3
2

A shape check is not a proof, but here it singles out the right answer. The formula follows from the chain rule: Cij = Σp AipBpj, so ∂Cij/∂Aip = Bpj.

G
The gradient of C = A @ B, shape (n, m).
dA
A's gradient, shape (n, k): (n, m) @ (m, k).
dB
B's gradient, shape (k, m): (k, n) @ (n, m).

Worked, A = [[1, 2]], B = [[3], [4]], so C = [[11]]. With G = [[1]]: dA = G BT = [[3, 4]], and dB = AT G = [[1], [2]]. Check one entry by hand: raise A01 from 2 to 2.1 and C becomes 11.4, a change of 0.4 = 4 × 0.1.

The sum rule is broadcasting in reverse: every entry that went into a sum gets the sum's gradient. If an axis was summed away, put it back as size 1 first, then broadcast. In a linear layer, the weight's gradient sums over the batch automatically: dW = GT X adds up one outer product per example.

A linear layer computes y = x WT with x of shape (B, nin) and W of shape (nout, nin). What is W's gradient, given G = ∂L/∂y of shape (B, nout)?

Chapter 5 How it works Lab 4

Module and Parameter: let the model find its own weights

Twenty lines turn a pile of tensors into a model that can list, name, save and clear its weights. Watch the name-building walk, then write the registry

With tensors and an engine, you can already train: keep a Python list of weight tensors and update each one. That breaks as soon as a model grows. Every new layer means editing the list by hand, and a forgotten tensor simply never trains.

PyTorch's answer has two classes. A Parameter is a tensor marked "this belongs to a model and should be trained". A Module watches every assignment self.name = value through __setattr__. Parameters go into one dict, sub-modules into another. Then parameters() can walk the tree and find every weight, with no list to maintain.

class Module:
    def __init__(self):
        object.__setattr__(self, '_parameters', {})   # bypass our own __setattr__
        object.__setattr__(self, '_modules', {})

    def __setattr__(self, name, value):          # runs on every  self.name = value
        if isinstance(value, Parameter):
            self._parameters[name] = value
        elif isinstance(value, Module):
            self._modules[name] = value
        object.__setattr__(self, name, value)

The names come from a recursive walk. Each module yields its own parameters with a prefix, then asks each child to do the same with a longer prefix. Step through it on the network of Lab 4.

Where "2.weight" comes from

Press Step or Play. Left: the call stack of named_parameters, one frame per module, each with its prefix. Right: the names yielded so far. Switch off "recurse" to see the bug you fix in the lab.

Sequential names its children "0", "1", "2". ReLU owns no parameters, so its frame yields nothing. The order (own parameters first, then children in assignment order) is PyTorch's order too.

The names are not decoration. They are the contract between your model and any checkpoint. In the lab, your names come out exactly as PyTorch's, so PyTorch's weights load into your model by name and both compute the same output.

In Lab 4's starter, named_parameters() yields only the module's own parameters and does not recurse. What does Sequential(Linear(2,16), ReLU(), Linear(16,3)).parameters() return?

Chapter 6 How it works Bug to spot Lab 5

Cross-entropy without overflow

The textbook formula for cross-entropy overflows as soon as logits get large. One subtraction fixes it, and costs nothing. Push the logits until the naive version breaks

A classifier outputs one score per class, called a logit. Softmax turns the scores into probabilities: pj = ezj / Σk ezk. The cross-entropy loss is −log py for the true class y. It is small when the model puts high probability on the right answer.

Written out, the loss is log(Σk ezk) − zy. The first term is called log-sum-exp. Computed naively, it fails: ez overflows to infinity once z passes about 88.7 in float32, or 709.8 in float64. Logits that large happen, for example when a model becomes very confident.

Push the logits until it breaks

Drag the scale. The logits are z = scale × [2, 1, 0.1, −1, 0.5], and the true class is the second (z1). Left bars: ez computed naively. Right bars: ez − max z. Below: the loss each way.

63

float32 is emulated with JavaScript's Math.fround after every operation, so overflow happens where it would in PyTorch: ex is infinite for x > 88.72 in float32 and x > 709.78 in float64.

The fix uses one identity. Subtract any constant m from every logit, and add it back outside the log:

log Σ ez
Log-sum-exp of one row of logits: the log of softmax's denominator.
m
Any constant. Choose the row's largest logit: then every exponent is ≤ 0, so no term overflows, and the largest term is exactly 1, so the sum cannot underflow to 0.

Worked, z = [1000, 999] with true class 0. Naively e1000 is infinite. With m = 1000: log(e0 + e−1) = log(1.3679) = 0.3133, so log-sum-exp = 1000.3133 and the loss is 1000.3133 − 1000 = 0.3133. The probabilities are [0.7311, 0.2689].

The gradient needs no special care. Because the shift cancels, the gradient with respect to the logits is softmax minus the one-hot target, divided by the batch size: [0.7311 − 1, 0.2689] = [−0.2689, 0.2689] for a batch of one. In the lab you build the loss from your engine's ops, so autograd finds that gradient by itself.

Why is it safe to treat the row maximum m as a constant with no gradient?

Chapter 7 How it works Lab 6

SGD and AdamW

An optimizer is a loop over parameters that changes p.data in place. Watch Adam make its step size independent of the gradient's size, and see why it needs bias correction

After backward(), every parameter holds a gradient. An optimizer owns a list of parameters and turns their gradients into updates. It has two methods: zero_grad() clears the gradients, and step() changes each p.data in place, outside the graph.

SGD steps against the gradient: p ← p − lr · g. With momentum, it keeps a running buffer, buf ← μ · buf + g, and steps along the buffer. That smooths out noise and speeds travel along a long valley.

Adam keeps two running means per weight: m of the gradient, and v of the squared gradient. It steps by m / √v. Dividing by the gradient's typical size makes the step about lr, whether the gradients are tiny or huge. Try it.

How big is each step?

One weight gets 200 noisy gradients of the size you choose. The chart shows each step's size, on a log scale, for SGD (lr 0.01) and Adam (lr 0.01). Switch bias correction off to see Adam's first steps without it.

10
0.5

Gradients are gt = size × (1 + noise × nt) with nt standard normal, the same seeded stream for both. Adam uses PyTorch's defaults: betas (0.9, 0.999), eps 1e-8.

Without bias correction, the first steps are several times too large. Both running means start at zero, so early on they are too small. v is too small for much longer (its memory is 1,000 steps, against 10 for m), so m / √v starts large. Adam fixes this by dividing each mean by the weight it has gathered so far:

m̂, v̂
The running means, corrected for starting at zero. t counts steps from 1. m ← β1m + (1−β1)g and v ← β2v + (1−β2)g².
λ
Weight decay. AdamW shrinks the weight directly, apart from the gradient: this is decoupled decay. torch.optim.AdamW's default is 0.01.
ε
A tiny number (1e-8) so the division never divides by zero.

Worked, the first step with g = 0.5, lr = 0.01, λ = 0: m = 0.1 × 0.5 = 0.05 and v = 0.001 × 0.25 = 0.00025. Corrected, m̂ = 0.05 / 0.1 = 0.5 and v̂ = 0.00025 / 0.001 = 0.25, so the step is 0.01 × 0.5 / 0.5 = 0.01: exactly lr. Uncorrected it would be 0.01 × 0.05 / 0.0158 = 0.0316, over three times larger.

The W in AdamW is the decoupled decay. Plain Adam with weight_decay adds λp to the gradient, and Adam's division then scales the decay down for weights with large gradients. AdamW applies the decay to the weight itself, so every weight shrinks by the same factor (1 − lr·λ) per step.

You multiply your loss by 1,000. What happens to the size of the first steps with SGD and with Adam?

Chapter 8 How it works Bug to spot Lab 7

Dataset and DataLoader

A Dataset answers "give me sample i". A DataLoader decides the order, cuts batches and stacks them. Train on sorted data without shuffling and watch the loss saw back and forth

The last part of the stack feeds the model. PyTorch splits the job in two. A Dataset is anything with __len__ and __getitem__: it knows how to fetch sample i, from memory or from disk. A DataLoader wraps a Dataset. It picks an order, cuts the order into batches, fetches each sample, and collates them: it stacks the samples of a batch into one array per field.

The order matters more than it looks. Real datasets are often stored sorted: all cats, then all dogs. Train on them in that order and every batch holds one class. The model chases whichever class it saw last.

Sorted data, shuffled or not

The 300 spiral points are stored sorted by arm. Pick shuffle on or off and a batch size, then press Train. Top: the classes inside each batch of the first epoch. Bottom: the training loss per step, and the accuracy on all 300 points.

The same 2 → 32 → 3 MLP and AdamW (lr 0.02) as the hero, trained for 20 epochs in JavaScript. Arm colours: blue, yellow and purple are class labels only.

The number of batches per epoch is the dataset size divided by the batch size, rounded up, unless you ask to drop a short last batch:

N
The number of samples: len(dataset).
B
The batch size.
len(loader)
Batches per epoch. The last batch is short when B does not divide N.

Worked: N = 300, B = 50 gives 6 batches. N = 50, B = 8 gives ⌈6.25⌉ = 7 batches, the last of size 2; with drop_last=True, 6. Lab 7 checks exactly these numbers against torch.utils.data.DataLoader.

A dataset is stored sorted by class and you train with shuffle=False. What does the loss curve usually look like?

Chapter 9 Did it work? Lab 8

Train it, and match PyTorch

The final test of a framework is not that the loss falls. It is that it falls exactly like the reference does, from the same start. Learn what "exactly" can mean, then run it

Every part is built. Lab 8 joins them into a real training job: a 2 → 32 → 3 MLP on a three-arm spiral, trained with AdamW for 240 steps. A falling loss would prove little: many buggy engines still train. So the lab trains PyTorch beside your engine, from the same starting weights, on the same batches, and compares the two loss curves step by step.

How close should they be? Not bit-for-bit. Your engine and PyTorch add numbers in different orders, and floating-point addition is not associative: (a + b) + c can differ from a + (b + c) in the last bit. Those tiny differences then grow as training goes on. The device shows how much each kind of difference costs.

How close is "the same"?

Copy A is the reference. Pick what copy B does differently, then compare. Top: both loss curves. Bottom: the gap between them on a log scale, from 1 down to 1e-17.

Both copies train in this page's JavaScript engine (float64). "summation order" makes B add the batch gradient up in reverse order. "float32 rounding" rounds B's weights, activations and gradients to float32 after every layer. Gaps are measured here, live.

So a threshold of 1e-6 is a strong test. A wrong gradient rule, a missing zero_grad or a mis-ordered step moves the curves apart by 0.01 or more within a few steps. Rounding noise in float64 stays near 1e-15. In Lab 8 the two curves agree to about 3e-16. When we re-ran it with the PyTorch side in float32 (on real PyTorch 2.10), the gap grew to 9.5e-7: just inside the threshold.

Lminet
Your engine's loss on the batch at step t.
Ltorcht
PyTorch's loss on the same batch, from the same weights at step 0.
gap
The worst disagreement over the run. Lab 8 asserts gap < 1e-6.

Worked, from the lab's own run in the browser: both curves start at 1.1449 (the same weights, the same first batch) and end at 0.0890 after 240 steps. The largest gap over all 240 steps is 3.3e-16, about one unit in the last bit of a float64. On real PyTorch 2.10 the random start differs, so the curve runs from 1.0618 to 0.0881, with the same tiny gap.

Your engine's loss curve differs from PyTorch's by 2e-16 at step 1 and by 4e-15 at step 240. What does that tell you?

Chapter 10 How it works

The same design, scaled up

Every Code Lab in this series ran on mini-torch, a numpy copy of the PyTorch API. Open its files: they are your engine with more care. Then see what real PyTorch adds underneath

Your engine is about 230 lines. It already has the shape of a real framework. Two bigger versions of the same design are close at hand. One is mini-torch, the package in micro/py/minitorch/ of this site, which ran every Code Lab in this series inside your browser. The other is PyTorch itself. Pick a part of the stack and see where it lives at each size.

One design, four sizes

Pick a part. Each row is one code base, with its size in lines of Python on a log scale, and the file where the part lives.

Sizes are counted lines of Python: micrograd's engine.py + nn.py; your engine from Lab 8 (code lines of Labs 1 to 7); all of mini-torch's torch/ package; and the Python files of the installed PyTorch 2.10 package (2,113 files). PyTorch's C++ and CUDA source is not in that count.

Read mini-torch: your engine, with more care

Here are four short excerpts, unchanged except for removed lines marked …. Compare each with your lab code.

The recording step. Your ops set out._parents and out._backward. mini-torch's ops call one function, track, which builds a node holding the backward function, the edges to the inputs' nodes, and the tensors it saved, with their version numbers:

micro/py/minitorch/torch/autograd/graph.py
def track(name, out, inputs, backward, saved=(), np_backward=False, ref=None):
    """Attach a `name` node to `out` when grad mode is on and an input requires grad."""
    if not GRAD_ENABLED[0]:
        return out
    …
    node = node_class(name)(backward, tuple(edges), tuple(meta),
                            tuple((s, s._vc[0], s._grad_fn, s._output_nr) for s in saved if s is not None))

And an op uses it the way your __add__ does: compute, then record the gradient rule.

micro/py/minitorch/torch/_ops_pointwise.py
def add(input, other, *, alpha=1, out=None):
    …
    o = _finish(res, dt)
    if _req(a, b):
        track("AddBackward0", o, (_T(a), _T(b)),
              lambda g: (g, g if alpha == 1 else g * alpha))

The engine. Instead of a depth-first sort, it counts each node's users (deps) and runs a node when its count reaches zero. Notice where unbroadcast went: the engine itself sums a gradient down whenever its shape does not match the input's, so no op has to remember.

micro/py/minitorch/torch/autograd/graph.py, inside run_backward
            for (child, nr), meta, g in zip(node._next, node._in_meta, outs):
                …
                if g is not None:
                    if g._data.shape != meta[0]:
                        g = sum_to(g, meta[0], type(node).__name__)
                    …
                    cb[nr] = g if cb[nr] is None else cb[nr] + g     # accumulate
                d = deps[child] - 1
                deps[child] = d
                if d == 0 and child not in queued:
                    queued.add(child)
                    heapq.heappush(heap, (-child._seq, id(child), child))

The registry. The same branches as your __setattr__, plus the errors you would want: assigning before __init__, or a plain tensor over a Parameter's name.

micro/py/minitorch/torch/nn/modules/module.py
        params = self.__dict__.get("_parameters")
        if isinstance(value, Parameter):
            if params is None:
                raise AttributeError("cannot assign parameters before Module.__init__() call")
            remove_from(self.__dict__, self._buffers, self._modules, self._non_persistent_buffers_set)
            self.register_parameter(name, value)

AdamW. Your six lines, in PyTorch's order, with the decay applied only when it is decoupled:

micro/py/minitorch/torch/optim/adam.py
                    if wd != 0:
                        if decoupled:
                            w = w * f(1 - lr * wd)
                        else:
                            g = g + w * f(wd)
                    …
                    ma = ma + f(1 - b1) * (g - ma)
                    va = va * f(b2) + (f(1 - b2) * g) * g
                    …
                    denom = np.sqrt(va) / f(bc2_sqrt) + f(eps)
                    _finish(p, w + f(-step_size) * (ma / denom))

What does mini-torch add that your engine lacks? Gradient rules written with tensor ops, so you can differentiate a gradient (create_graph=True). A version counter on every tensor, so the engine refuses to use a saved tensor that was later changed in place. Views that share memory. PyTorch's exact names, defaults and error messages. All of it is still numpy and Python.

What real PyTorch adds underneath

Real PyTorch keeps the same design and moves the heavy parts into C++. Its Python Tensor (in torch/_tensor.py) is a thin class over torch._C.TensorBase. When you call backward(), Python hands over to a C++ engine in one line:

torch/autograd/graph.py (PyTorch 2.10), inside _engine_run_backward
        return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
            t_outputs, *args, **kwargs
        )

The full path, from a Python call through the dispatcher to a kernel, is the subject of PyTorch Internals: From a Python Call to a Kernel.

In mini-torch, where is the "unbroadcast" step done?

Chapter 11

Connections

Turn a symptom into the part that broke, keep the one-screen cheat sheet, know the limits of a homemade engine, and see where the same design shows up

Having built every part, you can read a training bug as a fault in one layer of the stack. Pick a symptom.

Which part broke?

Each card names the part, the one-line check, and the lab where you built it.

The usual cause, not the only one. Confirm with the check before you change code.

The cheat sheet

PartShape signatureIn one line
Tensordata, grad: same shapeAn array + parents + a _backward closure. Ops record; gradients add up in _acc.
unbroadcastout shape → input shapeSum over added leading axes, then over stretched size-1 axes (keepdims).
backward()seed: ones like the outputDepth-first topological sort, then each _backward in reverse. Leaves accumulate across calls.
Gradient rulesC = A @ B: (n,k)(k,m)dA = G BT, dB = AT G; sum: broadcast back; ReLU: mask x > 0; exp: × ex; log: ÷ x.
ModuleLinear weight (out, in)__setattr__ files Parameters and Modules; named_parameters recurses with "prefix.".
Cross-entropy(B, C) logits, (B,) ids → ()Subtract each row's max, log-sum-exp, pick the true class; gradient (softmax − onehot) / B.
SGDone buffer per weightbuf = μ buf + g (first step buf = g); p −= lr · buf.
AdamWm, v per weight; t stepsp *= 1 − lrλ; update m, v; bias-correct; p −= lr m̂ / (√v̂ + ε).
DataLoaderN samples → ⌈N/B⌉ batchesNew permutation each epoch if shuffling; slice; collate with stack; drop a short tail if asked.
Parity testtwo curves, same startCopy weights by name, feed the same batches, assert max gap < 1e-6 in float64.

When to build your own, and when not

SituationUseWhy
Learning how frameworks workYour engine, then mini-torch's filesSmall enough to read; every number checkable.
Debugging a gradient bug in a real modelPyTorch + gradcheck + hooksYour mental model of the engine tells you where to look; the real tools do the looking.
Anything you will train for realPyTorchGPUs, fused kernels, mixed precision, distributed training, years of testing.
A new op with a custom gradienttorch.autograd.FunctionThe same forward + backward pair you wrote, plugged into the real engine.

Honest limits

Where the same design shows up

Where this sits, and where to go next

The takeaway. A framework is a tensor that remembers its history, an engine that replays that history backwards in topological order, a registry that finds the weights, an optimizer that moves them, and a loader that feeds them. You have written each one, and checked it against the real thing.
After a refactor, every gradient in your model is exactly twice what it was. Which part do you suspect first?

Now press Present or Teach and explain, out loud and from memory, why backward() must run each node after all of its users, and why a broadcast tensor sums its gradient. Then go back to the stack, pull out the data loader, and say why the loss falls while the accuracy stays at a third.

Build PyTorch from Scratch, part 11 of PyTorch, Zero to Expert in The Builder's Toolkit. Every PyTorch default, file name and number on this page was checked against PyTorch 2.10.0; every Code Lab runs unchanged on real PyTorch 2.10 and on mini-torch. The engine follows the design of Andrej Karpathy's micrograd (MIT licence), extended from scalars to tensors. Sources: the PyTorch source code (torch/_tensor.py, torch/autograd/graph.py, torch/nn/modules/module.py, torch/nn/functional.py, torch/optim/adam.py, torch/optim/adamw.py, torch/utils/data/dataloader.py) and this site's mini-torch (micro/py/minitorch/); D. P. Kingma, J. Ba, "Adam: A Method for Stochastic Optimization" (ICLR 2015, arXiv); I. Loshchilov, F. Hutter, "Decoupled Weight Decay Regularization" (ICLR 2019, arXiv); A. Paszke et al., "PyTorch: An Imperative Style, High-Performance Deep Learning Library" (NeurIPS 2019, arXiv); A. G. Baydin et al., "Automatic Differentiation in Machine Learning: a Survey" (JMLR 2018, arXiv).
Back to Gleams