What unrolling does to the parameter count, and what it does to the gradient.
python3 rnn.py
Unrolling, the flat parameter count, the decay and the fix.
python3 rnn.py --bptt
The whole backward pass for the chapter's three word sentence: the error at the scores, the sweep from the last step to the first, every gradient, and a numerical check that agrees to within 4e-10.
python3 rnn.py --vanish
Backpropagation through time multiplies one Jacobian per step. The evidence sits 37 words behind the gap, some 47 steps once punctuation counts as tokens, and at a per-step factor of 0.5 what reaches that far is 7.1e-15.
python3 rnn.py --clip
Clipping, before and after.
"""The recurrent network, worked as Chapter 12 works it.
Five things, all reproducing the chapter's tables:
unrolling three time steps by hand, h_0 to h_3
the parameter count why an RNN does not grow with the sequence
backpropagation every gradient of the loss, checked against a numerical one
vanishing gradients the product of Jacobians, and where it dies
gradient clipping what the rescale actually does
python3 rnn.py # all five
python3 rnn.py --unroll # the three-step trace
python3 rnn.py --params # RNN against a feed-forward window
python3 rnn.py --bptt # the backward pass, and the numerical check
python3 rnn.py --vanish # the decay table, and the 47-word example
python3 rnn.py --clip # clipping, before and after
Install: pip install numpy
"""
import argparse
import math
try:
import numpy as np
except ImportError:
raise SystemExit("this one needs numpy: pip install numpy")
# ------------------------------------------------------------- the recurrence
# A model small enough to print in full. Two hidden units, three vocabulary
# words, embeddings of size two.
WORDS = ["the", "dog", "ran"]
E = np.array([[0.50, -0.20], # the
[0.10, 0.80], # dog
[-0.60, 0.30]]) # ran
W = np.array([[0.60, -0.30], # input to hidden, 2 x 2
[0.20, 0.50]])
U = np.array([[0.40, 0.10], # hidden to hidden, 2 x 2
[-0.20, 0.70]])
bh = np.array([0.05, -0.05])
V = np.array([[0.70, -0.30], # hidden to vocabulary, 3 x 2
[-0.40, 0.60],
[0.10, 0.20]])
by = np.zeros(3)
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def show_unroll():
print("\nSTEP 1 unrolling three time steps by hand\n")
print(" h_t = tanh(W x_t + U h_{t-1} + b_h), y_t = softmax(V h_t + b_y)")
print(f"\n The same W, U and V are used at every step. That is what the")
print(f" word 'recurrent' means, and it is why the parameter count does")
print(f" not grow with the sentence.\n")
seq = ["the", "dog", "ran"]
h = np.zeros(2)
print(f" h_0 = {h} the state before any word is read\n")
def vec(a):
return "(" + ", ".join(f"{v:+.4f}" for v in a) + ")"
print(f" {'t':>2}{'word':>6}{'x_t':>21}{'W x + U h + b':>21}{'h_t':>21}")
print(" " + "-" * 71)
for t, w in enumerate(seq, start=1):
x = E[WORDS.index(w)]
pre = W @ x + U @ h + bh
h = np.tanh(pre)
print(f" {t:>2}{w:>6}{vec(x):>21}{vec(pre):>21}{vec(h):>21}")
print(f"\n Every h_t carries the whole prefix, not a fixed window.")
print(f" h_3 was computed from h_2, which was computed from h_1.")
print(f"\n The output at each step is a distribution over the vocabulary:\n")
h = np.zeros(2)
print(f" {'t':>2}{'read':>6} " + "".join(f"{w:>9}" for w in WORDS)
+ f"{' most likely next':>20}")
print(" " + "-" * 62)
for t, w in enumerate(seq, start=1):
h = np.tanh(W @ E[WORDS.index(w)] + U @ h + bh)
p = softmax(V @ h + by)
print(f" {t:>2}{w:>6} " + "".join(f"{v:>9.4f}" for v in p)
+ f"{WORDS[int(p.argmax())]:>20}")
print("\n The weights are random here, so the predictions mean nothing.")
print(" The shape is the point. One distribution per time step, and a")
print(" language model needs exactly one distribution per time step.")
# ------------------------------------------------------------ the parameters
def show_params(V_size=10000, d=100, H=500):
print(f"\n\nSTEP 2 the parameter count stops depending on the sequence\n")
print(f" |V| = {V_size}, embedding d = {d}, hidden H = {H}\n")
print(f" {'matrix':<10}{'shape':<18}{'parameters':>14}")
print(" " + "-" * 44)
rows = [("E", f"{V_size} x {d}", V_size * d),
("W", f"{H} x {d}", H * d),
("U", f"{H} x {H}", H * H),
("V", f"{H} x {V_size}", H * V_size),
("b_h", f"{H}", H),
("b_y", f"{V_size}", V_size)]
total = sum(n for _, _, n in rows)
for name, shape, n in rows:
print(f" {name:<10}{shape:<18}{n:>14,}")
print(" " + "-" * 44)
print(f" {'total':<28}{total:>14,}")
print(f"\n Not one of those shapes mentions the sentence length.")
print(f" U is H x H whether the sentence has 5 words or 500.\n")
print(f" Compare the feed-forward model of Chapter 11, whose W_h is")
print(f" (context x d) x H and therefore grows with the window:\n")
print(f" {'context words':>15}{'feed-forward W_h':>20}{'RNN U':>12}")
print(" " + "-" * 48)
for ctx in (3, 5, 10, 50, 500):
print(f" {ctx:>15}{ctx * d * H:>20,}{H * H:>12,}")
print(f"\n The left column grows without limit. The right column is a")
print(f" constant. That single fact is why the recurrence was worth")
print(f" inventing, and it is what lets an RNN read a whole paragraph.")
# ------------------------------------------------- backpropagation through time
def forward(Wm, Um, Vm, bhm, bym, inputs, targets):
"""Run the recurrence and return every state, every distribution, the loss."""
h = np.zeros(2)
states, dists, loss = [h], [], 0.0
for word, target in zip(inputs, targets):
h = np.tanh(Wm @ E[WORDS.index(word)] + Um @ h + bhm)
y_hat = softmax(Vm @ h + bym)
states.append(h)
dists.append(y_hat)
loss += -math.log(y_hat[WORDS.index(target)])
return states, dists, loss
def show_bptt(eta=0.1):
print("\n\nSTEP 3 backpropagation through time, by numbers\n")
print(" The sentence is 'the dog ran the', read three words at a time:")
print(" the model sees the, dog, ran and must predict dog, ran, the.\n")
inputs, targets = ["the", "dog", "ran"], ["dog", "ran", "the"]
T = len(inputs)
def vec(a):
return "(" + ", ".join(f"{v:+.4f}" for v in a) + ")"
h, y_hat, loss = forward(W, U, V, bh, by, inputs, targets)
onehot = [np.eye(3)[WORDS.index(t)] for t in targets]
print(" The forward pass. Loss at step t is -log of the probability given")
print(" to the word that actually came next.\n")
print(f" {'t':>2}{'read':>6}{'target':>8}{'h_t':>21}{'y_hat_t (the, dog, ran)':>34}{'E_t':>9}")
print(" " + "-" * 80)
for t in range(1, T + 1):
e_t = -math.log(y_hat[t - 1][WORDS.index(targets[t - 1])])
print(f" {t:>2}{inputs[t - 1]:>6}{targets[t - 1]:>8}{vec(h[t]):>21}"
f"{vec(y_hat[t - 1]):>34}{e_t:>9.4f}")
print(f"\n L = E_1 + E_2 + E_3 = {loss:.4f}")
# The error at the scores, for every step: y_hat - y.
d_out = [y_hat[k] - onehot[k] for k in range(T)]
print("\n\n Error at the scores, y_hat - y (softmax with cross-entropy)\n")
print(f" {'t':>2}{'y_hat - y':>34}")
print(" " + "-" * 36)
for t in range(1, T + 1):
print(f" {t:>2}{vec(d_out[t - 1]):>34}")
# The backward sweep. delta[k] is the error at the pre-activation of step k.
delta = {T + 1: np.zeros(2)}
print("\n\n The backward sweep, last step first. At each step two errors")
print(" arrive at h_k: one from its own output and one handed back by step")
print(" k+1 through U^T. Their sum is multiplied by 1 - h_k^2.\n")
print(f" {'k':>2}{'V^T (y_hat-y)':>21}{'U^T delta_k+1':>21}{'sum':>21}"
f"{'1 - h_k^2':>19}{'delta_k':>21}")
print(" " + "-" * 105)
for k in range(T, 0, -1):
own = V.T @ d_out[k - 1]
back = U.T @ delta[k + 1]
delta[k] = (own + back) * (1 - h[k] ** 2)
print(f" {k:>2}{vec(own):>21}{vec(back):>21}{vec(own + back):>21}"
f"{vec(1 - h[k] ** 2):>19}{vec(delta[k]):>21}")
print("\n Step 3 has nothing after it, so its second column is zero. Look at")
print(" step 2: its own output contributes almost nothing, yet delta_2 is")
print(" large, because step 3 sent blame back through U.")
xs = [E[WORDS.index(w)] for w in inputs]
gV = sum(np.outer(d_out[t - 1], h[t]) for t in range(1, T + 1))
gU = sum(np.outer(delta[t], h[t - 1]) for t in range(1, T + 1))
gW = sum(np.outer(delta[t], xs[t - 1]) for t in range(1, T + 1))
gbh = sum(delta[t] for t in range(1, T + 1))
gby = sum(d_out)
def show_matrix(name, g):
for i, row in enumerate(g):
lead = f" dL/d{name} = " if i == 0 else " " * (len(name) + 9)
print(lead + "(" + ", ".join(f"{v:+.4f}" for v in row) + ")")
print("\n\n The gradients, each a sum over the three steps\n")
show_matrix("V", gV)
print()
show_matrix("U", gU)
print()
show_matrix("W", gW)
print(f"\n dL/db_h = {vec(gbh)}")
print(f" dL/db_y = {vec(gby)}")
# The check that matters: nudge each parameter and watch the loss.
print("\n\n Check against a numerical gradient. Nudge one parameter by")
print(" 0.000001 each way, rerun the forward pass, and divide the change in")
print(" the loss by the nudge.\n")
params = {"V": (V.copy(), gV), "U": (U.copy(), gU), "W": (W.copy(), gW),
"b_h": (bh.copy(), gbh), "b_y": (by.copy(), gby)}
print(f" {'parameter':<11}{'largest |backprop - numerical|':>34}")
print(" " + "-" * 46)
for name, (arr, analytic) in params.items():
worst = 0.0
for i in np.ndindex(arr.shape):
trial = {k: v[0].copy() for k, v in params.items()}
trial[name][i] += 1e-6
up = forward(trial["W"], trial["U"], trial["V"], trial["b_h"], trial["b_y"],
inputs, targets)[2]
trial[name][i] -= 2e-6
down = forward(trial["W"], trial["U"], trial["V"], trial["b_h"], trial["b_y"],
inputs, targets)[2]
worst = max(worst, abs((up - down) / 2e-6 - analytic[i]))
print(f" {name:<11}{worst:>34.1e}")
print("\n Every entry agrees to nine decimal places or so, which is what")
print(" rounding error in the numerical version allows. The derivation holds.")
# One gradient descent step, and the loss it buys.
new = forward(W - eta * gW, U - eta * gU, V - eta * gV, bh - eta * gbh,
by - eta * gby, inputs, targets)[2]
print(f"\n\n One step of gradient descent, learning rate {eta}:\n")
print(f" loss before {loss:.4f}")
print(f" loss after {new:.4f}")
print("\n The same three matrices were reused at every step, so each is")
print(" updated once, by the sum of its three contributions.")
# ------------------------------------------------------- vanishing gradients
def show_vanish():
print("\n\nSTEP 4 why the memory fades\n")
print(" Backpropagation through time multiplies one Jacobian per step:\n")
print(" dE/dh_0 = dE/dh_tau * product over t of dh_t / dh_{t-1}\n")
print(" Each factor is diag(tanh'(...)) U. So the whole product behaves")
print(" like a number raised to the power of the distance.\n")
print(f" {'distance':>9}" + "".join(f"{f'x {g}':>13}" for g in
(0.5, 0.9, 1.0, 1.1, 1.2)))
print(" " + "-" * 74)
for tau in (1, 5, 10, 20, 47, 100):
cells = "".join(f"{g ** tau:>13.3e}" for g in (0.5, 0.9, 1.0, 1.1, 1.2))
print(f" {tau:>9}{cells}")
print(f"\n Read the columns. Below 1 the gradient dies. Above 1 it")
print(f" explodes. Exactly at 1 it survives, and nothing keeps it there.")
print(f"\n The threshold is the largest eigenvalue of U. If every")
print(f" eigenvalue satisfies |lambda| < 1 the gradients vanish, and if")
print(f" any satisfies |lambda| > 1 they explode.")
print(f"\n\n THE 47 WORD EXAMPLE\n")
print(" 'Raj entered CoffeeDay to meet his partner Dru. ... After a long")
print(" and fruitful discussion, Raj said goodbye to his ______'")
print("\n The answer is 'partner'. The passage is 44 words, so the")
print(" gap is 37 words, or 46 once punctuation counts as a token,")
print(" which is what the model steps over. Call it 47 steps.")
print(" What reaches it:\n")
for g in (0.01, 0.5, 1.2):
v = g ** 47
verdict = ("gone entirely" if v < 1e-12
else "exploded" if v > 1 else "too small to matter")
print(f" {g} ^ 47 = {v:.6e} {verdict}")
print("\n A gradient of 1e-94 is not a small update. It is no update.")
print(" The network cannot learn the dependency, however true it is.")
print("\n Note what is not broken. The forward pass carries information")
print(" fine. It is the backward pass that cannot deliver the blame,")
print(" so the weights that would capture the link never move.")
# ---------------------------------------------------------- gradient clipping
def show_clip(threshold=5.0):
print(f"\n\nSTEP 5 gradient clipping (threshold = {threshold})\n")
print(" Vanishing needs a new architecture. Exploding has a cheap fix.")
print(" If the gradient is longer than the threshold, rescale it to the")
print(" threshold and keep its direction:\n")
print(" if ||g|| > threshold: g <- (threshold / ||g||) g\n")
rng = np.random.default_rng(0)
print(f" {'step':>5}{'||g|| before':>15}{'||g|| after':>14}"
f"{'direction kept':>17}")
print(" " + "-" * 52)
for step, scale in enumerate([0.4, 1.2, 3.0, 40.0, 900.0], start=1):
g = rng.normal(0, 1, 6) * scale
n = np.linalg.norm(g)
g2 = g * (threshold / n) if n > threshold else g
cos = float(g @ g2 / (np.linalg.norm(g) * np.linalg.norm(g2)))
print(f" {step:>5}{n:>15.4f}{np.linalg.norm(g2):>14.4f}"
f"{cos:>17.4f}")
print("\n The last column is 1.0000 every time. Clipping changes how far")
print(" the step goes and never which way it points.")
print("\n That is the whole trick, and it is why one line of code stops")
print(" a training run from diverging. It does nothing at all for the")
print(" vanishing case, where the gradient is already too small.")
def main():
ap = argparse.ArgumentParser(description=__doc__)
for f in ("unroll", "params", "bptt", "vanish", "clip"):
ap.add_argument(f"--{f}", action="store_true")
a = ap.parse_args()
picked = a.unroll or a.params or a.bptt or a.vanish or a.clip
if a.unroll or not picked:
show_unroll()
if a.params or not picked:
show_params()
if a.bptt or not picked:
show_bptt()
if a.vanish or not picked:
show_vanish()
if a.clip or not picked:
show_clip()
print()
if __name__ == "__main__":
main()