Lecture 5 · ML Math I · September 30
How Does an Error Reach the Parameters?
What does $L$ do if a parameter moves?
Mathematics for Robotics · ROB-GY 6013 · NYU Tandon · Jing Zhang · Fall 2026
Recall
What We Already Know, and What We Need Next
Backprop produces $\nabla L$. Moving the parameters is a separate job.
Vote
Which Small Move Reduces the Error?
$L=\tfrac12(x_1+2x_2-3)^2$, now at $x=(0,0)$. Which step of length $\varepsilon=0.1$ lowers $L$ the most?
New losses $4.205$, $3.92$, $4.805$, against $4.5$ where we started.
B is the best of these three. The steepest direction of all is not on offer.
Definition
A Loss Turns Many Errors into One Number
Worked example
$e=(1,-2)$: $L=\tfrac12(1^2+2^2)=2.5$.
Lecture 3 measured $r=y^\star-\hat y$, so $e=-r$.
Vote
Scalar, Vector, or Matrix?
$x\in\R^3$, $W\in\R^{2\times3}$, $\hat y=Wx$, $L=\tfrac12\|\hat y-y^\star\|^2$. What shapes are $L$, $\nabla_xL$ and $\nabla_WL$?
A gradient carries the shape of the variable it differentiates. Row conventions exist; ours is columns.
Roadmap
One Question, Three Ways to Check the Answer
One derivative, three checks: a tensor program, autograd, a finite difference.
Definition
A Derivative Is a Local Slope
Vote
Does the Tangent Prediction Become Exact?
$f(x)=x^2$ at $x=1$. The tangent predicts $1+2h$; the curve gives $(1+h)^2$. How does actual minus predicted behave?
$(1+h)^2-(1+2h)=h^2$: $0.25$ at $h=0.5$, $0.01$ at $h=0.1$. Exact only at $h=0$.
Derivation
Partial Derivatives Hold Other Coordinates Fixed
Step $h$ in $x_1$: $\delta=h$, so $\partial_1L=s$.
Step $h$ in $x_2$: $\delta=2h$, so $\partial_2L=2s$.
Vote
Which Coordinate Has Greater Local Sensitivity?
At $x=(0,0)$, what is $\nabla L=(\partial_1L,\ \partial_2L)\T$?
$s=-3$, and the slices give $s$ and $2s$. Both slopes are signed derivatives per unit of their own coordinate, not a ranking of importance when the units differ.
Derivation
The Gradient Predicts a Small Loss Change
Numerical check
$\Delta x=(0.1,0.1)$: predicted $-0.9$, actual $-0.855$.
Derivation
Directional Derivatives and Steepest Ascent
Worked example
New loss: $\tfrac12(x_1^2+2x_2^2)$ at $(2,\tfrac12)$, $\nabla L=(2,1)$, $D_vL=\sqrt5\cos60^\circ\approx1.118$.
Vote
Which Direction Is Locally Flat?
Back at $x=(0,0)$. Which unit direction has $D_vL=0$?
$\nabla L\T v$ gives $-3\sqrt5$, $0$, $3\sqrt5$. Here B does better than first order: $L$ is constant along that whole line.
Synthesis
Gradient, Jacobian, and Hessian Have Different Jobs
Definition
Columns of the Jacobian Are Input Effects
Worked example
At $x=(1,2)$: $f(x)=(5,2)$, $J_f=\begin{bmatrix}1&2\\2&1\end{bmatrix}$, $dy=J_fe_1=(1,2)$.
Vote
Which Matrix Has the Right Shape?
$f:\R^3\to\R^2$. Which shape must $J_f$ have?
$dy=J_f\,dx$ with $dx$ of size $3\times1$ and $dy$ of size $2\times1$: rows are outputs, columns are inputs.
Derivation
Follow a Perturbation Through Two Maps
1 2 2 1
$dx=e_1$ gives $dy=(1,2)$
and then $dz=(3,4)$
$J_gJ_f=\begin{bmatrix}1&1\\0&2\end{bmatrix}\begin{bmatrix}1&2\\2&1\end{bmatrix}=\begin{bmatrix}3&3\\4&2\end{bmatrix}$
Derivation
Matrix Multiplication Is the Multivariable Chain Rule
Multiply along a route, add across routes.
Vote
Which Order Propagates the Input Change?
$f:\R^2\to\R^3$ then $g:\R^3\to\R$, with $L=g(f(x))$. Which product is $\partial L/\partial x$?
Inner dimensions must match, and a sum needs two equal shapes. Only B is defined, and it is $1\times2$, the shape of $(\nabla_xL)\T$.
Derivation
A Scalar Loss Sends Sensitivity Backward
$=(\nabla_yL)\T J_f\,dx$ : put $dy=J_f\,dx$ in
$=(J_f\T\nabla_yL)\T dx$ : move $J_f$ across the pairing
since $(J_f\T\nabla_yL)\T=(\nabla_yL)\T J_f$
$\nabla_xL=J_f\T\nabla_yL$ : the coefficient of $dx$
Definition
JVP and VJP Answer Different Questions
Worked example
$J=\begin{bmatrix}1&2\\3&4\end{bmatrix}$: $Jv=(1,3)$ for $v=(1,0)$, and $J\T u=(-2,-2)$ for $u=(1,-1)$.
Vote
Transpose or Pseudoinverse?
$J$ is $2\times3$ and $g=\nabla_yL\in\R^2$. Which product is $\nabla_xL$?
The middle caption is the question. $J^{+}g$ is the minimum-norm least-squares input for a requested $g$, which need not be reachable. With a square $J$ all three shapes agree, so a shape check goes quiet.
In practice
Why a Scalar Loss Favors Reverse Mode
Both modes are the same chain rule.
Vote
Choose a Differentiation Direction
Assign reverse mode or one forward JVP to jobs A, B and C.
C is one JVP along the supplied $v$, with no Jacobian built. Judge by the product you need, not by what networks usually do.
Method
Find the Coefficient of the Input Change
Match $dL=(\nabla_xL)\T dx$ for every $dx$: $dx=e_j$ reads off entry $j$. $d$ means differential, not a number to cancel.
Definition
Matrices Have an Inner Product Too
Worked example
$\langle A,B\rangle_F=4-3+0+0=1=\operatorname{tr}(A\T B)$.Vote
Which Matrix Is the Gradient?
$L(W)=2W_{11}-W_{12}+3W_{21}+0\cdot W_{22}$. Which matrix is $\nabla_WL$?
Each cell holds the coefficient of its own entry. A transposes them; $2W$ is $\nabla_W\|W\|_F^2$.
Derivation
Differentiate a Squared Length
Worked example
$x=(1,-2)$: $L=2.5$ and $\nabla L=(1,-2)$.Without the $\tfrac12$ the gradient would be $2x$.
Derivation
Differentiate a Quadratic Form
So $\nabla(x\T Ax)=(A+A\T)x$; $A$ need not be symmetric, and $\nabla(\tfrac12x\T Hx)=Hx$ when $H=H\T$.
Vote
Where Did the Factor of Two Go?
$L=2x_1^2+\tfrac12x_2^2=\tfrac12x\T Hx$ with $H$ diagonal. Which $H$?
$\nabla L=Hx=(4x_1,x_2)$. In $x\T Kx$ the coefficient matrix is $K$ itself, and the Hessian is $2K$ for symmetric $K$.
Derivation
The Least-Squares Gradient, One Step at a Time
$de=A\,dx$
$dL=e\T de=e\T A\,dx$
$\nabla_xL=A\T(Ax-b)$
Worked example
$x=(1,1)$: $e=(2,0,-1)$, $\nabla_xL=(1,4)$.Lecture 3’s $r=b-Ax$ is $-e$, so $\nabla_xL=-A\T r$.
Recall
Calculus Recovers the Orthogonality Condition
Curvature along any direction $v$ is $v\T A\T Av=\|Av\|^2\ge0$, so $L$ is convex and a stationary point is a global minimum. Unique unless some $v\ne0$ has $Av=0$.
Vote
Match the Gradient to the Geometry
1 1b =
3 1
$L(x)=\tfrac12[(x-3)^2+(x-1)^2]$ with scalar $x$. What is $L'(0)$?
$L'(x)=2x-4$, so a small increase in $x$ lowers the loss.
Minimiser $x=2$, output $(2,2)$, residual $(1,-1)$. The gradient is one number in parameter space; the residual is a vector in output space.
Recap
A Small Derivative Toolkit
Each row comes from writing $dL$ as a pairing with the increment.
$\nabla(a\T x)=a$ $n\times1$
$\nabla(\tfrac12\|x\|^2)=x$ $n\times1$
$\nabla(x\T Ax)=(A+A\T)x$ $n\times1$
$\nabla(\tfrac12\|Ax-b\|^2)=A\T(Ax-b)$ $n\times1$
$\nabla_W(\tfrac12\|W\|_F^2)=W$ $m\times n$
$a,A,b$ fixed. Row 3 holds for any $A$; $\nabla(\tfrac12x\T Hx)=Hx$ needs $H=H\T$.
Definition
Split a Formula into Small Operations
$u=ab=6$
$v=u+c=5$
$L=v^2=25$
The graph records dependencies, and the backward pass reuses exactly these stored values.
Vote
Fill the Forward Pass
Which triple is $(u,v,L)$, and at which node do the other two break?
B breaks at the addition node; C breaks at the multiplication node and then again at the addition.
Definition
Start Backward with One
$\bar x$ and $g_x$ name the same object. Upstream means nearer the loss along the backward path.
Rules
Addition Copies, Multiplication Scales
In the running graph $\bar v=10$ gives $\bar u=\bar c=10$.
Vote
Which Number Returns to a?
$\bar v=10$ is already known. Which number returns to $a$?
$\bar a=b\,\bar u=30$ and $\bar b=a\,\bar u=20$. A forgot the local factor; B used $a$ where the rule asks for $b$.
Derivation
Shared Variables Receive Contributions from Every Path
Worked example
At $x=3$: $2$ from $u$ and $6$ from $v$ add to $8$ in the accumulator.Vote · pairs
Find the Missing Path
At $x=3$ a program reports $dL/dx=6$. What is wrong?
Both paths contribute: $2$ through $u$ and $6$ through $v$, so $dL/dx=8$. The reported $6$ is the $v$ path alone. Overwriting is one possible cause; a $u$ term never added is another.
Worked example
The Same Operand Can Enter Twice
Worked example
At $x=3$: $\bar x=3+3=6$.One shared node is not two copies. This is the product rule, and where the factor $2$ on a squared length came from.
Method
Reverse Order Makes the Local Rules Work
Vote
Backpropagation or Optimization?
Which of these is backpropagation itself?
Backpropagation produces the gradient and stops.
Next lecture
$\theta_{\text{new}}=\theta-\eta\nabla_\theta L$, with a learning rate $\eta$.Definition
A Linear Layer Has Three Differentiable Inputs
Three arrows enter, so three gradients leave. With a bias the map is affine; “linear layer” is the usual name.
Derivation
Derive the Three Affine Backward Rules
$W\,dx\ \Rightarrow\ \nabla_xL=W\T g_z$
$(dW)x\ \Rightarrow\ \nabla_WL=g_zx\T$
$db\ \Rightarrow\ \nabla_bL=g_z$
Vote
Which Product Has the Weight’s Shape?
$x$ has $3$ entries and $z$ has $2$, so $W$ is $2\times3$. Which product has $W$’s shape?
A shape check rejects a wrong formula; it never proves a right one.
Definition
ReLU Passes Some Local Sensitivities
ReLU clamps the value. Backward, each entry is multiplied by $0$ or $1$ — the diagonal Jacobian, applied entrywise.
Vote
Which Gradient Entries Survive?
A ReLU layer had $z=(-2,3)$ on the forward pass, and $g_a=(4,-5)$ arrives. Which is $g_z$?
An active unit passes a negative sensitivity unchanged: ReLU clamps the value, not the gradient.
Worked setup
One Network We Can Calculate Completely
Worked forward
Forward Values Become Backward Ingredients
1 2y* =
1
Worked example
$z_1=(1{+}2,\,1{-}2)$, and the second unit is clamped, so $a_1$ keeps $3$ and drops the negative entry. Then $\hat y=2\cdot3-1\cdot0$.
Vote
Start at the Loss
1 2y* =
1
Three numbers sit at the end of the forward pass. Which one is $g_{\hat y}=\partial L/\partial\hat y$?
$\dfrac{d}{d\hat y}\tfrac12(\hat y-1)^2=\hat y-1$, so this loss makes the first prediction sensitivity equal the error.
Worked backward
Backpropagate Through the Output Layer
1 2y* =
1
The second weight’s gradient is zero because $a_{1,2}=0$, not because $g_{a_1,2}$ is.
Vote
Backward Through the Hidden Gate
1 2y* =
1
The forward pass left $z_1=(3,-1)$, and $g_{a_1}=(10,-5)$ now arrives. Which is $g_{z_1}$?
The mask is read from the forward row, never from the sign of the sensitivity above.
Worked backward
Finish the First Layer
1 2y* =
1
No parameter has moved: changing them is a separate job.
Vote · pairs
Diagnose a Zero Gradient
1 2y* =
1
Why is the second row of $\nabla_{W_1}L$ zero here?
Feed $x'=(2,1)$: now $z_1=(3,1)$, both units are active, and that row becomes $(-8,-4)$. A zero input or cancellation can zero a gradient too.
Convention
Put Samples in Rows
One sample gives $z=Wx+b$. Transposing turns $Wx$ into $x\T W\T$, so a row of $X$ goes through $W\T$. In code $b$ holds shape $(m,)$ and broadcasts.
Derivation
Matrix Multiplication Backward
$\nabla_XL=GU\T$: the $dX$ coefficient.
$\nabla_UL=X\T G$; entrywise $\partial L/\partial U_{kj}=\sum_iX_{ik}G_{ij}$.
With $U=W\T$: $\nabla_XL=GW$ and $\nabla_WL=G\T X$.
Vote
Choose the Batch Weight Gradient
$B=4$, $n=3$, $m=2$ and $Z=XW\T$, with $G=\nabla_ZL$. Which is $\nabla_WL$?
$X\T G$ is the gradient of $U$ in $Y=XU$. Name the parameter first, then multiply.
Derivation
Broadcasting Forward Means Summing Backward
A variable used in many places collects one contribution from each.
Vote
Which Axis Must Be Summed?
$G=\begin{bmatrix}1&2\\3&4\\-1&5\end{bmatrix}$ with $B=3$ and $m=2$. Which is $\nabla_bL$?
Sum over samples, not over features: in code, G.sum(dim=0). The bias has one entry per feature.
Definition
Define the Loss Reduction Before Differentiating
“MSE” alone is ambiguous: at the same denominator, a framework MSE without the one-half has twice this gradient.
Worked example
Per-Sample Contributions Add into a Matrix Gradient
Worked example
$X=\begin{bmatrix}1&0\\0&2\end{bmatrix}$, $W=[1,1]$, $b=0$, $Y=0$, $B=2$, $L=\frac1{2B}\|Z-Y\|_F^2$: then $Z=(1,2)\T$ and $L=1.25$.
Vote
Find the Double-Averaging Bug
$G$ is already $(Z-Y)/B$ for the same batch. The next line writes dW = G.T @ X / B. That result is:
$1/B$ appears twice: once inside $G$, once in the divide. Apply the loss scale exactly once.
Method
Compare a Gradient with a Measured Change
A finite difference measures. Reverse mode applies the chain rule to the operations as written.
Vote
Check One Weight Numerically
1 1 1 −1
Move $W_1[1,2]$ by $\varepsilon=0.01$, nothing else. Given $L_+=12.7008$ and $L_-=12.3008$, what is $\dfrac{L_+-L_-}{2\varepsilon}$?
$0.4/0.02=20$, and the hand value of $\nabla_{W_1}L$ at that entry agrees. The first unit reads $3.02>0$ then $2.98>0$: no gate flips.
Method
Check a Direction Without Building a Jacobian
A coordinate sweep costs two evaluations per coordinate. One direction that agrees is evidence, not proof.
Vote
Is a Smaller Epsilon Always Better?
Does a smaller $\varepsilon$ always give a better check?
Truncation here is $O(\varepsilon^2)$ for smooth enough $L$; the subtraction loses digits as $\varepsilon$ shrinks.
Sweep a few $\varepsilon$ in double precision; no one value fits all.
Warning
Nondifferentiability Needs a Different Check
Worked example
$\varepsilon=0.01$: $(0.01-0)/0.02=\tfrac12$, while the backward pass returns $0$.
A mismatch at the corner is not evidence of a broken smooth derivative.
Vote
What Counts as a Gradient Check?
Which test shows a manual backward returns the right numbers?
NoneA and C are diagnostics; neither establishes a value. Use a smooth fixture.
The linear task we read checks shapes, the forward product and that gradients exist, never their values.
Inspected 2026-09-30: TorchCode torch_judge/tasks/linear.py blob 82fe0b4d: one task at one version, not every TorchCode test.
In practice
Read the Exercise as a Mathematical Contract
Contract
affine_backward(X, W, G)
→ dX $B\times n$, dW $m\times n$, db $m$
Exercise shape after TorchCode, github.com/duoan/TorchCode; the fixtures and the checker are ours.
In practice
Translate the Affine Backward Rules
A manual backward uses basic tensor operations; it never calls .backward(). AD is the checker's job.
Vote
Find the Wrong Transpose
$X$ is $4\times3$, $W$ is $2\times3$, $G$ is $4\times2$. Which line gives $dX$?
G @ W✓G @ W.Tinner $2\ne3$W @ Ginner $3\ne4$$(4\times2)(2\times3)=4\times3$, the shape of $X$.
$dX_{ik}=\sum_jG_{ij}W_{jk}$ sums the $m$ outputs; the forward pass summed the $n$ inputs.
In practice
Translate ReLU Backward
g_z = g_a * (z > 0) — the mask needs the cached forward $z$.
A test that only checks nonnegative forward outputs says nothing about the backward pass.
Vote
Which Mask Computes the Correct Derivative?
$z=(-2,3)$ and $g_a=(4,-5)$. Which line gives $g_z$?
g_a * (g_a > 0)$(4,0)$g_a * (z > 0)✓relu(g_a)$(4,0)$B gives $(0,-5)$. A and C read the sign of the upstream gradient and delete a real negative entry; the mask belongs to the forward $z$.
In practice
Three Checks of the Same Small Network
1 1 1 −1
| entry | by hand | program | autograd | centred difference |
|---|---|---|---|---|
| W₁[1,2] | 20 | 20 | 20 | 20.000 |
| W₂[1,1] | 15 | 15 | 15 | 15.000 |
| b₂ | 5 | 5 | 5 | 5.000 |
Four columns, three checks of the hand column. ε = 1e−4 · autograd 0 (tol 1e−9) · fd ≤ 2.406e−12 (tol 2e−5)
Scaled error $|a-b|/\max(1,|a|,|b|)$: absolute near zero, not relative. No torch: autograd rows read skip, not pass.
Measured by python3 build/exercises/m5/check.py --verbose --require-autograd at 0b3feee, float64: 85 comparisons executed, 0 failed, 0 skipped. Transcript in build/exercises/m5/EVIDENCE.md.
Application
A Robot Error Uses the Same Chain Rule
Vote
Which Joint Has the Larger Signed Derivative?
$J=\begin{bmatrix}1&2\\0&1\end{bmatrix}$, $e=(1,-1)$. What is $\nabla_qL=J\T e$?
Each entry is one column of $J$ dotted with $e$: $1\cdot1+0\cdot(-1)$, then $2\cdot1+1\cdot(-1)$. Neither joint is larger.
Comparison
Input Gradients and Parameter Gradients Are Different Questions
Vote
Same Forward Value, Different Derivative
$x=2,\ w=3,\ b=1,\ y^\star=4$, so $z=7$ and $e=3$. What is $(\partial L/\partial x,\ \partial L/\partial w)$?
$\partial L/\partial x=ew=3\cdot3$ and $\partial L/\partial w=ex=3\cdot2$. One forward value, two partners.
Warning
Passing a Shape Check Is Not Enough
Worked example
Entry $(1,2)$ sums over the two samples: $1\cdot2+3\cdot1=5$. The transposed product puts $0$ there.
Vote
Which Test Detects the Hidden Bug?
Both candidates are $2\times2$. Which test separates them?
With $L(W)=\langle G,XW\T\rangle_F$, $G$ is $\nabla_ZL$ for $Z=XW\T$, exactly. Perturb $W_{12}$: the slope is 5, not 0.
Setup
A Complete Regression Graph
Worked forward
Forward Values and Local Derivatives
x (1,2) y (2,2) w 1 b 0
Vote · pairs
Accumulate the Parameter Gradients
x (1,2) y (2,2) w 1 b 0
With $\hat y=(1,2)$, $e=(-1,0)$ and $B=2$: what is $(\partial L/\partial w,\ \partial L/\partial b)$?
$(-1\cdot1+0\cdot2)/2$ and $(-1+0)/2$. Sample 2 contributes nothing: its error is zero.
Synthesis
Write the Same Calculation as Matrix Calculus
x (1,2) y (2,2) w 1 b 0
Vote
What If We Duplicate Every Sample?
x (1,2) y (2,2) w 1 b 0
Duplicate both samples, so $B=4$, with the same mean loss and the same $w,b$. The gradient…
$\sum e_ix_i$ goes from $-1$ to $-2$ and $B$ from 2 to 4. An unnormalised sum loss would double.
Check
Verify the Capstone Independently
x (1,2) y (2,2) w 1 b 0
Worked example
Probes $0.245125$ and $0.255125$ differ by $-0.01$; over $0.02$ that is $-0.5$.
Vote
Exit Vote: What Actually Travels Backward?
What actually travels backward?
Seed $\partial L/\partial L=1$. Then $\partial L/\partial\hat y=e$ for $L=\tfrac12e^2$, or $e_i/B$ for the batch mean.
Recap
Four Rules to Take Away
Next: new data, your choice of method.
Vote · pairs
New Data, Same Method?
Find $L$ and both gradients. Choose a method; check one slope.
| sample | $e_i$ | $e_ix_i/B$ | $e_i/B$ |
|---|---|---|---|
| 1 | $-2$ | $1$ | $-1$ |
| 2 | $1$ | $1$ | $1/2$ |
| sum | — | $2$ | $-1/2$ |
$L=5/4$.
Where the rules come from
Practice, and the course standards
Practice-sheet pattern after TorchCode, MIT licence. Gradient existence: its torch_judge/tasks/linear.py, blob 82fe0b4d81b5. Kink convention: tasks/relu.py, blob aea98fe24001. Both inspected 2026-09-30.