---
title: "Neural network lab: stable losses, recurrent gradients, attention and Adam"
heading: A softmax cross-entropy that can't overflow, backpropagation through time for a recurrent unit checked against finite differences, scaled dot-product attention with a causal mask, and the Adam optimizer on a badly conditioned bowl
eyebrow: S14 · Lesson 37 · Neural network lab
xp: 60
---

::: hook
Deep-learning libraries hide four pieces of code that every model depends on: a loss that stays finite for any logits, gradients through time for recurrent networks, attention, and an optimizer that copes with curvatures differing by orders of magnitude. Lessons 24 to 29 explained each. In this lab you'll write them in plain Python, small enough to check every number by hand or by finite differences, and see where each one would go wrong if written naively.
:::

::: play
- Gradient descent with step size η on a quadratic bowl whose curvatures are 1 and 100. The curves show how the error along each direction evolves, $|1 - \eta\lambda|^k$.
- The steep direction limits the step: above η = 0.02 it diverges, while the shallow direction still crawls.
- Adam (task 4) rescales each coordinate by its own gradient history, so both directions take steps of about the same size, which removes most of this conflict.
:::

```sim plot
view: graph
x: k = 0..300
y: e = 0.000001..1000000 log
slider: h = 0.001..0.025 = 0.015
plot: abs(1 - h)^k | label: curvature 1
plot: abs(1 - 100*h)^k | dashed | label: curvature 100
```

::: predict
## Adam (learning rate 0.1) starts at (1, 1) on $f = \frac12(x^2 + 100y^2)$, whose gradient there is (1, 100). How far does its first step move each coordinate?

- [ ] x by 0.1 and y by 10
- [x] Both by 0.1
- [ ] x by 0.001 and y by 0.1
- [ ] Neither moves on the first step

::: reveal
After bias correction, Adam's first step is $\eta\,\hat m/\sqrt{\hat v} = \eta\,g/|g|$: the learning rate times the sign of each gradient component, so both coordinates move by 0.1 whatever their gradients' sizes. Plain gradient descent would move y a hundred times further than x and, at this rate, overshoot wildly.
:::
:::

::: nameit
## What the lab computes

- **Stable softmax cross-entropy**: with m the largest logit, $\ln\sum_je^{z_j} = m + \ln\sum_je^{z_j - m}$, so no exponential overflows; the loss is that minus $z_k$, and its gradient is the softmax minus the one-hot target.
- **Backpropagation through time**: for $h_t = \tanh(wh_{t-1} + ux_t)$ with $h_0 = 0$ and loss $L = h_T$, run backward from $\partial L/\partial h_T = 1$: at each step $\delta_t = (\partial L/\partial h_t)(1 - h_t^2)$ adds $\delta_th_{t-1}$ to $\partial L/\partial w$ and $\delta_tx_t$ to $\partial L/\partial u$, gives $\partial L/\partial x_t = \delta_tu$, and passes $\delta_tw$ back to $h_{t-1}$.
- **Attention**: for each query, scores $\mathbf q\cdot\mathbf k_j/\sqrt d$, a stable softmax, and the weighted average of the values; with a causal mask, query i sees only keys 0 to i.
- **Adam**: $\mathbf m \leftarrow \beta_1\mathbf m + (1 - \beta_1)\mathbf g$, $\mathbf v \leftarrow \beta_2\mathbf v + (1 - \beta_2)\mathbf g^2$, then $\mathbf x \leftarrow \mathbf x - \eta\,\hat{\mathbf m}/(\sqrt{\hat{\mathbf v}} + \epsilon)$ with $\hat{\mathbf m} = \mathbf m/(1 - \beta_1^t)$ and $\hat{\mathbf v} = \mathbf v/(1 - \beta_2^t)$.
:::

::: check
kind: python

## Write `softmax_xent(z, k)`: the cross-entropy loss for logits z and true class k, and its gradient with respect to z, without overflow for any logits.

```python starter
import math

def softmax_xent(z, k):
    e = [math.exp(v) for v in z]
    s = sum(e)
    return -math.log(e[k] / s), [v / s for v in e]
```

```python solution
import math

def softmax_xent(z, k):
    m = max(z)
    e = [math.exp(v - m) for v in z]
    s = sum(e)
    g = [v / s for v in e]
    g[k] -= 1
    return m + math.log(s) - z[k], g
```

```python tests
import math
loss, g = softmax_xent([1000, 1001, 999], 1)
assert abs(loss - math.log(1 + math.exp(-1) + math.exp(-2))) < 1e-12, "Logits near 1000 must not overflow: the loss is 0.408."
assert abs(sum(g)) < 1e-12 and g[1] < 0 < g[0], "The gradient sums to zero and is negative only for the true class."
loss2, _ = softmax_xent([2, 1, 0], 1)
assert abs(loss2 - 1.407606) < 1e-6, "Lesson 16's example: 1.41 nats."
```

::: right
Right. Subtracting the largest logit changes nothing mathematically and everything numerically.
:::
:::

::: check
kind: python

## Write `rnn_forward(w, u, xs)` returning the states $h_0 = 0, h_1, \ldots, h_T$, and `rnn_grads(w, u, xs)` returning $\partial h_T/\partial w$, $\partial h_T/\partial u$ and the list of $\partial h_T/\partial x_t$.

```python starter
import math

def rnn_forward(w, u, xs):
    return [0.0] * (len(xs) + 1)

def rnn_grads(w, u, xs):
    return 0.0, 0.0, [0.0] * len(xs)
```

```python solution
import math

def rnn_forward(w, u, xs):
    hs = [0.0]
    for x in xs:
        hs.append(math.tanh(w * hs[-1] + u * x))
    return hs

def rnn_grads(w, u, xs):
    hs = rnn_forward(w, u, xs)
    gw = gu = 0.0
    dx = [0.0] * len(xs)
    dh = 1.0
    for t in range(len(xs), 0, -1):
        da = dh * (1 - hs[t] ** 2)
        gw += da * hs[t - 1]
        gu += da * xs[t - 1]
        dx[t - 1] = da * u
        dh = da * w
    return gw, gu, dx
```

```python tests
xs = [1.0, -0.5, 0.3, 0.8, -0.2, 0.1, 0.4, -0.3, 0.2, 0.5]
gw, gu, dx = rnn_grads(0.9, 0.7, xs)
h = 1e-6
nw = (rnn_forward(0.9 + h, 0.7, xs)[-1] - rnn_forward(0.9 - h, 0.7, xs)[-1]) / (2 * h)
nu = (rnn_forward(0.9, 0.7 + h, xs)[-1] - rnn_forward(0.9, 0.7 - h, xs)[-1]) / (2 * h)
assert abs(gw - nw) < 1e-7 and abs(gu - nu) < 1e-7, "Backpropagation matches central differences."
assert abs(gw - 0.931213) < 1e-5, "∂h/∂w = 0.931."
_, _, d = rnn_grads(0.5, 0.7, [0.5] * 30)
assert d[0] < 1e-12 < d[-1], "Thirty steps back, the gradient has vanished."
_, _, d2 = rnn_grads(1.5, 0.7, [0.5] * 30)
assert d2[0] < d[0], "A larger weight saturates the tanh, and the gradient vanishes even faster."
```

::: right
Right. A larger recurrent weight doesn't rescue the gradient here: it drives the tanh into saturation, where its slope is nearly zero.
:::
:::

::: check
kind: python

## Write `attention(Q, K, V, causal=False)` for lists of row vectors, returning one output row per query.

```python starter
def attention(Q, K, V, causal=False):
    return [row[:] for row in V]
```

```python solution
import math

def attention(Q, K, V, causal=False):
    d = len(Q[0])
    out = []
    for i, q in enumerate(Q):
        n = i + 1 if causal else len(K)
        s = [sum(a * b for a, b in zip(q, K[j])) / math.sqrt(d) for j in range(n)]
        m = max(s)
        e = [math.exp(v - m) for v in s]
        z = sum(e)
        out.append([sum(e[j] / z * V[j][c] for j in range(n)) for c in range(len(V[0]))])
    return out
```

```python tests
Q = [[1, 0], [0, 1], [1, 1]]
K = [[1, 0], [0, 1], [1, 1]]
V = [[1, 2], [3, 4], [5, 6]]
full = attention(Q, K, V)
masked = attention(Q, K, V, causal=True)
assert masked[0] == [1.0, 2.0], "With a causal mask, the first position sees only itself."
assert abs(masked[1][0] - 2.339523) < 1e-6, "The second position mixes the first two values."
assert full[2] == masked[2], "The last position sees everything either way."
same = attention([[3, -1]], [[2, 2]] * 4, [[1, 0], [0, 1], [2, 2], [5, 1]])
assert abs(same[0][0] - 2.0) < 1e-12 and abs(same[0][1] - 1.0) < 1e-12, "Identical keys give the plain average of the values."
```

::: right
Right. Attention is a softmax-weighted average; the mask only shortens the list it averages over.
:::
:::

::: check
kind: python

## Write `adam(grad, x0, lr, steps, b1=0.9, b2=0.999, eps=1e-8)`, returning the final point.

```python starter
def adam(grad, x0, lr, steps, b1=0.9, b2=0.999, eps=1e-8):
    x = list(x0)
    for _ in range(steps):
        x = [a - lr * g for a, g in zip(x, grad(x))]
    return x
```

```python solution
import math

def adam(grad, x0, lr, steps, b1=0.9, b2=0.999, eps=1e-8):
    x = list(x0)
    m = [0.0] * len(x)
    v = [0.0] * len(x)
    for t in range(1, steps + 1):
        g = grad(x)
        for i in range(len(x)):
            m[i] = b1 * m[i] + (1 - b1) * g[i]
            v[i] = b2 * v[i] + (1 - b2) * g[i] ** 2
            x[i] -= lr * (m[i] / (1 - b1 ** t)) / (math.sqrt(v[i] / (1 - b2 ** t)) + eps)
    return x
```

```python tests
grad = lambda x: [x[0], 100 * x[1]]
x1 = adam(grad, [1.0, 1.0], 0.1, 1)
assert abs(x1[0] - 0.9) < 1e-6 and abs(x1[1] - 0.9) < 1e-6, "The first step moves both coordinates by the learning rate."
x = adam(grad, [1.0, 1.0], 0.01, 2000)
assert abs(x[0]) < 1e-6 and abs(x[1]) < 1e-6, "It reaches the minimum."
y = adam(lambda x: [1000 * x[0]], [1.0], 0.01, 1)
assert abs(y[0] - 0.99) < 1e-6, "The step doesn't depend on the gradient's scale."
```

::: right
Right. Adam's per-coordinate scaling makes its steps insensitive to the curvature differences that limit plain gradient descent.
:::
:::

::: explain
## Why does gradient descent with one learning rate struggle on a loss whose curvature differs greatly between directions, and how does Adam help?

::: model
A step of size η along a direction of curvature λ shrinks the error there by $|1 - \eta\lambda|$, so η must stay below 2/λ for the steepest direction or that direction diverges. With such a small step, the shallow directions shrink by only $1 - \eta\lambda_\text{min}$ per step, and training takes about as many steps as the ratio of the two curvatures. Adam divides each coordinate's step by a running estimate of its gradient's size, so coordinates with large gradients take proportionally smaller steps and those with small gradients larger ones. When the curvature differences line up with the coordinates, this nearly equalizes them; it helps less when the steep directions are mixtures of many coordinates.
:::
:::
