What Each Box Hands Back

The Multivariate Chain RuleEasy+10 XP+10

What Each Box Hands Back

In a backward pass, no box ever looks at the whole graph. Each box receives one number from above — the gradient flowing back, ∂L∂(its output)\dfrac{\partial L}{\partial (\text{its output})}∂(its output)∂L​ — and multiplies it by its own local derivatives to hand one number back to each of its inputs. That is the chain rule, done one box at a time.

Task: write node_backward(op, inputs, upstream), which plays the part of a single box.

  • op names the box.
  • inputs lists the numbers that flowed into the box during the forward pass.
  • upstream is the gradient arriving at the box's output from above.

Return a list holding one gradient for each input value, in the same order as inputs, each rounded to 4 decimal places.

opinputswhat the box computes
"add"[x, y]x+yx + yx+y
"mul"[x, y]x⋅yx \cdot yx⋅y
"pow"[x, k]xkx^kxk
"exp"[x]exe^xex, available as math.exp
"tanh"[x]tanh⁡(x)\tanh(x)tanh(x), available as math.tanh

For "pow", the exponent k is a fixed number written into the box — it may be negative or a fraction — not a value flowing through the graph. It gets no gradient, so a "pow" box returns a one-element list. Whenever k is a fraction, x is positive.

tanh⁡\tanhtanh is the one box this course has not differentiated, so take its local derivative as given: if t=tanh⁡(x)t = \tanh(x)t=tanh(x), then

dtdx=1−t2\frac{dt}{dx} = 1 - t^2dxdt​=1−t2

Examples

op = "mul"
inputs = [4.0, -2.5]
upstream = 3.0
returns [-7.5, 12.0]
op = "tanh"
inputs = [0.5]
upstream = 2.0
returns [1.5729]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run