Library/Transformers from scratch/Gradients and fine-tuning

Matmul forward and backward

110 min6 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Derive dA = dY Bᵀ and dB = Aᵀ dY from one entry of Y = AB, and check them with the shapes
  • Why a weight shared by a whole batch gets the sum of the batch's gradients, and why PyTorch hides a missing sum
  • Write a torch.autograd.Function that saves its inputs in forward and returns one gradient per input from backward
  • Why backward uses the formula instead of calling autograd, and a Linear layer with a bias on top
  • Prove it with gradcheck in float64, and know what each common bug looks like when it fails
  • Answer the follow-ups on FLOPs, saved inputs, checkpointing and mixed precision
Part 1 of 6about 20 min
Derive the two gradients

Matrix multiplication's backward, from a skeleton

One OpenAI ML engineer candidate reports an ML coding round that asked for a matrix multiplication's forward pass and backprop in PyTorch, starting from a code skeleton (1 report). Matmuls do most of a transformer's arithmetic, so the question tests whether you can write a backward pass that autograd usually writes for you. Our version hands you this skeleton:

class MatMul(torch.autograd.Function):
    @staticmethod
    def forward(
        ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
    ) -> torch.Tensor:
        ...

    @staticmethod
    def backward(
        ctx: FunctionCtx, grad_out: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        ...

forward returns a @ b. That's one line. backward is the whole job: it gets the gradient of the loss with respect to the output, and it returns one gradient for a and one for b. ctx is the object that carries tensors from one to the other. Its type, FunctionCtx, comes from torch.autograd.function.

The practice comes in four levels. Level 1 is a 2-D a and b, checked by gradcheck. Level 2 gives a a batch axis, with one weight b shared by the whole batch. Level 3 allows any number of leading axes, and a b with a batch of its own. Level 4 puts a Linear layer on top and trains it.

You don't write it yet. The lesson derives the two gradients from one entry, handles a batch that shares the weight, plugs both into autograd, puts a Linear layer on top, and proves it all with gradcheck. At the end you solve the whole problem, level by level, in an interview simulation with a 40-minute timer.

This lesson builds on the backprop lesson, where the same two gradients came out of the shape rule in NumPy. Here you derive them from one entry, and hand them to PyTorch's autograd as a node of your own.

How autograd runs your Function

The skeleton is a node in autograd's graph, and it helps to see where it sits before you fill it in.

Your Function in the graphInteractive
a (2, 3)b (3, 2)@y (2, 2)opsloss
forward, values backward, gradients
MatMul.apply(a, b) runs your forward, y = a @ b, and records a MatMulBackward node in the graph.

This is how PyTorch runs that picture:

  • Autograd, PyTorch's gradient machinery, records each op whose inputs require grad as a node in a graph.
  • loss.backward() walks that graph in reverse and calls each node's backward with the gradient flowing in.
  • The results are added into the .grad of the tensors you made with requires_grad=True, such as the weights.

A torch.autograd.Function is a node of your own. You write its forward and its backward, and the engine calls your backward when its turn comes.

Read the two gradients off one entry of Y

One entry of Y is a row of A times a column of B

Start from one entry of the product, because both gradients fall out of it.

import torch

A = torch.tensor([[1., 2., 0.],
                  [0., 1., 3.]])
B = torch.tensor([[1., -1.],
                  [2.,  0.],
                  [0.,  1.]])
Y = A @ B
print(Y)
print(A[1] @ B[:, 0])
Predict

A is [[1, 2, 0], [0, 1, 3]], and B's first column is [1, 2, 0]. What is Y[1, 0], row 1 of A times column 0 of B?

Pick one to see what it prints.
Pick an answer above to see the rest

dY is how the loss moves with each entry of Y

Some loss LL sits after YY. Write dYdY for ∂L/∂Y\partial L / \partial Y: for each entry of YY, how fast the loss moves when that entry moves. It's one number per entry, so it has YY's shape.

Backward is handed dYdY, as grad_out, and has to produce dAdA and dBdB: one number per entry of AA and of BB.

One entry of A reaches one row of Y

Nudge one entry of A and watch what moves:

A2 = A.clone()
A2[1, 0] += 0.001
print(A2 @ B - Y)
Predict

Nudge A[1, 0] up by 0.001. Which entries of Y move?

Pick one to see what it prints.
Pick an answer above to see the rest

One entry of B reaches one column of Y

BpjB_{pj} feeds column jj of YY, and in each YijY_{ij} it's multiplied by AipA_{ip}:

An entry of B reaches one column of YInteractive
A (2, 3)
120013
B (3, 2)
Y = A @ B
5-123
dY
10-12
Tap an entry of B to nudge it.
B[0, 1] feeds column 1 of Y and nothing else, each entry times column 0 of A, [1, 0]. So dB[0, 1] = column 0 of A · column 1 of dY = (1)(0) + (0)(2) = 0.

Add up its effect down the column:

∂L∂Bpj=∑i=1nAip dYij\frac{\partial L}{\partial B_{pj}} = \sum_{i=1}^{n} A_{ip}\, dY_{ij}

That's column pp of AA times column jj of dYdY. Column pp of AA is row pp of A⊤A^\top, so it's entry (p,j)(p, j) of A⊤dYA^\top dY.

In the editor, write dB_entry(A, dY, p, j): that sum down column j, as a loop.

Every entry follows the same rule, so each gradient is one matmul

The two loops are the same rule written once for every entry.

dA=dY B⊤,dB=A⊤dYdA = dY\, B^\top, \qquad dB = A^\top dY

In code, next to the forward:

Code
forwardy = a @ b
backwardgrad_a = grad_out @ bᵀ
backwardgrad_b = aᵀ @ grad_out

Each gradient uses the other input, turned over, on the side where that input sat in the forward. In PyTorch, bᵀ is b.transpose(-1, -2).

In the editor, write grads(A, B, dY): both gradients, one matmul each.

The video builds the Jacobian, the grid of slopes of every output entry with respect to every input entry, one entry at a time.

Watch · 16 min

Why a custom op has to supply its own backward, then this lesson's derivation on a 1 by 3 input and a 3 by 4 weight, where the Jacobian built entry by entry turns out to be W transposed. His X and W are this lesson's A and B.

Flash Attention derived and coded from first principles with Triton (Python) · Umar Jamil · Nov 2024YouTube
Part 1 done
Part 2 of 6about 12 min
Shapes place each factor

The shapes leave one way to write each product

A gradient has the shape of its input

The derivation is the proof, but the shapes are the fastest check.

dAdA must be n×kn \times k like AA, and dBdB must be k×mk \times m like BB. With the practice tests' sizes, a is (3, 4), b is (4, 5) and grad_out is (3, 5). Try each product:

Only one product fits each gradientInteractive
grad_out(3n,5m)@b.T(5m,4k)=result(3n,4k)matches a (3, 4)
The inner m's meet and are summed away, which leaves (3, 4): the shape of a. This is the gradient.

grad_a has n rows and so does grad_out, so grad_out goes on the left. The other factor must be (m, k), and the only one is b transposed.

grad_b has m columns and so does grad_out, so grad_out goes on the right. The other factor must be (k, n), which is a transposed.

Forget the formulas under pressure and you can rebuild them this way in a few seconds. With the practice's names:

TensorShapeWhat it is
a(n, k)the first input
b(k, m)the second input, a weight
y(n, m)the output, a @ b
grad_outlike yhanded to backward
grad_alike agrad_out @ b.transpose(-1, -2)
grad_blike ba.transpose(-1, -2) @ grad_out

In the editor, write shapes(n, k, m): the shapes of grad_out, grad_a and grad_b as tuples, for any sizes.

Square shapes can't tell right from wrong

Make every size 4, and both products fit:

With n = k = m = 4, both fitInteractive
grad_out(4n,4m)@b(4k,4m)=result(4n,4m)matches a (4, 4)
Every size is 4, so this fits and even matches a's shape. It's still the wrong product, and every number it gives is wrong.

Make every size the same and every arrangement fits. Shapes are a check, not a proof. The derivation is the proof, and gradcheck, near the end, is the test.

In the editor, write errors(n, k, m): whether the wrong product, grad_out @ b, fails loudly at those sizes.

Swap the last two axes, never use .T

Once a has a batch axis, how you transpose matters.

x = torch.randn(2, 3, 4)
print(x.mT.shape)
print(x.T.shape)
Predict

x is (2, 3, 4), a batch of two matrices. What are x.mT.shape and x.T.shape?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 18 min
One weight, a whole batch

A weight shared by a batch gets the sum of the batch's gradients

Each batch element is its own matmul

A real layer sees a whole batch at once.

In a real layer, a carries a batch: (S, n, k), SS sequences of nn tokens each. The practice calls the batch size B, but here BB is the matrix, so the batch size is SS. The weight b stays (k, m), one matrix for the whole batch. Step through a batch of two:

One weight, two batch elementsInteractive
a[0] (2, 3)b (3, 2)a[1] (2, 3)@@y[0] (2, 2)y[1] (2, 2)
forward, values backward, gradients
Both batch elements use the one weight b: y[0] = a[0] @ b and y[1] = a[1] @ b.

a @ b broadcasts b across the batch. In symbols, Ys=AsBY_s = A_s B for each element ss from 1 to SS.

grad_a needs nothing new. grad_out @ b.transpose(-1, -2) broadcasts the same way and gives each element its own dYsB⊤dY_s B^\top.

b is used S times, so it collects S gradients, added up

A variable used in several places collects a gradient from each use, added up. b is used once per batch element:

dB=∑s=1SAs⊤ dYsdB = \sum_{s=1}^{S} A_s^\top\, dY_s

AsA_s is element ss's input and dYsdY_s is its output's gradient.

When the batch is folded into the rows, as (S·n, k), the product aᵀ @ grad_out does this adding for you, because the sum over rows happens inside the matmul. Here the batch is an axis of its own, outside the matmul, so the sum is yours to write.

TensorShapeWhat it is
a(S, n, k)a batch of inputs
b(k, m)one weight for the whole batch
y, grad_out(S, n, m)outputs and their gradient
grad_a(S, n, k)grad_out @ b.transpose(-1, -2)
per-element grad_b(S, k, m)a.transpose(-1, -2) @ grad_out
grad_b(k, m)that, summed over dim=0

In the editor, write grad_b_loop(a, grad_out): the sum, one batch element at a time.

Three ways to write the sum, all equal

A loop is clear, but not how you'd write it in practice. Here are two more ways, by_einsum and by_fold, which you write in this step's task, against the sum of the batched products:

torch.manual_seed(0)
a = torch.randn(2, 3, 4, dtype=torch.float64)
grad_out = torch.randn(2, 3, 5, dtype=torch.float64)

s1 = (a.transpose(-1, -2) @ grad_out).sum(dim=0)
s2 = by_einsum(a, grad_out)
s3 = by_fold(a, grad_out)
print(tuple(s1.shape), torch.allclose(s1, s2), torch.allclose(s1, s3))
Predict

Three ways to get b's gradient over a batch: sum the batched products, an einsum, or fold the batch into the rows first. Do they agree?

Pick one to see what it prints.
Pick an answer above to see the rest

Sum over every leading axis, behind an if

A batch can have more than one leading axis.

aPer-element grad_bSum over
(n, k)(k, m)nothing
(S, n, k)(S, k, m)axis 0
(P, S, n, k)(P, S, k, m)axes 0 and 1

For code that takes a 2-D or a 3-D a, or more, sum every axis in front of the last two:

if grad_b.dim() > b.dim():
    grad_b = grad_b.sum(dim=tuple(range(grad_b.dim() - b.dim())))

Read the second line from the inside out:

  • grad_b.dim() - b.dim() counts the leading axes that b doesn't have.
  • range numbers them from 0.
  • tuple hands them to sum as the axes to remove: (0,) for a 3-D a and (0, 1) for a 4-D one.

What's left has b's shape.

The if matters. With a 2-D a, the tuple is empty.

Predict

Without the if, a 2-D a gives grad_b.sum(dim=()). What happens?

Pick an answer above to see the rest

PyTorch hides a missing sum, and NumPy doesn't

Here is a backward that forgets the sum:

from torch.autograd.function import FunctionCtx

class NoSum(torch.autograd.Function):
    @staticmethod
    def forward(
        ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
    ) -> torch.Tensor:
        ctx.save_for_backward(a, b)
        return a @ b

    @staticmethod
    def backward(
        ctx: FunctionCtx, grad_out: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        a, b = ctx.saved_tensors
        # (2, 4, 5), never summed
        grad_b = a.transpose(-1, -2) @ grad_out
        print("returned", tuple(grad_b.shape))
        return grad_out @ b.transpose(-1, -2), grad_b

a = torch.randn(2, 3, 4, requires_grad=True)
b = torch.randn(4, 5, requires_grad=True)
NoSum.apply(a, b).sum().backward()
print("b.grad  ", tuple(b.grad.shape))
Predict

NoSum's backward returns a.transpose(-1, -2) @ grad_out for b, with no sum. What shape is that, before PyTorch sees it?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

In NumPy, W is (4, 5) and an unsummed dW is (2, 4, 5). What shape is W - 0.1 * dW?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 18 min
A Function of your own

torch.autograd.Function: save in forward, return gradients in backward

With both gradients derived and the batch handled, the formulas go into a Function.

Here's the whole Function, with the sum, and one call to it:

class MatMul(torch.autograd.Function):
    @staticmethod
    def forward(
        ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
    ) -> torch.Tensor:
        """a: (..., n, k), b: (k, m). Returns a @ b, (..., n, m)."""
        ctx.save_for_backward(a, b)
        return a @ b

    @staticmethod
    def backward(
        ctx: FunctionCtx, grad_out: torch.Tensor
    ) -> tuple[torch.Tensor | None, torch.Tensor | None]:
        """Returns (grad_a, grad_b), shaped like a and b."""
        a, b = ctx.saved_tensors
        grad_a = grad_b = None
        if ctx.needs_input_grad[0]:
            grad_a = grad_out @ b.transpose(-1, -2)
        if ctx.needs_input_grad[1]:
            grad_b = a.transpose(-1, -2) @ grad_out
            # sum the batch axes
            if grad_b.dim() > b.dim():
                grad_b = grad_b.sum(dim=tuple(range(grad_b.dim() - b.dim())))
        return grad_a, grad_b

a = torch.randn(2, 3, 4, requires_grad=True)
b = torch.randn(4, 5, requires_grad=True)
y = MatMul.apply(a, b)
print(tuple(y.shape), type(y.grad_fn).__name__)
y.sum().backward()
print(tuple(a.grad.shape), tuple(b.grad.shape))
Predict

a is (2, 3, 4) and b is (4, 5). After y.sum().backward(), what shapes are a.grad and b.grad?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

You call an instance, MatMul()(a, b), instead of MatMul.apply(a, b). What happens?

Pick an answer above to see the rest

ctx carries tensors from forward to backward

Tensors go in through ctx.save_for_backward(...) and come back out of ctx.saved_tensors. The PyTorch docs ask for this route for every tensor that backward uses: it prevents wrong gradients and memory leaks.

Saving copies nothing. It keeps the tensor alive until backward has run.

Non-tensors, like an int or a float, go straight onto ctx as attributes: ctx.scale = scale.

The stub puts ctx in forward, the older of two styles. Since PyTorch 2.0 you can also write a forward without ctx, plus a separate setup_context(ctx, inputs, output) that does the saving. The docs recommend that style. The math is the same in both styles.

needs_input_grad skips a gradient nobody wants

In a first layer, a is raw data and b is the weight.

Predict

ctx.needs_input_grad holds one True or False per input, in order. What is it in a first layer?

Pick an answer above to see the rest

Return one gradient per input, in forward's order

The engine has one more rule for what backward returns.

Position012
forward(ctx, ...) takesabscale
backward returnsgrad_agrad_bNone

The engine matches gradients to inputs by position, not by name. Use None for an input that needs no gradient or isn't a tensor, like the float scale in this step's task.

The wrong count fails with function MatMulBackward returned an incorrect number of gradients (expected 2, got 1).

Backward gets one gradient per output of forward. Here that's only grad_out, shaped like y. Treat it as read-only: the docs say never to change it in place.

In the editor, write ScaledMatMul, a Function with three inputs: two tensors and a plain float that gets None.

CheckpointA Function with a constant

Write ScaledMatMul, a torch.autograd.Function whose forward(ctx, a, b, scale) returns scale * (a @ b) for 2-D a and b. scale is a plain float, so it gets no gradient. Build the gradients from tensor ops, without calling autograd.

Autograd is off inside backward, so write the formula

Why write the formula at all, when autograd could work it out?

class Peek(torch.autograd.Function):
    @staticmethod
    def forward(ctx: FunctionCtx, a: torch.Tensor) -> torch.Tensor:
        print("forward, grad mode on:", torch.is_grad_enabled())
        return a * 2

    @staticmethod
    def backward(ctx: FunctionCtx, grad_out: torch.Tensor) -> torch.Tensor:
        print("backward, grad mode on:", torch.is_grad_enabled())
        return grad_out * 2

Peek.apply(torch.ones(3, requires_grad=True)).sum().backward()
Predict

Is grad mode, autograd's recording switch, on inside a custom forward, and inside its backward?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

gradgradcheck checks the gradient of your backward itself. Does MatMul pass?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 26 min
A Linear layer, proved by gradcheck

A Linear layer is MatMul plus a bias

The practice's last level puts a layer on top of your Function.

from torch import nn

class Linear(nn.Module):
    def __init__(self, in_features: int, out_features: int) -> None:
        super().__init__()
        self.weight = nn.Parameter(torch.randn(in_features, out_features) / in_features ** 0.5)
        self.bias = nn.Parameter(torch.zeros(out_features))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """x: (..., in). Returns (..., out)."""
        return MatMul.apply(x, self.weight) + self.bias

layer = Linear(3, 1)
print([(name, tuple(p.shape)) for name, p in layer.named_parameters()])
Predict

Linear(3, 1) stores a weight and a bias as nn.Parameter. What does named_parameters() list?

Pick one to see what it prints.
Pick an answer above to see the rest

Divide by the square root of in to keep the outputs' scale

A layer also has to start with weights of the right size.

torch.manual_seed(0)
x = torch.randn(1000, 400)
w = torch.randn(400, 300)
print(f"{(x @ w).std():.2f}", f"{(x @ (w / 400 ** 0.5)).std():.2f}")
Predict

x is (1000, 400) and w is (400, 300), both with spread 1. What is the spread of x @ w, and of x @ (w / √400)?

Pick one to see what it prints.
Pick an answer above to see the rest

The practice trains it to the exact answer

The practice trains Linear(3, 1) on 64 random points of y=x⋅[1,−2,0.5]+0.3y = x \cdot [1, -2, 0.5] + 0.3 with plain SGD:

torch.manual_seed(0)
layer = Linear(3, 1)
x = torch.randn(64, 3)
y = x @ torch.tensor([[1.0], [-2.0], [0.5]]) + 0.3
opt = torch.optim.SGD(layer.parameters(), lr=0.1)
for step in range(1, 101):
    loss = ((layer(x) - y) ** 2).mean()
    if step in (1, 100):
        print(step, f"{loss.item():.3g}")
    opt.zero_grad()
    loss.backward()
    opt.step()
print(layer.weight.detach().flatten(), layer.bias.detach())
Predict

Train Linear(3, 1) with SGD for 100 steps on data made from weights [1, -2, 0.5] and bias 0.3, with no noise. Where do the weights end?

Pick one to see what it prints.
Pick an answer above to see the rest

gradcheck proves the backward

One call checks every entry of every gradient.

torch.manual_seed(0)
a = torch.randn(2, 3, 4, dtype=torch.float64, requires_grad=True)
b = torch.randn(4, 5, dtype=torch.float64, requires_grad=True)
print(torch.autograd.gradcheck(MatMul.apply, (a, b)))
True

True means your backward agrees with a numerical estimate at every entry. A wrong one raises a GradcheckError that says where.

In the editor, write check(fn, *shapes): gradcheck on random float64 inputs of the shapes you name.

gradcheck builds the Jacobian two ways

gradcheck builds the Jacobian, the grid of every output's slope against every input, twice. Then it compares the two with allclose:

SideHow it builds the Jacobian
Numericalnudge one input entry by ±1e-6 and see how every output moves: one column per input entry
Analyticalrun your backward with grad_out = 1 at one output entry and 0 elsewhere: one row per output entry
Thencompare the two grids with allclose

The numerical side takes the central difference: the change in the outputs between the two nudges, divided by 2×10−62 \times 10^{-6}.

Predict

y is (2, 3, 5), a is (2, 3, 4) and b is (4, 5). How big is the Jacobian gradcheck builds?

Pick an answer above to see the rest

Run it in float64

The nudge is tiny, so precision decides whether the check works.

a32 = a.detach().float().requires_grad_()
b32 = b.detach().float().requires_grad_()
print(torch.autograd.gradcheck(MatMul.apply, (a32, b32), raise_exception=False))
Predict

Run the same gradcheck on float32 copies of a and b. What does it return?

Pick one to see what it prints.
Pick an answer above to see the rest

A worked example

Use the trick the practice's tests use. Pick a fixed matrix GG and set the loss to L=∑ijYijGijL = \sum_{ij} Y_{ij} G_{ij}, which in code is (y * g).sum(). Then dY=GdY = G exactly, so you choose the gradient backward receives.

A=[120013],B=[1−12001],G=[10−12]A = \begin{bmatrix} 1 & 2 & 0 \\ 0 & 1 & 3 \end{bmatrix}, \quad B = \begin{bmatrix} 1 & -1 \\ 2 & 0 \\ 0 & 1 \end{bmatrix}, \quad G = \begin{bmatrix} 1 & 0 \\ -1 & 2 \end{bmatrix}

The code checks autograd against worked(), this step's task, which returns dA and dB from the formulas:

A = torch.tensor([[1., 2., 0.], [0., 1., 3.]])
B = torch.tensor([[1., -1.], [2., 0.], [0., 1.]])
G = torch.tensor([[1., 0.], [-1., 2.]])

a = A.clone().requires_grad_()
b = B.clone().requires_grad_()
loss = (a @ b * G).sum()
loss.backward()
print(loss.item())
dA, dB = worked()
print(torch.equal(a.grad, dA), torch.equal(b.grad, dB))
Predict

With loss = (a @ b * G).sum(), G is the gradient that arrives at Y. Does autograd agree with the formulas' dA and dB, from worked()?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

Two batch elements, A with G and A2 with G2, share one b. What is b.grad?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 5 done
Part 6 of 6about 16 min
What interviewers ask next

What interviewers ask next

FLOPs: the backward costs twice the forward

The first follow-up is usually the cost.

ProductSizesMultiply-adds
Forwardy = a @ b(n×k)(k×m)nkm
Backwardgrad_a = grad_out @ bᵀ(n×m)(m×k)nkm
Backwardgrad_b = aᵀ @ grad_out(k×n)(n×m)nkm

The forward is one matmul: nkmnkm multiply-adds, or 2nkm2nkm FLOPs. The backward is two matmuls with the same three sizes, so it costs 4nkm4nkm, twice the forward. A training step costs about three forwards.

That's the rule of thumb of 6 FLOPs per parameter per token: 2 in the forward and 4 in the backward. Kaplan et al. (2020) count the backward the same way, at about twice the forward.

For a 4,096 by 4,096 weight and a batch of 16,384 tokens, that's 5.5×10115.5 \times 10^{11} FLOPs forward and 1.1×10121.1 \times 10^{12} backward.

Predict

A first layer's input is raw data. What does that layer's backward cost, against its forward?

Pick an answer above to see the rest

Memory: forward keeps its inputs alive

FLOPs are half the cost. Memory is the other half.

GradientNeedsCost
grad_ab, the weight, held anywaynothing extra
grad_ba, an activation that could be freed after this matmul128 MiB for one (8, 2048, 4096) bf16

a is an activation, an intermediate result that could otherwise be freed. Activations are where training memory goes, because every linear layer in every block saves one like it.

Predict

The weight b is frozen. Which input can the forward skip saving for backward?

Pick an answer above to see the rest
Predict

Save each block's input only, and rerun the block during backward. What does a training step cost now?

Pick an answer above to see the rest

Why it's two matmuls and never the full Jacobian

An interviewer may ask why the backward isn't the textbook recipe, the gradient times the Jacobian.

Numbers at n = k = m = 4,096
The full Jacobian ∂Y/∂A, (n·m) × (n·k)2482^{48}, about 2.8×10142.8 \times 10^{14}: 1 PiB in fp32, nearly all of it zero
B itself, k × m16.8 million

YY changes in a straight line with AA, so its backward is one more matmul: multiply by B⊤B^\top where the forward multiplied by BB. The same holds for BB, with A⊤A^\top.

So both gradients are matmuls with the forward's own three sizes: the same cost, the same fast kernels, and transposes that are free views.

The general recipe, the incoming gradient times the Jacobian, would never fit in memory. All but a 1/n1/n share of its numbers are zero, because YijY_{ij} depends only on row ii of AA. dY B⊤dY\,B^\top gets the same answer without building any of it.

In the editor, write jacobian_entries(n, k, m) and nonzero_share(n).

Mixed precision needs two decorators

The last follow-up is precision.

What runsThe result
Forward, under autocasta @ b runs in bf16y is bf16
Backward, no decoratorgrad_out bf16 @ b fp32a dtype error
Backward, with custom_bwdthe same autocast state as forwardruns

Under autocast, PyTorch's switch that runs matmuls in 16-bit floats, your forward's a @ b comes out in 16 bits. Your backward runs outside the autocast region, though. Two decorators fix it:

class MatMul(torch.autograd.Function):
    @staticmethod
    @torch.amp.custom_fwd(device_type="cuda")
    def forward(
        ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
    ) -> torch.Tensor:
        ...

    @staticmethod
    @torch.amp.custom_bwd(device_type="cuda")
    def backward(
        ctx: FunctionCtx, grad_out: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        ...

With them, both gradient matmuls run in half precision. The engine casts each returned gradient to its input's dtype, so fp32 weights still get an fp32 .grad.

Predict

fp16 has one more hazard. What does it store for a gradient of 1e-8?

Pick an answer above to see the rest

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.y = a @ b with a of shape (8, 16) and b of shape (16, 32). Which line computes the gradient for a?

  2. 2.Your backward ends with return grad_b, grad_a. With a of shape (3, 4) and b of shape (4, 5), PyTorch raises an error. What happens when a and b are both (4, 4)?

  3. 3.You average grad_b over the batch instead of summing it. The practice's batched tests use a batch of 2. What do the tests see?

  4. 4.a is (S, n, k) and b is (k, m). Your backward returns a.transpose(-1, -2) @ grad_out for b and never sums it. What happens in PyTorch?

  5. 5.a is (n, k) and b is (k, m), and both need gradients. The forward costs 2nkm FLOPs. What does the backward cost?

Where this shows up

The reports behind this lesson, each with its source.

Same report, ML coding round: matrix multiplication forward pass and backprop in PyTorch, from a given code skeleton.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-24Source

Practice

Sources (7)
  1. Extending PyTorch: Extending torch.autograd · PyTorch 2.15 documentation · Sep 16, 2026
    “It should return as many tensors as there were inputs, with each of them containing the gradient w.r.t. its corresponding input.”
  2. torch.autograd.function.FunctionCtx.save_for_backward · PyTorch 2.15 documentation · Oct 28, 2026
    “All tensors intended to be used in the backward pass should be saved with save_for_backward (as opposed to directly on ctx) to prevent incorrect gradients and memory leaks, and enable the application of saved tensor hooks.”
  3. torch.autograd.gradcheck.gradcheck · PyTorch 2.15 documentation · Oct 28, 2026
    “The default values are designed for input of double precision. This check will likely fail if input is of less precision, e.g., FloatTensor.”
  4. Automatic Mixed Precision examples: Autocast and Custom Autograd Functions · PyTorch 2.15 documentation · May 7, 2026
    “These ensure forward executes with the current autocast state and backward executes with the same autocast state as forward (which can prevent type mismatch errors)”
  5. torch.utils.checkpoint · PyTorch 2.15 documentation · Jul 27, 2026
    “Activation checkpointing is a technique that trades compute for memory.”
  6. Scaling Laws for Neural Language Models · arXiv 2001.08361 · Jan 23, 2020
    “Accounting for the backwards pass (approximately twice the compute as the forwards pass)”
  7. Training Deep Nets with Sublinear Memory Cost · arXiv 1604.06174 · Apr 21, 2016
    “Specifically, we design an algorithm that costs O(sqrt(n)) memory to train a n layer network, with only the computational cost of an extra forward pass per mini-batch.”