{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"backpropagation-as-bookkeeping","title":"Backpropagation, and where the memory goes","url":"https://addaly.com/learn/maths-you-need/backpropagation-as-bookkeeping","position":23,"of":76,"minutes":10,"answer":"Backpropagation computes every gradient in one backward sweep by reusing stored forward values, which is why training memory is dominated by activations rather than by weights.","keyIdea":"Backpropagation computes every gradient in one backward sweep by reusing stored forward values, which is why training memory is dominated by activations rather than by weights."},"body":{"format":"markdown","text":"## The problem it solves\n\nYou have a network with 7 billion parameters and you need the derivative of the loss with respect to each one. The naive approach is to nudge each parameter, rerun the network, and see how the loss changed. That is 7 billion forward passes per training step. At a tenth of a second each, one step would take twenty-two years.\n\nBackpropagation gets all 7 billion in roughly the cost of two forward passes. The trick is that most of the arithmetic is shared, and doing it backwards is what lets you share it.\n\n## The idea in one paragraph\n\nGoing forward, you compute and keep the intermediate values. Going backward, you carry a single quantity (the derivative of the loss with respect to the current layer's output) and at each layer you do two things with it: use it to compute this layer's weight gradients, and convert it into the same quantity for the layer below. One sweep, one pass, every gradient.\n\n## Worked, on a two-layer network\n\nSmall enough to check with a pen. One input, two layers, squared loss.\n\n```\nForward:\n  z1 = w1 * x           (cache x)\n  a1 = relu(z1)         (cache z1)\n  z2 = w2 * a1          (cache a1)\n  L  = (z2 - y)^2\n```\n\nNumbers: `x = 2`, `w1 = 0.5`, `w2 = 3`, `y = 1`.\n\n```\nz1 = 1.0\na1 = relu(1.0) = 1.0\nz2 = 3.0\nL  = (3 - 1)^2 = 4\n```\n\nNow backwards. Start with the derivative of the loss with respect to its own input.\n\n```\ndL/dz2 = 2(z2 - y) = 2(3 - 1) = 4\n\nlayer 2: dL/dw2 = dL/dz2 * a1 = 4 * 1.0 = 4\n         dL/da1 = dL/dz2 * w2 = 4 * 3   = 12       <- pass this down\n\n> Figure: One backward sweep over a two-layer network. Steps: 1. Forward, and cache (z1 = 0.5 times 2 = 1.0, a1 = relu(1.0) = 1.0, z2 = 3 times 1.0 = 3.0. Keep x, the sign of z1, and a1.); 2. Start at the loss (L = (3 minus 1) squared = 4, and the derivative with respect to z2 is 2 times (3 minus 1) = 4.); 3. Layer 2 (Weight gradient 4 times a1 = 4, which needed the cached a1. Pass down 4 times w2 = 12.); 4. Layer 1 (Through the relu: 12 times 1 = 12. Weight gradient 12 times x = 24, which needed the cached x.). Two weight gradients, 4 and 24, from one sweep. Notice which forward values had to survive to make it possible: a1 for the second layer and x for the first. That cache, held from the forward pass until the backward pass reaches it, is where training memory goes.\n\nlayer 1: dL/dz1 = dL/da1 * relu'(z1) = 12 * 1 = 12   (relu' is 1 since z1 > 0)\n         dL/dw1 = dL/dz1 * x = 12 * 2 = 24\n```\n\nTwo weight gradients, 4 and 24, obtained in one backward sweep. Notice that computing `dL/dw2` needed `a1`, and computing `dL/dw1` needed `x` and the sign of `z1`. **Every one of those is a forward value that had to be kept.** That is where the memory goes.\n\n## The memory arithmetic\n\nHere is the practical consequence, and it is the reason training a model needs so much more memory than running it.\n\nFor inference, you need the weights and one layer's activations at a time; earlier activations can be discarded as soon as they have been used. For training, every activation needed by the backward pass must survive from the forward pass until the backward pass reaches it. So peak memory scales with **depth × batch size × activation size**, on top of the weights.\n\nWork a rough example. A 7-billion-parameter model, 32 layers, batch of 8 sequences of 2,048 tokens, hidden width 4,096, activations in 16-bit:\n\n```\none layer's activations = 8 * 2048 * 4096 * 2 bytes = 134 MB\n32 layers, several tensors kept per layer, say 4:\n   32 * 4 * 134 MB = 17 GB of activations\n```\n\nagainst 14 GB for the weights themselves in 16-bit. Activations are the larger half, and they scale with batch size while the weights do not. That is why \"reduce the batch size\" is the first answer to an out-of-memory error, and why it works when nothing about the model has changed.\n\n## Gradient checkpointing, and the trade you are making\n\nThe standard remedy is gradient checkpointing: keep only a few activations (say every fourth layer) and recompute the rest during the backward pass. Memory falls by roughly the square root of the depth; compute rises by about 30 per cent, since you do part of the forward pass twice.\n\nIt is worth understanding as a pure trade. You are choosing to spend time to save memory, and it is the right trade whenever the alternative is not being able to run at all. One flag in most frameworks.\n\n## Two things worth knowing about the real implementation\n\n**The graph is built as you go.** In PyTorch, every operation on a tensor with `requires_grad=True` records itself. Calling `.backward()` walks that record in reverse. This is why a Python `if` inside a model is fine: the graph records whichever branch actually ran.\n\n**Gradients accumulate rather than replace.** Calling `.backward()` twice adds the second set to the first, which is a feature (it is how gradient accumulation lets you simulate a large batch on a small card) and a trap, because forgetting `optimizer.zero_grad()` silently sums every batch you have ever seen and your model diverges for no visible reason.\n\n## The asymmetry worth knowing\n\nBackpropagation is *reverse-mode* automatic differentiation, and it is cheap when there are many inputs and one output. That is exactly the shape of a loss function: billions of parameters in, one scalar out.\n\nForward-mode differentiation is the reverse trade and is cheap when there is one input and many outputs. If you ever need the derivative of many outputs with respect to a single parameter, forward mode is the efficient choice, and every serious framework provides it. The reason you rarely hear about it is that loss functions return one number.\n\n## The rule to keep\n\nBackpropagation is bookkeeping: cache on the way forward, reuse on the way back. The cache is why training memory is dominated by activations, and knowing that turns most out-of-memory errors into a choice between batch size and checkpointing rather than a mystery."},"check":{"question":"A model trains at batch size 8 but hits out-of-memory at batch size 16, even though the weights occupy well under half the card. What does this tell you about where the memory is going, and why does the model's size stay constant?","options":[{"text":"The optimiser states grow with batch size, since Adam keeps two moments per example.","correct":false,"tempting":"Adam's moments are per parameter, not per example, so they do not change with batch size at all."},{"text":"The gradients grow with batch size, since one gradient is computed per example.","correct":false,"tempting":"Per-example gradients are averaged into a single gradient of the same size as the weights; the gradient buffer does not scale with the batch."},{"text":"Cached forward activations dominate and scale linearly with batch size, while weights, gradients and optimiser states do not.","correct":true},{"text":"The weights are duplicated per batch element so that each example can be processed independently.","correct":false,"tempting":"Weights are shared across the batch and stored once; nothing duplicates them."}]},"prev":{"slug":"the-chain-rule","title":"The chain rule, which is the whole trick","url":"https://addaly.com/learn/maths-you-need/the-chain-rule"},"next":{"slug":"convexity-and-local-minima","title":"Convexity, and why nobody promises anything about deep networks","url":"https://addaly.com/learn/maths-you-need/convexity-and-local-minima"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Backpropagation, and where the memory goes', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/backpropagation-as-bookkeeping (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Backpropagation, and where the memory goes","courseTitle":"The Maths You Actually Need","module":{"index":3,"slug":"change-and-descent","title":"Change, slopes and the walk downhill"},"answer":null,"keyIdea":"Backpropagation computes every gradient in one backward sweep by reusing stored forward values, which is why training memory is dominated by activations rather than by weights.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"caption":"Two weight gradients, 4 and 24, from one sweep. Notice which forward values had to survive to make it possible: a1 for the second layer and x for the first. That cache, held from the forward pass until the backward pass reaches it, is where training memory goes.","steps":[{"label":"Forward, and cache","detail":"z1 = 0.5 times 2 = 1.0, a1 = relu(1.0) = 1.0, z2 = 3 times 1.0 = 3.0. Keep x, the sign of z1, and a1."},{"label":"Start at the loss","detail":"L = (3 minus 1) squared = 4, and the derivative with respect to z2 is 2 times (3 minus 1) = 4."},{"label":"Layer 2","detail":"Weight gradient 4 times a1 = 4, which needed the cached a1. Pass down 4 times w2 = 12."},{"label":"Layer 1","detail":"Through the relu: 12 times 1 = 12. Weight gradient 12 times x = 24, which needed the cached x."}],"title":"One backward sweep over a two-layer network","type":"flow"},"alt":"Figure: One backward sweep over a two-layer network. Steps: 1. Forward, and cache (z1 = 0.5 times 2 = 1.0, a1 = relu(1.0) = 1.0, z2 = 3 times 1.0 = 3.0. Keep x, the sign of z1, and a1.); 2. Start at the loss (L = (3 minus 1) squared = 4, and the derivative with respect to z2 is 2 times (3 minus 1) = 4.); 3. Layer 2 (Weight gradient 4 times a1 = 4, which needed the cached a1. Pass down 4 times w2 = 12.); 4. Layer 1 (Through the relu: 12 times 1 = 12. Weight gradient 12 times x = 24, which needed the cached x.). Two weight gradients, 4 and 24, from one sweep. Notice which forward values had to survive to make it possible: a1 for the second layer and x for the first. That cache, held from the forward pass until the backward pass reaches it, is where training memory goes."}},"blocks":[{"t":"h2","id":"the-problem-it-solves","runs":[{"text":"The problem it solves"}]},{"t":"p","runs":[{"text":"You have a network with 7 billion parameters and you need the derivative of the loss with respect to each one. The naive approach is to nudge each parameter, rerun the network, and see how the loss changed. That is 7 billion forward passes per training step. At a tenth of a second each, one step would take twenty-two years."}]},{"t":"p","runs":[{"text":"Backpropagation gets all 7 billion in roughly the cost of two forward passes. The trick is that most of the arithmetic is shared, and doing it backwards is what lets you share it."}]},{"t":"h2","id":"the-idea-in-one-paragraph","runs":[{"text":"The idea in one paragraph"}]},{"t":"p","runs":[{"text":"Going forward, you compute and keep the intermediate values. Going backward, you carry a single quantity (the derivative of the loss with respect to the current layer’s output) and at each layer you do two things with it: use it to compute this layer’s weight gradients, and convert it into the same quantity for the layer below. One sweep, one pass, every gradient."}]},{"t":"h2","id":"worked-on-a-two-layer-network","runs":[{"text":"Worked, on a two-layer network"}]},{"t":"p","runs":[{"text":"Small enough to check with a pen. One input, two layers, squared loss."}]},{"t":"code","lang":"","label":"Text","text":"Forward:\n  z1 = w1 * x           (cache x)\n  a1 = relu(z1)         (cache z1)\n  z2 = w2 * a1          (cache a1)\n  L  = (z2 - y)^2"},{"t":"p","runs":[{"text":"Numbers: "},{"text":"x = 2","code":true},{"text":", "},{"text":"w1 = 0.5","code":true},{"text":", "},{"text":"w2 = 3","code":true},{"text":", "},{"text":"y = 1","code":true},{"text":"."}]},{"t":"code","lang":"","label":"Text","text":"z1 = 1.0\na1 = relu(1.0) = 1.0\nz2 = 3.0\nL  = (3 - 1)^2 = 4"},{"t":"p","runs":[{"text":"Now backwards. Start with the derivative of the loss with respect to its own input."}]},{"t":"code","lang":"","label":"Text","text":"dL/dz2 = 2(z2 - y) = 2(3 - 1) = 4\n\nlayer 2: dL/dw2 = dL/dz2 * a1 = 4 * 1.0 = 4\n         dL/da1 = dL/dz2 * w2 = 4 * 3   = 12       <- pass this down\n\nlayer 1: dL/dz1 = dL/da1 * relu'(z1) = 12 * 1 = 12   (relu' is 1 since z1 > 0)\n         dL/dw1 = dL/dz1 * x = 12 * 2 = 24"},{"t":"p","runs":[{"text":"Two weight gradients, 4 and 24, obtained in one backward sweep. Notice that computing "},{"text":"dL/dw2","code":true},{"text":" needed "},{"text":"a1","code":true},{"text":", and computing "},{"text":"dL/dw1","code":true},{"text":" needed "},{"text":"x","code":true},{"text":" and the sign of "},{"text":"z1","code":true},{"text":". "},{"text":"Every one of those is a forward value that had to be kept.","b":true},{"text":" That is where the memory goes."}]},{"t":"h2","id":"the-memory-arithmetic","runs":[{"text":"The memory arithmetic"}]},{"t":"p","runs":[{"text":"Here is the practical consequence, and it is the reason training a model needs so much more memory than running it."}]},{"t":"p","runs":[{"text":"For inference, you need the weights and one layer’s activations at a time; earlier activations can be discarded as soon as they have been used. For training, every activation needed by the backward pass must survive from the forward pass until the backward pass reaches it. So peak memory scales with "},{"text":"depth × batch size × activation size","b":true},{"text":", on top of the weights."}]},{"t":"p","runs":[{"text":"Work a rough example. A 7-billion-parameter model, 32 layers, batch of 8 sequences of 2,048 tokens, hidden width 4,096, activations in 16-bit:"}]},{"t":"code","lang":"","label":"Text","text":"one layer's activations = 8 * 2048 * 4096 * 2 bytes = 134 MB\n32 layers, several tensors kept per layer, say 4:\n   32 * 4 * 134 MB = 17 GB of activations"},{"t":"p","runs":[{"text":"against 14 GB for the weights themselves in 16-bit. Activations are the larger half, and they scale with batch size while the weights do not. That is why “reduce the batch size” is the first answer to an out-of-memory error, and why it works when nothing about the model has changed."}]},{"t":"h2","id":"gradient-checkpointing-and-the-trade-you-are-making","runs":[{"text":"Gradient checkpointing, and the trade you are making"}]},{"t":"p","runs":[{"text":"The standard remedy is gradient checkpointing: keep only a few activations (say every fourth layer) and recompute the rest during the backward pass. Memory falls by roughly the square root of the depth; compute rises by about 30 per cent, since you do part of the forward pass twice."}]},{"t":"p","runs":[{"text":"It is worth understanding as a pure trade. You are choosing to spend time to save memory, and it is the right trade whenever the alternative is not being able to run at all. One flag in most frameworks."}]},{"t":"h2","id":"two-things-worth-knowing-about-the-real-implementation","runs":[{"text":"Two things worth knowing about the real implementation"}]},{"t":"p","runs":[{"text":"The graph is built as you go.","b":true},{"text":" In PyTorch, every operation on a tensor with "},{"text":"requires_grad=True","code":true},{"text":" records itself. Calling "},{"text":".backward()","code":true},{"text":" walks that record in reverse. This is why a Python "},{"text":"if","code":true},{"text":" inside a model is fine: the graph records whichever branch actually ran."}]},{"t":"p","runs":[{"text":"Gradients accumulate rather than replace.","b":true},{"text":" Calling "},{"text":".backward()","code":true},{"text":" twice adds the second set to the first, which is a feature (it is how gradient accumulation lets you simulate a large batch on a small card) and a trap, because forgetting "},{"text":"optimizer.zero_grad()","code":true},{"text":" silently sums every batch you have ever seen and your model diverges for no visible reason."}]},{"t":"h2","id":"the-asymmetry-worth-knowing","runs":[{"text":"The asymmetry worth knowing"}]},{"t":"p","runs":[{"text":"Backpropagation is "},{"text":"reverse-mode","i":true},{"text":" automatic differentiation, and it is cheap when there are many inputs and one output. That is exactly the shape of a loss function: billions of parameters in, one scalar out."}]},{"t":"p","runs":[{"text":"Forward-mode differentiation is the reverse trade and is cheap when there is one input and many outputs. If you ever need the derivative of many outputs with respect to a single parameter, forward mode is the efficient choice, and every serious framework provides it. The reason you rarely hear about it is that loss functions return one number."}]},{"t":"h2","id":"the-rule-to-keep","runs":[{"text":"The rule to keep"}]},{"t":"p","runs":[{"text":"Backpropagation is bookkeeping: cache on the way forward, reuse on the way back. The cache is why training memory is dominated by activations, and knowing that turns most out-of-memory errors into a choice between batch size and checkpointing rather than a mystery."}]}],"check":{"question":[{"text":"A model trains at batch size 8 but hits out-of-memory at batch size 16, even though the weights occupy well under half the card. What does this tell you about where the memory is going, and why does the model’s size stay constant?"}],"options":[{"text":[{"text":"The optimiser states grow with batch size, since Adam keeps two moments per example."}],"correct":false,"tempting":[{"text":"Adam’s moments are per parameter, not per example, so they do not change with batch size at all."}]},{"text":[{"text":"The gradients grow with batch size, since one gradient is computed per example."}],"correct":false,"tempting":[{"text":"Per-example gradients are averaged into a single gradient of the same size as the weights; the gradient buffer does not scale with the batch."}]},{"text":[{"text":"Cached forward activations dominate and scale linearly with batch size, while weights, gradients and optimiser states do not."}],"correct":true,"tempting":null},{"text":[{"text":"The weights are duplicated per batch element so that each example can be processed independently."}],"correct":false,"tempting":[{"text":"Weights are shared across the batch and stored once; nothing duplicates them."}]}],"order":[1,3,0,2],"why":null},"prev":{"slug":"the-chain-rule","title":"The chain rule, which is the whole trick","minutes":8},"next":{"slug":"convexity-and-local-minima","title":"Convexity, and why nobody promises anything about deep networks","minutes":9}}}