Backpropagation › Backpropagation Through Time: Gradient Accumulation

Michael BrenndoerferMay 6, 20252 min read
Language AI HandbookAll chapters
Part 10 of 67Neural Network Foundations
Chapter 65Backpropagation › Backpropagation Through Time: Gradient Accumulation
Reading section 9 of 20 · Backpropagation Through Time: Gradient Accumulation · 2 minSection 9 of 20 · 2 min

Book contents

Section 9 of 20 · 2 min read

Backpropagation › Backpropagation Through Time: Gradient AccumulationOne section · Sections in this chapter9 / 20 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

When a variable participates in multiple computations, its gradient accumulates. This is the gradient accumulation rule: the gradient of the loss with respect to any variable equals the sum of gradients from all downstream uses of that variable.

Consider a weight ww used in two computations: z1=w⋅x1z_1 = w \cdot x_1 and z2=w⋅x2z_2 = w \cdot x_2, with loss L=f(z1,z2)\mathcal{L} = f(z_1, z_2). The total gradient is:

∂L∂w=∂L∂z1⋅x1+∂L∂z2⋅x2\frac{\partial \mathcal{L}}{\partial w} = \frac{\partial \mathcal{L}}{\partial z_1} \cdot x_1 + \frac{\partial \mathcal{L}}{\partial z_2} \cdot x_2

This addition arises directly from the multivariate chain rule: ww has two "paths" to the loss, and the total effect is the sum of both paths' contributions.

This principle applies beyond mini-batch training. It is also the key concept behind backpropagation through time (BPTT) in recurrent neural networks, where the same weight matrix is used at each time step. The gradient of the loss with respect to the shared weight is the sum of gradients from every time step where that weight was used. This is why BPTT in deep recurrent networks also suffers from vanishing gradients: the gradient from a token 50 time steps ago must flow through 50 weight matrices, and the product of their individual contributions tends to vanish. LSTMs and GRUs were specifically designed to mitigate this by adding gating mechanisms that create shorter gradient paths.

In practice, deep learning frameworks handle gradient accumulation automatically. PyTorch's .grad attribute accumulates gradients from all backward passes through a tensor, which is why optimizer.zero_grad() must be called before each training step. Failing to zero gradients leads to gradients from multiple batches summing together, a common source of bugs that produces unexpectedly fast apparent convergence followed by instability.