Skip to content
ImagineWorld

Tensors, Autograd, and PyTorch

node_idnode-book_building-frontier-llm-from-scratch_chapter-03-tensors-autograd-and-pytorch
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleTensors, Autograd, and PyTorch
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Tensors, Autograd, and PyTorch

Section titled “Chapter 3 — Tensors, Autograd, and PyTorch”

The previous chapter argued that backpropagation is just the chain rule applied in reverse. This chapter makes that concrete by building a working automatic-differentiation engine in about forty lines of Python — small enough to hold in your head, complete enough to train a network. Once you have seen gradients flow through a graph you built yourself, PyTorch stops being magic and becomes what it actually is: the same idea, generalized to tensors and made fast. We start with the tensor, build the engine, then connect it to the framework you will use for the rest of the book.

A PyTorch tensor is a multidimensional array that also remembers how it was computed, so gradients can be traced back through it. For now, treat it as NumPy with two superpowers: it runs on the GPU, and it records a graph. The handful of operations in Table 3.1 account for the overwhelming majority of code you will read in this book.

OperationWhat it doesShape example
torch.randn(B,T,d)create a tensor of normal noise→ (B, T, d)
x @ W(batched) matrix multiply(B,T,d)·(d,k) → (B,T,k)
x.view(B, T, h, d//h)reshape without copying datasplits the last axis into heads
x.transpose(1, 2)swap two axes(B,T,h,·) → (B,h,T,·)
x.softmax(dim=-1)normalize along an axisshape unchanged
x.sum(dim=-1, keepdim=True)reduce an axis(B,T,d) → (B,T,1)
x.to(device, dtype)move / cast (CPU↔GPU, BF16, …)shape unchanged

Table 3.1 — The tensor operations you will use constantly

A tensor is a flat block of memory plus a shape and a set of strides that say how far to step in memory to move one element along each axis. Operations like view and transpose often just rewrite the strides without touching the data, which is why they are nearly free — but it is also why a transposed tensor can be non-contiguous and occasionally needs an explicit .contiguous() before a reshape. Broadcasting lets tensors of different but compatible shapes combine: adding a bias of shape (d,) to activations of shape (B, T, d) works because the smaller shape is virtually stretched along the missing axes. Almost every shape bug is a broadcasting surprise; reading shapes deliberately is the cure.

We will represent a single scalar as an object that knows its value, its gradient, and the operation that produced it. Each operation, besides computing its result, installs a small closure that knows how to push gradient from the output back to its inputs. To get the gradient of everything, we walk the graph once in reverse topological order and call those closures. That is the entire algorithm — and the entire implementation follows.

import math
class Value:
"""A scalar node in an autograd graph: value, gradient, and how to backprop."""
def __init__(self, data, _children=(), _op=''):
self.data = data
self.grad = 0.0
self._backward = lambda: None # pushes grad to inputs; set per op
self._prev = set(_children) # the inputs that produced this node
self._op = _op
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 += out.grad # d(a+b)/da = 1
other.grad += 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 # d(a*b)/da = b
other.grad += self.data * out.grad
out._backward = _backward
return out
def __pow__(self, p): # p is a constant exponent
out = Value(self.data ** p, (self,), f'**{p}')
def _backward():
self.grad += (p * self.data ** (p - 1)) * out.grad
out._backward = _backward
return out
def relu(self):
out = Value(0.0 if self.data < 0 else self.data, (self,), 'relu')
def _backward():
self.grad += (out.data > 0) * out.grad
out._backward = _backward
return out
def backward(self):
topo, seen = [], set() # reverse topological order
def build(v):
if v not in seen:
seen.add(v)
for child in v._prev: build(child)
topo.append(v)
build(self)
self.grad = 1.0 # seed: d(out)/d(out) = 1
for v in reversed(topo): v._backward()
def __neg__(self): return self * -1
def __sub__(self, o): return self + (-o)
def __radd__(self, o): return self + o
def __rmul__(self, o): return self * o
def __truediv__(self, o): return self * o**-1
def __repr__(self): return f"Value({self.data:.4f}, grad={self.grad:.4f})"

Python — micrograd.py: a complete reverse-mode autodiff engine

a, b, c = Value(2.0), Value(-3.0), Value(10.0)
d = a * b + c # -6 + 10 = 4
e = d.relu() # relu(4) = 4
e.backward()
print(a.grad, b.grad, c.grad) # -3.0 2.0 1.0

Python — using it: forward, then one call backpropagates everything

The result is exactly the calculus: with d = a·b + c and d > 0, the derivative of e with respect to a is b = -3, with respect to b is a = 2, and with respect to c is 1. Figure 3.1 shows the graph this code built, with forward values above each node and the gradients that flow back beneath them.

[!visual-conversion] Graph, PDF 046 (printed 48). Over the graph, the print’s legend reads “forward → (solid) computes values; backward ← accumulates gradients (grey)”. Each node shows its forward value, and its grey gradient sits beneath it.

flowchart LR
    a(("a<br/>2.0<br/>grad -3.0")) --> mul(("×<br/>-6.0<br/>grad 1.0"))
    b(("b<br/>-3.0<br/>grad 2.0")) --> mul
    mul --> add(("+<br/>4.0<br/>grad 1.0"))
    c(("c<br/>10.0<br/>grad 1.0")) --> add
    add --> relu(("relu<br/>4.0"))
    relu --> e["e<br/>4.0"]

Figure 3.1. The computational graph for e = relu(a·b + c). The forward pass fills in the values; backward() seeds the output gradient to 1 and walks the graph in reverse, each node adding its local derivative times the incoming gradient to its inputs.

Two design choices in those forty lines are exactly the ones real frameworks make. First, gradients accumulate (+= rather than =), because a value used in several places receives gradient from each — which is also why you must zero gradients between training steps. Second, the closure pattern means each operation defines only its local derivative; the global gradient emerges from composing them. PyTorch’s autograd is this same reverse-mode engine, generalized so that each node is a whole tensor and each local derivative is a matrix operation.

The engine above is, almost line for line, Andrej Karpathy’s micrograd — an MIT-licensed teaching implementation and the clearest minimal autodiff in existence. Because the licence permits it, and because reading real code beats reading a description of it, we reproduce the rest of the library here rather than merely pointing at it. On top of the Value class, micrograd builds a small neural-network library — a neuron, a layer, and a multi-layer perceptron — using nothing but the scalar operations we just defined. Each Neuron holds a weight per input and a bias, all Value objects, and computes a weighted sum followed by an optional nonlinearity; a Layer is a list of neurons; an MLP is a list of layers. The same parameters() method threads through all three so the optimizer can collect every weight in the network with one call.

import random
from micrograd.engine import Value
class Module:
def zero_grad(self):
for p in self.parameters():
p.grad = 0
def parameters(self):
return []
class Neuron(Module):
def __init__(self, nin, nonlin=True):
self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]
self.b = Value(0)
self.nonlin = nonlin
def __call__(self, x):
act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return act.relu() if self.nonlin else act
def parameters(self):
return self.w + [self.b]
class Layer(Module):
def __init__(self, nin, nout, **kwargs):
self.neurons = [Neuron(nin, **kwargs) for _ in range(nout)]
def __call__(self, x):
out = [n(x) for n in self.neurons]
return out[0] if len(out) == 1 else out
def parameters(self):
return [p for n in self.neurons for p in n.parameters()]
class MLP(Module):
def __init__(self, nin, nouts):
sz = [nin] + nouts
self.layers = [Layer(sz[i], sz[i+1], nonlin=i != len(nouts)-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()]

Python — karpathy/micrograd · micrograd/nn.py (reproduced, MIT licence)

That is a complete, trainable neural-network library in roughly forty more lines, and it contains no idea this book has not already covered. MLP([3, 4, 4, 1]) builds a network with three inputs, two hidden layers of four neurons, and a single output; calling it on an input runs the forward pass, building a graph of thousands of Value nodes; calling backward() on the resulting loss computes every gradient; and a gradient-descent step nudges each parameter against its gradient. The crucial point is one of scale, not kind: PyTorch replaces each scalar Value with a tensor and each Python loop with a fused GPU kernel, but the architecture — graph construction in the forward pass, closures for local derivatives, a reverse walk to accumulate gradients, a parameter collection for the optimizer — is exactly what you have just read. Everything that follows in this book is this same skeleton, made wide and made fast.

3.3 From Scalars to Tensors: nn.Module and Optimizers

Section titled “3.3 From Scalars to Tensors: nn.Module and Optimizers”

Scaling the toy engine to real models means three changes, all of which PyTorch handles: nodes become tensors, parameters are tracked automatically, and an optimizer applies the update rule. A Module is a container that registers its parameters so they can be collected, moved to the GPU, saved, and optimized as a group.

import torch, torch.nn as nn, torch.nn.functional as F
class MLP(nn.Module):
def __init__(self, d_in, d_hidden, d_out):
super().__init__()
self.fc1 = nn.Linear(d_in, d_hidden)
self.fc2 = nn.Linear(d_hidden, d_out)
def forward(self, x):
return self.fc2(F.relu(self.fc1(x)))
model = MLP(784, 256, 10)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4) # collects all params
x = torch.randn(64, 784); y = torch.randint(0, 10, (64,))
logits = model(x) # forward builds the graph
loss = F.cross_entropy(logits, y)
loss.backward() # reverse-mode AD over tensors
opt.step(); opt.zero_grad() # update, then clear grads

Python — the same idea in PyTorch: a module, a loss, gradients

Every tensor created inside forward carries a grad_fn recording the operation that made it — the tensor analogue of our _backward closure. Calling loss.backward() walks that graph; opt.step() applies AdamW’s update from Table 2.3; opt.zero_grad() resets the accumulators for the next step. The toy engine and the framework differ only in scale and speed.

Almost every model in this book — including the GPT we build in Chapter 10 and the full architecture in Part IV — is trained by the same loop. Learn its shape once and the rest is detail. Table 3.2 names the ingredients; the code shows them assembled.

StepCallWhy
Get a batchx, y = get_batch()data on the right device
Forwardlogits = model(x)builds the autograd graph
Lossloss = F.cross_entropy(…)scalar to differentiate
Zero gradsopt.zero_grad(set_to_none=True)clear last step’s accumulation
Backwardloss.backward()reverse-mode AD
Clipclip_grad_norm_(…, 1.0)survive loss spikes (Ch 21)
Stepopt.step()apply the update

Table 3.2 — Ingredients of a production training step

model.train()
for step in range(max_steps):
x, y = get_batch('train') # (B, T) token ids, already on GPU
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
logits = model(x) # mixed precision: BF16 math
loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
y.view(-1))
loss = loss / grad_accum_steps # average over accumulated micro-batches
loss.backward() # grads accumulate across micro-batches
if (step + 1) % grad_accum_steps == 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
opt.zero_grad(set_to_none=True)
sched.step() # advance the LR schedule (Ch 17)

Python — the canonical loop, with the production niceties

Four production details appear here that the toy loop omits. Mixed precision (autocast with BF16) roughly halves memory and doubles throughput, per Table 2.5. Gradient accumulation simulates a large batch on limited memory by summing gradients over several micro-batches before stepping. Gradient clipping bounds the update so a single bad batch cannot blow up training. And a learning-rate schedule (sched) warms up then decays the step size. Each is examined properly when we train at scale in Part V; seeing them here means the large-scale chapters introduce ideas, not syntax.

Reproducibility Before any run, seed every source of randomness — torch.manual_seed(s), the data sampler, and (for exact reproducibility) torch.use_deterministic_algorithms(True) — and log the seed with the checkpoint. Determinism is the difference between a bug you can fix and a ghost you cannot.

The one piece the skeleton above abbreviates as sched is the learning-rate schedule, and it is worth seeing concretely because it returns, expanded, in Chapter 17. Here, again reproduced from nanoGPT (MIT-licensed) rather than described, is the exact function that produces the warmup-then-cosine-decay curve used to train the original nanoGPT models — a few lines that have trained a great many networks:

import math
def get_lr(it):
# 1) linear warmup for warmup_iters steps
if it < warmup_iters:
return learning_rate * (it + 1) / (warmup_iters + 1)
# 2) past the decay horizon, return the floor
if it > lr_decay_iters:
return min_lr
# 3) in between, cosine-decay from the peak down to min_lr
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # 1 -> 0
return min_lr + coeff * (learning_rate - min_lr)

Python — karpathy/nanoGPT · train.py: get_lr (reproduced, MIT licence)

nanoGPT’s full train.py wraps the loop above with exactly four additions — checkpointing and resumption, gradient accumulation, distributed data parallelism, and this learning-rate decay — and nothing else; it is perhaps the single most valuable file to read after this chapter, because it is a complete, real training script with no wasted motion. We return to each of its four additions, in depth, across Parts III and V. The reason this chapter could reproduce it so casually is the same reason the whole book is possible: the machinery is genuinely small. What is large is everything you build with it.

You now have the three things every later chapter assumes: a feel for tensors, a mechanical understanding of autograd, and the training loop that ties them together. With the machinery in place, Chapter 4 turns to the object we are actually building — the language model itself — and the next-token objective that brings it to life.

Everything PyTorch provides — tensors, autograd, modules, optimizers — comes together in a training loop whose shape never really changes, from this first example to the distributed runs of Part V. It is worth committing to memory, because every training script in this book is an elaboration of these five steps:

for x, y in loader:
logits = model(x) # 1. forward
loss = F.cross_entropy(logits, y) # 2. loss
optimizer.zero_grad() # 3. clear old gradients
loss.backward() # 4. backpropagate
optimizer.step() # 5. update the weights

Python — train/loop.py: the canonical training loop

Each line maps to a concept already introduced. The forward pass runs the model to produce predictions; the loss measures how wrong they are (Section 4.6); zero_grad clears the gradients accumulated from the previous step (PyTorch accumulates by default, which matters for the gradient accumulation of Section 17.8); backward invokes the autograd engine to compute every parameter’s gradient by the chain rule of Section 2.5; and step applies those gradients through the optimizer (AdamW, Section 17.9). That is the whole skeleton of training. Astonishingly, the entire apparatus of Part V — mixed precision, distributed parallelism, gradient checkpointing, fault tolerance — exists to make these exact five steps run correctly and efficiently across thousands of GPUs and trillions of tokens. Master this loop and you have the conceptual core; everything after it is scale.

Five steps, then scale Forward, loss, zero gradients, backward, step — this loop is the skeleton of all training in the book. Part V is the story of running these same five steps across thousands of GPUs; the concept never changes, only its execution.