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
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
- Affine maps, nonlinearities and logits4h
- Stable softmax, cross-entropy and loss reductions5h
- Computation graphs and reverse accumulation5h
- Branches, broadcasting and saved values in backward5h
- Gradient checks with finite differences3h
- Tensor layout: shape, stride, views and copies3h
- Aliasing, mutation and module ownership3h
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.
- 1Implement a
Tensorclass on NumPy withadd,mul,matmul,sumover axes,exp,log,tanhandReLU, each with abackwardrule, and abackward()that visits a topological order and accumulates into.grad. - 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. - 3Add log-softmax and mean cross-entropy as one fused op whose gradient is softmax minus one-hot over the batch size. Test
float32logits of magnitude 1000 for finite loss and gradients, againsttorch.nn.functional.cross_entropy. - 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. - 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.
- 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 andstorage_offsetfor aslice, atransposeand anexpand. - 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:
float64finite-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
- TensorTonic autograd-from-scratch problems named in the units
Solve the dense layer, tanh, topological sort, shared-path accumulation and gradient-check problems before you wire the same rules into your engine.
- Self-grade with the rubric below
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
gradchecksignature defaults (eps1e-6,atol1e-5,rtol1e-3) and the note that inputs with overlapping memory, such asexpandoutputs, will likely fail the check. - `torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`PyTorch
Read the
ignore_indexandreductionparameters: 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:reshapemay copy,contiguouscopies 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_offsetthey 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_bufferholds persistent non-parameter tensors saved alongside them.