Three Runners, One Valley

OptimizersMedium+20 XP+20

Three Runners, One Valley

Chapter 4 compares plain descent, momentum and Adam by racing them on the same landscape. Here you build that race.

The track is a stretched bowl. With weights w1,…,wnw_1, \dots, w_nw1​,…,wn​ and a curvature ci>0c_i > 0ci​>0 for each coordinate,

L(w)=12∑ici wi2,∂L∂wi=ci wiL(w) = \tfrac{1}{2}\sum_i c_i\,w_i^2, \qquad \frac{\partial L}{\partial w_i} = c_i\,w_iL(w)=21​i∑​ci​wi2​,∂wi​∂L​=ci​wi​

A large cic_ici​ makes that direction steep and a small one makes it gentle. When the curvatures differ a lot, the bowl becomes a narrow valley.

The runners. All three start from the same point. Each takes exactly steps updates using its own learning rate α\alphaα from rates. At every update a runner measures the gradient ggg at its current position and then moves every coordinate at once. Everything below is per coordinate.

  • Plain descent ("sgd"): w←w−α gw \leftarrow w - \alpha\,gw←w−αg
  • Momentum ("momentum"), with velocity vvv starting at 000:
v←0.9 v+g,w←w−α vv \leftarrow 0.9\,v + g, \qquad w \leftarrow w - \alpha\,vv←0.9v+g,w←w−αv
  • Adam ("adam"), with mmm and sss starting at 000, and update number t=1,2,3,…t = 1, 2, 3, \dotst=1,2,3,…:
m←0.9 m+0.1 g,s←0.999 s+0.001 g2m \leftarrow 0.9\,m + 0.1\,g, \qquad s \leftarrow 0.999\,s + 0.001\,g^2m←0.9m+0.1g,s←0.999s+0.001g2 m^=m1−0.9 t,s^=s1−0.999 t,w←w−α m^s^+10−8\hat{m} = \frac{m}{1 - 0.9^{\,t}}, \qquad \hat{s} = \frac{s}{1 - 0.999^{\,t}}, \qquad w \leftarrow w - \alpha\,\frac{\hat{m}}{\sqrt{\hat{s}} + 10^{-8}}m^=1−0.9tm​,s^=1−0.999ts​,w←w−αs^​+10−8m^​

Task: write optimizer_race(curvatures, start, rates, steps).

  • curvatures and start are equal-length lists of floats.
  • rates is a dict with keys "sgd", "momentum" and "adam".

Return a dict with the same three keys, each mapped to that runner's final loss L(w)L(w)L(w), rounded to 4 decimal places. A runner whose learning rate is too large for the track still reports its loss, however huge.

plainmomentumadam

In a narrow valley the differences are stark: plain descent zig-zags while Adam heads almost straight in.

Examples

curvatures = [1.0, 50.0]
start = [6.0, 1.0]
rates = {"sgd": 0.035, "momentum": 0.01, "adam": 0.3}
steps = 40
returns {'sgd': 1.041, 'momentum': 0.3427, 'adam': 0.4199}
curvatures = [2.0, 2.0]
start = [3.0, -3.0]
rates = {"sgd": 0.1, "momentum": 0.05, "adam": 0.2}
steps = 15
returns {'sgd': 0.0223, 'momentum': 0.0478, 'adam': 0.1608}

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