Neural Machine Translation › Worked Example: A Toy Reordering Language

Michael BrenndoerferNovember 26, 202618 min read
Language AI HandbookAll chapters
Part 27 of 67Machine Translation and Speech Translation
Chapter 191Neural Machine Translation › Worked Example: A Toy Reordering Language
Reading section 9 of 12 · Worked Example: A Toy Reordering Language · 18 minSection 9 of 12 · 18 min

Section 9 of 12 · 18 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

We train and evaluate a small transformer on Mirror, a synthetic target language. Two deterministic rules generate its base translations:

  1. Full reordering. The target is the source in reverse word order.
  2. Lexical substitution. The definite article "the" becomes "der".

With these rules, “the big cat sees a small dog” becomes “dog small a sees cat big der.” In the seeded corpus, each occurrence of “the” is independently dropped with probability 0.15 during target generation. The reverse order supplies a reference correspondence for the retained words.

The synthetic corpus lets us compare decoders by exact match against one sampled target per input. If the reference drops an article, a prediction that includes it loses exact-match credit even when its other words follow both deterministic rules.

Generating the corpus

The generator samples source sentences of five or seven words. Reversal and substitution preserve length, and randomly dropping definite articles can shorten targets. Excluding the special markers, sampled targets in this fixture range from three to seven words.

PythonIn [9]
CollapseExpand
import math
import random

import torch
import torch.nn as nn
import torch.nn.functional as F

SEED = 13
random.seed(SEED)
torch.manual_seed(SEED)
device = torch.device("cpu")
# The tiny batches use one CPU thread throughout this notebook.
torch.set_num_threads(1)

DETS = ["the", "a"]
ADJS = ["big", "small", "red", "blue"]
NOUNS = ["cat", "dog", "bird", "fox"]
VERBS = ["sees", "chases", "likes"]


def make_sentence(rng):
    """Sample a source sentence from one of two templates."""
    if rng.random() < 0.5:
        return [
            rng.choice(DETS),
            rng.choice(ADJS),
            rng.choice(NOUNS),
            rng.choice(VERBS),
            rng.choice(DETS),
            rng.choice(ADJS),
            rng.choice(NOUNS),
        ]
    return [
        rng.choice(DETS),
        rng.choice(NOUNS),
        rng.choice(VERBS),
        rng.choice(DETS),
        rng.choice(NOUNS),
    ]


def to_mirror(tokens):
    """Mirror language: reverse the order and map 'the' -> 'der'."""
    return ["der" if t == "the" else t for t in reversed(tokens)]


def to_mirror_noisy(tokens, rng, drop_prob=0.15):
    """Mirror language with a learned exception: some articles are dropped.

    Independent random deletions make the observed target ambiguous, even when
    the deterministic reversal and substitution are known.
    """
    out = []
    for t in reversed(tokens):
        if t == "the":
            if rng.random() < drop_prob:
                continue
            out.append("der")
        else:
            out.append(t)
    return out
PythonIn [10]
CollapseExpand
rng = random.Random(SEED)
seen, pairs = set(), []
while len(pairs) < 900:
    src_tokens = make_sentence(rng)
    key = tuple(src_tokens)
    if key in seen:
        continue
    seen.add(key)
    pairs.append((src_tokens, to_mirror_noisy(src_tokens, rng)))

rng.shuffle(pairs)
train_pairs, test_pairs = pairs[:800], pairs[800:]
ConsoleOut [11]
CollapseExpand
Training pairs: 800
Test pairs:     100
  the small fox likes a blue fox                -> fox blue a likes fox small der
  a red cat likes a big cat                     -> cat big a likes cat red a
  a blue bird likes a blue bird                 -> bird blue a likes bird blue a

The model is trained to learn reversal and substitution. The sampled references can omit definite articles. The source tells you the positions where omission is possible, while the random draws determine which articles the sampled target drops. Exact match compares one sampled reference per input.

Building vocabularies

We build separate source and target vocabularies with four reserved symbols. PAD is index 0 because we will use it as the ignore_index in the loss and as the padding_idx in the embeddings.

PythonIn [12]
CollapseExpand
PAD, BOS, EOS, UNK = "<pad>", "<bos>", "<eos>", "<unk>"
PAD_ID, BOS_ID, EOS_ID, UNK_ID = 0, 1, 2, 3

src_itos = [PAD, BOS, EOS, UNK] + sorted({t for s, _ in train_pairs for t in s})
tgt_itos = [PAD, BOS, EOS, UNK] + sorted({t for _, t in train_pairs for t in t})
src_stoi = {t: i for i, t in enumerate(src_itos)}
tgt_stoi = {t: i for i, t in enumerate(tgt_itos)}


def encode(tokens, stoi, bos=False, eos=True):
    """Map tokens to ids, optionally wrapping with BOS/EOS."""
    ids = [stoi.get(t, UNK_ID) for t in tokens]
    if bos:
        ids = [stoi[BOS]] + ids
    if eos:
        ids = ids + [stoi[EOS]]
    return ids
ConsoleOut [13]
CollapseExpand
Source vocabulary (17): ['<pad>', '<bos>', '<eos>', '<unk>', 'a', 'big', 'bird', 'blue', 'cat', 'chases', 'dog', 'fox', 'likes', 'red', 'sees', 'small', 'the']
Target vocabulary (17): ['<pad>', '<bos>', '<eos>', '<unk>', 'a', 'big', 'bird', 'blue', 'cat', 'chases', 'der', 'dog', 'fox', 'likes', 'red', 'sees', 'small']

The source vocabulary includes the and the target vocabulary includes der. The model below uses separate source and target embedding tables. That choice is independent of the target embedding–output tie.

Batching with padding and masks

The batch builder produces three tensors: the source (with EOS), the decoder input (BOS + target, no EOS), and the decoder target (target + EOS, no BOS). This shift-by-one is the standard teacher-forcing arrangement.

PythonIn [14]
CollapseExpand
def make_batch(batch):
    src = [torch.tensor(encode(s, src_stoi, eos=True)) for s, _ in batch]
    tgt_in = [
        torch.tensor(encode(t, tgt_stoi, bos=True, eos=False)) for _, t in batch
    ]
    tgt_out = [
        torch.tensor(encode(t, tgt_stoi, bos=False, eos=True)) for _, t in batch
    ]
    src = nn.utils.rnn.pad_sequence(src, batch_first=True, padding_value=PAD_ID)
    tgt_in = nn.utils.rnn.pad_sequence(
        tgt_in, batch_first=True, padding_value=PAD_ID
    )
    tgt_out = nn.utils.rnn.pad_sequence(
        tgt_out, batch_first=True, padding_value=PAD_ID
    )
    return src.to(device), tgt_in.to(device), tgt_out.to(device)
ConsoleOut [15]
CollapseExpand
source ids      : [[4, 8, 14, 16, 6, 2, 0, 0], [16, 15, 11, 12, 4, 7, 11, 2]]
decoder input   : [[1, 6, 15, 8, 4, 0, 0, 0], [1, 12, 7, 4, 13, 12, 16, 10]]
decoder target  : [[6, 15, 8, 4, 2, 0, 0, 0], [12, 7, 4, 13, 12, 16, 10, 2]]
source key mask : [[False, False, False, False, False, False, True, True], [False, False, False, False, False, False, False, False]]
target loss mask: [[True, True, True, True, True, False, False, False], [True, True, True, True, True, True, True, True]]

The short row shows padding after the source and target sequences. In key_padding_mask, True masks the corresponding key/value column before the attention softmax. A padded query can still produce an output. The target loss mask marks labels that count toward the loss. The loss uses ignore_index=PAD_ID to exclude the other labels.

The model

We build a pre-norm transformer encoder-decoder. Three pieces: sinusoidal position encoding, an encoder layer with self-attention, and a decoder layer with masked self-attention plus cross-attention.

PythonIn [16]
CollapseExpand
class PositionalEncoding(nn.Module):
    """Fixed sinusoidal position signal, added to token embeddings."""

    def __init__(self, d_model, max_len=64):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        pos = torch.arange(max_len).unsqueeze(1).float()
        div = torch.exp(
            torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)
        )
        pe[:, 0::2] = torch.sin(pos * div)
        pe[:, 1::2] = torch.cos(pos * div)
        self.register_buffer("pe", pe)

    def forward(self, x):
        return x + self.pe[: x.size(1)].unsqueeze(0)
PythonIn [17]
CollapseExpand
class EncoderLayer(nn.Module):
    """Pre-norm self-attention block with a feed-forward sublayer."""

    def __init__(self, d_model, n_heads, d_ff, dropout=0.1):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(
            d_model, n_heads, dropout=dropout, batch_first=True
        )
        self.ff = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model)
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.drop = nn.Dropout(dropout)

    def forward(self, x, src_key_padding_mask):
        h = self.norm1(x)
        a, _ = self.self_attn(
            h, h, h, key_padding_mask=src_key_padding_mask, need_weights=False
        )
        x = x + self.drop(a)
        h = self.norm2(x)
        return x + self.drop(self.ff(h))

The decoder layer has the extra cross-attention sublayer. We return its weights when asked, so we can visualize the alignment later.

PythonIn [18]
CollapseExpand
class DecoderLayer(nn.Module):
    """Pre-norm block with masked self-attention and cross-attention."""

    def __init__(self, d_model, n_heads, d_ff, dropout=0.1):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(
            d_model, n_heads, dropout=dropout, batch_first=True
        )
        self.cross_attn = nn.MultiheadAttention(
            d_model, n_heads, dropout=dropout, batch_first=True
        )
        self.ff = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model)
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.norm3 = nn.LayerNorm(d_model)
        self.drop = nn.Dropout(dropout)

    def forward(
        self,
        x,
        memory,
        tgt_mask,
        tgt_key_padding_mask,
        memory_key_padding_mask,
        return_attn=False,
    ):
        h = self.norm1(x)
        a, _ = self.self_attn(
            h,
            h,
            h,
            attn_mask=tgt_mask,
            key_padding_mask=tgt_key_padding_mask,
            need_weights=False,
        )
        x = x + self.drop(a)

        h = self.norm2(x)
        c, w = self.cross_attn(
            h,
            memory,
            memory,
            key_padding_mask=memory_key_padding_mask,
            need_weights=return_attn,
        )
        x = x + self.drop(c)

        h = self.norm3(x)
        return x + self.drop(self.ff(h)), w

Now the full model. Note the weight tying between the target embedding and the output projection: it saves parameters and helps the model keep input and output token representations consistent.

PythonIn [19]
CollapseExpand
class TransformerMT(nn.Module):
    """Minimal transformer encoder-decoder for sequence-to-sequence translation."""

    def __init__(
        self,
        src_vocab_size,
        tgt_vocab_size,
        d_model=64,
        n_heads=4,
        n_layers=2,
        d_ff=128,
        dropout=0.1,
    ):
        super().__init__()
        self.d_model = d_model
        self.src_embed = nn.Embedding(
            src_vocab_size, d_model, padding_idx=PAD_ID
        )
        self.tgt_embed = nn.Embedding(
            tgt_vocab_size, d_model, padding_idx=PAD_ID
        )
        self.src_pos = PositionalEncoding(d_model)
        self.tgt_pos = PositionalEncoding(d_model)
        self.encoder_layers = nn.ModuleList(
            [
                EncoderLayer(d_model, n_heads, d_ff, dropout)
                for _ in range(n_layers)
            ]
        )
        self.decoder_layers = nn.ModuleList(
            [
                DecoderLayer(d_model, n_heads, d_ff, dropout)
                for _ in range(n_layers)
            ]
        )
        self.norm_out = nn.LayerNorm(d_model)
        self.out = nn.Linear(d_model, tgt_vocab_size)
        self.out.weight = (
            self.tgt_embed.weight
        )  # Share the complete target embedding matrix.

    def encode(self, src, src_key_padding_mask):
        x = self.src_pos(self.src_embed(src) * math.sqrt(self.d_model))
        for layer in self.encoder_layers:
            x = layer(x, src_key_padding_mask)
        return x

    def decode(
        self, tgt_in, memory, memory_key_padding_mask, return_attn=False
    ):
        length = tgt_in.size(1)
        tgt_mask = torch.triu(
            torch.ones(length, length, dtype=torch.bool, device=tgt_in.device),
            diagonal=1,
        )
        tgt_kpm = tgt_in == PAD_ID
        x = self.tgt_pos(self.tgt_embed(tgt_in) * math.sqrt(self.d_model))
        attn = None
        for layer in self.decoder_layers:
            x, w = layer(
                x,
                memory,
                tgt_mask,
                tgt_kpm,
                memory_key_padding_mask,
                return_attn,
            )
            if return_attn:
                attn = w
        logits = self.out(self.norm_out(x))
        return (logits, attn) if return_attn else logits
ConsoleOut [20]
CollapseExpand
Parameters: 169,745
Device:     cpu

This model has 169,745 parameters, about 1/383 of the 65 million reported for the original Transformer base configuration. The output layer and target embedding share the same 17×6417\times64 matrix. Vaswani et al. (2017), Table 3

Training

We use Adam with the Noam learning-rate schedule from the transformer paper: linear warmup followed by inverse-square-root decay.

lr(step)=dmodel−0.5⋅min⁡(step−0.5, step⋅warmup−1.5)\text{lr}(\text{step}) = d_{\text{model}}^{-0.5} \cdot \min\left(\text{step}^{-0.5},\ \text{step} \cdot \text{warmup}^{-1.5}\right)

The label_smoothing=0.1 in the loss is the term we analyzed earlier, applied for real.

PythonIn [21]
CollapseExpand
def train_model(
    model, data, epochs=70, batch_size=32, warmup=300, label_smoothing=0.1
):
    opt = torch.optim.Adam(
        model.parameters(), lr=1.0, betas=(0.9, 0.98), eps=1e-9
    )
    history = {"epoch": [], "loss": [], "tok_acc": []}
    step = 0

    for epoch in range(1, epochs + 1):
        model.train()
        rng.shuffle(data)
        ep_loss, ep_correct, ep_total = 0.0, 0, 0

        for i in range(0, len(data), batch_size):
            src, tgt_in, tgt_out = make_batch(data[i : i + batch_size])
            step += 1
            lr = model.d_model**-0.5 * min(step**-0.5, step * warmup**-1.5)
            for group in opt.param_groups:
                group["lr"] = lr

            src_kpm = src == PAD_ID
            memory = model.encode(src, src_kpm)
            logits = model.decode(tgt_in, memory, src_kpm)
            loss = F.cross_entropy(
                logits.reshape(-1, logits.size(-1)),
                tgt_out.reshape(-1),
                ignore_index=PAD_ID,
                label_smoothing=label_smoothing,
            )

            opt.zero_grad()
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), 1.0)
            opt.step()

            mask = tgt_out != PAD_ID
            ep_loss += loss.item() * mask.sum().item()
            ep_correct += ((logits.argmax(-1) == tgt_out) & mask).sum().item()
            ep_total += mask.sum().item()

        history["epoch"].append(epoch)
        history["loss"].append(ep_loss / ep_total)
        history["tok_acc"].append(ep_correct / ep_total)

    return history
PythonIn [22]
CollapseExpand
training_smoothing = 0.1
history = train_model(model, train_pairs, label_smoothing=training_smoothing)
vocab_size = len(tgt_itos)
uniform_mass = training_smoothing / vocab_size
gold_mass = 1 - training_smoothing + uniform_mass
loss_floor = -gold_mass * math.log(gold_mass) - (
    vocab_size - 1
) * uniform_mass * math.log(uniform_mass)
ConsoleOut [23]
CollapseExpand
epoch   1  loss 50.9890  token acc 0.0000
epoch   5  loss 1.7101  token acc 0.5444
epoch  10  loss 1.1861  token acc 0.7398
epoch  20  loss 0.8548  token acc 0.8894
epoch  40  loss 0.6803  token acc 0.9725
epoch  70  loss 0.6432  token acc 0.9770

Loss generally decreases and teacher-forced accuracy rises. The smoothed objective has a lower bound of H(q)=−∑kq(k)log⁡q(k)H(q)=-\sum_k q(k)\log q(k) per nonpadding target, about 0.57 nats for K=17K=17 and ϵ=0.1\epsilon=0.1. The observed loss can remain above this bound because the model need not predict each smoothed target distribution exactly.

VisualizationOut [24]
CollapseExpand
Two views of training cross-entropy. The late-epoch panel shows the observed curve above the dashed theoretical lower bound.
Smoothed token cross-entropy over 70 training epochs. The full run uses a logarithmic loss axis. The final 31 epochs use a linear loss axis to show the gap between the observed loss and the 0.57-nat theoretical lower bound.

The theoretical floor provides a reference for the loss curve. The accuracy curve measures how often the gold token has the highest predicted probability.

VisualizationOut [25]
CollapseExpand
Line chart of teacher-forced token accuracy rising from zero to near one over 70 epochs.
Teacher-forced token accuracy on the training set. It measures the model's next-token predictions when it receives the observed target prefix.

Teacher-forced accuracy scores individual predictions given a reference prefix. To assess free-running translation, decode complete outputs and compare them with references under a sequence-level metric.

Decoding implementations

Greedy decoding reruns the decoder on the full prefix at each step without caching its keys and values. This keeps the toy implementation short. A production benchmark should measure the cost of recomputing the prefix.

PythonIn [26]
CollapseExpand
@torch.no_grad()
def greedy_decode(model, src, max_len=16):
    model.eval()
    src_kpm = src == PAD_ID
    memory = model.encode(src, src_kpm)
    ys = torch.full(
        (src.size(0), 1), BOS_ID, dtype=torch.long, device=src.device
    )
    finished = torch.zeros(src.size(0), dtype=torch.bool, device=src.device)

    for _ in range(max_len):
        logits = model.decode(ys, memory, src_kpm)
        next_logits = logits[:, -1]
        next_logits[:, [PAD_ID, BOS_ID]] = float("-inf")
        nxt = next_logits.argmax(-1).masked_fill(finished, PAD_ID)
        ys = torch.cat([ys, nxt.unsqueeze(1)], dim=1)
        finished |= nxt == EOS_ID
        if finished.all():
            break

    return ys[:, 1:].cpu()

For each sentence, the beam keeps the highest raw scores among live prefixes. At each step it also scores EOS continuations and records the best completed output by length-normalized score. EOS counts toward length. At the cap, return the best recorded completion if one exists. If none exists, return the best live prefix from the last step with a finite score. If none was generated, return an empty unfinished output.

PythonIn [27]
CollapseExpand
@torch.no_grad()
def beam_search(model, src, beam_size=4, max_len=16, length_penalty=1.0):
    if beam_size < 1 or max_len < 0:
        raise ValueError(
            "beam_size must be positive and max_len must be nonnegative"
        )

    model.eval()
    B = src.size(0)
    K = beam_size
    V = len(tgt_itos)

    src_kpm = src == PAD_ID
    memory = model.encode(src, src_kpm).repeat_interleave(K, dim=0)
    mem_kpm = src_kpm.repeat_interleave(K, dim=0)

    ys = torch.full((B, K, 1), BOS_ID, dtype=torch.long, device=src.device)
    score_dtype = torch.promote_types(memory.dtype, torch.float32)
    scores = torch.full(
        (B, K), float("-inf"), dtype=score_dtype, device=src.device
    )
    scores[:, 0] = 0.0
    completed = torch.full(
        (B, max_len), PAD_ID, dtype=torch.long, device=src.device
    )
    completed_scores = scores.new_full((B,), float("-inf"))
    fallback = torch.full_like(completed, PAD_ID)
    fallback_scores = scores.new_zeros(B)
    rows = torch.arange(B, device=src.device)

    for step in range(max_len):
        logits = model.decode(ys.flatten(0, 1), memory, mem_kpm)[:, -1]
        score_dtype = torch.promote_types(scores.dtype, logits.dtype)
        scores = scores.to(score_dtype)
        completed_scores = completed_scores.to(score_dtype)
        fallback_scores = fallback_scores.to(score_dtype)
        log_probs = F.log_softmax(logits, dim=-1, dtype=score_dtype).view(
            B, K, V
        )
        log_probs[:, :, [PAD_ID, BOS_ID]] = float("-inf")
        log_probs = log_probs.masked_fill(
            ~torch.isfinite(log_probs), float("-inf")
        )
        candidates = scores.unsqueeze(-1) + log_probs

        eos_scores, eos_parents = candidates[:, :, EOS_ID].max(dim=1)
        eos_scores /= ((6.0 + step) / 6.0) ** length_penalty
        improved = eos_scores > completed_scores
        completed[improved, :] = PAD_ID
        completed[improved, :step] = ys[
            rows[improved], eos_parents[improved], 1:
        ]
        completed[improved, step] = EOS_ID
        completed_scores[improved] = eos_scores[improved]

        candidates[:, :, EOS_ID] = float("-inf")
        scores, top_idx = candidates.reshape(B, K * V).topk(K, dim=1)
        parents = top_idx // V
        next_ids = (top_idx % V).masked_fill(~torch.isfinite(scores), PAD_ID)
        ys = torch.cat(
            [ys[rows[:, None], parents], next_ids.unsqueeze(-1)], dim=-1
        )
        has_live = torch.isfinite(scores[:, 0])
        fallback[has_live, : step + 1] = ys[has_live, 0, 1:]
        fallback_scores[has_live] = (
            scores[has_live, 0] / ((6.0 + step) / 6.0) ** length_penalty
        )
        if not has_live.any():
            break

    missing = ~torch.isfinite(completed_scores)
    completed[missing] = fallback[missing]
    completed_scores[missing] = fallback_scores[missing]
    return completed.cpu(), completed_scores.cpu()

The ID parser keeps EOS completion separate from the visible token list. Exact match requires both the reference tokens and an EOS. An unfinished row stays in the denominator.

PythonIn [28]
CollapseExpand
def unpack_decoded(seq):
    """Return lexical IDs and whether EOS ended the sequence."""
    ids = []
    for tok in seq.tolist():
        if tok in (EOS_ID, PAD_ID):
            return ids, tok == EOS_ID
        ids.append(tok)
    return ids, False


def batch_src(data):
    src = [torch.tensor(encode(s, src_stoi)) for s, _ in data]
    return nn.utils.rnn.pad_sequence(
        src, batch_first=True, padding_value=PAD_ID
    ).to(device)


def exact_match(preds, data):
    if not data or len(preds) != len(data):
        raise ValueError(
            "exact match requires one prediction for each of a nonempty set of references"
        )
    golds = [encode(t, tgt_stoi, eos=False) for _, t in data]
    return sum(
        ended and ids == gold for (ids, ended), gold in zip(preds, golds)
    ) / len(golds)

Greedy results

PythonIn [29]
CollapseExpand
src_test = batch_src(test_pairs)
greedy_out = greedy_decode(model, src_test, max_len=16)
greedy_preds = [unpack_decoded(seq) for seq in greedy_out]
greedy_exact = exact_match(greedy_preds, test_pairs)
ConsoleOut [30]
CollapseExpand
Greedy exact match: 0.810

OK  src : a red fox chases the red cat
     gold: cat red der chases fox red a
     pred: cat red der chases fox red a
OK  src : a big fox chases a blue cat
     gold: cat blue a chases fox big a
     pred: cat blue a chases fox big a
OK  src : a big fox chases the red cat
     gold: cat red der chases fox big a
     pred: cat red der chases fox big a
ERR src : the blue fox sees the red cat
     gold: cat red sees fox blue der
     pred: cat red der sees fox blue der
OK  src : a big fox chases a red cat
     gold: cat red a chases fox big a
     pred: cat red a chases fox big a

Greedy exact match gives a baseline on the held-out sources. A prediction can disagree with the single sampled reference even when it obeys the deterministic reversal and substitution, because the reference may omit the article randomly.

Comparing decoding settings

PythonIn [31]
CollapseExpand
beam_sizes = [1, 2, 4, 8]
beam_exact = {}
beam_mean_len = {}
beam_completed = {}

for k in beam_sizes:
    if k == 1:
        preds = greedy_preds
    else:
        out, _ = beam_search(
            model, src_test, beam_size=k, max_len=16, length_penalty=1.0
        )
        preds = [unpack_decoded(seq) for seq in out]
    beam_exact[k] = exact_match(preds, test_pairs)
    beam_mean_len[k] = sum(len(ids) for ids, _ in preds) / len(preds)
    beam_completed[k] = sum(ended for _, ended in preds)
ConsoleOut [32]
CollapseExpand
Decoding setting    exact match   mean length  EOS rows
Greedy                    0.810          6.54       100
Beam 2                    0.810          6.54       100
Beam 4                    0.810          6.54       100
Beam 8                    0.810          6.54       100
VisualizationOut [33]
CollapseExpand
Four equal exact-match bars for greedy decoding and length-penalized beam search at widths two, four, and eight.
Held-out exact match for greedy decoding and length-penalized beam search at widths 2, 4, and 8. The comparison scores one sampled reference per source. A higher model score need not improve exact match.

Greedy and beam search at widths 2, 4, and 8 complete all 100 outputs with EOS, achieve 81% exact match, and produce 6.54 lexical tokens per output on average. The beam settings rank completed outputs with a length penalty. This sweep reports held-out accuracy, lexical length, and completion under each policy, with one sampled reference per source. When comparing model scores across decoding settings, evaluate the outputs with the same scoring rule.

What the cross-attention learned

For an undropped Mirror sentence, the known word correspondence runs in reverse order. The heatmap lets us compare that reference with the decoder's attention in one held-out example, including the EOS positions.

We switch the model to evaluation mode, feed the gold target prefix (teacher forcing), and read the cross-attention weights from the final decoder layer, averaged over heads.

PythonIn [34]
CollapseExpand
ex_src_tokens, ex_tgt_tokens = test_pairs[0]
ex_src_ids = torch.tensor([encode(ex_src_tokens, src_stoi)]).to(device)
ex_tgt_ids = torch.tensor(
    [[BOS_ID] + encode(ex_tgt_tokens, tgt_stoi, eos=False)]
).to(device)

model.eval()
with torch.no_grad():
    ex_memory = model.encode(ex_src_ids, ex_src_ids == PAD_ID)
    _, ex_attn = model.decode(
        ex_tgt_ids, ex_memory, ex_src_ids == PAD_ID, return_attn=True
    )

attn_matrix = ex_attn[0].cpu().numpy()
col_labels = ex_src_tokens + [EOS]
row_labels = ex_tgt_tokens + [EOS]
VisualizationOut [35]
CollapseExpand
Heatmap of final-layer cross-attention for one held-out example, with the encoder tokens across columns and the next target tokens down the rows.
Cross-attention weights from the final decoder layer for one test sentence, averaged over heads. Rows name the next tokens under teacher forcing and columns name encoder tokens, including the source end-of-sequence marker.

The model receives no explicit alignment labels, and attention need not place all its mass on the token a human would align to that prediction. A final-layer, head-averaged heatmap is a diagnostic of the recorded weights. It cannot show on its own which source tokens causally determine a given prediction.

The source EOS and the last prediction of target EOS are included in the heatmap. The plotted row labels describe predictions, so the first row is the first target token even though the decoder input at that position is BOS.

The bars show the maximum of each head-averaged row. A maximum below one leaves some mass on other source positions in that average. Individual heads can each assign all their weight to one position and still yield a spread-out average if they choose different positions.

PythonIn [36]
CollapseExpand
import numpy as np

row_max = attn_matrix.max(axis=1)
row_indices = np.arange(len(row_max))
VisualizationOut [37]
CollapseExpand
Bar chart of maxima from head-averaged cross-attention rows, mostly below one.
Maximum of each head-averaged cross-attention row in the example sentence. Values below one show mass at multiple source positions in the averaged row.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy