Unit 4 of 7 · about 5 hours · derive, implement

Branches, broadcasting and saved values in backward

Real graphs reuse nodes and stretch small tensors across batches. Each reuse adds an accumulation obligation and each stretch adds a reduction obligation; missing either gives a silently wrong gradient.

You'll be able to

  • Hand-compute vector-Jacobian products and accumulated gradients for a branched, broadcast graph with a repeated operand.
  • State the broadcast forward rules and implement the backward unbroadcast as a sum over exactly the broadcast axes.
  • Distinguish leaf from intermediate tensors, and name every forward value each backward function saves.

Covers

Repeated use, branches and gradient accumulationBroadcast forward rules and unbroadcast in backwardLeaf and intermediate tensors and saved forward values
1

Read

In this order, only the parts listed

0 of 4 done

  1. Accumulation and non-scalar seedsD2L - tensors, autograd, MLP and backpropagation

    Section 2.5.1: PyTorch does not reset the gradient buffer, so the new gradient is added and x.grad.zero_() resets it, which suits sums of objectives; Section 2.5.2: the gradient argument as the seed vector

  2. Broadcasting and in-place memoryD2L - tensors, autograd, MLP and backpropagation

    Broadcasting: a of shape (3, 1) plus b of shape (1, 2) giving a result by copying along length-1 axes; Saving Memory: Y = Y + X reallocates (id changes) while Z[:] = X + Y and X += Y reuse storage

    The page shows forward broadcasting only. Derive the backward rule in Focus below; the PyTorch note gives the exact forward contract it inverts.

  3. Exact broadcast contractPyTorch Broadcasting semantics

    General semantics: trailing-dimension rules, prepend-1 alignment, result size as the per-dimension max, with (5, 1, 4, 1) plus (3, 1, 1) giving (5, 3, 4, 1); In-place semantics: an in-place tensor may not change shape

  4. Saved forward valuesUnderstanding Deep Learning - Chapters 3 to 7

    Chapter 7, Section 7.2 Observation 1 (printed pp. 97 to 98): run the network and store the activations of all hidden units in the forward pass for later gradient computation

2

Focus on

  • A node feeding two downstream ops gets the sum of both vector-Jacobian products. PyTorch .grad also accumulates across backward calls, so a missing zero_() silently adds yesterday's gradient to today's.
  • Broadcast forward: align trailing dimensions, prepend 1 to the shorter shape, and take the per-dimension max. Backward inverts it: sum the upstream gradient over exactly the axes where the input had size 1 or a prepended dimension, then reshape back.
  • For with (2, 3) and (3,): keeps shape (2, 3), while = 2 times the sum of over rows. This matches centered differences to about 1e-8 in float64.
  • Leaves are user-created tensors with requires_grad; intermediates carry the graph. Backward saves the forward values its local derivatives need (activations for weights, inputs for nonlinearities); detaching cuts provenance so gradients stop at the cut.
Common mistakes · 3
  • Averaging instead of summing at a branch. The factor belongs to an explicit mean op, never to fan-out: a doubly used node contributes twice.
  • Summing over the wrong axes in unbroadcast. Sum exactly the axes where the input was size 1 or prepended; summing a full-size axis silently shrinks a real dimension.
  • Assuming backward zeroes .grad. It adds; the D2L page states this explicitly for PyTorch, unlike MXNet and TensorFlow which reset.
3

Try it yourself

Closed-book, before checking anything

Closed-book, for with (2, 3) and (3,): derive as 2 times the row sums of and as . Implement broadcast plus accumulation in your blank-file engine and match centered differences.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.z = x * u with u = y.detach() and y = x * x. What is , and why not ?Answer

    . Detach wipes provenance, so influences only directly through the factor; the path through carries no gradient. D2L verifies x.grad == u.

  2. 2.What is the shape of (5, 1, 4, 1) plus (3, 1, 1), and over which axes is the smaller operand's gradient summed?Answer

    The result is (5, 3, 4, 1). The smaller operand aligns as (1, 3, 1, 1), so its gradient sums over dims 0 and 2, then reshapes to (3, 1, 1).

  3. 3.What happens on a second backward call without zero_()?Answer

    The new gradient adds to the stored one. That suits optimizing a sum of objectives but corrupts per-batch training.

  4. 4.For inside a deeper network, which values must backward have available?Answer

    , for , and , for . costs no extra memory because the parameter is alive anyway; is the activation memory backward forces you to keep. needs only .

5

Practice

You're done when

Your engine accumulates shared-node gradients, unbroadcasts a (2, 3) plus (3,) graph, matches centered differences, and you can state the summation axes for any broadcast pair without notes.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 10 more in the section
  • Understanding Deep Learning - Chapters 3 to 7Simon J. D. Prince · primary

    Read Chapters 3-7, emphasizing Chapter 5 for likelihood-derived losses and Chapter 7 for backpropagation and initialization. Use notebooks 3.1, 4.1, 5.1, 6.1 and 7.1 only as equation and plot companions.

  • D2L - tensors, autograd, MLP and backpropagationD2L authors · required

    Use chapter_preliminaries ndarray and autograd, then MLP, backpropagation, and numerical stability and initialization. Recreate scalar operations, affine maps, activation, reduction, stable cross-entropy, topological backward and unbroadcast in a blank file.

  • PyTorch Broadcasting semanticsPyTorch · reference

    Read General semantics for the trailing-dimension rules, prepend-1 alignment and max-size result, with the (5, 1, 4, 1) plus (3, 1, 1) examples; read In-place semantics for why an in-place tensor may not change shape.

Also in this section

  • TensorTonic - Build Micrograd from ScratchTensorTonic · required

    Use the 25-problem Micrograd study plan in order for derivatives, gradient checks, value graphs, reverse mode, accumulation, operators, modules, losses and training. Preserve local tests as the evidence instead of a platform score.

  • Deep-ML candidate - autograd and loss problemsDeep-ML · optional

    After the five-sample platform check passes, use at most one of 26 Basic Autograd Operations, 997 Manual Cross-Entropy Backprop or 1227 Stable Softmax as a changed-prompt drill.

  • CS231n Linear Classification - Softmax classifier and numeric stabilityStanford CS231n · reference

    Read the Softmax classifier section for the cross-entropy form , then the Practical issues: Numeric stability part for the max-subtraction code f -= np.max(f).

  • CS231n Neural Networks 3 - Gradient checksStanford CS231n · reference

    Read the Gradient Checks section only: centered formula with error, relative error with thresholds, double precision, step size near 1e-5, kinks, few datapoints, burn-in, regularization and dropout discipline, and checking a few dimensions per parameter.

  • `torch.autograd.gradcheck` API and tolerancesPyTorch · reference

    Read the gradcheck signature defaults (eps 1e-6, atol 1e-5, rtol 1e-3) and the note that inputs with overlapping memory, such as expand outputs, will likely fail the check.

  • `torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`PyTorch · reference

    Read the ignore_index and reduction parameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only.

  • PyTorch Tensor ViewsPyTorch · reference

    Read the view and storage sharing example (data_ptr, mutating the view changes the base), the transpose non-contiguous example, the full view-ops list, and the special notes: reshape may copy, contiguous copies only when needed, basic indexing returns views while advanced indexing copies.

  • `torch.Tensor.stride` - stride and storage offsetPyTorch · reference

    Read the stride definition: strides are per-dimension element steps, and with storage_offset they locate every element. Combine with the Tensor Views page for transposed and expanded layouts.

  • PyTorch Autograd mechanics - in-place operationsPyTorch · reference

    Read In-place operations with autograd (why in-place rewrites the graph and is discouraged) and In-place correctness checks (the version counter and the error on accessing a modified saved tensor).

  • `torch.nn.Module` - parameters, buffers and statePyTorch · reference

    Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while register_buffer holds persistent non-parameter tensors saved alongside them.