Four sentence pairs, and a translation table that arrives without anyone labelling a single word. Then the neural turn, worked in full: the objective, an encoder and decoder, what one vector forgets, backpropagation checked against finite differences, both directions and two layers, global and local attention, the three phases of translating, a counted system, and zero-shot directions.
python3 ibm_model1.py
The corpus, the steps and what was learned.
python3 ibm_model1.py --step
One EM iteration in full, from uniform probabilities to updated counts.
python3 ibm_model1.py --learned
The table after convergence, and the alignments it implies.
python3 ibm_model1.py --neural
An encoder and a decoder on 'the dog ran', the first decoder step one stage at a time. Attention weights of 0.4996, 0.2818 and 0.2186 pull the context towards the first word, two scoring rules give two alignments, and the sum of log probabilities prefers a 3 token hypothesis that the per token average rejects.
python3 ibm_model1.py --bottleneck
Two sources that differ only in their first word. The distance between the last encoder states falls from 0.769006 to 0.000030 by twelve words, while the first state keeps all of it.
python3 ibm_model1.py --bptt
The backward pass through the decoder, step by step, and all thirty gradients compared with finite differences. The largest gap is 4.4e-10.
python3 ibm_model1.py --local
Global attention against a window around a predicted position of 1.9518, where a Gaussian cuts the first word's weight from 0.6394 to 0.1045.
python3 ibm_model1.py --infer
The three phases of translating a new sentence. Chosen weights give an empty output, then a repetition that runs to the length limit.
python3 ibm_model1.py --multi
Directions trained against directions served. At a hundred languages with English at the centre, 9,702 of 9,900 directions are zero-shot.
"""IBM Model 1, worked as Chapter 14 works it.
The translation model that learns word alignment from nothing but sentence
pairs. No dictionary, no alignment annotation, four sentences.
the corpus four English and Swahili pairs, from the lectures
one EM iteration every posterior and every count, by hand
convergence the table at iterations 1, 5 and 10
what it learned the alignments nobody supplied, and the one tie it
refuses to break
one more sentence what that tie needed, and what it also fixed
the neural turn an encoder and a decoder, attention as a soft alignment,
and why beam search needs a length correction
the bottleneck what one fixed vector forgets, as the source grows
the objective log p(E | F) for two pairs, and J(theta)
training backpropagation through the decoder, checked numerically
encoders both directions, and two layers
local attention a window around a predicted position
translating the three phases, and an alignment table
a typical system its parameters counted
many languages directions trained against directions served
python3 ibm_model1.py # all fourteen
python3 ibm_model1.py --step # one iteration in full detail
python3 ibm_model1.py --learned # the table, and the honest tie
python3 ibm_model1.py --extra # add a fifth pair, watch it resolve
python3 ibm_model1.py --neural # encoder, decoder, attention, beam length
python3 ibm_model1.py --bottleneck # --objective --bptt --encoders
python3 ibm_model1.py --local # --infer --setup --multi
python3 ibm_model1.py --iters 50 # the tie is still there at 50
python3 ibm_model1.py --pair "my dog" "mbwa wangu"
Install: nothing, the Python standard library is enough
"""
import argparse
import math
from collections import defaultdict
# The lecture corpus. English on the left, Swahili on the right. Nobody has
# said which word translates which; that is exactly what has to be learned.
PAIRS = [
(["my", "dog"], ["mbwa", "wangu"]),
(["my", "house"], ["nyumba", "yangu"]),
(["my", "cycle"], ["mzunguko", "wangu"]),
(["his", "dog"], ["mbwa", "wake"]),
]
# One more pair, held back on purpose. Section 4 shows what it fixes.
EXTRA = (["his", "house"], ["nyumba", "wake"])
EN = ["my", "house", "cycle", "his", "dog"]
SW = ["mbwa", "wangu", "nyumba", "yangu", "mzunguko", "wake"]
def init_table():
"""Uniform. Every Swahili word is equally likely for every English word."""
return {e: {f: 1.0 / len(SW) for f in SW} for e in EN}
def em_step(t):
"""One expectation-maximisation pass over the whole corpus.
E-step: for each Swahili word in a pair, split one unit of count across
the English words in that pair, in proportion to the current t(f|e).
That split is the posterior over alignments, and Model 1 makes it this
simple because it assumes all alignments are a priori equally likely.
M-step: renormalise the collected counts into probabilities.
"""
count = defaultdict(float) # count[(e, f)]
total = defaultdict(float) # total[e]
detail = []
for en, sw in PAIRS:
for f in sw:
z = sum(t[e][f] for e in en) # the normaliser
for e in en:
delta = t[e][f] / z
count[(e, f)] += delta
total[e] += delta
detail.append((en, sw, f, e, t[e][f], z, delta))
new = {e: {f: 0.0 for f in SW} for e in EN}
for (e, f), c in count.items():
new[e][f] = c / total[e]
return new, detail, count, total
def table(t, title, top=None):
print(f"\n {title}\n")
print(" " + " " * 9 + "".join(f"{f[:8]:>10}" for f in SW))
print(" " + "-" * (9 + 10 * len(SW)))
for e in EN:
row = "".join(f"{t[e][f]:>10.4f}" for f in SW)
best = max(SW, key=lambda f: t[e][f])
mark = f" -> {best}" if top else ""
print(f" {e:<9}{row}{mark}")
# ------------------------------------------------------------------ the corpus
def show_corpus():
print("\nSTEP 1 four sentence pairs, and nothing else\n")
for i, (en, sw) in enumerate(PAIRS, start=1):
print(f" {i}. {' '.join(en):<12} {' '.join(sw)}")
print(f"\n English vocabulary: {EN}")
print(f" Swahili vocabulary: {SW}")
print("\n Nobody has said which word translates which. There is no")
print(" dictionary and no alignment annotation. The only signal is that")
print(" these sentences mean the same thing.")
print("\n Two things make it solvable. 'my' appears in three pairs and")
print(" 'dog' in two, so the words that travel with them are visible.")
print(" And 'wangu' appears with 'my' twice, which is the wedge.")
print("\n One wrinkle worth noticing. Swahili marks possession by noun")
print(" class, so 'my' is 'wangu' with dog and cycle but 'yangu' with")
print(" house. A model that assumed one translation per word would be")
print(" wrong, and Model 1 does not assume that.")
# --------------------------------------------------------------- one iteration
def show_step():
t = init_table()
print("\n\nSTEP 2 one iteration, every number\n")
print(f" Start uniform: every t(f|e) = 1/{len(SW)} ="
f" {1/len(SW):.4f}\n")
print(" E-STEP. For each Swahili word, split one unit of count over the")
print(" English words in its pair, in proportion to t(f|e).\n")
new, detail, count, total = em_step(t)
seen = set()
print(f" {'pair':<24}{'f':<11}{'e':<8}{'t(f|e)':>9}{'sum':>9}"
f"{'delta':>9}")
print(" " + "-" * 72)
for en, sw, f, e, tv, z, d in detail:
key = " ".join(en)
label = f"{' '.join(en)} / {' '.join(sw)}" if key not in seen else ""
seen.add(key)
print(f" {label:<24}{f:<11}{e:<8}{tv:>9.4f}{z:>9.4f}{d:>9.4f}")
print("\n Every delta is 0.5000, because the table is still uniform and")
print(" each pair has two English words. The first iteration cannot")
print(" prefer anything. What it can do is count.\n")
print(" M-STEP. Collect the counts and renormalise.\n")
print(f" {'e':<9}{'f':<11}{'count(e,f)':>12}{'total(e)':>11}"
f"{'t(f|e)':>10}")
print(" " + "-" * 55)
for (e, f), c in sorted(count.items()):
print(f" {e:<9}{f:<11}{c:>12.4f}{total[e]:>11.4f}"
f"{c/total[e]:>10.4f}")
print("\n Read the rows for 'my'. It occurred in three pairs, so it")
print(" collected 3.0 units of count spread over six Swahili words.")
print(" 'wangu' got 1.0 of that and every other word got 0.5.")
print("\n That asymmetry is the entire seed. 'wangu' appeared alongside")
print(" 'my' twice and everything else once, and one pass of counting")
print(" is enough to notice.")
# ---------------------------------------------------------------- convergence
def show_convergence(iters=10, checkpoints=(1, 5, 10)):
print(f"\n\nSTEP 3 what repetition does\n")
t = init_table()
for i in range(1, iters + 1):
t, _, _, _ = em_step(t)
if i in checkpoints:
table(t, f"after iteration {i}")
print("\n Follow one cell across the three tables. t(mbwa | dog) goes")
for i, tt in enumerate([init_table()], start=0):
pass
t2 = init_table()
row = []
for i in range(1, iters + 1):
t2, _, _, _ = em_step(t2)
if i in (1, 5, 10):
row.append((i, t2["dog"]["mbwa"], t2["my"]["wangu"],
t2["house"]["yangu"]))
print(f"\n {'iteration':>10}{'t(mbwa|dog)':>14}{'t(wangu|my)':>14}"
f"{'t(yangu|house)':>16}")
print(" " + "-" * 56)
print(f" {'0 uniform':>10}{1/len(SW):>14.4f}{1/len(SW):>14.4f}"
f"{1/len(SW):>16.4f}")
for i, a, b, c in row:
print(f" {i:>10}{a:>14.4f}{b:>14.4f}{c:>16.4f}")
print("\n Nothing pushed those numbers except counting and")
print(" renormalising, repeated. That is all EM is here.")
# ------------------------------------------------------------- what it learned
def show_learned(iters=10):
t = init_table()
for _ in range(iters):
t, _, _, _ = em_step(t)
print(f"\n\nSTEP 4 the alignment nobody supplied (after {iters}"
f" iterations)\n")
print(f" {'English':<10}{'best Swahili':<12}{'p':>9}"
f"{'runner up':>12}{'p':>9}")
print(" " + "-" * 54)
for e in EN:
ranked = sorted(SW, key=lambda f: -t[e][f])
print(f" {e:<10}{ranked[0]:<12}{t[e][ranked[0]]:>9.4f}"
f"{ranked[1]:>12}{t[e][ranked[1]]:>9.4f}")
print("\n Four of the five are settled. 'dog' went to 'mbwa' at"
f" {t['dog']['mbwa']:.4f},")
print(f" 'cycle' to 'mzunguko' at {t['cycle']['mzunguko']:.4f}, 'his' to"
f" 'wake' at {t['his']['wake']:.4f},")
print(f" and 'my' to 'wangu' at {t['my']['wangu']:.4f}. Nobody supplied"
" any of that.")
print("\n\n NOW LOOK AT 'house'.\n")
print(f" t(nyumba | house) = {t['house']['nyumba']:.4f}")
print(f" t(yangu | house) = {t['house']['yangu']:.4f}")
t50 = init_table()
for _ in range(50):
t50, _, _, _ = em_step(t50)
print(f"\n Exactly tied, and it stays tied. After 50 iterations it is"
f" still")
print(f" {t50['house']['nyumba']:.4f} and {t50['house']['yangu']:.4f}.")
print("\n This is not a failure of EM. It is EM being honest.")
print("\n 'house' occurs in exactly one sentence pair, beside 'nyumba'")
print(" and 'yangu'. Nothing anywhere else in the corpus distinguishes")
print(" those two words. 'my' correctly pushes both of them down, and")
print(f" pushes them down equally: {t50['my']['nyumba']:.4f} each.")
print("\n So 'house' inherits both, in equal measure. The data contains")
print(" a tie, and the model reports a tie rather than inventing a")
print(" preference. A model that broke it would be making something up.")
def show_extra(iters=10):
"""Add one sentence pair and watch the tie resolve."""
global PAIRS
base = list(PAIRS)
t = init_table()
for _ in range(iters):
t, _, _, _ = em_step(t)
before = dict(t["house"])
PAIRS = base + [EXTRA]
t2 = init_table()
for _ in range(iters):
t2, _, _, _ = em_step(t2)
PAIRS = base
print("\n\nSTEP 5 one more sentence, and the tie breaks\n")
print(f" Add a fifth pair: {' '.join(EXTRA[0]):<12}"
f"{' '.join(EXTRA[1])}")
print("\n 'house' now meets 'nyumba' twice and 'yangu' once. That is")
print(" the only new information, and it is enough.\n")
print(f" {'':<10}{'4 pairs':>12}{'5 pairs':>12}")
print(" " + "-" * 36)
for f in ("nyumba", "yangu"):
print(f" t({f[:6]}|house){before[f]:>10.4f}{t2['house'][f]:>12.4f}")
print(f"\n 'house' resolves to 'nyumba' at {t2['house']['nyumba']:.4f}.")
print("\n Something else moved too. Watch 'my':\n")
print(f" {'':<12}{'4 pairs':>12}{'5 pairs':>12}")
print(" " + "-" * 36)
for f in ("wangu", "yangu"):
print(f" t({f}|my){t['my'][f]:>12.4f}{t2['my'][f]:>12.4f}")
print(f"\n t(yangu|my) rose from {t['my']['yangu']:.4f} to"
f" {t2['my']['yangu']:.4f}, which is more correct.")
print(" 'yangu' really is Swahili for 'my', in the noun class that")
print(" 'house' belongs to. Freeing 'house' from the tie let the")
print(" evidence for that reach 'my'.")
print("\n One sentence pair. That is the argument for parallel corpus")
print(" size, and it is why statistical MT waited for the Canadian")
print(" Hansard and the European Parliament proceedings.")
# ------------------------------------------------------------ the neural turn
# The source sentence and the encoder are those of Chapter 12, so the three
# states below are the ones printed there. The decoder is the same kind of
# recurrence. Every weight is chosen, not trained, so the probabilities mean
# nothing. The shapes and the flow of the numbers are the point.
SRC = ["the", "dog", "ran"]
SRC_EMB = {"the": [0.50, -0.20], "dog": [0.10, 0.80], "ran": [-0.60, 0.30]}
ENC_W = [[0.60, -0.30], [0.20, 0.50]]
ENC_U = [[0.40, 0.10], [-0.20, 0.70]]
ENC_B = [0.05, -0.05]
TGT = ["le", "chien", "courut", "</s>"]
TGT_EMB = {"<s>": [0.00, 0.00], "le": [0.40, -0.10], "chien": [0.20, 0.70],
"courut": [-0.50, 0.40], "</s>": [0.10, 0.10]}
DEC_W = [[0.50, -0.20], [0.30, 0.40]] # previous target word
DEC_U = [[0.30, 0.20], [-0.10, 0.60]] # previous decoder state
DEC_V = [[0.40, 0.10], [0.20, -0.30]] # context vector
DEC_B = [0.00, 0.00]
OUT = [[2.70, -0.90, 1.20, 0.60], # one row per target word,
[-1.20, 2.40, 0.30, -0.60], # reading [s_t ; c_t]
[0.90, 1.50, -1.80, 1.20],
[-0.60, -0.30, 0.90, 2.10]]
# The decoder state used to show attention on its own: it points towards the
# first source word, as a trained decoder asking for a subject might.
QUERY = [0.90, -0.80]
# Additive attention (Bahdanau): e = v . tanh(W_s s + W_h h)
ADD_WS = [[0.50, -0.40], [0.20, 0.60]]
ADD_WH = [[0.30, 0.50], [-0.60, 0.20]]
ADD_V = [0.70, -0.50]
def _mv(M, v):
return [sum(a * b for a, b in zip(r, v)) for r in M]
def _add(*vs):
return [sum(x) for x in zip(*vs)]
def _softmax(z):
m = max(z)
e = [math.exp(x - m) for x in z]
return [x / sum(e) for x in e]
def _vec(a):
return "(" + ", ".join(f"{v:+.4f}" for v in a) + ")"
def encode(src=None):
"""The Chapter 12 recurrence over the source: one state per word."""
h, out = [0.0, 0.0], []
for w in (src or SRC):
h = [math.tanh(x) for x in _add(_mv(ENC_W, SRC_EMB[w]), _mv(ENC_U, h), ENC_B)]
out.append(h)
return out
def attend(s, H, kind="dot"):
"""Scores, weights and the context vector for one decoder state s."""
if kind == "dot":
e = [sum(a * b for a, b in zip(s, h)) for h in H]
else:
e = [sum(v * math.tanh(a + b) for v, a, b in
zip(ADD_V, _mv(ADD_WS, s), _mv(ADD_WH, h))) for h in H]
alpha = _softmax(e)
c = [sum(alpha[j] * H[j][k] for j in range(len(H))) for k in range(2)]
return e, alpha, c
def decode_step(prev, s_prev, c):
s = [math.tanh(x) for x in _add(_mv(DEC_W, TGT_EMB[prev]), _mv(DEC_U, s_prev),
_mv(DEC_V, c), DEC_B)]
p = _softmax(_mv(OUT, s + c))
return s, p
def teacher_forced(H, attention, gold=None):
"""Run the decoder over the gold target, feeding it the gold words."""
gold = gold or ["le", "chien", "courut", "</s>"]
s, prev, rows = H[-1], "<s>", []
for g in gold:
e, a, c = attend(s, H) if attention else (None, None, H[-1])
s, p = decode_step(prev, s, c)
rows.append((g, p[TGT.index(g)], p, a))
prev = g
return rows
def show_neural():
H = encode()
print("\n\nSTEP 6 the neural turn: an encoder, a decoder, and attention\n")
print(" The encoder is Chapter 12's recurrence over the source 'the dog ran'.")
print(" The weights are chosen, not trained, so nothing here is a translation.\n")
print(f" {'j':>2}{'source':>8}{'h_j':>21}")
print(" " + "-" * 31)
for j, (w, h) in enumerate(zip(SRC, H), start=1):
print(f" {j:>2}{w:>8}{_vec(h):>21}")
show_decoder_step()
print("\n\n WITHOUT ATTENTION. The whole source is the last state h_3, and the")
print(" decoder starts from it and is handed it at every step.\n")
print(" WITH ATTENTION. At every step the decoder state s asks each source")
print(" state how relevant it is. Suppose the decoder, about to write the")
print(f" first target word, is in the state s = {_vec(QUERY)}:\n")
s0 = QUERY
e, a, c = attend(s0, H)
print(f" {'source':>8}{'h_j':>21}{'score s.h_j':>14}{'weight':>10}")
print(" " + "-" * 55)
for w, h, ej, aj in zip(SRC, H, e, a):
print(f" {w:>8}{_vec(h):>21}{ej:>14.4f}{aj:>10.4f}")
print(f"\n weights add to {sum(a):.4f}")
print(f" context c = sum of weight * h_j = {_vec(c)}")
print(f" Without attention the context is h_3 = {_vec(H[-1])}.")
print(" The weights are a soft alignment, computed fresh at every step.")
print("\n\n TWO WAYS TO SCORE\n")
print(" Dot product (Luong): e_j = s . h_j")
print(" Additive (Bahdanau): e_j = v . tanh(W_s s + W_h h_j)\n")
print(f" {'source':>8}{'dot score':>12}{'dot weight':>12}{'add score':>12}{'add weight':>12}")
print(" " + "-" * 56)
ed, ad, _ = attend(s0, H, "dot")
ea, aa, _ = attend(s0, H, "add")
for w, x1, x2, x3, x4 in zip(SRC, ed, ad, ea, aa):
print(f" {w:>8}{x1:>12.4f}{x2:>12.4f}{x3:>12.4f}{x4:>12.4f}")
print("\n Same state, same encoder, two different alignments. Neither is")
print(" right until the weights are trained.")
print("\n\n ONE DECODER STEP, THEN THE WHOLE SENTENCE\n")
print(" Teacher forcing: the decoder is fed the gold previous word, and the")
print(" loss at each step is -log of the probability of the gold word.\n")
plain = teacher_forced(H, attention=False)
att = teacher_forced(H, attention=True)
print(f" {'step':>5}{'gold':>9}{'p(gold), no attention':>24}{'p(gold), attention':>22}")
print(" " + "-" * 60)
for t, ((g, p1, _, _), (_, p2, _, _)) in enumerate(zip(plain, att), start=1):
print(f" {t:>5}{g:>9}{p1:>24.4f}{p2:>22.4f}")
l1 = -sum(math.log(p) for _, p, _, _ in plain)
l2 = -sum(math.log(p) for _, p, _, _ in att)
print(" " + "-" * 60)
print(f" {'loss':>14}{l1:>24.4f}{l2:>22.4f}")
g, p1, dist, _ = att[0]
print("\n The first step with attention, the whole distribution:\n")
print(" " + " ".join(f"{w} {q:.4f}" for w, q in zip(TGT, dist)))
print("\n The loss is the sum of -log p(gold) over the four steps. The two")
print(" columns differ only because the context differs, and since nothing")
print(" is trained, they do not show attention helping.")
print("\n\n BEAM SEARCH AND LENGTH\n")
print(" A hypothesis's score is the sum of its token log probabilities. Every")
print(" extra token adds a negative number, so a long hypothesis is punished")
print(" for being long. Two candidates for the same source:\n")
hyps = [("le chien </s>", [-0.7, -0.9, -0.2]),
("le chien courut vite </s>", [-0.7, -0.5, -0.4, -0.6, -0.3])]
print(f" {'hypothesis':<28}{'tokens':>7}{'sum log p':>11}{'per token':>11}")
print(" " + "-" * 57)
for h, lp in hyps:
print(f" {h:<28}{len(lp):>7}{sum(lp):>11.4f}{sum(lp) / len(lp):>11.4f}")
best_raw = max(hyps, key=lambda x: sum(x[1]))[0]
best_norm = max(hyps, key=lambda x: sum(x[1]) / len(x[1]))[0]
print(f"\n Highest sum: {best_raw}")
print(f" Highest per token: {best_norm}")
print("\n The sum prefers the short hypothesis and the average prefers the long")
print(" one, which is why NMT systems divide by length, or by a power of it,")
print(" before they choose.")
# ------------------------------------------------ the neural turn, in depth
#
# Everything below reuses the encoder and decoder above. The same chosen
# weights, so the same numbers, and still nothing here is trained.
def _norm(v):
return math.sqrt(sum(x * x for x in v))
def _sigmoid(x):
return 1.0 / (1.0 + math.exp(-x))
def show_decoder_step():
"""The first decoder step with c = h_3, one stage at a time."""
H = encode()
c = H[-1]
s0 = H[-1]
prev = TGT_EMB["<s>"]
a_w, a_u, a_v = _mv(DEC_W, prev), _mv(DEC_U, s0), _mv(DEC_V, c)
pre = _add(a_w, a_u, a_v, DEC_B)
s1 = [math.tanh(x) for x in pre]
z = _mv(OUT, s1 + c)
p = _softmax(z)
print("\n\n ONE DECODER STEP, A STAGE AT A TIME (context c = h_3)\n")
print(f" previous word <s> y_0 = {_vec(prev)}")
print(f" previous state s_0 = h_3 = {_vec(s0)}\n")
print(f" W_d y_0 {_vec(a_w)}")
print(f" U_d s_0 {_vec(a_u)}")
print(f" V_d c {_vec(a_v)}")
print(f" sum plus bias {_vec(pre)}")
print(f" s_1 = tanh of that {_vec(s1)}\n")
print(f" W_o [s_1 ; c] " + " ".join(f"{w} {x:+.4f}" for w, x in zip(TGT, z)))
print(f" softmax " + " ".join(f"{w} {x:.4f}" for w, x in zip(TGT, p)))
print(f"\n the gold word is 'le', so this step's loss is -log {p[0]:.4f} = {-math.log(p[0]):.4f}")
# ------------------------------------------------------------- the bottleneck
def show_bottleneck():
print("\n\nSTEP 7 the bottleneck: what one fixed vector forgets\n")
print(" Two sources that differ only in their FIRST word, 'the' against 'ran',")
print(" followed by T-1 copies of 'dog'. How far apart are the encoders' states?\n")
print(f" {'T':>3}{'distance of last states':>26}{'distance of first states':>27}")
print(" " + "-" * 56)
for T in (1, 2, 3, 5, 8, 12):
A = encode(["the"] + ["dog"] * (T - 1))
B = encode(["ran"] + ["dog"] * (T - 1))
last = _norm([x - y for x, y in zip(A[-1], B[-1])])
first = _norm([x - y for x, y in zip(A[0], B[0])])
print(f" {T:>3}{last:>26.6f}{first:>27.6f}")
print("\n Without attention the decoder sees only the last state, in which the")
print(" difference shrinks with every word that follows. With attention it can")
print(" still read the first state, where the difference is as large as ever.")
# --------------------------------------------------------------- the objective
PAIRS_NMT = [(["the", "dog", "ran"], ["le", "chien", "courut", "</s>"]),
(["dog", "ran"], ["chien", "courut", "</s>"])]
def show_objective():
print("\n\nSTEP 8 one model, one objective\n")
print(" log p(E | F) is the sum over target words of log p(y_t | y_<t, F).")
print(" Two training pairs, the decoder with attention, gold words fed in.\n")
logs = []
for src, gold in PAIRS_NMT:
rows = teacher_forced(encode(src), attention=True, gold=gold)
print(f" F = {' '.join(src)} E = {' '.join(gold)}")
print(f" {'step':>5}{'gold':>9}{'p(gold)':>10}{'log p':>10}")
for t, (g, p, _, _) in enumerate(rows, start=1):
print(f" {t:>5}{g:>9}{p:>10.4f}{math.log(p):>10.4f}")
total = sum(math.log(p) for _, p, _, _ in rows)
print(f" log p(E | F) = {total:.4f} p(E | F) = {math.exp(total):.6f}\n")
logs.append((total, len(gold)))
n = len(logs)
J = sum(t for t, _ in logs) / n
words = sum(k for _, k in logs)
print(f" J(theta) = (1/N) sum of log p(E | F) = {J:.4f} with N = {n}")
print(f" training minimises -J = {-J:.4f}")
print(f" the same loss per target word: {-sum(t for t, _ in logs) / words:.4f}"
f" ({words} words)")
# ------------------------------------------------------------------------ BPTT
def _plain_forward(Wd, Ud, Vd, Wo, h3, gold):
"""Decoder with c = h_3 held fixed. Returns the loss and what backward needs."""
s, prev = list(h3), "<s>"
steps = []
for g in gold:
y = TGT_EMB[prev]
a = _add(_mv(Wd, y), _mv(Ud, s), _mv(Vd, h3), DEC_B)
s_new = [math.tanh(x) for x in a]
p = _softmax(_mv(Wo, s_new + list(h3)))
steps.append({"g": g, "y": y, "s_prev": s, "s": s_new, "p": p})
s, prev = s_new, g
loss = -sum(math.log(st["p"][TGT.index(st["g"])]) for st in steps)
return loss, steps
def _outer(a, b):
return [[x * y for y in b] for x in a]
def _matT_v(M, v):
return [sum(M[i][j] * v[i] for i in range(len(M))) for j in range(len(M[0]))]
def show_bptt():
print("\n\nSTEP 9 training: backpropagation through time on the decoder\n")
print(" The decoder without attention, c = h_3 fixed, the gold target, and the")
print(" loss of the earlier table. The output matrix plays the part of V in the")
print(" recurrent chapter, W_d and U_d the parts of W and U.\n")
H = encode()
h3 = H[-1]
gold = ["le", "chien", "courut", "</s>"]
loss, st = _plain_forward(DEC_W, DEC_U, DEC_V, OUT, h3, gold)
print(f" forward pass: loss = {loss:.4f}\n")
dWo = [[0.0] * 4 for _ in range(4)]
dWd = [[0.0] * 2 for _ in range(2)]
dUd = [[0.0] * 2 for _ in range(2)]
dVd = [[0.0] * 2 for _ in range(2)]
dc = [0.0, 0.0]
carry = [0.0, 0.0]
rows = []
for t in range(len(gold) - 1, -1, -1):
k = st[t]
d = list(k["p"])
d[TGT.index(k["g"])] -= 1.0 # p minus the one-hot gold
ds_direct = _matT_v([r[:2] for r in OUT], d) # through W_o, state half
ds = [x + y for x, y in zip(ds_direct, carry)]
da = [(1 - s * s) * g for s, g in zip(k["s"], ds)]
for i in range(4):
for j in range(4):
dWo[i][j] += d[i] * (k["s"] + list(h3))[j]
for i in range(2):
for j in range(2):
dWd[i][j] += da[i] * k["y"][j]
dUd[i][j] += da[i] * k["s_prev"][j]
dVd[i][j] += da[i] * h3[j]
dc = [x + y + z for x, y, z in zip(dc, _matT_v([r[2:] for r in OUT], d),
_matT_v(DEC_V, da))]
carry = _matT_v(DEC_U, da)
rows.append((t + 1, k["g"], ds_direct, [c for c in carry], ds, da))
rows.reverse()
print(" backward pass, from the last word to the first. Each step adds what")
print(" the step after it sends back (the 'from later' column), which is how")
print(" one word's loss reaches every earlier state.\n")
print(f" {'t':>2}{'gold':>8}{'from the output':>20}{'from later':>20}{'dL/ds_t':>20}")
print(" " + "-" * 70)
for i, (t, g, dd, _, ds, da) in enumerate(rows):
later = [x - y for x, y in zip(ds, dd)]
print(f" {t:>2}{g:>8}{_vec(dd):>20}{_vec(later):>20}{_vec(ds):>20}")
print("\n the gradients, summed over the four steps:\n")
for name, M in (("dL/dW_d", dWd), ("dL/dU_d", dUd), ("dL/dV_d", dVd)):
print(f" {name} " + " ".join(_vec(r) for r in M))
print(f" dL/dW_o row for 'le' {_vec(dWo[0])}")
h3_grad = [a + b for a, b in zip(dc, carry)]
print(f"\n the gradient that reaches the encoder, dL/dh_3 = {_vec(h3_grad)}")
print(" (it enters twice, as the context at every step and as the first state)\n")
# finite differences over every entry of every matrix
eps, worst, count = 1e-6, 0.0, 0
for M, G, name in ((DEC_W, dWd, "W_d"), (DEC_U, dUd, "U_d"), (DEC_V, dVd, "V_d"),
(OUT, dWo, "W_o")):
for i in range(len(M)):
for j in range(len(M[0])):
M[i][j] += eps
up = _plain_forward(DEC_W, DEC_U, DEC_V, OUT, h3, gold)[0]
M[i][j] -= 2 * eps
dn = _plain_forward(DEC_W, DEC_U, DEC_V, OUT, h3, gold)[0]
M[i][j] += eps
worst = max(worst, abs((up - dn) / (2 * eps) - G[i][j]))
count += 1
for j in range(2):
h = list(h3)
h[j] += eps
up = _plain_forward(DEC_W, DEC_U, DEC_V, OUT, h, gold)[0]
h[j] -= 2 * eps
dn = _plain_forward(DEC_W, DEC_U, DEC_V, OUT, h, gold)[0]
worst = max(worst, abs((up - dn) / (2 * eps) - h3_grad[j]))
count += 1
print(f" check: {count} gradients compared with finite differences,")
print(f" the largest gap is {worst:.1e}")
# ----------------------------------------------------------- better encoders
BWD_W = [[0.40, 0.20], [-0.30, 0.60]]
BWD_U = [[0.50, -0.10], [0.20, 0.40]]
BWD_B = [0.00, 0.00]
L2_W = [[0.50, 0.20], [-0.40, 0.60]]
L2_U = [[0.30, 0.10], [0.00, 0.50]]
L2_B = [0.00, 0.00]
def _run(emb_seq, W, U, B):
h, out = [0.0, 0.0], []
for x in emb_seq:
h = [math.tanh(v) for v in _add(_mv(W, x), _mv(U, h), B)]
out.append(h)
return out
def _bidir(src):
emb = [SRC_EMB[w] for w in src]
fwd = _run(emb, ENC_W, ENC_U, ENC_B)
bwd = _run(emb[::-1], BWD_W, BWD_U, BWD_B)[::-1]
return fwd, bwd
def show_encoders():
print("\n\nSTEP 10 better encoders: both directions, and more layers\n")
fwd, bwd = _bidir(SRC)
print(" A second recurrence reads the source from the last word to the first.")
print(" Each word's annotation is the two states side by side.\n")
print(f" {'j':>2}{'source':>8}{'forward':>20}{'backward':>20}")
print(" " + "-" * 50)
for j, w in enumerate(SRC):
print(f" {j + 1:>2}{w:>8}{_vec(fwd[j]):>20}{_vec(bwd[j]):>20}")
print("\n Now change the LAST word, 'ran' to 'the', and see which states move.\n")
fwd2, bwd2 = _bidir(["the", "dog", "the"])
print(f" {'j':>2}{'source':>8}{'forward moved by':>20}{'backward moved by':>20}")
print(" " + "-" * 50)
for j, w in enumerate(SRC):
df = _norm([x - y for x, y in zip(fwd[j], fwd2[j])])
db = _norm([x - y for x, y in zip(bwd[j], bwd2[j])])
print(f" {j + 1:>2}{w:>8}{df:>20.4f}{db:>20.4f}")
print("\n A forward state cannot know what comes later. The backward state can.")
emb = [SRC_EMB[w] for w in SRC]
l1 = _run(emb, ENC_W, ENC_U, ENC_B)
l2 = _run(l1, L2_W, L2_U, L2_B)
print("\n A second layer reads the first layer's states instead of the words.\n")
print(f" {'j':>2}{'source':>8}{'layer 1':>20}{'layer 2':>20}")
print(" " + "-" * 50)
for j, w in enumerate(SRC):
print(f" {j + 1:>2}{w:>8}{_vec(l1[j]):>20}{_vec(l2[j]):>20}")
# ------------------------------------------------------------ local attention
LP_W = [[0.60, -0.40], [0.30, 0.50]]
LP_V = [0.80, -0.50]
def show_local():
H = encode()
S = len(H)
print("\n\nSTEP 11 global and local attention\n")
s = QUERY
e, a_glob, c_glob = attend(s, H)
print(f" Decoder state s = {_vec(s)}. Global attention scores all {S} positions:\n")
print(f" {'j':>2}{'source':>8}{'score':>10}{'weight':>10}")
for j, (w, ej, aj) in enumerate(zip(SRC, e, a_glob), start=1):
print(f" {j:>2}{w:>8}{ej:>10.4f}{aj:>10.4f}")
print(f" context = {_vec(c_glob)}")
z = sum(v * math.tanh(x) for v, x in zip(LP_V, _mv(LP_W, s)))
p = S * _sigmoid(z)
D = 1.0
sigma = D / 2
print(f"\n Local attention first predicts a position, p = S * sigmoid(v . tanh(W s))")
print(f" = {S} * sigmoid({z:+.4f}) = {p:.4f}, and looks only within D = {D:g} of it.\n")
win = [j for j in range(1, S + 1) if abs(j - p) <= D]
es = [e[j - 1] for j in win]
al = _softmax(es)
gauss = [math.exp(-((j - p) ** 2) / (2 * sigma ** 2)) for j in win]
fin = [x * g for x, g in zip(al, gauss)]
print(f" {'j':>2}{'source':>8}{'score':>10}{'softmax':>10}{'Gaussian':>10}{'weight':>10}")
for j, e_, x, g, f in zip(win, es, al, gauss, fin):
print(f" {j:>2}{SRC[j - 1]:>8}{e_:>10.4f}{x:>10.4f}{g:>10.4f}{f:>10.4f}")
cl = [sum(f * H[j - 1][k] for j, f in zip(win, fin)) for k in range(2)]
print(f" context = {_vec(cl)} (window of {len(win)}, weights add to {sum(fin):.4f})")
print("\n The Gaussian pulls the weight towards the predicted position p, and")
print(" the weights outside the window are zero, so they are never computed.")
print("\n What the window saves, per output word, for a source of S words:\n")
print(f" {'S':>5}{'global scores':>16}{'local scores, D=10':>22}")
for S_ in (10, 50, 200):
print(f" {S_:>5}{S_:>16}{min(S_, 21):>22}")
# --------------------------------------------------------------------- inference
def _greedy(H, max_len, min_len):
"""Greedy decoding with attention. The end marker is barred before min_len."""
s, prev, rows = H[-1], "<s>", []
for t in range(1, max_len + 1):
_, a, c = attend(s, H)
s, p = decode_step(prev, s, c)
ok = [i for i in range(len(TGT)) if not (TGT[i] == "</s>" and t < min_len)]
k = max(ok, key=lambda i: p[i])
rows.append((t, prev, a, TGT[k], p[k]))
prev = TGT[k]
if prev == "</s>":
break
return rows
def _show_run(rows, max_len):
print(f" {'t':>2}{'prev':>9} {'weights on the, dog, ran':<26}{'chosen':>9}{'p':>8}")
print(" " + "-" * 56)
for t, prev, a, w, p in rows:
print(f" {t:>2}{prev:>9} {' '.join(f'{x:.3f}' for x in a):<26}{w:>9}{p:>8.4f}")
out = [w for _, _, _, w, _ in rows]
print(f"\n output: {' '.join(out)}")
print(" stopped by: " + ("the end marker" if out[-1] == "</s>"
else f"the limit of {max_len} words"))
def show_infer(max_len=8):
print("\n\nSTEP 12 translating a new sentence, in three phases\n")
print(" PHASE 1. Encode the source and start the decoder from the last state.\n")
H = encode()
print(f" source states h_1..h_3 as before; s_0 = h_3 = {_vec(H[-1])}\n")
print(" PHASE 2. At each step: attend, update the state, take the likeliest word.")
print(" PHASE 3. Stop at the end marker, or at the length limit.\n")
_show_run(_greedy(H, max_len, 1), max_len)
print("\n These weights favour stopping, so the translation is empty. Systems")
print(" guard against that with a minimum length. Barring the end marker")
print(" before step 3:\n")
_show_run(_greedy(H, max_len, 3), max_len)
print("\n The weights are chosen, not trained, so neither is a translation.")
print("\n The attention weights of the TEACHER-FORCED run on the gold target,")
print(" one row per target word, form an alignment table:\n")
rows = teacher_forced(H, attention=True)
print(f" {'':>9}" + "".join(f"{w:>9}" for w in SRC) + f"{'largest':>10}")
for g, _, _, a in rows:
top = SRC[max(range(len(a)), key=lambda i: a[i])]
print(f" {g:>9}" + "".join(f"{x:>9.4f}" for x in a) + f"{top:>10}")
print("\n Each row adds to 1, as a row of Model 1's posterior table does. Untrained,")
print(" every row is close to even. Training is what makes the rows peak.")
# ---------------------------------------------------------------- typical setup
def show_setup():
print("\n\nSTEP 13 a typical system, counted\n")
V, d, h = 50_000, 1000, 1000
def lstm(inp, hid):
return 4 * (hid * (inp + hid) + hid)
print(f" vocabulary {V:,}, embeddings {d}, hidden size {h}, LSTM layers.\n")
print(f" one LSTM layer: 4 gates of ({h} x ({d} + {h}) + {h}) = {lstm(d, h):,}")
print(f" one embedding table: {V:,} x {d} = {V * d:,}")
print(f" the output layer: {h} x {V:,} + {V:,} = {h * V + V:,}\n")
print(f" {'layers each':>12}{'LSTM':>14}{'embeddings':>14}{'output':>14}{'total':>14}")
for L in (4, 8):
lay = 2 * L * lstm(h, h)
emb = 2 * V * d
out = h * V + V
print(f" {L:>12}{lay:>14,}{emb:>14,}{out:>14,}{lay + emb + out:>14,}")
print(f"\n per target word, the output layer costs {h * V:,} multiply-adds and")
print(f" one LSTM layer {lstm(h, h):,}: the softmax is {h * V / lstm(h, h):.1f} layers' worth.")
print("\n the corpus: 4M sentence pairs, 110M English words, 116M French words")
print(f" words per sentence: {110e6 / 4e6:.1f} English, {116e6 / 4e6:.1f} French")
print(f" updates per epoch at a mini-batch of 128: {4_000_000 // 128:,}")
# ----------------------------------------------------------------- many languages
def show_multi():
print("\n\nSTEP 14 many languages, one model\n")
print(" n languages, every direction wanted. Training data exists only")
print(" between English and each other language (the English-centred case).\n")
print(f" {'n':>5}{'separate models':>18}{'directions trained':>20}"
f"{'directions served':>19}{'zero-shot':>11}")
for n in (3, 10, 100):
sep = n * (n - 1)
trained = 2 * (n - 1)
print(f" {n:>5}{sep:>18,}{trained:>20,}{sep:>19,}{sep - trained:>11,}")
print("\n n = 3 is Japanese, Korean and English: trained are ja-en, en-ja, ko-en,")
print(" en-ko, and zero-shot are ja-ko and ko-ja. One model serves all six")
print(" when the source carries a token naming the target language:\n")
print(" <2ko> the dog ran")
print(" <2ja> the dog ran")
def trace_pair(en_s, sw_s, iters=10):
t = init_table()
for _ in range(iters):
t, _, _, _ = em_step(t)
en, sw = en_s.split(), sw_s.split()
print(f"\n\nALIGNMENT for '{en_s}' / '{sw_s}' (after {iters} iterations)\n")
print(f" {'Swahili':<12}" + "".join(f"{e:>10}" for e in en)
+ f"{' most likely':>16}")
print(" " + "-" * (12 + 10 * len(en) + 16))
for f in sw:
if f not in SW:
print(f" {f:<12}not in the vocabulary")
continue
z = sum(t[e][f] for e in en if e in EN)
post = {e: (t[e][f] / z if z else 0.0) for e in en if e in EN}
cells = "".join(f"{post.get(e, 0.0):>10.4f}" for e in en)
best = max(post, key=post.get) if post else "?"
print(f" {f:<12}{cells}{best:>16}")
print("\n Each row is a posterior over alignments for one target word.")
print(" Model 1 has no notion of position, so this is decided entirely")
print(" by the translation table.")
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--corpus", action="store_true")
ap.add_argument("--step", action="store_true")
ap.add_argument("--converge", action="store_true")
ap.add_argument("--learned", action="store_true")
ap.add_argument("--extra", action="store_true",
help="add a fifth pair and watch the tie break")
ap.add_argument("--neural", action="store_true",
help="encoder, decoder, attention and the beam length bias")
ap.add_argument("--bottleneck", action="store_true",
help="what one fixed vector forgets")
ap.add_argument("--objective", action="store_true",
help="log p(E | F) and J(theta)")
ap.add_argument("--bptt", action="store_true",
help="backpropagation through the decoder")
ap.add_argument("--encoders", action="store_true",
help="bidirectional and stacked encoders")
ap.add_argument("--local", action="store_true",
help="global against local attention")
ap.add_argument("--infer", action="store_true",
help="the three phases of translating a new sentence")
ap.add_argument("--setup", action="store_true",
help="a typical system, counted")
ap.add_argument("--multi", action="store_true",
help="many languages, one model")
ap.add_argument("--iters", type=int, default=10)
ap.add_argument("--pair", nargs=2, metavar=("ENGLISH", "SWAHILI"))
a = ap.parse_args()
if a.pair:
trace_pair(a.pair[0], a.pair[1], a.iters)
print()
return
later = [(a.bottleneck, show_bottleneck), (a.objective, show_objective),
(a.bptt, show_bptt), (a.encoders, show_encoders),
(a.local, show_local), (a.infer, show_infer),
(a.setup, show_setup), (a.multi, show_multi)]
picked = (a.corpus or a.step or a.converge or a.learned or a.extra
or a.neural or any(on for on, _ in later))
if a.corpus or not picked:
show_corpus()
if a.step or not picked:
show_step()
if a.converge or not picked:
show_convergence(a.iters)
if a.learned or not picked:
show_learned(a.iters)
if a.extra or not picked:
show_extra(a.iters)
if a.neural or not picked:
show_neural()
for on, show in later:
if on or not picked:
show()
print()
if __name__ == "__main__":
main()