Encoder-decoder and sequence-to-sequence learning
Build recurrent encoder-decoder models for sequence transduction, examine teacher forcing and greedy decoding, and interpret BLEU, chrF, source reversal, and context bottlenecks.
After this lesson you can
- Implement encoder-decoder models with context in the initial state or every decoder input.
- Train with teacher forcing and masked loss and implement greedy decoding with end-token stopping.
- Compute BLEU and explain clipping, brevity penalty, and tokenization effects.
- Measure quality by input length and discuss the context-vector bottleneck.
- Reproduce source reversal and explain why it helped under particular assumptions.
Before you start
- 17Recurrent language modelTeacher forcingAutoregressive factorizationAncestral sampling from an autoregressive modelLSTM cellGated recurrent unitStacked (deep) RNNsVariable-length batching: padding, masking and packing
- 07Cross-entropy minimization as maximum likelihoodConditional entropy
- 00Canonical training and evaluation loop
- 15Epochs and shuffling
- 14IBM alignment models
From one sequence to another
Translating a sentence, normalizing a written date, or summarizing a document produces a sequence whose length can differ from its input. There is also no need to emit each output word when its input counterpart is read. Instead of forcing a step-by-step correspondence, encode the entire input first and then generate output.
A recurrent encoder-decoder separates these operations. The encoder consumes and produces context ; the decoder uses that context and previous outputs to generate . Context is not a translation: it is a learned representation that must contain useful information for producing one.
In the figure the decoder predicts the second word incorrectly. During training it next receives the correct reference word. During generation it receives its own prediction and, in this constructed example, emits the end prematurely. The difference comes from the feeding procedure; it does not itself establish how much a trained model will suffer.
The conditional model
Autoregressive factorization now conditions on the entire source:
The end signal is part of the output sequence. A maximum length is practical protection during generation, not a substitute for learning that probability. Sequence-to-sequence learning maximizes the conditional probability of complete paired sequences, summing each term’s logarithm.
The encoder updates and in the simplest form returns . The decoder computes and a vocabulary distribution from its state. In the state-initialization-only variant, comes from and context is not concatenated to every input. An LSTM has both hidden and cell state: initialize both explicitly and do not confuse them.
For batch size , a stacked LSTM with layers and width returns hidden and cell states of shape . If encoder and decoder shapes match, pass the pair directly. Otherwise explicit projections and a choice of which encoder layers feed which decoder layers are needed. In the lab’s per-step context variant, the final layer’s hidden state is concatenated to each target embedding: decoder input width becomes , though state width remains .
In either design the decoder can ignore context if gates and weights permit; feeding it repeatedly supplies a direct path but does not guarantee use. A bidirectional encoder may summarize the whole source because it is available initially. During generation, by contrast, the decoder cannot condition on future target tokens that do not exist yet.
Phrase-based statistical translation combined translation proposals and scores with other components. Kalchbrenner and Blunsom studied continuous recurrent models; Cho and colleagues used an encoder-decoder to score phrase pairs. Sutskever and colleagues applied deep LSTMs to complete-sequence translation and reversed the source. These are distinct historical relationships, not the same system renamed.
Sutskever and colleagues used four LSTM layers of 1 000 cells each, 1 000-dimensional embeddings, and an 80 000-word output vocabulary. Their main WMT 2014 English-to-French result was 34.8 BLEU with an ensemble of five reversed-source models and beam width 12, penalizing out-of-vocabulary words. That number belongs to their system, data, and protocol, not this reduced lab. It is also insufficient to compare with BLEU computed using different segmentation or references.
Training and generation
For reference a b <eos>, decoder inputs are <bos> a b and labels are a b <eos>. In teacher forcing the previous reference is used even if the prediction differed. With padded batch sequences, loss sums only valid label positions:
Here is one for real tokens, including <eos>, and zero for padding. Dividing by valid-token count prevents loss magnitude depending on added padding. The encoder must know actual lengths to avoid using a state after padding as context.
To see backpropagation, let be logits and . At a valid position the cross-entropy derivative is ; under the normalization above it is multiplied by . Padding contributes zero gradient. The gradient crosses decoder recurrence toward and then the entire encoder; if context also enters every step, each such input adds a direct contribution. The manual cell makes this path explicit for the first design.
Greedy decoding chooses the most likely token at each step given the generated prefix. Each batch row must stop growing upon <eos> while others may continue. A maximum length is also imposed. This optimizes each local choice, not the probability of the complete sequence.
Reaching maximum length is not equivalent to emitting <eos>: the returned output is truncated. The lab figure distinguishes the two. In batched evaluation a finished row remains in the tensor to preserve shapes, but later emissions are ignored. Disable dropout and gradient computation during evaluation: measure the same inference rule used for translation.
BLEU and chrF
BLEU compares hypothesis n-grams with references. Modified precision clips each n-gram’s count to its maximum count in any reference. Repeating a word cannot create unlimited matches. For a corpus, sum matches and totals by order first; do not average sentence BLEU scores.
With precisions , total candidate length and effective reference length , unsmoothed BLEU is
If any precision is zero, unsmoothed BLEU is zero. With multiple references each sentence’s effective reference length is the closest to the hypothesis, choosing the shorter in a tie. The original paper is Papineni and colleagues. The metric depends on tokenization, case handling, and other decisions; Post explains why publishing the sacreBLEU signature with the value is essential for comparison.
The brevity penalty prevents a hypothesis of only a few very safe words from obtaining misleadingly high precision. BLEU does not directly measure semantic completeness, however, and different valid translations can share few n-grams with a particular reference. In small corpora a single sentence can change the score greatly; the lab therefore shows example counts per bucket and it is wise to inspect outputs as well as the mean.
chrF compares character n-grams with precision and recall combined in an F-mean weighted toward recall. It can recognize morphological overlap without word segmentation, but does not itself decide whether translation preserves meaning. The figure allows multiple references and uses explicit educational rules; it does not implement the sacreBLEU signature.
import math
precisions = [6/7, 4/6, 2/5, 1/4]
bp = math.exp(1 - 9/7)
bleu = 100 * bp * math.exp(sum(math.log(p) for p in precisions)/4)
print('BP:', round(bp, 6), 'BLEU:', round(bleu, 6))One vector and source order
The context-vector bottleneck means all source information must pass through a fixed-dimensional state before output generation. This is not an impossibility proof for every length or numerical precision, but it is an architectural restriction that can make details hard to retain. Cho and colleagues observed degradation for long sentences and unknown words in the systems studied. Length and unknowns may vary together, so an observational curve alone does not prove one cause.
Historical evidence also cautions against making this a universal law. Sutskever and colleagues, section 3.3, reported that reversing the source changed test perplexity from 5.8 to 4.7 and BLEU from 25.9 to 30.6 in their comparison. They proposed short dependencies as an explanation but said it was incomplete. In their deep-LSTM reversed-source configuration they also reported good behavior on long sentences. Read a length graph together with architecture, vocabulary, data, and decoding; it cannot alone identify the mechanism behind a difference.
In a one-to-one toy alignment with words and an equal-length decoder, count recurrent transitions from reading source word to emitting its translation . In normal order the distance is ; reversed, . The mean remains , but the minimum changes from to . This example explains short early paths, not a guarantee that real pairs align monotonically.
Laboratory: a toy GRU
The next cell reuses the variant and backward pass of the previous lesson’s GRU. Each example has its own length, so no padding is needed here. The encoder receives one-hot vectors and its final state initializes the decoder. Loss sums over every target symbol and <eos>; its gradient crosses the decoder’s initial state to the encoder. The two GRUs have separate parameters. To check the path without claiming learning, the visible run uses few updates; change updates for more training.
import numpy as np
V, BOS, EOS, H = 16, 14, 15, 12
eye = np.eye(V)
def sigmoid(x):
return np.exp(-np.logaddexp(0, -x))
def init_gru(rng):
return {'wx': rng.normal(0, .2, (V, 3*H)),
'wh': rng.normal(0, .2, (H, 3*H)),
'bi': np.zeros(3*H), 'bh': np.zeros(3*H)}
def step(x, h, p):
xr, xz, xn = np.split(x @ p['wx'] + p['bi'], 3)
hr, hz, hn = np.split(h @ p['wh'] + p['bh'], 3)
r, z = sigmoid(xr+hr), sigmoid(xz+hz)
n = np.tanh(xn+r*hn)
return (1-z)*n+z*h, (x, h, r, z, n, hn, p)
def step_back(dh, cache):
x, h, r, z, n, hn, p = cache
dan = dh*(1-z)*(1-n*n)
dar = dan*hn*r*(1-r)
daz = dh*(h-n)*z*(1-z)
di = np.concatenate((dar, daz, dan))
dr = np.concatenate((dar, daz, dan*r))
g = {'wx': np.outer(x, di), 'wh': np.outer(h, dr),
'bi': di, 'bh': dr}
return dh*z + dr @ p['wh'].T, g
def blank(p):
return {k: np.zeros_like(v) for k, v in p.items()}
def accumulate(total, part):
for key in total:
total[key] += part[key]
def loss_and_grad(src, target, enc, dec, head):
h = np.zeros(H); ec = []
for token in src:
h, cache = step(eye[token], h, enc); ec.append(cache)
dc = []; states = []; probabilities = []
previous = BOS
for token in target:
h, cache = step(eye[previous], h, dec)
logits = h @ head['w'] + head['b']
exp = np.exp(logits - logits.max()); p = exp/exp.sum()
states.append(h); probabilities.append(p); dc.append(cache)
previous = token
loss = -sum(np.log(p[y]) for p, y in zip(probabilities, target))/len(target)
ge, gd, gh = blank(enc), blank(dec), blank(head)
dh = np.zeros(H)
for t in range(len(target)-1, -1, -1):
dlogits = probabilities[t].copy()
dlogits[target[t]] -= 1
dlogits /= len(target)
gh['w'] += np.outer(states[t], dlogits); gh['b'] += dlogits
dh += dlogits @ head['w'].T
dh, g = step_back(dh, dc[t]); accumulate(gd, g)
for cache in reversed(ec):
dh, g = step_back(dh, cache); accumulate(ge, g)
return loss, (ge, gd, gh)
def decode(src, enc, dec, head, limit=12):
h = np.zeros(H)
for token in src:
h, _ = step(eye[token], h, enc)
previous = BOS; result = []
for _ in range(limit):
h, _ = step(eye[previous], h, dec)
previous = int(np.argmax(h @ head['w'] + head['b']))
if previous == EOS: break
result.append(previous)
return result
def example(rng, task, length):
src = rng.integers(0, 5, size=length).tolist()
target = src[::-1] if task == 'invertir' else sorted(src)
return src, target + [EOS]
def train_short(task, updates=30, seed=17):
rng = np.random.default_rng(seed)
enc, dec = init_gru(rng), init_gru(rng)
head = {'w': rng.normal(0, .2, (H, V)), 'b': np.zeros(V)}
first = last = 0.
for update in range(updates):
src, target = example(rng, task, int(rng.integers(2, 6)))
loss, gradients = loss_and_grad(src, target, enc, dec, head)
if update == 0: first = loss
last = loss
norm = np.sqrt(sum(np.sum(v*v) for g in gradients for v in g.values()))
scale = min(1., 1./max(norm, 1e-12))
for params, grad in zip((enc, dec, head), gradients):
for key in params: params[key] -= .1*scale*grad[key]
return enc, dec, head, first, last
enc, dec, head, first, last = train_short('invertir')
print('Pérdida inicial y última, ejemplos distintos:', round(first, 4), round(last, 4))
print('Prueba de flujo:', decode([1, 2, 3], enc, dec, head))The first and last losses come from different examples: they are neither a validation curve nor an accuracy estimate. To study generalization, generate fixed disjoint training and evaluation sets, evaluate by length without teacher forcing, and compare multiple seeds. The real translation experiment is measured by corpus and length bucket with constant references and tokenization.
To turn that flow check into an experiment, the next local cell repeats the implementation for autonomy, constructs splits with no repeated sources, trains, and evaluates whole-sequence exact match including correct stopping. Numbers 0 through 4 are symbols for reversal and sorting. For dates, days 1 through 4, months January through March (5 through 7), and years 2024 and 2025 (8 and 9) have distinct identifiers; the input represents día mes año and target año mes día. This is a deliberately tiny vocabulary, not a general date normalizer. The long cell is excluded from automatic checks because of its budget; run it explicitly and compare seeds before concluding.
For example 2 febrero 2024 is encoded as [2, 6, 8]; target [8, 6, 2] is interpreted as 2024-02-02. Month and year identifiers are not literal date numbers: the mapping belongs to the vocabulary. To turn a prediction into a printable date, check its three tokens belong to the expected categories; an output failing that shape is an error, not a valid date.
import numpy as np
V, BOS, EOS, H = 16, 14, 15, 12
eye = np.eye(V)
def sigmoid(x):
return np.exp(-np.logaddexp(0, -x))
def init_gru(rng):
return {'wx': rng.normal(0, .2, (V, 3*H)),
'wh': rng.normal(0, .2, (H, 3*H)),
'bi': np.zeros(3*H), 'bh': np.zeros(3*H)}
def step(x, h, p):
xr, xz, xn = np.split(x @ p['wx'] + p['bi'], 3)
hr, hz, hn = np.split(h @ p['wh'] + p['bh'], 3)
r, z = sigmoid(xr+hr), sigmoid(xz+hz)
n = np.tanh(xn+r*hn)
return (1-z)*n+z*h, (x, h, r, z, n, hn, p)
def step_back(dh, cache):
x, h, r, z, n, hn, p = cache
dan = dh*(1-z)*(1-n*n)
dar = dan*hn*r*(1-r)
daz = dh*(h-n)*z*(1-z)
di = np.concatenate((dar, daz, dan))
dr = np.concatenate((dar, daz, dan*r))
g = {'wx': np.outer(x, di), 'wh': np.outer(h, dr),
'bi': di, 'bh': dr}
return dh*z + dr @ p['wh'].T, g
def blank(p):
return {k: np.zeros_like(v) for k, v in p.items()}
def accumulate(total, part):
for key in total:
total[key] += part[key]
def loss_and_grad(src, target, enc, dec, head):
h = np.zeros(H); ec = []
for token in src:
h, cache = step(eye[token], h, enc); ec.append(cache)
dc = []; states = []; probabilities = []
previous = BOS
for token in target:
h, cache = step(eye[previous], h, dec)
logits = h @ head['w'] + head['b']
exp = np.exp(logits - logits.max()); p = exp/exp.sum()
states.append(h); probabilities.append(p); dc.append(cache)
previous = token
loss = -sum(np.log(p[y]) for p, y in zip(probabilities, target))/len(target)
ge, gd, gh = blank(enc), blank(dec), blank(head)
dh = np.zeros(H)
for t in range(len(target)-1, -1, -1):
dlogits = probabilities[t].copy()
dlogits[target[t]] -= 1
dlogits /= len(target)
gh['w'] += np.outer(states[t], dlogits); gh['b'] += dlogits
dh += dlogits @ head['w'].T
dh, g = step_back(dh, dc[t]); accumulate(gd, g)
for cache in reversed(ec):
dh, g = step_back(dh, cache); accumulate(ge, g)
return loss, (ge, gd, gh)
def decode(src, enc, dec, head, limit=12):
h = np.zeros(H)
for token in src:
h, _ = step(eye[token], h, enc)
previous = BOS; result = []
for _ in range(limit):
h, _ = step(eye[previous], h, dec)
previous = int(np.argmax(h @ head['w'] + head['b']))
if previous == EOS: break
result.append(previous)
return result
def example(rng, task, length):
src = rng.integers(0, 5, size=length).tolist()
target = src[::-1] if task == 'invertir' else sorted(src)
return src, target + [EOS]
def train_short(task, updates=30, seed=17):
rng = np.random.default_rng(seed)
enc, dec = init_gru(rng), init_gru(rng)
head = {'w': rng.normal(0, .2, (H, V)), 'b': np.zeros(V)}
first = last = 0.
for update in range(updates):
src, target = example(rng, task, int(rng.integers(2, 6)))
loss, gradients = loss_and_grad(src, target, enc, dec, head)
if update == 0: first = loss
last = loss
norm = np.sqrt(sum(np.sum(v*v) for g in gradients for v in g.values()))
scale = min(1., 1./max(norm, 1e-12))
for params, grad in zip((enc, dec, head), gradients):
for key in params: params[key] -= .1*scale*grad[key]
return enc, dec, head, first, last
from itertools import product
def make_split(task, seed=12):
rng = np.random.default_rng(seed)
if task == 'fecha':
sequences = [list(x) for x in product(range(1, 5), range(5, 8), range(8, 10))]
else:
sequences = [list(x) for length in range(2, 6) for x in product(range(5), repeat=length)]
order = rng.permutation(len(sequences))
cut = int(.8 * len(order))
def pairs(indices):
out = []
for i in indices:
src = sequences[i]
target = src[::-1] if task == 'invertir' else sorted(src) if task == 'ordenar' else [src[2], src[1], src[0]]
out.append((src, target + [EOS]))
return out
return pairs(order[:cut]), pairs(order[cut:])
def fit_dataset(task, updates=20000, seed=17):
train, test = make_split(task)
assert not ({tuple(s) for s, _ in train} & {tuple(s) for s, _ in test})
rng = np.random.default_rng(seed)
enc, dec = init_gru(rng), init_gru(rng)
head = {'w': rng.normal(0, .2, (H, V)), 'b': np.zeros(V)}
for _ in range(updates):
src, target = train[int(rng.integers(len(train)))]
_, gradients = loss_and_grad(src, target, enc, dec, head)
norm = np.sqrt(sum(np.sum(v*v) for g in gradients for v in g.values()))
scale = min(1., 1./max(norm, 1e-12))
for params, grad in zip((enc, dec, head), gradients):
for key in params: params[key] -= .1*scale*grad[key]
for length in sorted({len(s) for s, _ in test}):
subset = [(s,t) for s,t in test if len(s) == length]
# Exige que el resultado haya terminado en eos: decode devuelve también un indicador.
correct = sum(decode_complete(s, enc, dec, head) == (t[:-1], True) for s,t in subset)
print(task, 'longitud', length, 'n', len(subset), 'exactitud', round(correct/len(subset), 4))
def decode_complete(src, enc, dec, head, limit=12):
h = np.zeros(H)
for token in src: h, _ = step(eye[token], h, enc)
previous = BOS; result = []
for _ in range(limit):
h, _ = step(eye[previous], h, dec)
previous = int(np.argmax(h @ head['w'] + head['b']))
if previous == EOS: return result, True
result.append(previous)
return result, False
for task in ('invertir', 'ordenar', 'fecha'):
fit_dataset(task)npm run lab and open the connection link.In one local run with the cell’s seeds and 20 000 updates per task, reversal got 487 of 611 length-5 sequences right, and sorting got all 611. Lengths 2 and 3 had only 4 and 32 examples; the date set had only 5, of which 2 were correct. These are results of this small run, not precise estimates or a general task comparison. Another seed can change them; also observe whether the model stops or reaches the limit.
The implementation’s finite-difference check uses scalar loss and perturbs every encoder, decoder, and head weight. Maximum absolute error observed in the review run was below ; this checks backward for that example, not generalization.
Translation with PyTorch: preparation
The next experiment needs PyTorch and sacrebleu==2.5.1 locally. Download spa-eng.zip from ManyThings, based on Tatoeba into the working directory, or set its path in environment variable SEQ_DATA; preserve each row’s attribution. Rows are grouped by Spanish source before splitting so one source cannot appear in training and evaluation. Vocabulary uses training only; unknown words become <unk>. English references may repeat across groups, so the split does not guarantee semantic independence.
The short configuration runs five updates per condition to check the path, not establish quality. Long mode trains longer; results depend on corpus version, seed, and budget, so record its hash and metric signatures. Evaluate without teacher forcing, with per-row <eos> stopping and a maximum length. Because these strings are already segmented and lowercased, use tok:none: its BLEU is not directly comparable to one computed on unsegmented text with another signature.
import hashlib, io, os, random, re, zipfile
from pathlib import Path
from collections import Counter
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence
from sacrebleu.metrics import BLEU, CHRF
torch.manual_seed(1717); random.seed(1717)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
archive = Path(os.environ.get('SEQ_DATA', 'spa-eng.zip')).read_bytes()
print('SHA-256 del archivo:', hashlib.sha256(archive).hexdigest())
with zipfile.ZipFile(io.BytesIO(archive)) as z:
rows = z.read('spa.txt').decode('utf-8').splitlines()
def tokenize(s):
return re.findall(r'\w+|[^\w\s]', s.lower(), flags=re.UNICODE)
groups = {}
for row in rows:
parts = row.split('\t')
if len(parts) < 3: continue
en, es = tokenize(parts[0]), tokenize(parts[1])
if 2 <= len(es) <= 18 and 2 <= len(en) <= 18:
groups.setdefault(tuple(es), []).append(tuple(en))
keys = list(groups); random.shuffle(keys)
full = os.environ.get('SEQ2SEQ_FULL') == '1'
ntrain, nval, ntest = (30000, 2000, 2000) if full else (512, 64, 64)
assert len(keys) >= ntrain+nval+ntest
train_keys = keys[:ntrain]
val_keys = keys[ntrain:ntrain+nval]
test_keys = keys[ntrain+nval:ntrain+nval+ntest]
train = [(s, groups[s][0]) for s in train_keys]
valid = [(s, groups[s][0]) for s in val_keys]
test = [(s, groups[s][0]) for s in test_keys]
special = ['<pad>', '<bos>', '<eos>', '<unk>']
def vocab(seqs):
counts = Counter(token for seq in seqs for token in seq)
return special + sorted(token for token, count in counts.items() if count >= 2)
sv = vocab(s for s, t in train); tv = vocab(t for s, t in train)
si = {w:i for i,w in enumerate(sv)}; ti = {w:i for i,w in enumerate(tv)}
PAD, BOS, EOS, UNK = range(4)
def ids(seq, vocab): return [vocab.get(w, UNK) for w in seq]
def batch(examples, reverse):
sources = [list(reversed(s)) if reverse else list(s) for s, _ in examples]
x = [torch.tensor(ids(s, si), dtype=torch.long) for s in sources]
y = [torch.tensor(ids(t, ti)+[EOS], dtype=torch.long) for _, t in examples]
lengths = torch.tensor([len(s) for s in x], dtype=torch.long)
return pad_sequence(x, batch_first=True, padding_value=PAD).to(device), lengths, pad_sequence(y, batch_first=True, padding_value=PAD).to(device)
class Seq2Seq(nn.Module):
def __init__(self, hidden, context_each=False):
super().__init__()
self.context_each = context_each
self.src_emb = nn.Embedding(len(sv), hidden, padding_idx=PAD)
self.tgt_emb = nn.Embedding(len(tv), hidden, padding_idx=PAD)
self.encoder = nn.LSTM(hidden, hidden, 2, batch_first=True)
self.decoder = nn.LSTM(hidden*(2 if context_each else 1), hidden, 2, batch_first=True)
self.head = nn.Linear(hidden, len(tv))
def encode(self, x, lengths):
packed = pack_padded_sequence(self.src_emb(x), lengths.cpu(), batch_first=True, enforce_sorted=False)
_, state = self.encoder(packed)
return state
def forward(self, x, lengths, target):
state = self.encode(x, lengths); context = state[0][-1]
bos = torch.full((len(x), 1), BOS, dtype=torch.long, device=x.device)
shifted = torch.cat((bos, target[:, :-1]), dim=1)
inp = self.tgt_emb(shifted)
if self.context_each: inp = torch.cat((inp, context[:, None, :].expand(-1, inp.shape[1], -1)), dim=-1)
out, _ = self.decoder(inp, state)
return self.head(out)
@torch.no_grad()
def generate(self, x, lengths, limit=24, return_finished=False):
state = self.encode(x, lengths); context = state[0][-1]
token = torch.full((len(x),), BOS, dtype=torch.long, device=x.device)
done = torch.zeros(len(x), dtype=torch.bool, device=x.device)
result = [[] for _ in range(len(x))]
for _ in range(limit):
inp = self.tgt_emb(token)[:, None, :]
if self.context_each: inp = torch.cat((inp, context[:, None, :]), dim=-1)
out, state = self.decoder(inp, state)
token = self.head(out[:, 0]).argmax(-1)
token = torch.where(done, torch.full_like(token, EOS), token)
for i, k in enumerate(token.tolist()):
if not done[i] and k != EOS: result[i].append(k)
done |= token == EOS
if done.all(): break
return (result, done.tolist()) if return_finished else result
def metrics(model, examples, reverse):
model.eval(); hypotheses = []; references = []
for start in range(0, len(examples), 32):
group = examples[start:start+32]; x, lengths, _ = batch(group, reverse)
predictions = model.generate(x, lengths)
hypotheses.extend(' '.join(tv[k] for k in p) for p in predictions)
references.extend(' '.join(t) for _, t in group)
bleu, chrf = BLEU(tokenize='none', force=True), CHRF()
b = bleu.corpus_score(hypotheses, [references])
c = chrf.corpus_score(hypotheses, [references])
return b.score, c.score, str(bleu.get_signature()), str(chrf.get_signature())
length_results = {}
def experiment(hidden, reverse, context_each=False):
torch.manual_seed(1717)
rng = random.Random(1717)
model = Seq2Seq(hidden, context_each).to(device)
opt = torch.optim.Adam(model.parameters(), lr=.001)
steps = int(os.environ.get('SEQ_STEPS', '10000' if full else '5'))
model.train()
for step in range(steps):
examples = rng.sample(train, 32)
x, lengths, target = batch(examples, reverse)
logits = model(x, lengths, target)
loss = nn.functional.cross_entropy(logits.reshape(-1, len(tv)), target.reshape(-1), ignore_index=PAD)
opt.zero_grad(); loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.)
opt.step()
if full and (step + 1) % 500 == 0:
print('estado', hidden, 'inversión', reverse, 'paso', step + 1, 'pérdida', round(loss.item(), 4), flush=True)
print('estado:', hidden, 'inversión:', reverse, 'pasos:', steps, 'pérdida final:', round(loss.item(), 4))
print('validación BLEU, chrF y firmas:', metrics(model, valid, reverse))
buckets = []
for low, high in [(2, 5), (6, 9), (10, 13), (14, 18)]:
subset = [(s,t) for s,t in test if low <= len(s) <= high]
if subset:
scores = metrics(model, subset, reverse)[:2]
buckets.append({'label': f'{low}-{high}', 'n': len(subset), 'bleu': scores[0], 'chrf': scores[1]})
print('test longitud', low, high, 'n=', len(subset), 'BLEU/chrF=', scores)
length_results[(hidden, reverse)] = buckets
return model
models = {(h, rev): experiment(h, rev) for h in (128, 512) for rev in (False, True)}
# Comprueba también la variante con contexto en cada paso, sin presentarla como entrenada.
x, lengths, target = batch(train[:4], False)
alternate = Seq2Seq(128, context_each=True).to(device)
alternate_logits = alternate(x, lengths, target)
assert alternate_logits.shape == (4, target.shape[1], len(tv))
nn.functional.cross_entropy(alternate_logits.reshape(-1, len(tv)), target.reshape(-1), ignore_index=PAD).backward()
assert alternate.encoder.weight_ih_l0.grad is not None
print('Variante de contexto en cada paso: forma y backward comprobados')npm run lab and open the connection link.As reference for an intermediate run, four conditions trained for 1 000 updates on 30 000 training sources with one seed. For the 512-unit model without reversal, test BLEU went from 10.55 for sources of 2 to 5 tokens () to 2.90 for 14 to 18 (). With reversal those buckets scored 11.33 and 4.43. These used sacreBLEU 2.5.1 and signature tok:13a on presegmented strings: the current cell deliberately uses tok:none, so do not compare its scores directly. The budget is smaller than long mode, the long group is small, and one seed cannot establish causality or that reversal always helps. Figure outputs come from your own run, not the numbers reported here.
Exercises
Step 1 of 3. Which first token does greedy search choose?
import numpy as np
def greedy_decode(encoder, decoder, src, max_len, bos, eos):
pass