Neural Computation, Losses & Reverse Mode

Deep learning becomes debuggable when tensor semantics, objective reductions and reverse accumulation are understood below the framework surface.

Section 1 of 8 · 7 units · about 28 hours

0/7

By the end you can From a blank file, implement reverse accumulation for a branched broadcast graph, match finite differences and PyTorch within justified tolerance, and explain each saved value and mutation hazard.

Units

Build it

Mini project · about 10 to 14 hours

Tensor reverse-mode engine with differential checks

Build a small tensor autodiff engine on NumPy in your own repository: broadcast-aware operations, reverse accumulation over branched graphs, a stable cross-entropy and one tensor MLP. Prove its gradients against finite differences and PyTorch, not against a training curve.

  1. 1Implement a Tensor class on NumPy with add, mul, matmul, sum over axes, exp, log, tanh and ReLU, each with a backward rule, and a backward() that visits a topological order and accumulates into .grad.
  2. 2Make every binary op broadcast-aware: sum each incoming gradient over the broadcast axes back to the operand shape. Test (3, 1) with (1, 4), (4,) with (3, 4), and a scalar, against PyTorch.
  3. 3Add log-softmax and mean cross-entropy as one fused op whose gradient is softmax minus one-hot over the batch size. Test float32 logits of magnitude 1000 for finite loss and gradients, against torch.nn.functional.cross_entropy.
  4. 4Build a branched graph where one tensor reaches the loss through at least three paths including a broadcast. Check every leaf gradient against central differences and PyTorch in float64, keeping the comparison as evidence.
  5. 5Train a two-layer tensor MLP with your engine on a small synthetic classification set, and show its first-step gradients match a PyTorch copy with the same weights.
  6. 6Layout tests: feed transposed and noncontiguous arrays into your engine and match gradients from contiguous copies. For PyTorch views, assert shared storage through untyped_storage().data_ptr(), and compute the element offset from strides and storage_offset for a slice, a transpose and an expand.
  7. 7Reproduce one saved-value or mutation defect, such as an input edited in place between forward and backward. Show the wrong or refused gradient, fix it with a copy on save or a version counter, and keep a regression test.
What you hand in
  • The engine package: ops with broadcast-aware backward, topological backward, fused cross-entropy and the MLP.
  • The test suite: float64 finite-difference and PyTorch checks, broadcast cases, extreme-logit cases, layout and storage tests, and the defect regression test.
  • A one-page note listing the values each op saves for backward, why, and the tolerance chosen for each check.
How to check it
How it's graded

Gradient correctness

Pass: Every op matches PyTorch in float64 within a stated tolerance on random inputs.

Great: The branched broadcast graph matches both finite differences and PyTorch, and the note justifies the step size and tolerance.

Broadcasting

Pass: Gradients reduce to each operand shape in the tested broadcast cases.

Great: A property test draws random broadcast-compatible shape pairs and compares against PyTorch.

Numerical stability

Pass: Cross-entropy stays finite on extreme float32 logits.

Great: A test shows the naive form failing on the same input, and the note explains why the max shift leaves the gradient unchanged.

Saved values and mutation

Pass: One defect is reproduced, fixed and guarded by a test.

Great: The note lists every saved value per op, and the engine either refuses or survives an in-place edit of a saved input, with a test for each case.

Layout

Pass: Transposed and noncontiguous inputs give the same gradients as contiguous copies.

Great: Storage and offset assertions cover a slice, a transpose and an expand, checked against PyTorch strides.

Resources

  • Understanding Deep Learning - Chapters 3 to 7Simon J. D. Prince

    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

    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.

  • TensorTonic - Build Micrograd from ScratchTensorTonic

    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

    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

    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

    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.

  • PyTorch Broadcasting semanticsPyTorch

    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.

  • `torch.autograd.gradcheck` API and tolerancesPyTorch

    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

    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

    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

    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

    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

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